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") await expect(first[1]!.loadContents!()).rejects.toThrow("Offline");
269 expect(await first[1]!.loadContents!()).toBeNull();
270 const second = createPullRequestDiffHighlightFiles(
271 { target },
272 { ...parsed, files: [parsed.files[0]!, { ...parsed.files[1]! }] },
273 files,
274 fetch,
275 cache,
276 );
277 expect(await second[1]!.loadContents!()).toBe(contents);
278 expect(await first[1]!.loadContents!()).toBeNull();
279 expect(fetch).toHaveBeenCalledTimes(failure === "permanent" ? 2 : 3);
280 },
281);
282
283it("does not reuse reconstructed source after an appended page makes completeness uncertain", async () => {
284 const { parsed, files } = setup();
285 const cache = createPullRequestDiffHighlightCache();
286 const reconstructed = { oldContents: "", newContents: "reconstructed" };
287 const authoritative = { oldContents: "", newContents: "authoritative" };
288 parsed.files[0] = { ...parsed.files[0]!, completePatchSource: () => reconstructed };
289 const fetch = vi.fn(async () => AsyncResult.success(authoritative));
290 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
291 expect(await first[0]!.loadContents!()).toBe(reconstructed);
292 const next = createPullRequestDiffHighlightFiles(
293 { target },
294 { ...parsed, notice: "Some file contents are unavailable" },
295 files,
296 fetch,
297 cache,
298 );
299 expect(await next[0]!.loadContents!()).toBe(authoritative);
300 expect(fetch).toHaveBeenCalledOnce();
301});
302
303it.each([
304 ["characters", 2, 4_500_000],
305 ["file count", 5, 1],
306])(
307 "shares the source cache's aggregate %s budget across appended pages",
308 async (_name, count, size) => {
309 const { parsed, files } = setup();
310 const cache = createPullRequestDiffHighlightCache();
311 const contents = { oldContents: "", newContents: "x".repeat(size) };
312 const fetch = vi.fn(async () => AsyncResult.success(contents));
313 const first = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch, cache);
314 expect(await first[0]!.loadContents!()).toBe(contents);
315 let next = first;
316 for (let i = 1; i < count; i++) {
317 const appended = file(`page-${i}`, `page-${i}.ts`, null);
318 parsed.files.push(appended);
319 files.push({ ...files[0]!, id: appended.id, path: appended.path });
320 next = createPullRequestDiffHighlightFiles(
321 { target },
322 { ...parsed },
323 [...files],
324 fetch,
325 cache,
326 );
327 expect(await next.at(-1)!.loadContents!()).toBe(contents);
328 }
329 expect(fetch).toHaveBeenCalledTimes(count);
330 expect(await next[0]!.loadContents!()).toBe(contents);
331 expect(fetch).toHaveBeenCalledTimes(count + 1);
332 },
333);
334
335function addedPatch(body: string, header = "@@ -0,0 +1,2 @@") {
336 return `diff --git a/file.c b/file.c\nnew file mode 100644\n--- /dev/null\n+++ b/file.c\n${header}\n${body}`;
337}
338
339function loadPatch(patch: string, truncated = false) {
340 const parsed = combinePullRequestDiffPages(
341 [{ cursor: null, result: { patch, truncated, nextCursor: null } }],
342 new WeakMap(),
343 "complete-source",
344 sourceControlClients.get("github").changeRequest,
345 );
346 if (parsed.kind !== "files") throw new Error("Expected parsed files");
347 const files = parsed.files.map((file) => ({
348 id: file.id,
349 path: file.path,
350 language: "c" as const,
351 additions: file.additions,
352 deletions: file.deletions,
353 }));
354 const authoritative = { oldContents: "provider old", newContents: "provider new" };
355 const fetch = vi.fn(async () => AsyncResult.success(authoritative));
356 const loaded = createPullRequestDiffHighlightFiles({ target }, parsed, files, fetch);
357 return { loaded, fetch, authoritative };
358}
359
360it.each([0, 1])(
361 "loads a complete 100k-line addition with empty-side start %s beyond the RPC cap",
362 async (emptyStart) => {
363 const source = "/* generated C */ int value = 1;\n".repeat(100_000);
364 const body = source.replace(/^/gm, "+").slice(0, -1);
365 const { loaded, fetch } = loadPatch(addedPatch(body, `@@ -${emptyStart},0 +1,100000 @@`));
366 expect(source.length).toBeGreaterThan(1_048_576);
367 const contents = await loaded[0]!.loadContents!();
368 expect(contents?.oldContents).toBe("");
369 expect(contents?.newContents.length).toBe(source.length);
370 expect(contents?.newContents === source).toBe(true);
371 expect(fetch).not.toHaveBeenCalled();
372 },
373);
374
375it.each([
376 ["LF", "+first\n+last\n", "first\nlast\n"],
377 ["CRLF", "+first\r\n+last\r\n", "first\r\nlast\r\n"],
378 ["missing EOF newline", "+first\r\n+last\n\\ No newline at end of file\n", "first\r\nlast"],
379 ["final bare CR", "+first\r\n+last\r\n\\ No newline at end of file\n", "first\r\nlast\r"],
380])("preserves %s for complete additions and deletions", async (_name, body, source) => {
381 for (const emptyStart of [0, 1]) {
382 const added = addedPatch(body, `@@ -${emptyStart},0 +1,2 @@`);
383 const deleted = added
384 .replace("new file mode", "deleted file mode")
385 .replace("--- /dev/null\n+++ b/file.c", "--- a/file.c\n+++ /dev/null")
386 .replace(`@@ -${emptyStart},0 +1,2 @@`, `@@ -1,2 +${emptyStart},0 @@`);
387 const deletionPatch = deleted.replace(body, body.replace(/\+/g, "-"));
388 for (const [patch, expected] of [
389 [added, { oldContents: "", newContents: source }],
390 [deletionPatch, { oldContents: source, newContents: "" }],
391 ] as const) {
392 const { loaded, fetch } = loadPatch(patch);
393 expect(await loaded[0]!.loadContents!()).toEqual(expected);
394 expect(fetch).not.toHaveBeenCalled();
395 }
396 }
397});
398
399it.each([
400 ["too few lines", addedPatch("+first\n", "@@ -0,0 +1,2 @@")],
401 ["too many lines", addedPatch("+first\n+last\n", "@@ -0,0 +1 @@")],
402 ["zero repaired count", addedPatch("+first\n+last\n", "@@ -0,0 +1,0 @@")],
403 ["unterminated patch line", addedPatch("+first\n+last")],
404 ["missing count", addedPatch("+first\n+last\n", "@@ -0,0 +1, @@")],
405 ["gap", addedPatch("+first\n+last\n", "@@ -0,0 +2,2 @@")],
406 ["invalid empty-side start", addedPatch("+first\n+last\n", "@@ -2,0 +1,2 @@")],
407 ["converted underfull hunk", addedPatch("+first\n", "@@ -1,0 +1,2 @@")],
408 ["converted overfull hunk", addedPatch("+first\n+last\n", "@@ -1,0 +1 @@")],
409 ["converted nonempty old side", addedPatch("+first\n+last\n", "@@ -1,1 +1,2 @@")],
410 ["context", addedPatch(" first\n+last\n", "@@ -1 +1,2 @@")],
411 ["mixed sides", addedPatch("-first\n+last\n", "@@ -1 +1 @@")],
412 ["second hunk", addedPatch("+first\n@@ -0,0 +2 @@\n+last\n", "@@ -0,0 +1 @@")],
413 ["early EOF marker", addedPatch("+first\n\\ No newline at end of file\n+last\n")],
414 ["unknown marker", addedPatch("+first\n+last\n\\ unknown\n")],
415 ["trailing garbage", addedPatch("+first\n+last\nignored\n")],
416 ["submodule", addedPatch("+first\n+last\n").replace("100644", "160000")],
417 [
418 "binary",
419 addedPatch("+first\n+last\n").replace("--- /dev/null", "Binary files differ\n--- /dev/null"),
420 ],
421 ["changed", addedPatch("+first\n+last\n").replace("new file mode 100644\n", "")],
422 [
423 "rename",
424 addedPatch("+first\n+last\n").replace(
425 "new file mode 100644",
426 "similarity index 50%\nrename from old.c\nrename to file.c",
427 ),
428 ],
429 ["truncation marker", addedPatch("+first\n+last\n\n[truncated]\n")],
430])("uses authoritative RPC source when completeness is unproven: %s", async (_name, patch) => {
431 const { loaded, fetch, authoritative } = loadPatch(patch);
432 expect(await loaded[0]!.loadContents!()).toBe(authoritative);
433 expect(fetch).toHaveBeenCalledOnce();
434});
435
436it("rejects a complete-looking patch when the provider marks any page truncated", async () => {
437 const { loaded, fetch, authoritative } = loadPatch(addedPatch("+first\n+last\n"), true);
438 expect(await loaded[0]!.loadContents!()).toBe(authoritative);
439 expect(fetch).toHaveBeenCalledOnce();
440});