diff --git a/apps/web/tests/expected/forge-panel/base-menu.expected.md b/apps/web/tests/expected/forge-panel/base-menu.expected.md new file mode 100644 index 0000000000..59b64dc001 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/base-menu.expected.md @@ -0,0 +1,9 @@ +- textbox "搜索分支" +- group "默认": + - menuitem "origin/main 默认" +- group "本地分支": + - text: 本地分支 + - menuitem "topic" + - menuitem "main" + - menuitem "release" +- text: 与 HEAD 和所选分支的合并基准比较,包含未提交的修改 diff --git a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md index eef3d4c6df..114cf607bf 100644 --- a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md +++ b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md @@ -1,4 +1,6 @@ -- text: 与 origin/main 比较,包含未提交的修改 +- text: main +- button "基准分支:origin/main": origin/main +- text: 包含未提交的修改 - button "创建变更请求" - button "分支" - button "全部 0 个文件" [disabled] diff --git a/apps/web/tests/expected/forge-panel/review-message.expected.md b/apps/web/tests/expected/forge-panel/review-message.expected.md index c454458d69..83516e39df 100644 --- a/apps/web/tests/expected/forge-panel/review-message.expected.md +++ b/apps/web/tests/expected/forge-panel/review-message.expected.md @@ -3,6 +3,7 @@ > Side: R > Lines: 1 > Source: Local (branch) +> Base: origin/main > Diff hunk: > ```diff > @@ -0,0 +1,1 @@ @@ -16,6 +17,7 @@ > Side: R > Lines: 1 > Source: Local (branch) +> Base: origin/main > Diff hunk: > ```diff > @@ -0,0 +1,1 @@ diff --git a/apps/web/tests/expected/forge-panel/review-quotes.expected.md b/apps/web/tests/expected/forge-panel/review-quotes.expected.md index 602d647831..0f7262a4b1 100644 --- a/apps/web/tests/expected/forge-panel/review-quotes.expected.md +++ b/apps/web/tests/expected/forge-panel/review-quotes.expected.md @@ -1,6 +1,6 @@ - textbox "发消息或创建任务, / 调用指令, @ 文件或对话": - paragraph: - button "移除引用" - - text: "## User Comment 2 File: src/extra.ts Side: R Lines: 1 Source: Local (branch) Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const extra = 1 ``` Comment: 请检查这项修改" + - text: "## User Comment 2 File: src/extra.ts Side: R Lines: 1 Source: Local (branch) Base: origin/main Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const extra = 1 ``` Comment: 请检查这项修改" - button "移除引用" - - text: "## User Comment 1 File: src/app.ts Side: R Lines: 1 Source: Local (branch) Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const app = 1 ``` Comment: 请解释这行代码" + - text: "## User Comment 1 File: src/app.ts Side: R Lines: 1 Source: Local (branch) Base: origin/main Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const app = 1 ``` Comment: 请解释这行代码" diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 31b32ac9af..9985639f6d 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -688,7 +688,8 @@ it.skipIf(MODE === 'record')('marks a draft change request ready for review and it.skipIf(MODE === 'record')('shows the local changes of the Session by scope and the changes of its change requests, expanding unchanged lines', async () => { const { scaffold, page, root, project, tripwire } = await launchPanel('web-e2e-forge-panel-changes', 'follow-up', { branch: 'feat' }) - // origin/main stops at the twelve-line README; the branch adds a commit, a staged file, an edit, and an untracked file. + // origin/main stops at the twelve-line README; the branch adds a commit, which `topic` also has, a staged file, an edit, + // and an untracked file. await writeFile(join(project, 'README.md'), Array.from({ length: 12 }, (_, index) => `line ${index + 1}\n`).join('')) await git(project, 'commit', '--quiet', '-am', 'readme') await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') @@ -697,6 +698,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await writeFile(join(project, 'src', 'app.ts'), 'export const app = 1\n') await git(project, 'add', 'src/app.ts') await git(project, 'commit', '--quiet', '-m', 'app') + await git(project, 'branch', 'topic') await writeFile(join(project, 'src', 'extra.ts'), 'export const extra = 1\n') await git(project, 'add', 'src/extra.ts') await writeFile(join(project, 'README.md'), Array.from({ length: 12 }, (_, index) => index === 9 ? 'line ten\n' : `line ${index + 1}\n`).join('')) @@ -721,7 +723,8 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await card.getByRole('button', { name: '查看本会话的变更:4 个文件,新增 4 行,删除 1 行', exact: true }).click() const local = page.locator('[data-forge-changes="local"]') - await local.getByText('与 origin/main 比较,包含未提交的修改', { exact: true }).waitFor({ timeout: 20_000 }) + await local.getByRole('button', { name: '基准分支:origin/main', exact: true }).waitFor({ timeout: 20_000 }) + await local.getByText('包含未提交的修改', { exact: true }).waitFor() const files = local.locator('[data-forge-diff-file]') await expect.poll(() => files.evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file'))), { timeout: 20_000 }) .toEqual(['src/app.ts', 'src/extra.ts', 'README.md', 'notes.md']) @@ -768,6 +771,18 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an expect(comments).toHaveLength(1) await compareOrRefreshGolden(join(EXPECTED, 'review-message.expected.md'), comments.join('').trimEnd(), MODE) + // Compared with `topic`, which already has the committed `src/app.ts`, the branch scope keeps only the later changes. + await local.getByRole('button', { name: '基准分支:origin/main', exact: true }).click() + const bases = page.locator('[data-forge-base-menu]') + await bases.getByRole('menuitem', { name: 'topic', exact: true }).waitFor({ timeout: 20_000 }) + await compareOrRefreshGolden(join(EXPECTED, 'base-menu.expected.md'), await captureStableAria(page, '[data-forge-base-menu]', scaffold.workspaceCwd), MODE) + await bases.getByRole('textbox', { name: '搜索分支' }).fill('TOP') + await expect.poll(() => bases.getByRole('menuitem').allTextContents()).toEqual(['topic']) + await bases.getByRole('textbox', { name: '搜索分支' }).press('Enter') + await local.getByRole('button', { name: '基准分支:topic', exact: true }).waitFor() + await expect.poll(() => files.evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file'))), { timeout: 20_000 }) + .toEqual(['src/extra.ts', 'README.md', 'notes.md']) + await local.getByRole('button', { name: '分支', exact: true }).click() await page.getByRole('menuitem', { name: '已暂存', exact: true }).click() await local.getByText('暂存区与 HEAD 比较', { exact: true }).waitFor() diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 304b6de767..6d42bc33a7 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1046,7 +1046,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:318`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1061,14 +1061,14 @@ export interface Config { maxOutputBytes?: number /** Deadline in milliseconds for one provider sign-in probe. */ readinessTimeoutMs?: number - /** Most local branches listed as worktree bases. */ + /** Most local branches listed as worktree bases, and most branches in each group of base branches listed for the `branch` scope. */ maxBranches?: number /** * Prefix of the branch and checkout directory created for a Session worktree; the first eight * hexadecimal digits of the Session id's UUID, a hyphen, and four random hexadecimal digits follow it. */ worktreePrefix?: string - /** Largest diff, or file read to show unchanged lines, in bytes. */ + /** Largest diff, file read to show unchanged lines, or list of base branch refs, in bytes. */ maxDiffBytes?: number /** Most untracked files a local diff or the local changes card includes. */ maxUntrackedFiles?: number diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 182c220092..b478360483 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1048,7 +1048,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:318`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1063,14 +1063,14 @@ export interface Config { maxOutputBytes?: number /** Deadline in milliseconds for one provider sign-in probe. */ readinessTimeoutMs?: number - /** Most local branches listed as worktree bases. */ + /** Most local branches listed as worktree bases, and most branches in each group of base branches listed for the `branch` scope. */ maxBranches?: number /** * Prefix of the branch and checkout directory created for a Session worktree; the first eight * hexadecimal digits of the Session id's UUID, a hyphen, and four random hexadecimal digits follow it. */ worktreePrefix?: string - /** Largest diff, or file read to show unchanged lines, in bytes. */ + /** Largest diff, file read to show unchanged lines, or list of base branch refs, in bytes. */ maxDiffBytes?: number /** Most untracked files a local diff or the local changes card includes. */ maxUntrackedFiles?: number diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 379e181766..36f1e55d7d 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -18,5 +18,5 @@ en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: 9a84a26d97cb46f0 - zh: 5e1e03b7714bcbae + en: dbc28e731f357edf + zh: a1977fafc0651427 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index f56d88b848..ff5c6cfab8 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -567,16 +567,17 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card. +The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ type ForgeLocalScope = /** - * The working tree and untracked files against the fork point: the base commit of the worktree the - * Session created, else the merge base of HEAD with the default branch of the code host remote. + * The working tree and untracked files against a fork point: the merge base of HEAD with the + * `base` ref, or while `base` is null, the base commit of the worktree the Session created, + * else the merge base of HEAD with the default branch of the code host remote. */ - | { readonly kind: 'branch' } + | { readonly kind: 'branch'; readonly base: string | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -585,6 +586,38 @@ type ForgeLocalScope = | { readonly kind: 'staged' } ``` +```ts type-equiv +/** A branch the `branch` scope can compare with. */ +interface ForgeBaseBranch { + /** Full ref name: `refs/heads/` or `refs/remotes//`. */ + readonly ref: string + /** The ref without `refs/heads/` or `refs/remotes/`, such as `master` or `origin/master`. */ + readonly name: string +} +``` + +```ts type-equiv +/** What the `branch` scope compares with while no base branch is chosen. */ +interface ForgeAutomaticBase { + /** The created worktree's base branch or abbreviated base commit, or the default branch of the code host remote. */ + readonly name: string + /** Whether the fork point is the base commit of the worktree the Session created rather than a merge base. */ + readonly worktree: boolean +} +``` + +```ts type-equiv +/** Branches the `branch` scope can compare with, whose names contain a query. */ +interface ForgeBaseBranches { + /** The fork point used while no base branch is chosen, whatever the query; null without one. */ + readonly automatic: ForgeAutomaticBase | null + /** Remote-tracking branches without symbolic refs such as `origin/HEAD`, most recently committed first, at most `maxBranches`. */ + readonly remote: readonly ForgeBaseBranch[] + /** Local branches other than the checked-out one, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] +} +``` + ```ts type-equiv /** One hunk of a file diff. */ interface ForgeDiffHunk { @@ -887,6 +920,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async branches(session: Session, signal: AbortSignal): Promise +/** + * List the branches the `branch` scope of the Session's current checkout can compare with. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. + * @param signal - request cancellation. + * @returns the automatic fork point and at most `maxBranches` remote-tracking and local branches each, + * most recently committed first, without the checked-out branch. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. + */ +@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise + /** * Bind a change request to a Session by URL, or restore a dismissed binding. * @param session - Session that receives the binding. @@ -920,9 +964,10 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @param scope - which changes to read. * @param signal - request cancellation. * @returns the files, the base of the `branch` scope, and the untracked files left out. - * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/no-fork-point` for the `branch` - * scope of a checkout without one; `forgePanel/filter-config-failed` when filter configuration cannot be read - * completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch + * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without + * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index bbcf8ace8f..224d7aaac7 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -567,16 +567,17 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用。 +变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。 ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ type ForgeLocalScope = /** - * The working tree and untracked files against the fork point: the base commit of the worktree the - * Session created, else the merge base of HEAD with the default branch of the code host remote. + * The working tree and untracked files against a fork point: the merge base of HEAD with the + * `base` ref, or while `base` is null, the base commit of the worktree the Session created, + * else the merge base of HEAD with the default branch of the code host remote. */ - | { readonly kind: 'branch' } + | { readonly kind: 'branch'; readonly base: string | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -585,6 +586,38 @@ type ForgeLocalScope = | { readonly kind: 'staged' } ``` +```ts type-equiv +/** A branch the `branch` scope can compare with. */ +interface ForgeBaseBranch { + /** Full ref name: `refs/heads/` or `refs/remotes//`. */ + readonly ref: string + /** The ref without `refs/heads/` or `refs/remotes/`, such as `master` or `origin/master`. */ + readonly name: string +} +``` + +```ts type-equiv +/** What the `branch` scope compares with while no base branch is chosen. */ +interface ForgeAutomaticBase { + /** The created worktree's base branch or abbreviated base commit, or the default branch of the code host remote. */ + readonly name: string + /** Whether the fork point is the base commit of the worktree the Session created rather than a merge base. */ + readonly worktree: boolean +} +``` + +```ts type-equiv +/** Branches the `branch` scope can compare with, whose names contain a query. */ +interface ForgeBaseBranches { + /** The fork point used while no base branch is chosen, whatever the query; null without one. */ + readonly automatic: ForgeAutomaticBase | null + /** Remote-tracking branches without symbolic refs such as `origin/HEAD`, most recently committed first, at most `maxBranches`. */ + readonly remote: readonly ForgeBaseBranch[] + /** Local branches other than the checked-out one, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] +} +``` + ```ts type-equiv /** One hunk of a file diff. */ interface ForgeDiffHunk { @@ -887,6 +920,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async branches(session: Session, signal: AbortSignal): Promise +/** + * List the branches the `branch` scope of the Session's current checkout can compare with. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. + * @param signal - request cancellation. + * @returns the automatic fork point and at most `maxBranches` remote-tracking and local branches each, + * most recently committed first, without the checked-out branch. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. + */ +@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise + /** * Bind a change request to a Session by URL, or restore a dismissed binding. * @param session - Session that receives the binding. @@ -920,9 +964,10 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @param scope - which changes to read. * @param signal - request cancellation. * @returns the files, the base of the `branch` scope, and the untracked files left out. - * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/no-fork-point` for the `branch` - * scope of a checkout without one; `forgePanel/filter-config-failed` when filter configuration cannot be read - * completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch + * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without + * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 80a5b5d31b..1c664c6e1b 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,23 +15,23 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 6b4ef4961f236526 - zh: 41be8aa5aec35b05 + en: 058035fcf2a43fd0 + zh: 92d4f4f3e68d0fc5 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 1597090848784354 - zh: e0dcabfa803fe421 + en: 80ba18c47e570e5e + zh: 2f0fce0affa48f59 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience: - en: f7a1517de6265e7b - zh: 4e4ddc7e1fde8e54 + en: d62a9841cc34dfdd + zh: 5aa4ffb331c5bb93 /deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect: en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 03a5b04c9e7bf1b1 - zh: f606dabcf0ed2f1e + en: 0f795ca1c607af01 + zh: a05ac28fb2313d6e /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 813c110216..8056d0fe39 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -36,8 +36,8 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Header button** — appears when the Session has bound change requests or its directory is inside a Git checkout, and shows or hides the tab. A red dot marks an open change request with failed checks, requested changes, or conflicts. - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color with a dot for running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. - **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. -- **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. -- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point, which is the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. +- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. @@ -57,7 +57,7 @@ All files opens a searchable directory tree. Single-child directories share a ro `ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` for every change. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. -Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --short HEAD`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `branches` runs `symbolic-ref` and `for-each-ref --count=`. Inspection then sizes the `branch` scope for the local changes card: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy. +Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --short HEAD`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `branches` runs `symbolic-ref` and `for-each-ref --count=`; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes card: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy. A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first `created` record of an open request applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, and with `forgePanel/invalid-branch` for an empty branch; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt with a new branch name, publishing the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, failed step, and reason stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, refused with `forgePanel/not-waiting` while none waits or one runs, and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. The bundle isolates its `worktrees` service, so enabling Git Worktrees as well leaves two independent services. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason. @@ -66,11 +66,11 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. -The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope and layout choices of each tab in a slot store, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon. +The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, and layout choices of each tab in a slot store, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon. | Source | Responsibility | |---|---| @@ -86,6 +86,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | Local changes card | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view | +| [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | One file of the changes view | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | @@ -109,7 +110,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t ## Model Experience -Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. +Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, and local Branch quotes the base the view compared with. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. #### KV Cache effect @@ -128,7 +129,8 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. - **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree: under workspace-write its Git directory lies outside the writable root, so neither the new branch nor later commits could be written. -- **Changes scopes** — deferred: scopes for one commit and for the last turn. The Branch scope needs a remote whose default branch HEAD shares history with, or a worktree the Session created. +- **Changes scopes** — deferred: scopes for one commit and for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. +- **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index cc6d281d7f..8f189c0d18 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -36,8 +36,8 @@ kind: "package-reference" - **标题栏按钮**——Session 有已绑定的变更请求、或其目录位于 Git 检出中时出现,用来显示或隐藏标签页。打开状态的变更请求存在检查失败、被要求修改或冲突时,按钮带红点。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,并用圆点标出检查进行中、已通过或失败;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 - **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 -- **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更;分叉点是 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 @@ -57,7 +57,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 `ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,每次变化都发布新的 `ForgePanelState`。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。 -检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=`。之后,检查会为本地变更卡片统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 +检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更卡片统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;分支名为空时以 `forgePanel/invalid-branch` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留使用新分支名进行一次尝试,在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、失败步骤与原因以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。 @@ -66,11 +66,11 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 -浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围与布局选择,经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 +浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支与布局选择,经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 | 源码 | 职责 | |---|---| @@ -86,6 +86,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | +| [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | @@ -109,7 +110,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi ## 模型体验 -间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 +间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 #### KV Cache 影响 @@ -128,7 +129,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 - **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用:在 workspace-write 下它的 Git 目录位于可写根之外,新分支与之后的提交都无法写入。 -- **变更范围**——待办:单个提交与上一轮的范围。“分支”范围需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree。 +- **变更范围**——待办:单个提交与上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 +- **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/client/BaseMenu.module.css b/packages/experimental/client-ui-forge/src/client/BaseMenu.module.css new file mode 100644 index 0000000000..7d5e279d9d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/BaseMenu.module.css @@ -0,0 +1,153 @@ +/* Base branch trigger in the local changes header and its searchable menu. */ +.anchor { + flex: none; + min-width: 0; + max-width: min(60%, 320px); +} + +.trigger { + display: inline-flex; + align-items: center; + gap: 4px; + box-sizing: border-box; + max-width: 100%; + height: 26px; + padding: 0 6px 0 8px; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + font-family: var(--ds-font-family-code); + cursor: pointer; +} + +.trigger[aria-expanded='true'] { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .trigger:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.trigger:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -2px; +} + +.trigger svg { + flex: none; +} + +.triggerName { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.missing .triggerName { + color: var(--dsw-alias-label-secondary); + text-decoration: line-through; +} + +.warning { + color: var(--dsw-alias-state-warn-primary); +} + +.menu { + width: min(380px, calc(100vw - 24px)); +} + +.root { + display: flex; + flex-direction: column; + box-sizing: border-box; + width: 100%; + min-width: 0; + min-height: 0; + color: var(--dsw-alias-label-primary); + font-size: 12px; +} + +.search { + padding: 8px; +} + +.searchInput { + box-sizing: border-box; + width: 100%; + max-width: 100%; +} + +.searchInput input::placeholder { + color: var(--dsw-alias-label-secondary); +} + +.rows { + max-height: 320px; + overflow: auto; + padding: 0 4px 4px; +} + +.label { + padding: 6px 8px 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 15px; +} + +.option { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; +} + +.name { + min-width: 0; + overflow: hidden; + font-family: var(--ds-font-family-code); + text-overflow: ellipsis; + white-space: nowrap; +} + +.tag { + flex: none; + padding: 0 5px; + border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 16px; +} + +.check { + flex: none; + margin-left: auto; + color: var(--dsw-alias-state-business-primary); +} + +.status { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 8px; + color: var(--dsw-alias-label-secondary); +} + +.note { + padding: 8px 12px; + border-top: 0.5px solid var(--dsw-alias-border-l3); + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 16px; +} + +@media (pointer: coarse) { + .search input { + font-size: 16px; + } +} diff --git a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx new file mode 100644 index 0000000000..9125fef677 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx @@ -0,0 +1,184 @@ +/** Base branch picker of the local changes view's `branch` scope: the automatic fork point, then remote-tracking and local branches. */ + +import { useEffect, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconSearchOutlineRegular, + IconWarningTriangleOutlineRegular, Input, Menu, MenuItemButton, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts' +import type { NS } from './locales.ts' +import css from './BaseMenu.module.css' + +/** Milliseconds between the last keystroke of a search and the listing it reads. */ +const SEARCH_DELAY_MS = 150 + +/** Props of the base branch picker. */ +export interface BaseMenuProps extends PropsLocale { + /** Chosen branch, or null for the automatic fork point. */ + readonly chosen: ForgeBaseBranch | null + /** Name the trigger shows: the chosen branch, the automatic fork point, or the automatic choice's own name. */ + readonly label: string + /** Whether the chosen branch no longer exists. */ + readonly missing: boolean + /** Whether the owning tab is visible; a hidden tab keeps the menu closed. */ + readonly visible: boolean + /** Read the branches whose names contain `query`; `signal` aborts the read. */ + readonly list: (query: string, signal: AbortSignal) => Promise> + /** Compare with a branch, or with the automatic fork point for null. */ + readonly choose: (base: ForgeBaseBranch | null) => void +} + +/** One selectable row: a branch, or the automatic fork point. */ +interface BaseOption { + readonly key: string + readonly name: string + readonly base: ForgeBaseBranch | null + readonly tag?: string +} + +/** + * Render the trigger and, while open, the searchable menu. Opening and each + * search read the branches again; rows already shown follow the search at once + * until the new listing arrives. + * @param props - the choice, the trigger label, the listing read, the choose action, and copy. + * @returns the trigger with its portalled menu. + */ +export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: BaseMenuProps): ReactNode { + const [open, setOpen] = useState(false) + const [query, setQuery] = useState('') + const [attempt, setAttempt] = useState(0) + const [listing, setListing] = useState | null>(null) + const search = useRef(null) + const shown = visible && open + useEffect(() => { + if (!shown) return + const controller = new AbortController() + const timer = setTimeout(() => { + void list(query, controller.signal).then((result) => { if (!controller.signal.aborted) setListing(result) }) + }, query === '' ? 0 : SEARCH_DELAY_MS) + return () => { + clearTimeout(timer) + controller.abort() + } + }, [shown, query, attempt, list]) + // The portalled menu measures itself hidden before its first frame, and a hidden field cannot take the keyboard. + // A touch screen keeps its on-screen keyboard closed until the field is tapped. + useEffect(() => { + if (!shown || (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches)) return + const frame = requestAnimationFrame(() => { search.current?.focus() }) + return () => { cancelAnimationFrame(frame) } + }, [shown]) + const close = (): void => { + setOpen(false) + setQuery('') + } + const pick = (base: ForgeBaseBranch | null): void => { + close() + if ((base?.ref ?? null) !== (chosen?.ref ?? null)) choose(base) + } + + const value = listing?.ok === true ? listing.value : null + const needle = query.trim().toLowerCase() + const matches = (name: string): boolean => name.toLowerCase().includes(needle) + const automatic = value?.automatic ?? null + const groups: { readonly id: string; readonly label: string; readonly options: readonly BaseOption[] }[] = [ + { + id: 'automatic', + label: t('diff.base.automatic'), + options: automatic === null || !matches(automatic.name) ? [] : [{ + key: 'automatic', name: automatic.name, base: null, tag: t(automatic.worktree ? 'diff.base.worktree' : 'diff.base.automatic'), + }], + }, + { + id: 'remote', + label: t('diff.base.remote'), + // The automatic fork point of a code host's default branch is the same comparison as choosing that branch. + options: (value?.remote ?? []) + .filter(branch => matches(branch.name) && (automatic === null || automatic.worktree || branch.name !== automatic.name)) + .map(branch => ({ key: branch.ref, name: branch.name, base: branch })), + }, + { + id: 'local', + label: t('diff.base.local'), + options: (value?.local ?? []).filter(branch => matches(branch.name)) + .map(branch => ({ key: branch.ref, name: branch.name, base: branch })), + }, + ].filter(group => group.options.length > 0) + const first = groups[0]?.options[0] + + let body: ReactNode + if (listing === null) { + body =
{t('diff.base.loading')}
+ } else if (!listing.ok) { + body = ( +
+ {t('toast.branchesFailed')} + +
+ ) + } else if (groups.length === 0) { + body =
{t('diff.base.empty')}
+ } else { + body = groups.map(group => ( +
+ {/* The automatic row's tag names it, so its group shows no heading. */} + {group.id !== 'automatic' &&
{group.label}
} + {group.options.map((option) => { + const selected = (option.base?.ref ?? null) === (chosen?.ref ?? null) + return ( + } current={selected} + onSelect={() => { pick(option.base) }}> + + {option.name} + {option.tag !== undefined && {option.tag}} + {selected && } + + + ) + })} +
+ )) + } + + return ( + + + + )} + > +
+
+ } value={query} + aria-label={t('diff.base.search')} placeholder={t('diff.base.search')} + onChange={(event) => { setQuery(event.target.value) }} + onKeyDown={(event) => { + if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() + if (event.key !== 'Enter' || event.nativeEvent.isComposing || first === undefined) return + event.preventDefault() + pick(first.base) + }} /> +
+
{body}
+
{t('diff.base.note')}
+
+
+ ) +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 85c66d88c4..9795e3558c 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -9,7 +9,8 @@ import { useEffect, useState, type ReactNode } from 'react' import clsx from 'clsx' import { Button, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, - IconListPenOutlineRegular, IconRightUpOutlineRegular, IconUserOutlineRegular, Menu, MenuItemButton, StateDot, Tooltip, + IconListPenOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, IconUserOutlineRegular, Menu, MenuItemButton, + StateDot, Tooltip, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' @@ -327,7 +328,7 @@ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: { )} items={items} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 739513374c..66ea6bcf84 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -60,6 +60,39 @@ white-space: nowrap; } +/* The checked-out branch gives way first, so the base branch stays readable. */ +.headerHead { + flex: 0 100 auto; + min-width: 2.5em; + overflow: hidden; + color: var(--dsw-alias-label-secondary); + font-family: var(--ds-font-family-code); + text-overflow: ellipsis; + white-space: nowrap; +} + +.headerArrow { + flex: none; + color: var(--dsw-alias-label-tertiary); +} + +.headerSuffix { + color: var(--dsw-alias-label-tertiary); +} + +@container forge-changes (max-width: 520px) { + .headerSuffix { + display: none; + } +} + +@container forge-changes (max-width: 380px) { + .headerHead, + .headerArrow { + display: none; + } +} + .headerEnd { flex: none; margin-left: auto; diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index bd39ea3d27..983c6b58a3 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -10,8 +10,9 @@ import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, IconInfoOutlineRegular, - IconListPenOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular, IconWrapFillRegular, + Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, + IconInfoOutlineRegular, IconListPenOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular, + IconWrapFillRegular, Menu, StateDot, Tooltip, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' @@ -20,14 +21,16 @@ import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-rig import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { - ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, + ForgePanelState, } from '../types.ts' import type { ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' import type { ReviewActions } from './ReviewComposer.tsx' import { SubmitReview } from './SubmitReview.tsx' -import type { ReviewSelection } from './review.ts' +import type { ReviewSelection, ReviewSource } from './review.ts' +import { BaseMenu } from './BaseMenu.tsx' import { parseChangesAddress, type ChangesSource } from './changes-address.ts' import type { createChangesStore } from './changes-store.ts' import { Counts, DiffFile, type DiffFileAction } from './DiffFile.tsx' @@ -61,6 +64,8 @@ export interface ChangesTabInjected { readonly reconnect: () => void /** Read the local changes of one scope; `signal` aborts the read. */ readonly localDiff: (scope: ForgeLocalScope, signal: AbortSignal) => Promise> + /** Read the branches the `branch` scope can compare with, whose names contain `query`; `signal` aborts the read. */ + readonly diffBases: (query: string, signal: AbortSignal) => Promise> /** Read the new side of one file in a local scope. */ readonly localText: (scope: ForgeLocalScope, path: string) => Promise> /** Read the changes of a change request by its binding URL; `signal` aborts the read. */ @@ -90,7 +95,9 @@ type ChangesData = readonly kind: 'local' readonly files: readonly ForgeDiffFile[] /** Scope the files were read in. */ - readonly scope: ScopeKind + readonly scope: ForgeLocalScope + /** Name of what the `branch` scope compared with; null for other scopes. */ + readonly base: string | null /** Untracked files left out. */ readonly omitted: number } @@ -143,16 +150,35 @@ const FAILURE: Partial> = { 'forgePanel/filter-config-failed': 'diff.filterConfigFailed', } +/** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */ +const BASE_FAILURE: Partial> = { + 'forgePanel/base-missing': 'diff.baseMissing', + 'forgePanel/no-fork-point': 'diff.baseUnrelated', +} + +/** + * Explain a failure of the `branch` scope that its chosen base branch caused. + * @param failed - code of the failed read, or null. + * @param base - branch the read compared with, or null for the automatic fork point and other scopes. + * @param t - forge panel copy. + * @returns the message naming the branch, or undefined for another failure or without a chosen branch. + */ +function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: Translate): string | undefined { + const key = failed === null ? undefined : BASE_FAILURE[failed] + return key === undefined || base === null ? undefined : t(key, { base: base.name }) +} + async function readChanges( source: ChangesSource, - scope: ScopeKind, + scope: ForgeLocalScope, reads: Pick, signal: AbortSignal, ): Promise> { if (source.kind === 'local') { - const result = await reads.localDiff({ kind: scope }, signal) + const result = await reads.localDiff(scope, signal) if (!result.ok) return result - return { ok: true, value: { kind: 'local', files: result.value.files, scope, omitted: result.value.omitted } } + const { files, base, omitted } = result.value + return { ok: true, value: { kind: 'local', files, scope, base, omitted } } } const result = await reads.changeRequestDiff(source.url, signal) if (!result.ok) return result @@ -160,6 +186,18 @@ async function readChanges( return { ok: true, value: { kind: 'change', files, url: source.url, headSha, localAhead, fileUrls } } } +/** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */ +function baseRefOf(scope: ForgeLocalScope): string | null { + return scope.kind === 'branch' ? scope.base : null +} + +/** The source review comments on loaded changes record: the change request head, or the local scope with its base. */ +function reviewSourceOf(data: ChangesData): ReviewSource { + return data.kind === 'local' + ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope) } + : { kind: 'change', url: data.url, headSha: data.headSha } +} + /** The files that start expanded: every file until those above it change more than {@link OPEN_LINES} lines. */ function initiallyOpen(files: readonly ForgeDiffFile[]): ReadonlySet { const open = new Set() @@ -189,7 +227,7 @@ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string { if (file.status === 'added') parts.push(t('diff.newFile')) else if (file.status === 'deleted') parts.push(t('diff.deletedFile')) else if (file.status === 'renamed' && file.previousPath !== null) parts.push(t('diff.renamed', { from: renamedFrom(file.previousPath, file.path) })) - if (file.untracked && data.kind === 'local' && data.scope === 'branch') parts.push(t('diff.badgeUncommitted')) + if (file.untracked && data.kind === 'local' && data.scope.kind === 'branch') parts.push(t('diff.badgeUncommitted')) return parts.join(' · ') } @@ -223,19 +261,40 @@ function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onRev ) } -function LocalHeader({ state, scope, createChangeRequest, t }: { +/** + * The local view's header: for the `branch` scope, the checked-out branch, the base branch picker, and a note + * that uncommitted changes count; for another scope, what it compares. + */ +function LocalHeader({ state, scope, base, missing, visible, diffBases, choose, createChangeRequest, t }: { readonly state: ForgePanelState | null readonly scope: ScopeKind + readonly base: ForgeBaseBranch | null + /** Whether the chosen base branch no longer exists. */ + readonly missing: boolean + readonly visible: boolean + readonly diffBases: ChangesTabInjected['diffBases'] + readonly choose: (base: ForgeBaseBranch | null) => void readonly createChangeRequest: () => void readonly t: Translate }): ReactNode { - const base = state?.local?.base ?? null - const note = scope !== 'branch' ? t(SCOPE_NOTE[scope]) : base === null ? '' : t('diff.scopeNote.branch', { base }) const creatable = state !== null && state.repository !== null && openChangeRequestOf(state) === undefined + const checkout = state?.checkout.state === 'ready' ? state.checkout.checkout : null + const head = checkout?.branch ?? checkout?.commit ?? 'HEAD' return (
- - {note} + {scope === 'branch' ? <> + + + {head} + + + + {t('diff.base.uncommitted')} + : <> + + {t(SCOPE_NOTE[scope])} + } {creatable && ( )} @@ -310,7 +369,8 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { * @returns the view body. */ export function ChangesTab({ - useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, localText, changeRequestDiff, changeRequestText, + useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, changeRequestDiff, + changeRequestText, openLink, copyPath, createChangeRequest, addReviewToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -386,6 +446,8 @@ export function ChangesTab({ const snapshot = usePanel(tab.visible ? 'visible' : 'inactive') const state = snapshot?.state ?? null const scope = choices?.scope ?? 'branch' + const base = choices?.base ?? null + const localScope = useMemo((): ForgeLocalScope => scope === 'branch' ? { kind: 'branch', base: base?.ref ?? null } : { kind: scope }, [scope, base]) const split = choices?.split ?? true const wrap = choices?.wrap ?? true const entry = source.kind === 'change' ? state?.changeRequests.find(item => item.url === source.url) : undefined @@ -394,7 +456,7 @@ export function ChangesTab({ const pending = entry !== undefined && entry.ref !== null && entry.update === null const head = entry?.snapshot?.headSha ?? (pending ? null : '') const version = state === null ? null : source.kind === 'local' ? `${scope}\n${JSON.stringify(state.local)}` : head - const dataKey = source.kind === 'local' ? scope : 'change' + const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : 'change' const [loaded, setLoaded] = useState<{ readonly key: string; readonly data: ChangesData } | null>(null) const [failure, setFailure] = useState<{ readonly key: string; readonly code: string } | null>(null) // Names the read the inputs ask for; it is in flight until `finished` matches it. @@ -403,7 +465,7 @@ export function ChangesTab({ useEffect(() => { if (!tab.visible || read === null || read === finished) return const controller = new AbortController() - void readChanges(source, scope, { localDiff, changeRequestDiff }, controller.signal).then((result) => { + void readChanges(source, localScope, { localDiff, changeRequestDiff }, controller.signal).then((result) => { if (controller.signal.aborted) return setFinished(read) if (result.ok) { @@ -414,7 +476,7 @@ export function ChangesTab({ } }) return () => { controller.abort() } - }, [tab.visible, read, source, scope, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, source, localScope, dataKey, localDiff, changeRequestDiff]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null const files = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. @@ -438,10 +500,16 @@ export function ChangesTab({ }, [tab.visible, wanted, data]) const refresh = (): void => { setAttempt(value => value + 1) } const root = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.root : null + // A chosen base branch that is gone or shares no history with HEAD offers the automatic fork point instead. + const baseFailure = baseFailureOf(failed, source.kind === 'local' && scope === 'branch' ? base : null, t) // Configuration reads may recover after the user fixes Git settings or raises the output limit. const message = failed === null ? undefined : FAILURE[failed] + const failureText = baseFailure ?? t(message ?? 'diff.error') const changeUrl = source.kind === 'change' ? entry?.snapshot?.url ?? source.url : null - const retry = message === undefined || failed === 'forgePanel/filter-config-failed' + const retry = baseFailure === undefined && (message === undefined || failed === 'forgePanel/filter-config-failed') + const automaticBase = baseFailure !== undefined && ( + + ) /** Apply a change to the unchanged lines of `owner`, unless newer changes replaced it. */ const update = (owner: ChangesData, change: (value: Expansion) => Expansion): void => { @@ -455,7 +523,7 @@ export function ChangesTab({ update(owner, value => ({ ...value, open: { ...value.open, [path]: new Set([...value.open[path] ?? [], index]) } })) if (current.texts[path] !== undefined) return update(owner, value => ({ ...value, texts: { ...value.texts, [path]: 'loading' } })) - const reading = owner.kind === 'local' ? localText({ kind: owner.scope }, path) : changeRequestText(owner.url, owner.headSha, path) + const reading = owner.kind === 'local' ? localText(owner.scope, path) : changeRequestText(owner.url, owner.headSha, path) void reading.then((result) => { const lines = result.ok ? textLines(result.value) : undefined if (lines !== undefined && matchesHunks(lines, file.hunks)) { @@ -495,7 +563,9 @@ export function ChangesTab({ }} t={t} /> const recordActions: ReviewActions = { - source: source.kind === 'local' ? { kind: 'local', scope } : { kind: 'change', url: source.url, headSha: data?.kind === 'change' ? data.headSha : '' }, + source: data !== null ? reviewSourceOf(data) : source.kind === 'local' + ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope) } + : { kind: 'change', url: source.url, headSha: '' }, records: queue, addToInput: addReviewToInput, openLink, } const absentPaths = [...new Set([...reviewState.comments, ...reviewState.records.map(item => item.selection)] @@ -550,10 +620,11 @@ export function ChangesTab({ } else { body = (
- {t(message ?? 'diff.error')} - {(retry || changeUrl !== null) && ( + {failureText} + {(retry || changeUrl !== null || automaticBase !== false) && (
{retry && } + {automaticBase} {changeUrl !== null && ( )} @@ -578,7 +649,7 @@ export function ChangesTab({ key={path} visible={tab.visible} file={file} - review={{ source: data.kind === 'local' ? { kind: 'local', scope: data.scope } : { kind: 'change', url: data.url, headSha: data.headSha }, + review={{ source: reviewSourceOf(data), addToInput: addReviewToInput, records: queue, openLink, reviewStarted: reviewState.comments.length > 0, onQuoted: (selection) => { if (!queue.recordAgent(selection)) report('review.saveFailed') }, @@ -635,7 +706,8 @@ export function ChangesTab({ return (
{source.kind === 'local' - ? + ? { actions.based(tab.id, next) }} createChangeRequest={createChangeRequest} t={t} /> : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} @@ -687,8 +759,10 @@ export function ChangesTab({
{data !== null && failed !== null && ( - {t('retry')}}> - {t(message ?? 'diff.error')} + {t('retry')} + : automaticBase !== false && {automaticBase}}> + {failureText} )} {data?.kind === 'change' && data.localAhead !== null && data.localAhead > 0 && ( diff --git a/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css b/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css index 19d60ee8fe..7d89a05fad 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css @@ -529,6 +529,34 @@ line-height: 20px; } +/* + * The merge action takes the blue button fill, moved toward the label color so its 13px label keeps 4.5:1 contrast + * in both themes. The doubled class outranks the shared primary fill in any stylesheet order. + */ +.primaryAction.mergeAction { + gap: 6px; + padding: 0 10px 0 14px; + background: color-mix(in srgb, var(--dsw-alias-button-info-fill) 92%, var(--dsw-alias-label-primary)); + color: var(--dsw-alias-label-primary-foreground); +} + +@media (hover: hover) { + .primaryAction.mergeAction:hover:not(:disabled) { + background: color-mix(in srgb, var(--dsw-alias-button-info-fill) 85%, var(--dsw-alias-label-primary)); + } +} + +/* A solid caret that points down, and up while the menu is open. */ +.mergeCaret { + flex: none; + transform: rotate(90deg); + transition: transform 120ms ease; +} + +.mergeCaretOpen { + transform: rotate(-90deg); +} + /* A merge method row: its name with the note on what it does below. */ .method { display: flex; diff --git a/packages/experimental/client-ui-forge/src/client/changes-store.ts b/packages/experimental/client-ui-forge/src/client/changes-store.ts index 4606407b4f..6ad66a951e 100644 --- a/packages/experimental/client-ui-forge/src/client/changes-store.ts +++ b/packages/experimental/client-ui-forge/src/client/changes-store.ts @@ -1,17 +1,19 @@ /** - * Choices of each changes tab: the local scope, the side-by-side view, line - * wrapping, and the navigation it last applied. One bucket per tab, so two - * views in one Session keep their own choices; the bucket ends with the tab - * record's signal. + * Choices of each changes tab: the local scope, the base branch of the + * `branch` scope, the side-by-side view, line wrapping, and the navigation it + * last applied. One bucket per tab, so two views in one Session keep their own + * choices; the bucket ends with the tab record's signal. */ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' -import type { ForgeLocalScope } from '../types.ts' +import type { ForgeBaseBranch, ForgeLocalScope } from '../types.ts' /** One changes tab's choices. */ export interface ChangesTabState { /** Local changes shown; a change request view ignores it. */ scope: ForgeLocalScope['kind'] + /** Branch the `branch` scope compares with, or null for the automatic fork point; other scopes keep it. */ + base: ForgeBaseBranch | null /** Whether deletions and additions show in two columns. */ split: boolean /** Whether long lines wrap instead of being cut at the column edge. */ @@ -35,6 +37,7 @@ function bucket(state: ChangesState, tabId: string): ChangesTabState { type ChangesActions = { navigated: (draft: ChangesState, tabId: string, revision: number) => void scoped: (draft: ChangesState, tabId: string, scope: ForgeLocalScope['kind']) => void + based: (draft: ChangesState, tabId: string, base: ForgeBaseBranch | null) => void toggledSplit: (draft: ChangesState, tabId: string) => void toggledWrap: (draft: ChangesState, tabId: string) => void forget: (draft: ChangesState, tabId: string) => void @@ -50,14 +53,14 @@ export function createChangesStore(): EngineStoreHandle ({ byTab: {} }), actions: { /** - * Apply a navigation; the first one seeds the `branch` scope, two columns, and wrapped lines. + * Apply a navigation; the first one seeds the `branch` scope with the automatic fork point, two columns, and wrapped lines. * @param d - draft state. * @param tabId - the tab being drawn. * @param revision - the navigation revision being applied. */ navigated: (d, tabId: string, revision: number) => { const tab = d.byTab[tabId] - if (tab === undefined) d.byTab[tabId] = { scope: 'branch', split: true, wrap: true, navigated: revision } + if (tab === undefined) d.byTab[tabId] = { scope: 'branch', base: null, split: true, wrap: true, navigated: revision } else tab.navigated = revision }, /** @@ -67,6 +70,13 @@ export function createChangesStore(): EngineStoreHandle { bucket(d, tabId).scope = scope }, + /** + * Compare the `branch` scope with another branch. + * @param d - draft state. + * @param tabId - the tab being drawn. + * @param base - the branch, or null for the automatic fork point. + */ + based: (d, tabId: string, base: ForgeBaseBranch | null) => { bucket(d, tabId).base = base }, /** * Switch between one column and two. * @param d - draft state. diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index 8fe3515633..cceb6f7840 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -149,10 +149,22 @@ export const zh = { 'diff.scope.uncommitted': '未提交', 'diff.scope.unstaged': '未暂存', 'diff.scope.staged': '已暂存', - 'diff.scopeNote.branch': '与 {base} 比较,包含未提交的修改', 'diff.scopeNote.uncommitted': '与 HEAD 比较,包含未跟踪的文件', 'diff.scopeNote.unstaged': '与暂存区比较,包含未跟踪的文件', 'diff.scopeNote.staged': '暂存区与 HEAD 比较', + 'diff.base.aria': '基准分支:{base}', + 'diff.base.uncommitted': '包含未提交的修改', + 'diff.base.search': '搜索分支', + 'diff.base.loading': '正在读取分支…', + 'diff.base.empty': '没有匹配的分支', + 'diff.base.automatic': '默认', + 'diff.base.worktree': '工作树起点', + 'diff.base.remote': '远程分支', + 'diff.base.local': '本地分支', + 'diff.base.note': '与 HEAD 和所选分支的合并基准比较,包含未提交的修改', + 'diff.baseMissing': '找不到基准分支 {base},它可能已被删除', + 'diff.baseUnrelated': '{base} 与 HEAD 没有共同历史', + 'diff.useAutomaticBase': '使用默认基准分支', 'diff.allFiles': '全部 {count} 个文件', 'diff.filterFiles': '筛选文件…', 'diff.noMatchingFiles': '没有匹配的文件', @@ -180,7 +192,7 @@ export const zh = { 'diff.tooLarge': '变更太大,无法在这里显示', 'diff.filterConfigFailed': '无法完整读取 Git 过滤器配置,尚未执行比较。请检查 Git 配置和读取上限后重试', 'diff.viewInBrowser': '在浏览器中查看', - 'diff.noForkPoint': '找不到本分支的分叉点,请选择其他范围', + 'diff.noForkPoint': '找不到本分支的分叉点,请选择基准分支或其他范围', 'diff.empty': '没有变更', 'diff.omitted': '另有 {count} 个未跟踪的文件没有列出', 'diff.stale': '本地有 {count} 个提交尚未推送,这里显示的是变更请求上的变更', @@ -409,10 +421,22 @@ export const en: Record = { 'diff.scope.uncommitted': 'Uncommitted', 'diff.scope.unstaged': 'Unstaged', 'diff.scope.staged': 'Staged', - 'diff.scopeNote.branch': 'Compared with {base}, including uncommitted changes', 'diff.scopeNote.uncommitted': 'Compared with HEAD, including untracked files', 'diff.scopeNote.unstaged': 'Compared with the index, including untracked files', 'diff.scopeNote.staged': 'The index compared with HEAD', + 'diff.base.aria': 'Base branch: {base}', + 'diff.base.uncommitted': 'Including uncommitted changes', + 'diff.base.search': 'Search branches', + 'diff.base.loading': 'Reading branches…', + 'diff.base.empty': 'No matching branches', + 'diff.base.automatic': 'Default', + 'diff.base.worktree': 'Worktree start', + 'diff.base.remote': 'Remote branches', + 'diff.base.local': 'Local branches', + 'diff.base.note': 'Compared with the merge base of HEAD and the selected branch, including uncommitted changes', + 'diff.baseMissing': 'The base branch {base} was not found; it may have been deleted', + 'diff.baseUnrelated': '{base} shares no history with HEAD', + 'diff.useAutomaticBase': 'Use the default base branch', 'diff.allFiles': 'All {count} files', 'diff.filterFiles': 'Filter files…', 'diff.noMatchingFiles': 'No matching files', @@ -440,7 +464,7 @@ export const en: Record = { 'diff.tooLarge': 'These changes are too large to show here', 'diff.filterConfigFailed': 'No comparison was run because Git filter settings could not be read completely. Check the Git settings and output limit, then retry.', 'diff.viewInBrowser': 'View in browser', - 'diff.noForkPoint': 'No fork point was found for this branch; choose another scope', + 'diff.noForkPoint': 'No fork point was found for this branch; choose a base branch or another scope', 'diff.empty': 'No changes', 'diff.omitted': '{count} more untracked files are not listed', 'diff.stale': 'The local branch has {count} unpushed commits; these are the changes on the change request', @@ -673,10 +697,22 @@ export const ja: Record = { 'diff.scope.uncommitted': '未コミット', 'diff.scope.unstaged': '未ステージ', 'diff.scope.staged': 'ステージ済み', - 'diff.scopeNote.branch': '{base} と比較、未コミットの変更を含む', 'diff.scopeNote.uncommitted': 'HEAD と比較、未追跡ファイルを含む', 'diff.scopeNote.unstaged': 'インデックスと比較、未追跡ファイルを含む', 'diff.scopeNote.staged': 'インデックスと HEAD を比較', + 'diff.base.aria': '基準ブランチ:{base}', + 'diff.base.uncommitted': '未コミットの変更を含む', + 'diff.base.search': 'ブランチを検索', + 'diff.base.loading': 'ブランチを読み取り中…', + 'diff.base.empty': '一致するブランチがありません', + 'diff.base.automatic': 'デフォルト', + 'diff.base.worktree': 'ワークツリーの起点', + 'diff.base.remote': 'リモートブランチ', + 'diff.base.local': 'ローカルブランチ', + 'diff.base.note': 'HEAD と選択したブランチのマージベースと比較、未コミットの変更を含む', + 'diff.baseMissing': '基準ブランチ {base} が見つかりません。削除された可能性があります', + 'diff.baseUnrelated': '{base} は HEAD と共通の履歴がありません', + 'diff.useAutomaticBase': 'デフォルトの基準ブランチを使う', 'diff.allFiles': '全 {count} ファイル', 'diff.filterFiles': 'ファイルを絞り込み…', 'diff.noMatchingFiles': '一致するファイルがありません', @@ -704,7 +740,7 @@ export const ja: Record = { 'diff.tooLarge': '変更が大きすぎるため、ここには表示できません', 'diff.filterConfigFailed': 'Git フィルター設定を完全に読み取れないため、比較を実行していません。Git の設定と出力上限を確認して再試行してください。', 'diff.viewInBrowser': 'ブラウザーで表示', - 'diff.noForkPoint': 'このブランチの分岐点が見つかりません。別の範囲を選んでください', + 'diff.noForkPoint': 'このブランチの分岐点が見つかりません。基準ブランチか別の範囲を選んでください', 'diff.empty': '変更なし', 'diff.omitted': 'ほかに {count} 個の未追跡ファイルがあります', 'diff.stale': 'ローカルブランチに未プッシュのコミットが {count} 件あります。ここには変更リクエストの変更を表示しています', @@ -930,10 +966,22 @@ export const es: Record = { 'diff.scope.uncommitted': 'Sin confirmar', 'diff.scope.unstaged': 'Sin preparar', 'diff.scope.staged': 'Preparado', - 'diff.scopeNote.branch': 'Comparado con {base}, incluidos los cambios sin confirmar', 'diff.scopeNote.uncommitted': 'Comparado con HEAD, incluidos los archivos sin seguimiento', 'diff.scopeNote.unstaged': 'Comparado con el índice, incluidos los archivos sin seguimiento', 'diff.scopeNote.staged': 'Índice comparado con HEAD', + 'diff.base.aria': 'Rama base: {base}', + 'diff.base.uncommitted': 'Incluye los cambios sin confirmar', + 'diff.base.search': 'Buscar ramas', + 'diff.base.loading': 'Leyendo ramas…', + 'diff.base.empty': 'No hay ramas coincidentes', + 'diff.base.automatic': 'Predeterminada', + 'diff.base.worktree': 'Inicio del árbol de trabajo', + 'diff.base.remote': 'Ramas remotas', + 'diff.base.local': 'Ramas locales', + 'diff.base.note': 'Comparado con la base de fusión de HEAD y la rama elegida, incluidos los cambios sin confirmar', + 'diff.baseMissing': 'No se encontró la rama base {base}; puede que se haya eliminado', + 'diff.baseUnrelated': '{base} no comparte historial con HEAD', + 'diff.useAutomaticBase': 'Usar la rama base predeterminada', 'diff.allFiles': 'Los {count} archivos', 'diff.filterFiles': 'Filtrar archivos…', 'diff.noMatchingFiles': 'No hay archivos coincidentes', @@ -961,7 +1009,7 @@ export const es: Record = { 'diff.tooLarge': 'Estos cambios son demasiado grandes para mostrarlos aquí', 'diff.filterConfigFailed': 'No se pudo leer toda la configuración de filtros de Git. No se realizó la comparación. Comprueba la configuración de Git y el límite de salida, y vuelve a intentarlo.', 'diff.viewInBrowser': 'Ver en el navegador', - 'diff.noForkPoint': 'No se encontró el punto de bifurcación de esta rama; elige otro ámbito', + 'diff.noForkPoint': 'No se encontró el punto de bifurcación de esta rama; elige una rama base u otro ámbito', 'diff.empty': 'Sin cambios', 'diff.omitted': 'No se muestran otros {count} archivos sin seguimiento', 'diff.stale': 'La rama local tiene {count} commits sin enviar; se muestran los cambios de la solicitud', @@ -1187,10 +1235,22 @@ export const fr: Record = { 'diff.scope.uncommitted': 'Non commité', 'diff.scope.unstaged': 'Non indexé', 'diff.scope.staged': 'Indexé', - 'diff.scopeNote.branch': 'Comparaison avec {base}, modifications non commitées incluses', 'diff.scopeNote.uncommitted': 'Comparaison avec HEAD, fichiers non suivis inclus', 'diff.scopeNote.unstaged': 'Comparaison avec l’index, fichiers non suivis inclus', 'diff.scopeNote.staged': 'Comparaison de l’index avec HEAD', + 'diff.base.aria': 'Branche de base : {base}', + 'diff.base.uncommitted': 'Modifications non commitées incluses', + 'diff.base.search': 'Rechercher des branches', + 'diff.base.loading': 'Lecture des branches…', + 'diff.base.empty': 'Aucune branche correspondante', + 'diff.base.automatic': 'Par défaut', + 'diff.base.worktree': 'Départ de l’arbre de travail', + 'diff.base.remote': 'Branches distantes', + 'diff.base.local': 'Branches locales', + 'diff.base.note': 'Comparaison avec la base de fusion de HEAD et de la branche choisie, modifications non commitées incluses', + 'diff.baseMissing': 'La branche de base {base} est introuvable ; elle a peut-être été supprimée', + 'diff.baseUnrelated': '{base} n’a aucun historique commun avec HEAD', + 'diff.useAutomaticBase': 'Utiliser la branche de base par défaut', 'diff.allFiles': 'Les {count} fichiers', 'diff.filterFiles': 'Filtrer les fichiers…', 'diff.noMatchingFiles': 'Aucun fichier correspondant', @@ -1218,7 +1278,7 @@ export const fr: Record = { 'diff.tooLarge': 'Ces modifications sont trop volumineuses pour être affichées ici', 'diff.filterConfigFailed': 'Impossible de lire toute la configuration des filtres Git. Aucune comparaison effectuée. Vérifiez la configuration Git et la limite de sortie, puis réessayez.', 'diff.viewInBrowser': 'Voir dans le navigateur', - 'diff.noForkPoint': 'Le point de divergence de cette branche est introuvable ; choisissez une autre portée', + 'diff.noForkPoint': 'Le point de divergence de cette branche est introuvable ; choisissez une branche de base ou une autre portée', 'diff.empty': 'Aucune modification', 'diff.omitted': '{count} autres fichiers non suivis ne sont pas affichés', 'diff.stale': 'La branche locale contient {count} commits non envoyés ; les modifications de la demande sont affichées', @@ -1444,10 +1504,22 @@ export const de: Record = { 'diff.scope.uncommitted': 'Nicht committet', 'diff.scope.unstaged': 'Nicht vorgemerkt', 'diff.scope.staged': 'Vorgemerkt', - 'diff.scopeNote.branch': 'Vergleich mit {base}, einschließlich nicht committeter Änderungen', 'diff.scopeNote.uncommitted': 'Vergleich mit HEAD, einschließlich nicht verfolgter Dateien', 'diff.scopeNote.unstaged': 'Vergleich mit dem Index, einschließlich nicht verfolgter Dateien', 'diff.scopeNote.staged': 'Vergleich des Index mit HEAD', + 'diff.base.aria': 'Basis-Branch: {base}', + 'diff.base.uncommitted': 'Einschließlich nicht committeter Änderungen', + 'diff.base.search': 'Branches suchen', + 'diff.base.loading': 'Branches werden gelesen…', + 'diff.base.empty': 'Keine passenden Branches', + 'diff.base.automatic': 'Standard', + 'diff.base.worktree': 'Start des Arbeitsbaums', + 'diff.base.remote': 'Remote-Branches', + 'diff.base.local': 'Lokale Branches', + 'diff.base.note': 'Vergleich mit der Merge-Basis von HEAD und dem gewählten Branch, einschließlich nicht committeter Änderungen', + 'diff.baseMissing': 'Der Basis-Branch {base} wurde nicht gefunden; er wurde möglicherweise gelöscht', + 'diff.baseUnrelated': '{base} hat keinen gemeinsamen Verlauf mit HEAD', + 'diff.useAutomaticBase': 'Standard-Basis-Branch verwenden', 'diff.allFiles': 'Alle {count} Dateien', 'diff.filterFiles': 'Dateien filtern…', 'diff.noMatchingFiles': 'Keine passenden Dateien', @@ -1475,7 +1547,7 @@ export const de: Record = { 'diff.tooLarge': 'Diese Änderungen sind zu groß, um sie hier anzuzeigen', 'diff.filterConfigFailed': 'Die Git-Filtereinstellungen konnten nicht vollständig gelesen werden. Es wurde kein Vergleich ausgeführt. Prüfe die Git-Einstellungen und das Ausgabelimit und versuche es erneut.', 'diff.viewInBrowser': 'Im Browser ansehen', - 'diff.noForkPoint': 'Kein Verzweigungspunkt für diesen Branch gefunden; einen anderen Bereich wählen', + 'diff.noForkPoint': 'Kein Verzweigungspunkt für diesen Branch gefunden; einen Basis-Branch oder einen anderen Bereich wählen', 'diff.empty': 'Keine Änderungen', 'diff.omitted': '{count} weitere nicht verfolgte Dateien werden nicht angezeigt', 'diff.stale': 'Der lokale Branch hat {count} nicht gepushte Commits; angezeigt werden die Änderungen der Änderungsanfrage', @@ -1701,10 +1773,22 @@ export const ru: Record = { 'diff.scope.uncommitted': 'Без коммита', 'diff.scope.unstaged': 'Не в индексе', 'diff.scope.staged': 'В индексе', - 'diff.scopeNote.branch': 'Сравнение с {base}, включая изменения без коммита', 'diff.scopeNote.uncommitted': 'Сравнение с HEAD, включая неотслеживаемые файлы', 'diff.scopeNote.unstaged': 'Сравнение с индексом, включая неотслеживаемые файлы', 'diff.scopeNote.staged': 'Сравнение индекса с HEAD', + 'diff.base.aria': 'Базовая ветка: {base}', + 'diff.base.uncommitted': 'Включая изменения без коммита', + 'diff.base.search': 'Поиск веток', + 'diff.base.loading': 'Чтение веток…', + 'diff.base.empty': 'Нет подходящих веток', + 'diff.base.automatic': 'По умолчанию', + 'diff.base.worktree': 'Начало рабочего дерева', + 'diff.base.remote': 'Удалённые ветки', + 'diff.base.local': 'Локальные ветки', + 'diff.base.note': 'Сравнение с базой слияния HEAD и выбранной ветки, включая изменения без коммита', + 'diff.baseMissing': 'Базовая ветка {base} не найдена; возможно, она удалена', + 'diff.baseUnrelated': 'У {base} нет общей истории с HEAD', + 'diff.useAutomaticBase': 'Использовать базовую ветку по умолчанию', 'diff.allFiles': 'Все файлы: {count}', 'diff.filterFiles': 'Фильтр файлов…', 'diff.noMatchingFiles': 'Нет подходящих файлов', @@ -1732,7 +1816,7 @@ export const ru: Record = { 'diff.tooLarge': 'Изменения слишком велики для отображения здесь', 'diff.filterConfigFailed': 'Не удалось полностью прочитать настройки фильтров Git. Сравнение не выполнено. Проверьте настройки Git и ограничение вывода, затем повторите попытку.', 'diff.viewInBrowser': 'Посмотреть в браузере', - 'diff.noForkPoint': 'Не найдена точка ответвления этой ветки; выберите другую область', + 'diff.noForkPoint': 'Не найдена точка ответвления этой ветки; выберите базовую ветку или другую область', 'diff.empty': 'Нет изменений', 'diff.omitted': 'Не показано ещё неотслеживаемых файлов: {count}', 'diff.stale': 'В локальной ветке {count} неотправленных коммитов; показаны изменения из запроса', @@ -1958,10 +2042,22 @@ export const pt: Record = { 'diff.scope.uncommitted': 'Sem commit', 'diff.scope.unstaged': 'Fora da área de stage', 'diff.scope.staged': 'Na área de stage', - 'diff.scopeNote.branch': 'Comparação com {base}, incluindo alterações sem commit', 'diff.scopeNote.uncommitted': 'Comparação com HEAD, incluindo arquivos não rastreados', 'diff.scopeNote.unstaged': 'Comparação com o índice, incluindo arquivos não rastreados', 'diff.scopeNote.staged': 'Comparação do índice com HEAD', + 'diff.base.aria': 'Branch base: {base}', + 'diff.base.uncommitted': 'Incluindo alterações sem commit', + 'diff.base.search': 'Pesquisar branches', + 'diff.base.loading': 'Lendo branches…', + 'diff.base.empty': 'Nenhuma branch correspondente', + 'diff.base.automatic': 'Padrão', + 'diff.base.worktree': 'Início da árvore de trabalho', + 'diff.base.remote': 'Branches remotas', + 'diff.base.local': 'Branches locais', + 'diff.base.note': 'Comparação com a base de mesclagem de HEAD e da branch escolhida, incluindo alterações sem commit', + 'diff.baseMissing': 'A branch base {base} não foi encontrada; ela pode ter sido excluída', + 'diff.baseUnrelated': '{base} não compartilha histórico com HEAD', + 'diff.useAutomaticBase': 'Usar a branch base padrão', 'diff.allFiles': 'Todos os {count} arquivos', 'diff.filterFiles': 'Filtrar arquivos…', 'diff.noMatchingFiles': 'Nenhum arquivo correspondente', @@ -1989,7 +2085,7 @@ export const pt: Record = { 'diff.tooLarge': 'Estas alterações são grandes demais para serem exibidas aqui', 'diff.filterConfigFailed': 'Não foi possível ler todas as configurações de filtros do Git. A comparação não foi executada. Verifique as configurações do Git e o limite de saída e tente novamente.', 'diff.viewInBrowser': 'Ver no navegador', - 'diff.noForkPoint': 'Não foi encontrado o ponto de ramificação desta branch; escolha outro escopo', + 'diff.noForkPoint': 'Não foi encontrado o ponto de ramificação desta branch; escolha uma branch base ou outro escopo', 'diff.empty': 'Sem alterações', 'diff.omitted': 'Outros {count} arquivos não rastreados não são exibidos', 'diff.stale': 'A branch local tem {count} commits não enviados; são exibidas as alterações da solicitação', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index cd3aaa4c3d..3df7d4f8b3 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -201,6 +201,7 @@ function registerUi(ctx: Context): void { keyedHooks: { panel: visibility => visibility === 'visible' ? store.panel.hooks.panel : undefined }, reconnect: store.panel.reconnect, localDiff: (scope, signal) => ctx.remote.forgePanel.localDiff(sessionId, scope, signal), + diffBases: (query, signal) => ctx.remote.forgePanel.diffBases(sessionId, query, signal), localText: (scope, path) => ctx.remote.forgePanel.localText(sessionId, scope, path), changeRequestDiff: (url, signal) => ctx.remote.forgePanel.changeRequestDiff(sessionId, url, signal), changeRequestText: (url, commit, path) => ctx.remote.forgePanel.changeRequestText(sessionId, url, commit, path), diff --git a/packages/experimental/client-ui-forge/src/client/review-queue.ts b/packages/experimental/client-ui-forge/src/client/review-queue.ts index bb396cfd26..620c1eae77 100644 --- a/packages/experimental/client-ui-forge/src/client/review-queue.ts +++ b/packages/experimental/client-ui-forge/src/client/review-queue.ts @@ -7,7 +7,8 @@ import type { ReviewSelection, ReviewSource } from './review.ts' const line = z.object({ path: z.string(), side: z.enum(['L', 'R']), startLine: z.number().int().positive(), endLine: z.number().int().positive(), body: z.string() }) const selection = z.object({ source: z.object({ kind: z.literal('change'), url: z.string(), headSha: z.string() }), comment: line.extend({ hunk: z.string() }) }) const recordedSelection = selection.extend({ source: z.discriminatedUnion('kind', [ - selection.shape.source, z.object({ kind: z.literal('local'), scope: z.string() }), + selection.shape.source, + z.object({ kind: z.literal('local'), scope: z.string(), base: z.string().nullable().default(null), baseRef: z.string().nullable().default(null) }), ]) }) const record = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('agent'), selection: recordedSelection }), @@ -108,7 +109,7 @@ export class ReviewQueue { ...this.state.records.filter(item => matches(item.selection)).map(item => ({ ...item, key: this.keyOf(item.selection) })), ...this.state.comments.filter(matches).map(item => ({ kind: 'pending' as const, selection: item, key: this.keyOf(item) })), ] - const key = JSON.stringify([path, source.kind, source.kind === 'local' ? source.scope : source.url]) + const key = JSON.stringify([path, source.kind, source.kind === 'local' ? [source.scope, source.baseRef] : source.url]) const previous = this.files.get(key) const locked = this.state.uncertain !== null if (previous !== undefined && previous.locked === locked && previous.error === this.state.error @@ -250,9 +251,9 @@ export class ReviewQueue { * Compare review identity while allowing records from an older PR head to remain visible. * @param left - recorded source. * @param right - displayed source. - * @returns whether the sources name the same PR or local scope. + * @returns whether the sources name the same PR, or the same local scope and base ref. */ export function sameReviewSource(left: ReviewSource, right: ReviewSource): boolean { - return left.kind === 'local' ? right.kind === 'local' && left.scope === right.scope + return left.kind === 'local' ? right.kind === 'local' && left.scope === right.scope && left.baseRef === right.baseRef : right.kind === 'change' && left.url === right.url } diff --git a/packages/experimental/client-ui-forge/src/client/review.ts b/packages/experimental/client-ui-forge/src/client/review.ts index 034d6cad42..28109564ae 100644 --- a/packages/experimental/client-ui-forge/src/client/review.ts +++ b/packages/experimental/client-ui-forge/src/client/review.ts @@ -20,7 +20,11 @@ export interface ReviewComment { /** The immutable source from which a comment was selected. */ export type ReviewSource = - | { readonly kind: 'local'; readonly scope: string } + /** + * Local changes in a scope. `base` names what the `branch` scope compared with for the reader, and is null for + * other scopes; `baseRef` identifies the comparison: the chosen ref, or null for the automatic fork point and other scopes. + */ + | { readonly kind: 'local'; readonly scope: string; readonly base: string | null; readonly baseRef: string | null } | { readonly kind: 'change'; readonly url: string; readonly headSha: string } /** One selected range and the source the user saw. */ @@ -65,7 +69,8 @@ export function formatReviewComment(selection: ReviewSelection, index: number): const range = comment.startLine === comment.endLine ? String(comment.startLine) : `${comment.startLine}-${comment.endLine}` // A longer fence keeps code containing Markdown fences inside the quoted hunk. const fence = '`'.repeat(Math.max(3, ...Array.from(comment.hunk.matchAll(/`+/g), match => match[0].length + 1))) - const origin = source.kind === 'local' ? `Source: Local (${source.scope})` : `Source: ${source.url}\nCommit: ${source.headSha}` + const origin = source.kind === 'change' ? `Source: ${source.url}\nCommit: ${source.headSha}` + : `Source: Local (${source.scope})${source.base === null ? '' : `\nBase: ${source.base}`}` return `## User Comment ${index}\nFile: ${comment.path}\nSide: ${comment.side}\nLines: ${range}\n${origin}\nDiff hunk:\n${fence}diff\n${comment.hunk}\n${fence}\nComment:\n${comment.body}` } diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 7fa9010b81..41a3884dd4 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -18,14 +18,16 @@ import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typer import { gitIn, inspectCheckout, listBranches } from './git.ts' import type { Inspection } from './git.ts' import { parseDiff } from './diff.ts' -import { aheadOf, DiffTooLarge, FilterConfigError, forkPoint, localDiff, localText, NoForkPoint } from './local-diff.ts' +import { + aheadOf, BaseMissing, baseBranches, chosenForkPoint, DiffTooLarge, FilterConfigError, forkPoint, localDiff, localText, NoForkPoint, +} from './local-diff.ts' import { missingWorktree, SessionPanel } from './panel.ts' import { PatchCache } from './patch-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { - Config, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, - ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, + Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope, + ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, } from './types.ts' import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' @@ -189,6 +191,24 @@ export class ForgePanelController extends TypertRemoteService { return await listBranches(this.home, this.config, session, this.home.workingDirectory.get(session), this.config.maxBranches, signal) } + /** + * List the branches the `branch` scope of the Session's current checkout can compare with. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. + * @param signal - request cancellation. + * @returns the automatic fork point and at most `maxBranches` remote-tracking and local branches each, + * most recently committed first, without the checked-out branch. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. + */ + @Remote + async diffBases(session: Session, query: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + const inspection = await this.checkoutOf(session, signal) + // A search can match any branch, so every ref is listed; a repository's refs can far exceed other short Git output. + const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal) + return await baseBranches(git, inspection, this.worktreeState(session).created, query, this.config.maxBranches) + } + /* oxlint-disable typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect */ /** * Bind a change request to a Session by URL, or restore a dismissed binding. @@ -238,18 +258,20 @@ export class ForgePanelController extends TypertRemoteService { * @param scope - which changes to read. * @param signal - request cancellation. * @returns the files, the base of the `branch` scope, and the untracked files left out. - * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/no-fork-point` for the `branch` - * scope of a checkout without one; `forgePanel/filter-config-failed` when filter configuration cannot be read - * completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch + * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without + * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise { signal.throwIfAborted() const inspection = await this.checkoutOf(session, signal) const root = inspection.checkout.root - const fork = scope.kind === 'branch' - ? await forkPoint(gitIn(this.home, this.config, session, root, signal), inspection, this.worktreeState(session).created) - : null + const git = gitIn(this.home, this.config, session, root, signal) + const created = this.worktreeState(session).created + const fork = scope.kind !== 'branch' ? null + : await diffing(scope.base === null ? forkPoint(git, inspection, created) : chosenForkPoint(git, scope.base)) return await diffing(localDiff(this.home, this.config, session, root, fork, scope, signal)) } @@ -693,7 +715,7 @@ function readError(failure: ForgeFailure): RemoteError { } /** - * Settle a diff read, reporting its size limit and a missing fork point as Remote errors. + * Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, and a missing base branch as Remote errors. * @param reading - the read. * @returns what the read returned. */ @@ -704,6 +726,7 @@ async function diffing(reading: Promise): Promise { if (error instanceof FilterConfigError) throw new RemoteError('forgePanel/filter-config-failed', error.message, {}, { cause: error }) if (error instanceof DiffTooLarge) throw new RemoteError('forgePanel/diff-too-large', error.message, {}, { cause: error }) if (error instanceof NoForkPoint) throw new RemoteError('forgePanel/no-fork-point', error.message, {}, { cause: error }) + if (error instanceof BaseMissing) throw new RemoteError('forgePanel/base-missing', error.message, {}, { cause: error }) throw error } } diff --git a/packages/experimental/client-ui-forge/src/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index cbe09afbd5..34c6ac6114 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -13,8 +13,10 @@ import { assertNever } from '@deepseek-ai/dsh-util-values' import { decodeText, parseDiff, parseNumstat, untrackedFile } from './diff.ts' import { gitIn, GitOutputTooLarge } from './git.ts' import type { Git, GitConfig, GitOutput, Inspection } from './git.ts' -import { parseName, remoteOrder } from './parse.ts' -import type { ForgeDiffFile, ForgeLocalChanges, ForgeLocalDiff, ForgeLocalScope, ForgeSessionWorktree } from './types.ts' +import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts' +import type { + ForgeBaseBranches, ForgeDiffFile, ForgeLocalChanges, ForgeLocalDiff, ForgeLocalScope, ForgeSessionWorktree, +} from './types.ts' /** Git limits plus the size limits of local diffs. */ export interface DiffConfig extends GitConfig { @@ -28,8 +30,10 @@ export interface DiffConfig extends GitConfig { export interface ForkPoint { /** Full commit object name. */ readonly commit: string - /** Remote branch such as `origin/master`, the created worktree's base branch, or an abbreviated commit. */ + /** Branch such as `origin/master`, the created worktree's base branch, or an abbreviated commit. */ readonly label: string + /** Whether `commit` is the base commit of the worktree the Session created rather than a merge base. */ + readonly worktree: boolean } /** Thrown when a patch, a file list, or a file exceeds `maxDiffBytes`. */ @@ -47,6 +51,11 @@ export class NoForkPoint extends Error { override name = 'NoForkPoint' } +/** Thrown when the base branch chosen for the `branch` scope does not exist. */ +export class BaseMissing extends Error { + override name = 'BaseMissing' +} + /** No executable diff helpers or submodule working-tree inspection; preserve recorded submodule commit changes. */ const DIFF = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff', '--no-textconv', '--submodule=short', '--ignore-submodules=dirty', '--no-color', '-M', '--src-prefix=a/', '--dst-prefix=b/'] as const @@ -73,7 +82,7 @@ async function diffFilterOverrides(git: Git): Promise { if (created !== null && created.path === inspection.checkout.root) { - return { commit: created.baseCommit, label: created.from ?? created.baseCommit.slice(0, 7) } + return { commit: created.baseCommit, label: created.from ?? created.baseCommit.slice(0, 7), worktree: true } } for (const remote of remoteOrder(inspection.upstream, inspection.remotes)) { const head = await git('remote-head', ['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote.name}/HEAD`], [0, 1, 128]) @@ -92,11 +101,57 @@ export async function forkPoint(git: Git, inspection: Inspection, created: Forge if (base === null) continue const merge = await git('merge-base', ['merge-base', 'HEAD', base], [0, 1, 128]) const commit = merge.exitCode === 0 ? parseName(merge.stdout) : null - return commit === null ? null : { commit, label: base } + return commit === null ? null : { commit, label: base, worktree: false } } return null } +/** + * Find where the `branch` scope forks from a chosen base branch: the merge base of HEAD with it. + * @param git - runner bound to the checkout. + * @param ref - full ref name under `refs/heads/` or `refs/remotes/`. + * @returns the fork point, or null when HEAD shares no history with the branch or has no commit. + * @throws BaseMissing when the ref does not exist; an Error for another ref name or when Git fails. + */ +export async function chosenForkPoint(git: Git, ref: string): Promise { + const prefix = BASE_REF_PREFIXES.find(candidate => ref.startsWith(candidate) && ref.length > candidate.length) + if (prefix === undefined) throw new Error(`forge-panel: ${JSON.stringify(ref)} is not a branch ref`) + const name = ref.slice(prefix.length) + // `--verify` accepts only an exact ref path, so revision syntax such as `@{1}` never resolves. + const present = await git('show-ref', ['show-ref', '--verify', '--quiet', ref], [0, 1]) + if (present.exitCode !== 0) throw new BaseMissing(`The base branch ${name} does not exist`) + const merge = await git('merge-base', ['merge-base', 'HEAD', ref], [0, 1, 128]) + const commit = merge.exitCode === 0 ? parseName(merge.stdout) : null + return commit === null ? null : { commit, label: name, worktree: false } +} + +/** + * List the branches the `branch` scope can compare with. + * @param git - runner bound to the checkout. + * @param inspection - the checkout and its remotes. + * @param created - worktree the Session created, or null. + * @param query - text the branch names must contain, ignoring case; empty for every branch. + * @param limit - most branches in each group. + * @returns the automatic fork point, then remote-tracking and local branches, most recently committed first. + * @throws an Error when Git fails or prints more than the runner's output limit. + */ +export async function baseBranches( + git: Git, + inspection: Inspection, + created: ForgeSessionWorktree | null, + query: string, + limit: number, +): Promise { + const fork = await forkPoint(git, inspection, created) + const refs = await git('base-branches', [ + 'for-each-ref', '--sort=-committerdate', '--format=%(refname)%00%(symref)', ...BASE_REF_PREFIXES, + ]) + return { + automatic: fork === null ? null : { name: fork.label, worktree: fork.worktree }, + ...parseBaseBranches(refs.stdout, inspection.checkout.branch, query, limit), + } +} + /** * Read changes at `root` with command-local clean/process filter overrides and without * submodule working-tree inspection. Git's built-in newline, ident, and encoding conversions still apply. diff --git a/packages/experimental/client-ui-forge/src/parse.ts b/packages/experimental/client-ui-forge/src/parse.ts index 05cf03613c..b163c40e4a 100644 --- a/packages/experimental/client-ui-forge/src/parse.ts +++ b/packages/experimental/client-ui-forge/src/parse.ts @@ -1,5 +1,7 @@ /** Parsers for the porcelain output of the read-only Git commands the panel runs. */ +import type { ForgeBaseBranch } from './types.ts' + /** One remote with the URLs `git remote -v` prints for it. */ export interface GitRemote { /** Remote name such as `origin`. */ @@ -30,6 +32,40 @@ export function parseName(output: string): string | null { return name.length === 0 ? null : name } +/** Ref prefixes of the branches the `branch` scope can compare with: local branches, then remote-tracking branches. */ +export const BASE_REF_PREFIXES = ['refs/heads/', 'refs/remotes/'] as const + +/** + * Select the branches the `branch` scope can compare with from `git for-each-ref` + * output, keeping its order and leaving out symbolic refs and the checked-out branch. + * @param output - stdout of `git for-each-ref --format=%(refname)%00%(symref)` over {@link BASE_REF_PREFIXES}. + * @param current - checked-out branch, or null when HEAD is detached. + * @param query - text the names must contain, ignoring case; empty or blank for every branch. + * @param limit - most branches in each group. + * @returns remote-tracking and local branches, at most `limit` of each. + */ +export function parseBaseBranches( + output: string, + current: string | null, + query: string, + limit: number, +): { readonly remote: ForgeBaseBranch[]; readonly local: ForgeBaseBranch[] } { + const [heads, remotes] = BASE_REF_PREFIXES + const needle = query.trim().toLowerCase() + const remote: ForgeBaseBranch[] = [] + const local: ForgeBaseBranch[] = [] + for (const line of output.split(/\r?\n/)) { + const [ref = '', symref = ''] = line.split('\0') + if (symref.length > 0) continue + const group = ref.startsWith(heads) ? local : ref.startsWith(remotes) ? remote : undefined + if (group === undefined || group.length >= limit) continue + const name = ref.slice(group === local ? heads.length : remotes.length) + if (name.length === 0 || (group === local && name === current) || !name.toLowerCase().includes(needle)) continue + group.push({ ref, name }) + } + return { remote, local } +} + /** * Order worktree base branches: the checked-out branch first, then the other * listed branches in listed order. diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index c96b0a7bb6..2a11e67ac6 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -216,13 +216,40 @@ export interface ForgeBranches { readonly branches: readonly string[] } +/** A branch the `branch` scope can compare with. */ +export interface ForgeBaseBranch { + /** Full ref name: `refs/heads/` or `refs/remotes//`. */ + readonly ref: string + /** The ref without `refs/heads/` or `refs/remotes/`, such as `master` or `origin/master`. */ + readonly name: string +} + +/** What the `branch` scope compares with while no base branch is chosen. */ +export interface ForgeAutomaticBase { + /** The created worktree's base branch or abbreviated base commit, or the default branch of the code host remote. */ + readonly name: string + /** Whether the fork point is the base commit of the worktree the Session created rather than a merge base. */ + readonly worktree: boolean +} + +/** Branches the `branch` scope can compare with, whose names contain a query. */ +export interface ForgeBaseBranches { + /** The fork point used while no base branch is chosen, whatever the query; null without one. */ + readonly automatic: ForgeAutomaticBase | null + /** Remote-tracking branches without symbolic refs such as `origin/HEAD`, most recently committed first, at most `maxBranches`. */ + readonly remote: readonly ForgeBaseBranch[] + /** Local branches other than the checked-out one, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] +} + /** Which local changes a diff covers; each reads the Session's checkout through Git. */ export type ForgeLocalScope = /** - * The working tree and untracked files against the fork point: the base commit of the worktree the - * Session created, else the merge base of HEAD with the default branch of the code host remote. + * The working tree and untracked files against a fork point: the merge base of HEAD with the + * `base` ref, or while `base` is null, the base commit of the worktree the Session created, + * else the merge base of HEAD with the default branch of the code host remote. */ - | { readonly kind: 'branch' } + | { readonly kind: 'branch'; readonly base: string | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -326,14 +353,14 @@ export interface Config { maxOutputBytes?: number /** Deadline in milliseconds for one provider sign-in probe. */ readinessTimeoutMs?: number - /** Most local branches listed as worktree bases. */ + /** Most local branches listed as worktree bases, and most branches in each group of base branches listed for the `branch` scope. */ maxBranches?: number /** * Prefix of the branch and checkout directory created for a Session worktree; the first eight * hexadecimal digits of the Session id's UUID, a hyphen, and four random hexadecimal digits follow it. */ worktreePrefix?: string - /** Largest diff, or file read to show unchanged lines, in bytes. */ + /** Largest diff, file read to show unchanged lines, or list of base branch refs, in bytes. */ maxDiffBytes?: number /** Most untracked files a local diff or the local changes card includes. */ maxUntrackedFiles?: number @@ -367,8 +394,13 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/action-failed': Record /** The Session's directory is not inside a Git checkout, so it has no local changes. */ 'forgePanel/not-a-checkout': Record - /** No remote names a default branch that HEAD shares history with, and the checkout is not a worktree the Session created. */ + /** + * HEAD shares no history with the base branch chosen for the `branch` scope, or with none chosen, no remote names a + * default branch that HEAD shares history with and the checkout is not a worktree the Session created. + */ 'forgePanel/no-fork-point': Record + /** The base branch chosen for the `branch` scope does not exist, as after the branch was deleted. */ + 'forgePanel/base-missing': Record /** Filter configuration could not be read completely; no comparison ran. Correct Git settings or the output limit before retrying. */ 'forgePanel/filter-config-failed': Record /** diff --git a/packages/experimental/client-ui-forge/tests/base-menu.client.spec.tsx b/packages/experimental/client-ui-forge/tests/base-menu.client.spec.tsx new file mode 100644 index 0000000000..a4c5f659b8 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/base-menu.client.spec.tsx @@ -0,0 +1,214 @@ +// @vitest-environment jsdom +/** The base branch picker: listing, searching, choosing, failures, and when its search field takes the keyboard. */ +import { act, cleanup, fireEvent, render, within } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { BaseMenu, type BaseMenuProps } from '../src/client/BaseMenu.tsx' +import css from '../src/client/BaseMenu.module.css' +import { en } from '../src/client/locales.ts' +import type { ForgeBaseBranch, ForgeBaseBranches } from '../src/types.ts' + +const t = makeTranslate(en) +const MAIN: ForgeBaseBranch = { ref: 'refs/remotes/origin/main', name: 'origin/main' } +const RELEASE: ForgeBaseBranch = { ref: 'refs/remotes/origin/release/2.4', name: 'origin/release/2.4' } +const TOPIC: ForgeBaseBranch = { ref: 'refs/heads/topic', name: 'topic' } +const BRANCHES: ForgeBaseBranches = { automatic: { name: 'origin/main', worktree: false }, remote: [MAIN, RELEASE], local: [TOPIC] } +const FAILED: RemoteResult = { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) } + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +function ok(value: ForgeBaseBranches): RemoteResult { + return { ok: true, value } +} + +/** Let the listing reads the menu awaits settle, past the search delay when `ms` is given. */ +async function settle(ms = 0): Promise { + await act(async () => { await new Promise(resolve => setTimeout(resolve, ms)) }) +} + +function mount(props: Partial = {}) { + const list = props.list ?? vi.fn(async () => ok(BRANCHES)) + const choose = vi.fn() + const all: BaseMenuProps = { chosen: null, label: 'origin/main', missing: false, visible: true, t, ...props, list, choose } + const view = render() + const trigger = (): HTMLElement => view.getByRole('button', { name: `Base branch: ${all.label}` }) + const rows = (): string[] => view.queryAllByRole('menuitem').map(row => row.textContent ?? '') + const search = (): HTMLElement => view.getByRole('textbox', { name: en['diff.base.search'] }) + const rerender = (next: Partial): void => { view.rerender() } + return { view, list, choose, trigger, rows, search, rerender } +} + +describe('BaseMenu listing', () => { + it('lists the automatic fork point first, then remote-tracking and local branches without repeating the default branch', async () => { + const m = mount() + fireEvent.click(m.trigger()) + expect(m.view.getByRole('status').textContent).toBe(en['diff.base.loading']) + await settle() + expect(m.list).toHaveBeenCalledWith('', expect.any(AbortSignal)) + expect(m.rows()).toEqual(['origin/mainDefault', 'origin/release/2.4', 'topic']) + expect(m.view.getAllByRole('group').map(group => group.getAttribute('aria-label'))) + .toEqual([en['diff.base.automatic'], en['diff.base.remote'], en['diff.base.local']]) + expect(m.view.getByRole('menuitem', { name: /^origin\/main/ }).getAttribute('aria-current')).toBe('page') + + fireEvent.click(m.view.getByRole('menuitem', { name: 'topic' })) + expect(m.choose).toHaveBeenCalledWith(TOPIC) + expect(m.rows()).toEqual([]) + }) + + it('names the start of a created worktree, keeps the branch of the same name, and leaves out a missing automatic fork point', async () => { + const m = mount({ chosen: TOPIC, label: 'topic', list: vi.fn(async () => ok({ ...BRANCHES, automatic: { name: 'origin/main', worktree: true } })) }) + fireEvent.click(m.trigger()) + await settle() + expect(m.rows()).toEqual(['origin/mainWorktree start', 'origin/main', 'origin/release/2.4', 'topic']) + expect(m.view.getByRole('menuitem', { name: 'topic' }).getAttribute('aria-current')).toBe('page') + fireEvent.click(m.view.getByRole('menuitem', { name: 'topic' })) + expect(m.choose).not.toHaveBeenCalled() + + const without = mount({ label: 'Default', list: vi.fn(async () => ok({ ...BRANCHES, automatic: null })) }) + fireEvent.click(without.trigger()) + await settle() + expect(without.rows()).toEqual(['origin/main', 'origin/release/2.4', 'topic']) + }) + + it('reports a failed listing with a retry', async () => { + const m = mount({ list: vi.fn().mockResolvedValueOnce(FAILED).mockResolvedValue(ok(BRANCHES)) }) + fireEvent.click(m.trigger()) + await settle() + const status = m.view.getByRole('status') + expect(status.textContent).toBe(`${en['toast.branchesFailed']}${en.retry}`) + fireEvent.click(within(status).getByRole('button', { name: en.retry })) + await settle() + expect(m.list).toHaveBeenCalledTimes(2) + expect(m.rows()).toHaveLength(3) + }) + + it('drops a listing that ends after the menu closed', async () => { + let finish: (result: RemoteResult) => void = () => {} + const list = vi.fn().mockImplementationOnce(() => new Promise((resolve) => { finish = resolve })) + .mockImplementation(() => new Promise(() => {})) + const m = mount({ list }) + fireEvent.click(m.trigger()) + await settle() + fireEvent.click(m.trigger()) + await act(async () => { finish(ok(BRANCHES)) }) + fireEvent.click(m.trigger()) + await settle() + expect(list.mock.calls[0]?.[1].aborted).toBe(true) + expect(m.view.getByRole('status').textContent).toBe(en['diff.base.loading']) + }) +}) + +describe('BaseMenu search', () => { + it('filters listed rows at once, reads the search after a pause, and picks the first match with Enter', async () => { + const m = mount({ + list: vi.fn(async (query: string) => ok(query === '' ? BRANCHES : { automatic: BRANCHES.automatic, remote: [RELEASE], local: [] })), + }) + fireEvent.click(m.trigger()) + await settle() + fireEvent.change(m.search(), { target: { value: ' REL' } }) + expect(m.rows()).toEqual(['origin/release/2.4']) + expect(m.list).not.toHaveBeenCalledWith(' REL', expect.any(AbortSignal)) + await settle(200) + expect(m.list).toHaveBeenLastCalledWith(' REL', expect.any(AbortSignal)) + + fireEvent.keyDown(m.search(), { key: 'Enter', isComposing: true }) + fireEvent.keyDown(m.search(), { key: 'a' }) + expect(m.choose).not.toHaveBeenCalled() + fireEvent.keyDown(m.search(), { key: 'Enter' }) + expect(m.choose).toHaveBeenCalledWith(RELEASE) + }) + + it('says when no branch matches and keeps Enter from choosing', async () => { + const m = mount() + fireEvent.click(m.trigger()) + await settle() + fireEvent.change(m.search(), { target: { value: 'hotfix' } }) + expect(m.view.getByText(en['diff.base.empty'])).toBeTruthy() + fireEvent.keyDown(m.search(), { key: 'Enter' }) + expect(m.choose).not.toHaveBeenCalled() + expect(m.view.getByText(en['diff.base.empty'])).toBeTruthy() + }) + + it('keeps caret keys in the search field instead of walking the rows', async () => { + const m = mount() + fireEvent.click(m.trigger()) + await settle() + m.search().focus() + for (const key of ['Home', 'End', 'ArrowLeft', 'ArrowRight']) { + fireEvent.keyDown(m.search(), { key }) + expect(document.activeElement).toBe(m.search()) + } + }) +}) + +describe('BaseMenu trigger', () => { + it('marks a missing branch, closes on a second press, and stays closed while its tab is hidden', async () => { + const m = mount({ missing: true, label: 'topic', chosen: TOPIC }) + expect(m.trigger().classList.contains(css.missing ?? '')).toBe(true) + expect(m.trigger().getAttribute('data-forge-base')).toBe(TOPIC.ref) + fireEvent.click(m.trigger()) + await settle() + expect(m.trigger().getAttribute('aria-expanded')).toBe('true') + fireEvent.click(m.trigger()) + expect(m.rows()).toEqual([]) + + m.rerender({ visible: false }) + fireEvent.click(m.trigger()) + expect(m.trigger().getAttribute('aria-expanded')).toBe('false') + expect(m.rows()).toEqual([]) + m.rerender({ visible: true }) + await settle() + expect(m.rows()).toHaveLength(3) + }) + + it('gives the search field the keyboard one frame after opening, except on a touch screen', async () => { + let frames = new Map() + let next = 0 + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { + frames.set(++next, callback) + return next + }) + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => { frames.delete(id) }) + /** Run the frames queued so far; ones they queue wait for the next call. */ + const frame = (): void => { + const queued = frames + frames = new Map() + act(() => { for (const callback of queued.values()) callback(0) }) + } + const m = mount() + fireEvent.click(m.trigger()) + expect(document.activeElement).not.toBe(m.search()) + frame() + expect(document.activeElement).toBe(m.search()) + fireEvent.click(m.trigger()) + + const matchMedia = vi.fn((_query: string) => ({ matches: true })) + vi.stubGlobal('matchMedia', matchMedia) + m.trigger().focus() + fireEvent.click(m.trigger()) + frame() + expect(matchMedia).toHaveBeenCalledWith('(pointer: coarse)') + expect(document.activeElement).not.toBe(m.search()) + fireEvent.click(m.trigger()) + + matchMedia.mockReturnValue({ matches: false }) + fireEvent.click(m.trigger()) + frame() + expect(document.activeElement).toBe(m.search()) + }) + + it('cancels the pending focus when the menu closes before its frame', async () => { + const cancelled = vi.spyOn(window, 'cancelAnimationFrame') + const m = mount() + fireEvent.click(m.trigger()) + fireEvent.click(m.trigger()) + expect(cancelled).toHaveBeenCalled() + await settle(50) + expect(m.view.queryByRole('textbox')).toBeNull() + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx index 3b7b7d0c97..7ef34076a5 100644 --- a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx @@ -493,9 +493,13 @@ describe('ChangeRequestCard actions', () => { const button = within(b.item).getByRole('button', { name: en['change.merge'] }) expect(within(b.item).queryByRole('button', { name: en['change.markReady'] })).toBeNull() expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.classList.contains(css.mergeAction ?? '')).toBe(true) + const caret = (): Element | null => button.querySelector(`.${css.mergeCaret}`) + expect(caret()?.classList.contains(css.mergeCaretOpen ?? '')).toBe(false) fireEvent.click(button) expect(button.getAttribute('aria-expanded')).toBe('true') + expect(caret()?.classList.contains(css.mergeCaretOpen ?? '')).toBe(true) expect(within(screen.getByRole('menu')).getByText('Merge #7 into main')).toBeTruthy() expect(mergeRows()).toEqual([ 'Create a merge commitKeep every commit and add a merge commit ✓', diff --git a/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts b/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts index 15f96abb04..fe37c7bf52 100644 --- a/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/changes-address.client.spec.ts @@ -59,12 +59,15 @@ describe('createChangesStore', () => { it('seeds a tab on its first navigation, keeps its choices, and forgets it', () => { const store = createChangesStore().create() store.actions.navigated('tab-1', 1) - expect(store.getSnapshot().byTab['tab-1']).toEqual({ scope: 'branch', split: true, wrap: true, navigated: 1 }) + expect(store.getSnapshot().byTab['tab-1']).toEqual({ scope: 'branch', base: null, split: true, wrap: true, navigated: 1 }) store.actions.scoped('tab-1', 'staged') + store.actions.based('tab-1', { ref: 'refs/heads/topic', name: 'topic' }) store.actions.toggledSplit('tab-1') store.actions.toggledWrap('tab-1') store.actions.navigated('tab-1', 2) - expect(store.getSnapshot().byTab['tab-1']).toEqual({ scope: 'staged', split: false, wrap: false, navigated: 2 }) + expect(store.getSnapshot().byTab['tab-1']).toEqual({ + scope: 'staged', base: { ref: 'refs/heads/topic', name: 'topic' }, split: false, wrap: false, navigated: 2, + }) store.actions.navigated('tab-2', 1) store.actions.forget('tab-1') expect(Object.keys(store.getSnapshot().byTab)).toEqual(['tab-2']) diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 403ae91ad8..eaa90722ce 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -18,7 +18,10 @@ import { ChangesTab, type ChangesTabInjected, type ChangesTabProps } from '../sr import { en, zh } from '../src/client/locales.ts' import type { PanelSnapshot } from '../src/client/source.ts' import css from '../src/client/ChangesTab.module.css' -import type { ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelState } from '../src/types.ts' +import baseCss from '../src/client/BaseMenu.module.css' +import type { + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelState, +} from '../src/types.ts' import { entry, ready, snapshot } from './client-fixtures.client.ts' const t = makeTranslate(en) @@ -96,6 +99,14 @@ const CHANGE: ForgeChangeRequestDiff = { fileUrls: { 'src/app.ts': `https://github.com/octo/demo/blob/${HEAD}/src/app.ts`, 'docs/gone.txt': `https://github.com/octo/demo/blob/${HEAD}/docs/gone.txt` }, } +const TOPIC: ForgeBaseBranch = { ref: 'refs/heads/topic', name: 'topic' } +/** Branches the `branch` scope can compare with: `origin/main` automatically, a release branch, and `topic`. */ +const BASES: ForgeBaseBranches = { + automatic: { name: BASE, worktree: false }, + remote: [{ ref: 'refs/remotes/origin/main', name: BASE }, { ref: 'refs/remotes/origin/release/2.4', name: 'origin/release/2.4' }], + local: [TOPIC], +} + /** Panel state of `/work/repo` on `main` whose `branch` scope changes `src/app.ts` against `origin/main`. */ const LOCAL_STATE = ready({ local: { base: BASE, files: [{ path: 'src/app.ts', additions: 2, deletions: 2, binary: false }] } }) /** Panel state with change request #7 from `feat`. */ @@ -108,6 +119,7 @@ function ok(value: T): RemoteResult { /** Refused Remote reads, by what the Host said. */ const REFUSED = { noForkPoint: { ok: false, error: new RemoteError('forgePanel/no-fork-point', 'no fork point', {}) }, + baseMissing: { ok: false, error: new RemoteError('forgePanel/base-missing', 'no base branch', {}) }, notCheckout: { ok: false, error: new RemoteError('forgePanel/not-a-checkout', 'not a checkout', {}) }, tooLarge: { ok: false, error: new RemoteError('forgePanel/diff-too-large', 'too large', {}) }, filterConfig: { ok: false, error: new RemoteError('forgePanel/filter-config-failed', 'filter configuration unavailable', {}) }, @@ -202,6 +214,7 @@ function mount(options: MountOptions = {}) { const faces: Faces = { reconnect: vi.fn(), localDiff: vi.fn(async () => ok(LOCAL)), + diffBases: vi.fn(async () => ok(BASES)), localText: vi.fn(async () => ok(APP_TEXT)), changeRequestDiff: vi.fn(async () => ok(CHANGE)), changeRequestText: vi.fn(async () => ok(APP_TEXT)), @@ -393,14 +406,17 @@ describe('ChangesTab local reads', () => { const m = mount({ state: null }) expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() expect(m.view.queryByRole('button', { name: en['changes.local.create'] })).toBeNull() + expect(m.view.container.querySelector('[data-forge-head]')?.textContent).toBe('HEAD') expect(m.faces.localDiff).not.toHaveBeenCalled() act(() => { m.panel.set({ state: LOCAL_STATE, disconnected: false }) }) - expect(m.faces.localDiff).toHaveBeenCalledWith({ kind: 'branch' }, expect.any(AbortSignal)) + expect(m.faces.localDiff).toHaveBeenCalledWith({ kind: 'branch', base: null }, expect.any(AbortSignal)) await settle() expect(m.paths()).toEqual(['assets/logo.png', 'docs/gone.txt', 'lib/b.txt', 'logs/big.log', 'src/app.ts', 'src/new.ts']) - expect(m.view.getByText('Compared with origin/main, including uncommitted changes')).toBeTruthy() + expect(m.view.container.querySelector('[data-forge-head]')?.textContent).toBe('main') + expect(m.view.getByRole('button', { name: 'Base branch: origin/main' })).toBeTruthy() + expect(m.view.getByText(en['diff.base.uncommitted'])).toBeTruthy() expect(m.view.getByRole('status').textContent).toBe('2 more untracked files are not listed') expect(m.view.getByRole('button', { name: 'All 6 files' })).toBeTruthy() expect(m.view.container.querySelector(`.${css.totals}`)?.textContent).toBe('+4−3') @@ -453,10 +469,11 @@ describe('ChangesTab local reads', () => { expect(m.faces.localDiff.mock.calls.map(([scope]) => scope.kind)).toEqual(['branch', 'staged', 'unstaged', 'uncommitted']) }) - it('names no base while the panel has no fork point', async () => { - const m = mount({ state: ready() }) + it('names a detached HEAD by its commit, and the automatic choice while the panel has no fork point', async () => { + const m = mount({ state: ready({}, { branch: null, commit: 'abc1234' }) }) await settle() - expect(m.view.container.querySelector(`.${css.headerNote}`)?.textContent).toBe('') + expect(m.view.container.querySelector('[data-forge-head]')?.textContent).toBe('abc1234') + expect(m.view.getByRole('button', { name: 'Base branch: Default' })).toBeTruthy() }) it.each([ @@ -644,6 +661,106 @@ describe('ChangesTab local reads', () => { }) }) +describe('ChangesTab base branch', () => { + const CLEAN: ForgeLocalDiff = { ...LOCAL, omitted: 0 } + + it('compares the branch scope with a chosen branch, and again with the automatic fork point', async () => { + const m = mount() + await settle() + fireEvent.click(m.view.getByRole('button', { name: 'Base branch: origin/main' })) + await settle() + expect(m.faces.diffBases).toHaveBeenCalledWith('', expect.any(AbortSignal)) + fireEvent.click(m.view.getByRole('menuitem', { name: 'topic' })) + expect(m.store.getSnapshot().byTab[TAB]?.base).toEqual(TOPIC) + expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', base: TOPIC.ref }, expect.any(AbortSignal)) + expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() + await settle() + expect(m.paths()).toHaveLength(6) + + fireEvent.click(m.view.getByRole('button', { name: 'Base branch: topic' })) + await settle() + fireEvent.click(m.view.getByRole('menuitem', { name: /^origin\/main/ })) + expect(m.store.getSnapshot().byTab[TAB]?.base).toBeNull() + expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', base: null }, expect.any(AbortSignal)) + }) + + it('records review comments under the compared ref and names the base the Host reports', async () => { + const renderDiff = DiffFileModule.DiffFile + let source: ReviewActions['source'] | undefined + vi.spyOn(DiffFileModule, 'DiffFile').mockImplementation((props) => { + source = props.review?.source + return renderDiff(props) + }) + const m = mount({ + setup: (faces) => { + faces.localDiff.mockImplementation(async scope => ok({ ...CLEAN, base: scope.kind !== 'branch' ? null : scope.base === null ? BASE : 'topic' })) + }, + }) + await settle() + expect(source).toEqual({ kind: 'local', scope: 'branch', base: BASE, baseRef: null }) + + act(() => { m.store.actions.based(TAB, TOPIC) }) + await settle() + expect(source).toEqual({ kind: 'local', scope: 'branch', base: 'topic', baseRef: TOPIC.ref }) + + act(() => { m.store.actions.scoped(TAB, 'staged') }) + await settle() + expect(source).toEqual({ kind: 'local', scope: 'staged', base: null, baseRef: null }) + }) + + it('keeps the chosen branch while another scope shows, and reads that scope without it', async () => { + const m = mount() + await settle() + act(() => { m.store.actions.based(TAB, TOPIC) }) + act(() => { m.store.actions.scoped(TAB, 'staged') }) + await settle() + expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'staged' }, expect.any(AbortSignal)) + expect(m.view.queryByRole('button', { name: 'Base branch: topic' })).toBeNull() + act(() => { m.store.actions.scoped(TAB, 'branch') }) + expect(m.view.getByRole('button', { name: 'Base branch: topic' })).toBeTruthy() + }) + + it.each([ + ['is gone', REFUSED.baseMissing, 'The base branch topic was not found; it may have been deleted', true], + ['shares no history with HEAD', REFUSED.noForkPoint, 'topic shares no history with HEAD', false], + ])('offers the automatic fork point instead of a retry when the chosen branch %s', async (_label, refused, message, missing) => { + const m = mount({ + setup: (faces) => { faces.localDiff.mockImplementation(async scope => scope.kind === 'branch' && scope.base !== null ? refused : ok(CLEAN)) }, + }) + await settle() + act(() => { m.store.actions.based(TAB, TOPIC) }) + await settle() + expect(m.view.getByRole('status').textContent).toBe(`${message}${en['diff.useAutomaticBase']}`) + expect(m.view.queryByRole('button', { name: en.retry })).toBeNull() + expect(m.view.getByRole('button', { name: 'Base branch: topic' }).classList.contains(baseCss.missing ?? '')).toBe(missing) + + fireEvent.click(m.view.getByRole('button', { name: en['diff.useAutomaticBase'] })) + expect(m.store.getSnapshot().byTab[TAB]?.base).toBeNull() + await settle() + expect(m.paths()).toHaveLength(6) + }) + + it('names a later failure of the chosen branch beside its changes, and keeps a retry for other failures', async () => { + const m = mount({ setup: (faces) => { faces.localDiff.mockResolvedValue(ok(CLEAN)) } }) + await settle() + act(() => { m.store.actions.based(TAB, TOPIC) }) + await settle() + m.faces.localDiff.mockResolvedValueOnce(REFUSED.failed) + fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) + await settle() + expect(m.view.getByRole('status').textContent).toBe(`${en['diff.error']}${en.retry}`) + + m.faces.localDiff.mockResolvedValueOnce(REFUSED.baseMissing) + fireEvent.click(m.view.getByRole('button', { name: en.retry })) + await settle() + expect(m.paths()).toHaveLength(6) + const notice = m.view.getByRole('status') + expect(notice.textContent).toBe(`The base branch topic was not found; it may have been deleted${en['diff.useAutomaticBase']}`) + fireEvent.click(within(notice).getByRole('button', { name: en['diff.useAutomaticBase'] })) + expect(m.store.getSnapshot().byTab[TAB]?.base).toBeNull() + }) +}) + describe('ChangesTab layout', () => { it('draws lines side by side, then in one column, and wraps them by choice', async () => { const m = mount() @@ -779,7 +896,7 @@ describe('ChangesTab unchanged lines', () => { expect(gaps()).toEqual(['2 unchanged lines', '4 unchanged lines', en['diff.unchangedRest']]) fireEvent.click(within(app).getByRole('button', { name: '2 unchanged lines' })) - expect(m.faces.localText).toHaveBeenCalledWith({ kind: 'branch' }, 'src/app.ts') + expect(m.faces.localText).toHaveBeenCalledWith({ kind: 'branch', base: null }, 'src/app.ts') expect([...app.querySelectorAll('[data-forge-diff-gap]')].every(gap => gap.hasAttribute('disabled'))).toBe(true) await settle() expect(gaps()).toEqual(['4 unchanged lines', '2 unchanged lines']) @@ -1129,7 +1246,7 @@ describe('line review actions', () => { const m = mount({ source: { kind: 'change', url: URL7 } }) await settle() expect(publish).toBeDefined() - expect(await publish!({ source: { kind: 'local', scope: 'branch' }, comment: { + expect(await publish!({ source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null }, comment: { path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4, hunk: '', body: 'Local reference', } })).toBe(en['review.stale']) expect(m.faces.submitReview).not.toHaveBeenCalled() @@ -1145,7 +1262,7 @@ describe('line review actions', () => { fireEvent.change(section.getByRole('textbox'), { target: { value: 'Explain these lines' } }) expect(section.getByRole('textbox')).toHaveProperty('value', 'Explain these lines') fireEvent.click(within(m.section('src/app.ts').querySelector('[data-forge-comment]')!).getByRole('button', { name: 'Add to input' })) - expect(m.faces.addReviewToInput.mock.lastCall?.[0]).toMatchObject({ source: { kind: 'local', scope: 'branch' }, + expect(m.faces.addReviewToInput.mock.lastCall?.[0]).toMatchObject({ source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null }, comment: { path: 'src/app.ts', side: 'R', startLine: 4, endLine: 5, body: 'Explain these lines' } }) fireEvent.click(section.getByRole('button', { name: 'Select line L4' })) fireEvent.click(section.getByRole('button', { name: 'Add comment' })) diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index e379ac3126..192773fc2d 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -7,7 +7,8 @@ import { appendPluginRecord, SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' import WorktreeService from '@deepseek-ai/dsh-experimental-worktree' import ForgePanelController from '../src/index.ts' -import type { Config, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState } from '../src/index.ts' +import type { Config, ForgeLocalDiff, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState } from '../src/index.ts' +import { GitOutputTooLarge } from '../src/git.ts' import { WORKTREE_RECORD } from '../src/worktree.ts' import { missingWorktree } from '../src/panel.ts' import { @@ -500,13 +501,57 @@ describe('forgePanel local changes', () => { await writeFile(join(repo, 'notes.md'), 'hello\n') const opened = await open(repo) - const diff = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch' }, signal) + const diff = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal) expect(diff.base).toBe('origin/main') expect(diff.files.map(file => [file.path, file.status, file.untracked])).toEqual([['tracked.txt', 'modified', false], ['notes.md', 'added', true]]) await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'staged' }, signal)).resolves.toEqual({ base: null, files: [], omitted: 0 }) await expect(opened.ctx.forgePanel.localText(opened.session, { kind: 'unstaged' }, 'tracked.txt', signal)).resolves.toBe('initial\nmore\n') }) + it('compares the branch scope with a chosen base branch and lists the branches it can choose', async () => { + const { repo } = await project() + await withDefaultBranch(repo) + await writeFile(join(repo, 'feature.txt'), 'feature\n') + await git(repo, 'add', 'feature.txt') + await git(repo, 'commit', '--quiet', '-m', 'feature') + await git(repo, 'branch', 'topic') + await writeFile(join(repo, 'notes.md'), 'hello\n') + const opened = await open(repo) + const paths = (diff: ForgeLocalDiff): string[] => diff.files.map(file => file.path) + + const automatic = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal) + expect([automatic.base, paths(automatic)]).toEqual(['origin/main', ['feature.txt', 'notes.md']]) + const chosen = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/topic' }, signal) + expect([chosen.base, paths(chosen)]).toEqual(['topic', ['notes.md']]) + await expect(opened.ctx.forgePanel.diffBases(opened.session, '', signal)).resolves.toEqual({ + automatic: { name: 'origin/main', worktree: false }, + remote: [{ ref: 'refs/remotes/origin/main', name: 'origin/main' }], + local: [{ ref: 'refs/heads/topic', name: 'topic' }], + }) + await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/gone' }, signal)) + .rejects.toMatchObject({ code: 'forgePanel/base-missing' }) + + const outside = await open(await plain()) + await expect(outside.ctx.forgePanel.diffBases(outside.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) + }) + + it('lists more refs than other Git output may print, up to maxDiffBytes', async () => { + const { repo } = await project() + await withDefaultBranch(repo) + for (let index = 0; index < 40; index += 1) await git(repo, 'update-ref', `refs/remotes/origin/a-long-branch-name-${index}`, 'HEAD') + const listing = await git(repo, 'for-each-ref', 'refs/remotes/') + expect(listing.length).toBeGreaterThan(1024) + + const limited = await open(repo, { maxOutputBytes: 1024, maxBranches: 3 }) + await expect(limited.ctx.forgePanel.diffBases(limited.session, '', signal)).resolves.toMatchObject({ remote: { length: 3 } }) + await expect(limited.ctx.forgePanel.diffBases(limited.session, 'name-39', signal)).resolves.toMatchObject({ + remote: [{ name: 'origin/a-long-branch-name-39' }], + }) + + const refused = await open(repo, { maxOutputBytes: 1024, maxDiffBytes: 1024 }) + await expect(refused.ctx.forgePanel.diffBases(refused.session, '', signal)).rejects.toBeInstanceOf(GitOutputTooLarge) + }) + it('reports a directory outside a checkout, a branch without a fork point, and a diff over the limit', async () => { const outside = await open(await plain()) await expect(outside.ctx.forgePanel.localDiff(outside.session, { kind: 'unstaged' }, signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) @@ -516,7 +561,7 @@ describe('forgePanel local changes', () => { const { repo } = await project() await writeFile(join(repo, 'tracked.txt'), 'x\n'.repeat(2000)) const opened = await open(repo, { maxDiffBytes: 1024 }) - await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch' }, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) + await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'unstaged' }, signal)).rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) await expect(opened.ctx.forgePanel.localText(opened.session, { kind: 'unstaged' }, 'tracked.txt', signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) diff --git a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx index d0e34fb884..4f4f0e1efd 100644 --- a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx @@ -12,7 +12,7 @@ import type { ForgeDiffFile } from '../src/types.ts' const file: ForgeDiffFile = { path: 'a.txt', previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, additions: 3, deletions: 2, hunks: [{ oldStart: 2, oldLines: 3, newStart: 2, newLines: 4, lines: [' same', '-old first', '-old last', '+new first', '+new last', '+'] }] } -const source = { kind: 'local' as const, scope: 'branch' } +const source = { kind: 'local' as const, scope: 'branch', base: 'origin/main', baseRef: null } const t = makeTranslate(en) afterEach(() => { cleanup(); document.getSelection()?.removeAllRanges(); localStorage.clear(); vi.restoreAllMocks() }) diff --git a/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts index fb5f9ab250..0a2d95cdfc 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts @@ -26,7 +26,7 @@ async function setup(mode: SandboxMode = 'danger-full-access', real = false) { const session = plainSession(repo) setSandboxMode(session, mode) const signal = new AbortController().signal - const fork = { commit: await git(repo, 'rev-parse', 'HEAD'), label: 'main' } + const fork = { commit: await git(repo, 'rev-parse', 'HEAD'), label: 'main', worktree: false } await git(repo, 'remote', 'add', 'origin', 'https://example.invalid/repo') await git(repo, 'update-ref', 'refs/remotes/origin/main', fork.commit) await git(repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') diff --git a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts index fb22b07813..53e1a4a925 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts @@ -6,7 +6,9 @@ import type { Context } from '@deepseek-ai/cordis' import { FsError } from '@deepseek-ai/dsh-fs' import { gitIn, inspectCheckout } from '../src/git.ts' import type { Inspection } from '../src/git.ts' -import { aheadOf, DiffTooLarge, forkPoint, localChanges, localDiff, localText, NoForkPoint } from '../src/local-diff.ts' +import { + aheadOf, BaseMissing, baseBranches, chosenForkPoint, DiffTooLarge, forkPoint, localChanges, localDiff, localText, NoForkPoint, +} from '../src/local-diff.ts' import type { DiffConfig } from '../src/local-diff.ts' import type { ForgeLocalScope, ForgeSessionWorktree } from '../src/types.ts' import { git, gitContext, plainSession, repository, sandboxRecord, scratch } from './harness.ts' @@ -82,7 +84,7 @@ describe('forkPoint', () => { const ctx = await context(repo) const git = gitIn(ctx, CONFIG, plainSession(repo), repo, signal) - await expect(forkPoint(git, await inspected(ctx, repo), null)).resolves.toEqual({ commit: fork, label: 'origin/main' }) + await expect(forkPoint(git, await inspected(ctx, repo), null)).resolves.toEqual({ commit: fork, label: 'origin/main', worktree: false }) }) it('skips a remote without a default branch for the next one', async () => { @@ -95,7 +97,7 @@ describe('forkPoint', () => { const inspection = await inspected(ctx, repo) expect(inspection.upstream).toBe('mirror/feat') - await expect(forkPoint(gitIn(ctx, CONFIG, plainSession(repo), repo, signal), inspection, null)).resolves.toEqual({ commit: fork, label: 'origin/main' }) + await expect(forkPoint(gitIn(ctx, CONFIG, plainSession(repo), repo, signal), inspection, null)).resolves.toEqual({ commit: fork, label: 'origin/main', worktree: false }) }) it.each([ @@ -107,7 +109,7 @@ describe('forkPoint', () => { const created: ForgeSessionWorktree = { path: repo, branch: 'feat', from, baseCommit: `cccccc0${'1'.repeat(33)}`, repositoryRoot: repo } await expect(forkPoint(gitIn(ctx, CONFIG, plainSession(repo), repo, signal), await inspected(ctx, repo), created)) - .resolves.toEqual({ commit: created.baseCommit, label }) + .resolves.toEqual({ commit: created.baseCommit, label, worktree: true }) }) it('has no fork point without a remote default branch or a shared history', async () => { @@ -128,16 +130,87 @@ describe('forkPoint', () => { }) }) +describe('chosenForkPoint', () => { + it('forks the branch scope at the merge base of HEAD with a chosen remote-tracking or local branch', async () => { + const { repo, fork } = await forked(await directory()) + await git(repo, 'branch', 'topic') + const head = await git(repo, 'rev-parse', 'HEAD') + const confined = gitIn(await context(repo), CONFIG, plainSession(repo), repo, signal) + + await expect(chosenForkPoint(confined, 'refs/remotes/origin/main')).resolves.toEqual({ commit: fork, label: 'origin/main', worktree: false }) + await expect(chosenForkPoint(confined, 'refs/heads/topic')).resolves.toEqual({ commit: head, label: 'topic', worktree: false }) + }) + + it.each(['refs/heads/gone', 'refs/heads/feat@{1}', 'refs/remotes/origin/a..b'])('reports the missing base branch %s', async (ref) => { + const { repo } = await forked(await directory()) + const confined = gitIn(await context(repo), CONFIG, plainSession(repo), repo, signal) + + await expect(chosenForkPoint(confined, ref)).rejects.toBeInstanceOf(BaseMissing) + }) + + it('has no fork point with a branch that shares no history with HEAD', async () => { + const { repo } = await forked(await directory()) + await git(repo, 'stash', '--quiet', '--include-untracked') + await git(repo, 'checkout', '--quiet', '--orphan', 'solo') + await git(repo, 'commit', '--quiet', '-m', 'solo') + const confined = gitIn(await context(repo), CONFIG, plainSession(repo), repo, signal) + + await expect(chosenForkPoint(confined, 'refs/heads/feat')).resolves.toBeNull() + }) + + it.each(['HEAD', 'main', 'refs/tags/v1', 'refs/heads/', '--output=x'])('refuses %j, which names no branch', async (ref) => { + const { repo } = await forked(await directory()) + const confined = gitIn(await context(repo), CONFIG, plainSession(repo), repo, signal) + + await expect(chosenForkPoint(confined, ref)).rejects.toThrow('is not a branch ref') + }) +}) + +describe('baseBranches', () => { + it('lists the automatic fork point, remote-tracking branches without symbolic refs, and local branches but the checked-out one', async () => { + const { repo } = await forked(await directory()) + await git(repo, 'branch', 'Release-2') + await git(repo, 'update-ref', 'refs/remotes/origin/release/2.4', 'HEAD') + await git(repo, 'tag', 'v1') + const ctx = await context(repo) + const confined = gitIn(ctx, CONFIG, plainSession(repo), repo, signal) + const listed = await baseBranches(confined, await inspected(ctx, repo), null, '', 50) + const names = (branches: readonly { readonly name: string }[]): string[] => branches.map(branch => branch.name).sort() + + expect(listed.automatic).toEqual({ name: 'origin/main', worktree: false }) + expect(names(listed.remote)).toEqual(['origin/main', 'origin/release/2.4']) + expect(listed.remote).toContainEqual({ ref: 'refs/remotes/origin/release/2.4', name: 'origin/release/2.4' }) + expect(names(listed.local)).toEqual(['Release-2', 'main']) + + const searched = await baseBranches(confined, await inspected(ctx, repo), null, ' release ', 1) + expect(searched.automatic).toEqual({ name: 'origin/main', worktree: false }) + expect([searched.remote, searched.local].map(names)).toEqual([['origin/release/2.4'], ['Release-2']]) + }) + + it('names the start of the worktree the Session created, or no automatic fork point without one', async () => { + const { repo } = await forked(await directory()) + const ctx = await context(repo) + const created: ForgeSessionWorktree = { path: repo, branch: 'feat', from: 'main', baseCommit: 'a'.repeat(40), repositoryRoot: repo } + const confined = gitIn(ctx, CONFIG, plainSession(repo), repo, signal) + await expect(baseBranches(confined, await inspected(ctx, repo), created, '', 50)).resolves.toMatchObject({ automatic: { name: 'main', worktree: true } }) + + const plain = await repository(await directory(), 'plain') + const bare = await context(plain) + await expect(baseBranches(gitIn(bare, CONFIG, plainSession(plain), plain, signal), await inspected(bare, plain), null, '', 50)) + .resolves.toEqual({ automatic: null, remote: [], local: [] }) + }) +}) + describe('localDiff', () => { it.each([ - [{ kind: 'branch' }, 'origin/main', ['committed.txt added', 'staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], + [{ kind: 'branch', base: null }, 'origin/main', ['committed.txt added', 'staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'uncommitted' }, null, ['staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'unstaged' }, null, ['tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'staged' }, null, ['staged.txt added']], ] as const)('reads the %o scope with untracked files last, leaving out ignored files and nested repositories', async (scope, base, files) => { const { repo, fork } = await forked(await directory()) const ctx = await context(repo) - const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main' }, scope, signal) + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, scope, signal) expect(diff.base).toBe(base) expect(diff.omitted).toBe(0) @@ -146,7 +219,7 @@ describe('localDiff', () => { it('carries the hunks of tracked and untracked files', async () => { const { repo, fork } = await forked(await directory()) - const diff = await localDiff(await context(repo), CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main' }, { kind: 'unstaged' }, signal) + const diff = await localDiff(await context(repo), CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, { kind: 'unstaged' }, signal) expect(diff.files.map(file => [file.additions, file.deletions, file.hunks.flatMap(hunk => hunk.lines)])).toEqual([ [1, 0, [' initial', '+changed']], @@ -157,7 +230,7 @@ describe('localDiff', () => { it('refuses the branch scope without a fork point', async () => { const { repo } = await forked(await directory()) - await expect(localDiff(await context(repo), CONFIG, plainSession(repo), repo, null, { kind: 'branch' }, signal)).rejects.toBeInstanceOf(NoForkPoint) + await expect(localDiff(await context(repo), CONFIG, plainSession(repo), repo, null, { kind: 'branch', base: null }, signal)).rejects.toBeInstanceOf(NoForkPoint) }) it('compares a branch without commits with the empty tree', async () => { @@ -178,7 +251,7 @@ describe('localDiff', () => { const { repo, fork } = await forked(await directory()) await writeFile(join(repo, 'tracked.txt'), 'line\n'.repeat(400)) - await expect(localDiff(await context(repo), { ...CONFIG, maxDiffBytes: 512 }, plainSession(repo), repo, { commit: fork, label: 'x' }, { kind: 'unstaged' }, signal)) + await expect(localDiff(await context(repo), { ...CONFIG, maxDiffBytes: 512 }, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal)) .rejects.toBeInstanceOf(DiffTooLarge) }) @@ -196,7 +269,7 @@ describe('localDiff', () => { return await read(target, readSignal, maxBytes) }) const config = { ...CONFIG, maxDiffBytes: 2048, maxUntrackedFiles: 4 } - const diff = await localDiff(ctx, config, plainSession(repo), repo, { commit: fork, label: 'x' }, { kind: 'unstaged' }, signal) + const diff = await localDiff(ctx, config, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal) expect(diff.files.filter(file => file.untracked).map(file => [file.path, file.binary, file.oversized, file.additions])).toEqual([ ['more/big.txt', false, true, 0], @@ -211,13 +284,13 @@ describe('localDiff', () => { const ctx = await context(repo) vi.spyOn(ctx.fs, 'readBytes').mockRejectedValue(new Error('disk on fire')) - await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'x' }, { kind: 'unstaged' }, signal)) + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal)) .rejects.toThrow('disk on fire') }) }) describe('localText', () => { - const branch: ForgeLocalScope = { kind: 'branch' } + const branch: ForgeLocalScope = { kind: 'branch', base: null } it('reads the working tree, or the index for the staged scope', async () => { const { repo } = await forked(await directory()) 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 fd410f486a..0b634972ee 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -30,7 +30,7 @@ import type { ReviewSelection } from '../src/client/review.ts' import { WorktreeProgress, type WorktreeProgressInjected } from '../src/client/WorktreeProgress.tsx' import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx' import type { - ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, + ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, } from '../src/types.ts' import { entry, listState, ready, snapshot, unserved } from './client-fixtures.client.ts' @@ -159,6 +159,8 @@ async function base() { localDiff: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _signal?: AbortSignal): Read => ({ ok: true, value: LOCAL })), localText: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _path: string): Read => ({ ok: true, value: 'a\n' })), + diffBases: vi.fn(async (_sessionId: SessionId, _query: string, _signal?: AbortSignal): Read => + ({ ok: true, value: { automatic: null, remote: [], local: [] } })), changeRequestChecks: vi.fn(async ( _sessionId: SessionId, _url: string, _headSha: string, _signal: AbortSignal, ): Read => ({ ok: true, value: snapshot(7) })), @@ -711,7 +713,7 @@ describe('mountForgePanel changes view', () => { it('inserts numbered frozen quotes in the originating Session without sending a message', async () => { const f = await fixture() try { - const selection: ReviewSelection = { source: { kind: 'local', scope: 'branch' }, comment: { path: 'a.ts', side: 'R', startLine: 1, endLine: 1, body: 'Check this', hunk: '@@ -1 +1 @@\n-old\n+new' } } + const selection: ReviewSelection = { source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null }, comment: { path: 'a.ts', side: 'R', startLine: 1, endLine: 1, body: 'Check this', hunk: '@@ -1 +1 @@\n-old\n+new' } } const scope = f.sessions.scope(S1)! let draft = '' const focus = vi.fn(), send = vi.fn() @@ -740,7 +742,7 @@ describe('mountForgePanel changes view', () => { try { const view = f.changes(S1) if (missing === 'no scope') f.sessions.scope.mockReturnValue(undefined) - expect(view.addReviewToInput({ source: { kind: 'local', scope: 'branch' }, comment: { path: 'a', side: 'L', startLine: 1, endLine: 1, body: 'Comment', hunk: '' } })).toBe(false) + expect(view.addReviewToInput({ source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null }, comment: { path: 'a', side: 'L', startLine: 1, endLine: 1, body: 'Comment', hunk: '' } })).toBe(false) } finally { await f.dispose() } }) it('immediately closes an already-aborted occurrence and reports failed removal', async () => { @@ -757,7 +759,7 @@ describe('mountForgePanel changes view', () => { const f = await fixture() const lifetime = new AbortController() const tab = { id: 'review-tab' as TabId, signal: lifetime.signal } - const selection: ReviewSelection = { source: kind === 'local' ? { kind, scope: 'branch' } + const selection: ReviewSelection = { source: kind === 'local' ? { kind, scope: 'branch', base: 'origin/main', baseRef: null } : { kind, url: 'https://github.com/octo/demo/pull/7', headSha: 'a'.repeat(40) }, comment: { path: 'a.ts', side: 'R', startLine: 1, endLine: 1, body: 'Check this', hunk: '@@ -1 +1 @@\n-old\n+new' } } const queue = f.changes(S1).reviewQueue(tab) @@ -787,6 +789,8 @@ describe('mountForgePanel changes view', () => { const signal = new AbortController().signal expect(await view.localDiff({ kind: 'staged' }, signal)).toEqual({ ok: true, value: LOCAL }) expect(await view.localText({ kind: 'staged' }, 'src/a.ts')).toEqual({ ok: true, value: 'a\n' }) + expect(await view.diffBases('rel', signal)).toEqual({ ok: true, value: { automatic: null, remote: [], local: [] } }) + expect(f.forgePanel.diffBases).toHaveBeenCalledWith(S1, 'rel', signal) expect(await view.changeRequestDiff('https://github.com/octo/demo/pull/7', signal)).toEqual({ ok: true, value: CHANGE }) expect(await view.changeRequestText('https://github.com/octo/demo/pull/7', 'a'.repeat(40), 'src/a.ts')).toEqual({ ok: true, value: 'b\n' }) expect(f.forgePanel.localDiff).toHaveBeenCalledWith(S1, { kind: 'staged' }, signal) diff --git a/packages/experimental/client-ui-forge/tests/parse.host.spec.ts b/packages/experimental/client-ui-forge/tests/parse.host.spec.ts index a61dfa1a96..b2c49bd448 100644 --- a/packages/experimental/client-ui-forge/tests/parse.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/parse.host.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { baseBranches, parseName, parseRemotes, parseTopLevel, remoteOrder, upstreamBranch } from '../src/parse.ts' +import { baseBranches, parseBaseBranches, parseName, parseRemotes, parseTopLevel, remoteOrder, upstreamBranch } from '../src/parse.ts' import type { GitRemote } from '../src/parse.ts' describe('parseTopLevel', () => { @@ -48,6 +48,41 @@ describe('baseBranches', () => { }) }) +describe('parseBaseBranches', () => { + const output = [ + 'refs/remotes/origin/HEAD\0refs/remotes/origin/main', + 'refs/remotes/origin/main\0', + 'refs/heads/feat\0', + 'refs/heads/Release/2.4\0', + 'refs/remotes/upstream/release/2.3\0', + 'refs/heads/main\0', + 'refs/tags/v1\0', + '', + ].join('\r\n') + + it('keeps the listed order, leaving out symbolic refs, the checked-out branch, and other ref kinds', () => { + expect(parseBaseBranches(output, 'feat', '', 10)).toEqual({ + remote: [ + { ref: 'refs/remotes/origin/main', name: 'origin/main' }, + { ref: 'refs/remotes/upstream/release/2.3', name: 'upstream/release/2.3' }, + ], + local: [ + { ref: 'refs/heads/Release/2.4', name: 'Release/2.4' }, + { ref: 'refs/heads/main', name: 'main' }, + ], + }) + }) + + it('keeps names containing the trimmed query in any case, at most limit in each group', () => { + expect(parseBaseBranches(output, null, ' RELEASE ', 1)).toEqual({ + remote: [{ ref: 'refs/remotes/upstream/release/2.3', name: 'upstream/release/2.3' }], + local: [{ ref: 'refs/heads/Release/2.4', name: 'Release/2.4' }], + }) + expect(parseBaseBranches(output, null, '', 1).local).toEqual([{ ref: 'refs/heads/feat', name: 'feat' }]) + expect(parseBaseBranches('refs/heads/\0\n', null, '', 10)).toEqual({ remote: [], local: [] }) + }) +}) + describe('parseRemotes', () => { it('groups fetch and push URLs per remote in listed order', () => { const output = [ diff --git a/packages/experimental/client-ui-forge/tests/review.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review.client.spec.tsx index cf22f225c3..feac2e9793 100644 --- a/packages/experimental/client-ui-forge/tests/review.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review.client.spec.tsx @@ -29,7 +29,7 @@ describe('review references', () => { const deleted = { ...file, hunks: [{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 0, lines: ['-old'] }] } expect(selectReviewLines(added, 'R', 1, 1)?.hunk).toContain('@@ -0,0 +1,1 @@') expect(selectReviewLines(deleted, 'L', 1, 1)?.hunk).toContain('@@ -1,1 +0,0 @@') - expect(reviewMatches(selection, { kind: 'local', scope: 'branch' }, file)).toBe(false) + expect(reviewMatches(selection, { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null }, file)).toBe(false) expect(reviewMatches(selection, { kind: 'change', url: 'x', headSha: 'b' }, file)).toBe(false) expect(reviewMatches(selection, selection.source, added)).toBe(false) expect(reviewMatches(selection, selection.source, file)).toBe(true) @@ -104,8 +104,10 @@ describe('review references', () => { expect(selectReviewLines(file, 'L', 4, 4)).toBeUndefined() expect(selectReviewLines(file, 'R', 4, 11)).toBeUndefined() expect(formatReviewComment(selection, 1)).toBe(`## User Comment 1\nFile: a.ts\nSide: R\nLines: 3-4\nSource: https://github.com/octo/demo/pull/7\nCommit: ${'a'.repeat(40)}\nDiff hunk:\n\`\`\`diff\n@@ -2,2 +2,3 @@\n unchanged\n-old\n+new\n+another\n\`\`\`\nComment:\n为什么新增这两行?`) - expect(formatReviewComment({ source: { kind: 'local', scope: 'staged' }, comment: { ...selection.comment, startLine: 4, hunk: '```' } }, 2)) + expect(formatReviewComment({ source: { kind: 'local', scope: 'staged', base: null, baseRef: null }, comment: { ...selection.comment, startLine: 4, hunk: '```' } }, 2)) .toContain('Lines: 4\nSource: Local (staged)\nDiff hunk:\n````diff\n```\n````') + expect(formatReviewComment({ source: { kind: 'local', scope: 'branch', base: 'origin/release/2.4', baseRef: 'refs/remotes/origin/release/2.4' }, comment: selection.comment }, 3)) + .toContain('Lines: 3-4\nSource: Local (branch)\nBase: origin/release/2.4\nDiff hunk:\n') }) it('adds a quote without posting or closing when the input refuses it', () => { const addToInput = vi.fn<(selection: ReviewSelection) => boolean>().mockReturnValue(false) @@ -153,7 +155,7 @@ describe('review references', () => { describe('pending reviews', () => { it('edits only the chosen occurrence and refuses edits after publication or during dispatch', () => { const queue = new ReviewQueue('review-test') - expect(queue.add({ ...selection, source: { kind: 'local', scope: 'branch' } })).toBe(false) + expect(queue.add({ ...selection, source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null } })).toBe(false) queue.add(selection) queue.add({ ...selection, comment: { ...selection.comment, body: 'Second' } }) const first = queue.fileComments('a.ts', selection.source).threads[0]! @@ -223,10 +225,14 @@ describe('pending reviews', () => { queue.finish(true, 'https://github.com/octo/demo/pull/7#review-1') expect(queue.fileComments('a.ts', selection.source).threads[0]).toMatchObject({ key, kind: 'published' }) expect(new ReviewQueue('review-test').fileComments('a.ts', selection.source).threads[0]).toMatchObject({ kind: 'published' }) - const local = { ...selection, source: { kind: 'local' as const, scope: 'staged' } } + const local = { ...selection, source: { kind: 'local' as const, scope: 'staged', base: null, baseRef: null } } expect(queue.recordAgent(local)).toBe(true) expect(queue.fileComments('a.ts', local.source).threads).toHaveLength(1) - expect(queue.fileComments('a.ts', { kind: 'local', scope: 'branch' }).threads).toHaveLength(0) + expect(queue.fileComments('a.ts', { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null }).threads).toHaveLength(0) + const based = { ...selection, source: { kind: 'local' as const, scope: 'branch', base: 'origin/release', baseRef: 'refs/remotes/origin/release' } } + expect(queue.recordAgent(based)).toBe(true) + expect(queue.fileComments('a.ts', based.source).threads).toHaveLength(1) + expect(queue.fileComments('a.ts', { ...based.source, baseRef: null }).threads).toHaveLength(0) }) it('preserves malformed stored bytes and refuses to overwrite them', () => { localStorage.setItem('review-test', 'broken') @@ -235,6 +241,34 @@ describe('pending reviews', () => { expect(queue.add(selection)).toBe(false) expect(localStorage.getItem('review-test')).toBe('broken') }) + it.each([ + ['staged', null], + ['branch', 'origin/main'], + ])('shows a stored %s record that names no base in the comparison without a chosen branch', (scope, base) => { + const local = { ...selection, source: { kind: 'local' as const, scope, base, baseRef: null } } + expect(new ReviewQueue('review-test').recordAgent(local)).toBe(true) + const stored = JSON.parse(localStorage.getItem('review-test') ?? '') as { records: { selection: { source: Record } }[] } + for (const record of stored.records) { + Reflect.deleteProperty(record.selection.source, 'base') + Reflect.deleteProperty(record.selection.source, 'baseRef') + } + localStorage.setItem('review-test', JSON.stringify(stored)) + + const reopened = new ReviewQueue('review-test') + expect(reopened.fileComments('a.ts', local.source).threads).toHaveLength(1) + expect(reopened.fileComments('a.ts', { ...local.source, base: 'topic', baseRef: 'refs/heads/topic' }).threads).toHaveLength(0) + }) + it.each([ + ['the automatic start of a worktree and a local branch', { base: 'main', baseRef: null }, { base: 'main', baseRef: 'refs/heads/main' }], + ['a local and a remote-tracking branch', { base: 'origin/x', baseRef: 'refs/heads/origin/x' }, { base: 'origin/x', baseRef: 'refs/remotes/origin/x' }], + ])('keeps comparisons with one name apart: %s', (_label, left, right) => { + const source = { kind: 'local' as const, scope: 'branch' } + const queue = new ReviewQueue('review-test') + expect(queue.recordAgent({ ...selection, source: { ...source, ...left } })).toBe(true) + + expect(queue.fileComments('a.ts', { ...source, ...left }).threads).toHaveLength(1) + expect(queue.fileComments('a.ts', { ...source, ...right }).threads).toHaveLength(0) + }) it('keeps the previous queue on quota failure and allows retry after recovery', () => { const queue = new ReviewQueue('review-test') const setter = vi.spyOn(Storage.prototype, 'setItem').mockImplementationOnce(() => { throw new DOMException('quota', 'QuotaExceededError') }) @@ -328,7 +362,7 @@ describe('submission availability', () => { vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) queue.summarize('Summary', 'comment') } - if (kind === 'local') vi.spyOn(queue, 'getSnapshot').mockReturnValue({ ...queue.getSnapshot(), comments: [{ ...selection, source: { kind: 'local', scope: 'branch' } }] }) + if (kind === 'local') vi.spyOn(queue, 'getSnapshot').mockReturnValue({ ...queue.getSnapshot(), comments: [{ ...selection, source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null } }] }) const view = render() expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', true) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index a3d6d3c051..13e864ef14 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1316,6 +1316,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the checked-out branch and at most `maxBranches` local branches, the checked-out one first.', throws: ['when the current directory is not inside a checkout or Git fails.'], }, + { + signature: '@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise', + description: 'List the branches the `branch` scope of the Session\'s current checkout can compare with.', + parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'query', description: 'text the branch names must contain, ignoring case; empty for every branch.' }, { name: 'signal', description: 'request cancellation.' }], + returns: 'the automatic fork point and at most `maxBranches` remote-tracking and local branches each, most recently committed first, without the checked-out branch.', + throws: ['`forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.'], + }, { signature: '@Remote async track(session: Session, url: string, signal: AbortSignal): Promise', description: 'Bind a change request to a Session by URL, or restore a dismissed binding.', @@ -1338,7 +1345,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Read the changes one scope covers in the checkout of the Session\'s current directory, with Git using the Session\'s sandbox policy.', parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'scope', description: 'which changes to read.' }, { name: 'signal', description: 'request cancellation.' }], returns: 'the files, the base of the `branch` scope, and the untracked files left out.', - throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/no-fork-point` for the `branch` scope of a checkout without one; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.'], + throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.'], }, { signature: '@Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise', @@ -6402,6 +6409,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeActionFailure', declaration: 'export interface ForgeActionFailure {\n readonly code: \'unauthenticated\' | \'stale\' | \'failed\';\n readonly message: string;\n}', }, + { + name: 'ForgeAutomaticBase', + declaration: 'export interface ForgeAutomaticBase {\n readonly name: string;\n readonly worktree: boolean;\n}', + }, + { + name: 'ForgeBaseBranch', + declaration: 'export interface ForgeBaseBranch {\n readonly ref: string;\n readonly name: string;\n}', + }, + { + name: 'ForgeBaseBranches', + declaration: 'export interface ForgeBaseBranches {\n readonly automatic: ForgeAutomaticBase | null;\n readonly remote: readonly ForgeBaseBranch[];\n readonly local: readonly ForgeBaseBranch[];\n}', + }, { name: 'ForgeBranches', declaration: 'export interface ForgeBranches {\n readonly current: string | null;\n readonly branches: readonly string[];\n}', @@ -6460,7 +6479,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeLocalScope', - declaration: 'export type ForgeLocalScope = {\n readonly kind: \'branch\';\n} | {\n readonly kind: \'uncommitted\';\n} | {\n readonly kind: \'unstaged\';\n} | {\n readonly kind: \'staged\';\n};', + declaration: 'export type ForgeLocalScope = {\n readonly kind: \'branch\';\n readonly base: string | null;\n} | {\n readonly kind: \'uncommitted\';\n} | {\n readonly kind: \'unstaged\';\n} | {\n readonly kind: \'staged\';\n};', }, { name: 'ForgeMissingWorktree', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 4237a960a4..749892606b 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -406,6 +406,7 @@ export const LINK_MAP: Readonly> = { ForgeLineComment: 'forge.md', ForgeReviewRequest: 'forge.md', ForgeReviewResult: 'forge.md', + ForgeBaseBranches: 'forge.md', ForgeBranches: 'forge.md', ForgeChangeRequestDiff: 'forge.md', ForgeChangeRequestStatesFrame: 'forge.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 4896bf681f..ea7ae24936 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2697,6 +2697,21 @@ "symbol": "ForgeBranches", "source": "packages/experimental/client-ui-forge/src/types.ts" }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeBaseBranch", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeAutomaticBase", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeBaseBranches", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, { "doc": "docs/subsystems/forge.md", "symbol": "ForgeChangeRequestListState",