diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json index 8dd840d825..86c52c2524 100644 --- a/packages/experimental/client-ui-forge/package.json +++ b/packages/experimental/client-ui-forge/package.json @@ -67,6 +67,7 @@ }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "diff": "^9.0.0", "zod": "4.6.6", diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 3e42c6cfc6..3a8fdc4ca5 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -6,7 +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 { - BranchUpdateMethod, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, + BranchUpdateMethod, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, + ForgeFailure, ForgeLineComment, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod, } from '@deepseek-ai/dsh-experimental-forge' @@ -25,8 +26,12 @@ import type { Inspection } from './git.ts' import { parseDiff } from './diff.ts' import { aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint, - localCommits, localDiff, localText, NoForkPoint, + localCommits, localDiff, localOldText, localText, NoForkPoint, } from './local-diff.ts' +import type { ForkPoint } from './local-diff.ts' +import { LensCache, LensFailed, lensFrames, LensRegistry, LensWithdrawn, runLens } from './lenses.ts' +import type { LensSubject } from './lenses.ts' +import { lensVersion } from './lens-version.ts' import { rangeStart } from './commit-range.ts' import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' @@ -35,8 +40,9 @@ import { ReviewCache } from './review-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { - Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeLocalCommits, - ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, + Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile, + ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, + ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, } from './types.ts' import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' @@ -50,8 +56,16 @@ declare module '@deepseek-ai/cordis' { } } -/** Panel limits plus the branch and commit listing limits and the worktree branch prefix. */ -type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly maxCommits: number; readonly worktreePrefix: string } +/** Panel limits plus the branch and commit listing limits, the worktree branch prefix, and the lens and annotation limits. */ +type ControllerConfig = PanelConfig & { + readonly maxBranches: number + readonly maxCommits: number + readonly worktreePrefix: string + readonly lensTimeoutMs: number + readonly maxLensReadBytes: number + readonly maxCachedLensBytes: number + readonly maxAnnotationsPerFile: number +} /** * Serves the forge panel. Following a Session inspects the checkout of its @@ -89,6 +103,10 @@ export class ForgePanelController extends TypertRemoteService { interfacePaths: z.array(z.string()).default([]), maxCachedReviewBytes: z.number().default(16_777_216), reviewRefreshMs: z.number().default(60_000), + lensTimeoutMs: z.number().default(60_000), + maxLensReadBytes: z.number().default(33_554_432), + maxCachedLensBytes: z.number().default(4_194_304), + maxAnnotationsPerFile: z.number().default(100), }) private readonly home: Context @@ -99,6 +117,10 @@ export class ForgePanelController extends TypertRemoteService { private readonly patches: PatchCache private readonly layers: FileLayers private readonly reviews: ReviewCache + private readonly lenses = new LensRegistry() + private readonly lensResults: LensCache + /** Review changes `forge/review-changed` announced per change request, which each panel entry reports. */ + private readonly reviewRevisions = new Map() private states: ChangeRequestStates | undefined private readonly stopPanels: () => Promise private readonly stopStates: () => Promise @@ -107,13 +129,16 @@ 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', 'reviewRefreshMs'] as const) { + for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs', 'lensTimeoutMs'] 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', 'maxCachedReviewBytes'] as const) { + for (const key of [ + 'maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes', 'maxLensReadBytes', + 'maxCachedLensBytes', 'maxAnnotationsPerFile', + ] 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') @@ -125,6 +150,8 @@ export class ForgePanelController extends TypertRemoteService { this.config = resolved this.patches = new PatchCache(resolved.maxCachedDiffBytes) this.reviews = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs) + this.lensResults = new LensCache(resolved.maxCachedLensBytes) + ctx.effect(() => () => { this.lenses.close() }, 'forge-panel: lens streams') this.stopPanels = ctx.effect(() => async () => { const panels = [...this.panels.values()] this.panels.clear() @@ -153,6 +180,7 @@ export class ForgePanelController extends TypertRemoteService { const events = ctx.on('session/event', (session: Session, event: SessionEvent) => { this.panels.get(session)?.observe(event) }) + const reviewChanges = ctx.on('forge/review-changed', (ref: ChangeRequestRef) => { this.reviewChanged(ref) }) const services = ctx.on('internal/service', (name: string) => { if (name !== 'worktrees') return for (const panel of this.panels.values()) panel.updateWorktree() @@ -162,6 +190,7 @@ export class ForgePanelController extends TypertRemoteService { yield stateOwner.dispose yield inbox yield events + yield reviewChanges yield services yield stopPanels yield stopStates @@ -418,16 +447,13 @@ export class ForgePanelController extends TypertRemoteService { if (update === null || !('snapshot' in update)) { throw new RemoteError('forgePanel/diff-failed', 'The change request status has not been read yet', {}) } - if (commits !== null) return await this.commitsDiff(ref, commits, signal) - const { headSha, headBranch, baseBranch } = update.snapshot - const key = changeRequestKey(ref) - const version = JSON.stringify([headSha, baseBranch]) - let read = this.patches.get(key, version) - if (read === undefined) { - read = await this.patchAt(ref, headSha, async operation => await this.home.forge.diff(ref, headSha, operation), signal) - this.patches.set(key, version, read) + if (commits !== null) { + const { files } = await this.commitFiles(ref, commits, signal) + const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)])) + return { headSha: commits.to, files, localAhead: null, fileUrls } } - const files = this.layers.classify(parseDiff(read.patch), read.attributes) + const { headSha, headBranch } = update.snapshot + const files = await this.headFiles(ref, update.snapshot, signal) let localAhead: number | null = null try { localAhead = await aheadOf( @@ -462,6 +488,73 @@ export class ForgePanelController extends TypertRemoteService { return text } + /** + * Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending + * the registration aborts its running classifications and waits for them. + * @param lens - the lens. + * @returns the disposer that unregisters the lens and waits for its classifications to stop. + * @throws when another registration holds `lens.id`. + */ + registerLens(lens: ForgeLens): () => Promise { + const dispose = this.ctx.effect(() => this.lenses.add(lens), 'forge-panel: lens') + return async () => { await dispose() } + } + + /** + * Stream the facts every changes view reads about the panel's extensions: the current facts first, then the facts + * after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops. + * @param signal - ends the stream. + * @returns the registered lenses and the annotation limit, in publication order. + */ + @Remote({ mode: 'stream' }) + async *extensions(signal: AbortSignal): AsyncIterable { + for await (const lenses of this.lenses.follow(signal)) yield { lenses, maxAnnotationsPerFile: this.config.maxAnnotationsPerFile } + } + + /** + * Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens + * runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until + * `maxCachedLensBytes` evicts them. Local changes are read with the Session's permissions; a change request's files + * are those `changeRequestDiff` reads. + * @param session - Session whose checkout or binding the view shows. + * @param request - the view's source, the version of the files it shows, and the lens. + * @param signal - ends the classification. + * @returns progress frames, then one result frame. + * @throws `forgePanel/lens-missing` while no lens holds the identity or once its registration ends; + * `forgePanel/lens-stale` before a change request's status was read and when the files differ from `request.version`; + * `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers + * over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files. + */ + @Remote({ mode: 'stream' }) + async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable { + signal.throwIfAborted() + const registration = this.lenses.get(request.lens) + if (registration === undefined) throw new RemoteError('forgePanel/lens-missing', `No lens "${request.lens}" is registered`, {}) + const subject = await this.lensSubject(session, request.source, signal) + if (lensVersion(subject.files) !== request.version) { + throw new RemoteError('forgePanel/lens-stale', 'The changes were read again since the view showed them', {}) + } + const key = JSON.stringify([subject.key, request.version, request.lens, registration.lens.version]) + const kept = this.lensResults.get(key) + if (kept !== undefined) { + yield { kind: 'result', files: kept } + return + } + const limits = { + timeoutMs: this.config.lensTimeoutMs, maxReadBytes: this.config.maxLensReadBytes, maxResultBytes: this.config.maxCachedLensBytes, + } + try { + for await (const frame of lensFrames(progress => runLens(registration, subject, limits, signal, progress))) { + if (frame.kind === 'result') this.lensResults.set(key, frame.files) + yield frame + } + } catch (error) { + if (error instanceof LensWithdrawn) throw new RemoteError('forgePanel/lens-missing', error.message, {}) + if (error instanceof LensFailed) throw new RemoteError('forgePanel/lens-failed', error.message, {}) + throw error + } + } + /** * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the * whole change request. @@ -870,8 +963,23 @@ export class ForgePanelController extends TypertRemoteService { return this.home.workingDirectory.get(session) === directory ? missing : null } - /** The changes of consecutive commits of a change request, from the first one's first parent to the last. */ - private async commitsDiff(ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal): Promise { + /** The files of a change request at the head a status recorded, read once per head and base branch while the cache keeps them. */ + private async headFiles(ref: ChangeRequestRef, snapshot: ChangeRequestSnapshot, signal: AbortSignal): Promise { + const { headSha, baseBranch } = snapshot + const key = changeRequestKey(ref) + const version = JSON.stringify([headSha, baseBranch]) + let read = this.patches.get(key, version) + if (read === undefined) { + read = await this.patchAt(ref, headSha, async operation => await this.home.forge.diff(ref, headSha, operation), signal) + this.patches.set(key, version, read) + } + return this.layers.classify(parseDiff(read.patch), read.attributes) + } + + /** The files of consecutive commits of a change request, from the first one's first parent, which is returned too, to the last. */ + private async commitFiles( + ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal, + ): Promise<{ readonly files: ForgeDiffFile[]; readonly parent: string }> { const list = await this.home.forge.commits(ref, signal) if (list === undefined) throw new RemoteError('forgePanel/diff-failed', 'The code host provider does not read commits', {}) if ('code' in list) throw readError(list) @@ -883,9 +991,7 @@ export class ForgePanelController extends TypertRemoteService { const { patch, attributes } = await this.patchAt( ref, commits.to, async operation => await this.home.forge.compare(ref, parent, commits.to, operation), signal, ) - const files = this.layers.classify(parseDiff(patch), attributes) - const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)])) - return { headSha: commits.to, files, localAhead: null, fileUrls } + return { files: this.layers.classify(parseDiff(patch), attributes), parent } } /** @@ -1020,10 +1126,95 @@ export class ForgePanelController extends TypertRemoteService { return this.states } + /** Drop the threads kept for a change request after an accepted review change and let its panel entries report it. */ + private reviewChanged(ref: ChangeRequestRef): void { + const key = changeRequestKey(ref) + this.reviews.drop(key) + this.reviewRevisions.set(key, (this.reviewRevisions.get(key) ?? 0) + 1) + for (const panel of this.panels.values()) panel.reviewChanged() + } + + /** The files a lens request names with their reader and the key results for them are kept under. */ + private async lensSubject( + session: Session, source: ForgeLensRequest['source'], signal: AbortSignal, + ): Promise { + if (source.kind === 'local') { + const inspection = await this.checkoutOf(session, signal) + const root = inspection.checkout.root + const { scope } = source + const fork: ForkPoint | null = scope.kind !== 'branch' ? null : await diffing(scope.base === null + ? forkPoint(gitIn(this.home, this.config, session, root, signal), inspection, this.worktreeState(session).created) + : chosenForkPoint(gitIn(this.home, this.config, session, root, signal), scope.base)) + const { files } = await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal)) + return { + key: JSON.stringify(['local', session.id, scope]), + source: { kind: 'local', scope }, + files, + read: async (side, file, inner) => { + if (file.binary || (side === 'old' ? file.status === 'added' : file.status === 'deleted')) return null + return side === 'new' + ? await diffing(localText(this.home, this.config, session, root, scope, file.path, inner)) + : await diffing(localOldText(this.home, this.config, session, root, scope, fork, file.previousPath ?? file.path, inner)) + }, + } + } + const { ref, update } = this.bound(session, source.url) + if (update === null || !('snapshot' in update)) { + throw new RemoteError('forgePanel/lens-stale', 'The change request status has not been read yet', {}) + } + const { snapshot } = update + const { commits } = source + let files: ForgeDiffFile[] + let newCommit: string + let oldCommit: (inner: AbortSignal) => Promise + if (commits === null) { + files = await this.headFiles(ref, snapshot, signal) + newCommit = snapshot.headSha + // One merge base serves every old side of the run; a failed lookup is tried again by the next read. + let base: Promise | undefined + oldCommit = async (inner) => { + base ??= this.mergeBaseOf(ref, snapshot, inner) + try { + return await base + } catch (error) { + base = undefined + throw error + } + } + } else { + const read = await this.commitFiles(ref, commits, signal) + files = read.files + newCommit = commits.to + oldCommit = async () => read.parent + } + return { + key: JSON.stringify(['change', changeRequestKey(ref), newCommit, commits]), + source: { kind: 'change', ref, headSha: snapshot.headSha, commits }, + files, + read: async (side, file, inner) => { + if (file.binary || (side === 'old' ? file.status === 'added' : file.status === 'deleted')) return null + const commit = side === 'new' ? newCommit : await oldCommit(inner) + const text = await this.home.forge.fileText(ref, commit, side === 'new' ? file.path : file.previousPath ?? file.path, inner) + if (typeof text === 'string') return text + if (text.code === 'not-found') return null + throw new Error(text.message) + }, + } + } + + /** The merge base whose files the old side of a change request's diff at the status's head shows. */ + private async mergeBaseOf(ref: ChangeRequestRef, snapshot: ChangeRequestSnapshot, signal: AbortSignal): Promise { + if (snapshot.baseSha === undefined) throw new Error('The code host provider reports no base commit to read the old side at') + const base = await this.home.forge.mergeBase(ref, snapshot.baseSha, snapshot.headSha, signal) + if (typeof base !== 'string') throw new Error(base.message) + return base + } + private panelOf(session: Session): SessionPanel { let panel = this.panels.get(session) if (panel === undefined) { - const created: SessionPanel = new SessionPanel(this.home, this.config, session, this.worktreeStates, this.creations, () => { + const revision = (ref: ChangeRequestRef): number => this.reviewRevisions.get(changeRequestKey(ref)) ?? 0 + const created: SessionPanel = new SessionPanel(this.home, this.config, session, this.worktreeStates, this.creations, revision, () => { if (this.panels.get(session) !== created) return this.panels.delete(session) void created.dispose() diff --git a/packages/experimental/client-ui-forge/src/lens-version.ts b/packages/experimental/client-ui-forge/src/lens-version.ts new file mode 100644 index 0000000000..cca6dea479 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/lens-version.ts @@ -0,0 +1,27 @@ +/** + * The version of a diff's files that a lens request names. The panel host and the changes view compute it alike, so a + * request refers to exactly the files its view shows. + */ + +/** + * Name the files of one diff: equal versions describe the same paths with the same changes in the same order. + * @param files - the diff's files in display order. + * @returns 14 hexadecimal digits of a 53-bit hash over each path and change digest. + */ +export function lensVersion(files: readonly { readonly path: string; readonly digest: string }[]): string { + // cyrb53: two 32-bit multiply-xorshift lanes folded into 53 bits. + let h1 = 0xdeadbeef + let h2 = 0x41c6ce57 + for (const file of files) { + for (const text of [file.path, '\u0000', file.digest, '\u0001']) { + for (let index = 0; index < text.length; index += 1) { + const code = text.charCodeAt(index) + h1 = Math.imul(h1 ^ code, 2654435761) + h2 = Math.imul(h2 ^ code, 1597334677) + } + } + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909) + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909) + return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0') +} diff --git a/packages/experimental/client-ui-forge/src/lenses.ts b/packages/experimental/client-ui-forge/src/lenses.ts new file mode 100644 index 0000000000..fc2406182b --- /dev/null +++ b/packages/experimental/client-ui-forge/src/lenses.ts @@ -0,0 +1,276 @@ +/** Filter lenses registered on the forge panel host, the runs that classify one diff with one of them, and the kept results. */ + +import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' +import type { ForgeLens, ForgeLensFile, ForgeLensFrame, ForgeLensInput, ForgeLensKeep, ForgeLensSource } from './types.ts' + +/** The files a lens kept, by path. */ +export type LensFiles = Readonly> + +/** Why a lens run produced no result; the message names the cause for the reader. */ +export class LensFailed extends Error { + override name = 'LensFailed' +} + +/** The reason a run stops when its lens's registration ends. */ +export class LensWithdrawn extends Error { + override name = 'LensWithdrawn' +} + +/** One registered lens and the runs that use it. */ +export interface LensRegistration { + /** The lens as its plugin registered it. */ + readonly lens: ForgeLens + /** Aborts with a {@link LensWithdrawn} once the registration ends. */ + readonly lifetime: AbortSignal + /** + * Keep one run among the work the registration's disposer waits for. + * @param run - the run. + * @returns the same run. + */ + track(run: Promise): Promise +} + +/** + * The lenses registered on one panel host. Identities are unique while registered; the follow streams of every reader + * receive the list after each change, and end once the registry closes. + */ +export class LensRegistry { + private readonly entries = new Map() + private readonly listeners = new Set<() => void>() + private readonly closed = new AbortController() + + /** + * Register a lens. + * @param lens - the lens. + * @returns the disposer, which aborts the lens's running classifications and waits for them. + * @throws when another registration holds `lens.id`. + */ + add(lens: ForgeLens): () => Promise { + if (this.entries.has(lens.id)) throw new Error(`forge-panel: a lens "${lens.id}" is already registered`) + const lifetime = new AbortController() + const runs = new Set>() + const registration: LensRegistration = { + lens, + lifetime: lifetime.signal, + track: (run) => { + const settled = run.then(() => undefined, () => undefined) + runs.add(settled) + void settled.then(() => runs.delete(settled)) + return run + }, + } + this.entries.set(lens.id, registration) + this.changed() + return async () => { + this.entries.delete(lens.id) + lifetime.abort(new LensWithdrawn(`the lens "${lens.id}" was unregistered`)) + this.changed() + await Promise.allSettled([...runs]) + } + } + + /** + * Find a registered lens. + * @param id - its identity. + * @returns the registration, or undefined while no lens holds the identity. + */ + get(id: string): LensRegistration | undefined { + return this.entries.get(id) + } + + /** + * Stream the identities of the registered lenses: the current list first, then the list after each change; changes + * that arrive while the reader is busy collapse into the next list. + * @param signal - ends the stream. + * @returns identities in registration order. + */ + async *follow(signal: AbortSignal): AsyncIterable { + const stop = AbortSignal.any([signal, this.closed.signal]) + let wake = Promise.withResolvers() + const listener = (): void => { wake.resolve() } + this.listeners.add(listener) + stop.addEventListener('abort', listener) + try { + while (!stop.aborted) { + const current = wake + yield [...this.entries.keys()] + await current.promise + wake = Promise.withResolvers() + } + } finally { + this.listeners.delete(listener) + stop.removeEventListener('abort', listener) + } + } + + /** End every follow stream; registrations still end through their own disposers. */ + close(): void { + this.closed.abort() + } + + private changed(): void { + for (const listener of this.listeners) listener() + } +} + +/** One diff a lens classifies, with the reader of its files' sides. */ +export interface LensSubject { + /** What the view shows. */ + readonly source: ForgeLensSource + /** Every file of the diff in display order. */ + readonly files: readonly ForgeLensFile[] + /** + * Read one side of a file of `files`. + * @returns the text, or null when the side does not exist or holds binary content. + */ + readonly read: (side: 'old' | 'new', file: ForgeLensFile, signal: AbortSignal) => Promise +} + +/** Bounds of one lens run, from the panel's configuration. */ +export interface LensLimits { + /** `lensTimeoutMs`. */ + readonly timeoutMs: number + /** `maxLensReadBytes`. */ + readonly maxReadBytes: number + /** `maxCachedLensBytes`, which bounds one result as JSON. */ + readonly maxResultBytes: number +} + +/** + * Classify one diff with one lens. The lens's signal aborts with the caller's, when the registration ends, and after + * `timeoutMs`; the run settles then even when the lens ignores its signal. Paths the lens names outside the diff are + * left out of the result. + * @param registration - the registered lens. + * @param subject - the diff and its reader. + * @param limits - deadline, read budget, and result bound. + * @param signal - the caller's cancellation. + * @param progress - receives the lens's progress while it runs. + * @returns the files the lens kept. + * @throws `signal.reason` once the caller aborts; a {@link LensWithdrawn} once the registration ends; a + * {@link LensFailed} when the lens rejects, runs past the deadline, reads past the budget, or answers over the bound. + */ +export async function runLens( + registration: LensRegistration, + subject: LensSubject, + limits: LensLimits, + signal: AbortSignal, + progress: (done: number, total: number) => void, +): Promise { + using timer = deadline(AbortSignal.any([signal, registration.lifetime]), limits.timeoutMs, 'FORGE_LENS_TIMEOUT') + const operation = timer.signal + const byPath = new Map(subject.files.map(file => [file.path, file])) + let read = 0 + const overBudget = (): LensFailed => new LensFailed(`the lens read more than maxLensReadBytes (${limits.maxReadBytes} bytes) of file text`) + const input: ForgeLensInput = { + source: subject.source, + files: subject.files, + text: async (side, path, inner) => { + const file = byPath.get(path) + if (file === undefined) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a file of this diff`) + if (read > limits.maxReadBytes) throw overBudget() + const text = await subject.read(side, file, AbortSignal.any([inner, operation])) + if (text === null) return null + read += Buffer.byteLength(text) + if (read > limits.maxReadBytes) throw overBudget() + return text + }, + progress: (done, total) => { if (!operation.aborted) progress(done, total) }, + } + const stopped = new Promise((_resolve, reject) => { + operation.addEventListener('abort', () => { reject(operation.reason) }, { once: true }) + }) + // The race observes `stopped`; this handler only keeps a later abort from rejecting unobserved. + void stopped.catch(() => undefined) + let result: Awaited> + try { + result = await registration.track(Promise.race([Promise.resolve().then(() => registration.lens.classify(input, operation)), stopped])) + } catch (error) { + if (signal.aborted) throw signal.reason + if (registration.lifetime.aborted) throw registration.lifetime.reason + if (timeoutOf(operation) !== undefined) throw new LensFailed(`the lens ran past lensTimeoutMs (${limits.timeoutMs} ms)`) + if (error instanceof LensFailed) throw error + throw new LensFailed(`the lens failed: ${error instanceof Error ? error.message : String(error)}`) + } + if (read > limits.maxReadBytes) throw overBudget() + const files: Record = {} + for (const [path, keep] of Object.entries(result.files)) { + if (byPath.has(path)) files[path] = keep + } + if (Buffer.byteLength(JSON.stringify(files)) > limits.maxResultBytes) { + throw new LensFailed(`the lens result exceeds maxCachedLensBytes (${limits.maxResultBytes} bytes)`) + } + return files +} + +/** + * Turn one run into frames: the latest progress whenever the lens reported some since the last frame, then the result. + * @param run - starts the run with the progress receiver. + * @returns progress frames, then one result frame. + * @throws the run's failure after its last progress frame. + */ +export async function* lensFrames( + run: (progress: (done: number, total: number) => void) => Promise, +): AsyncIterable { + // A box, so the reads below see what the progress callback writes. + const reports: { latest: { readonly done: number; readonly total: number } | null } = { latest: null } + let wake = Promise.withResolvers() + let finished = false + const outcome = run((done, total) => { + reports.latest = { done, total } + wake.resolve() + }) + const settled = outcome.then(() => { finished = true }, () => { finished = true }) + while (!finished) { + const current = wake + await Promise.race([current.promise, settled]) + wake = Promise.withResolvers() + const reported = reports.latest + reports.latest = null + if (reported !== null && !finished) yield { kind: 'progress', done: reported.done, total: reported.total } + } + yield { kind: 'result', files: await outcome } +} + +/** Lens results kept for later requests, at most `maxBytes` of them as JSON, the least recently used dropped first. */ +export class LensCache { + private readonly entries = new Map() + private bytes = 0 + + /** @param maxBytes - `maxCachedLensBytes`. */ + constructor(private readonly maxBytes: number) {} + + /** + * Read a kept result, which becomes the most recently used. + * @param key - the request's files, lens, and lens version. + * @returns the result, or undefined when none is kept. + */ + get(key: string): LensFiles | undefined { + const entry = this.entries.get(key) + if (entry === undefined) return undefined + this.entries.delete(key) + this.entries.set(key, entry) + return entry.files + } + + /** + * Keep a result no larger than `maxBytes`, replacing one under the same key and dropping the least recently used + * results until the rest fit. + * @param key - the request's files, lens, and lens version. + * @param files - the result. + */ + set(key: string, files: LensFiles): void { + const previous = this.entries.get(key) + if (previous !== undefined) { + this.entries.delete(key) + this.bytes -= previous.bytes + } + const bytes = Buffer.byteLength(JSON.stringify(files)) + this.entries.set(key, { files, 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/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index 88496f040c..17c753643a 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -273,6 +273,51 @@ export async function localText( return text } +/** + * Read the old side of one changed file in a scope: the fork point for the `branch` scope, the first parent of the + * first chosen commit for chosen commits, the index for `unstaged`, else HEAD. + * @param ctx - context that provides `subprocess`, `sandbox`, and `sandboxPolicy`. + * @param config - Git and size limits. + * @param session - Session whose sandbox policy and execution world apply. + * @param root - top-level directory of the checkout. + * @param scope - the scope whose old side to read. + * @param fork - the `branch` scope's fork point, or null for other scopes. + * @param path - path relative to `root` on the old side, as the diff names it. + * @param signal - cancellation. + * @returns the text, or null when the old side has no such file or holds binary content. + * @throws NoForkPoint for the `branch` scope without `fork`; CommitsMissing for a chosen commit that is not a full + * object name; DiffTooLarge over `maxDiffBytes`; an Error for a path outside the checkout or a failed read. + */ +export async function localOldText( + ctx: Context, + config: DiffConfig, + session: Session, + root: string, + scope: ForgeLocalScope, + fork: ForkPoint | null, + path: string, + signal: AbortSignal, +): Promise { + if (!insideCheckout(path)) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a path inside the checkout`) + let revision: string + switch (scope.kind) { + case 'branch': + if (fork === null) throw new NoForkPoint('The checkout has no fork point to compare its branch with') + if (scope.commits !== null && !COMMIT.test(scope.commits.from)) throw new CommitsMissing('The chosen commit is not a full object name') + revision = scope.commits === null ? fork.commit : `${scope.commits.from}^` + break + case 'unstaged': revision = ''; break + case 'uncommitted': case 'staged': revision = 'HEAD'; break + /* v8 ignore next -- closed ForgeLocalScope union exhaustiveness guard */ + default: return assertNever(scope, 'ForgeLocalScope.kind') + } + const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal) + // Git exits with 128 for a path or revision that does not exist, such as the parent of a root commit. + const shown = await bounded(git('show', ['show', `${revision}:${path}`], [0, 128])) + if (shown.exitCode !== 0 || shown.stdout.slice(0, BINARY_PROBE).includes('\0')) return null + return shown.stdout +} + /** * Measure the `branch` scope for the panel's card. * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`. diff --git a/packages/experimental/client-ui-forge/src/panel.ts b/packages/experimental/client-ui-forge/src/panel.ts index ead8fecc97..f5f7a2f864 100644 --- a/packages/experimental/client-ui-forge/src/panel.ts +++ b/packages/experimental/client-ui-forge/src/panel.ts @@ -2,7 +2,7 @@ import { isDeepStrictEqual } from 'node:util' import type { Context } from '@deepseek-ai/cordis' -import type { ChangeRequestSnapshot, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge' +import type { ChangeRequestRef, ChangeRequestSnapshot, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type {} from '@deepseek-ai/dsh-experimental-worktree' import type {} from '@deepseek-ai/dsh-sandbox-policy' @@ -75,6 +75,7 @@ export class SessionPanel { * @param worktreeStates - reads the `forgeWorktree` projection of the Session. * @param creations - reads the running creation and restoration, the last failed creation, and what a message of the * Session waits for. + * @param reviewRevision - reads how many review changes were announced for a change request. * @param onIdle - called when the last follower leaves. */ constructor( @@ -83,6 +84,7 @@ export class SessionPanel { readonly session: Session, private readonly worktreeStates: ProjectionHandle, private readonly creations: Pick, + private readonly reviewRevision: (ref: ChangeRequestRef) => number, private readonly onIdle: () => void, ) { this.current = { @@ -202,6 +204,11 @@ export class SessionPanel { * Stop inspections, probes, and the change request watch, end every follower, and wait for pending work. * @returns settles once pending inspections and probes have ended. */ + /** Publish the review revisions of the bound change requests after a review change was announced. */ + reviewChanged(): void { + this.publish({ ...this.current, changeRequests: this.entries(this.ctx.forgeSession.changeRequests(this.session)) }) + } + async dispose(): Promise { this.lifetime.abort() this.stopWatching() @@ -211,7 +218,8 @@ export class SessionPanel { private entries(changeRequests: readonly SessionChangeRequest[]): ForgePanelChangeRequest[] { return changeRequests.map((entry) => { if (entry.update !== null && 'snapshot' in entry.update) this.snapshots.set(entry.url, entry.update.snapshot) - return { ...entry, snapshot: this.snapshots.get(entry.url) ?? null } + const reviewRevision = entry.ref === null ? 0 : this.reviewRevision(entry.ref) + return { ...entry, snapshot: this.snapshots.get(entry.url) ?? null, reviewRevision } }) } diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 22c641e0d3..afd3525c9e 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -1,7 +1,8 @@ /** Browser-safe panel state, the worktree request record, Remote error codes, and Host configuration of the forge panel. */ import type {} from '@deepseek-ai/dsh-typert-protocol' -import type { ChangeRequestSnapshot, ForgeCommit, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { ChangeRequestRef, ChangeRequestSnapshot, ForgeCommit, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session/types' /** Git facts for the checkout that contains the Session's current directory. */ @@ -185,6 +186,11 @@ export type ForgeChangeRequestStatesFrame = export interface ForgePanelChangeRequest extends SessionChangeRequest { /** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */ readonly snapshot: ChangeRequestSnapshot | null + /** + * Number of review changes `forge/review-changed` announced for the change request since the panel host started; it + * grows when any plugin's write is accepted, so a reader shows threads and viewed marks read after it. + */ + readonly reviewRevision: number } /** Everything the panel shows for one Session. */ @@ -347,6 +353,94 @@ export interface ForgeChangeRequestDiff { readonly fileUrls: Readonly> } +/** Opaque identity of a filter lens, chosen by the plugin that registers it, such as `example/public-interface`. */ +export type ForgeLensId = Branded<'ForgeLensId'> + +/** One changed file a lens classifies: the diff's description of it, without the lines. */ +export type ForgeLensFile = Pick + +/** Lines `start` through `end` of one side of a file, both inclusive and 1-based. */ +export interface ForgeLineRange { + readonly start: number + readonly end: number +} + +/** What a lens keeps of one file. */ +export interface ForgeLensKeep { + /** + * Lines the lens is about on each side; hunks that touch none of them fold into one row the reader can expand. + * Omitted: every hunk of the file shows. + */ + readonly ranges?: { readonly old: readonly ForgeLineRange[]; readonly new: readonly ForgeLineRange[] } +} + +/** The files a lens keeps, by path; a file the result does not name is filtered out. */ +export interface ForgeLensResult { + readonly files: Readonly> +} + +/** What a changes view shows, as a lens sees it. */ +export type ForgeLensSource = + /** Local changes of a Session's checkout in one scope. */ + | { readonly kind: 'local'; readonly scope: ForgeLocalScope } + /** A change request at one head commit, whole or as consecutive commits. */ + | { readonly kind: 'change'; readonly ref: ChangeRequestRef; readonly headSha: string; readonly commits: ForgeCommitRange | null } + +/** What one `classify` call receives. */ +export interface ForgeLensInput { + /** What the view shows. */ + readonly source: ForgeLensSource + /** Every file of the diff in display order, with the layer the panel gave it. */ + readonly files: readonly ForgeLensFile[] + /** + * Read one side of a file of `files`, by its `path`: the old side reads `previousPath` for a renamed file. Resolves to + * null when the side does not exist, as the old side of an added file, or holds binary content. Rejects for a path not + * in `files`, once the reads of one call exceed the panel's `maxLensReadBytes`, for an old side the provider cannot + * locate, and when the read fails. + */ + text(side: 'old' | 'new', path: string, signal: AbortSignal): Promise + /** Report how many of `total` units the lens finished; the changes view shows it while the lens runs. */ + progress(done: number, total: number): void +} + +/** A filter over the files of a changes view, which a plugin registers with `ctx.forgePanel.registerLens()`. */ +export interface ForgeLens { + /** Identity the plugin chooses; one registration holds an id at a time. */ + readonly id: ForgeLensId + /** Changes whenever `classify` may answer differently for the same input, which drops results kept under another version. */ + readonly version: string + /** + * Decide which files the lens keeps and which lines it is about. The signal aborts when the reader stops waiting, the + * registration ends, or `lensTimeoutMs` passes; a rejection fails the request without a partial result. + */ + classify(input: ForgeLensInput, signal: AbortSignal): Promise +} + +/** What a changes view asks a lens to classify: its source, the version of the files it shows, and the lens. */ +export interface ForgeLensRequest { + /** The view's source: local changes in a scope, or a binding URL with its chosen commits. */ + readonly source: + | { readonly kind: 'local'; readonly scope: ForgeLocalScope } + | { readonly kind: 'change'; readonly url: string; readonly commits: ForgeCommitRange | null } + /** `lensVersion` of the files the view shows; files read since with another version refuse the request. */ + readonly version: string + /** Identity of the registered lens. */ + readonly lens: string +} + +/** One frame of a lens request: how far the lens is, then what it keeps. */ +export type ForgeLensFrame = + | { readonly kind: 'progress'; readonly done: number; readonly total: number } + | { readonly kind: 'result'; readonly files: Readonly> } + +/** Facts about the panel's extensions that every changes view reads. */ +export interface ForgeExtensionState { + /** Identities of the registered lenses, in registration order. */ + readonly lenses: readonly string[] + /** Most line annotations a changes view shows in one file, across every annotation source. */ + readonly maxAnnotationsPerFile: number +} + /** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */ export interface ForgeLocalCommits { /** HEAD commit the list was read at. */ @@ -421,6 +515,14 @@ export interface Config { * request's update time does not change when a thread is resolved. */ reviewRefreshMs?: number + /** Deadline in milliseconds for one lens `classify` call. */ + lensTimeoutMs?: number + /** Most UTF-8 bytes of file text one lens `classify` call may read. */ + maxLensReadBytes?: number + /** Most UTF-8 bytes, as JSON, of lens results kept in memory for later requests with the same files, lens, and lens version. */ + maxCachedLensBytes?: number + /** Most line annotations a changes view shows in one file, across every annotation source. */ + maxAnnotationsPerFile?: number } declare module '@deepseek-ai/dsh-typert-protocol' { @@ -486,6 +588,15 @@ declare module '@deepseek-ai/dsh-typert-protocol' { '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 + /** No lens with the requested identity is registered, as after its plugin unloaded. */ + 'forgePanel/lens-missing': Record + /** The files the view shows are no longer the files the panel reads, so the view reads them again before asking. */ + 'forgePanel/lens-stale': Record + /** + * The lens failed, ran past `lensTimeoutMs`, read more than `maxLensReadBytes`, or answered over `maxCachedLensBytes`; + * the message says which. + */ + 'forgePanel/lens-failed': Record } } diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index 064d66d112..8a7c391f56 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -1822,7 +1822,7 @@ describe('forgePanel actions', () => { // The refresh found the same state, which the panel already published. const refreshed = follower.states.at(-1) expect(refreshed?.checkout.state).toBe('none') - expect(refreshed?.changeRequests).toEqual([{ url: 'https://unserved.test/a/b/pull/3', origin: 'created', ref: null, update: null, snapshot: null }]) + expect(refreshed?.changeRequests).toEqual([{ url: 'https://unserved.test/a/b/pull/3', origin: 'created', ref: null, update: null, snapshot: null, reviewRevision: 0 }]) expect(opened.sandbox.calls.length).toBeGreaterThan(inspections) expect(opened.provider.fetches).toEqual([]) expect(opened.provider.probes).toEqual([]) @@ -2060,6 +2060,10 @@ describe('forgePanel configuration', () => { [{ maxBranches: 2.5 }, 'forge-panel: maxBranches must be a positive integer'], [{ maxCachedDiffBytes: 0 }, 'forge-panel: maxCachedDiffBytes must be a positive integer'], [{ maxCommits: 0 }, 'forge-panel: maxCommits must be a positive integer'], + [{ lensTimeoutMs: 0 }, 'forge-panel: lensTimeoutMs must be a positive integer no greater than 2147483647'], + [{ maxLensReadBytes: 0 }, 'forge-panel: maxLensReadBytes must be a positive integer'], + [{ maxCachedLensBytes: -1 }, 'forge-panel: maxCachedLensBytes must be a positive integer'], + [{ maxAnnotationsPerFile: 1.5 }, 'forge-panel: maxAnnotationsPerFile must be a positive integer'], [{ testPaths: ['**/*.spec.*', ' '] }, 'forge-panel: testPaths entries must not be empty'], [{ interfacePaths: [''] }, 'forge-panel: interfacePaths entries must not be empty'], [{ worktreePrefix: '-dsh/' }, prefix], diff --git a/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts b/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts new file mode 100644 index 0000000000..8bb1b1216a --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/lens-panel.host.spec.ts @@ -0,0 +1,375 @@ +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge' +import type { Session } from '@deepseek-ai/dsh-session' +import type { + ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensId, ForgeLensInput, ForgeLensRequest, ForgeLensResult, +} from '../src/index.ts' +import { lensVersion } from '../src/lens-version.ts' +import { bench, follow, git, pullUrl, repository, scratch, shellTurn } from './harness.ts' +import type { Bench } from './harness.ts' + +const cleanups: (() => Promise)[] = [] + +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() +}) + +const signal = new AbortController().signal +const HEAD = 'a'.repeat(40) +const BASE = 'b'.repeat(40) +const MERGE_BASE = 'c'.repeat(40) + +async function project(): Promise { + const { path, remove } = await scratch('dsh-forge-lens-') + cleanups.push(remove) + const repo = await repository(path) + await git(repo, 'remote', 'add', 'origin', 'https://fake.test/octo/demo.git') + await git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + return repo +} + +async function open(repo: string, config: Parameters[1] = {}): Promise { + const opened = await bench(repo, config) + cleanups.push(() => opened.ctx.fiber.dispose()) + return opened +} + +/** Register `lens` from its own plugin fiber, as a third-party plugin does. */ +async function provideLens(ctx: Context, lens: ForgeLens): Promise> { + const fiber = ctx.plugin({ inject: ['forgePanel'], apply(child: Context) { child.forgePanel.registerLens(lens) } }) + await fiber + return fiber +} + +/** A lens that keeps the files whose new side contains `export`, about those lines, recording every side it read. */ +function exportsLens(reads: string[] = [], id = 'fixture/exports'): ForgeLens & { readonly classify: ReturnType } { + return { + id: id as ForgeLensId, + version: '1', + classify: vi.fn(async (input: ForgeLensInput): Promise => { + const files: Record = {} + for (const [index, file] of input.files.entries()) { + const old = await input.text('old', file.path, signal) + const next = await input.text('new', file.path, signal) + reads.push(`${file.path} old=${JSON.stringify(old)} new=${JSON.stringify(next)}`) + input.progress(index + 1, input.files.length) + const lines = (next ?? '').split('\n') + const exported = lines.flatMap((line, at) => line.startsWith('export') ? [{ start: at + 1, end: at + 1 }] : []) + if (exported.length > 0) files[file.path] = { ranges: { old: [], new: exported } } + } + return { files } + }), + } +} + +async function frames(ctx: Context, session: Session, request: ForgeLensRequest): Promise { + const list: ForgeLensFrame[] = [] + for await (const frame of ctx.forgePanel.changesLens(session, request, signal)) list.push(frame) + return list +} + +async function rejection(ctx: Context, session: Session, request: ForgeLensRequest): Promise { + try { + await frames(ctx, session, request) + } catch (error) { + return error + } + throw new Error('the lens request succeeded') +} + +describe('forgePanel lens registrations', () => { + it('lists each registered lens while its plugin is loaded and withdraws it when the plugin unloads', async () => { + const opened = await open(await project(), { maxAnnotationsPerFile: 7 }) + const controller = new AbortController() + const states = opened.ctx.forgePanel.extensions(controller.signal)[Symbol.asyncIterator]() + cleanups.push(async () => { + controller.abort() + await states.return?.() + }) + const empty: ForgeExtensionState = { lenses: [], maxAnnotationsPerFile: 7 } + await expect(states.next()).resolves.toEqual({ done: false, value: empty }) + + const fiber = await provideLens(opened.ctx, exportsLens()) + await expect(states.next()).resolves.toEqual({ done: false, value: { lenses: ['fixture/exports'], maxAnnotationsPerFile: 7 } }) + await expect(provideLens(opened.ctx, exportsLens())).rejects.toThrow('forge-panel: a lens "fixture/exports" is already registered') + await fiber.dispose() + await expect(states.next()).resolves.toEqual({ done: false, value: { lenses: [], maxAnnotationsPerFile: 7 } }) + }) + + it('ends the extension stream when the panel stops', async () => { + const opened = await open(await project()) + const states = opened.ctx.forgePanel.extensions(signal)[Symbol.asyncIterator]() + await states.next() + const waiting = states.next() + await opened.panel.dispose() + await expect(waiting).resolves.toEqual({ done: true, value: undefined }) + }) + + it('returns a disposer that withdraws the lens', async () => { + const opened = await open(await project()) + const dispose = opened.ctx.forgePanel.registerLens(exportsLens()) + await dispose() + const error = await rejection(opened.ctx, opened.session, { source: { kind: 'local', scope: { kind: 'unstaged' } }, version: '', lens: 'fixture/exports' }) + expect(error).toMatchObject({ code: 'forgePanel/lens-missing', message: 'No lens "fixture/exports" is registered' }) + }) +}) + +describe('forgePanel lenses over local changes', () => { + it('classifies the shown files with both sides read in the Session\'s checkout, then reuses the result', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'export const value = 1\n') + await writeFile(join(repo, 'notes.md'), 'hello\n') + await writeFile(join(repo, 'image.bin'), Buffer.from([0, 1, 2])) + const opened = await open(repo) + const reads: string[] = [] + const lens = exportsLens(reads) + await provideLens(opened.ctx, lens) + const scope = { kind: 'branch', base: null, commits: null } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const request: ForgeLensRequest = { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/exports' } + + const first = await frames(opened.ctx, opened.session, request) + expect(first.at(-1)).toEqual({ kind: 'result', files: { 'tracked.txt': { ranges: { old: [], new: [{ start: 1, end: 1 }] } } } }) + expect(first.slice(0, -1).every(frame => frame.kind === 'progress' && frame.total === 3)).toBe(true) + expect(first.length).toBeGreaterThan(1) + expect(reads).toEqual([ + 'tracked.txt old="initial\\n" new="export const value = 1\\n"', + 'image.bin old=null new=null', + 'notes.md old=null new="hello\\n"', + ]) + expect(lens.classify.mock.calls[0]?.[0]).toMatchObject({ source: { kind: 'local', scope } }) + await expect(frames(opened.ctx, opened.session, request)).resolves.toEqual([ + { kind: 'result', files: { 'tracked.txt': { ranges: { old: [], new: [{ start: 1, end: 1 }] } } } }, + ]) + expect(lens.classify).toHaveBeenCalledTimes(1) + }) + + it('reads the old side at HEAD, at the index, and before the first chosen commit', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'staged\n') + await git(repo, 'add', 'tracked.txt') + await writeFile(join(repo, 'tracked.txt'), 'working\n') + const opened = await open(repo) + const reads: string[] = [] + await provideLens(opened.ctx, exportsLens(reads)) + const ask = async (scope: Extract['scope']): Promise => { + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + await frames(opened.ctx, opened.session, { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/exports' }) + } + await ask({ kind: 'branch', base: 'refs/remotes/origin/main', commits: null }) + await ask({ kind: 'uncommitted' }) + await ask({ kind: 'staged' }) + await ask({ kind: 'unstaged' }) + await git(repo, 'commit', '--quiet', '-m', 'staged') + const commit = await git(repo, 'rev-parse', 'HEAD') + await ask({ kind: 'branch', base: null, commits: { from: commit, to: commit } }) + expect(reads).toEqual([ + 'tracked.txt old="initial\\n" new="working\\n"', + 'tracked.txt old="initial\\n" new="working\\n"', + 'tracked.txt old="initial\\n" new="staged\\n"', + 'tracked.txt old="staged\\n" new="working\\n"', + 'tracked.txt old="initial\\n" new="staged\\n"', + ]) + }) + + it('reads a renamed file\'s old side at its previous path and a deleted file\'s new side as missing', async () => { + const repo = await project() + await writeFile(join(repo, 'gone.txt'), 'gone\n') + await git(repo, 'add', 'gone.txt') + await git(repo, 'commit', '--quiet', '-m', 'add gone') + await git(repo, 'mv', 'tracked.txt', 'moved.txt') + await git(repo, 'rm', '--quiet', 'gone.txt') + const opened = await open(repo) + const reads: string[] = [] + await provideLens(opened.ctx, exportsLens(reads)) + const scope = { kind: 'staged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + await frames(opened.ctx, opened.session, { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/exports' }) + expect(reads.sort()).toEqual(['gone.txt old="gone\\n" new=null', 'moved.txt old="initial\\n" new="initial\\n"']) + }) + + it('refuses a request for other files, maps a failed lens, and reports a lens withdrawn while it runs as missing', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'changed\n') + const opened = await open(repo) + const scope = { kind: 'unstaged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const version = lensVersion(files) + await provideLens(opened.ctx, { id: 'fixture/broken' as ForgeLensId, version: '1', classify: async () => { throw new Error('parser crashed') } }) + const started = Promise.withResolvers() + const slow = await provideLens(opened.ctx, { + id: 'fixture/slow' as ForgeLensId, + version: '1', + classify: async () => { + started.resolve(undefined) + return await new Promise(() => {}) + }, + }) + + await expect(rejection(opened.ctx, opened.session, { source: { kind: 'local', scope }, version: 'other', lens: 'fixture/broken' })) + .resolves.toMatchObject({ code: 'forgePanel/lens-stale' }) + await expect(rejection(opened.ctx, opened.session, { source: { kind: 'local', scope }, version, lens: 'fixture/broken' })) + .resolves.toMatchObject({ code: 'forgePanel/lens-failed', message: 'the lens failed: parser crashed' }) + const pending = rejection(opened.ctx, opened.session, { source: { kind: 'local', scope }, version, lens: 'fixture/slow' }) + await started.promise + await slow.dispose() + await expect(pending).resolves.toMatchObject({ code: 'forgePanel/lens-missing', message: 'the lens "fixture/slow" was unregistered' }) + }) + + it('passes a cancellation of the reader on unchanged', async () => { + const repo = await project() + await writeFile(join(repo, 'tracked.txt'), 'changed\n') + const opened = await open(repo) + const scope = { kind: 'unstaged' } as const + const { files } = await opened.ctx.forgePanel.localDiff(opened.session, scope, signal) + const started = Promise.withResolvers() + await provideLens(opened.ctx, { + id: 'fixture/slow' as ForgeLensId, + version: '1', + classify: async () => { + started.resolve(undefined) + return await new Promise(() => {}) + }, + }) + const controller = new AbortController() + const iterator = opened.ctx.forgePanel.changesLens(opened.session, { source: { kind: 'local', scope }, version: lensVersion(files), lens: 'fixture/slow' }, + controller.signal)[Symbol.asyncIterator]() + const next = iterator.next() + await started.promise + controller.abort(new Error('view closed')) + await expect(next).rejects.toThrow('view closed') + }) +}) + +describe('forgePanel lenses over change requests', () => { + const PATCH = [ + 'diff --git a/src/a.ts b/src/a.ts', '--- a/src/a.ts', '+++ b/src/a.ts', '@@ -1 +1 @@', '-const a = 1', '+export const a = 1', + 'diff --git a/src/old.ts b/src/new.ts', 'similarity index 90%', 'rename from src/old.ts', 'rename to src/new.ts', + '--- a/src/old.ts', '+++ b/src/new.ts', '@@ -1 +1 @@', '-old', '+export new', + 'diff --git a/src/added.ts b/src/added.ts', 'new file mode 100644', '--- /dev/null', '+++ b/src/added.ts', '@@ -0,0 +1 @@', '+added', + '', + ].join('\n') + + async function bound(overrides: Partial<{ baseSha: string | undefined }> = { baseSha: BASE }): Promise { + const opened = await open(await project()) + opened.provider.overrides.set(7, { headSha: HEAD, ...overrides }) + opened.provider.patches.set(7, PATCH) + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + const follower = follow(opened.ctx, opened.session) + cleanups.push(follower.stop) + await follower.until(state => state.changeRequests.some(entry => entry.snapshot !== null)) + return opened + } + + it('reads the new side at the head and the old side at the merge base the provider names', async () => { + const opened = await bound() + const mergeBase = vi.fn(async () => MERGE_BASE) + Object.assign(opened.provider, { mergeBase }) + opened.provider.texts.set(`${HEAD}:src/a.ts`, 'export const a = 1\n') + opened.provider.texts.set(`${MERGE_BASE}:src/a.ts`, 'const a = 1\n') + opened.provider.texts.set(`${HEAD}:src/new.ts`, 'export new\n') + opened.provider.texts.set(`${MERGE_BASE}:src/old.ts`, 'old\n') + const reads: string[] = [] + const lens = exportsLens(reads) + await provideLens(opened.ctx, lens) + const { files } = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) + + const result = await frames(opened.ctx, opened.session, + { source: { kind: 'change', url: pullUrl(7), commits: null }, version: lensVersion(files), lens: 'fixture/exports' }) + expect(result.at(-1)).toEqual({ kind: 'result', files: { + 'src/a.ts': { ranges: { old: [], new: [{ start: 1, end: 1 }] } }, + 'src/new.ts': { ranges: { old: [], new: [{ start: 1, end: 1 }] } }, + } }) + expect(reads).toEqual([ + 'src/a.ts old="const a = 1\\n" new="export const a = 1\\n"', + 'src/new.ts old="old\\n" new="export new\\n"', + 'src/added.ts old=null new=null', + ]) + expect(mergeBase).toHaveBeenCalledTimes(1) + expect(mergeBase).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), BASE, HEAD, expect.any(AbortSignal)) + expect(lens.classify.mock.calls[0]?.[0]).toMatchObject({ source: { kind: 'change', headSha: HEAD, commits: null, ref: { number: 7 } } }) + }) + + it('reads the old side of chosen commits at the first one\'s parent', async () => { + const opened = await bound() + const first = 'd'.repeat(40) + const parent = 'e'.repeat(40) + const list: ForgeCommitList = { headSha: HEAD, truncated: false, commits: [ + { sha: first, parent, title: 'first', author: null, authoredAt: '2026-11-01T00:00:00Z' }, + { sha: HEAD, parent: first, title: 'head', author: null, authoredAt: '2026-11-02T00:00:00Z' }, + ] } + opened.provider.commitLists.set(7, list) + opened.provider.comparisons.set(`${parent}..${first}`, PATCH) + opened.provider.texts.set(`${parent}:src/a.ts`, 'parent\n') + opened.provider.texts.set(`${first}:src/a.ts`, 'first\n') + const reads: string[] = [] + await provideLens(opened.ctx, exportsLens(reads)) + const commits = { from: first, to: first } + const { files } = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), commits, signal) + + await frames(opened.ctx, opened.session, { source: { kind: 'change', url: pullUrl(7), commits }, version: lensVersion(files), lens: 'fixture/exports' }) + expect(reads[0]).toBe('src/a.ts old="parent\\n" new="first\\n"') + // A missing file reads as an absent side. + expect(reads[1]).toBe('src/new.ts old=null new=null') + }) + + it('fails reads of an old side the provider cannot locate and retries a failed merge base lookup', async () => { + const withoutBase = await bound({ baseSha: undefined }) + await provideLens(withoutBase.ctx, exportsLens()) + const { files } = await withoutBase.ctx.forgePanel.changeRequestDiff(withoutBase.session, pullUrl(7), null, signal) + const request: ForgeLensRequest = { source: { kind: 'change', url: pullUrl(7), commits: null }, version: lensVersion(files), lens: 'fixture/exports' } + await expect(rejection(withoutBase.ctx, withoutBase.session, request)).resolves.toMatchObject({ + code: 'forgePanel/lens-failed', message: 'the lens failed: The code host provider reports no base commit to read the old side at', + }) + + const flaky = await bound() + const mergeBase = vi.fn() + .mockResolvedValueOnce({ code: 'unavailable', message: 'compare failed' }) + .mockResolvedValue(MERGE_BASE) + Object.assign(flaky.provider, { mergeBase }) + flaky.provider.texts.set(`${HEAD}:src/a.ts`, 'export const a = 1\n') + flaky.provider.texts.set(`${MERGE_BASE}:src/a.ts`, 'const a = 1\n') + await provideLens(flaky.ctx, { + id: 'fixture/retry' as ForgeLensId, + version: '1', + classify: async (input) => { + await expect(input.text('old', 'src/a.ts', signal)).rejects.toThrow('compare failed') + expect(await input.text('old', 'src/a.ts', signal)).toBe('const a = 1\n') + return { files: {} } + }, + }) + await expect(frames(flaky.ctx, flaky.session, { ...request, lens: 'fixture/retry' })).resolves.toEqual([{ kind: 'result', files: {} }]) + expect(mergeBase).toHaveBeenCalledTimes(2) + }) + + it('fails a file read the host refuses and refuses a change request whose status is not read', async () => { + const opened = await bound() + opened.provider.texts.set(`${HEAD}:src/a.ts`, { code: 'too-large', message: 'file over the contents limit' }) + await provideLens(opened.ctx, { + id: 'fixture/new-only' as ForgeLensId, + version: '1', + classify: async (input) => { + await input.text('new', 'src/a.ts', signal) + return { files: {} } + }, + }) + const { files } = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) + const request: ForgeLensRequest = { source: { kind: 'change', url: pullUrl(7), commits: null }, version: lensVersion(files), lens: 'fixture/new-only' } + await expect(rejection(opened.ctx, opened.session, request)) + .resolves.toMatchObject({ code: 'forgePanel/lens-failed', message: 'the lens failed: file over the contents limit' }) + + const unread = await open(await project()) + unread.provider.failures.set(9, { code: 'unavailable', message: 'down' }) + shellTurn(unread.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(9)}\n` }]) + const follower = follow(unread.ctx, unread.session) + cleanups.push(follower.stop) + await follower.until(state => state.changeRequests.some(entry => entry.update !== null)) + await provideLens(unread.ctx, exportsLens()) + await expect(rejection(unread.ctx, unread.session, { source: { kind: 'change', url: pullUrl(9), commits: null }, version: '', lens: 'fixture/exports' })) + .resolves.toMatchObject({ code: 'forgePanel/lens-stale', message: 'The change request status has not been read yet' }) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/lenses.host.spec.ts b/packages/experimental/client-ui-forge/tests/lenses.host.spec.ts new file mode 100644 index 0000000000..e49e08d535 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/lenses.host.spec.ts @@ -0,0 +1,241 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { ForgeLens, ForgeLensFile, ForgeLensFrame, ForgeLensId, ForgeLensInput, ForgeLensResult } from '../src/types.ts' +import { LensCache, LensFailed, lensFrames, LensRegistry, LensWithdrawn, runLens } from '../src/lenses.ts' +import type { LensRegistration, LensSubject } from '../src/lenses.ts' +import { lensVersion } from '../src/lens-version.ts' + +afterEach(() => { + vi.useRealTimers() +}) + +const limits = { timeoutMs: 1_000, maxReadBytes: 64, maxResultBytes: 1_024 } + +function file(path: string, overrides: Partial = {}): ForgeLensFile { + return { path, previousPath: null, status: 'modified', binary: false, layer: 'implementation', hunks: [], digest: `d-${path}`, ...overrides } +} + +function lens(classify: (input: ForgeLensInput, signal: AbortSignal) => Promise, id = 'test/lens'): ForgeLens { + return { id: id as ForgeLensId, version: '1', classify } +} + +function subject(files: readonly ForgeLensFile[], read: LensSubject['read'] = async (side, target) => `${side}:${target.path}`): LensSubject { + return { source: { kind: 'local', scope: { kind: 'unstaged' } }, files, read } +} + +/** Register `target` and return its registration and disposer. */ +function registered(target: ForgeLens): { registry: LensRegistry; registration: LensRegistration; dispose: () => Promise } { + const registry = new LensRegistry() + const dispose = registry.add(target) + const registration = registry.get(target.id) + if (registration === undefined) throw new Error('not registered') + return { registry, registration, dispose } +} + +async function collect(frames: AsyncIterable): Promise { + const list: ForgeLensFrame[] = [] + for await (const frame of frames) list.push(frame) + return list +} + +describe('LensRegistry', () => { + it('refuses a second registration of one identity and frees it once the first ends', async () => { + const registry = new LensRegistry() + const first = lens(async () => ({ files: {} })) + const dispose = registry.add(first) + expect(() => registry.add(lens(async () => ({ files: {} })))).toThrow('forge-panel: a lens "test/lens" is already registered') + expect(registry.get('test/lens')?.lens).toBe(first) + await dispose() + expect(registry.get('test/lens')).toBeUndefined() + await registry.add(first)() + }) + + it('streams the identities after each change, collapsing changes a busy reader missed, until the registry closes', async () => { + const registry = new LensRegistry() + const controller = new AbortController() + const iterator = registry.follow(controller.signal)[Symbol.asyncIterator]() + await expect(iterator.next()).resolves.toEqual({ done: false, value: [] }) + const a = registry.add(lens(async () => ({ files: {} }), 'a')) + registry.add(lens(async () => ({ files: {} }), 'b')) + await expect(iterator.next()).resolves.toEqual({ done: false, value: ['a', 'b'] }) + await a() + await expect(iterator.next()).resolves.toEqual({ done: false, value: ['b'] }) + const waiting = iterator.next() + registry.close() + await expect(waiting).resolves.toEqual({ done: true, value: undefined }) + + const stopped = registry.follow(controller.signal)[Symbol.asyncIterator]() + await expect(stopped.next()).resolves.toEqual({ done: true, value: undefined }) + }) + + it('ends a follow stream when its own signal aborts', async () => { + const registry = new LensRegistry() + const controller = new AbortController() + const iterator = registry.follow(controller.signal)[Symbol.asyncIterator]() + await iterator.next() + const waiting = iterator.next() + controller.abort() + await expect(waiting).resolves.toEqual({ done: true, value: undefined }) + }) + + it('aborts a running classification when its registration ends and waits for the run', async () => { + const started = Promise.withResolvers() + const { registration, dispose } = registered(lens(async (_input, signal) => { + started.resolve(signal) + return await new Promise(() => {}) + })) + const run = runLens(registration, subject([]), limits, new AbortController().signal, () => {}) + const signal = await started.promise + await dispose() + expect(signal.aborted).toBe(true) + await expect(run).rejects.toBeInstanceOf(LensWithdrawn) + }) +}) + +describe('runLens', () => { + it('passes the source, files, and reader, and keeps only paths of the diff', async () => { + const files = [file('a.ts'), file('b.ts', { status: 'added' })] + const { registration } = registered(lens(async (input) => { + expect(input.source).toEqual({ kind: 'local', scope: { kind: 'unstaged' } }) + expect(input.files).toBe(files) + expect(await input.text('new', 'a.ts', new AbortController().signal)).toBe('new:a.ts') + return { files: { 'a.ts': { ranges: { old: [], new: [{ start: 1, end: 2 }] } }, 'gone.ts': {} } } + })) + await expect(runLens(registration, subject(files), limits, new AbortController().signal, () => {})) + .resolves.toEqual({ 'a.ts': { ranges: { old: [], new: [{ start: 1, end: 2 }] } } }) + }) + + it('refuses a path outside the diff and counts no text for a missing side', async () => { + const { registration } = registered(lens(async (input) => { + await expect(input.text('old', 'other.ts', new AbortController().signal)).rejects.toThrow('"other.ts" is not a file of this diff') + for (let index = 0; index < 100; index += 1) expect(await input.text('old', 'a.ts', new AbortController().signal)).toBeNull() + return { files: { 'a.ts': {} } } + })) + await expect(runLens(registration, subject([file('a.ts')], async () => null), limits, new AbortController().signal, () => {})) + .resolves.toEqual({ 'a.ts': {} }) + }) + + it('fails once the reads exceed the budget, even when the lens swallows the refusal', async () => { + const text = 'x'.repeat(40) + const reads: string[] = [] + const greedy = registered(lens(async (input) => { + reads.push(String(await input.text('new', 'a.ts', new AbortController().signal))) + await input.text('new', 'a.ts', new AbortController().signal) + return { files: {} } + })) + await expect(runLens(greedy.registration, subject([file('a.ts')], async () => text), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens read more than maxLensReadBytes (64 bytes) of file text')) + expect(reads).toEqual([text]) + + const swallowing = registered(lens(async (input) => { + await input.text('new', 'a.ts', new AbortController().signal) + await input.text('new', 'a.ts', new AbortController().signal).catch(() => null) + await expect(input.text('new', 'a.ts', new AbortController().signal)).rejects.toBeInstanceOf(LensFailed) + return { files: {} } + })) + await expect(runLens(swallowing.registration, subject([file('a.ts')], async () => text), limits, new AbortController().signal, () => {})) + .rejects.toBeInstanceOf(LensFailed) + }) + + it('fails a lens that runs past the deadline even when it ignores its signal', async () => { + vi.useFakeTimers() + const { registration } = registered(lens(async () => await new Promise(() => {}))) + const run = runLens(registration, subject([]), limits, new AbortController().signal, () => {}) + const outcome = expect(run).rejects.toThrow(new LensFailed('the lens ran past lensTimeoutMs (1000 ms)')) + await vi.advanceTimersByTimeAsync(1_000) + await outcome + }) + + it('names the cause of a rejected lens, including a thrown value that is not an error and a synchronous throw', async () => { + const failing = registered(lens(async () => { throw new Error('parser crashed') })) + await expect(runLens(failing.registration, subject([]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens failed: parser crashed')) + const odd = registered(lens(async () => { throw 'nope' })) + await expect(runLens(odd.registration, subject([]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens failed: nope')) + const sync = registered({ id: 'sync' as ForgeLensId, version: '1', classify: () => { throw new Error('at once') } }) + await expect(runLens(sync.registration, subject([]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens failed: at once')) + }) + + it('fails a result over the bound', async () => { + const { registration } = registered(lens(async () => ({ files: { 'a.ts': { ranges: { old: [], new: Array.from({ length: 100 }, (_v, start) => ({ start, end: start })) } } } }))) + await expect(runLens(registration, subject([file('a.ts')]), limits, new AbortController().signal, () => {})) + .rejects.toThrow(new LensFailed('the lens result exceeds maxCachedLensBytes (1024 bytes)')) + }) + + it('rethrows the caller\'s reason and stops reporting progress once the caller aborts', async () => { + const controller = new AbortController() + const progress = vi.fn() + const reported = Promise.withResolvers() + const { registration } = registered(lens(async (input) => { + input.progress(1, 2) + reported.resolve(input) + return await new Promise(() => {}) + })) + const run = runLens(registration, subject([]), limits, controller.signal, progress) + const input = await reported.promise + controller.abort(new Error('reader left')) + await expect(run).rejects.toThrow('reader left') + input.progress(2, 2) + expect(progress.mock.calls).toEqual([[1, 2]]) + }) +}) + +describe('lensFrames', () => { + it('yields the latest progress since the previous frame, then the result', async () => { + const step = Promise.withResolvers() + const finish = Promise.withResolvers() + const frames = lensFrames(async (progress) => { + progress(1, 3) + progress(2, 3) + await step.promise + progress(3, 3) + await finish.promise + return { 'a.ts': {} } + })[Symbol.asyncIterator]() + await expect(frames.next()).resolves.toEqual({ done: false, value: { kind: 'progress', done: 2, total: 3 } }) + step.resolve(undefined) + await expect(frames.next()).resolves.toEqual({ done: false, value: { kind: 'progress', done: 3, total: 3 } }) + finish.resolve(undefined) + await expect(frames.next()).resolves.toEqual({ done: false, value: { kind: 'result', files: { 'a.ts': {} } } }) + await expect(frames.next()).resolves.toEqual({ done: true, value: undefined }) + }) + + it('drops progress reported as the run finishes and passes a failure on', async () => { + await expect(collect(lensFrames(async (progress) => { + progress(1, 1) + return {} + }))).resolves.toEqual([{ kind: 'result', files: {} }]) + await expect(collect(lensFrames(async () => { throw new LensFailed('broken') }))).rejects.toThrow('broken') + }) +}) + +describe('LensCache', () => { + it('keeps results up to its bound, dropping the least recently used and replacing equal keys', () => { + const one = { 'a.ts': {} } + const size = Buffer.byteLength(JSON.stringify(one)) + const cache = new LensCache(size * 2) + cache.set('a', one) + cache.set('b', { 'b.ts': {} }) + expect(cache.get('a')).toBe(one) + cache.set('c', { 'c.ts': {} }) + expect(cache.get('b')).toBeUndefined() + expect(cache.get('a')).toBe(one) + const replaced = { 'c.ts': {} } + cache.set('c', replaced) + expect(cache.get('c')).toBe(replaced) + expect(cache.get('a')).toBe(one) + }) +}) + +describe('lensVersion', () => { + it('changes with any path, digest, or order and is stable otherwise', () => { + const files = [{ path: 'a.ts', digest: '1' }, { path: 'b.ts', digest: '2' }] + expect(lensVersion(files)).toBe(lensVersion([...files])) + expect(lensVersion(files)).toMatch(/^[0-9a-f]{14}$/) + expect(new Set([ + lensVersion(files), lensVersion([...files].reverse()), lensVersion([{ path: 'a.ts', digest: '3' }, files[1]!]), + lensVersion([{ path: 'a.t', digest: 's1' }, files[1]!]), lensVersion([]), + ]).size).toBe(5) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts index 79e7653bfc..cd4a2caa08 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts @@ -8,7 +8,7 @@ import { gitIn, inspectCheckout } from '../src/git.ts' import type { Inspection } from '../src/git.ts' import { aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, forkPoint, localChanges, - localCommits, localDiff, localText, NoForkPoint, + localCommits, localDiff, localOldText, localText, NoForkPoint, } from '../src/local-diff.ts' import type { DiffConfig, ForkPoint } from '../src/local-diff.ts' import { FileLayers } from '../src/layers.ts' @@ -469,6 +469,51 @@ describe('commits of the branch scope', () => { }) }) +describe('localOldText', () => { + it('reads the old side at the fork point, HEAD, the index, or before the first chosen commit', async () => { + const { repo, fork } = await forked(await directory()) + await writeFile(join(repo, 'staged.txt'), 'edited after staging\n') + const ctx = await context(repo) + const point: ForkPoint = { commit: fork, label: 'origin/main', worktree: false } + const committed = await git(repo, 'rev-parse', 'HEAD') + const read = (scope: ForgeLocalScope, path: string, at: ForkPoint | null = null): Promise => + localOldText(ctx, CONFIG, plainSession(repo), repo, scope, at, path, signal) + + await expect(read({ kind: 'branch', base: null, commits: null }, 'tracked.txt', point)).resolves.toBe('initial\n') + await expect(read({ kind: 'branch', base: null, commits: null }, 'committed.txt', point)).resolves.toBeNull() + await expect(read({ kind: 'uncommitted' }, 'committed.txt')).resolves.toBe('one\n') + await expect(read({ kind: 'staged' }, 'staged.txt')).resolves.toBeNull() + await expect(read({ kind: 'unstaged' }, 'staged.txt')).resolves.toBe('staged\n') + await expect(read({ kind: 'branch', base: null, commits: { from: committed, to: committed } }, 'tracked.txt', point)).resolves.toBe('initial\n') + }) + + it('reads binary content and the parent of a root commit as missing', async () => { + const { repo } = await forked(await directory()) + await writeFile(join(repo, 'blob.bin'), Uint8Array.from([0x61, 0, 0x62])) + await git(repo, 'add', 'blob.bin') + await git(repo, 'commit', '--quiet', '-m', 'blob') + const ctx = await context(repo) + const root = await git(repo, 'rev-list', '--max-parents=0', 'HEAD') + + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'unstaged' }, null, 'blob.bin', signal)).resolves.toBeNull() + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'branch', base: null, commits: { from: root, to: root } }, + { commit: root, label: 'root', worktree: false }, 'tracked.txt', signal)).resolves.toBeNull() + }) + + it('refuses a path outside the checkout, a branch without a fork point, and a chosen commit that is not an object name', async () => { + const { repo, fork } = await forked(await directory()) + const ctx = await context(repo) + const point: ForkPoint = { commit: fork, label: 'origin/main', worktree: false } + + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'unstaged' }, null, '../outside.txt', signal)) + .rejects.toThrow('is not a path inside the checkout') + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'branch', base: null, commits: null }, null, 'tracked.txt', signal)) + .rejects.toBeInstanceOf(NoForkPoint) + await expect(localOldText(ctx, CONFIG, plainSession(repo), repo, { kind: 'branch', base: null, commits: { from: 'HEAD', to: 'HEAD' } }, point, + 'tracked.txt', signal)).rejects.toBeInstanceOf(CommitsMissing) + }) +}) + describe('localText', () => { const branch: ForgeLocalScope = { kind: 'branch', base: null, commits: null } 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 dd9c41145a..c0b85fc02a 100644 --- a/packages/experimental/client-ui-forge/tests/review.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review.host.spec.ts @@ -47,6 +47,25 @@ function polledAt(state: ForgePanelState, url: string, headSha = HEAD, updatedAt } describe('forgePanel change request reviews', () => { + it('reports each accepted review change of any plugin on the bound entry and reads the threads again after 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, writeReview: async () => ({ ok: true }) }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + const polled = await follower.until(state => polledAt(state, pullUrl(7))) + expect(polled.changeRequests[0]?.reviewRevision).toBe(0) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal) + const ref = polled.changeRequests[0]?.ref + if (ref === null || ref === undefined) throw new Error('unbound') + + // Another plugin writes through `ctx.forge`, not through this panel. + await panel.ctx.forge.writeReview(ref, { kind: 'resolve', headSha: HEAD, thread: 'thread-1' as ForgeThreadId, resolved: true }, signal) + await follower.until(state => state.changeRequests[0]?.reviewRevision === 1) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal) + expect(readReview).toHaveBeenCalledTimes(2) + }) + + 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)) diff --git a/packages/experimental/client-ui-forge/tsconfig.client.json b/packages/experimental/client-ui-forge/tsconfig.client.json index 6bc548094f..779c176d28 100644 --- a/packages/experimental/client-ui-forge/tsconfig.client.json +++ b/packages/experimental/client-ui-forge/tsconfig.client.json @@ -9,6 +9,7 @@ "src/client", "src/commit-range.ts", "src/css-modules.d.ts", + "src/lens-version.ts", "src/types.ts" ], "references": [ @@ -66,6 +67,9 @@ { "path": "../../typert/protocol" }, + { + "path": "../../util/brand" + }, { "path": "../../util/values" }, diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index 051f252042..d92dfcba55 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -12,6 +12,8 @@ "src/git.ts", "src/local-diff.ts", "src/layers.ts", + "src/lens-version.ts", + "src/lenses.ts", "src/panel.ts", "src/parse.ts", "src/patch-cache.ts", @@ -67,6 +69,9 @@ { "path": "../../typert/protocol" }, + { + "path": "../../util/brand" + }, { "path": "../../util/timeout" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65f0388b77..74ece9e6ae 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9261,6 +9261,9 @@ importers: packages/experimental/client-ui-forge: dependencies: + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand '@deepseek-ai/dsh-storage-domain': specifier: workspace:* version: link:../../storage/storage-domain