Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2import { diffWordsWithSpace } from "diff";
3import { AsyncResult } from "effect/reactivity";
4import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
5import { EnvironmentId, ProjectId, type PullRequestDiffResult } from "@t3tools/contracts";
6
7import { combinePullRequestDiffPages } from "../pull-requests/pullRequestDiffPages";
8import { createPullRequestDiffHighlightFiles } from "../pull-requests/pullRequestDiffHighlightFiles";
9import {
10 buildNativeReviewDiffData,
11 getCachedNativeReviewDiffData,
12} from "./nativeReviewDiffAdapter";
13import type { ReviewInlineComment } from "./reviewCommentSelection";
14import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
15
16vi.mock("diff", { spy: true });
17
18function makeComment(text: string): ReviewInlineComment {
19 return {
20 id: "comment-1",
21 sectionId: "git:working-tree",
22 sectionTitle: "Dirty worktree",
23 filePath: "example.ts",
24 startIndex: 0,
25 endIndex: 0,
26 rangeLabel: "-1",
27 text,
28 diff: "@@ -1,1 +1,0 @@\n-const before = 1;",
29 };
30}
31
32function filesPatch(paths: ReadonlyArray<string>) {
33 return paths
34 .map((path) =>
35 [
36 `diff --git a/${path} b/${path}`,
37 `--- a/${path}`,
38 `+++ b/${path}`,
39 "@@ -1,2 +1,2 @@",
40 '-const first = renderPanel({ label: "before", enabled: true });',
41 '-const second = renderPanel({ label: "before", enabled: true });',
42 '+const first = renderPanel({ label: "after", enabled: true });',
43 '+const second = renderPanel({ label: "after", enabled: true });',
44 ].join("\n"),
45 )
46 .join("\n");
47}
48
49describe("buildNativeReviewDiffData languages", () => {
50 it.each([
51 ["js", "javascript"],
52 ["cjs", "javascript"],
53 ["mjs", "javascript"],
54 ["jsx", "jsx"],
55 ["ts", "typescript"],
56 ["mts", "typescript"],
57 ["cts", "typescript"],
58 ["tsx", "tsx"],
59 ])("assigns %s files their syntax language when deleted", (extension, language) => {
60 const path = `scripts/dev-runner.${extension}`;
61 const data = buildNativeReviewDiffData(
62 buildReviewParsedDiff(
63 [
64 `diff --git a/${path} b/${path}`,
65 "deleted file mode 100644",
66 `--- a/${path}`,
67 "+++ /dev/null",
68 "@@ -1,2 +0,0 @@",
69 '-import process from "node:process";',
70 "-const port = process.env.PORT;",
71 "",
72 ].join("\n"),
73 "deleted-script-language",
74 ),
75 );
76
77 expect(data.files).toMatchObject([{ path, language }]);
78 expect(data.rows.filter((row) => row.kind === "line")).toMatchObject([
79 { content: 'import process from "node:process";', change: "delete" },
80 { content: "const port = process.env.PORT;", change: "delete" },
81 ]);
82 });
83});
84
85describe("getCachedNativeReviewDiffData", () => {
86 it("keeps compact identities aligned through page append, filtering, comments, and source lookup", async () => {
87 const scope = JSON.stringify({ remote: 'long-target\\"'.repeat(100) });
88 const cache = new WeakMap<PullRequestDiffResult, ReviewParsedDiff>();
89 const firstPage = {
90 cursor: null,
91 result: {
92 patch: filesPatch(["example.ts", "hidden.test.ts"]),
93 truncated: false,
94 nextCursor: "next",
95 },
96 };
97 const terminology = sourceControlClients.get("github").changeRequest;
98 const first = combinePullRequestDiffPages([firstPage], cache, scope, terminology);
99 if (first.kind !== "files") throw new Error("Expected parsed first page");
100 const before = getCachedNativeReviewDiffData({ parsedDiff: first });
101 const selectedRowId = before.rows.find((row) => row.kind === "line")!.id;
102 const combined = combinePullRequestDiffPages(
103 [
104 firstPage,
105 {
106 cursor: "next",
107 result: { patch: filesPatch(["last.ts"]), truncated: false, nextCursor: null },
108 },
109 ],
110 cache,
111 scope,
112 terminology,
113 );
114 if (combined.kind !== "files") throw new Error("Expected parsed appended pages");
115 expect(combined.files[0]).toBe(first.files[0]);
116 const filtered = {
117 ...combined,
118 files: combined.files.filter((file) => !file.path.includes(".test.")),
119 };
120 const input = { parsedDiff: filtered, comments: [makeComment("Feedback")] };
121 const data = getCachedNativeReviewDiffData(input);
122 expect(getCachedNativeReviewDiffData(input)).toBe(data);
123 expect(new Set(data.rows.map((row) => row.id)).size).toBe(data.rows.length);
124 expect(data.rows.find((row) => row.id === selectedRowId)).toBe(
125 before.rows.find((row) => row.id === selectedRowId),
126 );
127 // IDs used by native initialFileId/collapse and parsed source lookup share one namespace.
128 expect(data.files.map((file) => file.id)).toEqual(filtered.files.map((file) => file.id));
129 for (const file of filtered.files) {
130 const header = data.rows.find((row) => row.kind === "file" && row.fileId === file.id)!;
131 expect(header.filePath).toBe(file.path);
132 const lines = file.rows.filter((row) => row.kind === "line");
133 for (const [lineIndex, line] of lines.entries()) {
134 const nativeId = data.rowIdByCommentLineId.get(line.id)!;
135 const row = data.rows.find((row) => row.id === nativeId)!;
136 expect(row.fileId).toBe(file.id);
137 expect(row.content).toBe(line.content);
138 expect(nativeId.length).toBeLessThan(64);
139 const target = data.commentTargetsByRowId.get(nativeId)!;
140 expect(target.filePath).toBe(file.path);
141 expect(target.lines[lineIndex]).toBe(line);
142 expect(target.lineIndex).toBe(lineIndex);
143 expect(row.wordDiffRanges?.length).toBeGreaterThan(0);
144 expect(
145 row.wordDiffRanges?.map((range) => row.content!.slice(range.start, range.end)),
146 ).toEqual([line.change === "delete" ? "before" : "after"]);
147 }
148 }
149 const commentIndex = data.rows.findIndex((row) => row.id === "comment-1");
150 expect(data.rows[commentIndex - 1]!.id).toBe(selectedRowId);
151 expect(data.rows[commentIndex]!.fileId).toBe(first.files[0]!.id);
152
153 const target = {
154 environmentId: EnvironmentId.make("remote"),
155 input: {
156 projectId: ProjectId.make("project"),
157 repository: "org/repo",
158 number: 23,
159 },
160 };
161 const contents = { oldContents: "old source", newContents: "new source" };
162 const fetch = vi.fn(async () => AsyncResult.success(contents));
163 const highlightFiles = createPullRequestDiffHighlightFiles(
164 { target },
165 filtered,
166 data.files,
167 fetch,
168 );
169 expect(await highlightFiles[1]!.loadContents!()).toBe(contents);
170 expect(fetch).toHaveBeenCalledExactlyOnceWith({
171 ...target,
172 input: { ...target.input, changeType: "change", oldPath: "last.ts", newPath: "last.ts" },
173 });
174 expect(JSON.stringify(data.rows).length).toBeLessThan(5000);
175 });
176
177 it("keeps Pierre's matching lines in the GitHub credential pinning excerpt", () => {
178 const parsed = buildReviewParsedDiff(
179 [
180 "diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts",
181 "--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts",
182 "+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts",
183 "@@ -1221,11 +1240,4 @@",
184 "- operation: input.operation,",
185 "- path: input.path,",
186 "- ...(Option.isSome(previous) ? { ifNoneMatch: previous.value.etag } : {}),",
187 "- })",
188 "- .pipe(",
189 "- Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {",
190 "- host,",
191 "- token,",
192 "- credentialFingerprint: fingerprint,",
193 "- }),",
194 "- );",
195 "+ token,",
196 "+ credentialFingerprint: fingerprint,",
197 "+ }),",
198 "+ );",
199 "",
200 ].join("\n"),
201 "credential-pinning",
202 );
203 expect(parsed.kind).toBe("files");
204 if (parsed.kind !== "files") return;
205 expect(
206 parsed.files[0]?.rows.find((row) => row.kind === "line" && row.newLineNumber === 1242),
207 ).toMatchObject({
208 comparison: { change: "delete", tokenIndex: 9 },
209 });
210 const data = buildNativeReviewDiffData(parsed);
211 expect(
212 data.rows.find((row) => row.kind === "line" && row.newLineNumber === 1242)?.wordDiffRanges,
213 ).toBeUndefined();
214 });
215
216 it.each([
217 [true, false, "Old file has no newline at end of file."],
218 [false, true, "New file has no newline at end of file."],
219 [true, true, "Old and new files have no newline at end of file."],
220 [false, false, null],
221 ])("shows missing-newline notices for old=%s new=%s", (oldMissing, newMissing, notice) => {
222 const data = buildNativeReviewDiffData(
223 buildReviewParsedDiff(
224 [
225 "diff --git a/example.ts b/example.ts",
226 "--- a/example.ts",
227 "+++ b/example.ts",
228 "@@ -1 +1 @@",
229 "-value",
230 ...(oldMissing ? ["\\ No newline at end of file"] : []),
231 "+value",
232 ...(newMissing ? ["\\ No newline at end of file"] : []),
233 "",
234 ].join("\n"),
235 "native-eof",
236 ),
237 );
238 expect(data.rows.filter((row) => row.kind === "notice").map((row) => row.text)).toEqual(
239 notice ? [notice] : [],
240 );
241 expect(data.rows.filter((row) => row.kind === "line")).toHaveLength(2);
242 expect(data.commentTargetsByRowId.size).toBe(2);
243 });
244
245 it("keeps cached IDs and targets local to each parsed section and file layout", () => {
246 const original = filesPatch(["example.ts", "second.ts"]);
247 const variants = [
248 buildReviewParsedDiff(original, "first-section"),
249 buildReviewParsedDiff(original, "second-section"),
250 buildReviewParsedDiff(
251 filesPatch(["inserted.ts", "example.ts", "second.ts"]),
252 "first-section",
253 ),
254 buildReviewParsedDiff(filesPatch(["second.ts", "example.ts"]), "first-section"),
255 buildReviewParsedDiff(filesPatch(["example.ts"]), "first-section"),
256 buildReviewParsedDiff(
257 original.replaceAll("@@ -1,2 +1,2 @@", "@@ -7,2 +12,2 @@"),
258 "first-section",
259 ),
260 ];
261 for (const diff of [...variants, variants[0]!]) {
262 const input = { parsedDiff: diff, comments: [makeComment("Coordinates")] };
263 expect(getCachedNativeReviewDiffData(input)).toEqual(buildNativeReviewDiffData(input));
264 }
265 });
266});
267
268describe("buildNativeReviewDiffData row bound", () => {
269 function singleFilePatch(path: string, lineCount: number) {
270 return [
271 `diff --git a/${path} b/${path}`,
272 `--- a/${path}`,
273 `+++ b/${path}`,
274 `@@ -0,0 +1,${lineCount} @@`,
275 ...Array.from({ length: lineCount }, (_, index) => `+const value${index} = ${index};`),
276 ].join("\n");
277 }
278
279 it("caps each huge file excerpt while preserving full counts and ordinary files", () => {
280 const data = buildNativeReviewDiffData(
281 buildReviewParsedDiff(
282 [singleFilePatch("huge.ts", 200_000), singleFilePatch("ordinary.ts", 1_000)].join("\n"),
283 "native-review-row-bound",
284 ),
285 );
286 const hugeHeader = data.rows.find((row) => row.kind === "file" && row.filePath === "huge.ts");
287 const ordinaryHeader = data.rows.find(
288 (row) => row.kind === "file" && row.filePath === "ordinary.ts",
289 );
290 expect(hugeHeader).toMatchObject({ additions: 200_000, deletions: 0 });
291 expect(ordinaryHeader).toMatchObject({ additions: 1_000, deletions: 0 });
292 expect(data).toMatchObject({ additions: 201_000, deletions: 0 });
293 const hugeRows = data.rows.filter((row) => row.fileId === hugeHeader?.fileId);
294 expect(hugeRows.filter((row) => row.kind === "line" || row.kind === "hunk")).toHaveLength(
295 100_000,
296 );
297 expect(hugeRows.at(-2)).toMatchObject({ kind: "line", newLineNumber: 99_999 });
298 expect(hugeRows.at(-1)).toMatchObject({
299 kind: "notice",
300 text: "This diff is too large to show in full.",
301 });
302 const ordinaryRows = data.rows.filter((row) => row.fileId === ordinaryHeader?.fileId);
303 expect(ordinaryRows.filter((row) => row.kind === "line")).toHaveLength(1_000);
304 expect(ordinaryRows.at(-1)).toMatchObject({
305 kind: "line",
306 newLineNumber: 1_000,
307 content: "const value999 = 999;",
308 });
309 expect(ordinaryRows.some((row) => row.kind === "notice")).toBe(false);
310 });
311});
312
313describe("buildNativeReviewDiffData word comparison bound", () => {
314 function modifiedFilePatch(pairCount: number, contextCount = 0) {
315 const lineCount = pairCount + contextCount;
316 return [
317 "diff --git a/example.ts b/example.ts",
318 "--- a/example.ts",
319 "+++ b/example.ts",
320 `@@ -1,${lineCount} +1,${lineCount} @@`,
321 ...Array.from({ length: contextCount }, (_, index) => ` const context${index} = true;`),
322 ...Array.from(
323 { length: pairCount },
324 (_, index) => `-const value${index} = renderPanel({ label: "before", enabled: true });`,
325 ),
326 ...Array.from(
327 { length: pairCount },
328 (_, index) => `+const value${index} = renderPanel({ label: "after", enabled: true });`,
329 ),
330 ].join("\n");
331 }
332
333 it("bounds eager word comparisons without truncating a large modified file", () => {
334 const parsedDiff = buildReviewParsedDiff(modifiedFilePatch(20_000), "native-word-bound");
335 const comparisons = vi.mocked(diffWordsWithSpace).mockClear();
336 const data = buildNativeReviewDiffData(parsedDiff);
337
338 expect(comparisons).toHaveBeenCalledTimes(1_000);
339 expect(data).toMatchObject({ additions: 20_000, deletions: 20_000 });
340 const lines = data.rows.filter((row) => row.kind === "line");
341 expect(lines).toHaveLength(40_000);
342 expect(data.rows.some((row) => row.kind === "notice")).toBe(false);
343 for (const offset of [0, 20_000]) {
344 expect(lines[offset]?.wordDiffRanges?.length).toBeGreaterThan(0);
345 expect(lines[offset + 999]?.wordDiffRanges?.length).toBeGreaterThan(0);
346 expect(lines[offset + 1_000]?.wordDiffRanges).toBeUndefined();
347 }
348 expect(lines.at(-1)).toMatchObject({
349 content: 'const value19999 = renderPanel({ label: "after", enabled: true });',
350 newLineNumber: 20_000,
351 });
352 expect(data.commentTargetsByRowId.size).toBe(40_000);
353 expect(data.commentTargetsByRowId.get(lines.at(-1)!.id)?.lineIndex).toBe(39_999);
354 });
355
356 it.each([0, 20_000])("preserves small word differences with %s context rows", (contextCount) => {
357 const parsedDiff = buildReviewParsedDiff(
358 modifiedFilePatch(2, contextCount),
359 "native-word-context",
360 );
361 const comparisons = vi.mocked(diffWordsWithSpace).mockClear();
362 const data = buildNativeReviewDiffData(parsedDiff);
363
364 expect(comparisons).toHaveBeenCalledTimes(2);
365 const changes = data.rows.filter((row) => row.kind === "line" && row.change !== "context");
366 expect(changes).toHaveLength(4);
367 for (const row of changes) {
368 expect(
369 row.wordDiffRanges?.map((range) => row.content!.slice(range.start, range.end)),
370 ).toEqual([row.change === "delete" ? "before" : "after"]);
371 }
372 });
373});