diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffHighlightFiles.ts b/apps/mobile/src/features/diffs/nativeReviewDiffHighlightFiles.ts new file mode 100644 index 0000000000000..e4e2522cddd30 --- /dev/null +++ b/apps/mobile/src/features/diffs/nativeReviewDiffHighlightFiles.ts @@ -0,0 +1,60 @@ +import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel"; +import { createNativeReviewDiffSourceLoader } from "./nativeReviewDiffSource"; +import type { NativeReviewDiffFile, NativeReviewDiffSource } from "./nativeReviewDiffTypes"; + +type SourceRequest = () => Promise; + +interface SourceSnapshot { + readonly firstFile: ReviewRenderableFile; + readonly scope: string; + readonly load: ReturnType>; + readonly requests: WeakMap< + ReviewRenderableFile, + { readonly completePatch: boolean; readonly request: SourceRequest } + >; +} + +export function createDiffHighlightCache(): { snapshot?: SourceSnapshot } { + return {}; +} + +/** + * Gives each file a loader for its whole old and new contents, so a hunk that starts inside a + * docstring or an embedded script block is tokenized with the lines above it. `scope` names + * everything `fetchFile` reads; a new scope or a new first file starts a new snapshot. + */ +export function withDiffSourceLoaders( + scope: string, + parsed: ReviewParsedDiff, + files: ReadonlyArray, + fetchFile: (file: ReviewRenderableFile) => Promise, + cache = createDiffHighlightCache(), +): ReadonlyArray { + if (parsed.kind !== "files" || !parsed.files[0]) return files; + const byId = new Map(parsed.files.map((file) => [file.id, file])); + const firstFile = parsed.files[0]; + // Appended pages share one loader budget; a new first file starts a new snapshot. + let snapshot = cache.snapshot; + if (!snapshot || snapshot.firstFile !== firstFile || snapshot.scope !== scope) { + snapshot = { + firstFile, + scope, + load: createNativeReviewDiffSourceLoader((request) => request()), + requests: new WeakMap(), + }; + cache.snapshot = snapshot; + } + const { load, requests } = snapshot; + return files.map((nativeFile) => { + const file = byId.get(nativeFile.id); + if (!file) return nativeFile; + const completePatch = parsed.notice === null && !!file.completePatchSource; + const cached = requests.get(file); + if (cached?.completePatch === completePatch) + return { ...nativeFile, loadContents: (signal) => load(cached.request, signal) }; + const request: SourceRequest = async () => + completePatch && file.completePatchSource ? file.completePatchSource() : fetchFile(file); + requests.set(file, { completePatch, request }); + return { ...nativeFile, loadContents: (signal) => load(request, signal) }; + }); +} diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.ts index 8d9432368f7e8..e6c3bcbd2a5bf 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffHighlightFiles.ts @@ -7,14 +7,17 @@ import type { PullRequestDiffFileContentsResult, } from "@t3tools/contracts"; -import { createNativeReviewDiffSourceLoader } from "../diffs/nativeReviewDiffSource"; +import { + createDiffHighlightCache, + withDiffSourceLoaders, +} from "../diffs/nativeReviewDiffHighlightFiles"; import { diffHighlightTraceHash, diffHighlightTraceId, traceDiffHighlight, } from "../diffs/nativeReviewDiffTrace"; -import type { NativeReviewDiffFile, NativeReviewDiffSource } from "../diffs/nativeReviewDiffTypes"; -import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel"; +import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes"; +import type { ReviewParsedDiff } from "../review/reviewModel"; import type { pullRequestTarget } from "./usePullRequestDiff"; type FetchContents = (request: { @@ -22,21 +25,7 @@ type FetchContents = (request: { readonly input: PullRequestDiffFileContentsInput; }) => Promise>; -type SourceRequest = () => Promise; - -interface SourceSnapshot { - readonly firstFile: ReviewRenderableFile; - readonly scope: string; - readonly load: ReturnType>; - readonly requests: WeakMap< - ReviewRenderableFile, - { readonly completePatch: boolean; readonly request: SourceRequest } - >; -} - -export function createPullRequestDiffHighlightCache(): { snapshot?: SourceSnapshot } { - return {}; -} +export const createPullRequestDiffHighlightCache = createDiffHighlightCache; export function createPullRequestDiffHighlightFiles( source: { @@ -49,7 +38,6 @@ export function createPullRequestDiffHighlightFiles( cache = createPullRequestDiffHighlightCache(), ): ReadonlyArray { if (parsed.kind !== "files" || !parsed.files[0]) return files; - const byId = new Map(parsed.files.map((file) => [file.id, file])); const { target, commit } = source; traceDiffHighlight("source-target", { environment: diffHighlightTraceHash(target.environmentId), @@ -65,28 +53,11 @@ export function createPullRequestDiffHighlightFiles( target.input.host, commit, ]); - const firstFile = parsed.files[0]; - // Appended pages share one loader budget; a new first file starts a new snapshot. - let snapshot = cache.snapshot; - if (!snapshot || snapshot.firstFile !== firstFile || snapshot.scope !== scope) { - snapshot = { - firstFile, - scope, - load: createNativeReviewDiffSourceLoader((request) => request()), - requests: new WeakMap(), - }; - cache.snapshot = snapshot; - } - const { load, requests } = snapshot; - return files.map((nativeFile) => { - const file = byId.get(nativeFile.id); - if (!file) return nativeFile; - const completePatch = parsed.notice === null && !!file.completePatchSource; - const cached = requests.get(file); - if (cached?.completePatch === completePatch) - return { ...nativeFile, loadContents: (signal) => load(cached.request, signal) }; - const request: SourceRequest = async () => { - if (completePatch && file.completePatchSource) return file.completePatchSource(); + return withDiffSourceLoaders( + scope, + parsed, + files, + async (file) => { traceDiffHighlight("source-params", { file: diffHighlightTraceId(file.id), oldPath: diffHighlightTraceHash(file.previousPath ?? file.path), @@ -106,8 +77,7 @@ export function createPullRequestDiffHighlightFiles( }); if (result._tag !== "Success") throw squashAtomCommandFailure(result); return result.value; - }; - requests.set(file, { completePatch, request }); - return { ...nativeFile, loadContents: (signal) => load(request, signal) }; - }); + }, + cache, + ); } diff --git a/apps/mobile/src/features/review/reviewDiffHighlightFiles.test.ts b/apps/mobile/src/features/review/reviewDiffHighlightFiles.test.ts new file mode 100644 index 0000000000000..f11f121433301 --- /dev/null +++ b/apps/mobile/src/features/review/reviewDiffHighlightFiles.test.ts @@ -0,0 +1,125 @@ +import { highlightCode } from "../../lib/highlights"; + +import { + EnvironmentId, + GitCommandError, + type ReviewDiffFileContentsResult, +} from "@t3tools/contracts"; +import { Cause } from "effect"; +import { AsyncResult } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; + +import { highlightNativeReviewDiffVisibleRows } from "../diffs/nativeReviewDiffHighlighter"; +import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter"; +import { createReviewDiffHighlightFiles } from "./reviewDiffHighlightFiles"; +import { buildReviewParsedDiff } from "./reviewModel"; + +vi.mock("react-native-nitro-modules", async () => { + const { createWasmHighlightsModule } = await import("../../lib/highlights.testing"); + const highlights = createWasmHighlightsModule(); + return { NitroModules: { hasHybridObject: () => true, createHybridObject: () => highlights } }; +}); + +const source = { + environmentId: EnvironmentId.make("environment"), + cwd: "/repo", + sourceKind: "revision-range" as const, + baseRef: "turn-start", + headRef: "refs/t3/turn/2", + diffKey: "turn:2", +}; +const docstring = (line: string) => + ["def load():", ' """', " Reads settings.", "", " Notes:", line, ' """', ""].join( + "\n", + ); +const oldContents = docstring(" the result is not a dict of dicts"); +const newContents = docstring(" the result is and is not a dict"); +const patch = [ + "diff --git a/settings.py b/settings.py", + "--- a/settings.py", + "+++ b/settings.py", + "@@ -5,3 +5,3 @@ def load():", + " Notes:", + "- the result is not a dict of dicts", + "+ the result is and is not a dict", + ' """', + "diff --git a/top.py b/top.py", + "--- a/top.py", + "+++ b/top.py", + "@@ -1,2 +1,2 @@", + "-x = 1", + "+x = 2", + " y = 3", + "", +].join("\n"); + +function setup() { + const parsed = buildReviewParsedDiff(patch, "scope"); + const data = buildNativeReviewDiffData(parsed); + return { parsed, data }; +} + +it("colours a hunk inside a docstring from the whole file, and leaves files that start at the top", async () => { + const { parsed, data } = setup(); + const fetch = vi.fn(async () => AsyncResult.success({ oldContents, newContents })); + const files = createReviewDiffHighlightFiles(source, parsed, data.files, fetch); + + expect(files[1]!.loadContents).toBeUndefined(); + const rowIndex = data.rows.findIndex( + (row) => row.kind === "line" && row.content === " the result is and is not a dict", + ); + const result = await highlightNativeReviewDiffVisibleRows({ + rows: data.rows, + files, + scheme: "dark", + firstRowIndex: rowIndex, + lastRowIndex: rowIndex, + overscanRows: 0, + }); + + expect(fetch).toHaveBeenCalledExactlyOnceWith({ + environmentId: source.environmentId, + input: { + cwd: "/repo", + sourceKind: "revision-range", + changeType: "change", + baseRef: "turn-start", + headRef: "refs/t3/turn/2", + oldPath: "settings.py", + newPath: "settings.py", + }, + }); + expect(result.tokensByRowId[data.rows[rowIndex]!.id]).toEqual( + highlightCode(newContents, "python", "dark")[5], + ); +}); + +it("keeps patch colours and stops asking for a file the server cannot read", async () => { + const { parsed, data } = setup(); + const error = new GitCommandError({ + operation: "read", + command: "git", + cwd: "/repo", + detail: "Git output exceeded the size limit.", + }); + const fetch = vi.fn(async () => + AsyncResult.failure(Cause.fail(error)), + ); + const files = createReviewDiffHighlightFiles(source, parsed, data.files, fetch); + + const highlight = (withFiles: typeof files) => + highlightNativeReviewDiffVisibleRows({ + rows: data.rows, + files: withFiles, + scheme: "dark", + firstRowIndex: 0, + lastRowIndex: data.rows.length - 1, + overscanRows: 0, + }); + + expect((await highlight(files)).tokensByRowId).toEqual( + (await highlight(data.files)).tokensByRowId, + ); + expect(await files[0]!.loadContents!()).toBeNull(); + expect(fetch).toHaveBeenCalledTimes(1); +}); diff --git a/apps/mobile/src/features/review/reviewDiffHighlightFiles.ts b/apps/mobile/src/features/review/reviewDiffHighlightFiles.ts new file mode 100644 index 0000000000000..9211655888403 --- /dev/null +++ b/apps/mobile/src/features/review/reviewDiffHighlightFiles.ts @@ -0,0 +1,90 @@ +import { + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { + EnvironmentAuthorizationError, + ReviewDiffPreviewError, + type EnvironmentId, + type ReviewDiffFileContentsInput, + type ReviewDiffFileContentsResult, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +import { + createDiffHighlightCache, + withDiffSourceLoaders, +} from "../diffs/nativeReviewDiffHighlightFiles"; +import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes"; +import type { ReviewParsedDiff, ReviewRenderableFile } from "./reviewModel"; + +export interface ReviewDiffContentsSource { + readonly environmentId: EnvironmentId; + readonly cwd: string; + readonly sourceKind: ReviewDiffFileContentsInput["sourceKind"]; + readonly baseRef: string | null; + readonly headRef: string | null; + /** Changes whenever the diff does, so contents read for an older diff are not reused. */ + readonly diffKey: string; +} + +type FetchContents = (request: { + readonly environmentId: EnvironmentId; + readonly input: ReviewDiffFileContentsInput; +}) => Promise>; + +const isServerAnswer = Schema.is( + Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]), +); + +// Only a hunk with lines hidden above it can open inside a docstring or script block. +function hidesLinesAboveAHunk(file: ReviewRenderableFile): boolean { + let hunkStart = true; + for (const row of file.rows) { + if (row.kind === "hunk") hunkStart = true; + else if (row.kind === "line") { + if (hunkStart && Math.max(row.oldLineNumber ?? 0, row.newLineNumber ?? 0) > 1) return true; + hunkStart = false; + } + } + return false; +} + +export function createReviewDiffHighlightFiles( + source: ReviewDiffContentsSource, + parsed: ReviewParsedDiff, + files: ReadonlyArray, + fetchContents: FetchContents, + cache = createDiffHighlightCache(), +): ReadonlyArray { + const { environmentId, cwd, sourceKind, baseRef, headRef, diffKey } = source; + const scope = JSON.stringify([environmentId, cwd, sourceKind, baseRef, headRef, diffKey]); + if (parsed.kind !== "files") return files; + const needsContents = new Set(parsed.files.filter(hidesLinesAboveAHunk).map((file) => file.id)); + const loaded = withDiffSourceLoaders( + scope, + parsed, + files, + async (file) => { + const result = await fetchContents({ + environmentId, + input: { + cwd, + sourceKind, + changeType: file.changeType, + baseRef, + headRef, + oldPath: file.previousPath ?? file.path, + newPath: file.path, + }, + }); + if (result._tag === "Success") return result.value; + const error = squashAtomCommandFailure(result); + // The server gives the same answer (too large, binary, no access) until the diff changes, + // so the loader stops asking for this file instead of retrying on every scroll. + throw isServerAnswer(error) ? { reason: "unsupported", cause: error } : error; + }, + cache, + ); + return loaded.map((file, index) => (needsContents.has(file.id) ? file : files[index]!)); +} diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index c1ac48615e53e..7121da0d71060 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -2,7 +2,7 @@ import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { turnChanges, turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories"; -import type { ReviewDiffPreviewSource } from "@t3tools/contracts"; +import type { OrchestrationGetTurnDiffResult, ReviewDiffPreviewSource } from "@t3tools/contracts"; import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; @@ -40,6 +40,8 @@ export interface ReviewSectionItem { readonly files?: ReviewDiffPreviewSource["files"]; readonly truncated?: boolean; readonly source?: ReviewGitSource; + /** The revisions a turn diff compares; absent from older servers. */ + readonly turnSource?: OrchestrationGetTurnDiffResult["source"]; /** Set when a turn's patch spans more than one folder. */ readonly repositoryGroups?: ReadonlyArray; /** Repositories the turn changed that have nothing recorded before it to compare with. */ diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index d530279f8ca25..7dcd9e8261690 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -4,6 +4,10 @@ import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; import { parseReviewInlineComments } from "./reviewCommentSelection"; import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter"; +import { + createReviewDiffHighlightFiles, + type ReviewDiffContentsSource, +} from "./reviewDiffHighlightFiles"; import { getCachedReviewParsedDiff } from "./reviewState"; import { applyReviewDiffMetadata, @@ -24,6 +28,8 @@ import { RegistryContext, useAtomValue } from "@effect/atom-react"; import * as AsyncResult from "effect/reactivity/AsyncResult"; import * as Atom from "effect/reactivity/Atom"; import { reviewEnvironment } from "../../state/review"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { createDiffHighlightCache } from "../diffs/nativeReviewDiffHighlightFiles"; import type { MessageResolver } from "../../i18n/messages"; import { filterPullRequestTestFiles, @@ -302,10 +308,58 @@ export function useReviewDiffData(input: { ? parsedDiff.fileCount - shownDiff.fileCount : 0, }; - const nativeReviewDiffData = getCachedNativeReviewDiffData({ - parsedDiff: fileFilter.parsed, + const baseNativeReviewDiffData = getCachedNativeReviewDiffData({ + parsedDiff: shownDiff, comments: selectedSectionInlineComments, }); + const fetchContents = useAtomCommand(reviewEnvironment.diffFileContents, { + reportFailure: false, + }); + const [highlightCache] = useState(createDiffHighlightCache); + const turnSource = selectedSection?.turnSource; + const nativeReviewDiffData = useMemo(() => { + const contentsSource: ReviewDiffContentsSource | null = + !environmentId || !selectedSectionId + ? null + : turnSource + ? { + environmentId, + cwd: turnSource.cwd, + sourceKind: "revision-range", + baseRef: turnSource.baseRef, + headRef: turnSource.headRef, + diffKey: selectedSectionId, + } + : source && cwd + ? { + environmentId, + cwd, + sourceKind: source.kind, + baseRef: source.baseRef, + headRef: source.headRef, + diffKey: source.diffHash, + } + : null; + if (!contentsSource) return baseNativeReviewDiffData; + const files = createReviewDiffHighlightFiles( + contentsSource, + shownDiff, + baseNativeReviewDiffData.files, + fetchContents, + highlightCache, + ); + return { ...baseNativeReviewDiffData, files }; + }, [ + environmentId, + selectedSectionId, + turnSource, + source, + cwd, + shownDiff, + baseNativeReviewDiffData, + fetchContents, + highlightCache, + ]); const pendingReviewCommentCount = inlineReviewComments.length; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records review perf marks and diagnostic logs once a parsed diff has committed diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts index 8cb6929169771..65a7ad2ec7d05 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -138,6 +138,11 @@ export function useReviewSections(input: { () => (activeTurnDiffData == null ? null : reviewTurnDiffText(activeTurnDiffData)), [activeTurnDiffData], ); + // The source names the thread folder's own patch, so it serves only a turn with no other patch. + const turnSource = + canReadFiles && activeTurnDiffData != null && activeTurnDiffText === activeTurnDiffData.diff + ? activeTurnDiffData.source + : undefined; const reviewSections = cachedSections.map((section): ReviewSectionItem => { if (section.kind === "turn") { @@ -146,6 +151,7 @@ export function useReviewSections(input: { ...section, diff: activeTurnDiffText ?? section.diff, isLoading: activeTurnDiff.isPending, + ...(turnSource ? { turnSource } : {}), } : section; } diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index d3dec1efe59ff..2eb2e61854816 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -60,6 +60,7 @@ function layerFor(input: { }), Layer.mock(CheckpointStore.CheckpointStore)({ diffCheckpoints: input.diffCheckpoints ?? (() => Effect.succeed("diff")), + resolveDiffBase: () => Effect.succeed("turn-start-sha"), listAuthoredPaths: () => Effect.succeed(input.authoredPaths ?? null), }), ), @@ -159,6 +160,11 @@ it.effect.each([false, true])( const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 2, toTurnCount: 3 }); assert.strictEqual(result.diff, "diff --git a/file b/file"); + assert.deepEqual(result.source, { + cwd: "/repo", + baseRef: "turn-start-sha", + headRef: "refs/t3/test/ordinal/3", + }); yield* query.getTurnDiff({ threadId, fromTurnCount: 1, toTurnCount: 3 }); yield* query.getFullThreadDiff({ threadId, toTurnCount: 3 }); assert.deepEqual( diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index d5344ecaa2fbb..42f88abe0ef73 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -81,6 +81,7 @@ function buildTurnDiffResult( }, diff: string, repositories?: ReadonlyArray, + source?: OrchestrationGetTurnDiffResultType["source"], ): OrchestrationGetTurnDiffResultType { return { threadId: input.threadId, @@ -88,6 +89,7 @@ function buildTurnDiffResult( toTurnCount: input.toTurnCount, diff, ...(repositories === undefined ? {} : { repositories }), + ...(source === undefined ? {} : { source }), }; } @@ -354,7 +356,10 @@ export const make = Effect.gen(function* () { Effect.provideService(Path.Path, path), ) : undefined; - const withRepositories = Effect.fnUntraced(function* (diff: string) { + const withRepositories = Effect.fnUntraced(function* ( + diff: string, + source?: OrchestrationGetTurnDiffResultType["source"], + ) { const repositories = nested === undefined ? undefined @@ -367,7 +372,7 @@ export const make = Effect.gen(function* () { nested, maxBytes: Math.max(0, CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - Buffer.byteLength(diff)), }); - const turnDiff = buildTurnDiffResult(input, diff, repositories); + const turnDiff = buildTurnDiffResult(input, diff, repositories, source); if (!isTurnDiffResult(turnDiff)) { return yield* new CheckpointDiffResultInvalidError({ operation, @@ -418,18 +423,24 @@ export const make = Effect.gen(function* () { } const excludePaths = nested?.get(toScope.id); - const diff = yield* patchBetween( - { - cwd: toScope.cwd, - fromCheckpointRef, - toCheckpointRef: toCheckpoint.ref, - fallbackFromToHead: false, - ignoreWhitespace, - ...(excludePaths === undefined ? {} : { excludePaths }), - }, - CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + const comparison = { + cwd: toScope.cwd, + fromCheckpointRef, + toCheckpointRef: toCheckpoint.ref, + fallbackFromToHead: false, + ignoreWhitespace, + ...(excludePaths === undefined ? {} : { excludePaths }), + } as const; + const diff = yield* patchBetween(comparison, CHECKPOINT_DIFF_MAX_OUTPUT_BYTES); + const baseRef = yield* checkpointStore + .resolveDiffBase(comparison) + .pipe(Effect.orElseSucceed(() => undefined)); + return yield* withRepositories( + diff, + baseRef === undefined + ? undefined + : { cwd: comparison.cwd, baseRef, headRef: comparison.toCheckpointRef }, ); - return yield* withRepositories(diff); }, ); diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 7b2667be6d2c1..52bff785d3eb4 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -641,6 +641,12 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { expect(switched.patch).toContain("-# test\n+# on b\n"); expect(switched.patch).toContain("b/b.txt"); expect(switched.authored).toBeNull(); + const switchedBase = yield* checkpointStore.resolveDiffBase({ + cwd: tmp, + fromCheckpointRef: first, + toCheckpointRef: second, + }); + expect(yield* git(tmp, ["show", `${switchedBase}:README.md`])).toBe("# test"); // A reset also moves HEAD off a commit, and what it removed is the turn's doing. yield* git(tmp, ["add", "."]); diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index 425cd2b0c815d..820dab947dae4 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -94,6 +94,11 @@ export class CheckpointStore extends Context.Service< input: DiffCheckpointsInput, ) => Effect.Effect; + /** The revision `diffCheckpoints` reads its old side from. */ + readonly resolveDiffBase: ( + input: ListAuthoredPathsInput, + ) => Effect.Effect; + /** Null means HEAD is unchanged or unrecorded; all changed paths then belong to the turn. */ readonly listAuthoredPaths: ( input: ListAuthoredPathsInput, @@ -167,6 +172,13 @@ export const make = Effect.gen(function* () { return yield* checkpoints.diffCheckpoints(input); }); + const resolveDiffBase: CheckpointStore["Service"]["resolveDiffBase"] = Effect.fn( + "resolveDiffBase", + )(function* (input) { + const checkpoints = yield* resolveCheckpoints(input.cwd); + return yield* checkpoints.resolveDiffBase(input); + }); + const listAuthoredPaths: CheckpointStore["Service"]["listAuthoredPaths"] = Effect.fn( "listAuthoredPaths", )(function* (input) { @@ -189,6 +201,7 @@ export const make = Effect.gen(function* () { hasCheckpointRef, restoreCheckpoint, diffCheckpoints, + resolveDiffBase, listAuthoredPaths, deleteCheckpointRefs, }); diff --git a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts index c73e1be396187..7ecf06a0f8347 100644 --- a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts @@ -222,6 +222,7 @@ it.effect("resolves the thread baseline after a second root run replaces scope o }), Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), + resolveDiffBase: (input) => Effect.succeed(input.fromCheckpointRef), diffCheckpoints: (input) => { assert.equal(input.cwd, "/prepared-repo"); assert.equal(input.fromCheckpointRef, checkpointRefs[0]); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 3a4dd7cedf10a..b9c30563c6df9 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -2315,6 +2315,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( return result.stdout; }), + resolveDiffBase: resolveTurnStart, + listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) { const operation = "GitVcsDriver.checkpoints.listAuthoredPaths"; const turnStart = yield* resolveTurnStart(input); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d9a661c7b1237..e7c1cf48f6511 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -3598,6 +3598,25 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reads both sides of a revision range from Git, not the working tree", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const baseRef = (yield* git(cwd, ["rev-parse", "HEAD"])).trim(); + yield* writeTextFile(cwd, "README.md", "# later\n"); + yield* git(cwd, ["commit", "-am", "later"]); + const headRef = (yield* git(cwd, ["rev-parse", "HEAD"])).trim(); + yield* writeTextFile(cwd, "README.md", "# dirty\n"); + + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { sourceKind: "revision-range", baseRef, headRef }), + ); + + assert.deepStrictEqual(contents, { oldContents: "# test\n", newContents: "# later\n" }); + }), + ); + it.effect("loads repository-relative files from nested directories and aliases", () => Effect.gen(function* () { const directory = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 8f3e3e16ca12b..2c4c8d49522e3 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -5088,6 +5088,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return result.stdout; }); + const readReviewFilesAtRevisions = Effect.fn("readReviewFilesAtRevisions")(function* ( + input: ReviewDiffFileContentsInput, + oldRevision: string, + newRevision: string, + ) { + const [oldContents, newContents] = yield* Effect.all( + [ + input.changeType === "new" + ? Effect.succeed("") + : readReviewFileAtRevision(input, oldRevision, input.oldPath), + input.changeType === "deleted" + ? Effect.succeed("") + : readReviewFileAtRevision(input, newRevision, input.newPath), + ], + { concurrency: 2 }, + ); + return { oldContents, newContents }; + }); + const readWorkingTreeReviewFile = Effect.fn("readWorkingTreeReviewFile")(function* ( input: ReviewDiffFileContentsInput, repositoryRoot: string, @@ -5214,18 +5233,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "Selected commit changed. Refresh the comparison.", ); } - const [oldContents, newContents] = yield* Effect.all( - [ - input.changeType === "new" - ? Effect.succeed("") - : readReviewFileAtRevision(input, commit.parent, input.oldPath), - input.changeType === "deleted" - ? Effect.succeed("") - : readReviewFileAtRevision(input, commit.sha, input.newPath), - ], - { concurrency: 2 }, - ); - return { oldContents, newContents }; + return yield* readReviewFilesAtRevisions(input, commit.parent, commit.sha); + } + if (input.sourceKind === "revision-range") { + if (!input.baseRef || !input.headRef) { + return yield* reviewDiffFileError(input, "Both revisions of the diff are required."); + } + return yield* readReviewFilesAtRevisions(input, input.baseRef, input.headRef); } const oldRevision = input.sourceKind === "working-tree" diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index c5a6408db0128..e63f11d5b77fd 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -86,6 +86,8 @@ export interface VcsCheckpointOps { input: VcsRestoreCheckpointInput, ) => Effect.Effect; readonly diffCheckpoints: (input: VcsDiffCheckpointsInput) => Effect.Effect; + /** The revision `diffCheckpoints` reads its old side from, which a branch switch moves. */ + readonly resolveDiffBase: (input: VcsListAuthoredPathsInput) => Effect.Effect; readonly listAuthoredPaths: ( input: VcsListAuthoredPathsInput, ) => Effect.Effect | null, VcsError>; diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 561bcd2b3e040..6cb082a27e5fa 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -28,7 +28,7 @@ import { ChevronsUpDownIcon, } from "lucide-react"; import * as Schema from "effect/Schema"; -import { type MouseEvent, useEffect, useRef, useState } from "react"; +import { type ComponentProps, type MouseEvent, useEffect, useRef, useState } from "react"; import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal"; import { useCodeViewScrollRestore } from "./diffs/useCodeViewScrollRestore"; import { useFilesystemReadAccess } from "~/state/filesystem"; @@ -112,7 +112,11 @@ import { reviewEnvironment } from "../state/review"; import { filesystemEnvironment } from "../state/filesystem"; import { vcsEnvironment } from "../state/vcs"; import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices"; -import { createGitDiffFileContentsLoader } from "../lib/diffFileContents"; +import { + claimHighlightContextLoad, + createGitDiffFileContentsLoader, + releaseHighlightContextLoad, +} from "../lib/diffFileContents"; import { observeIntersection } from "~/lib/observeIntersection"; import { useReviewFilePatches } from "./diffs/useReviewFilePatches"; @@ -131,6 +135,14 @@ import { import { useOpenLink } from "../browser/useOpenLink"; type DiffThemeType = "light" | "dark"; +// Pierre overloads the callback for file and diff items; one handler takes either set of arguments. +type CodeViewPostRenderArgs = + NonNullable["options"]["onPostRender"]> extends { + (...args: infer FileArgs): void; + (...args: infer DiffArgs): void; + } + ? FileArgs | DiffArgs + : never; const AUTOMATIC_BASE_REF = "__automatic_base_ref__"; const ALL_REPOSITORIES = "__all_repositories__"; const THREAD_FOLDER = "__thread_folder__"; @@ -638,17 +650,34 @@ export default function DiffPanel({ { additions: 0, deletions: 0 }, ) : null; - const currentLoadDiffFiles = - isGitSelection && activeThread && preview && selectedGitSource && canReadFiles - ? createGitDiffFileContentsLoader(getDiffFileContents, { - environmentId: activeThread.environmentId, - cwd: preview.cwd, - sourceKind: selectedGitSource.kind, - baseRef: selectedGitSource.baseRef, - headRef: selectedGitSource.headRef, - cacheKey: selectedGitSource.diffHash, - }) + // The source names the thread folder's own patch; a turn that also changed tracked + // repositories shows their patches beside it, which it cannot load files for. + const turnDiffSource = + selectedTurn && !toolCallSelection && repositorySections.length === 0 + ? activeCheckpointDiff.data?.source : undefined; + const currentLoadDiffFiles = + !activeThread || !canReadFiles + ? undefined + : turnDiffSource && selectedTurn + ? createGitDiffFileContentsLoader(getDiffFileContents, { + environmentId: activeThread.environmentId, + cwd: turnDiffSource.cwd, + sourceKind: "revision-range", + baseRef: turnDiffSource.baseRef, + headRef: turnDiffSource.headRef, + cacheKey: `turn:${selectedTurn.runId}`, + }) + : isGitSelection && preview && selectedGitSource + ? createGitDiffFileContentsLoader(getDiffFileContents, { + environmentId: activeThread.environmentId, + cwd: preview.cwd, + sourceKind: selectedGitSource.kind, + baseRef: selectedGitSource.baseRef, + headRef: selectedGitSource.headRef, + cacheKey: selectedGitSource.diffHash, + }) + : undefined; const loadDiffFiles: FileDiffContentsLoader = useStableCallback(async (fileDiff) => { if (!currentLoadDiffFiles) { throw new Error(gt("Diff file contents are unavailable for this selection.")); @@ -812,6 +841,24 @@ export default function DiffPanel({ codeViewScroll.flush(); codeViewReveal.flush(); }); + const onCodeViewPostRender = useStableCallback( + (...[, , phase, context]: CodeViewPostRenderArgs) => { + if (context.type === "diff") { + const { fileDiff, collapsed } = context.item; + if (phase === "unmount") { + releaseHighlightContextLoad(fileDiff); + } else if ( + currentLoadDiffFiles && + collapsed !== true && + claimHighlightContextLoad(fileDiff) + ) { + // Rejects when the files cannot load; the patch stays as rendered. + context.instance.prepareForEditing().catch(() => undefined); + } + } + flushCodeView(); + }, + ); const revealDiffFile = (filePath: string) => { const index = renderableFileEntries.findIndex( (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, @@ -1780,7 +1827,7 @@ export default function DiffPanel({ preferredHighlighter: PREFERRED_HIGHLIGHTER, themeType: resolvedTheme as DiffThemeType, stickyHeaders: true, - onPostRender: flushCodeView, + onPostRender: onCodeViewPostRender, ...(currentLoadDiffFiles ? { loadDiffFiles } : {}), }} /> diff --git a/apps/web/src/lib/diffFileContents.test.ts b/apps/web/src/lib/diffFileContents.test.ts index d88ddffc95c93..b87a7dc166156 100644 --- a/apps/web/src/lib/diffFileContents.test.ts +++ b/apps/web/src/lib/diffFileContents.test.ts @@ -3,7 +3,11 @@ import { EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; -import { createGitDiffFileContentsLoader } from "./diffFileContents"; +import { + claimHighlightContextLoad, + createGitDiffFileContentsLoader, + releaseHighlightContextLoad, +} from "./diffFileContents"; import { getRenderablePatch } from "./diffRendering"; const originalLines = Array.from({ length: 40 }, (_, index) => `line ${index + 1}`); @@ -162,3 +166,39 @@ describe("createGitDiffFileContentsLoader", () => { expect(loaded.oldFile?.contents).toBe("a\nb\n c\nd\ne"); }); }); + +describe("claimHighlightContextLoad", () => { + it("claims a patch whose hunk starts below the top of the file once per mount", () => { + const fileDiff = partialFileDiff(); + + expect(claimHighlightContextLoad(fileDiff)).toBe(true); + expect(claimHighlightContextLoad(fileDiff)).toBe(false); + releaseHighlightContextLoad(fileDiff); + expect(claimHighlightContextLoad(fileDiff)).toBe(true); + }); + + it("does not claim again after the files failed to load", async () => { + const fileDiff = partialFileDiff(); + const loader = loaderReturning(toContents(originalLines), toContents(originalLines)); + + await expect(loader(fileDiff)).rejects.toThrow("changed since the diff was loaded"); + releaseHighlightContextLoad(fileDiff); + + expect(claimHighlightContextLoad(fileDiff)).toBe(false); + }); + + it.each([ + { + name: "a patch whose only hunk starts at the first line", + patch: ["--- a/a.py", "+++ b/a.py", "@@ -1,2 +1,2 @@", "-old", "+new", " kept", ""], + }, + { + name: "an added file", + patch: ["new file mode 100644", "--- /dev/null", "+++ b/a.py", "@@ -0,0 +1 @@", "+new", ""], + }, + ])("leaves $name as parsed", ({ patch }) => { + const fileDiff = parsePartialFileDiff(["diff --git a/a.py b/a.py", ...patch].join("\n")); + + expect(claimHighlightContextLoad(fileDiff)).toBe(false); + }); +}); diff --git a/apps/web/src/lib/diffFileContents.ts b/apps/web/src/lib/diffFileContents.ts index 7fcd821df7394..e13e097dbfbab 100644 --- a/apps/web/src/lib/diffFileContents.ts +++ b/apps/web/src/lib/diffFileContents.ts @@ -11,7 +11,6 @@ import type { PullRequestRef, ReviewDiffFileContentsInput, ReviewDiffFileContentsResult, - ReviewDiffPreviewSourceKind, } from "@t3tools/contracts"; import { m } from "../i18n/messages"; @@ -20,7 +19,7 @@ import { resolveFileDiffPath } from "./diffRendering"; interface GitDiffFileContentsSource { readonly environmentId: EnvironmentId; readonly cwd: string; - readonly sourceKind: ReviewDiffPreviewSourceKind; + readonly sourceKind: ReviewDiffFileContentsInput["sourceKind"]; readonly baseRef: string | null; readonly headRef: string | null; readonly cacheKey: string; @@ -106,6 +105,29 @@ function reproducesPatch(fileDiff: FileDiffMetadata, oldContents: string, newCon ); } +const highlightContextLoads = new WeakMap(); + +// Pierre tokenizes each hunk of a partial patch from a fresh grammar state, so one that starts +// inside a docstring or an embedded script block gets the wrong syntax colours until the whole +// files are loaded. True once per mounted diff with such a hunk, and never after a failed load. +export function claimHighlightContextLoad(fileDiff: FileDiffMetadata): boolean { + if ( + !fileDiff.isPartial || + (fileDiff.type !== "change" && fileDiff.type !== "rename-changed") || + !fileDiff.hunks.some((hunk) => hunk.collapsedBefore > 0) || + highlightContextLoads.has(fileDiff) + ) { + return false; + } + highlightContextLoads.set(fileDiff, "requested"); + return true; +} + +/** Pierre drops the files loaded for a diff that unmounts, so its next mount asks again. */ +export function releaseHighlightContextLoad(fileDiff: FileDiffMetadata): void { + if (highlightContextLoads.get(fileDiff) === "requested") highlightContextLoads.delete(fileDiff); +} + function createDiffFileContentsLoader( load: (input: { readonly changeType: PullRequestDiffFileContentsInput["changeType"]; @@ -119,7 +141,12 @@ function createDiffFileContentsLoader( const oldPath = fileDiff.prevName ? resolveFileDiffPath({ ...fileDiff, name: fileDiff.prevName }) : newPath; - const contents = await load({ changeType: fileDiff.type, oldPath, newPath }); + const contents = await load({ changeType: fileDiff.type, oldPath, newPath }).catch( + (error: unknown) => { + highlightContextLoads.set(fileDiff, "failed"); + throw error; + }, + ); const newFile = { name: newPath, contents: contents.newContents, @@ -129,6 +156,7 @@ function createDiffFileContentsLoader( return { oldFile: null, newFile }; } if (!reproducesPatch(fileDiff, contents.oldContents, contents.newContents)) { + highlightContextLoads.set(fileDiff, "failed"); throw new Error( m(msg("This file changed since the diff was loaded. Refresh the diff to expand it.")), ); diff --git a/packages/contracts/src/checkpointDiff.ts b/packages/contracts/src/checkpointDiff.ts index 84a4dad91615e..0c326206d4f05 100644 --- a/packages/contracts/src/checkpointDiff.ts +++ b/packages/contracts/src/checkpointDiff.ts @@ -40,6 +40,14 @@ export const ThreadTurnDiff = TurnCountRange.mapFields( diff: Schema.String, /** Tracked repositories that changed in the range. Absent when the thread has none. */ repositories: Schema.optionalKey(Schema.Array(ThreadTurnRepositoryDiff)), + // The revisions `diff` compares, for loading either side's whole file. Older servers omit it. + source: Schema.optionalKey( + Schema.Struct({ + cwd: TrimmedNonEmptyString, + baseRef: TrimmedNonEmptyString, + headRef: TrimmedNonEmptyString, + }), + ), }), { unsafePreserveChecks: true }, ); diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index d43946e217219..96b22a84b9f5e 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -95,7 +95,8 @@ export type ReviewDiffPreviewSource = typeof ReviewDiffPreviewSource.Type; export const ReviewDiffFileContentsInput = Schema.Struct({ cwd: TrimmedNonEmptyString, - sourceKind: ReviewDiffPreviewSourceKind, + // "revision-range" reads the old file at baseRef and the new one at headRef, as a turn diff does. + sourceKind: Schema.Literals([...ReviewDiffPreviewSourceKind.literals, "revision-range"]), changeType: ReviewDiffChangeType, baseRef: Schema.NullOr(TrimmedNonEmptyString), headRef: Schema.NullOr(TrimmedNonEmptyString),