Open History to see the last commit
1import { highlightCode } from "../../lib/highlights";
2
3import { EnvironmentId, ProjectId } from "@t3tools/contracts";
4import { expect, it, vi } from "vite-plus/test";
5import { AsyncResult } from "effect/reactivity";
6
7import { highlightNativeReviewDiffVisibleRows } from "../diffs/nativeReviewDiffHighlighter";
8import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
9import type { ReviewParsedDiff, ReviewRenderableFile } from "../review/reviewModel";
10import { combinePullRequestDiffPages } from "./pullRequestDiffPages";
11import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
12import {
13 createPullRequestDiffHighlightCache,
14 createPullRequestDiffHighlightFiles,
15} from "./pullRequestDiffHighlightFiles";
16
17vi.mock("expo", async () => {
18 const { createWasmHighlightsModule } = await import("../../lib/highlights.testing");
19 return { requireOptionalNativeModule: () => createWasmHighlightsModule() };
20});
21
22const target = {
23 environmentId: EnvironmentId.make("remote-environment"),
24 input: {
25 projectId: ProjectId.make("project"),
26 repository: "org/repo",
27 number: 23,
28 host: "forge.example.com",
29 },
30};
31
32function file(id: string, path: string, previousPath: string | null): ReviewRenderableFile {
33 return {
34 id,
35 path,
36 previousPath,
37 cacheKey: id,
38 changeType: previousPath ? "rename-changed" : "change",
39 additions: 1,
40 deletions: 1,
41 languageHint: "typescript",
42 additionLines: [],
43 deletionLines: [],
44 rows: [],
45 };
46}
47
48function setup() {
49 const parsed = {
50 kind: "files",
51 fileCount: 2,
52 additions: 2,
53 deletions: 2,
54 notice: null,
55 files: [file("selected", "renderer.ts", "old-renderer.ts"), file("unseen", "unseen.ts", null)],
56 } satisfies ReviewParsedDiff;
57 const files: NativeReviewDiffFile[] = parsed.files.map((file) => ({
58 id: file.id,
59 path: file.path,
60 language: "typescript",
61 additions: 1,
62 deletions: 1,
63 }));
64 return { parsed, files };
65}
66
67it("loads only the selected PR file using its remote target, commit, and rename paths", async () => {
68 const { parsed, files } = setup();
69 const contents = {
70 oldContents: "/* Previous renderer\nconst removed = 1;\n*/",
71 newContents: "const heading = `Current renderer\nWelcome to the workspace.\n`;",
72 };
73 const fetch = vi.fn(async () => AsyncResult.success(contents));
74 const loaded = createPullRequestDiffHighlightFiles(
75 { target, commit: "abc123" },
76 parsed,
77 files,
78 fetch,
79 );
80 expect(fetch).not.toHaveBeenCalled();
81 const rows = [
82 {
83 kind: "line" as const,
84 id: "removed",
85 fileId: "selected",
86 change: "delete" as const,
87 oldLineNumber: 2,
88 newLineNumber: null,
89 content: "const removed = 1;",
90 },
91 {
92 kind: "line" as const,
93 id: "added",
94 fileId: "selected",
95 change: "add" as const,
96 oldLineNumber: null,
97 newLineNumber: 2,
98 content: "Welcome to the workspace.",
99 },
100 {
101 kind: "line" as const,
102 id: "unseen",
103 fileId: "unseen",
104 change: "add" as const,
105 oldLineNumber: null,
106 newLineNumber: 1,
107 content: "export const unseen = true;",
108 },
109 ];
110 const result = await highlightNativeReviewDiffVisibleRows({
111 rows,
112 files: loaded,
113 scheme: "dark",
114 firstRowIndex: 0,
115 lastRowIndex: 1,
116 overscanRows: 0,
117 });
118 expect(fetch.mock.calls).toEqual([
119 [
120 {
121 ...target,
122 input: {
123 ...target.input,
124 commit: "abc123",
125 changeType: "rename-changed",
126 oldPath: "old-renderer.ts",
127 newPath: "renderer.ts",
128 },
129 },
130 ],
131 ]);
132 expect(result.tokensByRowId.removed).toEqual(
133 highlightCode(contents.oldContents, "typescript", "dark")[1],
134 );
135 expect(result.tokensByRowId.added).toEqual(
136 highlightCode(contents.newContents, "typescript", "dark")[1],
137 );
138 expect(result.tokensByRowId.unseen).toBeUndefined();
139 expect(await loaded[0]!.loadContents!()).toBe(contents);
140 expect(fetch).toHaveBeenCalledTimes(1);
141});
142
143it.each([null, "Some file contents are unavailable"])(
144 "retains fetched and unavailable source when another diff page is appended (notice: %s)",
145 async (notice) => {
146 const { parsed, files } = setup();
147 const contents = { oldContents: "before", newContents: "after" };
148 const fetch = vi.fn(async ({ input }: { input: { newPath: string } }) => {
149 if (input.newPath === "unseen.ts") throw { reason: "unsupported" };
150 return AsyncResult.success(contents);
151 });
152 const cache = createPullRequestDiffHighlightCache();
153 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
154 expect(await first[0]!.loadContents!()).toBe(contents);
155 expect(await first[1]!.loadContents!()).toBeNull();
156 const appended = file("appended", "appended.ts", null);
157 const next = createPullRequestDiffHighlightFiles(
158 { target },
159 { ...parsed, files: [...parsed.files, appended], fileCount: 3, notice },
160 [...files, { ...files[1]!, id: appended.id, path: appended.path }],
161 fetch,
162 cache,
163 );
164 expect(await next[0]!.loadContents!()).toBe(contents);
165 expect(await next[1]!.loadContents!()).toBeNull();
166 expect(fetch).toHaveBeenCalledTimes(2);
167 },
168);
169
170it("does not reuse source from another diff snapshot", async () => {
171 const { parsed, files } = setup();
172 const fetch = vi.fn(async () =>
173 AsyncResult.success({ oldContents: "", newContents: "const current = true;" }),
174 );
175 const cache = createPullRequestDiffHighlightCache();
176 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
177 const second = createPullRequestDiffHighlightFiles(
178 { target },
179 { ...parsed, files: parsed.files.map((file) => ({ ...file })) },
180 files,
181 fetch,
182 cache,
183 );
184 await first[0]!.loadContents!();
185 await second[0]!.loadContents!();
186 expect(fetch).toHaveBeenCalledTimes(2);
187});
188
189it.each([
190 [
191 "environment",
192 { target: { ...target, environmentId: EnvironmentId.make("other") }, commit: "abc" },
193 ],
194 [
195 "project",
196 {
197 target: { ...target, input: { ...target.input, projectId: ProjectId.make("other") } },
198 commit: "abc",
199 },
200 ],
201 [
202 "repository",
203 { target: { ...target, input: { ...target.input, repository: "other/repo" } }, commit: "abc" },
204 ],
205 ["PR", { target: { ...target, input: { ...target.input, number: 24 } }, commit: "abc" }],
206 [
207 "host",
208 { target: { ...target, input: { ...target.input, host: "other.example.com" } }, commit: "abc" },
209 ],
210 ["commit", { target, commit: "def" }],
211 ["unpinned commit", { target }],
212])("isolates retained file objects after changing the %s", async (_name, source) => {
213 const { parsed, files } = setup();
214 const cache = createPullRequestDiffHighlightCache();
215 const previous = { oldContents: "", newContents: "previous" };
216 const current = { oldContents: "", newContents: "current" };
217 const fetch = vi
218 .fn()
219 .mockResolvedValueOnce(AsyncResult.success(previous))
220 .mockResolvedValueOnce(AsyncResult.success(current));
221 const first = createPullRequestDiffHighlightFiles(
222 { target, commit: "abc" },
223 parsed,
224 files,
225 fetch,
226 cache,
227 );
228 expect(await first[0]!.loadContents!()).toBe(previous);
229 const second = createPullRequestDiffHighlightFiles(source, parsed, files, fetch, cache);
230 expect(await second[0]!.loadContents!()).toBe(current);
231 expect(await first[0]!.loadContents!()).toBe(previous);
232 expect(fetch).toHaveBeenCalledTimes(2);
233});
234
235it("does not reuse a replaced later-page file with the same ID", async () => {
236 const { parsed, files } = setup();
237 const cache = createPullRequestDiffHighlightCache();
238 const previous = { oldContents: "", newContents: "previous" };
239 const current = { oldContents: "", newContents: "current" };
240 const fetch = vi
241 .fn()
242 .mockResolvedValueOnce(AsyncResult.success(previous))
243 .mockResolvedValueOnce(AsyncResult.success(current));
244 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
245 expect(await first[1]!.loadContents!()).toBe(previous);
246 const second = createPullRequestDiffHighlightFiles(
247 { target },
248 { ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },
249 files,
250 fetch,
251 cache,
252 );
253 expect(await second[1]!.loadContents!()).toBe(current);
254 expect(fetch).toHaveBeenCalledTimes(2);
255});
256
257it.each(["permanent", "transient"])(
258 "does not reuse a replaced later-page file's %s failure with the same ID",
259 async (failure) => {
260 const { parsed, files } = setup();
261 const cache = createPullRequestDiffHighlightCache();
262 const contents = { oldContents: "", newContents: "current" };
263 const fetch = vi.fn(async () => AsyncResult.success(contents));
264 const error = failure === "permanent" ? { reason: "unsupported" } : new Error("Offline");
265 fetch.mockRejectedValueOnce(error);
266 if (failure === "transient") fetch.mockRejectedValueOnce(error);
267 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
268 if (failure === "transient") {
269 await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");
270 await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");
271 } else {
272 expect(await first[1]!.loadContents!()).toBeNull();
273 }
274 const second = createPullRequestDiffHighlightFiles(
275 { target },
276 { ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },
277 files,
278 fetch,
279 cache,
280 );
281 expect(await second[1]!.loadContents!()).toBe(contents);
282 expect(await first[1]!.loadContents!()).toBe(failure === "permanent" ? null : contents);
283 expect(fetch).toHaveBeenCalledTimes(failure === "permanent" ? 2 : 4);
284 },
285);
286
287it("does not reuse reconstructed source after an appended page makes completeness uncertain", async () => {
288 const { parsed, files } = setup();
289 const cache = createPullRequestDiffHighlightCache();
290 const reconstructed = { oldContents: "", newContents: "reconstructed" };
291 const authoritative = { oldContents: "", newContents: "authoritative" };
292 parsed.files[0] = { ...parsed.files[0]!, completePatchSource: () => reconstructed };
293 const fetch = vi.fn(async () => AsyncResult.success(authoritative));
294 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
295 expect(await first[0]!.loadContents!()).toBe(reconstructed);
296 const next = createPullRequestDiffHighlightFiles(
297 { target },
298 { ...parsed, notice: "Some file contents are unavailable" },
299 files,
300 fetch,
301 cache,
302 );
303 expect(await next[0]!.loadContents!()).toBe(authoritative);
304 expect(fetch).toHaveBeenCalledOnce();
305});
306
307it.each([
308 ["characters", 2, 4_500_000],
309 ["file count", 5, 1],
310])(
311 "shares the source cache's aggregate %s budget across appended pages",
312 async (_name, count, size) => {
313 const { parsed, files } = setup();
314 const cache = createPullRequestDiffHighlightCache();
315 const contents = { oldContents: "", newContents: "x".repeat(size) };
316 const fetch = vi.fn(async () => AsyncResult.success(contents));
317 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
318 expect(await first[0]!.loadContents!()).toBe(contents);
319 let next = first;
320 for (let i = 1; i < count; i++) {
321 const appended = file(`page-${i}`, `page-${i}.ts`, null);
322 parsed.files.push(appended);
323 files.push({ ...files[0]!, id: appended.id, path: appended.path });
324 next = createPullRequestDiffHighlightFiles(
325 { target },
326 { ...parsed },
327 [...files],
328 fetch,
329 cache,
330 );
331 expect(await next.at(-1)!.loadContents!()).toBe(contents);
332 }
333 expect(fetch).toHaveBeenCalledTimes(count);
334 expect(await next[0]!.loadContents!()).toBe(contents);
335 expect(fetch).toHaveBeenCalledTimes(count + 1);
336 },
337);
338
339function addedPatch(body: string, header = "@@ -0,0 +1,2 @@") {
340 return `diff --git a/file.c b/file.c\nnew file mode 100644\n--- /dev/null\n+++ b/file.c\n${header}\n${body}`;
341}
342
343function loadPatch(patch: string, truncated = false) {
344 const parsed = combinePullRequestDiffPages(
345 [{ cursor: null, result: { patch, truncated, nextCursor: null } }],
346 new WeakMap(),
347 "complete-source",
348 sourceControlClients.get("github").changeRequest,
349 );
350 if (parsed.kind !== "files") throw new Error("Expected parsed files");
351 const files = parsed.files.map((file) => ({
352 id: file.id,
353 path: file.path,
354 language: "c" as const,
355 additions: file.additions,
356 deletions: file.deletions,
357 }));
358 const authoritative = { oldContents: "provider old", newContents: "provider new" };
359 const fetch = vi.fn(async () => AsyncResult.success(authoritative));
360 const loaded = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch);
361 return { loaded, fetch, authoritative };
362}
363
364it.each([0, 1])(
365 "loads a complete 100k-line addition with empty-side start %s beyond the RPC cap",
366 async (emptyStart) => {
367 const source = "/* generated C */ int value = 1;\n".repeat(100_000);
368 const body = source.replace(/^/gm, "+").slice(0, -1);
369 const { loaded, fetch } = loadPatch(addedPatch(body, `@@ -${emptyStart},0 +1,100000 @@`));
370 expect(source.length).toBeGreaterThan(1_048_576);
371 const contents = await loaded[0]!.loadContents!();
372 expect(contents?.oldContents).toBe("");
373 expect(contents?.newContents.length).toBe(source.length);
374 expect(contents?.newContents === source).toBe(true);
375 expect(fetch).not.toHaveBeenCalled();
376 },
377);
378
379it.each([
380 ["LF", "+first\n+last\n", "first\nlast\n"],
381 ["CRLF", "+first\r\n+last\r\n", "first\r\nlast\r\n"],
382 ["missing EOF newline", "+first\r\n+last\n\\ No newline at end of file\n", "first\r\nlast"],
383 ["final bare CR", "+first\r\n+last\r\n\\ No newline at end of file\n", "first\r\nlast\r"],
384])("preserves %s for complete additions and deletions", async (_name, body, source) => {
385 for (const emptyStart of [0, 1]) {
386 const added = addedPatch(body, `@@ -${emptyStart},0 +1,2 @@`);
387 const deleted = added
388 .replace("new file mode", "deleted file mode")
389 .replace("--- /dev/null\n+++ b/file.c", "--- a/file.c\n+++ /dev/null")
390 .replace(`@@ -${emptyStart},0 +1,2 @@`, `@@ -1,2 +${emptyStart},0 @@`);
391 const deletionPatch = deleted.replace(body, body.replace(/\+/g, "-"));
392 for (const [patch, expected] of [
393 [added, { oldContents: "", newContents: source }],
394 [deletionPatch, { oldContents: source, newContents: "" }],
395 ] as const) {
396 const { loaded, fetch } = loadPatch(patch);
397 expect(await loaded[0]!.loadContents!()).toEqual(expected);
398 expect(fetch).not.toHaveBeenCalled();
399 }
400 }
401});
402
403it.each([
404 ["too few lines", addedPatch("+first\n", "@@ -0,0 +1,2 @@")],
405 ["too many lines", addedPatch("+first\n+last\n", "@@ -0,0 +1 @@")],
406 ["zero repaired count", addedPatch("+first\n+last\n", "@@ -0,0 +1,0 @@")],
407 ["unterminated patch line", addedPatch("+first\n+last")],
408 ["missing count", addedPatch("+first\n+last\n", "@@ -0,0 +1, @@")],
409 ["gap", addedPatch("+first\n+last\n", "@@ -0,0 +2,2 @@")],
410 ["invalid empty-side start", addedPatch("+first\n+last\n", "@@ -2,0 +1,2 @@")],
411 ["converted underfull hunk", addedPatch("+first\n", "@@ -1,0 +1,2 @@")],
412 ["converted overfull hunk", addedPatch("+first\n+last\n", "@@ -1,0 +1 @@")],
413 ["converted nonempty old side", addedPatch("+first\n+last\n", "@@ -1,1 +1,2 @@")],
414 ["context", addedPatch(" first\n+last\n", "@@ -1 +1,2 @@")],
415 ["mixed sides", addedPatch("-first\n+last\n", "@@ -1 +1 @@")],
416 ["second hunk", addedPatch("+first\n@@ -0,0 +2 @@\n+last\n", "@@ -0,0 +1 @@")],
417 ["early EOF marker", addedPatch("+first\n\\ No newline at end of file\n+last\n")],
418 ["unknown marker", addedPatch("+first\n+last\n\\ unknown\n")],
419 ["trailing garbage", addedPatch("+first\n+last\nignored\n")],
420 ["submodule", addedPatch("+first\n+last\n").replace("100644", "160000")],
421 [
422 "binary",
423 addedPatch("+first\n+last\n").replace("--- /dev/null", "Binary files differ\n--- /dev/null"),
424 ],
425 ["changed", addedPatch("+first\n+last\n").replace("new file mode 100644\n", "")],
426 [
427 "rename",
428 addedPatch("+first\n+last\n").replace(
429 "new file mode 100644",
430 "similarity index 50%\nrename from old.c\nrename to file.c",
431 ),
432 ],
433 ["truncation marker", addedPatch("+first\n+last\n\n[truncated]\n")],
434])("uses authoritative RPC source when completeness is unproven: %s", async (_name, patch) => {
435 const { loaded, fetch, authoritative } = loadPatch(patch);
436 expect(await loaded[0]!.loadContents!()).toBe(authoritative);
437 expect(fetch).toHaveBeenCalledOnce();
438});
439
440it("rejects a complete-looking patch when the provider marks any page truncated", async () => {
441 const { loaded, fetch, authoritative } = loadPatch(addedPatch("+first\n+last\n"), true);
442 expect(await loaded[0]!.loadContents!()).toBe(authoritative);
443 expect(fetch).toHaveBeenCalledOnce();
444});