From 8c5ea0e6389915a29957ff436cf10f65952348e9 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 19 Nov 2026 13:07:21 +0800 Subject: [PATCH 01/14] feat(forge): edit the hosts of the GitHub and GitLab providers on the Plugins page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The GitHub and GitLab rows of the Forge bundle each gain a page on the Plugins page that lists the hosts the provider serves. Hosts are added and removed there and saved to the profile patch, and the provider serves the saved list without a restart. Each saved host shows whether the provider's CLI is signed in to it, with the sign-in command to copy. - forge: `ctx.forge.register` returns a handle whose `replace(provider)` puts another provider of the same family in the registered one's place in one step; `readiness` reads only the forge family and the host. - forge-github, forge-gitlab: `hosts` is a volatile Config field that the schema validates; a changed list replaces the registered provider. - client-ui-forge: `forgePanel.hostReadiness`, the two row pages, and an "Add host…" action on the review page for a link whose host no provider serves. That state's copy is reworded in eight languages. --- apps/web/tests/forge-panel.e2e.ts | 40 ++++ docs/config-catalog.md | 22 +- docs/config-catalog.zh.md | 22 +- docs/event-producer-consumer.md | 6 +- docs/event-producer-consumer.zh.md | 6 +- docs/module-graph.md | 6 +- docs/module-graph.zh.md | 6 +- docs/subsystems/forge.i18n.yaml | 4 +- docs/subsystems/forge.md | 51 ++++- docs/subsystems/forge.zh.md | 51 ++++- .../client-ui-forge/README.i18n.yaml | 8 +- .../experimental/client-ui-forge/README.md | 5 +- .../experimental/client-ui-forge/README.zh.md | 5 +- .../src/client/HostSettings.module.css | 194 ++++++++++++++++ .../src/client/HostSettings.tsx | 192 ++++++++++++++++ .../src/client/WorktreeSettings.tsx | 11 +- .../src/client/host-settings-form.ts | 115 ++++++++++ .../src/client/host-sign-in.ts | 46 ++++ .../client-ui-forge/src/client/locales.ts | 184 +++++++++++++-- .../client-ui-forge/src/client/mount.ts | 40 +++- .../src/client/review-page/ReviewDetail.tsx | 16 +- .../src/client/review-page/ReviewPage.tsx | 12 +- .../src/client/review-page/review-mount.ts | 15 +- .../src/client/row-form-labels.ts | 17 ++ .../experimental/client-ui-forge/src/index.ts | 27 ++- .../tests/host-readiness.host.spec.ts | 82 +++++++ .../tests/host-settings-form.client.spec.ts | 82 +++++++ .../tests/host-settings.client.spec.tsx | 212 ++++++++++++++++++ .../tests/host-sign-in.client.spec.ts | 93 ++++++++ .../tests/mount.client.spec.ts | 152 ++++++++++++- .../tests/review-detail.client.spec.tsx | 14 +- .../tests/review-page.client.spec.tsx | 23 +- .../forge-bundle/README.i18n.yaml | 4 +- packages/experimental/forge-bundle/README.md | 2 +- .../experimental/forge-bundle/README.zh.md | 2 +- .../forge-github/README.i18n.yaml | 4 +- packages/experimental/forge-github/README.md | 2 +- .../experimental/forge-github/README.zh.md | 2 +- .../experimental/forge-github/package.json | 14 +- .../experimental/forge-github/src/index.ts | 34 ++- .../forge-github/tests/plugin.spec.ts | 54 ++++- .../experimental/forge-github/tsconfig.json | 6 + .../forge-gitlab/README.i18n.yaml | 4 +- packages/experimental/forge-gitlab/README.md | 2 +- .../experimental/forge-gitlab/README.zh.md | 2 +- .../experimental/forge-gitlab/package.json | 14 +- .../experimental/forge-gitlab/src/index.ts | 36 ++- .../forge-gitlab/tests/plugin.spec.ts | 48 +++- .../experimental/forge-gitlab/tsconfig.json | 6 + packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 2 +- packages/experimental/forge/README.zh.md | 2 +- packages/experimental/forge/src/index.ts | 88 +++++--- packages/experimental/forge/src/types.ts | 18 ++ .../forge/tests/lifecycle.spec.ts | 98 ++++++++ .../src/client/slot-catalog.ts | 1 + .../extensions/tool-cordis/src/api-catalog.ts | 26 ++- pnpm-lock.yaml | 12 + scripts/gen-cordis-catalog.ts | 1 + scripts/type-equiv.manifest.json | 5 + 60 files changed, 2073 insertions(+), 179 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/client/HostSettings.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/HostSettings.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/host-settings-form.ts create mode 100644 packages/experimental/client-ui-forge/src/client/host-sign-in.ts create mode 100644 packages/experimental/client-ui-forge/src/client/row-form-labels.ts create mode 100644 packages/experimental/client-ui-forge/tests/host-readiness.host.spec.ts create mode 100644 packages/experimental/client-ui-forge/tests/host-settings-form.client.spec.ts create mode 100644 packages/experimental/client-ui-forge/tests/host-settings.client.spec.tsx create mode 100644 packages/experimental/client-ui-forge/tests/host-sign-in.client.spec.ts diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index df85abc053..5d013a199e 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -767,6 +767,46 @@ it.skipIf(MODE === 'record')('reports incomplete filter configuration and retrie expect(tripwire.warnings).toEqual([]) }) +it.skipIf(MODE === 'record')('adds a host on the GitLab row of the Plugins page, which the provider serves without a restart', async () => { + const { scaffold, page, tripwire } = await launchPanel('web-e2e-forge-hosts') + // The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first. + const { settled } = await sendPrompt(page, scaffold) + await settled + const merge = 'https://gitlab.example.test/group/app/-/merge_requests/3' + expect(scaffold.ctx.forge.changeRequestFromUrl(merge)).toBeUndefined() + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + await page.locator('[data-plugin-panel]').getByText('变更请求与工作树', { exact: true }).first().click() + await page.getByRole('button', { name: '配置 GitLab 变更请求', exact: true }).click() + const hosts = page.getByRole('list', { name: '主机', exact: true }) + await hosts.locator('[data-forge-host="gitlab.com"]').waitFor() + const input = page.getByRole('textbox', { name: '要添加的主机', exact: true }) + + // The GitHub row serves github.com, and a host has one provider. + await input.fill('github.com') + await input.press('Enter') + await page.getByRole('alert').filter({ hasText: 'github.com 已由 GitHub 组件使用' }).waitFor() + expect(await hosts.getByRole('listitem').count()).toBe(1) + + await input.fill(merge) + await input.press('Enter') + const added = hosts.locator('[data-forge-host="gitlab.example.test"]') + const unsaved = added.getByText('未保存', { exact: true }) + await unsaved.waitFor() + expect(scaffold.ctx.forge.changeRequestFromUrl(merge)).toBeUndefined() + await page.getByRole('button', { name: '保存', exact: true }).click() + // The sign-in state that takes the mark's place depends on the GitLab CLI of the machine, so only the mark's removal is expected. + await unsaved.waitFor({ state: 'detached' }) + + expect(scaffold.ctx.forge.changeRequestFromUrl(merge)).toEqual({ + repository: { forge: 'gitlab', host: 'gitlab.example.test', owner: 'group', name: 'app' }, number: 3, + }) + expect(scaffold.ctx.forge.changeRequestFromUrl('https://gitlab.com/group/app/-/merge_requests/3')).toBeDefined() + expect(scaffold.ctx.forge.changeRequestFromUrl(PULL)).toBeDefined() + expect(await readFile(scaffold.ctx.settings.documentPath, 'utf8')).toMatch(/- id: forge-gitlab\n(?: .*\n)* +hosts:\n +- gitlab\.com\n +- gitlab\.example\.test\n/) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + /** * Expect the panel to show PR 7, which the model viewed by number without its URL in the output, and the lookup that resolved it. * @param launch - the panel launched for a reference scenario. diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 1677edf573..fe3c88ce19 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1328,7 +1328,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:785`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1351,15 +1351,19 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge-github` - `inject`: `forge` -- `source`: [`packages/experimental/forge-github/src/index.ts:19`](../packages/experimental/forge-github/src/index.ts) +- `refs`: `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/experimental/forge-github/src/index.ts:22`](../packages/experimental/forge-github/src/index.ts) ```ts config-catalog /** GitHub CLI executable, served hosts, and invocation limits. */ export interface Config { /** GitHub CLI executable name or absolute host path. */ ghCommand?: string - /** Host names this provider serves; list GitHub Enterprise hosts explicitly. */ - hosts?: string[] + /** + * Host names this provider serves, at least one; list GitHub Enterprise hosts explicitly. Editable live: the + * provider registers again with the new list. + */ + hosts: Volatile /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */ @@ -1695,15 +1699,19 @@ export interface Config { ## `@deepseek-ai/dsh-forge-gitlab` - `inject`: `forge` -- `source`: [`packages/experimental/forge-gitlab/src/index.ts:19`](../packages/experimental/forge-gitlab/src/index.ts) +- `refs`: `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/experimental/forge-gitlab/src/index.ts:22`](../packages/experimental/forge-gitlab/src/index.ts) ```ts config-catalog /** GitLab CLI executable, served hosts, and read limits. */ export interface Config { /** GitLab CLI executable name or absolute host path. */ glabCommand?: string - /** Host names this provider serves; list self-managed GitLab hosts explicitly. */ - hosts?: string[] + /** + * Host names this provider serves, at least one; list self-managed GitLab hosts explicitly. Editable live: the + * provider registers again with the new list. + */ + hosts: Volatile /** Deadline in milliseconds for one `glab` invocation. */ timeoutMs?: number /** Maximum captured bytes per `glab` output stream and combined JSON bytes of one complete check read or review read. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c95fcbd47f..2d72caff96 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1330,7 +1330,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:785`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1353,15 +1353,19 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge-github` - `inject`: `forge` -- `source`: [`packages/experimental/forge-github/src/index.ts:19`](../packages/experimental/forge-github/src/index.ts) +- `refs`: `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/experimental/forge-github/src/index.ts:22`](../packages/experimental/forge-github/src/index.ts) ```ts config-catalog /** GitHub CLI executable, served hosts, and invocation limits. */ export interface Config { /** GitHub CLI executable name or absolute host path. */ ghCommand?: string - /** Host names this provider serves; list GitHub Enterprise hosts explicitly. */ - hosts?: string[] + /** + * Host names this provider serves, at least one; list GitHub Enterprise hosts explicitly. Editable live: the + * provider registers again with the new list. + */ + hosts: Volatile /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */ @@ -1697,15 +1701,19 @@ export interface Config { ## `@deepseek-ai/dsh-forge-gitlab` - `inject`: `forge` -- `source`: [`packages/experimental/forge-gitlab/src/index.ts:19`](../packages/experimental/forge-gitlab/src/index.ts) +- `refs`: `Volatile` (`@deepseek-ai/cordis`) +- `source`: [`packages/experimental/forge-gitlab/src/index.ts:22`](../packages/experimental/forge-gitlab/src/index.ts) ```ts config-catalog /** GitLab CLI executable, served hosts, and read limits. */ export interface Config { /** GitLab CLI executable name or absolute host path. */ glabCommand?: string - /** Host names this provider serves; list self-managed GitLab hosts explicitly. */ - hosts?: string[] + /** + * Host names this provider serves, at least one; list self-managed GitLab hosts explicitly. Editable live: the + * provider registers again with the new list. + */ + hosts: Volatile /** Deadline in milliseconds for one `glab` invocation. */ timeoutMs?: number /** Maximum captured bytes per `glab` output stream and combined JSON bytes of one complete check read or review read. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index c22d3e8795..907bb37fd0 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -47,8 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-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:32`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | -| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:41`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:33`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:42`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `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` | @@ -124,7 +124,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` | | `internal/service` | - | `client-ui-forge`, `gateway` | | `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) | -| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) | +| `loader/volatile-update` | - | `forge-github`, [`forge-gitlab`](../packages/experimental/forge-gitlab), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) | | `locale/change` | `locale` (`emit`) | `locale` | | `slots/changed` | `ui-renderer` (`emit`) | - | | `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index cbffa01407..9040255789 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -49,8 +49,8 @@ | `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-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:32`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | -| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:41`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:33`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:42`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `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` | @@ -126,7 +126,7 @@ | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` | | `internal/service` | - | `client-ui-forge`, `gateway` | | `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) | -| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) | +| `loader/volatile-update` | - | `forge-github`, [`forge-gitlab`](../packages/experimental/forge-gitlab), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) | | `locale/change` | `locale` (`emit`) | `locale` | | `slots/changed` | `ui-renderer` (`emit`) | - | | `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 2e18191e32..182aa316f6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1339,6 +1339,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_experimental_forge_session + pkg_experimental_forge_github --> pkg_settings pkg_experimental_forge_github --> pkg_subprocess pkg_experimental_worktree --> pkg_agent pkg_experimental_worktree --> pkg_error @@ -1355,6 +1356,7 @@ flowchart TD pkg_experimental_worktree --> pkg_workspace pkg_forge_gitlab --> pkg_experimental_forge pkg_forge_gitlab --> pkg_experimental_forge_session + pkg_forge_gitlab --> pkg_settings pkg_forge_gitlab --> pkg_subprocess pkg_tool_session_query --> pkg_agent pkg_tool_session_query --> pkg_llm @@ -1968,9 +1970,9 @@ flowchart TD | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | -| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) | +| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`credentials`](../packages/credentials/credentials), [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index c281107e79..ac52e184a0 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1341,6 +1341,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_experimental_forge_session + pkg_experimental_forge_github --> pkg_settings pkg_experimental_forge_github --> pkg_subprocess pkg_experimental_worktree --> pkg_agent pkg_experimental_worktree --> pkg_error @@ -1357,6 +1358,7 @@ flowchart TD pkg_experimental_worktree --> pkg_workspace pkg_forge_gitlab --> pkg_experimental_forge pkg_forge_gitlab --> pkg_experimental_forge_session + pkg_forge_gitlab --> pkg_settings pkg_forge_gitlab --> pkg_subprocess pkg_tool_session_query --> pkg_agent pkg_tool_session_query --> pkg_llm @@ -1970,9 +1972,9 @@ flowchart TD | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | -| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) | +| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`credentials`](../packages/credentials/credentials), [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 0f1d528cdf..cd72faedd1 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -6,8 +6,8 @@ en: 37c9cbfb3141702b zh: c5fcbb7f4fda1dbc /forges/providers-and-change-requests: - en: 8df1bf8a6d294252 - zh: 79ba96596739569f + en: ef1335232f8e2156 + zh: b19c42e7f8671b01 /forges/status-polling: en: 26ccfa2e342e3e67 zh: fe6cc2a622757c48 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index f7cea75239..4081e9c672 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -167,6 +167,28 @@ interface ForgeProvider { } ``` +`ctx.forge.register` returns the disposer of the registration. Its `replace` puts another provider of the same family in the registered one's place; a provider whose host list is edited while it runs calls it to serve the new list: + +```ts type-equiv +/** + * What `ctx.forge.register` returns: the disposer, plus the replacement of the registered provider by another provider + * of the same forge family, for a provider whose configuration changes while it runs. + */ +interface ForgeRegistrationHandle { + /** Unregister the provider this registration holds and wait for its calls, and those of the providers it replaced, to finish. */ + (): Promise + /** + * Replace the registered provider in one synchronous step, so no reader finds the family without a provider. The + * replaced provider's in-flight calls are cancelled and their results discarded; watches of the family poll at once + * and `forge/providers-changed` announces the change. + * @param provider - provider of the same forge family. + * @throws when the registration was withdrawn, `provider.forge` is another family, or another family's provider + * serves one of `provider.hosts`, compared without case; the registered provider then keeps serving. + */ + replace(provider: ForgeProvider): void +} +``` + ```ts type-equiv /** One commit of a change request. */ interface ForgeCommit { @@ -1661,10 +1683,11 @@ Registry of forge providers. Watchers of one change request share a single polli * registration ends. Unregistering cancels and awaits its in-flight calls; * results from the withdrawn registration are discarded. * @param provider - provider to serve `provider.forge` on `provider.hosts`. - * @returns the disposer that unregisters the provider and waits for its calls to finish. + * @returns the disposer that unregisters the provider and waits for its calls to finish, carrying + * {@link ForgeRegistrationHandle.replace}. * @throws when another provider already serves the same forge or one of the same hosts, compared without case. */ -register(provider: ForgeProvider): () => Promise +register(provider: ForgeProvider): ForgeRegistrationHandle /** * Name a forge family and its change requests for readers. @@ -1706,13 +1729,13 @@ changeRequestUrl(ref: ChangeRequestRef): string async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise /** - * Report whether the provider can reach the repository's host with current credentials. - * @param repository - repository served by a registered provider. + * Report whether a provider can reach one host with current credentials. + * @param repository - forge family of a registered provider and the host to probe; a repository names both. * @param signal - cancellation for the probe. * @returns the provider's readiness for the host. - * @throws when no provider serves the repository's forge. + * @throws when no provider serves the forge. */ -async readiness(repository: ForgeRepository, signal: AbortSignal): Promise +async readiness(repository: Pick, signal: AbortSignal): Promise /** * Mark a draft change request ready for review, then poll it at once when it is watched. @@ -2035,6 +2058,18 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewRefresh(signal: AbortSignal): Promise +/** + * Report whether a provider reaches one of its hosts with the Host's current credentials, for the host list on the + * Plugins page of that provider's row. The read names no Session, so, like the review page reads, only callers that + * may use the Host's code host credentials reach it. + * @param forge - forge family of a registered provider, such as `gitlab`. + * @param host - host name as the provider's configuration lists it. + * @param signal - request cancellation. + * @returns the provider's readiness for the host; `unavailable` with the reason when no provider serves the family, + * the probe fails, or it runs past `readinessTimeoutMs`. + */ +@Remote async hostReadiness(forge: string, host: string, signal: AbortSignal): Promise + /** * Poll one change request the review page shows at once; its stream reports the result. * @param url - web URL of the change request. @@ -2759,11 +2794,11 @@ Source: [`packages/experimental/forge-session/src/index.ts`](../../packages/expe #### `forge/providers-changed` — parallel -Announces a provider registration or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running. +Announces a provider registration, replacement, or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running. ```ts cordis-catalog /** - * Announces a provider registration or withdrawal after the registry changes. + * Announces a provider registration, replacement, or withdrawal after the registry changes. * Listener failures are logged without preventing other listeners from running. * @param forge - family whose provider changed. * @mode parallel diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 712903907d..8dbfb232e5 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -167,6 +167,28 @@ interface ForgeProvider { } ``` +`ctx.forge.register` 返回该次注册的 disposer。它的 `replace` 用同一家族的另一个提供方替换已注册的提供方;主机列表在运行期间被修改的提供方调用它来服务新的列表: + +```ts type-equiv +/** + * What `ctx.forge.register` returns: the disposer, plus the replacement of the registered provider by another provider + * of the same forge family, for a provider whose configuration changes while it runs. + */ +interface ForgeRegistrationHandle { + /** Unregister the provider this registration holds and wait for its calls, and those of the providers it replaced, to finish. */ + (): Promise + /** + * Replace the registered provider in one synchronous step, so no reader finds the family without a provider. The + * replaced provider's in-flight calls are cancelled and their results discarded; watches of the family poll at once + * and `forge/providers-changed` announces the change. + * @param provider - provider of the same forge family. + * @throws when the registration was withdrawn, `provider.forge` is another family, or another family's provider + * serves one of `provider.hosts`, compared without case; the registered provider then keeps serving. + */ + replace(provider: ForgeProvider): void +} +``` + ```ts type-equiv /** One commit of a change request. */ interface ForgeCommit { @@ -1665,10 +1687,11 @@ Registry of forge providers. Watchers of one change request share a single polli * registration ends. Unregistering cancels and awaits its in-flight calls; * results from the withdrawn registration are discarded. * @param provider - provider to serve `provider.forge` on `provider.hosts`. - * @returns the disposer that unregisters the provider and waits for its calls to finish. + * @returns the disposer that unregisters the provider and waits for its calls to finish, carrying + * {@link ForgeRegistrationHandle.replace}. * @throws when another provider already serves the same forge or one of the same hosts, compared without case. */ -register(provider: ForgeProvider): () => Promise +register(provider: ForgeProvider): ForgeRegistrationHandle /** * Name a forge family and its change requests for readers. @@ -1710,13 +1733,13 @@ changeRequestUrl(ref: ChangeRequestRef): string async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise /** - * Report whether the provider can reach the repository's host with current credentials. - * @param repository - repository served by a registered provider. + * Report whether a provider can reach one host with current credentials. + * @param repository - forge family of a registered provider and the host to probe; a repository names both. * @param signal - cancellation for the probe. * @returns the provider's readiness for the host. - * @throws when no provider serves the repository's forge. + * @throws when no provider serves the forge. */ -async readiness(repository: ForgeRepository, signal: AbortSignal): Promise +async readiness(repository: Pick, signal: AbortSignal): Promise /** * Mark a draft change request ready for review, then poll it at once when it is watched. @@ -2039,6 +2062,18 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewRefresh(signal: AbortSignal): Promise +/** + * Report whether a provider reaches one of its hosts with the Host's current credentials, for the host list on the + * Plugins page of that provider's row. The read names no Session, so, like the review page reads, only callers that + * may use the Host's code host credentials reach it. + * @param forge - forge family of a registered provider, such as `gitlab`. + * @param host - host name as the provider's configuration lists it. + * @param signal - request cancellation. + * @returns the provider's readiness for the host; `unavailable` with the reason when no provider serves the family, + * the probe fails, or it runs past `readinessTimeoutMs`. + */ +@Remote async hostReadiness(forge: string, host: string, signal: AbortSignal): Promise + /** * Poll one change request the review page shows at once; its stream reports the result. * @param url - web URL of the change request. @@ -2763,11 +2798,11 @@ Source: [`packages/experimental/forge-session/src/index.ts`](../../packages/expe #### `forge/providers-changed` — parallel -Announces a provider registration or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running. +Announces a provider registration, replacement, or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running. ```ts cordis-catalog /** - * Announces a provider registration or withdrawal after the registry changes. + * Announces a provider registration, replacement, or withdrawal after the registry changes. * Listener failures are logged without preventing other listeners from running. * @param forge - family whose provider changed. * @mode parallel diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index b5185916ec..7022d47d3f 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: b09c31932092f0a0 - zh: b16598d5f50baab6 + en: 25a848f542fbd03d + zh: bc36a3a5aa4972c3 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 5876ab4a46ee5e65 - zh: b5ea47ac9665530e + en: 7acf0e13702d4b49 + zh: 95b0f34f8a92ae67 /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 236072f2c5..986229b09f 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -31,9 +31,10 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector. The selector's searchable menu lists, most recently committed first, the current branch, then each remote's default branch, then local branches, then one group per remote headed by its name and its repository, `owner/name` for a recognized code host or else its fetch URL without the user name and password a URL can carry; typing filters the rows at once and lists the branches whose names contain the text after a short pause, and Enter chooses the first row. A remote branch is fetched, only that branch and without tags, when the worktree is created. The menu's last row, Name the new branch, opens a dialog whose field starts with the `worktreePrefix` and checks Git's branch-name rules while the name is typed; Save asks the Host, which also refuses a name the checkout already uses as a branch, and keeps the dialog open with the reason. With a chosen name, the selector shows the name before the base, and the dialog offers to use a generated name again. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the chosen branch, or else `dsh--<4 random hexadecimal digits>`, is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. - **Archive cleanup** — archiving a Session lets the [worktree service](../worktree/README.md) reclaim the clean, unreferenced worktree it created, whether through the New Session option or the model's `enter_worktree` tool, while retaining the branch and its commits. A scheduled cleanup uses the archive notice “Archived; the worktree will be cleaned up”; one that ends retained returns to the ordinary notice, and one that fails replaces it with a warning while the Session stays archived. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow. The bundle's worktree row on the Plugins page offers Keep worktrees when archiving: once saved, archiving keeps every worktree and shows the ordinary archive notice; the switch is read at each archive, so it does not affect a cleanup already scheduled. +- **Provider hosts** — the bundle's GitHub and GitLab rows on the Plugins page each open a page that lists the hosts the provider serves. Add, or Enter, stages the typed host name, or the host and port of a pasted URL, and refuses below the field a name that is malformed, already listed, or served by the other provider; a row's remove button stages its removal, except for the last host. Save writes the whole list to the profile patch, and the provider serves it without a restart. Each saved host shows Signed in, Not signed in with the provider's sign-in command and Copy, or Can't check with the reason; the page reads these when it shows, after a save, when the window regains focus, and from the button beside the list's title. A deployment that stores settings read-only shows the list without the edits. - **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph. -- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a list is read, skeleton rows laid out as the chosen view stand in for its items. A list item names the repository when the lists span more than one, the author, the update time, the issues it closes, and at most one hint, such as You requested changes · Requested again or a team request; the search box filters the lists by title, number, repository, and author under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and unrecognized links show where they apply. +- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a list is read, skeleton rows laid out as the chosen view stand in for its items. A list item names the repository when the lists span more than one, the author, the update time, the issues it closes, and at most one hint, such as You requested changes · Requested again or a team request; the search box filters the lists by title, number, repository, and author under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and links whose host no provider serves show where they apply; such a link shows Unknown code host with Add host…, which opens the bundle's page on the Plugins page while that page is available. - **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden. - **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row. - **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away. @@ -77,6 +78,8 @@ Each inspection also decides whether the worktree is missing: the Session's dire `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. +`hostReadiness(forge, host)` names no Session. It asks the provider of the forge family whether it reaches the host with the Host's credentials, within `readinessTimeoutMs`, and answers `unavailable` with the reason when no provider serves the family, the probe fails, or the time runs out; a cancelled call rejects. The provider rows' host pages read it once per saved host. + `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 Session panel entries, the New Session option, and the creation card; it opens with the first subscriber, after a `forgePanel` Session reference has opened the Session's history, so the Host resumes the Session once rather than beside that opening, holds that reference until the stream ends, 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 change requests section is the `change-requests` entry of `conversation.session.panel.section` at order 100 with its count in `conversation.session.panel.section.actions`; the checkout, local changes, and connection rows are `conversation.session.panel.environment.row` entries at orders 20, 30, and 40, after the project row, and the attention mark is a `conversation.session.panel.indicator` entry. The checkout row shortens paths with the Host home from the Remote's Host facts, read again after each transport reset; it is mounted whenever the panel shows, so it runs the automatic refresh on mount and on window `focus` and `visibilitychange`, throttled per Session by the shared panel store; a refresh asked for before the first panel state arrives runs once that state arrives, because the Host refreshes only a panel it follows. The toast lives in a `shell.overlay` entry so it outlives the panel. 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. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index db3cb23eac..22c5a1baf1 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -31,9 +31,10 @@ kind: "package-reference" - **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器。选择器的菜单可搜索,按最近提交排序依次列出:当前分支、每个远程的默认分支、本地分支,然后每个远程一组,组名旁显示该远程对应的仓库(识别出代码托管仓库时为 `owner/name`,否则为去掉用户名和密码后的获取地址);输入时已列出的行立即过滤,短暂停顿后列出名称包含所输入文字的分支,按 Enter 选择第一行。远程分支在创建 worktree 时获取,只获取这一个分支,不获取标签。菜单最后一行“指定新分支名称…”打开对话框:输入框以 `worktreePrefix` 开头,输入时检查 Git 的分支名规则;“确定”交给 Host,Host 还会拒绝检出中已有的分支名,拒绝时对话框保持打开并显示原因。指定名称后,选择器在基准前显示该名称,对话框也提供“改回自动命名”。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建指定的分支,未指定时为 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 - **归档清理**——归档一个会话后,由[工作树服务](../worktree/README.zh.md)回收它创建的干净且无人引用的工作树,无论来自新会话选项还是模型的 `enter_worktree` 工具,分支及其提交保留。清理排队后,归档提示为“已归档,工作树将被清理”;最终保留时恢复为普通归档提示,失败时替换为警告而会话仍保持归档。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。插件页上该套件的 worktree 行提供“归档时不删除工作树”开关:保存后,归档会保留所有工作树并显示普通归档提示;开关在每次归档时读取,不影响已排队的清理。 +- **提供方主机**——插件页上该套件的 GitHub 行与 GitLab 行各打开一个页面,列出该提供方服务的主机。“添加”或 Enter 把输入的主机名(粘贴 URL 时取其中的主机与端口)加入待保存的列表;格式不对、已在列表中或已由另一个提供方服务的主机名不会加入,原因显示在输入框下方。行尾的移除按钮把该主机从待保存的列表中去掉,最后一个主机不能移除。“保存”把整个列表写入 profile patch,提供方无需重启即服务新列表。每个已保存的主机显示“已登录”、“未登录”(附提供方给出的登录命令与“复制”)或“无法检查”(附原因);页面在显示时、保存后、窗口重新获得焦点时以及点击列表标题旁的按钮时读取这些状态。以只读方式保存设置的部署只显示列表,不能修改。 - **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。 -- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。列表读取期间,按所选视图排布的骨架行占据列表项的位置。列表项在列表跨多个仓库时写出仓库名,并显示作者、更新时间、会关闭的 issue 和至多一条提示,如“你请求过修改 · 已再次请求”或团队请求;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库和作者筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接无法识别时在对应位置提示。 +- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。列表读取期间,按所选视图排布的骨架行占据列表项的位置。列表项在列表跨多个仓库时写出仓库名,并显示作者、更新时间、会关闭的 issue 和至多一条提示,如“你请求过修改 · 已再次请求”或团队请求;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库和作者筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接的主机没有提供方服务时在对应位置提示;后一种情况显示“未知的代码托管平台”与“添加主机…”,在插件页可用时打开该套件的页面。 - **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。 - **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。 - **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。 @@ -77,6 +78,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi `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 加载后才结束的写入不会改动它。 +`hostReadiness(forge, host)` 不指定 Session。它在 `readinessTimeoutMs` 内询问该 forge 家族的提供方能否用 Host 的凭据访问该主机;没有提供方服务该家族、探测失败或超时时,返回 `unavailable` 及原因;调用被取消时拒绝。提供方行的主机页面对每个已保存的主机读取一次。 + `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 一条流,同时供给会话面板中的条目、新会话选项与创建卡片;第一个订阅方出现时,先由一个 `forgePanel` Session 引用打开该 Session 的历史再打开流,使 Host 只恢复一次该 Session、而不与这次打开并行,并持有该引用直到流结束;最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。变更请求分栏是 `conversation.session.panel.section` 中 order 为 100 的 `change-requests` 条目,数量位于 `conversation.session.panel.section.actions`;检出行、本地变更行与连接行是 `conversation.session.panel.environment.row` 中 order 为 20、30 与 40 的条目,位于项目行之后;提醒标记是 `conversation.session.panel.indicator` 条目。检出行用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取;面板显示时它始终挂载,因此由它在挂载时以及窗口 `focus` 与 `visibilitychange` 时触发自动刷新,按会话由共享的面板 store 限流;首个面板状态到达前请求的刷新等到该状态到达后执行,因为 Host 只刷新它正在跟随的面板。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 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。 diff --git a/packages/experimental/client-ui-forge/src/client/HostSettings.module.css b/packages/experimental/client-ui-forge/src/client/HostSettings.module.css new file mode 100644 index 0000000000..57767453fd --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/HostSettings.module.css @@ -0,0 +1,194 @@ +/* A provider row page: the host list under the Plugins form's tokens. */ +.field { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px 0; +} + +/* The recheck button stands in the column of the rows' removal buttons. */ +.head { + display: flex; + align-items: center; + gap: 8px; + padding-right: 8px; +} + +.label { + flex: 1; + min-width: 0; + font-size: 13px; + font-weight: 500; + line-height: 1.5; + color: var(--dsw-alias-label-primary); +} + +.iconButton { + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: var(--dsw-radius-sm); + background: none; + color: var(--dsw-alias-label-tertiary); + cursor: pointer; +} + +.iconButton:disabled, +.iconButton[aria-disabled='true'] { + opacity: 0.4; + cursor: default; +} + +@media (hover: hover) { + .iconButton:hover:not(:disabled, [aria-disabled='true']) { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-secondary); + } +} + +.iconButton:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} + +/* The list is a group of read values, so it has the fields' edge without their fill. */ +.hosts { + margin: 0; + padding: 0; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-md); + list-style: none; +} + +.host { + padding: 8px 8px 8px 12px; +} + +.host + .host { + border-top: 0.5px solid var(--dsw-alias-border-l2); +} + +.row { + display: flex; + align-items: center; + gap: 10px; + min-height: 24px; +} + +/* A host name wraps instead of being cut, so a long one stays readable where no pointer can hover it. */ +.name { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; + font-size: 13px; + line-height: 18px; + color: var(--dsw-alias-label-primary); +} + +.state, +.unsaved { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + font-size: 12.5px; + line-height: 18px; + color: var(--dsw-alias-label-secondary); + white-space: nowrap; +} + +.unsaved { + color: var(--dsw-alias-label-tertiary); +} + +/* The command and the reason end where the state text ends, short of the removal button's column. */ +.command { + display: flex; + align-items: flex-start; + gap: 8px; + margin: 6px 34px 2px 0; + padding: 4px 4px 4px 10px; + border-radius: var(--dsw-radius-sm); + background: var(--dsw-alias-bg-module-platform); +} + +.commandText { + flex: 1; + min-width: 0; + padding: 5px 0; + font-family: var(--ds-font-family-code); + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-label-primary); + overflow-wrap: anywhere; +} + +.reason { + margin: 4px 34px 2px 0; + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-label-tertiary); + overflow-wrap: anywhere; +} + +.addRow { + display: flex; + gap: 8px; + margin-top: 2px; +} + +.input { + flex: 1; + min-width: 0; + height: 34px; + padding: 0 12px; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-md); + background: var(--dsw-alias-bg-layer-3); + font: inherit; + font-size: 13px; + line-height: 1.5; + color: var(--dsw-alias-label-primary); +} + +.input::placeholder { + color: var(--dsw-alias-label-tertiary); +} + +.input:focus-visible { + outline: none; + border-color: var(--dsw-alias-state-business-primary); +} + +.input:disabled { + color: var(--dsw-alias-label-tertiary); + cursor: default; +} + +.input[aria-invalid='true'] { + border-color: var(--dsw-alias-state-error-primary); +} + +.add { + flex: none; + height: 34px; + padding: 0 14px; + font-size: 13px; +} + +.hint, +.invalid { + margin: 0; + font-size: 12px; + line-height: 1.5; + color: var(--dsw-alias-label-tertiary); +} + +.invalid { + color: var(--dsw-alias-state-error-primary); +} diff --git a/packages/experimental/client-ui-forge/src/client/HostSettings.tsx b/packages/experimental/client-ui-forge/src/client/HostSettings.tsx new file mode 100644 index 0000000000..4c42e431e3 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/HostSettings.tsx @@ -0,0 +1,192 @@ +/** A provider row's page on the Plugins page: the hosts the provider serves, each with its sign-in state. */ +import { useEffect, useId, useRef, useState, type ReactNode } from 'react' +import { + Button, IconRefreshOutlineRegular, IconTrashOutlineRegular, SettingsForm, StateDot, Tooltip, type StateDotState, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { ForgePanelKey, NS } from './locales.ts' +import type { HostFormActions, HostFormState, HostProblem } from './host-settings-form.ts' +import type { HostSignIn } from './host-sign-in.ts' +import { rowFormLabels } from './row-form-labels.ts' +import css from './HostSettings.module.css' + +/** The forge family of a provider row that has a host page. */ +export type HostForge = 'github' | 'gitlab' + +/** Registration-side face of a provider row's host page. */ +export interface HostSettingsInjected extends HostFormActions { + readonly hooks: { + /** The saved and staged host lists. */ + readonly hostForm: SnapshotStore + /** Sign-in state by saved host. */ + readonly signIn: SnapshotStore> + } + /** Which provider the row mounts. */ + readonly forge: HostForge + /** Read the sign-in state of the saved hosts; `visibly` shows each host as being checked until its read answers. */ + readonly checkSignIn: (hosts: readonly string[], visibly: boolean) => void + /** Copy a sign-in command and report the outcome. */ + readonly copyCommand: (command: string) => void +} + +export type HostSettingsProps = PropsRuntime<'plugins.row.config'> & PropsLocale & InjectFace + +type Translate = HostSettingsProps['t'] + +/** What differs between the two rows' pages. */ +interface ForgeCopy { + /** Key of what the provider's hosts call a change request. */ + readonly noun: ForgePanelKey + /** The CLI the provider signs in with. */ + readonly cli: string + /** A host name the field shows as its placeholder and a refusal names as an example. */ + readonly example: string + /** Key of the refusal of a host the other provider serves. */ + readonly taken: ForgePanelKey +} + +const FORGES: Record = { + github: { noun: 'noun.pullRequest', cli: 'gh', example: 'github.example.com', taken: 'hosts.taken.gitlab' }, + gitlab: { noun: 'noun.mergeRequest', cli: 'glab', example: 'gitlab.example.com', taken: 'hosts.taken.github' }, +} + +const STATES: Record = { + ready: { dot: 'done', key: 'hosts.state.ready' }, + unauthenticated: { dot: 'warning', key: 'hosts.state.unauthenticated' }, + unavailable: { dot: 'error', key: 'hosts.state.unavailable' }, + checking: { dot: 'ongoing', key: 'hosts.state.checking' }, +} + +const CHECKING: HostSignIn = { state: 'checking' } + +function problemText(problem: HostProblem, forge: HostForge, t: Translate): string { + switch (problem.kind) { + case 'invalid': return t('hosts.invalid', { example: FORGES[forge].example }) + case 'duplicate': return t('hosts.duplicate', { host: problem.host }) + case 'taken': return t(FORGES[forge].taken, { host: problem.host }) + /* v8 ignore next -- closed union. */ + default: return assertNever(problem, 'HostProblem') + } +} + +/** + * One host of the list: its name, its sign-in state once saved, and its removal. A host that needs sign-in shows the + * provider's command to copy; a host that could not be checked shows why. + */ +function HostRow({ host, signIn, removable, disabled, onRemove, onCopy, t }: { + readonly host: string + /** The sign-in state of a saved host, or undefined for a host a save would add. */ + readonly signIn: HostSignIn | undefined + /** Whether another host would remain. */ + readonly removable: boolean + readonly disabled: boolean + readonly onRemove: (host: string) => void + readonly onCopy: (command: string) => void + readonly t: Translate +}): ReactNode { + const command = signIn?.state === 'unauthenticated' ? signIn.signIn?.command : undefined + const reason = signIn !== undefined && signIn.state !== 'checking' && signIn.state !== 'ready' && command === undefined ? signIn.message : null + return ( +
  • +
    + {host} + {signIn === undefined + ? {t('hosts.state.unsaved')} + : ( + + + {t(STATES[signIn.state].key)} + + )} + + + +
    + {command !== undefined && ( +
    + {command} + +
    + )} + {reason !== null && reason !== '' &&

    {reason}

    } +
  • + ) +} + +/** + * Render a provider row's configuration: the hosts it serves, staged until one save, and the sign-in state of each + * saved host, read when the page shows, after a save, and when the window regains focus. The summary view names the list. + * @param props - the Plugins page view, the staged list with its actions, the sign-in states, and copy. + * @returns the row page's form, or the summary line. + */ +export function HostSettings(props: HostSettingsProps): ReactNode { + const { t, forge, view } = props + const labelId = useId() + const messageId = useId() + const state = props.useHostForm(value => value) + const signIn = props.useSignIn(value => value) + const [text, setText] = useState('') + const [problem, setProblem] = useState() + // The effect reads the latest list and check through refs, so it runs again only when the saved hosts change. + const saved = useRef(state.saved) + saved.current = state.saved + const checkSignIn = useRef(props.checkSignIn) + checkSignIn.current = props.checkSignIn + const shown = view === 'page' && state.available + const savedKey = state.saved.join('\n') + useEffect(() => { + if (!shown) return + const again = (): void => { checkSignIn.current(saved.current, false) } + again() + window.addEventListener('focus', again) + return () => { window.removeEventListener('focus', again) } + }, [shown, savedKey]) + if (view === 'summary') return t('hosts.title') + const disabled = !state.writable || state.saving + const add = (): void => { + const refused = props.add(text) + setProblem(refused) + if (refused === undefined) setText('') + } + return ( + +
    +
    + {t('hosts.title')} + + + +
    +
      + {state.draft.map(host => ( + 1} disabled={disabled} onRemove={props.remove} onCopy={props.copyCommand} t={t} /> + ))} +
    +
    + { setText(event.target.value); setProblem(undefined) }} + onKeyDown={(event) => { + if (event.key !== 'Enter' || event.nativeEvent.isComposing) return + event.preventDefault() + add() + }} /> + +
    + {problem === undefined + ?

    {t('hosts.hint', { noun: t(FORGES[forge].noun), cli: FORGES[forge].cli })}

    + : } +
    +
    + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/WorktreeSettings.tsx b/packages/experimental/client-ui-forge/src/client/WorktreeSettings.tsx index 2fbc6f97b2..68d3406c24 100644 --- a/packages/experimental/client-ui-forge/src/client/WorktreeSettings.tsx +++ b/packages/experimental/client-ui-forge/src/client/WorktreeSettings.tsx @@ -1,22 +1,15 @@ /** The worktree service's row page on the Plugins page: the archive cleanup switch. */ import { useId } from 'react' import { SettingsForm, Switch } from '@deepseek-ai/dsh-client-ui-primitives' -import type { SettingsFormLabels } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type { NS } from './locales.ts' +import { rowFormLabels } from './row-form-labels.ts' import type { WorktreeSettingsInjected } from './worktree-settings-form.ts' import css from './WorktreeSettings.module.css' export type WorktreeSettingsProps = PropsRuntime<'plugins.row.config'> & PropsLocale & InjectFace -function formLabels(t: WorktreeSettingsProps['t']): SettingsFormLabels { - return { - unavailable: t('settings.unavailable'), readOnly: t('settings.readOnly'), saveFailed: t('settings.saveFailed'), - save: t('settings.save'), saving: t('settings.saving'), - } -} - /** * Render the worktree row's configuration: one switch that keeps every * checkout when its Session is archived. The summary view names the switch. @@ -29,7 +22,7 @@ export function WorktreeSettings(props: WorktreeSettingsProps) { const state = props.useWorktreeForm(value => value) if (props.view === 'summary') return t('settings.retainOnArchive.title') const disabled = !state.writable || state.saving - return + return
    diff --git a/packages/experimental/client-ui-forge/src/client/host-settings-form.ts b/packages/experimental/client-ui-forge/src/client/host-settings-form.ts new file mode 100644 index 0000000000..31dcb8966d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/host-settings-form.ts @@ -0,0 +1,115 @@ +/** Staged host list of a provider row, using the shared Plugins form model. */ +import { SettingsFormModel, type SettingsFormScope, type SettingsFormShell } from '@deepseek-ai/dsh-client-ui-primitives' +import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' + +/** The live-editable field of a forge provider's Config. */ +export interface HostSettings { + hosts: string[] +} + +/** The saved and staged host lists with the shared form status. */ +export interface HostFormState extends SettingsFormShell { + /** Hosts the provider serves, as its configuration lists them. */ + readonly saved: readonly string[] + /** Hosts a save would store: `saved` while nothing is staged. */ + readonly draft: readonly string[] +} + +/** Why a typed host was not staged. */ +export type HostProblem = + | { readonly kind: 'invalid' } + | { readonly kind: 'duplicate'; readonly host: string } + | { readonly kind: 'taken'; readonly host: string } + +/** What a provider row's host list offers its page. */ +export interface HostFormActions { + /** + * Stage one more host. The text is a host name with an optional port, or a URL, of which only the host is taken. + * @param text - what the reader typed. + * @returns undefined once staged or for blank text, else why the host was refused. + */ + readonly add: (text: string) => HostProblem | undefined + /** Stage the removal of a host; the last host stays. */ + readonly remove: (host: string) => void + /** Write the staged list, then read back what the Host accepted. */ + readonly save: () => void + /** Drop the staged list. */ + readonly discard: () => void +} + +/** + * A host name with an optional port. The providers' Config holds the same rule and decides what a save stores; this + * copy only answers before a save. + */ +const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i + +/** A URL with a scheme, of which a typed host keeps only the authority. */ +const URL_FORM = /^[a-z][a-z0-9+.-]*:\/\//i + +/** + * Read the host a reader typed: a URL gives its host and port, any other text is taken as written, in lowercase. + * @param text - what the reader typed. + * @returns the lowercase host, which may still be malformed. + */ +export function typedHost(text: string): string { + const trimmed = text.trim() + const host = URL_FORM.test(trimmed) && URL.canParse(trimmed) ? new URL(trimmed).host : trimmed + return host.toLowerCase() +} + +function listed(text: string): string[] { + return text.split('\n').filter(host => host !== '') +} + +/** Stages additions and removals of a provider's hosts until the reader saves them as one list. */ +export class HostSettingsForm { + private readonly form: SettingsFormModel + private readonly state: SnapshotStore + + /** + * @param scope - Host-backed configuration form of the provider row. + * @param taken - hosts the other providers serve now, which this row cannot add. + */ + constructor(private readonly scope: SettingsFormScope, private readonly taken: () => readonly string[]) { + this.form = new SettingsFormModel(scope, [{ + field: 'hosts', + format: value => (value as readonly string[] | undefined ?? []).join('\n'), + // `remove` keeps the last host, so every staged text lists at least one. + parse: text => ({ kind: 'set', value: listed(text) }), + }]) + this.state = this.form.bind(() => ({ + ...this.form.shell(), saved: this.scope.getSnapshot().value?.hosts ?? [], draft: listed(this.form.field('hosts').text), + })) + } + + /** + * Build the registration face for the row page. + * @returns the list observable with the add, remove, save, and discard actions. + */ + inject(): { hooks: { hostForm: SnapshotStore } } & HostFormActions { + const { edit, save, discard } = this.form.actions() + const stage = (hosts: readonly string[]): void => { edit('hosts', hosts.join('\n')) } + return { + hooks: { hostForm: this.state }, + add: (text) => { + const host = typedHost(text) + if (host === '') return undefined + if (!HOST.test(host)) return { kind: 'invalid' } + const { draft } = this.state.getSnapshot() + if (draft.some(other => other.toLowerCase() === host)) return { kind: 'duplicate', host } + if (this.taken().some(other => other.toLowerCase() === host)) return { kind: 'taken', host } + stage([...draft, host]) + return undefined + }, + remove: (host) => { + const { draft } = this.state.getSnapshot() + if (draft.length > 1) stage(draft.filter(other => other !== host)) + }, + save, + discard, + } + } + + /** Release the accepted-value subscription. */ + dispose(): void { this.form.dispose() } +} diff --git a/packages/experimental/client-ui-forge/src/client/host-sign-in.ts b/packages/experimental/client-ui-forge/src/client/host-sign-in.ts new file mode 100644 index 0000000000..52fe280c38 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/host-sign-in.ts @@ -0,0 +1,46 @@ +/** Sign-in state of the hosts a provider row serves, read through `forgePanel.hostReadiness`. */ +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' + +/** What the page knows of one host: its readiness once read, or that the first read is under way. */ +export type HostSignIn = ForgeReadiness | { readonly state: 'checking' } + +/** Reads one host's readiness; the signal ends the read. */ +export type HostReadinessRead = (host: string, signal: AbortSignal) => Promise> + +/** + * Keeps the last read sign-in state of each host of one provider. A check reads every named host at once and forgets + * the hosts it does not name; a later check ends the reads of an earlier one. + */ +export class HostSignInStates { + /** Sign-in state by host as the provider's configuration lists it. */ + readonly states: SnapshotStore> = createSnapshotStore>(new Map()) + private reads = new AbortController() + + /** @param read - one host's readiness read. */ + constructor(private readonly read: HostReadinessRead) {} + + /** + * Read the sign-in state of `hosts`. + * @param hosts - every host to keep a state for. + * @param visibly - show each host as being checked until its read answers; otherwise a host keeps the state it has. + */ + check(hosts: readonly string[], visibly: boolean): void { + this.reads.abort() + const reads = new AbortController() + this.reads = reads + const known = this.states.getSnapshot() + this.states.set(new Map(hosts.map(host => [host, visibly ? { state: 'checking' } : known.get(host) ?? { state: 'checking' }]))) + for (const host of hosts) { + void this.read(host, reads.signal).then((result) => { + if (reads.signal.aborted) return + const readiness: ForgeReadiness = result.ok ? result.value : { state: 'unavailable', message: result.error.message, signIn: null } + this.states.set(new Map(this.states.getSnapshot()).set(host, readiness)) + }) + } + } + + /** End the reads under way; their answers are dropped. */ + dispose(): void { this.reads.abort() } +} diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index cd5f252402..b5eb2fa8ef 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -12,6 +12,23 @@ export const zh = { 'settings.saveFailed': '此部署未接受这些值,已保留以便修改。', 'settings.save': '保存', 'settings.saving': '保存中…', + 'hosts.title': '主机', + 'hosts.hint': '这些主机上的 {noun} 链接和 Git 远端会被识别。添加主机后,在终端用 {cli} 登录。', + 'hosts.unavailable': '主机设置不可用。', + 'hosts.add': '添加', + 'hosts.addLabel': '要添加的主机', + 'hosts.remove': '移除 {host}', + 'hosts.keepOne': '至少保留一个主机', + 'hosts.recheck': '重新检查登录状态', + 'hosts.state.ready': '已登录', + 'hosts.state.unauthenticated': '未登录', + 'hosts.state.unavailable': '无法检查', + 'hosts.state.checking': '检查中…', + 'hosts.state.unsaved': '未保存', + 'hosts.invalid': '主机名格式不对,例如 {example}', + 'hosts.duplicate': '{host} 已在列表中', + 'hosts.taken.github': '{host} 已由 GitHub 组件使用', + 'hosts.taken.gitlab': '{host} 已由 GitLab 组件使用', 'toast.archiveCleanupScheduled': '已归档,工作树将被清理', 'toast.archiveCleanupFailed': '已归档,工作树清理失败。分支已保留,请检查工作树。', 'review.startReview': '开始评审', @@ -424,6 +441,7 @@ export const zh = { 'toast.mergeFailed': '合并失败:{message}', 'toast.mergeStale': '{name} 有新的提交,确认后再合并', 'toast.pathCopied': '已复制路径', + 'toast.commandCopied': '已复制命令', 'toast.expandFailed': '无法显示未变更的行:{message}', 'toast.expandStale': '文件在读取变更后又有修改,刷新后再展开', 'toast.prompted': '已发送:{text}', @@ -544,8 +562,9 @@ export const zh = { 'reviewPage.requestReview': '请求评审', 'reviewPage.showAll': '显示全部 {count} 项', 'reviewPage.notFound': '变更请求不存在或没有访问权限', - 'reviewPage.unrecognized': 'DSH 不认识这个链接的主机', - 'reviewPage.unrecognizedHint': '只有已启用的代码托管组件所服务的主机能在这里打开。', + 'reviewPage.unrecognized': '未知的代码托管平台', + 'reviewPage.unrecognizedHint': '此链接的主机尚未添加到代码托管组件', + 'reviewPage.addHost': '添加主机…', 'reviewPage.loadFailed': '变更请求读取失败', 'reviewPage.markdown.copy': '复制', 'reviewPage.markdown.copied': '已复制', @@ -596,6 +615,23 @@ export const en: Record = { 'settings.saveFailed': 'The deployment did not accept these values; they were left for you to correct.', 'settings.save': 'Save', 'settings.saving': 'Saving…', + 'hosts.title': 'Hosts', + 'hosts.hint': '{noun} links and Git remotes on these hosts are recognized. After adding a host, sign in to it with {cli} in a terminal.', + 'hosts.unavailable': 'Host settings are unavailable.', + 'hosts.add': 'Add', + 'hosts.addLabel': 'Host to add', + 'hosts.remove': 'Remove {host}', + 'hosts.keepOne': 'Keep at least one host', + 'hosts.recheck': 'Check sign-in again', + 'hosts.state.ready': 'Signed in', + 'hosts.state.unauthenticated': 'Not signed in', + 'hosts.state.unavailable': 'Can\'t check', + 'hosts.state.checking': 'Checking…', + 'hosts.state.unsaved': 'Not saved', + 'hosts.invalid': 'Enter a host name such as {example}', + 'hosts.duplicate': '{host} is already in the list', + 'hosts.taken.github': 'The GitHub component already uses {host}', + 'hosts.taken.gitlab': 'The GitLab component already uses {host}', 'toast.archiveCleanupScheduled': 'Archived; the worktree will be cleaned up', 'toast.archiveCleanupFailed': 'Archived; worktree cleanup failed. The branch is retained. Check the worktree.', 'review.startReview': 'Start review', @@ -1008,6 +1044,7 @@ export const en: Record = { 'toast.mergeFailed': 'Could not merge: {message}', 'toast.mergeStale': '{name} has new commits; review them before merging', 'toast.pathCopied': 'Path copied', + 'toast.commandCopied': 'Command copied', 'toast.expandFailed': 'Unchanged lines could not be shown: {message}', 'toast.expandStale': 'The file changed after its changes were read; refresh before expanding', 'toast.prompted': 'Sent: {text}', @@ -1128,8 +1165,9 @@ export const en: Record = { 'reviewPage.requestReview': 'Request a review', 'reviewPage.showAll': 'Show all {count}', 'reviewPage.notFound': 'The change request does not exist or you cannot access it', - 'reviewPage.unrecognized': 'DSH does not recognize this link\'s host', - 'reviewPage.unrecognizedHint': 'Only hosts that an enabled code host component serves open here.', + 'reviewPage.unrecognized': 'Unknown code host', + 'reviewPage.unrecognizedHint': 'This link\'s host has not been added to a code host component.', + 'reviewPage.addHost': 'Add host…', 'reviewPage.loadFailed': 'Couldn\'t read the change request', 'reviewPage.markdown.copy': 'Copy', 'reviewPage.markdown.copied': 'Copied', @@ -1184,6 +1222,23 @@ export const ja: Record = { 'settings.saveFailed': 'このデプロイでは値が受け入れられませんでした。修正のために値はそのまま残されています。', 'settings.save': '保存', 'settings.saving': '保存中…', + 'hosts.title': 'ホスト', + 'hosts.hint': 'これらのホストの {noun} リンクと Git リモートを認識します。ホストを追加したら、ターミナルで {cli} を使ってログインしてください。', + 'hosts.unavailable': 'ホスト設定を利用できません。', + 'hosts.add': '追加', + 'hosts.addLabel': '追加するホスト', + 'hosts.remove': '{host} を削除', + 'hosts.keepOne': 'ホストを少なくとも 1 つ残してください', + 'hosts.recheck': 'ログイン状態を再確認', + 'hosts.state.ready': 'ログイン済み', + 'hosts.state.unauthenticated': '未ログイン', + 'hosts.state.unavailable': '確認できません', + 'hosts.state.checking': '確認中…', + 'hosts.state.unsaved': '未保存', + 'hosts.invalid': 'ホスト名の形式が正しくありません(例: {example})', + 'hosts.duplicate': '{host} はすでに一覧にあります', + 'hosts.taken.github': '{host} は GitHub コンポーネントが使用しています', + 'hosts.taken.gitlab': '{host} は GitLab コンポーネントが使用しています', 'toast.archiveCleanupScheduled': 'アーカイブしました。ワークツリーを削除します', 'toast.archiveCleanupFailed': 'アーカイブしましたが、ワークツリーの削除に失敗しました。ブランチは保持されています。ワークツリーを確認してください。', 'review.startReview': 'レビューを開始', @@ -1596,6 +1651,7 @@ export const ja: Record = { 'toast.mergeFailed': 'マージできませんでした:{message}', 'toast.mergeStale': '{name} に新しいコミットがあります。確認してからマージしてください', 'toast.pathCopied': 'パスをコピーしました', + 'toast.commandCopied': 'コマンドをコピーしました', 'toast.expandFailed': '未変更の行を表示できませんでした:{message}', 'toast.expandStale': '変更の読み取り後にファイルが更新されています。更新してから展開してください', 'toast.prompted': '送信しました:{text}', @@ -1716,8 +1772,9 @@ export const ja: Record = { 'reviewPage.requestReview': 'レビューを依頼', 'reviewPage.showAll': '{count}件すべて表示', 'reviewPage.notFound': '変更リクエストが存在しないか、アクセス権がありません', - 'reviewPage.unrecognized': 'DSH はこのリンクのホストを認識できません', - 'reviewPage.unrecognizedHint': '有効なコードホストコンポーネントが扱うホストだけをここで開けます。', + 'reviewPage.unrecognized': '不明なコードホスト', + 'reviewPage.unrecognizedHint': 'このリンクのホストはコードホストコンポーネントに追加されていません。', + 'reviewPage.addHost': 'ホストを追加…', 'reviewPage.loadFailed': '変更リクエストを読み込めませんでした', 'reviewPage.markdown.copy': 'コピー', 'reviewPage.markdown.copied': 'コピーしました', @@ -1765,6 +1822,23 @@ export const es: Record = { 'settings.saveFailed': 'La implementación no aceptó estos valores; se dejaron para que los corrijas.', 'settings.save': 'Guardar', 'settings.saving': 'Guardando…', + 'hosts.title': 'Hosts', + 'hosts.hint': 'Se reconocen los enlaces de {noun} y los remotos de Git de estos hosts. Después de añadir un host, inicia sesión en él con {cli} en una terminal.', + 'hosts.unavailable': 'La configuración de hosts no está disponible.', + 'hosts.add': 'Añadir', + 'hosts.addLabel': 'Host que se va a añadir', + 'hosts.remove': 'Quitar {host}', + 'hosts.keepOne': 'Conserva al menos un host', + 'hosts.recheck': 'Comprobar de nuevo el inicio de sesión', + 'hosts.state.ready': 'Sesión iniciada', + 'hosts.state.unauthenticated': 'Sin iniciar sesión', + 'hosts.state.unavailable': 'No se puede comprobar', + 'hosts.state.checking': 'Comprobando…', + 'hosts.state.unsaved': 'Sin guardar', + 'hosts.invalid': 'Escribe un nombre de host, por ejemplo {example}', + 'hosts.duplicate': '{host} ya está en la lista', + 'hosts.taken.github': 'El componente de GitHub ya usa {host}', + 'hosts.taken.gitlab': 'El componente de GitLab ya usa {host}', 'toast.archiveCleanupScheduled': 'Archivado; se eliminará el árbol de trabajo', 'toast.archiveCleanupFailed': 'Archivado; no se pudo eliminar el árbol de trabajo. La rama se conserva. Revisa el árbol de trabajo.', 'review.startReview': 'Iniciar revisión', @@ -2177,6 +2251,7 @@ export const es: Record = { 'toast.mergeFailed': 'No se pudo fusionar: {message}', 'toast.mergeStale': '{name} tiene nuevos commits; revísalos antes de fusionar', 'toast.pathCopied': 'Ruta copiada', + 'toast.commandCopied': 'Comando copiado', 'toast.expandFailed': 'No se pudieron mostrar las líneas sin cambios: {message}', 'toast.expandStale': 'El archivo cambió después de leer sus cambios; actualiza antes de expandir', 'toast.prompted': 'Enviado: {text}', @@ -2297,8 +2372,9 @@ export const es: Record = { 'reviewPage.requestReview': 'Solicitar revisión', 'reviewPage.showAll': 'Mostrar los {count}', 'reviewPage.notFound': 'La solicitud de cambio no existe o no tienes acceso', - 'reviewPage.unrecognized': 'DSH no reconoce el host de este enlace', - 'reviewPage.unrecognizedHint': 'Aquí solo se abren hosts que atiende un componente de servicio de código activado.', + 'reviewPage.unrecognized': 'Servicio de código desconocido', + 'reviewPage.unrecognizedHint': 'El host de este enlace no se ha añadido a ningún componente de servicio de código.', + 'reviewPage.addHost': 'Añadir host…', 'reviewPage.loadFailed': 'No se pudo leer la solicitud de cambio', 'reviewPage.markdown.copy': 'Copiar', 'reviewPage.markdown.copied': 'Copiado', @@ -2346,6 +2422,23 @@ export const fr: Record = { 'settings.saveFailed': 'Le déploiement n’a pas accepté ces valeurs ; elles ont été laissées pour correction.', 'settings.save': 'Enregistrer', 'settings.saving': 'Enregistrement…', + 'hosts.title': 'Hôtes', + 'hosts.hint': 'Les liens de {noun} et les dépôts distants Git de ces hôtes sont reconnus. Après avoir ajouté un hôte, connectez-vous-y avec {cli} dans un terminal.', + 'hosts.unavailable': 'Les paramètres des hôtes sont indisponibles.', + 'hosts.add': 'Ajouter', + 'hosts.addLabel': 'Hôte à ajouter', + 'hosts.remove': 'Retirer {host}', + 'hosts.keepOne': 'Conservez au moins un hôte', + 'hosts.recheck': 'Vérifier à nouveau la connexion', + 'hosts.state.ready': 'Connecté', + 'hosts.state.unauthenticated': 'Non connecté', + 'hosts.state.unavailable': 'Vérification impossible', + 'hosts.state.checking': 'Vérification…', + 'hosts.state.unsaved': 'Non enregistré', + 'hosts.invalid': 'Saisissez un nom d’hôte, par exemple {example}', + 'hosts.duplicate': '{host} figure déjà dans la liste', + 'hosts.taken.github': 'Le composant GitHub utilise déjà {host}', + 'hosts.taken.gitlab': 'Le composant GitLab utilise déjà {host}', 'toast.archiveCleanupScheduled': 'Archivé ; l’arbre de travail sera supprimé', 'toast.archiveCleanupFailed': 'Archivé ; échec de la suppression de l’arbre de travail. La branche est conservée. Vérifiez l’arbre de travail.', 'review.startReview': 'Commencer la revue', @@ -2758,6 +2851,7 @@ export const fr: Record = { 'toast.mergeFailed': 'Impossible de fusionner : {message}', 'toast.mergeStale': '{name} contient de nouveaux commits ; vérifiez-les avant de fusionner', 'toast.pathCopied': 'Chemin copié', + 'toast.commandCopied': 'Commande copiée', 'toast.expandFailed': 'Impossible d’afficher les lignes inchangées : {message}', 'toast.expandStale': 'Le fichier a changé depuis la lecture des modifications ; actualisez avant de développer', 'toast.prompted': 'Envoyé : {text}', @@ -2878,8 +2972,9 @@ export const fr: Record = { 'reviewPage.requestReview': 'Demander une revue', 'reviewPage.showAll': 'Afficher les {count}', 'reviewPage.notFound': 'La demande de modification n\'existe pas ou vous n\'y avez pas accès', - 'reviewPage.unrecognized': 'DSH ne reconnaît pas l\'hôte de ce lien', - 'reviewPage.unrecognizedHint': 'Seuls les hôtes servis par un composant d\'hébergement de code activé s\'ouvrent ici.', + 'reviewPage.unrecognized': 'Hébergement de code inconnu', + 'reviewPage.unrecognizedHint': 'L’hôte de ce lien n’a été ajouté à aucun composant d’hébergement de code.', + 'reviewPage.addHost': 'Ajouter un hôte…', 'reviewPage.loadFailed': 'Impossible de lire la demande de modification', 'reviewPage.markdown.copy': 'Copier', 'reviewPage.markdown.copied': 'Copié', @@ -2927,6 +3022,23 @@ export const de: Record = { 'settings.saveFailed': 'Die Bereitstellung hat diese Werte nicht übernommen; sie wurden zur Korrektur belassen.', 'settings.save': 'Speichern', 'settings.saving': 'Wird gespeichert…', + 'hosts.title': 'Hosts', + 'hosts.hint': '{noun}-Links und Git-Remotes auf diesen Hosts werden erkannt. Melden Sie sich nach dem Hinzufügen eines Hosts im Terminal mit {cli} dort an.', + 'hosts.unavailable': 'Die Host-Einstellungen sind nicht verfügbar.', + 'hosts.add': 'Hinzufügen', + 'hosts.addLabel': 'Hinzuzufügender Host', + 'hosts.remove': '{host} entfernen', + 'hosts.keepOne': 'Mindestens ein Host muss bleiben', + 'hosts.recheck': 'Anmeldung erneut prüfen', + 'hosts.state.ready': 'Angemeldet', + 'hosts.state.unauthenticated': 'Nicht angemeldet', + 'hosts.state.unavailable': 'Prüfung nicht möglich', + 'hosts.state.checking': 'Wird geprüft…', + 'hosts.state.unsaved': 'Nicht gespeichert', + 'hosts.invalid': 'Geben Sie einen Hostnamen ein, zum Beispiel {example}', + 'hosts.duplicate': '{host} steht bereits in der Liste', + 'hosts.taken.github': 'Die GitHub-Komponente verwendet {host} bereits', + 'hosts.taken.gitlab': 'Die GitLab-Komponente verwendet {host} bereits', 'toast.archiveCleanupScheduled': 'Archiviert; der Arbeitsbaum wird entfernt', 'toast.archiveCleanupFailed': 'Archiviert; der Arbeitsbaum konnte nicht entfernt werden. Der Branch bleibt erhalten. Prüfe den Arbeitsbaum.', 'review.startReview': 'Review starten', @@ -3339,6 +3451,7 @@ export const de: Record = { 'toast.mergeFailed': 'Zusammenführung fehlgeschlagen: {message}', 'toast.mergeStale': '{name} enthält neue Commits; vor dem Zusammenführen prüfen', 'toast.pathCopied': 'Pfad kopiert', + 'toast.commandCopied': 'Befehl kopiert', 'toast.expandFailed': 'Unveränderte Zeilen konnten nicht angezeigt werden: {message}', 'toast.expandStale': 'Die Datei wurde nach dem Lesen der Änderungen verändert; vor dem Aufklappen aktualisieren', 'toast.prompted': 'Gesendet: {text}', @@ -3459,8 +3572,9 @@ export const de: Record = { 'reviewPage.requestReview': 'Review anfordern', 'reviewPage.showAll': 'Alle {count} anzeigen', 'reviewPage.notFound': 'Die Änderungsanfrage existiert nicht oder Sie haben keinen Zugriff', - 'reviewPage.unrecognized': 'DSH erkennt den Host dieses Links nicht', - 'reviewPage.unrecognizedHint': 'Hier öffnen sich nur Hosts, die eine aktivierte Code-Host-Komponente bedient.', + 'reviewPage.unrecognized': 'Unbekannter Code-Host', + 'reviewPage.unrecognizedHint': 'Der Host dieses Links wurde keiner Code-Host-Komponente hinzugefügt.', + 'reviewPage.addHost': 'Host hinzufügen…', 'reviewPage.loadFailed': 'Änderungsanfrage konnte nicht gelesen werden', 'reviewPage.markdown.copy': 'Kopieren', 'reviewPage.markdown.copied': 'Kopiert', @@ -3508,6 +3622,23 @@ export const ru: Record = { 'settings.saveFailed': 'Развёртывание не приняло эти значения; они оставлены для исправления.', 'settings.save': 'Сохранить', 'settings.saving': 'Сохранение…', + 'hosts.title': 'Хосты', + 'hosts.hint': 'Ссылки на {noun} и удалённые репозитории Git на этих хостах распознаются. Добавив хост, войдите на него через {cli} в терминале.', + 'hosts.unavailable': 'Настройки хостов недоступны.', + 'hosts.add': 'Добавить', + 'hosts.addLabel': 'Добавляемый хост', + 'hosts.remove': 'Убрать {host}', + 'hosts.keepOne': 'Оставьте хотя бы один хост', + 'hosts.recheck': 'Проверить вход ещё раз', + 'hosts.state.ready': 'Вход выполнен', + 'hosts.state.unauthenticated': 'Вход не выполнен', + 'hosts.state.unavailable': 'Не удаётся проверить', + 'hosts.state.checking': 'Проверка…', + 'hosts.state.unsaved': 'Не сохранено', + 'hosts.invalid': 'Введите имя хоста, например {example}', + 'hosts.duplicate': '{host} уже есть в списке', + 'hosts.taken.github': 'Компонент GitHub уже использует {host}', + 'hosts.taken.gitlab': 'Компонент GitLab уже использует {host}', 'toast.archiveCleanupScheduled': 'Архивировано; рабочее дерево будет удалено', 'toast.archiveCleanupFailed': 'Архивировано; не удалось удалить рабочее дерево. Ветка сохранена. Проверьте рабочее дерево.', 'review.startReview': 'Начать проверку', @@ -3920,6 +4051,7 @@ export const ru: Record = { 'toast.mergeFailed': 'Не удалось объединить: {message}', 'toast.mergeStale': 'В {name} есть новые коммиты; проверьте их перед слиянием', 'toast.pathCopied': 'Путь скопирован', + 'toast.commandCopied': 'Команда скопирована', 'toast.expandFailed': 'Не удалось показать неизменённые строки: {message}', 'toast.expandStale': 'Файл изменился после чтения изменений; обновите перед разворачиванием', 'toast.prompted': 'Отправлено: {text}', @@ -4040,8 +4172,9 @@ export const ru: Record = { 'reviewPage.requestReview': 'Запросить ревью', 'reviewPage.showAll': 'Показать все {count}', 'reviewPage.notFound': 'Запрос на изменение не существует или у вас нет доступа', - 'reviewPage.unrecognized': 'DSH не распознаёт хост этой ссылки', - 'reviewPage.unrecognizedHint': 'Здесь открываются только хосты, которые обслуживает включённый компонент хостинга кода.', + 'reviewPage.unrecognized': 'Неизвестный хостинг кода', + 'reviewPage.unrecognizedHint': 'Хост этой ссылки не добавлен ни в один компонент хостинга кода.', + 'reviewPage.addHost': 'Добавить хост…', 'reviewPage.loadFailed': 'Не удалось прочитать запрос на изменение', 'reviewPage.markdown.copy': 'Копировать', 'reviewPage.markdown.copied': 'Скопировано', @@ -4089,6 +4222,23 @@ export const pt: Record = { 'settings.saveFailed': 'A implantação não aceitou estes valores; eles foram mantidos para correção.', 'settings.save': 'Salvar', 'settings.saving': 'Salvando…', + 'hosts.title': 'Hosts', + 'hosts.hint': 'Os links de {noun} e os remotos do Git nestes hosts são reconhecidos. Depois de adicionar um host, entre nele com {cli} em um terminal.', + 'hosts.unavailable': 'As configurações de hosts não estão disponíveis.', + 'hosts.add': 'Adicionar', + 'hosts.addLabel': 'Host a adicionar', + 'hosts.remove': 'Remover {host}', + 'hosts.keepOne': 'Mantenha pelo menos um host', + 'hosts.recheck': 'Verificar o login novamente', + 'hosts.state.ready': 'Conectado', + 'hosts.state.unauthenticated': 'Não conectado', + 'hosts.state.unavailable': 'Não é possível verificar', + 'hosts.state.checking': 'Verificando…', + 'hosts.state.unsaved': 'Não salvo', + 'hosts.invalid': 'Digite um nome de host, por exemplo {example}', + 'hosts.duplicate': '{host} já está na lista', + 'hosts.taken.github': 'O componente do GitHub já usa {host}', + 'hosts.taken.gitlab': 'O componente do GitLab já usa {host}', 'toast.archiveCleanupScheduled': 'Arquivado; a árvore de trabalho será removida', 'toast.archiveCleanupFailed': 'Arquivado; a remoção da árvore de trabalho falhou. O ramo foi mantido. Verifique a árvore de trabalho.', 'review.startReview': 'Iniciar revisão', @@ -4501,6 +4651,7 @@ export const pt: Record = { 'toast.mergeFailed': 'Não foi possível mesclar: {message}', 'toast.mergeStale': '{name} tem novos commits; revise-os antes de mesclar', 'toast.pathCopied': 'Caminho copiado', + 'toast.commandCopied': 'Comando copiado', 'toast.expandFailed': 'Não foi possível mostrar as linhas sem alterações: {message}', 'toast.expandStale': 'O arquivo mudou após a leitura das alterações; atualize antes de expandir', 'toast.prompted': 'Enviado: {text}', @@ -4621,8 +4772,9 @@ export const pt: Record = { 'reviewPage.requestReview': 'Solicitar revisão', 'reviewPage.showAll': 'Mostrar todos os {count}', 'reviewPage.notFound': 'A solicitação de alteração não existe ou você não tem acesso', - 'reviewPage.unrecognized': 'O DSH não reconhece o host deste link', - 'reviewPage.unrecognizedHint': 'Aqui só abrem hosts atendidos por um componente de serviço de código ativado.', + 'reviewPage.unrecognized': 'Serviço de código desconhecido', + 'reviewPage.unrecognizedHint': 'O host deste link não foi adicionado a nenhum componente de serviço de código.', + 'reviewPage.addHost': 'Adicionar host…', 'reviewPage.loadFailed': 'Não foi possível ler a solicitação de alteração', 'reviewPage.markdown.copy': 'Copiar', 'reviewPage.markdown.copied': 'Copiado', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index 7114c97cf0..739047752a 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -43,6 +43,9 @@ import { ChangesTabTitle } from './ChangesTabTitle.tsx' import { CheckoutRow, ConnectionRow, LocalChangesRow, type CheckoutRowInjected, type ConnectionRowInjected, type LocalChangesRowInjected, } from './EnvironmentRows.tsx' +import { HostSettings, type HostForge, type HostSettingsInjected } from './HostSettings.tsx' +import { HostSettingsForm, type HostSettings as HostSettingsFields } from './host-settings-form.ts' +import { HostSignInStates } from './host-sign-in.ts' import { de, en, es, fr, ja, NS, pt, ru, zh, type ForgePanelKey } from './locales.ts' import type { SessionListInjected } from './session-list.ts' import { SessionHoverForge } from './SessionHoverForge.tsx' @@ -60,12 +63,24 @@ import { WorktreeToggle, type WorktreeToggleInjected } from './WorktreeToggle.ts /** Services required before the Remote contribution mounts. */ export const inject = ['remote', 'slots', 'locale', 'sidebarRightTabs', 'sidebarRight', 'sessions', 'configForms', 'remoteAccess', 'workspaces', 'uiWorkspace'] +/** The Forge bundle, whose page on the Plugins page lists the rows below. */ +export const FORGE_BUNDLE = '@deepseek-ai/dsh-experimental-forge-bundle' + /** The worktree row of the Forge bundle, whose Plugins page carries the archive cleanup switch. */ -export const WORKTREE_ROW_KEY = '@deepseek-ai/dsh-experimental-forge-bundle#worktree' +export const WORKTREE_ROW_KEY = `${FORGE_BUNDLE}#worktree` /** The Loader entry id the worktree service's settings namespace follows. */ export const WORKTREE_NS = 'worktree' +/** + * The provider rows of the Forge bundle whose Plugins pages carry a host list. A row's id is also the Loader entry id + * its settings namespace follows. + */ +export const HOST_ROWS: readonly { readonly forge: HostForge; readonly row: string }[] = [ + { forge: 'github', row: 'forge-github' }, + { forge: 'gitlab', row: 'forge-gitlab' }, +] + /** * Open a URL in a new browsing context without giving it access to this page. * @param url - change request web URL. @@ -524,12 +539,35 @@ function registerUi(ctx: Context): void { }, SessionHoverForge)) registerReviewPage(ctx, { notices, settled, nameOf, openLink, copyText, copyPath, locale, quoteReview: addReviewToInput, quoteThread: addThreadToInput, + hostSettings: FORGE_BUNDLE, }) const worktreeSettings = new WorktreeSettingsForm(ctx.configForms.get(WORKTREE_NS)) ctx.effect(() => () => { worktreeSettings.dispose() }, 'forge-panel: worktree settings form') ctx.slots.inject('plugins.row.config', () => ctx.slots.register({ name: 'plugins.row.config', key: WORKTREE_ROW_KEY, locale: NS, inject: () => worktreeSettings.inject(), }, WorktreeSettings)) + const hostRows = HOST_ROWS.map(row => ({ ...row, scope: ctx.configForms.get(row.row) })) + for (const { forge, row, scope } of hostRows) { + // A host has one provider, so a row refuses the hosts the other rows serve now. + const taken = (): string[] => hostRows.flatMap(other => other.row === row ? [] : other.scope.getSnapshot().value?.hosts ?? []) + const form = new HostSettingsForm(scope, taken) + const signIn = new HostSignInStates((host, signal) => ctx.remote.forgePanel.hostReadiness(forge, host, signal)) + ctx.effect(() => () => { + form.dispose() + signIn.dispose() + }, `forge-panel: ${row} host settings`) + const { hooks, ...actions } = form.inject() + const face: HostSettingsInjected = { + ...actions, + hooks: { ...hooks, signIn: signIn.states }, + forge, + checkSignIn: (hosts, visibly) => { signIn.check(hosts, visibly) }, + copyCommand: (command) => { copy(command, 'toast.commandCopied') }, + } + ctx.slots.inject('plugins.row.config', () => ctx.slots.register({ + name: 'plugins.row.config', key: `${FORGE_BUNDLE}#${row}`, locale: NS, inject: () => face, + }, HostSettings)) + } } /** diff --git a/packages/experimental/client-ui-forge/src/client/review-page/ReviewDetail.tsx b/packages/experimental/client-ui-forge/src/client/review-page/ReviewDetail.tsx index 91ce79bd09..12291c9a19 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/ReviewDetail.tsx +++ b/packages/experimental/client-ui-forge/src/client/review-page/ReviewDetail.tsx @@ -67,6 +67,8 @@ export interface ReviewDetailProps { readonly actions: ChangeRequestActions /** Read the description and labels. */ readonly readDescription: (url: string, signal: AbortSignal) => Promise> + /** Open the providers' host lists, offered for a URL no provider serves; undefined while they cannot be opened. */ + readonly onAddHost: (() => void) | undefined /** The changes tab's content, kept while the detail shows so pending review comments survive tab switches. */ readonly renderChanges: (frame: ForgeReviewChangeRequest) => ReactNode /** The chat tab's content. */ @@ -221,8 +223,8 @@ function Summary({ frame, snapshot, description, now, locale, actions, t }: { * @returns the detail. */ export function ReviewDetail({ - url, read, tab, onTab, listHidden, onToggleList, onBack, now, locale, actions, readDescription, renderChanges, renderChat, unseenQuotes, - t, + url, read, tab, onTab, listHidden, onToggleList, onBack, now, locale, actions, readDescription, onAddHost, renderChanges, renderChat, + unseenQuotes, t, }: ReviewDetailProps): ReactNode { const frame = read.frame const snapshot = frame?.snapshot ?? null @@ -244,7 +246,15 @@ export function ReviewDetail({ const failure = frame?.update !== undefined && frame.update !== null && 'failure' in frame.update ? frame.update.failure : undefined let body: ReactNode = if (read.stopped?.code === 'forgePanel/unrecognized-url') { - body = <>

    {t('reviewPage.unrecognized')}

    {t('reviewPage.unrecognizedHint')}

    + body = ( + <> +

    {t('reviewPage.unrecognized')}

    +

    {t('reviewPage.unrecognizedHint')}

    + {onAddHost !== undefined && ( +
    + )} + + ) } else if (read.stopped !== null || failure !== undefined) { body = ( <> diff --git a/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx b/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx index 7b77e505f9..99f429d0ef 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx +++ b/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx @@ -39,8 +39,12 @@ const CHAT_QUOTE_COPY: QuoteCopy = { add: 'reviewPage.addToChat', added: 'review /** Business face of the review page. */ export interface ReviewPageInjected { - /** The UI language; the renderer binds it as `useLocale`. */ - readonly hooks: { readonly locale: HostObservable } + readonly hooks: { + /** The UI language; the renderer binds it as `useLocale`. */ + readonly locale: HostObservable + /** Whether the Plugins page can be opened; the renderer binds it as `usePluginNavigation`. */ + readonly pluginNavigation: HostObservable + } /** Open the list stream of one repository, named `owner/name`, or of every repository for the empty string. */ readonly openLists: (scope: string, signal: AbortSignal) => HostStream /** Open the stream of one change request by URL. */ @@ -51,6 +55,8 @@ export interface ReviewPageInjected { readonly refresh: () => Promise /** Read the description and labels of a change request. */ readonly readDescription: (url: string, signal: AbortSignal) => Promise> + /** Open the Plugins page where the providers' hosts are listed, while `pluginNavigation` holds. */ + readonly openHostSettings: () => void /** The card actions acting on one change request; `showChanges` opens the changes tab. */ readonly actionsFor: (url: string, showChanges: () => void) => ChangeRequestActions /** Reads and writes of the changes view. */ @@ -149,6 +155,7 @@ function DetailPane({ url, read, tab, listHidden, now, locale, cardActions, conversationId, onConversation, unseenQuotes, page, }: DetailPaneProps): ReactNode { const { actions, changes, chat, quoteReview, quoteThread, readDescription, renderSlot, SessionProvider, useStore, t } = page + const hostSettings = page.usePluginNavigation(value => value) const conversation = useReviewConversation(read.frame, conversationId, onConversation, chat) const { start } = conversation const quoteChanges = useMemo(() => { @@ -178,6 +185,7 @@ function DetailPane({ locale={locale} actions={cardActions} readDescription={readDescription} + onAddHost={hostSettings ? page.openHostSettings : undefined} renderChanges={frame => ( )} diff --git a/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts b/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts index 1664d5fdba..d4fa6a30f9 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts +++ b/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts @@ -7,7 +7,9 @@ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-api-remote-access/client' import type {} from '@deepseek-ai/dsh-api-session-controller/client' import type {} from '@deepseek-ai/dsh-api-workspace-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' @@ -66,6 +68,8 @@ export interface ReviewPageDeps { readonly quoteThread: ReviewPageInjected['quoteThread'] /** The UI language. */ readonly locale: HostObservable + /** Package name of the bundle whose page on the Plugins page lists the provider rows with their host lists. */ + readonly hostSettings: string } /** @@ -183,6 +187,14 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void { void remote.requestWorktree(sessionId, null, null).then(result => settled(result, 'toast.worktreeFailed')) }, } + // The Plugins page provides its navigation only while the current Peer may use it. + const pluginNavigation = createSnapshotStore(false) + ctx.inject(['pluginNavigation'], (scope: Context) => { + scope.effect(() => { + pluginNavigation.set(true) + return () => { pluginNavigation.set(false) } + }, 'forge-panel: plugin navigation presence') + }) const count = createStreamSource({ open: signal => remote.reviewCount(signal), subscribeReset, @@ -195,7 +207,7 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void { locale: NS, store: createReviewStore(), inject: (): ReviewPageInjected => ({ - hooks: { locale: deps.locale }, + hooks: { locale: deps.locale, pluginNavigation }, openLists: (scope, signal) => { const slash = scope.indexOf('/') return remote.reviewLists(slash < 0 ? null : { owner: scope.slice(0, slash), name: scope.slice(slash + 1) }, signal) @@ -204,6 +216,7 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void { subscribeReset, refresh: async () => { settled(await remote.reviewRefresh(), 'toast.refreshFailed') }, readDescription: (url, signal) => remote.reviewDescription(url, signal), + openHostSettings: () => { ctx.get('pluginNavigation')?.openBundle(deps.hostSettings) }, actionsFor, changes, copyText, diff --git a/packages/experimental/client-ui-forge/src/client/row-form-labels.ts b/packages/experimental/client-ui-forge/src/client/row-form-labels.ts new file mode 100644 index 0000000000..996017180d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/row-form-labels.ts @@ -0,0 +1,17 @@ +/** Copy of the Plugins form that the row pages of the Forge bundle share. */ +import type { SettingsFormLabels } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ForgePanelKey, NS } from './locales.ts' + +/** + * Build the form copy of one row page. + * @param t - forge panel copy. + * @param unavailable - key of the text shown while the Host does not serve the row's form. + * @returns the labels of the shared settings form. + */ +export function rowFormLabels(t: PropsLocale['t'], unavailable: ForgePanelKey): SettingsFormLabels { + return { + unavailable: t(unavailable), readOnly: t('settings.readOnly'), saveFailed: t('settings.saveFailed'), + save: t('settings.save'), saving: t('settings.saving'), + } +} diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index f575805b8c..d330f4bfce 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -9,7 +9,8 @@ import type { BranchUpdateMethod, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeActionFailure, ForgeCommitList, ForgeFailure, - ForgeLineComment, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, + ForgeLineComment, ForgeReadiness, 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' @@ -19,7 +20,7 @@ import type { Session, SessionEvent, SessionId, UserMessage } from '@deepseek-ai import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' import type {} from '@deepseek-ai/dsh-session-query' -import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { assertNever } from '@deepseek-ai/dsh-util-values' import { gitIn, hasBranch, inspectCheckout } from './git.ts' @@ -315,6 +316,28 @@ export class ForgePanelController extends TypertRemoteService { this.viewerLists.refresh() } + /** + * Report whether a provider reaches one of its hosts with the Host's current credentials, for the host list on the + * Plugins page of that provider's row. The read names no Session, so, like the review page reads, only callers that + * may use the Host's code host credentials reach it. + * @param forge - forge family of a registered provider, such as `gitlab`. + * @param host - host name as the provider's configuration lists it. + * @param signal - request cancellation. + * @returns the provider's readiness for the host; `unavailable` with the reason when no provider serves the family, + * the probe fails, or it runs past `readinessTimeoutMs`. + */ + @Remote + async hostReadiness(forge: string, host: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + try { + using timeout = deadline(signal, this.config.readinessTimeoutMs, 'FORGE_PANEL_READINESS_TIMEOUT') + return await this.home.forge.readiness({ forge, host: host.toLowerCase() }, timeout.signal) + } catch (error) { + signal.throwIfAborted() + return { state: 'unavailable', message: messageOf(error), signIn: null } + } + } + /** * Poll one change request the review page shows at once; its stream reports the result. * @param url - web URL of the change request. diff --git a/packages/experimental/client-ui-forge/tests/host-readiness.host.spec.ts b/packages/experimental/client-ui-forge/tests/host-readiness.host.spec.ts new file mode 100644 index 0000000000..f4c85fb8c1 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/host-readiness.host.spec.ts @@ -0,0 +1,82 @@ +/** `forgePanel.hostReadiness`, which the host list on a provider row's Plugins page reads. */ +import { afterEach, describe, expect, it } from 'vitest' +import type { ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge' +import type { Config } from '../src/index.ts' +import { bench, scratch } from './harness.ts' +import type { Bench } from './harness.ts' + +const cleanups: (() => Promise)[] = [] + +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() +}) + +const signal = new AbortController().signal + +/** A panel Remote whose Session directory is no checkout; the read names no Session. */ +async function opened(config: Config = {}): Promise { + const { path, remove } = await scratch('dsh-forge-host-readiness-') + cleanups.push(remove) + const result = await bench(path, config) + cleanups.push(() => result.ctx.fiber.dispose()) + return result +} + +describe('forgePanel.hostReadiness', () => { + it('reports the provider\'s readiness for the host in lowercase', async () => { + const { ctx, provider } = await opened() + const signIn: ForgeReadiness = { state: 'unauthenticated', message: 'not signed in', signIn: { command: 'fake auth login --hostname fake.test' } } + const probed: string[] = [] + provider.readinessImpl = (host) => { probed.push(host); return Promise.resolve(signIn) } + + await expect(ctx.forgePanel.hostReadiness('fake', 'Fake.TEST', signal)).resolves.toEqual(signIn) + + expect(probed).toEqual(['fake.test']) + }) + + it('reports a family no provider serves as unavailable', async () => { + const { ctx } = await opened() + + await expect(ctx.forgePanel.hostReadiness('absent', 'absent.test', signal)).resolves.toEqual({ + state: 'unavailable', message: 'forge: no provider is registered for "absent"', signIn: null, + }) + }) + + it('reports a probe that fails as unavailable with its reason', async () => { + const { ctx, provider } = await opened() + provider.readinessImpl = () => Promise.reject(new Error('fake: connection refused')) + + await expect(ctx.forgePanel.hostReadiness('fake', 'fake.test', signal)).resolves.toEqual({ + state: 'unavailable', message: 'fake: connection refused', signIn: null, + }) + }) + + it('reports a probe past readinessTimeoutMs as unavailable', async () => { + const { ctx, provider } = await opened({ readinessTimeoutMs: 50 }) + provider.readinessImpl = (_host, abort) => new Promise((_resolve, reject) => { + abort.addEventListener('abort', () => { reject(abort.reason as Error) }) + }) + + await expect(ctx.forgePanel.hostReadiness('fake', 'fake.test', signal)).resolves.toEqual({ + state: 'unavailable', message: 'FORGE_PANEL_READINESS_TIMEOUT after 50ms', signIn: null, + }) + }) + + it('rejects when the caller cancels before or during the probe', async () => { + const { ctx, provider } = await opened() + const stopped = new Error('caller left') + await expect(ctx.forgePanel.hostReadiness('fake', 'fake.test', AbortSignal.abort(stopped))).rejects.toBe(stopped) + + const caller = new AbortController() + const entered = Promise.withResolvers() + provider.readinessImpl = (_host, abort) => new Promise((_resolve, reject) => { + abort.addEventListener('abort', () => { reject(abort.reason as Error) }) + entered.resolve(undefined) + }) + const read = ctx.forgePanel.hostReadiness('fake', 'fake.test', caller.signal) + await entered.promise + caller.abort(stopped) + + await expect(read).rejects.toBe(stopped) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/host-settings-form.client.spec.ts b/packages/experimental/client-ui-forge/tests/host-settings-form.client.spec.ts new file mode 100644 index 0000000000..2c2f788f7e --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/host-settings-form.client.spec.ts @@ -0,0 +1,82 @@ +/** The staged host list of a provider row: what a typed host stages, what is refused, and what one save writes. */ +import { expect, it, vi } from 'vitest' +import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { HostSettingsForm, typedHost, type HostSettings } from '../src/client/host-settings-form.ts' + +/** A form over a row that serves `gitlab.com`, with the hosts `taken` by other rows. */ +function mounted(taken: readonly string[] = []) { + const scope = stubConfigForm() + scope.publish({ status: 'ready', value: { hosts: ['gitlab.com'] }, base: { hosts: ['gitlab.com'] }, user: {}, writable: true, revision: 4 }) + const form = new HostSettingsForm(scope.scope, () => taken) + const { hooks, ...actions } = form.inject() + return { scope, form, state: () => hooks.hostForm.getSnapshot(), ...actions } +} + +it.each([ + [' GitLab.Example.com ', 'gitlab.example.com'], + ['https://GitLab.example.com:8443/group/app/-/merge_requests/2', 'gitlab.example.com:8443'], + ['ssh://git@gitlab.example.com/group/app.git', 'gitlab.example.com'], + ['https://', 'https://'], + ['a b', 'a b'], + ['', ''], +])('reads %j as the host %j', (text, host) => { + expect(typedHost(text)).toBe(host) +}) + +it('shows no hosts before the Host serves the row', () => { + const scope = stubConfigForm() + const form = new HostSettingsForm(scope.scope, () => []) + try { + expect(form.inject().hooks.hostForm.getSnapshot()).toMatchObject({ available: false, dirty: false, saved: [], draft: [] }) + } finally { form.dispose() } +}) + +it('stages added hosts and writes the whole list in one save', async () => { + const m = mounted() + try { + expect(m.state()).toMatchObject({ available: true, dirty: false, saved: ['gitlab.com'], draft: ['gitlab.com'] }) + + expect(m.add('https://GitLab.Example.com/group/app/-/merge_requests/2')).toBeUndefined() + expect(m.add('git.corp.example:8443')).toBeUndefined() + + expect(m.state()).toMatchObject({ dirty: true, invalid: false, saved: ['gitlab.com'], draft: ['gitlab.com', 'gitlab.example.com', 'git.corp.example:8443'] }) + expect(m.scope.mutate).not.toHaveBeenCalled() + m.save() + await vi.waitFor(() => { + expect(m.scope.mutate).toHaveBeenCalledWith([{ op: 'set', path: ['hosts'], value: ['gitlab.com', 'gitlab.example.com', 'git.corp.example:8443'] }], 4) + }) + } finally { m.form.dispose() } + expect(m.scope.listenerCount()).toBe(0) +}) + +it('stages nothing for blank text, a malformed host, a listed host, or a host another row serves', () => { + const m = mounted(['GitHub.com']) + try { + expect(m.add(' ')).toBeUndefined() + expect(m.add('a b')).toEqual({ kind: 'invalid' }) + expect(m.add('-gitlab.example.com')).toEqual({ kind: 'invalid' }) + expect(m.add('GITLAB.com')).toEqual({ kind: 'duplicate', host: 'gitlab.com' }) + expect(m.add('https://github.com/octo/demo/pull/1')).toEqual({ kind: 'taken', host: 'github.com' }) + + expect(m.state()).toMatchObject({ dirty: false, draft: ['gitlab.com'] }) + } finally { m.form.dispose() } +}) + +it('stages removals but keeps the last host, and drops the staged list on discard', async () => { + const m = mounted() + try { + m.remove('gitlab.com') + expect(m.state()).toMatchObject({ dirty: false, draft: ['gitlab.com'] }) + + m.add('gitlab.example.com') + m.remove('gitlab.com') + expect(m.state()).toMatchObject({ dirty: true, draft: ['gitlab.example.com'] }) + m.discard() + expect(m.state()).toMatchObject({ dirty: false, draft: ['gitlab.com'] }) + + m.add('gitlab.example.com') + m.remove('gitlab.com') + m.save() + await vi.waitFor(() => { expect(m.scope.mutate).toHaveBeenCalledWith([{ op: 'set', path: ['hosts'], value: ['gitlab.example.com'] }], 4) }) + } finally { m.form.dispose() } +}) diff --git a/packages/experimental/client-ui-forge/tests/host-settings.client.spec.tsx b/packages/experimental/client-ui-forge/tests/host-settings.client.spec.tsx new file mode 100644 index 0000000000..f1bdd21607 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/host-settings.client.spec.tsx @@ -0,0 +1,212 @@ +// @vitest-environment jsdom +/** A provider row's host page: the list with each host's sign-in state, staged additions and removals, and one save. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, within } from '@testing-library/react' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { bindSnapshotSelector, makeTranslate, stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { HostSettings, type HostForge, type HostSettingsProps } from '../src/client/HostSettings.tsx' +import { HostSettingsForm, type HostSettings as HostSettingsFields } from '../src/client/host-settings-form.ts' +import type { HostSignIn } from '../src/client/host-sign-in.ts' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) + +const t = makeTranslate(en) +const COMMAND = 'glab auth login --hostname gitlab.example.com' + +interface MountOptions { + readonly forge?: HostForge + readonly view?: 'page' | 'summary' + readonly hosts?: string[] + readonly taken?: readonly string[] + readonly writable?: boolean + readonly signIn?: readonly (readonly [string, HostSignIn])[] + /** Leave the row's form unserved. */ + readonly unserved?: boolean +} + +/** Render the page of a row that serves `hosts` over a real staged form, with the sign-in states and every face call recorded. */ +function mount(options: MountOptions = {}) { + const scope = stubConfigForm() + const hosts = options.hosts ?? ['gitlab.com'] + if (options.unserved !== true) { + scope.publish({ status: 'ready', value: { hosts }, base: { hosts: ['gitlab.com'] }, user: {}, writable: options.writable ?? true, revision: 2 }) + } + const form = new HostSettingsForm(scope.scope, () => options.taken ?? []) + const { hooks, ...actions } = form.inject() + const signIn = createSnapshotStore>(new Map(options.signIn ?? [])) + const checkSignIn = vi.fn() + const copyCommand = vi.fn() + const props = { + view: options.view ?? 'page', forge: options.forge ?? 'gitlab', ...actions, + add: vi.fn(actions.add), remove: vi.fn(actions.remove), save: vi.fn(actions.save), discard: vi.fn(actions.discard), + useHostForm: bindSnapshotSelector(hooks.hostForm), useSignIn: bindSnapshotSelector(signIn), checkSignIn, copyCommand, t, + } as HostSettingsProps + const view = render() + const row = (host: string): HTMLElement => { + const element = view.container.querySelector(`[data-forge-host="${host}"]`) + if (!(element instanceof HTMLElement)) throw new Error(`no row for ${host}`) + return element + } + const input = (): HTMLInputElement => { + const element = view.getByRole('textbox', { name: 'Host to add' }) + if (!(element instanceof HTMLInputElement)) throw new Error('no field for the host to add') + return element + } + const type = (text: string): void => { fireEvent.change(input(), { target: { value: text } }) } + return { view, scope, form, props, signIn, checkSignIn, copyCommand, row, input, type } +} + +describe('HostSettings', () => { + it('names the list in the summary view without reading sign-in state', () => { + const m = mount({ view: 'summary' }) + try { + expect(m.view.container.textContent).toBe('Hosts') + expect(m.checkSignIn).not.toHaveBeenCalled() + } finally { m.form.dispose() } + }) + + it('says the settings are unavailable while the Host does not serve the row, and reads no sign-in state', () => { + const m = mount({ unserved: true }) + try { + expect(m.view.getByRole('status').textContent).toBe('Host settings are unavailable.') + expect(m.view.queryByRole('list')).toBeNull() + expect(m.checkSignIn).not.toHaveBeenCalled() + } finally { m.form.dispose() } + }) + + it('lists each saved host with its sign-in state, the command to copy, or why it could not be checked', () => { + const m = mount({ + hosts: ['gitlab.com', 'gitlab.example.com', 'quiet.example.com', 'down.example.com', 'silent.example.com', 'new.example.com'], + signIn: [ + ['gitlab.com', { state: 'ready', message: null, signIn: null }], + ['gitlab.example.com', { state: 'unauthenticated', message: 'not signed in', signIn: { command: COMMAND } }], + ['quiet.example.com', { state: 'unauthenticated', message: 'the token expired', signIn: null }], + ['down.example.com', { state: 'unavailable', message: 'glab: connection timed out', signIn: null }], + ['silent.example.com', { state: 'unavailable', message: '', signIn: null }], + ], + }) + try { + expect(within(m.view.getByRole('list', { name: 'Hosts' })).getAllByRole('listitem')).toHaveLength(6) + expect(m.row('gitlab.com').textContent).toBe('gitlab.comSigned in') + expect(m.row('gitlab.com').querySelector('[data-state="ready"] [data-state="done"]')).not.toBeNull() + expect(m.row('gitlab.example.com').textContent).toBe(`gitlab.example.comNot signed in${COMMAND}Copy`) + expect(m.row('quiet.example.com').textContent).toBe('quiet.example.comNot signed inthe token expired') + expect(m.row('down.example.com').textContent).toBe('down.example.comCan\'t checkglab: connection timed out') + expect(m.row('silent.example.com').textContent).toBe('silent.example.comCan\'t check') + expect(m.row('new.example.com').textContent).toBe('new.example.comChecking…') + + fireEvent.click(within(m.row('gitlab.example.com')).getByRole('button', { name: 'Copy sign-in command' })) + expect(m.copyCommand).toHaveBeenCalledWith(COMMAND) + } finally { m.form.dispose() } + }) + + it('reads sign-in state when shown, when the window regains focus, and after the saved hosts change, until it is left', () => { + const m = mount() + try { + expect(m.checkSignIn.mock.calls).toEqual([[['gitlab.com'], false]]) + fireEvent.focus(window) + expect(m.checkSignIn).toHaveBeenCalledTimes(2) + + act(() => { m.signIn.set(new Map([['gitlab.com', { state: 'ready', message: null, signIn: null }]])) }) + expect(m.row('gitlab.com').textContent).toBe('gitlab.comSigned in') + expect(m.checkSignIn).toHaveBeenCalledTimes(2) + act(() => { m.scope.publish({ value: { hosts: ['gitlab.com', 'gitlab.example.com'] } }) }) + expect(m.checkSignIn).toHaveBeenLastCalledWith(['gitlab.com', 'gitlab.example.com'], false) + expect(m.checkSignIn).toHaveBeenCalledTimes(3) + + fireEvent.click(m.view.getByRole('button', { name: 'Check sign-in again' })) + expect(m.checkSignIn).toHaveBeenLastCalledWith(['gitlab.com', 'gitlab.example.com'], true) + + m.view.unmount() + fireEvent.focus(window) + expect(m.checkSignIn).toHaveBeenCalledTimes(4) + expect(m.props.discard).toHaveBeenCalledOnce() + } finally { m.form.dispose() } + }) + + it('stages a typed host from the Add button or Enter, marks it as not saved, and writes the list on save', async () => { + const m = mount() + try { + const add = m.view.getByRole('button', { name: 'Add' }) + expect(add).toHaveProperty('disabled', true) + expect(m.input().placeholder).toBe('gitlab.example.com') + expect(m.view.getByText('MR links and Git remotes on these hosts are recognized. After adding a host, sign in to it with glab in a terminal.')).toBeTruthy() + + m.type('https://gitlab.example.com/group/app/-/merge_requests/2') + fireEvent.click(add) + expect(m.input().value).toBe('') + expect(m.row('gitlab.example.com').textContent).toBe('gitlab.example.comNot saved') + + m.type('git.corp.example') + fireEvent.keyDown(m.input(), { key: 'a' }) + fireEvent.keyDown(m.input(), { key: 'Enter', isComposing: true }) + expect(m.props.add).toHaveBeenCalledOnce() + fireEvent.keyDown(m.input(), { key: 'Enter' }) + expect(m.row('git.corp.example').textContent).toBe('git.corp.exampleNot saved') + + fireEvent.click(m.view.getByRole('button', { name: 'Save' })) + await vi.waitFor(() => { + expect(m.scope.mutate).toHaveBeenCalledWith([{ op: 'set', path: ['hosts'], value: ['gitlab.com', 'gitlab.example.com', 'git.corp.example'] }], 2) + }) + } finally { m.form.dispose() } + }) + + it.each([ + ['gitlab', 'a b', 'Enter a host name such as gitlab.example.com'], + ['gitlab', 'GitLab.com', 'gitlab.com is already in the list'], + ['gitlab', 'github.com', 'The GitHub component already uses github.com'], + ['github', 'github.com', 'The GitLab component already uses github.com'], + ] as const)('on the %s page, refuses %j below the field until the text changes', (forge, text, message) => { + const m = mount({ forge, taken: ['github.com'] }) + try { + m.type(text) + fireEvent.click(m.view.getByRole('button', { name: 'Add' })) + + expect(m.view.getByRole('alert').textContent).toBe(message) + expect(m.input().getAttribute('aria-invalid')).toBe('true') + expect(m.input().getAttribute('aria-describedby')).toBe(m.view.getByRole('alert').id) + expect(m.input().value).toBe(text) + + m.type(`${text}x`) + expect(m.view.queryByRole('alert')).toBeNull() + expect(m.input().getAttribute('aria-invalid')).toBeNull() + } finally { m.form.dispose() } + }) + + it('names pull requests and gh on the GitHub page', () => { + const m = mount({ forge: 'github', hosts: ['github.com'] }) + try { + expect(m.input().placeholder).toBe('github.example.com') + expect(m.view.getByText('PR links and Git remotes on these hosts are recognized. After adding a host, sign in to it with gh in a terminal.')).toBeTruthy() + } finally { m.form.dispose() } + }) + + it('removes a host from the staged list, but not the last one', () => { + const m = mount({ hosts: ['gitlab.com', 'gitlab.example.com'] }) + try { + const remove = (host: string): HTMLElement => within(m.row(host)).getByRole('button', { name: `Remove ${host}` }) + expect(remove('gitlab.com').getAttribute('aria-disabled')).toBeNull() + + fireEvent.click(remove('gitlab.com')) + expect(m.props.remove).toHaveBeenCalledWith('gitlab.com') + expect(m.view.container.querySelector('[data-forge-host="gitlab.com"]')).toBeNull() + + expect(remove('gitlab.example.com').getAttribute('aria-disabled')).toBe('true') + fireEvent.click(remove('gitlab.example.com')) + expect(m.props.remove).toHaveBeenCalledOnce() + expect(m.row('gitlab.example.com')).toBeTruthy() + } finally { m.form.dispose() } + }) + + it('disables every edit while the document is read-only', () => { + const m = mount({ hosts: ['gitlab.com', 'gitlab.example.com'], writable: false }) + try { + expect(m.view.getByText('This deployment stores settings read-only.')).toBeTruthy() + expect(m.input()).toHaveProperty('disabled', true) + expect(m.view.getByRole('button', { name: 'Add' })).toHaveProperty('disabled', true) + expect(within(m.row('gitlab.com')).getByRole('button', { name: 'Remove gitlab.com' })).toHaveProperty('disabled', true) + expect(m.view.getByRole('button', { name: 'Check sign-in again' })).toHaveProperty('disabled', false) + } finally { m.form.dispose() } + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/host-sign-in.client.spec.ts b/packages/experimental/client-ui-forge/tests/host-sign-in.client.spec.ts new file mode 100644 index 0000000000..d6e29a41b4 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/host-sign-in.client.spec.ts @@ -0,0 +1,93 @@ +/** The sign-in states a provider row's page keeps for its hosts. */ +import { expect, it, vi } from 'vitest' +import type { ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge/types' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { HostSignInStates, type HostReadinessRead } from '../src/client/host-sign-in.ts' + +const READY: ForgeReadiness = { state: 'ready', message: null, signIn: null } +const SIGN_IN: ForgeReadiness = { state: 'unauthenticated', message: 'not signed in', signIn: { command: 'glab auth login --hostname gitlab.example.com' } } + +/** One readiness read the test answers by hand. */ +interface PendingRead { + readonly host: string + readonly signal: AbortSignal + readonly answer: (result: RemoteResult) => void +} + +/** Readiness reads the test answers by hand, in call order. */ +function reads() { + const calls: PendingRead[] = [] + const read = vi.fn((host, signal) => new Promise((resolve) => { calls.push({ host, signal, answer: resolve }) })) + return { calls, read } +} + +/** Let answered reads reach the store. */ +async function settle(): Promise { + await new Promise((resolve) => { setTimeout(resolve, 0) }) +} + +it('shows every host as being checked, then each answer as it arrives', async () => { + const { calls, read } = reads() + const signIn = new HostSignInStates(read) + expect(signIn.states.getSnapshot().size).toBe(0) + + signIn.check(['gitlab.com', 'gitlab.example.com'], true) + + expect(calls.map(call => call.host)).toEqual(['gitlab.com', 'gitlab.example.com']) + expect([...signIn.states.getSnapshot()]).toEqual([['gitlab.com', { state: 'checking' }], ['gitlab.example.com', { state: 'checking' }]]) + calls[1]?.answer({ ok: true, value: SIGN_IN }) + await settle() + expect([...signIn.states.getSnapshot()]).toEqual([['gitlab.com', { state: 'checking' }], ['gitlab.example.com', SIGN_IN]]) + calls[0]?.answer({ ok: true, value: READY }) + await settle() + expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual(READY) +}) + +it('reports a refused read as a host it could not check, with the reason', async () => { + const { calls, read } = reads() + const signIn = new HostSignInStates(read) + signIn.check(['gitlab.com'], true) + + calls[0]?.answer({ ok: false, error: new RemoteError('gateway/internal', 'The Host did not answer the sign-in read', {}) }) + await settle() + + expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual({ + state: 'unavailable', message: 'The Host did not answer the sign-in read', signIn: null, + }) +}) + +it('keeps the states it has during a quiet check, shows only new hosts as being checked, and forgets hosts no longer named', async () => { + const { calls, read } = reads() + const signIn = new HostSignInStates(read) + signIn.check(['gitlab.com', 'old.example.com'], true) + calls[0]?.answer({ ok: true, value: READY }) + calls[1]?.answer({ ok: true, value: SIGN_IN }) + await settle() + + signIn.check(['gitlab.com', 'gitlab.example.com'], false) + + expect([...signIn.states.getSnapshot()]).toEqual([['gitlab.com', READY], ['gitlab.example.com', { state: 'checking' }]]) + calls[2]?.answer({ ok: true, value: SIGN_IN }) + await settle() + expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual(SIGN_IN) +}) + +it('ends the reads of an earlier check and drops their answers', async () => { + const { calls, read } = reads() + const signIn = new HostSignInStates(read) + signIn.check(['gitlab.com'], true) + + signIn.check(['gitlab.com'], true) + + expect(calls[0]?.signal.aborted).toBe(true) + expect(calls[1]?.signal.aborted).toBe(false) + calls[0]?.answer({ ok: true, value: SIGN_IN }) + await settle() + expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual({ state: 'checking' }) + + signIn.dispose() + expect(calls[1]?.signal.aborted).toBe(true) + calls[1]?.answer({ ok: true, value: READY }) + await settle() + expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual({ state: 'checking' }) +}) 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 70a2064476..48d33e5120 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -13,7 +13,8 @@ import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SidebarRightTabDefinition, TabId } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import type { - ChangeRequestDescription, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeCommitList, ForgeRerunRequest, ForgeReviewData, + ChangeRequestDescription, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeCommitList, ForgeReadiness, ForgeRerunRequest, + ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest, } from '@deepseek-ai/dsh-experimental-forge/types' @@ -31,8 +32,10 @@ import { ChangesTabTitle } from '../src/client/ChangesTabTitle.tsx' import { CheckoutRow, ConnectionRow, LocalChangesRow, type CheckoutRowInjected, type ConnectionRowInjected, type LocalChangesRowInjected, } from '../src/client/EnvironmentRows.tsx' +import { HostSettings, type HostSettingsInjected } from '../src/client/HostSettings.tsx' +import type { HostSettings as HostSettingsFields } from '../src/client/host-settings-form.ts' import { en, NS, zh } from '../src/client/locales.ts' -import { inject, mountForgePanel, WORKTREE_NS, WORKTREE_ROW_KEY } from '../src/client/mount.ts' +import { FORGE_BUNDLE, HOST_ROWS, inject, mountForgePanel, WORKTREE_NS, WORKTREE_ROW_KEY } from '../src/client/mount.ts' import type { SessionListInjected } from '../src/client/session-list.ts' import { SessionHoverForge } from '../src/client/SessionHoverForge.tsx' import { SessionRowForge } from '../src/client/SessionRowForge.tsx' @@ -162,6 +165,10 @@ function isReviewPageFace(value: Record): value is Record): value is Record & HostSettingsInjected { + return typeof value.add === 'function' && typeof value.checkSignIn === 'function' +} + function isReviewCountFace(value: Record): value is Record & ReviewNavCountInjected { return typeof value.hooks === 'object' && value.hooks !== null && 'count' in value.hooks } @@ -297,6 +304,8 @@ async function base() { reviewSubmit: vi.fn(async (_url: string, _request: ForgeReviewRequest): Read => ({ ok: true, value: { ok: true, url: 'https://github.com/review/2' } })), reviewStage: vi.fn(async (_sessionId: SessionId, _url: string | null): Promise> => OK), + hostReadiness: vi.fn(async (_forge: string, _host: string, _signal: AbortSignal): Read => + ({ ok: true, value: { state: 'ready', message: null, signIn: null } })), } ctx.provide('remote.forgePanel', forgePanel) ctx.provide('locale', new LocaleRuntime(ctx)) @@ -318,7 +327,14 @@ async function base() { } ctx.provide('sessions', sessions) const worktreeForm = stubConfigForm() - ctx.provide('configForms', { get: (name: string) => { expect(name).toBe(WORKTREE_NS); return worktreeForm.scope } } as never) + const hostForms = { 'forge-github': stubConfigForm(), 'forge-gitlab': stubConfigForm() } + ctx.provide('configForms', { + get: (name: string) => { + if (name === WORKTREE_NS) return worktreeForm.scope + if (name === 'forge-github' || name === 'forge-gitlab') return hostForms[name].scope + throw new Error(`no form expected for the entry ${name}`) + }, + } as never) ctx.provide('sidebarRight', sidebarRight) const remoteAccess = { whenAccess: vi.fn((_action: string, callback: () => Iterable<() => unknown>) => { @@ -357,7 +373,7 @@ async function base() { } as never, () => null) return { ctx, remote, unmount, streams, stateStreams, extensionStreams, countStreams, forgePanel, sidebarRightTabs, unregisterTab, sidebarRight, - sessions, scopes, worktreeForm, remoteAccess, workspaces, uiWorkspace, + sessions, scopes, worktreeForm, hostForms, remoteAccess, workspaces, uiWorkspace, } } @@ -1306,6 +1322,115 @@ describe('worktree row settings', () => { }) }) +describe('provider row host settings', () => { + /** The host page faces of the GitHub and GitLab rows. */ + function hostPages(f: Awaited>): Record<'github' | 'gitlab', HostSettingsInjected> { + const rows = f.ctx.slots.entries('plugins.row.config').filter(candidate => candidate.component === HostSettings) + expect(rows.map(row => row.options)).toMatchObject([{ key: `${FORGE_BUNDLE}#forge-github` }, { key: `${FORGE_BUNDLE}#forge-gitlab` }]) + const [github, gitlab] = rows.map(row => row.inject?.()) + assert(github !== undefined && isHostFace(github) && gitlab !== undefined && isHostFace(gitlab)) + return { github, gitlab } + } + + /** Serve a row's form with `hosts`. */ + function serve(f: Awaited>, row: 'forge-github' | 'forge-gitlab', hosts: string[]): void { + f.hostForms[row].publish({ status: 'ready', value: { hosts }, base: { hosts }, user: {}, writable: true, revision: 1 }) + } + + it('registers a host page for each provider row over the entry of the same id and writes the staged list on save', async () => { + const f = await fixture() + try { + expect(HOST_ROWS).toEqual([{ forge: 'github', row: 'forge-github' }, { forge: 'gitlab', row: 'forge-gitlab' }]) + const pages = hostPages(f) + expect([pages.github.forge, pages.gitlab.forge]).toEqual(['github', 'gitlab']) + serve(f, 'forge-gitlab', ['gitlab.com']) + expect(pages.gitlab.hooks.hostForm.getSnapshot()).toMatchObject({ available: true, dirty: false, saved: ['gitlab.com'], draft: ['gitlab.com'] }) + expect(pages.github.hooks.hostForm.getSnapshot()).toMatchObject({ available: false, saved: [] }) + + expect(pages.gitlab.add('gitlab.example.com')).toBeUndefined() + pages.gitlab.save() + + await vi.waitFor(() => { expect(f.hostForms['forge-gitlab'].mutate).toHaveBeenCalledOnce() }) + expect(f.hostForms['forge-gitlab'].mutate.mock.calls[0]?.[0]).toEqual([{ op: 'set', path: ['hosts'], value: ['gitlab.com', 'gitlab.example.com'] }]) + expect(f.hostForms['forge-github'].mutate).not.toHaveBeenCalled() + } finally { await f.ctx.fiber.dispose() } + }) + + it('refuses a host the other provider row serves now', async () => { + const f = await fixture() + try { + const pages = hostPages(f) + serve(f, 'forge-gitlab', ['gitlab.com']) + // The GitHub row is not served yet, so it holds no host. + expect(pages.gitlab.add('ghe.corp.example')).toBeUndefined() + pages.gitlab.discard() + + serve(f, 'forge-github', ['github.com', 'ghe.corp.example']) + + expect(pages.gitlab.add('ghe.corp.example')).toEqual({ kind: 'taken', host: 'ghe.corp.example' }) + expect(pages.github.add('gitlab.com')).toEqual({ kind: 'taken', host: 'gitlab.com' }) + expect(pages.github.add('ghe.corp.example')).toEqual({ kind: 'duplicate', host: 'ghe.corp.example' }) + } finally { await f.ctx.fiber.dispose() } + }) + + it('reads sign-in state through the Remote under the row\'s forge family', async () => { + const f = await fixture() + try { + const pages = hostPages(f) + const signIn: ForgeReadiness = { state: 'unauthenticated', message: 'not signed in', signIn: { command: 'glab auth login --hostname gitlab.example.com' } } + f.forgePanel.hostReadiness.mockResolvedValueOnce({ ok: true, value: signIn }) + + pages.gitlab.checkSignIn(['gitlab.example.com'], true) + + expect(f.forgePanel.hostReadiness).toHaveBeenCalledWith('gitlab', 'gitlab.example.com', expect.any(AbortSignal)) + expect(pages.gitlab.hooks.signIn.getSnapshot().get('gitlab.example.com')).toEqual({ state: 'checking' }) + await settle() + expect(pages.gitlab.hooks.signIn.getSnapshot().get('gitlab.example.com')).toEqual(signIn) + expect(pages.github.hooks.signIn.getSnapshot().size).toBe(0) + + pages.github.checkSignIn(['github.com'], false) + expect(f.forgePanel.hostReadiness).toHaveBeenLastCalledWith('github', 'github.com', expect.any(AbortSignal)) + } finally { await f.ctx.fiber.dispose() } + }) + + it('copies a sign-in command and confirms it', async () => { + const f = await fixture() + const writeText = vi.fn(async (_text: string) => {}) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + try { + hostPages(f).gitlab.copyCommand('glab auth login --hostname gitlab.example.com') + await settle() + + expect(writeText).toHaveBeenCalledWith('glab auth login --hostname gitlab.example.com') + expect(f.notice()).toMatchObject({ key: 'toast.commandCopied', tone: 'success' }) + } finally { await f.ctx.fiber.dispose() } + }) + + it('withdraws both host pages, releases their forms, and ends the sign-in reads under way with its fiber', async () => { + const b = await base() + const fiber = b.ctx.plugin({ inject: [...inject], apply: (plugin: Context) => mountForgePanel(plugin, REMOTE) }) + await fiber + const rows = () => b.ctx.slots.entries('plugins.row.config').filter(candidate => candidate.component === HostSettings) + expect(rows()).toHaveLength(2) + const github = rows()[0]?.inject?.() + assert(github !== undefined && isHostFace(github)) + const signals: AbortSignal[] = [] + b.forgePanel.hostReadiness.mockImplementation((_forge, _host, signal) => { + signals.push(signal) + return new Promise(() => {}) + }) + github.checkSignIn(['github.com'], true) + expect(b.hostForms['forge-github'].listenerCount()).toBe(1) + + await fiber.dispose() + + expect(rows()).toHaveLength(0) + expect(signals.map(signal => signal.aborted)).toEqual([true]) + expect(b.hostForms['forge-github'].listenerCount()).toBe(0) + expect(b.hostForms['forge-gitlab'].listenerCount()).toBe(0) + }) +}) + describe('archive notices', () => { it('uses the scheduled cleanup notice and reports a later failure', async () => { const f = await fixture() @@ -1487,6 +1612,25 @@ describe('mountForgePanel review page', () => { await f.dispose() }) + it('opens the Forge bundle on the Plugins page for the host lists while the Plugins page provides its navigation', async () => { + const f = await fixture() + try { + const page = reviewPage(f) + expect(page.hooks.pluginNavigation.getSnapshot()).toBe(false) + expect(() => { page.openHostSettings() }).not.toThrow() + const openBundle = vi.fn() + const navigation = f.ctx.plugin({ apply: (ctx: Context) => { ctx.provide('pluginNavigation', { openBundle } as never) } }) + await navigation + await vi.waitFor(() => { expect(page.hooks.pluginNavigation.getSnapshot()).toBe(true) }) + + page.openHostSettings() + + expect(openBundle).toHaveBeenCalledWith(FORGE_BUNDLE) + await navigation.dispose() + expect(page.hooks.pluginNavigation.getSnapshot()).toBe(false) + } finally { await f.ctx.fiber.dispose() } + }) + it('reads every list again and reports only a failure', async () => { const f = await fixture() await reviewPage(f).refresh() diff --git a/packages/experimental/client-ui-forge/tests/review-detail.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-detail.client.spec.tsx index 4c06acde06..3cf4913ef0 100644 --- a/packages/experimental/client-ui-forge/tests/review-detail.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-detail.client.spec.tsx @@ -64,7 +64,7 @@ function renderDetail(overrides: Partial = {}) { const read = stream(reviewed(7)) const props: ReviewDetailProps = { url: URL7, read, tab: 'summary', onTab: vi.fn(), listHidden: false, onToggleList: vi.fn(), onBack: vi.fn(), now: NOW, locale: 'en', - actions, readDescription: vi.fn(async () => ok(description('Body'))), + actions, readDescription: vi.fn(async () => ok(description('Body'))), onAddHost: undefined, renderChanges: vi.fn(() =>

    changes body

    ), renderChat: vi.fn(() =>

    chat body

    ), unseenQuotes: 0, t, ...overrides, } const view = render() @@ -100,10 +100,18 @@ describe('ReviewDetail before a status', () => { expect(polled.view.getByRole('status').textContent).toBe('') }) - it('explains a link no enabled code host serves', () => { + it('explains a link whose host no code host component serves', () => { const b = renderDetail({ read: stream(undefined, { code: 'forgePanel/unrecognized-url', message: 'no provider' }) }) - expect(b.view.getByRole('status').textContent).toBe(`${en['reviewPage.unrecognized']}${en['reviewPage.unrecognizedHint']}`) + expect(b.view.getByRole('status').textContent).toBe('Unknown code hostThis link\'s host has not been added to a code host component.') expect(b.view.queryByRole('button', { name: 'Retry' })).toBeNull() + expect(b.view.queryByRole('button', { name: 'Add host…' })).toBeNull() + }) + + it('offers the host lists for such a link while they can be opened', () => { + const onAddHost = vi.fn() + const b = renderDetail({ read: stream(undefined, { code: 'forgePanel/unrecognized-url', message: 'no provider' }), onAddHost }) + fireEvent.click(within(b.view.getByRole('status')).getByRole('button', { name: 'Add host…' })) + expect(onAddHost).toHaveBeenCalledOnce() }) it('offers to open the stream again or the browser once the stream stopped', () => { diff --git a/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx index a73d33363c..98c0248adf 100644 --- a/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx @@ -14,7 +14,7 @@ import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-tes import type { SessionAreaProps } from '@deepseek-ai/dsh-client-ui-slots' import type { ChangeRequestSnapshot, ForgeCommitList, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { brandString } from '@deepseek-ai/dsh-brand' import type { ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx' import type { ViewAnnotations } from '../src/client/annotations.ts' @@ -136,6 +136,7 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) { openInMain: vi.fn(), requestWorktree: vi.fn(), } + const pluginNavigation = createSnapshotStore(false) const conversations: ForgeReviewConversationProps[] = [] const renderSlot = ((_key: string, owner: ForgeReviewConversationProps) => { conversations.push(owner) @@ -146,6 +147,7 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) { } const props: ReviewPageProps = { useLocale: bindSnapshotSelector(createSnapshotStore('en')), + usePluginNavigation: bindSnapshotSelector(pluginNavigation), openLists: vi.fn((scope: string, signal: AbortSignal) => { const stream = fed(scope, signal) lists.push(stream) @@ -163,6 +165,7 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) { return refresh.promise }), readDescription: vi.fn(async () => ok(description('Body'))), + openHostSettings: vi.fn(), actionsFor: vi.fn((_url: string, showChanges: () => void): ChangeRequestActions => { shown.push(showChanges) return { openLink: vi.fn(), copyLink: vi.fn(), retry: vi.fn(), viewChanges: () => { showChanges() } } @@ -190,7 +193,7 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) { return element } return { - view, props, store, lists, details, refreshes, shown, changes, chat, conversations, page, + view, props, store, lists, details, refreshes, shown, changes, chat, conversations, page, pluginNavigation, list: () => last(lists), detail: () => last(details), } } @@ -334,6 +337,22 @@ describe('ReviewPage lists', () => { }) describe('ReviewPage detail', () => { + it('offers the host lists for a link no provider serves only while the Plugins page can be opened', async () => { + const b = renderPage() + b.list().push(frame(host({ 'review-requested': list([summary(7)]) }))) + await settle() + fireEvent.click(b.view.container.querySelector(`[data-forge-review-item="${URL7}"]`) ?? document.body) + b.detail().fail(new RemoteError('forgePanel/unrecognized-url', 'no provider serves it', {})) + await settle() + expect(b.view.getByText('Unknown code host')).toBeTruthy() + expect(b.view.queryByRole('button', { name: 'Add host…' })).toBeNull() + + act(() => { b.pluginNavigation.set(true) }) + fireEvent.click(b.view.getByRole('button', { name: 'Add host…' })) + + expect(b.props.openHostSettings).toHaveBeenCalledOnce() + }) + it('shows the chosen change request with its card actions, and goes back to the list', async () => { const b = renderPage() await select(b) diff --git a/packages/experimental/forge-bundle/README.i18n.yaml b/packages/experimental/forge-bundle/README.i18n.yaml index 4a494146b2..f6c08e04f1 100644 --- a/packages/experimental/forge-bundle/README.i18n.yaml +++ b/packages/experimental/forge-bundle/README.i18n.yaml @@ -30,8 +30,8 @@ en: 0192ab064b8000a7 zh: 1a1de04f87631b9a /deepseek-ai-dsh-experimental-forge-bundle/known-limitations-and-deferred-work: - en: 0c681a81348e10e3 - zh: 40d04b43b23e4259 + en: 7446ae5ff50a9540 + zh: 05b3b00cc35b32db /deepseek-ai-dsh-experimental-forge-bundle/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/forge-bundle/README.md b/packages/experimental/forge-bundle/README.md index 83b8d7a143..91e4b8a356 100644 --- a/packages/experimental/forge-bundle/README.md +++ b/packages/experimental/forge-bundle/README.md @@ -63,7 +63,7 @@ Enabling or disabling the bundle changes the model's tool schema list. Calls app -- The bundle serves github.com and gitlab.com only; a GitHub Enterprise or self-managed GitLab host needs a profile patch that lists it in the `forge-github` row's [`hosts`](../forge-github/README.md#use-this-package) or the `forge-gitlab` row's [`hosts`](../forge-gitlab/README.md#use-this-package). No provider recognizes other code hosts. +- The bundle serves github.com and gitlab.com until another host is added: the page of its GitHub or GitLab row on the Plugins page adds a GitHub Enterprise or self-managed GitLab host and writes it to the profile patch, in the `forge-github` row's [`hosts`](../forge-github/README.md#use-this-package) or the `forge-gitlab` row's [`hosts`](../forge-gitlab/README.md#use-this-package). No provider recognizes other code hosts. - The model has no tool for bound change requests yet. ----- diff --git a/packages/experimental/forge-bundle/README.zh.md b/packages/experimental/forge-bundle/README.zh.md index 2629589962..19d48dd30f 100644 --- a/packages/experimental/forge-bundle/README.zh.md +++ b/packages/experimental/forge-bundle/README.zh.md @@ -63,7 +63,7 @@ kind: "package-bundle" -- 本 Bundle 只服务 github.com 和 gitlab.com;GitHub Enterprise 或自建 GitLab 主机需要用 profile patch 把它列入 `forge-github` 行的 [`hosts`](../forge-github/README.zh.md#use-this-package) 或 `forge-gitlab` 行的 [`hosts`](../forge-gitlab/README.zh.md#use-this-package)。没有提供方识别其他代码托管平台。 +- 在添加其他主机之前,本 Bundle 只服务 github.com 和 gitlab.com:插件页上本 Bundle 的 GitHub 行或 GitLab 行的页面可以添加 GitHub Enterprise 或自建 GitLab 主机,并把它写入 profile patch 中 `forge-github` 行的 [`hosts`](../forge-github/README.zh.md#use-this-package) 或 `forge-gitlab` 行的 [`hosts`](../forge-gitlab/README.zh.md#use-this-package)。没有提供方识别其他代码托管平台。 - 模型目前还没有读取已绑定变更请求的工具。 ----- diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index 3d6ae047b6..b59623351b 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: b916d3e2bd0cce2d - zh: 943e6caad6972b0f + en: 771bc00731511732 + zh: 18fc99e8290cee61 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: b3407071292d7d98 zh: dfe8f077cd041909 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 132bc7d282..81bde72813 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -25,7 +25,7 @@ Read GitHub and GitHub Enterprise pull requests for `ctx.forge` with the GitHub ## Use this package -Mount the provider after the forge registry and list every GitHub Enterprise host explicitly. +Mount the provider after the forge registry and list every GitHub Enterprise host explicitly. `hosts` lists at least one host name, each with an optional port, and is editable while the provider runs: the [forge panel](../client-ui-forge/README.md) draws the list on this row's page on the Plugins page, and a saved list replaces the registered provider without mounting the plugin again. A list that names a host the GitLab provider serves is not registered: the Loader logs the refusal and the previous list keeps being served until a restart, where the provider that mounts second fails to load. ```yaml - name: '@deepseek-ai/dsh-experimental-forge' diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 6b5cf6f164..e5c71630ab 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在 forge 注册表之后挂载提供方,并显式列出每个 GitHub Enterprise 主机。 +在 forge 注册表之后挂载提供方,并显式列出每个 GitHub Enterprise 主机。`hosts` 至少列出一个主机名,每个可带端口,并且可以在提供方运行期间修改:[forge 面板](../client-ui-forge/README.zh.md)在插件页上这一行的页面里绘制该列表,保存后的列表会替换已注册的提供方,无需重新挂载插件。列出 GitLab 提供方所服务主机的列表不会被注册:Loader 记录这次拒绝,之前的列表继续服务,直到重启;重启时后挂载的提供方加载失败。 ```yaml - name: '@deepseek-ai/dsh-experimental-forge' diff --git a/packages/experimental/forge-github/package.json b/packages/experimental/forge-github/package.json index 0c6ac7485a..28fd4cb938 100644 --- a/packages/experimental/forge-github/package.json +++ b/packages/experimental/forge-github/package.json @@ -42,18 +42,28 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-experimental-forge-session": "workspace:*", - "@deepseek-ai/dsh-subprocess": "workspace:*" + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-settings": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-experimental-forge-session": "workspace:*", - "@deepseek-ai/dsh-subprocess": "workspace:*" + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-settings": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-experimental-forge-session": { "optional": true + }, + "@deepseek-ai/cordis-plugin-loader": { + "optional": true + }, + "@deepseek-ai/dsh-settings": { + "optional": true } } } diff --git a/packages/experimental/forge-github/src/index.ts b/packages/experimental/forge-github/src/index.ts index 82760fca3f..e3a6abcb49 100644 --- a/packages/experimental/forge-github/src/index.ts +++ b/packages/experimental/forge-github/src/index.ts @@ -3,10 +3,13 @@ * forge-session runs, the `gh` commands that bind pull requests to a Session. */ -import type { Context } from '@deepseek-ai/cordis' +import type { Context, Volatile } from '@deepseek-ai/cordis' +// Type-only: the Loader's `loader/volatile-update` event and the optional `settings` service. +import type {} from '@deepseek-ai/cordis-plugin-loader' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-experimental-forge' import type {} from '@deepseek-ai/dsh-experimental-forge-session' +import type {} from '@deepseek-ai/dsh-settings' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { GH_COMMANDS } from './commands.ts' import { ghRunner } from './gh.ts' @@ -19,8 +22,11 @@ export const inject = ['forge'] export interface Config { /** GitHub CLI executable name or absolute host path. */ ghCommand?: string - /** Host names this provider serves; list GitHub Enterprise hosts explicitly. */ - hosts?: string[] + /** + * Host names this provider serves, at least one; list GitHub Enterprise hosts explicitly. Editable live: the + * provider registers again with the new list. + */ + hosts: Volatile /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */ @@ -38,9 +44,12 @@ export interface Config { maxViewerItems?: number } -export const Config: z = z.object({ +/** A host name with an optional port, as `hosts` lists it. */ +const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i + +export const Config = z.object({ ghCommand: z.string().default('gh'), - hosts: z.array(z.string()).default(['github.com']), + hosts: z.array(z.string().pattern(HOST)).min(1).default(['github.com']).volatile(), timeoutMs: z.number().default(30_000), maxOutputBytes: z.number().default(8_388_608), maxReviewThreads: z.number().default(1_000), @@ -52,15 +61,9 @@ export const Config: z = z.object({ /** Most results one GitHub search page returns. */ const SEARCH_PAGE = 100 -const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i - export function apply(ctx: Context, config: Config): void { const resolved = config as Required if (resolved.ghCommand.trim().length === 0) throw new Error('forge-github: ghCommand must not be empty') - if (resolved.hosts.length === 0) throw new Error('forge-github: hosts must list at least one host') - for (const host of resolved.hosts) { - if (!HOST.test(host)) throw new Error(`forge-github: invalid host ${JSON.stringify(host)}`) - } 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}`) } @@ -68,7 +71,14 @@ export function apply(ctx: Context, config: Config): void { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`) } if (resolved.maxViewerItems > SEARCH_PAGE) throw new Error(`forge-github: maxViewerItems must be no greater than ${SEARCH_PAGE}`) - ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved)) + const gh = ghRunner(resolved) + const provider = (): GitHubProvider => new GitHubProvider(gh, resolved.hosts.get(), resolved) + const registration = ctx.forge.register(provider()) + // A list the registry refuses, because the GitLab provider serves one of its hosts, throws here: the Loader logs it + // and the previous list keeps being served. + ctx.on('loader/volatile-update', () => { registration.replace(provider()) }) + // The Forge panel draws the host list on this row's Plugins page. + ctx.inject(['settings'], (scope) => { scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)) }) ctx.inject(['forgeSession'], (scope) => { scope.forgeSession.registerCommands(GH_COMMANDS) }) diff --git a/packages/experimental/forge-github/tests/plugin.spec.ts b/packages/experimental/forge-github/tests/plugin.spec.ts index 6ddb5134c5..99c86f4f75 100644 --- a/packages/experimental/forge-github/tests/plugin.spec.ts +++ b/packages/experimental/forge-github/tests/plugin.spec.ts @@ -1,9 +1,10 @@ import { Context, Service } from '@deepseek-ai/cordis' import ForgeService from '@deepseek-ai/dsh-experimental-forge' import type { ForgeCommandRule } from '@deepseek-ai/dsh-experimental-forge-session' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { GH_COMMANDS } from '../src/commands.ts' import * as ForgeGitHub from '../src/index.ts' +import { liveConfig, omitsGeneratedPage } from '../../../settings/settings/tests/live-config.ts' let ctx: Context | undefined @@ -88,8 +89,8 @@ describe('forge-github plugin', () => { it.each([ [{ ghCommand: ' ' }, 'forge-github: ghCommand must not be empty'], - [{ hosts: [] }, 'forge-github: hosts must list at least one host'], - [{ hosts: ['https://github.com'] }, 'forge-github: invalid host "https://github.com"'], + [{ hosts: [] }, '$.hosts expected array length >= 1 but got 0'], + [{ hosts: ['https://github.com'] }, '$.hosts[0] expect string to match regexp'], [{ timeoutMs: 0 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'], [{ timeoutMs: 2_147_483_648 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'], [{ timeoutMs: 1.5 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'], @@ -108,9 +109,56 @@ describe('forge-github plugin', () => { await expect(context.plugin(ForgeGitHub, config)).rejects.toThrow(message) }) + it('serves the host list a live edit sets without mounting again', async () => { + const context = await forge() + const live = await liveConfig(context, ForgeGitHub) + expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toBeUndefined() + + await live.update({ hosts: ['github.com', 'ghe.corp.example'] }) + + expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toEqual({ forge: 'github', host: 'ghe.corp.example', owner: 'team', name: 'svc' }) + expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toBeDefined() + // Identity only: printing a Fiber walks Context proxies. + expect(Object.is(live.entry.fiber, live.fiber)).toBe(true) + + await live.update({ hosts: ['github.com'] }) + expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toBeUndefined() + }) + + it('keeps serving its previous hosts when a live edit adds one another provider serves', async () => { + const context = await forge() + context.forge.register({ ...otherProvider(), hosts: ['code.example.test'] }) + const live = await liveConfig(context, ForgeGitHub) + const warned = vi.spyOn(context.logger, 'warn').mockImplementation(() => {}) + + await live.update({ hosts: ['github.com', 'code.example.test'] }) + + expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toMatchObject({ forge: 'github', host: 'github.com' }) + expect(context.forge.changeRequestFromUrl('https://code.example.test/octo/demo/pull/1')).toBeUndefined() + expect(warned.mock.calls.map((call): unknown => call[0])) + .toContainEqual(new Error('forge: host "code.example.test" is already served by the "gitlab" provider')) + }) + + it('keeps its own instance off the generated Settings pages', async () => { + await omitsGeneratedPage(async (context) => { + await context.plugin(ForgeService) + return context.plugin(ForgeGitHub, {}) + }) + }) + it('does not apply timer limits to the output byte budget', async () => { const context = await forge() await context.plugin(ForgeGitHub, { maxOutputBytes: 2_147_483_648 }) expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toBeDefined() }) }) + +/** A provider of the `gitlab` family that serves nothing it is asked. */ +function otherProvider(): Parameters[0] { + const never = (): never => { throw new Error('not called') } + return { + forge: 'gitlab', hosts: [], label: 'GitLab', changeRequestNoun: 'merge-request', + repositoryFromRemote: () => undefined, changeRequestFromUrl: () => undefined, changeRequestUrl: never, fetch: never, + findByHead: never, readiness: never, markReady: never, merge: never, diff: never, fileText: never, fileUrl: never, + } +} diff --git a/packages/experimental/forge-github/tsconfig.json b/packages/experimental/forge-github/tsconfig.json index 5d7a8b52df..9a91c28e94 100644 --- a/packages/experimental/forge-github/tsconfig.json +++ b/packages/experimental/forge-github/tsconfig.json @@ -34,6 +34,12 @@ }, { "path": "../../util/values" + }, + { + "path": "../../../vendor/loader" + }, + { + "path": "../../settings/settings" } ] } diff --git a/packages/experimental/forge-gitlab/README.i18n.yaml b/packages/experimental/forge-gitlab/README.i18n.yaml index da6c848bd5..c3e91afadd 100644 --- a/packages/experimental/forge-gitlab/README.i18n.yaml +++ b/packages/experimental/forge-gitlab/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-forge-gitlab/use-this-package: - en: 72868d01b31182c4 - zh: d408278eed166c7f + en: 5868c7487e1d6eff + zh: 292b016cf57a05d4 /deepseek-ai-dsh-forge-gitlab/understand-the-implementation: en: 30b70996dfeb92c9 zh: 6ef0f4b3bbe75ffa diff --git a/packages/experimental/forge-gitlab/README.md b/packages/experimental/forge-gitlab/README.md index bbbf896a82..838e019b4b 100644 --- a/packages/experimental/forge-gitlab/README.md +++ b/packages/experimental/forge-gitlab/README.md @@ -25,7 +25,7 @@ Read and write GitLab.com and self-managed GitLab merge requests for `ctx.forge` ## Use this package -Mount the provider after the forge registry and list every self-managed host explicitly. The Forge bundle mounts it with `gitlab.com`. +Mount the provider after the forge registry and list every self-managed host explicitly. The Forge bundle mounts it with `gitlab.com`. `hosts` lists at least one host name, each with an optional port, and is editable while the provider runs: the [forge panel](../client-ui-forge/README.md) draws the list on this row's page on the Plugins page, and a saved list replaces the registered provider without mounting the plugin again. A list that names a host the GitHub provider serves is not registered: the Loader logs the refusal and the previous list keeps being served until a restart, where the provider that mounts second fails to load. ```yaml - name: '@deepseek-ai/dsh-experimental-forge' diff --git a/packages/experimental/forge-gitlab/README.zh.md b/packages/experimental/forge-gitlab/README.zh.md index 8d9a4c4c69..120af9bf69 100644 --- a/packages/experimental/forge-gitlab/README.zh.md +++ b/packages/experimental/forge-gitlab/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在 forge 注册表之后挂载提供方,并显式列出每个自建主机。Forge 插件包以 `gitlab.com` 挂载它。 +在 forge 注册表之后挂载提供方,并显式列出每个自建主机。Forge 插件包以 `gitlab.com` 挂载它。`hosts` 至少列出一个主机名,每个可带端口,并且可以在提供方运行期间修改:[forge 面板](../client-ui-forge/README.zh.md)在插件页上这一行的页面里绘制该列表,保存后的列表会替换已注册的提供方,无需重新挂载插件。列出 GitHub 提供方所服务主机的列表不会被注册:Loader 记录这次拒绝,之前的列表继续服务,直到重启;重启时后挂载的提供方加载失败。 ```yaml - name: '@deepseek-ai/dsh-experimental-forge' diff --git a/packages/experimental/forge-gitlab/package.json b/packages/experimental/forge-gitlab/package.json index f69de35e08..45dec98c37 100644 --- a/packages/experimental/forge-gitlab/package.json +++ b/packages/experimental/forge-gitlab/package.json @@ -44,18 +44,28 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-experimental-forge-session": "workspace:*", - "@deepseek-ai/dsh-subprocess": "workspace:*" + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-settings": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-experimental-forge-session": "workspace:*", - "@deepseek-ai/dsh-subprocess": "workspace:*" + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-settings": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-experimental-forge-session": { "optional": true + }, + "@deepseek-ai/cordis-plugin-loader": { + "optional": true + }, + "@deepseek-ai/dsh-settings": { + "optional": true } } } diff --git a/packages/experimental/forge-gitlab/src/index.ts b/packages/experimental/forge-gitlab/src/index.ts index f4e404fbac..bf5bd51d95 100644 --- a/packages/experimental/forge-gitlab/src/index.ts +++ b/packages/experimental/forge-gitlab/src/index.ts @@ -3,10 +3,13 @@ * while forge-session runs, the `glab` commands that bind merge requests to a Session. */ -import type { Context } from '@deepseek-ai/cordis' +import type { Context, Volatile } from '@deepseek-ai/cordis' +// Type-only: the Loader's `loader/volatile-update` event and the optional `settings` service. +import type {} from '@deepseek-ai/cordis-plugin-loader' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-experimental-forge' import type {} from '@deepseek-ai/dsh-experimental-forge-session' +import type {} from '@deepseek-ai/dsh-settings' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { GLAB_COMMANDS } from './commands.ts' import { glabRunner } from './glab.ts' @@ -19,8 +22,11 @@ export const inject = ['forge'] export interface Config { /** GitLab CLI executable name or absolute host path. */ glabCommand?: string - /** Host names this provider serves; list self-managed GitLab hosts explicitly. */ - hosts?: string[] + /** + * Host names this provider serves, at least one; list self-managed GitLab hosts explicitly. Editable live: the + * provider registers again with the new list. + */ + hosts: Volatile /** Deadline in milliseconds for one `glab` invocation. */ timeoutMs?: number /** Maximum captured bytes per `glab` output stream and combined JSON bytes of one complete check read or review read. */ @@ -37,9 +43,12 @@ export interface Config { maxCachedVersionBytes?: number } -export const Config: z = z.object({ +/** A host name with an optional port, as `hosts` lists it. */ +const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i + +export const Config = z.object({ glabCommand: z.string().default('glab'), - hosts: z.array(z.string()).default(['gitlab.com']), + hosts: z.array(z.string().pattern(HOST)).min(1).default(['gitlab.com']).volatile(), timeoutMs: z.number().default(30_000), maxOutputBytes: z.number().default(8_388_608), maxReviewThreads: z.number().default(1_000), @@ -49,22 +58,25 @@ export const Config: z = z.object({ maxCachedVersionBytes: z.number().default(16_777_216), }) -const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i - export function apply(ctx: Context, config: Config): void { const resolved = config as Required if (resolved.glabCommand.trim().length === 0) throw new Error('forge-gitlab: glabCommand must not be empty') - if (resolved.hosts.length === 0) throw new Error('forge-gitlab: hosts must list at least one host') - for (const host of resolved.hosts) { - if (!HOST.test(host)) throw new Error(`forge-gitlab: invalid host ${JSON.stringify(host)}`) - } if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) { throw new Error(`forge-gitlab: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits', 'statusBatchSize', 'maxConcurrentRequests', 'maxCachedVersionBytes'] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-gitlab: ${key} must be a positive safe integer`) } - ctx.forge.register(new GitLabProvider(glabRunner(resolved), resolved.hosts, resolved)) + const glab = glabRunner(resolved) + /* jscpd:ignore-start -- the GitLab and GitHub providers wire their own registration; no package below both holds plugin wiring. */ + const provider = (): GitLabProvider => new GitLabProvider(glab, resolved.hosts.get(), resolved) + const registration = ctx.forge.register(provider()) + // A list the registry refuses, because the GitHub provider serves one of its hosts, throws here: the Loader logs it + // and the previous list keeps being served. + ctx.on('loader/volatile-update', () => { registration.replace(provider()) }) + // The Forge panel draws the host list on this row's Plugins page. + ctx.inject(['settings'], (scope) => { scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)) }) + /* jscpd:ignore-end */ ctx.inject(['forgeSession'], (scope) => { scope.forgeSession.registerCommands(GLAB_COMMANDS) }) diff --git a/packages/experimental/forge-gitlab/tests/plugin.spec.ts b/packages/experimental/forge-gitlab/tests/plugin.spec.ts index 29d692ba46..fc4d68d470 100644 --- a/packages/experimental/forge-gitlab/tests/plugin.spec.ts +++ b/packages/experimental/forge-gitlab/tests/plugin.spec.ts @@ -1,9 +1,10 @@ import { Context, Service } from '@deepseek-ai/cordis' import ForgeService from '@deepseek-ai/dsh-experimental-forge' import type { ForgeCommandRule } from '@deepseek-ai/dsh-experimental-forge-session' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { GLAB_COMMANDS } from '../src/commands.ts' import * as ForgeGitLab from '../src/index.ts' +import { liveConfig, omitsGeneratedPage } from '../../../settings/settings/tests/live-config.ts' let ctx: Context | undefined @@ -79,8 +80,8 @@ describe('forge-gitlab plugin', () => { it.each([ [{ glabCommand: ' ' }, 'forge-gitlab: glabCommand must not be empty'], - [{ hosts: [] }, 'forge-gitlab: hosts must list at least one host'], - [{ hosts: ['https://gitlab.com'] }, 'forge-gitlab: invalid host "https://gitlab.com"'], + [{ hosts: [] }, '$.hosts expected array length >= 1 but got 0'], + [{ hosts: ['https://gitlab.com'] }, '$.hosts[0] expect string to match regexp'], [{ timeoutMs: 0 }, 'forge-gitlab: timeoutMs must be a positive integer no greater than 2147483647'], [{ timeoutMs: 2_147_483_648 }, 'forge-gitlab: timeoutMs must be a positive integer no greater than 2147483647'], [{ maxOutputBytes: 0 }, 'forge-gitlab: maxOutputBytes must be a positive safe integer'], @@ -94,9 +95,46 @@ describe('forge-gitlab plugin', () => { await expect(context.plugin(ForgeGitLab, config)).rejects.toThrow(message) }) + it('serves the host list a live edit sets without mounting again', async () => { + const context = await forge() + const live = await liveConfig(context, ForgeGitLab) + expect(context.forge.repositoryFromRemote('git@gitlab.example.test:group/app.git')).toBeUndefined() + + await live.update({ hosts: ['gitlab.com', 'gitlab.example.test'] }) + + expect(context.forge.repositoryFromRemote('git@gitlab.example.test:group/app.git')).toEqual({ forge: 'gitlab', host: 'gitlab.example.test', owner: 'group', name: 'app' }) + expect(context.forge.repositoryFromRemote('git@gitlab.com:group/app.git')).toBeDefined() + // Identity only: printing a Fiber walks Context proxies. + expect(Object.is(live.entry.fiber, live.fiber)).toBe(true) + + await live.update({ hosts: ['gitlab.com'] }) + expect(context.forge.repositoryFromRemote('git@gitlab.example.test:group/app.git')).toBeUndefined() + }) + + it('keeps serving its previous hosts when a live edit adds one another provider serves', async () => { + const context = await forge() + context.forge.register({ ...otherProvider(), hosts: ['code.example.test'] }) + const live = await liveConfig(context, ForgeGitLab) + const warned = vi.spyOn(context.logger, 'warn').mockImplementation(() => {}) + + await live.update({ hosts: ['gitlab.com', 'code.example.test'] }) + + expect(context.forge.repositoryFromRemote('git@gitlab.com:group/app.git')).toMatchObject({ forge: 'gitlab', host: 'gitlab.com' }) + expect(context.forge.changeRequestFromUrl('https://code.example.test/group/app/-/merge_requests/1')).toBeUndefined() + expect(warned.mock.calls.map((call): unknown => call[0])) + .toContainEqual(new Error('forge: host "code.example.test" is already served by the "github" provider')) + }) + + it('keeps its own instance off the generated Settings pages', async () => { + await omitsGeneratedPage(async (context) => { + await context.plugin(ForgeService) + return context.plugin(ForgeGitLab, {}) + }) + }) + it('refuses a host the GitHub provider already serves', async () => { const context = await forge() - context.forge.register({ ...stubProvider(), hosts: ['code.example.test'] }) + context.forge.register({ ...otherProvider(), hosts: ['code.example.test'] }) await expect(context.plugin(ForgeGitLab, { hosts: ['code.example.test'] })) .rejects.toThrow('forge: host "code.example.test" is already served by the "github" provider') @@ -104,7 +142,7 @@ describe('forge-gitlab plugin', () => { }) /** A provider of the `github` family that serves nothing it is asked. */ -function stubProvider(): Parameters[0] { +function otherProvider(): Parameters[0] { const never = (): never => { throw new Error('not called') } return { forge: 'github', hosts: [], label: 'GitHub', changeRequestNoun: 'pull-request', diff --git a/packages/experimental/forge-gitlab/tsconfig.json b/packages/experimental/forge-gitlab/tsconfig.json index 34fc412ae8..0ce26185bb 100644 --- a/packages/experimental/forge-gitlab/tsconfig.json +++ b/packages/experimental/forge-gitlab/tsconfig.json @@ -34,6 +34,12 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../../vendor/loader" + }, + { + "path": "../../settings/settings" } ] } diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index 8b9f1a6aef..599a994685 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: 521ff8f9951fd69d - zh: 9d6f4781b996efa4 + en: 4274699614016357 + zh: 3ea092e444ed91c4 /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 b523957ea9..3836dc6b48 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -32,7 +32,7 @@ Mount the registry with at least one provider package, such as the GitHub provid - name: '@deepseek-ai/dsh-experimental-forge-github' ``` -`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 on the hosts its `hosts` lists, and names itself with `label`, such as `GitHub`, and `changeRequestNoun`, `pull-request` or `merge-request`; registering a second provider for the same family, or one that lists a host, compared without case, that a registered provider lists, throws. Registration changes announce `forge/providers-changed`; registering a provider polls its existing watches immediately. `repositoryFromRemote(url)` and `changeRequestFromUrl(url)` return the match of the provider that serves the URL's host, and `describe(forge)` returns a family's `ForgeDescription`, its `label` and `changeRequestNoun`, or undefined without a provider. `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 and, while it cannot sign in, the shell command that signs the user in as `signIn`. +`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. The disposer carries `replace(provider)`, which puts another provider of the same family in the registered one's place in one synchronous step, for a provider whose configuration changes while it runs: no reader finds the family without a provider, the replaced provider's calls are cancelled, and a replacement that lists another family's host throws and leaves the registered provider serving. One provider serves one forge family on the hosts its `hosts` lists, and names itself with `label`, such as `GitHub`, and `changeRequestNoun`, `pull-request` or `merge-request`; registering a second provider for the same family, or one that lists a host, compared without case, that a registered provider lists, throws. Registrations, replacements, and withdrawals announce `forge/providers-changed`; registering or replacing a provider polls its existing watches immediately. `repositoryFromRemote(url)` and `changeRequestFromUrl(url)` return the match of the provider that serves the URL's host, and `describe(forge)` returns a family's `ForgeDescription`, its `label` and `changeRequestNoun`, or undefined without a provider. `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` reads only the forge family and the host, both of which a repository names, and reports whether the provider can reach the host with current credentials and, while it cannot sign in, the shell command that signs the user in as `signIn`. `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 --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index df9840368c..59a82f6c19 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -32,7 +32,7 @@ kind: "package-reference" - name: '@deepseek-ai/dsh-experimental-forge-github' ``` -`ctx.forge.register(provider)` 是调用方 fiber 上的 effect,返回异步 disposer,取消并等待该次注册的调用结束。取消后到达的结果会被丢弃。一个提供方在其 `hosts` 列出的主机上服务一个 forge 家族,并用 `label`(例如 `GitHub`)和 `changeRequestNoun`(`pull-request` 或 `merge-request`)称呼自己;为同一家族注册第二个提供方,或注册一个列出了已注册提供方所列主机(不区分大小写)的提供方,都会抛错。注册变化会发出 `forge/providers-changed`;注册提供方会立即轮询其已有监听。`repositoryFromRemote(url)` 与 `changeRequestFromUrl(url)` 返回服务该 URL 主机的提供方的匹配结果;`describe(forge)` 返回一个家族的 `ForgeDescription`,即它的 `label` 与 `changeRequestNoun`,没有提供方时返回 undefined。`changeRequestUrl(ref)`、`findByHead(repository, branch, signal)` 与 `readiness(repository, signal)` 委托给引用所属 forge 的提供方,没有注册提供方时抛错;`readiness` 报告提供方能否用当前凭据访问该主机;无法登录时还在 `signIn` 中给出让用户登录的 shell 命令。 +`ctx.forge.register(provider)` 是调用方 fiber 上的 effect,返回异步 disposer,取消并等待该次注册的调用结束。取消后到达的结果会被丢弃。该 disposer 还带有 `replace(provider)`:在一个同步步骤内用同一家族的另一个提供方替换已注册的提供方,供配置在运行期间变化的提供方使用;读取方不会遇到该家族没有提供方的时刻,被替换提供方的调用会被取消,列出其他家族主机的替换会抛错,已注册的提供方继续服务。一个提供方在其 `hosts` 列出的主机上服务一个 forge 家族,并用 `label`(例如 `GitHub`)和 `changeRequestNoun`(`pull-request` 或 `merge-request`)称呼自己;为同一家族注册第二个提供方,或注册一个列出了已注册提供方所列主机(不区分大小写)的提供方,都会抛错。注册、替换与撤销都会发出 `forge/providers-changed`;注册或替换提供方会立即轮询其已有监听。`repositoryFromRemote(url)` 与 `changeRequestFromUrl(url)` 返回服务该 URL 主机的提供方的匹配结果;`describe(forge)` 返回一个家族的 `ForgeDescription`,即它的 `label` 与 `changeRequestNoun`,没有提供方时返回 undefined。`changeRequestUrl(ref)`、`findByHead(repository, branch, signal)` 与 `readiness(repository, signal)` 委托给引用所属 forge 的提供方,没有注册提供方时抛错;`readiness` 只读取 forge 家族与主机(仓库同时给出这两项),报告提供方能否用当前凭据访问该主机;无法登录时还在 `signIn` 中给出让用户登录的 shell 命令。 `markReady(ref, signal)` 把草稿标记为可评审;`merge(ref, { method, headSha }, signal)` 只在 head 仍是 `headSha` 时合并变更请求。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错;主机接受时 resolve 为 undefined,否则为 `ForgeActionFailure`:`unauthenticated`、head 已越过 `headSha` 时的 `stale`、带主机原因的 `failed`,或主机的答复无法确认结果时的 `unknown`:此时改动可能已经生效,再次尝试前必须先到主机上核对。两者结束后,被监听的变更请求会立即重新轮询。快照带有 `mergeReady`(主机现在是否会为已登录用户合并该变更请求)与 `mergeMethods`(仓库接受的合并方式,该用户常用的方式排在最前)。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index b02aff3fc7..3016cdda98 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -8,7 +8,8 @@ import { nextPollDelay } from './schedule.ts' import type { BranchUpdateRequest, ChangeRequestDescription, ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, - ForgeCommitList, ForgeActionFailure, ForgeDescription, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, + ForgeCommitList, ForgeActionFailure, ForgeDescription, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRegistrationHandle, + ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewChange, ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, @@ -24,7 +25,7 @@ declare module '@deepseek-ai/cordis' { } interface Events { /** - * Announces a provider registration or withdrawal after the registry changes. + * Announces a provider registration, replacement, or withdrawal after the registry changes. * Listener failures are logged without preventing other listeners from running. * @param forge - family whose provider changed. * @mode parallel @@ -119,36 +120,67 @@ export class ForgeService extends Service { * registration ends. Unregistering cancels and awaits its in-flight calls; * results from the withdrawn registration are discarded. * @param provider - provider to serve `provider.forge` on `provider.hosts`. - * @returns the disposer that unregisters the provider and waits for its calls to finish. + * @returns the disposer that unregisters the provider and waits for its calls to finish, carrying + * {@link ForgeRegistrationHandle.replace}. * @throws when another provider already serves the same forge or one of the same hosts, compared without case. */ - register(provider: ForgeProvider): () => Promise { + register(provider: ForgeProvider): ForgeRegistrationHandle { + const { forge } = provider + // The registration this handle holds; `replace` swaps it and the disposer clears it. + let held: Registration | undefined + // Calls of replaced providers still in flight, which the disposer waits for. + const retired = new Set>() const dispose = this.ctx.effect(() => { - if (this.providers.has(provider.forge)) throw new Error(`forge: a provider for "${provider.forge}" is already registered`) - for (const { provider: other } of this.providers.values()) { - const taken = new Set(other.hosts.map(host => host.toLowerCase())) - const host = provider.hosts.find(candidate => taken.has(candidate.toLowerCase())) - if (host !== undefined) throw new Error(`forge: host "${host}" is already served by the "${other.forge}" provider`) - } - const registration: Registration = { provider, lifetime: new AbortController(), pending: new Set() } - this.providers.set(provider.forge, registration) - for (const watch of this.watches.values()) { - if (watch.ref.repository.forge === provider.forge) watch.dueAt = Date.now() - } - this.providersChanged(provider.forge) - this.schedule() + if (this.providers.has(forge)) throw new Error(`forge: a provider for "${forge}" is already registered`) + held = this.admit(provider) return async () => { - this.providers.delete(provider.forge) - registration.lifetime.abort(new Error(`forge: provider "${provider.forge}" was unregistered`)) + const registration = held as Registration + held = undefined + this.providers.delete(forge) + registration.lifetime.abort(new Error(`forge: provider "${forge}" was unregistered`)) for (const watch of [...this.watches.values()]) { - if (watch.ref.repository.forge === provider.forge) this.settle(watch, this.missing(provider.forge), undefined) + if (watch.ref.repository.forge === forge) this.settle(watch, this.missing(forge), undefined) } - this.providersChanged(provider.forge) + this.providersChanged(forge) this.schedule() - await Promise.allSettled(registration.pending) + await Promise.allSettled([...registration.pending, ...retired]) } - }, `forge.register(${provider.forge})`) - return async () => { await dispose() } + }, `forge.register(${forge})`) + const handle = (async () => { await dispose() }) as ForgeRegistrationHandle + handle.replace = (next) => { + if (held === undefined) throw new Error(`forge: the withdrawn registration of "${forge}" cannot replace its provider`) + if (next.forge !== forge) throw new Error(`forge: the registration of "${forge}" cannot serve "${next.forge}"`) + const previous = held + held = this.admit(next) + previous.lifetime.abort(new Error(`forge: provider "${forge}" was replaced`)) + for (const call of previous.pending) { + retired.add(call) + void call.then(() => retired.delete(call)) + } + } + return handle + } + + /** + * Make `provider` the provider of its forge family, in place of the family's current one when there is one: its + * watches poll at once and `forge/providers-changed` announces the change. + * @throws when another family's provider serves one of `provider.hosts`, compared without case; the registry is unchanged. + */ + private admit(provider: ForgeProvider): Registration { + for (const { provider: other } of this.providers.values()) { + if (other.forge === provider.forge) continue + const taken = new Set(other.hosts.map(host => host.toLowerCase())) + const host = provider.hosts.find(candidate => taken.has(candidate.toLowerCase())) + if (host !== undefined) throw new Error(`forge: host "${host}" is already served by the "${other.forge}" provider`) + } + const registration: Registration = { provider, lifetime: new AbortController(), pending: new Set() } + this.providers.set(provider.forge, registration) + for (const watch of this.watches.values()) { + if (watch.ref.repository.forge === provider.forge) watch.dueAt = Date.now() + } + this.providersChanged(provider.forge) + this.schedule() + return registration } /** @@ -211,13 +243,13 @@ export class ForgeService extends Service { } /** - * Report whether the provider can reach the repository's host with current credentials. - * @param repository - repository served by a registered provider. + * Report whether a provider can reach one host with current credentials. + * @param repository - forge family of a registered provider and the host to probe; a repository names both. * @param signal - cancellation for the probe. * @returns the provider's readiness for the host. - * @throws when no provider serves the repository's forge. + * @throws when no provider serves the forge. */ - async readiness(repository: ForgeRepository, signal: AbortSignal): Promise { + async readiness(repository: Pick, signal: AbortSignal): Promise { return await this.invoke(this.registration(repository.forge), signal, (provider, operation) => provider.readiness(repository.host, operation)) } diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index b13a016010..646307c62c 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -757,6 +757,24 @@ export interface ForgeProvider { updateBranch?(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise } +/** + * What `ctx.forge.register` returns: the disposer, plus the replacement of the registered provider by another provider + * of the same forge family, for a provider whose configuration changes while it runs. + */ +export interface ForgeRegistrationHandle { + /** Unregister the provider this registration holds and wait for its calls, and those of the providers it replaced, to finish. */ + (): Promise + /** + * Replace the registered provider in one synchronous step, so no reader finds the family without a provider. The + * replaced provider's in-flight calls are cancelled and their results discarded; watches of the family poll at once + * and `forge/providers-changed` announces the change. + * @param provider - provider of the same forge family. + * @throws when the registration was withdrawn, `provider.forge` is another family, or another family's provider + * serves one of `provider.hosts`, compared without case; the registered provider then keeps serving. + */ + replace(provider: ForgeProvider): void +} + /** * Receives every polling result for one watched change request. * @param update - the settled result. diff --git a/packages/experimental/forge/tests/lifecycle.spec.ts b/packages/experimental/forge/tests/lifecycle.spec.ts index e5d19fb61e..cb85d82d56 100644 --- a/packages/experimental/forge/tests/lifecycle.spec.ts +++ b/packages/experimental/forge/tests/lifecycle.spec.ts @@ -120,6 +120,104 @@ it('does not announce provider withdrawal after its registry has stopped', async expect(observer).toHaveBeenCalledTimes(1) }) +it('replaces a registered provider in one step and polls its watches at once', async () => { + vi.useFakeTimers() + ctx = await forgeContext() + const first = new FakeProvider() + first.results.set(changeRequestKey(ref(1)), snapshot(ref(1))) + const registration = ctx.forge.register(first) + const titles: string[] = [] + ctx.forge.watch(ref(1), (update) => { titles.push('snapshot' in update ? update.snapshot.title : update.failure.code) }) + await vi.advanceTimersByTimeAsync(0) + const changes: string[] = [] + ctx.on('forge/providers-changed', (forge) => { changes.push(forge) }) + const second = new FakeProvider('fake', ['fake.test', 'second.test']) + second.results.set(changeRequestKey(ref(1)), snapshot(ref(1), { title: 'Read by the second provider' })) + + registration.replace(second) + + expect(ctx.forge.repositoryFromRemote('fake://second.test/Octo/Demo')).toEqual({ ...demo, host: 'second.test' }) + await vi.advanceTimersByTimeAsync(0) + expect(first.fetches).toEqual([[ref(1)]]) + expect(second.fetches).toEqual([[ref(1)]]) + expect(titles).toEqual(['Change 1', 'Read by the second provider']) + expect(changes).toEqual(['fake']) + + await registration() + expect(ctx.forge.repositoryFromRemote('fake://second.test/Octo/Demo')).toBeUndefined() +}) + +it('cancels the calls of a replaced provider and waits for them when the registration ends', async () => { + ctx = await forgeContext() + const first: ForgeProvider = new FakeProvider() + const result = Promise.withResolvers>>() + const aborted = Promise.withResolvers() + vi.spyOn(first, 'findByHead').mockImplementation((_repository, _branch, signal) => { + signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true }) + return result.promise + }) + const registration = ctx.forge.register(first) + const lookup = ctx.forge.findByHead(demo, 'topic', new AbortController().signal) + const rejected = expect(lookup).rejects.toThrow('forge: provider "fake" was replaced') + let disposed = false + try { + registration.replace(new FakeProvider()) + await aborted.promise + const disposal = registration().then(() => { disposed = true }) + await new Promise((resolve) => { setTimeout(resolve, 0) }) + expect(disposed).toBe(false) + result.resolve([ref(3)]) + await rejected + await disposal + expect(disposed).toBe(true) + } finally { + result.resolve([]) + await rejected + } +}) + +it('forgets a replaced provider\'s call once it finishes', async () => { + ctx = await forgeContext() + const first: ForgeProvider = new FakeProvider() + const result = Promise.withResolvers>>() + vi.spyOn(first, 'findByHead').mockReturnValue(result.promise) + const registration = ctx.forge.register(first) + const rejected = expect(ctx.forge.findByHead(demo, 'topic', new AbortController().signal)).rejects.toThrow('was replaced') + registration.replace(new FakeProvider()) + + result.resolve([]) + await rejected + + await expect(registration()).resolves.toBeUndefined() +}) + +it('keeps the registered provider when its replacement is refused', async () => { + ctx = await forgeContext() + ctx.forge.register(new FakeProvider('other', ['other.test'])) + const registration = ctx.forge.register(new FakeProvider()) + const observer = vi.fn() + ctx.on('forge/providers-changed', observer) + + expect(() => { registration.replace(new FakeProvider('other', ['third.test'])) }) + .toThrow('forge: the registration of "fake" cannot serve "other"') + expect(() => { registration.replace(new FakeProvider('fake', ['fake.test', 'OTHER.test'])) }) + .toThrow('forge: host "OTHER.test" is already served by the "other" provider') + + expect(ctx.forge.repositoryFromRemote('fake://fake.test/Octo/Demo')).toEqual(demo) + expect(ctx.forge.repositoryFromRemote('fake://other.test/Octo/Demo')).toMatchObject({ forge: 'other' }) + await Promise.resolve() + expect(observer).not.toHaveBeenCalled() +}) + +it('refuses to replace the provider of a withdrawn registration', async () => { + ctx = await forgeContext() + const registration = ctx.forge.register(new FakeProvider()) + await registration() + + expect(() => { registration.replace(new FakeProvider()) }).toThrow('forge: the withdrawn registration of "fake" cannot replace its provider') + expect(ctx.forge.repositoryFromRemote('fake://fake.test/Octo/Demo')).toBeUndefined() +}) + it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', 'fetchChecks', 'commits', 'compare'] as const)( 'cancels and drains %s when its provider stops', async (method) => { ctx = await forgeContext() diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 1c3519ff2f..d8ddd6a714 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -3778,6 +3778,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', occupants: [ 'experimental-client-ui-forge WorktreeSettings', + 'experimental-client-ui-forge HostSettings', ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.row.config\', () => ctx.slots.register(\n { name: \'plugins.row.config\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 070c1782a7..75d58c66a3 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1343,10 +1343,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Registry of forge providers. Watchers of one change request share a single polling loop; each forge has at most one fetch in flight, which batches every due change request of that forge.', methods: [ { - signature: 'register(provider: ForgeProvider): () => Promise', + signature: 'register(provider: ForgeProvider): ForgeRegistrationHandle', description: 'Register the provider of one forge family as an effect on the calling fiber. Watches of that forge receive an `unavailable` failure when the registration ends. Unregistering cancels and awaits its in-flight calls; results from the withdrawn registration are discarded.', parameters: [{ name: 'provider', description: 'provider to serve `provider.forge` on `provider.hosts`.' }], - returns: 'the disposer that unregisters the provider and waits for its calls to finish.', + returns: 'the disposer that unregisters the provider and waits for its calls to finish, carrying {@link ForgeRegistrationHandle.replace}.', throws: ['when another provider already serves the same forge or one of the same hosts, compared without case.'], }, { @@ -1382,11 +1382,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['when no provider serves the repository\'s forge or the lookup fails.'], }, { - signature: 'async readiness(repository: ForgeRepository, signal: AbortSignal): Promise', - description: 'Report whether the provider can reach the repository\'s host with current credentials.', - parameters: [{ name: 'repository', description: 'repository served by a registered provider.' }, { name: 'signal', description: 'cancellation for the probe.' }], + signature: 'async readiness(repository: Pick, signal: AbortSignal): Promise', + description: 'Report whether a provider can reach one host with current credentials.', + parameters: [{ name: 'repository', description: 'forge family of a registered provider and the host to probe; a repository names both.' }, { name: 'signal', description: 'cancellation for the probe.' }], returns: 'the provider\'s readiness for the host.', - throws: ['when no provider serves the repository\'s forge.'], + throws: ['when no provider serves the forge.'], }, { signature: 'async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise', @@ -1594,6 +1594,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Read every streamed review page list and the count again at once.', parameters: [{ name: 'signal', description: 'request cancellation.' }], }, + { + signature: '@Remote async hostReadiness(forge: string, host: string, signal: AbortSignal): Promise', + description: 'Report whether a provider reaches one of its hosts with the Host\'s current credentials, for the host list on the Plugins page of that provider\'s row. The read names no Session, so, like the review page reads, only callers that may use the Host\'s code host credentials reach it.', + parameters: [{ name: 'forge', description: 'forge family of a registered provider, such as `gitlab`.' }, { name: 'host', description: 'host name as the provider\'s configuration lists it.' }, { name: 'signal', description: 'request cancellation.' }], + returns: 'the provider\'s readiness for the host; `unavailable` with the reason when no provider serves the family, the probe fails, or it runs past `readinessTimeoutMs`.', + }, { signature: '@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewPoll(url: string, signal: AbortSignal): Promise', description: 'Poll one change request the review page shows at once; its stream reports the result.', @@ -5754,8 +5760,8 @@ export const EVENT_API: readonly EventApiEntry[] = [ name: 'forge/providers-changed', mode: 'parallel', signature: '\'forge/providers-changed\'(forge: string): void | Promise', - summary: 'Announces a provider registration or withdrawal after the registry changes.', - description: 'Announces a provider registration or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running.', + summary: 'Announces a provider registration, replacement, or withdrawal after the registry changes.', + description: 'Announces a provider registration, replacement, or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running.', parameters: [{ name: 'forge', description: 'family whose provider changed.' }], }, { @@ -7674,6 +7680,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeRegisteredLens', declaration: 'export interface ForgeRegisteredLens {\n readonly id: string;\n readonly version: string;\n}', }, + { + name: 'ForgeRegistrationHandle', + declaration: 'export interface ForgeRegistrationHandle {\n (): Promise;\n replace(provider: ForgeProvider): void;\n}', + }, { name: 'ForgeRemoteBranches', declaration: 'export interface ForgeRemoteBranches {\n readonly name: string;\n readonly repository: string | null;\n readonly branches: readonly ForgeBaseBranch[];\n}', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4964dd920d..1cb1245672 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11333,6 +11333,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand @@ -11342,6 +11345,9 @@ importers: '@deepseek-ai/dsh-experimental-forge-session': specifier: workspace:* version: link:../forge-session + '@deepseek-ai/dsh-settings': + specifier: workspace:* + version: link:../../settings/settings '@deepseek-ai/dsh-subprocess': specifier: workspace:* version: link:../../subprocess/subprocess @@ -11373,6 +11379,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand @@ -11382,6 +11391,9 @@ importers: '@deepseek-ai/dsh-experimental-forge-session': specifier: workspace:* version: link:../forge-session + '@deepseek-ai/dsh-settings': + specifier: workspace:* + version: link:../../settings/settings '@deepseek-ai/dsh-subprocess': specifier: workspace:* version: link:../../subprocess/subprocess diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 759380effe..ac83bf60cd 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -439,6 +439,7 @@ export const LINK_MAP: Readonly> = { ChangeRequestRef: 'forge.md', ChangeRequestSnapshot: 'forge.md', ChangeRequestUpdate: 'forge.md', + ForgeRegistrationHandle: 'forge.md', ForgeActionFailure: 'forge.md', ForgeLineComment: 'forge.md', ForgeReviewRequest: 'forge.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index d9fbfbfb45..3f12a8c68c 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2454,6 +2454,11 @@ "symbol": "ForgeProvider", "source": "packages/experimental/forge/src/types.ts" }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeRegistrationHandle", + "source": "packages/experimental/forge/src/types.ts" + }, { "doc": "docs/subsystems/forge.md", "symbol": "ForgeCommit", From 6e94624bc97050750c89fc1f372cb8e957c3db35 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 19 Nov 2026 21:03:30 +0800 Subject: [PATCH 02/14] feat(forge): list GitLab merge requests on the Code review page and redraw its list card The Code review page lists the change requests of every host a provider serves, GitHub and GitLab together, and its filter menu narrows the lists to one host or one repository on a host. - forge: `ChangeRequestSummary` drops `closingIssues` and `closingIssuesTruncated`; a list row no longer names linked issues. - forge-gitlab: the provider declares `viewer` and implements `listForViewer`, `countForViewer`, and `readDescription` through GraphQL `currentUser` connections. "Involving me" is the merge requests the user reviewed or is assigned to. - client-ui-forge (Host): each host backs off on its own failed reads, so one failing host no longer slows the others; a repository scope names its host and is read on that host only; a host that failed for lack of sign-in carries the provider's sign-in command. - client-ui-forge (Client): the list card shows the title on at most two lines, then repository, number, author, one hint, and a short time; a host that could not be read shows one notice after the lists with the sign-in command and a way to the host settings; a section keeps skeleton rows and holds back its count while a host's first read still runs. The re-request hint is shortened in eight languages. --- .../2026-11-11-forge-review-page.i18n.yaml | 4 +- .../feature/2026-11-11-forge-review-page.md | 2 +- .../2026-11-11-forge-review-page.zh.md | 2 +- apps/web/tests/forge-panel.e2e.ts | 114 ++++++- docs/config-catalog.md | 6 +- docs/config-catalog.zh.md | 6 +- docs/subsystems/forge.i18n.yaml | 4 +- docs/subsystems/forge.md | 16 +- docs/subsystems/forge.zh.md | 16 +- .../forge-viewer-list-rows/guide.i18n.yaml | 16 + .../forge-viewer-list-rows/guide.md | 19 ++ .../forge-viewer-list-rows/guide.zh.md | 19 ++ .../client-ui-forge/README.i18n.yaml | 8 +- .../experimental/client-ui-forge/README.md | 4 +- .../experimental/client-ui-forge/README.zh.md | 4 +- .../client-ui-forge/src/client/locales.ts | 56 ++-- .../src/client/review-page/ReviewList.tsx | 285 ++++++++++-------- .../client/review-page/ReviewPage.module.css | 98 +++++- .../src/client/review-page/ReviewPage.tsx | 19 +- .../src/client/review-page/review-lists.ts | 107 +++++-- .../src/client/review-page/review-mount.ts | 5 +- .../src/client/review-page/review-store.ts | 14 +- .../experimental/client-ui-forge/src/index.ts | 13 +- .../experimental/client-ui-forge/src/types.ts | 17 +- .../client-ui-forge/src/viewer-lists.ts | 172 ++++++++--- .../tests/mount.client.spec.ts | 6 +- .../tests/review-fixtures.client.ts | 6 +- .../tests/review-list.client.spec.tsx | 224 ++++++++++---- .../tests/review-lists.client.spec.ts | 145 ++++++--- .../tests/review-page.client.spec.tsx | 46 ++- .../tests/review-page.host.spec.ts | 19 +- .../tests/viewer-lists.host.spec.ts | 178 ++++++++++- .../forge-github/README.i18n.yaml | 4 +- packages/experimental/forge-github/README.md | 2 +- .../experimental/forge-github/README.zh.md | 2 +- .../experimental/forge-github/src/graphql.ts | 4 +- .../experimental/forge-github/src/viewer.ts | 21 +- .../forge-github/tests/viewer.spec.ts | 18 +- .../forge-gitlab/README.i18n.yaml | 12 +- packages/experimental/forge-gitlab/README.md | 10 +- .../experimental/forge-gitlab/README.zh.md | 10 +- .../forge-gitlab/src/description.ts | 72 +++++ .../experimental/forge-gitlab/src/provider.ts | 81 ++++- .../experimental/forge-gitlab/src/status.ts | 50 ++- .../experimental/forge-gitlab/src/urls.ts | 2 +- .../experimental/forge-gitlab/src/viewer.ts | 285 ++++++++++++++++++ .../forge-gitlab/tests/description.spec.ts | 83 +++++ .../forge-gitlab/tests/provider.spec.ts | 130 ++++++++ .../forge-gitlab/tests/viewer.spec.ts | 223 ++++++++++++++ packages/experimental/forge/src/types.ts | 4 - .../extensions/tool-cordis/src/api-catalog.ts | 14 +- scripts/gen-cordis-catalog.ts | 1 + 52 files changed, 2175 insertions(+), 503 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.zh.md create mode 100644 packages/experimental/forge-gitlab/src/description.ts create mode 100644 packages/experimental/forge-gitlab/src/viewer.ts create mode 100644 packages/experimental/forge-gitlab/tests/description.spec.ts create mode 100644 packages/experimental/forge-gitlab/tests/viewer.spec.ts diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml index ea1862a84e..0f370ec259 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml @@ -9,8 +9,8 @@ en: ad1da0c97cfc9c2d zh: f4420c0b004fd189 /agent-note-code-review-page/decision: - en: b0ba35d7c5818dc3 - zh: 5414ec6190be0726 + en: 8bba17ff42512edd + zh: 5fc73c84fdfc4834 /agent-note-code-review-page/alternatives-considered: en: 963b1be39a0e4bac zh: 940b86a5e2036477 diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md index 205baefe8f..29bef8f6af 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md @@ -17,7 +17,7 @@ A left-navigation Code review page in [`dsh-experimental-client-ui-forge`](../.. - **Description** — `readDescription` returns the Markdown body, labels, and signed addresses for private attachments, which the page substitutes before rendering with HTML omitted. - **Changes** — the page draws the changes view itself, split from the right-sidebar tab, with a panel state that holds only the shown change request; plugin lenses, annotations, and slots stay with the Session tab, whose extension points name a Session. - **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. A Workspace picked in the Hero is handled by the page, as every owner of the content handles its own picks: the page connects that Workspace's blank and shows it in the chat tab, where the main Conversation opens it as the main Session. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound. -- **Hosts** — the page lists every configured host together; choosing among hosts and accounts waits for a second provider that lists change requests. +- **Hosts** — the page lists every configured host together, GitHub and GitLab. A host whose read failed is read again later each time without delaying the others, since the bundle ships a GitLab host most users are not signed in to. A repository scope names its host and is read there only: one `owner/name` can exist on two hosts, and a GitLab project path nests groups. The filter offers each host once the lists span several, and a host that could not be read shows one notice after the lists. A row names no host, because every row would then need a second line of small text; choosing among accounts of one host is not offered. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md index 3c342919a6..0bbaddbe96 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md @@ -17,7 +17,7 @@ Status: implemented - **描述**——`readDescription` 返回 Markdown 正文、标签以及私有附件的签名地址,页面替换这些地址后以省略 HTML 的方式渲染。 - **变更**——页面自己绘制变更视图(从右侧栏标签中拆出),面板状态只含显示中的变更请求;插件的透镜、行注释和插槽仍只在会话标签中,因为这些扩展点以会话为对象。 - **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。在 Hero 中选择工作区由页面自己处理,这与内容的每个属主处理各自的选择一致:页面连接该工作区的空白会话并在对话标签中显示它,而主 Conversation 会把它打开为主会话。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。 -- **主机**——页面把所有已配置的主机合并列出;在主机与账号之间选择要等到第二个能列出变更请求的提供方。 +- **主机**——页面把所有已配置的主机合并列出,包括 GitHub 与 GitLab。读取失败的主机每次间隔更久再读,不拖慢其他主机,因为套件自带的 GitLab 主机多数用户并未登录。仓库范围带有主机,只在该主机上读取:同一个 `owner/name` 可以存在于两个主机,GitLab 的项目路径还有嵌套分组。列表跨多个主机时,筛选列出每个主机;读取失败的主机在列表之后显示一条提示。列表行不写主机,否则每一行都要多一行小字;同一主机的多个账号之间不提供选择。 ## Alternatives considered diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 73146827c0..0d742c6140 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -230,6 +230,28 @@ if (args[0] === 'api' && args[1] === 'graphql') { }) const overview = existsSync(join(here, 'overview.json')) ? JSON.parse(readFileSync(join(here, 'overview.json'), 'utf8')) : {} const none = { totalCount: 0, nodes: [] } + if (query.includes('search(type: ISSUE')) { + // The review page's lists and their count, which only a case that writes lists.json shows. + if (!existsSync(join(here, 'lists.json'))) { + process.stderr.write('no lists fixture\\n') + process.exit(1) + } + const lists = JSON.parse(readFileSync(join(here, 'lists.json'), 'utf8')) + if (query.includes('review: search(')) { + process.stdout.write(JSON.stringify({ data: { review: { issueCount: lists['review-requested'].length }, + authored: { issueCount: lists.authored.length }, involved: { issueCount: lists.involved.length } } })) + process.exit(0) + } + const q = args.find(arg => arg.startsWith('q=')).slice(2) + const filter = q.includes('involves:@me') ? 'involved' : q.includes('review-requested:@me') ? 'review-requested' : 'authored' + const row = number => ({ __typename: 'PullRequest', number, title: 'Pull request ' + number, url: 'https://github.com/octo/demo/pull/' + number, isDraft: false, + updatedAt: new Date(Date.now() - 5 * 60000).toISOString(), headRefOid: 'a'.repeat(40), reviewDecision: null, + repository: { name: 'demo', owner: { login: 'octo' } }, author: { __typename: 'User', login: 'octo', avatarUrl: null }, + commits: { nodes: [{ commit: { statusCheckRollup: { state: 'SUCCESS' } } }] }, viewerLatestReview: null, + viewerLatestReviewRequest: filter === 'review-requested' ? { requestedReviewer: { __typename: 'User' } } : null }) + process.stdout.write(JSON.stringify({ data: { viewer: { login: VIEWER }, search: { issueCount: lists[filter].length, nodes: lists[filter].map(row) } } })) + process.exit(0) + } 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] } @@ -472,12 +494,43 @@ interface PanelLaunch { readonly tripwire: ReturnType } +/** + * A GitLab CLI double for the review page's lists on gitlab.com: user `lin` is asked to review merge request 12 of the + * nested-group project `group/sub/app`, updated three minutes before each read, and has no other merge request. + */ +const GLAB = `#!/usr/bin/env node +import { readFileSync } from 'node:fs' +const args = process.argv.slice(2) +if (args[0] === 'api' && args[1] === 'graphql') { + const { query, variables } = JSON.parse(readFileSync(0, 'utf8')) + const row = { iid: '12', title: 'Fix the gateway timeout', webUrl: 'https://gitlab.com/group/sub/app/-/merge_requests/12', draft: false, + updatedAt: new Date(Date.now() - 3 * 60000).toISOString(), diffHeadSha: 'c'.repeat(40), approved: false, + author: { username: 'mona', avatarUrl: null, bot: false }, project: { fullPath: 'group/sub/app' }, headPipeline: { status: 'SUCCESS' }, + reviewers: { nodes: [{ username: 'lin', mergeRequestInteraction: { reviewState: 'UNREVIEWED' } }] } } + const page = nodes => ({ count: nodes.length, nodes }) + const listed = variables.project === null || variables.project === 'group/sub/app' ? [row] : [] + const user = query.includes('awaited:') ? { awaited: { count: 1 }, authored: { count: 0 }, reviewed: { count: 0 }, assigned: { count: 0 } } + : query.includes('reviewed:') ? { reviewed: page([]), assigned: page([]) } + : query.includes('list: reviewRequestedMergeRequests') ? { list: page(listed) } + : query.includes('list: authoredMergeRequests') ? { list: page([]) } : {} + process.stdout.write(JSON.stringify({ data: { currentUser: { username: 'lin', ...user } } })) + process.exit(0) +} +if (args[0] === 'api') { + process.stdout.write(JSON.stringify({ username: 'lin' })) + process.exit(0) +} +process.stderr.write('unexpected glab call\\n') +process.exit(1) +` + /** * Launch the bundle against a GitHub checkout of `main` and `release` and open the New Session screen of that workspace. * @param failureShot - name of the screenshot saved when the test fails. * @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup through `bash` or a PTC program. - * @param options - desktop transport, checkout branch, browser input, sandbox runner availability, diff output limit, and - * whether the extension fixture plugin loads. + * @param options - desktop transport, checkout branch, browser input, sandbox runner availability, diff output limit, + * whether the extension fixture plugin loads, the pull requests each review page list of github.com holds, and whether + * the GitLab provider runs {@link GLAB} instead of the machine's GitLab CLI. * @returns the scaffold, page, and checkout. */ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' | 'ptc-reference' = 'normal', @@ -488,6 +541,8 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' missingSandbox?: boolean maxDiffBytes?: number extension?: boolean + lists?: Readonly> + glab?: boolean } = {}): Promise { const { desktop } = options const resources: { scaffold?: WebScaffold; browser?: Browser } = {} @@ -502,12 +557,19 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' const gh = join(root, 'gh') await writeFile(gh, GH) await chmod(gh, 0o755) + if (options.lists !== undefined) await writeFile(join(root, 'lists.json'), JSON.stringify(options.lists)) + const glab = join(root, 'glab') + if (options.glab === true) { + await writeFile(glab, GLAB) + await chmod(glab, 0o755) + } await writeFile(join(root, 'pr-7.diff'), PR7_DIFF) await writeFile(join(root, 'pr-9.diff'), PR9_DIFF) const panelText = `${Array.from({ length: 20 }, (_, index) => panelLine(index + 1, 'new')).join('\n')}\n` await writeFile(join(root, 'contents.json'), JSON.stringify({ [`src/panel.ts@${HEAD7}`]: panelText })) const overlay = join(root, 'forge.patch.yml') await writeFile(overlay, `- id: forge-github\n config: ${JSON.stringify({ ghCommand: gh })}\n` + + (options.glab === true ? `- id: forge-gitlab\n config: ${JSON.stringify({ glabCommand: glab })}\n` : '') + (options.maxDiffBytes === undefined ? '' : `- id: forge-panel\n config: ${JSON.stringify({ maxDiffBytes: options.maxDiffBytes })}\n`) + (options.missingSandbox ? `- id: sandbox\n config: ${JSON.stringify({ runnerCommand: [join(root, 'missing-sandbox')], runnerFailureSignatures: ['sandbox startup failed'] })}\n` : '')) const override = join(root, 'replay.override.json') @@ -768,6 +830,54 @@ it.skipIf(MODE === 'record')('reports incomplete filter configuration and retrie expect(tripwire.warnings).toEqual([]) }) +it.skipIf(MODE === 'record')('lists the change requests of a GitHub and a GitLab host on the Code review page and narrows them to one host or project', async () => { + const { scaffold, page, tripwire } = await launchPanel('web-e2e-forge-review-lists', 'normal', { + glab: true, lists: { 'review-requested': [7], 'authored': [], 'involved': [] }, + }) + // The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first. + const { settled } = await sendPrompt(page, scaffold) + await settled + const entry = page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '代码评审', exact: true }) + // The navigation entry counts the requests of both hosts. + await page.getByRole('button', { name: '代码评审', exact: true, description: '2 个变更请求等你评审' }).waitFor() + await entry.click() + const list = page.locator('[data-forge-review-list]') + const requested = list.locator('[data-forge-review-section="review-requested"]') + const items = requested.locator('[data-forge-review-item]') + const shown = async (): Promise<(string | null)[]> => await items.evaluateAll(rows => rows.map(row => row.textContent)) + const MERGE = 'https://gitlab.com/group/sub/app/-/merge_requests/12' + + // Both hosts' change requests show together, most recently updated first, each on a card without a closing issue. + await list.locator(`[data-forge-review-item="${MERGE}"]`).waitFor() + await list.locator(`[data-forge-review-item="${PULL}"]`).waitFor() + await expect.poll(shown).toEqual([ + expect.stringMatching(/^Fix the gateway timeoutapp#12·mona\d+分钟$/), expect.stringMatching(/^Pull request 7demo#7·octo\d+分钟$/), + ]) + expect(await requested.getByRole('button', { name: /待我评审/ }).textContent()).toBe('待我评审2') + expect(await list.locator('[data-forge-review-failure]').count()).toBe(0) + + // The repository submenu offers each host with its repositories below it; a host narrows the lists on the page. + await list.getByRole('button', { name: '筛选', exact: true }).click() + await page.getByRole('menuitem', { name: /^仓库/ }).click() + const offered = page.getByRole('menu').last().getByRole('menuitem') + await expect.poll(async () => await offered.allTextContents()).toEqual(['全部仓库', 'github.com', 'octo/demo', 'gitlab.com', 'group/sub/app']) + await offered.filter({ hasText: 'gitlab.com' }).click() + // One repository is left in the lists, so its name leaves the card. + await expect.poll(shown).toEqual([expect.stringMatching(/^Fix the gateway timeout#12·mona\d+分钟$/)]) + expect(await requested.getByRole('button', { name: /待我评审/ }).textContent()).toBe('待我评审1') + + // A project in a nested group is one choice, read on its own host only: GitHub is not asked for it, so no host fails. + await list.getByRole('button', { name: '筛选', exact: true }).click() + expect(await page.getByRole('menuitem', { name: /^仓库/ }).textContent()).toBe('仓库gitlab.com') + await page.getByRole('menuitem', { name: /^仓库/ }).click() + await page.getByRole('menu').last().getByRole('menuitem', { name: 'group/sub/app', exact: true }).click() + await expect.poll(shown).toEqual([expect.stringMatching(/^Fix the gateway timeout#12·mona\d+分钟$/)]) + expect(await list.locator('[data-forge-review-item]').count()).toBe(1) + expect(await list.locator('[data-forge-review-failure]').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + it.skipIf(MODE === 'record')('adds a host on the GitLab row of the Plugins page, which the provider serves without a restart', async () => { const { scaffold, page, tripwire } = await launchPanel('web-e2e-forge-hosts') // The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first. diff --git a/docs/config-catalog.md b/docs/config-catalog.md index f6caa0a5ec..4c61c3a61b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1232,7 +1232,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:587`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:602`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1300,7 +1300,7 @@ export interface Config { reviewListIntervalMs?: number /** Milliseconds between two reads of the review page's navigation count while it is shown. */ reviewCountIntervalMs?: number - /** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */ + /** Largest delay in milliseconds between two reads of the review page's lists or count on one host after its consecutive failed reads. */ reviewMaxBackoffMs?: number /** Most change requests one review page list shows, capped by each provider's own limit. */ reviewPageSize?: number @@ -1337,7 +1337,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:851`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:847`](../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 2b13f25880..b9a96ff978 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1234,7 +1234,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:587`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:602`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1302,7 +1302,7 @@ export interface Config { reviewListIntervalMs?: number /** Milliseconds between two reads of the review page's navigation count while it is shown. */ reviewCountIntervalMs?: number - /** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */ + /** Largest delay in milliseconds between two reads of the review page's lists or count on one host after its consecutive failed reads. */ reviewMaxBackoffMs?: number /** Most change requests one review page list shows, capped by each provider's own limit. */ reviewPageSize?: number @@ -1339,7 +1339,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:851`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:847`](../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 472c785852..faeaa7ed01 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -30,8 +30,8 @@ en: 83ad892728d13987 zh: d19b012f5898ef07 /forges/panel/review-page: - en: f576f6e104ec9546 - zh: b97efdd34b3a9d1b + en: 0e003249228a7d55 + zh: 1643e6c79f4c255b /forges/extension-api: en: f35345e482e84f4f zh: 2ecb7d9498decb31 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index e874f4a4e7..7eb94e2631 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -949,10 +949,6 @@ interface ChangeRequestSummary { * `organization/slug`, when the request asks a team the user belongs to rather than the user. */ readonly viewerRequest: { readonly team: string | null } | null - /** Issues the host closes once the change request merges, in host order, at most the provider's limit. */ - 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 } @@ -1620,7 +1616,7 @@ interface ForgeLocalChanges { ### Review page -The [code review page](../../packages/experimental/client-ui-forge/README.md#use-this-package) reads change requests by URL instead of through a Session binding. Its `forgePanel` methods (`reviewLists`, `reviewCount`, `reviewChangeRequest`, `reviewDescription`, and the `review*` reads and actions that mirror the Session-bound ones) resolve the URL with `ForgeService.changeRequestFromUrl`, fail with `forgePanel/unrecognized-url` when no provider serves it, and name no Session resource, so only callers that may use the Host's code host credentials reach them. One list hub reads the [viewer lists](#viewer-lists-and-descriptions) only while a list or count stream lasts: streams of one repository scope share one reader that reads every list of every host each `reviewListIntervalMs`, hosts in parallel and each host's lists in order, stops the round's further reads on a host that refuses the viewer or is rate-limited, and backs off after failed rounds up to `reviewMaxBackoffMs`; the count reads every `reviewCountIntervalMs`, and lists of every repository refresh it too. `reviewLists` streams `ForgeReviewFrame` values with each host's lists, the items of the latest successful read, and the failure of the latest read; `reviewCount` streams `ForgeReviewCountFrame` values; and `reviewChangeRequest` streams `ForgeReviewChangeRequest` values for the shown change request, which is polled through `ForgeService.watch` while its stream lasts. +The [code review page](../../packages/experimental/client-ui-forge/README.md#use-this-package) reads change requests by URL instead of through a Session binding. Its `forgePanel` methods (`reviewLists`, `reviewCount`, `reviewChangeRequest`, `reviewDescription`, and the `review*` reads and actions that mirror the Session-bound ones) resolve the URL with `ForgeService.changeRequestFromUrl`, fail with `forgePanel/unrecognized-url` when no provider serves it, and name no Session resource, so only callers that may use the Host's code host credentials reach them. One list hub reads the [viewer lists](#viewer-lists-and-descriptions) only while a list or count stream lasts: streams of one repository scope share one reader that reads every list of every host each `reviewListIntervalMs`, hosts in parallel and each host's lists in order, stops the round's further reads on a host that refuses the viewer or is rate-limited, and reads a host whose read failed again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence; the count reads every `reviewCountIntervalMs` in the same way, and lists of every repository refresh it too. A scope is every repository of every host or one `ForgeReviewRepository`, which names its host and is read on that host only. `reviewLists` streams `ForgeReviewFrame` values with each host's lists, the items of the latest successful read, the failure of the latest read, and, for a host that refused the viewer, the sign-in command its provider's `readiness` names; `reviewCount` streams `ForgeReviewCountFrame` values; and `reviewChangeRequest` streams `ForgeReviewChangeRequest` values for the shown change request, which is polled through `ForgeService.watch` while its stream lasts. The chat tab starts in the blank Session `connectWorkspace` resolves and records the change request with `reviewStage`; the Host keeps that choice in memory and binds the change request once the Session's next message enters its inbox, so an untouched blank stays unbound. @@ -2139,13 +2135,15 @@ Serves the forge panel. Following a Session inspects the checkout of its current /** * Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on: * the lists read so far first, then a frame after each read settles. Readers of one repository scope share one - * reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to - * `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops. - * @param repository - one repository to list in, or null for every repository the user can read. + * reader, which reads each host every `reviewListIntervalMs` while some stream lasts and reads a host whose read failed + * again later each time, up to `reviewMaxBackoffMs`, without delaying the other hosts; nothing is read while no stream + * lasts. The stream ends when `signal` aborts or the Remote stops. + * @param repository - one repository to list in, read on its host only, or null for every repository the user can + * read on every host. * @param signal - ends the stream. * @returns frames, each complete. */ -@Remote({ mode: 'stream' }) async *reviewLists( repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, ): AsyncIterable +@Remote({ mode: 'stream' }) async *reviewLists( repository: ForgeReviewRepository | null, signal: AbortSignal, ): AsyncIterable /** * Stream the number of open change requests that ask the signed-in user for a review, summed over the hosts read: diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 4bbf9b0f63..637f3f3b3e 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -953,10 +953,6 @@ interface ChangeRequestSummary { * `organization/slug`, when the request asks a team the user belongs to rather than the user. */ readonly viewerRequest: { readonly team: string | null } | null - /** Issues the host closes once the change request merges, in host order, at most the provider's limit. */ - 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 } @@ -1624,7 +1620,7 @@ interface ForgeLocalChanges { ### 代码评审页 -[代码评审页](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)按 URL 读取变更请求,而不经过会话绑定。它的 `forgePanel` 方法(`reviewLists`、`reviewCount`、`reviewChangeRequest`、`reviewDescription`,以及与会话绑定版本对应的各个 `review*` 读取与操作)用 `ForgeService.changeRequestFromUrl` 解析 URL,没有提供方能处理时以 `forgePanel/unrecognized-url` 失败;它们不指向任何会话资源,因此只有可以使用 Host 代码托管凭据的调用方能访问。一个列表中心只在列表流或计数流存在时读取[登录用户的列表](#viewer-lists-and-descriptions):同一仓库范围的流共用一个读取器,它每隔 `reviewListIntervalMs` 读取每个主机的每个列表,各主机并行、同一主机的列表依次读取;某主机拒绝当前用户或触发限流时,本轮不再读取它的其余列表;连续失败的轮次按 `reviewMaxBackoffMs` 为上限退避。计数每隔 `reviewCountIntervalMs` 读取一次,全部仓库范围的列表读取也会更新它。`reviewLists` 流式返回 `ForgeReviewFrame`,含每个主机的列表、最近一次成功读取的条目以及最近一次读取的失败;`reviewCount` 流式返回 `ForgeReviewCountFrame`;`reviewChangeRequest` 为显示中的变更请求流式返回 `ForgeReviewChangeRequest`,该变更请求在其流存在期间经 `ForgeService.watch` 轮询。 +[代码评审页](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)按 URL 读取变更请求,而不经过会话绑定。它的 `forgePanel` 方法(`reviewLists`、`reviewCount`、`reviewChangeRequest`、`reviewDescription`,以及与会话绑定版本对应的各个 `review*` 读取与操作)用 `ForgeService.changeRequestFromUrl` 解析 URL,没有提供方能处理时以 `forgePanel/unrecognized-url` 失败;它们不指向任何会话资源,因此只有可以使用 Host 代码托管凭据的调用方能访问。一个列表中心只在列表流或计数流存在时读取[登录用户的列表](#viewer-lists-and-descriptions):同一仓库范围的流共用一个读取器,它每隔 `reviewListIntervalMs` 读取每个主机的每个列表,各主机并行、同一主机的列表依次读取;某主机拒绝当前用户或触发限流时,本轮不再读取它的其余列表;读取失败的主机每次间隔更久再读,以 `reviewMaxBackoffMs` 为上限,其他主机保持原来的间隔。计数每隔 `reviewCountIntervalMs` 以同样的方式读取,全部仓库范围的列表读取也会更新它。范围是全部主机的全部仓库,或一个 `ForgeReviewRepository`;后者带有主机,只在该主机上读取。`reviewLists` 流式返回 `ForgeReviewFrame`,含每个主机的列表、最近一次成功读取的条目、最近一次读取的失败,以及主机拒绝当前用户时其提供方的 `readiness` 给出的登录命令;`reviewCount` 流式返回 `ForgeReviewCountFrame`;`reviewChangeRequest` 为显示中的变更请求流式返回 `ForgeReviewChangeRequest`,该变更请求在其流存在期间经 `ForgeService.watch` 轮询。 对话标签在 `connectWorkspace` 解析出的空白会话中开始,并用 `reviewStage` 记录该变更请求;Host 只在内存中保存这个选择,等该会话的下一条消息进入收件箱时再绑定,因此未使用的空白会话保持未绑定。 @@ -2143,13 +2139,15 @@ Serves the forge panel. Following a Session inspects the checkout of its current /** * Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on: * the lists read so far first, then a frame after each read settles. Readers of one repository scope share one - * reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to - * `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops. - * @param repository - one repository to list in, or null for every repository the user can read. + * reader, which reads each host every `reviewListIntervalMs` while some stream lasts and reads a host whose read failed + * again later each time, up to `reviewMaxBackoffMs`, without delaying the other hosts; nothing is read while no stream + * lasts. The stream ends when `signal` aborts or the Remote stops. + * @param repository - one repository to list in, read on its host only, or null for every repository the user can + * read on every host. * @param signal - ends the stream. * @returns frames, each complete. */ -@Remote({ mode: 'stream' }) async *reviewLists( repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, ): AsyncIterable +@Remote({ mode: 'stream' }) async *reviewLists( repository: ForgeReviewRepository | null, signal: AbortSignal, ): AsyncIterable /** * Stream the number of open change requests that ask the signed-in user for a review, summed over the hosts read: diff --git a/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.i18n.yaml new file mode 100644 index 0000000000..3ab2206a07 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/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.5/forge-viewer-list-rows/guide.md +/: + en: 91fe2557764d542b + zh: df56ac645185f7ad +/forge-viewer-list-rows-no-longer-carry-closing-issues: + en: 6865171b0acfaf1d + zh: 74095f9b0aeaca36 +/forge-viewer-list-rows-no-longer-carry-closing-issues/change: + en: 5af1ffb988831fb8 + zh: e092f9f5b57ac4ec +/forge-viewer-list-rows-no-longer-carry-closing-issues/migration: + en: f7e099958709e74e + zh: faaf41046a4e9b42 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.md new file mode 100644 index 0000000000..42652cba6d --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSummary loses closingIssues and closingIssuesTruncated." +--- + +# Forge viewer list rows no longer carry closing issues + +English | [中文](guide.zh.md) + +## Change + +`ChangeRequestSummary`, the row a `ForgeProvider` returns from `listForViewer`, loses `closingIssues` and `closingIssuesTruncated`. The Code review page no longer names the issues a listed change request closes; the change request's own overview still lists them from `ChangeRequestSnapshot.closingIssues`, which is unchanged. The GitHub provider's list search no longer reads closing issues. + +This affects third-party `ForgeProvider` implementations that offer viewer lists and other code that builds or reads `ChangeRequestSummary` values. The type comes from `@deepseek-ai/dsh-experimental-forge`. + +## Migration + +1. In every `ChangeRequestSummary` a provider builds, remove `closingIssues` and `closingIssuesTruncated`, and drop the read that served only them. +2. In code that reads those fields from a list row, read `closingIssues` and `closingIssuesTruncated` of the change request's `ChangeRequestSnapshot` instead, which `ctx.forge.watch` delivers. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.zh.md new file mode 100644 index 0000000000..d852ad85b9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/forge-viewer-list-rows/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSummary 去掉 closingIssues 与 closingIssuesTruncated。" +--- + +# Forge 的 viewer 列表项不再带会关闭的 issue + +[English](guide.md) | 中文 + +## 变更 + +`ChangeRequestSummary`(`ForgeProvider` 的 `listForViewer` 返回的列表项)去掉了 `closingIssues` 与 `closingIssuesTruncated`。代码评审页不再显示列表里的变更请求会关闭哪些 issue;变更请求自己的概览仍从未改动的 `ChangeRequestSnapshot.closingIssues` 列出它们。GitHub 提供方的列表搜索不再读取会关闭的 issue。 + +受影响的是提供 viewer 列表的第三方 `ForgeProvider` 实现,以及其他构造或读取 `ChangeRequestSummary` 的代码。该类型来自 `@deepseek-ai/dsh-experimental-forge`。 + +## 迁移 + +1. 在提供方构造的每个 `ChangeRequestSummary` 中去掉 `closingIssues` 与 `closingIssuesTruncated`,并删除只为它们服务的读取。 +2. 原先从列表项读取这两个字段的代码,改为读取该变更请求的 `ChangeRequestSnapshot` 上的 `closingIssues` 与 `closingIssuesTruncated`,它由 `ctx.forge.watch` 送达。 diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 1e6287574e..a6f925b625 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 0bd2c1b78f34d768 - zh: 8f6f89b097156fca + en: 359352a208ca8a11 + zh: b581a4d0a7067e3d /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: en: e20276738f193646 zh: 79f2fa0e734f8f93 @@ -30,8 +30,8 @@ en: c1b5bfb0e5a1801e zh: 2bbe1a2845aa5d20 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: bd19347052d20055 - zh: b9fe5cb782d2d534 + en: bf093028c331e076 + zh: da05205c6b036b16 /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 89d1093c89..4e719e3406 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -34,7 +34,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Provider hosts** — the bundle's GitHub and GitLab rows on the Plugins page each open a page that lists the hosts the provider serves. Add, or Enter, stages the typed host name, or the host and port of a pasted URL, and refuses below the field a name that is malformed, already listed, or served by the other provider; a row's remove button stages its removal, except for the last host. Save writes the whole list to the profile patch, and the provider serves it without a restart. Each saved host shows Signed in, Not signed in with the provider's sign-in command and Copy, or Can't check with the reason; the page reads these when it shows, after a save, when the window regains focus, and from the button beside the list's title. A deployment that stores settings read-only shows the list without the edits. - **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph. -- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a list is read, skeleton rows laid out as the chosen view stand in for its items. A list item names the repository when the lists span more than one, the author, the update time, the issues it closes, and at most one hint, such as You requested changes · Requested again or a team request; the search box filters the lists by title, number, repository, and author under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and links whose host no provider serves show where they apply; such a link shows Unknown code host with Add host…, which opens the bundle's page on the Plugins page while that page is available. +- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a host's first read of a list runs, skeleton rows laid out as the chosen view stand in for its items, below the items of the hosts that answered, and the list's count and its empty text wait for that host. A list item shows its title on at most two lines and its small text on at most two: the repository when the lists span more than one, the number, and the author, with the short update time at the end of that line, then at most one hint, such as Re-review requested or a team request, which shares that line where both fit and takes the second where they do not; the search box filters the lists by title, number, repository, author, and host under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. Once the lists name repositories on more than one host, the submenu lists each host with its repositories below it: choosing a host shows only its change requests, and choosing a repository reads the lists in it on its host only. A host whose lists could not be read shows one notice after the lists, with the sign-in command its provider names and Copy, or else the reason, and Open settings, which opens the bundle's page on the Plugins page while that page is available; when no host listed anything, the notices are all the column shows. A host whose read failed is read again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and links whose host no provider serves show where they apply; such a link shows Unknown code host with Add host…, which opens the bundle's page on the Plugins page while that page is available. - **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden. - **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row. - **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away. @@ -177,7 +177,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Extensions** — a lens runs only once it is chosen, and its result applies to the files the view showed when it asked; reading the old side of a whole change request needs a provider that names merge bases. Line annotations stay out of the thread list, the unresolved counts, and thread navigation. - **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. - **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. -- **Review page** — only the GitHub provider lists change requests and reads descriptions, so the lists hold GitHub hosts, each provider's configured hosts together; a GitLab merge request opened from a pasted link shows its status, changes, and chat, with a read failure in place of its description. Choosing among hosts and accounts waits for a second provider that lists change requests. The changes tab shows no plugin lenses, annotations, toolbar, file-menu, or comment-form entries, whose extension points name a Session, and its quotes go to the chat's draft instead of the Session's input. The chat starts in the Workspace's shared blank Session, which New Session also shows, and does not check that the Workspace is a checkout of the repository; the change request to bind waits in Host memory until the first message, so a Host restart forgets it. Pending review comments last while the page shows their change request. +- **Review page** — the lists hold every configured host of every provider that lists change requests, the GitHub and GitLab providers today, and what a list holds on a host is its provider's to define: the GitLab provider's lists and their differences from GitHub's are in [its limitations](../forge-gitlab/README.md#known-limitations-and-deferred-work). A list row names no host; the repository submenu and the search box tell hosts apart. The left navigation's count does not follow the host or repository the lists are narrowed to. Choosing among accounts of one host is not offered. The changes tab shows no plugin lenses, annotations, toolbar, file-menu, or comment-form entries, whose extension points name a Session, and its quotes go to the chat's draft instead of the Session's input. The chat starts in the Workspace's shared blank Session, which New Session also shows, and does not check that the Workspace is a checkout of the repository; the change request to bind waits in Host memory until the first message, so a Host restart forgets it. Pending review comments last while the page shows their change request. ### Dev Note diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index a4d60f31aa..0a59d5d4bc 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -34,7 +34,7 @@ kind: "package-reference" - **提供方主机**——插件页上该套件的 GitHub 行与 GitLab 行各打开一个页面,列出该提供方服务的主机。“添加”或 Enter 把输入的主机名(粘贴 URL 时取其中的主机与端口)加入待保存的列表;格式不对、已在列表中或已由另一个提供方服务的主机名不会加入,原因显示在输入框下方。行尾的移除按钮把该主机从待保存的列表中去掉,最后一个主机不能移除。“保存”把整个列表写入 profile patch,提供方无需重启即服务新列表。每个已保存的主机显示“已登录”、“未登录”(附提供方给出的登录命令与“复制”)或“无法检查”(附原因);页面在显示时、保存后、窗口重新获得焦点时以及点击列表标题旁的按钮时读取这些状态。以只读方式保存设置的部署只显示列表,不能修改。 - **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。 -- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。列表读取期间,按所选视图排布的骨架行占据列表项的位置。列表项在列表跨多个仓库时写出仓库名,并显示作者、更新时间、会关闭的 issue 和至多一条提示,如“你请求过修改 · 已再次请求”或团队请求;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库和作者筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接的主机没有提供方服务时在对应位置提示;后一种情况显示“未知的代码托管平台”与“添加主机…”,在插件页可用时打开该套件的页面。 +- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。某个主机首次读取列表期间,按所选视图排布的骨架行占据它的列表项的位置,排在已返回的主机的列表项之后,列表的计数与空列表文字等它返回后再显示。列表项的标题至多两行,小字至多两行:列表跨多个仓库时写出仓库名,然后是编号和作者,简短的更新时间在这一行末尾,之后是至多一条提示,如“待你复审”或团队请求,放得下时与它们同一行,放不下时换到第二行;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库、作者和主机筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。列表里的仓库来自多个主机时,子菜单列出每个主机,主机的仓库列在它下面:选主机只显示该主机的变更请求,选仓库只在它所在的主机上读取列表。读取失败的主机在列表之后各显示一条提示:提供方给出登录命令时显示该命令与“复制”,否则显示原因;另有“前往配置”,在插件页可用时打开该套件的页面;没有主机列出任何内容时,这一栏只显示这些提示。读取失败的主机每次间隔更久再读,上限为 `reviewMaxBackoffMs`,其他主机保持原来的间隔。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接的主机没有提供方服务时在对应位置提示;后一种情况显示“未知的代码托管平台”与“添加主机…”,在插件页可用时打开该套件的页面。 - **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。 - **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。 - **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。 @@ -177,7 +177,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **扩展**——透镜只在被选中后运行,结果作用于发出请求时视图所显示的文件;读取整个变更请求的旧侧需要能给出合并基准的提供方。行注解不进入讨论列表、未解决数和讨论导航。 - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 -- **代码评审页**——只有 GitHub 提供方能列出变更请求并读取描述,因此列表中只有 GitHub 主机,每个提供方配置的主机合并列出;通过粘贴链接打开的 GitLab 合并请求显示状态、变更与对话,描述处显示读取失败。在主机与账号之间选择要等到第二个能列出变更请求的提供方。“变更”标签不显示插件的透镜、行注释、工具栏、文件菜单和评论表单入口(这些扩展点以会话为对象),引用放进对话草稿而不是会话输入框。对话在工作区共享的空白会话中开始,“新会话”也显示这个会话,且不检查该工作区是否是此仓库的检出;待绑定的变更请求在首条消息前只保存在 Host 内存中,Host 重启会丢失。未提交的评审评论只在页面显示该变更请求期间保留。 +- **代码评审页**——列表合并列出每个能列出变更请求的提供方(目前是 GitHub 与 GitLab 提供方)的全部已配置主机,某个列表在一个主机上包含什么由该主机的提供方决定:GitLab 提供方的列表及其与 GitHub 的差别见[它的限制](../forge-gitlab/README.zh.md#known-limitations-and-deferred-work)。列表行不写主机,主机通过仓库子菜单和搜索框区分。左侧导航上的计数不随列表所限定的主机或仓库变化。同一主机的多个账号之间不提供选择。“变更”标签不显示插件的透镜、行注释、工具栏、文件菜单和评论表单入口(这些扩展点以会话为对象),引用放进对话草稿而不是会话输入框。对话在工作区共享的空白会话中开始,“新会话”也显示这个会话,且不检查该工作区是否是此仓库的检出;待绑定的变更请求在首条消息前只保存在 Host 内存中,Host 重启会丢失。未提交的评审评论只在页面显示该变更请求期间保留。 ### 开发备注 diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index b5eb2fa8ef..883f0b9404 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -526,18 +526,16 @@ export const zh = { 'reviewPage.empty.search': '没有匹配的变更请求', 'reviewPage.truncated': '还有 {count} 个未列出', 'reviewPage.noHosts': '没有能列出变更请求的代码托管平台', - 'reviewPage.noHostsHint': '启用 GitHub 组件后,这里会列出请你评审、你创建和与你有关的变更请求。', + 'reviewPage.noHostsHint': '启用 GitHub 或 GitLab 组件后,这里会列出请你评审、你创建和与你有关的变更请求。', 'reviewPage.signIn': '登录 {host} 后才能列出你的变更请求', 'reviewPage.listFailed': '读取 {host} 的列表失败:{message}', 'reviewPage.streamFailed': '列表连接已中断', 'reviewPage.openUrl': '打开 {url}', - 'reviewPage.hint.rerequested': '你请求过修改 · 已再次请求', + 'reviewPage.hint.rerequested': '待你复审', 'reviewPage.hint.team': '团队 {team}', 'reviewPage.hint.approvedByYou': '你已批准', 'reviewPage.hint.changesRequested': '要求修改', 'reviewPage.hint.approved': '已批准', - 'reviewPage.issuesMore': '等 {count} 个', - 'reviewPage.issuesMoreTruncated': '等 {count}+ 个', 'reviewPage.countAria': '{count} 个变更请求等你评审', 'reviewPage.select': '选择一个变更请求', 'reviewPage.selectHint': '从左侧列表选择,或在搜索框粘贴变更请求链接。', @@ -565,6 +563,7 @@ export const zh = { 'reviewPage.unrecognized': '未知的代码托管平台', 'reviewPage.unrecognizedHint': '此链接的主机尚未添加到代码托管组件', 'reviewPage.addHost': '添加主机…', + 'reviewPage.hostSettings': '前往配置', 'reviewPage.loadFailed': '变更请求读取失败', 'reviewPage.markdown.copy': '复制', 'reviewPage.markdown.copied': '已复制', @@ -1129,18 +1128,16 @@ export const en: Record = { 'reviewPage.empty.search': 'No matching change requests', 'reviewPage.truncated': '{count} more not listed', 'reviewPage.noHosts': 'No code host lists change requests', - 'reviewPage.noHostsHint': 'Enable the GitHub component to list the change requests that ask for your review, that you created, and that involve you.', + 'reviewPage.noHostsHint': 'Enable the GitHub or GitLab component to list the change requests that ask for your review, that you created, and that involve you.', 'reviewPage.signIn': 'Sign in to {host} to list your change requests', 'reviewPage.listFailed': 'Couldn\'t read the list on {host}: {message}', 'reviewPage.streamFailed': 'The list connection ended', 'reviewPage.openUrl': 'Open {url}', - 'reviewPage.hint.rerequested': 'You requested changes · Requested again', + 'reviewPage.hint.rerequested': 'Re-review requested', 'reviewPage.hint.team': 'Team {team}', 'reviewPage.hint.approvedByYou': 'You approved', 'reviewPage.hint.changesRequested': 'Changes requested', 'reviewPage.hint.approved': 'Approved', - 'reviewPage.issuesMore': 'and {count} more', - 'reviewPage.issuesMoreTruncated': 'and {count}+ more', 'reviewPage.countAria': '{count} change requests await your review', 'reviewPage.select': 'Select a change request', 'reviewPage.selectHint': 'Choose one from the list, or paste a change request link into the search box.', @@ -1168,6 +1165,7 @@ export const en: Record = { 'reviewPage.unrecognized': 'Unknown code host', 'reviewPage.unrecognizedHint': 'This link\'s host has not been added to a code host component.', 'reviewPage.addHost': 'Add host…', + 'reviewPage.hostSettings': 'Open settings', 'reviewPage.loadFailed': 'Couldn\'t read the change request', 'reviewPage.markdown.copy': 'Copy', 'reviewPage.markdown.copied': 'Copied', @@ -1736,18 +1734,16 @@ export const ja: Record = { 'reviewPage.empty.search': '一致する変更リクエストはありません', 'reviewPage.truncated': 'ほか {count} 件は未表示', 'reviewPage.noHosts': '変更リクエストを一覧できるコードホストがありません', - 'reviewPage.noHostsHint': 'GitHub コンポーネントを有効にすると、レビュー依頼、自分が作成したもの、自分に関係するものがここに一覧されます。', + 'reviewPage.noHostsHint': 'GitHub または GitLab コンポーネントを有効にすると、レビュー依頼、自分が作成したもの、自分に関係するものがここに一覧されます。', 'reviewPage.signIn': '{host} にサインインすると変更リクエストを一覧できます', 'reviewPage.listFailed': '{host} のリストを読み込めませんでした:{message}', 'reviewPage.streamFailed': 'リストの接続が切れました', 'reviewPage.openUrl': '{url} を開く', - 'reviewPage.hint.rerequested': '変更を要求済み · 再依頼あり', + 'reviewPage.hint.rerequested': '再レビュー依頼', 'reviewPage.hint.team': 'チーム {team}', 'reviewPage.hint.approvedByYou': '承認済み(自分)', 'reviewPage.hint.changesRequested': '変更が要求されています', 'reviewPage.hint.approved': '承認済み', - 'reviewPage.issuesMore': 'ほか {count} 件', - 'reviewPage.issuesMoreTruncated': 'ほか {count}+ 件', 'reviewPage.countAria': 'レビュー待ちの変更リクエスト {count} 件', 'reviewPage.select': '変更リクエストを選択', 'reviewPage.selectHint': 'リストから選ぶか、検索欄に変更リクエストのリンクを貼り付けてください。', @@ -1775,6 +1771,7 @@ export const ja: Record = { 'reviewPage.unrecognized': '不明なコードホスト', 'reviewPage.unrecognizedHint': 'このリンクのホストはコードホストコンポーネントに追加されていません。', 'reviewPage.addHost': 'ホストを追加…', + 'reviewPage.hostSettings': '設定を開く', 'reviewPage.loadFailed': '変更リクエストを読み込めませんでした', 'reviewPage.markdown.copy': 'コピー', 'reviewPage.markdown.copied': 'コピーしました', @@ -2336,18 +2333,16 @@ export const es: Record = { 'reviewPage.empty.search': 'Ninguna solicitud de cambio coincide', 'reviewPage.truncated': '{count} más sin listar', 'reviewPage.noHosts': 'Ningún servicio de código lista solicitudes de cambio', - 'reviewPage.noHostsHint': 'Activa el componente de GitHub para listar las solicitudes de cambio que piden tu revisión, las que creaste y las que te involucran.', + 'reviewPage.noHostsHint': 'Activa el componente de GitHub o de GitLab para listar las solicitudes de cambio que piden tu revisión, las que creaste y las que te involucran.', 'reviewPage.signIn': 'Inicia sesión en {host} para listar tus solicitudes de cambio', 'reviewPage.listFailed': 'No se pudo leer la lista de {host}: {message}', 'reviewPage.streamFailed': 'La conexión de la lista terminó', 'reviewPage.openUrl': 'Abrir {url}', - 'reviewPage.hint.rerequested': 'Pediste cambios · Se volvió a solicitar', + 'reviewPage.hint.rerequested': 'Nueva revisión solicitada', 'reviewPage.hint.team': 'Equipo {team}', 'reviewPage.hint.approvedByYou': 'Aprobaste', 'reviewPage.hint.changesRequested': 'Cambios solicitados', 'reviewPage.hint.approved': 'Aprobada', - 'reviewPage.issuesMore': 'y {count} más', - 'reviewPage.issuesMoreTruncated': 'y {count}+ más', 'reviewPage.countAria': '{count} solicitudes de cambio esperan tu revisión', 'reviewPage.select': 'Selecciona una solicitud de cambio', 'reviewPage.selectHint': 'Elige una de la lista o pega un enlace de solicitud de cambio en la búsqueda.', @@ -2375,6 +2370,7 @@ export const es: Record = { 'reviewPage.unrecognized': 'Servicio de código desconocido', 'reviewPage.unrecognizedHint': 'El host de este enlace no se ha añadido a ningún componente de servicio de código.', 'reviewPage.addHost': 'Añadir host…', + 'reviewPage.hostSettings': 'Abrir ajustes', 'reviewPage.loadFailed': 'No se pudo leer la solicitud de cambio', 'reviewPage.markdown.copy': 'Copiar', 'reviewPage.markdown.copied': 'Copiado', @@ -2936,18 +2932,16 @@ export const fr: Record = { 'reviewPage.empty.search': 'Aucune demande de modification correspondante', 'reviewPage.truncated': '{count} autres non listées', 'reviewPage.noHosts': 'Aucun hébergeur de code ne liste de demandes de modification', - 'reviewPage.noHostsHint': 'Activez le composant GitHub pour lister les demandes de modification qui attendent votre revue, que vous avez créées et qui vous concernent.', + 'reviewPage.noHostsHint': 'Activez le composant GitHub ou GitLab pour lister les demandes de modification qui attendent votre revue, que vous avez créées et qui vous concernent.', 'reviewPage.signIn': 'Connectez-vous à {host} pour lister vos demandes de modification', 'reviewPage.listFailed': 'Impossible de lire la liste de {host} : {message}', 'reviewPage.streamFailed': 'La connexion de la liste a pris fin', 'reviewPage.openUrl': 'Ouvrir {url}', - 'reviewPage.hint.rerequested': 'Vous avez demandé des modifications · Revue redemandée', + 'reviewPage.hint.rerequested': 'Nouvelle revue demandée', 'reviewPage.hint.team': 'Équipe {team}', 'reviewPage.hint.approvedByYou': 'Vous avez approuvé', 'reviewPage.hint.changesRequested': 'Modifications demandées', 'reviewPage.hint.approved': 'Approuvée', - 'reviewPage.issuesMore': 'et {count} autres', - 'reviewPage.issuesMoreTruncated': 'et {count}+ autres', 'reviewPage.countAria': '{count} demandes de modification attendent votre revue', 'reviewPage.select': 'Sélectionnez une demande de modification', 'reviewPage.selectHint': 'Choisissez-en une dans la liste ou collez un lien de demande de modification dans la recherche.', @@ -2975,6 +2969,7 @@ export const fr: Record = { 'reviewPage.unrecognized': 'Hébergement de code inconnu', 'reviewPage.unrecognizedHint': 'L’hôte de ce lien n’a été ajouté à aucun composant d’hébergement de code.', 'reviewPage.addHost': 'Ajouter un hôte…', + 'reviewPage.hostSettings': 'Ouvrir les réglages', 'reviewPage.loadFailed': 'Impossible de lire la demande de modification', 'reviewPage.markdown.copy': 'Copier', 'reviewPage.markdown.copied': 'Copié', @@ -3536,18 +3531,16 @@ export const de: Record = { 'reviewPage.empty.search': 'Keine passenden Änderungsanfragen', 'reviewPage.truncated': '{count} weitere nicht aufgeführt', 'reviewPage.noHosts': 'Kein Code-Host listet Änderungsanfragen', - 'reviewPage.noHostsHint': 'Aktivieren Sie die GitHub-Komponente, um Änderungsanfragen aufzulisten, die Ihr Review anfragen, die Sie erstellt haben und an denen Sie beteiligt sind.', + 'reviewPage.noHostsHint': 'Aktivieren Sie die GitHub- oder GitLab-Komponente, um Änderungsanfragen aufzulisten, die Ihr Review anfragen, die Sie erstellt haben und an denen Sie beteiligt sind.', 'reviewPage.signIn': 'Melden Sie sich bei {host} an, um Ihre Änderungsanfragen aufzulisten', 'reviewPage.listFailed': 'Liste von {host} konnte nicht gelesen werden: {message}', 'reviewPage.streamFailed': 'Die Verbindung der Liste wurde beendet', 'reviewPage.openUrl': '{url} öffnen', - 'reviewPage.hint.rerequested': 'Sie haben Änderungen angefordert · Erneut angefragt', + 'reviewPage.hint.rerequested': 'Erneutes Review angefragt', 'reviewPage.hint.team': 'Team {team}', 'reviewPage.hint.approvedByYou': 'Von Ihnen genehmigt', 'reviewPage.hint.changesRequested': 'Änderungen angefordert', 'reviewPage.hint.approved': 'Genehmigt', - 'reviewPage.issuesMore': 'und {count} weitere', - 'reviewPage.issuesMoreTruncated': 'und {count}+ weitere', 'reviewPage.countAria': '{count} Änderungsanfragen warten auf Ihr Review', 'reviewPage.select': 'Änderungsanfrage auswählen', 'reviewPage.selectHint': 'Wählen Sie eine aus der Liste oder fügen Sie einen Link in die Suche ein.', @@ -3575,6 +3568,7 @@ export const de: Record = { 'reviewPage.unrecognized': 'Unbekannter Code-Host', 'reviewPage.unrecognizedHint': 'Der Host dieses Links wurde keiner Code-Host-Komponente hinzugefügt.', 'reviewPage.addHost': 'Host hinzufügen…', + 'reviewPage.hostSettings': 'Einstellungen öffnen', 'reviewPage.loadFailed': 'Änderungsanfrage konnte nicht gelesen werden', 'reviewPage.markdown.copy': 'Kopieren', 'reviewPage.markdown.copied': 'Kopiert', @@ -4136,18 +4130,16 @@ export const ru: Record = { 'reviewPage.empty.search': 'Нет подходящих запросов на изменение', 'reviewPage.truncated': 'Ещё {count} не показаны', 'reviewPage.noHosts': 'Ни один хостинг кода не выводит запросы на изменение', - 'reviewPage.noHostsHint': 'Включите компонент GitHub, чтобы видеть запросы на изменение, ожидающие вашего ревью, созданные вами и с вашим участием.', + 'reviewPage.noHostsHint': 'Включите компонент GitHub или GitLab, чтобы видеть запросы на изменение, ожидающие вашего ревью, созданные вами и с вашим участием.', 'reviewPage.signIn': 'Войдите в {host}, чтобы увидеть свои запросы на изменение', 'reviewPage.listFailed': 'Не удалось прочитать список {host}: {message}', 'reviewPage.streamFailed': 'Соединение списка прервано', 'reviewPage.openUrl': 'Открыть {url}', - 'reviewPage.hint.rerequested': 'Вы запросили изменения · Ревью запрошено снова', + 'reviewPage.hint.rerequested': 'Запрошено повторное ревью', 'reviewPage.hint.team': 'Команда {team}', 'reviewPage.hint.approvedByYou': 'Вы одобрили', 'reviewPage.hint.changesRequested': 'Запрошены изменения', 'reviewPage.hint.approved': 'Одобрено', - 'reviewPage.issuesMore': 'и ещё {count}', - 'reviewPage.issuesMoreTruncated': 'и ещё {count}+', 'reviewPage.countAria': 'Запросов на изменение, ожидающих вашего ревью: {count}', 'reviewPage.select': 'Выберите запрос на изменение', 'reviewPage.selectHint': 'Выберите его в списке или вставьте ссылку на запрос в поле поиска.', @@ -4175,6 +4167,7 @@ export const ru: Record = { 'reviewPage.unrecognized': 'Неизвестный хостинг кода', 'reviewPage.unrecognizedHint': 'Хост этой ссылки не добавлен ни в один компонент хостинга кода.', 'reviewPage.addHost': 'Добавить хост…', + 'reviewPage.hostSettings': 'Открыть настройки', 'reviewPage.loadFailed': 'Не удалось прочитать запрос на изменение', 'reviewPage.markdown.copy': 'Копировать', 'reviewPage.markdown.copied': 'Скопировано', @@ -4736,18 +4729,16 @@ export const pt: Record = { 'reviewPage.empty.search': 'Nenhuma solicitação de alteração corresponde', 'reviewPage.truncated': 'Mais {count} não listadas', 'reviewPage.noHosts': 'Nenhum serviço de código lista solicitações de alteração', - 'reviewPage.noHostsHint': 'Ative o componente do GitHub para listar as solicitações de alteração que pedem sua revisão, que você criou e que envolvem você.', + 'reviewPage.noHostsHint': 'Ative o componente do GitHub ou do GitLab para listar as solicitações de alteração que pedem sua revisão, que você criou e que envolvem você.', 'reviewPage.signIn': 'Entre em {host} para listar suas solicitações de alteração', 'reviewPage.listFailed': 'Não foi possível ler a lista de {host}: {message}', 'reviewPage.streamFailed': 'A conexão da lista terminou', 'reviewPage.openUrl': 'Abrir {url}', - 'reviewPage.hint.rerequested': 'Você pediu alterações · Solicitado novamente', + 'reviewPage.hint.rerequested': 'Nova revisão solicitada', 'reviewPage.hint.team': 'Equipe {team}', 'reviewPage.hint.approvedByYou': 'Você aprovou', 'reviewPage.hint.changesRequested': 'Alterações solicitadas', 'reviewPage.hint.approved': 'Aprovada', - 'reviewPage.issuesMore': 'e mais {count}', - 'reviewPage.issuesMoreTruncated': 'e mais {count}+', 'reviewPage.countAria': '{count} solicitações de alteração aguardam sua revisão', 'reviewPage.select': 'Selecione uma solicitação de alteração', 'reviewPage.selectHint': 'Escolha uma na lista ou cole um link de solicitação de alteração na pesquisa.', @@ -4775,6 +4766,7 @@ export const pt: Record = { 'reviewPage.unrecognized': 'Serviço de código desconhecido', 'reviewPage.unrecognizedHint': 'O host deste link não foi adicionado a nenhum componente de serviço de código.', 'reviewPage.addHost': 'Adicionar host…', + 'reviewPage.hostSettings': 'Abrir configurações', 'reviewPage.loadFailed': 'Não foi possível ler a solicitação de alteração', 'reviewPage.markdown.copy': 'Copiar', 'reviewPage.markdown.copied': 'Copiado', diff --git a/packages/experimental/client-ui-forge/src/client/review-page/ReviewList.tsx b/packages/experimental/client-ui-forge/src/client/review-page/ReviewList.tsx index 57505cb974..edc792a032 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/ReviewList.tsx +++ b/packages/experimental/client-ui-forge/src/client/review-page/ReviewList.tsx @@ -1,6 +1,6 @@ /** - * The review page's list column: the search box that also opens a pasted change request link, the repository filter, - * and one foldable section per list with its items, empty state, and failure. + * The review page's list column: the search box that also opens a pasted change request link, the filter of hosts and + * repositories, one foldable section per list with its items and empty state, and one notice per host that could not be read. */ import { useMemo, useRef, useState, type ReactNode } from 'react' @@ -19,8 +19,8 @@ import { ChangeRequestGlyph } from '../glyphs.tsx' import type { ForgePanelKey, NS } from '../locales.ts' import { RefreshGlyph } from '../RefreshGlyph.tsx' import { - mergeRepositories, pastedUrl, reviewHint, reviewRepositories, reviewSearchKeys, reviewSections, summaryTone, - type ReviewItem, type ReviewRepository, type ReviewSection, + mergeRepositories, pastedUrl, reviewFailures, reviewHint, reviewRepositories, reviewSearchKeys, reviewSections, sameScope, + scopeRepository, summaryTone, type ReviewHostFailure, type ReviewItem, type ReviewRepository, type ReviewScope, type ReviewSection, } from './review-lists.ts' import type { ReviewView } from './review-store.ts' import loading from '../ChangesLoading.module.css' @@ -44,8 +44,8 @@ export interface ReviewListProps { readonly selected: string | null /** Search text. */ readonly query: string - /** Repository the lists are read in, or null for every repository. */ - readonly repository: ReviewRepository | null + /** The host or repository the lists are narrowed to, or null for every repository of every host. */ + readonly scope: ReviewScope | null /** Whether the review-requested list leaves out requests made only of the user's teams. */ readonly directOnly: boolean /** Folded sections. */ @@ -60,8 +60,8 @@ export interface ReviewListProps { readonly onSearch: (query: string) => void /** Repositories the lists named while read in every repository, offered whatever repository the lists are read in now. */ readonly repositories: readonly ReviewRepository[] - /** Read the lists in one repository, or in every repository. */ - readonly onScope: (repository: ReviewRepository | null) => void + /** Narrow the lists to one host or one repository, or to nothing. */ + readonly onScope: (scope: ReviewScope | null) => void /** Toggle whether the review-requested list leaves out team requests. */ readonly onToggleDirect: () => void /** How list items show: two lines each, or one line each with the rest on hover. */ @@ -76,6 +76,8 @@ export interface ReviewListProps { readonly onRetry: () => void /** Copy text and report the outcome. */ readonly copyText: (text: string) => void + /** Open the page where the providers' hosts and sign-in states are, or undefined while it cannot be opened. */ + readonly onOpenSettings: (() => void) | undefined /** Forge panel copy. */ readonly t: Translate } @@ -84,27 +86,38 @@ export interface ReviewListProps { * A submenu row's label with the tick a chosen row shows, since a submenu does not mark its own choice. * @param text - the row's text. * @param chosen - whether the row is the current choice. + * @param nested - whether the row is a repository below the row of its host. * @returns the label. */ -function chosenLabel(text: string, chosen: boolean): ReactNode { +function chosenLabel(text: string, chosen: boolean, nested = false): ReactNode { return ( - {text} + {text} {chosen && } ) } -/** The view menu, laid out like the Session list's: the list view, the repository the lists are read in, and whether team requests show. */ -function FilterMenu({ frame, repository, repositories, directOnly, view, onScope, onToggleDirect, onView, t }: Pick): ReactNode { +/** + * The view menu, laid out like the Session list's: the list view, the host or repository the lists are narrowed to, and + * whether team requests show. Once the lists name repositories on more than one host, each host is a choice with its + * repositories below it. + */ +function FilterMenu({ frame, scope, repositories, directOnly, view, onScope, onToggleDirect, onView, t }: Pick): ReactNode { const [open, setOpen] = useState(false) - const chosen = repository === null ? null : `${repository.owner}/${repository.name}` + const repository = scopeRepository(scope) // Lists read in one repository name only that one, so the menu offers the repositories remembered from the lists of // every repository, with those the shown lists name and the chosen one, which stays offered while its lists are empty. const offered = mergeRepositories(repositories, reviewRepositories(frame), repository === null ? [] : [repository]) + const hosts = [...new Set(offered.map(item => item.host))] // Before any list of every repository was read, the offer is still growing. const reading = repositories.length === 0 && (frame === undefined || frame.reading) + // A row's id is its place among the choices, which the selection reads back. + const choices: ReviewScope[] = [] + const choice = (value: ReviewScope, text: string, nested: boolean): MenuEntry => + ({ id: `scope:${choices.push(value) - 1}`, label: chosenLabel(text, sameScope(value, scope), nested) }) + const all = t('reviewPage.filter.allRepositories') const items: MenuEntry[] = [ { type: 'label', id: 'view', text: t('reviewPage.filter.view') }, { id: 'view:detailed', label: t('reviewPage.filter.detailed'), icon: }, @@ -117,13 +130,16 @@ function FilterMenu({ frame, repository, repositories, directOnly, view, onScope label: ( {t('reviewPage.filter.repository')} - {chosen ?? t('reviewPage.filter.allRepositories')} + {scope === null ? all : repository === null ? scope.host : `${repository.owner}/${repository.name}`} ), submenu: [ - { id: 'repo:', label: chosenLabel(t('reviewPage.filter.allRepositories'), chosen === null) }, + { id: 'scope:', label: chosenLabel(all, scope === null) }, { type: 'separator', id: 'repo-separator' }, - ...offered.map(item => `${item.owner}/${item.name}`).map(name => ({ id: `repo:${name}`, label: chosenLabel(name, name === chosen) })), + ...hosts.flatMap(host => [ + ...hosts.length > 1 ? [choice({ host }, host, false)] : [], + ...offered.filter(item => item.host === host).map(item => choice(item, `${item.owner}/${item.name}`, hosts.length > 1)), + ]), ...reading ? [{ type: 'label' as const, id: 'repo-reading', text: t('reviewPage.loading') }] : [], ], }, @@ -132,7 +148,7 @@ function FilterMenu({ frame, repository, repositories, directOnly, view, onScope { id: 'requests:all', label: t('reviewPage.filter.teamRequests'), icon: }, { id: 'requests:direct', label: t('reviewPage.filter.directOnly'), icon: }, ] - const active = repository !== null || directOnly + const active = scope !== null || directOnly return ( )} items={items} - selectedIds={[`view:${view}`, `repo:${chosen ?? ''}`, directOnly ? 'requests:direct' : 'requests:all']} + selectedIds={[`view:${view}`, directOnly ? 'requests:direct' : 'requests:all']} onSelect={(id) => { setOpen(false) if (id === 'view:detailed' || id === 'view:compact') onView(id === 'view:compact' ? 'compact' : 'detailed') else if (id === 'requests:all' || id === 'requests:direct') { if ((id === 'requests:direct') !== directOnly) onToggleDirect() } else { - // Menu never selects a submenu parent, so every remaining row is a `repo:` row. - const [owner = '', name = ''] = id.slice('repo:'.length).split('/') - onScope(id === 'repo:' ? null : { owner, name }) + // Menu never selects a submenu parent, so every remaining row is a `scope:` row. + onScope(choices[Number(id.slice('scope:'.length) || NaN)] ?? null) } }} /> ) } -/** The closing issues of an item: the first issue's number, and how many more. */ -function Issues({ item, t }: { readonly item: ReviewItem; readonly t: Translate }): ReactNode { - const [first] = item.summary.closingIssues - if (first === undefined) return null - const more = item.summary.closingIssues.length - 1 + (item.summary.closingIssuesTruncated ? 1 : 0) - return ( - <> - - - - {t('change.number', { number: first.number })} - {more > 0 && {t(item.summary.closingIssuesTruncated ? 'reviewPage.issuesMoreTruncated' : 'reviewPage.issuesMore', { count: more })}} - - - ) -} - /** Props of one list item, in either view. */ interface ItemProps { readonly item: ReviewItem @@ -191,39 +189,18 @@ interface ItemProps { readonly selected: boolean /** Whether the item names its repository, because the lists span more than one. */ readonly qualified: boolean + /** Whether the item's hover card names its host, because the lists span more than one. */ + readonly hosted: boolean readonly now: number readonly onSelect: (url: string) => void readonly t: Translate } -/** The meta line of an item: its name, author, update time, the issues it closes, and what follows them. */ -function ItemMeta({ item, name, ago, children, t }: { - readonly item: ReviewItem - readonly name: string - readonly ago: string | undefined - readonly children?: ReactNode - readonly t: Translate -}): ReactNode { - const { author } = item.summary - return ( - - {name} - {author !== null && <>{author.login}} - {ago !== undefined && <>{ago}} - - {children} - - ) -} - -/** What the hover card of a compact item shows: the full title and every fact the detailed item names. */ -function CompactDetails({ item, filter, qualified, now, t }: { - readonly item: ReviewItem - readonly filter: ForgeViewerFilter - readonly qualified: boolean - readonly now: number - readonly t: Translate -}): ReactNode { +/** + * What the hover card of a compact item shows: the full title, the host where the lists span several, and every fact the + * detailed item names. + */ +function CompactDetails({ item, filter, qualified, hosted, now, t }: Pick): ReactNode { const { summary } = item const { repository, number } = summary.ref const hint = reviewHint(summary, filter) @@ -231,15 +208,19 @@ function CompactDetails({ item, filter, qualified, now, t }: { return ( {summary.title} - + + {hosted && <>{item.host}} + {qualified ? `${repository.owner}/${repository.name}#${number}` : t('change.number', { number })} + {summary.author !== null && <>{summary.author.login}} + {ago !== undefined && <>{ago}} + {hint !== undefined && {t(hint.key, hint.params)}} ) } /** One listed change request on one line: its glyph, its title, which marquees while hovered, and its update time. */ -function CompactItem({ item, filter, selected, qualified, now, onSelect, t }: ItemProps): ReactNode { +function CompactItem({ item, filter, selected, qualified, hosted, now, onSelect, t }: ItemProps): ReactNode { const { summary } = item const title = useRef(null) const marquee = useHoverMarquee(title) @@ -253,7 +234,7 @@ function CompactItem({ item, filter, selected, qualified, now, onSelect, t }: It copyText={summary.title} copyLabel={t('reviewPage.copyTitle')} copiedLabel={t('toast.copied')} - content={} + content={} anchor={( ) } -/** A section's failure: the sign-in command for an unauthenticated GitHub host, otherwise the reason. */ -function SectionFailure({ section, copyText, t }: { - readonly section: ReviewSection +/** + * One notice per host whose lists could not be read: what failed, the sign-in command for a host that needs sign-in + * when its provider names one, and the way to the providers' settings while that page can be opened. + */ +function HostFailures({ failures, copyText, onOpenSettings, t }: { + readonly failures: readonly ReviewHostFailure[] readonly copyText: (text: string) => void + readonly onOpenSettings: (() => void) | undefined readonly t: Translate }): ReactNode { - if (section.failure === null) return null - const { host, forge, failure } = section.failure - if (failure.code === 'unauthenticated') { - const command = forge === 'github' ? `gh auth login --hostname ${host}` : undefined - return ( -
    - {t('reviewPage.signIn', { host })} - {command !== undefined && ( - - {command} - - - )} -
    - ) - } - if (failure.code === 'rate-limited') return
    {t('change.failure.rateLimited')}
    - return
    {t('reviewPage.listFailed', { host, message: failure.message })}
    + if (failures.length === 0) return null + return ( +
    + {failures.map(({ forge, host, failure, signIn }) => { + const command = failure.code === 'unauthenticated' ? signIn : null + return ( +
    + + {failure.code === 'unauthenticated' ? t('reviewPage.signIn', { host }) + : t('reviewPage.listFailed', { host, message: failure.code === 'rate-limited' ? t('change.failure.rateLimited') : failure.message })} + + {command !== null && {command}} + {(command !== null || onOpenSettings !== undefined) && ( + + {command !== null && } + {onOpenSettings !== undefined && } + + )} +
    + ) + })} +
    + ) } /** @@ -366,14 +370,18 @@ function SkeletonItems({ view, count }: { readonly view: ReviewView; readonly co * @returns the column. */ export function ReviewList(props: ReviewListProps): ReactNode { - const { frame, stopped, selected, query, folded, refreshing, now, view } = props - const { onSelect, onSearch, onFold, onRefresh, onRetry, copyText, t } = props + const { frame, stopped, selected, query, folded, refreshing, now, view, scope } = props + const { onSelect, onSearch, onFold, onRefresh, onRetry, copyText, onOpenSettings, t } = props const { directOnly } = props + const host = scope?.host ?? null // Each section with its search index, rebuilt when the lists change; a blank search returns a list as built. - const sections = useMemo(() => reviewSections(frame, directOnly).map(section => - ({ section, index: new TextSearchIndex(section.items ?? [], reviewSearchKeys) })), [frame, directOnly]) + const sections = useMemo(() => reviewSections(frame, directOnly, host).map(section => + ({ section, index: new TextSearchIndex(section.items ?? [], reviewSearchKeys) })), [frame, directOnly, host]) + const failures = useMemo(() => reviewFailures(frame, host), [frame, host]) const pasted = pastedUrl(query) - const qualified = reviewRepositories(frame).length > 1 + const named = reviewRepositories(frame).filter(item => host === null || item.host === host) + const qualified = named.length > 1 + const hosted = new Set(named.map(item => item.host)).size > 1 let body: ReactNode if (stopped !== null && frame === undefined) { body = ( @@ -397,39 +405,48 @@ export function ReviewList(props: ReviewListProps): ReactNode {
    ) } else { - body = sections.map(({ section, index }) => { - const title = t(SECTION[section.filter]) - const open = folded[section.filter] !== true - const shown = index.search(query) - return ( -
    - - {open && <> - - {section.items === null - ? section.failure === null &&
    - : shown.length === 0 - ?

    {t(query.trim() === '' ? 'reviewPage.empty.section' : 'reviewPage.empty.search')}

    - : ( -
      - {shown.map((item) => { - const Row = view === 'compact' ? CompactItem : Item - return - })} -
    + // A host whose first read of a list is still running: its rows are to come, so the count and the empty text wait. + const awaits = (section: ReviewSection): boolean => section.pending && frame.reading + // Where no host listed anything and none is still to answer, the notices of the hosts that failed are all there is to show. + const unread = failures.length > 0 && sections.every(({ section }) => section.items === null && !awaits(section)) + body = ( + <> + {!unread && sections.map(({ section, index }) => { + const title = t(SECTION[section.filter]) + const open = folded[section.filter] !== true + const shown = index.search(query) + const awaited = awaits(section) + return ( +
    + + {open && <> + {shown.length > 0 + ? ( +
      + {shown.map((item) => { + const Row = view === 'compact' ? CompactItem : Item + return + })} +
    + ) + : section.items !== null && !awaited + &&

    {t(query.trim() === '' ? 'reviewPage.empty.section' : 'reviewPage.empty.search')}

    } + {awaited &&
    0 ? 1 : 3} />
    } + {section.truncated && query.trim() === '' && ( +

    {t('reviewPage.truncated', { count: section.total - shown.length })}

    )} - {section.truncated && query.trim() === '' && ( -

    {t('reviewPage.truncated', { count: section.total - shown.length })}

    - )} - } -
    - ) - }) + } +
    + ) + })} + + + ) } return (
    diff --git a/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.module.css b/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.module.css index 36a693c81c..dcaee2811b 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.module.css +++ b/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.module.css @@ -113,6 +113,11 @@ color: var(--dsw-alias-label-primary); } +/* A repository below the row of its host. */ +.menuNested { + padding-left: 16px; +} + .menuValue { overflow: hidden; color: var(--dsw-alias-label-tertiary); @@ -223,6 +228,7 @@ .itemText { display: flex; + flex: 1; flex-direction: column; gap: 2px; min-width: 0; @@ -236,25 +242,84 @@ overflow-wrap: anywhere; } +/* An item's small text on at most two lines: "repository#number · author" and the hint in the first column, the update + time in the second. The first column's line does not wrap; the hint follows it where both fit and wraps below it + where they do not. */ .itemMeta { - display: flex; - flex-wrap: wrap; - gap: 0 4px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: start; + gap: 0 8px; min-width: 0; color: var(--dsw-alias-label-tertiary); font-size: 12px; line-height: 18px; } -.itemIssues { - display: inline-flex; - gap: 2px; +.itemFacts { + display: flex; + flex-wrap: wrap; + column-gap: 12px; + min-width: 0; + overflow: hidden; +} + +.itemLine { + display: flex; + flex: 0 1 auto; + gap: 4px; + min-width: 0; + white-space: nowrap; +} + +/* Where the line is too narrow the author gives way first, then the repository name; the number is never cut. */ +.itemName { + display: flex; + flex: 0 1 auto; + min-width: 0; +} + +.itemRepository { + flex: 0 1 auto; + min-width: 2ch; + overflow: hidden; + text-overflow: ellipsis; +} + +.itemNumber { + flex: none; +} + +.itemAuthor { + flex: 0 100000 auto; + min-width: 3ch; + overflow: hidden; + text-overflow: ellipsis; +} + +.itemTime { + white-space: nowrap; } .itemHint { color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 18px; + white-space: nowrap; +} + +/* The separator before a hint is drawn in the gap to its left. A hint that starts the second line has that gap outside + `.itemFacts`, which clips the separator there. */ +.itemFacts > .itemHint { + position: relative; + flex: none; +} + +.itemFacts > .itemHint::before { + position: absolute; + left: -8px; + color: var(--dsw-alias-label-tertiary); + content: '·'; } .itemHint[data-tone='error'] { @@ -330,7 +395,11 @@ overflow-wrap: anywhere; } -.compactCard .itemMeta { +.cardMeta { + display: flex; + flex-wrap: wrap; + gap: 0 4px; + min-width: 0; color: var(--dsw-alias-hovercard-label-tertiary); } @@ -387,6 +456,21 @@ gap: 6px; } +.noticeActions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +/* The notices of the hosts that could not be read, after the sections. */ +.notices { + padding-top: 10px; +} + +.notices:first-child { + padding-top: 4px; +} + .noticeCommand code { font-family: var(--dsw-font-mono, ui-monospace, monospace); overflow-wrap: anywhere; diff --git a/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx b/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx index 99f429d0ef..1d6cd98a9c 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx +++ b/packages/experimental/client-ui-forge/src/client/review-page/ReviewPage.tsx @@ -20,7 +20,7 @@ import { ReviewChat, useReviewConversation, type ReviewChatFace } from './Review import { ReviewDetail } from './ReviewDetail.tsx' import { ReviewList } from './ReviewList.tsx' import type { QuoteCopy, ReviewSelection } from '../review.ts' -import { reviewListsComplete, reviewRepositories } from './review-lists.ts' +import { reviewListsComplete, reviewRepositories, scopeRepository, type ReviewRepository } from './review-lists.ts' import type { createReviewStore, ReviewTab } from './review-store.ts' import type { HostStream, StreamSnapshot } from '../source.ts' import type { ChangesPanelState } from '../status.ts' @@ -45,8 +45,8 @@ export interface ReviewPageInjected { /** Whether the Plugins page can be opened; the renderer binds it as `usePluginNavigation`. */ readonly pluginNavigation: HostObservable } - /** Open the list stream of one repository, named `owner/name`, or of every repository for the empty string. */ - readonly openLists: (scope: string, signal: AbortSignal) => HostStream + /** Open the list stream of one repository on its host, or of every repository of every host for null. */ + readonly openLists: (repository: ReviewRepository | null, signal: AbortSignal) => HostStream /** Open the stream of one change request by URL. */ readonly openChangeRequest: (url: string, signal: AbortSignal) => HostStream /** Subscribe to transport resets, after which open streams no longer deliver. */ @@ -212,7 +212,8 @@ export function ReviewPage(props: ReviewPageProps): ReactNode { const tab = useStore(state => state.tab) const listHidden = useStore(state => state.listHidden) const folded = useStore(state => state.folded) - const repository = useStore(state => state.repository) + const scope = useStore(state => state.scope) + const repository = scopeRepository(scope) const repositories = useStore(state => state.repositories) const query = useStore(state => state.query) const directOnly = useStore(state => state.directOnly) @@ -222,8 +223,11 @@ export function ReviewPage(props: ReviewPageProps): ReactNode { const onConversation = useMemo(() => selected === null ? null : (sessionId: SessionId | null) => { actions.conversed(selected, sessionId) }, [actions, selected]) - const scope = repository === null ? '' : `${repository.owner}/${repository.name}` - const lists = useHostStream(openLists, scope, subscribeReset) + // A scope that names a host only narrows the lists of every repository on the page; one repository is read on its host. + const listsKey = repository === null ? '' : JSON.stringify([repository.host, repository.owner, repository.name]) + const openScoped = useCallback((_key: string, signal: AbortSignal) => openLists(repository, signal), [openLists, repository]) + const lists = useHostStream(openScoped, listsKey, subscribeReset) + const hostSettings = props.usePluginNavigation(value => value) // Lists read in one repository name only that one, so the repository menu's offer is recorded while they are read in all. const listsFrame = lists.frame useEffect(() => { @@ -246,7 +250,7 @@ export function ReviewPage(props: ReviewPageProps): ReactNode { stopped={lists.stopped} selected={selected} query={query} - repository={repository} + scope={scope} repositories={repositories} directOnly={directOnly} folded={folded} @@ -262,6 +266,7 @@ export function ReviewPage(props: ReviewPageProps): ReactNode { onRefresh={startRefresh} onRetry={lists.retry} copyText={copyText} + onOpenSettings={hostSettings ? props.openHostSettings : undefined} t={t} /> {selected === null || cardActions === null || onConversation === null diff --git a/packages/experimental/client-ui-forge/src/client/review-page/review-lists.ts b/packages/experimental/client-ui-forge/src/client/review-page/review-lists.ts index 5963711a27..60ebc302d2 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/review-lists.ts +++ b/packages/experimental/client-ui-forge/src/client/review-page/review-lists.ts @@ -1,6 +1,7 @@ /** * What the review page's list column shows from the Host's list frames: one section per list with its items and the - * text they are searched by, the hint each item carries, the repositories the lists name, and the failure each section reports. + * text they are searched by, the hint each item carries, the repositories the lists name by host, and the hosts whose + * read failed. */ import type { ChangeRequestSummary, ForgeFailure, ForgeViewerFilter } from '@deepseek-ai/dsh-experimental-forge/types' @@ -32,73 +33,130 @@ export interface ReviewSection { readonly total: number /** Whether some host listed fewer change requests than its total. */ readonly truncated: boolean - /** The first failure of the latest read on any host, or null. */ - readonly failure: { readonly host: string; readonly forge: string; readonly failure: ForgeFailure } | null + /** Whether some host has neither read the list nor failed to, so its change requests are still to come. */ + readonly pending: boolean } -/** A repository the lists name. */ +/** A repository the lists name, on the host that listed it. */ export interface ReviewRepository { + /** Host the repository was listed on. */ + readonly host: string /** Owner or namespace. */ readonly owner: string /** Repository name. */ readonly name: string } +/** What the reader narrowed the lists to: every repository of one host, or one repository. */ +export type ReviewScope = { readonly host: string } | ReviewRepository + +/** A host whose latest read of some list failed. */ +export interface ReviewHostFailure { + /** Forge family of the provider that lists on the host. */ + readonly forge: string + /** The host. */ + readonly host: string + /** The first failure among the host's lists, in page order. */ + readonly failure: ForgeFailure + /** The command that signs the provider's CLI in to the host, or null when the failure is another or the provider names none. */ + readonly signIn: string | null +} + +/** + * The repository a scope names. + * @param scope - the reader's scope, or null for every repository of every host. + * @returns the repository, or null for a scope that names a host only or none. + */ +export function scopeRepository(scope: ReviewScope | null): ReviewRepository | null { + return scope !== null && 'name' in scope ? scope : null +} + +/** + * Whether two scopes narrow the lists to the same host or repository. + * @param left - one scope, or null for none. + * @param right - the other scope, or null for none. + * @returns whether they are the same. + */ +export function sameScope(left: ReviewScope | null, right: ReviewScope | null): boolean { + if (left === null || right === null) return left === right + const one = scopeRepository(left) + const other = scopeRepository(right) + return left.host === right.host && one?.owner === other?.owner && one?.name === other?.name +} + /** * Build the list sections from one frame. * @param frame - the latest frame, or undefined before the first. * @param directOnly - whether the review-requested list leaves out requests made only of one of the user's teams. + * @param host - the host the reader narrowed the lists to, or null for every host of the frame. * @returns one section per list some host offers, in page order, each with every item most recently updated first. */ -export function reviewSections(frame: ForgeReviewFrame | undefined, directOnly: boolean): readonly ReviewSection[] { +export function reviewSections(frame: ForgeReviewFrame | undefined, directOnly: boolean, host: string | null): readonly ReviewSection[] { if (frame === undefined) return [] const sections: ReviewSection[] = [] for (const filter of REVIEW_FILTERS) { - const lists = frame.hosts.flatMap((host) => { - const list = host.lists[filter] - return list === undefined ? [] : [{ host, list }] + const lists = frame.hosts.flatMap((entry) => { + const list = entry.lists[filter] + return list === undefined || (host !== null && entry.host !== host) ? [] : [{ host: entry, list }] }) if (lists.length === 0) continue let items: ReviewItem[] | null = null let total = 0 let truncated = false - let failure: ReviewSection['failure'] = null - for (const { host, list } of lists) { - if (list.failure !== null && failure === null) failure = { host: host.host, forge: host.forge, failure: list.failure } - if (list.items === null) continue + let pending = false + for (const { host: entry, list } of lists) { + if (list.items === null) { + pending ||= list.failure === null + continue + } total += list.total truncated ||= list.total > list.items.length items ??= [] for (const summary of list.items) { if (filter === 'review-requested' && directOnly && summary.viewerRequest !== null && summary.viewerRequest.team !== null) continue - items.push({ summary, forge: host.forge, host: host.host }) + items.push({ summary, forge: entry.forge, host: entry.host }) } } items?.sort((left, right) => Date.parse(right.summary.updatedAt) - Date.parse(left.summary.updatedAt)) - sections.push({ filter, items, total, truncated, failure }) + sections.push({ filter, items, total, truncated, pending }) } return sections } /** - * The text a listed change request is searched by under the client search rule: its title, number, repository, and - * author each match as a substring or a word-start fuzzy subsequence. + * List the hosts whose latest read of some list failed, so the page reports each once. + * @param frame - the latest frame, or undefined before the first. + * @param host - the host the reader narrowed the lists to, or null for every host of the frame. + * @returns the hosts in frame order, each with the first failure among its lists. + */ +export function reviewFailures(frame: ForgeReviewFrame | undefined, host: string | null): readonly ReviewHostFailure[] { + return (frame?.hosts ?? []).flatMap((entry) => { + if (host !== null && entry.host !== host) return [] + const failure = REVIEW_FILTERS.map(filter => entry.lists[filter]?.failure ?? null).find(found => found !== null) + return failure === undefined ? [] : [{ forge: entry.forge, host: entry.host, failure, signIn: entry.signIn }] + }) +} + +/** + * The text a listed change request is searched by under the client search rule: its title, number, repository, author, + * and host each match as a substring or a word-start fuzzy subsequence. * @param item - the listed change request. * @returns the search keys. */ export function reviewSearchKeys(item: ReviewItem): SearchKeys { const { repository, number } = item.summary.ref - return { fuzzy: [item.summary.title, `#${number}`, `${repository.owner}/${repository.name}`, item.summary.author?.login] } + return { fuzzy: [item.summary.title, `#${number}`, `${repository.owner}/${repository.name}`, item.summary.author?.login, item.host] } } /** - * List the repositories the lists name, by owner then name. + * List the repositories the lists name, by host, then owner, then name. * @param frame - the latest frame, or undefined before the first. * @returns distinct repositories. */ export function reviewRepositories(frame: ForgeReviewFrame | undefined): readonly ReviewRepository[] { return mergeRepositories((frame?.hosts ?? []).flatMap(host => - Object.values(host.lists).flatMap(list => (list.items ?? []).map(item => item.ref.repository)))) + Object.values(host.lists).flatMap(list => (list.items ?? []).map(({ ref: { repository } }) => + ({ host: host.host, owner: repository.owner, name: repository.name }))))) } /** @@ -112,15 +170,20 @@ export function reviewListsComplete(frame: ForgeReviewFrame | undefined): boolea && frame.hosts.every(host => Object.values(host.lists).every(list => list.items !== null && list.failure === null)) } +/** A repository's place in the order {@link mergeRepositories} sorts by, which is also its identity. */ +function repositoryKey({ host, owner, name }: ReviewRepository): string { + return `${host}\n${owner}/${name}`.toLowerCase() +} + /** - * Merge repositories into one list without duplicates, by owner then name. + * Merge repositories into one list without duplicates, by host, then owner, then name. * @param groups - lists of repositories. * @returns the distinct repositories, sorted as {@link reviewRepositories} sorts. */ export function mergeRepositories(...groups: readonly (readonly ReviewRepository[])[]): readonly ReviewRepository[] { const seen = new Map() - for (const { owner, name } of groups.flat()) seen.set(`${owner}/${name}`.toLowerCase(), { owner, name }) - return [...seen.values()].sort((left, right) => `${left.owner}/${left.name}`.localeCompare(`${right.owner}/${right.name}`)) + for (const { host, owner, name } of groups.flat()) seen.set(repositoryKey({ host, owner, name }), { host, owner, name }) + return [...seen].sort(([left], [right]) => left.localeCompare(right)).map(([, repository]) => repository) } /** The hint an item carries: a dictionary key and its values. */ diff --git a/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts b/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts index b63ed786ee..6001cdbee3 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts +++ b/packages/experimental/client-ui-forge/src/client/review-page/review-mount.ts @@ -209,10 +209,7 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void { store: createReviewStore(), inject: (): ReviewPageInjected => ({ hooks: { locale: deps.locale, pluginNavigation }, - openLists: (scope, signal) => { - const slash = scope.indexOf('/') - return remote.reviewLists(slash < 0 ? null : { owner: scope.slice(0, slash), name: scope.slice(slash + 1) }, signal) - }, + openLists: (repository, signal) => remote.reviewLists(repository, signal), openChangeRequest: (url, signal) => remote.reviewChangeRequest(url, signal), subscribeReset, refresh: async () => { settled(await remote.reviewRefresh(), 'toast.refreshFailed') }, diff --git a/packages/experimental/client-ui-forge/src/client/review-page/review-store.ts b/packages/experimental/client-ui-forge/src/client/review-page/review-store.ts index 1b1ce1d992..aa4c288914 100644 --- a/packages/experimental/client-ui-forge/src/client/review-page/review-store.ts +++ b/packages/experimental/client-ui-forge/src/client/review-page/review-store.ts @@ -1,6 +1,6 @@ /** * Choices of the review page that outlive its mount: the change request shown in full, its tab, whether the list column - * hides, which list sections fold, the repository the lists are read in, the search text, the conversation the page + * hides, which list sections fold, the host or repository the lists are narrowed to, the search text, the conversation the page * started for each change request, and the changes view's choices for each change request. */ @@ -8,7 +8,7 @@ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-sto import type { ForgeViewerFilter } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { changesActions, type ChangesState } from '../changes-store.ts' -import { mergeRepositories, type ReviewRepository } from './review-lists.ts' +import { mergeRepositories, type ReviewRepository, type ReviewScope } from './review-lists.ts' /** A tab of the review page's detail. */ export type ReviewTab = 'summary' | 'changes' | 'chat' @@ -26,8 +26,8 @@ export interface ReviewPageState extends ChangesState { listHidden: boolean /** List sections the reader folded. */ folded: Partial> - /** Repository the lists are read in, or null for every repository. */ - repository: { readonly owner: string; readonly name: string } | null + /** What the lists are narrowed to: one host, one repository, or null for every repository of every host. */ + scope: ReviewScope | null /** * Repositories the lists named while they were read in every repository, which the repository menu keeps offering * while the lists are read in one. @@ -62,14 +62,14 @@ const reviewActions = { }, toggledList: (state: ReviewPageState) => { state.listHidden = !state.listHidden }, folded: (state: ReviewPageState, filter: ForgeViewerFilter) => { state.folded[filter] = state.folded[filter] !== true }, - scopedTo: (state: ReviewPageState, repository: ReviewPageState['repository']) => { state.repository = repository }, + scopedTo: (state: ReviewPageState, scope: ReviewScope | null) => { state.scope = scope }, /** * Record the repositories the lists read in every repository name: a complete read replaces the record, and a read * still under way or failed in part adds to it. */ listed: (state: ReviewPageState, repositories: ReviewPageState['repositories'], complete: boolean) => { const next = complete ? mergeRepositories(repositories) : mergeRepositories(state.repositories, repositories) - const names = (list: ReviewPageState['repositories']): string => list.map(item => `${item.owner}/${item.name}`).join('\n') + const names = (list: ReviewPageState['repositories']): string => list.map(item => `${item.host} ${item.owner}/${item.name}`).join('\n') if (names(next) !== names(state.repositories)) state.repositories = [...next] }, searched: (state: ReviewPageState, query: string) => { state.query = query }, @@ -87,7 +87,7 @@ const reviewActions = { export function createReviewStore(): EngineStoreHandle { return defineStore({ init: (): ReviewPageState => ({ - selected: null, tab: 'summary', listHidden: false, folded: {}, repository: null, repositories: [], query: '', directOnly: false, conversations: {}, view: 'detailed', unseenQuotes: {}, byTab: {}, + selected: null, tab: 'summary', listHidden: false, folded: {}, scope: null, repositories: [], query: '', directOnly: false, conversations: {}, view: 'detailed', unseenQuotes: {}, byTab: {}, }), actions: reviewActions, }) diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index cf10661e27..3024e66c89 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -45,7 +45,7 @@ import { Reader, ViewerLists } from './viewer-lists.ts' import type { KeptPanel, PanelConfig } from './panel.ts' import type { Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile, - ForgeReviewChangeRequest, ForgeReviewCountFrame, ForgeReviewFrame, + ForgeReviewChangeRequest, ForgeReviewCountFrame, ForgeReviewFrame, ForgeReviewRepository, ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState, } from './types.ts' @@ -196,6 +196,7 @@ export class ForgePanelController extends TypertRemoteService { sources: () => ctx.forge.viewerSources(), list: async (forge, query, signal) => await ctx.forge.listForViewer(forge, query, signal), count: async (forge, host, signal) => await ctx.forge.countForViewer(forge, host, signal), + signIn: async (forge, host, signal) => (await ctx.forge.readiness({ forge, host }, signal)).signIn?.command ?? null, report: (error) => { ctx.logger.warn(`forge-panel: reading a review list failed: ${String(error)}`) }, }, { listIntervalMs: resolved.reviewListIntervalMs, @@ -287,15 +288,17 @@ export class ForgePanelController extends TypertRemoteService { /** * Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on: * the lists read so far first, then a frame after each read settles. Readers of one repository scope share one - * reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to - * `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops. - * @param repository - one repository to list in, or null for every repository the user can read. + * reader, which reads each host every `reviewListIntervalMs` while some stream lasts and reads a host whose read failed + * again later each time, up to `reviewMaxBackoffMs`, without delaying the other hosts; nothing is read while no stream + * lasts. The stream ends when `signal` aborts or the Remote stops. + * @param repository - one repository to list in, read on its host only, or null for every repository the user can + * read on every host. * @param signal - ends the stream. * @returns frames, each complete. */ @Remote({ mode: 'stream' }) async *reviewLists( - repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, + repository: ForgeReviewRepository | null, signal: AbortSignal, ): AsyncIterable { yield* this.viewerLists.lists(repository, signal) } diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index eefd005c52..f7b9f3f94a 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -219,6 +219,16 @@ export interface ForgeReviewList { readonly failure: ForgeFailure | null } +/** One repository on one host, which the review page's lists can be read in. */ +export interface ForgeReviewRepository { + /** Host name of the provider that lists the repository, compared without case. */ + readonly host: string + /** Owner or namespace; nested groups of a GitLab project stay in it. */ + readonly owner: string + /** Repository name. */ + readonly name: string +} + /** The review page's lists on one host of one provider. */ export interface ForgeReviewHost { /** Forge family of the provider. */ @@ -227,6 +237,11 @@ export interface ForgeReviewHost { readonly host: string /** Login of the signed-in user the latest successful read named, or null before one. */ readonly viewer: string | null + /** + * The command that signs the provider's CLI in to the host, while the latest read failed for lack of sign-in and the + * provider names one; null otherwise. + */ + readonly signIn: string | null /** Each list the provider offers on the host; a list it does not offer is absent. */ readonly lists: Partial>> } @@ -648,7 +663,7 @@ export interface Config { reviewListIntervalMs?: number /** Milliseconds between two reads of the review page's navigation count while it is shown. */ reviewCountIntervalMs?: number - /** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */ + /** Largest delay in milliseconds between two reads of the review page's lists or count on one host after its consecutive failed reads. */ reviewMaxBackoffMs?: number /** Most change requests one review page list shows, capped by each provider's own limit. */ reviewPageSize?: number diff --git a/packages/experimental/client-ui-forge/src/viewer-lists.ts b/packages/experimental/client-ui-forge/src/viewer-lists.ts index 228f470899..054e03a621 100644 --- a/packages/experimental/client-ui-forge/src/viewer-lists.ts +++ b/packages/experimental/client-ui-forge/src/viewer-lists.ts @@ -1,15 +1,16 @@ /** * The review page's lists of the signed-in user's change requests and its navigation count. Lists are read only while * some reader streams them and the count only while some reader streams it; neither joins the forge's status polling. - * Readers of one repository scope share one poller, which reads every list of every host each round, hosts in parallel - * and each host's lists one after another, so one host has at most one read in flight. A round with a failure delays - * the next round as status polling does after consecutive failures. + * Readers of one repository scope share one poller, which reads every list of every due host each round, hosts in + * parallel and each host's lists one after another, so one host has at most one read in flight. A host whose read + * failed is read again later each time, as status polling waits after consecutive failures, while the other hosts + * keep their cadence. A scope that names a repository reads only the host the repository is on. */ import type { ForgeFailure, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery, ForgeViewerSource, } from '@deepseek-ai/dsh-experimental-forge/types' -import type { ForgeReviewCountFrame, ForgeReviewFrame, ForgeReviewHost, ForgeReviewList } from './types.ts' +import type { ForgeReviewCountFrame, ForgeReviewFrame, ForgeReviewHost, ForgeReviewList, ForgeReviewRepository } from './types.ts' /** The lists in the order the page shows them. */ const FILTERS: readonly ForgeViewerFilter[] = ['review-requested', 'authored', 'involved'] @@ -22,6 +23,8 @@ export interface ViewerListSources { readonly list: (forge: string, query: ForgeViewerQuery, signal: AbortSignal) => Promise /** Read the size of every list on one host. */ readonly count: (forge: string, host: string, signal: AbortSignal) => Promise | ForgeFailure> + /** The command that signs the provider's CLI in to a host, or null when the provider names none. */ + readonly signIn: (forge: string, host: string, signal: AbortSignal) => Promise /** Report a read that rejected instead of resolving to a failure. */ readonly report: (error: unknown) => void } @@ -32,14 +35,14 @@ export interface ViewerListTiming { readonly listIntervalMs: number /** Milliseconds between two rounds of the count poller. */ readonly countIntervalMs: number - /** Largest delay in milliseconds after consecutive failed rounds. */ + /** Largest delay in milliseconds before a host is read again after consecutive failed reads. */ readonly maxBackoffMs: number /** Most change requests one list read asks for, before each provider's own limit. */ readonly pageSize: number } -/** One repository to list in, or null for every repository. */ -export type ViewerScope = { readonly owner: string; readonly name: string } | null +/** One repository on one host to list in, or null for every repository of every host. */ +export type ViewerScope = ForgeReviewRepository | null /** A stream's latest undelivered frame; a newer frame replaces one the reader has not taken. */ export class Reader { @@ -92,15 +95,15 @@ export class Reader { } } -/** A loop that runs one round, waits, and repeats until stopped; a refresh ends the wait early. */ +/** A loop that runs one round, waits as long as the round asks, and repeats until stopped; a refresh ends the wait early. */ class Poller { private readonly aborter = new AbortController() private wake: (() => void) | undefined private refreshing = false - private failures = 0 readonly done: Promise - constructor(private readonly round: (signal: AbortSignal) => Promise, private readonly delay: (failures: number) => number) { + /** @param round - runs one round, `forced` after a refresh, and resolves to the milliseconds to wait before the next. */ + constructor(private readonly round: (signal: AbortSignal, forced: boolean) => Promise) { this.done = this.loop() } @@ -123,12 +126,12 @@ class Poller { private async loop(): Promise { const { signal } = this.aborter while (!signal.aborted) { + const forced = this.refreshing this.refreshing = false - const succeeded = await this.round(signal) - this.failures = succeeded ? 0 : this.failures + 1 + const wait = await this.round(signal, forced) if (this.skipsWait(signal)) continue await new Promise((resolve) => { - const timer = setTimeout(resolve, this.delay(this.failures)) + const timer = setTimeout(resolve, wait) this.wake = () => { clearTimeout(timer); resolve() } }) this.wake = undefined @@ -136,28 +139,72 @@ class Poller { } } -/** The readers of one repository scope, the poller they share, and what it read. */ +/** + * When each host of one poller is read next. A host is due at once until its first read settles; after a read it is + * due one delay after the start of the round that read it, and the delay grows with its consecutive failed reads. + */ +class HostSchedule { + private readonly hosts = new Map() + + /** @param delay - milliseconds between two reads of a host after the given number of consecutive failed reads. */ + constructor(private readonly delay: (failures: number) => number) {} + + /** Whether a round that starts at `now` reads the host. */ + due(key: string, now: number): boolean { + return (this.hosts.get(key)?.dueAt ?? 0) <= now + } + + /** Record whether the read of the host succeeded in the round that started at `started`. */ + settle(key: string, started: number, succeeded: boolean): void { + const failures = succeeded ? 0 : (this.hosts.get(key)?.failures ?? 0) + 1 + this.hosts.set(key, { failures, dueAt: started + this.delay(failures) }) + } + + /** Milliseconds from `now` until the first of `keys` is due, or the delay between two successful reads without any key. */ + wait(keys: readonly string[], now: number): number { + if (keys.length === 0) return this.delay(0) + return Math.max(0, Math.min(...keys.map(key => this.hosts.get(key)?.dueAt ?? 0)) - now) + } +} + +/** One host a scope reads, with the provider that lists on it. */ +interface Target { + readonly source: ForgeViewerSource + readonly host: string + readonly key: string +} + +/** The readers of one repository scope, the poller they share, when each host is read next, and what was read. */ class Scope { readonly readers = new Set>() readonly hosts = new Map() + readonly schedule: HostSchedule reading = false readonly poller: Poller /** - * @param round - reads every list of the scope once; resolves to whether every read succeeded. - * @param delay - milliseconds before the next round after the given number of consecutive failed rounds. + * @param repository - the repository the scope lists in, or null for every repository of every host. + * @param round - reads the scope's due hosts once, every host when `forced`; resolves to the wait before the next round. + * @param delay - milliseconds between two reads of a host after the given number of consecutive failed reads. */ - constructor(round: (scope: Scope, signal: AbortSignal) => Promise, delay: (failures: number) => number) { - this.poller = new Poller(signal => round(this, signal), delay) + constructor( + readonly repository: ViewerScope, + round: (scope: Scope, signal: AbortSignal, forced: boolean) => Promise, + delay: (failures: number) => number, + ) { + this.schedule = new HostSchedule(delay) + this.poller = new Poller((signal, forced) => round(this, signal, forced)) + } + + /** The hosts the scope reads, in registration and configuration order: every host, or the one its repository is on. */ + targets(order: readonly ForgeViewerSource[]): Target[] { + const only = this.repository?.host.toLowerCase() + return order.flatMap(source => source.hosts.filter(host => only === undefined || host === only) + .map(host => ({ source, host, key: hostKey(source.forge, host) }))) } frame(order: readonly ForgeViewerSource[]): ForgeReviewFrame { - const hosts: ForgeReviewHost[] = [] - for (const source of order) { - for (const host of source.hosts) { - hosts.push(this.hosts.get(hostKey(source.forge, host)) ?? emptyHost(source, host)) - } - } + const hosts = this.targets(order).map(({ source, host, key }) => this.hosts.get(key) ?? emptyHost(source, host)) return { hosts, reading: this.reading } } } @@ -167,6 +214,7 @@ export class ViewerLists { private readonly scopes = new Map() private readonly countReaders = new Set>() private readonly counts = new Map() + private readonly countSchedule = new HostSchedule(failures => this.delay(this.timing.countIntervalMs, failures)) private countPoller: Poller | undefined private disposed = false @@ -179,18 +227,19 @@ export class ViewerLists { /** * Stream the lists of one repository scope: the lists read so far first, then a frame after each read settles. * The stream ends when `signal` aborts or the hub is disposed; the last stream of a scope stops its reads. - * @param scope - one repository, or null for every repository. + * @param scope - one repository on its host, or null for every repository of every host. * @param signal - ends the stream. * @returns frames, each complete. */ async *lists(scope: ViewerScope, signal: AbortSignal): AsyncIterable { signal.throwIfAborted() if (this.disposed) return - const key = scope === null ? '' : `${scope.owner}/${scope.name}`.toLowerCase() + const key = scope === null ? '' : `${scope.host}\n${scope.owner}/${scope.name}`.toLowerCase() let state = this.scopes.get(key) if (state === undefined) { state = new Scope( - (created, round) => this.readScope(created, scope, round), failures => this.delay(this.timing.listIntervalMs, failures), + scope, (created, round, forced) => this.readScope(created, round, forced), + failures => this.delay(this.timing.listIntervalMs, failures), ) this.scopes.set(key, state) } @@ -221,7 +270,7 @@ export class ViewerLists { const reader = new Reader(signal) this.countReaders.add(reader) reader.push(this.countFrame()) - this.countPoller ??= new Poller(round => this.readCounts(round), failures => this.delay(this.timing.countIntervalMs, failures)) + this.countPoller ??= new Poller((round, forced) => this.readCounts(round, forced)) try { yield* reader.frames() } finally { @@ -271,45 +320,72 @@ export class ViewerLists { await Promise.all(pollers.map(async (poller) =>{ await poller.stop() })) } - /** Read every list of every host once; resolves to whether every read succeeded. */ - private async readScope(scope: Scope, repository: ViewerScope, signal: AbortSignal): Promise { - const order = this.sources.sources() + /** + * Read every list of the scope's due hosts once, of every host when `forced`. + * @returns milliseconds until the scope's next host is due. + */ + private async readScope(scope: Scope, signal: AbortSignal, forced: boolean): Promise { + const started = Date.now() + const targets = scope.targets(this.sources.sources()) + const repository = scope.repository === null ? null : { owner: scope.repository.owner, name: scope.repository.name } scope.reading = true this.publish(scope) - const results = await Promise.all(order.flatMap(source => source.hosts.map(async (host) => { + await Promise.all(targets.filter(target => forced || scope.schedule.due(target.key, started)).map(async ({ source, host, key }) => { let succeeded = true let hostFailure: ForgeFailure | undefined for (const filter of FILTERS) { if (!source.filters.has(filter)) continue const query: ForgeViewerQuery = { host, filter, repository, limit: Math.min(source.maxItems, this.timing.pageSize) } const result = hostFailure ?? await this.read(() => this.sources.list(source.forge, query, signal), signal) - if (signal.aborted) return false + if (signal.aborted) return if ('code' in result && HOST_FAILURES.has(result.code)) hostFailure = result succeeded = this.settle(scope, source, host, filter, result) && succeeded if (repository === null && !('code' in result) && filter === 'review-requested') { - this.counts.set(hostKey(source.forge, host), result.total) + this.counts.set(key, result.total) this.publishCount() } this.publish(scope) } - return succeeded - }))) + const signIn = hostFailure?.code === 'unauthenticated' ? await this.signInOf(scope, source, host, signal) : null + if (signal.aborted) return + const current = scope.hosts.get(key) ?? emptyHost(source, host) + if (current.signIn !== signIn) { + scope.hosts.set(key, { ...current, signIn }) + this.publish(scope) + } + scope.schedule.settle(key, started, succeeded) + })) scope.reading = false if (!signal.aborted) this.publish(scope) - return results.every(Boolean) + return scope.schedule.wait(targets.map(target => target.key), Date.now()) } - /** Read the count of every host once; resolves to whether every read succeeded. */ - private async readCounts(signal: AbortSignal): Promise { - const results = await Promise.all(this.sources.sources().flatMap(source => source.hosts.map(async (host) => { - if (!source.filters.has('review-requested')) return true + /** The sign-in command the scope already holds for the host, else the one its provider names now, else null. */ + private async signInOf(scope: Scope, source: ForgeViewerSource, host: string, signal: AbortSignal): Promise { + const known = scope.hosts.get(hostKey(source.forge, host))?.signIn ?? null + if (known !== null) return known + const command = await this.read(() => this.sources.signIn(source.forge, host, signal), signal) + return typeof command === 'string' ? command : null + } + + /** + * Read the count of every due host once, of every host when `forced`. + * @returns milliseconds until the next host is due. + */ + private async readCounts(signal: AbortSignal, forced: boolean): Promise { + const started = Date.now() + const targets = this.sources.sources().filter(source => source.filters.has('review-requested')) + .flatMap(source => source.hosts.map(host => ({ source, host, key: hostKey(source.forge, host) }))) + await Promise.all(targets.filter(target => forced || this.countSchedule.due(target.key, started)).map(async ({ source, host, key }) => { const result = await this.read(() => this.sources.count(source.forge, host, signal), signal) - if (signal.aborted || 'code' in result) return false - this.counts.set(hostKey(source.forge, host), result.get('review-requested') ?? 0) - this.publishCount() - return true - }))) - return results.every(Boolean) + if (signal.aborted) return + if (!('code' in result)) { + this.counts.set(key, result.get('review-requested') ?? 0) + this.publishCount() + } + this.countSchedule.settle(key, started, !('code' in result)) + })) + return this.countSchedule.wait(targets.map(target => target.key), Date.now()) } /** Run one read, turning a rejection into an `unavailable` failure and reporting it unless `signal` aborted. */ @@ -371,5 +447,5 @@ function hostKey(forge: string, host: string): string { function emptyHost(source: ForgeViewerSource, host: string): ForgeReviewHost { const lists: Partial> = {} for (const filter of FILTERS) if (source.filters.has(filter)) lists[filter] = EMPTY_LIST - return { forge: source.forge, host, viewer: null, lists } + return { forge: source.forge, host, viewer: null, signIn: null, lists } } 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 307e90d72b..4ccfe93885 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -1636,10 +1636,10 @@ describe('mountForgePanel review page', () => { const f = await fixture() const page = reviewPage(f) const signal = new AbortController().signal - page.openLists('', signal) + page.openLists(null, signal) expect(f.forgePanel.reviewLists).toHaveBeenLastCalledWith(null, signal) - page.openLists('octo/demo', signal) - expect(f.forgePanel.reviewLists).toHaveBeenLastCalledWith({ owner: 'octo', name: 'demo' }, signal) + page.openLists({ host: 'gitlab.example', owner: 'group/sub', name: 'app' }, signal) + expect(f.forgePanel.reviewLists).toHaveBeenLastCalledWith({ host: 'gitlab.example', owner: 'group/sub', name: 'app' }, signal) page.openChangeRequest(url, signal) expect(f.forgePanel.reviewChangeRequest).toHaveBeenCalledWith(url, signal) expect(await page.readDescription(url, signal)).toEqual({ ok: true, value: description('Body') }) diff --git a/packages/experimental/client-ui-forge/tests/review-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/review-fixtures.client.ts index 3a516b50c5..789f1f7c23 100644 --- a/packages/experimental/client-ui-forge/tests/review-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/review-fixtures.client.ts @@ -16,7 +16,7 @@ export function prUrl(number: number): string { /** * Open pull request `number` in `octo/demo` by `octo` with passed checks and no review, updated `2026-10-09T00:00:00Z`, - * that asks nothing of the signed-in user and closes no issue. + * that asks nothing of the signed-in user. */ export function summary(number: number, overrides: Partial = {}): ChangeRequestSummary { return { @@ -30,8 +30,6 @@ export function summary(number: number, overrides: Partial reviewDecision: 'none', viewerReview: null, viewerRequest: null, - closingIssues: [], - closingIssuesTruncated: false, updatedAt: '2026-10-09T00:00:00Z', ...overrides, } @@ -51,7 +49,7 @@ export function failedList(code: ForgeFailure['code'], message = 'down'): ForgeR export function host( lists: Partial>, overrides: Partial = {}, ): ForgeReviewHost { - return { forge: 'github', host: 'github.com', viewer: 'octo', lists, ...overrides } + return { forge: 'github', host: 'github.com', viewer: 'octo', signIn: null, lists, ...overrides } } /** A frame of `hosts` with no read in flight. */ diff --git a/packages/experimental/client-ui-forge/tests/review-list.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-list.client.spec.tsx index 4be3d62fbf..64d0b96c85 100644 --- a/packages/experimental/client-ui-forge/tests/review-list.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-list.client.spec.tsx @@ -1,14 +1,15 @@ // @vitest-environment jsdom /** - * The review page's list column, its navigation row, and the label line: sections with their items, empty states, and - * failures, the search box and pasted links, the filter menu, the navigation count, and labels folding into a chip. + * The review page's list column, its navigation row, and the label line: sections with their items and empty states, + * the notices of hosts that could not be read, the search box and pasted links, the filter menu of hosts and repositories, + * the navigation count, and labels folding into a chip. */ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { ChangeRequestIssue, ChangeRequestLabel, ChangeRequestSummary } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ChangeRequestLabel, ChangeRequestSummary } from '@deepseek-ai/dsh-experimental-forge/types' import { en } from '../src/client/locales.ts' import { fittingLabels, ReviewLabels } from '../src/client/review-page/ReviewLabels.tsx' import { ReviewList, type ReviewListProps } from '../src/client/review-page/ReviewList.tsx' @@ -31,10 +32,10 @@ const NOW = Date.parse('2026-10-09T00:05:00Z') /** Render the list column with every handler recorded and no choice made, unless `overrides` makes one. */ function renderList(overrides: Partial = {}) { const props: ReviewListProps = { - frame: undefined, stopped: null, selected: null, query: '', repository: null, repositories: [], directOnly: false, folded: {}, refreshing: false, + frame: undefined, stopped: null, selected: null, query: '', scope: null, repositories: [], directOnly: false, folded: {}, refreshing: false, now: NOW, view: 'detailed', onSelect: vi.fn(), onSearch: vi.fn(), onScope: vi.fn(), onToggleDirect: vi.fn(), onView: vi.fn(), onFold: vi.fn(), onRefresh: vi.fn(), - onRetry: vi.fn(), copyText: vi.fn(), t, ...overrides, + onRetry: vi.fn(), copyText: vi.fn(), onOpenSettings: undefined, t, ...overrides, } const view = render() /** The section of one list. */ @@ -52,11 +53,6 @@ function renderList(overrides: Partial = {}) { return { view, props, section, item } } -function issue(number: number): ChangeRequestIssue { - const url = `https://github.com/octo/demo/issues/${number}` - return { repository: ref(number).repository, number, title: `Issue ${number}`, state: 'open', url } -} - function inRepository(number: number, owner: string, name: string, overrides: Partial = {}): ChangeRequestSummary { return summary(number, { ref: { ...ref(number), repository: { ...ref(number).repository, owner, name } }, ...overrides }) } @@ -158,74 +154,149 @@ describe('ReviewList sections', () => { expect(b.view.queryByText(/more not listed/)).toBeNull() }) - it('shows skeleton rows for a list no host has read yet, and only the failure once a read failed', () => { - const b = renderList({ frame: frame(host({ authored: list(null), involved: failedList('unavailable', 'GitHub is down') })) }) + it('shows skeleton rows for a list no host has read yet while a read runs, and none once every read settled', () => { + const lists = frame(host({ authored: list(null), involved: list([summary(1)]) })) + const b = renderList({ frame: { ...lists, reading: true } }) expect(b.section('authored').querySelectorAll(`[aria-busy="true"] .${css.skeletonItem}`)).toHaveLength(3) expect(within(b.section('authored')).queryByRole('button', { name: /\d/ })).toBeNull() - const involved = b.section('involved') - expect(involved.querySelector('[aria-busy="true"]')).toBeNull() - expect(within(involved).getByRole('status').textContent).toBe('Couldn\'t read the list on github.com: GitHub is down') + cleanup() + const settled = renderList({ frame: lists }) + expect(settled.section('authored').querySelector('[aria-busy="true"]')).toBeNull() + expect(settled.section('authored').textContent).toBe('Created by me') }) - it('asks the user to sign in to a GitHub host with a command to copy, and to other hosts without one', () => { - const b = renderList({ frame: frame( - host({ authored: failedList('unauthenticated') }, { host: 'ghe.example' }), + it('keeps one skeleton row under the rows of the hosts that answered while another host still reads the list', () => { + const slow = { forge: 'gitlab', host: 'gitlab.com' } + const lists = frame( + host({ authored: list([summary(1)]), involved: list([]) }), host({ authored: list(null), involved: list(null) }, slow), + ) + const b = renderList({ frame: { ...lists, reading: true } }) + // The count and the empty text wait for the host that has not answered. + expect(b.section('authored').querySelectorAll('[data-forge-review-item]')).toHaveLength(1) + expect(b.section('authored').querySelectorAll(`[aria-busy="true"] .${css.skeletonItem}`)).toHaveLength(1) + expect(within(b.section('authored')).getByRole('button', { name: /Created by me/ }).textContent).toBe('Created by me') + expect(b.section('involved').querySelectorAll(`[aria-busy="true"] .${css.skeletonItem}`)).toHaveLength(3) + expect(within(b.section('involved')).queryByText('No change requests')).toBeNull() + cleanup() + // A host that failed is not waited for: its notice reports it. + const failed = frame(host({ authored: list([summary(1)]) }), host({ authored: failedList('unavailable') }, slow)) + const c = renderList({ frame: { ...failed, reading: true } }) + expect(c.section('authored').querySelector('[aria-busy="true"]')).toBeNull() + expect(within(c.section('authored')).getByRole('button', { name: /Created by me/ }).textContent).toBe('Created by me1') + }) +}) + +describe('ReviewList hosts that could not be read', () => { + it('reports each host once after the sections, with its sign-in command and the way to the settings', () => { + const onOpenSettings = vi.fn() + const b = renderList({ onOpenSettings, frame: frame( + host({ 'authored': list([summary(1)]), 'review-requested': failedList('rate-limited'), 'involved': list([]) }), + host({ authored: failedList('unauthenticated'), involved: failedList('unauthenticated') }, { host: 'ghe.example', signIn: 'gh auth login --hostname ghe.example' }), host({ involved: failedList('unauthenticated') }, { forge: 'gitlab', host: 'gitlab.example' }), - host({ 'review-requested': failedList('rate-limited') }), + host({ involved: failedList('unavailable', 'glab could not start') }, { forge: 'gitlab', host: 'gitlab.com' }), ) }) - const github = within(b.section('authored')).getByRole('status') - expect(github.textContent).toContain('Sign in to ghe.example to list your change requests') - expect(within(github).getByText('gh auth login --hostname ghe.example')).toBeTruthy() - fireEvent.click(within(github).getByRole('button', { name: 'Copy sign-in command' })) + const notices = b.view.getAllByRole('status') + expect(notices.map(notice => notice.getAttribute('data-forge-review-failure'))).toEqual(['github.com', 'ghe.example', 'gitlab.example', 'gitlab.com']) + // The notices follow the last section instead of repeating inside each one. + expect(b.section('involved').parentElement?.lastElementChild?.contains(notices[0] ?? null)).toBe(true) + expect(b.view.container.querySelector('[data-forge-review-section] [role="status"]')).toBeNull() + const [limited, enterprise, gitlab, down] = notices as [HTMLElement, HTMLElement, HTMLElement, HTMLElement] + expect(limited.textContent).toBe(`Couldn't read the list on github.com: ${en['change.failure.rateLimited']}Open settings`) + expect(enterprise.textContent).toContain('Sign in to ghe.example to list your change requests') + expect(within(enterprise).getByText('gh auth login --hostname ghe.example')).toBeTruthy() + fireEvent.click(within(enterprise).getByRole('button', { name: 'Copy sign-in command' })) expect(b.props.copyText).toHaveBeenCalledWith('gh auth login --hostname ghe.example') - const gitlab = within(b.section('involved')).getByRole('status') - expect(gitlab.textContent).toBe('Sign in to gitlab.example to list your change requests') - expect(within(gitlab).queryByRole('button')).toBeNull() - expect(within(b.section('review-requested')).getByRole('status').textContent).toBe(en['change.failure.rateLimited']) + // A provider that names no sign-in command leaves the notice without one. + expect(gitlab.textContent).toBe('Sign in to gitlab.example to list your change requestsOpen settings') + expect(within(gitlab).queryByRole('button', { name: 'Copy sign-in command' })).toBeNull() + expect(down.textContent).toBe('Couldn\'t read the list on gitlab.com: glab could not startOpen settings') + fireEvent.click(within(down).getByRole('button', { name: 'Open settings' })) + expect(onOpenSettings).toHaveBeenCalledOnce() + }) + + it('shows only the notices once no host listed anything, without a settings button while the settings cannot be opened', () => { + const lists = frame( + host({ 'authored': failedList('unauthenticated'), 'review-requested': failedList('unauthenticated') }, { signIn: 'gh auth login --hostname github.com' }), + host({ involved: failedList('unavailable', 'down') }, { forge: 'gitlab', host: 'gitlab.com' }), + ) + const b = renderList({ frame: lists }) + expect(b.view.container.querySelector('[data-forge-review-section]')).toBeNull() + const notices = b.view.getAllByRole('status') as [HTMLElement, HTMLElement] + expect(notices).toHaveLength(2) + expect(within(notices[0]).getAllByRole('button').map(button => button.textContent)).toEqual(['Copy sign-in command']) + expect(notices[1].textContent).toBe('Couldn\'t read the list on gitlab.com: down') + expect(within(notices[1]).queryByRole('button')).toBeNull() + cleanup() + // A later read of the hosts that failed changes nothing on the page until one answers. + const reading = renderList({ frame: { ...lists, reading: true } }) + expect(reading.view.container.querySelector('[data-forge-review-section]')).toBeNull() + expect(reading.view.getAllByRole('status')).toHaveLength(2) + cleanup() + // A host still to answer keeps the sections, with their skeletons above the notices. + const first = renderList({ frame: { hosts: [...lists.hosts, host({ authored: list(null) }, { host: 'ghe.example' })], reading: true } }) + expect(first.section('authored').querySelector('[aria-busy="true"]')).not.toBeNull() + expect(first.view.getAllByRole('status')).toHaveLength(2) + }) + + it('leaves out the notices and the lists of hosts other than the one the lists are narrowed to', () => { + const b = renderList({ scope: { host: 'github.com' }, frame: frame( + host({ authored: list([summary(1)]) }), host({ involved: failedList('unauthenticated') }, { forge: 'gitlab', host: 'gitlab.com' }), + ) }) + expect(b.view.queryByRole('status')).toBeNull() + expect([...b.view.container.querySelectorAll('[data-forge-review-section]')].map(section => section.getAttribute('data-forge-review-section'))).toEqual(['authored']) }) }) describe('ReviewList items', () => { - it('names an item by its number, author, update time, closing issues, and the hint the user acts on', () => { + it('names an item by its number and author with the short update time beside them, then the hint the user acts on', () => { const b = renderList({ frame: frame(host({ 'review-requested': list([ - summary(1, { - viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null }, closingIssues: [issue(5)], - }), - summary(2, { author: null, updatedAt: 'not a time', checksRollup: 'none', closingIssues: [issue(5), issue(6), issue(8)] }), - summary(3, { - viewerReview: { verdict: 'approved', reviewedSha: 'a'.repeat(40) }, closingIssues: [issue(5)], closingIssuesTruncated: true, - }), + summary(1, { viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null } }), + summary(2, { author: null, updatedAt: 'not a time', checksRollup: 'none' }), + summary(3, { viewerReview: { verdict: 'approved', reviewedSha: 'a'.repeat(40) } }), summary(4, { viewerRequest: { team: 'octo/core' }, checksRollup: 'failure' }), ]), })) }) const first = b.item(prUrl(1)) - expect(first.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#1·octo·5 min ago·⊙#5·You requested changes · Requested again') - expect(first.querySelector(`.${css.itemMeta} .${css.itemHint}`)?.textContent).toBe('You requested changes · Requested again') + expect(first.querySelector(`.${css.itemLine}`)?.textContent).toBe('#1·octo') + expect(first.querySelector(`.${css.itemMeta} > .${css.itemTime}`)?.textContent).toBe('5min') + // The hint stands beside the number and the author, so it shares their line where it fits and wraps below it where it does not. + expect(first.querySelector(`.${css.itemFacts} > .${css.itemHint}`)?.textContent).toBe('Re-review requested') expect(first.querySelector(`.${css.itemHint}`)?.getAttribute('data-tone')).toBe('error') expect(first.querySelector('[data-forge-glyph]')?.getAttribute('data-tone')).toBe('open') expect(first.querySelector('[data-checks]')?.getAttribute('data-checks')).toBe('success') const second = b.item(prUrl(2)) - expect(second.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#2·⊙#5and 2 more') + expect(second.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#2') + expect(second.querySelector(`.${css.itemTime}`)).toBeNull() expect(second.querySelector(`.${css.itemHint}`)).toBeNull() expect(second.querySelector('[data-checks]')).toBeNull() const third = b.item(prUrl(3)) - expect(third.querySelector(`.${css.itemIssues}`)?.textContent).toBe('⊙#5and 1+ more') + expect(third.querySelector(`.${css.itemHint}`)?.textContent).toBe('You approved') expect(third.querySelector(`.${css.itemHint}`)?.getAttribute('data-tone')).toBe('success') const fourth = b.item(prUrl(4)) - expect(fourth.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#4·octo·5 min ago·Team octo/core') + expect(fourth.querySelector(`.${css.itemFacts}`)?.textContent).toBe('#4·octoTeam octo/core') expect(fourth.querySelector(`.${css.itemHint}`)?.textContent).toBe('Team octo/core') expect(fourth.querySelector(`.${css.itemHint}`)?.hasAttribute('data-tone')).toBe(false) expect(fourth.querySelector('[data-forge-glyph]')?.getAttribute('data-tone')).toBe('blocked') }) - it('names each item\'s repository once the lists span more than one', () => { + it('names each item\'s repository before its number once the lists span more than one', () => { const b = renderList({ frame: frame(host({ authored: list([summary(1), inRepository(2, 'acme', 'widgets')]) })) }) - expect(b.item(prUrl(1)).querySelector(`.${css.itemMeta}`)?.firstChild?.textContent).toBe('demo#1') - expect(b.item(prUrl(2)).querySelector(`.${css.itemMeta}`)?.firstChild?.textContent).toBe('widgets#2') + expect(b.item(prUrl(1)).querySelector(`.${css.itemName}`)?.textContent).toBe('demo#1') + expect(b.item(prUrl(2)).querySelector(`.${css.itemName} > .${css.itemRepository}`)?.textContent).toBe('widgets') + expect(b.item(prUrl(2)).querySelector(`.${css.itemName} > .${css.itemNumber}`)?.textContent).toBe('#2') + cleanup() + const single = renderList({ frame: frame(host({ authored: list([summary(1)]) })) }) + expect(single.item(prUrl(1)).querySelector(`.${css.itemRepository}`)).toBeNull() + cleanup() + // Narrowed to one host, the lists span the repositories of that host only. + const narrowed = renderList({ scope: { host: 'github.com' }, frame: frame( + host({ authored: list([summary(1)]) }), host({ authored: list([inRepository(2, 'acme', 'widgets')]) }, { forge: 'gitlab', host: 'gitlab.example' }), + ) }) + expect(narrowed.item(prUrl(1)).querySelector(`.${css.itemRepository}`)).toBeNull() }) }) @@ -256,9 +327,7 @@ describe('ReviewList compact view', () => { it('names the full title and every fact of the detailed item in a hover card that copies the title', () => { vi.useFakeTimers() const b = renderList({ view: 'compact', frame: frame(host({ 'review-requested': list([ - summary(1, { - viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null }, closingIssues: [issue(5)], - }), + summary(1, { viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null } }), inRepository(2, 'acme', 'widgets', { author: null, updatedAt: 'not a time' }), ]) })) }) fireEvent.pointerEnter(b.item(prUrl(1))) @@ -268,11 +337,11 @@ describe('ReviewList compact view', () => { act(() => { vi.advanceTimersByTime(1) }) const first = screen.getByRole('button', { name: 'Copy title: Change 1' }) expect(first.querySelector(`.${css.compactCardTitle}`)?.textContent).toBe('Change 1') - expect(first.querySelector(`.${css.itemMeta}`)?.textContent).toBe('octo/demo#1·octo·5 min ago·⊙#5') - expect(first.querySelector(`.${css.itemHint}`)?.textContent).toBe('You requested changes · Requested again') + expect(first.querySelector(`.${css.cardMeta}`)?.textContent).toBe('octo/demo#1·octo·5 min ago') + expect(first.querySelector(`.${css.itemHint}`)?.textContent).toBe('Re-review requested') expect(first.querySelector(`.${css.itemHint}`)?.getAttribute('data-tone')).toBe('error') const second = screen.getByRole('button', { name: 'Copy title: Change 2' }) - expect(second.querySelector(`.${css.itemMeta}`)?.textContent).toBe('acme/widgets#2') + expect(second.querySelector(`.${css.cardMeta}`)?.textContent).toBe('acme/widgets#2') expect(second.querySelector(`.${css.itemHint}`)).toBeNull() cleanup() @@ -281,7 +350,17 @@ describe('ReviewList compact view', () => { fireEvent.pointerEnter(single.item(prUrl(3))) act(() => { vi.advanceTimersByTime(800) }) const card = screen.getByRole('button', { name: 'Copy title: Change 3' }) - expect(card.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#3·octo·5 min ago') + expect(card.querySelector(`.${css.cardMeta}`)?.textContent).toBe('#3·octo·5 min ago') + cleanup() + + // Once the lists span more than one host, the card starts with the host. + const hosts = renderList({ view: 'compact', frame: frame( + host({ authored: list([summary(4)]) }), host({ authored: list([inRepository(5, 'group/sub', 'app')]) }, { forge: 'gitlab', host: 'gitlab.example' }), + ) }) + fireEvent.pointerEnter(hosts.item(prUrl(5))) + act(() => { vi.advanceTimersByTime(800) }) + expect(screen.getByRole('button', { name: 'Copy title: Change 5' }).querySelector(`.${css.cardMeta}`)?.textContent) + .toBe('gitlab.example·group/sub/app#5·octo·5 min ago') }) it('marquees a clipped title while the item is hovered and returns it on leave', () => { @@ -382,7 +461,7 @@ describe('ReviewList filter menu', () => { const button = open(b) expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo']) fireEvent.click(within(document.body).getByRole('menuitem', { name: 'acme/widgets' })) - expect(b.props.onScope).toHaveBeenCalledWith({ owner: 'acme', name: 'widgets' }) + expect(b.props.onScope).toHaveBeenCalledWith({ host: 'github.com', owner: 'acme', name: 'widgets' }) expect(button.getAttribute('aria-expanded')).toBe('false') open(b) repositories() @@ -397,40 +476,71 @@ describe('ReviewList filter menu', () => { }) it('keeps offering a chosen repository whose lists are empty, and names the chosen repository on its row', () => { - const b = renderList({ frame: lists, repository: { owner: 'zeta', name: 'empty' } }) + const b = renderList({ frame: lists, scope: { host: 'github.com', owner: 'zeta', name: 'empty' } }) const button = open(b) expect(button.matches(`.${css.iconButtonActive}`)).toBe(true) expect(within(document.body).getByRole('menuitem', { name: /^Repository/ }).textContent).toBe('Repositoryzeta/empty') expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo', 'zeta/empty']) cleanup() - const listed = renderList({ frame: lists, repository: { owner: 'acme', name: 'widgets' } }) + const listed = renderList({ frame: lists, scope: { host: 'github.com', owner: 'acme', name: 'widgets' } }) open(listed) expect(within(document.body).getByRole('menuitem', { name: /^Repository/ }).textContent).toBe('Repositoryacme/widgets') expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo']) }) it('keeps offering the repositories remembered from every repository while the lists are read in one, marking the chosen one', () => { - const remembered = [{ owner: 'acme', name: 'widgets' }, { owner: 'octo', name: 'demo' }, { owner: 'zeta', name: 'tools' }] + const remembered = ['acme/widgets', 'octo/demo', 'zeta/tools'].map((path) => { + const [owner = '', name = ''] = path.split('/') + return { host: 'github.com', owner, name } + }) // Lists read in octo/demo name only that repository. const scoped = frame(host({ authored: list([summary(1)]) })) - const b = renderList({ frame: scoped, repository: { owner: 'octo', name: 'demo' }, repositories: remembered }) + const b = renderList({ frame: scoped, scope: { host: 'github.com', owner: 'octo', name: 'demo' }, repositories: remembered }) open(b) expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo', 'zeta/tools']) const child = within(document.body).getAllByRole('menu').at(-1) as HTMLElement expect(within(child).getAllByRole('menuitem').map(row => row.querySelector(CHECK) !== null)).toEqual([false, false, true, false]) // Another repository is one choice away, without returning to every repository first. fireEvent.click(within(child).getByRole('menuitem', { name: 'zeta/tools' })) - expect(b.props.onScope).toHaveBeenCalledWith({ owner: 'zeta', name: 'tools' }) + expect(b.props.onScope).toHaveBeenCalledWith({ host: 'github.com', owner: 'zeta', name: 'tools' }) cleanup() // The offer also survives the wait for the chosen repository's first frame. - const waiting = renderList({ repository: { owner: 'octo', name: 'demo' }, repositories: remembered }) + const waiting = renderList({ scope: { host: 'github.com', owner: 'octo', name: 'demo' }, repositories: remembered }) open(waiting) expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo', 'zeta/tools']) expect(within(document.body).queryByText('Reading the lists', { selector: '[role="menu"] *' })).toBeNull() }) + it('offers each host with its repositories below it once the lists name repositories on more than one host', () => { + const two = frame( + host({ authored: list([summary(1), inRepository(2, 'acme', 'widgets')]) }), + host({ involved: list([inRepository(3, 'group/sub', 'app')]) }, { forge: 'gitlab', host: 'gitlab.example' }), + ) + const b = renderList({ frame: two }) + open(b) + expect(repositories()).toEqual(['All repositories', 'github.com', 'acme/widgets', 'octo/demo', 'gitlab.example', 'group/sub/app']) + const offered = within(within(document.body).getAllByRole('menu').at(-1) as HTMLElement).getAllByRole('menuitem') + // A repository stands below the row of its host. + expect(offered.map(row => row.querySelector(`.${css.menuNested}`) !== null)).toEqual([false, false, true, true, false, true]) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'gitlab.example' })) + expect(b.props.onScope).toHaveBeenCalledWith({ host: 'gitlab.example' }) + cleanup() + + const narrowed = renderList({ frame: two, scope: { host: 'gitlab.example' } }) + const button = open(narrowed) + expect(button.matches(`.${css.iconButtonActive}`)).toBe(true) + expect(within(document.body).getByRole('menuitem', { name: /^Repository/ }).textContent).toBe('Repositorygitlab.example') + repositories() + const rows = within(within(document.body).getAllByRole('menu').at(-1) as HTMLElement).getAllByRole('menuitem') + expect(rows.map(row => row.querySelector(CHECK) !== null)).toEqual([false, false, false, false, true, false]) + // Only the chosen host's change requests show, and a nested group's project is one choice. + expect([...narrowed.view.container.querySelectorAll('[data-forge-review-item]')].map(item => item.getAttribute('data-forge-review-item'))).toEqual([prUrl(3)]) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'group/sub/app' })) + expect(narrowed.props.onScope).toHaveBeenCalledWith({ host: 'gitlab.example', owner: 'group/sub', name: 'app' }) + }) + it('says that the lists are still read while no repository was remembered and a read is under way', () => { const reading = (): boolean => within(document.body).getAllByRole('menu').at(-1)?.textContent?.includes('Reading the lists') === true const first = renderList() diff --git a/packages/experimental/client-ui-forge/tests/review-lists.client.spec.ts b/packages/experimental/client-ui-forge/tests/review-lists.client.spec.ts index d813dc6578..f9e8dbf0af 100644 --- a/packages/experimental/client-ui-forge/tests/review-lists.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review-lists.client.spec.ts @@ -1,6 +1,6 @@ /** - * The review page's list helpers and store: list sections and their search, the repositories the lists name, item hints - * and tones, pasted links, description Markdown, and the page's choices. + * The review page's list helpers and store: list sections and their search, the hosts that failed, the repositories and + * scopes the lists name, item hints and tones, pasted links, description Markdown, and the page's choices. */ import { describe, expect, it } from 'vitest' import { brandString } from '@deepseek-ai/dsh-brand' @@ -8,8 +8,8 @@ import type { ChangeRequestSummary } from '@deepseek-ai/dsh-experimental-forge/t import type { SessionId } from '@deepseek-ai/dsh-session/types' import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search' import { - descriptionMarkdown, mergeRepositories, pastedUrl, REVIEW_FILTERS, reviewHint, reviewListsComplete, reviewRepositories, reviewSearchKeys, - reviewSections, summaryTone, + descriptionMarkdown, mergeRepositories, pastedUrl, REVIEW_FILTERS, reviewFailures, reviewHint, reviewListsComplete, reviewRepositories, + reviewSearchKeys, reviewSections, sameScope, scopeRepository, summaryTone, } from '../src/client/review-page/review-lists.ts' import { createReviewStore } from '../src/client/review-page/review-store.ts' import { ref } from './client-fixtures.client.ts' @@ -27,7 +27,7 @@ function urls(sections: ReturnType): Record { it('shows no section before the first frame', () => { - expect(reviewSections(undefined, false)).toEqual([]) + expect(reviewSections(undefined, false, null)).toEqual([]) }) it('shows one section per offered list in page order, newest first, summing totals over hosts and marking cut lists', () => { @@ -35,32 +35,53 @@ describe('reviewSections', () => { const newer = summary(2, { updatedAt: '2026-10-05T00:00:00Z' }) const middle = summary(4, { updatedAt: '2026-10-03T00:00:00Z' }) const requested = summary(3) - const sections = reviewSections(frame( + const lists = frame( host({ 'authored': list([older, newer], { total: 5 }), 'review-requested': list([requested]) }), host({ authored: list([middle]) }, { forge: 'gitlab', host: 'gitlab.example' }), - ), false) + ) + const sections = reviewSections(lists, false, null) expect(REVIEW_FILTERS).toEqual(['review-requested', 'authored', 'involved']) expect(sections.map(section => section.filter)).toEqual(['review-requested', 'authored']) expect(sections[1]?.items?.map(item => [item.summary.ref.number, item.forge, item.host])).toEqual([ [2, 'github', 'github.com'], [4, 'gitlab', 'gitlab.example'], [1, 'github', 'github.com'], ]) - expect(sections[1]).toMatchObject({ total: 6, truncated: true, failure: null }) - expect(sections[0]).toMatchObject({ total: 1, truncated: false, failure: null }) + expect(sections[1]).toEqual(expect.objectContaining({ total: 6, truncated: true })) + expect(sections[0]).toEqual(expect.objectContaining({ total: 1, truncated: false })) }) - it('reports the first failure of any host, keeping the items a host read and null items before any host read the list', () => { + it('marks a list some host has neither read nor failed to read, and no list whose hosts all answered or failed', () => { + const lists = frame( + host({ 'authored': list([summary(1)]), 'review-requested': list(null), 'involved': list([]) }), + host({ authored: list(null), involved: failedList('unavailable') }, { forge: 'gitlab', host: 'gitlab.example' }), + ) + expect(reviewSections(lists, false, null).map(section => [section.filter, section.items?.length ?? null, section.pending])).toEqual([ + ['review-requested', null, true], ['authored', 1, true], ['involved', 0, false], + ]) + // The host that has not answered is out of a reader's narrowed lists. + expect(reviewSections(lists, false, 'github.com').map(section => section.pending)).toEqual([true, false, false]) + }) + + it('shows only the lists of the host the reader narrowed them to', () => { + const lists = frame( + host({ 'authored': list([summary(1), summary(2)], { total: 5 }), 'review-requested': list([summary(3)]) }), + host({ authored: list([summary(4)]) }, { forge: 'gitlab', host: 'gitlab.example' }), + ) + expect(reviewSections(lists, false, 'gitlab.example')).toEqual([ + { filter: 'authored', items: [{ summary: summary(4), forge: 'gitlab', host: 'gitlab.example' }], total: 1, truncated: false, pending: false }, + ]) + expect(reviewSections(lists, false, 'github.com').map(section => [section.filter, section.total])).toEqual([['review-requested', 1], ['authored', 5]]) + expect(reviewSections(lists, false, 'other.example')).toEqual([]) + }) + + it('keeps the items a host read while its latest read failed, and null items before any host read the list', () => { const sections = reviewSections(frame( host({ involved: list([summary(1)], { failure: { code: 'rate-limited', message: 'slow down' } }), authored: failedList('unauthenticated'), }), host({ involved: failedList('unavailable'), authored: failedList('unavailable') }, { host: 'ghe.example' }), - ), false) + ), false, null) expect(urls(sections)).toEqual({ authored: null, involved: ['https://github.com/octo/demo/pull/1'] }) - expect(sections.map(section => section.failure)).toEqual([ - { host: 'github.com', forge: 'github', failure: { code: 'unauthenticated', message: 'down' } }, - { host: 'github.com', forge: 'github', failure: { code: 'rate-limited', message: 'slow down' } }, - ]) - expect(sections[0]).toMatchObject({ total: 0, truncated: false }) + expect(sections[0]).toEqual({ filter: 'authored', items: null, total: 0, truncated: false, pending: false }) }) it('leaves out review requests made only of one of the user\'s teams from the review-requested list when asked', () => { @@ -68,20 +89,23 @@ describe('reviewSections', () => { const direct = summary(2, { viewerRequest: { team: null }, updatedAt: '2026-10-08T00:00:00Z' }) const none = summary(3, { updatedAt: '2026-10-07T00:00:00Z' }) const lists = frame(host({ 'review-requested': list([team, direct, none]), 'authored': list([team]) })) - expect(urls(reviewSections(lists, true))).toEqual({ + expect(urls(reviewSections(lists, true, null))).toEqual({ 'review-requested': ['https://github.com/octo/demo/pull/2', 'https://github.com/octo/demo/pull/3'], 'authored': ['https://github.com/octo/demo/pull/1'], }) - expect(reviewSections(lists, false)[0]?.items).toHaveLength(3) + expect(reviewSections(lists, false, null)[0]?.items).toHaveLength(3) }) - it('offers the title, the number, the repository, and the author to the shared list search', () => { + it('offers the title, the number, the repository, the author, and the host to the shared list search', () => { const parser = summary(11, { title: 'Fix the Parser' }) const widgets = inRepository(22, 'Acme', 'Widgets', { title: 'Tidy up' }) const mona = summary(33, { title: 'Docs', author: { login: 'Mona', avatarUrl: null, bot: true } }) const hidden = summary(44, { title: 'Hidden author', author: null }) - const lists = frame(host({ involved: list([parser, widgets, mona, hidden]) })) - const [section] = reviewSections(lists, false) + const elsewhere = summary(55, { title: 'Elsewhere' }) + const lists = frame( + host({ involved: list([parser, widgets, mona, hidden]) }), host({ involved: list([elsewhere]) }, { forge: 'gitlab', host: 'gitlab.example' }), + ) + const [section] = reviewSections(lists, false, null) const index = new TextSearchIndex(section?.items ?? [], reviewSearchKeys) const search = (query: string): number[] => index.search(query).map(item => item.summary.ref.number) expect(search(' PARSER ')).toEqual([11]) @@ -89,14 +113,54 @@ describe('reviewSections', () => { expect(search('22')).toEqual([22]) expect(search('acme/wid')).toEqual([22]) expect(search('mon')).toEqual([33]) + expect(search('gitlab')).toEqual([55]) + expect(search('github.com')).toEqual([11, 22, 33, 44]) // A fuzzy subsequence from a word start finds a title, as the client search rule lets it. expect(search('tdy')).toEqual([22]) expect(search('fix docs')).toEqual([]) expect(search('zzz')).toEqual([]) - expect(search(' ')).toEqual([11, 22, 33, 44]) + expect(search(' ')).toEqual([11, 22, 33, 44, 55]) // The section keeps every item and the whole list's size; the search only narrows what shows. - expect(section).toMatchObject({ total: 4 }) - expect(section?.items).toHaveLength(4) + expect(section?.total).toBe(5) + expect(section?.items).toHaveLength(5) + }) +}) + +describe('reviewFailures', () => { + it('reports each host whose read failed once, with the first failure among its lists and its sign-in command', () => { + const lists = frame( + host({ + involved: list([summary(1)], { failure: { code: 'rate-limited', message: 'slow down' } }), authored: failedList('unauthenticated'), + }, { signIn: 'gh auth login --hostname github.com' }), + host({ involved: list([summary(2)]) }, { host: 'ghe.example' }), + host({ involved: failedList('unavailable') }, { forge: 'gitlab', host: 'gitlab.example' }), + ) + expect(reviewFailures(undefined, null)).toEqual([]) + expect(reviewFailures(lists, null)).toEqual([ + { forge: 'github', host: 'github.com', failure: { code: 'unauthenticated', message: 'down' }, signIn: 'gh auth login --hostname github.com' }, + { forge: 'gitlab', host: 'gitlab.example', failure: { code: 'unavailable', message: 'down' }, signIn: null }, + ]) + expect(reviewFailures(lists, 'gitlab.example').map(failure => failure.host)).toEqual(['gitlab.example']) + expect(reviewFailures(lists, 'ghe.example')).toEqual([]) + }) +}) + +describe('review scopes', () => { + it('names the repository of a scope and tells two scopes apart by host and repository', () => { + const repository = { host: 'github.com', owner: 'octo', name: 'demo' } + expect(scopeRepository(null)).toBeNull() + expect(scopeRepository({ host: 'github.com' })).toBeNull() + expect(scopeRepository(repository)).toBe(repository) + expect(sameScope(null, null)).toBe(true) + expect(sameScope(null, repository)).toBe(false) + expect(sameScope({ host: 'github.com' }, null)).toBe(false) + expect(sameScope({ host: 'github.com' }, { host: 'github.com' })).toBe(true) + expect(sameScope({ host: 'github.com' }, { host: 'ghe.example' })).toBe(false) + expect(sameScope({ host: 'github.com' }, repository)).toBe(false) + expect(sameScope(repository, { ...repository })).toBe(true) + expect(sameScope(repository, { ...repository, host: 'ghe.example' })).toBe(false) + expect(sameScope(repository, { ...repository, owner: 'acme' })).toBe(false) + expect(sameScope(repository, { ...repository, name: 'other' })).toBe(false) }) }) @@ -111,22 +175,26 @@ describe('reviewListsComplete', () => { }) describe('mergeRepositories', () => { - it('merges lists without duplicates, whatever their case, by owner then name', () => { + it('merges lists without duplicates, whatever their case, by host, then owner, then name', () => { + const on = (host: string, owner: string, name: string): { host: string; owner: string; name: string } => ({ host, owner, name }) expect(mergeRepositories()).toEqual([]) expect(mergeRepositories( - [{ owner: 'octo', name: 'demo' }, { owner: 'acme', name: 'widgets' }], [{ owner: 'Octo', name: 'Demo' }], [{ owner: 'acme', name: 'gears' }], - )).toEqual([{ owner: 'acme', name: 'gears' }, { owner: 'acme', name: 'widgets' }, { owner: 'Octo', name: 'Demo' }]) + [on('github.com', 'octo', 'demo'), on('github.com', 'acme', 'widgets')], [on('github.com', 'Octo', 'Demo')], + [on('gitlab.example', 'acme', 'gears'), on('github.com', 'acme', 'gears')], + )).toEqual([ + on('github.com', 'acme', 'gears'), on('github.com', 'acme', 'widgets'), on('github.com', 'Octo', 'Demo'), on('gitlab.example', 'acme', 'gears'), + ]) }) }) describe('reviewRepositories', () => { - it('lists each repository the lists name once, by owner then name, skipping lists not read yet', () => { + it('lists each repository the lists name once with its host, by host, then owner, then name, skipping lists not read yet', () => { expect(reviewRepositories(undefined)).toEqual([]) const repositories = reviewRepositories(frame( host({ authored: list([summary(1), inRepository(2, 'Octo', 'Demo')]), involved: failedList('unavailable') }), host({ 'review-requested': list([inRepository(3, 'acme', 'widgets')]) }, { host: 'ghe.example' }), )) - expect(repositories).toEqual([{ owner: 'acme', name: 'widgets' }, { owner: 'Octo', name: 'Demo' }]) + expect(repositories).toEqual([{ host: 'ghe.example', owner: 'acme', name: 'widgets' }, { host: 'github.com', owner: 'Octo', name: 'Demo' }]) }) }) @@ -201,7 +269,7 @@ describe('createReviewStore', () => { const store = createReviewStore().create() const { actions } = store expect(store.getSnapshot()).toEqual({ - selected: null, tab: 'summary', listHidden: false, folded: {}, repository: null, repositories: [], query: '', directOnly: false, + selected: null, tab: 'summary', listHidden: false, folded: {}, scope: null, repositories: [], query: '', directOnly: false, conversations: {}, view: 'detailed', unseenQuotes: {}, byTab: {}, }) actions.tabbed('chat') @@ -210,18 +278,20 @@ describe('createReviewStore', () => { actions.tabbed('changes') actions.toggledList() actions.folded('authored') - actions.scopedTo({ owner: 'octo', name: 'demo' }) + actions.scopedTo({ host: 'github.com', owner: 'octo', name: 'demo' }) actions.searched('parser') actions.toggledDirect() expect(store.getSnapshot()).toMatchObject({ - tab: 'changes', listHidden: true, folded: { authored: true }, repository: { owner: 'octo', name: 'demo' }, query: 'parser', + tab: 'changes', listHidden: true, folded: { authored: true }, scope: { host: 'github.com', owner: 'octo', name: 'demo' }, query: 'parser', directOnly: true, }) actions.folded('authored') actions.toggledList() actions.toggledDirect() + actions.scopedTo({ host: 'gitlab.example' }) + expect(store.getSnapshot().scope).toEqual({ host: 'gitlab.example' }) actions.scopedTo(null) - expect(store.getSnapshot()).toMatchObject({ listHidden: false, folded: { authored: false }, repository: null, directOnly: false }) + expect(store.getSnapshot()).toMatchObject({ listHidden: false, folded: { authored: false }, scope: null, directOnly: false }) const first = brandString('s1') const second = brandString('s2') @@ -238,8 +308,8 @@ describe('createReviewStore', () => { it('records the repositories of every repository\'s lists: a read under way adds to the record, a complete read replaces it', () => { const store = createReviewStore().create() const { actions } = store - const demo = { owner: 'octo', name: 'demo' } - const widgets = { owner: 'acme', name: 'widgets' } + const demo = { host: 'github.com', owner: 'octo', name: 'demo' } + const widgets = { host: 'github.com', owner: 'acme', name: 'widgets' } actions.listed([demo], false) actions.listed([widgets], false) expect(store.getSnapshot().repositories).toEqual([widgets, demo]) @@ -249,8 +319,9 @@ describe('createReviewStore', () => { expect(store.getSnapshot().repositories).toBe(recorded) actions.listed([demo], true) expect(store.getSnapshot().repositories).toEqual([demo]) - actions.listed([{ owner: 'octo', name: 'other' }], true) - expect(store.getSnapshot().repositories).toEqual([{ owner: 'octo', name: 'other' }]) + // The same repository on another host is another repository. + actions.listed([{ ...demo, host: 'ghe.example' }], true) + expect(store.getSnapshot().repositories).toEqual([{ host: 'ghe.example', owner: 'octo', name: 'demo' }]) }) it('shows the list in the view the reader chose', () => { diff --git a/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx index 98c0248adf..371cc7237b 100644 --- a/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-page.client.spec.tsx @@ -34,7 +34,8 @@ import type { ForgeChangeRequestDiff, ForgeDiffFile, ForgeExtensionState, ForgeReviewChangeRequest, ForgeReviewFrame, } from '../src/types.ts' import { entry, ready, ref, snapshot } from './client-fixtures.client.ts' -import { description, fed, frame, host, list, prUrl, reviewed, summary, type Fed } from './review-fixtures.client.ts' +import { description, failedList, fed, frame, host, list, prUrl, reviewed, summary, type Fed } from './review-fixtures.client.ts' +import type { ReviewRepository } from '../src/client/review-page/review-lists.ts' import { reviewThread } from './thread-fixtures.client.ts' const t = makeTranslate(en) @@ -148,8 +149,8 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) { const props: ReviewPageProps = { useLocale: bindSnapshotSelector(createSnapshotStore('en')), usePluginNavigation: bindSnapshotSelector(pluginNavigation), - openLists: vi.fn((scope: string, signal: AbortSignal) => { - const stream = fed(scope, signal) + openLists: vi.fn((repository: ReviewRepository | null, signal: AbortSignal) => { + const stream = fed(repository === null ? '' : `${repository.host} ${repository.owner}/${repository.name}`, signal) lists.push(stream) return stream }), @@ -231,7 +232,7 @@ async function quoteComment(section: HTMLElement, body: string): Promise { describe('ReviewPage lists', () => { it('lists the change requests of every repository beside a placeholder until one is chosen', async () => { const b = renderPage() - expect(b.props.openLists).toHaveBeenCalledWith('', b.list().signal) + expect(b.props.openLists).toHaveBeenCalledWith(null, b.list().signal) expect(b.props.openChangeRequest).not.toHaveBeenCalled() expect(b.view.getByText('Select a change request')).toBeTruthy() b.list().push(frame(host({ authored: list([summary(7)]) }))) @@ -246,9 +247,9 @@ describe('ReviewPage lists', () => { fireEvent.click(b.view.getByRole('button', { name: 'Filter' })) fireEvent.click(within(document.body).getByRole('menuitem', { name: /^Repository/ })) fireEvent.click(within(document.body).getByRole('menuitem', { name: 'octo/demo' })) - expect(b.store.getSnapshot().repository).toEqual({ owner: 'octo', name: 'demo' }) + expect(b.store.getSnapshot().scope).toEqual({ host: 'github.com', owner: 'octo', name: 'demo' }) expect(b.lists[0]?.disposed).toHaveBeenCalledOnce() - expect(b.list().key).toBe('octo/demo') + expect(b.props.openLists).toHaveBeenLastCalledWith({ host: 'github.com', owner: 'octo', name: 'demo' }, b.list().signal) fireEvent.click(b.view.getByRole('button', { name: 'Filter' })) fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Only requests made of me' })) expect(b.store.getSnapshot().directOnly).toBe(true) @@ -280,14 +281,14 @@ describe('ReviewPage lists', () => { // A read under way adds what it has read so far; the settled read is the record. b.list().push({ ...frame(host({ 'review-requested': list([summary(7)]), 'authored': list(null) })), reading: true }) await settle() - expect(b.store.getSnapshot().repositories).toEqual([{ owner: 'octo', name: 'demo' }]) + expect(b.store.getSnapshot().repositories).toEqual([{ host: 'github.com', owner: 'octo', name: 'demo' }]) b.list().push(frame(host({ 'review-requested': list([summary(7)]), 'authored': list([other]) }))) await settle() expect(offered()).toEqual(['All repositories', 'acme/widgets', 'octo/demo']) fireEvent.click(within(document.body).getByRole('menuitem', { name: 'acme/widgets' })) // The chosen repository's lists name only it, before and after its first frame. - expect(b.list().key).toBe('acme/widgets') + expect(b.list().key).toBe('github.com acme/widgets') expect(offered()).toEqual(['All repositories', 'acme/widgets', 'octo/demo']) fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }) fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }) @@ -301,7 +302,30 @@ describe('ReviewPage lists', () => { expect(b.store.getSnapshot().repositories).toHaveLength(2) b.list().push(frame(host({ 'review-requested': list([summary(7)]), 'authored': list([]) }))) await settle() - expect(b.store.getSnapshot().repositories).toEqual([{ owner: 'octo', name: 'demo' }]) + expect(b.store.getSnapshot().repositories).toEqual([{ host: 'github.com', owner: 'octo', name: 'demo' }]) + }) + + it('narrows the lists to one host on the page, without another stream, and offers the settings from a host that failed while they can be opened', async () => { + const b = renderPage() + b.list().push(frame( + host({ 'review-requested': list([summary(7)]) }), + host({ authored: list([summary(8)]) }, { forge: 'gitlab', host: 'gitlab.example' }), + host({ involved: failedList('unauthenticated') }, { forge: 'gitlab', host: 'gitlab.com' }), + )) + await settle() + expect(b.view.getByRole('status').textContent).toBe('Sign in to gitlab.com to list your change requests') + act(() => { b.pluginNavigation.set(true) }) + fireEvent.click(b.view.getByRole('button', { name: 'Open settings' })) + expect(b.props.openHostSettings).toHaveBeenCalledOnce() + + fireEvent.click(b.view.getByRole('button', { name: 'Filter' })) + fireEvent.click(within(document.body).getByRole('menuitem', { name: /^Repository/ })) + fireEvent.click(within(document.body).getByRole('menuitem', { name: 'gitlab.example' })) + expect(b.store.getSnapshot().scope).toEqual({ host: 'gitlab.example' }) + expect(b.lists).toHaveLength(1) + expect(b.lists[0]?.disposed).not.toHaveBeenCalled() + expect([...b.view.container.querySelectorAll('[data-forge-review-item]')].map(item => item.getAttribute('data-forge-review-item'))).toEqual([prUrl(8)]) + expect(b.view.queryByRole('status')).toBeNull() }) it('reads every list again once at a time, showing the refresh until it settles', async () => { @@ -330,9 +354,9 @@ describe('ReviewPage lists', () => { b.list().push(frame(host({ authored: list([summary(7)]) }))) await settle() const meta = (): string | null | undefined => b.view.container.querySelector(`.${css.itemMeta}`)?.textContent - expect(meta()).toBe('#7·octo·5 min ago') + expect(meta()).toBe('#7·octo5min') act(() => { vi.advanceTimersByTime(60_000) }) - expect(meta()).toBe('#7·octo·6 min ago') + expect(meta()).toBe('#7·octo6min') }) }) diff --git a/packages/experimental/client-ui-forge/tests/review-page.host.spec.ts b/packages/experimental/client-ui-forge/tests/review-page.host.spec.ts index c334704a14..03e6d87c0a 100644 --- a/packages/experimental/client-ui-forge/tests/review-page.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review-page.host.spec.ts @@ -535,7 +535,7 @@ describe('forgePanel review lists', () => { const { provider, registration } = await registerViewer(opened) const read = await lists.until(frame => !frame.reading && frame.hosts[0]?.viewer === 'mona') const listed = { items: [], total: 2, fetchedAt: ANY_TIME, failure: null } - expect(read.hosts).toEqual([{ forge: 'viewer', host: 'view.test', viewer: 'mona', lists: { 'review-requested': listed, authored: listed } }]) + expect(read.hosts).toEqual([{ forge: 'viewer', host: 'view.test', viewer: 'mona', signIn: null, lists: { 'review-requested': listed, authored: listed } }]) expect(provider.queries).toEqual([ { host: 'view.test', filter: 'review-requested', repository: null, limit: 10 }, { host: 'view.test', filter: 'authored', repository: null, limit: 10 }, @@ -552,7 +552,7 @@ describe('forgePanel review lists', () => { const { provider } = await registerViewer(opened) provider.list = () => Promise.reject(new Error('gh crashed')) const warn = vi.spyOn(opened.ctx.logger, 'warn').mockImplementation(() => undefined) - const lists = streamed(stop => opened.ctx.forgePanel.reviewLists({ owner: 'octo', name: 'demo' }, stop)) + const lists = streamed(stop => opened.ctx.forgePanel.reviewLists({ host: 'view.test', owner: 'octo', name: 'demo' }, stop)) const failed = await lists.until(frame => !frame.reading && (frame.hosts[0]?.lists.authored?.failure ?? null) !== null) expect(failed.hosts[0]?.lists['review-requested']?.failure).toEqual({ code: 'unavailable', message: 'gh crashed' }) @@ -560,6 +560,21 @@ describe('forgePanel review lists', () => { expect(warn).toHaveBeenCalledWith('forge-panel: reading a review list failed: Error: gh crashed') }) + it('names the provider\'s sign-in command beside the lists of a host that refuses the viewer', async () => { + const opened = await page() + const { provider } = await registerViewer(opened) + provider.list = () => Promise.resolve({ code: 'unauthenticated', message: 'sign in' }) + const lists = streamed(stop => opened.ctx.forgePanel.reviewLists(null, stop)) + + // A provider that names no command leaves the host without one. + const unnamed = await lists.until(frame => !frame.reading && (frame.hosts[0]?.lists.authored?.failure ?? null) !== null) + expect(unnamed.hosts[0]?.signIn).toBeNull() + provider.readiness = () => Promise.resolve({ state: 'unauthenticated', message: 'sign in', signIn: { command: 'viewer auth login' } }) + await opened.ctx.forgePanel.reviewRefresh(signal) + const refused = await lists.until(frame => !frame.reading && (frame.hosts[0]?.signIn ?? null) !== null) + expect(refused.hosts[0]).toEqual(expect.objectContaining({ host: 'view.test', viewer: null, signIn: 'viewer auth login' })) + }) + it('streams the review request count from count reads and from lists of every repository', async () => { const opened = await page() const { registration } = await registerViewer(opened) diff --git a/packages/experimental/client-ui-forge/tests/viewer-lists.host.spec.ts b/packages/experimental/client-ui-forge/tests/viewer-lists.host.spec.ts index 0d52cbbf61..c6049c2755 100644 --- a/packages/experimental/client-ui-forge/tests/viewer-lists.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/viewer-lists.host.spec.ts @@ -22,8 +22,6 @@ function summary(number: number, repository = 'demo'): ChangeRequestSummary { reviewDecision: 'none', viewerReview: null, viewerRequest: null, - closingIssues: [], - closingIssuesTruncated: false, updatedAt: '2026-11-10T09:00:00Z', } } @@ -32,9 +30,11 @@ function summary(number: number, repository = 'demo'): ChangeRequestSummary { interface RegistryFake extends ViewerListSources { readonly calls: ForgeViewerQuery[] readonly counts: string[] + readonly signIns: string[] readonly reported: unknown[] answer: (query: ForgeViewerQuery, signal: AbortSignal) => Promise - answerCount: (host: string) => Promise | ForgeFailure> + answerCount: (host: string, signal: AbortSignal) => Promise | ForgeFailure> + answerSignIn: (host: string, signal: AbortSignal) => Promise sourcesNow: ForgeViewerSource[] } @@ -42,20 +42,26 @@ function registry(sources: ForgeViewerSource[]): RegistryFake { const fake: RegistryFake = { calls: [], counts: [], + signIns: [], reported: [], sourcesNow: sources, answer: async (query: ForgeViewerQuery): Promise => await Promise.resolve({ viewer: 'octo', items: [summary(query.filter === 'authored' ? 2 : 1)], total: 3 }), answerCount: async (): Promise | ForgeFailure> => await Promise.resolve(new Map([['review-requested', 7]])), + answerSignIn: async host => await Promise.resolve(`gh auth login --hostname ${host}`), sources: () => fake.sourcesNow, list: async (_forge: string, query: ForgeViewerQuery, signal: AbortSignal) => { fake.calls.push(query) return await fake.answer(query, signal) }, - count: async (_forge: string, host: string) => { + count: async (_forge: string, host: string, signal: AbortSignal) => { fake.counts.push(host) - return await fake.answerCount(host) + return await fake.answerCount(host, signal) + }, + signIn: async (_forge: string, host: string, signal: AbortSignal) => { + fake.signIns.push(host) + return await fake.answerSignIn(host, signal) }, report: (error: unknown) => { fake.reported.push(error) }, } @@ -64,6 +70,14 @@ function registry(sources: ForgeViewerSource[]): RegistryFake { const github: ForgeViewerSource = { forge: 'github', hosts: ['github.com'], filters: ALL, maxItems: 50 } +const gitlab: ForgeViewerSource = { forge: 'gitlab', hosts: ['gitlab.example'], filters: ALL, maxItems: 10 } + +const refused = async (): Promise => await Promise.resolve({ code: 'unauthenticated', message: 'sign in' }) + +/** A read that settles only when its signal aborts, as a provider's read does. */ +const pending = async (_host: string, signal: AbortSignal): Promise => + await new Promise((_resolve, reject) => { signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) }) + const hubs: ViewerLists[] = [] afterEach(async () => { @@ -136,9 +150,9 @@ describe('ViewerLists', () => { const fake = registry([github]) const lists = hub(fake, { ...timing, listIntervalMs: 60_000 }) const controller = new AbortController() - const read = follow(lists.lists({ owner: 'octo', name: 'demo' }, controller.signal)) + const read = follow(lists.lists({ host: 'github.com', owner: 'octo', name: 'demo' }, controller.signal)) await until(read, frame => !frame.reading && frame.hosts[0]?.lists.involved?.items !== null) - fake.answer = async () => await Promise.resolve({ code: 'unauthenticated', message: 'sign in' }) + fake.answer = refused fake.calls.length = 0 lists.refresh() const failed = await until(read, frame => (frame.hosts[0]?.lists.involved?.failure ?? null) !== null) @@ -194,7 +208,7 @@ describe('ViewerLists', () => { await read.done }) - it('shares one reader per repository scope, waits between rounds, backs off after failures, and stops with its last stream', async () => { + it('shares one reader per repository scope, reads a failing host again later each time, and stops with its last stream', async () => { vi.useFakeTimers() const fake = registry([github]) fake.answer = async () => await Promise.resolve({ code: 'not-found', message: 'gone' }) @@ -223,6 +237,152 @@ describe('ViewerLists', () => { expect(fake.calls).toHaveLength(15) }) + it('keeps the cadence of the other hosts while it reads a failing host again later each time, and reads every host on a refresh', async () => { + vi.useFakeTimers() + const fake = registry([github, { ...gitlab, filters: new Set(['authored']) }]) + fake.answer = async query => await Promise.resolve(query.host === 'gitlab.example' + ? { code: 'unavailable', message: 'down' } : { viewer: 'octo', items: [], total: 0 }) + const lists = hub(fake) + const controller = new AbortController() + const read = follow(lists.lists(null, controller.signal)) + const reads = (): number[] => ['github.com', 'gitlab.example'].map(host => fake.calls.filter(call => call.host === host).length) + + await vi.advanceTimersByTimeAsync(0) + expect(reads()).toEqual([3, 1]) + // github.com is read every second; gitlab.example after two seconds, then four, then the largest delay of five. + await vi.advanceTimersByTimeAsync(1_000) + expect(reads()).toEqual([6, 1]) + await vi.advanceTimersByTimeAsync(1_000) + expect(reads()).toEqual([9, 2]) + await vi.advanceTimersByTimeAsync(3_999) + expect(reads()).toEqual([18, 2]) + await vi.advanceTimersByTimeAsync(1) + expect(reads()).toEqual([21, 3]) + lists.refresh() + await vi.advanceTimersByTimeAsync(0) + expect(reads()).toEqual([24, 4]) + controller.abort() + await read.done + }) + + it('reads a repository scope only on the host the repository is on, whatever case names it', async () => { + vi.useFakeTimers() + const fake = registry([github, gitlab]) + const lists = hub(fake) + const controller = new AbortController() + const read = follow(lists.lists({ host: 'GitLab.Example', owner: 'group/sub', name: 'app' }, controller.signal)) + await vi.advanceTimersByTimeAsync(0) + expect(read.frames.at(-1)?.hosts.map(host => host.host)).toEqual(['gitlab.example']) + expect(fake.calls.map(call => [call.host, call.filter, call.repository])).toEqual([ + ['gitlab.example', 'review-requested', { owner: 'group/sub', name: 'app' }], + ['gitlab.example', 'authored', { owner: 'group/sub', name: 'app' }], + ['gitlab.example', 'involved', { owner: 'group/sub', name: 'app' }], + ]) + controller.abort() + await read.done + }) + + it('keeps the sign-in command of a host that refuses the viewer, without asking for it again, until a read succeeds', async () => { + vi.useFakeTimers() + const fake = registry([github]) + const accepted = fake.answer + fake.answer = refused + const lists = hub(fake) + const controller = new AbortController() + const read = follow(lists.lists(null, controller.signal)) + + await vi.advanceTimersByTimeAsync(0) + expect(read.frames.at(-1)?.hosts[0]).toEqual(expect.objectContaining({ signIn: 'gh auth login --hostname github.com', viewer: null })) + lists.refresh() + await vi.advanceTimersByTimeAsync(0) + expect(fake.signIns).toEqual(['github.com']) + fake.answer = accepted + lists.refresh() + await vi.advanceTimersByTimeAsync(0) + expect(read.frames.at(-1)?.hosts[0]).toEqual(expect.objectContaining({ signIn: null, viewer: 'octo' })) + controller.abort() + await read.done + }) + + it('lists a refused host without a sign-in command when its provider names none or cannot be asked', async () => { + vi.useFakeTimers() + const fake = registry([github]) + fake.answer = refused + fake.answerSignIn = async () => await Promise.resolve(null) + const lists = hub(fake) + const controller = new AbortController() + const read = follow(lists.lists(null, controller.signal)) + + await vi.advanceTimersByTimeAsync(0) + expect(read.frames.at(-1)?.hosts[0]?.signIn).toBeNull() + fake.answerSignIn = async () => await Promise.reject(new Error('no provider')) + lists.refresh() + await vi.advanceTimersByTimeAsync(0) + expect(read.frames.at(-1)?.hosts[0]?.signIn).toBeNull() + expect(fake.signIns).toEqual(['github.com', 'github.com']) + expect(fake.reported).toEqual([new Error('no provider')]) + controller.abort() + await read.done + }) + + it('ends a stream whose sign-in command or count is still being read, without recording or reporting that read', async () => { + vi.useFakeTimers() + const fake = registry([github]) + fake.answer = refused + fake.answerSignIn = pending + fake.answerCount = pending + const lists = hub(fake) + const listing = new AbortController() + const counting = new AbortController() + const read = follow(lists.lists(null, listing.signal)) + const counts = follow(lists.count(counting.signal)) + await vi.advanceTimersByTimeAsync(0) + expect(fake.signIns).toEqual(['github.com']) + expect(fake.counts).toEqual(['github.com']) + listing.abort() + counting.abort() + await Promise.all([read.done, counts.done]) + expect(read.frames.at(-1)?.hosts[0]?.signIn).toBeNull() + expect(counts.frames).toEqual([{ reviewRequested: null }]) + expect(fake.reported).toEqual([]) + }) + + it('lists a host whose provider offers no list with no lists and reads nothing on it', async () => { + vi.useFakeTimers() + const fake = registry([{ ...gitlab, filters: new Set() }]) + const lists = hub(fake) + const controller = new AbortController() + const read = follow(lists.lists(null, controller.signal)) + await vi.advanceTimersByTimeAsync(0) + expect(read.frames.at(-1)).toEqual({ hosts: [{ forge: 'gitlab', host: 'gitlab.example', viewer: null, signIn: null, lists: {} }], reading: false }) + expect(fake.calls).toEqual([]) + controller.abort() + await read.done + }) + + it('reads the count of a failing host again later each time while the other hosts keep their cadence', async () => { + vi.useFakeTimers() + const fake = registry([github, gitlab]) + fake.answerCount = async host => await Promise.resolve(host === 'gitlab.example' + ? { code: 'unavailable', message: 'down' } : new Map([['review-requested', 7]])) + const lists = hub(fake) + const controller = new AbortController() + const counts = follow(lists.count(controller.signal)) + + await vi.advanceTimersByTimeAsync(0) + expect(fake.counts).toEqual(['github.com', 'gitlab.example']) + expect(counts.frames.at(-1)).toEqual({ reviewRequested: 7 }) + await vi.advanceTimersByTimeAsync(2_000) + expect(fake.counts).toEqual(['github.com', 'gitlab.example', 'github.com']) + await vi.advanceTimersByTimeAsync(2_000) + expect(fake.counts).toEqual(['github.com', 'gitlab.example', 'github.com', 'github.com', 'gitlab.example']) + lists.refresh() + await vi.advanceTimersByTimeAsync(0) + expect(fake.counts).toHaveLength(7) + controller.abort() + await counts.done + }) + it('counts review requests from its own reads and from lists of every repository', async () => { vi.useFakeTimers() const fake = registry([github, { forge: 'other', hosts: ['other.example'], filters: new Set(['authored']), maxItems: 5 }]) @@ -268,7 +428,7 @@ describe('ViewerLists', () => { }) it('forgets hosts whose provider left, publishes that, and reads the hosts that remain', async () => { - const fake = registry([github, { forge: 'gitlab', hosts: ['gitlab.example'], filters: ALL, maxItems: 10 }]) + const fake = registry([github, gitlab]) const lists = hub(fake) const controller = new AbortController() const read = follow(lists.lists(null, controller.signal)) diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index b85d0cacdd..a1075b543f 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: c386b3621943cafe - zh: 1156f07ba0aee6bc + en: e8f12bb7632f5b73 + zh: 42405d1612eac455 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: ed8edec5c90cc1eb zh: e3a5b74f75dfc17d diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 0f1cb5c9ce..8a9ed1a22d 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -64,7 +64,7 @@ Every status read also reads the overview of each pull request: up to 25 review `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. -`viewer` offers the `review-requested`, `authored`, and `involved` lists on every configured host, up to `maxViewerItems` (default 50) pull requests per read. `listForViewer` reads one list through one GraphQL `search` of open pull requests in unarchived repositories, most recently updated first: `review-requested:@me`, which also matches a request to one of the user's teams, `author:@me`, or `involves:@me -author:@me -review-requested:@me`, so the lists share no pull request; a repository adds `repo:/`, and a name that is not a valid owner or repository segment returns `not-found` without a request. GitHub answers one document that searches several lists with a gateway error, so each list is its own request. Each item carries the viewer's latest submitted review, the review request that asks the viewer or one of the viewer's teams, the head commit's combined check state, and up to three closing issues; results that are not pull requests are left out. `countForViewer` reads every list's `issueCount` in one request. Search reads a search index, so a pull request can appear in or leave a list some minutes after the change. `readDescription` reads `body`, `bodyHTML`, `createdAt`, and up to 100 labels in one GraphQL query. On a private repository an uploaded image's Markdown address, `https:///user-attachments/assets/`, answers only with the user's GitHub session, while `bodyHTML` names the same upload at a signed `private-user-images` address that loads without one for five minutes; `images` maps each Markdown address to the signed address of the same upload, and `imagesExpireAt` is the earliest `exp` of their tokens. `bodyHTML` is read for these addresses only. +`viewer` offers the `review-requested`, `authored`, and `involved` lists on every configured host, up to `maxViewerItems` (default 50) pull requests per read. `listForViewer` reads one list through one GraphQL `search` of open pull requests in unarchived repositories, most recently updated first: `review-requested:@me`, which also matches a request to one of the user's teams, `author:@me`, or `involves:@me -author:@me -review-requested:@me`, so the lists share no pull request; a repository adds `repo:/`, and a name that is not a valid owner or repository segment returns `not-found` without a request. GitHub answers one document that searches several lists with a gateway error, so each list is its own request. Each item carries the viewer's latest submitted review, the review request that asks the viewer or one of the viewer's teams, and the head commit's combined check state; results that are not pull requests are left out. `countForViewer` reads every list's `issueCount` in one request. Search reads a search index, so a pull request can appear in or leave a list some minutes after the change. `readDescription` reads `body`, `bodyHTML`, `createdAt`, and up to 100 labels in one GraphQL query. On a private repository an uploaded image's Markdown address, `https:///user-attachments/assets/`, answers only with the user's GitHub session, while `bodyHTML` names the same upload at a signed `private-user-images` address that loads without one for five minutes; `images` maps each Markdown address to the signed address of the same upload, and `imagesExpireAt` is the earliest `exp` of their tokens. `bodyHTML` is read for these addresses only. ----- diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index b1f55a9295..26f47d2c44 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -64,7 +64,7 @@ pull request 处于打开状态、不是草稿、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 的原因。 -`viewer` 在每个已配置主机上提供 `review-requested`、`authored` 与 `involved` 三个列表,每次读取最多 `maxViewerItems`(默认 50)个拉取请求。`listForViewer` 用一次 GraphQL `search` 读取一个列表:未归档仓库中打开的拉取请求,按最近更新在前;三个列表的限定词分别为 `review-requested:@me`(也匹配请求给用户所在团队的评审)、`author:@me` 与 `involves:@me -author:@me -review-requested:@me`,因此互不重叠;限定仓库时追加 `repo:/`,owner 或仓库名不是合法片段时不发请求,直接返回 `not-found`。GitHub 对在一个文档里搜索多个列表的请求返回网关错误,所以每个列表单独请求。每项带有当前用户最近提交的评审、请求当前用户或其所在团队评审的那条请求、head 提交的检查汇总,以及最多三个会关闭的 issue;不是拉取请求的结果被忽略。`countForViewer` 在一次请求中读取每个列表的 `issueCount`。search 读的是搜索索引,所以拉取请求在变化后可能要过几分钟才进入或离开列表。`readDescription` 用一次 GraphQL 查询读取 `body`、`bodyHTML`、`createdAt` 与最多 100 个标签。私有仓库中,上传图片在 Markdown 里的地址 `https:///user-attachments/assets/` 只在带有用户 GitHub 会话时才返回图片,而 `bodyHTML` 为同一上传给出带签名的 `private-user-images` 地址,五分钟内无需会话即可加载;`images` 把每个 Markdown 地址映射到同一上传的签名地址,`imagesExpireAt` 为这些令牌中最早的 `exp`。读取 `bodyHTML` 只为得到这些地址。 +`viewer` 在每个已配置主机上提供 `review-requested`、`authored` 与 `involved` 三个列表,每次读取最多 `maxViewerItems`(默认 50)个拉取请求。`listForViewer` 用一次 GraphQL `search` 读取一个列表:未归档仓库中打开的拉取请求,按最近更新在前;三个列表的限定词分别为 `review-requested:@me`(也匹配请求给用户所在团队的评审)、`author:@me` 与 `involves:@me -author:@me -review-requested:@me`,因此互不重叠;限定仓库时追加 `repo:/`,owner 或仓库名不是合法片段时不发请求,直接返回 `not-found`。GitHub 对在一个文档里搜索多个列表的请求返回网关错误,所以每个列表单独请求。每项带有当前用户最近提交的评审、请求当前用户或其所在团队评审的那条请求,以及 head 提交的检查汇总;不是拉取请求的结果被忽略。`countForViewer` 在一次请求中读取每个列表的 `issueCount`。search 读的是搜索索引,所以拉取请求在变化后可能要过几分钟才进入或离开列表。`readDescription` 用一次 GraphQL 查询读取 `body`、`bodyHTML`、`createdAt` 与最多 100 个标签。私有仓库中,上传图片在 Markdown 里的地址 `https:///user-attachments/assets/` 只在带有用户 GitHub 会话时才返回图片,而 `bodyHTML` 为同一上传给出带签名的 `private-user-images` 地址,五分钟内无需会话即可加载;`images` 把每个 Markdown 地址映射到同一上传的签名地址,`imagesExpireAt` 为这些令牌中最早的 `exp`。读取 `bodyHTML` 只为得到这些地址。 ----- diff --git a/packages/experimental/forge-github/src/graphql.ts b/packages/experimental/forge-github/src/graphql.ts index c28cab0c9e..c5f1591772 100644 --- a/packages/experimental/forge-github/src/graphql.ts +++ b/packages/experimental/forge-github/src/graphql.ts @@ -142,8 +142,8 @@ export interface SnapshotPages { const actorSchema = z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }) -/** The closing issues references of a pull request, the snapshot's and a viewer list item's. */ -export const closingIssuesSchema = z.object({ +/** The closing issues references of a pull request snapshot. */ +const closingIssuesSchema = z.object({ totalCount: z.number().int().nonnegative(), nodes: z.array(z.object({ number: z.number().int().positive(), diff --git a/packages/experimental/forge-github/src/viewer.ts b/packages/experimental/forge-github/src/viewer.ts index 6371c017f0..38d90e6820 100644 --- a/packages/experimental/forge-github/src/viewer.ts +++ b/packages/experimental/forge-github/src/viewer.ts @@ -5,15 +5,12 @@ import type { } from '@deepseek-ai/dsh-experimental-forge' import { z } from 'zod' import type { GraphqlReader } from './commits.ts' -import { checksRollup, closingIssuesSchema, reviewDecision, VERDICTS } from './graphql.ts' +import { checksRollup, reviewDecision, VERDICTS } from './graphql.ts' import { isSegment } from './urls.ts' /** The lists GitHub search reads, each the same search the GitHub pull request page offers. */ export const VIEWER_FILTERS: ReadonlySet = new Set(['review-requested', 'authored', 'involved']) -/** Most closing issues one list item names. */ -const CLOSING_ISSUES = 3 - /** * Search qualifiers of each list. `involved` leaves out the other two lists, so the three never share a pull request; * `review-requested:@me` also matches a request to one of the user's teams. @@ -29,8 +26,7 @@ const ROW_FIELDS = `number title url isDraft updatedAt headRefOid reviewDecision author { __typename login avatarUrl } commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } viewerLatestReview { state commit { oid } } - viewerLatestReviewRequest { requestedReviewer { __typename ... on Team { combinedSlug } } } - closingIssuesReferences(first: ${CLOSING_ISSUES}) { totalCount nodes { number title state url repository { name owner { login } } } }` + viewerLatestReviewRequest { requestedReviewer { __typename ... on Team { combinedSlug } } }` /** One page of one list with the signed-in user; variables `q` and the integer `first`. */ export const VIEWER_LIST_QUERY = `query($q: String!, $first: Int!) { @@ -63,7 +59,6 @@ const rowSchema = z.object({ viewerLatestReviewRequest: z.object({ requestedReviewer: z.object({ __typename: z.string(), combinedSlug: z.string().optional() }).nullable(), }).nullable(), - closingIssuesReferences: closingIssuesSchema, }) const listSchema = z.object({ @@ -168,18 +163,6 @@ function summaryOf(host: string, row: z.infer): ChangeRequestS reviewDecision: reviewDecision(row.reviewDecision), viewerReview: review === null || verdict === undefined ? null : { verdict, reviewedSha: review.commit?.oid ?? null }, viewerRequest: reviewer == null ? null : { team: reviewer.__typename === 'Team' ? reviewer.combinedSlug ?? null : null }, - closingIssues: row.closingIssuesReferences.nodes.flatMap((issue) => { - const { owner: { login: issueOwner }, name: issueName } = issue.repository - if (!isSegment(issueOwner) || !isSegment(issueName)) return [] - return [{ - repository: { forge: 'github', host, owner: issueOwner, name: issueName }, - number: issue.number, - title: issue.title, - state: issue.state === 'OPEN' ? 'open' as const : 'closed' as const, - url: issue.url, - }] - }), - closingIssuesTruncated: row.closingIssuesReferences.totalCount > row.closingIssuesReferences.nodes.length, updatedAt: row.updatedAt, } } diff --git a/packages/experimental/forge-github/tests/viewer.spec.ts b/packages/experimental/forge-github/tests/viewer.spec.ts index 6f67152256..1389be1210 100644 --- a/packages/experimental/forge-github/tests/viewer.spec.ts +++ b/packages/experimental/forge-github/tests/viewer.spec.ts @@ -40,7 +40,6 @@ function row(number: number, overrides: Record = {}): Record { it('reads one list through one search on the queried host and maps each pull request', async () => { const gh = fakeGh(() => output(listBody([ - row(8225, { - closingIssuesReferences: { - totalCount: 4, - nodes: [ - { number: 8224, title: 'Identify the client', state: 'OPEN', url: 'https://github.com/octo/demo/issues/8224', repository: { name: 'demo', owner: { login: 'octo' } } }, - { number: 9, title: 'Closed elsewhere', state: 'CLOSED', url: 'https://github.com/octo/other/issues/9', repository: { name: 'other', owner: { login: 'octo' } } }, - { number: 10, title: 'Bad repository', state: 'OPEN', url: 'https://github.com/x/y/issues/10', repository: { name: 'a b', owner: { login: 'x' } } }, - ], - }, - }), + row(8225), row(7155, { isDraft: true, reviewDecision: 'CHANGES_REQUESTED', @@ -114,11 +104,6 @@ describe('GitHub viewer lists', () => { reviewDecision: 'none', viewerReview: null, viewerRequest: { team: null }, - closingIssues: [ - { repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 8224, title: 'Identify the client', state: 'open', url: 'https://github.com/octo/demo/issues/8224' }, - { repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'other' }, number: 9, title: 'Closed elsewhere', state: 'closed', url: 'https://github.com/octo/other/issues/9' }, - ], - closingIssuesTruncated: true, updatedAt: '2026-11-10T09:29:00Z', }, expect.objectContaining({ @@ -128,7 +113,6 @@ describe('GitHub viewer lists', () => { reviewDecision: 'changes-requested', viewerReview: { verdict: 'changes-requested', reviewedSha: '2'.repeat(40) }, viewerRequest: { team: 'octo/core' }, - closingIssuesTruncated: false, }), expect.objectContaining({ title: 'Change 6', author: null, viewerReview: null, viewerRequest: null }), expect.objectContaining({ title: 'Change 7', viewerReview: { verdict: 'commented', reviewedSha: null }, viewerRequest: { team: null } }), diff --git a/packages/experimental/forge-gitlab/README.i18n.yaml b/packages/experimental/forge-gitlab/README.i18n.yaml index c3e91afadd..ff0fa2c4ed 100644 --- a/packages/experimental/forge-gitlab/README.i18n.yaml +++ b/packages/experimental/forge-gitlab/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-forge-gitlab/use-this-package: - en: 5868c7487e1d6eff - zh: 292b016cf57a05d4 + en: ed5f9195305ccb8d + zh: 69ec9d6052b55729 /deepseek-ai-dsh-forge-gitlab/understand-the-implementation: - en: 30b70996dfeb92c9 - zh: 6ef0f4b3bbe75ffa + en: f48c5a9988f99e95 + zh: 87c0569c6a6fe4ee /deepseek-ai-dsh-forge-gitlab/further-exploration: en: c281ce669b4d88f8 zh: 520e7de0da749b8e @@ -30,8 +30,8 @@ en: 26b946af4b742e17 zh: 00b34f0721ac72f6 /deepseek-ai-dsh-forge-gitlab/known-limitations-and-deferred-work: - en: 97434ca5954ad014 - zh: b1766f724762e3d1 + en: 44b142b96fef75ee + zh: 397863435027dde1 /deepseek-ai-dsh-forge-gitlab/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/forge-gitlab/README.md b/packages/experimental/forge-gitlab/README.md index 838e019b4b..ee04ac4f6c 100644 --- a/packages/experimental/forge-gitlab/README.md +++ b/packages/experimental/forge-gitlab/README.md @@ -52,6 +52,8 @@ Review writes read the newest diff version first and refuse with `stale` unless `rerunChecks` retries the head pipeline once it has failed jobs and none pending. `requestReviews` adds new reviewers with `mergeRequestSetReviewers` and asks current ones again with `mergeRequestReviewerRereview`; a merge request that takes one reviewer, as on GitLab's free tier, refuses a second, and GitLab has no team reviewers. `reviewerCandidates` lists at most 20 of GitLab's matches among the users who can see the project, never the author, none suggested. `updateBranch` only rebases: GitLab names no head in a rebase request, so the provider reads the head first and refuses a moved one with `stale`, and GitLab rebases in the background once it accepted the request. Writes are never retried: a 4xx answer is a refusal, `failed`, except HTTP 401, `unauthenticated`, and HTTP 409 to a merge or an approval, `stale`; a 5xx answer, an answer without a status, and a write past `timeoutMs` are `unknown`. +`viewer` offers the `review-requested`, `authored`, and `involved` lists on every configured host, up to 100 merge requests per read, GitLab's page maximum. `listForViewer` reads one list of open merge requests, most recently updated first, through one GraphQL request to `currentUser`. `review-requested` holds the merge requests that still await the user's review, where the user is a reviewer whose state is `UNREVIEWED` or `REVIEW_STARTED`, and `authored` the ones the user wrote. GitLab has no single query for `involved`, so its request reads two connections, merges them by update time, and reports the sum of their sizes as the total: the merge requests the user reviewed and did not write, and the ones assigned to the user who neither wrote nor reviews them. These two share no merge request with each other or with the other two lists. A repository limits a read to one project by its full path, and a path with a segment GitLab does not permit returns `not-found` without a request. Each item carries the head pipeline's status as its check outcome and `changes-requested`, `approved`, or `none` as its review decision by the rules of a status read. When the user is among the first 20 reviewers, the user's review state gives the item its review or its review request; every item of `review-requested` names a request. A merge request without commits has no head and is left out of the items, though the total counts it. `countForViewer` reads the sizes of the same four connections in every project through one request. The `involved` list and the counts name the user by username in their requests: the provider keeps the username that the latest viewer read on a host answered as, reads it through one more request when it keeps none, and repeats a read once when its answer names another user, as after `glab` signed in as someone else. An answer without a user is `unauthenticated`. `readDescription` reads `description`, `createdAt`, up to 100 labels, and the project's id in one GraphQL query. GitLab writes an upload in Markdown without host or project, as `/uploads/<32 hex digits>/`, and serves it at `https:///-/project//uploads/…`; where a Markdown link or image or an HTML `src` names an upload, the description returns that address, as GitLab's own rendering does. A label's `#rrggbb` color is returned without `#`, and `images` maps nothing. + ----- @@ -66,7 +68,7 @@ Each status query reads several merge requests under aliases with their project |---|---| | [`src/index.ts`](src/index.ts) | Configuration validation, and provider and command rule registration | | [`src/commands.ts`](src/commands.ts) | The `glab` command rule that forge-session binds merge requests by | -| [`src/provider.ts`](src/provider.ts) | URL mapping, batching, closing issue and diff caches, and actions | +| [`src/provider.ts`](src/provider.ts) | URL mapping, batching, closing issue and diff caches, the signed-in username kept per host, and actions | | [`src/api.ts`](src/api.ts) | REST, GraphQL, and write requests through `glab api`, and failure mapping | | [`src/status.ts`](src/status.ts) | Status query construction and snapshot mapping | | [`src/diff.ts`](src/diff.ts) | Version-pinned patches, comparisons, merge bases, and file texts | @@ -75,6 +77,8 @@ Each status query reads several merge requests under aliases with their project | [`src/writes.ts`](src/writes.ts) | Review writes and submissions through discussions, draft notes, and approvals | | [`src/position.ts`](src/position.ts) | Diff note positions and line codes from a version's file diff | | [`src/overview.ts`](src/overview.ts) | Pipeline retries, review requests, reviewer candidates, and rebases | +| [`src/viewer.ts`](src/viewer.ts) | Viewer list, count, and username queries, and summary mapping | +| [`src/description.ts`](src/description.ts) | Description and label reads, and the addresses of uploads | | [`src/pool.ts`](src/pool.ts) | Bounded concurrency | | [`src/glab.ts`](src/glab.ts) | Host `glab` execution with environment scrubbing and limits | | [`src/urls.ts`](src/urls.ts) | Remote, merge request, and issue URL parsing, and project path validation | @@ -110,8 +114,10 @@ None. Provider output reaches only host-side watchers. - **Rebase without a head check** — a push between the head read and the rebase request is rebased too, and a rebase GitLab fails in the background is not reported. - **Overview discussions** — discussions that are not on a file count toward `unresolvedThreads` but are not returned as threads. - **Bots and draft times** — comment authors are never marked as bots, and draft notes carry the read's time. +- **Viewer lists** — GitLab has no team review requests, so no list item names a team. `involved` holds the merge requests the user reviewed or is assigned to, not the ones that only mention the user or that the user only commented on. List items carry no reviewed commit, so the review page cannot tell an approval of the head from an older one, and they never report `review-required`, because the lists read no merge status. The list and count queries need a GitLab version whose `reviewRequestedMergeRequests` accepts `reviewStates` and `not`; they work on GitLab 19.5.1, and the oldest version that accepts them is not known. +- **Descriptions** — an upload image of a private project needs a GitLab session and does not load. GitLab's own reference forms, such as `!12`, `#34`, and `@name`, are plain text. - **CE fields only** — the status query reads fields Community Edition has; required approvals, code owners, suggested reviewers, and merged-results pipelines of paid tiers are not read. -- **Rate limits** — every poll costs one GraphQL query per batch plus one REST request per merge request whose update time changed; a review read costs one REST and one GraphQL request per 100 discussions, one request each for the versions, the draft notes, and the approval, and up to two per outdated file not yet cached; a write reads the newest version first, and a comment reads its version's files once. +- **Rate limits** — every poll costs one GraphQL query per batch plus one REST request per merge request whose update time changed; a review read costs one REST and one GraphQL request per 100 discussions, one request each for the versions, the draft notes, and the approval, and up to two per outdated file not yet cached; a write reads the newest version first, and a comment reads its version's files once; a viewer list costs one GraphQL request and the counts cost one, plus one for the username when the `involved` list or the counts are read before any viewer read on the host named it. ### Dev Note diff --git a/packages/experimental/forge-gitlab/README.zh.md b/packages/experimental/forge-gitlab/README.zh.md index 120af9bf69..436fde3fa4 100644 --- a/packages/experimental/forge-gitlab/README.zh.md +++ b/packages/experimental/forge-gitlab/README.zh.md @@ -52,6 +52,8 @@ kind: "package-reference" `rerunChecks` 在 head 流水线有失败作业且没有 pending 作业时重试它。`requestReviews` 用 `mergeRequestSetReviewers` 添加新评审者,用 `mergeRequestReviewerRereview` 再次请求现有评审者;只能有一位评审者的合并请求(如 GitLab 免费版)会拒绝第二位,GitLab 也没有团队评审者。`reviewerCandidates` 在能看到该项目的用户中列出 GitLab 匹配到的最多 20 人,永远不含作者,也都不标记为建议。`updateBranch` 只做变基:GitLab 的变基请求不指明 head,所以提供方先读取 head,head 已变化时以 `stale` 拒绝;GitLab 接受请求后在后台变基。写入从不重试:4xx 答复为拒绝,即 `failed`,但 HTTP 401 为 `unauthenticated`,对合并或批准的 HTTP 409 为 `stale`;5xx 答复、没有状态码的答复和超过 `timeoutMs` 的写入为 `unknown`。 +`viewer` 在每个已配置主机上提供 `review-requested`、`authored` 与 `involved` 三个列表,每次读取最多 100 个合并请求,即 GitLab 的分页上限。`listForViewer` 用一次发往 `currentUser` 的 GraphQL 请求读取一个列表:打开状态的合并请求,按最近更新在前。`review-requested` 是仍在等待当前用户评审的合并请求,即当前用户是评审者且状态为 `UNREVIEWED` 或 `REVIEW_STARTED` 的合并请求;`authored` 是当前用户为作者的合并请求。GitLab 没有对应 `involved` 的单个查询,所以它的请求读取两个连接,按更新时间合并,并以两者大小之和作为总数:当前用户评审过且不是其作者的合并请求,以及指派给当前用户、而当前用户既不是作者也不是评审者的合并请求。这两个连接彼此不重叠,也不与另外两个列表重叠。限定仓库时,读取按项目的完整路径限定在一个项目内;路径中有 GitLab 不允许的片段时不发请求,直接返回 `not-found`。每项以 head 流水线的状态作为检查汇总,评审结论按状态读取的规则取 `changes-requested`、`approved` 或 `none`。当前用户在前 20 位评审者之中时,其评审状态决定该项的评审或评审请求;`review-requested` 的每一项都带有评审请求。没有提交的合并请求没有 head,不出现在各项中,但仍计入总数。`countForViewer` 用一次请求读取同样四个连接在所有项目中的大小。`involved` 列表和计数在请求中以用户名指明当前用户:提供方保存主机上最近一次 viewer 读取的答复所对应的用户名,没有保存时多发一次请求读取它;答复对应另一位用户时(例如 `glab` 改以其他账号登录之后),把该读取重复一次。答复中没有用户时为 `unauthenticated`。`readDescription` 用一次 GraphQL 查询读取 `description`、`createdAt`、最多 100 个标签和项目的 id。GitLab 在 Markdown 中写上传文件时不带主机和项目,写成 `/uploads/<32 位十六进制数字>/`,而提供该文件的地址是 `https:///-/project//uploads/…`;Markdown 链接或图片、或 HTML 的 `src` 指向上传文件时,描述返回这个地址,与 GitLab 自己的渲染结果一致。标签的 `#rrggbb` 颜色去掉 `#` 后返回,`images` 不映射任何地址。 + ----- @@ -66,7 +68,7 @@ kind: "package-reference" |---|---| | [`src/index.ts`](src/index.ts) | 配置校验,以及提供方与命令规则注册 | | [`src/commands.ts`](src/commands.ts) | forge-session 据以绑定 merge request 的 `glab` 命令规则 | -| [`src/provider.ts`](src/provider.ts) | URL 映射、分批、关闭 issue 与 diff 缓存,以及操作 | +| [`src/provider.ts`](src/provider.ts) | URL 映射、分批、关闭 issue 与 diff 缓存、按主机保存的当前用户名,以及操作 | | [`src/api.ts`](src/api.ts) | 经 `glab api` 发出的 REST、GraphQL 与写入请求,以及失败映射 | | [`src/status.ts`](src/status.ts) | 状态查询构造与快照映射 | | [`src/diff.ts`](src/diff.ts) | 钉在版本上的补丁、比较、合并基础与文件文本 | @@ -75,6 +77,8 @@ kind: "package-reference" | [`src/writes.ts`](src/writes.ts) | 经讨论、草稿笔记和批准完成的评审写入与提交 | | [`src/position.ts`](src/position.ts) | 由版本的文件 diff 推出 diff 笔记位置与行码 | | [`src/overview.ts`](src/overview.ts) | 流水线重试、评审请求、评审者候选与变基 | +| [`src/viewer.ts`](src/viewer.ts) | viewer 列表、计数与用户名查询,以及摘要映射 | +| [`src/description.ts`](src/description.ts) | 描述与标签读取,以及上传文件的地址 | | [`src/pool.ts`](src/pool.ts) | 有上限的并发 | | [`src/glab.ts`](src/glab.ts) | 在宿主上执行 `glab`,清理环境变量并施加限制 | | [`src/urls.ts`](src/urls.ts) | 远端、合并请求与 issue URL 解析,以及项目路径校验 | @@ -110,8 +114,10 @@ kind: "package-reference" - **变基不校验 head**——在读取 head 与发出变基请求之间的推送也会被变基,GitLab 在后台变基失败时不会报告。 - **概览讨论**——不在文件上的讨论会计入 `unresolvedThreads`,但不会作为讨论返回。 - **机器人与草稿时间**——评论作者从不标记为机器人,草稿笔记带的是读取时间。 +- **viewer 列表**——GitLab 没有团队评审请求,所以列表项从不指明团队。`involved` 包含当前用户评审过或被指派的合并请求,不包含只是提及当前用户、或当前用户只发表过评论的合并请求。列表项不带评审所在的提交,所以评审页无法区分对 head 的批准与对更早提交的批准;列表项也从不报告 `review-required`,因为列表不读取合并状态。列表与计数查询要求 GitLab 版本的 `reviewRequestedMergeRequests` 接受 `reviewStates` 与 `not`;它们在 GitLab 19.5.1 上可用,接受它们的最低版本尚不清楚。 +- **描述**——私有项目的上传图片需要 GitLab 会话,无法加载。GitLab 自己的引用形式(如 `!12`、`#34` 和 `@name`)是纯文本。 - **只读 CE 字段**——状态查询只读取社区版具备的字段;付费版的必需批准、代码所有者、建议的评审者和合并结果流水线都不读取。 -- **速率限制**——每次轮询每批花费一个 GraphQL 查询,每个更新时间变化的合并请求再花费一个 REST 请求;一次评审读取每 100 个讨论花费一个 REST 请求和一个 GraphQL 请求,版本、草稿笔记和批准情况各一个,每个尚未缓存的过期文件最多两个;一次写入先读取最新版本,一条评论只读取一次其版本的文件。 +- **速率限制**——每次轮询每批花费一个 GraphQL 查询,每个更新时间变化的合并请求再花费一个 REST 请求;一次评审读取每 100 个讨论花费一个 REST 请求和一个 GraphQL 请求,版本、草稿笔记和批准情况各一个,每个尚未缓存的过期文件最多两个;一次写入先读取最新版本,一条评论只读取一次其版本的文件;一次 viewer 列表读取花费一个 GraphQL 请求,一次计数花费一个;读取 `involved` 列表或计数时,如果主机上还没有任何 viewer 读取给出过用户名,再为用户名花费一个。 ### 开发备注 diff --git a/packages/experimental/forge-gitlab/src/description.ts b/packages/experimental/forge-gitlab/src/description.ts new file mode 100644 index 0000000000..4b2ed3ffcb --- /dev/null +++ b/packages/experimental/forge-gitlab/src/description.ts @@ -0,0 +1,72 @@ +/** Merge request descriptions through GraphQL, with the uploads they name at the addresses GitLab serves them from. */ + +import type { ChangeRequestDescription, ChangeRequestRef, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import type { GitLabApi } from './api.ts' +import { checkedProject } from './urls.ts' + +/** Most labels one read lists, GitLab's connection page maximum. */ +const LABELS = 100 + +/** One merge request's description, creation time, and labels, with its project's id; variables `path` and `iid` are strings. */ +export const DESCRIPTION_QUERY = `query($path: ID!, $iid: String!) { + project(fullPath: $path) { id mergeRequest(iid: $iid) { description createdAt labels(first: ${LABELS}) { count nodes { title color } } } } +}` + +/** Global id of a project, which ends in the number that names the project in upload addresses. */ +const PROJECT_ID = /^gid:\/\/gitlab\/Project\/\d+$/ + +const descriptionSchema = z.object({ + project: z.object({ + id: z.string().regex(PROJECT_ID), + mergeRequest: z.object({ + description: z.string().nullable(), + createdAt: z.string(), + labels: z.object({ + count: z.number().int().nonnegative(), + nodes: z.array(z.object({ title: z.string(), color: z.string() })), + }), + }).nullable(), + }).nullable(), +}) + +/** + * The start of an upload address as GitLab writes it in Markdown, `/uploads/<32 hex digits>/` without host or + * project, where a Markdown link or image (`](`) or an HTML `src="` names it. + */ +const UPLOAD = /(\]\(|\bsrc=")(\/uploads\/[0-9a-f]{32}\/)/g + +/** A label color as GitLab reports it, `#rrggbb`. */ +const COLOR = /^#([0-9a-f]{6})$/i + +/** + * Read a merge request's description and labels through one request. Upload addresses in the description become the + * ones GitLab's own rendering gives them, `https:///-/project//uploads/…`; an upload of a private + * project answers only with a GitLab session, and `images` maps none. + * @param api - GitLab reads. + * @param ref - merge request. + * @param signal - cancellation of the read. + * @returns the description, or why GitLab did not provide it. + * @throws when the project path or the number of `ref` is not one GitLab can hold. + */ +export async function readDescription( + api: GitLabApi, ref: ChangeRequestRef, signal: AbortSignal, +): Promise { + const path = checkedProject(ref) + const read = await api.graphql(ref.repository.host, DESCRIPTION_QUERY, { path, iid: String(ref.number) }, signal) + if (!read.ok) return read.failure + const parsed = descriptionSchema.safeParse(read.body) + if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitLab response to the description read' } + const { project } = parsed.data + const merge = project?.mergeRequest + if (project === null || merge == null) return { code: 'not-found', message: `merge request ${ref.number} was not found` } + const uploads = `https://${ref.repository.host}/-/project/${project.id.slice(project.id.lastIndexOf('/') + 1)}` + return { + body: (merge.description ?? '').replace(UPLOAD, (_, lead: string, upload: string) => `${lead}${uploads}${upload}`), + labels: merge.labels.nodes.map(label => ({ name: label.title, color: COLOR.exec(label.color)?.[1]?.toLowerCase() ?? null })), + labelsTruncated: merge.labels.count > merge.labels.nodes.length, + images: {}, + imagesExpireAt: null, + createdAt: merge.createdAt, + } +} diff --git a/packages/experimental/forge-gitlab/src/provider.ts b/packages/experimental/forge-gitlab/src/provider.ts index 0351474b15..361fcccc8d 100644 --- a/packages/experimental/forge-gitlab/src/provider.ts +++ b/packages/experimental/forge-gitlab/src/provider.ts @@ -2,13 +2,15 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - BranchUpdateRequest, ChangeRequestIssue, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, - ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, - ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, MergeRequest, + BranchUpdateRequest, ChangeRequestDescription, ChangeRequestIssue, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, + ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, + ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, + ForgeViewerCapability, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' import { z } from 'zod' import { GitLabApi } from './api.ts' import { readCommits } from './commits.ts' +import { readDescription } from './description.ts' import { comparePatch, fileTextOf, isCommit, mergeBaseOf, newestVersion, textPatch, versionFileDiffs, versionPatch } from './diff.ts' import type { GlabRunner } from './glab.ts' import { gitLabReviewerCandidates, requestGitLabReviews, rerunGitLabChecks, updateGitLabBranch } from './overview.ts' @@ -21,6 +23,7 @@ import { } from './status.ts' import type { JobNode, MergeRequestNode } from './status.ts' import { checkedProject, encodedPath, mergeRequestPath, parseMergeRequestUrl, parseRemoteUrl, repositoryOf } from './urls.ts' +import { countViewerLists, readInvolvedList, readViewerList, readViewerName, VIEWER_FILTERS, VIEWER_PAGE } from './viewer.ts' import { submitGitLabReview, writeGitLabReview } from './writes.ts' import type { VersionFiles } from './writes.ts' @@ -69,8 +72,11 @@ export class GitLabProvider implements ForgeProvider { readonly hosts: readonly string[] readonly label = 'GitLab' readonly changeRequestNoun = 'merge-request' + readonly viewer: ForgeViewerCapability private readonly served: ReadonlySet private readonly api: GitLabApi + /** Username of the signed-in user by host, as the latest viewer read on the host named it. */ + private readonly viewers = new Map() /** Closing issues by merge request; one entry per merge request this provider polled. */ private readonly closing = new Map() /** Diff version patches by merge request and version, least recently read first. */ @@ -88,6 +94,50 @@ export class GitLabProvider implements ForgeProvider { this.api = new GitLabApi(glab) this.hosts = [...new Set(hosts.map(host => host.toLowerCase()))] this.served = new Set(this.hosts) + this.viewer = { hosts: this.hosts, filters: VIEWER_FILTERS, maxItems: VIEWER_PAGE } + } + + /** + * Read one list of the signed-in user's open merge requests through one GraphQL request; the `involved` list names + * the user in its request. + * @see readViewerList + * @see readInvolvedList + * @see GitLabProvider.asViewer + * @throws when the limit is not a positive integer no greater than {@link VIEWER_PAGE}. + */ + async listForViewer(query: ForgeViewerQuery, signal: AbortSignal): Promise { + const { host, filter, limit } = query + const failure = this.hostFailure(host) + if (failure !== undefined) return failure + if (!Number.isSafeInteger(limit) || limit <= 0 || limit > VIEWER_PAGE) { + throw new Error(`forge-gitlab: viewer list limit must be a positive integer no greater than ${VIEWER_PAGE}`) + } + if (filter === 'involved') return await this.asViewer(host, async me => await readInvolvedList(this.api, query, me, signal), signal) + const list = await readViewerList(this.api, filter, query, signal) + if (!('code' in list)) this.viewers.set(host, list.viewer) + return list + } + + /** + * Count the signed-in user's open merge requests in every list through one GraphQL request, which names the user. + * @see countViewerLists + * @see GitLabProvider.asViewer + */ + async countForViewer(host: string, signal: AbortSignal): Promise | ForgeFailure> { + const failure = this.hostFailure(host) + if (failure !== undefined) return failure + const counted = await this.asViewer(host, async me => await countViewerLists(this.api, host, me, signal), signal) + return 'code' in counted ? counted : counted.counts + } + + /** + * Read a merge request's description and labels through GraphQL. + * @see readDescription + */ + async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise { + const failure = this.hostFailure(ref.repository.host) + if (failure !== undefined) return failure + return await readDescription(this.api, ref, signal) } repositoryFromRemote(url: string): ForgeRepository | undefined { @@ -288,6 +338,31 @@ export class GitLabProvider implements ForgeProvider { return await readReviewThreads(this.api, ref, headSha, this.limits, async file => await this.positionPatch(ref, file, signal), signal) } + /** + * Run a read that names the signed-in user of `host` in its request: with the username the latest viewer read on the + * host returned, which one request reads first when there is none. An answer that names another user, as after + * `glab` signed in as someone else, replaces the kept username, and the read runs once more with it. + * @param host - host the read is on. + * @param read - the read for one username, whose result names the user GitLab answered as. + * @param signal - cancellation of the username read. + * @returns the result of the last read, or why GitLab named no user. + */ + private async asViewer( + host: string, read: (me: string) => Promise, signal: AbortSignal, + ): Promise { + let me = this.viewers.get(host) + if (me === undefined) { + const named = await readViewerName(this.api, host, signal) + if (typeof named !== 'string') return named + me = named + this.viewers.set(host, me) + } + const result = await read(me) + if ('code' in result || result.viewer === me) return result + this.viewers.set(host, result.viewer) + return await read(result.viewer) + } + /** * Read the status of merge requests on one host with one GraphQL query, halving the batch while GitLab refuses it as * too complex, then read each one's closing issues unless its update time is the one they were read at. diff --git a/packages/experimental/forge-gitlab/src/status.ts b/packages/experimental/forge-gitlab/src/status.ts index 068adf8f3c..7816e1b2ec 100644 --- a/packages/experimental/forge-gitlab/src/status.ts +++ b/packages/experimental/forge-gitlab/src/status.ts @@ -152,7 +152,21 @@ export function needsMergeCheck(node: MergeRequestNode): boolean { } /** Review states of a reviewer whose review is still awaited. */ -const AWAITED = new Set(['UNREVIEWED', 'REVIEW_STARTED']) +export const AWAITED_REVIEW_STATES: ReadonlySet = new Set(['UNREVIEWED', 'REVIEW_STARTED']) + +/** One reviewer's review state as GitLab returns it with a merge request. */ +export interface ReviewerInteraction { + /** The reviewer's interaction with the merge request, or null when GitLab reports none. */ + readonly mergeRequestInteraction: { readonly reviewState: string | null } | null +} + +/** The approval and reviewers of a merge request, which decide its aggregate review outcome with its merge status. */ +export interface ReviewedMergeRequest { + /** Whether GitLab reports the merge request approved. */ + readonly approved: boolean + /** The reviewers GitLab listed. */ + readonly reviewers: { readonly nodes: readonly ReviewerInteraction[] } +} /** A merge request whose status is known, and the parts of it read elsewhere. */ export interface StatusParts { @@ -238,8 +252,15 @@ function mergeMethods(fastForwardOnly: boolean, node: MergeRequestNode): MergeMe return node.squash ? ['squash', base] : [base, 'squash'] } -/** A reviewer who requested changes decides first, then an approval, then GitLab's demand for one. */ -function reviewDecision(node: MergeRequestNode, status: string): ReviewDecision { +/** + * Decide a merge request's aggregate review outcome: a reviewer who requested changes decides first, then an approval, + * then GitLab's demand for one. + * @param node - the merge request's approval and reviewers. + * @param status - the merge request's `detailedMergeStatus`, or null for a read that does not select it, which then + * reports a demanded approval as `none`. + * @returns the review decision. + */ +export function reviewDecision(node: ReviewedMergeRequest, status: string | null): ReviewDecision { if (node.reviewers.nodes.some(reviewer => reviewer.mergeRequestInteraction?.reviewState === 'REQUESTED_CHANGES')) return 'changes-requested' if (node.approved) return 'approved' if (status === 'NOT_APPROVED') return 'review-required' @@ -257,10 +278,9 @@ function reviewers(node: MergeRequestNode, host: string): ChangeRequestReviewer[ listed.push(entry) } for (const reviewer of node.reviewers.nodes) { - const state = reviewer.mergeRequestInteraction?.reviewState ?? 'UNREVIEWED' add(reviewer.username, { - kind: reviewer.bot ? 'bot' : 'user', login: reviewer.username, avatarUrl: avatarUrlOf(host, reviewer.avatarUrl), requested: AWAITED.has(state), - codeOwner: false, verdict: verdictOf(state), reviewedSha: null, + kind: reviewer.bot ? 'bot' : 'user', login: reviewer.username, avatarUrl: avatarUrlOf(host, reviewer.avatarUrl), codeOwner: false, + ...reviewOf(reviewer), reviewedSha: null, }) } for (const approver of node.approvedBy?.nodes ?? []) { @@ -272,6 +292,16 @@ function reviewers(node: MergeRequestNode, host: string): ChangeRequestReviewer[ return listed } +/** + * Read one reviewer's review state; a reviewer GitLab reports no state for has not reviewed. + * @param reviewer - the reviewer as GitLab returned it. + * @returns whether the reviewer's review is still awaited, and the outcome of their latest review. + */ +export function reviewOf(reviewer: ReviewerInteraction): Pick { + const state = reviewer.mergeRequestInteraction?.reviewState ?? 'UNREVIEWED' + return { requested: AWAITED_REVIEW_STATES.has(state), verdict: verdictOf(state) } +} + /** A reviewer state as the outcome of their latest review; states outside the documented set read as none. */ function verdictOf(state: string): ReviewVerdict | null { switch (state) { @@ -316,8 +346,12 @@ function jobState(job: JobNode): CheckState { } } -/** A pipeline status as the combined check outcome; a merge request without a pipeline has none. */ -function rollup(status: string | null): ChecksRollup { +/** + * Map a pipeline status to the combined check outcome; statuses outside the documented set read as pending. + * @param status - status of the head pipeline, or null for a merge request without a pipeline. + * @returns the combined outcome, `none` without a pipeline. + */ +export function rollup(status: string | null): ChecksRollup { switch (status) { case null: return 'none' case 'SUCCESS': diff --git a/packages/experimental/forge-gitlab/src/urls.ts b/packages/experimental/forge-gitlab/src/urls.ts index 209f189fb5..78323624b0 100644 --- a/packages/experimental/forge-gitlab/src/urls.ts +++ b/packages/experimental/forge-gitlab/src/urls.ts @@ -30,7 +30,7 @@ export function isSegment(value: string): boolean { * @param parts - path segments, the project last. * @returns the namespace and project, or undefined. */ -function location(host: string, parts: readonly string[]): GitLabLocation | undefined { +export function location(host: string, parts: readonly string[]): GitLabLocation | undefined { if (parts.length < 2 || !parts.every(isSegment)) return undefined return { host: host.toLowerCase(), owner: parts.slice(0, -1).join('/'), name: parts.slice(-1).join('') } } diff --git a/packages/experimental/forge-gitlab/src/viewer.ts b/packages/experimental/forge-gitlab/src/viewer.ts new file mode 100644 index 0000000000..13c2903dc8 --- /dev/null +++ b/packages/experimental/forge-gitlab/src/viewer.ts @@ -0,0 +1,285 @@ +/** Lists and counts of the signed-in user's open merge requests through GraphQL. */ + +import type { + ChangeRequestSummary, ForgeFailure, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery, +} from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import type { GitLabApi } from './api.ts' +import { AWAITED_REVIEW_STATES, PEOPLE_PAGE, reviewDecision, reviewOf, rollup } from './status.ts' +import { avatarUrlOf, isSegment, location, repositoryOf } from './urls.ts' + +/** The lists the provider reads on every host it serves. */ +export const VIEWER_FILTERS: ReadonlySet = new Set(['review-requested', 'authored', 'involved']) + +/** Most merge requests one list read returns, GitLab's connection page maximum. */ +export const VIEWER_PAGE = 100 + +/** The lists GitLab reads from one connection of the signed-in user; `involved` joins two. */ +export type SingleListFilter = Exclude + +/** Host, project, and limit of one list read. */ +export type ViewerScope = Omit + +/** The size of every list with the user GitLab counted them for. */ +export interface ViewerCounts { + /** Username of the signed-in user GitLab answered as. */ + readonly viewer: string + /** Number of open merge requests in each list. */ + readonly counts: ReadonlyMap +} + +/** The review states of a reviewer whose review is still awaited, as a GraphQL list. */ +const AWAITED = `[${[...AWAITED_REVIEW_STATES].join(', ')}]` + +/** Arguments that select the open merge requests of a connection. */ +const OPEN = 'state: opened' + +/** Arguments of one list page: most recently updated first, `$first` merge requests, in `$project` or in every project. */ +const PAGE = `${OPEN}, sort: UPDATED_DESC, first: $first, projectPath: $project` + +/** + * The four connections of `currentUser` that the lists are read from, each built from the arguments that select its + * state and page: merge requests that await the user's review, ones the user wrote, ones the user reviewed and did not + * write, and ones assigned to the user who neither wrote nor reviews them. The last two name the user as `$me` and + * share no merge request with each other or with the first two. + */ +const CONNECTIONS = { + awaited: (selected: string): string => `reviewRequestedMergeRequests(${selected}, reviewStates: ${AWAITED})`, + authored: (selected: string): string => `authoredMergeRequests(${selected})`, + reviewed: (selected: string): string => + `reviewRequestedMergeRequests(${selected}, not: { reviewStates: ${AWAITED}, authorUsername: $me })`, + assigned: (selected: string): string => `assignedMergeRequests(${selected}, not: { authorUsername: $me, reviewerUsername: $me })`, +} + +/** Merge request fields one list row takes; the reviewers decide the review outcome and name the signed-in user's own review state. */ +const ROW_FRAGMENT = `fragment ViewerRow on MergeRequest { + iid title webUrl draft updatedAt diffHeadSha approved + author { username avatarUrl bot } + project { fullPath } + headPipeline { status } + reviewers(first: ${PEOPLE_PAGE}) { nodes { username mergeRequestInteraction { reviewState } } } +}` + +const ROWS = '{ count nodes { ...ViewerRow } }' + +/** One page of a list read from one connection; variables: the integer `first` and the nullable string `project`. */ +export const VIEWER_LIST_QUERIES: Readonly> = { + 'review-requested': `query($first: Int!, $project: String) { + currentUser { username list: ${CONNECTIONS.awaited(PAGE)} ${ROWS} } +} +${ROW_FRAGMENT}`, + 'authored': `query($first: Int!, $project: String) { + currentUser { username list: ${CONNECTIONS.authored(PAGE)} ${ROWS} } +} +${ROW_FRAGMENT}`, +} + +/** One page of each connection of the `involved` list; variables: `first`, `project`, and `me`, the signed-in user's username. */ +export const VIEWER_INVOLVED_QUERY = `query($first: Int!, $project: String, $me: String!) { + currentUser { + username + reviewed: ${CONNECTIONS.reviewed(PAGE)} ${ROWS} + assigned: ${CONNECTIONS.assigned(PAGE)} ${ROWS} + } +} +${ROW_FRAGMENT}` + +/** The size of every connection in every project; variable `me` is the signed-in user's username. */ +export const VIEWER_COUNT_QUERY = `query($me: String!) { + currentUser { + username + awaited: ${CONNECTIONS.awaited(OPEN)} { count } + authored: ${CONNECTIONS.authored(OPEN)} { count } + reviewed: ${CONNECTIONS.reviewed(OPEN)} { count } + assigned: ${CONNECTIONS.assigned(OPEN)} { count } + } +}` + +/** The signed-in user's username. */ +export const VIEWER_NAME_QUERY = 'query { currentUser { username } }' + +const rowSchema = z.object({ + iid: z.string(), + title: z.string(), + webUrl: z.string(), + draft: z.boolean(), + updatedAt: z.string(), + diffHeadSha: z.string().nullable(), + approved: z.boolean(), + author: z.object({ username: z.string(), avatarUrl: z.string().nullable(), bot: z.boolean() }).nullable(), + project: z.object({ fullPath: z.string() }), + headPipeline: z.object({ status: z.string() }).nullable(), + reviewers: z.object({ + nodes: z.array(z.object({ + username: z.string(), + mergeRequestInteraction: z.object({ reviewState: z.string().nullable() }).nullable(), + })), + }), +}) + +const sizeSchema = z.object({ count: z.number().int().nonnegative() }) +const pageSchema = sizeSchema.extend({ nodes: z.array(rowSchema) }) +const userSchema = z.object({ username: z.string() }) + +const nameSchema = z.object({ currentUser: userSchema.nullable() }) +const listSchema = z.object({ currentUser: userSchema.extend({ list: pageSchema }).nullable() }) +const involvedSchema = z.object({ currentUser: userSchema.extend({ reviewed: pageSchema, assigned: pageSchema }).nullable() }) +const countSchema = z.object({ + currentUser: userSchema.extend({ awaited: sizeSchema, authored: sizeSchema, reviewed: sizeSchema, assigned: sizeSchema }).nullable(), +}) + +/** A merge request number as GitLab spells it, short enough to be a safe integer. */ +const IID = /^[1-9]\d{0,14}$/ + +/** + * Read the `review-requested` or the `authored` list through one request: the open merge requests on which the user's + * review state is unreviewed or started, or the ones the user wrote, most recently updated first. Merge requests this + * provider cannot address and ones without a head commit are left out of `items` and still counted in `total`. + * @param api - GitLab reads. + * @param filter - the list. + * @param scope - host, project, and a limit the caller already bounded by {@link VIEWER_PAGE}. + * @param signal - cancellation of the read. + * @returns the list, or why GitLab did not provide it; `not-found`, without a request, for a project path GitLab cannot hold. + */ +export async function readViewerList( + api: GitLabApi, filter: SingleListFilter, scope: ViewerScope, signal: AbortSignal, +): Promise { + const project = projectPathOf(scope.repository) + if (project === undefined) return UNSEARCHABLE + const variables = { first: scope.limit, project } + const user = await readAsUser(api, scope.host, VIEWER_LIST_QUERIES[filter], variables, listSchema, 'merge request list', signal) + if ('code' in user) return user + const awaited = filter === 'review-requested' + return { + viewer: user.username, + items: user.list.nodes.flatMap(row => summaryOf(scope.host, row, user.username, awaited) ?? []), + total: user.list.count, + } +} + +/** + * Read the `involved` list through one request of two connections, since GitLab has no single one for it: the open merge + * requests the user reviewed and did not write, and the ones assigned to the user who neither wrote nor reviews them. + * Both are merged most recently updated first and cut to the limit; `total` is the sum of their sizes. + * @param api - GitLab reads. + * @param scope - host, project, and a limit the caller already bounded by {@link VIEWER_PAGE}. + * @param me - username of the signed-in user, which the connections exclude as author and as reviewer. A list whose + * `viewer` is another username was selected for the wrong user and must be read again with that username. + * @param signal - cancellation of the read. + * @returns the list, or why GitLab did not provide it; `not-found`, without a request, for a project path GitLab cannot hold. + */ +export async function readInvolvedList( + api: GitLabApi, scope: ViewerScope, me: string, signal: AbortSignal, +): Promise { + const project = projectPathOf(scope.repository) + if (project === undefined) return UNSEARCHABLE + const variables = { first: scope.limit, project, me } + const user = await readAsUser(api, scope.host, VIEWER_INVOLVED_QUERY, variables, involvedSchema, 'merge request list', signal) + if ('code' in user) return user + const items = [...user.reviewed.nodes, ...user.assigned.nodes].flatMap(row => summaryOf(scope.host, row, user.username, false) ?? []) + items.sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt)) + return { viewer: user.username, items: items.slice(0, scope.limit), total: user.reviewed.count + user.assigned.count } +} + +/** + * Count every list on one host, in every project, through one request: `involved` is the sum of its two connections. + * @param api - GitLab reads. + * @param host - host to count on. + * @param me - username of the signed-in user, as {@link readInvolvedList} takes it; counts whose `viewer` is another + * username must be read again with that username. + * @param signal - cancellation of the read. + * @returns the size of each list with the user GitLab answered as, or why GitLab did not provide them. + */ +export async function countViewerLists( + api: GitLabApi, host: string, me: string, signal: AbortSignal, +): Promise { + const user = await readAsUser(api, host, VIEWER_COUNT_QUERY, { me }, countSchema, 'merge request count', signal) + if ('code' in user) return user + return { + viewer: user.username, + counts: new Map([ + ['review-requested', user.awaited.count], ['authored', user.authored.count], ['involved', user.reviewed.count + user.assigned.count], + ]), + } +} + +/** + * Read the username of the signed-in user. + * @param api - GitLab reads. + * @param host - host to read on. + * @param signal - cancellation of the read. + * @returns the username, or why GitLab did not name one. + */ +export async function readViewerName(api: GitLabApi, host: string, signal: AbortSignal): Promise { + const user = await readAsUser(api, host, VIEWER_NAME_QUERY, {}, nameSchema, 'user read', signal) + return 'code' in user ? user : user.username +} + +const UNSEARCHABLE: ForgeFailure = { code: 'not-found', message: 'the project path cannot be searched' } + +/** + * The `projectPath` argument of a list read. + * @param repository - one project to read in, or null for every project. + * @returns the project's full path, null for every project, or undefined for a path with a segment GitLab does not permit. + */ +function projectPathOf(repository: ForgeViewerQuery['repository']): string | null | undefined { + if (repository === null) return null + const { owner, name } = repository + return owner.split('/').every(isSegment) && isSegment(name) ? `${owner}/${name}` : undefined +} + +/** + * Run one query and read `currentUser` from its answer. + * @param api - GitLab reads. + * @param host - host to read on. + * @param query - GraphQL document that selects `currentUser`. + * @param variables - query variables. + * @param schema - the answer's `data`. + * @param subject - what the query reads, for the failure of an answer `schema` does not accept. + * @param signal - cancellation of the read. + * @returns the user's fields; `unauthenticated` when GitLab answers without a user, as it does for a request whose + * credentials it did not take; or the failure of the read. + */ +async function readAsUser( + api: GitLabApi, host: string, query: string, variables: Readonly>, + schema: z.ZodType<{ readonly currentUser: User | null }>, subject: string, signal: AbortSignal, +): Promise { + const read = await api.graphql(host, query, variables, signal) + if (!read.ok) return read.failure + const parsed = schema.safeParse(read.body) + if (!parsed.success) return { code: 'unavailable', message: `unexpected GitLab response to the ${subject}` } + return parsed.data.currentUser ?? { code: 'unauthenticated', message: `GitLab named no signed-in user on ${host}` } +} + +/** + * Map one merge request of a list. GitLab has no team review requests and records no commit with a review, so a request + * never names a team and a review never names a commit; the row reads no merge status, so an approval GitLab demands + * reads as no review decision. + * @param host - host the list was read on. + * @param row - the merge request fields. + * @param viewer - username of the signed-in user. + * @param awaited - whether the list holds only merge requests that await the user's review, which then all name a + * request, also past the reviewers the row reads. + * @returns the summary, or undefined for a project path or number this provider cannot address and for a merge request + * without commits, which has no head. + */ +function summaryOf(host: string, row: z.infer, viewer: string, awaited: boolean): ChangeRequestSummary | undefined { + const place = location(host, row.project.fullPath.split('/')) + if (place === undefined || !IID.test(row.iid) || row.diffHeadSha === null) return undefined + const { author } = row + const reviewer = row.reviewers.nodes.find(entry => entry.username.toLowerCase() === viewer.toLowerCase()) + const review = reviewer === undefined ? undefined : reviewOf(reviewer) + return { + ref: { repository: repositoryOf(place), number: Number(row.iid) }, + url: row.webUrl, + title: row.title, + draft: row.draft, + author: author === null ? null : { login: author.username, avatarUrl: avatarUrlOf(host, author.avatarUrl), bot: author.bot }, + headSha: row.diffHeadSha, + checksRollup: rollup(row.headPipeline?.status ?? null), + reviewDecision: reviewDecision(row, null), + viewerReview: review?.verdict == null ? null : { verdict: review.verdict, reviewedSha: null }, + viewerRequest: awaited || review?.requested === true ? { team: null } : null, + updatedAt: row.updatedAt, + } +} diff --git a/packages/experimental/forge-gitlab/tests/description.spec.ts b/packages/experimental/forge-gitlab/tests/description.spec.ts new file mode 100644 index 0000000000..bd3cedf0e7 --- /dev/null +++ b/packages/experimental/forge-gitlab/tests/description.spec.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from 'vitest' +import { GitLabApi } from '../src/api.ts' +import { DESCRIPTION_QUERY, readDescription } from '../src/description.ts' +import type { GlabOutput } from '../src/glab.ts' +import { app, fakeGlab, HOST, json, merge, output, sent } from './fixtures.ts' + +const signal = new AbortController().signal + +/** The secret GitLab names one upload by. */ +const SECRET = '0123456789abcdef0123456789abcdef' + +function api(answer: GlabOutput) { + const glab = fakeGlab(() => answer) + return { subject: new GitLabApi(glab.run), calls: glab.calls } +} + +/** An answer with one merge request of project 278, or with none. */ +function answer(mergeRequest: unknown, id = 'gid://gitlab/Project/278'): GlabOutput { + return json({ data: { project: { id, mergeRequest } } }) +} + +describe('GitLab descriptions', () => { + it('reads the description and labels through one request and names uploads where GitLab serves them', async () => { + const description = [ + 'Motivation', '', + `![shot](/uploads/${SECRET}/shot.png)`, + `[log](/uploads/${SECRET}/build.log) and `, + '![badge](https://img.shields.io/badge/x-y-blue)', + '[guide](/help/user/index) and ![short](/uploads/0123/short.png)', + `plain /uploads/${SECRET}/plain.png`, + ].join('\n') + const labels = [{ title: 'kind::feature', color: '#A2EEEF' }, { title: 'area/web', color: 'red' }, { title: 'short', color: '#fff' }] + const { subject, calls } = api(answer({ description, createdAt: '2026-11-08T12:00:00Z', labels: { count: 4, nodes: labels } })) + + const result = await readDescription(subject, merge(6), signal) + + expect(calls.map(call => call.args)) + .toEqual([['api', 'graphql', '--hostname', HOST, '--input', '-', '-H', 'Content-Type: application/json']]) + expect(sent(calls[0])).toEqual({ query: DESCRIPTION_QUERY, variables: { path: 'group/sub/app', iid: '6' } }) + const uploads = `https://${HOST}/-/project/278/uploads/${SECRET}` + expect(result).toEqual({ + body: [ + 'Motivation', '', + `![shot](${uploads}/shot.png)`, + `[log](${uploads}/build.log) and `, + '![badge](https://img.shields.io/badge/x-y-blue)', + '[guide](/help/user/index) and ![short](/uploads/0123/short.png)', + `plain /uploads/${SECRET}/plain.png`, + ].join('\n'), + labels: [{ name: 'kind::feature', color: 'a2eeef' }, { name: 'area/web', color: null }, { name: 'short', color: null }], + labelsTruncated: true, + images: {}, + imagesExpireAt: null, + createdAt: '2026-11-08T12:00:00Z', + }) + }) + + it('reads a merge request without a description or labels', async () => { + const { subject } = api(answer({ description: null, createdAt: '2026-11-08T12:00:00Z', labels: { count: 0, nodes: [] } })) + await expect(readDescription(subject, merge(6), signal)).resolves.toEqual({ + body: '', labels: [], labelsTruncated: false, images: {}, imagesExpireAt: null, createdAt: '2026-11-08T12:00:00Z', + }) + }) + + it.each([ + ['a missing merge request', answer(null), { code: 'not-found', message: 'merge request 3 was not found' }], + ['a missing project', json({ data: { project: null } }), { code: 'not-found', message: 'merge request 3 was not found' }], + ['an unexpected answer', answer({ description: 1 }), + { code: 'unavailable', message: 'unexpected GitLab response to the description read' }], + ['a project id that names no number', answer(null, 'gid://gitlab/Project/'), + { code: 'unavailable', message: 'unexpected GitLab response to the description read' }], + ['a refusal', output('', 1, 'glab: 502 Bad Gateway (HTTP 502)'), { code: 'unavailable', message: '502 Bad Gateway (HTTP 502)' }], + ])('reports %s', async (_label, body, failure) => { + await expect(readDescription(api(body).subject, merge(3), signal)).resolves.toEqual(failure) + }) + + it('rejects a project path GitLab cannot hold before any request', async () => { + const { subject, calls } = api(answer(null)) + await expect(readDescription(subject, merge(6, { ...app, name: 'a b' }), signal)) + .rejects.toThrow('forge-gitlab: invalid project "group/sub/a b"') + expect(calls).toEqual([]) + }) +}) diff --git a/packages/experimental/forge-gitlab/tests/provider.spec.ts b/packages/experimental/forge-gitlab/tests/provider.spec.ts index 7dabd0f60c..e9bdf3afcb 100644 --- a/packages/experimental/forge-gitlab/tests/provider.spec.ts +++ b/packages/experimental/forge-gitlab/tests/provider.spec.ts @@ -5,6 +5,7 @@ import type { GlabOutput } from '../src/glab.ts' import { GitLabProvider } from '../src/provider.ts' import type { GitLabLimits } from '../src/provider.ts' import type { MergeRequestNode } from '../src/status.ts' +import { VIEWER_COUNT_QUERY, VIEWER_INVOLVED_QUERY, VIEWER_LIST_QUERIES, VIEWER_NAME_QUERY } from '../src/viewer.ts' import { app, fakeGlab, HOST, json, merge, mrPath, output, pathOf, sent, sha } from './fixtures.ts' import type { GlabCall } from './fixtures.ts' import { job, mergeRequestNode, PIPELINE } from './status.spec.ts' @@ -496,6 +497,135 @@ describe('GitLab provider writes', () => { }) }) +/** The viewer queries by the name the request lists below give them. */ +const VIEWER_QUERIES = new Map([ + [VIEWER_NAME_QUERY, 'name'], [VIEWER_COUNT_QUERY, 'count'], [VIEWER_INVOLVED_QUERY, 'involved'], + [VIEWER_LIST_QUERIES['review-requested'], 'review-requested'], [VIEWER_LIST_QUERIES.authored, 'authored'], +]) + +/** Each call as the viewer query it sent and its variables. */ +function viewerRequests(calls: readonly GlabCall[]): unknown[] { + return calls.map(call => [VIEWER_QUERIES.get(sent(call).query), sent(call).variables]) +} + +/** An answer to any viewer query as `username`, with lists of no merge requests, or as nobody for null. */ +function viewerAnswer(call: GlabCall, username: string | null): GlabOutput { + if (username === null) return json({ data: { currentUser: null } }) + const page = { count: 0, nodes: [] } + const size = { count: 2 } + const user = { username, list: page, reviewed: page, assigned: page, awaited: size, authored: size, ...counted(call) } + return json({ data: { currentUser: user } }) +} + +/** The sizes of the two connections of the involved list when `call` counts them, which name who they were counted for. */ +function counted(call: GlabCall): Record { + if (sent(call).query !== VIEWER_COUNT_QUERY) return {} + return { reviewed: { count: sent(call).variables.me === 'lin' ? 1 : 10 }, assigned: { count: 4 } } +} + +describe('GitLab provider viewer lists and descriptions', () => { + const involved = { host: HOST, filter: 'involved', repository: null, limit: 20 } as const + const counts = (reviewed: number) => new Map([['review-requested', 2], ['authored', 2], ['involved', reviewed + 4]]) + + it('offers the three lists on every host it serves, up to GitLab\'s page of 100', () => { + expect(provider(() => json({})).subject.viewer).toEqual({ + hosts: [HOST, 'gitlab.com'], filters: new Set(['review-requested', 'authored', 'involved']), maxItems: 100, + }) + }) + + it('refuses lists, counts, and descriptions on an unserved host without a request', async () => { + const { subject, calls } = provider(() => json({})) + const refused = { code: 'unavailable', message: 'forge-gitlab does not serve elsewhere.test; add it to the provider\'s hosts setting' } + await expect(subject.listForViewer({ ...involved, host: 'elsewhere.test' }, signal)).resolves.toEqual(refused) + await expect(subject.countForViewer('elsewhere.test', signal)).resolves.toEqual(refused) + await expect(subject.readDescription(merge(6, { ...app, host: 'elsewhere.test' }), signal)).resolves.toEqual(refused) + expect(calls).toEqual([]) + }) + + it.each([0, -1, 1.5, 101])('rejects a list limit of %s outside 1 to 100', async (limit) => { + const { subject, calls } = provider((_path, call) => viewerAnswer(call, 'lin')) + await expect(subject.listForViewer({ ...involved, filter: 'authored', limit }, signal)) + .rejects.toThrow('forge-gitlab: viewer list limit must be a positive integer no greater than 100') + expect(calls).toEqual([]) + }) + + it('reads a list of 100 merge requests in one request', async () => { + const { subject, calls } = provider((_path, call) => viewerAnswer(call, 'lin')) + const authored = { ...involved, filter: 'authored', repository: { owner: 'group/sub', name: 'app' }, limit: 100 } as const + await expect(subject.listForViewer(authored, signal)).resolves.toEqual({ viewer: 'lin', items: [], total: 0 }) + expect(viewerRequests(calls)).toEqual([['authored', { first: 100, project: 'group/sub/app' }]]) + }) + + it('reads the username once for the reads that name the user, and keeps it for later ones', async () => { + const { subject, calls } = provider((_path, call) => viewerAnswer(call, 'lin')) + await expect(subject.countForViewer(HOST, signal)).resolves.toEqual(counts(1)) + await expect(subject.listForViewer(involved, signal)).resolves.toEqual({ viewer: 'lin', items: [], total: 0 }) + await expect(subject.countForViewer(HOST, signal)).resolves.toEqual(counts(1)) + expect(viewerRequests(calls)).toEqual([ + ['name', {}], ['count', { me: 'lin' }], ['involved', { first: 20, project: null, me: 'lin' }], ['count', { me: 'lin' }], + ]) + }) + + it('keeps the username a list answered as, per host', async () => { + const { subject, calls } = provider((_path, call) => viewerAnswer(call, call.args.includes(HOST) ? 'lin' : 'zhou')) + await subject.listForViewer({ ...involved, filter: 'review-requested' }, signal) + await expect(subject.countForViewer(HOST, signal)).resolves.toEqual(counts(1)) + await expect(subject.countForViewer('gitlab.com', signal)).resolves.toEqual(counts(10)) + expect(viewerRequests(calls)).toEqual([ + ['review-requested', { first: 20, project: null }], ['count', { me: 'lin' }], ['name', {}], ['count', { me: 'zhou' }], + ]) + expect(calls.map(call => call.args[3])).toEqual([HOST, HOST, 'gitlab.com', 'gitlab.com']) + }) + + it('reads once more as the user GitLab answered as when it is another one, and keeps that user', async () => { + let user = 'lin' + const { subject, calls } = provider((_path, call) => viewerAnswer(call, user)) + await subject.countForViewer(HOST, signal) + user = 'zhou' + await expect(subject.countForViewer(HOST, signal)).resolves.toEqual(counts(10)) + await expect(subject.listForViewer(involved, signal)).resolves.toMatchObject({ viewer: 'zhou' }) + expect(viewerRequests(calls).slice(2)).toEqual([ + ['count', { me: 'lin' }], ['count', { me: 'zhou' }], ['involved', { first: 20, project: null, me: 'zhou' }], + ]) + }) + + it('reads at most twice when every answer names another user', async () => { + const users = ['lin', 'zhou', 'wang'] + const { subject, calls } = provider((_path, call) => viewerAnswer(call, users.shift() ?? 'chen')) + await expect(subject.listForViewer(involved, signal)).resolves.toMatchObject({ viewer: 'wang' }) + expect(viewerRequests(calls)).toEqual([ + ['name', {}], ['involved', { first: 20, project: null, me: 'lin' }], ['involved', { first: 20, project: null, me: 'zhou' }], + ]) + }) + + it('keeps no username from a read GitLab did not answer', async () => { + let user: string | null = null + const { subject, calls } = provider((_path, call) => viewerAnswer(call, user)) + const signedOut = { code: 'unauthenticated', message: `GitLab named no signed-in user on ${HOST}` } + await expect(subject.listForViewer({ ...involved, filter: 'authored' }, signal)).resolves.toEqual(signedOut) + await expect(subject.countForViewer(HOST, signal)).resolves.toEqual(signedOut) + user = 'lin' + await expect(subject.countForViewer(HOST, signal)).resolves.toEqual(counts(1)) + user = null + await expect(subject.listForViewer(involved, signal)).resolves.toEqual(signedOut) + expect(viewerRequests(calls)).toEqual([ + ['authored', { first: 20, project: null }], ['name', {}], ['name', {}], ['count', { me: 'lin' }], + ['involved', { first: 20, project: null, me: 'lin' }], + ]) + }) + + it('reads a description through one request', async () => { + const { subject, calls } = provider(() => json({ data: { project: { id: 'gid://gitlab/Project/278', mergeRequest: { + description: 'Why', createdAt: '2026-11-08T12:00:00Z', labels: { count: 1, nodes: [{ title: 'bug', color: '#d9534f' }] }, + } } } })) + await expect(subject.readDescription(merge(6), signal)).resolves.toEqual({ + body: 'Why', labels: [{ name: 'bug', color: 'd9534f' }], labelsTruncated: false, images: {}, imagesExpireAt: null, + createdAt: '2026-11-08T12:00:00Z', + }) + expect(calls.map(call => sent(call).variables)).toEqual([{ path: 'group/sub/app', iid: '6' }]) + }) +}) + /** Narrow a fetch result for assertions. */ export function isFailure(result: ChangeRequestSnapshot | ForgeFailure | undefined): result is ForgeFailure { return result !== undefined && 'code' in result diff --git a/packages/experimental/forge-gitlab/tests/viewer.spec.ts b/packages/experimental/forge-gitlab/tests/viewer.spec.ts new file mode 100644 index 0000000000..58a6c61923 --- /dev/null +++ b/packages/experimental/forge-gitlab/tests/viewer.spec.ts @@ -0,0 +1,223 @@ +import { describe, expect, it } from 'vitest' +import { GitLabApi } from '../src/api.ts' +import type { GlabOutput } from '../src/glab.ts' +import { + countViewerLists, readInvolvedList, readViewerList, readViewerName, VIEWER_COUNT_QUERY, VIEWER_INVOLVED_QUERY, VIEWER_LIST_QUERIES, + VIEWER_NAME_QUERY, +} from '../src/viewer.ts' +import { app, fakeGlab, HOST, json, output, sent, sha } from './fixtures.ts' + +const signal = new AbortController().signal + +/** Every project on {@link HOST}, 20 merge requests. */ +const scope = { host: HOST, repository: null, limit: 20 } + +/** One merge request as the list queries return it: in `group/sub/app`, with a passed pipeline and no reviewers. */ +function row(iid: string, overrides: Record = {}): Record { + return { + iid, title: `Change ${iid}`, webUrl: `https://${HOST}/group/sub/app/-/merge_requests/${iid}`, draft: false, + updatedAt: '2026-11-10T08:00:00Z', diffHeadSha: sha('a'), approved: false, + author: { username: 'octo', avatarUrl: '/uploads/-/system/user/avatar/7/octo.png', bot: false }, + project: { fullPath: 'group/sub/app' }, headPipeline: { status: 'SUCCESS' }, reviewers: { nodes: [] }, + ...overrides, + } +} + +/** One reviewer of a row in `reviewState`, or one GitLab reports no interaction for. */ +function reviewer(username: string, reviewState: string | null): Record { + return { username, mergeRequestInteraction: reviewState === null ? null : { reviewState } } +} + +/** An answer to a query of one connection as `lin`. */ +function listAnswer(nodes: readonly unknown[], count = nodes.length): GlabOutput { + return json({ data: { currentUser: { username: 'lin', list: { count, nodes } } } }) +} + +function api(answer: GlabOutput) { + const glab = fakeGlab(() => answer) + return { subject: new GitLabApi(glab.run), calls: glab.calls } +} + +describe('GitLab viewer queries', () => { + const page = 'state: opened, sort: UPDATED_DESC, first: $first, projectPath: $project' + const rows = '{ count nodes { ...ViewerRow } }' + const awaited = 'reviewStates: [UNREVIEWED, REVIEW_STARTED]' + const reviewed = `not: { ${awaited}, authorUsername: $me }` + const assigned = 'not: { authorUsername: $me, reviewerUsername: $me }' + + it('selects the open merge requests of each list, most recently updated first', () => { + expect(VIEWER_LIST_QUERIES['review-requested']).toContain(`list: reviewRequestedMergeRequests(${page}, ${awaited}) ${rows}`) + expect(VIEWER_LIST_QUERIES.authored).toContain(`list: authoredMergeRequests(${page}) ${rows}`) + expect(VIEWER_INVOLVED_QUERY).toContain(`reviewed: reviewRequestedMergeRequests(${page}, ${reviewed}) ${rows}`) + expect(VIEWER_INVOLVED_QUERY).toContain(`assigned: assignedMergeRequests(${page}, ${assigned}) ${rows}`) + for (const query of [...Object.values(VIEWER_LIST_QUERIES), VIEWER_INVOLVED_QUERY]) { + expect(query).toContain('reviewers(first: 20) { nodes { username mergeRequestInteraction { reviewState } } }') + } + }) + + it('counts the same connections in every project', () => { + expect(VIEWER_COUNT_QUERY).toContain(`awaited: reviewRequestedMergeRequests(state: opened, ${awaited}) { count }`) + expect(VIEWER_COUNT_QUERY).toContain('authored: authoredMergeRequests(state: opened) { count }') + expect(VIEWER_COUNT_QUERY).toContain(`reviewed: reviewRequestedMergeRequests(state: opened, ${reviewed}) { count }`) + expect(VIEWER_COUNT_QUERY).toContain(`assigned: assignedMergeRequests(state: opened, ${assigned}) { count }`) + expect(VIEWER_COUNT_QUERY).not.toContain('nodes') + }) +}) + +describe('GitLab viewer lists', () => { + it('reads the merge requests that await the user\'s review through one request and maps each', async () => { + const { subject, calls } = api(listAnswer([ + row('8'), + row('7', { + draft: true, author: { username: 'renovate', avatarUrl: null, bot: true }, headPipeline: null, project: { fullPath: 'group/app' }, + reviewers: { nodes: [reviewer('zhou', 'REQUESTED_CHANGES'), reviewer('Lin', 'REVIEW_STARTED')] }, + }), + row('6', { author: null, approved: true, headPipeline: { status: 'FAILED' } }), + row('5', { project: { fullPath: 'app' } }), + row('4', { project: { fullPath: 'group/bad name/app' } }), + row('0'), + row('1e3'), + row('3', { diffHeadSha: null }), + ], 32)) + + const list = await readViewerList(subject, 'review-requested', scope, signal) + + expect(calls.map(call => call.args)) + .toEqual([['api', 'graphql', '--hostname', HOST, '--input', '-', '-H', 'Content-Type: application/json']]) + expect(sent(calls[0])).toEqual({ query: VIEWER_LIST_QUERIES['review-requested'], variables: { first: 20, project: null } }) + expect(list).toEqual({ + viewer: 'lin', + total: 32, + items: [ + { + ref: { repository: app, number: 8 }, + url: `https://${HOST}/group/sub/app/-/merge_requests/8`, + title: 'Change 8', + draft: false, + author: { login: 'octo', avatarUrl: `https://${HOST}/uploads/-/system/user/avatar/7/octo.png`, bot: false }, + headSha: sha('a'), + checksRollup: 'success', + reviewDecision: 'none', + viewerReview: null, + viewerRequest: { team: null }, + updatedAt: '2026-11-10T08:00:00Z', + }, + expect.objectContaining({ + ref: { repository: { forge: 'gitlab', host: HOST, owner: 'group', name: 'app' }, number: 7 }, + draft: true, + author: { login: 'renovate', avatarUrl: null, bot: true }, + checksRollup: 'none', + reviewDecision: 'changes-requested', + viewerReview: null, + viewerRequest: { team: null }, + }), + expect.objectContaining({ title: 'Change 6', author: null, checksRollup: 'failure', reviewDecision: 'approved' }), + ], + }) + }) + + it('reads the merge requests the user wrote in one project, with the user\'s own review state on each', async () => { + const { subject, calls } = api(listAnswer([ + row('9', { reviewers: { nodes: [reviewer('zhou', 'UNREVIEWED'), reviewer('lin', 'APPROVED')] } }), + row('8', { reviewers: { nodes: [reviewer('lin', null)] } }), + row('7', { reviewers: { nodes: [reviewer('lin', 'SOMETHING_NEW')] } }), + row('6', { reviewers: { nodes: [reviewer('zhou', 'REVIEWED')] } }), + ])) + + const inProject = { host: HOST, repository: { owner: 'group/sub', name: 'app' }, limit: 5 } + const list = await readViewerList(subject, 'authored', inProject, signal) + + expect(sent(calls[0])).toEqual({ query: VIEWER_LIST_QUERIES.authored, variables: { first: 5, project: 'group/sub/app' } }) + expect('items' in list ? list.items.map(item => [item.ref.number, item.viewerReview, item.viewerRequest]) : list).toEqual([ + [9, { verdict: 'approved', reviewedSha: null }, null], + [8, null, { team: null }], + [7, null, null], + [6, null, null], + ]) + expect(list).toMatchObject({ viewer: 'lin', total: 4 }) + }) + + it('merges the reviewed and the assigned merge requests most recently updated first, cut to the limit', async () => { + const { subject, calls } = api(json({ data: { currentUser: { + username: 'lin', + reviewed: { count: 4, nodes: [ + row('1', { updatedAt: '2026-11-10T10:00:00Z', reviewers: { nodes: [reviewer('lin', 'REVIEWED')] } }), + row('3', { updatedAt: '2026-11-10T08:00:00Z' }), + row('5', { updatedAt: '2026-11-10T11:00:00Z', diffHeadSha: null }), + ] }, + assigned: { count: 5, nodes: [ + // An instance in another time zone reports the same instant with its offset. + row('2', { updatedAt: '2026-11-10T17:30:00+08:00' }), + row('4', { updatedAt: '2026-11-10T07:00:00Z' }), + ] }, + } } })) + + const list = await readInvolvedList(subject, { ...scope, limit: 3 }, 'lin', signal) + + expect(sent(calls[0])).toEqual({ query: VIEWER_INVOLVED_QUERY, variables: { first: 3, project: null, me: 'lin' } }) + expect(calls).toHaveLength(1) + expect('items' in list ? list.items.map(item => [item.ref.number, item.viewerReview, item.viewerRequest]) : list).toEqual([ + [1, { verdict: 'commented', reviewedSha: null }, null], + [2, null, null], + [3, null, null], + ]) + expect(list).toMatchObject({ viewer: 'lin', total: 9 }) + }) + + it('refuses a project path GitLab cannot hold without a request', async () => { + const { subject, calls } = api(listAnswer([])) + const refused = { code: 'not-found', message: 'the project path cannot be searched' } + const within = (owner: string, name: string) => ({ ...scope, repository: { owner, name } }) + await expect(readViewerList(subject, 'authored', within('group/bad name', 'app'), signal)).resolves.toEqual(refused) + await expect(readViewerList(subject, 'review-requested', within('group', 'sub/app'), signal)).resolves.toEqual(refused) + await expect(readInvolvedList(subject, within('..', 'app'), 'lin', signal)).resolves.toEqual(refused) + expect(calls).toEqual([]) + }) + + it('counts every list in one request, the involved list as the sum of its two connections', async () => { + const { subject, calls } = api(json({ data: { currentUser: { + username: 'lin', awaited: { count: 32 }, authored: { count: 23 }, reviewed: { count: 4 }, assigned: { count: 11 }, + } } })) + await expect(countViewerLists(subject, HOST, 'lin', signal)).resolves.toEqual({ + viewer: 'lin', counts: new Map([['review-requested', 32], ['authored', 23], ['involved', 15]]), + }) + expect(calls.map(sent)).toEqual([{ query: VIEWER_COUNT_QUERY, variables: { me: 'lin' } }]) + }) + + it('reads the username of the signed-in user', async () => { + const { subject, calls } = api(json({ data: { currentUser: { username: 'lin' } } })) + await expect(readViewerName(subject, HOST, signal)).resolves.toBe('lin') + expect(calls.map(sent)).toEqual([{ query: VIEWER_NAME_QUERY, variables: {} }]) + }) + + const reads = { + 'a list': async (subject: GitLabApi) => await readViewerList(subject, 'review-requested', scope, signal), + 'the involved list': async (subject: GitLabApi) => await readInvolvedList(subject, scope, 'lin', signal), + 'the counts': async (subject: GitLabApi) => await countViewerLists(subject, HOST, 'lin', signal), + 'the username': async (subject: GitLabApi) => await readViewerName(subject, HOST, signal), + } + + it.each(Object.entries(reads))('reports %s GitLab answers without a signed-in user as unauthenticated', async (_label, read) => { + await expect(read(api(json({ data: { currentUser: null } })).subject)) + .resolves.toEqual({ code: 'unauthenticated', message: `GitLab named no signed-in user on ${HOST}` }) + }) + + it.each([ + ['a list', 'merge request list'], ['the involved list', 'merge request list'], ['the counts', 'merge request count'], + ['the username', 'user read'], + ] as const)('reports an answer to %s it cannot read as unavailable', async (label, read) => { + const unexpected = { code: 'unavailable', message: `unexpected GitLab response to the ${read}` } + await expect(reads[label](api(json({ data: { currentUser: { username: 7 } } })).subject)).resolves.toEqual(unexpected) + await expect(reads[label](api(json({ data: { project: null } })).subject)).resolves.toEqual(unexpected) + }) + + it.each([ + ['a signed-out glab', output('', 1, 'Unauthenticated.'), { code: 'unauthenticated', message: 'Unauthenticated.' }], + ['a gateway error', output('', 1, 'glab: 502 Bad Gateway (HTTP 502)'), { code: 'unavailable', message: '502 Bad Gateway (HTTP 502)' }], + ['a query over GitLab\'s complexity limit', + output(JSON.stringify({ errors: [{ message: 'Query has complexity of 270, which exceeds max complexity of 250' }] }), 1), + { code: 'too-large', message: 'Query has complexity of 270, which exceeds max complexity of 250' }], + ])('reports %s for every read', async (_label, answer, failure) => { + for (const read of Object.values(reads)) await expect(read(api(answer).subject)).resolves.toEqual(failure) + }) +}) diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index c53e0be53d..bd11a7171c 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -583,10 +583,6 @@ export interface ChangeRequestSummary { * `organization/slug`, when the request asks a team the user belongs to rather than the user. */ readonly viewerRequest: { readonly team: string | null } | null - /** Issues the host closes once the change request merges, in host order, at most the provider's limit. */ - 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 } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 5126671e8c..9bc901d398 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1589,9 +1589,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['when the Host lacks the Session query, projection cache, storage, or Session store service.'], }, { - signature: '@Remote({ mode: \'stream\' }) async *reviewLists( repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, ): AsyncIterable', - description: 'Stream the review page\'s lists of the signed-in user\'s open change requests on every host a provider lists them on: the lists read so far first, then a frame after each read settles. Readers of one repository scope share one reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops.', - parameters: [{ name: 'repository', description: 'one repository to list in, or null for every repository the user can read.' }, { name: 'signal', description: 'ends the stream.' }], + signature: '@Remote({ mode: \'stream\' }) async *reviewLists( repository: ForgeReviewRepository | null, signal: AbortSignal, ): AsyncIterable', + description: 'Stream the review page\'s lists of the signed-in user\'s open change requests on every host a provider lists them on: the lists read so far first, then a frame after each read settles. Readers of one repository scope share one reader, which reads each host every `reviewListIntervalMs` while some stream lasts and reads a host whose read failed again later each time, up to `reviewMaxBackoffMs`, without delaying the other hosts; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops.', + parameters: [{ name: 'repository', description: 'one repository to list in, read on its host only, or null for every repository the user can read on every host.' }, { name: 'signal', description: 'ends the stream.' }], returns: 'frames, each complete.', }, { @@ -6771,7 +6771,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ChangeRequestSummary', - declaration: 'export interface ChangeRequestSummary {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly draft: boolean;\n readonly author: ForgeCommentAuthor | null;\n readonly headSha: string;\n readonly checksRollup: ChecksRollup;\n readonly reviewDecision: ReviewDecision;\n readonly viewerReview: ChangeRequestViewerReview | null;\n readonly viewerRequest: {\n readonly team: string | null;\n } | null;\n readonly closingIssues: readonly ChangeRequestIssue[];\n readonly closingIssuesTruncated: boolean;\n readonly updatedAt: string;\n}', + declaration: 'export interface ChangeRequestSummary {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly draft: boolean;\n readonly author: ForgeCommentAuthor | null;\n readonly headSha: string;\n readonly checksRollup: ChecksRollup;\n readonly reviewDecision: ReviewDecision;\n readonly viewerReview: ChangeRequestViewerReview | null;\n readonly viewerRequest: {\n readonly team: string | null;\n } | null;\n readonly updatedAt: string;\n}', }, { name: 'ChangeRequestUpdate', @@ -7775,7 +7775,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeReviewHost', - declaration: 'export interface ForgeReviewHost {\n readonly forge: string;\n readonly host: string;\n readonly viewer: string | null;\n readonly lists: Partial>>;\n}', + declaration: 'export interface ForgeReviewHost {\n readonly forge: string;\n readonly host: string;\n readonly viewer: string | null;\n readonly signIn: string | null;\n readonly lists: Partial>>;\n}', }, { name: 'ForgeReviewId', @@ -7785,6 +7785,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeReviewList', declaration: 'export interface ForgeReviewList {\n readonly items: readonly ChangeRequestSummary[] | null;\n readonly total: number;\n readonly fetchedAt: number | null;\n readonly failure: ForgeFailure | null;\n}', }, + { + name: 'ForgeReviewRepository', + declaration: 'export interface ForgeReviewRepository {\n readonly host: string;\n readonly owner: string;\n readonly name: string;\n}', + }, { name: 'ForgeReviewRequest', declaration: 'export type ForgeReviewRequest = {\n readonly headSha: string;\n} & ({\n readonly kind: \'comment\';\n readonly comment: ForgeLineComment;\n} | {\n readonly kind: \'review\';\n readonly event: ForgeReviewEvent;\n readonly body: string;\n readonly comments: readonly ForgeLineComment[];\n});', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index c981b12b83..1e2a3163bb 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -479,6 +479,7 @@ export const LINK_MAP: Readonly> = { ForgeFileLayer: 'forge.md', ForgeChangeRequestStatesFrame: 'forge.md', ForgeReviewFrame: 'forge.md', + ForgeReviewRepository: 'forge.md', ForgeReviewCountFrame: 'forge.md', ForgeReviewChangeRequest: 'forge.md', ForgeFailure: 'forge.md', From 21b35a3b388db05ee01fb2290dc2ddd57abefc74 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 19 Nov 2026 21:09:30 +0800 Subject: [PATCH 03/14] feat(forge): declare the activity read and the comment action of a change request `ForgeProvider` gains two optional methods: `readActivity` reads the comments, submitted reviews, commits, and state changes of a change request, and `addComment` adds a comment to its conversation. `ctx.forge` forwards both; a provider without them answers `unsupported` and `failed`. --- packages/experimental/forge/src/index.ts | 29 ++++++++++- packages/experimental/forge/src/types.ts | 52 +++++++++++++++++++ .../experimental/forge/tests/viewer.spec.ts | 34 +++++++++++- .../experimental/forge/tests/watch.spec.ts | 4 +- 4 files changed, 116 insertions(+), 3 deletions(-) diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index f4eb06f31d..dde9b194a4 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -6,7 +6,8 @@ import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { changeRequestKey } from './keys.ts' import { backoffDelay, nextPollDelay } from './schedule.ts' import type { - BranchUpdateRequest, ChangeRequestBrief, ChangeRequestBriefListener, ChangeRequestBriefUpdate, ChangeRequestDescription, ChangeRequestKey, + BranchUpdateRequest, ChangeRequestActivity, ChangeRequestBrief, ChangeRequestBriefListener, ChangeRequestBriefUpdate, + ChangeRequestDescription, ChangeRequestKey, ChangeRequestKnownState, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ChangeRequestWatchOptions, Config, ForgeCommitList, ForgeActionFailure, ForgeDescription, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRegistrationHandle, @@ -607,6 +608,32 @@ export class ForgeService extends Service { ?? Promise.resolve({ code: 'unsupported', message: 'This provider does not read descriptions' } as const)) } + /** + * Read the activity of a change request: its comments, submitted reviews, commits, and changes of state. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the activity, or why the host did not provide it; `unsupported` when the provider reads no activity. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async readActivity(ref: ChangeRequestRef, signal: AbortSignal): Promise { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.readActivity?.(ref, operation) + ?? Promise.resolve({ code: 'unsupported', message: 'This provider does not read activity' } as const)) + } + + /** + * Add a comment to a change request's conversation, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param body - Markdown source of the comment. + * @param signal - cancellation of the request. + * @returns undefined once the host saved the comment, or why it did not; a provider that adds no comments fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async addComment(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise { + return await this.act(ref, signal, provider => provider.addComment?.bind(provider), 'adds no comments', + (action, operation) => action(ref, body, operation)) + } + /** * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced * with `forge/review-changed`. diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index bd11a7171c..dcf85ce99f 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -624,6 +624,47 @@ export interface ChangeRequestLabel { readonly color: string | null } +/** + * One entry of a change request's activity: a comment in its conversation, a submitted review, a commit, a change of + * its state, or a record the host words itself. + */ +export type ChangeRequestActivityItem = { + /** ISO 8601 time of the entry. */ + readonly at: string + /** Account the entry is by, or null when the host names none or the account no longer exists. */ + readonly actor: ForgeCommentAuthor | null +} & ( + /** A comment in the conversation. `body` is Markdown source; it may contain raw HTML, which readers must not render as HTML. */ + | { readonly kind: 'comment'; readonly body: string; readonly url: string | null } + /** + * A submitted review: its decision, its own Markdown text, which follows the rule of a comment's `body` and is empty + * without one, and the number of comments it left on lines and files. + */ + | { readonly kind: 'review'; readonly verdict: ReviewVerdict; readonly body: string; readonly comments: number; readonly url: string | null } + /** + * A commit added to the change request: its object name, abbreviated when the host records only an abbreviation, and + * the first line of its message. + */ + | { readonly kind: 'commit'; readonly sha: string; readonly title: string } + | { readonly kind: 'merged' | 'closed' | 'reopened' | 'ready-for-review' | 'converted-to-draft' | 'force-pushed' } + | { readonly kind: 'auto-merge-enabled' | 'auto-merge-disabled' } + /** A review was requested from an account or a team, named as the host spells it; null when the host names neither. */ + | { readonly kind: 'review-requested'; readonly reviewer: string | null } + | { readonly kind: 'renamed'; readonly from: string; readonly to: string } + /** A record with no kind of its own, as plain text in the host's own words. */ + | { readonly kind: 'other'; readonly text: string } +) + +/** The activity of a change request. */ +export interface ChangeRequestActivity { + /** Entries oldest first, at most the provider's limit; the latest ones when the change request has more. */ + readonly items: readonly ChangeRequestActivityItem[] + /** Whether the change request has entries older than `items` holds. */ + readonly truncated: boolean + /** Whether the signed-in user can add a comment through `addComment`; false for a provider without it. */ + readonly viewerCanComment: boolean +} + /** Whether a provider can reach one host with the current credentials. */ export interface ForgeReadiness { /** `ready`, `unauthenticated` (sign-in needed), or `unavailable` (tool missing or host unreachable). */ @@ -677,6 +718,17 @@ export interface ForgeProvider { countForViewer?(host: string, signal: AbortSignal): Promise | ForgeFailure> /** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */ readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the activity of a change request: the comments in its conversation, its submitted reviews, its commits, and + * the changes of its state. Omission declares that this provider reads no activity. + */ + readActivity?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Add a comment of Markdown source `body` to a change request's conversation, resolving to undefined once the host + * saved it. A comment is never retried. Omission declares that this provider adds no comments, and its `readActivity` + * then denies `viewerCanComment`. + */ + addComment?(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise /** diff --git a/packages/experimental/forge/tests/viewer.spec.ts b/packages/experimental/forge/tests/viewer.spec.ts index 852aac5cd5..34bb58d5ca 100644 --- a/packages/experimental/forge/tests/viewer.spec.ts +++ b/packages/experimental/forge/tests/viewer.spec.ts @@ -1,6 +1,6 @@ import type { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ChangeRequestDescription, ForgeViewerList, ForgeViewerQuery } from '../src/types.ts' +import type { ChangeRequestActivity, ChangeRequestDescription, ForgeViewerList, ForgeViewerQuery } from '../src/types.ts' import { FakeProvider, forgeContext, provide, ref } from './fake-provider.ts' let ctx: Context | undefined @@ -102,3 +102,35 @@ describe('forge descriptions', () => { expect(readDescription).toHaveBeenCalledWith(ref(4), expect.any(AbortSignal)) }) }) + +describe('forge activity', () => { + it('delegates an activity read and reports a provider without it as unsupported', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + + await expect(ctx.forge.readActivity(ref(4), signal)) + .resolves.toEqual({ code: 'unsupported', message: 'This provider does not read activity' }) + const activity: ChangeRequestActivity = { + items: [{ kind: 'comment', at: '2026-11-10T00:00:00Z', actor: null, body: 'Looks good', url: null }], truncated: false, viewerCanComment: true, + } + const readActivity = vi.fn(async () => activity) + Object.assign(provider, { readActivity }) + await expect(ctx.forge.readActivity(ref(4), signal)).resolves.toBe(activity) + expect(readActivity).toHaveBeenCalledWith(ref(4), expect.any(AbortSignal)) + }) + + it('fails a comment for a provider that adds none and forwards it to one that does', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + + await expect(ctx.forge.addComment(ref(4), 'Thanks', signal)).resolves.toEqual({ code: 'failed', message: 'This provider adds no comments' }) + const addComment = vi.fn(async () => undefined) + Object.assign(provider, { addComment }) + await expect(ctx.forge.addComment(ref(4), 'Thanks', signal)).resolves.toBeUndefined() + expect(addComment).toHaveBeenCalledWith(ref(4), 'Thanks', expect.any(AbortSignal)) + addComment.mockResolvedValueOnce({ code: 'unknown', message: 'no answer' } as never) + await expect(ctx.forge.addComment(ref(4), 'Thanks', signal)).resolves.toEqual({ code: 'unknown', message: 'no answer' }) + }) +}) diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index a9c685f02f..f439b8bbee 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -360,7 +360,7 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(2) }) - it.each(['rerunChecks', 'requestReviews', 'updateBranch'] as const)('polls at once after %s, whatever the host answered', async (action) => { + it.each(['rerunChecks', 'requestReviews', 'updateBranch', 'addComment'] 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, { @@ -368,12 +368,14 @@ describe('forge watch', () => { requestReviews: vi.fn(async () => undefined), reviewerCandidates: vi.fn(async () => []), updateBranch: vi.fn(async () => ({ code: 'stale', message: 'moved' })), + addComment: vi.fn(async () => ({ code: 'unknown', message: 'no answer' })), }) 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 === 'addComment') await context.forge.addComment(ref(1), 'Thanks', 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) From 4f600dbef6662174fdbf4b60d4693e6ba8f1cd6b Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 19 Nov 2026 21:51:22 +0800 Subject: [PATCH 04/14] feat(forge): show a change request's activity on the Code review page and add comments from it Under the description, the summary tab lists the comments, submitted reviews, commits, and changes of state of a change request, oldest first, with a field that adds a comment to its conversation. - forge-github: `readActivity` reads the latest 100 timeline entries in one GraphQL request; `addComment` posts one REST request. The close a merge records is left out. - forge-gitlab: `readActivity` reads the latest 100 notes through GraphQL and the state changes through REST; system notes map by their recorded action, and one with no kind of its own shows its sentence. `addComment` creates one note. - client-ui-forge (Host): `forgePanel.reviewActivity` returns null for a provider that reads no activity; `forgePanel.reviewComment` refuses a blank comment before the host is asked. - client-ui-forge (Client): runs of commits fold into one line, a review that left inline comments opens the changes tab, a long comment starts cut short, and the field keeps its text when the host did not save the comment. The activity is read again after a comment and when the change request's update time or reviews change. Copy in eight languages. --- .../2026-11-11-forge-review-page.i18n.yaml | 4 +- .../feature/2026-11-11-forge-review-page.md | 1 + .../2026-11-11-forge-review-page.zh.md | 1 + apps/web/tests/forge-panel.e2e.ts | 68 ++++ docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 4 +- docs/event-producer-consumer.zh.md | 4 +- docs/subsystems/forge.i18n.yaml | 7 +- docs/subsystems/forge.md | 102 ++++- docs/subsystems/forge.zh.md | 102 ++++- .../client-ui-forge/README.i18n.yaml | 8 +- .../experimental/client-ui-forge/README.md | 4 +- .../experimental/client-ui-forge/README.zh.md | 4 +- .../client-ui-forge/src/client/locales.ts | 200 +++++++++ .../src/client/review-page/ReviewActivity.tsx | 378 ++++++++++++++++++ .../src/client/review-page/ReviewDetail.tsx | 71 ++-- .../client/review-page/ReviewPage.module.css | 201 ++++++++++ .../src/client/review-page/ReviewPage.tsx | 14 +- .../src/client/review-page/review-activity.ts | 64 +++ .../src/client/review-page/review-mount.ts | 2 + .../experimental/client-ui-forge/src/index.ts | 39 +- .../experimental/client-ui-forge/src/types.ts | 2 + .../tests/mount.client.spec.ts | 11 +- .../tests/review-activity.client.spec.tsx | 327 +++++++++++++++ .../tests/review-detail.client.spec.tsx | 52 ++- .../tests/review-page.client.spec.tsx | 2 + .../tests/review-page.host.spec.ts | 31 +- .../forge-github/README.i18n.yaml | 12 +- packages/experimental/forge-github/README.md | 7 +- .../experimental/forge-github/README.zh.md | 7 +- .../experimental/forge-github/src/activity.ts | 203 ++++++++++ .../experimental/forge-github/src/mutation.ts | 4 +- .../experimental/forge-github/src/provider.ts | 52 ++- .../experimental/forge-github/src/threads.ts | 16 +- .../forge-github/tests/activity.spec.ts | 288 +++++++++++++ .../forge-gitlab/README.i18n.yaml | 12 +- packages/experimental/forge-gitlab/README.md | 8 +- .../experimental/forge-gitlab/README.zh.md | 8 +- .../experimental/forge-gitlab/src/activity.ts | 315 +++++++++++++++ .../forge-gitlab/src/description.ts | 21 +- .../experimental/forge-gitlab/src/provider.ts | 35 +- .../forge-gitlab/tests/activity.spec.ts | 264 ++++++++++++ .../forge-gitlab/tests/provider.spec.ts | 57 ++- packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 2 +- packages/experimental/forge/README.zh.md | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 37 +- scripts/gen-cordis-catalog.ts | 2 + scripts/type-equiv.manifest.json | 10 + 50 files changed, 2975 insertions(+), 98 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/client/review-page/ReviewActivity.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/review-page/review-activity.ts create mode 100644 packages/experimental/client-ui-forge/tests/review-activity.client.spec.tsx create mode 100644 packages/experimental/forge-github/src/activity.ts create mode 100644 packages/experimental/forge-github/tests/activity.spec.ts create mode 100644 packages/experimental/forge-gitlab/src/activity.ts create mode 100644 packages/experimental/forge-gitlab/tests/activity.spec.ts diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml index 0f370ec259..3a3d9986d5 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml @@ -9,8 +9,8 @@ en: ad1da0c97cfc9c2d zh: f4420c0b004fd189 /agent-note-code-review-page/decision: - en: 8bba17ff42512edd - zh: 5fc73c84fdfc4834 + en: 0e720fb68f23b83f + zh: 24989acf4da0e92a /agent-note-code-review-page/alternatives-considered: en: 963b1be39a0e4bac zh: 940b86a5e2036477 diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md index 29bef8f6af..7949365edc 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md @@ -15,6 +15,7 @@ A left-navigation Code review page in [`dsh-experimental-client-ui-forge`](../.. - **Lists** — an optional `ForgeProvider` capability (`viewer`, `listForViewer`, `countForViewer`) returns summaries of open change requests; GitHub answers each list with one GraphQL search, because one document with several searches times out. The Host reads the lists only while a page or count stream lasts, outside the forge's status polling, since a batch snapshot of dozens of change requests exceeds GitHub's query timeout; only the shown change request is polled through `ForgeService.watch`. - **Reads by URL** — the page's `forgePanel/review*` methods name a change request by URL and no Session; they share the Session-bound methods' implementation and are reachable only by callers that may use the Host's code host credentials. - **Description** — `readDescription` returns the Markdown body, labels, and signed addresses for private attachments, which the page substitutes before rendering with HTML omitted. +- **Activity** — two more optional `ForgeProvider` methods, `readActivity` and `addComment`, give the summary tab the comments, submitted reviews, commits, and changes of state of a change request and a field that adds a comment. A provider maps its host's records to one entry type, so the page words every entry in the reader's language and shows a host's own sentence only for a record the type has no kind for. A review's comments on lines stay on the changes tab, which already reads, answers, and resolves them; the activity counts them and opens that tab. - **Changes** — the page draws the changes view itself, split from the right-sidebar tab, with a panel state that holds only the shown change request; plugin lenses, annotations, and slots stay with the Session tab, whose extension points name a Session. - **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. A Workspace picked in the Hero is handled by the page, as every owner of the content handles its own picks: the page connects that Workspace's blank and shows it in the chat tab, where the main Conversation opens it as the main Session. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound. - **Hosts** — the page lists every configured host together, GitHub and GitLab. A host whose read failed is read again later each time without delaying the others, since the bundle ships a GitLab host most users are not signed in to. A repository scope names its host and is read there only: one `owner/name` can exist on two hosts, and a GitLab project path nests groups. The filter offers each host once the lists span several, and a host that could not be read shows one notice after the lists. A row names no host, because every row would then need a second line of small text; choosing among accounts of one host is not offered. diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md index 0bbaddbe96..16877e2b33 100644 --- a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md @@ -15,6 +15,7 @@ Status: implemented - **列表**——可选的 `ForgeProvider` 能力(`viewer`、`listForViewer`、`countForViewer`)返回未关闭变更请求的摘要;GitHub 每个列表用一次 GraphQL 搜索回答,因为在一个文档中放多个搜索会超时。Host 只在页面流或计数流存在时读取列表,不经过 forge 的状态轮询,因为几十个变更请求的批量快照会超过 GitHub 的查询时限;只有显示中的变更请求经 `ForgeService.watch` 轮询。 - **按 URL 读取**——页面的 `forgePanel/review*` 方法以 URL 而不是会话指定变更请求;它们与会话绑定的方法共用实现,只有可以使用 Host 代码托管凭据的调用方能访问。 - **描述**——`readDescription` 返回 Markdown 正文、标签以及私有附件的签名地址,页面替换这些地址后以省略 HTML 的方式渲染。 +- **动态**——另外两个可选的 `ForgeProvider` 方法 `readActivity` 与 `addComment` 为概要标签页提供变更请求的评论、已提交的评审、提交和状态变化,以及一个添加评论的输入框。提供方把所在主机的记录映射为同一种条目类型,所以页面用读者的语言表述每个条目,只有该类型没有对应种类的记录才显示主机自己的句子。评审在行上留下的评论仍在变更标签页,那里已经能读取、回复和解决它们;动态只显示条数并打开该标签页。 - **变更**——页面自己绘制变更视图(从右侧栏标签中拆出),面板状态只含显示中的变更请求;插件的透镜、行注释和插槽仍只在会话标签中,因为这些扩展点以会话为对象。 - **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。在 Hero 中选择工作区由页面自己处理,这与内容的每个属主处理各自的选择一致:页面连接该工作区的空白会话并在对话标签中显示它,而主 Conversation 会把它打开为主会话。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。 - **主机**——页面把所有已配置的主机合并列出,包括 GitHub 与 GitLab。读取失败的主机每次间隔更久再读,不拖慢其他主机,因为套件自带的 GitLab 主机多数用户并未登录。仓库范围带有主机,只在该主机上读取:同一个 `owner/name` 可以存在于两个主机,GitLab 的项目路径还有嵌套分组。列表跨多个主机时,筛选列出每个主机;读取失败的主机在列表之后显示一条提示。列表行不写主机,否则每一行都要多一行小字;同一主机的多个账号之间不提供选择。 diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 0d742c6140..e6b509052d 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -143,6 +143,13 @@ 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] === 'repos/octo/demo/issues/7/comments') { + const { body } = JSON.parse(readFileSync(0, 'utf8')) + state.comments = [...state.comments ?? [], { body, at: new Date().toISOString() }] + save() + process.stdout.write(JSON.stringify({ id: 1000 + state.comments.length, html_url: 'https://github.com/octo/demo/pull/7#issuecomment-1' })) + 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]] @@ -230,6 +237,30 @@ if (args[0] === 'api' && args[1] === 'graphql') { }) const overview = existsSync(join(here, 'overview.json')) ? JSON.parse(readFileSync(join(here, 'overview.json'), 'utf8')) : {} const none = { totalCount: 0, nodes: [] } + if (query.includes('bodyHTML')) { + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { + body: 'Adds the panel.', bodyHTML: '

    Adds the panel.

    ', createdAt: '2026-10-08T00:00:00Z', labels: none, + } } } })) + process.exit(0) + } + if (query.includes('timelineItems(')) { + const account = login => ({ __typename: 'User', login, avatarUrl: null }) + const commit = (oid, messageHeadline) => ({ __typename: 'PullRequestCommit', + commit: { oid: oid.repeat(40), messageHeadline, committedDate: '2026-10-08T01:00:00Z', author: { user: account('octo') } } }) + const comment = (body, createdAt, login) => ({ __typename: 'IssueComment', createdAt, body, author: account(login), + url: 'https://github.com/octo/demo/pull/7#issuecomment-1' }) + process.stdout.write(JSON.stringify({ data: { repository: { isArchived: false, viewerPermission: 'WRITE', pullRequest: { + locked: false, merged: false, timelineItems: { pageInfo: { hasPreviousPage: false }, nodes: [ + commit('d', 'Add the panel'), commit('e', 'Fix the build'), + { __typename: 'ReviewRequestedEvent', createdAt: '2026-10-08T02:00:00Z', actor: account('octo'), requestedReviewer: { login: 'mona' } }, + { __typename: 'PullRequestReview', createdAt: '2026-10-08T03:00:00Z', submittedAt: '2026-10-08T03:00:00Z', body: '', state: 'APPROVED', + url: 'https://github.com/octo/demo/pull/7#pullrequestreview-1', author: account('mona'), comments: { totalCount: 0 } }, + comment('Looks **good** to me.', '2026-10-08T04:00:00Z', 'mona'), + ...(state.comments ?? []).map(posted => comment(posted.body, posted.at, 'octocat')), + ] }, + } } } })) + process.exit(0) + } if (query.includes('search(type: ISSUE')) { // The review page's lists and their count, which only a case that writes lists.json shows. if (!existsSync(join(here, 'lists.json'))) { @@ -878,6 +909,43 @@ it.skipIf(MODE === 'record')('lists the change requests of a GitHub and a GitLab expect(tripwire.warnings).toEqual([]) }) +it.skipIf(MODE === 'record')('shows the activity of a pull request on the Code review page and adds a comment to it', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-activity', 'normal', { + lists: { 'review-requested': [7], 'authored': [], 'involved': [] }, + }) + // The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first. + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '代码评审', exact: true }).click() + await page.locator(`[data-forge-review-item="${PULL}"]`).click() + const activity = page.locator(`[data-forge-review-detail="${PULL}"]`).getByRole('region', { name: '动态', exact: true }) + + // Commits fold into one line; the review request, the approval, and the comment follow in the code host's order. + const lines = async (): Promise => await activity.locator('[data-forge-review-line]') + .evaluateAll(rows => rows.map(row => (row.textContent ?? '').replace(/\d+ ?(天|个月|年)前.*$/, ''))) + await expect.poll(lines).toEqual(['2 次提交', 'octo 请求 mona 评审', 'mona 批准了这些更改']) + const comments = activity.locator('[data-forge-review-comment]') + await expect.poll(async () => await comments.count()).toBe(1) + expect(await comments.first().locator('strong').textContent()).toBe('good') + await activity.getByRole('button', { name: '2 次提交', exact: true }).click() + await expect.poll(lines).toEqual(['2 次提交', 'Add the panel', 'Fix the build', 'octo 请求 mona 评审', 'mona 批准了这些更改']) + + // A comment goes to the pull request's conversation in one request and then shows at the end of the activity. + const field = activity.getByRole('textbox', { name: '留下评论', exact: true }) + const send = activity.getByRole('button', { name: '评论', exact: true }) + expect(await send.isDisabled()).toBe(true) + await field.fill('Thanks for the fix') + await send.click() + await expect.poll(async () => await comments.count()).toBe(2) + expect(await comments.last().textContent()).toContain('Thanks for the fix') + expect(await field.inputValue()).toBe('') + const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) + expect(calls.filter(call => call[4] === 'POST')) + .toEqual([['api', '--hostname', 'github.com', '--method', 'POST', 'repos/octo/demo/issues/7/comments', '--input', '-']]) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + it.skipIf(MODE === 'record')('adds a host on the GitLab row of the Plugins page, which the provider serves without a restart', async () => { const { scaffold, page, tripwire } = await launchPanel('web-e2e-forge-hosts') // The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first. diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 4c61c3a61b..5425d1af7b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1337,7 +1337,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:847`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:899`](../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 b9a96ff978..d8f5764c47 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1339,7 +1339,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:847`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:899`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index a32e903195..10d73bc0b7 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -47,8 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-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:34`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | -| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:43`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:35`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:44`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `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 6eb93f5c6f..e17c7eea77 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -49,8 +49,8 @@ | `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-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:34`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | -| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:43`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:35`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:44`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `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 faeaa7ed01..fa6ad6f83f 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -23,6 +23,9 @@ /forges/viewer-lists-and-descriptions: en: 05dba49e668fbd82 zh: 7502689f5dd46118 +/forges/activity-and-comments: + en: fdfee3180c86d028 + zh: 8b092bb23594c7a7 /forges/session-bindings: en: 74255d6005e1c9e8 zh: 252d0d552f1e26a1 @@ -30,8 +33,8 @@ en: 83ad892728d13987 zh: d19b012f5898ef07 /forges/panel/review-page: - en: 0e003249228a7d55 - zh: 1643e6c79f4c255b + en: 048a1c4986943570 + zh: a87afd2830c9fb15 /forges/extension-api: en: f35345e482e84f4f zh: 2ecb7d9498decb31 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 7eb94e2631..4393c4a9ee 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -68,6 +68,17 @@ interface ForgeProvider { countForViewer?(host: string, signal: AbortSignal): Promise | ForgeFailure> /** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */ readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the activity of a change request: the comments in its conversation, its submitted reviews, its commits, and + * the changes of its state. Omission declares that this provider reads no activity. + */ + readActivity?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Add a comment of Markdown source `body` to a change request's conversation, resolving to undefined once the host + * saved it. A comment is never retried. Omission declares that this provider adds no comments, and its `readActivity` + * then denies `viewerCanComment`. + */ + addComment?(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise /** @@ -997,6 +1008,55 @@ interface ChangeRequestLabel { } ``` +## Activity and comments + +`ctx.forge.readActivity` reads what happened on a change request: the comments in its conversation, its submitted reviews, its commits, and the changes of its state, oldest first, at most the provider's limit with the latest entries kept. `ctx.forge.addComment` adds a comment to the conversation and then polls the change request at once when it is watched. A provider implements either method or both: `readActivity` of a provider without it returns `unsupported`, `addComment` of one without it fails, and an activity's `viewerCanComment` says whether the signed-in user can add a comment. The text of a comment or review is Markdown source whose raw HTML must not render as HTML. The [GitHub](../../packages/experimental/forge-github/README.md#use-this-package) and [GitLab](../../packages/experimental/forge-gitlab/README.md#use-this-package) provider READMEs own the requests and how each host's records become entries. + +```ts type-equiv +/** + * One entry of a change request's activity: a comment in its conversation, a submitted review, a commit, a change of + * its state, or a record the host words itself. + */ +type ChangeRequestActivityItem = { + /** ISO 8601 time of the entry. */ + readonly at: string + /** Account the entry is by, or null when the host names none or the account no longer exists. */ + readonly actor: ForgeCommentAuthor | null +} & ( + /** A comment in the conversation. `body` is Markdown source; it may contain raw HTML, which readers must not render as HTML. */ + | { readonly kind: 'comment'; readonly body: string; readonly url: string | null } + /** + * A submitted review: its decision, its own Markdown text, which follows the rule of a comment's `body` and is empty + * without one, and the number of comments it left on lines and files. + */ + | { readonly kind: 'review'; readonly verdict: ReviewVerdict; readonly body: string; readonly comments: number; readonly url: string | null } + /** + * A commit added to the change request: its object name, abbreviated when the host records only an abbreviation, and + * the first line of its message. + */ + | { readonly kind: 'commit'; readonly sha: string; readonly title: string } + | { readonly kind: 'merged' | 'closed' | 'reopened' | 'ready-for-review' | 'converted-to-draft' | 'force-pushed' } + | { readonly kind: 'auto-merge-enabled' | 'auto-merge-disabled' } + /** A review was requested from an account or a team, named as the host spells it; null when the host names neither. */ + | { readonly kind: 'review-requested'; readonly reviewer: string | null } + | { readonly kind: 'renamed'; readonly from: string; readonly to: string } + /** A record with no kind of its own, as plain text in the host's own words. */ + | { readonly kind: 'other'; readonly text: string } +) +``` + +```ts type-equiv +/** The activity of a change request. */ +interface ChangeRequestActivity { + /** Entries oldest first, at most the provider's limit; the latest ones when the change request has more. */ + readonly items: readonly ChangeRequestActivityItem[] + /** Whether the change request has entries older than `items` holds. */ + readonly truncated: boolean + /** Whether the signed-in user can add a comment through `addComment`; false for a provider without it. */ + readonly viewerCanComment: boolean +} +``` + ## Session bindings `ctx.forgeSession` derives each Session's bindings from its own log by the command rules that providers register: forge-github's `gh` rule and forge-gitlab's `glab` rule bind the URLs that `gh pr create` and `glab mr create` results print and the change request that `gh pr view`, `glab mr view`, and their sibling reference commands 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. @@ -1616,7 +1676,7 @@ interface ForgeLocalChanges { ### Review page -The [code review page](../../packages/experimental/client-ui-forge/README.md#use-this-package) reads change requests by URL instead of through a Session binding. Its `forgePanel` methods (`reviewLists`, `reviewCount`, `reviewChangeRequest`, `reviewDescription`, and the `review*` reads and actions that mirror the Session-bound ones) resolve the URL with `ForgeService.changeRequestFromUrl`, fail with `forgePanel/unrecognized-url` when no provider serves it, and name no Session resource, so only callers that may use the Host's code host credentials reach them. One list hub reads the [viewer lists](#viewer-lists-and-descriptions) only while a list or count stream lasts: streams of one repository scope share one reader that reads every list of every host each `reviewListIntervalMs`, hosts in parallel and each host's lists in order, stops the round's further reads on a host that refuses the viewer or is rate-limited, and reads a host whose read failed again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence; the count reads every `reviewCountIntervalMs` in the same way, and lists of every repository refresh it too. A scope is every repository of every host or one `ForgeReviewRepository`, which names its host and is read on that host only. `reviewLists` streams `ForgeReviewFrame` values with each host's lists, the items of the latest successful read, the failure of the latest read, and, for a host that refused the viewer, the sign-in command its provider's `readiness` names; `reviewCount` streams `ForgeReviewCountFrame` values; and `reviewChangeRequest` streams `ForgeReviewChangeRequest` values for the shown change request, which is polled through `ForgeService.watch` while its stream lasts. +The [code review page](../../packages/experimental/client-ui-forge/README.md#use-this-package) reads change requests by URL instead of through a Session binding. Its `forgePanel` methods (`reviewLists`, `reviewCount`, `reviewChangeRequest`, `reviewDescription`, `reviewActivity`, `reviewComment`, and the `review*` reads and actions that mirror the Session-bound ones) resolve the URL with `ForgeService.changeRequestFromUrl`, fail with `forgePanel/unrecognized-url` when no provider serves it, and name no Session resource, so only callers that may use the Host's code host credentials reach them. One list hub reads the [viewer lists](#viewer-lists-and-descriptions) only while a list or count stream lasts: streams of one repository scope share one reader that reads every list of every host each `reviewListIntervalMs`, hosts in parallel and each host's lists in order, stops the round's further reads on a host that refuses the viewer or is rate-limited, and reads a host whose read failed again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence; the count reads every `reviewCountIntervalMs` in the same way, and lists of every repository refresh it too. A scope is every repository of every host or one `ForgeReviewRepository`, which names its host and is read on that host only. `reviewLists` streams `ForgeReviewFrame` values with each host's lists, the items of the latest successful read, the failure of the latest read, and, for a host that refused the viewer, the sign-in command its provider's `readiness` names; `reviewCount` streams `ForgeReviewCountFrame` values; and `reviewChangeRequest` streams `ForgeReviewChangeRequest` values for the shown change request, which is polled through `ForgeService.watch` while its stream lasts. The chat tab starts in the blank Session `connectWorkspace` resolves and records the change request with `reviewStage`; the Host keeps that choice in memory and binds the change request once the Session's next message enters its inbox, so an untouched blank stays unbound. @@ -2014,6 +2074,25 @@ async countForViewer(forge: string, host: string, signal: AbortSignal): Promise< */ async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Read the activity of a change request: its comments, submitted reviews, commits, and changes of state. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the activity, or why the host did not provide it; `unsupported` when the provider reads no activity. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async readActivity(ref: ChangeRequestRef, signal: AbortSignal): Promise + +/** + * Add a comment to a change request's conversation, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param body - Markdown source of the comment. + * @param signal - cancellation of the request. + * @returns undefined once the host saved the comment, or why it did not; a provider that adds no comments fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async addComment(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced * with `forge/review-changed`. @@ -2202,6 +2281,27 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async reviewDescription(url: string, signal: AbortSignal): Promise +/** + * Read the activity of a change request for the review page: its comments, submitted reviews, commits, and changes + * of state. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @returns the activity, or null when the change request's provider reads none. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/activity-failed` with the + * host's reason when the host does not provide it. + */ +@Remote async reviewActivity(url: string, signal: AbortSignal): Promise + +/** + * Add a comment to the conversation of a change request the review page shows. + * @param url - web URL of the change request. + * @param body - Markdown source of the comment. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` when `body` is + * blank, or with the host's reason; `forgePanel/action-unknown` when the host's answer did not confirm the comment. + */ +@Remote async reviewComment(url: string, body: string, signal: AbortSignal): Promise + /** * Read every check of a change request the review page shows. * @param url - web URL of the change request. diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 637f3f3b3e..b8d3ed71b9 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -68,6 +68,17 @@ interface ForgeProvider { countForViewer?(host: string, signal: AbortSignal): Promise | ForgeFailure> /** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */ readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the activity of a change request: the comments in its conversation, its submitted reviews, its commits, and + * the changes of its state. Omission declares that this provider reads no activity. + */ + readActivity?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Add a comment of Markdown source `body` to a change request's conversation, resolving to undefined once the host + * saved it. A comment is never retried. Omission declares that this provider adds no comments, and its `readActivity` + * then denies `viewerCanComment`. + */ + addComment?(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise /** @@ -1001,6 +1012,55 @@ interface ChangeRequestLabel { } ``` +## 动态与评论 + +`ctx.forge.readActivity` 读取变更请求上发生过的事:对话中的评论、已提交的评审、提交,以及状态的变化,按时间从旧到新,最多为提供方的上限,超出时保留最新的条目。`ctx.forge.addComment` 向对话添加一条评论,之后如果该变更请求正被监视,就立即轮询一次。提供方可以实现其中一个或两个方法:没有 `readActivity` 的提供方返回 `unsupported`,没有 `addComment` 的提供方返回失败;动态的 `viewerCanComment` 说明当前用户能否添加评论。评论和评审的正文是 Markdown 源文本,其中的原始 HTML 不得作为 HTML 渲染。请求以及各主机的记录如何变成条目,由 [GitHub](../../packages/experimental/forge-github/README.zh.md#use-this-package) 与 [GitLab](../../packages/experimental/forge-gitlab/README.zh.md#use-this-package) 提供方的 README 说明。 + +```ts type-equiv +/** + * One entry of a change request's activity: a comment in its conversation, a submitted review, a commit, a change of + * its state, or a record the host words itself. + */ +type ChangeRequestActivityItem = { + /** ISO 8601 time of the entry. */ + readonly at: string + /** Account the entry is by, or null when the host names none or the account no longer exists. */ + readonly actor: ForgeCommentAuthor | null +} & ( + /** A comment in the conversation. `body` is Markdown source; it may contain raw HTML, which readers must not render as HTML. */ + | { readonly kind: 'comment'; readonly body: string; readonly url: string | null } + /** + * A submitted review: its decision, its own Markdown text, which follows the rule of a comment's `body` and is empty + * without one, and the number of comments it left on lines and files. + */ + | { readonly kind: 'review'; readonly verdict: ReviewVerdict; readonly body: string; readonly comments: number; readonly url: string | null } + /** + * A commit added to the change request: its object name, abbreviated when the host records only an abbreviation, and + * the first line of its message. + */ + | { readonly kind: 'commit'; readonly sha: string; readonly title: string } + | { readonly kind: 'merged' | 'closed' | 'reopened' | 'ready-for-review' | 'converted-to-draft' | 'force-pushed' } + | { readonly kind: 'auto-merge-enabled' | 'auto-merge-disabled' } + /** A review was requested from an account or a team, named as the host spells it; null when the host names neither. */ + | { readonly kind: 'review-requested'; readonly reviewer: string | null } + | { readonly kind: 'renamed'; readonly from: string; readonly to: string } + /** A record with no kind of its own, as plain text in the host's own words. */ + | { readonly kind: 'other'; readonly text: string } +) +``` + +```ts type-equiv +/** The activity of a change request. */ +interface ChangeRequestActivity { + /** Entries oldest first, at most the provider's limit; the latest ones when the change request has more. */ + readonly items: readonly ChangeRequestActivityItem[] + /** Whether the change request has entries older than `items` holds. */ + readonly truncated: boolean + /** Whether the signed-in user can add a comment through `addComment`; false for a provider without it. */ + readonly viewerCanComment: boolean +} +``` + ## Session 绑定 `ctx.forgeSession` 按提供方注册的命令规则,从每个 Session 自己的日志派生其绑定:forge-github 的 `gh` 规则与 forge-gitlab 的 `glab` 规则绑定 `gh pr create` 与 `glab mr create` 结果输出的 URL,以及 `gh pr view`、`glab mr view` 及其同类引用命令所操作的变更请求,`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)。 @@ -1620,7 +1680,7 @@ interface ForgeLocalChanges { ### 代码评审页 -[代码评审页](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)按 URL 读取变更请求,而不经过会话绑定。它的 `forgePanel` 方法(`reviewLists`、`reviewCount`、`reviewChangeRequest`、`reviewDescription`,以及与会话绑定版本对应的各个 `review*` 读取与操作)用 `ForgeService.changeRequestFromUrl` 解析 URL,没有提供方能处理时以 `forgePanel/unrecognized-url` 失败;它们不指向任何会话资源,因此只有可以使用 Host 代码托管凭据的调用方能访问。一个列表中心只在列表流或计数流存在时读取[登录用户的列表](#viewer-lists-and-descriptions):同一仓库范围的流共用一个读取器,它每隔 `reviewListIntervalMs` 读取每个主机的每个列表,各主机并行、同一主机的列表依次读取;某主机拒绝当前用户或触发限流时,本轮不再读取它的其余列表;读取失败的主机每次间隔更久再读,以 `reviewMaxBackoffMs` 为上限,其他主机保持原来的间隔。计数每隔 `reviewCountIntervalMs` 以同样的方式读取,全部仓库范围的列表读取也会更新它。范围是全部主机的全部仓库,或一个 `ForgeReviewRepository`;后者带有主机,只在该主机上读取。`reviewLists` 流式返回 `ForgeReviewFrame`,含每个主机的列表、最近一次成功读取的条目、最近一次读取的失败,以及主机拒绝当前用户时其提供方的 `readiness` 给出的登录命令;`reviewCount` 流式返回 `ForgeReviewCountFrame`;`reviewChangeRequest` 为显示中的变更请求流式返回 `ForgeReviewChangeRequest`,该变更请求在其流存在期间经 `ForgeService.watch` 轮询。 +[代码评审页](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)按 URL 读取变更请求,而不经过会话绑定。它的 `forgePanel` 方法(`reviewLists`、`reviewCount`、`reviewChangeRequest`、`reviewDescription`、`reviewActivity`、`reviewComment`,以及与会话绑定版本对应的各个 `review*` 读取与操作)用 `ForgeService.changeRequestFromUrl` 解析 URL,没有提供方能处理时以 `forgePanel/unrecognized-url` 失败;它们不指向任何会话资源,因此只有可以使用 Host 代码托管凭据的调用方能访问。一个列表中心只在列表流或计数流存在时读取[登录用户的列表](#viewer-lists-and-descriptions):同一仓库范围的流共用一个读取器,它每隔 `reviewListIntervalMs` 读取每个主机的每个列表,各主机并行、同一主机的列表依次读取;某主机拒绝当前用户或触发限流时,本轮不再读取它的其余列表;读取失败的主机每次间隔更久再读,以 `reviewMaxBackoffMs` 为上限,其他主机保持原来的间隔。计数每隔 `reviewCountIntervalMs` 以同样的方式读取,全部仓库范围的列表读取也会更新它。范围是全部主机的全部仓库,或一个 `ForgeReviewRepository`;后者带有主机,只在该主机上读取。`reviewLists` 流式返回 `ForgeReviewFrame`,含每个主机的列表、最近一次成功读取的条目、最近一次读取的失败,以及主机拒绝当前用户时其提供方的 `readiness` 给出的登录命令;`reviewCount` 流式返回 `ForgeReviewCountFrame`;`reviewChangeRequest` 为显示中的变更请求流式返回 `ForgeReviewChangeRequest`,该变更请求在其流存在期间经 `ForgeService.watch` 轮询。 对话标签在 `connectWorkspace` 解析出的空白会话中开始,并用 `reviewStage` 记录该变更请求;Host 只在内存中保存这个选择,等该会话的下一条消息进入收件箱时再绑定,因此未使用的空白会话保持未绑定。 @@ -2018,6 +2078,25 @@ async countForViewer(forge: string, host: string, signal: AbortSignal): Promise< */ async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Read the activity of a change request: its comments, submitted reviews, commits, and changes of state. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the activity, or why the host did not provide it; `unsupported` when the provider reads no activity. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async readActivity(ref: ChangeRequestRef, signal: AbortSignal): Promise + +/** + * Add a comment to a change request's conversation, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param body - Markdown source of the comment. + * @param signal - cancellation of the request. + * @returns undefined once the host saved the comment, or why it did not; a provider that adds no comments fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async addComment(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced * with `forge/review-changed`. @@ -2206,6 +2285,27 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async reviewDescription(url: string, signal: AbortSignal): Promise +/** + * Read the activity of a change request for the review page: its comments, submitted reviews, commits, and changes + * of state. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @returns the activity, or null when the change request's provider reads none. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/activity-failed` with the + * host's reason when the host does not provide it. + */ +@Remote async reviewActivity(url: string, signal: AbortSignal): Promise + +/** + * Add a comment to the conversation of a change request the review page shows. + * @param url - web URL of the change request. + * @param body - Markdown source of the comment. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` when `body` is + * blank, or with the host's reason; `forgePanel/action-unknown` when the host's answer did not confirm the comment. + */ +@Remote async reviewComment(url: string, body: string, signal: AbortSignal): Promise + /** * Read every check of a change request the review page shows. * @param url - web URL of the change request. diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index a6f925b625..c722e7c287 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 359352a208ca8a11 - zh: b581a4d0a7067e3d + en: 003ae721f4b9a77b + zh: 3e398fbe15513ecd /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: en: e20276738f193646 zh: 79f2fa0e734f8f93 @@ -30,8 +30,8 @@ en: c1b5bfb0e5a1801e zh: 2bbe1a2845aa5d20 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: bf093028c331e076 - zh: da05205c6b036b16 + en: 24b2aa5275faac64 + zh: 4b2f2819b479a363 /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 4e719e3406..91ff02b468 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -34,7 +34,8 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Provider hosts** — the bundle's GitHub and GitLab rows on the Plugins page each open a page that lists the hosts the provider serves. Add, or Enter, stages the typed host name, or the host and port of a pasted URL, and refuses below the field a name that is malformed, already listed, or served by the other provider; a row's remove button stages its removal, except for the last host. Save writes the whole list to the profile patch, and the provider serves it without a restart. Each saved host shows Signed in, Not signed in with the provider's sign-in command and Copy, or Can't check with the reason; the page reads these when it shows, after a save, when the window regains focus, and from the button beside the list's title. A deployment that stores settings read-only shows the list without the edits. - **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph. -- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a host's first read of a list runs, skeleton rows laid out as the chosen view stand in for its items, below the items of the hosts that answered, and the list's count and its empty text wait for that host. A list item shows its title on at most two lines and its small text on at most two: the repository when the lists span more than one, the number, and the author, with the short update time at the end of that line, then at most one hint, such as Re-review requested or a team request, which shares that line where both fit and takes the second where they do not; the search box filters the lists by title, number, repository, author, and host under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. Once the lists name repositories on more than one host, the submenu lists each host with its repositories below it: choosing a host shows only its change requests, and choosing a repository reads the lists in it on its host only. A host whose lists could not be read shows one notice after the lists, with the sign-in command its provider names and Copy, or else the reason, and Open settings, which opens the bundle's page on the Plugins page while that page is available; when no host listed anything, the notices are all the column shows. A host whose read failed is read again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and links whose host no provider serves show where they apply; such a link shows Unknown code host with Add host…, which opens the bundle's page on the Plugins page while that page is available. +- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a host's first read of a list runs, skeleton rows laid out as the chosen view stand in for its items, below the items of the hosts that answered, and the list's count and its empty text wait for that host. A list item shows its title on at most two lines and its small text on at most two: the repository when the lists span more than one, the number, and the author, with the short update time at the end of that line, then at most one hint, such as Re-review requested or a team request, which shares that line where both fit and takes the second where they do not; the search box filters the lists by title, number, repository, author, and host under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. Once the lists name repositories on more than one host, the submenu lists each host with its repositories below it: choosing a host shows only its change requests, and choosing a repository reads the lists in it on its host only. A host whose lists could not be read shows one notice after the lists, with the sign-in command its provider names and Copy, or else the reason, and Open settings, which opens the bundle's page on the Plugins page while that page is available; when no host listed anything, the notices are all the column shows. A host whose read failed is read again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description, with the activity under it, beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and links whose host no provider serves show where they apply; such a link shows Unknown code host with Add host…, which opens the bundle's page on the Plugins page while that page is available. +- **Review page activity** — under the description, the Summary tab lists what happened on the change request, oldest first: each comment as a card with its author and Markdown text, each submitted review with its decision, each commit, and each change of state, such as a review request, a title change, or the merge. Consecutive commits show as one line that unfolds them, a review that left comments on lines or files opens the Changes tab, and a long comment starts cut short with Expand. The field under the list adds a comment through the Comment button or Command or Control with Enter; when the code host did not save the comment, the field keeps its text and says why. The list is read again after a comment and whenever the change request's update time or its reviews change. A provider that reads no activity shows no such section, and the field shows only where the signed-in user can comment. - **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden. - **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row. - **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away. @@ -178,6 +179,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. - **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — the lists hold every configured host of every provider that lists change requests, the GitHub and GitLab providers today, and what a list holds on a host is its provider's to define: the GitLab provider's lists and their differences from GitHub's are in [its limitations](../forge-gitlab/README.md#known-limitations-and-deferred-work). A list row names no host; the repository submenu and the search box tell hosts apart. The left navigation's count does not follow the host or repository the lists are narrowed to. Choosing among accounts of one host is not offered. The changes tab shows no plugin lenses, annotations, toolbar, file-menu, or comment-form entries, whose extension points name a Session, and its quotes go to the chat's draft instead of the Session's input. The chat starts in the Workspace's shared blank Session, which New Session also shows, and does not check that the Workspace is a checkout of the repository; the change request to bind waits in Host memory until the first message, so a Host restart forgets it. Pending review comments last while the page shows their change request. +- **Review page activity** — the list holds the latest entries up to the provider's limit and links to the code host for earlier ones. Comments cannot be edited, deleted, or answered with a reaction, `@` names are not completed, a comment's images that need the user's host session do not load, and the comments a review left on lines or files are read and answered on the Changes tab only. ### Dev Note diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 0a59d5d4bc..fa4769023d 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -34,7 +34,8 @@ kind: "package-reference" - **提供方主机**——插件页上该套件的 GitHub 行与 GitLab 行各打开一个页面,列出该提供方服务的主机。“添加”或 Enter 把输入的主机名(粘贴 URL 时取其中的主机与端口)加入待保存的列表;格式不对、已在列表中或已由另一个提供方服务的主机名不会加入,原因显示在输入框下方。行尾的移除按钮把该主机从待保存的列表中去掉,最后一个主机不能移除。“保存”把整个列表写入 profile patch,提供方无需重启即服务新列表。每个已保存的主机显示“已登录”、“未登录”(附提供方给出的登录命令与“复制”)或“无法检查”(附原因);页面在显示时、保存后、窗口重新获得焦点时以及点击列表标题旁的按钮时读取这些状态。以只读方式保存设置的部署只显示列表,不能修改。 - **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。 -- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。某个主机首次读取列表期间,按所选视图排布的骨架行占据它的列表项的位置,排在已返回的主机的列表项之后,列表的计数与空列表文字等它返回后再显示。列表项的标题至多两行,小字至多两行:列表跨多个仓库时写出仓库名,然后是编号和作者,简短的更新时间在这一行末尾,之后是至多一条提示,如“待你复审”或团队请求,放得下时与它们同一行,放不下时换到第二行;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库、作者和主机筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。列表里的仓库来自多个主机时,子菜单列出每个主机,主机的仓库列在它下面:选主机只显示该主机的变更请求,选仓库只在它所在的主机上读取列表。读取失败的主机在列表之后各显示一条提示:提供方给出登录命令时显示该命令与“复制”,否则显示原因;另有“前往配置”,在插件页可用时打开该套件的页面;没有主机列出任何内容时,这一栏只显示这些提示。读取失败的主机每次间隔更久再读,上限为 `reviewMaxBackoffMs`,其他主机保持原来的间隔。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接的主机没有提供方服务时在对应位置提示;后一种情况显示“未知的代码托管平台”与“添加主机…”,在插件页可用时打开该套件的页面。 +- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。某个主机首次读取列表期间,按所选视图排布的骨架行占据它的列表项的位置,排在已返回的主机的列表项之后,列表的计数与空列表文字等它返回后再显示。列表项的标题至多两行,小字至多两行:列表跨多个仓库时写出仓库名,然后是编号和作者,简短的更新时间在这一行末尾,之后是至多一条提示,如“待你复审”或团队请求,放得下时与它们同一行,放不下时换到第二行;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库、作者和主机筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。列表里的仓库来自多个主机时,子菜单列出每个主机,主机的仓库列在它下面:选主机只显示该主机的变更请求,选仓库只在它所在的主机上读取列表。读取失败的主机在列表之后各显示一条提示:提供方给出登录命令时显示该命令与“复制”,否则显示原因;另有“前往配置”,在插件页可用时打开该套件的页面;没有主机列出任何内容时,这一栏只显示这些提示。读取失败的主机每次间隔更久再读,上限为 `reviewMaxBackoffMs`,其他主机保持原来的间隔。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述及其下方的动态旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接的主机没有提供方服务时在对应位置提示;后一种情况显示“未知的代码托管平台”与“添加主机…”,在插件页可用时打开该套件的页面。 +- **评审页动态**——“概要”标签页在描述下方按时间从旧到新列出变更请求上发生过的事:每条评论是一张带作者和 Markdown 正文的卡片,每次已提交的评审带它的结论,每个提交,以及每次状态变化,如请求评审、修改标题或合并。连续的提交合成一行,可展开;在行或文件上留了评论的评审会打开“变更”标签页;长评论先截短显示,可“展开”。列表下方的输入框用“评论”按钮或 Command / Control 加 Enter 添加评论;代码托管平台没有保存评论时,输入框保留文字并说明原因。添加评论之后,以及变更请求的更新时间或评审发生变化时,列表会重新读取。提供方不读取动态时不显示这一区域,输入框只在当前用户可以评论时显示。 - **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。 - **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。 - **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。 @@ -178,6 +179,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码评审页**——列表合并列出每个能列出变更请求的提供方(目前是 GitHub 与 GitLab 提供方)的全部已配置主机,某个列表在一个主机上包含什么由该主机的提供方决定:GitLab 提供方的列表及其与 GitHub 的差别见[它的限制](../forge-gitlab/README.zh.md#known-limitations-and-deferred-work)。列表行不写主机,主机通过仓库子菜单和搜索框区分。左侧导航上的计数不随列表所限定的主机或仓库变化。同一主机的多个账号之间不提供选择。“变更”标签不显示插件的透镜、行注释、工具栏、文件菜单和评论表单入口(这些扩展点以会话为对象),引用放进对话草稿而不是会话输入框。对话在工作区共享的空白会话中开始,“新会话”也显示这个会话,且不检查该工作区是否是此仓库的检出;待绑定的变更请求在首条消息前只保存在 Host 内存中,Host 重启会丢失。未提交的评审评论只在页面显示该变更请求期间保留。 +- **评审页动态**——列表保留最新的条目,数量不超过提供方的上限,更早的条目给出到代码托管平台查看的链接。评论不能编辑、删除或用表情回应,`@` 名字没有补全,评论中需要用户托管平台会话的图片无法加载;评审在行或文件上留下的评论只能在“变更”标签页查看和回复。 ### 开发备注 diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index 883f0b9404..3abe7bb4bf 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -556,6 +556,31 @@ export const zh = { 'reviewPage.description': '描述', 'reviewPage.descriptionEmpty': '没有描述', 'reviewPage.descriptionFailed': '描述读取失败:{message}', + 'reviewPage.activity': '动态', + 'reviewPage.activity.empty': '还没有动态', + 'reviewPage.activity.failed': '动态读取失败:{message}', + 'reviewPage.activity.older': '更早的动态没有列出', + 'reviewPage.activity.commits': '{count} 次提交', + 'reviewPage.activity.inline': '{count} 条行内评论', + 'reviewPage.activity.viewInChanges': '在变更中查看', + 'reviewPage.activity.approved': '{actor} 批准了这些更改', + 'reviewPage.activity.changesRequested': '{actor} 要求修改', + 'reviewPage.activity.commented': '{actor} 评审了', + 'reviewPage.activity.dismissed': '{actor} 的评审被撤销', + 'reviewPage.activity.merged': '{actor} 合并了这个变更请求', + 'reviewPage.activity.closed': '{actor} 关闭了这个变更请求', + 'reviewPage.activity.reopened': '{actor} 重新打开了这个变更请求', + 'reviewPage.activity.readyForReview': '{actor} 标记为可以评审', + 'reviewPage.activity.convertedToDraft': '{actor} 转为草稿', + 'reviewPage.activity.forcePushed': '{actor} 强制推送了分支', + 'reviewPage.activity.autoMergeEnabled': '{actor} 启用了自动合并', + 'reviewPage.activity.autoMergeDisabled': '{actor} 取消了自动合并', + 'reviewPage.activity.reviewRequested': '{actor} 请求 {reviewer} 评审', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor} 请求了评审', + 'reviewPage.activity.renamed': '{actor} 把标题由“{from}”改为“{to}”', + 'reviewPage.activity.commentPlaceholder': '留下评论', + 'reviewPage.activity.comment': '评论', + 'reviewPage.activity.commentFailed': '评论没有发布:{message}', 'reviewPage.status': '状态', 'reviewPage.requestReview': '请求评审', 'reviewPage.showAll': '显示全部 {count} 项', @@ -1158,6 +1183,31 @@ export const en: Record = { 'reviewPage.description': 'Description', 'reviewPage.descriptionEmpty': 'No description', 'reviewPage.descriptionFailed': 'Couldn\'t read the description: {message}', + 'reviewPage.activity': 'Activity', + 'reviewPage.activity.empty': 'No activity yet', + 'reviewPage.activity.failed': 'Couldn\'t read the activity: {message}', + 'reviewPage.activity.older': 'Earlier activity is not listed', + 'reviewPage.activity.commits': 'Commits: {count}', + 'reviewPage.activity.inline': 'Inline comments: {count}', + 'reviewPage.activity.viewInChanges': 'View in Changes', + 'reviewPage.activity.approved': '{actor} approved these changes', + 'reviewPage.activity.changesRequested': '{actor} requested changes', + 'reviewPage.activity.commented': '{actor} reviewed', + 'reviewPage.activity.dismissed': '{actor}\'s review was dismissed', + 'reviewPage.activity.merged': '{actor} merged this', + 'reviewPage.activity.closed': '{actor} closed this', + 'reviewPage.activity.reopened': '{actor} reopened this', + 'reviewPage.activity.readyForReview': '{actor} marked this ready for review', + 'reviewPage.activity.convertedToDraft': '{actor} converted this to a draft', + 'reviewPage.activity.forcePushed': '{actor} force-pushed the branch', + 'reviewPage.activity.autoMergeEnabled': '{actor} enabled auto-merge', + 'reviewPage.activity.autoMergeDisabled': '{actor} disabled auto-merge', + 'reviewPage.activity.reviewRequested': '{actor} requested a review from {reviewer}', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor} requested a review', + 'reviewPage.activity.renamed': '{actor} changed the title from “{from}” to “{to}”', + 'reviewPage.activity.commentPlaceholder': 'Leave a comment', + 'reviewPage.activity.comment': 'Comment', + 'reviewPage.activity.commentFailed': 'The comment was not posted: {message}', 'reviewPage.status': 'Status', 'reviewPage.requestReview': 'Request a review', 'reviewPage.showAll': 'Show all {count}', @@ -1764,6 +1814,31 @@ export const ja: Record = { 'reviewPage.description': '説明', 'reviewPage.descriptionEmpty': '説明はありません', 'reviewPage.descriptionFailed': '説明を読み込めませんでした:{message}', + 'reviewPage.activity': 'アクティビティ', + 'reviewPage.activity.empty': 'まだアクティビティはありません', + 'reviewPage.activity.failed': 'アクティビティを読み込めませんでした:{message}', + 'reviewPage.activity.older': 'これより前のアクティビティは表示されていません', + 'reviewPage.activity.commits': 'コミット {count} 件', + 'reviewPage.activity.inline': '行コメント {count} 件', + 'reviewPage.activity.viewInChanges': '変更で表示', + 'reviewPage.activity.approved': '{actor} が変更を承認しました', + 'reviewPage.activity.changesRequested': '{actor} が修正を依頼しました', + 'reviewPage.activity.commented': '{actor} がレビューしました', + 'reviewPage.activity.dismissed': '{actor} のレビューは却下されました', + 'reviewPage.activity.merged': '{actor} がマージしました', + 'reviewPage.activity.closed': '{actor} がクローズしました', + 'reviewPage.activity.reopened': '{actor} が再オープンしました', + 'reviewPage.activity.readyForReview': '{actor} がレビュー可能にしました', + 'reviewPage.activity.convertedToDraft': '{actor} が下書きに戻しました', + 'reviewPage.activity.forcePushed': '{actor} がブランチを強制プッシュしました', + 'reviewPage.activity.autoMergeEnabled': '{actor} が自動マージを有効にしました', + 'reviewPage.activity.autoMergeDisabled': '{actor} が自動マージを無効にしました', + 'reviewPage.activity.reviewRequested': '{actor} が {reviewer} にレビューを依頼しました', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor} がレビューを依頼しました', + 'reviewPage.activity.renamed': '{actor} がタイトルを「{from}」から「{to}」に変更しました', + 'reviewPage.activity.commentPlaceholder': 'コメントを書く', + 'reviewPage.activity.comment': 'コメント', + 'reviewPage.activity.commentFailed': 'コメントを投稿できませんでした:{message}', 'reviewPage.status': '状態', 'reviewPage.requestReview': 'レビューを依頼', 'reviewPage.showAll': '{count}件すべて表示', @@ -2363,6 +2438,31 @@ export const es: Record = { 'reviewPage.description': 'Descripción', 'reviewPage.descriptionEmpty': 'Sin descripción', 'reviewPage.descriptionFailed': 'No se pudo leer la descripción: {message}', + 'reviewPage.activity': 'Actividad', + 'reviewPage.activity.empty': 'Aún no hay actividad', + 'reviewPage.activity.failed': 'No se pudo leer la actividad: {message}', + 'reviewPage.activity.older': 'La actividad anterior no se muestra', + 'reviewPage.activity.commits': 'Commits: {count}', + 'reviewPage.activity.inline': 'Comentarios en línea: {count}', + 'reviewPage.activity.viewInChanges': 'Ver en Cambios', + 'reviewPage.activity.approved': '{actor} aprobó estos cambios', + 'reviewPage.activity.changesRequested': '{actor} pidió cambios', + 'reviewPage.activity.commented': '{actor} revisó', + 'reviewPage.activity.dismissed': 'La revisión de {actor} fue descartada', + 'reviewPage.activity.merged': '{actor} fusionó esta solicitud', + 'reviewPage.activity.closed': '{actor} cerró esta solicitud', + 'reviewPage.activity.reopened': '{actor} reabrió esta solicitud', + 'reviewPage.activity.readyForReview': '{actor} la marcó como lista para revisión', + 'reviewPage.activity.convertedToDraft': '{actor} la convirtió en borrador', + 'reviewPage.activity.forcePushed': '{actor} forzó el push de la rama', + 'reviewPage.activity.autoMergeEnabled': '{actor} activó la fusión automática', + 'reviewPage.activity.autoMergeDisabled': '{actor} desactivó la fusión automática', + 'reviewPage.activity.reviewRequested': '{actor} pidió una revisión a {reviewer}', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor} pidió una revisión', + 'reviewPage.activity.renamed': '{actor} cambió el título de «{from}» a «{to}»', + 'reviewPage.activity.commentPlaceholder': 'Deja un comentario', + 'reviewPage.activity.comment': 'Comentar', + 'reviewPage.activity.commentFailed': 'El comentario no se publicó: {message}', 'reviewPage.status': 'Estado', 'reviewPage.requestReview': 'Solicitar revisión', 'reviewPage.showAll': 'Mostrar los {count}', @@ -2962,6 +3062,31 @@ export const fr: Record = { 'reviewPage.description': 'Description', 'reviewPage.descriptionEmpty': 'Aucune description', 'reviewPage.descriptionFailed': 'Impossible de lire la description : {message}', + 'reviewPage.activity': 'Activité', + 'reviewPage.activity.empty': 'Aucune activité pour le moment', + 'reviewPage.activity.failed': 'Impossible de lire l’activité : {message}', + 'reviewPage.activity.older': 'L’activité plus ancienne n’est pas affichée', + 'reviewPage.activity.commits': 'Commits : {count}', + 'reviewPage.activity.inline': 'Commentaires en ligne : {count}', + 'reviewPage.activity.viewInChanges': 'Voir dans Modifications', + 'reviewPage.activity.approved': '{actor} a approuvé ces modifications', + 'reviewPage.activity.changesRequested': '{actor} a demandé des modifications', + 'reviewPage.activity.commented': '{actor} a fait une revue', + 'reviewPage.activity.dismissed': 'La revue de {actor} a été rejetée', + 'reviewPage.activity.merged': '{actor} a fusionné cette demande', + 'reviewPage.activity.closed': '{actor} a fermé cette demande', + 'reviewPage.activity.reopened': '{actor} a rouvert cette demande', + 'reviewPage.activity.readyForReview': '{actor} l’a marquée comme prête pour la revue', + 'reviewPage.activity.convertedToDraft': '{actor} l’a convertie en brouillon', + 'reviewPage.activity.forcePushed': '{actor} a forcé le push de la branche', + 'reviewPage.activity.autoMergeEnabled': '{actor} a activé la fusion automatique', + 'reviewPage.activity.autoMergeDisabled': '{actor} a désactivé la fusion automatique', + 'reviewPage.activity.reviewRequested': '{actor} a demandé une revue à {reviewer}', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor} a demandé une revue', + 'reviewPage.activity.renamed': '{actor} a changé le titre de « {from} » en « {to} »', + 'reviewPage.activity.commentPlaceholder': 'Laisser un commentaire', + 'reviewPage.activity.comment': 'Commenter', + 'reviewPage.activity.commentFailed': 'Le commentaire n’a pas été publié : {message}', 'reviewPage.status': 'État', 'reviewPage.requestReview': 'Demander une revue', 'reviewPage.showAll': 'Afficher les {count}', @@ -3561,6 +3686,31 @@ export const de: Record = { 'reviewPage.description': 'Beschreibung', 'reviewPage.descriptionEmpty': 'Keine Beschreibung', 'reviewPage.descriptionFailed': 'Beschreibung konnte nicht gelesen werden: {message}', + 'reviewPage.activity': 'Aktivität', + 'reviewPage.activity.empty': 'Noch keine Aktivität', + 'reviewPage.activity.failed': 'Aktivität konnte nicht gelesen werden: {message}', + 'reviewPage.activity.older': 'Ältere Aktivität wird nicht aufgeführt', + 'reviewPage.activity.commits': 'Commits: {count}', + 'reviewPage.activity.inline': 'Zeilenkommentare: {count}', + 'reviewPage.activity.viewInChanges': 'In Änderungen ansehen', + 'reviewPage.activity.approved': '{actor} hat diese Änderungen genehmigt', + 'reviewPage.activity.changesRequested': '{actor} hat Änderungen angefordert', + 'reviewPage.activity.commented': '{actor} hat ein Review abgegeben', + 'reviewPage.activity.dismissed': 'Das Review von {actor} wurde verworfen', + 'reviewPage.activity.merged': '{actor} hat diesen Request gemergt', + 'reviewPage.activity.closed': '{actor} hat diesen Request geschlossen', + 'reviewPage.activity.reopened': '{actor} hat diesen Request wieder geöffnet', + 'reviewPage.activity.readyForReview': '{actor} hat ihn als bereit zum Review markiert', + 'reviewPage.activity.convertedToDraft': '{actor} hat ihn in einen Entwurf umgewandelt', + 'reviewPage.activity.forcePushed': '{actor} hat den Branch per Force-Push aktualisiert', + 'reviewPage.activity.autoMergeEnabled': '{actor} hat Auto-Merge aktiviert', + 'reviewPage.activity.autoMergeDisabled': '{actor} hat Auto-Merge deaktiviert', + 'reviewPage.activity.reviewRequested': '{actor} hat ein Review von {reviewer} angefragt', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor} hat ein Review angefragt', + 'reviewPage.activity.renamed': '{actor} hat den Titel von „{from}“ in „{to}“ geändert', + 'reviewPage.activity.commentPlaceholder': 'Kommentar schreiben', + 'reviewPage.activity.comment': 'Kommentieren', + 'reviewPage.activity.commentFailed': 'Der Kommentar wurde nicht veröffentlicht: {message}', 'reviewPage.status': 'Status', 'reviewPage.requestReview': 'Review anfordern', 'reviewPage.showAll': 'Alle {count} anzeigen', @@ -4160,6 +4310,31 @@ export const ru: Record = { 'reviewPage.description': 'Описание', 'reviewPage.descriptionEmpty': 'Нет описания', 'reviewPage.descriptionFailed': 'Не удалось прочитать описание: {message}', + 'reviewPage.activity': 'Активность', + 'reviewPage.activity.empty': 'Активности пока нет', + 'reviewPage.activity.failed': 'Не удалось прочитать активность: {message}', + 'reviewPage.activity.older': 'Более ранняя активность не показана', + 'reviewPage.activity.commits': 'Коммиты: {count}', + 'reviewPage.activity.inline': 'Комментарии к строкам: {count}', + 'reviewPage.activity.viewInChanges': 'Смотреть в изменениях', + 'reviewPage.activity.approved': '{actor}: изменения одобрены', + 'reviewPage.activity.changesRequested': '{actor}: запрошены правки', + 'reviewPage.activity.commented': '{actor}: проведено ревью', + 'reviewPage.activity.dismissed': '{actor}: ревью отклонено', + 'reviewPage.activity.merged': '{actor}: запрос слит', + 'reviewPage.activity.closed': '{actor}: запрос закрыт', + 'reviewPage.activity.reopened': '{actor}: запрос открыт заново', + 'reviewPage.activity.readyForReview': '{actor}: отмечено как готовое к ревью', + 'reviewPage.activity.convertedToDraft': '{actor}: переведено в черновик', + 'reviewPage.activity.forcePushed': '{actor}: ветка обновлена принудительной отправкой', + 'reviewPage.activity.autoMergeEnabled': '{actor}: включено автослияние', + 'reviewPage.activity.autoMergeDisabled': '{actor}: отключено автослияние', + 'reviewPage.activity.reviewRequested': '{actor}: запрошено ревью у {reviewer}', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor}: запрошено ревью', + 'reviewPage.activity.renamed': '{actor}: заголовок изменён с «{from}» на «{to}»', + 'reviewPage.activity.commentPlaceholder': 'Оставьте комментарий', + 'reviewPage.activity.comment': 'Комментировать', + 'reviewPage.activity.commentFailed': 'Комментарий не опубликован: {message}', 'reviewPage.status': 'Состояние', 'reviewPage.requestReview': 'Запросить ревью', 'reviewPage.showAll': 'Показать все {count}', @@ -4759,6 +4934,31 @@ export const pt: Record = { 'reviewPage.description': 'Descrição', 'reviewPage.descriptionEmpty': 'Sem descrição', 'reviewPage.descriptionFailed': 'Não foi possível ler a descrição: {message}', + 'reviewPage.activity': 'Atividade', + 'reviewPage.activity.empty': 'Ainda não há atividade', + 'reviewPage.activity.failed': 'Não foi possível ler a atividade: {message}', + 'reviewPage.activity.older': 'A atividade anterior não é exibida', + 'reviewPage.activity.commits': 'Commits: {count}', + 'reviewPage.activity.inline': 'Comentários em linha: {count}', + 'reviewPage.activity.viewInChanges': 'Ver em Alterações', + 'reviewPage.activity.approved': '{actor} aprovou estas alterações', + 'reviewPage.activity.changesRequested': '{actor} pediu alterações', + 'reviewPage.activity.commented': '{actor} revisou', + 'reviewPage.activity.dismissed': 'A revisão de {actor} foi descartada', + 'reviewPage.activity.merged': '{actor} fez o merge desta solicitação', + 'reviewPage.activity.closed': '{actor} fechou esta solicitação', + 'reviewPage.activity.reopened': '{actor} reabriu esta solicitação', + 'reviewPage.activity.readyForReview': '{actor} marcou como pronta para revisão', + 'reviewPage.activity.convertedToDraft': '{actor} converteu em rascunho', + 'reviewPage.activity.forcePushed': '{actor} forçou o push do branch', + 'reviewPage.activity.autoMergeEnabled': '{actor} ativou o merge automático', + 'reviewPage.activity.autoMergeDisabled': '{actor} desativou o merge automático', + 'reviewPage.activity.reviewRequested': '{actor} pediu uma revisão a {reviewer}', + 'reviewPage.activity.reviewRequestedUnnamed': '{actor} pediu uma revisão', + 'reviewPage.activity.renamed': '{actor} alterou o título de “{from}” para “{to}”', + 'reviewPage.activity.commentPlaceholder': 'Deixe um comentário', + 'reviewPage.activity.comment': 'Comentar', + 'reviewPage.activity.commentFailed': 'O comentário não foi publicado: {message}', 'reviewPage.status': 'Estado', 'reviewPage.requestReview': 'Solicitar revisão', 'reviewPage.showAll': 'Mostrar todos os {count}', diff --git a/packages/experimental/client-ui-forge/src/client/review-page/ReviewActivity.tsx b/packages/experimental/client-ui-forge/src/client/review-page/ReviewActivity.tsx new file mode 100644 index 0000000000..b609c8b9af --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/review-page/ReviewActivity.tsx @@ -0,0 +1,378 @@ +/** + * The summary tab's activity of one change request: its comments, submitted reviews, commits, and changes of state, + * oldest first, and the field that adds a comment. + */ + +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconBranchOutlineRegular, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconClockOutlineRegular, + IconCloseCircleFillRegular, IconEditOutlineRegular, IconEyeOutlineRegular, IconUserOutlineRegular, MarkdownText, StateDot, + type MarkdownLabels, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ChangeRequestActivity, ForgeCommentAuthor, ReviewVerdict } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { formatAgo } from '../format.ts' +import { ChangeRequestGlyph } from '../glyphs.tsx' +import type { NS } from '../locales.ts' +import { Avatar } from '../ReviewThreads.tsx' +import { activityEntries, longBody, type ActivityCommit, type ActivityEvent } from './review-activity.ts' +import { descriptionMarkdown } from './review-lists.ts' +import css from './ReviewPage.module.css' + +type Translate = PropsLocale['t'] + +/** Stands for the actor's name in a translated sentence, so each locale keeps its word order around the name. */ +const ACTOR = '\u0000' + +/** Characters of a commit's object name a row shows. */ +const SHORT_SHA = 7 + +/** Props of the activity. */ +export interface ReviewActivityProps { + /** URL of the change request. */ + readonly url: string + /** A value that differs once the change request changed, after which the activity is read again. */ + readonly revision: string + /** Product name of the change request's code host, or null once its provider left. */ + readonly forge: string | null + /** Read the activity; null for a provider that reads none. */ + readonly read: (url: string, signal: AbortSignal) => Promise> + /** Add a comment to the conversation. */ + readonly comment: (url: string, body: string) => Promise> + /** Show the changes tab. */ + readonly onOpenChanges: () => void + /** Open a web page in the browser. */ + readonly openLink: (url: string) => void + /** Current epoch milliseconds for relative times. */ + readonly now: number + /** Localized labels of rendered Markdown. */ + readonly markdown: MarkdownLabels + /** Forge panel copy. */ + readonly t: Translate +} + +/** The latest read of one change request's activity. */ +interface ActivityRead { + readonly url: string + /** The activity, null for a provider that reads none, or undefined while no read of this URL succeeded. */ + readonly activity: ChangeRequestActivity | null | undefined + readonly failure: string | null +} + +/** + * The activity of one change request, read again when the change request changes; + * an earlier read stays while a later one fails. + */ +function useActivity(url: string, revision: string, read: ReviewActivityProps['read']): { + readonly activity: ChangeRequestActivity | null | undefined + readonly failure: string | null + readonly reload: () => void +} { + const [attempt, setAttempt] = useState(0) + const [state, setState] = useState(null) + useEffect(() => { + const controller = new AbortController() + void read(url, controller.signal).then((result) => { + if (controller.signal.aborted) return + setState(previous => result.ok + ? { url, activity: result.value, failure: null } + : { url, activity: previous?.url === url ? previous.activity : undefined, failure: result.error.message }) + }) + return () => { controller.abort() } + }, [url, revision, attempt, read]) + const current = state?.url === url ? state : null + return { activity: current?.activity, failure: current?.failure ?? null, reload: () => { setAttempt(value => value + 1) } } +} + +/** The glyph of a commit. */ +function CommitGlyph(): ReactNode { + return ( + + ) +} + +/** + * One line of the activity: a glyph, what happened, when, and what stands at its end. With `act` it is a button of that + * accessible name. + */ +function Line({ glyph, tone, text, at, end, nested = false, expanded, act, now, t }: { + readonly glyph: ReactNode + readonly tone?: 'success' | 'error' | undefined + readonly text: ReactNode + readonly at: string + readonly end?: ReactNode + readonly nested?: boolean + readonly expanded?: boolean | undefined + readonly act?: { readonly label: string; readonly run: () => void } | undefined + readonly now: number + readonly t: Translate +}): ReactNode { + const content = ( + <> + {glyph} + {text} + {formatAgo(at, now, t)} + {end !== undefined && {end}} + + ) + const className = clsx(css.activityLine, nested && css.activityNested) + return act === undefined + ?
    {content}
    + : ( + + ) +} + +/** A translated sentence with the actor's name set apart from the rest. */ +function sentence(text: string, actor: ForgeCommentAuthor | null, t: Translate): ReactNode { + const [before, ...after] = text.split(ACTOR) + const name = actor?.login ?? t('thread.deletedAuthor') + return <>{before}{name}{after.join('')} +} + +/** One commit: its title, its time, and the start of its object name. */ +function CommitLine({ commit, nested, now, t }: { + readonly commit: ActivityCommit + readonly nested: boolean + readonly now: number + readonly t: Translate +}): ReactNode { + return ( + } text={nested ? commit.title : {commit.title}} at={commit.at} + nested={nested} end={{commit.sha.slice(0, SHORT_SHA)}} now={now} t={t} /> + ) +} + +/** A run of commits: one commit as its own line, several as a line that unfolds them. */ +function Commits({ commits, now, t }: { + readonly commits: readonly [ActivityCommit, ...ActivityCommit[]] + readonly now: number + readonly t: Translate +}): ReactNode { + const [open, setOpen] = useState(false) + const [first, ...later] = commits + const last = later.at(-1) + if (last === undefined) return + const count = t('reviewPage.activity.commits', { count: commits.length }) + return ( + <> + } text={{count}} + at={last.at} expanded={open} act={{ label: count, run: () => { setOpen(!open) } }} now={now} t={t} + end={} /> + {open && commits.map(commit => )} + + ) +} + +/** A comment's author, time, and text; a long text starts cut short. */ +function CommentCard({ actor, at, body, now, markdown, t }: { + readonly actor: ForgeCommentAuthor | null + readonly at: string + readonly body: string + readonly now: number + readonly markdown: MarkdownLabels + readonly t: Translate +}): ReactNode { + const long = longBody(body) + const [open, setOpen] = useState(false) + const text = useMemo(() => descriptionMarkdown(body, {}), [body]) + return ( +
    +
    + + {actor?.login ?? t('thread.deletedAuthor')} + {actor?.bot === true && {t('thread.bot')}} + {formatAgo(at, now, t)} +
    +
    + +
    + {long && ( + + )} +
    + ) +} + +/** The glyph, tone, and sentence of a submitted review's decision. */ +function verdictLine(verdict: ReviewVerdict, t: Translate): { + readonly glyph: ReactNode + readonly tone: 'success' | 'error' | undefined + readonly text: string +} { + const actor = { actor: ACTOR } + switch (verdict) { + case 'approved': + return { glyph: , tone: 'success', text: t('reviewPage.activity.approved', actor) } + case 'changes-requested': + return { glyph: , tone: 'error', text: t('reviewPage.activity.changesRequested', actor) } + case 'commented': + return { glyph: , tone: undefined, text: t('reviewPage.activity.commented', actor) } + case 'dismissed': + return { glyph: , tone: undefined, text: t('reviewPage.activity.dismissed', actor) } + /* v8 ignore next -- closed ReviewVerdict union exhaustiveness guard */ + default: return assertNever(verdict, 'ReviewVerdict') + } +} + +/** One activity item other than a commit. */ +function Event({ item, onOpenChanges, now, markdown, t }: { + readonly item: ActivityEvent + readonly onOpenChanges: () => void + readonly now: number + readonly markdown: MarkdownLabels + readonly t: Translate +}): ReactNode { + const line = (glyph: ReactNode, text: string): ReactNode => ( + + ) + switch (item.kind) { + case 'comment': + return + case 'review': { + const { glyph, tone, text } = verdictLine(item.verdict, t) + // A review that left comments on lines or files opens the changes tab, where they show. + const inline = item.comments === 0 ? undefined : { + text: `${text} · ${t('reviewPage.activity.inline', { count: item.comments })}`, open: t('reviewPage.activity.viewInChanges'), + } + const name = item.actor?.login ?? t('thread.deletedAuthor') + return ( + <> + + {item.body.trim() !== '' && } + + ) + } + case 'merged': return line(, t('reviewPage.activity.merged', { actor: ACTOR })) + case 'closed': return line(, t('reviewPage.activity.closed', { actor: ACTOR })) + case 'reopened': return line(, t('reviewPage.activity.reopened', { actor: ACTOR })) + case 'ready-for-review': return line(, t('reviewPage.activity.readyForReview', { actor: ACTOR })) + case 'converted-to-draft': + return line(, t('reviewPage.activity.convertedToDraft', { actor: ACTOR })) + case 'force-pushed': return line(, t('reviewPage.activity.forcePushed', { actor: ACTOR })) + case 'auto-merge-enabled': + return line(, t('reviewPage.activity.autoMergeEnabled', { actor: ACTOR })) + case 'auto-merge-disabled': + return line(, t('reviewPage.activity.autoMergeDisabled', { actor: ACTOR })) + case 'review-requested': + return line(, item.reviewer === null + ? t('reviewPage.activity.reviewRequestedUnnamed', { actor: ACTOR }) + : t('reviewPage.activity.reviewRequested', { actor: ACTOR, reviewer: item.reviewer })) + case 'renamed': + return line(, t('reviewPage.activity.renamed', { actor: ACTOR, from: item.from, to: item.to })) + case 'other': return line(, `${ACTOR} ${item.text}`) + /* v8 ignore next -- closed ChangeRequestActivityItem kind union exhaustiveness guard */ + default: return assertNever(item, 'ChangeRequestActivityItem.kind') + } +} + +/** The field that adds a comment: it keeps its text until the host saved the comment, and says why one was not saved. */ +function Composer({ url, forge, comment, onPosted, t }: { + readonly url: string + readonly forge: string | null + readonly comment: ReviewActivityProps['comment'] + readonly onPosted: () => void + readonly t: Translate +}): ReactNode { + const [text, setText] = useState('') + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const field = useRef(null) + // The field is as tall as its text, up to the height its style allows. + useEffect(() => { + const element = field.current + element?.style.setProperty('height', 'auto') + element?.style.setProperty('height', `${element.scrollHeight}px`) + }, [text]) + // The field and the button are disabled while a comment is sent, so one is sent at a time. + const post = async (): Promise => { + if (text.trim() === '') return + setBusy(true) + setError(null) + const result = await comment(url, text) + setBusy(false) + if (result.ok) { + setText('') + onPosted() + } else if (result.error.code === 'forgePanel/action-unknown' && forge !== null) { + setError(t('review.unknown', { forge })) + } else { + setError(t('reviewPage.activity.commentFailed', { message: result.error.message })) + } + } + return ( +
    +
    +