@devries-cameron20 / t3code Mirror · read-only / commits / bd02e64b5f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

fix(web): expanding a diff whose files changed no longer crashes (#28056)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 11:54 UTC bd02e64b5f1a22318bd17729f969ae584f896693
5 files changed +315 -32
apps/web/src/components/pullRequest/guide/GuideExcerpt.logic.test.ts new
+93
@@ -0,0 +1,93 @@
1 +import { DiffHunksRenderer, hydratePartialDiff, type FileDiffMetadata } from "@pierre/diffs";
2 +import { excerptRows, fileDiffRows, rowsToPatch } from "@t3tools/client-runtime/review-guide-tour";
3 +import { EnvironmentId } from "@t3tools/contracts";
4 +import { AsyncResult } from "effect/reactivity";
5 +import { expect, it } from "vite-plus/test";
6 +
7 +import { createGitDiffFileContentsLoader } from "~/lib/diffFileContents";
8 +import { getRenderablePatch } from "~/lib/diffRendering";
9 +import { excerptLoader } from "./GuideExcerpt.logic";
10 +
11 +function parse(patch: string): FileDiffMetadata {
12 + const renderable = getRenderablePatch(patch, "guide-excerpt-test");
13 + if (renderable?.kind !== "files") throw new Error("Expected a parsed patch.");
14 + return renderable.files[0]!;
15 +}
16 +
17 +it("expands an excerpt whose file has another hunk that changes its length", async () => {
18 + const original = Array.from({ length: 100 }, (_, index) => `line ${index + 1}`);
19 + const changed = original.map((line, index) => (index === 29 ? "line 30 changed" : line));
20 + changed.splice(80, 0, "later insertion");
21 + const file = parse(
22 + [
23 + "diff --git a/file.ts b/file.ts",
24 + "--- a/file.ts",
25 + "+++ b/file.ts",
26 + "@@ -27,7 +27,7 @@",
27 + " line 27",
28 + " line 28",
29 + " line 29",
30 + "-line 30",
31 + "+line 30 changed",
32 + " line 31",
33 + " line 32",
34 + " line 33",
35 + "@@ -78,6 +78,7 @@",
36 + " line 78",
37 + " line 79",
38 + " line 80",
39 + "+later insertion",
40 + " line 81",
41 + " line 82",
42 + " line 83",
43 + "",
44 + ].join("\n"),
45 + );
46 + const excerpt = { path: "file.ts", side: "new", start: 30, end: 30, caption: "" } as const;
47 + const rows = excerptRows(fileDiffRows(file), excerpt);
48 + const excerptDiff = parse(rowsToPatch("file.ts", "file.ts", rows));
49 + const loadDiffFiles = createGitDiffFileContentsLoader(
50 + async () =>
51 + AsyncResult.success({
52 + oldContents: `${original.join("\n")}\n`,
53 + newContents: `${changed.join("\n")}\n`,
54 + }),
55 + {
56 + environmentId: EnvironmentId.make("environment-guide-excerpt-test"),
57 + cwd: "/repo",
58 + sourceKind: "working-tree",
59 + baseRef: null,
60 + headRef: null,
61 + cacheKey: "diff-hash",
62 + },
63 + );
64 +
65 + const files = await excerptLoader(excerpt, file, rows, loadDiffFiles)!(excerptDiff);
66 + const hydrated = hydratePartialDiff("clone", excerptDiff, files);
67 +
68 + await expect(
69 + new DiffHunksRenderer({ expandUnchanged: true }).asyncRender(hydrated),
70 + ).resolves.toBeDefined();
71 +});
72 +
73 +it("leaves a deleted file's excerpt without context expansion", () => {
74 + const file = parse(
75 + [
76 + "diff --git a/file.ts b/file.ts",
77 + "deleted file mode 100644",
78 + "--- a/file.ts",
79 + "+++ /dev/null",
80 + "@@ -1,3 +0,0 @@",
81 + "-a",
82 + "-b",
83 + "-c",
84 + "",
85 + ].join("\n"),
86 + );
87 + const excerpt = { path: "file.ts", side: "old", start: 2, end: 2, caption: "" } as const;
88 + const rows = excerptRows(fileDiffRows(file), excerpt);
89 +
90 + expect(excerptLoader(excerpt, file, rows, async () => Promise.reject(new Error("unused")))).toBe(
91 + null,
92 + );
93 +});
apps/web/src/components/pullRequest/guide/GuideExcerpt.logic.ts new
+37
@@ -0,0 +1,37 @@
1 +import type { FileDiffContentsLoader, FileDiffMetadata } from "@pierre/diffs";
2 +import {
3 + excerptExpansionOldContents,
4 + type DiffRow,
5 +} from "@t3tools/client-runtime/review-guide-tour";
6 +import type { PullRequestReviewGuideExcerpt } from "@t3tools/contracts";
7 +
8 +// Other hunks shift old-side context; expand against an excerpt-matching old side.
9 +// Loads with the source file's diff, which the loaded contents must reproduce.
10 +export function excerptLoader(
11 + excerpt: PullRequestReviewGuideExcerpt,
12 + file: FileDiffMetadata,
13 + sliceRows: ReadonlyArray<DiffRow>,
14 + loadDiffFiles: FileDiffContentsLoader,
15 +): FileDiffContentsLoader | null {
16 + // An added or deleted file has no unchanged context to expand.
17 + if (
18 + file.type === "new" ||
19 + file.type === "deleted" ||
20 + sliceRows.some((row) => row.hunk !== sliceRows[0]?.hunk)
21 + ) {
22 + return null;
23 + }
24 + return async () => {
25 + const loaded = await loadDiffFiles(file);
26 + const oldContents = excerptExpansionOldContents(loaded.newFile.contents, sliceRows);
27 + if (oldContents === null) return loaded;
28 + return {
29 + newFile: loaded.newFile,
30 + oldFile: {
31 + name: loaded.oldFile?.name ?? loaded.newFile.name,
32 + contents: oldContents,
33 + cacheKey: `${loaded.newFile.cacheKey ?? loaded.newFile.name}:excerpt:${excerpt.side}:${excerpt.start}-${excerpt.end}`,
34 + },
35 + };
36 + };
37 +}
apps/web/src/components/pullRequest/guide/GuideExcerpt.tsx
+3 -31
@@ -31,13 +31,9 @@ import {
31 toViewerSide,
32 } from "../PullRequestReviewAnnotation";
33 import type { PendingReviewComment } from "../pullRequestReviewStore";
34 -import {
35 - excerptExpansionOldContents,
36 - excerptRows,
37 - fileDiffRows,
38 - rowsToPatch,
39 -} from "@t3tools/client-runtime/review-guide-tour";
34 +import { excerptRows, fileDiffRows, rowsToPatch } from "@t3tools/client-runtime/review-guide-tour";
35 import type { PullRequestCompletionScope } from "../PullRequestMarkdownTextarea";
36 +import { excerptLoader } from "./GuideExcerpt.logic";
37 import { GuideNoteMarker } from "./GuideNotes";
38 import { GuideProse } from "./GuideProse";
39
@@ -101,30 +97,6 @@ function excerptSlice(file: FileDiffMetadata | null, excerpt: PullRequestReviewG
97 return { fileDiff, rows: shown, shown: shown.length, total: rows.length, drawn };
98 }
99
104 -// Other hunks shift old-side context; expand against an excerpt-matching old side.
105 -function excerptLoader(
106 - excerpt: PullRequestReviewGuideExcerpt,
107 - sliceRows: ExcerptSlice["rows"],
108 - loadDiffFiles: FileDiffContentsLoader,
109 -): FileDiffContentsLoader | null {
110 - if (sliceRows.some((row) => row.hunk !== sliceRows[0]?.hunk)) {
111 - return null;
112 - }
113 - return async (fileDiff) => {
114 - const loaded = await loadDiffFiles(fileDiff);
115 - const oldContents = excerptExpansionOldContents(loaded.newFile.contents, sliceRows);
116 - if (oldContents === null) return loaded;
117 - return {
118 - newFile: loaded.newFile,
119 - oldFile: {
120 - name: loaded.oldFile?.name ?? loaded.newFile.name,
121 - contents: oldContents,
122 - cacheKey: `${loaded.newFile.cacheKey ?? loaded.newFile.name}:excerpt:${excerpt.side}:${excerpt.start}-${excerpt.end}`,
123 - },
124 - };
125 - };
126 -}
127 -
100 export function GuideExcerpt({
101 excerpt,
102 file,
@@ -206,7 +178,7 @@ function ExcerptDiff({
178 onOpenFile: (path: string) => void;
179 }) {
180 const resolvedTheme = useRenderedAppearance();
209 - const loadExcerptFiles = excerptLoader(excerpt, slice.rows, loadDiffFiles);
181 + const loadExcerptFiles = excerptLoader(excerpt, file, slice.rows, loadDiffFiles);
182
183 const annotations = (() => {
184 const groups = new Map<string, DiffLineAnnotation<ExcerptAnnotation>>();
apps/web/src/lib/diffFileContents.test.ts new
+113
@@ -0,0 +1,113 @@
1 +import type { FileDiffMetadata } from "@pierre/diffs";
2 +import { EnvironmentId } from "@t3tools/contracts";
3 +import { AsyncResult } from "effect/reactivity";
4 +import { describe, expect, it } from "vite-plus/test";
5 +
6 +import { createGitDiffFileContentsLoader } from "./diffFileContents";
7 +import { getRenderablePatch } from "./diffRendering";
8 +
9 +const originalLines = Array.from({ length: 40 }, (_, index) => `line ${index + 1}`);
10 +const changedLines = originalLines.map((line, index) => (index === 29 ? "line 30 changed" : line));
11 +
12 +function toContents(lines: ReadonlyArray<string>) {
13 + return `${lines.join("\n")}\n`;
14 +}
15 +
16 +function parsePartialFileDiff(patch: string): FileDiffMetadata {
17 + const renderable = getRenderablePatch(patch, "diff-panel:light", {
18 + compactPartialHunkOffsets: true,
19 + });
20 + if (renderable?.kind !== "files") throw new Error("Expected a parsed patch.");
21 + return renderable.files[0]!;
22 +}
23 +
24 +function partialFileDiff(): FileDiffMetadata {
25 + const patch = [
26 + "diff --git a/src/file01.ts b/src/file01.ts",
27 + "index 1111111..2222222 100644",
28 + "--- a/src/file01.ts",
29 + "+++ b/src/file01.ts",
30 + "@@ -27,7 +27,7 @@",
31 + " line 27",
32 + " line 28",
33 + " line 29",
34 + "-line 30",
35 + "+line 30 changed",
36 + " line 31",
37 + " line 32",
38 + " line 33",
39 + "",
40 + ].join("\n");
41 + return parsePartialFileDiff(patch);
42 +}
43 +
44 +function loaderReturning(oldContents: string, newContents: string) {
45 + return createGitDiffFileContentsLoader(
46 + async () => AsyncResult.success({ oldContents, newContents }),
47 + {
48 + environmentId: EnvironmentId.make("environment-diff-contents-test"),
49 + cwd: "/repo",
50 + sourceKind: "working-tree",
51 + baseRef: null,
52 + headRef: null,
53 + cacheKey: "diff-hash",
54 + },
55 + );
56 +}
57 +
58 +describe("createGitDiffFileContentsLoader", () => {
59 + it("loads contents that still reproduce the patch", async () => {
60 + const loaded = await loaderReturning(
61 + toContents(originalLines),
62 + toContents(changedLines),
63 + )(partialFileDiff());
64 +
65 + expect(loaded.newFile.contents).toBe(toContents(changedLines));
66 + });
67 +
68 + it.each([
69 + {
70 + name: "end before the patch's hunk",
71 + oldLines: originalLines.slice(0, 30),
72 + newLines: changedLines.slice(0, 30),
73 + },
74 + {
75 + name: "have unchanged tails that no longer match between sides",
76 + oldLines: originalLines,
77 + newLines: [...changedLines, "line 41 appended"],
78 + },
79 + {
80 + name: "changed hunk lines without moving them",
81 + oldLines: originalLines,
82 + newLines: changedLines.map((line, index) => (index === 30 ? "edited since" : line)),
83 + },
84 + ])("rejects contents that $name", async ({ oldLines, newLines }) => {
85 + const loader = loaderReturning(toContents(oldLines), toContents(newLines));
86 +
87 + await expect(loader(partialFileDiff())).rejects.toThrow("changed since the diff was loaded");
88 + });
89 +
90 + it("loads a whitespace-ignored patch whose context shows one side's whitespace", async () => {
91 + const patch = [
92 + "diff --git a/src/file01.ts b/src/file01.ts",
93 + "index 1111111..2222222 100644",
94 + "--- a/src/file01.ts",
95 + "+++ b/src/file01.ts",
96 + "@@ -2,4 +2,4 @@ a",
97 + " b",
98 + " c",
99 + " d",
100 + "-e",
101 + "\\ No newline at end of file",
102 + "+E",
103 + "\\ No newline at end of file",
104 + "",
105 + ].join("\n");
106 + const loaded = await loaderReturning(
107 + "a\nb\n c\nd\ne",
108 + "a\nb\nc\nd\nE",
109 + )(parsePartialFileDiff(patch));
110 +
111 + expect(loaded.oldFile?.contents).toBe("a\nb\n c\nd\ne");
112 + });
113 +});
apps/web/src/lib/diffFileContents.ts
+69 -1
@@ -1,4 +1,4 @@
1 -import type { FileDiffContentsLoader } from "@pierre/diffs";
1 +import type { FileDiffContentsLoader, FileDiffMetadata } from "@pierre/diffs";
2 import {
3 squashAtomCommandFailure,
4 type AtomCommandResult,
@@ -41,6 +41,69 @@ type GetPullRequestDiffFileContents<E> = (request: {
41 readonly input: PullRequestDiffFileContentsInput;
42 }) => Promise<AtomCommandResult<PullRequestDiffFileContentsResult, E>>;
43
44 +// Mirrors Pierre's splitFileContents so line counts match its hydration.
45 +function splitLines(contents: string): ReadonlyArray<string> {
46 + return contents === "" ? [] : contents.split(/(?<=\n)/);
47 +}
48 +
49 +// Whitespace-insensitive: `git diff -w` prints context lines from only one side.
50 +function sameLine(patchLine: string | undefined, fileLine: string | undefined): boolean {
51 + return (
52 + patchLine !== undefined &&
53 + fileLine !== undefined &&
54 + patchLine.replace(/\s/g, "") === fileLine.replace(/\s/g, "")
55 + );
56 +}
57 +
58 +function hunkSideEnd(start: number, count: number): number {
59 + return start - (count === 0 ? 0 : 1) + count;
60 +}
61 +
62 +function hunkSideMatches(
63 + patchLines: ReadonlyArray<string>,
64 + patchIndex: number,
65 + fileLines: ReadonlyArray<string>,
66 + start: number,
67 + count: number,
68 +): boolean {
69 + const fileIndex = hunkSideEnd(start, count) - count;
70 + for (let offset = 0; offset < count; offset++) {
71 + if (!sameLine(patchLines[patchIndex + offset], fileLines[fileIndex + offset])) return false;
72 + }
73 + return true;
74 +}
75 +
76 +// Pierre hydrates a partial patch by trusting its hunk positions, so contents that
77 +// changed since the patch was computed make it render corrupt hunks or throw.
78 +function reproducesPatch(fileDiff: FileDiffMetadata, oldContents: string, newContents: string) {
79 + const lastHunk = fileDiff.hunks.at(-1);
80 + if (lastHunk === undefined) return true;
81 + const oldLines = splitLines(oldContents);
82 + const newLines = splitLines(newContents);
83 + const hunksMatch = fileDiff.hunks.every(
84 + (hunk) =>
85 + hunkSideMatches(
86 + fileDiff.deletionLines,
87 + hunk.deletionLineIndex,
88 + oldLines,
89 + hunk.deletionStart,
90 + hunk.deletionCount,
91 + ) &&
92 + hunkSideMatches(
93 + fileDiff.additionLines,
94 + hunk.additionLineIndex,
95 + newLines,
96 + hunk.additionStart,
97 + hunk.additionCount,
98 + ),
99 + );
100 + return (
101 + hunksMatch &&
102 + oldLines.length - hunkSideEnd(lastHunk.deletionStart, lastHunk.deletionCount) ===
103 + newLines.length - hunkSideEnd(lastHunk.additionStart, lastHunk.additionCount)
104 + );
105 +}
106 +
107 function createDiffFileContentsLoader(
108 load: (input: {
109 readonly changeType: PullRequestDiffFileContentsInput["changeType"];
@@ -63,6 +126,11 @@ function createDiffFileContentsLoader(
126 if (fileDiff.type === "rename-pure") {
127 return { oldFile: null, newFile };
128 }
129 + if (!reproducesPatch(fileDiff, contents.oldContents, contents.newContents)) {
130 + throw new Error(
131 + "This file changed since the diff was loaded. Refresh the diff to expand it.",
132 + );
133 + }
134 return {
135 oldFile: {
136 name: oldPath,