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

reviewModel.test.ts

426 lines14.4 KB

1import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
2import { CheckpointRef, CheckpointScopeId, RunId } from "@t3tools/contracts";
3import { describe, expect, it } from "vite-plus/test";
4​
5import {
6 applyReviewDiffMetadata,
7 buildReviewParsedDiff,
8 buildReviewSectionItems,
9 filterReviewParsedDiffToFolder,
10 resolveReviewSelectedSectionId,
11 type ReviewRenderableFile,
12 type ReviewSectionItem,
13} from "./reviewModel";
14​
15function makeSection(id: string): ReviewSectionItem {
16 return {
17 id,
18 kind: id.startsWith("turn:") ? "turn" : "branch-range",
19 title: id,
20 subtitle: null,
21 diff: null,
22 isLoading: false,
23 };
25​
26describe("resolveReviewSelectedSectionId", () => {
27 const turn = makeSection("turn:2");
28 const changes = makeSection("git:branch-range");
29​
30 it("shows Changes before anything is picked, not the first section", () => {
31 expect(resolveReviewSelectedSectionId([turn, changes], null)).toBe("git:branch-range");
32 });
33​
34 it("shows the default while the picked section loads and returns to the pick once it does", () => {
35 expect(resolveReviewSelectedSectionId([changes], "turn:2")).toBe("git:branch-range");
36 expect(resolveReviewSelectedSectionId([turn, changes], "turn:2")).toBe("turn:2");
37 });
38});
39​
40describe("buildReviewSectionItems", () => {
41 const checkpoint = (turn: number, repositories?: ThreadCheckpointSummary["repositories"]) =>
42 ({
43 runId: RunId.make(`run-${turn}`),
44 checkpointTurnCount: turn,
45 checkpointRef: CheckpointRef.make(`ref-${turn}`),
46 status: "missing",
47 files: [],
48 ...(repositories === undefined ? {} : { repositories }),
49 assistantMessageId: null,
50 completedAt: "2026-11-10T00:00:00.000Z",
51 }) satisfies ThreadCheckpointSummary;
52 const repository = (name: string, paths: ReadonlyArray<string>) => ({
53 scopeId: CheckpointScopeId.make(`scope-${name}`),
54 name,
55 repositoryPath: `/work/${name}`,
56 cwd: `/work/${name}`,
57 relativePath: name,
58 files: paths.map((path) => ({ path, kind: "modified", additions: 2, deletions: 1 })),
59 baselineMissing: paths.length === 0,
60 });
61​
62 it("offers a plain folder's turns that changed its repositories", () => {
63 const sections = buildReviewSectionItems({
64 checkpoints: [
65 checkpoint(1),
66 checkpoint(2, [repository("api", ["a.ts", "b.ts"]), repository("web", ["a.ts"])]),
67 checkpoint(3, [repository("api", ["a.ts"]), repository("web", [])]),
68 ],
69 gitSections: [],
70 turnDiffById: {},
71 gitSectionStates: { "working-tree": null, "branch-range": null },
72 });
73​
74 expect(sections).toMatchObject([
75 { id: "turn:3", subtitle: "1 file changed · api, web", unlistedRepositories: ["web"] },
76 {
77 id: "turn:2",
78 subtitle: "3 files changed · api, web",
79 repositoryGroups: [
80 { key: "/work/api", name: "api", relativePath: "api" },
81 { key: "/work/web", name: "web", relativePath: "web" },
82 ],
83 },
84 ]);
85 expect(sections[0]).not.toHaveProperty("repositoryGroups");
86 });
87});
88​
89describe("filterReviewParsedDiffToFolder", () => {
90 it("keeps the files of one folder, giving a nested repository its own", () => {
91 const file = (path: string) => ({ path, additions: 2, deletions: 1 }) as ReviewRenderableFile;
92 const parsed = {
93 kind: "files" as const,
94 files: ["README.md", "api/src/a.ts", "api/vendor/lib/a.ts", "apiary/a.ts"].map(file),
95 fileCount: 4,
96 additions: 8,
97 deletions: 4,
98 notice: null,
99 };
100 const folders = ["", "api", "api/vendor/lib"];
101 const paths = (folder: string) => {
102 const filtered = filterReviewParsedDiffToFolder(parsed, folder, folders);
103 return filtered.kind === "files" ? filtered.files.map((entry) => entry.path) : null;
104 };
105​
106 expect(paths("")).toEqual(["README.md", "apiary/a.ts"]);
107 expect(paths("api/vendor/lib")).toEqual(["api/vendor/lib/a.ts"]);
108 expect(filterReviewParsedDiffToFolder(parsed, "api", folders)).toMatchObject({
109 files: [{ path: "api/src/a.ts" }],
110 fileCount: 1,
111 additions: 2,
112 deletions: 1,
113 });
114 });
115});
116​
117describe("buildReviewParsedDiff", () => {
118 it("keeps UI identities compact, stable, and isolated from parser cache keys", () => {
119 const patch =
120 "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-before\n+after\n";
121 const scope = JSON.stringify({ target: 'remote\\"scope'.repeat(100) });
122 const parsed = buildReviewParsedDiff(patch + patch, scope);
123 const repeated = buildReviewParsedDiff(patch + patch, scope);
124 const otherSection = buildReviewParsedDiff(patch + patch, `${scope}:other`);
125 const changed = buildReviewParsedDiff((patch + patch).replaceAll("after", "changed"), scope);
126 if (
127 parsed.kind !== "files" ||
128 repeated.kind !== "files" ||
129 otherSection.kind !== "files" ||
130 changed.kind !== "files"
131 )
132 throw new Error("Expected structured diffs");
133​
134 expect(parsed.files).toHaveLength(2);
135 expect(parsed.files.map((file) => file.id)).toEqual(repeated.files.map((file) => file.id));
136 expect(parsed.files.map((file) => file.cacheKey)).toEqual(
137 repeated.files.map((file) => file.cacheKey),
138 );
139 const ids = parsed.files.flatMap((file) => [file.id, ...file.rows.map((row) => row.id)]);
140 expect(new Set(ids).size).toBe(ids.length);
141 for (const id of ids) expect(id.length).toBeLessThan(48);
142 for (const variant of [otherSection, changed]) {
143 const otherIds = variant.files.flatMap((file) => [
144 file.id,
145 ...file.rows.map((row) => row.id),
146 ]);
147 expect(otherIds.some((id) => ids.includes(id))).toBe(false);
148 }
149 expect(parsed.files[0]!.cacheKey.length).toBeGreaterThan(scope.length);
150 expect(parsed.files[0]!.id).not.toBe(parsed.files[0]!.cacheKey);
151 expect(repeated.files[0]!.rows.map((row) => row.id)).toEqual(
152 parsed.files[0]!.rows.map((row) => row.id),
153 );
154 });
155​
156 it.each(["", "\n\n[truncated]"])(
157 "preserves the final blank context in the resourceTelemetry excerpt with suffix %j",
158 (suffix) => {
159 const parsed = buildReviewParsedDiff(
160 [
161 "diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts",
162 "--- a/packages/contracts/src/resourceTelemetry.ts",
163 "+++ b/packages/contracts/src/resourceTelemetry.ts",
164 "@@ -350,6 +371,7 @@",
165 " DesktopTelemetryRequestDesktopUpdate,",
166 " DesktopTelemetryCommitDesktopUpdate,",
167 " DesktopTelemetryCancelDesktopUpdate,",
168 "+ DesktopUpdateRestartPolicyResult,",
169 " ]);",
170 " export type DesktopTelemetryControlMessage = typeof DesktopTelemetryControlMessage.Type;",
171 " ",
172 "",
173 ].join("\n") + suffix,
174 "resource-telemetry",
175 );
176 expect(parsed.kind).toBe("files");
177 if (parsed.kind !== "files") return;
178 expect(parsed.files[0]?.rows.at(-1)).toMatchObject({
179 kind: "line",
180 change: "context",
181 oldLineNumber: 355,
182 newLineNumber: 377,
183 content: "",
184 });
185 expect(parsed.files[0]?.additionLines.at(-1)).toBe("\n");
186 expect(parsed.files[0]?.deletionLines.at(-1)).toBe("\n");
187 },
188 );
189​
190 it("preserves final content whitespace and gives distinct patches distinct cache keys", () => {
191 const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -0,0 +1 @@\n+value \t\n";
192 const parsed = buildReviewParsedDiff(patch, "whitespace");
193 const withoutWhitespace = buildReviewParsedDiff(
194 patch.replace("value \t", "value"),
195 "whitespace",
196 );
197 expect(parsed.kind).toBe("files");
198 expect(withoutWhitespace.kind).toBe("files");
199 if (parsed.kind !== "files" || withoutWhitespace.kind !== "files") return;
200 expect(parsed.files[0]?.rows.at(-1)).toMatchObject({ content: "value \t" });
201 expect(parsed.files[0]?.additionLines).toEqual(["value \t\n"]);
202 expect(parsed.files[0]?.cacheKey).not.toBe(withoutWhitespace.files[0]?.cacheKey);
203 });
204​
205 it.each([
206 [true, false],
207 [false, true],
208 [true, true],
209 [false, false],
210 ])("preserves missing-newline flags for old=%s and new=%s", (oldMissing, newMissing) => {
211 const parsed = buildReviewParsedDiff(
212 [
213 "diff --git a/a.ts b/a.ts",
214 "--- a/a.ts",
215 "+++ b/a.ts",
216 "@@ -1 +1 @@",
217 "-value",
218 ...(oldMissing ? ["\\ No newline at end of file"] : []),
219 "+value",
220 ...(newMissing ? ["\\ No newline at end of file"] : []),
221 "",
222 ].join("\n"),
223 "eof",
224 );
225 expect(parsed.kind).toBe("files");
226 if (parsed.kind !== "files") return;
227 expect(parsed.files[0]).toMatchObject({
228 noEOFCRDeletions: oldMissing,
229 noEOFCRAdditions: newMissing,
230 deletionLines: [oldMissing ? "value" : "value\n"],
231 additionLines: [newMissing ? "value" : "value\n"],
232 });
233 });
234​
235 it.each([
236 ["a/example.ts", "a/example.ts"],
237 ["a/before.ts", "b/after.ts"],
238 ])("preserves repository paths from %s to %s", (previousPath, path) => {
239 const parsed = buildReviewParsedDiff(
240 [
241 `diff --git a/${previousPath} b/${path}`,
242 ...(previousPath === path
243 ? []
244 : ["similarity index 50%", `rename from ${previousPath}`, `rename to ${path}`]),
245 `--- a/${previousPath}`,
246 `+++ b/${path}`,
247 "@@ -1 +1 @@",
248 "-before",
249 "+after",
250 ].join("\n"),
251 "repository-paths",
252 );
253 expect(parsed.kind).toBe("files");
254 if (parsed.kind !== "files") return;
255 expect(parsed.files[0]).toMatchObject({
256 path,
257 previousPath: previousPath === path ? null : previousPath,
258 additions: 1,
259 deletions: 1,
260 });
261 });
262​
263 it("builds renderable rows from a unified patch", () => {
264 const parsed = buildReviewParsedDiff(
265 [
266 "diff --git a/apps/mobile/src/a.ts b/apps/mobile/src/a.ts",
267 "index 1111111..2222222 100644",
268 "--- a/apps/mobile/src/a.ts",
269 "+++ b/apps/mobile/src/a.ts",
270 "@@ -1,2 +1,3 @@",
271 "-const before = 1;",
272 "+const after = 2;",
273 "+console.log(after);",
274 " return true;",
275 ].join("\n"),
276 "unit",
277 );
278​
279 expect(parsed.kind).toBe("files");
280 if (parsed.kind !== "files") {
281 return;
282 }
283​
284 expect(parsed.fileCount).toBe(1);
285 expect(parsed.additions).toBe(2);
286 expect(parsed.deletions).toBe(1);
287 expect(parsed.files[0]).toMatchObject({
288 path: "apps/mobile/src/a.ts",
289 additions: 2,
290 deletions: 1,
291 });
292 expect(parsed.files[0]?.rows).toEqual([
293 expect.objectContaining({ kind: "hunk", header: "@@ -1,2 +1,3 @@" }),
294 expect.objectContaining({
295 kind: "line",
296 change: "delete",
297 oldLineNumber: 1,
298 newLineNumber: null,
299 content: "const before = 1;",
300 comparison: { change: "add", tokenIndex: 0 },
301 }),
302 expect.objectContaining({
303 kind: "line",
304 change: "add",
305 oldLineNumber: null,
306 newLineNumber: 1,
307 content: "const after = 2;",
308 comparison: { change: "delete", tokenIndex: 0 },
309 }),
310 expect.objectContaining({
311 kind: "line",
312 change: "add",
313 oldLineNumber: null,
314 newLineNumber: 2,
315 content: "console.log(after);",
316 comparison: null,
317 }),
318 expect.objectContaining({
319 kind: "line",
320 change: "context",
321 oldLineNumber: 2,
322 newLineNumber: 3,
323 content: "return true;",
324 comparison: null,
325 }),
326 ]);
327 });
328​
329 it("treats truncated patches as partial diffs instead of failing", () => {
330 const parsed = buildReviewParsedDiff(
331 [
332 "diff --git a/apps/mobile/src/a.ts b/apps/mobile/src/a.ts",
333 "index 1111111..2222222 100644",
334 "--- a/apps/mobile/src/a.ts",
335 "+++ b/apps/mobile/src/a.ts",
336 "@@ -1 +1,2 @@",
337 " const before = 1;",
338 "+const after = 2;",
339 "",
340 "[truncated]",
341 ].join("\n"),
342 "unit-truncated",
343 );
344​
345 expect(parsed.kind).toBe("files");
346 if (parsed.kind !== "files") {
347 return;
348 }
349​
350 expect(parsed.notice).toContain("server size cap");
351 expect(parsed.fileCount).toBe(1);
352 expect(parsed.files[0]?.rows[0]).toMatchObject({
353 kind: "hunk",
354 header: "@@ -1,1 +1,2 @@",
355 });
356 });
357});
358​
359describe("buildReviewSectionItems", () => {
360 it("keeps a failed or loading git source selectable beside the other one", () => {
361 const source = (kind: "working-tree" | "branch-range") => ({
362 id: kind,
363 kind,
364 title: kind === "working-tree" ? "Uncommitted" : "Changes",
365 baseRef: "HEAD",
366 headRef: null,
367 diff: "diff --git a/a.ts b/a.ts\n",
368 diffHash: "hash",
369 truncated: false,
370 });
371 const build = (
372 gitSections: ReadonlyArray<ReturnType<typeof source>>,
373 gitSectionStates: Parameters<typeof buildReviewSectionItems>[0]["gitSectionStates"],
374 ) =>
375 buildReviewSectionItems({
376 checkpoints: [],
377 gitSections,
378 turnDiffById: {},
379 gitSectionStates,
380 }).map((section) => [section.id, section.diff === null, section.isLoading]);
381​
382 expect(
383 build([source("working-tree")], { "working-tree": null, "branch-range": "failed" }),
384 ).toEqual([
385 ["git:working-tree", false, false],
386 ["git:branch-range", true, false],
387 ]);
388 expect(
389 build([source("branch-range")], { "working-tree": "loading", "branch-range": null }),
390 ).toEqual([
391 ["git:working-tree", true, true],
392 ["git:branch-range", false, false],
393 ]);
394 });
395});
396​
397describe("applyReviewDiffMetadata", () => {
398 it("uses complete counts even when the preview contains only part of one file", () => {
399 const parsed = buildReviewParsedDiff(
400 [
401 "diff --git a/large.txt b/large.txt",
402 "--- a/large.txt",
403 "+++ b/large.txt",
404 "@@ -1 +1 @@",
405 "-before",
406 "+after",
407 ].join("\n"),
408 "partial",
409 );
410 const result = applyReviewDiffMetadata(parsed, {
411 truncated: true,
412 files: [
413 { path: "large.txt", previousPath: null, additions: 4000, deletions: 3000 },
414 { path: "unseen.txt", previousPath: null, additions: 100, deletions: 20 },
415 ],
416 });
417 expect(result.kind).toBe("files");
418 if (result.kind !== "files") return;
419 expect(result.fileCount).toBe(2);
420 expect(result.additions).toBe(4100);
421 expect(result.deletions).toBe(3020);
422 expect(result.files[0]?.additions).toBe(4000);
423 expect(result.notice).toContain("Counts include all changes");
424 expect(applyReviewDiffMetadata(parsed, null)).toEqual(parsed);
425 });
426});