Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nativeReviewDiffAdapter.test.ts

465 lines17.9 KB

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