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