From 1a3d59a0ff4d1b68a01514d3a9e6c5fe2e13e5eb Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 6 Nov 2026 16:06:14 +0800 Subject: [PATCH 01/29] test(ui-theme): skip dot directories in the package scan The hover-styles contract walks packages/ for package.json files. Typert generator specs create temporary roots inside that tree with mkdtempSync(join(import.meta.dirname, '....')) and remove them in afterEach, so a concurrent scan can readdir one and then hit ENOENT when its owner deletes it. Dot directories hold VCS metadata and those transient roots, never shipped source, so skip them and let the helper walk an explicit root for the regression test. --- .../ui-theme/tests/stylesheet-scan.spec.ts | 23 +++++++++++++++++++ .../client/ui-theme/tests/stylesheet-scan.ts | 12 ++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 packages/client/ui-theme/tests/stylesheet-scan.spec.ts diff --git a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.spec.ts new file mode 100644 index 0000000000..1614ee55a7 --- /dev/null +++ b/packages/client/ui-theme/tests/stylesheet-scan.spec.ts @@ -0,0 +1,23 @@ +/** Tests for the package-tree scan helpers that the stylesheet contracts range over. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { packageFiles } from './stylesheet-scan.ts' + +const roots: string[] = [] + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +it('walks shipped package files and skips dot directories holding transient roots', () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-stylesheet-scan-')) + roots.push(root) + mkdirSync(join(root, 'pkg')) + writeFileSync(join(root, 'pkg', 'package.json'), '{}') + mkdirSync(join(root, '.typert-worker-failure-probe')) + writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}') + + expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root}/pkg/package.json`]) +}) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.ts b/packages/client/ui-theme/tests/stylesheet-scan.ts index 91311945bf..0ddb93e0f8 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.ts @@ -75,20 +75,24 @@ export function varReferences(value: string): string[] { * Every file shipped as package source whose name the predicate accepts, * excluding build output and installed dependencies. * @param accepts - filename predicate. - * @returns absolute paths under packages/, `/`-separated on every platform so + * @param root - tree to walk, the packages directory by default. + * @returns absolute paths under `root`, `/`-separated on every platform so * specs can match repo-relative suffixes verbatim. */ -export function packageFiles(accepts: (name: string) => boolean): string[] { +export function packageFiles(accepts: (name: string) => boolean, root: string = PACKAGES_DIR): string[] { const found: string[] = [] const walk = (dir: string): void => { for (const entry of readdirSync(dir, { withFileTypes: true })) { const path = join(dir, entry.name) if (entry.isDirectory()) { - if (entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) + // Dot directories hold VCS metadata and per-test temporary roots (for + // example `.typert-worker-failure-*`), never shipped package source; a + // concurrent owner can remove one while a scan reads it. + if (!entry.name.startsWith('.') && entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) } else if (accepts(entry.name)) found.push(path.replaceAll('\\', '/')) } } - walk(PACKAGES_DIR) + walk(root) return found } From 646e46e0afeb47bce742a1eae4e473b8d6f51a99 Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 6 Nov 2026 16:24:29 +0800 Subject: [PATCH 02/29] test(ui-theme): scope the package-scan spec to the client face packageFiles() reports '/'-separated paths on every platform, so the fixture's temporary root must be normalized before it forms the expectation; otherwise the Windows coverage lane fails. The spec also belongs to the client aggregate, because an unsuffixed spec file under packages/client is compiled by both aggregates. --- ...stylesheet-scan.spec.ts => stylesheet-scan.client.spec.ts} | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename packages/client/ui-theme/tests/{stylesheet-scan.spec.ts => stylesheet-scan.client.spec.ts} (82%) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts similarity index 82% rename from packages/client/ui-theme/tests/stylesheet-scan.spec.ts rename to packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts index 1614ee55a7..312ee01382 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts @@ -19,5 +19,7 @@ it('walks shipped package files and skips dot directories holding transient root mkdirSync(join(root, '.typert-worker-failure-probe')) writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}') - expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root}/pkg/package.json`]) + // The helper reports `/`-separated paths on every platform, so the Windows + // temporary root's separators must not reach the expectation. + expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root.replaceAll('\\', '/')}/pkg/package.json`]) }) From 256e1ae370e2668dd1998e7021525eb72a1020b3 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 12:30:49 +0800 Subject: [PATCH 03/29] feat(forge): read pull request review threads at the displayed head ForgeProvider gains the optional readReview(ref, headSha, signal), which returns ForgeReviewData only when the read names headSha as the head and a stale failure otherwise. Each thread carries a current position on the head and the original position it was written at; ForgeFailure gains the unsupported code that ctx.forge.readReview returns for a provider without review reads. forge-github reads the threads, the head, and the viewer in one GraphQL query, pages threads up to maxReviewThreads and comments to their end, re-checks the head on every following thread page, and bounds all pages by maxOutputBytes. A thread is placed at the head only when GitHub keeps it current and its first comment is on the head commit. The forge panel adds the changeRequestReview Remote, cached per change request by head and update time and read again after reviewRefreshMs, since resolving a thread does not change a pull request's updatedAt. --- .../src/client/ChangeRequestCard.tsx | 1 + .../experimental/client-ui-forge/src/index.ts | 69 ++++- .../client-ui-forge/src/review-cache.ts | 73 +++++ .../experimental/client-ui-forge/src/types.ts | 16 +- .../tests/review-cache.host.spec.ts | 51 ++++ .../client-ui-forge/tests/review.host.spec.ts | 137 ++++++++++ .../client-ui-forge/tsconfig.host.json | 1 + .../experimental/forge-github/src/provider.ts | 20 +- .../experimental/forge-github/src/threads.ts | 209 ++++++++++++++ .../forge-github/tests/threads.spec.ts | 256 ++++++++++++++++++ packages/experimental/forge/src/index.ts | 36 ++- packages/experimental/forge/src/types.ts | 90 +++++- .../experimental/forge/tests/registry.spec.ts | 16 ++ .../experimental/forge/tests/watch.spec.ts | 25 +- 14 files changed, 980 insertions(+), 20 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/review-cache.ts create mode 100644 packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts create mode 100644 packages/experimental/client-ui-forge/tests/review.host.spec.ts create mode 100644 packages/experimental/forge-github/src/threads.ts create mode 100644 packages/experimental/forge-github/tests/threads.spec.ts diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 5a90b9e6b3..a5f1abbab2 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -76,6 +76,7 @@ const FAILURE: Record = { 'unauthenticated': 'change.failure.unauthenticated', 'too-large': 'change.failure.unavailable', 'stale': 'change.failure.unavailable', + 'unsupported': 'change.failure.unavailable', 'unavailable': 'change.failure.unavailable', } diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 708eb757f4..6a1baaa71d 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -6,8 +6,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-api-remote-access' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeReviewRequest, ForgeReviewResult, - MergeMethod, + ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeReviewData, ForgeReviewRequest, + ForgeReviewResult, MergeMethod, } from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' @@ -30,6 +30,7 @@ import { rangeStart } from './commit-range.ts' import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' import { PatchCache } from './patch-cache.ts' +import { ReviewCache } from './review-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { @@ -85,6 +86,8 @@ export class ForgePanelController extends TypertRemoteService { maxCommits: z.number().default(250), testPaths: z.array(z.string()).default([]), interfacePaths: z.array(z.string()).default([]), + maxCachedReviewBytes: z.number().default(4_194_304), + reviewRefreshMs: z.number().default(60_000), }) private readonly home: Context @@ -94,6 +97,7 @@ export class ForgePanelController extends TypertRemoteService { private creations!: WorktreeCreations private readonly patches: PatchCache private readonly layers: FileLayers + private readonly reviews: ReviewCache private states: ChangeRequestStates | undefined private readonly stopPanels: () => Promise private readonly stopStates: () => Promise @@ -102,13 +106,13 @@ export class ForgePanelController extends TypertRemoteService { super(ctx, 'forgePanel') const resolved = config as Required if (resolved.gitCommand.trim().length === 0) throw new Error('forge-panel: gitCommand must not be empty') - for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs'] as const) { + for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs'] as const) { const value = resolved[key] if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) { throw new Error(`forge-panel: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } } - for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits'] as const) { + for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes'] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`) } if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') @@ -119,6 +123,7 @@ export class ForgePanelController extends TypertRemoteService { this.home = ctx this.config = resolved this.patches = new PatchCache(resolved.maxCachedDiffBytes) + this.reviews = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs) this.stopPanels = ctx.effect(() => async () => { const panels = [...this.panels.values()] this.panels.clear() @@ -458,6 +463,42 @@ export class ForgePanelController extends TypertRemoteService { return text } + /** + * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read + * at the same head commit and update time are reused from memory, for any Session, until they are + * `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age shows threads resolved + * since, which do not change a GitHub pull request's update time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param headSha - head commit of the displayed diff. + * @param signal - request cancellation. + * @returns the threads at `headSha`, with `current` positions numbering the files of that diff. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again; + * `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the + * status was read and when the host does not provide the threads otherwise. + */ + @Remote + async changeRequestReview(session: Session, url: string, headSha: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + const { ref, update } = this.bound(session, url) + if (update === null || !('snapshot' in update)) { + throw new RemoteError('forgePanel/review-failed', 'The change request status has not been read yet', {}) + } + if (update.snapshot.headSha !== headSha) { + throw new RemoteError('forgePanel/stale-head', `The change request head moved from ${headSha} to ${update.snapshot.headSha}`, {}) + } + const key = changeRequestKey(ref) + const version = JSON.stringify([headSha, update.snapshot.updatedAt]) + const readAt = Date.now() + const kept = this.reviews.get(key, version, readAt) + if (kept !== undefined) return kept + const review = await this.home.forge.readReview(ref, headSha, signal) + if ('code' in review) throw reviewError(review) + this.reviews.set(key, version, review, readAt) + return review + } + /** * Publish a line comment or completed review for a visible Session binding. * @param session - Session retaining the change request. @@ -822,12 +863,32 @@ function readError(failure: ForgeFailure): RemoteError { case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {}) case 'not-found': case 'unauthenticated': + case 'unsupported': case 'unavailable': return new RemoteError('forgePanel/diff-failed', failure.message, {}) /* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */ default: return assertNever(failure.code, 'ForgeFailure.code') } } +/** + * Report why the code host did not provide review threads. + * @param failure - the provider's failure. + * @returns `forgePanel/stale-head` for a head that moved, `forgePanel/review-unsupported` for a provider without + * review reads, else `forgePanel/review-failed`, with the provider's message. + */ +function reviewError(failure: ForgeFailure): RemoteError { + switch (failure.code) { + case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {}) + case 'unsupported': return new RemoteError('forgePanel/review-unsupported', failure.message, {}) + case 'not-found': + case 'unauthenticated': + case 'too-large': + case 'unavailable': return new RemoteError('forgePanel/review-failed', failure.message, {}) + /* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */ + default: return assertNever(failure.code, 'ForgeFailure.code') + } +} + /** * Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, a missing base branch, and chosen * commits that are not on the branch as Remote errors. diff --git a/packages/experimental/client-ui-forge/src/review-cache.ts b/packages/experimental/client-ui-forge/src/review-cache.ts new file mode 100644 index 0000000000..6a8d9f0d1e --- /dev/null +++ b/packages/experimental/client-ui-forge/src/review-cache.ts @@ -0,0 +1,73 @@ +/** + * Review threads of change requests kept in memory, so the changes view reads them from the code host again only + * after the change request's head or update time changes or the kept threads reach their age limit. + */ + +import { Buffer } from 'node:buffer' +import type { ChangeRequestKey, ForgeReviewData } from '@deepseek-ai/dsh-experimental-forge' + +interface Entry { + /** Head commit and update time the threads were read at. */ + readonly version: string + readonly review: ForgeReviewData + /** Epoch milliseconds of the read. */ + readonly readAt: number + /** UTF-8 size of the threads as JSON. */ + readonly bytes: number +} + +/** + * One read of review threads per change request, bounded by age and by the total UTF-8 size of the kept reads as + * JSON; the least recently read change request leaves first. + */ +export class ReviewCache { + private readonly entries = new Map() + private bytes = 0 + + /** + * @param maxBytes - most UTF-8 bytes kept together; a larger read is not kept. + * @param maxAgeMs - age in milliseconds at which a kept read is no longer returned. + */ + constructor(private readonly maxBytes: number, private readonly maxAgeMs: number) {} + + /** + * Read the threads kept for a change request at a version while they are younger than the age limit, marking them + * the most recently read. + * @param key - the change request. + * @param version - head commit and update time the reader needs. + * @param now - current epoch milliseconds. + * @returns the threads, or undefined when none are kept at that version or they reached the age limit. + */ + get(key: ChangeRequestKey, version: string, now: number): ForgeReviewData | undefined { + const entry = this.entries.get(key) + if (entry?.version !== version || now - entry.readAt >= this.maxAgeMs) return undefined + this.entries.delete(key) + this.entries.set(key, entry) + return entry.review + } + + /** + * Keep a read in place of the change request's earlier one, then drop the least recently read change requests + * until the rest fit within `maxBytes`. + * @param key - the change request. + * @param version - head commit and update time the threads were read at. + * @param review - the threads. + * @param readAt - epoch milliseconds when the read started. + */ + set(key: ChangeRequestKey, version: string, review: ForgeReviewData, readAt: number): void { + const previous = this.entries.get(key) + if (previous !== undefined) { + this.entries.delete(key) + this.bytes -= previous.bytes + } + const bytes = Buffer.byteLength(JSON.stringify(review)) + if (bytes > this.maxBytes) return + this.entries.set(key, { version, review, readAt, bytes }) + this.bytes += bytes + for (const [oldest, entry] of this.entries) { + if (this.bytes <= this.maxBytes) break + this.entries.delete(oldest) + this.bytes -= entry.bytes + } + } +} diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 11dc7549e3..1588277207 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -414,6 +414,13 @@ export interface Config { * `testPaths` and before the built-in rules. */ interfacePaths?: string[] + /** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */ + maxCachedReviewBytes?: number + /** + * Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull + * request's update time does not change when a thread is resolved. + */ + reviewRefreshMs?: number } declare module '@deepseek-ai/dsh-typert-protocol' { @@ -438,8 +445,9 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/not-bound': Record /** * The change request's head is no longer the commit the request named: the head the user confirmed for a merge, - * the head displayed for complete checks, or the head of the latest status for a diff. A diff read polls the change - * request again at once, so a later status names the current head. + * the head displayed for complete checks, the head of the latest status for a diff, or the head of the displayed + * diff for review threads. A diff or review read the host refuses polls the change request again at once, so a + * later status names the current head. */ 'forgePanel/stale-head': Record /** The code host refused the change or could not be reached; the message gives the host's reason. */ @@ -468,6 +476,10 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/commits-missing': Record /** A chosen commit after the first lacks the commit listed before it as its first parent, so two ends cannot name the run. */ 'forgePanel/commits-not-linear': Record + /** The code host's provider cannot read review threads, so the changes view shows none. */ + 'forgePanel/review-unsupported': Record + /** The code host did not provide the change request's review threads, or its status has not been read yet; the message says why. */ + 'forgePanel/review-failed': Record } } diff --git a/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts b/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts new file mode 100644 index 0000000000..de498b8bbf --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import { Buffer } from 'node:buffer' +import type { ChangeRequestKey, ForgeReviewData } from '@deepseek-ai/dsh-experimental-forge' +import { ReviewCache } from '../src/review-cache.ts' + +const a = 'fake:a#1' as ChangeRequestKey +const b = 'fake:b#2' as ChangeRequestKey +const c = 'fake:c#3' as ChangeRequestKey + +function review(viewer: string): ForgeReviewData { + return { headSha: 'a'.repeat(40), viewer, threads: [], truncated: false } +} + +const size = Buffer.byteLength(JSON.stringify(review('x'))) + +describe('ReviewCache', () => { + it('returns threads kept at the same version until they reach the age limit', () => { + const cache = new ReviewCache(size * 4, 100) + cache.set(a, 'v1', review('x'), 1_000) + + expect(cache.get(a, 'v1', 1_099)).toEqual(review('x')) + expect(cache.get(a, 'v2', 1_050)).toBeUndefined() + expect(cache.get(b, 'v1', 1_050)).toBeUndefined() + expect(cache.get(a, 'v1', 1_100)).toBeUndefined() + }) + + it('replaces a change request\'s earlier read and drops the least recently read reads past the byte limit', () => { + const cache = new ReviewCache(size * 2, 100) + cache.set(a, 'v1', review('x'), 0) + cache.set(a, 'v2', review('y'), 0) + cache.set(b, 'v1', review('z'), 0) + expect(cache.get(a, 'v1', 0)).toBeUndefined() + expect(cache.get(a, 'v2', 0)).toEqual(review('y')) + + cache.set(c, 'v1', review('w'), 0) + expect(cache.get(b, 'v1', 0)).toBeUndefined() + expect(cache.get(a, 'v2', 0)).toEqual(review('y')) + expect(cache.get(c, 'v1', 0)).toEqual(review('w')) + }) + + it('keeps no read larger than the byte limit and forgets the read it replaced', () => { + const cache = new ReviewCache(size, 100) + cache.set(a, 'v1', review('x'), 0) + cache.set(a, 'v2', review('longer'), 0) + + expect(cache.get(a, 'v1', 0)).toBeUndefined() + expect(cache.get(a, 'v2', 0)).toBeUndefined() + cache.set(b, 'v1', review('x'), 0) + expect(cache.get(b, 'v1', 0)).toEqual(review('x')) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/review.host.spec.ts b/packages/experimental/client-ui-forge/tests/review.host.spec.ts new file mode 100644 index 0000000000..6869d3acb6 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/review.host.spec.ts @@ -0,0 +1,137 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { ChangeRequestRef, ForgeFailure, ForgeReviewData, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge' +import { SessionId } from '@deepseek-ai/dsh-session' +import ForgePanelController from '../src/index.ts' +import type { ForgePanelState } from '../src/index.ts' +import { bench, follow, git, pullUrl, repository, scratch, shellTurn } from './harness.ts' +import type { Bench, Follower } from './harness.ts' + +const cleanups: (() => Promise)[] = [] + +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() +}) + +const signal = new AbortController().signal +const HEAD = 'a'.repeat(40) + +async function opened(config: Parameters[1] = {}): Promise<{ opened: Bench; follower: Follower; repo: string }> { + const { path, remove } = await scratch('dsh-forge-review-') + cleanups.push(remove) + const repo = await repository(path) + await git(repo, 'remote', 'add', 'origin', 'https://fake.test/octo/demo.git') + const result = await bench(repo, config) + cleanups.push(() => result.ctx.fiber.dispose()) + const follower = follow(result.ctx, result.session) + cleanups.push(follower.stop) + return { opened: result, follower, repo } +} + +function review(headSha: string, path = 'src/a.ts'): ForgeReviewData { + return { + headSha, viewer: 'octo', truncated: false, + threads: [{ + id: 'thread-1' as ForgeThreadId, path, side: 'R', subject: 'line', resolved: false, diffHunk: '@@ -1 +1 @@\n-old\n+new', + current: { commit: headSha, startLine: 1, endLine: 1 }, original: { commit: headSha, startLine: 1, endLine: 1 }, comments: [], + }], + } +} + +/** Whether the change request at `url` holds a snapshot with the given head and update time. */ +function polledAt(state: ForgePanelState, url: string, headSha = HEAD, updatedAt?: string): boolean { + const snapshot = state.changeRequests.find(entry => entry.url === url)?.snapshot ?? null + return snapshot !== null && snapshot.headSha === headSha && (updatedAt === undefined || snapshot.updatedAt === updatedAt) +} + +describe('forgePanel change request reviews', () => { + it('reads threads at the displayed head and reuses them for every Session until the update time changes', async () => { + const { opened: panel, follower, repo } = await opened() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + Object.assign(panel.provider, { readReview }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + + await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal)).resolves.toEqual(review(HEAD)) + const other = panel.ctx.sessions.create(SessionId('forge-review-other'), { meta: { cwd: repo } }) + panel.ctx.forgeSession.track(other, pullUrl(7)) + await expect(panel.ctx.forgePanel.changeRequestReview(other, pullUrl(7), HEAD, signal)).resolves.toEqual(review(HEAD)) + expect(readReview).toHaveBeenCalledTimes(1) + + panel.provider.overrides.set(7, { updatedAt: '2026-11-07T05:00:00Z' }) + await panel.ctx.forgePanel.refresh(panel.session, signal) + await follower.until(state => polledAt(state, pullUrl(7), HEAD, '2026-11-07T05:00:00Z')) + readReview.mockResolvedValueOnce(review(HEAD, 'src/b.ts')) + await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal)) + .resolves.toMatchObject({ threads: [{ path: 'src/b.ts' }] }) + expect(readReview).toHaveBeenCalledTimes(2) + }) + + it('reads again once the kept threads reach reviewRefreshMs', async () => { + const { opened: panel, follower } = await opened({ reviewRefreshMs: 1 }) + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + Object.assign(panel.provider, { readReview }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + await new Promise(resolve => setTimeout(resolve, 5)) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + expect(readReview).toHaveBeenCalledTimes(2) + }) + + it('refuses a head other than the latest status without reading, and polls again when the host names another head', async () => { + const { opened: panel, follower } = await opened() + const pushed = 'b'.repeat(40) + const readReview = vi.fn(async (): Promise => ({ code: 'stale', message: `head moved to ${pushed}` })) + Object.assign(panel.provider, { readReview }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + + await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), pushed, signal)) + .rejects.toMatchObject({ code: 'forgePanel/stale-head', message: `The change request head moved from ${pushed} to ${HEAD}` }) + expect(readReview).not.toHaveBeenCalled() + + panel.provider.overrides.set(7, { headSha: pushed }) + const fetches = panel.provider.fetches.length + await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal)) + .rejects.toMatchObject({ code: 'forgePanel/stale-head', message: `head moved to ${pushed}` }) + await follower.until(state => polledAt(state, pullUrl(7), pushed)) + expect(panel.provider.fetches.length).toBe(fetches + 1) + }) + + it('reports an unbound change request, one not read yet, a provider without review reads, and a failed read, keeping no failure', async () => { + const { opened: panel, follower } = await opened() + panel.provider.failures.set(8, { code: 'unavailable', message: 'down' }) + shellTurn(panel.session, 1, [ + { callId: 'seven', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }, + { callId: 'eight', command: 'gh pr create --fill', output: `${pullUrl(8)}\n` }, + ]) + await follower.until(state => polledAt(state, pullUrl(7)) + && state.changeRequests.some(entry => entry.url === pullUrl(8) && entry.update !== null && 'failure' in entry.update)) + const read = (url: string): Promise => panel.ctx.forgePanel.changeRequestReview(panel.session, url, HEAD, signal) + + await expect(read(pullUrl(9))).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(read(pullUrl(8))).rejects.toMatchObject({ code: 'forgePanel/review-failed', message: 'The change request status has not been read yet' }) + await expect(read(pullUrl(7))) + .rejects.toMatchObject({ code: 'forgePanel/review-unsupported', message: 'This provider does not support review reads' }) + const codes = ['too-large', 'not-found', 'unauthenticated', 'unavailable'] as const + const readReview = vi.fn(async (): Promise => ({ code: 'unavailable', message: 'down' })) + Object.assign(panel.provider, { readReview }) + for (const code of codes) { + readReview.mockResolvedValueOnce({ code, message: `threads ${code}` }) + await expect(read(pullUrl(7))).rejects.toMatchObject({ code: 'forgePanel/review-failed', message: `threads ${code}` }) + } + expect(readReview).toHaveBeenCalledTimes(codes.length) + }) + + it.each([ + [{ reviewRefreshMs: 0 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'], + [{ reviewRefreshMs: 2_147_483_648 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'], + [{ maxCachedReviewBytes: 1.5 }, 'forge-panel: maxCachedReviewBytes must be a positive integer'], + ])('rejects %j at load', async (config, message) => { + const { opened: panel } = await opened() + await panel.panel.dispose() + + await expect(panel.ctx.plugin(ForgePanelController, config)).rejects.toThrow(message) + }) +}) diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index a6c004f078..051f252042 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -15,6 +15,7 @@ "src/panel.ts", "src/parse.ts", "src/patch-cache.ts", + "src/review-cache.ts", "src/states.ts", "src/types.ts", "src/wildmatch.ts", diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index 67e963e3d9..cf6905149e 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -3,7 +3,7 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, - ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, + ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' import { listCommits } from './commits.ts' import type { GraphqlReader } from './commits.ts' @@ -17,6 +17,7 @@ import { import type { PageResult, SnapshotPages } from './graphql.ts' import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' import { submitGitHubReview } from './review.ts' +import { readReviewThreads } from './threads.ts' const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i @@ -34,9 +35,9 @@ const NOT_ACCEPTABLE = '406' /** Bounds on what one read retains or counts. */ export interface GitHubLimits { - /** Maximum combined JSON bytes retained by an explicit check read. */ + /** Maximum combined JSON bytes retained by an explicit check read or a review read. */ readonly maxOutputBytes: number - /** Most review threads counted per pull request in one status read. */ + /** Most review threads counted per pull request in one status read, and read in one review read. */ readonly maxReviewThreads: number /** Most commits one commit listing returns. */ readonly maxCommits: number @@ -53,10 +54,21 @@ export class GitHubProvider implements ForgeProvider { return await submitGitHubReview(this.gh, ref, request, signal) } + /** + * Read the review threads of a pull request at `headSha` through GraphQL, each page naming the head it was read at. + * @see readReviewThreads + */ + async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { + const failure = this.hostFailure(ref.repository.host) + if (failure !== undefined) return failure + if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`) + return await readReviewThreads(this.graphql, ref, headSha, this.limits, signal) + } + /** * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. - * @param limits - bounds on retained check bytes, counted review threads, and listed commits. + * @param limits - bounds on retained check and review bytes, counted and read review threads, and listed commits. */ constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) { this.hosts = new Set(hosts.map(host => host.toLowerCase())) diff --git a/packages/experimental/forge-github/src/threads.ts b/packages/experimental/forge-github/src/threads.ts new file mode 100644 index 0000000000..f23507e374 --- /dev/null +++ b/packages/experimental/forge-github/src/threads.ts @@ -0,0 +1,209 @@ +/** Reads the review threads of a GitHub pull request at one head commit through GraphQL. */ + +import { Buffer } from 'node:buffer' +import type { + ChangeRequestRef, ForgeAnchor, ForgeCommentId, ForgeFailure, ForgeReviewComment, ForgeReviewData, ForgeReviewThread, ForgeThreadId, +} from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import type { GraphqlReader } from './commits.ts' +import { checkedRepository, isCommit } from './urls.ts' + +/** Most nodes GitHub returns in one connection page. */ +const PAGE_SIZE = 100 + +const COMMENT_FIELDS = 'id state createdAt url body author { __typename login avatarUrl(size: 48) }' + +const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { ${COMMENT_FIELDS} } }` + +/** + * Thread fields. `root` reads the commits and diff hunk of the first comment once, since replies repeat them; the + * first page of comments starts without a cursor. + */ +const THREAD_FIELDS = `id isOutdated isResolved path diffSide startDiffSide line startLine originalLine originalStartLine subjectType + root: comments(first: 1) { nodes { diffHunk commit { oid } originalCommit { oid } } } + ${COMMENT_PAGE.replace(', after: $cursor', '')}` + +const THREAD_PAGE = `pageInfo { hasNextPage endCursor } nodes { ${THREAD_FIELDS} }` + +/** First thread page with the head and the viewer; variables `owner` and `name` are strings, `number` and `first` integers. */ +export const REVIEW_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!) { + viewer { login } + repository(owner: $owner, name: $name) { pullRequest(number: $number) { id headRefOid reviewThreads(first: $first) { ${THREAD_PAGE} } } } +}` + +/** Following thread page with the head it was read at; variables `id` and `cursor` are strings, `first` an integer. */ +export const REVIEW_THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) { + node(id: $id) { ... on PullRequest { headRefOid reviewThreads(first: $first, after: $cursor) { ${THREAD_PAGE} } } } +}` + +/** Following comment page of one thread; variables `id` and `cursor` are strings. */ +export const THREAD_COMMENTS_QUERY = `query($id: ID!, $cursor: String!) { + node(id: $id) { ... on PullRequestReviewThread { ${COMMENT_PAGE} } } +}` + +/** Bounds of one review read. */ +export interface ReviewLimits { + /** Most threads read. */ + readonly maxReviewThreads: number + /** Most JSON bytes of all pages together; a page that would pass it ends the read as truncated. */ + readonly maxOutputBytes: number +} + +const pageInfoSchema = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }) + +const commitSchema = z.object({ oid: z.string().refine(isCommit) }).nullable() + +const commentSchema = z.object({ + id: z.string(), + state: z.string(), + createdAt: z.string(), + url: z.string().nullable(), + body: z.string(), + author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }).nullable(), +}) + +const commentPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(commentSchema) }) + +const threadSchema = z.object({ + id: z.string(), + isOutdated: z.boolean(), + isResolved: z.boolean(), + path: z.string(), + diffSide: z.string(), + startDiffSide: z.string().nullable(), + line: z.number().int().nullable(), + startLine: z.number().int().nullable(), + originalLine: z.number().int().nullable(), + originalStartLine: z.number().int().nullable(), + subjectType: z.string(), + root: z.object({ nodes: z.array(z.object({ diffHunk: z.string(), commit: commitSchema, originalCommit: commitSchema })) }), + comments: commentPageSchema, +}) + +const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(threadSchema) }) + +const firstPageSchema = z.object({ data: z.object({ + viewer: z.object({ login: z.string() }).nullable(), + repository: z.object({ pullRequest: z.object({ id: z.string(), headRefOid: z.string(), reviewThreads: threadPageSchema }) }), +}) }) + +const nextPageSchema = z.object({ data: z.object({ node: z.object({ headRefOid: z.string(), reviewThreads: threadPageSchema }) }) }) + +const commentsPageSchema = z.object({ data: z.object({ node: z.object({ comments: commentPageSchema }) }) }) + +type ThreadNode = z.infer +type CommentNode = z.infer + +/** + * Read the review threads of a pull request while its head is `headSha`. The first page also names the head and the + * signed-in user; every following thread page names the head again, so a head that moves during the read returns + * `stale`. Threads are read up to `maxReviewThreads`, each with all of its comments. A page that would bring the + * pages read, measured as JSON, past `maxOutputBytes` is dropped with the threads after it, and the result is marked truncated. + * @param read - runs one GraphQL request. + * @param ref - pull request, with an owner and name already checked for inlining. + * @param headSha - head commit the threads must be read at. + * @param limits - thread and byte bounds. + * @param signal - cancellation of the read. + * @returns the threads, or why GitHub did not provide them at `headSha`. + */ +export async function readReviewThreads( + read: GraphqlReader, ref: ChangeRequestRef, headSha: string, limits: ReviewLimits, signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const graphql = async (variables: readonly string[]): Promise<{ readonly body: unknown; readonly bytes: number } | ForgeFailure> => { + const output = await read(['api', 'graphql', '--hostname', host, ...variables], signal) + if (!output.ok) return output.failure + return { body: output.body, bytes: Buffer.byteLength(JSON.stringify(output.body)) } + } + const unexpected: ForgeFailure = { code: 'unavailable', message: 'unexpected GitHub response to the review thread read' } + const stale = (head: string): ForgeFailure | undefined => head.toLowerCase() === headSha.toLowerCase() ? undefined + : { code: 'stale', message: `the pull request head moved from ${headSha} to ${head}` } + const first = await graphql(['-f', `query=${REVIEW_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, + '-F', `number=${ref.number}`, '-F', `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads)}`]) + if ('code' in first) return first + const parsed = firstPageSchema.safeParse(first.body) + if (!parsed.success) return unexpected + const pull = parsed.data.data.repository.pullRequest + const moved = stale(pull.headRefOid) + if (moved !== undefined) return moved + let bytes = first.bytes + let page = pull.reviewThreads + const threads: ForgeReviewThread[] = [] + const viewer = parsed.data.data.viewer?.login ?? null + const result = (truncated: boolean): ForgeReviewData => ({ headSha, viewer, threads, truncated }) + const cursors = new Set() + for (;;) { + for (const node of page.nodes.slice(0, limits.maxReviewThreads - threads.length)) { + const comments = [...node.comments.nodes] + const commentCursors = new Set() + let more = node.comments.pageInfo + while (more.hasNextPage) { + const cursor = more.endCursor + if (cursor === null || commentCursors.has(cursor)) return { code: 'unavailable', message: 'GitHub review comment pagination did not advance' } + commentCursors.add(cursor) + const next = await graphql(['-f', `query=${THREAD_COMMENTS_QUERY}`, '-f', `id=${node.id}`, '-f', `cursor=${cursor}`]) + if ('code' in next) return next + const comment = commentsPageSchema.safeParse(next.body) + if (!comment.success) return unexpected + bytes += next.bytes + if (bytes > limits.maxOutputBytes) return result(true) + comments.push(...comment.data.data.node.comments.nodes) + more = comment.data.data.node.comments.pageInfo + } + if (comments.length > 0) threads.push(toThread(node, comments, headSha)) + } + if (threads.length >= limits.maxReviewThreads || !page.pageInfo.hasNextPage) return result(page.pageInfo.hasNextPage) + const cursor = page.pageInfo.endCursor + if (cursor === null || cursors.has(cursor)) return { code: 'unavailable', message: 'GitHub review thread pagination did not advance' } + cursors.add(cursor) + const next = await graphql(['-f', `query=${REVIEW_THREADS_QUERY}`, '-f', `id=${pull.id}`, '-f', `cursor=${cursor}`, + '-F', `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads - threads.length)}`]) + if ('code' in next) return next + const following = nextPageSchema.safeParse(next.body) + if (!following.success) return unexpected + const movedLater = stale(following.data.data.node.headRefOid) + if (movedLater !== undefined) return movedLater + bytes += next.bytes + if (bytes > limits.maxOutputBytes) return result(true) + page = following.data.data.node.reviewThreads + } +} + +/** + * Map one thread. GitHub keeps a thread's `line` on the commit of its first comment, which stays an older commit for + * a comment written on a commit the head no longer is; such a thread, like one GitHub marks outdated or leaves + * without a line, has no position at `head`. A range whose start is on the other side of the diff keeps its last line. + */ +function toThread(node: ThreadNode, comments: readonly CommentNode[], head: string): ForgeReviewThread { + const root = node.root.nodes[0] + const line = node.subjectType !== 'FILE' + const sameSide = node.startDiffSide === null || node.startDiffSide === node.diffSide + const placed = line && !node.isOutdated && node.line !== null && root?.commit?.oid.toLowerCase() === head.toLowerCase() + return { + id: node.id as ForgeThreadId, + path: node.path, + side: node.diffSide === 'LEFT' ? 'L' : 'R', + subject: line ? 'line' : 'file', + current: placed && node.line !== null ? anchor(head, sameSide ? node.startLine : null, node.line) : null, + original: line && node.originalLine !== null && root?.originalCommit != null + ? anchor(root.originalCommit.oid, sameSide ? node.originalStartLine : null, node.originalLine) : null, + diffHunk: root === undefined || root.diffHunk === '' ? null : root.diffHunk, + resolved: node.isResolved, + comments: comments.map(toComment), + } +} + +function anchor(commit: string, start: number | null, end: number): ForgeAnchor { + return { commit, startLine: start !== null && start >= 1 && start <= end ? start : end, endLine: end } +} + +function toComment(node: CommentNode): ForgeReviewComment { + return { + id: node.id as ForgeCommentId, + author: node.author === null ? null : { login: node.author.login, avatarUrl: node.author.avatarUrl, bot: node.author.__typename === 'Bot' }, + body: node.body, + createdAt: node.createdAt, + pending: node.state === 'PENDING', + url: node.url, + } +} diff --git a/packages/experimental/forge-github/tests/threads.spec.ts b/packages/experimental/forge-github/tests/threads.spec.ts new file mode 100644 index 0000000000..f90c18b0a0 --- /dev/null +++ b/packages/experimental/forge-github/tests/threads.spec.ts @@ -0,0 +1,256 @@ +import { describe, expect, it } from 'vitest' +import type { GhOutput, GhRunner } from '../src/gh.ts' +import { GitHubProvider } from '../src/provider.ts' +import type { GitHubLimits } from '../src/provider.ts' +import { REVIEW_QUERY, REVIEW_THREADS_QUERY, THREAD_COMMENTS_QUERY } from '../src/threads.ts' +import { demo, pull } from './fixtures.ts' + +const head = 'c'.repeat(40) +const older = 'a'.repeat(40) +const pushed = 'd'.repeat(40) +const signal = new AbortController().signal + +function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { + return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr } +} + +/** Answer each `gh` call through `handler`, recording the arguments. */ +function fakeGh(handler: (args: readonly string[]) => GhOutput): { run: GhRunner; calls: string[][] } { + const calls: string[][] = [] + return { calls, run: async (args) => { calls.push([...args]); return handler(args) } } +} + +function provider(run: GhRunner, limits: Partial = {}): GitHubProvider { + return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, ...limits }) +} + +function page(nodes: readonly unknown[], next: string | null = null): Record { + return { pageInfo: { hasNextPage: next !== null, endCursor: next }, nodes } +} + +/** One review comment node as the thread query selects it. */ +function commentNode(id: string, overrides: Record = {}): Record { + return { + id, state: 'SUBMITTED', createdAt: '2026-11-05T08:00:00Z', url: `https://github.com/octo/demo/pull/7#discussion_${id}`, body: `Body of ${id}`, + author: { __typename: 'User', login: 'reviewer', avatarUrl: 'https://avatars.githubusercontent.com/u/1?s=48&v=4' }, + ...overrides, + } +} + +/** One review thread node on a new-side line at the head, with one comment. */ +function threadNode(id: string, overrides: Record = {}, root: Record = {}): Record { + return { + id, isOutdated: false, isResolved: false, path: 'src/a.ts', diffSide: 'RIGHT', startDiffSide: null, + line: 12, startLine: null, originalLine: 12, originalStartLine: null, subjectType: 'LINE', + root: { nodes: [{ diffHunk: '@@ -10,2 +10,3 @@\n a\n+b\n c', commit: { oid: head }, originalCommit: { oid: head }, ...root }] }, + comments: page([commentNode(`${id}-1`)]), + ...overrides, + } +} + +function firstPage(threads: Record, headRefOid = head, viewer: unknown = { login: 'octo' }): Record { + return { data: { viewer, repository: { pullRequest: { id: 'pull-7', headRefOid, reviewThreads: threads } } } } +} + +function nextPage(threads: Record, headRefOid = head): Record { + return { data: { node: { headRefOid, reviewThreads: threads } } } +} + +/** Answer the first thread page with `first`, later thread pages from `later` by cursor, and comment pages from `comments` by cursor. */ +function review( + first: Record | GhOutput, + later: Readonly>> = {}, + comments: Readonly>> = {}, +): ReturnType { + return fakeGh((args) => { + const cursor = args.find(arg => arg.startsWith('cursor='))?.slice('cursor='.length) ?? '' + if (args.includes(`query=${REVIEW_QUERY}`)) return 'exitCode' in first ? first : output(first) + if (args.includes(`query=${REVIEW_THREADS_QUERY}`)) return output(later[cursor] ?? { data: { node: null } }) + if (args.includes(`query=${THREAD_COMMENTS_QUERY}`)) return output(comments[cursor] ?? { data: { node: null } }) + throw new Error(`unexpected gh ${args.join(' ')}`) + }) +} + +describe('GitHub provider review threads', () => { + it('reads the first page with the head, the viewer, and the pull request as variables, and maps a thread placed at the head', async () => { + const gh = review(firstPage(page([threadNode('t1', { isResolved: true })]))) + + await expect(provider(gh.run).readReview(pull(7), head, signal)).resolves.toEqual({ + headSha: head, + viewer: 'octo', + truncated: false, + threads: [{ + id: 't1', path: 'src/a.ts', side: 'R', subject: 'line', + current: { commit: head, startLine: 12, endLine: 12 }, + original: { commit: head, startLine: 12, endLine: 12 }, + diffHunk: '@@ -10,2 +10,3 @@\n a\n+b\n c', + resolved: true, + comments: [{ + id: 't1-1', body: 'Body of t1-1', createdAt: '2026-11-05T08:00:00Z', pending: false, + url: 'https://github.com/octo/demo/pull/7#discussion_t1-1', + author: { login: 'reviewer', avatarUrl: 'https://avatars.githubusercontent.com/u/1?s=48&v=4', bot: false }, + }], + }], + }) + expect(gh.calls).toEqual([['api', 'graphql', '--hostname', 'github.com', '-f', `query=${REVIEW_QUERY}`, + '-f', `owner=${demo.owner}`, '-f', `name=${demo.name}`, '-F', 'number=7', '-F', 'first=100']]) + }) + + it('places a thread GitHub moved to the head at its current lines and keeps the lines it was written on', async () => { + const gh = review(firstPage(page([threadNode('moved', { line: 136, originalLine: 135 }, { originalCommit: { oid: older } })]))) + + const result = await provider(gh.run).readReview(pull(7), head, signal) + + expect(result).toMatchObject({ threads: [{ + current: { commit: head, startLine: 136, endLine: 136 }, original: { commit: older, startLine: 135, endLine: 135 }, + }] }) + }) + + it.each([ + ['GitHub marks it outdated without a line', { isOutdated: true, line: null }, {}], + ['GitHub marks it outdated but keeps a line', { isOutdated: true, line: 303, startLine: 294 }, {}], + ['GitHub reports no line', { line: null }, {}], + ['its comment is on a commit other than the head', {}, { commit: { oid: older }, originalCommit: { oid: older } }], + ['its comment has no commit', {}, { commit: null }], + ] as const)('gives a thread no current position when %s', async (_label, thread, root) => { + const gh = review(firstPage(page([threadNode('old', { originalLine: 9, ...thread }, root)]))) + + const result = await provider(gh.run).readReview(pull(7), head, signal) + + expect(result).toMatchObject({ threads: [{ current: null, original: { startLine: 9, endLine: 9 } }] }) + }) + + it('maps a file thread without positions or hunk, an old-side range, and a range that starts on the other side', async () => { + const gh = review(firstPage(page([ + threadNode('file', { subjectType: 'FILE', line: null, originalLine: null }, { diffHunk: '' }), + threadNode('left', { diffSide: 'LEFT', startDiffSide: 'LEFT', startLine: 3, line: 5, originalStartLine: 3, originalLine: 5 }), + threadNode('cross', { diffSide: 'RIGHT', startDiffSide: 'LEFT', startLine: 4, line: 6, originalStartLine: 4, originalLine: 6 }), + threadNode('reversed', { startLine: 8, line: 6, originalStartLine: 0, originalLine: 6 }), + ]))) + + const result = await provider(gh.run).readReview(pull(7), head, signal) + + expect(result).toMatchObject({ threads: [ + { id: 'file', subject: 'file', side: 'R', current: null, original: null, diffHunk: null }, + { id: 'left', side: 'L', current: { startLine: 3, endLine: 5 }, original: { startLine: 3, endLine: 5 } }, + { id: 'cross', side: 'R', current: { startLine: 6, endLine: 6 }, original: { startLine: 6, endLine: 6 } }, + { id: 'reversed', current: { startLine: 6, endLine: 6 }, original: { startLine: 6, endLine: 6 } }, + ] }) + }) + + it('maps pending comments, bots, deleted authors, a missing viewer, and drops a thread without comments', async () => { + const gh = review(firstPage(page([ + threadNode('t1', { comments: page([ + commentNode('c1', { author: { __typename: 'Bot', login: 'ci', avatarUrl: null } }), + commentNode('c2', { state: 'PENDING', author: null, url: null }), + ]) }), + threadNode('empty', { comments: page([]) }, { diffHunk: '' }), + ]), head, null)) + + const result = await provider(gh.run).readReview(pull(7), head, signal) + + expect(result).toMatchObject({ viewer: null, threads: [{ id: 't1', comments: [ + { id: 'c1', author: { login: 'ci', avatarUrl: null, bot: true }, pending: false }, + { id: 'c2', author: null, pending: true, url: null }, + ] }] }) + expect(result).toMatchObject({ threads: { length: 1 } }) + }) + + it('reads the following thread and comment pages, asking only for the threads left under maxReviewThreads', async () => { + const gh = review( + firstPage(page([threadNode('t1', { comments: page([commentNode('c1')], 'comments-1') })], 'threads-1')), + { 'threads-1': nextPage(page([threadNode('t2')], 'threads-2')) }, + { 'comments-1': { data: { node: { comments: page([commentNode('c2')]) } } } }, + ) + + const result = await provider(gh.run, { maxReviewThreads: 2 }).readReview(pull(7), head, signal) + + expect(result).toMatchObject({ truncated: true, threads: [ + { id: 't1', comments: [{ id: 'c1' }, { id: 'c2' }] }, { id: 't2' }, + ] }) + expect(gh.calls.slice(1)).toEqual([ + ['api', 'graphql', '--hostname', 'github.com', '-f', `query=${THREAD_COMMENTS_QUERY}`, '-f', 'id=t1', '-f', 'cursor=comments-1'], + ['api', 'graphql', '--hostname', 'github.com', '-f', `query=${REVIEW_THREADS_QUERY}`, '-f', 'id=pull-7', '-f', 'cursor=threads-1', '-F', 'first=1'], + ]) + expect(gh.calls[0]).toContain('first=2') + }) + + it('reports a head other than the requested commit as stale, on the first page or on a later one', async () => { + const moved = review(firstPage(page([threadNode('t1')]), pushed)) + await expect(provider(moved.run).readReview(pull(7), head, signal)) + .resolves.toEqual({ code: 'stale', message: `the pull request head moved from ${head} to ${pushed}` }) + + const later = review(firstPage(page([threadNode('t1')], 'threads-1')), { 'threads-1': nextPage(page([threadNode('t2')]), pushed) }) + await expect(provider(later.run).readReview(pull(7), head.toUpperCase(), signal)) + .resolves.toEqual({ code: 'stale', message: `the pull request head moved from ${head.toUpperCase()} to ${pushed}` }) + }) + + it('keeps the threads read before a page that passes maxOutputBytes and marks the result truncated', async () => { + const first = firstPage(page([threadNode('t1', { comments: page([commentNode('c1')], 'comments-1') })], 'threads-1')) + const size = JSON.stringify(first).length + const comments = { 'comments-1': { data: { node: { comments: page([commentNode('c2')]) } } } } + const threads = { 'threads-1': nextPage(page([threadNode('t2')])) } + + const byComments = review(first, threads, comments) + await expect(provider(byComments.run, { maxOutputBytes: size + 10 }).readReview(pull(7), head, signal)) + .resolves.toEqual({ headSha: head, viewer: 'octo', threads: [], truncated: true }) + + const commentBytes = JSON.stringify(comments['comments-1']).length + const byThreads = review(first, threads, comments) + await expect(provider(byThreads.run, { maxOutputBytes: size + commentBytes + 10 }).readReview(pull(7), head, signal)) + .resolves.toMatchObject({ threads: [{ id: 't1' }], truncated: true }) + }) + + it.each([ + ['a thread page without a cursor', firstPage({ pageInfo: { hasNextPage: true, endCursor: null }, nodes: [] }), {}, {}, + 'GitHub review thread pagination did not advance'], + ['a thread page that repeats its cursor', firstPage(page([], 'threads-1')), { 'threads-1': nextPage(page([], 'threads-1')) }, {}, + 'GitHub review thread pagination did not advance'], + ['a comment page that repeats its cursor', firstPage(page([threadNode('t1', { comments: page([commentNode('c1')], 'comments-1') })])), {}, + { 'comments-1': { data: { node: { comments: page([], 'comments-1') } } } }, 'GitHub review comment pagination did not advance'], + ['a comment page without a cursor', firstPage(page([threadNode('t1', { comments: { pageInfo: { hasNextPage: true, endCursor: null }, nodes: [] } })])), + {}, {}, 'GitHub review comment pagination did not advance'], + ['an unexpected first page', { data: { repository: { pullRequest: null } } }, {}, {}, 'unexpected GitHub response to the review thread read'], + ['an unexpected thread page', firstPage(page([], 'threads-1')), {}, {}, 'unexpected GitHub response to the review thread read'], + ['an unexpected comment page', firstPage(page([threadNode('t1', { comments: page([], 'comments-1') })])), {}, {}, + 'unexpected GitHub response to the review thread read'], + ] as const)('reports %s as unavailable', async (_label, first, later, comments, message) => { + const gh = review(first, later, comments) + + await expect(provider(gh.run).readReview(pull(7), head, signal)).resolves.toEqual({ code: 'unavailable', message }) + }) + + it('passes on the failure of any page read and of a response that is not JSON', async () => { + const missing = review(output('', 1, 'gh: Could not resolve to a PullRequest with the number of 7.')) + await expect(provider(missing.run).readReview(pull(7), head, signal)) + .resolves.toEqual({ code: 'not-found', message: 'gh: Could not resolve to a PullRequest with the number of 7.' }) + + const garbled = review(output('not json')) + await expect(provider(garbled.run).readReview(pull(7), head, signal)).resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response' }) + + const refused = review(output({ data: null, errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible by integration' }] })) + await expect(provider(refused.run).readReview(pull(7), head, signal)) + .resolves.toEqual({ code: 'unavailable', message: 'Resource not accessible by integration' }) + + const failing = fakeGh(args => args.includes(`query=${REVIEW_QUERY}`) + ? output(firstPage(page([threadNode('t1', { comments: page([], 'comments-1') })], 'threads-1'))) + : output('', 1, 'gh: Server Error (HTTP 502)')) + await expect(provider(failing.run).readReview(pull(7), head, signal)).resolves.toEqual({ code: 'unavailable', message: 'gh: Server Error (HTTP 502)' }) + + const failingThreads = fakeGh(args => args.includes(`query=${REVIEW_QUERY}`) + ? output(firstPage(page([threadNode('t1')], 'threads-1'))) + : output('', 1, 'gh: Server Error (HTTP 502)')) + await expect(provider(failingThreads.run).readReview(pull(7), head, signal)) + .resolves.toEqual({ code: 'unavailable', message: 'gh: Server Error (HTTP 502)' }) + }) + + it('refuses an unconfigured host without starting gh and a head that is not a commit object name', async () => { + const gh = review(firstPage(page([]))) + const elsewhere = { ...demo, host: 'ghe.other.example' } + + await expect(provider(gh.run).readReview(pull(7, elsewhere), head, signal)) + .resolves.toEqual({ code: 'unavailable', message: 'forge-github: host "ghe.other.example" is not configured' }) + await expect(provider(gh.run).readReview(pull(7), 'main', signal)).rejects.toThrow('forge-github: invalid head commit "main"') + expect(gh.calls).toEqual([]) + }) +}) diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index f52f77e818..88068c3aee 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -7,7 +7,8 @@ import { changeRequestKey } from './keys.ts' import { nextPollDelay } from './schedule.ts' import type { ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, - ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, + ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, + MergeRequest, } from './types.ts' export { changeRequestKey } from './keys.ts' @@ -44,7 +45,7 @@ interface Watch { /** Epoch milliseconds of the next poll; undefined while in flight or after a terminal state. */ dueAt: number | undefined failures: number - /** Head commit whose `stale` diff read last polled at once, so further stale reads at it wait for the regular poll. */ + /** Head commit whose `stale` diff or review read last polled at once, so further stale reads at it wait for the regular poll. */ staleHead: string | undefined } @@ -252,11 +253,24 @@ export class ForgeService extends Service { async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { const result = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => provider.diff(ref, headSha, operation)) - const watch = this.watches.get(changeRequestKey(ref)) - if (typeof result !== 'string' && result.code === 'stale' && watch !== undefined && watch.staleHead !== headSha) { - watch.staleHead = headSha - this.refresh(ref) - } + if (typeof result !== 'string') this.staleRead(ref, headSha, result) + return result + } + + /** + * Read the review threads of a change request at one head commit. A + * `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param headSha - head commit the threads must be read at, usually the head of the displayed diff. + * @param signal - cancellation of the read. + * @returns the threads read at `headSha`, or why the host did not provide them; `unsupported` when the provider cannot read reviews. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { + const result = await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.readReview?.(ref, headSha, operation) + ?? Promise.resolve({ code: 'unsupported', message: 'This provider does not support review reads' } as const)) + if ('code' in result) this.staleRead(ref, headSha, result) return result } @@ -384,6 +398,14 @@ export class ForgeService extends Service { return this.watches.get(changeRequestKey(ref))?.latest } + /** Poll a watched change request at once after the first `stale` read at `headSha`; later ones wait for the regular poll. */ + private staleRead(ref: ChangeRequestRef, headSha: string, failure: ForgeFailure): void { + const watch = this.watches.get(changeRequestKey(ref)) + if (failure.code !== 'stale' || watch === undefined || watch.staleHead === headSha) return + watch.staleHead = headSha + this.refresh(ref) + } + private provider(forge: string): ForgeProvider { return this.registration(forge).provider } diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 18c8b02e6d..71bd7270e0 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -116,9 +116,9 @@ export interface ForgeFailure { * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of - * a later status can succeed; `unavailable`: any other failure. + * a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -163,6 +163,86 @@ export type ForgeReviewRequest = { | { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] } ) +/** Opaque host identity of one review thread. */ +export type ForgeThreadId = Branded<'ForgeThreadId'> + +/** Opaque host identity of one review comment. */ +export type ForgeCommentId = Branded<'ForgeCommentId'> + +/** Consecutive lines of one file at one commit. */ +export interface ForgeAnchor { + /** Full object name of the commit whose file the lines number. */ + readonly commit: string + /** First line, inclusive. */ + readonly startLine: number + /** Last line, inclusive. */ + readonly endLine: number +} + +/** Account that wrote a review comment. */ +export interface ForgeCommentAuthor { + /** Login as the host spells it. */ + readonly login: string + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether the account is an app or bot rather than a person. */ + readonly bot: boolean +} + +/** One comment of a review thread. */ +export interface ForgeReviewComment { + /** Host identity of the comment. */ + readonly id: ForgeCommentId + /** Author, or null when the account no longer exists. */ + readonly author: ForgeCommentAuthor | null + /** Markdown source as the author wrote it; it may contain raw HTML, which readers must not render as HTML. */ + readonly body: string + /** ISO 8601 time the comment was created. */ + readonly createdAt: string + /** Whether the comment belongs to the signed-in user's review that is not submitted yet, which only that user sees. */ + readonly pending: boolean + /** Web page of the comment, or null when the host reports none. */ + readonly url: string | null +} + +/** + * One review thread on a file of a change request. A line thread has two positions: `original` on the commit it was + * written on, and `current` on the head commit of the read. `current` is null once the host no longer places the + * thread on the head commit, as after later commits changed its lines. + */ +export interface ForgeReviewThread { + /** Host identity of the thread. */ + readonly id: ForgeThreadId + /** Repository-relative path the thread is on. */ + readonly path: string + /** Old (`L`) or new (`R`) side of the diff the lines number. */ + readonly side: 'L' | 'R' + /** Whether the thread is on lines or on the whole file. */ + readonly subject: 'line' | 'file' + /** Lines at the head commit of the read, whose `commit` is that head; null for an outdated or file thread. */ + readonly current: ForgeAnchor | null + /** Lines at the commit the thread was written on; null for a file thread. */ + readonly original: ForgeAnchor | null + /** Diff hunk the host recorded when the thread was written, ending at its last line; null when it recorded none. */ + readonly diffHunk: string | null + /** Whether the thread is marked resolved. */ + readonly resolved: boolean + /** Comments oldest first; the first starts the thread. */ + readonly comments: readonly ForgeReviewComment[] +} + +/** Review threads of a change request read at one head commit. */ +export interface ForgeReviewData { + /** Head commit the threads were read at; `current` positions number its files. */ + readonly headSha: string + /** Login of the signed-in user the provider read as, or null when the host does not name one. */ + readonly viewer: string | null + /** Threads in host order, at most the provider's limit. */ + readonly threads: readonly ForgeReviewThread[] + /** Whether the change request has more threads than `threads` holds. */ + readonly truncated: boolean +} + /** Result of a review write; unknown outcomes must be checked on the host before another submission. */ export type ForgeReviewResult = | { readonly ok: true; readonly url: string } @@ -220,6 +300,12 @@ export interface ForgeProvider { readonly forge: string /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise + /** + * Read the review threads of a change request at head commit `headSha`. The threads are returned only when the + * read names `headSha` as the head; once the head is another commit, the read resolves to a `stale` failure. + * Omission declares that this provider cannot read reviews. + */ + readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ diff --git a/packages/experimental/forge/tests/registry.spec.ts b/packages/experimental/forge/tests/registry.spec.ts index 7a5d84ab7b..a87103be4e 100644 --- a/packages/experimental/forge/tests/registry.spec.ts +++ b/packages/experimental/forge/tests/registry.spec.ts @@ -1,6 +1,7 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' import ForgeService, { changeRequestKey } from '../src/index.ts' +import type { ForgeReviewData } from '../src/types.ts' import { demo, FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts' let ctx: Context | undefined @@ -125,6 +126,21 @@ describe('forge registry', () => { expect(compare).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), 'b'.repeat(40), expect.any(AbortSignal)) }) + it('delegates review reads to the provider of their forge and reports a provider without them as unsupported', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + + await expect(ctx.forge.readReview(ref(3), 'a'.repeat(40), signal)) + .resolves.toEqual({ code: 'unsupported', message: 'This provider does not support review reads' }) + const review: ForgeReviewData = { headSha: 'a'.repeat(40), viewer: 'octo', threads: [], truncated: false } + const readReview = vi.fn(async () => review) + Object.assign(provider, { readReview }) + await expect(ctx.forge.readReview(ref(3), 'a'.repeat(40), signal)).resolves.toBe(review) + expect(readReview).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), expect.any(AbortSignal)) + }) + it('delegates change request actions to the provider of their forge and returns its outcome', async () => { ctx = await forgeContext() const provider = new FakeProvider() diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index 4537d82670..5903fb42fa 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -1,7 +1,7 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import ForgeService, { changeRequestKey } from '../src/index.ts' -import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeRepository } from '../src/types.ts' +import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeRepository, ForgeReviewData } from '../src/types.ts' import { FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts' const config = { activeIntervalMs: 1_000, idleIntervalMs: 5_000, maxBackoffMs: 6_000, fetchTimeoutMs: 500 } @@ -266,6 +266,29 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(4) }) + it('polls at once after a review read finds a newer head, sharing the once-per-head bound with diff reads', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const readReview = vi.fn(async (): Promise => ({ code: 'unavailable', message: 'down' })) + Object.assign(provider, { readReview }) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + + await context.forge.readReview(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(1) + readReview.mockResolvedValue({ code: 'stale', message: 'the head moved' }) + await expect(context.forge.readReview(ref(1), 'a'.repeat(40), signal)).resolves.toEqual({ code: 'stale', message: 'the head moved' }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + provider.readResult = { code: 'stale', message: 'the head moved' } + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + }) + it('coalesces refreshes during a fetch into one immediate subsequent fetch', async () => { const provider = new FakeProvider() const release = held(provider, target => snapshot(target)) From a39bcaec124a20091a284554793a9f3c9a6eda69 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 13:58:57 +0800 Subject: [PATCH 04/29] feat(forge-panel): overlay GitHub review threads on the changes view Threads read at the shown head sit under the row of their last line, or after the collapsed lines that hold it; resolved threads fold into one row, file threads open their file, and outdated threads gather after the lines with the end of their recorded hunk and the file at the commit they were written on. Chosen commits place only new-side threads whose lines number the last chosen commit. The file tree and file headers count unresolved threads, and a thread list filters unresolved, outdated, resolved, and awaiting-my-reply threads by file and opens each at its place. A thread offers only Add to input, which quotes the whole thread, and View on GitHub. --- .../src/client/ChangedFiles.module.css | 2 + .../src/client/ChangedFiles.tsx | 6 +- .../src/client/ChangesTab.module.css | 58 +++ .../client-ui-forge/src/client/ChangesTab.tsx | 88 ++++- .../client-ui-forge/src/client/DiffFile.tsx | 58 ++- .../src/client/ReviewThreads.module.css | 219 ++++++++++++ .../src/client/ReviewThreads.tsx | 265 ++++++++++++++ .../src/client/ThreadList.module.css | 168 +++++++++ .../client-ui-forge/src/client/ThreadList.tsx | 163 +++++++++ .../client-ui-forge/src/client/locales.ts | 336 ++++++++++++++++++ .../client-ui-forge/src/client/mount.ts | 18 +- .../src/client/review-threads.ts | 171 +++++++++ .../src/client/thread-state.ts | 124 +++++++ .../tests/changes-tab.client.spec.tsx | 187 +++++++++- .../tests/mount.client.spec.ts | 17 +- .../tests/review-thread-cards.client.spec.tsx | 214 +++++++++++ .../tests/review-threads.client.spec.ts | 132 +++++++ .../tests/thread-fixtures.client.ts | 43 +++ 18 files changed, 2247 insertions(+), 22 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/ThreadList.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/ThreadList.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/review-threads.ts create mode 100644 packages/experimental/client-ui-forge/src/client/thread-state.ts create mode 100644 packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx create mode 100644 packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts create mode 100644 packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css index 4a57098d20..2006c2b546 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css @@ -5,6 +5,8 @@ .row { box-sizing: border-box; display: flex; align-items: center; gap: 6px; width: 100%; min-width: 0; min-height: 30px; padding: 4px 6px; border: 0; border-radius: var(--dsw-radius-sm); background: transparent; color: inherit; font: inherit; text-align: start; cursor: pointer; } .row svg { flex: none; } .name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +/* Unresolved host review threads of a file, in the thread count chip treatment of the file header. */ +.threads { flex: none; min-width: 16px; padding: 0 5px; box-sizing: border-box; border-radius: var(--dsw-radius-xs); background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 12%, transparent); color: var(--dsw-alias-state-business-primary); font-size: 11px; line-height: 16px; text-align: center; } .selected { background: var(--dsw-alias-interactive-bg-hover); } .chevron { display: inline-flex; flex: 0 0 12px; } .collapsed { transform: rotate(-90deg); } diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx index 995bae454d..eb24d62b51 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -25,6 +25,8 @@ export interface ChangedFilesProps extends PropsLocale { readonly jump: (path: string) => void /** A menu row participates in the shared menu's keyboard walk. */ readonly menu?: boolean + /** Unresolved host review threads by file path; files without any are absent. */ + readonly threadCounts?: ReadonlyMap } function Rows({ nodes, depth, props }: { @@ -32,10 +34,11 @@ function Rows({ nodes, depth, props }: { readonly depth: number readonly props: ChangedFilesProps }): ReactNode { - const { state, toggle, jump, menu, t } = props + const { state, toggle, jump, menu, threadCounts, t } = props return nodes.map((node) => { const directory = node.kind === 'directory' const expanded = directory && (state.query.trim() !== '' || state.collapsed[node.path] !== true) + const threads = node.kind === 'file' ? threadCounts?.get(node.path) ?? 0 : 0 const label = node.kind === 'file' && node.file.previousPath !== null ? t('diff.renamedPath', { from: node.file.previousPath, path: node.path }) : node.path return
@@ -54,6 +57,7 @@ function Rows({ nodes, depth, props }: { {directory ? : } {node.name} + {threads > 0 && {threads}} {node.kind === 'file' && } 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 f664c4b2fa..23452bbc00 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -333,6 +333,7 @@ } .body { + position: relative; display: flex; flex: 1; min-height: 0; @@ -813,3 +814,60 @@ .code[data-single-side]:not([data-wrap]) .line { grid-template-columns: var(--forge-number-width) 1.4em max-content; } .reviewFile { padding: 12px 0; } .reviewFile > h3 { margin: 0 10px; font-size: 12px; font-weight: 500; overflow-wrap: anywhere; } + +/* The unresolved thread count of a file opens the thread list at the file. */ +.threadCount { + flex: none; + height: 20px; + padding: 0 6px; + border: 0; + border-radius: var(--dsw-radius-xs); + background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 12%, transparent); + color: var(--dsw-alias-state-business-primary); + font: inherit; + font-size: 11px; + line-height: 20px; + white-space: nowrap; + cursor: pointer; +} + +.threadCount:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} + +@media (hover: hover) { + .threadCount:hover { background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 20%, transparent); } +} + +/* Opens the thread list; pressed while the list shows. */ +.threadsToggle { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + height: 28px; + padding: 0 8px; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + white-space: nowrap; + cursor: pointer; +} + +.threadsToggle[aria-pressed='true'] { background: var(--dsw-alias-interactive-bg-hover); } + +@media (hover: hover) { + .threadsToggle:hover { background: var(--dsw-alias-interactive-bg-hover); } +} + +.threadsTotal { + padding: 0 5px; + border-radius: var(--dsw-radius-xs); + background: var(--forge-fill); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 16px; +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index f57bb937bb..5763304362 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -27,7 +27,9 @@ import type { ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' -import type { ForgeCommitList, ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' +import type { + ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, +} 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' @@ -47,6 +49,10 @@ import { drawnLines, matchesHunks, textLines } from './diff-rows.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import { RefreshGlyph } from './RefreshGlyph.tsx' +import type { FileThreads, ThreadActions, ThreadFocus } from './ReviewThreads.tsx' +import type { ThreadFilter } from './review-threads.ts' +import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts' +import { ThreadList } from './ThreadList.tsx' import type { PanelSnapshot } from './source.ts' import { numberOf, openChangeRequestOf, TONE_LABEL, toneOf } from './status.ts' import css from './ChangesTab.module.css' @@ -86,6 +92,10 @@ export interface ChangesTabInjected { readonly viewedFiles: ViewedFiles /** Read one file of a change request at a commit. */ readonly changeRequestText: (url: string, commit: string, path: string) => Promise> + /** Read the review threads of a change request at the head of its latest status; `signal` aborts the read. */ + readonly changeRequestReview: (url: string, headSha: string, signal: AbortSignal) => Promise> + /** Quote a whole review thread of the change request at `url` in the main input without submitting it. */ + readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean /** Open a URL outside the app. */ readonly openLink: (url: string) => void /** Copy a path to the clipboard and report the outcome. */ @@ -423,8 +433,8 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { */ export function ChangesTab({ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, - changeRequestText, changeRequestCommits, viewedFiles, - openLink, copyPath, createChangeRequest, addReviewToInput, reviewQueue, submitReview, report, t, + changeRequestText, changeRequestCommits, changeRequestReview, viewedFiles, + openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() const { navigation, signal } = tab @@ -560,6 +570,22 @@ export function ChangesTab({ return () => { controller.abort() } }, [tab.visible, read, refused, waiting, source, localScope, changeCommits, dataKey, localDiff, changeRequestDiff]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null + // Threads show only while they were read at the head of the latest status and, for the whole change request, at + // the head the shown diff was read at, so their positions number the shown files. + const prHead = entry?.snapshot?.headSha ?? null + const prAuthor = entry?.snapshot?.author ?? null + const threadRead = useThreadRead({ visible: tab.visible, url: source.kind === 'change' ? source.url : null, head: prHead, + updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, read: changeRequestReview }) + const review = data?.kind === 'change' && threadRead.review !== null && threadRead.review.headSha === prHead + && (data.commits !== null || data.headSha === prHead) ? threadRead.review : null + const placed = usePlacedThreads(review, data?.kind === 'change' ? { head: prHead ?? '', end: data.headSha, commits: data.commits } : null) + const [threadList, setThreadList] = useState<{ + readonly open: boolean + readonly filter: ThreadFilter | null + /** File whose group the list scrolls to, or null. */ + readonly file: string | null + }>({ open: false, filter: 'unresolved', file: null }) + const [focus, setFocus] = useState(null) const allFiles = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests)), [allFiles, lens, hideTests]) const lensCounts = useMemo(() => Object.fromEntries(LENSES.map(item => [item, @@ -594,10 +620,16 @@ export function ChangesTab({ if (hideTests && hidden.layer === 'test') actions.toggledTests(tab.id) return } - sections.current.get(wanted)?.scrollIntoView({ block: 'start' }) + const section = sections.current.get(wanted) + section?.scrollIntoView({ block: 'start' }) + // A thread the reader opened from the thread list centers inside its file, which the jump expanded and revealed. + /* v8 ignore next 2 -- a focused thread's file is drawn and its card unfolded, so both are found. */ + const card = focus === null ? undefined : [...section?.querySelectorAll('[data-forge-thread]') ?? []] + .find(element => element.dataset.forgeThread === focus.id) + card?.scrollIntoView({ block: 'center' }) if (scrollport.current !== null) jumpPosition.current = { data, top: scrollport.current.scrollTop } setWanted(null) - }, [tab.visible, wanted, data, allFiles, lens, hideTests, actions, tab.id]) + }, [tab.visible, wanted, data, allFiles, lens, hideTests, actions, tab.id, focus]) 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. @@ -676,6 +708,32 @@ export function ChangesTab({ .filter(path => !data?.files.some(file => file.path === path)) const orphanRecords = absentPaths.map(path => ) + const threadActions: ThreadActions | null = review === null || data?.kind !== 'change' ? null : { + viewer: review.viewer, + author: prAuthor, + addToInput: (thread, range) => addThreadToInput(thread, data.url, range), + openLink, + readText: (commit, path) => changeRequestText(data.url, commit, path), + inputFailed: () => { report('thread.inputFailed') }, + focused: focus, + } + const threadsOf = (path: string): FileThreads | undefined => { + const group = placed.files.get(path) + return threadActions === null || group === undefined ? undefined + : { ...group, actions: threadActions, openList: () => { setThreadList(value => ({ ...value, open: true, file: path })) } } + } + /** Show a thread from the list: all commits for a thread the chosen ones do not hold, then its file, unfolded and centered. */ + const openThread = ({ thread, place }: PlacedThread): void => { + const url = thread.comments[0]?.url ?? null + if (!allFiles.some(file => file.path === thread.path)) { + if (url !== null) openLink(url) + return + } + if (place.kind === 'elsewhere') actions.committed(tab.id, null) + setFocus(value => ({ id: thread.id, revision: (value?.revision ?? 0) + 1 })) + setRevealed(value => new Set([...value, thread.path])) + jump(thread.path) + } const jump = (path: string): void => { setTreeState(value => ({ ...value, selected: path })) setChosen(value => ({ ...value, [path]: true })) @@ -820,6 +878,7 @@ export function ChangesTab({ badge={badgeOf(file, data, t)} tooltip={pathTooltipOf(file, t)} actions={fileActions(data, file)} + threads={threadsOf(path)} viewed={viewedStateOf(marks, path, file.digest)} onViewed={(viewed) => { markViewed(data, file, viewed) }} sectionRef={(element) => { @@ -839,6 +898,7 @@ export function ChangesTab({ filter: (query) => { setTreeState(value => ({ ...value, query })) }, toggle: (path) => { setTreeState(value => ({ ...value, collapsed: { ...value.collapsed, [path]: value.collapsed[path] !== true } })) }, jump, + ...review === null ? {} : { threadCounts: placed.unresolved }, } // The toolbar collapses every file while any is expanded, as the files on screen show, and expands every file otherwise. const anyExpanded = files.some(isExpanded) @@ -887,6 +947,13 @@ export function ChangesTab({
) diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index ad46c66132..0e7c561125 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -18,6 +18,8 @@ import { segmentsOf, splitRows, type DiffRow, type SplitCell, type SplitRow } fr import { codeSideAt, readCodeSelection } from './code-selection.ts' import { reviewMatches, selectReviewLines, type ReviewSelection } from './review.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' +import { OutdatedThreads, ThreadCard, type FileThreads, type LineThread, type ThreadActions } from './ReviewThreads.tsx' +import { gapOf } from './review-threads.ts' import type { FileReviewState } from './review-queue.ts' import { ReviewComposer, type ReviewActions } from './ReviewComposer.tsx' import reviewCss from './ReviewComposer.module.css' @@ -77,6 +79,8 @@ export interface DiffFileProps { readonly viewed: ViewedState /** Mark the file viewed, which also collapses it, or clear the mark. */ readonly onViewed: (viewed: boolean) => void + /** Review threads of the file from the code host, or undefined while none are read. */ + readonly threads?: FileThreads | undefined /** Receives the section element, which scrolling to the file targets. */ readonly sectionRef: (element: HTMLElement | null) => void /** Forge panel copy. */ @@ -144,8 +148,8 @@ function pairKind(pair: SplitRow): 'context' | 'change' { } /** The hunks of one file with their collapsed and expanded unchanged lines. */ -function Lines({ file, text, open, onExpand, split, wrap, review, visible, comments, t }: Pick & { readonly comments: FileReviewState }): ReactNode { +function Lines({ file, text, open, onExpand, split, wrap, review, visible, comments, threads, t }: Pick & { readonly comments: FileReviewState }): ReactNode { const lines = typeof text === 'object' ? text : undefined const columns = split && file.additions > 0 && file.deletions > 0 const singleSide = file.status === 'added' ? 'R' : file.status === 'deleted' ? 'L' : null @@ -313,6 +317,17 @@ function Lines({ file, text, open, onExpand, split, wrap, review, visible, comme remaining.delete(thread) } } + // A host thread follows the row of its last line, or the collapsed unchanged lines that hold it. + const unplaced = new Set(threads === undefined ? [] : threads.lines.map(item => ({ ...item, actions: threads.actions }))) + const threadCard = (item: LineThread & { readonly actions: ThreadActions }, columns: boolean): ReactNode => + + const appendThreads = (old: number | null, next: number | null): void => { + for (const item of unplaced) { + if ((item.place.side === 'L' ? old : next) !== item.place.endLine) continue + rows.push(threadCard(item, columns)) + unplaced.delete(item) + } + } const endsAt = (old: number | null, next: number | null): boolean => selection !== null && (selection.comment.side === 'L' ? old : next) === selection.comment.endLine for (const [at, segment] of prepared.entries()) { @@ -322,6 +337,11 @@ function Lines({ file, text, open, onExpand, split, wrap, review, visible, comme {segment.count === null ? t('diff.unchangedRest') : t('diff.unchanged', { count: segment.count.toLocaleString('en-US') })} ) + for (const item of unplaced) { + if (gapOf(file, item.place.side, item.place.endLine) !== segment.index) continue + rows.push(threadCard(item, columns)) + unplaced.delete(item) + } } else if (columns) { for (const [index, pair] of splitRows(segment.rows).entries()) { rows.push(
) } + for (const item of unplaced) rows.push(threadCard(item, false)) if (!inserted) rows.push(editor) return
{rows}
} -function Body(props: DiffFileProps): ReactNode { - const { file, large, revealed, onReveal, review, t } = props +/** The file's lines or the note that replaces them, with its saved comments; host threads on lines follow when no lines show. */ +function Content(props: DiffFileProps): ReactNode { + const { file, large, revealed, onReveal, review, threads, t } = props const comments = useFileReview(review, file.path) const records = review === undefined ? null : comments.threads.map(thread => ) - if (file.binary) return <>

{t('diff.binary')}

{records} - if (file.oversized) return <>

{t('diff.fileTooLarge')}

{records} - if (file.hunks.length === 0) return records + const lineThreads = threads?.lines.map(item => ) + if (file.binary) return <>

{t('diff.binary')}

{records}{lineThreads} + if (file.oversized) return <>

{t('diff.fileTooLarge')}

{records}{lineThreads} + if (file.hunks.length === 0) return <>{records}{lineThreads} if (large && !revealed) { // A large file starts as one collapsed strip, drawn and opened like the collapsed unchanged lines. return ( <>{records} + {records}{lineThreads} ) } return } +/** Host threads on the whole file, the lines, then the host threads that later commits made outdated. */ +function Body(props: DiffFileProps): ReactNode { + const { threads, t } = props + return <> + {threads?.file.map(thread => )} + + {threads !== undefined && } + +} + /** File actions live only while their owning tab is visible. */ function FileMenu({ name, actions, t }: { readonly name: string @@ -443,7 +479,7 @@ function FileMenu({ name, actions, t }: { * @returns the file section. */ export function DiffFile(props: DiffFileProps): ReactNode { - const { file, expanded, onToggle, badge, tooltip, actions, viewed, onViewed, sectionRef, t } = props + const { file, expanded, onToggle, badge, tooltip, actions, viewed, onViewed, threads, sectionRef, t } = props const name = file.path.slice(file.path.lastIndexOf('/') + 1) return (
{viewed === 'changed' && {t('viewed.changed')}} + {threads !== undefined && threads.unresolved > 0 && ( + + )} {badge !== '' && {badge}} {!file.binary && } diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css new file mode 100644 index 0000000000..00ed916016 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css @@ -0,0 +1,219 @@ +/* Review thread cards share the inline review form's card material; comment rows follow the conversation's 13px detail size. */ +.card, +.folded { + box-sizing: border-box; + width: calc(100% - 20px); + max-width: 720px; + margin: 10px; + border: 0.5px solid var(--dsw-alias-border-l3); + border-radius: var(--dsw-radius-md); + background: var(--dsw-alias-bg-layer-1); + color: var(--dsw-alias-label-primary); + font: var(--dsw-font-xs-13); + font-family: Inter, var(--dsw-font-family); + white-space: normal; +} + +.card { padding: 10px 12px; } + +.card[data-split][data-side="R"], +.folded[data-split][data-side="R"] { + margin-inline-start: clamp(10px, calc(100% - 740px), calc(50% + 10px)); +} + +.card[data-resolved] { background: var(--dsw-alias-bg-layer-2); } + +.folded { + display: flex; + align-items: center; + gap: 6px; + min-height: 32px; + padding: 4px 12px; + color: var(--dsw-alias-label-secondary); +} + +.folded > svg { flex: none; color: var(--dsw-alias-state-success-primary); } + +.foldedText { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-bottom: 8px; +} + +.place { + min-width: 0; + color: var(--dsw-alias-label-secondary); + font-size: 12px; + overflow-wrap: anywhere; +} + +.spacer { flex: 1; } + +/* Text actions inside a card: no fill, accent ink, the same height as the tags beside them. */ +.link { + display: inline-flex; + flex: none; + align-items: center; + gap: 2px; + padding: 0; + border: 0; + background: transparent; + color: var(--dsw-alias-state-business-primary); + font: inherit; + font-size: 12px; + cursor: pointer; +} + +.link:disabled { color: var(--dsw-alias-label-dimmed); cursor: default; } + +.link:focus-visible { + border-radius: var(--dsw-radius-xs); + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 2px; +} + +@media (hover: hover) { + .link:not(:disabled):hover { text-decoration: underline; } +} + +.turned { transform: rotate(-90deg); } + +.comments { + display: flex; + flex-direction: column; + gap: 12px; +} + +.comment { + display: flex; + gap: 8px; + min-width: 0; +} + +.avatar { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + overflow: hidden; + border-radius: 50%; + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-secondary); + font-weight: 500; + line-height: 1; + user-select: none; +} + +.avatar img { + display: block; + width: 100%; + height: 100%; + border-radius: 50%; + object-fit: cover; +} + +.commentMain { + flex: 1; + min-width: 0; +} + +.commentHeader { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + min-height: 20px; +} + +.login { font-weight: 500; overflow-wrap: anywhere; } + +.time { color: var(--dsw-alias-label-tertiary); font-size: 12px; } + +.body { + min-width: 0; + margin-top: 2px; + overflow-wrap: anywhere; +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin: 10px -8px -4px; +} + +/* The end of the recorded hunk, drawn like the diff rows it came from. */ +.excerpt, +.original { + margin-bottom: 10px; + overflow-x: auto; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: var(--dsw-radius-sm); + font: var(--dsw-font-markdown-code-block); +} + +.excerptLine, +.originalLine { + min-height: 20px; + padding: 0 10px; + line-height: 20px; + white-space: pre; +} + +.excerptHeader { color: var(--dsw-alias-label-tertiary); } + +.added { background: var(--dsw-alias-file-diff-added-bg); } + +.deleted { background: var(--dsw-alias-file-diff-deleted-bg); } + +.original { + max-height: 320px; + overflow: auto; +} + +.originalLine { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 12px; +} + +.originalNumber { + min-width: 3ch; + color: var(--dsw-alias-label-tertiary); + text-align: right; + user-select: none; +} + +.marked { background: var(--dsw-alias-interactive-bg-hover); } + +.originalNote { + padding: 8px 10px; + color: var(--dsw-alias-label-secondary); + font-family: Inter, var(--dsw-font-family); +} + +/* Outdated threads of one file, after its lines. */ +.outdated { + border-top: 0.5px solid var(--dsw-alias-border-l3); + padding-bottom: 2px; +} + +.outdatedHeader { + display: flex; + align-items: center; + gap: 6px; + min-height: 32px; + padding: 0 12px; + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xs-13); + font-family: Inter, var(--dsw-font-family); +} diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx b/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx new file mode 100644 index 0000000000..2ba58c24c3 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx @@ -0,0 +1,265 @@ +/** + * Read-only review threads of a change request inside the changes view: a thread card at its lines or at the top of + * its file, a resolved thread folded into one row, and the outdated threads of a file in a section after its lines. + */ + +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconRightUpOutlineRegular, MarkdownText, Tag, type MarkdownLabels, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ForgeReviewComment, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { formatAgo } from './format.ts' +import { anchorRange, hunkExcerpt, type ThreadPlace } from './review-threads.ts' +import type { NS } from './locales.ts' +import css from './ReviewThreads.module.css' + +type Translate = PropsLocale['t'] + +/** Reads, actions, and identities every thread card of one changes view shares. */ +export interface ThreadActions { + /** Login of the signed-in user, or null when the host names none. */ + readonly viewer: string | null + /** Login of the change request's author, or null when the host hides it. */ + readonly author: string | null + /** Quote the whole thread in the main input without sending it; false when the input refused it. */ + readonly addToInput: (thread: ForgeReviewThread, range: string | null) => boolean + /** Open a URL outside the app. */ + readonly openLink: (url: string) => void + /** Read a file of the change request's repository at a commit. */ + readonly readText: (commit: string, path: string) => Promise> + /** Report that the input refused a thread. */ + readonly inputFailed: () => void + /** The latest jump to a thread, which unfolds that thread and its section until the reader folds them again; null before any. */ + readonly focused: ThreadFocus | null +} + +/** One jump to a thread; each jump has its own revision, so a jump to the same thread unfolds it again. */ +export interface ThreadFocus { + readonly id: ForgeThreadId + readonly revision: number +} + +/** A host thread shown on lines of one side. */ +export interface LineThread { + readonly thread: ForgeReviewThread + readonly place: Extract +} + +/** Host threads of one file and how its section reaches them. */ +export interface FileThreads { + /** Threads on lines, which follow the row of their last line. */ + readonly lines: readonly LineThread[] + /** Threads on the whole file, shown above its lines. */ + readonly file: readonly ForgeReviewThread[] + /** Threads no longer on the head's lines, shown after them. */ + readonly outdated: readonly ForgeReviewThread[] + /** Unresolved threads of the file in every place, including threads the chosen commits do not show. */ + readonly unresolved: number + /** Reads, actions, and identities shared by the cards. */ + readonly actions: ThreadActions + /** Open the thread list at this file. */ + readonly openList: () => void +} + +/** The commit a thread was written on, abbreviated, or null for a file thread. */ +function writtenOn(thread: ForgeReviewThread): string | null { + return thread.original === null ? null : thread.original.commit.slice(0, 7) +} + +/** + * Build the Markdown chrome copy of comment bodies. + * @param t - forge panel copy. + * @returns labels for code fences and footnotes. + */ +export function useMarkdownLabels(t: Translate): MarkdownLabels { + return useMemo(() => ({ + code: { copyLabel: t('thread.copy'), copiedLabel: t('thread.copied'), + toolbarLabels: { codeLabel: t('thread.codeBlock'), wrapLabel: t('thread.wrap'), unwrapLabel: t('thread.unwrap') } }, + footnotes: t('thread.footnotes'), + }), [t]) +} + +/** + * Render an author's avatar, or the first letter of the login when the image is missing or fails. + * @param props - the comment's author and the avatar size. + * @returns the round avatar. + */ +export function Avatar({ author, size = 20 }: { readonly author: ForgeReviewComment['author']; readonly size?: number }): ReactNode { + const [failed, setFailed] = useState(false) + const login = author?.login ?? '?' + return +} + +function Comment({ comment, actions, labels, now, t }: { + readonly comment: ForgeReviewComment + readonly actions: ThreadActions + readonly labels: MarkdownLabels + readonly now: number + readonly t: Translate +}): ReactNode { + const login = comment.author?.login ?? null + return
+ +
+
+ {login ?? t('thread.deletedAuthor')} + {formatAgo(comment.createdAt, now, t) ?? comment.createdAt} + {login !== null && login === actions.author && {t('thread.author')}} + {comment.author?.bot === true && {t('thread.bot')}} + {comment.pending && {t('review.pending')}} +
+ {/* Raw HTML renders nothing, as GitHub hides comments and unknown tags, and never enters the DOM. */} +
+
+
+} + +/** + * Render one thread: its place, every comment, and the read-only actions. A resolved thread folds into one row + * until the reader unfolds it or jumps to it. + * @param props - the thread, where it shows, the shared actions, the layout, and copy. + * @returns the thread card or its folded row. + */ +export function ThreadCard({ thread, place, actions, split = false, t }: PropsLocale & { + readonly thread: ForgeReviewThread + readonly place: ThreadPlace + readonly actions: ThreadActions + /** Whether the card sits under the side of a side-by-side row that its lines number. */ + readonly split?: boolean +}): ReactNode { + const [open, setOpen] = useState(false) + // The jump the reader folded the thread after, which no longer unfolds it. + const [foldedAt, setFoldedAt] = useState(null) + const labels = useMarkdownLabels(t) + const now = Date.now() + const focused = actions.focused?.id === thread.id && actions.focused.revision !== foldedAt + const unfolded = open || !thread.resolved || focused + const side = place.kind === 'line' ? place.side : thread.side + const range = place.kind === 'line' ? anchorRange(place.side, place) : null + const commit = writtenOn(thread) + const first = thread.comments[0] + const url = first?.url ?? null + if (!unfolded) { + return
+ + {t('thread.resolvedRow', { author: first?.author?.login ?? t('thread.deletedAuthor') })} + +
+ } + const original = place.kind === 'outdated' && thread.original !== null ? thread.original : null + return
+
+ + {original !== null ? t('thread.originally', { range: anchorRange(thread.side, original) }) + : range ?? t('thread.fileLevel')} + {commit !== null && <> · {t('thread.onCommit', { commit })}} + + {place.kind === 'outdated' && {t('thread.outdatedTag')}} + {thread.resolved && {t('thread.filter.resolved')}} + + {thread.resolved && } + {original !== null && thread.side === 'R' && } +
+ {place.kind === 'outdated' && thread.diffHunk !== null && original !== null + && } +
+ {thread.comments.map(comment => )} +
+
+ + {url !== null && } +
+
+} + +/** The end of a recorded diff hunk: the lines a thread was written on and a few before them. */ +function Excerpt({ hunk, side, lines }: { readonly hunk: string; readonly side: 'L' | 'R'; readonly lines: number }): ReactNode { + const excerpt = hunkExcerpt(hunk, side, lines) + return
+ {excerpt.header !== null &&
{excerpt.header}
} + {excerpt.lines.map((line, index) =>
{line}
)} +
+} + +/** + * Show the whole file at the commit a thread was written on, with the thread's lines marked, under the thread header. + * Only a new-side thread offers it: its lines number that commit's file. + */ +function OriginalFile({ thread, commit, actions, t }: PropsLocale & { + readonly thread: ForgeReviewThread + readonly commit: string + readonly actions: ThreadActions +}): ReactNode { + const [state, setState] = useState<{ readonly lines: readonly string[] } | 'closed' | 'loading' | { readonly failed: string }>('closed') + const marked = useRef(null) + useEffect(() => { marked.current?.scrollIntoView({ block: 'center' }) }, [state]) + const toggle = (): void => { + if (state !== 'closed' && state !== 'loading') { setState('closed'); return } + setState('loading') + void actions.readText(commit, thread.path).then((result) => { + setState(result.ok ? { lines: result.value.split('\n') } : { failed: result.error.message }) + }) + } + const open = state !== 'closed' + const range = thread.original + return <> + + {open &&
+ {state === 'loading' ?
{t('thread.originalLoading')}
+ : 'failed' in state ?
{t('thread.originalFailed', { message: state.failed })}
+ : state.lines.map((line, index) => { + const number = index + 1 + const inside = range !== null && number >= range.startLine && number <= range.endLine + return
+ {number}{line} +
+ })} +
} + +} + +/** + * Render the outdated threads of a file after its lines, as one section the reader can fold. + * @param props - the threads, the shared actions, and copy. + * @returns the section, or nothing without outdated threads. + */ +export function OutdatedThreads({ threads, actions, t }: PropsLocale & { + readonly threads: readonly ForgeReviewThread[] + readonly actions: ThreadActions +}): ReactNode { + // The section is folded after the jump with this revision, or -1 before any jump, or null while unfolded. + const [folded, setFolded] = useState(null) + if (threads.length === 0) return null + const jump = actions.focused + const open = folded === null || (jump !== null && jump.revision !== folded && threads.some(thread => thread.id === jump.id)) + return
+
+ {t('thread.outdatedSection', { count: threads.length })} + + +
+ {open && threads.map(thread => )} +
+} diff --git a/packages/experimental/client-ui-forge/src/client/ThreadList.module.css b/packages/experimental/client-ui-forge/src/client/ThreadList.module.css new file mode 100644 index 0000000000..c38bf4b549 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ThreadList.module.css @@ -0,0 +1,168 @@ +/* The thread list docks at the end of the changes body on wide panes and floats over the files on narrow ones. */ +.pane { + display: flex; + flex: none; + flex-direction: column; + box-sizing: border-box; + width: 320px; + min-height: 0; + border-inline-start: 0.5px solid var(--dsw-alias-border-l3); + background: var(--forge-changes-bg, var(--dsw-alias-bg-base)); + color: var(--dsw-alias-label-primary); + font: var(--dsw-font-xs-13); + font-family: Inter, var(--dsw-font-family); +} + +@container forge-changes (max-width: 759px) { + .pane { + position: absolute; + z-index: 3; + inset-block: 0; + inset-inline-end: 0; + width: min(320px, 100%); + box-shadow: var(--dsw-shadow-l2, 0 4px 16px rgb(0 0 0 / 12%)); + } +} + +.header { + display: flex; + align-items: center; + gap: 6px; + min-height: 40px; + padding: 0 6px 0 12px; +} + +.title { font-weight: 500; } + +.total { + padding: 0 6px; + border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-card-fill); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 18px; +} + +.spacer { flex: 1; } + +.close { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +@media (hover: hover) { + .close:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } +} + +.filters { + display: flex; + flex-wrap: wrap; + gap: 6px; + padding: 0 12px 10px; + border-bottom: 0.5px solid var(--dsw-alias-border-l3); +} + +.rows { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 4px 6px; +} + +.group + .group { margin-top: 6px; } + +.path { + margin: 0; + padding: 8px 6px 4px; + overflow: hidden; + color: var(--dsw-alias-label-secondary); + font: inherit; + font-size: 12px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.item { + display: flex; + gap: 8px; + box-sizing: border-box; + width: 100%; + padding: 8px 6px; + border: 0; + border-radius: var(--dsw-radius-md); + background: transparent; + color: inherit; + font: inherit; + text-align: start; + cursor: pointer; +} + +@media (hover: hover) { + .item:hover { background: var(--dsw-alias-interactive-bg-hover); } +} + +.item:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -1px; +} + +.itemMain { + display: flex; + flex: 1; + flex-direction: column; + gap: 2px; + min-width: 0; +} + +.meta { color: var(--dsw-alias-label-tertiary); font-size: 12px; } + +.excerpt { + display: -webkit-box; + overflow: hidden; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow-wrap: anywhere; +} + +.tags { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.tags:empty { display: none; } + +.note { + padding: 24px 12px; + color: var(--dsw-alias-label-secondary); + text-align: center; +} + +.footer { + padding: 10px 12px; + border-top: 0.5px solid var(--dsw-alias-border-l3); + color: var(--dsw-alias-label-secondary); + font-size: 12px; +} + +.link { + padding: 0; + border: 0; + background: transparent; + color: var(--dsw-alias-state-business-primary); + font: inherit; + cursor: pointer; +} + +@media (hover: hover) { + .link:hover { text-decoration: underline; } +} diff --git a/packages/experimental/client-ui-forge/src/client/ThreadList.tsx b/packages/experimental/client-ui-forge/src/client/ThreadList.tsx new file mode 100644 index 0000000000..66a968c788 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ThreadList.tsx @@ -0,0 +1,163 @@ +/** + * The thread list of a change request beside its changes: every thread grouped by file in file tree order, narrowed + * by one filter, each opening the place it shows at. + */ + +import { useLayoutEffect, useMemo, useRef, type ReactNode } from 'react' +import { IconCloseOutlineRegular, Pill, Tag, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { Avatar } from './ReviewThreads.tsx' +import { anchorRange, awaitsViewer, passesFilter, THREAD_FILTERS, type ThreadFilter, type ThreadPlace } from './review-threads.ts' +import type { NS } from './locales.ts' +import type { PlacedThread } from './thread-state.ts' +import css from './ThreadList.module.css' + +type Translate = PropsLocale['t'] + +/** Props of the thread list. */ +export interface ThreadListProps extends PropsLocale { + /** Every thread read, in host order, with where the current changes show it. */ + readonly entries: readonly PlacedThread[] + /** Changed file paths in file tree order; threads on other paths follow them. */ + readonly order: readonly string[] + /** Login of the signed-in user. */ + readonly viewer: string | null + /** Whether the host has more threads than were read. */ + readonly truncated: boolean + /** Host name the threads were read from, such as `github.com`. */ + readonly host: string + /** Web page of the change request. */ + readonly url: string + /** The active filter, or null for every thread. */ + readonly filter: ThreadFilter | null + /** Choose a filter, or null for every thread. */ + readonly choose: (filter: ThreadFilter | null) => void + /** File whose group the list scrolls to when it changes, or null. */ + readonly file: string | null + /** Open the place of a thread. */ + readonly open: (entry: PlacedThread) => void + /** Open a URL outside the app. */ + readonly openLink: (url: string) => void + /** Close the list. */ + readonly close: () => void +} + +/** Sort key of a thread inside its file: file threads first, then by first line, outdated and elsewhere last. */ +function rank(place: ThreadPlace): number { + switch (place.kind) { + case 'file': return -1 + case 'line': return place.startLine + case 'outdated': + case 'elsewhere': return Number.MAX_SAFE_INTEGER + /* v8 ignore next -- closed ThreadPlace union exhaustiveness guard */ + default: return assertNever(place, 'ThreadPlace') + } +} + +function meta(thread: ForgeReviewThread, place: ThreadPlace, t: Translate): string { + const replies = thread.comments.length - 1 + const parts: string[] = [] + if (thread.subject === 'file') parts.push(t('thread.fileLevel')) + else if (place.kind === 'line') parts.push(anchorRange(place.side, place)) + else if (thread.original !== null) { + parts.push(t('thread.originally', { range: anchorRange(thread.side, thread.original) }), t('thread.onCommit', { commit: thread.original.commit.slice(0, 7) })) + } + if (replies > 0) parts.push(t('thread.replies', { count: replies })) + return parts.join(' · ') +} + +/** + * The first comment as one line of plain text: without raw HTML, strong, strikethrough, and code marks, quote or + * heading marks, and link targets. + */ +function plainExcerpt(body: string): string { + return body.replace(/<[^>]*>/g, ' ').replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/^\s*(?:#{1,6}|>)\s*/gm, '') + .replace(/\*\*|__|~~|`/g, '').replace(/\s+/g, ' ').trim() +} + +function Item({ entry, viewer, open, t }: { + readonly entry: PlacedThread + readonly viewer: string | null + readonly open: (entry: PlacedThread) => void + readonly t: Translate +}): ReactNode { + const { thread, place } = entry + const first = thread.comments[0] + return +} + +/** + * Render the thread list. + * @param props - threads, their places, the file order, the filter, and the list's actions. + * @returns the list pane. + */ +export function ThreadList(props: ThreadListProps): ReactNode { + const { entries, order, viewer, filter, t } = props + const threads = useMemo(() => entries.map(entry => entry.thread), [entries]) + const counts = useMemo(() => Object.fromEntries(THREAD_FILTERS.map(item => [item, + threads.filter(thread => passesFilter(thread, item, viewer)).length])) as Record, [threads, viewer]) + const groups = useMemo(() => { + const position = new Map(order.map((path, index) => [path, index])) + const byPath = new Map() + for (const entry of entries) { + if (!passesFilter(entry.thread, filter, viewer)) continue + const list = byPath.get(entry.thread.path) + if (list === undefined) byPath.set(entry.thread.path, [entry]) + else list.push(entry) + } + return [...byPath].sort(([a], [b]) => (position.get(a) ?? order.length) - (position.get(b) ?? order.length) || a.localeCompare(b)) + .map(([path, list]) => [path, list.toSorted((a, b) => rank(a.place) - rank(b.place))] as const) + }, [entries, order, filter, viewer]) + const rows = useRef(null) + useLayoutEffect(() => { + const container = rows.current + /* v8 ignore next -- the ref is attached before layout effects run. */ + if (props.file === null || container === null) return + for (const group of container.querySelectorAll('[data-forge-thread-group]')) { + if (group.dataset.forgeThreadGroup === props.file) group.scrollIntoView({ block: 'start' }) + } + }, [props.file]) + return +} diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index 81cb739802..96955093d2 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -308,6 +308,48 @@ export const zh = { 'toast.expandStale': '文件在读取变更后又有修改,刷新后再展开', 'toast.prompted': '已发送:{text}', 'toast.promptFailed': '无法发送消息', + 'thread.list': '讨论', + 'thread.listAria': '讨论列表,共 {count} 个', + 'thread.close': '关闭讨论列表', + 'thread.filterAria': '筛选讨论', + 'thread.filter.unresolved': '未解决', + 'thread.filter.outdated': '已过期', + 'thread.filter.resolved': '已解决', + 'thread.filter.mine': '需要我回复', + 'thread.none': '没有符合筛选条件的讨论', + 'thread.empty': '还没有评审讨论', + 'thread.total': '{host} 上共 {count} 个讨论', + 'thread.truncated': '讨论太多,只显示了前 {count} 个', + 'thread.openAll': '在 GitHub 中查看', + 'thread.replies': '{count} 条回复', + 'thread.fileLevel': '文件级讨论', + 'thread.onCommit': '在 {commit} 上', + 'thread.originally': '原在 {range}', + 'thread.outdatedTag': '已过期', + 'thread.elsewhereTag': '不在所选提交中', + 'thread.author': '作者', + 'thread.bot': 'bot', + 'thread.deletedAuthor': '已删除的账号', + 'thread.resolvedRow': '已解决的讨论 · {author}', + 'thread.expand': '展开', + 'thread.collapse': '收起', + 'thread.outdatedSection': '{count} 条讨论已过期:所在代码已被后续提交修改', + 'thread.viewOriginal': '查看当时的文件', + 'thread.hideOriginal': '收起当时的文件', + 'thread.originalLoading': '正在读取当时的文件…', + 'thread.originalFailed': '无法读取当时的文件:{message}', + 'thread.openOnHost': '在 GitHub 中查看', + 'thread.unresolvedCount': '{count} 条未解决', + 'thread.unresolvedAria': '{name} 有 {count} 条未解决的讨论,打开讨论列表', + 'thread.treeCount': '{count} 条未解决的讨论', + 'thread.loadFailed': '无法读取 GitHub 讨论:{message}', + 'thread.inputFailed': '输入框暂时无法添加这个讨论,请稍后重试', + 'thread.copy': '复制', + 'thread.copied': '复制成功', + 'thread.codeBlock': '代码块', + 'thread.wrap': '自动换行', + 'thread.unwrap': '取消自动换行', + 'thread.footnotes': '脚注', } as const /** Key of the forge panel dictionaries. */ @@ -618,6 +660,48 @@ export const en: Record = { 'toast.expandStale': 'The file changed after its changes were read; refresh before expanding', 'toast.prompted': 'Sent: {text}', 'toast.promptFailed': 'The message could not be sent', + 'thread.list': 'Threads', + 'thread.listAria': 'Review threads, {count} in total', + 'thread.close': 'Close the thread list', + 'thread.filterAria': 'Filter threads', + 'thread.filter.unresolved': 'Unresolved', + 'thread.filter.outdated': 'Outdated', + 'thread.filter.resolved': 'Resolved', + 'thread.filter.mine': 'Awaiting my reply', + 'thread.none': 'No threads match this filter', + 'thread.empty': 'No review threads yet', + 'thread.total': '{count} threads on {host}', + 'thread.truncated': 'Too many threads; showing the first {count}', + 'thread.openAll': 'View on GitHub', + 'thread.replies': '{count} replies', + 'thread.fileLevel': 'File thread', + 'thread.onCommit': 'on {commit}', + 'thread.originally': 'Originally {range}', + 'thread.outdatedTag': 'Outdated', + 'thread.elsewhereTag': 'Not in the chosen commits', + 'thread.author': 'Author', + 'thread.bot': 'bot', + 'thread.deletedAuthor': 'Deleted account', + 'thread.resolvedRow': 'Resolved thread · {author}', + 'thread.expand': 'Expand', + 'thread.collapse': 'Collapse', + 'thread.outdatedSection': '{count} outdated threads: later commits changed their code', + 'thread.viewOriginal': 'View file at that commit', + 'thread.hideOriginal': 'Hide file at that commit', + 'thread.originalLoading': 'Reading the file at that commit…', + 'thread.originalFailed': 'Could not read the file at that commit: {message}', + 'thread.openOnHost': 'View on GitHub', + 'thread.unresolvedCount': '{count} unresolved', + 'thread.unresolvedAria': '{name} has {count} unresolved threads; open the thread list', + 'thread.treeCount': '{count} unresolved threads', + 'thread.loadFailed': 'Could not read GitHub threads: {message}', + 'thread.inputFailed': 'The input could not take this thread; try again later', + 'thread.copy': 'Copy', + 'thread.copied': 'Copied', + 'thread.codeBlock': 'Code block', + 'thread.wrap': 'Wrap lines', + 'thread.unwrap': 'Do not wrap lines', + 'thread.footnotes': 'Footnotes', } declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -932,6 +1016,48 @@ export const ja: Record = { 'toast.expandStale': '変更の読み取り後にファイルが更新されています。更新してから展開してください', 'toast.prompted': '送信しました:{text}', 'toast.promptFailed': 'メッセージを送信できませんでした', + 'thread.list': 'スレッド', + 'thread.listAria': 'レビュースレッド(全 {count} 件)', + 'thread.close': 'スレッド一覧を閉じる', + 'thread.filterAria': 'スレッドを絞り込む', + 'thread.filter.unresolved': '未解決', + 'thread.filter.outdated': '古い', + 'thread.filter.resolved': '解決済み', + 'thread.filter.mine': '自分の返信待ち', + 'thread.none': 'この条件に一致するスレッドはありません', + 'thread.empty': 'レビュースレッドはまだありません', + 'thread.total': '{host} 上のスレッド {count} 件', + 'thread.truncated': 'スレッドが多いため、最初の {count} 件のみ表示しています', + 'thread.openAll': 'GitHub で表示', + 'thread.replies': '返信 {count} 件', + 'thread.fileLevel': 'ファイルへのスレッド', + 'thread.onCommit': '{commit} 上', + 'thread.originally': '元の位置 {range}', + 'thread.outdatedTag': '古い', + 'thread.elsewhereTag': '選択したコミットにない', + 'thread.author': '作成者', + 'thread.bot': 'bot', + 'thread.deletedAuthor': '削除されたアカウント', + 'thread.resolvedRow': '解決済みのスレッド · {author}', + 'thread.expand': '展開', + 'thread.collapse': '折りたたむ', + 'thread.outdatedSection': '古いスレッド {count} 件:後のコミットで該当コードが変更されました', + 'thread.viewOriginal': '当時のファイルを表示', + 'thread.hideOriginal': '当時のファイルを閉じる', + 'thread.originalLoading': '当時のファイルを読み込み中…', + 'thread.originalFailed': '当時のファイルを読み込めません:{message}', + 'thread.openOnHost': 'GitHub で表示', + 'thread.unresolvedCount': '未解決 {count} 件', + 'thread.unresolvedAria': '{name} に未解決のスレッドが {count} 件あります。スレッド一覧を開く', + 'thread.treeCount': '未解決のスレッド {count} 件', + 'thread.loadFailed': 'GitHub のスレッドを読み込めません:{message}', + 'thread.inputFailed': '入力欄にこのスレッドを追加できません。しばらくしてから再試行してください', + 'thread.copy': 'コピー', + 'thread.copied': 'コピーしました', + 'thread.codeBlock': 'コードブロック', + 'thread.wrap': '行を折り返す', + 'thread.unwrap': '行を折り返さない', + 'thread.footnotes': '脚注', } /** Spanish copy with the same keys. */ @@ -1239,6 +1365,48 @@ export const es: Record = { 'toast.expandStale': 'El archivo cambió después de leer sus cambios; actualiza antes de expandir', 'toast.prompted': 'Enviado: {text}', 'toast.promptFailed': 'No se pudo enviar el mensaje', + 'thread.list': 'Hilos', + 'thread.listAria': 'Hilos de revisión, {count} en total', + 'thread.close': 'Cerrar la lista de hilos', + 'thread.filterAria': 'Filtrar hilos', + 'thread.filter.unresolved': 'Sin resolver', + 'thread.filter.outdated': 'Desactualizados', + 'thread.filter.resolved': 'Resueltos', + 'thread.filter.mine': 'Esperan mi respuesta', + 'thread.none': 'Ningún hilo coincide con este filtro', + 'thread.empty': 'Aún no hay hilos de revisión', + 'thread.total': '{count} hilos en {host}', + 'thread.truncated': 'Hay demasiados hilos; se muestran los primeros {count}', + 'thread.openAll': 'Ver en GitHub', + 'thread.replies': '{count} respuestas', + 'thread.fileLevel': 'Hilo del archivo', + 'thread.onCommit': 'en {commit}', + 'thread.originally': 'Originalmente {range}', + 'thread.outdatedTag': 'Desactualizado', + 'thread.elsewhereTag': 'No está en los commits elegidos', + 'thread.author': 'Autor', + 'thread.bot': 'bot', + 'thread.deletedAuthor': 'Cuenta eliminada', + 'thread.resolvedRow': 'Hilo resuelto · {author}', + 'thread.expand': 'Expandir', + 'thread.collapse': 'Contraer', + 'thread.outdatedSection': '{count} hilos desactualizados: commits posteriores cambiaron su código', + 'thread.viewOriginal': 'Ver el archivo en ese commit', + 'thread.hideOriginal': 'Ocultar el archivo de ese commit', + 'thread.originalLoading': 'Leyendo el archivo de ese commit…', + 'thread.originalFailed': 'No se pudo leer el archivo de ese commit: {message}', + 'thread.openOnHost': 'Ver en GitHub', + 'thread.unresolvedCount': '{count} sin resolver', + 'thread.unresolvedAria': '{name} tiene {count} hilos sin resolver; abrir la lista de hilos', + 'thread.treeCount': '{count} hilos sin resolver', + 'thread.loadFailed': 'No se pudieron leer los hilos de GitHub: {message}', + 'thread.inputFailed': 'El campo de entrada no pudo recibir este hilo; inténtalo más tarde', + 'thread.copy': 'Copiar', + 'thread.copied': 'Copiado', + 'thread.codeBlock': 'Bloque de código', + 'thread.wrap': 'Ajustar líneas', + 'thread.unwrap': 'No ajustar líneas', + 'thread.footnotes': 'Notas a pie de página', } /** French copy with the same keys. */ @@ -1546,6 +1714,48 @@ export const fr: Record = { 'toast.expandStale': 'Le fichier a changé depuis la lecture des modifications ; actualisez avant de développer', 'toast.prompted': 'Envoyé : {text}', 'toast.promptFailed': 'Impossible d’envoyer le message', + 'thread.list': 'Fils', + 'thread.listAria': 'Fils de revue, {count} au total', + 'thread.close': 'Fermer la liste des fils', + 'thread.filterAria': 'Filtrer les fils', + 'thread.filter.unresolved': 'Non résolus', + 'thread.filter.outdated': 'Obsolètes', + 'thread.filter.resolved': 'Résolus', + 'thread.filter.mine': 'Attendent ma réponse', + 'thread.none': 'Aucun fil ne correspond à ce filtre', + 'thread.empty': 'Aucun fil de revue pour le moment', + 'thread.total': '{count} fils sur {host}', + 'thread.truncated': 'Trop de fils ; seuls les {count} premiers sont affichés', + 'thread.openAll': 'Voir sur GitHub', + 'thread.replies': '{count} réponses', + 'thread.fileLevel': 'Fil du fichier', + 'thread.onCommit': 'sur {commit}', + 'thread.originally': 'À l’origine {range}', + 'thread.outdatedTag': 'Obsolète', + 'thread.elsewhereTag': 'Hors des commits choisis', + 'thread.author': 'Auteur', + 'thread.bot': 'bot', + 'thread.deletedAuthor': 'Compte supprimé', + 'thread.resolvedRow': 'Fil résolu · {author}', + 'thread.expand': 'Développer', + 'thread.collapse': 'Réduire', + 'thread.outdatedSection': '{count} fils obsolètes : des commits ultérieurs ont modifié leur code', + 'thread.viewOriginal': 'Voir le fichier à ce commit', + 'thread.hideOriginal': 'Masquer le fichier à ce commit', + 'thread.originalLoading': 'Lecture du fichier à ce commit…', + 'thread.originalFailed': 'Impossible de lire le fichier à ce commit : {message}', + 'thread.openOnHost': 'Voir sur GitHub', + 'thread.unresolvedCount': '{count} non résolus', + 'thread.unresolvedAria': '{name} a {count} fils non résolus ; ouvrir la liste des fils', + 'thread.treeCount': '{count} fils non résolus', + 'thread.loadFailed': 'Impossible de lire les fils GitHub : {message}', + 'thread.inputFailed': 'Le champ de saisie n’a pas pu recevoir ce fil ; réessayez plus tard', + 'thread.copy': 'Copier', + 'thread.copied': 'Copié', + 'thread.codeBlock': 'Bloc de code', + 'thread.wrap': 'Activer le retour à la ligne', + 'thread.unwrap': 'Désactiver le retour à la ligne', + 'thread.footnotes': 'Notes de bas de page', } /** German copy with the same keys. */ @@ -1853,6 +2063,48 @@ export const de: Record = { 'toast.expandStale': 'Die Datei wurde nach dem Lesen der Änderungen verändert; vor dem Aufklappen aktualisieren', 'toast.prompted': 'Gesendet: {text}', 'toast.promptFailed': 'Nachricht konnte nicht gesendet werden', + 'thread.list': 'Threads', + 'thread.listAria': 'Review-Threads, insgesamt {count}', + 'thread.close': 'Threadliste schließen', + 'thread.filterAria': 'Threads filtern', + 'thread.filter.unresolved': 'Ungelöst', + 'thread.filter.outdated': 'Veraltet', + 'thread.filter.resolved': 'Gelöst', + 'thread.filter.mine': 'Warten auf meine Antwort', + 'thread.none': 'Keine Threads entsprechen diesem Filter', + 'thread.empty': 'Noch keine Review-Threads', + 'thread.total': '{count} Threads auf {host}', + 'thread.truncated': 'Zu viele Threads; die ersten {count} werden angezeigt', + 'thread.openAll': 'Auf GitHub ansehen', + 'thread.replies': '{count} Antworten', + 'thread.fileLevel': 'Thread zur Datei', + 'thread.onCommit': 'auf {commit}', + 'thread.originally': 'Ursprünglich {range}', + 'thread.outdatedTag': 'Veraltet', + 'thread.elsewhereTag': 'Nicht in den gewählten Commits', + 'thread.author': 'Autor', + 'thread.bot': 'Bot', + 'thread.deletedAuthor': 'Gelöschtes Konto', + 'thread.resolvedRow': 'Gelöster Thread · {author}', + 'thread.expand': 'Aufklappen', + 'thread.collapse': 'Zuklappen', + 'thread.outdatedSection': '{count} veraltete Threads: Spätere Commits haben ihren Code geändert', + 'thread.viewOriginal': 'Datei in diesem Commit ansehen', + 'thread.hideOriginal': 'Datei in diesem Commit ausblenden', + 'thread.originalLoading': 'Datei in diesem Commit wird gelesen…', + 'thread.originalFailed': 'Die Datei in diesem Commit konnte nicht gelesen werden: {message}', + 'thread.openOnHost': 'Auf GitHub ansehen', + 'thread.unresolvedCount': '{count} ungelöst', + 'thread.unresolvedAria': '{name} hat {count} ungelöste Threads; Threadliste öffnen', + 'thread.treeCount': '{count} ungelöste Threads', + 'thread.loadFailed': 'GitHub-Threads konnten nicht gelesen werden: {message}', + 'thread.inputFailed': 'Das Eingabefeld konnte diesen Thread nicht aufnehmen; später erneut versuchen', + 'thread.copy': 'Kopieren', + 'thread.copied': 'Kopiert', + 'thread.codeBlock': 'Codeblock', + 'thread.wrap': 'Zeilen umbrechen', + 'thread.unwrap': 'Zeilen nicht umbrechen', + 'thread.footnotes': 'Fußnoten', } /** Russian copy with the same keys. */ @@ -2160,6 +2412,48 @@ export const ru: Record = { 'toast.expandStale': 'Файл изменился после чтения изменений; обновите перед разворачиванием', 'toast.prompted': 'Отправлено: {text}', 'toast.promptFailed': 'Не удалось отправить сообщение', + 'thread.list': 'Обсуждения', + 'thread.listAria': 'Обсуждения ревью, всего {count}', + 'thread.close': 'Закрыть список обсуждений', + 'thread.filterAria': 'Фильтр обсуждений', + 'thread.filter.unresolved': 'Нерешённые', + 'thread.filter.outdated': 'Устаревшие', + 'thread.filter.resolved': 'Решённые', + 'thread.filter.mine': 'Ждут моего ответа', + 'thread.none': 'Нет обсуждений, подходящих под фильтр', + 'thread.empty': 'Обсуждений ревью пока нет', + 'thread.total': 'Обсуждений на {host}: {count}', + 'thread.truncated': 'Обсуждений слишком много; показаны первые {count}', + 'thread.openAll': 'Открыть на GitHub', + 'thread.replies': 'Ответов: {count}', + 'thread.fileLevel': 'Обсуждение файла', + 'thread.onCommit': 'в {commit}', + 'thread.originally': 'Изначально {range}', + 'thread.outdatedTag': 'Устарело', + 'thread.elsewhereTag': 'Нет в выбранных коммитах', + 'thread.author': 'Автор', + 'thread.bot': 'бот', + 'thread.deletedAuthor': 'Удалённая учётная запись', + 'thread.resolvedRow': 'Решённое обсуждение · {author}', + 'thread.expand': 'Развернуть', + 'thread.collapse': 'Свернуть', + 'thread.outdatedSection': 'Устаревших обсуждений: {count}. Их код изменили более поздние коммиты', + 'thread.viewOriginal': 'Открыть файл в том коммите', + 'thread.hideOriginal': 'Скрыть файл в том коммите', + 'thread.originalLoading': 'Чтение файла в том коммите…', + 'thread.originalFailed': 'Не удалось прочитать файл в том коммите: {message}', + 'thread.openOnHost': 'Открыть на GitHub', + 'thread.unresolvedCount': 'Нерешённых: {count}', + 'thread.unresolvedAria': 'В {name} нерешённых обсуждений: {count}. Открыть список обсуждений', + 'thread.treeCount': 'Нерешённых обсуждений: {count}', + 'thread.loadFailed': 'Не удалось прочитать обсуждения GitHub: {message}', + 'thread.inputFailed': 'Не удалось добавить обсуждение в поле ввода; повторите попытку позже', + 'thread.copy': 'Копировать', + 'thread.copied': 'Скопировано', + 'thread.codeBlock': 'Блок кода', + 'thread.wrap': 'Переносить строки', + 'thread.unwrap': 'Не переносить строки', + 'thread.footnotes': 'Сноски', } /** Portuguese copy with the same keys. */ @@ -2467,4 +2761,46 @@ export const pt: Record = { 'toast.expandStale': 'O arquivo mudou após a leitura das alterações; atualize antes de expandir', 'toast.prompted': 'Enviado: {text}', 'toast.promptFailed': 'Não foi possível enviar a mensagem', + 'thread.list': 'Discussões', + 'thread.listAria': 'Discussões de revisão, {count} no total', + 'thread.close': 'Fechar a lista de discussões', + 'thread.filterAria': 'Filtrar discussões', + 'thread.filter.unresolved': 'Não resolvidas', + 'thread.filter.outdated': 'Desatualizadas', + 'thread.filter.resolved': 'Resolvidas', + 'thread.filter.mine': 'Aguardando minha resposta', + 'thread.none': 'Nenhuma discussão corresponde a este filtro', + 'thread.empty': 'Ainda não há discussões de revisão', + 'thread.total': '{count} discussões no {host}', + 'thread.truncated': 'Há discussões demais; mostrando as primeiras {count}', + 'thread.openAll': 'Ver no GitHub', + 'thread.replies': '{count} respostas', + 'thread.fileLevel': 'Discussão do arquivo', + 'thread.onCommit': 'em {commit}', + 'thread.originally': 'Originalmente {range}', + 'thread.outdatedTag': 'Desatualizada', + 'thread.elsewhereTag': 'Fora dos commits escolhidos', + 'thread.author': 'Autor', + 'thread.bot': 'bot', + 'thread.deletedAuthor': 'Conta excluída', + 'thread.resolvedRow': 'Discussão resolvida · {author}', + 'thread.expand': 'Expandir', + 'thread.collapse': 'Recolher', + 'thread.outdatedSection': '{count} discussões desatualizadas: commits posteriores alteraram o código delas', + 'thread.viewOriginal': 'Ver o arquivo naquele commit', + 'thread.hideOriginal': 'Ocultar o arquivo daquele commit', + 'thread.originalLoading': 'Lendo o arquivo naquele commit…', + 'thread.originalFailed': 'Não foi possível ler o arquivo naquele commit: {message}', + 'thread.openOnHost': 'Ver no GitHub', + 'thread.unresolvedCount': '{count} não resolvidas', + 'thread.unresolvedAria': '{name} tem {count} discussões não resolvidas; abrir a lista de discussões', + 'thread.treeCount': '{count} discussões não resolvidas', + 'thread.loadFailed': 'Não foi possível ler as discussões do GitHub: {message}', + 'thread.inputFailed': 'O campo de entrada não pôde receber esta discussão; tente novamente mais tarde', + 'thread.copy': 'Copiar', + 'thread.copied': 'Copiado', + 'thread.codeBlock': 'Bloco de código', + 'thread.wrap': 'Quebrar linhas', + 'thread.unwrap': 'Não quebrar linhas', + 'thread.footnotes': 'Notas de rodapé', } diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index 34fee1a16b..84f58d4be7 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -7,19 +7,21 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import { IconBranchOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconBranchOutlineRegular, type QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import type {} from '@deepseek-ai/dsh-experimental-client-ui-forge/remote' +import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { RemoteResult, TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' import type { ForgeChangeRequestListState, ForgeChangeRequestStatesFrame, ForgePanelChangeRequest } from '../types.ts' import { ReviewQueue } from './review-queue.ts' import { ViewedFiles } from './viewed-files.ts' import { formatReviewComment, reviewQuoteSummary, type ReviewSelection } from './review.ts' +import { formatThreadQuote, threadQuoteSummary } from './review-threads.ts' import { ActionToast } from './ActionToast.tsx' import { CHANGES_ID, changesDefinition } from './changes-address.ts' import { createChangesStore } from './changes-store.ts' @@ -147,16 +149,22 @@ function registerUi(ctx: Context): void { () => { notices.report('toast.promptFailed') }, ) } - const addReviewToInput = (sessionId: SessionId, selection: ReviewSelection): boolean => { + /** Insert one quote into the Session's main input, numbering it after the quotes of the same heading already there. */ + const quoteInInput = (sessionId: SessionId, heading: RegExp, quote: (index: number) => string, summary: QuoteSummary): boolean => { const scope = ctx.sessions.scope(sessionId) const conversation = scope?.get('conversation') if (scope === undefined || conversation === undefined) return false const input = conversation.input.for(scope) - const numbers = Array.from(input.state.getSnapshot().draft.matchAll(/(?:^|\n)(?:> )?## User Comment (\d+)/g), match => Number(match[1])) - if (!input.insertQuote(formatReviewComment(selection, Math.max(0, ...numbers) + 1), reviewQuoteSummary(selection.comment))) return false + const numbers = Array.from(input.state.getSnapshot().draft.matchAll(heading), match => Number(match[1])) + if (!input.insertQuote(quote(Math.max(0, ...numbers) + 1), summary)) return false input.focus() return true } + const addReviewToInput = (sessionId: SessionId, selection: ReviewSelection): boolean => quoteInInput(sessionId, + /(?:^|\n)(?:> )?## User Comment (\d+)/g, index => formatReviewComment(selection, index), reviewQuoteSummary(selection.comment)) + const addThreadToInput = (sessionId: SessionId, thread: ForgeReviewThread, url: string, range: string | null): boolean => + quoteInInput(sessionId, /(?:^|\n)(?:> )?## Review Thread (\d+)/g, index => formatThreadQuote(thread, url, index), + threadQuoteSummary(thread, range)) /** How toasts name a change request: its number, else its title, else its URL. */ const nameOf = (entry: ForgePanelChangeRequest): string => { const number = numberOf(entry) @@ -242,6 +250,8 @@ function registerUi(ctx: Context): void { viewedFiles: store.viewed, changeRequestText: (url, commit, path) => ctx.remote.forgePanel.changeRequestText(sessionId, url, commit, path), addReviewToInput: selection => addReviewToInput(sessionId, selection), + addThreadToInput: (thread, url, range) => addThreadToInput(sessionId, thread, url, range), + changeRequestReview: (url, headSha, signal) => ctx.remote.forgePanel.changeRequestReview(sessionId, url, headSha, signal), reviewQueue: ({ id, signal }) => { let queue = store.reviews.get(signal) if (queue === undefined) { diff --git a/packages/experimental/client-ui-forge/src/client/review-threads.ts b/packages/experimental/client-ui-forge/src/client/review-threads.ts new file mode 100644 index 0000000000..831b2acc0a --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/review-threads.ts @@ -0,0 +1,171 @@ +/** + * Where the changes view shows each review thread of a change request, which threads each filter of the thread list + * keeps, and the composer quote of a whole thread. + */ + +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ForgeAnchor, ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { ForgeCommitRange, ForgeDiffFile } from '../types.ts' + +/** The changes a view shows, which decides where a thread can sit. */ +export interface ThreadView { + /** Head commit the threads were read at. */ + readonly head: string + /** Commit the shown changes end at: the head, or the last chosen commit. */ + readonly end: string + /** Chosen consecutive commits, or null for the whole change request. */ + readonly commits: ForgeCommitRange | null +} + +/** + * Where a thread shows in the changes view: on lines of one side, at the top of its file, in its file's outdated + * section, or nowhere in the file because the chosen commits do not hold the lines it is on. + */ +export type ThreadPlace = + | { readonly kind: 'line'; readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } + | { readonly kind: 'file' } + | { readonly kind: 'outdated' } + | { readonly kind: 'elsewhere' } + +/** One filter of the thread list. */ +export type ThreadFilter = 'unresolved' | 'outdated' | 'resolved' | 'mine' + +/** Filters of the thread list in display order. */ +export const THREAD_FILTERS: readonly ThreadFilter[] = ['unresolved', 'outdated', 'resolved', 'mine'] + +/** + * Place a thread in a view. The whole change request shows a thread at its position on the head. Chosen commits show + * only a new-side thread whose lines number the file at the last chosen commit: its position on the head when the + * commits end at the head, else the lines it was written on at that commit. The old side of chosen commits starts + * at the parent of the first commit, which no thread position numbers. + * @param thread - the thread. + * @param view - the shown changes. + * @returns where the thread shows. + */ +export function placeThread(thread: ForgeReviewThread, view: ThreadView): ThreadPlace { + if (thread.subject === 'file') return { kind: 'file' } + if (view.commits === null) return thread.current === null ? { kind: 'outdated' } : onLines(thread.side, thread.current) + if (thread.side === 'R' && thread.current !== null && view.end === view.head) return onLines('R', thread.current) + if (thread.side === 'R' && thread.original !== null && thread.original.commit === view.end) return onLines('R', thread.original) + return thread.current === null ? { kind: 'outdated' } : { kind: 'elsewhere' } +} + +function onLines(side: 'L' | 'R', anchor: ForgeAnchor): ThreadPlace { + return { kind: 'line', side, startLine: anchor.startLine, endLine: anchor.endLine } +} + +/** + * Name a side and lines, such as `R12` or `L3–5`. + * @param side - old or new side. + * @param anchor - the lines. + * @returns the range label. + */ +export function anchorRange(side: 'L' | 'R', anchor: Pick): string { + return `${side}${anchor.startLine}${anchor.endLine === anchor.startLine ? '' : `–${anchor.endLine}`}` +} + +/** + * Find the collapsed unchanged lines that hold a line: the index of the hunk they precede, or the hunk count after the last hunk. + * @param file - the diff file. + * @param side - side the line numbers. + * @param line - the line. + * @returns the gap index, or undefined when a hunk shows the line. + */ +export function gapOf(file: ForgeDiffFile, side: 'L' | 'R', line: number): number | undefined { + for (const [index, hunk] of file.hunks.entries()) { + const start = side === 'L' ? hunk.oldStart : hunk.newStart + const count = side === 'L' ? hunk.oldLines : hunk.newLines + if (line < start) return index + if (line < start + count) return undefined + } + return file.hunks.length +} + +/** + * Whether the signed-in user should answer a thread: it is not resolved, the user wrote in it, and someone else wrote last. + * @param thread - the thread. + * @param viewer - login of the signed-in user, or null when the host names none. + * @returns whether the thread awaits the user's reply. + */ +export function awaitsViewer(thread: ForgeReviewThread, viewer: string | null): boolean { + if (viewer === null || thread.resolved) return false + const last = thread.comments.at(-1)?.author?.login + return last !== viewer && thread.comments.some(comment => comment.author?.login === viewer) +} + +/** + * Whether a thread passes a filter of the thread list; `outdated` keeps a line thread without a position on the head. + * @param thread - the thread. + * @param filter - the filter, or null for every thread. + * @param viewer - login of the signed-in user. + * @returns whether the list shows the thread. + */ +export function passesFilter(thread: ForgeReviewThread, filter: ThreadFilter | null, viewer: string | null): boolean { + switch (filter) { + case null: return true + case 'unresolved': return !thread.resolved + case 'outdated': return thread.subject === 'line' && thread.current === null + case 'resolved': return thread.resolved + case 'mine': return awaitsViewer(thread, viewer) + /* v8 ignore next -- closed ThreadFilter union exhaustiveness guard */ + default: return assertNever(filter, 'ThreadFilter') + } +} + +/** Lines of a recorded diff hunk shown before its last line, beside the lines the thread is on. */ +const EXCERPT_CONTEXT = 3 + +/** + * Cut a recorded diff hunk to its header and the lines that end it: the thread's lines on its side plus a few before. + * GitHub records the hunk up to the thread's last line. + * @param hunk - the recorded hunk, header first. + * @param side - side the thread's lines number. + * @param lines - how many lines the thread covers. + * @returns the header and the kept lines. + */ +export function hunkExcerpt(hunk: string, side: 'L' | 'R', lines: number): { readonly header: string | null; readonly lines: readonly string[] } { + const header = hunk.startsWith('@@') ? hunk.split('\n', 1).join('') : null + const body = (header === null ? hunk : hunk.slice(header.length + 1)).split('\n') + const other = side === 'L' ? '+' : '-' + const kept: string[] = [] + let wanted = lines + EXCERPT_CONTEXT + for (const line of body.toReversed()) { + if (wanted === 0) break + kept.push(line) + if (!line.startsWith(other)) wanted -= 1 + } + return { header, lines: kept.reverse() } +} + +/** + * Describe a composer quote of a thread by its file, range, and first comment. + * @param thread - the quoted thread. + * @param range - the thread's range label, or null for a file thread. + * @returns the composer's display of the quote. + */ +export function threadQuoteSummary(thread: ForgeReviewThread, range: string | null): QuoteSummary { + const name = thread.path.slice(thread.path.lastIndexOf('/') + 1) + return { label: range === null ? name : `${name} ${range}`, title: thread.path, detail: range ?? thread.path, body: thread.comments[0]?.body ?? '' } +} + +/** + * Format a whole thread for the ordinary, logged user message. Comment bodies are quoted line by line, so their + * Markdown cannot add headings to the message. + * @param thread - the thread. + * @param url - web page of the change request. + * @param index - one-based thread number in the composer. + * @returns Markdown content for an atomic composer quote. + */ +export function formatThreadQuote(thread: ForgeReviewThread, url: string, index: number): string { + const anchor = thread.current ?? thread.original + const where = thread.subject === 'file' || anchor === null ? 'Lines: whole file' + : `Side: ${thread.side}\nLines: ${anchor.startLine === anchor.endLine ? anchor.startLine : `${anchor.startLine}-${anchor.endLine}`}\nCommit: ${anchor.commit}` + const state = [thread.resolved ? 'resolved' : 'unresolved', ...thread.subject === 'line' && thread.current === null ? ['outdated'] : []].join(', ') + const fence = thread.diffHunk === null ? '' : '`'.repeat(Math.max(3, ...Array.from(thread.diffHunk.matchAll(/`+/g), match => match[0].length + 1))) + const hunk = thread.diffHunk === null ? '' : `Diff hunk:\n${fence}diff\n${thread.diffHunk}\n${fence}\n` + const comments = thread.comments.map(comment => `${comment.author === null ? 'Unknown author' : `@${comment.author.login}`} (${comment.createdAt}):\n` + + comment.body.split('\n').map(line => `> ${line}`).join('\n')).join('\n\n') + const link = thread.comments[0]?.url ?? url + return `## Review Thread ${index}\nFile: ${thread.path}\n${where}\nState: ${state}\nSource: ${link}\n${hunk}Comments:\n${comments}` +} diff --git a/packages/experimental/client-ui-forge/src/client/thread-state.ts b/packages/experimental/client-ui-forge/src/client/thread-state.ts new file mode 100644 index 0000000000..742cc8b1bd --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/thread-state.ts @@ -0,0 +1,124 @@ +/** Reads the review threads of the change request a changes view shows and places them in its files. */ + +import { useEffect, useMemo, useState } from 'react' +import type { ForgeReviewData, ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { LineThread } from './ReviewThreads.tsx' +import { placeThread, type ThreadPlace, type ThreadView } from './review-threads.ts' + +/** What the changes view knows about its change request when it reads threads. */ +export interface ThreadReadInput { + /** Whether the view is visible; a hidden view reads nothing. */ + readonly visible: boolean + /** Binding URL of the change request, or null for local changes. */ + readonly url: string | null + /** Head commit of the latest status, or null before one. */ + readonly head: string | null + /** Update time of the latest status, or null before one. */ + readonly updatedAt: string | null + /** Epoch milliseconds of the latest status, so every status asks the Host again; the Host answers from memory until the threads age. */ + readonly statusAt: number | null + /** Changes on each refresh. */ + readonly attempt: number + /** Read the threads at a head commit. */ + readonly read: (url: string, headSha: string, signal: AbortSignal) => Promise> +} + +/** The last threads read and why the latest read failed. */ +export interface ThreadReadState { + /** Threads of the last successful read for the URL, at any head, or null. */ + readonly review: ForgeReviewData | null + /** Message of the latest failed read, or null. */ + readonly failure: string | null + /** Whether the provider cannot read reviews, so the view shows no threads and no failure. */ + readonly unsupported: boolean +} + +/** + * Read the threads at the head of each status while the view is visible. A read refused because the head moved + * keeps the previous threads; the next status names the new head and reads again. + * @param input - the change request and the reader. + * @returns the last threads and the latest failure. + */ +export function useThreadRead(input: ThreadReadInput): ThreadReadState { + const { visible, url, head, updatedAt, statusAt, attempt, read } = input + const [state, setState] = useState( + { url: null, review: null, failure: null, unsupported: false }) + useEffect(() => { + if (!visible || url === null || head === null) return + const controller = new AbortController() + void read(url, head, controller.signal).then((result) => { + if (controller.signal.aborted) return + if (result.ok) { + setState({ url, review: result.value, failure: null, unsupported: false }) + return + } + const { code, message } = result.error + if (code === 'forgePanel/stale-head') return + setState(previous => ({ url, review: previous.url === url ? previous.review : null, + failure: code === 'forgePanel/review-unsupported' ? null : message, unsupported: code === 'forgePanel/review-unsupported' })) + }) + return () => { controller.abort() } + }, [visible, url, head, updatedAt, statusAt, attempt, read]) + return state.url === url ? state : { review: null, failure: null, unsupported: false } +} + +/** Threads of one file grouped by where they show, and how many of them are unresolved. */ +export interface PlacedFileThreads { + readonly lines: readonly LineThread[] + readonly file: readonly ForgeReviewThread[] + readonly outdated: readonly ForgeReviewThread[] + readonly unresolved: number +} + +/** One thread and where the shown changes place it. */ +export interface PlacedThread { + readonly thread: ForgeReviewThread + readonly place: ThreadPlace +} + +/** Every thread with its place and the threads of each file. */ +export interface PlacedThreads { + /** Every thread in host order with its place. */ + readonly entries: readonly PlacedThread[] + /** Threads of each path. */ + readonly files: ReadonlyMap + /** Unresolved threads by path, for the file tree. */ + readonly unresolved: ReadonlyMap +} + +const NONE: PlacedThreads = { entries: [], files: new Map(), unresolved: new Map() } + +/** + * Place the threads of a review in the shown changes. + * @param review - threads read at the head of the latest status, or null. + * @param view - the shown changes, or null before they load. + * @returns places, per-file groups, and unresolved counts. + */ +export function usePlacedThreads(review: ForgeReviewData | null, view: ThreadView | null): PlacedThreads { + const commits = view?.commits ?? null + const end = view?.end ?? null + return useMemo(() => { + if (review === null || end === null) return NONE + const entries: PlacedThread[] = [] + const files = new Map() + const unresolved = new Map() + for (const thread of review.threads) { + const place = placeThread(thread, { head: review.headSha, end, commits }) + entries.push({ thread, place }) + let group = files.get(thread.path) + if (group === undefined) { + group = { lines: [], file: [], outdated: [], unresolved: 0 } + files.set(thread.path, group) + } + if (place.kind === 'line') group.lines.push({ thread, place }) + else if (place.kind === 'file') group.file.push(thread) + else if (place.kind === 'outdated') group.outdated.push(thread) + if (!thread.resolved) { + group.unresolved += 1 + unresolved.set(thread.path, group.unresolved) + } + } + return { entries, files, unresolved } + }, [review, end, commits]) +} 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 a4b277e34c..9cbb1f9656 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 @@ -23,8 +23,11 @@ import baseCss from '../src/client/BaseMenu.module.css' import type { ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelChangeRequest, ForgePanelState, } from '../src/types.ts' -import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge/types' +import type { + ChangeRequestKey, ForgeCommitList, ForgeReviewData, ForgeReviewThread, ForgeThreadId, +} from '@deepseek-ai/dsh-experimental-forge/types' import { entry, ready, snapshot } from './client-fixtures.client.ts' +import { reviewComment, reviewThread } from './thread-fixtures.client.ts' const t = makeTranslate(en) const SESSION = SessionId('s1') @@ -138,6 +141,8 @@ const REFUSED = { staleHead: { ok: false, error: new RemoteError('forgePanel/stale-head', 'the head moved', {}) }, hostRefused: { ok: false, error: new RemoteError('forgePanel/diff-failed', 'diff too large', {}) }, failed: { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) }, + reviewUnsupported: { ok: false, error: new RemoteError('forgePanel/review-unsupported', 'no review reads', {}) }, + reviewFailed: { ok: false, error: new RemoteError('forgePanel/review-failed', 'GitHub is down', {}) }, } satisfies Record> /** @@ -239,6 +244,8 @@ function mount(options: MountOptions = {}) { reviewQueue: vi.fn().mockReturnValue(new ReviewQueue('test-review')), submitReview: vi.fn().mockResolvedValue({ ok: true, value: { ok: true, url: URL7 } }), addReviewToInput: vi.fn().mockReturnValue(true), + addThreadToInput: vi.fn().mockReturnValue(true), + changeRequestReview: vi.fn(async () => REFUSED.reviewUnsupported), createChangeRequest: vi.fn(), report: vi.fn(), } @@ -1632,3 +1639,181 @@ describe('ChangesTab commits', () => { expect(m.view.queryByRole('button', { name: /^Commits shown/ })).toBeNull() }) }) + +describe('ChangesTab review threads', () => { + const source: ChangesSource = { kind: 'change', url: URL7 } + const OLD = 'b'.repeat(40) + const LARGE = file('logs/large.txt', { status: 'added', additions: 1001, + hunks: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: 1001, lines: Array.from({ length: 1001 }, (_, index) => `+${index}`) }] }) + const FILES = [APP, NOTES, GONE, LOGO, BIG, MOVED, LARGE] + const line = (id: string, path: string, side: 'L' | 'R', at: number, overrides: Partial = {}): ForgeReviewThread => reviewThread({ + id: id as ForgeThreadId, path, side, + current: { commit: HEAD, startLine: at, endLine: at }, original: { commit: HEAD, startLine: at, endLine: at }, + comments: [reviewComment({ body: `Comment ${id}` })], ...overrides, + }) + const THREADS: ForgeReviewThread[] = [ + line('on-row', 'src/app.ts', 'R', 4, { comments: [reviewComment({ body: 'Comment on-row', author: { login: 'octo', avatarUrl: null, bot: false } }), + reviewComment({ body: 'Reply', author: { login: 'lin', avatarUrl: null, bot: false } })] }), + line('old-side', 'src/app.ts', 'L', 11), + line('in-gap', 'src/app.ts', 'R', 8), + line('resolved', 'src/app.ts', 'R', 5, { resolved: true }), + line('outdated', 'src/app.ts', 'R', 0, { current: null, original: { commit: OLD, startLine: 9, endLine: 9 } }), + reviewThread({ id: 'file-thread' as ForgeThreadId, path: 'docs/notes.txt', subject: 'file', current: null, original: null, diffHunk: null, + comments: [reviewComment({ body: 'Comment file-thread' })] }), + line('beyond', 'docs/gone.txt', 'L', 3), + line('binary', 'assets/logo.png', 'R', 1), + line('oversized', 'logs/big.log', 'R', 1), + line('renamed', 'lib/b.txt', 'R', 1), + line('large', 'logs/large.txt', 'R', 1), + line('missing', 'src/missing.ts', 'R', 1), + line('missing-no-url', 'src/missing.ts', 'R', 2, { comments: [reviewComment({ url: null })] }), + ] + const REVIEW: ForgeReviewData = { headSha: HEAD, viewer: 'octo', threads: THREADS, truncated: false } + const reviewed = (review: ForgeReviewData = REVIEW) => (faces: Faces): void => { + faces.changeRequestDiff.mockImplementation(async () => ok({ ...CHANGE, files: FILES })) + faces.changeRequestReview.mockImplementation(async () => ok(review)) + } + /** Binding of #7 at the head whose latest status settled at `fetchedAt`. */ + const polledAt = (fetchedAt: number): ForgePanelChangeRequest => { + const bound = entry(7, snapshot(7)) + return { ...bound, update: { key: 'github:github.com/octo/demo#7' as ChangeRequestKey, fetchedAt, snapshot: snapshot(7) } } + } + const card = (m: ReturnType, id: string): HTMLElement | null => m.view.container.querySelector(`[data-forge-thread="${id}"]`) + /** Code of the row a thread follows, on the side its lines number. */ + const following = (m: ReturnType, id: string, side: 'L' | 'R' = 'R'): string | null => + card(m, id)?.previousElementSibling?.querySelector(side === 'L' ? '[data-old-line]' : '[data-new-line]')?.textContent ?? null + + it('reads threads at the head of the latest status and places them on rows, gaps, files, and outdated sections', async () => { + const m = mount({ source, setup: reviewed() }) + await settle() + expect(m.faces.changeRequestReview).toHaveBeenCalledWith(URL7, HEAD, expect.any(AbortSignal)) + const app = m.section('src/app.ts') + expect(following(m, 'on-row')).toBe('const y = 4') + expect(following(m, 'old-side', 'L')).toBe('const w = 12') + expect(card(m, 'in-gap')?.previousElementSibling?.getAttribute('data-forge-diff-gap')).toBe('1') + expect(card(m, 'resolved')?.textContent).toContain('Resolved thread · reviewer') + expect(within(app).getByRole('button', { name: 'app.ts has 4 unresolved threads; open the thread list' }).textContent).toBe('4 unresolved') + expect(app.querySelector('[data-forge-outdated-threads]')?.textContent).toContain('1 outdated threads') + fireEvent.click(within(card(m, 'outdated')!).getByRole('button', { name: en['thread.viewOriginal'] })) + expect(m.faces.changeRequestText).toHaveBeenLastCalledWith(URL7, OLD, 'src/app.ts') + expect(m.section('docs/notes.txt').firstElementChild?.nextElementSibling?.getAttribute('data-forge-thread')).toBe('file-thread') + expect(m.section('docs/gone.txt').querySelector(`.${css.code}`)?.lastElementChild?.getAttribute('data-forge-thread')).toBe('beyond') + for (const id of ['binary', 'oversized', 'renamed', 'large']) expect(card(m, id)).not.toBeNull() + expect(within(m.view.getByRole('navigation')).getByTitle('4 unresolved threads').textContent).toBe('4') + fireEvent.click(within(app).getByRole('button', { name: '4 unchanged lines' })) + await settle() + expect(following(m, 'in-gap')).toBe('const a7 = 8') + fireEvent.click(within(card(m, 'on-row')!).getByRole('button', { name: en['review.addToInput'] })) + expect(m.faces.addThreadToInput).toHaveBeenCalledWith(THREADS[0], URL7, 'R4') + m.faces.addThreadToInput.mockReturnValue(false) + fireEvent.click(within(card(m, 'on-row')!).getByRole('button', { name: en['review.addToInput'] })) + expect(m.faces.report).toHaveBeenLastCalledWith('thread.inputFailed') + }) + + it('opens the thread list, filters it, and opens each thread at its place', async () => { + const m = mount({ source, setup: reviewed({ ...REVIEW, truncated: true }) }) + await settle() + fireEvent.click(m.view.getByRole('button', { name: 'Review threads, 13 in total' })) + const list = m.view.getByRole('complementary', { name: 'Review threads, 13 in total' }) + expect(within(list).getAllByRole('button', { pressed: true }).map(button => button.textContent)).toEqual(['Unresolved 12']) + expect(within(list).getByText(/^Too many threads; showing the first 13/)).toBeDefined() + expect([...list.querySelectorAll('[data-forge-thread-group]')].map(group => group.getAttribute('data-forge-thread-group'))) + .toEqual(['assets/logo.png', 'docs/gone.txt', 'docs/notes.txt', 'lib/b.txt', 'logs/big.log', 'logs/large.txt', 'src/app.ts', 'src/missing.ts']) + scrolled.mockClear() + fireEvent.click(list.querySelector('[data-forge-thread-item="on-row"]')!) + expect(scrolled.mock.contexts).toContain(card(m, 'on-row')) + fireEvent.click(within(list).getByRole('button', { name: 'Resolved 1' })) + fireEvent.click(list.querySelector('[data-forge-thread-item="resolved"]')!) + expect(card(m, 'resolved')?.tagName).toBe('SECTION') + fireEvent.click(within(list).getByRole('button', { name: 'Resolved 1' })) + fireEvent.click(list.querySelector('[data-forge-thread-item="missing"]')!) + expect(m.faces.openLink).toHaveBeenLastCalledWith(THREADS[11]?.comments[0]?.url) + m.faces.openLink.mockClear() + fireEvent.click(list.querySelector('[data-forge-thread-item="missing-no-url"]')!) + expect(m.faces.openLink).not.toHaveBeenCalled() + fireEvent.click(within(list).getByRole('button', { name: en['thread.openAll'] })) + expect(m.faces.openLink).toHaveBeenLastCalledWith(URL7) + fireEvent.click(within(list).getByRole('button', { name: 'Awaiting my reply 1' })) + expect([...list.querySelectorAll('[data-forge-thread-item]')].map(item => item.getAttribute('data-forge-thread-item'))).toEqual(['on-row']) + fireEvent.click(within(list).getByRole('button', { name: en['thread.close'] })) + expect(m.view.queryByRole('complementary')).toBeNull() + scrolled.mockClear() + fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: /^app\.ts has 4 unresolved threads/ })) + expect(scrolled.mock.contexts).toContain(m.view.container.querySelector('[data-forge-thread-group="src/app.ts"]')) + }) + + it('places only the threads whose lines number the last chosen commit, and shows the others after choosing all commits', async () => { + const two = '2'.repeat(40) + const threads = [line('at-head', 'src/app.ts', 'R', 4), line('written-on-two', 'src/app.ts', 'R', 3, { current: null, original: { commit: two, startLine: 3, endLine: 3 } })] + const m = mount({ source, setup: (faces) => { + faces.changeRequestDiff.mockImplementation(async (_url, commits) => ok({ ...CHANGE, headSha: commits?.to ?? HEAD })) + faces.changeRequestReview.mockImplementation(async () => ok({ ...REVIEW, threads })) + } }) + await settle() + m.store.actions.committed(TAB, { from: two, to: two }) + await settle() + expect(card(m, 'at-head')).toBeNull() + expect(following(m, 'written-on-two')).toBe('const a3 = 3') + fireEvent.click(m.view.getByRole('button', { name: 'Review threads, 2 in total' })) + const list = m.view.getByRole('complementary') + fireEvent.click(within(list).getByRole('button', { name: 'Unresolved 2' })) + expect(list.querySelector('[data-forge-thread-item="at-head"]')?.textContent).toContain(en['thread.elsewhereTag']) + fireEvent.click(list.querySelector('[data-forge-thread-item="at-head"]')!) + expect(m.store.getSnapshot().byTab[TAB]?.commits).toBeNull() + await settle() + expect(following(m, 'at-head')).toBe('const y = 4') + }) + + it('shows threads only at the head the diff and the latest status name, and reports a failed read with a retry', async () => { + const m = mount({ source, setup: (faces) => { faces.changeRequestReview.mockResolvedValue(REFUSED.reviewFailed) } }) + await settle() + expect(m.view.getByText('Could not read GitHub threads: GitHub is down')).toBeDefined() + m.faces.changeRequestReview.mockResolvedValue(ok({ ...REVIEW, threads: [line('on-row', 'src/app.ts', 'R', 4)] })) + fireEvent.click(within(m.view.getByText('Could not read GitHub threads: GitHub is down').closest('[role="status"]')!).getByRole('button', { name: en.retry })) + await settle() + expect(card(m, 'on-row')).not.toBeNull() + m.faces.changeRequestReview.mockResolvedValue(REFUSED.staleHead) + act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(2)] }), disconnected: false }) }) + await settle() + expect(card(m, 'on-row')).not.toBeNull() + m.faces.changeRequestReview.mockResolvedValue(REFUSED.reviewFailed) + act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(3)] }), disconnected: false }) }) + await settle() + expect(card(m, 'on-row')).not.toBeNull() + expect(m.view.getByText('Could not read GitHub threads: GitHub is down')).toBeDefined() + act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7, { headSha: OLD }))] }), disconnected: false }) }) + await settle() + expect(card(m, 'on-row')).toBeNull() + }) + + it('names no author when the host hides the change request\'s author', async () => { + const m = mount({ source, state: ready({ changeRequests: [entry(7, snapshot(7, { author: null }))] }), setup: reviewed({ ...REVIEW, + threads: [line('on-row', 'src/app.ts', 'R', 4, { comments: [reviewComment({ author: { login: 'octo', avatarUrl: null, bot: false } })] })] }) }) + await settle() + expect(within(card(m, 'on-row')!).queryByText(en['thread.author'])).toBeNull() + }) + + it('reads no threads for local changes or a hidden view, and shows none for a provider without review reads', async () => { + const local = mount() + await settle() + expect(local.faces.changeRequestReview).not.toHaveBeenCalled() + cleanup() + const m = mount({ source }) + await settle() + expect(m.faces.changeRequestReview).toHaveBeenCalledOnce() + expect(m.view.queryByRole('button', { name: /^Review threads/ })).toBeNull() + expect(m.view.queryByText(/^Could not read GitHub threads/)).toBeNull() + let answer: (value: RemoteResult) => void = () => {} + m.faces.changeRequestReview.mockImplementation(() => new Promise((resolve) => { answer = resolve })) + act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(2)] }), disconnected: false }) }) + expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(2) + act(() => { m.visibility.set(false) }) + await act(async () => { answer(ok(REVIEW)) }) + act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(3)] }), disconnected: false }) }) + await settle() + expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(2) + act(() => { m.visibility.set(true) }) + await settle() + expect(card(m, 'on-row')).toBeNull() + }) +}) 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 177a4784bd..46b484be84 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -12,7 +12,7 @@ import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SidebarRightTabDefinition, TabId } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { - ChangeRequestSnapshot, ForgeCommitList, ForgeReviewRequest, ForgeReviewResult, + ChangeRequestSnapshot, ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, } from '@deepseek-ai/dsh-experimental-forge/types' import { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, type RemoteResult, type TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' @@ -31,6 +31,7 @@ import { SessionHoverForge } from '../src/client/SessionHoverForge.tsx' import { SessionRowForge } from '../src/client/SessionRowForge.tsx' import type { NoticeSource } from '../src/client/source.ts' import type { ReviewSelection } from '../src/client/review.ts' +import { reviewThread } from './thread-fixtures.client.ts' import { WorktreeProgress, type WorktreeProgressInjected } from '../src/client/WorktreeProgress.tsx' import { WorktreeSettings } from '../src/client/WorktreeSettings.tsx' import type { WorktreeSettingsInjected, WorktreeSettings as WorktreeSettingsFields } from '../src/client/worktree-settings-form.ts' @@ -183,6 +184,8 @@ async function base() { changeRequestCommits: vi.fn(async (_sessionId: SessionId, _url: string, _signal?: AbortSignal): Read => ({ ok: true, value: COMMITS })), changeRequestText: vi.fn(async (_sessionId: SessionId, _url: string, _commit: string, _path: string): Read => ({ ok: true, value: 'b\n' })), + changeRequestReview: vi.fn(async (_sessionId: SessionId, _url: string, headSha: string, _signal?: AbortSignal): Read => + ({ ok: true, value: { headSha, viewer: 'octo', threads: [], truncated: false } })), submitReview: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeReviewRequest): Read => ({ ok: true, value: { ok: true, url: 'https://github.com/review' } })), } ctx.provide('remote.forgePanel', forgePanel) @@ -750,9 +753,16 @@ describe('mountForgePanel changes view', () => { expect(insertQuote.mock.calls[0]?.[1]).toEqual({ label: 'a.ts R1', title: 'a.ts', detail: 'R1', body: 'Check this' }) expect(resolve).toHaveBeenCalledWith(scope) expect(focus).toHaveBeenCalledTimes(2) + const thread = reviewThread({ path: 'src/a.ts' }) + expect(view.addThreadToInput(thread, 'https://github.com/octo/demo/pull/7', 'R3')).toBe(true) + expect(view.addThreadToInput(thread, 'https://github.com/octo/demo/pull/7', 'R3')).toBe(true) + expect(insertQuote.mock.calls.slice(2).map(([text, summary]) => [text.split('\n')[0], summary?.label])) + .toEqual([['## Review Thread 1', 'a.ts R3'], ['## Review Thread 2', 'a.ts R3']]) + insertQuote.mockClear() + focus.mockClear() insertQuote.mockReturnValueOnce(false) expect(view.addReviewToInput(selection)).toBe(false) - expect(focus).toHaveBeenCalledTimes(2) + expect(focus).not.toHaveBeenCalled() expect(send).not.toHaveBeenCalled() const request: ForgeReviewRequest = { kind: 'review', headSha: 'a', event: 'comment', body: 'Summary', comments: [] } expect(await view.submitReview('https://github.com/pr', request)).toMatchObject({ ok: true, value: { ok: true } }) @@ -823,6 +833,9 @@ describe('mountForgePanel changes view', () => { expect(f.forgePanel.localCommits).toHaveBeenCalledWith(S1, 'refs/heads/topic', signal) expect(await view.changeRequestCommits('https://github.com/octo/demo/pull/7', signal)).toEqual({ ok: true, value: COMMITS }) expect(f.forgePanel.changeRequestCommits).toHaveBeenCalledWith(S1, 'https://github.com/octo/demo/pull/7', signal) + expect(await view.changeRequestReview('https://github.com/octo/demo/pull/7', 'a'.repeat(40), signal)) + .toEqual({ ok: true, value: { headSha: 'a'.repeat(40), viewer: 'octo', threads: [], truncated: false } }) + expect(f.forgePanel.changeRequestReview).toHaveBeenCalledWith(S1, 'https://github.com/octo/demo/pull/7', 'a'.repeat(40), signal) expect(view.viewedFiles).toBe(f.changes(S1).viewedFiles) expect(view.viewedFiles).not.toBe(f.changes(S2).viewedFiles) view.reconnect() diff --git a/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx new file mode 100644 index 0000000000..b6173e7853 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx @@ -0,0 +1,214 @@ +// @vitest-environment jsdom +/** Host review thread cards, the outdated section, and the thread list rendered on their own. */ +import { act, cleanup, fireEvent, render, within } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { en } from '../src/client/locales.ts' +import { Avatar, OutdatedThreads, ThreadCard, type ThreadActions } from '../src/client/ReviewThreads.tsx' +import { ThreadList, type ThreadListProps } from '../src/client/ThreadList.tsx' +import { reviewComment, reviewThread } from './thread-fixtures.client.ts' + +const t = makeTranslate(en) +const OLD = 'b'.repeat(40) +const scrolled = vi.fn() + +beforeEach(() => { + Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, value: scrolled }) +}) + +afterEach(() => { + cleanup() + scrolled.mockReset() + Reflect.deleteProperty(Element.prototype, 'scrollIntoView') +}) + +function actions(overrides: Partial = {}): ThreadActions { + return { + viewer: 'octo', author: 'octo', focused: null, + addToInput: vi.fn(() => true), openLink: vi.fn(), readText: vi.fn(async (): Promise> => ({ ok: true, value: 'a\nb\nc' })), + inputFailed: vi.fn(), + ...overrides, + } +} + +const outdated = (overrides: Partial = {}): ForgeReviewThread => reviewThread({ + id: 'old' as ForgeThreadId, current: null, original: { commit: OLD, startLine: 2, endLine: 3 }, diffHunk: '@@ -1 +1,3 @@\n a\n+b\n+c', ...overrides, +}) + +describe('Avatar', () => { + it('shows the image, or the login\'s first letter when there is none or it fails, or a mark for a deleted account', () => { + const view = render(<> + ) + const image = view.container.querySelector('img')! + expect(image.getAttribute('referrerpolicy')).toBe('no-referrer') + fireEvent.error(image) + expect([...view.container.querySelectorAll('span')].map(span => span.textContent)).toEqual(['O', 'L', '?']) + }) +}) + +describe('ThreadCard', () => { + it('shows each comment with its author, time, role tags, and Markdown without raw HTML', () => { + const thread = reviewThread({ comments: [ + reviewComment({ author: { login: 'octo', avatarUrl: null, bot: false }, body: '**bold** raw', createdAt: 'not a time' }), + reviewComment({ author: { login: 'ci', avatarUrl: null, bot: true }, pending: true }), + reviewComment({ author: null }), + ] }) + const view = render() + const card = view.container.querySelector('[data-forge-thread]')! + expect(card.getAttribute('data-split')).toBe('') + expect(card.querySelector('strong')?.textContent).toBe('bold') + expect(card.textContent).not.toContain('') + expect(card.textContent).not.toContain('hidden') + expect(within(card as HTMLElement).getByText('not a time')).toBeDefined() + expect(card.querySelectorAll('[data-forge-thread-comment]')).toHaveLength(3) + expect(within(card as HTMLElement).getAllByText(en['thread.author'])).toHaveLength(1) + expect(within(card as HTMLElement).getByText(en['thread.bot'])).toBeDefined() + expect(within(card as HTMLElement).getByText(en['review.pending'])).toBeDefined() + expect(within(card as HTMLElement).getByText(en['thread.deletedAuthor'])).toBeDefined() + }) + + it('quotes the thread, reports a refused quote, and opens its page', () => { + const shared = actions({ addToInput: vi.fn(() => false) }) + const thread = reviewThread() + const view = render() + fireEvent.click(view.getByRole('button', { name: en['review.addToInput'] })) + expect(shared.addToInput).toHaveBeenCalledWith(thread, 'R3') + expect(shared.inputFailed).toHaveBeenCalledOnce() + fireEvent.click(view.getByRole('button', { name: en['thread.openOnHost'] })) + expect(shared.openLink).toHaveBeenCalledWith(thread.comments[0]?.url) + }) + + it('names a file thread and offers no page without one', () => { + const view = render() + expect(view.getByRole('region', { name: en['thread.fileLevel'] }).textContent).toContain(en['thread.fileLevel']) + expect(view.queryByRole('button', { name: en['thread.openOnHost'] })).toBeNull() + }) + + it('folds a resolved thread into one row until unfolded or jumped to, and folds it again after a jump', () => { + const thread = reviewThread({ resolved: true, comments: [] }) + const place = { kind: 'line', side: 'R', startLine: 3, endLine: 3 } as const + const view = render() + expect(view.container.textContent).toContain('Resolved thread · Deleted account') + fireEvent.click(view.getByRole('button', { name: en['thread.expand'] })) + expect(view.getByRole('region', { name: 'R3' })).toBeDefined() + fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] })) + expect(view.queryByRole('region')).toBeNull() + view.rerender() + expect(view.getByRole('region', { name: 'R3' })).toBeDefined() + fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] })) + expect(view.queryByRole('region')).toBeNull() + view.rerender() + expect(view.getByRole('region', { name: 'R3' })).toBeDefined() + }) + + it('shows an outdated thread at its original lines with the end of its hunk and the file at that commit', async () => { + let answer: (value: RemoteResult) => void = () => {} + const shared = actions({ readText: vi.fn(() => new Promise>((resolve) => { answer = resolve })) }) + const view = render() + const card = view.getByRole('region', { name: en['thread.fileLevel'] }) + expect(card.textContent).toContain(`Originally R2–3 · on ${OLD.slice(0, 7)}`) + expect([...card.querySelectorAll('[class*="excerptLine"]')].map(line => line.textContent)).toEqual(['@@ -1 +1,3 @@', ' a', '+b', '+c']) + fireEvent.click(view.getByRole('button', { name: en['thread.viewOriginal'] })) + expect(shared.readText).toHaveBeenCalledWith(OLD, 'src/a.ts') + expect(view.getByText(en['thread.originalLoading'])).toBeDefined() + await act(async () => { answer({ ok: true, value: 'one\ntwo\nthree\nfour' }) }) + const file = view.getByRole('region', { name: en['thread.viewOriginal'] }) + expect([...file.querySelectorAll('[class*="marked"]')].map(line => line.textContent)).toEqual(['2two', '3three']) + expect(scrolled.mock.contexts).toContain(file.querySelectorAll('[class*="marked"]')[0]) + fireEvent.click(view.getByRole('button', { name: en['thread.hideOriginal'] })) + expect(view.queryByRole('region', { name: en['thread.viewOriginal'] })).toBeNull() + const failing = { ...shared, readText: vi.fn(async (): Promise> => ({ ok: false, error: new RemoteError('forgePanel/diff-failed', 'gone', {}) })) } + view.rerender() + fireEvent.click(view.getByRole('button', { name: en['thread.viewOriginal'] })) + await act(async () => { await Promise.resolve() }) + expect(view.getByRole('alert').textContent).toBe('Could not read the file at that commit: gone') + }) + + it('offers no file at that commit for an old-side thread and no excerpt without a recorded hunk', () => { + const view = render() + expect(view.queryByRole('button', { name: en['thread.viewOriginal'] })).toBeNull() + expect(view.container.querySelector('[class*="excerpt"]')).toBeNull() + }) +}) + +describe('OutdatedThreads', () => { + it('renders nothing without threads, folds on request, and opens again for a later jump to one of its threads', () => { + const empty = render() + expect(empty.container.textContent).toBe('') + cleanup() + const view = render() + expect(view.container.textContent).toContain('1 outdated threads') + fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] })) + expect(view.container.querySelector('[data-forge-thread]')).toBeNull() + view.rerender() + expect(view.container.querySelector('[data-forge-thread]')).toBeNull() + view.rerender() + expect(view.container.querySelector('[data-forge-thread]')).not.toBeNull() + fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] })) + expect(view.container.querySelector('[data-forge-thread]')).toBeNull() + fireEvent.click(view.getByRole('button', { name: en['thread.expand'] })) + expect(view.container.querySelector('[data-forge-thread]')).not.toBeNull() + }) +}) + +describe('ThreadList', () => { + function list(overrides: Partial = {}) { + const props: ThreadListProps = { + entries: [], order: [], viewer: 'octo', truncated: false, host: 'github.com', url: 'https://github.com/octo/demo/pull/7', filter: null, + file: null, choose: vi.fn(), open: vi.fn(), openLink: vi.fn(), close: vi.fn(), t, ...overrides, + } + return { props, view: render() } + } + + it('says when there are no threads, when none pass the filter, and how many the host has', () => { + expect(list().view.getByText(en['thread.empty'])).toBeDefined() + cleanup() + const { view } = list({ entries: [{ thread: reviewThread(), place: { kind: 'line', side: 'R', startLine: 3, endLine: 3 } }], filter: 'resolved' }) + expect(view.getByText(en['thread.none'])).toBeDefined() + expect(view.getByText(/^1 threads on github\.com/)).toBeDefined() + }) + + it('orders each file\'s threads from file threads to lines to outdated ones and describes each', () => { + const entries = [ + { thread: outdated({ id: 'gone' as ForgeThreadId, comments: [reviewComment(), reviewComment()] }), place: { kind: 'outdated' } as const }, + { thread: reviewThread({ id: 'late' as ForgeThreadId }), place: { kind: 'line', side: 'R', startLine: 9, endLine: 9 } as const }, + { thread: reviewThread({ id: 'away' as ForgeThreadId, current: null, original: null }), place: { kind: 'elsewhere' } as const }, + { thread: reviewThread({ id: 'whole' as ForgeThreadId, subject: 'file', current: null, original: null }), place: { kind: 'file' } as const }, + { thread: reviewThread({ id: 'early' as ForgeThreadId, comments: [reviewComment({ + body: '# Title\n> **Note** `code` [link](https://example.test) x', author: { login: 'ci', avatarUrl: null, bot: true } })] }), + place: { kind: 'line', side: 'L', startLine: 2, endLine: 4 } as const }, + ] + const { view, props } = list({ entries }) + const items = [...view.container.querySelectorAll('[data-forge-thread-item]')] + expect(items.map(item => item.getAttribute('data-forge-thread-item'))).toEqual(['whole', 'early', 'late', 'gone', 'away']) + expect(items.map(item => item.querySelector('[class*="meta"]')?.textContent)).toEqual([ + en['thread.fileLevel'], 'L2–4', 'R9', `Originally R2–3 · on ${OLD.slice(0, 7)} · 1 replies`, '', + ]) + expect(items[1]?.querySelector('[class*="excerpt"]')?.textContent).toBe('Title Note code link x') + expect(items[1]?.textContent).toContain(en['thread.bot']) + expect(items[3]?.textContent).toContain(en['thread.outdatedTag']) + expect(items[4]?.textContent).toContain(en['thread.elsewhereTag']) + fireEvent.click(items[3]!) + expect(props.open).toHaveBeenCalledWith(entries[0]) + fireEvent.click(view.getByRole('button', { name: 'Outdated 2' })) + expect(props.choose).toHaveBeenCalledWith('outdated') + fireEvent.click(view.getByRole('button', { name: en['thread.close'] })) + expect(props.close).toHaveBeenCalledOnce() + }) + + it('clears the active filter when it is chosen again and scrolls to a file\'s group', () => { + const entry = { thread: reviewThread({ path: 'b.ts' }), place: { kind: 'line', side: 'R', startLine: 3, endLine: 3 } as const } + const other = { thread: reviewThread({ path: 'a.ts' }), place: { kind: 'line', side: 'R', startLine: 3, endLine: 3 } as const } + const empty = { thread: reviewThread({ path: 'c.ts', comments: [] }), place: { kind: 'file' } as const } + const { view, props } = list({ entries: [empty, entry, other], order: ['b.ts'], filter: 'unresolved', file: 'a.ts' }) + expect([...view.container.querySelectorAll('[data-forge-thread-group]')].map(group => group.getAttribute('data-forge-thread-group'))) + .toEqual(['b.ts', 'a.ts', 'c.ts']) + expect(view.container.querySelector('[data-forge-thread-group="c.ts"] [class*="excerpt"]')?.textContent).toBe('') + expect(scrolled.mock.contexts).toEqual([view.container.querySelector('[data-forge-thread-group="a.ts"]')]) + fireEvent.click(view.getByRole('button', { name: 'Unresolved 3' })) + expect(props.choose).toHaveBeenCalledWith(null) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts b/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts new file mode 100644 index 0000000000..2942e99f8a --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts @@ -0,0 +1,132 @@ +/** Placement, filters, excerpts, and composer quotes of host review threads. */ +import { describe, expect, it } from 'vitest' +import type { ForgeReviewComment, ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' +import { + anchorRange, awaitsViewer, formatThreadQuote, gapOf, hunkExcerpt, passesFilter, placeThread, threadQuoteSummary, THREAD_FILTERS, +} from '../src/client/review-threads.ts' +import type { ForgeDiffFile } from '../src/types.ts' +import { reviewComment, reviewThread } from './thread-fixtures.client.ts' + +const HEAD = 'a'.repeat(40) +const OLD = 'b'.repeat(40) +const MIDDLE = 'c'.repeat(40) + +describe('placeThread', () => { + const current = reviewThread({ current: { commit: HEAD, startLine: 3, endLine: 5 }, original: { commit: OLD, startLine: 2, endLine: 4 } }) + + it('places a thread on the whole change request at its position on the head, else in the outdated section', () => { + const whole = { head: HEAD, end: HEAD, commits: null } + expect(placeThread(current, whole)).toEqual({ kind: 'line', side: 'R', startLine: 3, endLine: 5 }) + expect(placeThread(reviewThread({ side: 'L', current: { commit: HEAD, startLine: 1, endLine: 1 } }), whole)) + .toEqual({ kind: 'line', side: 'L', startLine: 1, endLine: 1 }) + expect(placeThread(reviewThread({ current: null }), whole)).toEqual({ kind: 'outdated' }) + expect(placeThread(reviewThread({ subject: 'file', current: null, original: null }), whole)).toEqual({ kind: 'file' }) + }) + + it('places a new-side thread in chosen commits only where its lines number the last chosen commit', () => { + expect(placeThread(current, { head: HEAD, end: HEAD, commits: { from: MIDDLE, to: HEAD } })) + .toEqual({ kind: 'line', side: 'R', startLine: 3, endLine: 5 }) + expect(placeThread(current, { head: HEAD, end: OLD, commits: { from: OLD, to: OLD } })) + .toEqual({ kind: 'line', side: 'R', startLine: 2, endLine: 4 }) + expect(placeThread(current, { head: HEAD, end: MIDDLE, commits: { from: MIDDLE, to: MIDDLE } })).toEqual({ kind: 'elsewhere' }) + expect(placeThread(reviewThread({ side: 'L', current: { commit: HEAD, startLine: 1, endLine: 1 } }), + { head: HEAD, end: HEAD, commits: { from: HEAD, to: HEAD } })).toEqual({ kind: 'elsewhere' }) + expect(placeThread(reviewThread({ current: null, original: null }), { head: HEAD, end: OLD, commits: { from: OLD, to: OLD } })) + .toEqual({ kind: 'outdated' }) + expect(placeThread(reviewThread({ subject: 'file', current: null, original: null }), { head: HEAD, end: OLD, commits: { from: OLD, to: OLD } })) + .toEqual({ kind: 'file' }) + }) +}) + +it('names a side and its lines', () => { + expect(anchorRange('R', { startLine: 12, endLine: 12 })).toBe('R12') + expect(anchorRange('L', { startLine: 3, endLine: 5 })).toBe('L3–5') +}) + +it('finds the collapsed unchanged lines that hold a line on either side', () => { + const file: ForgeDiffFile = { + path: 'a.ts', previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, additions: 2, deletions: 2, + digest: 'digest', layer: 'implementation', + hunks: [ + { oldStart: 5, oldLines: 3, newStart: 5, newLines: 3, lines: [' a', '-b', '+b', ' c'] }, + { oldStart: 20, oldLines: 2, newStart: 22, newLines: 2, lines: ['-x', '+x', ' y'] }, + ], + } + expect(gapOf(file, 'R', 2)).toBe(0) + expect(gapOf(file, 'R', 6)).toBeUndefined() + expect(gapOf(file, 'R', 10)).toBe(1) + expect(gapOf(file, 'L', 21)).toBeUndefined() + expect(gapOf(file, 'R', 21)).toBe(1) + expect(gapOf(file, 'R', 40)).toBe(2) +}) + +describe('thread filters', () => { + const by = (login: string | null): ForgeReviewComment => + reviewComment({ author: login === null ? null : { login, avatarUrl: null, bot: false } }) + + it('awaits the viewer only on an unresolved thread the viewer wrote in and someone else wrote last', () => { + expect(awaitsViewer(reviewThread({ comments: [by('octo'), by('lin')] }), 'octo')).toBe(true) + expect(awaitsViewer(reviewThread({ comments: [by('lin'), by('octo')] }), 'octo')).toBe(false) + expect(awaitsViewer(reviewThread({ comments: [by('lin'), by(null)] }), 'octo')).toBe(false) + expect(awaitsViewer(reviewThread({ comments: [by('octo'), by(null)] }), 'octo')).toBe(true) + expect(awaitsViewer(reviewThread({ comments: [by('octo'), by('lin')], resolved: true }), 'octo')).toBe(false) + expect(awaitsViewer(reviewThread({ comments: [by('octo'), by('lin')] }), null)).toBe(false) + expect(awaitsViewer(reviewThread({ comments: [] }), 'octo')).toBe(false) + }) + + it('keeps the threads each filter names', () => { + const outdated = reviewThread({ current: null }) + const resolved = reviewThread({ resolved: true }) + const file = reviewThread({ subject: 'file', current: null, original: null }) + expect(THREAD_FILTERS).toEqual(['unresolved', 'outdated', 'resolved', 'mine']) + expect([outdated, resolved, file].map(thread => passesFilter(thread, null, null))).toEqual([true, true, true]) + expect([outdated, resolved, file].map(thread => passesFilter(thread, 'unresolved', null))).toEqual([true, false, true]) + expect([outdated, resolved, file].map(thread => passesFilter(thread, 'outdated', null))).toEqual([true, false, false]) + expect([outdated, resolved, file].map(thread => passesFilter(thread, 'resolved', null))).toEqual([false, true, false]) + expect(passesFilter(reviewThread({ comments: [by('octo'), by('lin')] }), 'mine', 'octo')).toBe(true) + }) +}) + +describe('hunkExcerpt', () => { + const hunk = '@@ -1,8 +1,9 @@\n a\n b\n-c\n+C\n+D\n d\n e' + + it('keeps the header and the thread\'s lines on its side with three before them', () => { + expect(hunkExcerpt(hunk, 'R', 1)).toEqual({ header: '@@ -1,8 +1,9 @@', lines: ['+C', '+D', ' d', ' e'] }) + expect(hunkExcerpt(hunk, 'L', 2)).toEqual({ header: '@@ -1,8 +1,9 @@', lines: [' a', ' b', '-c', '+C', '+D', ' d', ' e'] }) + }) + + it('keeps every line of a short hunk without a header', () => { + expect(hunkExcerpt(' a\n+b', 'R', 1)).toEqual({ header: null, lines: [' a', '+b'] }) + }) +}) + +describe('thread quotes', () => { + it('summarizes a quote by file name, range, and first comment', () => { + expect(threadQuoteSummary(reviewThread({ path: 'src/a.ts' }), 'R3')).toEqual({ label: 'a.ts R3', title: 'src/a.ts', detail: 'R3', body: 'First comment' }) + expect(threadQuoteSummary(reviewThread({ path: 'a.ts', comments: [] }), null)).toEqual({ label: 'a.ts', title: 'a.ts', detail: 'a.ts', body: '' }) + }) + + it('formats a line thread with its hunk, state, and every comment quoted line by line', () => { + const thread: ForgeReviewThread = reviewThread({ + current: { commit: HEAD, startLine: 3, endLine: 5 }, diffHunk: '@@ -1 +1 @@\n-```\n+````', + comments: [reviewComment({ body: '# Heading\nsecond line', url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), + reviewComment({ author: null, body: 'reply' })], + }) + expect(formatThreadQuote(thread, 'https://github.com/octo/demo/pull/7', 2)).toBe([ + '## Review Thread 2', 'File: src/a.ts', 'Side: R', 'Lines: 3-5', `Commit: ${HEAD}`, 'State: unresolved', + 'Source: https://github.com/octo/demo/pull/7#discussion_r1', 'Diff hunk:', '`````diff', '@@ -1 +1 @@\n-```\n+````', '`````', + 'Comments:', '@reviewer (2026-11-05T08:00:00Z):', '> # Heading', '> second line', '', 'Unknown author (2026-11-05T08:00:00Z):', '> reply', + ].join('\n')) + }) + + it('formats an outdated single line at the lines it was written on, and a file thread without lines or hunk', () => { + const outdated = reviewThread({ current: null, resolved: true, original: { commit: OLD, startLine: 9, endLine: 9 }, diffHunk: null, + comments: [reviewComment({ url: null })] }) + expect(formatThreadQuote(outdated, 'https://github.com/octo/demo/pull/7', 1)).toBe([ + '## Review Thread 1', 'File: src/a.ts', 'Side: R', 'Lines: 9', `Commit: ${OLD}`, 'State: resolved, outdated', + 'Source: https://github.com/octo/demo/pull/7', 'Comments:', '@reviewer (2026-11-05T08:00:00Z):', '> First comment', + ].join('\n')) + const file = reviewThread({ subject: 'file', current: null, original: null, diffHunk: null }) + expect(formatThreadQuote(file, 'https://github.com/octo/demo/pull/7', 1)).toContain('File: src/a.ts\nLines: whole file\nState: unresolved\n') + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts new file mode 100644 index 0000000000..fe08cb6a60 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts @@ -0,0 +1,43 @@ +/** Host review threads and comments shared by the browser-side thread tests. */ + +import type { ForgeCommentId, ForgeReviewComment, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' + +let comments = 0 + +/** + * Build a comment by `reviewer` that has a web page. + * @param overrides - fields to replace. + * @returns the comment. + */ +export function reviewComment(overrides: Partial = {}): ForgeReviewComment { + comments += 1 + return { + id: `comment-${comments}` as ForgeCommentId, + author: { login: 'reviewer', avatarUrl: 'https://avatars.example/u/1', bot: false }, + body: 'First comment', + createdAt: '2026-11-05T08:00:00Z', + pending: false, + url: `https://github.com/octo/demo/pull/7#discussion_r${comments}`, + ...overrides, + } +} + +/** + * Build an unresolved new-side thread on line 3 of `src/a.ts`, written at the head `a…a` and placed there, with one comment. + * @param overrides - fields to replace. + * @returns the thread. + */ +export function reviewThread(overrides: Partial = {}): ForgeReviewThread { + return { + id: `thread-${comments + 1}` as ForgeThreadId, + path: 'src/a.ts', + side: 'R', + subject: 'line', + current: { commit: 'a'.repeat(40), startLine: 3, endLine: 3 }, + original: { commit: 'a'.repeat(40), startLine: 3, endLine: 3 }, + diffHunk: '@@ -1,3 +1,3 @@\n a\n-b\n+B', + resolved: false, + comments: [reviewComment()], + ...overrides, + } +} From f11daf3ad3d50769b8d07416473a5537dcb9b966 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 14:24:37 +0800 Subject: [PATCH 05/29] docs(forge): document review thread reads, the thread overlay, and the unsupported failure The forge subsystem page documents ctx.forge.readReview, its thread types, and the panel's changeRequestReview cache; the package READMEs describe the GitHub thread mapping, the overlay and thread list, and the new panel Config fields. An upgrade guide covers the unsupported ForgeFailure code. The Web e2e overlays scripted threads, opens them from the thread list, and sends a quoted thread through a replayed turn. --- .../review-thread-list.expected.md | 17 +++ .../review-thread-message.expected.md | 19 +++ .../forge-panel/review-threads.expected.md | 82 +++++++++++ apps/web/tests/forge-panel.e2e.ts | 90 +++++++++++- docs/config-catalog.md | 16 +- docs/config-catalog.zh.md | 16 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/subsystems/forge.i18n.yaml | 7 +- docs/subsystems/forge.md | 138 +++++++++++++++++- docs/subsystems/forge.zh.md | 138 +++++++++++++++++- .../forge-review-reads/guide.i18n.yaml | 16 ++ .../v0.2.2-rc.1/forge-review-reads/guide.md | 19 +++ .../forge-review-reads/guide.zh.md | 19 +++ .../client-ui-forge/README.i18n.yaml | 16 +- .../experimental/client-ui-forge/README.md | 13 +- .../experimental/client-ui-forge/README.zh.md | 13 +- .../client-ui-forge/src/client/ChangesTab.tsx | 2 +- .../src/client/ReviewThreads.tsx | 6 +- .../src/client/review-threads.ts | 4 +- .../tests/changes-tab.client.spec.tsx | 7 + .../tests/review-thread-cards.client.spec.tsx | 2 +- .../tests/review-threads.client.spec.ts | 4 +- .../forge-github/README.i18n.yaml | 12 +- packages/experimental/forge-github/README.md | 7 +- .../experimental/forge-github/README.zh.md | 7 +- .../experimental/forge-github/src/index.ts | 7 +- .../forge-github/tests/threads.spec.ts | 15 +- packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 2 + packages/experimental/forge/README.zh.md | 2 + .../extensions/tool-cordis/src/api-catalog.ts | 46 +++++- scripts/gen-cordis-catalog.ts | 1 + scripts/type-equiv.manifest.json | 35 +++++ 34 files changed, 727 insertions(+), 59 deletions(-) create mode 100644 apps/web/tests/expected/forge-panel/review-thread-list.expected.md create mode 100644 apps/web/tests/expected/forge-panel/review-thread-message.expected.md create mode 100644 apps/web/tests/expected/forge-panel/review-threads.expected.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.zh.md diff --git a/apps/web/tests/expected/forge-panel/review-thread-list.expected.md b/apps/web/tests/expected/forge-panel/review-thread-list.expected.md new file mode 100644 index 0000000000..0a2d0acbd7 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-thread-list.expected.md @@ -0,0 +1,17 @@ +- complementary "讨论列表,共 5 个": + - text: 讨论 5 + - button "关闭讨论列表" + - group "筛选讨论": + - button "未解决 4" + - button "已过期 1" + - button "已解决 1" + - button "需要我回复 0" + - heading "panel.md" [level=3] + - button "文件级讨论 Add a screenshot." + - heading "panel.ts" [level=3] + - button "R2 · 1 条回复 Why two?" + - button "L15 The old fifteen was a number." + - button "R15 Settled. 已解决" + - button "原在 R9 · 在 fffffff 上 This line moved. 已过期" + - text: github.com 上共 5 个讨论 · + - button "在 GitHub 中查看" diff --git a/apps/web/tests/expected/forge-panel/review-thread-message.expected.md b/apps/web/tests/expected/forge-panel/review-thread-message.expected.md new file mode 100644 index 0000000000..0ea820a2af --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-thread-message.expected.md @@ -0,0 +1,19 @@ +> ## Review Thread 1 +> File: src/panel.ts +> Side: R +> Lines: 2 +> Commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +> State: unresolved +> Source: https://github.com/octo/demo/pull/7#discussion_on-line_0 +> Diff hunk: +> ```diff +> @@ -1,5 +1,5 @@ +> export const n1 = 1 +> -export const n2 = 2 +> +export const n2 = 'two' +> ``` +> Comments: +> @lin (2026-10-09T00:00:00Z): +> > Why **two**? +> @octo (2026-10-09T00:00:00Z): +> > It reads better. diff --git a/apps/web/tests/expected/forge-panel/review-threads.expected.md b/apps/web/tests/expected/forge-panel/review-threads.expected.md new file mode 100644 index 0000000000..9b229274bd --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-threads.expected.md @@ -0,0 +1,82 @@ +- button "收起 panel.ts" [expanded] +- text: src/panel.ts +- button "panel.ts 有 3 条未解决的讨论,打开讨论列表": 3 条未解决 +- text: +2 −2 +- checkbox "将 panel.ts 标记为已审阅" +- button "panel.ts 的更多操作" +- button "选择第 L1 行": "1" +- text: export const n1 = 1 +- button "选择第 R1 行": "1" +- text: export const n1 = 1 +- button "选择第 L2 行": "2" +- text: export const n2 = 2 +- button "选择第 R2 行": "2" +- text: export const n2 = 'two' +- region "R2": + - text: R2 · 在 aaaaaaa 上 lin 2 小时前 + - paragraph: + - text: Why + - strong: two + - text: "?" + - text: octo 2 小时前 作者 + - paragraph: It reads better. + - button "添加到输入框" + - button "在 GitHub 中查看" +- button "选择第 L3 行": "3" +- text: export const n3 = 3 +- button "选择第 R3 行": "3" +- text: export const n3 = 3 +- button "选择第 L4 行": "4" +- text: export const n4 = 4 +- button "选择第 R4 行": "4" +- text: export const n4 = 4 +- button "选择第 L5 行": "5" +- text: export const n5 = 5 +- button "选择第 R5 行": "5" +- text: export const n5 = 5 +- button "6 行未变更" +- button "选择第 L12 行": "12" +- text: export const n12 = 12 +- button "选择第 R12 行": "12" +- text: export const n12 = 12 +- button "选择第 L13 行": "13" +- text: export const n13 = 13 +- button "选择第 R13 行": "13" +- text: export const n13 = 13 +- button "选择第 L14 行": "14" +- text: export const n14 = 14 +- button "选择第 R14 行": "14" +- text: export const n14 = 14 +- button "选择第 L15 行": "15" +- text: export const n15 = 15 +- button "选择第 R15 行": "15" +- text: export const n15 = 'fifteen' +- region "L15": + - text: L15 · 在 aaaaaaa 上 lin 2 小时前 + - paragraph: The old fifteen was a number. + - button "添加到输入框" + - button "在 GitHub 中查看" +- text: 已解决的讨论 · lin +- button "展开" +- button "选择第 L16 行": "16" +- text: export const n16 = 16 +- button "选择第 R16 行": "16" +- text: export const n16 = 16 +- button "选择第 L17 行": "17" +- text: export const n17 = 17 +- button "选择第 R17 行": "17" +- text: export const n17 = 17 +- button "选择第 L18 行": "18" +- text: export const n18 = 18 +- button "选择第 R18 行": "18" +- text: export const n18 = 18 +- button "其余未变更的行" +- text: 1 条讨论已过期:所在代码已被后续提交修改 +- button "收起" [expanded] +- region "原在 R9": + - text: 原在 R9 · 在 fffffff 上 已过期 + - button "查看当时的文件" + - text: "@@ -1,5 +1,5 @@ export const n1 = 1 -export const n2 = 2 +export const n2 = 'two' lin 2 小时前" + - paragraph: This line moved. + - button "添加到输入框" + - button "在 GitHub 中查看" diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index f66c449b52..1b0c0bc8fb 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -49,8 +49,9 @@ const run = promisify(execFile) * `pr-N.diff`, or, when `pr-N.refused` exists, fails with that JSON error body * and the matching diagnostic as GitHub's HTTP 406 refusal. The raw contents API * serves `contents.json`, keyed by `path@commit`, and the commit listing of pull - * request 7 serves `commits.json`, oldest first. Every invocation is appended to - * `calls.jsonl`. + * request 7 serves `commits.json`, oldest first. The review thread read serves + * `threads.json` as its one page of threads, with the viewer `octo`, or no threads + * without it. Every invocation is appended to `calls.jsonl`. */ const GH = `#!/usr/bin/env node import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' @@ -171,6 +172,13 @@ if (args[0] === 'api' && args[1] === 'graphql') { } } } } })) process.exit(0) } + if (query.includes('viewer { login }')) { + const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) + const threads = existsSync(join(here, 'threads.json')) ? JSON.parse(readFileSync(join(here, 'threads.json'), 'utf8')) : [] + process.stdout.write(JSON.stringify({ data: { viewer: { login: 'octo' }, repository: { pullRequest: { id: 'pull-' + number, + headRefOid: pulls[number].headRefOid, reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: threads } } } } })) + process.exit(0) + } if (query.includes('pullRequest(number: $number)')) { const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid, baseRefOid: BASE } } } })) @@ -1844,3 +1852,81 @@ it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a await page.keyboard.press('Escape') expect(tripwire.pageErrors).toEqual([]) }) + +/** One review thread node of pull request 7 as the GraphQL thread read returns it, its comments by `lin` then `octo`. */ +function threadNode( + id: string, fields: Record, bodies: readonly string[], commit: string = HEAD7, +): Record { + return { + id, isOutdated: false, isResolved: false, path: 'src/panel.ts', diffSide: 'RIGHT', startDiffSide: null, line: null, startLine: null, + originalLine: null, originalStartLine: null, subjectType: 'LINE', ...fields, + root: { nodes: [{ diffHunk: '@@ -1,5 +1,5 @@\n export const n1 = 1\n-export const n2 = 2\n+export const n2 = \'two\'', + commit: { oid: commit }, originalCommit: { oid: commit } }] }, + comments: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: bodies.map((body, index) => ({ + id: `${id}-${index}`, state: 'SUBMITTED', createdAt: '2026-10-09T00:00:00Z', url: `${PULL}#discussion_${id}_${index}`, body, + author: { __typename: 'User', login: index === 0 ? 'lin' : 'octo', avatarUrl: null }, + })) }, + } +} + +/** Threads of pull request 7: on new line 2, on old line 15, resolved on new line 15, outdated, and on the whole of `docs/panel.md`. */ +const THREADS = [ + threadNode('on-line', { line: 2, originalLine: 2 }, ['Why **two**?', 'It reads better.']), + threadNode('old-side', { diffSide: 'LEFT', line: 15, originalLine: 15 }, ['The old fifteen was a number.']), + threadNode('resolved', { isResolved: true, line: 15, originalLine: 15 }, ['Settled.']), + threadNode('outdated', { isOutdated: true, originalLine: 9 }, ['This line moved.'], 'f'.repeat(40)), + threadNode('whole-file', { path: 'docs/panel.md', subjectType: 'FILE' }, ['Add a screenshot.']), +] + +it.skipIf(MODE === 'record')('overlays the review threads of a change request and opens them from the thread list', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-threads', 'follow-up') + await writeFile(join(root, 'threads.json'), JSON.stringify(THREADS)) + // Comments were written two hours before the browser's clock, so their relative times stay fixed. + await page.clock.setFixedTime(Date.parse('2026-10-09T02:00:00Z')) + const { view, sessionId } = await openReview(page, scaffold) + const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') + const onLine = panel.locator('[data-forge-thread="on-line"]') + await onLine.getByText('two', { exact: true }).waitFor({ timeout: 20_000 }) + // The thread follows the row of its last line, under the new side. + expect(await onLine.evaluate(card => card.previousElementSibling?.querySelector('[data-new-line]')?.textContent)).toBe('export const n2 = \'two\'') + expect(await panel.locator('[data-forge-thread="old-side"]').evaluate(card => card.previousElementSibling?.querySelector('[data-old-line]')?.textContent)) + .toBe('export const n15 = 15') + await panel.locator('[data-forge-thread="resolved"]').getByText('已解决的讨论 · lin', { exact: true }).waitFor() + await panel.locator('[data-forge-outdated-threads]').getByText('1 条讨论已过期:所在代码已被后续提交修改', { exact: true }).waitFor() + await view.locator('[data-forge-diff-file="docs/panel.md"] [data-forge-thread="whole-file"]').getByText('文件级讨论', { exact: true }).waitFor() + await panel.getByRole('button', { name: 'panel.ts 有 3 条未解决的讨论,打开讨论列表', exact: true }).waitFor() + await view.getByRole('navigation').getByTitle('3 条未解决的讨论', { exact: true }).waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'review-threads.expected.md'), + await captureStableAria(page, '[data-forge-diff-file="src/panel.ts"]', scaffold.workspaceCwd), MODE) + + await view.getByRole('button', { name: '讨论列表,共 5 个', exact: true }).click() + const list = view.getByRole('complementary', { name: '讨论列表,共 5 个' }) + await expect.poll(() => list.getByRole('button', { pressed: true }).allTextContents()).toEqual(['未解决 4']) + await expect.poll(() => list.locator('[data-forge-thread-item]').evaluateAll(items => items.map(item => item.getAttribute('data-forge-thread-item')))) + .toEqual(['whole-file', 'on-line', 'old-side', 'outdated']) + await list.getByRole('button', { name: '已解决 1', exact: true }).click() + await list.locator('[data-forge-thread-item="resolved"]').click() + // Opening a resolved thread unfolds it inside its file. + await panel.locator('[data-forge-thread="resolved"]').getByText('Settled.', { exact: true }).waitFor() + await list.getByRole('button', { name: '已解决 1', exact: true }).click() + await list.getByRole('button', { name: '需要我回复 0', exact: true }).waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'review-thread-list.expected.md'), + await captureStableAria(page, '[data-forge-thread-list]', scaffold.workspaceCwd), MODE) + + await onLine.getByRole('button', { name: '添加到输入框', exact: true }).click() + await page.locator('[data-composer-input]').first().getByText('panel.ts R2', { exact: true }).first().waitFor() + const sent = scaffold.whenTurnSettled() + await page.locator('[data-composer-input]').first().press('Enter') + await sent + await page.getByText(FOLLOW_UP_REPLY, { exact: true }).waitFor() + // The quoted thread reaches the model only inside the ordinary logged user message. + const quotes = (await readPersistedEvents(scaffold, sessionId)).flatMap(event => event.type === 'user/message' + ? event.data.content.flatMap(block => block.type === 'text' && block.text.includes('## Review Thread') ? [block.text] : []) : []) + expect(quotes).toHaveLength(1) + await compareOrRefreshGolden(join(EXPECTED, 'review-thread-message.expected.md'), quotes.join('').trimEnd(), MODE) + const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[]) + const reads = calls.filter(args => args.some(arg => arg.startsWith('query=') && arg.includes('viewer { login }'))) + expect(reads.length).toBeGreaterThan(0) + expect(reads[0]).toEqual(expect.arrayContaining(['owner=octo', 'name=demo', 'number=7', 'first=100'])) + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d85683e33e..e68110b349 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1121,6 +1121,13 @@ export interface Config { * `testPaths` and before the built-in rules. */ interfacePaths?: string[] + /** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */ + maxCachedReviewBytes?: number + /** + * Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull + * request's update time does not change when a thread is resolved. + */ + reviewRefreshMs?: number } ``` @@ -1188,7 +1195,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:273`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:359`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1222,9 +1229,12 @@ export interface Config { hosts?: string[] /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number - /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ + /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */ maxOutputBytes?: number - /** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */ + /** + * Most review threads counted per pull request in one status read, which reports a lower bound past it, and read in + * one review read, which reports itself truncated past it. + */ maxReviewThreads?: number /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ maxCommits?: number diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index ceab76dfec..1956f19ac1 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1123,6 +1123,13 @@ export interface Config { * `testPaths` and before the built-in rules. */ interfacePaths?: string[] + /** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */ + maxCachedReviewBytes?: number + /** + * Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull + * request's update time does not change when a thread is resolved. + */ + reviewRefreshMs?: number } ``` @@ -1190,7 +1197,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:273`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:359`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1224,9 +1231,12 @@ export interface Config { hosts?: string[] /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number - /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ + /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */ maxOutputBytes?: number - /** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */ + /** + * Most review threads counted per pull request in one status read, which reports a lower bound past it, and read in + * one review read, which reports itself truncated past it. + */ maxReviewThreads?: number /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ maxCommits?: number diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index b4cffaf1aa..d157809e13 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -47,7 +47,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | -| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index b1b58ef08a..194d956a4f 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -49,7 +49,7 @@ | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | -| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 97ebf7bece..1407e29d9d 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -14,9 +14,12 @@ /forges/change-request-actions: en: 87d2c81d9514267f zh: 1daf31c5b0127a1c +/forges/review-threads: + en: 351af1e634f70a40 + zh: 2f0bba65d3b01277 /forges/session-bindings: en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: e52a5c57abc4d30e - zh: 509a40f421cc3d33 + en: 11b157e9debe81cd + zh: b197644deabe727d diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index b5156c101f..0a632c5de1 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -47,6 +47,12 @@ interface ForgeProvider { readonly forge: string /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise + /** + * Read the review threads of a change request at head commit `headSha`. The threads are returned only when the + * read names `headSha` as the head; once the head is another commit, the read resolves to a `stale` failure. + * Omission declares that this provider cannot read reviews. + */ + readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ @@ -238,9 +244,9 @@ interface ForgeFailure { * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of - * a later status can succeed; `unavailable`: any other failure. + * a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -328,6 +334,104 @@ type ForgeReviewResult = | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } ``` +## Review threads + +`ctx.forge.readReview(ref, headSha, signal)` reads the review threads of a change request at one head commit. The provider returns `ForgeReviewData` only when the read names `headSha` as the head; otherwise it returns `stale`, which polls a watched change request again at once, as a stale diff read does. For a provider without `readReview` the service returns `unsupported`, so consumers show no threads instead of a failure. A line thread has two positions: `original` on the commit it was written on, and `current` on the head of the read, which is null once the host no longer places the thread on that commit. A consumer that shows the head's diff places a thread at `current` and shows the others with their `diffHunk`; reading the file at `original.commit` through `fileText` shows the whole file the thread was written on. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns how GitHub's fields map onto these positions. + +```ts type-equiv +/** Opaque host identity of one review thread. */ +type ForgeThreadId = Branded<'ForgeThreadId'> +``` + +```ts type-equiv +/** Opaque host identity of one review comment. */ +type ForgeCommentId = Branded<'ForgeCommentId'> +``` + +```ts type-equiv +/** Consecutive lines of one file at one commit. */ +interface ForgeAnchor { + /** Full object name of the commit whose file the lines number. */ + readonly commit: string + /** First line, inclusive. */ + readonly startLine: number + /** Last line, inclusive. */ + readonly endLine: number +} +``` + +```ts type-equiv +/** Account that wrote a review comment. */ +interface ForgeCommentAuthor { + /** Login as the host spells it. */ + readonly login: string + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether the account is an app or bot rather than a person. */ + readonly bot: boolean +} +``` + +```ts type-equiv +/** One comment of a review thread. */ +interface ForgeReviewComment { + /** Host identity of the comment. */ + readonly id: ForgeCommentId + /** Author, or null when the account no longer exists. */ + readonly author: ForgeCommentAuthor | null + /** Markdown source as the author wrote it; it may contain raw HTML, which readers must not render as HTML. */ + readonly body: string + /** ISO 8601 time the comment was created. */ + readonly createdAt: string + /** Whether the comment belongs to the signed-in user's review that is not submitted yet, which only that user sees. */ + readonly pending: boolean + /** Web page of the comment, or null when the host reports none. */ + readonly url: string | null +} +``` + +```ts type-equiv +/** + * One review thread on a file of a change request. A line thread has two positions: `original` on the commit it was + * written on, and `current` on the head commit of the read. `current` is null once the host no longer places the + * thread on the head commit, as after later commits changed its lines. + */ +interface ForgeReviewThread { + /** Host identity of the thread. */ + readonly id: ForgeThreadId + /** Repository-relative path the thread is on. */ + readonly path: string + /** Old (`L`) or new (`R`) side of the diff the lines number. */ + readonly side: 'L' | 'R' + /** Whether the thread is on lines or on the whole file. */ + readonly subject: 'line' | 'file' + /** Lines at the head commit of the read, whose `commit` is that head; null for an outdated or file thread. */ + readonly current: ForgeAnchor | null + /** Lines at the commit the thread was written on; null for a file thread. */ + readonly original: ForgeAnchor | null + /** Diff hunk the host recorded when the thread was written, ending at its last line; null when it recorded none. */ + readonly diffHunk: string | null + /** Whether the thread is marked resolved. */ + readonly resolved: boolean + /** Comments oldest first; the first starts the thread. */ + readonly comments: readonly ForgeReviewComment[] +} +``` + +```ts type-equiv +/** Review threads of a change request read at one head commit. */ +interface ForgeReviewData { + /** Head commit the threads were read at; `current` positions number its files. */ + readonly headSha: string + /** Login of the signed-in user the provider read as, or null when the host does not name one. */ + readonly viewer: string | null + /** Threads in host order, at most the provider's limit. */ + readonly threads: readonly ForgeReviewThread[] + /** Whether the change request has more threads than `threads` holds. */ + readonly truncated: boolean +} +``` + ## Session bindings `ctx.forgeSession` derives each Session's bindings from its own log: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results trigger head-branch discovery through `ctx.forge`; the panel also reports the branch its checkout tracks for the same discovery. Track, dismiss, and discovery actions are `plugin:forge-session/binding` records, which stay outside the model-visible conversation. The `forgeChangeRequests` projection's client view, which the Session summary carries, lists the bindings without their status. The [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition and discovery rules. @@ -617,6 +721,8 @@ type ForgeChangeRequestStatesFrame = The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows. +`changeRequestReview(session, url, headSha)` reads the threads of a bound change request at the head of the diff the view shows and refuses another head with `forgePanel/stale-head`, `forgePanel/review-unsupported` for a provider without review reads, and `forgePanel/review-failed` otherwise. It keeps one read per change request in memory, keyed by head commit and the status's update time and bounded by `maxCachedReviewBytes`, and reads again once the kept read is `reviewRefreshMs` old: on GitHub a new comment or reply changes a pull request's update time, but resolving a thread does not. The changes view asks again at every status it receives while visible, and overlays the threads on the files the [panel README](../../packages/experimental/client-ui-forge/README.md#use-this-package) describes. + ```ts type-equiv /** * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order @@ -916,6 +1022,17 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Read the review threads of a change request at one head commit. A + * `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param headSha - head commit the threads must be read at, usually the head of the displayed diff. + * @param signal - cancellation of the read. + * @returns the threads read at `headSha`, or why the host did not provide them; `unsupported` when the provider cannot read reviews. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** * List the commits of a change request at its current head. * @param ref - change request served by a registered provider. @@ -1186,6 +1303,23 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read + * at the same head commit and update time are reused from memory, for any Session, until they are + * `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age shows threads resolved + * since, which do not change a GitHub pull request's update time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param headSha - head commit of the displayed diff. + * @param signal - request cancellation. + * @returns the threads at `headSha`, with `current` positions numbering the files of that diff. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again; + * `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the + * status was read and when the host does not provide the threads otherwise. + */ +@Remote async changeRequestReview(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + /** * Publish a line comment or completed review for a visible Session binding. * @param session - Session retaining the change request. diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 2ca42cde71..3c4459101f 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -47,6 +47,12 @@ interface ForgeProvider { readonly forge: string /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise + /** + * Read the review threads of a change request at head commit `headSha`. The threads are returned only when the + * read names `headSha` as the head; once the head is another commit, the read resolves to a `stale` failure. + * Omission declares that this provider cannot read reviews. + */ + readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ @@ -238,9 +244,9 @@ interface ForgeFailure { * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of - * a later status can succeed; `unavailable`: any other failure. + * a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -328,6 +334,104 @@ type ForgeReviewResult = | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } ``` +## 评审讨论 + +`ctx.forge.readReview(ref, headSha, signal)` 读取变更请求在某个 head 提交处的评审讨论。只有当读取时的 head 就是 `headSha` 时,提供方才返回 `ForgeReviewData`;否则返回 `stale`,并像 diff 读取遇到 `stale` 时一样,立即重新轮询被关注的变更请求。提供方没有实现 `readReview` 时,服务返回 `unsupported`,使用方据此不显示讨论,也不报错。行级讨论有两套位置:`original` 是写下讨论时所在提交上的行,`current` 是本次读取的 head 上的行;托管平台不再把讨论放在该提交上时,`current` 为 null。显示 head diff 的使用方把讨论放在 `current` 位置,其余讨论用 `diffHunk` 展示;用 `fileText` 读取 `original.commit` 上的文件,可以看到写下讨论时的完整文件。GitHub 各字段如何映射到这两套位置,由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。 + +```ts type-equiv +/** Opaque host identity of one review thread. */ +type ForgeThreadId = Branded<'ForgeThreadId'> +``` + +```ts type-equiv +/** Opaque host identity of one review comment. */ +type ForgeCommentId = Branded<'ForgeCommentId'> +``` + +```ts type-equiv +/** Consecutive lines of one file at one commit. */ +interface ForgeAnchor { + /** Full object name of the commit whose file the lines number. */ + readonly commit: string + /** First line, inclusive. */ + readonly startLine: number + /** Last line, inclusive. */ + readonly endLine: number +} +``` + +```ts type-equiv +/** Account that wrote a review comment. */ +interface ForgeCommentAuthor { + /** Login as the host spells it. */ + readonly login: string + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether the account is an app or bot rather than a person. */ + readonly bot: boolean +} +``` + +```ts type-equiv +/** One comment of a review thread. */ +interface ForgeReviewComment { + /** Host identity of the comment. */ + readonly id: ForgeCommentId + /** Author, or null when the account no longer exists. */ + readonly author: ForgeCommentAuthor | null + /** Markdown source as the author wrote it; it may contain raw HTML, which readers must not render as HTML. */ + readonly body: string + /** ISO 8601 time the comment was created. */ + readonly createdAt: string + /** Whether the comment belongs to the signed-in user's review that is not submitted yet, which only that user sees. */ + readonly pending: boolean + /** Web page of the comment, or null when the host reports none. */ + readonly url: string | null +} +``` + +```ts type-equiv +/** + * One review thread on a file of a change request. A line thread has two positions: `original` on the commit it was + * written on, and `current` on the head commit of the read. `current` is null once the host no longer places the + * thread on the head commit, as after later commits changed its lines. + */ +interface ForgeReviewThread { + /** Host identity of the thread. */ + readonly id: ForgeThreadId + /** Repository-relative path the thread is on. */ + readonly path: string + /** Old (`L`) or new (`R`) side of the diff the lines number. */ + readonly side: 'L' | 'R' + /** Whether the thread is on lines or on the whole file. */ + readonly subject: 'line' | 'file' + /** Lines at the head commit of the read, whose `commit` is that head; null for an outdated or file thread. */ + readonly current: ForgeAnchor | null + /** Lines at the commit the thread was written on; null for a file thread. */ + readonly original: ForgeAnchor | null + /** Diff hunk the host recorded when the thread was written, ending at its last line; null when it recorded none. */ + readonly diffHunk: string | null + /** Whether the thread is marked resolved. */ + readonly resolved: boolean + /** Comments oldest first; the first starts the thread. */ + readonly comments: readonly ForgeReviewComment[] +} +``` + +```ts type-equiv +/** Review threads of a change request read at one head commit. */ +interface ForgeReviewData { + /** Head commit the threads were read at; `current` positions number its files. */ + readonly headSha: string + /** Login of the signed-in user the provider read as, or null when the host does not name one. */ + readonly viewer: string | null + /** Threads in host order, at most the provider's limit. */ + readonly threads: readonly ForgeReviewThread[] + /** Whether the change request has more threads than `threads` holds. */ + readonly truncated: boolean +} +``` + ## Session 绑定 `ctx.forgeSession` 从每个 Session 自己的日志派生其绑定:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果通过 `ctx.forge` 触发按 head 分支的发现;面板也会报告其检出所跟踪的分支,触发同样的发现。track、dismiss 与发现操作都是 `plugin:forge-session/binding` 插件记录,位于模型可见对话之外。`forgeChangeRequests` 投影的客户端视图随 Session 摘要下发,列出绑定但不含其状态。识别与发现规则见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。 @@ -617,6 +721,8 @@ type ForgeChangeRequestStatesFrame = 变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更(提供方只返回描述该 head 提交的补丁),或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。 +`changeRequestReview(session, url, headSha)` 在视图所显示 diff 的 head 处读取已绑定变更请求的讨论;head 不同时以 `forgePanel/stale-head` 拒绝,提供方不支持读取讨论时返回 `forgePanel/review-unsupported`,其他失败返回 `forgePanel/review-failed`。每个变更请求在内存里保留一次读取结果,以 head 提交和状态的更新时间为键、受 `maxCachedReviewBytes` 约束,保留时间达到 `reviewRefreshMs` 后重新读取:在 GitHub 上,新评论和回复会改变 PR 的更新时间,解决讨论则不会。变更视图可见时,每收到一次状态就重新请求一次,并按[面板 README](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package) 所述把讨论叠加到文件上。 + ```ts type-equiv /** * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order @@ -916,6 +1022,17 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Read the review threads of a change request at one head commit. A + * `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param headSha - head commit the threads must be read at, usually the head of the displayed diff. + * @param signal - cancellation of the read. + * @returns the threads read at `headSha`, or why the host did not provide them; `unsupported` when the provider cannot read reviews. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** * List the commits of a change request at its current head. * @param ref - change request served by a registered provider. @@ -1186,6 +1303,23 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read + * at the same head commit and update time are reused from memory, for any Session, until they are + * `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age shows threads resolved + * since, which do not change a GitHub pull request's update time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param headSha - head commit of the displayed diff. + * @param signal - request cancellation. + * @returns the threads at `headSha`, with `current` positions numbering the files of that diff. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again; + * `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the + * status was read and when the host does not provide the threads otherwise. + */ +@Remote async changeRequestReview(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + /** * Publish a line comment or completed review for a visible Session binding. * @param session - Session retaining the change request. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.i18n.yaml new file mode 100644 index 0000000000..8377a14f8a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.md +/: + en: 53dbdc67362a5851 + zh: 9c7b2c4dd31cf666 +/forge-failures-report-unsupported-reads: + en: 3e5488f3008886b7 + zh: 8123e954c41d559c +/forge-failures-report-unsupported-reads/change: + en: 77712ff12908e838 + zh: 00714f77f3b7ae80 +/forge-failures-report-unsupported-reads/migration: + en: 698a34a7e09be2be + zh: a32a64dc130f496f diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.md new file mode 100644 index 0000000000..d6c6aa2962 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "ForgeFailure gains the unsupported code, which ctx.forge.readReview returns for a provider without review reads." +--- + +# Forge failures report unsupported reads + +English | [中文](guide.zh.md) + +## Change + +`ForgeFailure['code']` gains `unsupported`. `ctx.forge.readReview(ref, headSha, signal)`, new beside the optional `ForgeProvider.readReview`, returns it when the provider of the change request does not read review threads. Other reads keep their codes: a provider without `fetchChecks` still makes `ctx.forge.fetchChecks` return `unavailable`. + +This affects code that switches exhaustively over `ForgeFailure['code']`, such as a `Record` lookup or a `switch` that ends in `assertNever`. All types come from `@deepseek-ai/dsh-experimental-forge`. Providers need no change: `readReview` is optional. + +## Migration + +1. Handle `unsupported` wherever code switches exhaustively over `ForgeFailure['code']`; treat it as a capability the provider lacks, not as a failed read to retry. +2. Run your type check; it succeeds when no `ForgeFailure` code is unhandled. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.zh.md new file mode 100644 index 0000000000..75f8a1057e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-review-reads/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "ForgeFailure 新增 unsupported 代码;提供方不支持读取评审讨论时,ctx.forge.readReview 返回它。" +--- + +# Forge 失败代码报告不支持的读取 + +[English](guide.md) | 中文 + +## 变更 + +`ForgeFailure['code']` 新增 `unsupported`。新增的 `ctx.forge.readReview(ref, headSha, signal)` 对应可选的 `ForgeProvider.readReview`;变更请求的提供方不支持读取评审讨论时,它返回 `unsupported`。其他读取的代码不变:提供方未实现 `fetchChecks` 时,`ctx.forge.fetchChecks` 仍返回 `unavailable`。 + +受影响的是对 `ForgeFailure['code']` 做穷举的代码,例如 `Record` 查表,或以 `assertNever` 结尾的 `switch`。所有类型都来自 `@deepseek-ai/dsh-experimental-forge`。提供方无需修改:`readReview` 是可选方法。 + +## 迁移 + +1. 在所有对 `ForgeFailure['code']` 做穷举的地方处理 `unsupported`,把它当作提供方缺少的能力,而不是需要重试的读取失败。 +2. 运行类型检查;没有未处理的 `ForgeFailure` 代码时即通过。 diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 5b25741184..a0392da274 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: 05ee6d9ba0b8d2c7 - zh: 98c988e8f957511f + en: e9ecdf9670bd6324 + zh: 6f5e3027afb18a3e /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 7495fe1e0d0ee643 - zh: f820a5790ae6e2a7 + en: 78cab599dbd4aa57 + zh: 87265844f34efbc5 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience: - en: 10101427d1e0589b - zh: c981cec12f64eb75 + en: 795766e162ebf4df + zh: 893de3302798330a /deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect: en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 5e29ac36aad15d02 - zh: e46339bb637a69ef + en: 70d01fb04317f94a + zh: 6a287a063603f61d /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 27ff8a01c3..190c23e7d0 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -41,12 +41,13 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **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. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. - **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. +- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads; the count in a header, like the Threads toolbar button, opens the thread list, which groups the threads by file in file tree order, filters Unresolved, Outdated, Resolved, or Awaiting my reply, which keeps unresolved threads the signed-in user wrote in where someone else wrote last, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list names a truncated read. A thread offers only Add to input, which quotes the whole thread, and View on GitHub. Threads are read again at each status while the view shows; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior. -`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). +`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. The GitHub split button starts or adds to a pending review; its menu publishes a single comment immediately. Comments remain beside their code after quoting, queueing, or publishing. Pending comments are edited or removed there. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. Added and deleted files show only their populated line-number column. Pending reviews and comment records are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears its comments, summary, and decision, and reopening starts an empty review. Published GitHub comments and references already added to the main composer are unaffected. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. @@ -69,7 +70,7 @@ 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`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestReview` acts on the same visible bindings, refuses a head other than the latest status's with `forgePanel/stale-head` before reading, and reads the provider's `readReview`, mapping `stale` to `forgePanel/stale-head`, `unsupported` to `forgePanel/review-unsupported`, and other failures to `forgePanel/review-failed`. It keeps one read per change request, keyed by head commit and update time, drops the least recently read once the kept reads exceed `maxCachedReviewBytes` as JSON, and reads again once a kept read is `reviewRefreshMs` old, since resolving a GitHub thread leaves the update time unchanged. `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. @@ -95,6 +96,11 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | Lens, test file switch, and viewed progress | | [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | Commit picker | | [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | Viewed marks kept in the browser | +| [`src/client/ReviewThreads.tsx`](src/client/ReviewThreads.tsx) | Review thread cards and the outdated section | +| [`src/client/ThreadList.tsx`](src/client/ThreadList.tsx) | Thread list | +| [`src/client/review-threads.ts`](src/client/review-threads.ts) | Thread places, list filters, hunk excerpts, and thread quotes | +| [`src/client/thread-state.ts`](src/client/thread-state.ts) | Thread reads and their places in the shown changes | +| [`src/review-cache.ts`](src/review-cache.ts) | Review threads kept in memory | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card | @@ -117,7 +123,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, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. +Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. Add to input on a review thread contributes a frozen `## Review Thread N` quote with File, Side, Lines, the commit those lines number, State, Source, the recorded diff hunk, and every comment's author, time, and body quoted line by line. #### KV Cache effect @@ -140,6 +146,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **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. - **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. +- **Review thread actions** — threads are read-only: replying, resolving, and editing comments, and drafts in GitHub's pending review, are deferred to the provider's review writes. Minimized comments show like others, and avatars load from the code host's image server in the browser. - **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. - **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 4aca1d2c38..f7ced4299b 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -41,12 +41,13 @@ kind: "package-reference" - **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 - **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 +- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数;点击文件标题上的计数或工具栏的“讨论”按钮会打开讨论列表。列表按文件树顺序分组,可按未解决、已过期、已解决和“需要我回复”筛选(“需要我回复”保留当前登录用户参与过、且最后一条评论来自他人的未解决讨论),点击讨论会跳到它的位置;若所选提交中没有该讨论,会先切换到全部提交。读取被截断时,列表会注明。讨论上只有“添加到输入框”(把整个讨论作为引用插入)和“在 GitHub 中查看”两个操作。视图显示期间,每收到一次状态就重新读取讨论;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。 -`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 +`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 “全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。GitHub 分段按钮用于开始或加入待提交评审,下拉菜单可以立即发布单条评论。评论在引用、暂存或发布后保留在对应代码旁,暂存评论可在那里编辑或删除。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。新建和删除文件只显示有内容的一侧行号。待提交评审与评论记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空该页签的评论、总结与评审决定,重新打开从空评审开始。已发布到 GitHub 的评论与已加入主输入框的引用不受影响。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 @@ -69,7 +70,7 @@ 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` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。`changeRequestReview` 同样只作用于可见的绑定;head 与最新状态的 head 不同时,读取前就以 `forgePanel/stale-head` 拒绝;随后调用提供方的 `readReview`,把 `stale` 映射为 `forgePanel/stale-head`、`unsupported` 映射为 `forgePanel/review-unsupported`、其余失败映射为 `forgePanel/review-failed`。每个变更请求保留一次读取结果,以 head 提交和更新时间为键;保留的结果按 JSON 计超过 `maxCachedReviewBytes` 时,最久未读的先被丢弃;保留时间达到 `reviewRefreshMs` 后重新读取,因为解决 GitHub 讨论不会改变更新时间。 `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 存储服务时,流以失败结束。 @@ -95,6 +96,11 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | 分层透镜、测试文件开关与已审阅进度 | | [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | 提交选择器 | | [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | 保存在浏览器中的已审阅标记 | +| [`src/client/ReviewThreads.tsx`](src/client/ReviewThreads.tsx) | 评审讨论卡片与已过期区域 | +| [`src/client/ThreadList.tsx`](src/client/ThreadList.tsx) | 讨论列表 | +| [`src/client/review-threads.ts`](src/client/review-threads.ts) | 讨论位置、列表筛选、hunk 摘录与讨论引用 | +| [`src/client/thread-state.ts`](src/client/thread-state.ts) | 读取讨论并确定它们在所显示变更中的位置 | +| [`src/review-cache.ts`](src/review-cache.ts) | 保存在内存中的评审讨论 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | @@ -117,7 +123,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 评审提交不会增加模型上下文。对评审讨论使用“添加到输入框”时,会加入一段固定的 `## Review Thread N` 引用,包含 File、Side、Lines、这些行号所在的提交、State、Source、记录下的 diff hunk,以及逐行引用的每条评论的作者、时间和正文。 #### KV Cache 影响 @@ -140,6 +146,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 +- **评审讨论的操作**——讨论是只读的:回复、解决、编辑评论,以及 GitHub 待提交评审中的草稿,留待提供方的评审写入能力实现。被折叠隐藏的评论与其他评论显示方式相同;头像由浏览器从代码托管平台的图片服务器加载。 - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 5763304362..d550841145 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -947,7 +947,7 @@ export function ChangesTab({
} - {review !== null && ( + {review !== null && review.threads.length > 0 && (
} const original = place.kind === 'outdated' && thread.original !== null ? thread.original : null + const label = original !== null ? t('thread.originally', { range: anchorRange(thread.side, original) }) : range ?? t('thread.fileLevel') return
+ data-resolved={thread.resolved ? '' : undefined} aria-label={label}>
- {original !== null ? t('thread.originally', { range: anchorRange(thread.side, original) }) - : range ?? t('thread.fileLevel')} + {label} {commit !== null && <> · {t('thread.onCommit', { commit })}} {place.kind === 'outdated' && {t('thread.outdatedTag')}} diff --git a/packages/experimental/client-ui-forge/src/client/review-threads.ts b/packages/experimental/client-ui-forge/src/client/review-threads.ts index 831b2acc0a..5080059646 100644 --- a/packages/experimental/client-ui-forge/src/client/review-threads.ts +++ b/packages/experimental/client-ui-forge/src/client/review-threads.ts @@ -164,8 +164,10 @@ export function formatThreadQuote(thread: ForgeReviewThread, url: string, index: const state = [thread.resolved ? 'resolved' : 'unresolved', ...thread.subject === 'line' && thread.current === null ? ['outdated'] : []].join(', ') const fence = thread.diffHunk === null ? '' : '`'.repeat(Math.max(3, ...Array.from(thread.diffHunk.matchAll(/`+/g), match => match[0].length + 1))) const hunk = thread.diffHunk === null ? '' : `Diff hunk:\n${fence}diff\n${thread.diffHunk}\n${fence}\n` + // A blank comment line becomes a bare `>` and comments follow one another without blank lines, since the composer + // quotes every line of the reference again. const comments = thread.comments.map(comment => `${comment.author === null ? 'Unknown author' : `@${comment.author.login}`} (${comment.createdAt}):\n` - + comment.body.split('\n').map(line => `> ${line}`).join('\n')).join('\n\n') + + comment.body.split('\n').map(line => line.trim() === '' ? '>' : `> ${line}`).join('\n')).join('\n') const link = thread.comments[0]?.url ?? url return `## Review Thread ${index}\nFile: ${thread.path}\n${where}\nState: ${state}\nSource: ${link}\n${hunk}Comments:\n${comments}` } 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 9cbb1f9656..88485d2ea6 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 @@ -1786,6 +1786,13 @@ describe('ChangesTab review threads', () => { expect(card(m, 'on-row')).toBeNull() }) + it('offers no thread list for a change request without threads', async () => { + const m = mount({ source, setup: reviewed({ ...REVIEW, threads: [] }) }) + await settle() + expect(m.faces.changeRequestReview).toHaveBeenCalledOnce() + expect(m.view.queryByRole('button', { name: /^Review threads/ })).toBeNull() + }) + it('names no author when the host hides the change request\'s author', async () => { const m = mount({ source, state: ready({ changeRequests: [entry(7, snapshot(7, { author: null }))] }), setup: reviewed({ ...REVIEW, threads: [line('on-row', 'src/app.ts', 'R', 4, { comments: [reviewComment({ author: { login: 'octo', avatarUrl: null, bot: false } })] })] }) }) diff --git a/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx index b6173e7853..b29d22434b 100644 --- a/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx @@ -108,7 +108,7 @@ describe('ThreadCard', () => { let answer: (value: RemoteResult) => void = () => {} const shared = actions({ readText: vi.fn(() => new Promise>((resolve) => { answer = resolve })) }) const view = render() - const card = view.getByRole('region', { name: en['thread.fileLevel'] }) + const card = view.getByRole('region', { name: 'Originally R2–3' }) expect(card.textContent).toContain(`Originally R2–3 · on ${OLD.slice(0, 7)}`) expect([...card.querySelectorAll('[class*="excerptLine"]')].map(line => line.textContent)).toEqual(['@@ -1 +1,3 @@', ' a', '+b', '+c']) fireEvent.click(view.getByRole('button', { name: en['thread.viewOriginal'] })) diff --git a/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts b/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts index 2942e99f8a..1d793a7fc3 100644 --- a/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts @@ -109,13 +109,13 @@ describe('thread quotes', () => { it('formats a line thread with its hunk, state, and every comment quoted line by line', () => { const thread: ForgeReviewThread = reviewThread({ current: { commit: HEAD, startLine: 3, endLine: 5 }, diffHunk: '@@ -1 +1 @@\n-```\n+````', - comments: [reviewComment({ body: '# Heading\nsecond line', url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), + comments: [reviewComment({ body: '# Heading\n\nsecond line', url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), reviewComment({ author: null, body: 'reply' })], }) expect(formatThreadQuote(thread, 'https://github.com/octo/demo/pull/7', 2)).toBe([ '## Review Thread 2', 'File: src/a.ts', 'Side: R', 'Lines: 3-5', `Commit: ${HEAD}`, 'State: unresolved', 'Source: https://github.com/octo/demo/pull/7#discussion_r1', 'Diff hunk:', '`````diff', '@@ -1 +1 @@\n-```\n+````', '`````', - 'Comments:', '@reviewer (2026-11-05T08:00:00Z):', '> # Heading', '> second line', '', 'Unknown author (2026-11-05T08:00:00Z):', '> reply', + 'Comments:', '@reviewer (2026-11-05T08:00:00Z):', '> # Heading', '>', '> second line', 'Unknown author (2026-11-05T08:00:00Z):', '> reply', ].join('\n')) }) diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index c329bf236f..6d3ca2d441 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: 0f8041e0380036c9 - zh: 63cbdc82c9f438d4 + en: dc1fc7eb436482c8 + zh: 968aa86136fdd840 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: - en: f98e77171cba809f - zh: 1b330cb342d69efe + en: f3d0a577b0a4db0a + zh: 0c15ac7979909117 /deepseek-ai-dsh-experimental-forge-github/further-exploration: en: d377d5fd9d9f190e zh: 920bcbfdb8c993f2 @@ -30,8 +30,8 @@ en: 26b946af4b742e17 zh: 00b34f0721ac72f6 /deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work: - en: 9f13ae6d928e4ef7 - zh: 09a549b1655f4de3 + en: b5ad30bb209cdd48 + zh: eaea2d4cbe350ce4 /deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 84a261269a..0d5f8ea6b6 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -50,6 +50,8 @@ A pull request is `mergeReady` when it is open, not a draft, GitHub reports its Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. +`readReview` reads review threads with one GraphQL query that names `headRefOid` and the signed-in viewer, and returns `stale` when the head is not the requested commit. It reads threads in pages of up to 100 until it has read `maxReviewThreads` of them, each page after the first naming the head again, so a push during the read returns `stale`; it reads every comment of each thread, and the commits and `diffHunk` of a thread's first comment once. All pages together, measured as JSON, must fit `maxOutputBytes`: the page that would pass it is dropped with the threads after it, and the result is marked `truncated`, as when more than `maxReviewThreads` threads exist. A thread on lines gets a `current` position only when GitHub reports it not outdated, with a `line`, and its first comment's `commit` is the head: a comment written on an earlier commit after a force-push keeps a `line` that numbers that commit, and GitHub can mark a thread outdated while keeping its `line`. `original` comes from `originalLine` and `originalStartLine` at the first comment's `originalCommit`; `subjectType: FILE` threads have neither. A range whose start is on the other side of the diff keeps its last line. Threads without comments are left out. REST's `position` does not tell outdated threads apart and is not read. + ----- @@ -66,6 +68,7 @@ A fetch groups references by host and sends one initial `gh api graphql` query p | [`src/provider.ts`](src/provider.ts) | URL mapping, host grouping, and failure classification | | [`src/graphql.ts`](src/graphql.ts) | Query construction and response validation and mapping | | [`src/compare.ts`](src/compare.ts) | Patch between two commits through the compare API, shared by every diff read | +| [`src/threads.ts`](src/threads.ts) | Review thread read, pagination, and mapping onto head and original positions | | [`src/gh.ts`](src/gh.ts) | Host `gh` execution with environment scrubbing and limits | | [`src/urls.ts`](src/urls.ts) | Remote URL and pull request URL parsing, and validation of inlined names and commits | @@ -96,11 +99,11 @@ None. Provider output reaches only host-side watchers. - **GitHub CLI on the host** — `gh` must be installed and signed in for each configured host; tokens in environment variables are not forwarded. Hosts missing from `hosts` are never read, including references retained across configuration changes. A status fetch returns `unavailable` for those references; a head lookup rejects before starting `gh`. -- **Review thread bound** — a status read counts at most `maxReviewThreads` review threads per pull request; beyond it `unresolvedThreads` is a lower bound that `threadsTruncated` marks. +- **Review thread bound** — a status read counts, and a review read reads, at most `maxReviewThreads` review threads per pull request; beyond it `unresolvedThreads` is a lower bound that `threadsTruncated` marks, and a review read is `truncated`. - **Batch deadline** — continuation pages of a pull request with many review threads lengthen its host's polling batch; a batch that outlives `ctx.forge`'s `fetchTimeoutMs` reports `unavailable` for every pull request in it, not only for the one with many threads. - **Rewritten base branch** — the diff starts from the merge base of the head and the base commit GitHub recorded at the pull request's last update. After the base branch is force-pushed, that merge base can differ from the one GitHub's pull request view uses, so the patch can include or omit commits until the pull request is updated. - **No fork discovery** — head lookups exclude pull requests whose head is in another repository. -- **Rate limits** — every poll costs one GraphQL query per host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request. All count against the signed-in account’s rate limit. +- **Rate limits** — every poll costs one GraphQL query per host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request. All count against the signed-in account’s rate limit. A review read costs one GraphQL query per page of 100 threads and one more per further page of 100 comments in a thread. - **No merge queue** — a base branch that requires a merge queue refuses a direct merge, and the provider never queues one. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 205a8f0439..99896c73d8 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -50,6 +50,8 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 +`readReview` 用一次 GraphQL 查询读取评审讨论,同时读出 `headRefOid` 和当前登录的用户;head 不是所请求的提交时返回 `stale`。讨论按每页最多 100 个分页读取,直到读满 `maxReviewThreads` 个;第一页之后的每一页都会再次读取 head,因此读取期间有新的推送时返回 `stale`。每个讨论的评论都会全部读出,讨论第一条评论的提交和 `diffHunk` 只读一次。所有页面按 JSON 计合计不得超过 `maxOutputBytes`:会超出上限的那一页及其后的讨论被丢弃,结果标记为 `truncated`,与讨论数超过 `maxReviewThreads` 时相同。行级讨论只有在 GitHub 报告它未过期、带有 `line`,且第一条评论的 `commit` 就是 head 时,才得到 `current` 位置:force-push 之后写在旧提交上的评论保留的 `line` 是那个旧提交的行号,GitHub 也可能在标记讨论过期的同时保留它的 `line`。`original` 取自第一条评论 `originalCommit` 上的 `originalLine` 和 `originalStartLine`;`subjectType: FILE` 的讨论两者都没有。起始行在 diff 另一侧的范围只保留最后一行。没有评论的讨论会被略去。REST 的 `position` 无法区分已过期的讨论,因此不读取。 + ----- @@ -66,6 +68,7 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 | [`src/provider.ts`](src/provider.ts) | URL 映射、按主机分组与失败分类 | | [`src/graphql.ts`](src/graphql.ts) | 构造查询,并校验和映射响应 | | [`src/compare.ts`](src/compare.ts) | 经 compare API 读取两个提交之间的补丁,供所有 diff 读取共用 | +| [`src/threads.ts`](src/threads.ts) | 读取评审讨论、分页,并映射到 head 位置与原始位置 | | [`src/gh.ts`](src/gh.ts) | 在宿主上执行 `gh`,清理环境变量并施加限制 | | [`src/urls.ts`](src/urls.ts) | 解析远端 URL 与 pull request URL,并校验写入请求的名称与提交 | @@ -96,11 +99,11 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 - **宿主需要 GitHub CLI**——必须安装 `gh` 并为每个已配置主机登录;环境变量中的令牌不会被转发。不在 `hosts` 中的主机永远不会被读取,包括配置变更后保留的引用。状态读取为这些引用返回 `unavailable`;head 查找会在启动 `gh` 前拒绝。 -- **评审讨论上限**——每次状态读取每个 pull request 最多统计 `maxReviewThreads` 个评审讨论;超出时 `unresolvedThreads` 只是下限,由 `threadsTruncated` 标出。 +- **评审讨论上限**——每次状态读取每个 pull request 最多统计、每次评审读取最多读取 `maxReviewThreads` 个评审讨论;超出时 `unresolvedThreads` 只是下限,由 `threadsTruncated` 标出,评审读取的结果标记为 `truncated`。 - **批次时限**——评审讨论很多的 pull request 的续页会拉长其主机的轮询批次;批次超过 `ctx.forge` 的 `fetchTimeoutMs` 时,批次内每个 pull request 都报告 `unavailable`,而不只是讨论很多的那个。 - **基准分支被改写**——diff 从 head 与 GitHub 在 pull request 最后一次更新时记录的基准提交的合并基准开始。基准分支被强制推送后,该合并基准可能不同于 GitHub pull request 页面使用的合并基准,因此在 pull request 更新前,补丁可能多出或缺少提交。 - **不发现 fork**——按 head 分支查找时,不包含 head 位于其他仓库的 pull request。 -- **速率限制**——每次轮询为每个主机消耗一次 GraphQL 查询,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求。这些都计入已登录账号的速率配额。 +- **速率限制**——每次轮询为每个主机消耗一次 GraphQL 查询,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求。这些都计入已登录账号的速率配额。每次评审读取每页 100 个讨论消耗一次 GraphQL 查询,单个讨论的评论每多一页(100 条)再消耗一次。 - **不支持合并队列**——要求合并队列的基准分支会拒绝直接合并,提供方也不会把变更请求加入队列。 diff --git a/packages/experimental/forge-github/src/index.ts b/packages/experimental/forge-github/src/index.ts index 7daff01956..3235e030a3 100644 --- a/packages/experimental/forge-github/src/index.ts +++ b/packages/experimental/forge-github/src/index.ts @@ -18,9 +18,12 @@ export interface Config { hosts?: string[] /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number - /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ + /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */ maxOutputBytes?: number - /** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */ + /** + * Most review threads counted per pull request in one status read, which reports a lower bound past it, and read in + * one review read, which reports itself truncated past it. + */ maxReviewThreads?: number /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ maxCommits?: number diff --git a/packages/experimental/forge-github/tests/threads.spec.ts b/packages/experimental/forge-github/tests/threads.spec.ts index f90c18b0a0..7962e90280 100644 --- a/packages/experimental/forge-github/tests/threads.spec.ts +++ b/packages/experimental/forge-github/tests/threads.spec.ts @@ -56,15 +56,20 @@ function nextPage(threads: Record, headRefOid = head): Record | { readonly raw: GhOutput }): answer is { readonly raw: GhOutput } { + return 'raw' in answer +} + /** Answer the first thread page with `first`, later thread pages from `later` by cursor, and comment pages from `comments` by cursor. */ function review( - first: Record | GhOutput, + first: Record | { readonly raw: GhOutput }, later: Readonly>> = {}, comments: Readonly>> = {}, ): ReturnType { return fakeGh((args) => { const cursor = args.find(arg => arg.startsWith('cursor='))?.slice('cursor='.length) ?? '' - if (args.includes(`query=${REVIEW_QUERY}`)) return 'exitCode' in first ? first : output(first) + if (args.includes(`query=${REVIEW_QUERY}`)) return isRaw(first) ? first.raw : output(first) if (args.includes(`query=${REVIEW_THREADS_QUERY}`)) return output(later[cursor] ?? { data: { node: null } }) if (args.includes(`query=${THREAD_COMMENTS_QUERY}`)) return output(comments[cursor] ?? { data: { node: null } }) throw new Error(`unexpected gh ${args.join(' ')}`) @@ -221,14 +226,14 @@ describe('GitHub provider review threads', () => { }) it('passes on the failure of any page read and of a response that is not JSON', async () => { - const missing = review(output('', 1, 'gh: Could not resolve to a PullRequest with the number of 7.')) + const missing = review({ raw: output('', 1, 'gh: Could not resolve to a PullRequest with the number of 7.') }) await expect(provider(missing.run).readReview(pull(7), head, signal)) .resolves.toEqual({ code: 'not-found', message: 'gh: Could not resolve to a PullRequest with the number of 7.' }) - const garbled = review(output('not json')) + const garbled = review({ raw: output('not json') }) await expect(provider(garbled.run).readReview(pull(7), head, signal)).resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response' }) - const refused = review(output({ data: null, errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible by integration' }] })) + const refused = review({ raw: output({ data: null, errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible by integration' }] }) }) await expect(provider(refused.run).readReview(pull(7), head, signal)) .resolves.toEqual({ code: 'unavailable', message: 'Resource not accessible by integration' }) diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index ce02168f4c..2b96a443f1 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: 66ce801db0de565f - zh: 884973fad2ad2540 + en: 2327b151ac15aa2f + zh: 429988457f4a67bd /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index 8727e8cd2b..72bdb80f85 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -48,6 +48,8 @@ Reaching `fetchTimeoutMs` aborts the fetch signal with `FORGE_FETCH_TIMEOUT`. Pr Providers may implement `submitReview` to publish a line comment or a completed review at an explicit head commit. The registry returns unsupported when that capability is absent and refreshes watched status after a submission. Successful writes return their web URL; failures distinguish changed heads, refusals, and unknown outcomes. Callers must reconcile unknown outcomes before another submission. Pending drafts belong to the consumer, not the polling registry. +Providers may implement `readReview` to read a change request's review threads at one head commit. `readReview(ref, headSha, signal)` returns `ForgeReviewData`, the threads with each line thread's position at the head and at the commit it was written on, only when the read names `headSha` as the head; otherwise `stale`, which polls a watched change request at once, once per head commit shared with stale diff reads. The registry returns an `unsupported` failure when the provider lacks the method. + ----- diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 168012126c..543f6ca83f 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -48,6 +48,8 @@ kind: "package-reference" provider 可以实现 `submitReview`,在指定的 head 提交上发布行内评论或完整评审。未实现该能力时,注册表返回不支持;提交结束后会刷新受关注的状态。成功的写操作返回网页 URL;失败区分 head 变化、明确拒绝与结果不明。调用方必须先核对结果不明的操作,再次提交。待提交草稿由消费者管理,不由轮询注册表保存。 +提供方可以实现 `readReview`,在一个 head 提交处读取变更请求的评审讨论。只有读取时的 head 就是 `headSha` 时,`readReview(ref, headSha, signal)` 才返回 `ForgeReviewData`,其中每个行级讨论都带有它在 head 上的位置和在写下时所在提交上的位置;否则返回 `stale`,并立即重新轮询被关注的变更请求,每个 head 提交只轮询一次,这个次数与 diff 读取遇到 `stale` 时共用。提供方未实现该方法时,注册表返回 `unsupported` 失败。 + ----- diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index de37043f87..1c342a0672 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1276,6 +1276,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`.', throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], }, + { + signature: 'async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise', + description: 'Read the review threads of a change request at one head commit. A `stale` failure polls a watched change request again as ForgeService.diff does.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'headSha', description: 'head commit the threads must be read at, usually the head of the displayed diff.' }, { name: 'signal', description: 'cancellation of the read.' }], + returns: 'the threads read at `headSha`, or why the host did not provide them; `unsupported` when the provider cannot read reviews.', + throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], + }, { signature: 'async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise', description: 'List the commits of a change request at its current head.', @@ -1433,6 +1440,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the text.', throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/diff-too-large` when the host or its provider refuses the file over a size limit; `forgePanel/diff-failed` when the host does not provide the file otherwise.'], }, + { + signature: '@Remote async changeRequestReview(session: Session, url: string, headSha: string, signal: AbortSignal): Promise', + description: 'Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read at the same head commit and update time are reused from memory, for any Session, until they are `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age shows threads resolved since, which do not change a GitHub pull request\'s update time.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'headSha', description: 'head commit of the displayed diff.' }, { name: 'signal', description: 'request cancellation.' }], + returns: 'the threads at `headSha`, with `current` positions numbering the files of that diff.', + throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again; `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the status was read and when the host does not provide the threads otherwise.'], + }, { signature: '@Remote async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise', description: 'Publish a line comment or completed review for a visible Session binding.', @@ -6621,6 +6635,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeActionFailure', declaration: 'export interface ForgeActionFailure {\n readonly code: \'unauthenticated\' | \'stale\' | \'failed\';\n readonly message: string;\n}', }, + { + name: 'ForgeAnchor', + declaration: 'export interface ForgeAnchor {\n readonly commit: string;\n readonly startLine: number;\n readonly endLine: number;\n}', + }, { name: 'ForgeAutomaticBase', declaration: 'export interface ForgeAutomaticBase {\n readonly name: string;\n readonly worktree: boolean;\n}', @@ -6661,6 +6679,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeCheckoutState', declaration: 'export type ForgeCheckoutState = {\n readonly state: \'pending\';\n} | {\n readonly state: \'none\';\n} | {\n readonly state: \'failed\';\n readonly message: string;\n} | {\n readonly state: \'ready\';\n readonly checkout: ForgeCheckout;\n};', }, + { + name: 'ForgeCommentAuthor', + declaration: 'export interface ForgeCommentAuthor {\n readonly login: string;\n readonly avatarUrl: string | null;\n readonly bot: boolean;\n}', + }, + { + name: 'ForgeCommentId', + declaration: 'export type ForgeCommentId = Branded<\'ForgeCommentId\'>;', + }, { name: 'ForgeCommit', declaration: 'export interface ForgeCommit {\n readonly sha: string;\n readonly parent: string | null;\n readonly title: string;\n readonly author: string | null;\n readonly authoredAt: string;\n}', @@ -6687,7 +6713,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeFailure', - declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'stale\' | \'unavailable\';\n readonly message: string;\n}', + declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'stale\' | \'unsupported\' | \'unavailable\';\n readonly message: string;\n}', }, { name: 'ForgeFileLayer', @@ -6731,7 +6757,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeProvider', - declaration: 'export interface ForgeProvider {\n readonly forge: string;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise>;\n fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise;\n readiness(host: string, signal: AbortSignal): Promise;\n markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise;\n diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise;\n fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise;\n fileUrl(ref: ChangeRequestRef, commit: string, path: string): string;\n commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n compare?(ref: ChangeRequestRef, base: string, head: string, s /* …truncated — full shape in source */', + declaration: 'export interface ForgeProvider {\n readonly forge: string;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise;\n readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise>;\n fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise;\n readiness(host: string, signal: AbortSignal): Promise;\n markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise;\n diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise;\n fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise;\n fileUrl(ref: ChangeRequestRef, commit: string, path: string): string;\n commits?(ref: ChangeRequestRef, signal: A /* …truncated — full shape in source */', }, { name: 'ForgeReadiness', @@ -6741,6 +6767,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeRepository', declaration: 'export interface ForgeRepository {\n readonly forge: string;\n readonly host: string;\n readonly owner: string;\n readonly name: string;\n}', }, + { + name: 'ForgeReviewComment', + declaration: 'export interface ForgeReviewComment {\n readonly id: ForgeCommentId;\n readonly author: ForgeCommentAuthor | null;\n readonly body: string;\n readonly createdAt: string;\n readonly pending: boolean;\n readonly url: string | null;\n}', + }, + { + name: 'ForgeReviewData', + declaration: 'export interface ForgeReviewData {\n readonly headSha: string;\n readonly viewer: string | null;\n readonly threads: readonly ForgeReviewThread[];\n readonly truncated: boolean;\n}', + }, { name: 'ForgeReviewRequest', declaration: 'export type ForgeReviewRequest = {\n readonly headSha: string;\n} & ({\n readonly kind: \'comment\';\n readonly comment: ForgeLineComment;\n} | {\n readonly kind: \'review\';\n readonly event: \'comment\' | \'approve\' | \'request-changes\';\n readonly body: string;\n readonly comments: readonly ForgeLineComment[];\n});', @@ -6749,10 +6783,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeReviewResult', declaration: 'export type ForgeReviewResult = {\n readonly ok: true;\n readonly url: string;\n} | {\n readonly ok: false;\n readonly code: \'unsupported\' | \'stale\' | \'failed\' | \'unknown\';\n readonly message: string;\n};', }, + { + name: 'ForgeReviewThread', + declaration: 'export interface ForgeReviewThread {\n readonly id: ForgeThreadId;\n readonly path: string;\n readonly side: \'L\' | \'R\';\n readonly subject: \'line\' | \'file\';\n readonly current: ForgeAnchor | null;\n readonly original: ForgeAnchor | null;\n readonly diffHunk: string | null;\n readonly resolved: boolean;\n readonly comments: readonly ForgeReviewComment[];\n}', + }, { name: 'ForgeSessionWorktree', declaration: 'export interface ForgeSessionWorktree {\n readonly path: string;\n readonly branch: string;\n readonly from: string | null;\n readonly baseCommit: string;\n readonly repositoryRoot: string;\n}', }, + { + name: 'ForgeThreadId', + declaration: 'export type ForgeThreadId = Branded<\'ForgeThreadId\'>;', + }, { name: 'ForgeWorktreeBlocker', declaration: 'export type ForgeWorktreeBlocker = \'not-git\' | \'outside-writable-root\' | \'read-only\';', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 92c46bf4b5..ee6fdd75bf 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -428,6 +428,7 @@ export const LINK_MAP: Readonly> = { ForgeChangeRequestDiff: 'forge.md', ForgeCommit: 'forge.md', ForgeCommitList: 'forge.md', + ForgeReviewData: 'forge.md', ForgeCommitRange: 'forge.md', ForgeFileLayer: 'forge.md', ForgeChangeRequestStatesFrame: 'forge.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index eb54361c8d..ad71d6ad42 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2821,6 +2821,41 @@ "doc": "docs/subsystems/forge.md", "symbol": "ForgeReviewResult", "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeThreadId", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeCommentId", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeAnchor", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeCommentAuthor", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeReviewComment", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeReviewThread", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeReviewData", + "source": "packages/experimental/forge/src/types.ts" } ] } From b07f93af189d6d1723723647d87f7689ae122779 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 16:46:56 +0800 Subject: [PATCH 06/29] feat(forge-panel): filter review threads by resolution and fit the thread list to narrow views The thread list chooses Unresolved, Resolved, or All in the segmented radio group the lens uses, and drops the Outdated and Awaiting my reply filters with the Awaiting my reply tag. Its footer keeps only View on GitHub, after a note when the read was truncated, and each file group names the file before its directory. The list's width rules queried the changes view's container by name, which CSS Modules rename per file, so they never applied and a narrow view squeezed the files beside a 320px list. The rules now query the nearest container: a view at least 1040px wide docks the list; a narrower one floats it over the files with a scrim, moves the focus into it, and closes it before opening a thread; below 480px it takes the files' whole width with Back to changes. Escape, the scrim, and the close actions return the focus to the Threads button. Below 480px a file header shows the unresolved count alone and thread cards keep 6px margins. --- .../review-thread-list.expected.md | 14 +- apps/web/tests/forge-panel.e2e.ts | 17 ++- .../client-ui-forge/README.i18n.yaml | 4 +- .../experimental/client-ui-forge/README.md | 2 +- .../experimental/client-ui-forge/README.zh.md | 2 +- .../src/client/ChangesTab.module.css | 8 ++ .../client-ui-forge/src/client/ChangesTab.tsx | 29 ++-- .../client-ui-forge/src/client/DiffFile.tsx | 5 +- .../src/client/ReviewControls.module.css | 7 +- .../src/client/ReviewControls.tsx | 64 ++++++--- .../src/client/ReviewThreads.module.css | 12 ++ .../src/client/ThreadList.module.css | 86 +++++++++--- .../client-ui-forge/src/client/ThreadList.tsx | 126 +++++++++++------- .../client-ui-forge/src/client/locales.ts | 40 +++--- .../src/client/review-threads.ts | 29 +--- .../tests/changes-tab.client.spec.tsx | 56 ++++++-- .../tests/review-thread-cards.client.spec.tsx | 20 +-- .../tests/review-threads.client.spec.ts | 27 +--- 18 files changed, 346 insertions(+), 202 deletions(-) diff --git a/apps/web/tests/expected/forge-panel/review-thread-list.expected.md b/apps/web/tests/expected/forge-panel/review-thread-list.expected.md index 0a2d0acbd7..bdfb2dc803 100644 --- a/apps/web/tests/expected/forge-panel/review-thread-list.expected.md +++ b/apps/web/tests/expected/forge-panel/review-thread-list.expected.md @@ -1,17 +1,15 @@ - complementary "讨论列表,共 5 个": - text: 讨论 5 - button "关闭讨论列表" - - group "筛选讨论": - - button "未解决 4" - - button "已过期 1" - - button "已解决 1" - - button "需要我回复 0" - - heading "panel.md" [level=3] + - radiogroup "筛选讨论": + - radio "未解决 4" + - radio "已解决 1" + - radio "全部 5" [checked] + - heading "docs/panel.md" [level=3] - button "文件级讨论 Add a screenshot." - - heading "panel.ts" [level=3] + - heading "src/panel.ts" [level=3] - button "R2 · 1 条回复 Why two?" - button "L15 The old fifteen was a number." - button "R15 Settled. 已解决" - button "原在 R9 · 在 fffffff 上 This line moved. 已过期" - - text: github.com 上共 5 个讨论 · - button "在 GitHub 中查看" diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 1b0c0bc8fb..e8804e0253 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -1901,17 +1901,24 @@ it.skipIf(MODE === 'record')('overlays the review threads of a change request an await view.getByRole('button', { name: '讨论列表,共 5 个', exact: true }).click() const list = view.getByRole('complementary', { name: '讨论列表,共 5 个' }) - await expect.poll(() => list.getByRole('button', { pressed: true }).allTextContents()).toEqual(['未解决 4']) + await expect.poll(() => list.getByRole('radio', { checked: true }).allTextContents()).toEqual(['未解决4']) await expect.poll(() => list.locator('[data-forge-thread-item]').evaluateAll(items => items.map(item => item.getAttribute('data-forge-thread-item')))) .toEqual(['whole-file', 'on-line', 'old-side', 'outdated']) - await list.getByRole('button', { name: '已解决 1', exact: true }).click() + await list.getByRole('radio', { name: /^已解决/ }).click() await list.locator('[data-forge-thread-item="resolved"]').click() - // Opening a resolved thread unfolds it inside its file. + // Opening a resolved thread unfolds it inside its file, and the docked list stays. await panel.locator('[data-forge-thread="resolved"]').getByText('Settled.', { exact: true }).waitFor() - await list.getByRole('button', { name: '已解决 1', exact: true }).click() - await list.getByRole('button', { name: '需要我回复 0', exact: true }).waitFor() + await list.getByRole('radio', { name: /^全部/ }).click() + await expect.poll(() => list.locator('[data-forge-thread-item]').count()).toBe(5) await compareOrRefreshGolden(join(EXPECTED, 'review-thread-list.expected.md'), await captureStableAria(page, '[data-forge-thread-list]', scaffold.workspaceCwd), MODE) + // A view narrower than 480px gives the list the files' whole width and closes it before opening a thread. + await view.evaluate((element) => { element.style.width = '420px'; element.style.flex = 'none' }) + await expect.poll(() => list.evaluate(element => [getComputedStyle(element).position, element.getBoundingClientRect().width])) + .toEqual(['absolute', 420]) + await list.locator('[data-forge-thread-item="on-line"]').click() + await list.waitFor({ state: 'detached' }) + await view.evaluate((element) => { element.style.width = ''; element.style.flex = '' }) await onLine.getByRole('button', { name: '添加到输入框', exact: true }).click() await page.locator('[data-composer-input]').first().getByText('panel.ts R2', { exact: true }).first().waitFor() diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index a0392da274..b9dab01161 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: e9ecdf9670bd6324 - zh: 6f5e3027afb18a3e + en: 18b49590a4cda9ed + zh: 71e6de165fa4febc /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: en: 78cab599dbd4aa57 zh: 87265844f34efbc5 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 190c23e7d0..230c028eb1 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -41,7 +41,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **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. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. - **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. -- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads; the count in a header, like the Threads toolbar button, opens the thread list, which groups the threads by file in file tree order, filters Unresolved, Outdated, Resolved, or Awaiting my reply, which keeps unresolved threads the signed-in user wrote in where someone else wrote last, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list names a truncated read. A thread offers only Add to input, which quotes the whole thread, and View on GitHub. Threads are read again at each status while the view shows; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. +- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads; the count in a header, like the Threads toolbar button, opens the thread list, which groups the threads by file in file tree order, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers only Add to input, which quotes the whole thread, and View on GitHub. Threads are read again at each status while the view shows; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index f7ced4299b..a3ce630d6a 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference" - **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 - **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 -- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数;点击文件标题上的计数或工具栏的“讨论”按钮会打开讨论列表。列表按文件树顺序分组,可按未解决、已过期、已解决和“需要我回复”筛选(“需要我回复”保留当前登录用户参与过、且最后一条评论来自他人的未解决讨论),点击讨论会跳到它的位置;若所选提交中没有该讨论,会先切换到全部提交。读取被截断时,列表会注明。讨论上只有“添加到输入框”(把整个讨论作为引用插入)和“在 GitHub 中查看”两个操作。视图显示期间,每收到一次状态就重新读取讨论;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 +- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数;点击文件标题上的计数或工具栏的“讨论”按钮会打开讨论列表。列表按文件树顺序分组,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上只有“添加到输入框”(把整个讨论作为引用插入)和“在 GitHub 中查看”两个操作。视图显示期间,每收到一次状态就重新读取讨论;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 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 23452bbc00..8d5c5b2a1d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -840,6 +840,14 @@ .threadCount:hover { background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 20%, transparent); } } +/* A view narrower than 480px shows the count alone. */ +.threadCountNumber { display: none; } + +@container forge-changes (max-width: 479px) { + .threadCountText { display: none; } + .threadCountNumber { display: inline; } +} + /* Opens the thread list; pressed while the list shows. */ .threadsToggle { display: inline-flex; diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index d550841145..ec7fc28444 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -581,10 +581,13 @@ export function ChangesTab({ const placed = usePlacedThreads(review, data?.kind === 'change' ? { head: prHead ?? '', end: data.headSha, commits: data.commits } : null) const [threadList, setThreadList] = useState<{ readonly open: boolean - readonly filter: ThreadFilter | null + readonly filter: ThreadFilter /** File whose group the list scrolls to, or null. */ readonly file: string | null - }>({ open: false, filter: 'unresolved', file: null }) + /** Whether the reader just opened the list and it has not taken the focus yet. */ + readonly claim: boolean + }>({ open: false, filter: 'unresolved', file: null, claim: false }) + const threadsToggle = useRef(null) const [focus, setFocus] = useState(null) const allFiles = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests)), [allFiles, lens, hideTests]) @@ -720,7 +723,13 @@ export function ChangesTab({ const threadsOf = (path: string): FileThreads | undefined => { const group = placed.files.get(path) return threadActions === null || group === undefined ? undefined - : { ...group, actions: threadActions, openList: () => { setThreadList(value => ({ ...value, open: true, file: path })) } } + : { ...group, actions: threadActions, + openList: () => { setThreadList(value => ({ ...value, open: true, file: path, claim: true })) } } + } + /** Close the thread list at the reader's request and return the focus to its toggle. */ + const closeThreadList = (): void => { + setThreadList(value => ({ ...value, open: false })) + threadsToggle.current?.focus() } /** Show a thread from the list: all commits for a thread the chosen ones do not hold, then its file, unfolded and centered. */ const openThread = ({ thread, place }: PlacedThread): void => { @@ -948,9 +957,9 @@ export function ChangesTab({ } {review !== null && review.threads.length > 0 && ( - )} @@ -1015,10 +1024,14 @@ export function ChangesTab({ {body} {allFiles.length > 0 && } {review !== null && data?.kind === 'change' && threadList.open && ( - file.path)} viewer={review.viewer} - truncated={review.truncated} host={new URL(data.url).host} url={data.url} + file.path)} truncated={review.truncated} url={data.url} filter={threadList.filter} choose={(filter) => { setThreadList(value => ({ ...value, filter })) }} file={threadList.file} - open={openThread} openLink={openLink} close={() => { setThreadList(value => ({ ...value, open: false })) }} t={t} /> + claim={threadList.claim} claimed={() => { setThreadList(value => ({ ...value, claim: false })) }} + open={(entry, covering) => { + if (covering) setThreadList(value => ({ ...value, open: false })) + openThread(entry) + }} + openLink={openLink} close={closeThreadList} t={t} /> )}
diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index 0e7c561125..97478379ef 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -501,7 +501,10 @@ export function DiffFile(props: DiffFileProps): ReactNode { {viewed === 'changed' && {t('viewed.changed')}} {threads !== undefined && threads.unresolved > 0 && ( + onClick={threads.openList}> + {t('thread.unresolvedCount', { count: threads.unresolved })} + {threads.unresolved} + )} {badge !== '' && {badge}} diff --git a/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css b/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css index a08dc8e88e..655cf83171 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css @@ -1,6 +1,7 @@ -/* Review controls of the changes toolbar. The lens draws the segmented track and raised indicator of the shared - segmented control at the toolbar's 28px control height and 12px text, with each segment's file count after its label. */ -.lens { +/* Review controls of the changes toolbar. The segmented radio group of the lens and the thread list's filter draws the + track and raised indicator of the shared segmented control at the toolbar's 28px control height and 12px text, with + each segment's count after its label. */ +.segmented { box-sizing: border-box; display: grid; grid-auto-columns: minmax(0, 1fr); diff --git a/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx b/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx index 735c0148c4..b6765c158a 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx @@ -1,7 +1,7 @@ /** * Review controls of the changes toolbar: the lens that keeps the files of one review layer, as a full-width * radio group above the file tree or as a menu where no tree shows; the switch that hides test files; and the - * share of shown files the reader marked viewed. + * share of shown files the reader marked viewed. The thread list shares the segmented radio group. */ import { useRef, useState, type KeyboardEvent, type ReactNode } from 'react' @@ -33,17 +33,35 @@ export interface LensProps extends PropsLocale { readonly choose: (lens: ChangesLens) => void } +/** One segment of a {@link SegmentedChoice}. */ +export interface Segment { + /** Value the segment chooses. */ + readonly value: Value + /** Localized label. */ + readonly label: string + /** Count shown after the label, or null for none. */ + readonly count: number | null + /** Localized hover text of a disabled segment, or null for an enabled one. */ + readonly disabledTip: string | null +} + /** - * Render the lens as a radio group whose segments share its width; arrow keys, Home, and End move between enabled lenses. - * @param props - the lens, its counts, whether test files hide, the choose action, and copy. + * Render a radio group whose segments share its width, each with a count after its label; arrow keys, Home, and End + * move between enabled segments. + * @param props - the segments, the chosen value, the choose action, and the group's localized accessible name. * @returns the radio group. */ -export function LensControl({ lens, counts, hideTests, choose, t }: LensProps): ReactNode { +export function SegmentedChoice({ segments, value, choose, label }: { + readonly segments: readonly Segment[] + readonly value: Value + readonly choose: (value: Value) => void + readonly label: string +}): ReactNode { const group = useRef(null) - const enabled = LENSES.filter(item => item !== 'test' || !hideTests) + const enabled = segments.filter(segment => segment.disabledTip === null).map(segment => segment.value) const move = (event: KeyboardEvent): void => { - const at = enabled.indexOf(lens) - let next: ChangesLens | undefined + const at = enabled.indexOf(value) + let next: Value | undefined switch (event.key) { case 'ArrowLeft': case 'ArrowUp': next = enabled[(at + enabled.length - 1) % enabled.length]; break case 'ArrowRight': case 'ArrowDown': next = enabled[(at + 1) % enabled.length]; break @@ -53,28 +71,40 @@ export function LensControl({ lens, counts, hideTests, choose, t }: LensProps): } event.preventDefault() event.stopPropagation() - /* v8 ignore next -- at most the test lens is disabled, so every key lands on an enabled lens */ + /* v8 ignore next -- every caller keeps a segment enabled, so every key lands on one */ if (next === undefined) return choose(next) - group.current?.querySelector(`[data-forge-lens="${next}"]`)?.focus() + group.current?.querySelector(`[data-segment="${next}"]`)?.focus() } return ( -
- {LENSES.map((item) => { - const disabled = item === 'test' && hideTests +
+ {segments.map((segment) => { const button = ( - ) - return disabled ? {button} : button + return segment.disabledTip === null ? button : {button} })}
) } +/** + * Render the lens as a radio group whose segments share its width. + * @param props - the lens, its counts, whether test files hide, the choose action, and copy. + * @returns the radio group. + */ +export function LensControl({ lens, counts, hideTests, choose, t }: LensProps): ReactNode { + // A disabled lens shows no count, since hidden test files are not counted. + return item === 'test' && hideTests + ? { value: item, label: t(LENS_LABEL[item]), count: null, disabledTip: t('lens.testHidden') } + : { value: item, label: t(LENS_LABEL[item]), count: counts[item], disabledTip: null })} /> +} + /** * Render the lens as a menu button, for a toolbar without the file tree beside it. * @param props - the lens, its counts, whether test files hide, the choose action, copy, and whether the owning tab is visible. diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css index 00ed916016..b84b5a8428 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css @@ -217,3 +217,15 @@ font: var(--dsw-font-xs-13); font-family: Inter, var(--dsw-font-family); } + +/* A changes view narrower than 480px gives the code more width; the query names no container, since CSS Modules rename + a container name per file, and the nearest inline-size container is the changes view. */ +@container (max-width: 479px) { + .card, + .folded, + .card[data-split][data-side="R"], + .folded[data-split][data-side="R"] { + width: calc(100% - 12px); + margin: 6px; + } +} diff --git a/packages/experimental/client-ui-forge/src/client/ThreadList.module.css b/packages/experimental/client-ui-forge/src/client/ThreadList.module.css index c38bf4b549..2e91c9681f 100644 --- a/packages/experimental/client-ui-forge/src/client/ThreadList.module.css +++ b/packages/experimental/client-ui-forge/src/client/ThreadList.module.css @@ -1,4 +1,9 @@ -/* The thread list docks at the end of the changes body on wide panes and floats over the files on narrow ones. */ +/* The thread list docks at the end of the changes body in a view at least 1040px wide, which leaves the code about + 480px beside the file tree and the list; it floats over the files with a scrim behind it in a narrower view, and + takes the files' whole width below 480px. The queries name no container, since CSS Modules rename a container name + per file; the nearest inline-size container is the changes view. */ +.scrim { display: none; } + .pane { display: flex; flex: none; @@ -13,16 +18,7 @@ font-family: Inter, var(--dsw-font-family); } -@container forge-changes (max-width: 759px) { - .pane { - position: absolute; - z-index: 3; - inset-block: 0; - inset-inline-end: 0; - width: min(320px, 100%); - box-shadow: var(--dsw-shadow-l2, 0 4px 16px rgb(0 0 0 / 12%)); - } -} +.pane:focus { outline: none; } .header { display: flex; @@ -34,6 +30,25 @@ .title { font-weight: 500; } +/* Takes the place of the title and the close button where the list covers the files' whole width. */ +.back { + display: none; + align-items: center; + gap: 2px; + height: 28px; + padding: 0 8px 0 4px; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + cursor: pointer; +} + +@media (hover: hover) { + .back:hover { background: var(--dsw-alias-interactive-bg-hover); } +} + .total { padding: 0 6px; border-radius: var(--dsw-radius-xs); @@ -64,9 +79,6 @@ } .filters { - display: flex; - flex-wrap: wrap; - gap: 6px; padding: 0 12px 10px; border-bottom: 0.5px solid var(--dsw-alias-border-l3); } @@ -83,12 +95,9 @@ .path { margin: 0; padding: 8px 6px 4px; - overflow: hidden; - color: var(--dsw-alias-label-secondary); font: inherit; font-size: 12px; - text-overflow: ellipsis; - white-space: nowrap; + font-weight: 500; } .item { @@ -155,6 +164,9 @@ } .link { + display: inline-flex; + align-items: center; + gap: 2px; padding: 0; border: 0; background: transparent; @@ -166,3 +178,41 @@ @media (hover: hover) { .link:hover { text-decoration: underline; } } + +/* Above the sticky file headers (z-index 2). */ +@container (max-width: 1039px) { + .scrim { + position: absolute; + z-index: 3; + inset: 0; + display: block; + background: var(--dsw-alias-bg-mask-1); + } + + .pane { + position: absolute; + z-index: 3; + inset-block: 0; + inset-inline-end: 0; + width: min(340px, calc(100% - 40px)); + box-shadow: var(--dsw-elevation-panel); + } +} + +@container (max-width: 479px) { + .scrim { display: none; } + + .pane { + width: 100%; + border-inline-start: 0; + box-shadow: none; + } + + .header { padding-inline-start: 6px; } + + .back { display: inline-flex; } + + .title, + .total, + .close { display: none; } +} diff --git a/packages/experimental/client-ui-forge/src/client/ThreadList.tsx b/packages/experimental/client-ui-forge/src/client/ThreadList.tsx index 66a968c788..cdebe62f5b 100644 --- a/packages/experimental/client-ui-forge/src/client/ThreadList.tsx +++ b/packages/experimental/client-ui-forge/src/client/ThreadList.tsx @@ -1,15 +1,18 @@ /** * The thread list of a change request beside its changes: every thread grouped by file in file tree order, narrowed - * by one filter, each opening the place it shows at. + * by whether it is resolved, each opening the place it shows at. A wide changes view docks the list beside the files; + * a narrower one floats it over them, and the narrowest gives it their whole width. */ -import { useLayoutEffect, useMemo, useRef, type ReactNode } from 'react' -import { IconCloseOutlineRegular, Pill, Tag, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { useLayoutEffect, useMemo, useRef, type KeyboardEvent, type ReactNode } from 'react' +import { IconChevronLeftOutlineRegular, IconCloseOutlineRegular, IconRightUpOutlineRegular, Tag, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' import { assertNever } from '@deepseek-ai/dsh-util-values' +import { FileLabel } from './FileLabel.tsx' +import { SegmentedChoice } from './ReviewControls.tsx' import { Avatar } from './ReviewThreads.tsx' -import { anchorRange, awaitsViewer, passesFilter, THREAD_FILTERS, type ThreadFilter, type ThreadPlace } from './review-threads.ts' +import { anchorRange, passesFilter, THREAD_FILTERS, type ThreadFilter, type ThreadPlace } from './review-threads.ts' import type { NS } from './locales.ts' import type { PlacedThread } from './thread-state.ts' import css from './ThreadList.module.css' @@ -22,25 +25,25 @@ export interface ThreadListProps extends PropsLocale { readonly entries: readonly PlacedThread[] /** Changed file paths in file tree order; threads on other paths follow them. */ readonly order: readonly string[] - /** Login of the signed-in user. */ - readonly viewer: string | null /** Whether the host has more threads than were read. */ readonly truncated: boolean - /** Host name the threads were read from, such as `github.com`. */ - readonly host: string /** Web page of the change request. */ readonly url: string - /** The active filter, or null for every thread. */ - readonly filter: ThreadFilter | null - /** Choose a filter, or null for every thread. */ - readonly choose: (filter: ThreadFilter | null) => void + /** The active filter. */ + readonly filter: ThreadFilter + /** Choose a filter. */ + readonly choose: (filter: ThreadFilter) => void /** File whose group the list scrolls to when it changes, or null. */ readonly file: string | null - /** Open the place of a thread. */ - readonly open: (entry: PlacedThread) => void + /** Whether the reader just opened the list, so a list that covers the files takes the focus. */ + readonly claim: boolean + /** Report that the list handled `claim`. */ + readonly claimed: () => void + /** Open the place of a thread; `covering` says the list covers the files, so the owner closes it first. */ + readonly open: (entry: PlacedThread, covering: boolean) => void /** Open a URL outside the app. */ readonly openLink: (url: string) => void - /** Close the list. */ + /** Close the list at the reader's request. */ readonly close: () => void } @@ -68,6 +71,11 @@ function meta(thread: ForgeReviewThread, place: ThreadPlace, t: Translate): stri return parts.join(' · ') } +/** Whether the list floats over the files or takes their width, which its narrow-view styles decide. */ +function covers(pane: HTMLElement | null): pane is HTMLElement { + return pane !== null && getComputedStyle(pane).position === 'absolute' +} + /** * The first comment as one line of plain text: without raw HTML, strong, strikethrough, and code marks, quote or * heading marks, and link targets. @@ -77,9 +85,8 @@ function plainExcerpt(body: string): string { .replace(/\*\*|__|~~|`/g, '').replace(/\s+/g, ' ').trim() } -function Item({ entry, viewer, open, t }: { +function Item({ entry, open, t }: { readonly entry: PlacedThread - readonly viewer: string | null readonly open: (entry: PlacedThread) => void readonly t: Translate }): ReactNode { @@ -94,7 +101,6 @@ function Item({ entry, viewer, open, t }: { {place.kind === 'outdated' && {t('thread.outdatedTag')}} {place.kind === 'elsewhere' && {t('thread.elsewhereTag')}} {thread.resolved && {t('thread.filter.resolved')}} - {awaitsViewer(thread, viewer) && {t('thread.filter.mine')}} {first?.author?.bot === true && {t('thread.bot')}} @@ -104,25 +110,26 @@ function Item({ entry, viewer, open, t }: { /** * Render the thread list. * @param props - threads, their places, the file order, the filter, and the list's actions. - * @returns the list pane. + * @returns the list pane and the scrim behind it where it floats over the files. */ export function ThreadList(props: ThreadListProps): ReactNode { - const { entries, order, viewer, filter, t } = props + const { entries, order, filter, t } = props const threads = useMemo(() => entries.map(entry => entry.thread), [entries]) const counts = useMemo(() => Object.fromEntries(THREAD_FILTERS.map(item => [item, - threads.filter(thread => passesFilter(thread, item, viewer)).length])) as Record, [threads, viewer]) + threads.filter(thread => passesFilter(thread, item)).length])) as Record, [threads]) const groups = useMemo(() => { const position = new Map(order.map((path, index) => [path, index])) const byPath = new Map() for (const entry of entries) { - if (!passesFilter(entry.thread, filter, viewer)) continue + if (!passesFilter(entry.thread, filter)) continue const list = byPath.get(entry.thread.path) if (list === undefined) byPath.set(entry.thread.path, [entry]) else list.push(entry) } return [...byPath].sort(([a], [b]) => (position.get(a) ?? order.length) - (position.get(b) ?? order.length) || a.localeCompare(b)) .map(([path, list]) => [path, list.toSorted((a, b) => rank(a.place) - rank(b.place))] as const) - }, [entries, order, filter, viewer]) + }, [entries, order, filter]) + const pane = useRef(null) const rows = useRef(null) useLayoutEffect(() => { const container = rows.current @@ -132,32 +139,49 @@ export function ThreadList(props: ThreadListProps): ReactNode { if (group.dataset.forgeThreadGroup === props.file) group.scrollIntoView({ block: 'start' }) } }, [props.file]) - return + useLayoutEffect(() => { + if (!props.claim) return + props.claimed() + if (covers(pane.current)) pane.current.focus({ preventScroll: true }) + }, [props.claim]) + const escape = (event: KeyboardEvent): void => { + if (event.key !== 'Escape') return + event.preventDefault() + event.stopPropagation() + props.close() + } + const open = (entry: PlacedThread): void => { props.open(entry, covers(pane.current)) } + return <> + -
+
{threads.length === 0 ?
{t('thread.empty')}
: groups.length === 0 ?
{t('thread.none')}
: groups.map(([path, list]) =>
diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index 9ba50586b3..5a95837897 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -339,7 +339,8 @@ export const zh = { 'thread.originalFailed': '无法读取当时的文件:{message}', 'thread.openOnHost': '在 GitHub 中查看', 'thread.unresolvedCount': '{count} 条未解决', - 'thread.unresolvedAria': '{name} 有 {count} 条未解决的讨论,打开讨论列表', + 'thread.unresolvedAria': '{name} 有 {count} 条未解决的讨论,跳到下一条', + 'thread.next': '跳到下一条未解决的讨论', 'thread.treeCount': '{count} 条未解决的讨论', 'thread.loadFailed': '无法读取 GitHub 讨论:{message}', 'thread.inputFailed': '输入框暂时无法添加这个讨论,请稍后重试', @@ -690,7 +691,8 @@ export const en: Record = { 'thread.originalFailed': 'Could not read the file at that commit: {message}', 'thread.openOnHost': 'View on GitHub', 'thread.unresolvedCount': '{count} unresolved', - 'thread.unresolvedAria': '{name} has {count} unresolved threads; open the thread list', + 'thread.unresolvedAria': '{name} has {count} unresolved threads; go to the next one', + 'thread.next': 'Go to the next unresolved thread', 'thread.treeCount': '{count} unresolved threads', 'thread.loadFailed': 'Could not read GitHub threads: {message}', 'thread.inputFailed': 'The input could not take this thread; try again later', @@ -1045,7 +1047,8 @@ export const ja: Record = { 'thread.originalFailed': '当時のファイルを読み込めません:{message}', 'thread.openOnHost': 'GitHub で表示', 'thread.unresolvedCount': '未解決 {count} 件', - 'thread.unresolvedAria': '{name} に未解決のスレッドが {count} 件あります。スレッド一覧を開く', + 'thread.unresolvedAria': '{name} に未解決のスレッドが {count} 件あります。次のスレッドへ移動', + 'thread.next': '次の未解決のスレッドへ移動', 'thread.treeCount': '未解決のスレッド {count} 件', 'thread.loadFailed': 'GitHub のスレッドを読み込めません:{message}', 'thread.inputFailed': '入力欄にこのスレッドを追加できません。しばらくしてから再試行してください', @@ -1393,7 +1396,8 @@ export const es: Record = { 'thread.originalFailed': 'No se pudo leer el archivo de ese commit: {message}', 'thread.openOnHost': 'Ver en GitHub', 'thread.unresolvedCount': '{count} sin resolver', - 'thread.unresolvedAria': '{name} tiene {count} hilos sin resolver; abrir la lista de hilos', + 'thread.unresolvedAria': '{name} tiene {count} hilos sin resolver; ir al siguiente', + 'thread.next': 'Ir al siguiente hilo sin resolver', 'thread.treeCount': '{count} hilos sin resolver', 'thread.loadFailed': 'No se pudieron leer los hilos de GitHub: {message}', 'thread.inputFailed': 'El campo de entrada no pudo recibir este hilo; inténtalo más tarde', @@ -1741,7 +1745,8 @@ export const fr: Record = { 'thread.originalFailed': 'Impossible de lire le fichier à ce commit : {message}', 'thread.openOnHost': 'Voir sur GitHub', 'thread.unresolvedCount': '{count} non résolus', - 'thread.unresolvedAria': '{name} a {count} fils non résolus ; ouvrir la liste des fils', + 'thread.unresolvedAria': '{name} a {count} fils non résolus ; aller au suivant', + 'thread.next': 'Aller au fil non résolu suivant', 'thread.treeCount': '{count} fils non résolus', 'thread.loadFailed': 'Impossible de lire les fils GitHub : {message}', 'thread.inputFailed': 'Le champ de saisie n’a pas pu recevoir ce fil ; réessayez plus tard', @@ -2089,7 +2094,8 @@ export const de: Record = { 'thread.originalFailed': 'Die Datei in diesem Commit konnte nicht gelesen werden: {message}', 'thread.openOnHost': 'Auf GitHub ansehen', 'thread.unresolvedCount': '{count} ungelöst', - 'thread.unresolvedAria': '{name} hat {count} ungelöste Threads; Threadliste öffnen', + 'thread.unresolvedAria': '{name} hat {count} ungelöste Threads; zum nächsten springen', + 'thread.next': 'Zum nächsten ungelösten Thread springen', 'thread.treeCount': '{count} ungelöste Threads', 'thread.loadFailed': 'GitHub-Threads konnten nicht gelesen werden: {message}', 'thread.inputFailed': 'Das Eingabefeld konnte diesen Thread nicht aufnehmen; später erneut versuchen', @@ -2437,7 +2443,8 @@ export const ru: Record = { 'thread.originalFailed': 'Не удалось прочитать файл в том коммите: {message}', 'thread.openOnHost': 'Открыть на GitHub', 'thread.unresolvedCount': 'Нерешённых: {count}', - 'thread.unresolvedAria': 'В {name} нерешённых обсуждений: {count}. Открыть список обсуждений', + 'thread.unresolvedAria': 'В {name} нерешённых обсуждений: {count}. Перейти к следующему', + 'thread.next': 'Перейти к следующему нерешённому обсуждению', 'thread.treeCount': 'Нерешённых обсуждений: {count}', 'thread.loadFailed': 'Не удалось прочитать обсуждения GitHub: {message}', 'thread.inputFailed': 'Не удалось добавить обсуждение в поле ввода; повторите попытку позже', @@ -2785,7 +2792,8 @@ export const pt: Record = { 'thread.originalFailed': 'Não foi possível ler o arquivo naquele commit: {message}', 'thread.openOnHost': 'Ver no GitHub', 'thread.unresolvedCount': '{count} não resolvidas', - 'thread.unresolvedAria': '{name} tem {count} discussões não resolvidas; abrir a lista de discussões', + 'thread.unresolvedAria': '{name} tem {count} discussões não resolvidas; ir para a próxima', + 'thread.next': 'Ir para a próxima discussão não resolvida', 'thread.treeCount': '{count} discussões não resolvidas', 'thread.loadFailed': 'Não foi possível ler as discussões do GitHub: {message}', 'thread.inputFailed': 'O campo de entrada não pôde receber esta discussão; tente novamente mais tarde', diff --git a/packages/experimental/client-ui-forge/src/client/review-threads.ts b/packages/experimental/client-ui-forge/src/client/review-threads.ts index b560da934c..84091aae7f 100644 --- a/packages/experimental/client-ui-forge/src/client/review-threads.ts +++ b/packages/experimental/client-ui-forge/src/client/review-threads.ts @@ -1,12 +1,13 @@ /** - * Where the changes view shows each review thread of a change request, which threads each filter of the thread list - * keeps, and the composer quote of a whole thread. + * Where the changes view shows each review thread of a change request, the order a file shows them in, which threads + * each filter of the thread list keeps, and the composer quote of a whole thread. */ import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { ForgeAnchor, ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { ForgeCommitRange, ForgeDiffFile } from '../types.ts' +import type { ForgeCommitRange, ForgeDiffFile, ForgeDiffHunk } from '../types.ts' +import { hunkRows } from './diff-rows.ts' /** The changes a view shows, which decides where a thread can sit. */ export interface ThreadView { @@ -65,6 +66,19 @@ export function anchorRange(side: 'L' | 'R', anchor: Pick(items: readonly Item[], file: ForgeDiffFile | undefined): Item[] { + const rank = ({ place }: Item): readonly [number, number, number] => { + switch (place.kind) { + case 'file': return [0, 0, 0] + case 'line': return [1, ...rowOf(file, place.side, place.endLine)] + case 'outdated': return [2, 0, 0] + case 'elsewhere': return [3, 0, 0] + /* v8 ignore next -- closed ThreadPlace union exhaustiveness guard */ + default: return assertNever(place, 'ThreadPlace') + } } - return file.hunks.length + const keyed = items.map(item => [rank(item), item] as const) + return keyed.toSorted(([a], [b]) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]).map(([, item]) => item) +} + +/** + * Where a line draws: twice the index of the collapsed lines that hold it, or twice a hunk's index plus one with the + * line's row in that hunk, so rows of one hunk keep their patch order across both sides. + */ +function rowOf(file: ForgeDiffFile | undefined, side: 'L' | 'R', line: number): readonly [number, number] { + if (file === undefined) return [0, line] + const spot = spotOf(file, side, line) + if (spot.kind === 'gap') return [2 * spot.index, line] + return [2 * spot.index + 1, hunkRows(spot.hunk).findIndex(row => (side === 'L' ? row.old : row.new) === line)] } /** 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 c7e4c4e00a..1448f60b4e 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 @@ -1693,7 +1693,7 @@ describe('ChangesTab review threads', () => { expect(card(m, 'in-gap')?.previousElementSibling?.getAttribute('data-forge-diff-gap')).toBe('1') expect(card(m, 'resolved')?.textContent).toContain('Resolved thread · reviewer') // The count alone shows below 480px. - expect([...within(app).getByRole('button', { name: 'app.ts has 4 unresolved threads; open the thread list' }).children] + expect([...within(app).getByRole('button', { name: 'app.ts has 4 unresolved threads; go to the next one' }).children] .map(text => text.textContent)).toEqual(['4 unresolved', '4']) expect(app.querySelector('[data-forge-outdated-threads]')?.textContent).toContain('1 outdated threads') fireEvent.click(within(card(m, 'outdated')!).getByRole('button', { name: en['thread.viewOriginal'] })) @@ -1746,9 +1746,7 @@ describe('ChangesTab review threads', () => { fireEvent.keyDown(list, { key: 'Escape' }) expect(m.view.queryByRole('complementary')).toBeNull() expect(document.activeElement).toBe(toggle) - scrolled.mockClear() - fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: /^app\.ts has 4 unresolved threads/ })) - expect(scrolled.mock.contexts).toContain(m.view.container.querySelector('[data-forge-thread-group="src/app.ts"]')) + fireEvent.click(toggle) fireEvent.click(within(m.view.getByRole('complementary')).getByRole('button', { name: en['thread.close'] })) expect(m.view.queryByRole('complementary')).toBeNull() fireEvent.click(toggle) @@ -1759,6 +1757,21 @@ describe('ChangesTab review threads', () => { expect(m.view.queryByRole('complementary')).toBeNull() }) + it('steps through a file\'s unresolved threads in display order from the count in its header', async () => { + const m = mount({ source, setup: reviewed() }) + await settle() + const shown: (string | undefined)[] = [] + for (let step = 0; step < 5; step += 1) { + scrolled.mockClear() + fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: 'app.ts has 4 unresolved threads; go to the next one' })) + await settle() + shown.push((scrolled.mock.contexts as HTMLElement[]).find(element => element.dataset.forgeThread !== undefined)?.dataset.forgeThread) + } + // R4 in the first hunk, R8 in the unchanged lines after it, L11 in the second hunk, then the outdated thread, then R4 again. + expect(shown).toEqual(['on-row', 'in-gap', 'old-side', 'outdated', 'on-row']) + expect(m.view.queryByRole('complementary')).toBeNull() + }) + it('takes the focus where the thread list covers the files, and closes it before opening a thread', async () => { // The narrow-view styles float the list; jsdom computes this rule in their place. const style = document.createElement('style') diff --git a/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx index 172bf55921..0e27ce88c4 100644 --- a/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-thread-cards.client.spec.tsx @@ -8,7 +8,7 @@ import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol import { en } from '../src/client/locales.ts' import { Avatar, OutdatedThreads, ThreadCard, type ThreadActions } from '../src/client/ReviewThreads.tsx' import { ThreadList, type ThreadListProps } from '../src/client/ThreadList.tsx' -import { reviewComment, reviewThread } from './thread-fixtures.client.ts' +import { diffFile, reviewComment, reviewThread } from './thread-fixtures.client.ts' const t = makeTranslate(en) const OLD = 'b'.repeat(40) @@ -157,7 +157,7 @@ describe('OutdatedThreads', () => { describe('ThreadList', () => { function list(overrides: Partial = {}) { const props: ThreadListProps = { - entries: [], order: [], truncated: false, url: 'https://github.com/octo/demo/pull/7', filter: 'all', file: null, claim: false, + entries: [], files: [], truncated: false, url: 'https://github.com/octo/demo/pull/7', filter: 'all', claim: false, claimed: vi.fn(), choose: vi.fn(), open: vi.fn(), openLink: vi.fn(), close: vi.fn(), t, ...overrides, } return { props, view: render() } @@ -199,15 +199,19 @@ describe('ThreadList', () => { expect(props.close).toHaveBeenCalledOnce() }) - it('groups threads by file in file order, scrolls to a file\'s group, and moves the filter with arrow keys', () => { - const entry = { thread: reviewThread({ path: 'b.ts' }), place: { kind: 'line', side: 'R', startLine: 3, endLine: 3 } as const } - const other = { thread: reviewThread({ path: 'a.ts' }), place: { kind: 'line', side: 'R', startLine: 3, endLine: 3 } as const } + it('groups threads by file in file order, orders them by row, and moves the filter with arrow keys', () => { + const at = (id: string, path: string, side: 'L' | 'R', line: number) => ({ thread: reviewThread({ id: id as ForgeThreadId, path }), + place: { kind: 'line', side, startLine: line, endLine: line } as const }) const empty = { thread: reviewThread({ path: 'c.ts', comments: [] }), place: { kind: 'file' } as const } - const { view, props } = list({ entries: [empty, entry, other], order: ['b.ts'], filter: 'unresolved', file: 'a.ts' }) + // In b.ts the added R2 row follows the deleted L2 row, and L9 sits in the unchanged lines after the hunk. + const files = [diffFile('b.ts', [{ oldStart: 1, oldLines: 2, newStart: 1, newLines: 2, lines: [' a', '-b', '+B'] }])] + const { view, props } = list({ entries: [empty, at('late', 'b.ts', 'L', 9), at('added', 'b.ts', 'R', 2), at('other', 'a.ts', 'R', 3), + at('deleted', 'b.ts', 'L', 2)], files, filter: 'unresolved' }) expect([...view.container.querySelectorAll('[data-forge-thread-group]')].map(group => group.getAttribute('data-forge-thread-group'))) .toEqual(['b.ts', 'a.ts', 'c.ts']) + expect([...view.container.querySelectorAll('[data-forge-thread-group="b.ts"] [data-forge-thread-item]')].map(item => item.getAttribute('data-forge-thread-item'))) + .toEqual(['deleted', 'added', 'late']) expect(view.container.querySelector('[data-forge-thread-group="c.ts"] [class*="excerpt"]')?.textContent).toBe('') - expect(scrolled.mock.contexts).toEqual([view.container.querySelector('[data-forge-thread-group="a.ts"]')]) fireEvent.keyDown(view.getByRole('radio', { name: /^Unresolved/ }), { key: 'ArrowRight' }) expect(props.choose).toHaveBeenCalledWith('resolved') }) diff --git a/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts b/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts index 1ac3c0120a..f2f5f6e644 100644 --- a/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review-threads.client.spec.ts @@ -2,10 +2,9 @@ import { describe, expect, it } from 'vitest' import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types' import { - anchorRange, formatThreadQuote, gapOf, hunkExcerpt, passesFilter, placeThread, threadQuoteSummary, THREAD_FILTERS, + anchorRange, formatThreadQuote, gapOf, inFileOrder, hunkExcerpt, passesFilter, placeThread, threadQuoteSummary, THREAD_FILTERS, } from '../src/client/review-threads.ts' -import type { ForgeDiffFile } from '../src/types.ts' -import { reviewComment, reviewThread } from './thread-fixtures.client.ts' +import { diffFile, reviewComment, reviewThread } from './thread-fixtures.client.ts' const HEAD = 'a'.repeat(40) const OLD = 'b'.repeat(40) @@ -44,14 +43,10 @@ it('names a side and its lines', () => { }) it('finds the collapsed unchanged lines that hold a line on either side', () => { - const file: ForgeDiffFile = { - path: 'a.ts', previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, additions: 2, deletions: 2, - digest: 'digest', layer: 'implementation', - hunks: [ - { oldStart: 5, oldLines: 3, newStart: 5, newLines: 3, lines: [' a', '-b', '+b', ' c'] }, - { oldStart: 20, oldLines: 2, newStart: 22, newLines: 2, lines: ['-x', '+x', ' y'] }, - ], - } + const file = diffFile('a.ts', [ + { oldStart: 5, oldLines: 3, newStart: 5, newLines: 3, lines: [' a', '-b', '+b', ' c'] }, + { oldStart: 20, oldLines: 2, newStart: 22, newLines: 2, lines: ['-x', '+x', ' y'] }, + ]) expect(gapOf(file, 'R', 2)).toBe(0) expect(gapOf(file, 'R', 6)).toBeUndefined() expect(gapOf(file, 'R', 10)).toBe(1) @@ -60,6 +55,23 @@ it('finds the collapsed unchanged lines that hold a line on either side', () => expect(gapOf(file, 'R', 40)).toBe(2) }) +it('orders a file\'s threads as its section shows them', () => { + const file = diffFile('a.ts', [ + { oldStart: 5, oldLines: 3, newStart: 5, newLines: 3, lines: [' a', '-b', '+b', ' c'] }, + { oldStart: 20, oldLines: 2, newStart: 22, newLines: 2, lines: ['-x', '+x', ' y'] }, + ]) + const line = (id: string, side: 'L' | 'R', at: number) => ({ id, place: { kind: 'line', side, startLine: at, endLine: at } as const }) + const items = [ + { id: 'away', place: { kind: 'elsewhere' } as const }, { id: 'gone', place: { kind: 'outdated' } as const }, + line('tail', 'R', 40), line('added', 'R', 6), line('second-hunk', 'L', 20), line('before', 'R', 2), line('deleted', 'L', 6), + { id: 'whole', place: { kind: 'file' } as const }, line('between', 'L', 10), + ] + expect(inFileOrder(items, file).map(item => item.id)) + .toEqual(['whole', 'before', 'deleted', 'added', 'between', 'second-hunk', 'tail', 'gone', 'away']) + // Without the file's diff, lines sort by their number. + expect(inFileOrder([line('b', 'R', 9), line('a', 'L', 2)], undefined).map(item => item.id)).toEqual(['a', 'b']) +}) + describe('thread filters', () => { it('keeps the threads each filter names', () => { const outdated = reviewThread({ current: null }) diff --git a/packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts index fe08cb6a60..d4aa1d0f02 100644 --- a/packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/thread-fixtures.client.ts @@ -1,6 +1,7 @@ -/** Host review threads and comments shared by the browser-side thread tests. */ +/** Host review threads, comments, and diff files shared by the browser-side thread tests. */ import type { ForgeCommentId, ForgeReviewComment, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeDiffFile, ForgeDiffHunk } from '../src/types.ts' let comments = 0 @@ -41,3 +42,14 @@ export function reviewThread(overrides: Partial = {}): ForgeR ...overrides, } } + +/** + * Build a modified text file with hunks. + * @param path - the file's path. + * @param hunks - its hunks. + * @returns the diff file. + */ +export function diffFile(path: string, hunks: readonly ForgeDiffHunk[]): ForgeDiffFile { + return { path, previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, additions: 1, deletions: 1, + digest: 'digest', layer: 'implementation', hunks } +} From d6208abfcaff5526a1c623ff4d54ed9e4bb73a59 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 18:21:08 +0800 Subject: [PATCH 08/29] docs(forge-github): state how review reads bound the first page and which pages re-check the head A first review thread page whose output alone passes maxOutputBytes fails the read as too-large through gh's output limit, rather than ending it as truncated as the README and the ReviewLimits documentation said; only a later page that would pass the limit truncates the read. Thread pages after the first re-check the head, while a thread's comment pages do not. A test pins the first-page failure. --- packages/experimental/forge-github/README.i18n.yaml | 4 ++-- packages/experimental/forge-github/README.md | 2 +- packages/experimental/forge-github/README.zh.md | 2 +- packages/experimental/forge-github/src/threads.ts | 10 +++++++--- .../experimental/forge-github/tests/threads.spec.ts | 8 +++++++- 5 files changed, 18 insertions(+), 8 deletions(-) diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index 6d3ca2d441..a12b42da43 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: dc1fc7eb436482c8 - zh: 968aa86136fdd840 + en: e01228c710824a6c + zh: d59f5f14f7e8150f /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: f3d0a577b0a4db0a zh: 0c15ac7979909117 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 0d5f8ea6b6..437f23b2ec 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -50,7 +50,7 @@ A pull request is `mergeReady` when it is open, not a draft, GitHub reports its Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. -`readReview` reads review threads with one GraphQL query that names `headRefOid` and the signed-in viewer, and returns `stale` when the head is not the requested commit. It reads threads in pages of up to 100 until it has read `maxReviewThreads` of them, each page after the first naming the head again, so a push during the read returns `stale`; it reads every comment of each thread, and the commits and `diffHunk` of a thread's first comment once. All pages together, measured as JSON, must fit `maxOutputBytes`: the page that would pass it is dropped with the threads after it, and the result is marked `truncated`, as when more than `maxReviewThreads` threads exist. A thread on lines gets a `current` position only when GitHub reports it not outdated, with a `line`, and its first comment's `commit` is the head: a comment written on an earlier commit after a force-push keeps a `line` that numbers that commit, and GitHub can mark a thread outdated while keeping its `line`. `original` comes from `originalLine` and `originalStartLine` at the first comment's `originalCommit`; `subjectType: FILE` threads have neither. A range whose start is on the other side of the diff keeps its last line. Threads without comments are left out. REST's `position` does not tell outdated threads apart and is not read. +`readReview` reads review threads with one GraphQL query that names `headRefOid` and the signed-in viewer, and returns `stale` when the head is not the requested commit. It reads threads in pages of up to 100 until it has read `maxReviewThreads` of them, each thread page after the first naming the head again, so a push during the read returns `stale`; it reads every comment of each thread through comment pages, which do not name the head, and the commits and `diffHunk` of a thread's first comment once. All pages together, measured as JSON, must fit `maxOutputBytes`: a later page that would pass it is dropped with the threads after it, and the result is marked `truncated`, as when more than `maxReviewThreads` threads exist; a first page whose output alone passes it fails the read as `too-large`. A thread on lines gets a `current` position only when GitHub reports it not outdated, with a `line`, and its first comment's `commit` is the head: a comment written on an earlier commit after a force-push keeps a `line` that numbers that commit, and GitHub can mark a thread outdated while keeping its `line`. `original` comes from `originalLine` and `originalStartLine` at the first comment's `originalCommit`; `subjectType: FILE` threads have neither. A range whose start is on the other side of the diff keeps its last line. Threads without comments are left out. REST's `position` does not tell outdated threads apart and is not read. ----- diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 99896c73d8..2f94f93d75 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -50,7 +50,7 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 -`readReview` 用一次 GraphQL 查询读取评审讨论,同时读出 `headRefOid` 和当前登录的用户;head 不是所请求的提交时返回 `stale`。讨论按每页最多 100 个分页读取,直到读满 `maxReviewThreads` 个;第一页之后的每一页都会再次读取 head,因此读取期间有新的推送时返回 `stale`。每个讨论的评论都会全部读出,讨论第一条评论的提交和 `diffHunk` 只读一次。所有页面按 JSON 计合计不得超过 `maxOutputBytes`:会超出上限的那一页及其后的讨论被丢弃,结果标记为 `truncated`,与讨论数超过 `maxReviewThreads` 时相同。行级讨论只有在 GitHub 报告它未过期、带有 `line`,且第一条评论的 `commit` 就是 head 时,才得到 `current` 位置:force-push 之后写在旧提交上的评论保留的 `line` 是那个旧提交的行号,GitHub 也可能在标记讨论过期的同时保留它的 `line`。`original` 取自第一条评论 `originalCommit` 上的 `originalLine` 和 `originalStartLine`;`subjectType: FILE` 的讨论两者都没有。起始行在 diff 另一侧的范围只保留最后一行。没有评论的讨论会被略去。REST 的 `position` 无法区分已过期的讨论,因此不读取。 +`readReview` 用一次 GraphQL 查询读取评审讨论,同时读出 `headRefOid` 和当前登录的用户;head 不是所请求的提交时返回 `stale`。讨论按每页最多 100 个分页读取,直到读满 `maxReviewThreads` 个;第一页之后的每一页讨论都会再次读取 head,因此读取期间有新的推送时返回 `stale`。每个讨论的评论都会经评论分页全部读出,评论分页不读取 head;讨论第一条评论的提交和 `diffHunk` 只读一次。所有页面按 JSON 计合计不得超过 `maxOutputBytes`:之后的某一页会超出上限时,该页及其后的讨论被丢弃,结果标记为 `truncated`,与讨论数超过 `maxReviewThreads` 时相同;第一页的输出本身超过上限时,读取以 `too-large` 失败。行级讨论只有在 GitHub 报告它未过期、带有 `line`,且第一条评论的 `commit` 就是 head 时,才得到 `current` 位置:force-push 之后写在旧提交上的评论保留的 `line` 是那个旧提交的行号,GitHub 也可能在标记讨论过期的同时保留它的 `line`。`original` 取自第一条评论 `originalCommit` 上的 `originalLine` 和 `originalStartLine`;`subjectType: FILE` 的讨论两者都没有。起始行在 diff 另一侧的范围只保留最后一行。没有评论的讨论会被略去。REST 的 `position` 无法区分已过期的讨论,因此不读取。 ----- diff --git a/packages/experimental/forge-github/src/threads.ts b/packages/experimental/forge-github/src/threads.ts index f23507e374..5717f47a0c 100644 --- a/packages/experimental/forge-github/src/threads.ts +++ b/packages/experimental/forge-github/src/threads.ts @@ -45,7 +45,10 @@ export const THREAD_COMMENTS_QUERY = `query($id: ID!, $cursor: String!) { export interface ReviewLimits { /** Most threads read. */ readonly maxReviewThreads: number - /** Most JSON bytes of all pages together; a page that would pass it ends the read as truncated. */ + /** + * Most JSON bytes of all pages together: a later page that would pass it ends the read as truncated, and a first + * page whose output alone passes it fails the read as `too-large`. + */ readonly maxOutputBytes: number } @@ -97,8 +100,9 @@ type CommentNode = z.infer /** * Read the review threads of a pull request while its head is `headSha`. The first page also names the head and the * signed-in user; every following thread page names the head again, so a head that moves during the read returns - * `stale`. Threads are read up to `maxReviewThreads`, each with all of its comments. A page that would bring the - * pages read, measured as JSON, past `maxOutputBytes` is dropped with the threads after it, and the result is marked truncated. + * `stale`, while a thread's comment pages do not. Threads are read up to `maxReviewThreads`, each with all of its + * comments. A later page that would bring the pages read, measured as JSON, past `maxOutputBytes` is dropped with the + * threads after it, and the result is marked truncated; `read` fails a first page whose output alone passes the limit. * @param read - runs one GraphQL request. * @param ref - pull request, with an owner and name already checked for inlining. * @param headSha - head commit the threads must be read at. diff --git a/packages/experimental/forge-github/tests/threads.spec.ts b/packages/experimental/forge-github/tests/threads.spec.ts index 7962e90280..42c49f389a 100644 --- a/packages/experimental/forge-github/tests/threads.spec.ts +++ b/packages/experimental/forge-github/tests/threads.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { GhOutput, GhRunner } from '../src/gh.ts' +import { GhOutputLimitError, type GhOutput, type GhRunner } from '../src/gh.ts' import { GitHubProvider } from '../src/provider.ts' import type { GitHubLimits } from '../src/provider.ts' import { REVIEW_QUERY, REVIEW_THREADS_QUERY, THREAD_COMMENTS_QUERY } from '../src/threads.ts' @@ -206,6 +206,12 @@ describe('GitHub provider review threads', () => { .resolves.toMatchObject({ threads: [{ id: 't1' }], truncated: true }) }) + it('fails a read whose first page alone passes maxOutputBytes as too-large', async () => { + const run: GhRunner = async () => { throw new GhOutputLimitError('gh output exceeds maxOutputBytes') } + + await expect(provider(run).readReview(pull(7), head, signal)).resolves.toEqual({ code: 'too-large', message: 'gh output exceeds maxOutputBytes' }) + }) + it.each([ ['a thread page without a cursor', firstPage({ pageInfo: { hasNextPage: true, endCursor: null }, nodes: [] }), {}, {}, 'GitHub review thread pagination did not advance'], From b02529e520756f2fe7f0a81677d210568b12c9c8 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 11:21:00 +0800 Subject: [PATCH 09/29] feat(forge): write review threads and the pending review through the provider ForgeProvider gains an optional writeReview for replies, resolution, comment edits and deletions, and the viewer's pending review, which review reads now report with the viewer's permissions. The GitHub provider checks the head and the pending review in one query, then sends one GraphQL mutation on stdin and never retries it; a reply at once is refused while a pending review exists, since GitHub adds it to that review. The forge panel Remote changeRequestReviewWrite drops the kept threads after every write, because resolving a thread does not move a pull request's updatedAt. --- .../experimental/client-ui-forge/src/index.ts | 92 ++++++- .../client-ui-forge/src/review-cache.ts | 43 ++- .../tests/review-cache.host.spec.ts | 37 ++- .../client-ui-forge/tests/review.host.spec.ts | 107 +++++++- .../experimental/forge-github/package.json | 1 + .../experimental/forge-github/src/provider.ts | 15 +- .../forge-github/src/review-writes.ts | 209 +++++++++++++++ .../experimental/forge-github/src/threads.ts | 61 ++++- .../forge-github/tests/review-writes.spec.ts | 253 ++++++++++++++++++ .../forge-github/tests/threads.spec.ts | 63 ++++- .../experimental/forge-github/tsconfig.json | 3 + packages/experimental/forge/src/index.ts | 31 ++- packages/experimental/forge/src/types.ts | 68 ++++- .../experimental/forge/tests/registry.spec.ts | 21 +- .../experimental/forge/tests/watch.spec.ts | 32 ++- pnpm-lock.yaml | 3 + 16 files changed, 987 insertions(+), 52 deletions(-) create mode 100644 packages/experimental/forge-github/src/review-writes.ts create mode 100644 packages/experimental/forge-github/tests/review-writes.spec.ts diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 6a1baaa71d..aa6e09c9d8 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -6,8 +6,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-api-remote-access' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeReviewData, ForgeReviewRequest, - ForgeReviewResult, MergeMethod, + ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeLineComment, ForgeReviewData, + ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, MergeMethod, } from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' @@ -466,8 +466,8 @@ export class ForgePanelController extends TypertRemoteService { /** * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read * at the same head commit and update time are reused from memory, for any Session, until they are - * `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age shows threads resolved - * since, which do not change a GitHub pull request's update time. + * `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read + * again after that age shows threads resolved elsewhere since, which do not change a GitHub pull request's update time. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param headSha - head commit of the displayed diff. @@ -493,14 +493,16 @@ export class ForgePanelController extends TypertRemoteService { const readAt = Date.now() const kept = this.reviews.get(key, version, readAt) if (kept !== undefined) return kept + const token = this.reviews.token() const review = await this.home.forge.readReview(ref, headSha, signal) if ('code' in review) throw reviewError(review) - this.reviews.set(key, version, review, readAt) + this.reviews.set(key, version, review, readAt, token) return review } /** - * Publish a line comment or completed review for a visible Session binding. + * Publish a line comment or completed review for a visible Session binding. The threads kept for the change request + * are dropped once the host answers, so the next read shows the comments. * @param session - Session retaining the change request. * @param url - visible binding URL. * @param request - reviewed head, ranges, plain text, and explicit review decision. @@ -511,13 +513,43 @@ export class ForgePanelController extends TypertRemoteService { async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise { signal.throwIfAborted() const { ref } = this.bound(session, url) - if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(request.headSha)) throw new Error('Invalid review commit') + if (!isCommit(request.headSha)) throw new Error('Invalid review commit') const comments = request.kind === 'comment' ? [request.comment] : request.comments - if (comments.some(comment => comment.path === '' || comment.body.trim() === '' - || !Number.isSafeInteger(comment.startLine) || comment.startLine < 1 - || !Number.isSafeInteger(comment.endLine) || comment.endLine < comment.startLine)) throw new Error('Invalid review comment') + if (!comments.every(validComment)) throw new Error('Invalid review comment') if (request.kind === 'review' && request.event !== 'approve' && request.body.trim() === '' && comments.length === 0) throw new Error('Empty review') - return await this.home.forge.submitReview(ref, request, signal) + try { + return await this.home.forge.submitReview(ref, request, signal) + } finally { + this.reviews.drop(changeRequestKey(ref)) + } + } + + /** + * Write to the review threads or the pending review of a change request of a Session while its head is still the + * head the user saw. The threads kept for the change request are dropped once the host answers, so the next read + * shows the write, which a resolve does not show through a GitHub pull request's update time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param write - the write and the head commit of the threads the user saw. + * @param signal - request cancellation. + * @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and + * `unknown` when the outcome must be checked on the host before the write is tried again. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error + * for a write without text, a head that is not a commit object name, or an invalid line range. + */ + @Remote + async changeRequestReviewWrite( + session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal, + ): Promise { + signal.throwIfAborted() + const { ref } = this.bound(session, url) + if (!isCommit(write.headSha)) throw new Error('Invalid review commit') + if (!validWrite(write)) throw new Error('Invalid review write') + try { + return await this.home.forge.writeReview(ref, write, signal) + } finally { + this.reviews.drop(changeRequestKey(ref)) + } } /** @@ -851,6 +883,44 @@ export class ForgePanelController extends TypertRemoteService { } } +/** + * Whether a value names a full commit object name. + * @param value - the value from the browser. + * @returns whether it is 40 or 64 hexadecimal digits. + */ +function isCommit(value: string): boolean { + return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value) +} + +/** + * Whether a line comment from the browser names a path, consecutive positive lines, and text. + * @param comment - the comment. + * @returns whether a provider may write it. + */ +function validComment(comment: ForgeLineComment): boolean { + return comment.path !== '' && comment.body.trim() !== '' && Number.isSafeInteger(comment.startLine) && comment.startLine >= 1 + && Number.isSafeInteger(comment.endLine) && comment.endLine >= comment.startLine +} + +/** + * Whether a review write from the browser names its target and carries text where the write needs it. + * @param write - the write. + * @returns whether a provider may perform it. + */ +function validWrite(write: ForgeReviewWrite): boolean { + switch (write.kind) { + case 'reply': return write.thread !== '' && write.body.trim() !== '' + case 'resolve': return write.thread !== '' + case 'edit-comment': return write.comment !== '' && write.body.trim() !== '' + case 'delete-comment': return write.comment !== '' + case 'add-pending': return validComment(write.comment) + case 'submit-pending': return write.review !== '' && (write.event !== 'request-changes' || write.body.trim() !== '') + case 'discard-pending': return write.review !== '' + /* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */ + default: return assertNever(write, 'ForgeReviewWrite.kind') + } +} + /** * Report why the code host did not provide a diff or file. * @param failure - the provider's failure. diff --git a/packages/experimental/client-ui-forge/src/review-cache.ts b/packages/experimental/client-ui-forge/src/review-cache.ts index 6a8d9f0d1e..fa8c54f53a 100644 --- a/packages/experimental/client-ui-forge/src/review-cache.ts +++ b/packages/experimental/client-ui-forge/src/review-cache.ts @@ -1,6 +1,6 @@ /** * Review threads of change requests kept in memory, so the changes view reads them from the code host again only - * after the change request's head or update time changes or the kept threads reach their age limit. + * after the change request's head or update time changes, the kept threads reach their age limit, or a review write drops them. */ import { Buffer } from 'node:buffer' @@ -18,11 +18,14 @@ interface Entry { /** * One read of review threads per change request, bounded by age and by the total UTF-8 size of the kept reads as - * JSON; the least recently read change request leaves first. + * JSON; the least recently read change request leaves first. A read that started before a drop of any change request + * is not kept, so threads read before a write never replace the drop. */ export class ReviewCache { private readonly entries = new Map() private bytes = 0 + /** Number of drops so far. */ + private drops = 0 /** * @param maxBytes - most UTF-8 bytes kept together; a larger read is not kept. @@ -46,20 +49,26 @@ export class ReviewCache { return entry.review } + /** + * Name the cache's state when a read starts, for {@link ReviewCache.set}. + * @returns the token of the read. + */ + token(): number { + return this.drops + } + /** * Keep a read in place of the change request's earlier one, then drop the least recently read change requests - * until the rest fit within `maxBytes`. + * until the rest fit within `maxBytes`. A read whose token a drop outdated is not kept. * @param key - the change request. * @param version - head commit and update time the threads were read at. * @param review - the threads. * @param readAt - epoch milliseconds when the read started. + * @param token - what {@link ReviewCache.token} returned when the read started. */ - set(key: ChangeRequestKey, version: string, review: ForgeReviewData, readAt: number): void { - const previous = this.entries.get(key) - if (previous !== undefined) { - this.entries.delete(key) - this.bytes -= previous.bytes - } + set(key: ChangeRequestKey, version: string, review: ForgeReviewData, readAt: number, token: number): void { + if (token !== this.drops) return + this.forget(key) const bytes = Buffer.byteLength(JSON.stringify(review)) if (bytes > this.maxBytes) return this.entries.set(key, { version, review, readAt, bytes }) @@ -70,4 +79,20 @@ export class ReviewCache { this.bytes -= entry.bytes } } + + /** + * Forget the threads kept for a change request, and every read in flight, after a write changed them. + * @param key - the change request. + */ + drop(key: ChangeRequestKey): void { + this.drops += 1 + this.forget(key) + } + + private forget(key: ChangeRequestKey): void { + const previous = this.entries.get(key) + if (previous === undefined) return + this.entries.delete(key) + this.bytes -= previous.bytes + } } diff --git a/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts b/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts index de498b8bbf..119f69dffd 100644 --- a/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts @@ -8,7 +8,7 @@ const b = 'fake:b#2' as ChangeRequestKey const c = 'fake:c#3' as ChangeRequestKey function review(viewer: string): ForgeReviewData { - return { headSha: 'a'.repeat(40), viewer, threads: [], truncated: false } + return { headSha: 'a'.repeat(40), viewer, threads: [], truncated: false, pendingReview: null, viewerCanReview: false } } const size = Buffer.byteLength(JSON.stringify(review('x'))) @@ -16,7 +16,7 @@ const size = Buffer.byteLength(JSON.stringify(review('x'))) describe('ReviewCache', () => { it('returns threads kept at the same version until they reach the age limit', () => { const cache = new ReviewCache(size * 4, 100) - cache.set(a, 'v1', review('x'), 1_000) + cache.set(a, 'v1', review('x'), 1_000, cache.token()) expect(cache.get(a, 'v1', 1_099)).toEqual(review('x')) expect(cache.get(a, 'v2', 1_050)).toBeUndefined() @@ -26,26 +26,45 @@ describe('ReviewCache', () => { it('replaces a change request\'s earlier read and drops the least recently read reads past the byte limit', () => { const cache = new ReviewCache(size * 2, 100) - cache.set(a, 'v1', review('x'), 0) - cache.set(a, 'v2', review('y'), 0) - cache.set(b, 'v1', review('z'), 0) + cache.set(a, 'v1', review('x'), 0, cache.token()) + cache.set(a, 'v2', review('y'), 0, cache.token()) + cache.set(b, 'v1', review('z'), 0, cache.token()) expect(cache.get(a, 'v1', 0)).toBeUndefined() expect(cache.get(a, 'v2', 0)).toEqual(review('y')) - cache.set(c, 'v1', review('w'), 0) + cache.set(c, 'v1', review('w'), 0, cache.token()) expect(cache.get(b, 'v1', 0)).toBeUndefined() expect(cache.get(a, 'v2', 0)).toEqual(review('y')) expect(cache.get(c, 'v1', 0)).toEqual(review('w')) }) + it('forgets a dropped change request and keeps no read that started before any drop', () => { + const cache = new ReviewCache(size * 4, 100) + const early = cache.token() + cache.set(a, 'v1', review('x'), 0, early) + cache.set(b, 'v1', review('y'), 0, early) + cache.drop(a) + cache.drop(c) + + expect(cache.get(a, 'v1', 0)).toBeUndefined() + expect(cache.get(b, 'v1', 0)).toEqual(review('y')) + cache.set(a, 'v1', review('z'), 0, early) + expect(cache.get(a, 'v1', 0)).toBeUndefined() + cache.set(a, 'v1', review('z'), 0, cache.token()) + expect(cache.get(a, 'v1', 0)).toEqual(review('z')) + cache.set(a, 'v2', review('much longer than the others'), 0, cache.token()) + cache.set(c, 'v1', review('w'), 0, cache.token()) + expect(cache.get(c, 'v1', 0)).toEqual(review('w')) + }) + it('keeps no read larger than the byte limit and forgets the read it replaced', () => { const cache = new ReviewCache(size, 100) - cache.set(a, 'v1', review('x'), 0) - cache.set(a, 'v2', review('longer'), 0) + cache.set(a, 'v1', review('x'), 0, cache.token()) + cache.set(a, 'v2', review('longer'), 0, cache.token()) expect(cache.get(a, 'v1', 0)).toBeUndefined() expect(cache.get(a, 'v2', 0)).toBeUndefined() - cache.set(b, 'v1', review('x'), 0) + cache.set(b, 'v1', review('x'), 0, cache.token()) expect(cache.get(b, 'v1', 0)).toEqual(review('x')) }) }) diff --git a/packages/experimental/client-ui-forge/tests/review.host.spec.ts b/packages/experimental/client-ui-forge/tests/review.host.spec.ts index 6869d3acb6..bf34f81384 100644 --- a/packages/experimental/client-ui-forge/tests/review.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review.host.spec.ts @@ -1,5 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ChangeRequestRef, ForgeFailure, ForgeReviewData, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge' +import type { + ChangeRequestRef, ForgeCommentId, ForgeFailure, ForgeReviewData, ForgeReviewId, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, +} from '@deepseek-ai/dsh-experimental-forge' import { SessionId } from '@deepseek-ai/dsh-session' import ForgePanelController from '../src/index.ts' import type { ForgePanelState } from '../src/index.ts' @@ -29,10 +31,11 @@ async function opened(config: Parameters[1] = {}): Promise<{ opene function review(headSha: string, path = 'src/a.ts'): ForgeReviewData { return { - headSha, viewer: 'octo', truncated: false, + headSha, viewer: 'octo', truncated: false, pendingReview: null, viewerCanReview: true, threads: [{ id: 'thread-1' as ForgeThreadId, path, side: 'R', subject: 'line', resolved: false, diffHunk: '@@ -1 +1 @@\n-old\n+new', current: { commit: headSha, startLine: 1, endLine: 1 }, original: { commit: headSha, startLine: 1, endLine: 1 }, comments: [], + viewerCanReply: true, viewerCanResolve: true, }], } } @@ -124,6 +127,106 @@ describe('forgePanel change request reviews', () => { expect(readReview).toHaveBeenCalledTimes(codes.length) }) + it('writes through the provider, then drops the kept threads so the next read goes to the host', async () => { + const { opened: panel, follower } = await opened() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + const writeReview = vi.fn(async (): Promise => ({ ok: true })) + Object.assign(panel.provider, { readReview, writeReview }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + const write: ForgeReviewWrite = { kind: 'resolve', headSha: HEAD, thread: 'thread-1' as ForgeThreadId, resolved: true } + + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + await expect(panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), write, signal)).resolves.toEqual({ ok: true }) + expect(writeReview).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), write, expect.any(AbortSignal)) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + expect(readReview).toHaveBeenCalledTimes(2) + + writeReview.mockRejectedValueOnce(new Error('gh crashed')) + await expect(panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), write, signal)).rejects.toThrow('gh crashed') + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + expect(readReview).toHaveBeenCalledTimes(3) + }) + + it('keeps no threads read before a write that settled during the read', async () => { + const { opened: panel, follower } = await opened() + const reading = Promise.withResolvers() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + readReview.mockReturnValueOnce(reading.promise) + Object.assign(panel.provider, { readReview, writeReview: async (): Promise => ({ ok: true }) }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + + const first = panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + await vi.waitFor(() => { expect(readReview).toHaveBeenCalledTimes(1) }) + await panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), + { kind: 'delete-comment', headSha: HEAD, comment: 'comment-1' as ForgeCommentId }, signal) + reading.resolve(review(HEAD, 'src/before.ts')) + await expect(first).resolves.toMatchObject({ threads: [{ path: 'src/before.ts' }] }) + await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal)) + .resolves.toMatchObject({ threads: [{ path: 'src/a.ts' }] }) + expect(readReview).toHaveBeenCalledTimes(2) + }) + + it('reports a provider without review writes as unsupported and refuses an unbound change request and invalid writes', async () => { + const { opened: panel, follower } = await opened() + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + const write = (url: string, value: ForgeReviewWrite): Promise => + panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, url, value, signal) + const thread = 'thread-1' as ForgeThreadId + const comment = 'comment-1' as ForgeCommentId + const reviewId = 'review-1' as ForgeReviewId + const line = { path: 'src/a.ts', side: 'R' as const, startLine: 2, endLine: 3, body: 'Check' } + + await expect(write(pullUrl(7), { kind: 'resolve', headSha: HEAD, thread, resolved: false })) + .resolves.toEqual({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' }) + await expect(write(pullUrl(9), { kind: 'resolve', headSha: HEAD, thread, resolved: false })).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(write(pullUrl(7), { kind: 'resolve', headSha: 'main', thread, resolved: false })).rejects.toThrow('Invalid review commit') + const invalid: ForgeReviewWrite[] = [ + { kind: 'reply', headSha: HEAD, thread, body: ' ', pending: false }, + { kind: 'reply', headSha: HEAD, thread: '' as ForgeThreadId, body: 'Done', pending: false }, + { kind: 'resolve', headSha: HEAD, thread: '' as ForgeThreadId, resolved: true }, + { kind: 'edit-comment', headSha: HEAD, comment, body: '' }, + { kind: 'edit-comment', headSha: HEAD, comment: '' as ForgeCommentId, body: 'Text' }, + { kind: 'delete-comment', headSha: HEAD, comment: '' as ForgeCommentId }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, path: '' } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, body: '\n' } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, startLine: 0 } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, startLine: 1.5 } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, endLine: 1 } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, endLine: Number.POSITIVE_INFINITY } }, + { kind: 'submit-pending', headSha: HEAD, review: '' as ForgeReviewId, event: 'comment', body: '' }, + { kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'request-changes', body: ' ' }, + { kind: 'discard-pending', headSha: HEAD, review: '' as ForgeReviewId }, + ] + for (const value of invalid) await expect(write(pullUrl(7), value)).rejects.toThrow('Invalid review write') + const valid: ForgeReviewWrite[] = [ + { kind: 'reply', headSha: HEAD, thread, body: 'Done', pending: true }, + { kind: 'edit-comment', headSha: HEAD, comment, body: 'Text' }, + { kind: 'delete-comment', headSha: HEAD, comment }, + { kind: 'add-pending', headSha: HEAD, comment: line }, + { kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'approve', body: '' }, + { kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'request-changes', body: 'Fix it' }, + { kind: 'discard-pending', headSha: HEAD, review: reviewId }, + ] + for (const value of valid) await expect(write(pullUrl(7), value)).resolves.toMatchObject({ ok: false, code: 'unsupported' }) + }) + + it('drops the kept threads after publishing a comment so the next read shows it', async () => { + const { opened: panel, follower } = await opened() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + Object.assign(panel.provider, { readReview, submitReview: async () => ({ ok: true as const, url: `${pullUrl(7)}#discussion_r1` }) }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + await panel.ctx.forgePanel.submitReview(panel.session, pullUrl(7), + { kind: 'comment', headSha: HEAD, comment: { path: 'src/a.ts', side: 'R', startLine: 1, endLine: 1, body: 'Nit' } }, signal) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + expect(readReview).toHaveBeenCalledTimes(2) + }) + it.each([ [{ reviewRefreshMs: 0 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'], [{ reviewRefreshMs: 2_147_483_648 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'], diff --git a/packages/experimental/forge-github/package.json b/packages/experimental/forge-github/package.json index d0270615b4..9d9fcc6391 100644 --- a/packages/experimental/forge-github/package.json +++ b/packages/experimental/forge-github/package.json @@ -34,6 +34,7 @@ "dependencies": { "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/dsh-timeout": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", "execa": "^10.0.1", "zod": "4.6.6" }, diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index cf6905149e..806ef46d7b 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -3,7 +3,8 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, - ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, MergeRequest, + ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, + MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' import { listCommits } from './commits.ts' import type { GraphqlReader } from './commits.ts' @@ -17,6 +18,7 @@ import { import type { PageResult, SnapshotPages } from './graphql.ts' import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' import { submitGitHubReview } from './review.ts' +import { writeGitHubReview } from './review-writes.ts' import { readReviewThreads } from './threads.ts' const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i @@ -65,6 +67,17 @@ export class GitHubProvider implements ForgeProvider { return await readReviewThreads(this.graphql, ref, headSha, this.limits, signal) } + /** + * Write to the review threads or the pending review of a pull request through GraphQL mutations after a check of its head. + * @see writeGitHubReview + */ + async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise { + const failure = this.hostFailure(ref.repository.host) + if (failure !== undefined) return { ok: false, code: 'failed', message: failure.message } + if (!isCommit(write.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(write.headSha)}`) + return await writeGitHubReview(this.graphql, this.gh, ref, write, signal) + } + /** * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. diff --git a/packages/experimental/forge-github/src/review-writes.ts b/packages/experimental/forge-github/src/review-writes.ts new file mode 100644 index 0000000000..d2c6835512 --- /dev/null +++ b/packages/experimental/forge-github/src/review-writes.ts @@ -0,0 +1,209 @@ +/** GitHub writes to review threads and the pending review through GraphQL mutations, each after a check of the head. */ + +import type { + ChangeRequestRef, ForgeLineComment, ForgeReviewId, ForgeReviewWrite, ForgeReviewWriteResult, +} from '@deepseek-ai/dsh-experimental-forge' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { z } from 'zod' +import type { GraphqlReader } from './commits.ts' +import { GhUnavailableError, type GhOutput, type GhRunner } from './gh.ts' +import { checkedRepository } from './urls.ts' + +/** The pull request, its head, and the signed-in user's pending review; variables `owner` and `name` are strings, `number` an integer. */ +export const WRITE_CHECK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { id headRefOid reviews(states: PENDING, first: 1) { nodes { id viewerDidAuthor } } } + } +}` + +/** Start a pending review at a commit, with the line threads of `threads`. */ +export const ADD_REVIEW_MUTATION = `mutation($pull: ID!, $commit: GitObjectID!, $threads: [DraftPullRequestReviewThread]) { + addPullRequestReview(input: { pullRequestId: $pull, commitOID: $commit, threads: $threads }) { pullRequestReview { id } } +}` + +/** Add one line thread to a pending review. */ +export const ADD_THREAD_MUTATION = `mutation($review: ID!, $path: String!, $body: String!, $line: Int!, $side: DiffSide!, $startLine: Int, $startSide: DiffSide) { + addPullRequestReviewThread(input: { + pullRequestReviewId: $review, path: $path, body: $body, line: $line, side: $side, startLine: $startLine, startSide: $startSide + }) { thread { id } } +}` + +/** Reply to a thread, inside the pending review `review` when it is set. */ +export const REPLY_MUTATION = `mutation($thread: ID!, $body: String!, $review: ID) { + addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $thread, body: $body, pullRequestReviewId: $review }) { comment { id } } +}` + +/** Mark a thread resolved. */ +export const RESOLVE_MUTATION = 'mutation($thread: ID!) { resolveReviewThread(input: { threadId: $thread }) { thread { id } } }' + +/** Mark a thread unresolved. */ +export const UNRESOLVE_MUTATION = 'mutation($thread: ID!) { unresolveReviewThread(input: { threadId: $thread }) { thread { id } } }' + +/** Replace the text of a review comment. */ +export const EDIT_COMMENT_MUTATION = `mutation($comment: ID!, $body: String!) { + updatePullRequestReviewComment(input: { pullRequestReviewCommentId: $comment, body: $body }) { pullRequestReviewComment { id } } +}` + +/** Delete a review comment. */ +export const DELETE_COMMENT_MUTATION = 'mutation($comment: ID!) { deletePullRequestReviewComment(input: { id: $comment }) { clientMutationId } }' + +/** Submit a pending review with a decision and summary. */ +export const SUBMIT_REVIEW_MUTATION = `mutation($review: ID!, $event: PullRequestReviewEvent!, $body: String) { + submitPullRequestReview(input: { pullRequestReviewId: $review, event: $event, body: $body }) { pullRequestReview { id } } +}` + +/** Delete a pending review with its comments. */ +export const DELETE_REVIEW_MUTATION = 'mutation($review: ID!) { deletePullRequestReview(input: { pullRequestReviewId: $review }) { pullRequestReview { id } } }' + +const EVENTS = { comment: 'COMMENT', approve: 'APPROVE', 'request-changes': 'REQUEST_CHANGES' } as const + +/** HTTP statuses that mean GitHub refused the request, so it changed nothing. */ +const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/ + +const checkSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ + id: z.string(), + headRefOid: z.string(), + reviews: z.object({ nodes: z.array(z.object({ id: z.string(), viewerDidAuthor: z.boolean() })) }), +}) }) }) }) + +const graphqlErrors = z.object({ errors: z.array(z.object({ message: z.string() })).min(1) }) + +/** One mutation and the payload field that holds its result. */ +interface Mutation { + readonly query: string + readonly field: string + readonly variables: Readonly> +} + +/** A mutation's result: the payload on success, else the write's outcome. */ +type Sent = { readonly ok: true; readonly payload: unknown } | Extract + +const stringId = z.object({ id: z.string() }) + +/** + * Write to the review threads or the pending review of a pull request. One read first checks that the head is still + * `write.headSha` and finds the signed-in user's pending review; a moved head returns `stale` without writing. A pending + * reply or comment without a pending review starts one at `write.headSha`, so it takes two mutations. A reply at once is + * refused with `failed` while the user has a pending review, since GitHub would add it to that review. Mutations send + * their variables as JSON on stdin, and none is retried: a refusal GitHub reports returns `failed`, and an answer that + * does not show whether GitHub applied a mutation returns `unknown`. + * @param read - runs the check as one GraphQL request. + * @param gh - bounded, cancellable GitHub CLI runner for the mutations. + * @param ref - pull request, with an owner and name already checked for inlining. + * @param write - the write and the head commit the user saw. + * @param signal - cancellation of the check and the mutations. + * @returns whether GitHub took the write. + * @throws with `signal.reason` when the signal aborts before a mutation is sent. + */ +export async function writeGitHubReview( + read: GraphqlReader, gh: GhRunner, ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const checked = await read(['api', 'graphql', '--hostname', host, + '-f', `query=${WRITE_CHECK_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, '-F', `number=${ref.number}`], signal) + if (!checked.ok) return { ok: false, code: 'failed', message: checked.failure.message } + const parsed = checkSchema.safeParse(checked.body) + if (!parsed.success) return { ok: false, code: 'failed', message: 'unexpected GitHub response to the pull request check' } + const pull = parsed.data.data.repository.pullRequest + if (pull.headRefOid.toLowerCase() !== write.headSha.toLowerCase()) { + return { ok: false, code: 'stale', message: `the pull request head moved from ${write.headSha} to ${pull.headRefOid}` } + } + const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor)?.id ?? null + signal.throwIfAborted() + const send = async (mutation: Mutation): Promise => await sendMutation(gh, host, mutation, signal) + const done = (sent: Sent): ForgeReviewWriteResult => sent.ok ? { ok: true } : sent + /** Find the pending review, starting one at the head without threads when the user has none. */ + const pendingReview = async (): Promise<{ readonly ok: true; readonly id: string } | Extract> => { + if (pending !== null) return { ok: true, id: pending } + const started = await send({ query: ADD_REVIEW_MUTATION, field: 'addPullRequestReview', + variables: { pull: pull.id, commit: write.headSha, threads: null } }) + if (!started.ok) return started + const review = z.object({ pullRequestReview: stringId }).safeParse(started.payload) + return review.success ? { ok: true, id: review.data.pullRequestReview.id } + : { ok: false, code: 'unknown', message: 'unexpected GitHub response to starting a pending review' } + } + switch (write.kind) { + case 'reply': { + // GitHub adds every reply of a user with a pending review to that review, even one sent without its id. + if (!write.pending && pending !== null) { + return { ok: false, code: 'failed', message: 'GitHub adds a reply to the pending review while one exists; submit or discard it first' } + } + const review = write.pending ? await pendingReview() : { ok: true as const, id: null } + if (!review.ok) return review + return done(await send({ query: REPLY_MUTATION, field: 'addPullRequestReviewThreadReply', + variables: { thread: write.thread, body: write.body, review: review.id } })) + } + case 'resolve': + return done(await send(write.resolved + ? { query: RESOLVE_MUTATION, field: 'resolveReviewThread', variables: { thread: write.thread } } + : { query: UNRESOLVE_MUTATION, field: 'unresolveReviewThread', variables: { thread: write.thread } })) + case 'edit-comment': + return done(await send({ query: EDIT_COMMENT_MUTATION, field: 'updatePullRequestReviewComment', + variables: { comment: write.comment, body: write.body } })) + case 'delete-comment': + return done(await send({ query: DELETE_COMMENT_MUTATION, field: 'deletePullRequestReviewComment', variables: { comment: write.comment } })) + case 'add-pending': + return done(await send(pending === null + ? { query: ADD_REVIEW_MUTATION, field: 'addPullRequestReview', + variables: { pull: pull.id, commit: write.headSha, threads: [draftThread(write.comment)] } } + : { query: ADD_THREAD_MUTATION, field: 'addPullRequestReviewThread', variables: { review: pending, ...draftThread(write.comment) } })) + case 'submit-pending': + if (pending !== write.review) return missingReview(write.review) + return done(await send({ query: SUBMIT_REVIEW_MUTATION, field: 'submitPullRequestReview', + variables: { review: write.review, event: EVENTS[write.event], body: write.body } })) + case 'discard-pending': + if (pending !== write.review) return missingReview(write.review) + return done(await send({ query: DELETE_REVIEW_MUTATION, field: 'deletePullRequestReview', variables: { review: write.review } })) + /* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */ + default: return assertNever(write, 'ForgeReviewWrite.kind') + } +} + +/** The fields of a line thread in a pending review, for one side of the diff. */ +function draftThread(comment: ForgeLineComment): Readonly> { + const side = comment.side === 'L' ? 'LEFT' : 'RIGHT' + return { path: comment.path, body: comment.body, line: comment.endLine, side, + ...comment.startLine === comment.endLine ? { startLine: null, startSide: null } : { startLine: comment.startLine, startSide: side } } +} + +function missingReview(review: ForgeReviewId): ForgeReviewWriteResult { + return { ok: false, code: 'failed', message: `the pending review ${review} is no longer the signed-in user's pending review` } +} + +/** + * Send one mutation with its query and variables as JSON on stdin. + * @returns the payload of `mutation.field`; `failed` when GitHub reports a refusal or `gh` cannot start, else `unknown`. + */ +async function sendMutation(gh: GhRunner, host: string, mutation: Mutation, signal: AbortSignal): Promise { + let output: GhOutput + try { + output = await gh(['api', 'graphql', '--hostname', host, '--input', '-'], signal, + JSON.stringify({ query: mutation.query, variables: mutation.variables })) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return { ok: false, code: error instanceof GhUnavailableError ? 'failed' : 'unknown', message } + } + const body = parse(output.stdout) + // A payload means GitHub applied the mutation, even beside errors about the fields it selects. + const payload = z.object({ data: z.record(z.string(), z.unknown()) }).safeParse(body) + const value = payload.success ? payload.data.data[mutation.field] : undefined + if (value !== undefined && value !== null) return { ok: true, payload: value } + const errors = graphqlErrors.safeParse(body) + if (errors.success) return { ok: false, code: 'failed', message: errors.data.errors.map(error => error.message).join('; ') } + if (output.exitCode !== 0) { + const message = output.stderr.trim() || output.stdout.trim() || `gh exited with ${output.exitCode}` + return { ok: false, code: REFUSED.test(output.stderr) ? 'failed' : 'unknown', message } + } + return { ok: false, code: 'unknown', message: `unexpected GitHub response to ${mutation.field}` } +} + +function parse(text: string): unknown { + let value: unknown + try { + value = JSON.parse(text) + } catch (error) { + void error // gh prints diagnostics instead of JSON when a request fails before GitHub answers. + return undefined + } + return value +} diff --git a/packages/experimental/forge-github/src/threads.ts b/packages/experimental/forge-github/src/threads.ts index 5717f47a0c..6b1e6096b3 100644 --- a/packages/experimental/forge-github/src/threads.ts +++ b/packages/experimental/forge-github/src/threads.ts @@ -2,7 +2,8 @@ import { Buffer } from 'node:buffer' import type { - ChangeRequestRef, ForgeAnchor, ForgeCommentId, ForgeFailure, ForgeReviewComment, ForgeReviewData, ForgeReviewThread, ForgeThreadId, + ChangeRequestRef, ForgeAnchor, ForgeCommentId, ForgeFailure, ForgeReviewComment, ForgeReviewData, ForgeReviewId, ForgeReviewThread, + ForgeThreadId, } from '@deepseek-ai/dsh-experimental-forge' import { z } from 'zod' import type { GraphqlReader } from './commits.ts' @@ -11,7 +12,10 @@ import { checkedRepository, isCommit } from './urls.ts' /** Most nodes GitHub returns in one connection page. */ const PAGE_SIZE = 100 -const COMMENT_FIELDS = 'id state createdAt url body author { __typename login avatarUrl(size: 48) }' +/** Repository permissions that may comment on a locked conversation. */ +const WRITERS: ReadonlySet = new Set(['ADMIN', 'MAINTAIN', 'WRITE']) + +const COMMENT_FIELDS = 'id state createdAt url body viewerCanUpdate viewerCanDelete author { __typename login avatarUrl(size: 48) }' const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { ${COMMENT_FIELDS} } }` @@ -20,15 +24,26 @@ const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { * first page of comments starts without a cursor. */ const THREAD_FIELDS = `id isOutdated isResolved path diffSide startDiffSide line startLine originalLine originalStartLine subjectType + viewerCanReply viewerCanResolve viewerCanUnresolve root: comments(first: 1) { nodes { diffHunk commit { oid } originalCommit { oid } } } ${COMMENT_PAGE.replace(', after: $cursor', '')}` const THREAD_PAGE = `pageInfo { hasNextPage endCursor } nodes { ${THREAD_FIELDS} }` -/** First thread page with the head and the viewer; variables `owner` and `name` are strings, `number` and `first` integers. */ +/** + * First thread page with the head, the viewer, whether the viewer may comment, and the viewer's pending review; variables + * `owner` and `name` are strings, `number` and `first` integers. + */ export const REVIEW_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!) { viewer { login } - repository(owner: $owner, name: $name) { pullRequest(number: $number) { id headRefOid reviewThreads(first: $first) { ${THREAD_PAGE} } } } + repository(owner: $owner, name: $name) { + isArchived viewerPermission + pullRequest(number: $number) { + id headRefOid locked + reviews(states: PENDING, first: 1) { nodes { id viewerDidAuthor commit { oid } comments { totalCount } } } + reviewThreads(first: $first) { ${THREAD_PAGE} } + } + } }` /** Following thread page with the head it was read at; variables `id` and `cursor` are strings, `first` an integer. */ @@ -62,6 +77,8 @@ const commentSchema = z.object({ createdAt: z.string(), url: z.string().nullable(), body: z.string(), + viewerCanUpdate: z.boolean(), + viewerCanDelete: z.boolean(), author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }).nullable(), }) @@ -79,15 +96,35 @@ const threadSchema = z.object({ originalLine: z.number().int().nullable(), originalStartLine: z.number().int().nullable(), subjectType: z.string(), + viewerCanReply: z.boolean(), + viewerCanResolve: z.boolean(), + viewerCanUnresolve: z.boolean(), root: z.object({ nodes: z.array(z.object({ diffHunk: z.string(), commit: commitSchema, originalCommit: commitSchema })) }), comments: commentPageSchema, }) const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(threadSchema) }) +const pendingSchema = z.object({ + id: z.string(), + viewerDidAuthor: z.boolean(), + commit: commitSchema, + comments: z.object({ totalCount: z.number().int().nonnegative() }), +}) + const firstPageSchema = z.object({ data: z.object({ viewer: z.object({ login: z.string() }).nullable(), - repository: z.object({ pullRequest: z.object({ id: z.string(), headRefOid: z.string(), reviewThreads: threadPageSchema }) }), + repository: z.object({ + isArchived: z.boolean(), + viewerPermission: z.string().nullable(), + pullRequest: z.object({ + id: z.string(), + headRefOid: z.string(), + locked: z.boolean(), + reviews: z.object({ nodes: z.array(pendingSchema) }), + reviewThreads: threadPageSchema, + }), + }), }) }) const nextPageSchema = z.object({ data: z.object({ node: z.object({ headRefOid: z.string(), reviewThreads: threadPageSchema }) }) }) @@ -127,14 +164,20 @@ export async function readReviewThreads( if ('code' in first) return first const parsed = firstPageSchema.safeParse(first.body) if (!parsed.success) return unexpected - const pull = parsed.data.data.repository.pullRequest + const repository = parsed.data.data.repository + const pull = repository.pullRequest const moved = stale(pull.headRefOid) if (moved !== undefined) return moved let bytes = first.bytes let page = pull.reviewThreads const threads: ForgeReviewThread[] = [] const viewer = parsed.data.data.viewer?.login ?? null - const result = (truncated: boolean): ForgeReviewData => ({ headSha, viewer, threads, truncated }) + const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor) + const pendingReview = pending?.commit == null ? null + : { id: pending.id as ForgeReviewId, commit: pending.commit.oid, comments: pending.comments.totalCount } + // GitHub refuses every write to an archived repository, and comments on a locked conversation from anyone without write access. + const viewerCanReview = !repository.isArchived && (!pull.locked || WRITERS.has(repository.viewerPermission ?? '')) + const result = (truncated: boolean): ForgeReviewData => ({ headSha, viewer, threads, truncated, pendingReview, viewerCanReview }) const cursors = new Set() for (;;) { for (const node of page.nodes.slice(0, limits.maxReviewThreads - threads.length)) { @@ -193,6 +236,8 @@ function toThread(node: ThreadNode, comments: readonly CommentNode[], head: stri ? anchor(root.originalCommit.oid, sameSide ? node.originalStartLine : null, node.originalLine) : null, diffHunk: root === undefined || root.diffHunk === '' ? null : root.diffHunk, resolved: node.isResolved, + viewerCanReply: node.viewerCanReply, + viewerCanResolve: node.isResolved ? node.viewerCanUnresolve : node.viewerCanResolve, comments: comments.map(toComment), } } @@ -209,5 +254,7 @@ function toComment(node: CommentNode): ForgeReviewComment { createdAt: node.createdAt, pending: node.state === 'PENDING', url: node.url, + viewerCanEdit: node.viewerCanUpdate, + viewerCanDelete: node.viewerCanDelete, } } diff --git a/packages/experimental/forge-github/tests/review-writes.spec.ts b/packages/experimental/forge-github/tests/review-writes.spec.ts new file mode 100644 index 0000000000..d620401e36 --- /dev/null +++ b/packages/experimental/forge-github/tests/review-writes.spec.ts @@ -0,0 +1,253 @@ +/** GitHub review thread and pending review writes check the head first, send JSON on stdin, and never retry. */ +import { describe, expect, it } from 'vitest' +import type { ForgeCommentId, ForgeReviewId, ForgeReviewWrite, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge' +import { GhTimeoutError, GhUnavailableError, type GhOutput, type GhRunner } from '../src/gh.ts' +import { GitHubProvider } from '../src/provider.ts' +import { + ADD_REVIEW_MUTATION, ADD_THREAD_MUTATION, DELETE_COMMENT_MUTATION, DELETE_REVIEW_MUTATION, EDIT_COMMENT_MUTATION, REPLY_MUTATION, + RESOLVE_MUTATION, SUBMIT_REVIEW_MUTATION, UNRESOLVE_MUTATION, WRITE_CHECK_QUERY, +} from '../src/review-writes.ts' +import { demo, pull } from './fixtures.ts' + +const head = 'c'.repeat(40) +const pushed = 'd'.repeat(40) +const signal = new AbortController().signal +const thread = 'thread-1' as ForgeThreadId +const comment = 'comment-1' as ForgeCommentId +const review = 'review-1' as ForgeReviewId + +function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { + return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr } +} + +function checked(pending: string | null = null, headRefOid = head, viewerDidAuthor = true): GhOutput { + return output({ data: { repository: { pullRequest: { + id: 'pull-7', headRefOid, reviews: { nodes: pending === null ? [] : [{ id: pending, viewerDidAuthor }] }, + } } } }) +} + +/** One recorded `gh` call: its arguments and, for a mutation, the JSON it sent on stdin. */ +interface Call { + readonly args: readonly string[] + readonly input: { readonly query: string; readonly variables: Record } | undefined +} + +/** A mutation answer that throws `throws` instead of printing output. */ +interface Thrown { readonly throws: unknown } + +/** Answer the check with `check`, then each mutation in turn from `mutations`. */ +function fakeGh(check: GhOutput, ...mutations: Array): { run: GhRunner; calls: Call[] } { + const calls: Call[] = [] + const queue = [...mutations] + return { calls, run: async (args, _signal, input) => { + calls.push({ args: [...args], input: input === undefined ? undefined : JSON.parse(input) as Call['input'] }) + if (input === undefined) return check + const next = queue.shift() + if (next === undefined) throw new Error(`unexpected gh ${args.join(' ')}`) + if ('throws' in next) throw next.throws + return next + } } +} + +function provider(run: GhRunner): GitHubProvider { + return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 }) +} + +function payload(field: string, value: unknown = { id: 'x' }): GhOutput { + return output({ data: { [field]: value } }) +} + +const MUTATION_ARGS = ['api', 'graphql', '--hostname', 'github.com', '--input', '-'] + +describe('GitHub review writes', () => { + it('checks the head with the pull request as variables and replies at once without a pending review', async () => { + const gh = fakeGh(checked(), payload('addPullRequestReviewThreadReply', { comment: { id: 'reply-1' } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Fixed in `$(x)`', pending: false }, signal)) + .resolves.toEqual({ ok: true }) + expect(gh.calls).toEqual([ + { args: ['api', 'graphql', '--hostname', 'github.com', '-f', `query=${WRITE_CHECK_QUERY}`, '-f', `owner=${demo.owner}`, + '-f', `name=${demo.name}`, '-F', 'number=7'], input: undefined }, + { args: MUTATION_ARGS, input: { query: REPLY_MUTATION, variables: { thread, body: 'Fixed in `$(x)`', review: null } } }, + ]) + }) + + it('refuses a reply at once without a mutation while the viewer has a pending review, which GitHub would add it to', async () => { + const gh = fakeGh(checked('review-9')) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Now', pending: false }, signal)) + .resolves.toEqual({ ok: false, code: 'failed', + message: 'GitHub adds a reply to the pending review while one exists; submit or discard it first' }) + expect(gh.calls).toHaveLength(1) + }) + + it('replies inside the existing pending review', async () => { + const gh = fakeGh(checked('review-9'), payload('addPullRequestReviewThreadReply')) + + await provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Later', pending: true }, signal) + + expect(gh.calls[1]?.input).toEqual({ query: REPLY_MUTATION, variables: { thread, body: 'Later', review: 'review-9' } }) + }) + + it('starts a pending review at the head before a pending reply when the viewer has none', async () => { + const gh = fakeGh(checked('review-of-other', head, false), + payload('addPullRequestReview', { pullRequestReview: { id: 'review-new' } }), payload('addPullRequestReviewThreadReply')) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Later', pending: true }, signal)) + .resolves.toEqual({ ok: true }) + expect(gh.calls.slice(1).map(call => call.input)).toEqual([ + { query: ADD_REVIEW_MUTATION, variables: { pull: 'pull-7', commit: head, threads: null } }, + { query: REPLY_MUTATION, variables: { thread, body: 'Later', review: 'review-new' } }, + ]) + }) + + it('returns the failure of starting a pending review and an unexpected start without replying', async () => { + const write: ForgeReviewWrite = { kind: 'reply', headSha: head, thread, body: 'Later', pending: true } + const refused = fakeGh(checked(), output({ data: { addPullRequestReview: null }, errors: [{ message: 'Pull request is locked' }] }, 1)) + await expect(provider(refused.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'Pull request is locked' }) + expect(refused.calls).toHaveLength(2) + + const odd = fakeGh(checked(), payload('addPullRequestReview', { pullRequestReview: null })) + await expect(provider(odd.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'unknown', message: 'unexpected GitHub response to starting a pending review' }) + expect(odd.calls).toHaveLength(2) + }) + + it.each([ + [true, RESOLVE_MUTATION, 'resolveReviewThread'], + [false, UNRESOLVE_MUTATION, 'unresolveReviewThread'], + ] as const)('marks a thread resolved %s through its mutation', async (resolved, query, field) => { + const gh = fakeGh(checked(), payload(field, { thread: { id: thread } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved }, signal)).resolves.toEqual({ ok: true }) + expect(gh.calls[1]?.input).toEqual({ query, variables: { thread } }) + }) + + it('edits and deletes a comment', async () => { + const edit = fakeGh(checked(), payload('updatePullRequestReviewComment')) + await provider(edit.run).writeReview(pull(7), { kind: 'edit-comment', headSha: head, comment, body: 'Reworded' }, signal) + expect(edit.calls[1]?.input).toEqual({ query: EDIT_COMMENT_MUTATION, variables: { comment, body: 'Reworded' } }) + + const remove = fakeGh(checked(), payload('deletePullRequestReviewComment', { clientMutationId: null })) + await expect(provider(remove.run).writeReview(pull(7), { kind: 'delete-comment', headSha: head, comment }, signal)).resolves.toEqual({ ok: true }) + expect(remove.calls[1]?.input).toEqual({ query: DELETE_COMMENT_MUTATION, variables: { comment } }) + }) + + it('starts a pending review at the head holding a new comment when the viewer has none', async () => { + const gh = fakeGh(checked(), payload('addPullRequestReview', { pullRequestReview: { id: 'review-new' } })) + + await provider(gh.run).writeReview(pull(7), { kind: 'add-pending', headSha: head, + comment: { path: 'src/a.ts', side: 'L', startLine: 3, endLine: 5, body: 'Range' } }, signal) + + expect(gh.calls[1]?.input).toEqual({ query: ADD_REVIEW_MUTATION, variables: { pull: 'pull-7', commit: head, threads: [ + { path: 'src/a.ts', body: 'Range', line: 5, side: 'LEFT', startLine: 3, startSide: 'LEFT' }, + ] } }) + }) + + it('adds a new single-line comment to the existing pending review', async () => { + const gh = fakeGh(checked('review-9'), payload('addPullRequestReviewThread', { thread: { id: 'thread-new' } })) + + await provider(gh.run).writeReview(pull(7), { kind: 'add-pending', headSha: head, + comment: { path: 'src/a.ts', side: 'R', startLine: 8, endLine: 8, body: 'Line' } }, signal) + + expect(gh.calls[1]?.input).toEqual({ query: ADD_THREAD_MUTATION, variables: { + review: 'review-9', path: 'src/a.ts', body: 'Line', line: 8, side: 'RIGHT', startLine: null, startSide: null, + } }) + }) + + it.each([ + ['comment', 'COMMENT'], ['approve', 'APPROVE'], ['request-changes', 'REQUEST_CHANGES'], + ] as const)('submits the pending review as a %s review', async (event, graphqlEvent) => { + const gh = fakeGh(checked(review), payload('submitPullRequestReview', { pullRequestReview: { id: review } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'submit-pending', headSha: head, review, event, body: 'Summary' }, signal)) + .resolves.toEqual({ ok: true }) + expect(gh.calls[1]?.input).toEqual({ query: SUBMIT_REVIEW_MUTATION, variables: { review, event: graphqlEvent, body: 'Summary' } }) + }) + + it('discards the pending review', async () => { + const gh = fakeGh(checked(review), payload('deletePullRequestReview', { pullRequestReview: { id: review } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'discard-pending', headSha: head, review }, signal)).resolves.toEqual({ ok: true }) + expect(gh.calls[1]?.input).toEqual({ query: DELETE_REVIEW_MUTATION, variables: { review } }) + }) + + it.each([ + ['submit', { kind: 'submit-pending', headSha: head, review, event: 'comment', body: '' }], + ['discard', { kind: 'discard-pending', headSha: head, review }], + ] as const)('refuses to %s a pending review that is no longer the viewer\'s without a mutation', async (_label, write) => { + for (const pending of [null, 'review-other']) { + const gh = fakeGh(checked(pending)) + await expect(provider(gh.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'the pending review review-1 is no longer the signed-in user\'s pending review' }) + expect(gh.calls).toHaveLength(1) + } + }) + + it('refuses a moved head without a mutation and accepts a head in another case', async () => { + const write: ForgeReviewWrite = { kind: 'resolve', headSha: head, thread, resolved: true } + const moved = fakeGh(checked(null, pushed)) + await expect(provider(moved.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'stale', message: `the pull request head moved from ${head} to ${pushed}` }) + expect(moved.calls).toHaveLength(1) + + const upper = fakeGh(checked(null, head.toUpperCase()), payload('resolveReviewThread')) + await expect(provider(upper.run).writeReview(pull(7), write, signal)).resolves.toEqual({ ok: true }) + }) + + it('reports a failed or unexpected check as failed without a mutation', async () => { + const write: ForgeReviewWrite = { kind: 'resolve', headSha: head, thread, resolved: true } + const down = fakeGh(output('', 1, 'gh: Server Error (HTTP 502)')) + await expect(provider(down.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'gh: Server Error (HTTP 502)' }) + + const odd = fakeGh(output({ data: { repository: { pullRequest: null } } })) + await expect(provider(odd.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'unexpected GitHub response to the pull request check' }) + expect([down.calls, odd.calls].map(calls => calls.length)).toEqual([1, 1]) + }) + + it.each([ + ['a gh that cannot start', { throws: new GhUnavailableError('gh could not start: ENOENT') }, 'failed', 'gh could not start: ENOENT'], + ['a gh that times out', { throws: new GhTimeoutError('gh api timed out after 30000ms') }, 'unknown', 'gh api timed out after 30000ms'], + ['a thrown value that is not an error', { throws: 'lost' }, 'unknown', 'lost'], + ['GraphQL errors', output({ data: { resolveReviewThread: null }, errors: [{ message: 'one' }, { message: 'two' }] }, 1), 'failed', 'one; two'], + ['an HTTP refusal', output('', 1, 'gh: Validation Failed (HTTP 422)'), 'failed', 'gh: Validation Failed (HTTP 422)'], + ['a server error', output('', 1, 'gh: Server Error (HTTP 502)'), 'unknown', 'gh: Server Error (HTTP 502)'], + ['a failure printed on stdout', output('connection reset', 1), 'unknown', 'connection reset'], + ['a failure without output', output('', 1), 'unknown', 'gh exited with 1'], + ['an answer that is not JSON', output(''), 'unknown', 'unexpected GitHub response to resolveReviewThread'], + ['an empty payload', payload('resolveReviewThread', null), 'unknown', 'unexpected GitHub response to resolveReviewThread'], + ] as const)('reports a mutation ending in %s as %s', async (_label, answer, code, message) => { + const gh = fakeGh(checked(), answer) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved: true }, signal)) + .resolves.toEqual({ ok: false, code, message }) + }) + + it('treats a payload beside errors about its fields as applied', async () => { + const gh = fakeGh(checked(), output({ data: { resolveReviewThread: { thread: null } }, errors: [{ message: 'thread is not visible' }] })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved: true }, signal)) + .resolves.toEqual({ ok: true }) + }) + + it('throws the abort reason when the signal aborts before a mutation is sent', async () => { + const controller = new AbortController() + const reason = new Error('closed') + const run: GhRunner = async () => { controller.abort(reason); return checked() } + + await expect(provider(run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved: true }, controller.signal)).rejects.toBe(reason) + }) + + it('refuses an unconfigured host without starting gh and a head that is not a commit object name', async () => { + const gh = fakeGh(checked()) + const write: ForgeReviewWrite = { kind: 'resolve', headSha: head, thread, resolved: true } + + await expect(provider(gh.run).writeReview(pull(7, { ...demo, host: 'ghe.other.example' }), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'forge-github: host "ghe.other.example" is not configured' }) + await expect(provider(gh.run).writeReview(pull(7), { ...write, headSha: 'main' }, signal)).rejects.toThrow('forge-github: invalid head commit "main"') + expect(gh.calls).toEqual([]) + }) +}) diff --git a/packages/experimental/forge-github/tests/threads.spec.ts b/packages/experimental/forge-github/tests/threads.spec.ts index 42c49f389a..1e4fc80037 100644 --- a/packages/experimental/forge-github/tests/threads.spec.ts +++ b/packages/experimental/forge-github/tests/threads.spec.ts @@ -32,6 +32,7 @@ function page(nodes: readonly unknown[], next: string | null = null): Record = {}): Record { return { id, state: 'SUBMITTED', createdAt: '2026-11-05T08:00:00Z', url: `https://github.com/octo/demo/pull/7#discussion_${id}`, body: `Body of ${id}`, + viewerCanUpdate: false, viewerCanDelete: false, author: { __typename: 'User', login: 'reviewer', avatarUrl: 'https://avatars.githubusercontent.com/u/1?s=48&v=4' }, ...overrides, } @@ -42,14 +43,20 @@ function threadNode(id: string, overrides: Record = {}, root: R return { id, isOutdated: false, isResolved: false, path: 'src/a.ts', diffSide: 'RIGHT', startDiffSide: null, line: 12, startLine: null, originalLine: 12, originalStartLine: null, subjectType: 'LINE', + viewerCanReply: true, viewerCanResolve: true, viewerCanUnresolve: false, root: { nodes: [{ diffHunk: '@@ -10,2 +10,3 @@\n a\n+b\n c', commit: { oid: head }, originalCommit: { oid: head }, ...root }] }, comments: page([commentNode(`${id}-1`)]), ...overrides, } } -function firstPage(threads: Record, headRefOid = head, viewer: unknown = { login: 'octo' }): Record { - return { data: { viewer, repository: { pullRequest: { id: 'pull-7', headRefOid, reviewThreads: threads } } } } +function firstPage( + threads: Record, headRefOid = head, viewer: unknown = { login: 'octo' }, pull: Record = {}, + repository: Record = {}, +): Record { + return { data: { viewer, repository: { isArchived: false, viewerPermission: 'READ', ...repository, pullRequest: { + id: 'pull-7', headRefOid, locked: false, reviews: { nodes: [] }, reviewThreads: threads, ...pull, + } } } } } function nextPage(threads: Record, headRefOid = head): Record { @@ -84,16 +91,21 @@ describe('GitHub provider review threads', () => { headSha: head, viewer: 'octo', truncated: false, + pendingReview: null, + viewerCanReview: true, threads: [{ id: 't1', path: 'src/a.ts', side: 'R', subject: 'line', current: { commit: head, startLine: 12, endLine: 12 }, original: { commit: head, startLine: 12, endLine: 12 }, diffHunk: '@@ -10,2 +10,3 @@\n a\n+b\n c', resolved: true, + viewerCanReply: true, + viewerCanResolve: false, comments: [{ id: 't1-1', body: 'Body of t1-1', createdAt: '2026-11-05T08:00:00Z', pending: false, url: 'https://github.com/octo/demo/pull/7#discussion_t1-1', author: { login: 'reviewer', avatarUrl: 'https://avatars.githubusercontent.com/u/1?s=48&v=4', bot: false }, + viewerCanEdit: false, viewerCanDelete: false, }], }], }) @@ -161,6 +173,51 @@ describe('GitHub provider review threads', () => { expect(result).toMatchObject({ threads: { length: 1 } }) }) + it('maps the permissions of the viewer on threads and comments, resolving an unresolved thread and unresolving a resolved one', async () => { + const gh = review(firstPage(page([ + threadNode('open', { viewerCanReply: false, viewerCanResolve: true, viewerCanUnresolve: false, comments: page([ + commentNode('mine', { viewerCanUpdate: true, viewerCanDelete: true }), + ]) }), + threadNode('settled', { isResolved: true, viewerCanResolve: false, viewerCanUnresolve: true }), + ]))) + + const result = await provider(gh.run).readReview(pull(7), head, signal) + + expect(result).toMatchObject({ threads: [ + { id: 'open', viewerCanReply: false, viewerCanResolve: true, comments: [{ id: 'mine', viewerCanEdit: true, viewerCanDelete: true }] }, + { id: 'settled', viewerCanReply: true, viewerCanResolve: true }, + ] }) + }) + + it('reports the pending review the viewer authored with its commit and comment count', async () => { + const reviews = { nodes: [{ id: 'review-1', viewerDidAuthor: true, commit: { oid: older }, comments: { totalCount: 2 } }] } + const gh = review(firstPage(page([]), head, { login: 'octo' }, { reviews })) + + await expect(provider(gh.run).readReview(pull(7), head, signal)) + .resolves.toMatchObject({ pendingReview: { id: 'review-1', commit: older, comments: 2 } }) + }) + + it.each([ + ['another user authored', { id: 'review-2', viewerDidAuthor: false, commit: { oid: head }, comments: { totalCount: 1 } }], + ['names no commit', { id: 'review-3', viewerDidAuthor: true, commit: null, comments: { totalCount: 1 } }], + ] as const)('reports no pending review for one %s', async (_label, node) => { + const gh = review(firstPage(page([]), head, { login: 'octo' }, { reviews: { nodes: [node] } })) + + await expect(provider(gh.run).readReview(pull(7), head, signal)).resolves.toMatchObject({ pendingReview: null }) + }) + + it.each([ + ['an archived repository', {}, { isArchived: true, viewerPermission: 'ADMIN' }, false], + ['a locked conversation without write access', { locked: true }, { viewerPermission: 'TRIAGE' }, false], + ['a locked conversation without a known permission', { locked: true }, { viewerPermission: null }, false], + ['a locked conversation with write access', { locked: true }, { viewerPermission: 'WRITE' }, true], + ['an open conversation with read access', {}, { viewerPermission: 'READ' }, true], + ] as const)('reports whether the viewer can review in %s', async (_label, pullFields, repository, expected) => { + const gh = review(firstPage(page([]), head, { login: 'octo' }, pullFields, repository)) + + await expect(provider(gh.run).readReview(pull(7), head, signal)).resolves.toMatchObject({ viewerCanReview: expected }) + }) + it('reads the following thread and comment pages, asking only for the threads left under maxReviewThreads', async () => { const gh = review( firstPage(page([threadNode('t1', { comments: page([commentNode('c1')], 'comments-1') })], 'threads-1')), @@ -198,7 +255,7 @@ describe('GitHub provider review threads', () => { const byComments = review(first, threads, comments) await expect(provider(byComments.run, { maxOutputBytes: size + 10 }).readReview(pull(7), head, signal)) - .resolves.toEqual({ headSha: head, viewer: 'octo', threads: [], truncated: true }) + .resolves.toEqual({ headSha: head, viewer: 'octo', threads: [], truncated: true, pendingReview: null, viewerCanReview: true }) const commentBytes = JSON.stringify(comments['comments-1']).length const byThreads = review(first, threads, comments) diff --git a/packages/experimental/forge-github/tsconfig.json b/packages/experimental/forge-github/tsconfig.json index fea1cc6ec1..ff2c3474bc 100644 --- a/packages/experimental/forge-github/tsconfig.json +++ b/packages/experimental/forge-github/tsconfig.json @@ -28,6 +28,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../util/values" } ] } diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index 88068c3aee..1373810e80 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -8,7 +8,7 @@ import { nextPollDelay } from './schedule.ts' import type { ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, - MergeRequest, + ForgeReviewWrite, ForgeReviewWriteResult, MergeRequest, } from './types.ts' export { changeRequestKey } from './keys.ts' @@ -253,7 +253,7 @@ export class ForgeService extends Service { async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { const result = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => provider.diff(ref, headSha, operation)) - if (typeof result !== 'string') this.staleRead(ref, headSha, result) + if (typeof result !== 'string') this.staleRead(ref, headSha, result.code) return result } @@ -270,7 +270,26 @@ export class ForgeService extends Service { const result = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => provider.readReview?.(ref, headSha, operation) ?? Promise.resolve({ code: 'unsupported', message: 'This provider does not support review reads' } as const)) - if ('code' in result) this.staleRead(ref, headSha, result) + if ('code' in result) this.staleRead(ref, headSha, result.code) + return result + } + + /** + * Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then + * poll the change request at once when it is watched. A `stale` result polls it as a stale read does. + * @param ref - change request served by a registered provider. + * @param write - the write and the head commit the user saw. + * @param signal - cancellation of the write. + * @returns whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the + * outcome must be checked on the host before the write is tried again. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise { + const result = await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.writeReview?.(ref, write, operation) + ?? Promise.resolve({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' } as const)) + if (!result.ok && result.code === 'stale') this.staleRead(ref, write.headSha, result.code) + else this.refresh(ref) return result } @@ -398,10 +417,10 @@ export class ForgeService extends Service { return this.watches.get(changeRequestKey(ref))?.latest } - /** Poll a watched change request at once after the first `stale` read at `headSha`; later ones wait for the regular poll. */ - private staleRead(ref: ChangeRequestRef, headSha: string, failure: ForgeFailure): void { + /** Poll a watched change request at once after the first `stale` read or write at `headSha`; later ones wait for the regular poll. */ + private staleRead(ref: ChangeRequestRef, headSha: string, code: ForgeFailure['code']): void { const watch = this.watches.get(changeRequestKey(ref)) - if (failure.code !== 'stale' || watch === undefined || watch.staleHead === headSha) return + if (code !== 'stale' || watch === undefined || watch.staleHead === headSha) return watch.staleHead = headSha this.refresh(ref) } diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 71bd7270e0..6ef6526059 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -160,7 +160,7 @@ export type ForgeReviewRequest = { readonly headSha: string } & ( | { readonly kind: 'comment'; readonly comment: ForgeLineComment } - | { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] } + | { readonly kind: 'review'; readonly event: ForgeReviewEvent; readonly body: string; readonly comments: readonly ForgeLineComment[] } ) /** Opaque host identity of one review thread. */ @@ -169,6 +169,9 @@ export type ForgeThreadId = Branded<'ForgeThreadId'> /** Opaque host identity of one review comment. */ export type ForgeCommentId = Branded<'ForgeCommentId'> +/** Opaque host identity of one review. */ +export type ForgeReviewId = Branded<'ForgeReviewId'> + /** Consecutive lines of one file at one commit. */ export interface ForgeAnchor { /** Full object name of the commit whose file the lines number. */ @@ -203,6 +206,10 @@ export interface ForgeReviewComment { readonly pending: boolean /** Web page of the comment, or null when the host reports none. */ readonly url: string | null + /** Whether the signed-in user can replace the comment's text through `writeReview`; false for a provider without it. */ + readonly viewerCanEdit: boolean + /** Whether the signed-in user can delete the comment through `writeReview`; false for a provider without it. */ + readonly viewerCanDelete: boolean } /** @@ -227,10 +234,27 @@ export interface ForgeReviewThread { readonly diffHunk: string | null /** Whether the thread is marked resolved. */ readonly resolved: boolean + /** Whether the signed-in user can reply to the thread through `writeReview`; false for a provider without it. */ + readonly viewerCanReply: boolean + /** + * Whether the signed-in user can mark the thread resolved, or unresolved when `resolved`, through `writeReview`; false + * for a provider without it. + */ + readonly viewerCanResolve: boolean /** Comments oldest first; the first starts the thread. */ readonly comments: readonly ForgeReviewComment[] } +/** The signed-in user's review of a change request that is not submitted yet, which only that user sees. */ +export interface ForgePendingReview { + /** Host identity of the review. */ + readonly id: ForgeReviewId + /** Full object name of the commit the review addresses. */ + readonly commit: string + /** Comments the review holds. */ + readonly comments: number +} + /** Review threads of a change request read at one head commit. */ export interface ForgeReviewData { /** Head commit the threads were read at; `current` positions number its files. */ @@ -241,8 +265,44 @@ export interface ForgeReviewData { readonly threads: readonly ForgeReviewThread[] /** Whether the change request has more threads than `threads` holds. */ readonly truncated: boolean + /** The signed-in user's pending review, or null without one. */ + readonly pendingReview: ForgePendingReview | null + /** + * Whether the signed-in user can add comments to a pending review and submit or discard it through `writeReview`; + * false for a provider without it. + */ + readonly viewerCanReview: boolean } +/** Decision a submitted review records. */ +export type ForgeReviewEvent = 'comment' | 'approve' | 'request-changes' + +/** + * One write to the review threads and the pending review of a change request. `pending` replies and `add-pending` + * comments join the signed-in user's pending review, which is started when the user has none. A host that adds every + * reply to an existing pending review, as GitHub does, refuses a reply with `pending: false` while one exists. + */ +export type ForgeReviewWrite = { + /** Head commit the user saw; providers check it before writing and refuse with `stale` once the head is another commit. */ + readonly headSha: string +} & ( + | { readonly kind: 'reply'; readonly thread: ForgeThreadId; readonly body: string; readonly pending: boolean } + | { readonly kind: 'resolve'; readonly thread: ForgeThreadId; readonly resolved: boolean } + | { readonly kind: 'edit-comment'; readonly comment: ForgeCommentId; readonly body: string } + /** Deleting the only comment of a thread deletes the thread. */ + | { readonly kind: 'delete-comment'; readonly comment: ForgeCommentId } + /** A comment on lines of `headSha`. */ + | { readonly kind: 'add-pending'; readonly comment: ForgeLineComment } + | { readonly kind: 'submit-pending'; readonly review: ForgeReviewId; readonly event: ForgeReviewEvent; readonly body: string } + /** Delete the pending review with every comment it holds. */ + | { readonly kind: 'discard-pending'; readonly review: ForgeReviewId } +) + +/** Result of a review write; an `unknown` outcome must be checked on the host before the write is tried again. */ +export type ForgeReviewWriteResult = + | { readonly ok: true } + | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } + /** Result of a review write; unknown outcomes must be checked on the host before another submission. */ export type ForgeReviewResult = | { readonly ok: true; readonly url: string } @@ -306,6 +366,12 @@ export interface ForgeProvider { * Omission declares that this provider cannot read reviews. */ readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Write to the review threads or the pending review of a change request while its head is `write.headSha`; once the + * head is another commit, the write resolves to `stale` without writing. A write is never retried. Omission declares + * that this provider cannot write reviews, and its `readReview` then reports no viewer permission. + */ + writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ diff --git a/packages/experimental/forge/tests/registry.spec.ts b/packages/experimental/forge/tests/registry.spec.ts index a87103be4e..b9d24f6338 100644 --- a/packages/experimental/forge/tests/registry.spec.ts +++ b/packages/experimental/forge/tests/registry.spec.ts @@ -1,7 +1,7 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' import ForgeService, { changeRequestKey } from '../src/index.ts' -import type { ForgeReviewData } from '../src/types.ts' +import type { ForgeReviewData, ForgeReviewWrite, ForgeThreadId } from '../src/types.ts' import { demo, FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts' let ctx: Context | undefined @@ -134,13 +134,30 @@ describe('forge registry', () => { await expect(ctx.forge.readReview(ref(3), 'a'.repeat(40), signal)) .resolves.toEqual({ code: 'unsupported', message: 'This provider does not support review reads' }) - const review: ForgeReviewData = { headSha: 'a'.repeat(40), viewer: 'octo', threads: [], truncated: false } + const review: ForgeReviewData = { + headSha: 'a'.repeat(40), viewer: 'octo', threads: [], truncated: false, pendingReview: null, viewerCanReview: false, + } const readReview = vi.fn(async () => review) Object.assign(provider, { readReview }) await expect(ctx.forge.readReview(ref(3), 'a'.repeat(40), signal)).resolves.toBe(review) expect(readReview).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), expect.any(AbortSignal)) }) + it('delegates review writes to the provider of their forge and reports a provider without them as unsupported', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + const write: ForgeReviewWrite = { kind: 'resolve', headSha: 'a'.repeat(40), thread: 'thread-1' as ForgeThreadId, resolved: true } + + await expect(ctx.forge.writeReview(ref(3), write, signal)) + .resolves.toEqual({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' }) + const writeReview = vi.fn(async () => ({ ok: true as const })) + Object.assign(provider, { writeReview }) + await expect(ctx.forge.writeReview(ref(3), write, signal)).resolves.toEqual({ ok: true }) + expect(writeReview).toHaveBeenCalledWith(ref(3), write, expect.any(AbortSignal)) + }) + it('delegates change request actions to the provider of their forge and returns its outcome', async () => { ctx = await forgeContext() const provider = new FakeProvider() diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index 5903fb42fa..43dc792c07 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -1,7 +1,10 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import ForgeService, { changeRequestKey } from '../src/index.ts' -import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeRepository, ForgeReviewData } from '../src/types.ts' +import type { + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeRepository, ForgeReviewData, + ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, +} from '../src/types.ts' import { FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts' const config = { activeIntervalMs: 1_000, idleIntervalMs: 5_000, maxBackoffMs: 6_000, fetchTimeoutMs: 500 } @@ -289,6 +292,33 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(2) }) + it('polls at once after every review write, and after a stale one only once per head', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const writeReview = vi.fn(async (): Promise => ({ ok: true })) + Object.assign(provider, { writeReview }) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + const write: ForgeReviewWrite = { kind: 'reply', headSha: 'a'.repeat(40), thread: 'thread-1' as ForgeThreadId, body: 'Done', pending: false } + + await expect(context.forge.writeReview(ref(1), write, signal)).resolves.toEqual({ ok: true }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + writeReview.mockResolvedValue({ ok: false, code: 'unknown', message: 'connection reset' }) + await context.forge.writeReview(ref(1), write, signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(3) + writeReview.mockResolvedValue({ ok: false, code: 'stale', message: 'the head moved' }) + await expect(context.forge.writeReview(ref(1), write, signal)).resolves.toEqual({ ok: false, code: 'stale', message: 'the head moved' }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(4) + await context.forge.writeReview(ref(1), write, signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(4) + }) + it('coalesces refreshes during a fetch into one immediate subsequent fetch', async () => { const provider = new FakeProvider() const release = held(provider, target => snapshot(target)) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a2b3cbd92..f6b6836d6f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10172,6 +10172,9 @@ importers: '@deepseek-ai/dsh-timeout': specifier: workspace:* version: link:../../util/timeout + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery From b1aa940b0fa92b870ff91539cea9ba23480b53f5 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 11:21:15 +0800 Subject: [PATCH 10/29] feat(forge-panel): reply to, resolve, and edit review threads and submit the pending review Thread cards gain a reply field, Resolve and Unresolve, and edit and delete for the viewer's own comments. Start review and Add to review add pull request comments to the GitHub pending review, which Submit review submits or discards; while one exists, replies join it and no single comment is offered, as GitHub refuses one. On the viewer's own pull request the dialog offers only Comment. Comment drafts an earlier panel kept in the browser stay editable, can move into the pending review, and block submission while one exists. --- .../client-ui-forge/src/client/ChangesTab.tsx | 113 +++++++- .../src/client/ReviewComposer.tsx | 53 ++-- .../src/client/ReviewThread.tsx | 31 ++- .../src/client/ReviewThreads.module.css | 78 ++++++ .../src/client/ReviewThreads.tsx | 177 +++++++++++- .../src/client/SubmitReview.module.css | 3 + .../src/client/SubmitReview.tsx | 51 +++- .../client-ui-forge/src/client/locales.ts | 184 +++++++++++++ .../client-ui-forge/src/client/mount.ts | 3 +- .../src/client/review-queue.ts | 15 +- .../src/client/thread-state.ts | 6 +- .../tests/changes-tab.client.spec.tsx | 259 ++++++++++++++++-- .../tests/mount.client.spec.ts | 15 +- .../tests/review-thread-cards.client.spec.tsx | 174 +++++++++++- .../tests/review.client.spec.tsx | 190 ++++++++++--- .../tests/thread-fixtures.client.ts | 9 +- 16 files changed, 1214 insertions(+), 147 deletions(-) diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 0747a901bc..91ef3242e7 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -22,13 +22,14 @@ import { import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' import type { - ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, + ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult, } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' @@ -49,7 +50,7 @@ import { drawnLines, matchesHunks, textLines } from './diff-rows.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import { RefreshGlyph } from './RefreshGlyph.tsx' -import type { FileThreads, ThreadActions, ThreadFocus } from './ReviewThreads.tsx' +import type { FileThreads, ThreadActions, ThreadFocus, ThreadWrite } from './ReviewThreads.tsx' import { inFileOrder, type ThreadFilter } from './review-threads.ts' import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts' import { ThreadList } from './ThreadList.tsx' @@ -94,6 +95,8 @@ export interface ChangesTabInjected { readonly changeRequestText: (url: string, commit: string, path: string) => Promise> /** Read the review threads of a change request at the head of its latest status; `signal` aborts the read. */ readonly changeRequestReview: (url: string, headSha: string, signal: AbortSignal) => Promise> + /** Write to the review threads or the pending review of a change request; never retries a write. */ + readonly changeRequestReviewWrite: (url: string, write: ForgeReviewWrite) => Promise> /** Quote a whole review thread of the change request at `url` in the main input without submitting it. */ readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean /** Open a URL outside the app. */ @@ -433,7 +436,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { */ export function ChangesTab({ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, - changeRequestText, changeRequestCommits, changeRequestReview, viewedFiles, + changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -482,6 +485,40 @@ export function ChangesTab({ setReviewBusy(false) } } + // Every write that may have changed the threads reads them again; writes run one at a time, so a write that starts a + // pending review settles before the next write looks for one. + const [reviewRevision, setReviewRevision] = useState(0) + const writing = useRef>(Promise.resolve()) + const writeReview = (url: string, write: ForgeReviewWrite): Promise => { + const run = async (): Promise => { + const response = await changeRequestReviewWrite(url, write) + if (!response.ok) { + if (response.error.code === 'forgePanel/not-bound') return t('thread.writeFailed', { message: response.error.message }) + setReviewRevision(value => value + 1) + return t('thread.writeUnknown') + } + const result = response.value + if (result.ok) { + setReviewRevision(value => value + 1) + return undefined + } + switch (result.code) { + case 'unsupported': return t('thread.writeUnsupported') + case 'failed': + setReviewRevision(value => value + 1) + return t('thread.writeFailed', { message: result.message }) + case 'stale': return t('thread.writeStale') + case 'unknown': + setReviewRevision(value => value + 1) + return t('thread.writeUnknown') + /* v8 ignore next -- closed ForgeReviewWriteResult code union exhaustiveness guard */ + default: return assertNever(result.code, 'ForgeReviewWriteResult.code') + } + } + const next = writing.current.then(run, run) + writing.current = next + return next + } const choices = useStore(store => store.byTab[tab.id]) const [wanted, setWanted] = useState(null) const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) @@ -575,7 +612,7 @@ export function ChangesTab({ const prHead = entry?.snapshot?.headSha ?? null const prAuthor = entry?.snapshot?.author ?? null const threadRead = useThreadRead({ visible: tab.visible, url: source.kind === 'change' ? source.url : null, head: prHead, - updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, read: changeRequestReview }) + updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, revision: reviewRevision, read: changeRequestReview }) const review = data?.kind === 'change' && threadRead.review !== null && threadRead.review.headSha === prHead && (data.commits !== null || data.headSha === prHead) ? threadRead.review : null const placed = usePlacedThreads(review, data?.kind === 'change' ? { head: prHead ?? '', end: data.headSha, commits: data.commits } : null) @@ -689,16 +726,61 @@ export function ChangesTab({ return list } - // A review addresses the head commit, so it is submitted from the view of the whole change request. + // A review addresses the head commit, so it is submitted from the view of the whole change request. A pending review on + // the code host is submitted or discarded there; without one, the summary and any comment drafts kept in the browser + // are published as one review. + const pendingReview = review?.pendingReview ?? null + // Logins compare without case, as GitHub's do. + const ownChangeRequest = review?.viewer != null && prAuthor !== null && review.viewer.toLowerCase() === prAuthor.toLowerCase() + const finishWrite = async (send: () => Promise, done: ForgePanelKey): Promise => { + if (reviewRunning.current) return + reviewRunning.current = true + setReviewBusy(true) + setReviewError(null) + try { + const failure = await send() + if (failure !== undefined) { + setReviewError(failure) + return + } + report(done) + setReviewOpen(false) + } finally { + reviewRunning.current = false + setReviewBusy(false) + } + } const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && data.commits === null && { setReviewOpen(false) }} + url={data.url} headSha={data.headSha} pending={pendingReview} own={ownChangeRequest} busy={reviewBusy} error={reviewError} + close={() => { setReviewOpen(false) }} check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }} submit={() => { const latest = queue.getSnapshot() - void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event, - body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url)) + if (pendingReview === null) { + void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event, + body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url)) + return + } + void finishWrite(async () => { + const failure = await writeReview(data.url, { kind: 'submit-pending', headSha: data.headSha, review: pendingReview.id, + event: latest.event, body: latest.body }) + if (failure === undefined && !queue.finish(true)) report('review.saveFailed') + return failure + }, 'review.submitted') + }} + discard={pendingReview === null ? undefined : () => { + void finishWrite(() => writeReview(data.url, { kind: 'discard-pending', headSha: data.headSha, review: pendingReview.id }), 'review.discarded') }} t={t} /> + /** Add a comment to the pending review on the code host at the head the comment was selected on. */ + const addPending = (selection: ReviewSelection): Promise => { + if (selection.source.kind !== 'change') return Promise.resolve(t('review.stale')) + const { path, side, startLine, endLine, body } = selection.comment + return writeReview(selection.source.url, { kind: 'add-pending', headSha: selection.source.headSha, comment: { path, side, startLine, endLine, body } }) + } + // Only the whole change request takes new comments for its pending review, once the threads say the user may review. + const pendingComments = data?.kind === 'change' && data.commits === null && review?.viewerCanReview === true ? { queue: addPending } : {} + const recordActions: ReviewActions = { source: shownSource ?? (source.kind === 'local' ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) } @@ -718,6 +800,11 @@ export function ChangesTab({ readText: (commit, path) => changeRequestText(data.url, commit, path), inputFailed: () => { report('thread.inputFailed') }, focused: focus, + writes: { + write: (write: ThreadWrite) => writeReview(data.url, { ...write, headSha: review.headSha }), + reviewStarted: review.pendingReview !== null, + canReview: review.viewerCanReview, + }, } const threadsOf = (path: string): FileThreads | undefined => { const group = placed.files.get(path) @@ -869,11 +956,12 @@ export function ChangesTab({ file={file} review={{ source: reviewSourceOf(data), addToInput: addReviewToInput, - records: queue, openLink, reviewStarted: reviewState.comments.length > 0, + records: queue, openLink, reviewStarted: pendingReview !== null, onQuoted: (selection) => { if (!queue.recordAgent(selection)) report('review.saveFailed') }, publishingBlocked: reviewState.uncertain !== null, - ...data.kind === 'local' || data.commits !== null ? {} : { - queue: selection => queue.add(selection), + ...pendingComments, + // GitHub refuses a comment published on its own while the user has a pending review. + ...data.kind === 'local' || data.commits !== null || pendingReview !== null ? {} : { publish: selection => selection.source.kind === 'change' ? publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, url => queue.published(selection, url)) @@ -939,7 +1027,8 @@ export function ChangesTab({ ? { actions.based(tab.id, next) }} commitMenu={commitMenu} createChangeRequest={createChangeRequest} t={t} /> - : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' &&
diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx index 94407dfee8..82e482c35f 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx @@ -15,7 +15,7 @@ export interface ReviewActions { readonly source: ReviewSource /** Browser records shared by the changes tab. */ readonly records?: ReviewQueue - /** Whether another comment already started a pending review. */ + /** Whether the signed-in user has a pending review on the code host that the next comment joins. */ readonly reviewStarted?: boolean /** Open the confirmed publication URL. */ readonly openLink?: (url: string) => void @@ -27,26 +27,32 @@ export interface ReviewActions { readonly onQuoted?: (selection: ReviewSelection) => void /** Publish one comment; an error string preserves the editor. */ readonly publish?: (selection: ReviewSelection) => Promise - /** Keep one comment for the final review; false preserves the editor. */ - readonly queue?: (selection: ReviewSelection) => boolean + /** Add one comment to the pending review on the code host, starting one when needed; an error string preserves the editor. */ + readonly queue?: (selection: ReviewSelection) => Promise } -function GitHubAction({ disabled, busy, started, queue, publish, t }: PropsLocale & { +/** + * Render a primary action with an optional second action in its menu. + * @param props - the main action, the optional menu action, the menu's name, and availability. + * @returns the split button. + */ +export function SplitAction({ disabled, label, run, menuLabel, menu, other }: { readonly disabled: boolean - readonly busy: boolean - readonly started: boolean - readonly queue: () => void - readonly publish: (() => void) | undefined + readonly label: string + readonly run: () => void + /** Accessible name of the menu button. */ + readonly menuLabel: string + /** Label of the action in the menu, or undefined without one. */ + readonly other: string | undefined + readonly menu: () => void }): ReactNode { const [open, setOpen] = useState(false) return
- - {publish !== undefined && { setOpen(false) }} + + {other !== undefined && { setOpen(false) }} anchor={}> - { setOpen(false); publish() }}>{t('review.publish')} + aria-label={menuLabel} onClick={() => { setOpen(value => !value) }}>}> + { setOpen(false); menu() }}>{other} }
} @@ -73,13 +79,14 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli useEffect(() => { input.current?.focus() }, []) const comment = (): ReviewSelection => ({ ...selection, comment: { ...selection.comment, body: body.current } }) const range = reviewRange(selection.comment) - const publish = async (): Promise => { - if (running.current || actions.publish === undefined) return + /** Send the comment to the code host, closing the form once it is taken and keeping its text otherwise. */ + const send = async (destination: ((selection: ReviewSelection) => Promise) | undefined): Promise => { + if (running.current || destination === undefined) return running.current = true setBusy(true) setError(null) try { - const failure = await actions.publish(comment()) + const failure = await destination(comment()) if (failure === undefined) close() else setError(failure) } catch (_error) { @@ -108,14 +115,12 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli if (actions.addToInput(selected)) { actions.onQuoted?.(selected); close() } else setError(t('review.inputFailed')) }}>{t('review.addToInput')} - {visible && actions.queue !== undefined && { - if (actions.queue?.(comment()) === true) close() - else setError(t('review.saveFailed')) - }} publish={actions.publish === undefined ? undefined : () => { void publish() }} t={t} />} + {visible && actions.queue !== undefined && { void send(actions.queue) }} menuLabel={t('review.githubActions')} + other={actions.publish === undefined ? undefined : t('review.publish')} menu={() => { void send(actions.publish) }} />} {actions.queue === undefined && actions.publish !== undefined && } + disabled={busy || actions.publishingBlocked === true || empty} onClick={() => { void send(actions.publish) }}>{t('review.publish')}}
diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx b/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx index f626c2dc47..7abb3a7f67 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx @@ -1,4 +1,4 @@ -/** Inline comment records and editing of a pending review at its captured code location. */ +/** Inline comment records and the editing of comment drafts kept in the browser at their captured code location. */ import { useCallback, useState, useSyncExternalStore, type ReactNode } from 'react' import { Button, Tag } from '@deepseek-ai/dsh-client-ui-primitives' @@ -24,7 +24,8 @@ export function useFileReview(actions: ReviewActions | undefined, path: string): } /** - * Render a saved comment at its line, with pending edits kept in the browser queue. + * Render a saved comment at its line. A comment draft kept in the browser can be edited, deleted, or moved into the + * pending review on the code host. * @param props - record, edit availability, source actions, and localized copy. * @returns one compact inline comment card. */ @@ -38,11 +39,27 @@ export function ReviewThread({ thread, actions, locked, outdated, split, t }: Pr const [editing, setEditing] = useState(false) const [body, setBody] = useState(thread.selection.comment.body) const [error, setError] = useState(null) + const [moving, setMoving] = useState(false) const comment = thread.selection.comment const quoted = editing && thread.kind === 'pending' ? { ...thread.selection, comment: { ...comment, body } } : thread.selection const range = reviewRange(comment) - const status = thread.kind === 'pending' ? 'review.pending' : thread.kind === 'published' ? 'review.published' : 'review.quoted' + const status = thread.kind === 'pending' ? 'review.browserDraft' : thread.kind === 'published' ? 'review.published' : 'review.quoted' const save = (): boolean => actions.records?.editThread(thread.key, body) === true + const queue = actions.queue + /** Add the draft to the pending review on the code host, then delete it from the browser. */ + const move = async (add: NonNullable): Promise => { + setMoving(true) + setError(null) + try { + const failure = await add(thread.selection) + if (failure !== undefined) setError(failure) + else if (actions.records?.editThread(thread.key, null) !== true) setError(t('review.saveFailed')) + } catch (_error) { + setError(t('review.unknown')) + } finally { + setMoving(false) + } + } return
@@ -65,13 +82,15 @@ export function ReviewThread({ thread, actions, locked, outdated, split, t }: Pr }}>{t('review.addToInput')} {thread.kind === 'pending' && <> {editing - ? - : } - } + + {queue !== undefined && !editing && !outdated && } } {thread.kind === 'published' && actions.openLink !== undefined && }
diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css index b84b5a8428..046ba7baad 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css @@ -151,6 +151,84 @@ margin: 10px -8px -4px; } +/* A reply or a comment edit uses the inline review form's field; its actions sit under it like the form's. */ +.form { margin-top: 10px; } + +.formActions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 8px; + margin-top: 8px; +} + +/* The collapsed reply field, a field-shaped button that opens the reply form. */ +.replyPrompt { + display: block; + box-sizing: border-box; + width: 100%; + min-height: 32px; + margin-top: 10px; + padding: 6px 12px; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-md); + background: var(--dsw-alias-bg-layer-3); + color: var(--dsw-alias-label-dimmed); + font: inherit; + text-align: start; + cursor: text; +} + +.replyPrompt:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 2px; +} + +.menuAnchor { display: inline-flex; flex: none; } + +/* The comment menu's icon button keeps the 20px row height of the header it ends. */ +.icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + padding: 0; + border: 0; + border-radius: var(--dsw-radius-xs); + background: transparent; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +.icon[aria-expanded="true"] { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } + +.icon:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} + +@media (hover: hover) { + .icon:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } +} + +/* Confirming a deletion replaces nothing: the comment stays readable above the question. */ +.confirm { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 8px; +} + +.confirmText { flex: 1 1 auto; min-width: 0; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; } + +.confirmError, +.actionError { flex-basis: 100%; margin-top: 0; } + +.actionError { padding-inline: 8px; } + /* The end of the recorded hunk, drawn like the diff rows it came from. */ .excerpt, .original { diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx b/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx index 02cf0c8fae..feedfe071b 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx @@ -1,23 +1,44 @@ /** - * Read-only review threads of a change request inside the changes view: a thread card at its lines or at the top of - * its file, a resolved thread folded into one row, and the outdated threads of a file in a section after its lines. + * Review threads of a change request inside the changes view: a thread card at its lines or at the top of its file, a + * resolved thread folded into one row, and the outdated threads of a file in a section after its lines. A card offers + * the writes the signed-in user may make: a reply, published at once or added to the pending review, resolving or + * unresolving the thread, and editing or deleting the user's own comments. */ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconRightUpOutlineRegular, MarkdownText, Tag, type MarkdownLabels, + Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconEllipsisOutlineRegular, IconRightUpOutlineRegular, MarkdownText, + Menu, Tag, Tooltip, type MarkdownLabels, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' -import type { ForgeReviewComment, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeReviewComment, ForgeReviewThread, ForgeReviewWrite, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { formatAgo } from './format.ts' import { anchorRange, hunkExcerpt, type ThreadPlace } from './review-threads.ts' +import { SplitAction } from './ReviewComposer.tsx' import type { NS } from './locales.ts' import css from './ReviewThreads.module.css' +import composerCss from './ReviewComposer.module.css' type Translate = PropsLocale['t'] +/** Each member of a union without its `headSha`. */ +type WithoutHead = T extends unknown ? Omit : never + +/** A write to one thread or its comments, without the head commit the changes view adds. */ +export type ThreadWrite = WithoutHead> + +/** Writes the signed-in user can make to the threads of one changes view. */ +export interface ThreadWrites { + /** Send a write; resolves to the message to show, or undefined once the code host took it. */ + readonly write: (write: ThreadWrite) => Promise + /** Whether the user has a pending review, which every reply then joins. */ + readonly reviewStarted: boolean + /** Whether the user can add a reply to a pending review, starting one when needed. */ + readonly canReview: boolean +} + /** Reads, actions, and identities every thread card of one changes view shares. */ export interface ThreadActions { /** Login of the signed-in user, or null when the host names none. */ @@ -34,6 +55,8 @@ export interface ThreadActions { readonly inputFailed: () => void /** The latest jump to a thread, which unfolds that thread and its section until the reader folds them again; null before any. */ readonly focused: ThreadFocus | null + /** Writes the user can make, or null when the code host takes none from this view. */ + readonly writes: ThreadWrites | null } /** One jump to a thread; each jump has its own revision, so a jump to the same thread unfolds it again. */ @@ -97,14 +120,77 @@ export function Avatar({ author, size = 20 }: { readonly author: ForgeReviewComm } -function Comment({ comment, actions, labels, now, t }: { +/** Run one write at a time for a card section, keeping its error until the next attempt. */ +function useWriting(t: Translate): { + readonly busy: boolean + readonly error: string | null + readonly run: (send: () => Promise) => Promise +} { + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const running = useRef(false) + const run = async (send: () => Promise): Promise => { + if (running.current) return false + running.current = true + setBusy(true) + setError(null) + try { + const failure = await send() + setError(failure ?? null) + return failure === undefined + } catch (_error) { + setError(t('thread.writeUnknown')) + return false + } finally { + running.current = false + setBusy(false) + } + } + return { busy, error, run } +} + +/** A plain-text field with Cancel and the actions that send it, for a reply or a comment edit. */ +function TextForm({ label, initial, busy, error, cancel, children }: { + readonly label: string + readonly initial: string + readonly busy: boolean + readonly error: string | null + readonly cancel: { readonly label: string; readonly run: () => void } + /** The sending actions, given the current text and whether it is blank. */ + readonly children: (text: string, blank: boolean) => ReactNode +}): ReactNode { + const [text, setText] = useState(initial) + return
+