Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import { getDiffLineStat, getRenderablePatch, resolveFileDiffPath } from "./diffRendering";
3import { toolCallDiff } from "./toolCallDiff";
4
5describe("toolCallDiff", () => {
6 it("builds a diff from the before and after snippets of a completed edit", () => {
7 const { patch, content } = toolCallDiff(
8 {
9 fileName: "/workspace/src/file with spaces.ts",
10 oldStr: " validateRetries();\n return options;",
11 newStr: " validateRetries();\n validateAllowance();\n return options;",
12 status: "completed",
13 },
14 "/workspace",
15 );
16 expect(content).toEqual([]);
17 const rendered = getRenderablePatch(patch);
18 expect(rendered?.kind).toBe("files");
19 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
20 expect(resolveFileDiffPath(rendered.files[0]!)).toBe("src/file with spaces.ts");
21 expect(getDiffLineStat(rendered.files)).toEqual({ additions: 1, deletions: 0 });
22 });
23
24 it("renders recorded hunks without reading a repository, including renamed paths", () => {
25 for (const changes of [
26 undefined,
27 [{ operation: "update", oldPath: "old.ts", path: "new.ts" }],
28 ]) {
29 const { patch } = toolCallDiff({
30 fileName: "old.ts",
31 diffStr: "@@ -1 +1 @@\n-before\n+after\n",
32 ...(changes ? { changes } : {}),
33 });
34 const rendered = getRenderablePatch(patch);
35 expect(rendered?.kind).toBe("files");
36 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
37 expect(rendered.files).toHaveLength(1);
38 expect(resolveFileDiffPath(rendered.files[0]!)).toBe(changes ? "new.ts" : "old.ts");
39 expect(rendered.files[0]!.additionLines.join("")).toContain("after");
40 expect(rendered.files[0]!.deletionLines.join("")).toContain("before");
41 }
42 });
43
44 it("renders added and deleted file contents as a file diff", () => {
45 for (const operation of ["add", "delete"]) {
46 for (const [content, ending] of [
47 ["first\nsecond", ""],
48 ["@@ -0,0 +1 @@\n+content", "\n"],
49 ["@@ -1 +0,0 @@\n-content", "\n"],
50 ["first\nsecond", "\n"],
51 ["--- notes\nsecond", "\n"],
52 ["diff --git notes\nsecond", "\n"],
53 ["--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after", "\n"],
54 [
55 "diff --git a/embedded.ts b/embedded.ts\n--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after",
56 "\n",
57 ],
58 ] as const) {
59 const recordedContent = `${content}${ending}`;
60 const rendered = getRenderablePatch(
61 toolCallDiff({
62 fileName: "file with spaces.ts",
63 diffStr: recordedContent,
64 changes: [{ operation, path: "file with spaces.ts" }],
65 }).patch,
66 );
67 expect(rendered?.kind).toBe("files");
68 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
69 expect(resolveFileDiffPath(rendered.files[0]!)).toBe("file with spaces.ts");
70 const file = rendered.files[0]!;
71 const lines = content.split("\n").length;
72 expect(file.additionLines).toHaveLength(operation === "add" ? lines : 0);
73 expect(file.deletionLines).toHaveLength(operation === "delete" ? lines : 0);
74 expect((operation === "add" ? file.additionLines : file.deletionLines).join("")).toBe(
75 recordedContent,
76 );
77 }
78 }
79 });
80
81 it("keeps content-only writes out of the patch and preserves empty recorded content", () => {
82 for (const operation of ["add", "delete"]) {
83 expect(
84 toolCallDiff({
85 fileName: "empty.ts",
86 diffStr: "",
87 changes: [{ operation, path: "empty.ts" }],
88 }).content,
89 ).toEqual([
90 {
91 label: operation === "add" ? "Recorded content after" : "Recorded content before",
92 text: "",
93 },
94 ]);
95 }
96 for (const status of ["running", "cancelled", "failed"] as const) {
97 expect(toolCallDiff({ fileName: "a.ts", oldStr: "before", newStr: "", status })).toEqual({
98 patch: undefined,
99 content: [
100 { label: "Recorded content before", text: "before" },
101 { label: "Recorded content after", text: "" },
102 ],
103 truncated: false,
104 });
105 }
106 expect(toolCallDiff({ fileName: "a.ts", newStr: "after" }).content).toEqual([
107 { label: "Recorded content after", text: "after" },
108 ]);
109 });
110
111 it("removes transport truncation markers before converting file contents", () => {
112 const suffix = "\n… output truncated for transport";
113 const diff = toolCallDiff({
114 fileName: "a.ts",
115 diffStr: `first\nsecond${suffix}`,
116 changes: [{ operation: "add", path: "a.ts" }],
117 });
118 expect(diff.truncated).toBe(true);
119 expect(diff.patch).not.toContain("output truncated");
120 expect(getRenderablePatch(diff.patch)?.kind).toBe("files");
121 expect(toolCallDiff({ fileName: "a.ts", newStr: `content${suffix}` })).toMatchObject({
122 content: [{ label: "Recorded content after", text: "content" }],
123 truncated: true,
124 });
125 expect(toolCallDiff({ fileName: "a.ts", oldStr: `before${suffix}`, newStr: "after" })).toEqual({
126 patch: undefined,
127 content: [
128 { label: "Recorded content before", text: "before" },
129 { label: "Recorded content after", text: "after" },
130 ],
131 truncated: true,
132 });
133 });
134
135 it("names files under the workspace relative to it in headers only", () => {
136 const root = "/Users/me/project";
137 const paths = (patch: string | undefined) => {
138 const rendered = getRenderablePatch(patch);
139 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
140 return rendered.files.map((file) => resolveFileDiffPath(file));
141 };
142 // Claude's Edit: absolute headers; hunk lines that look like headers keep the root.
143 const claude = `--- ${root}/docs/plan.md\n+++ ${root}/docs/plan.md\n@@ -2 +2 @@\n-- ${root}/x\n++ ${root}/y\n`;
144 const { patch } = toolCallDiff({ fileName: `${root}/docs/plan.md`, diffStr: claude }, root);
145 expect(paths(patch)).toEqual(["docs/plan.md"]);
146 expect(patch).toContain(`\n-- ${root}/x\n++ ${root}/y\n`);
147 // Synthesized headers, a trailing separator on the root, and a path outside it.
148 const hunk = "@@ -1 +1 @@\n-x\n+y\n";
149 expect(
150 paths(toolCallDiff({ fileName: `${root}/src/a.ts`, diffStr: hunk }, `${root}/`).patch),
151 ).toEqual(["src/a.ts"]);
152 expect(paths(toolCallDiff({ fileName: "/elsewhere/b.ts", diffStr: hunk }, root).patch)).toEqual(
153 ["/elsewhere/b.ts"],
154 );
155 // A relative path, and on POSIX a backslash that is part of a name, keep theirs.
156 for (const [fileName, workspace] of [
157 ["repo/src/a.ts", "/repo"],
158 ["/repo/back/slash/a.ts", "/repo/back\\slash"],
159 ] as const) {
160 const diffStr = `--- ${fileName}\n+++ ${fileName}\n${hunk}`;
161 expect(toolCallDiff({ fileName, diffStr }, workspace).patch).toBe(diffStr);
162 }
163 const backslash = toolCallDiff(
164 { fileName: "/repo/back\\slash/a.ts", diffStr: hunk },
165 "/repo/back\\slash",
166 ).patch;
167 expect(paths(backslash)).toEqual(["a.ts"]);
168 // Each file of a multi-file patch; a path that merely contains the root keeps it.
169 const twoFiles = [
170 `diff --git a/${root}/a.ts b/${root}/a.ts`,
171 `--- a/${root}/a.ts`,
172 `+++ b/${root}/a.ts`,
173 hunk.trimEnd(),
174 `diff --git a/backup${root}/b.ts b/backup${root}/b.ts`,
175 `--- a/backup${root}/b.ts`,
176 `+++ b/backup${root}/b.ts`,
177 hunk,
178 ].join("\n");
179 expect(
180 paths(toolCallDiff({ fileName: `${root}/a.ts`, diffStr: twoFiles }, root).patch),
181 ).toEqual(["a.ts", `backup${root}/b.ts`]);
182 // Only where a name starts: a quoted name with a space before the root.
183 expect(
184 paths(toolCallDiff({ fileName: `${root}/docs ${root}/a.md`, diffStr: hunk }, root).patch),
185 ).toEqual([`docs ${root}/a.md`]);
186 expect(
187 paths(toolCallDiff({ fileName: `/backup ${root}/a.md`, diffStr: hunk }, root).patch),
188 ).toEqual([`/backup ${root}/a.md`]);
189 // Windows paths, which a quoted header escapes, compared without case.
190 const windows = toolCallDiff(
191 { fileName: "C:\\repo\\src\\a.ts", diffStr: hunk },
192 "c:\\repo",
193 ).patch;
194 expect(paths(windows)).toEqual(["src\\a.ts"]);
195 });
196
197 it.each(['/repo"name', "/repo\tname"])("relativizes synthesized headers under %j", (root) => {
198 const diffStr = "@@ -1 +1 @@\n-x\n+y\n";
199 const { patch } = toolCallDiff({ fileName: `${root}/src/a.ts`, diffStr }, root);
200 const rendered = getRenderablePatch(patch);
201 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
202 expect(patch?.endsWith(diffStr)).toBe(true);
203 expect(rendered.files.map(resolveFileDiffPath)).toEqual(["src/a.ts"]);
204 });
205
206 it("keeps a tab inside a quoted Claude Write filename", () => {
207 const diffStr = '--- /dev/null\n+++ "/w/name\\tpart.txt"\n@@ -0,0 +1,1 @@\n+hello\n';
208 const rendered = getRenderablePatch(
209 toolCallDiff({ fileName: "/w/name\tpart.txt", diffStr }, "/w").patch,
210 );
211 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
212 expect(rendered.files.map((file) => resolveFileDiffPath(file))).toEqual(["name\tpart.txt"]);
213 expect(getDiffLineStat(rendered.files)).toEqual({ additions: 1, deletions: 0 });
214 });
215
216 it("preserves a multi-file patch whose first change is an empty file", () => {
217 const diffStr = [
218 'diff --git "a/empty.ts" "b/empty.ts"',
219 "--- /dev/null",
220 '+++ "b/empty.ts"',
221 'diff --git "a/c.ts" "b/c.ts"',
222 '--- "a/c.ts"',
223 '+++ "b/c.ts"',
224 "@@ -1 +1 @@",
225 "-before",
226 "+after",
227 'diff --git "a/gone.ts" "b/gone.ts"',
228 '--- "a/gone.ts"',
229 "+++ /dev/null",
230 "",
231 ].join("\n");
232 const { patch } = toolCallDiff({
233 fileName: "empty.ts",
234 diffStr,
235 changes: [
236 { operation: "add", path: "empty.ts" },
237 { operation: "update", path: "c.ts" },
238 { operation: "delete", path: "gone.ts" },
239 ],
240 });
241 expect(patch).toBe(diffStr);
242 });
243
244 it("keeps both files of a multi-file add whose first path has a control character", () => {
245 const diffStr = [
246 'diff --git "a//w/odd\\aname.txt" "b//w/odd\\aname.txt"',
247 "--- /dev/null",
248 '+++ "b//w/odd\\aname.txt"',
249 "@@ -0,0 +1,1 @@",
250 "+hello",
251 'diff --git "a//w/z-normal.txt" "b//w/z-normal.txt"',
252 "--- /dev/null",
253 '+++ "b//w/z-normal.txt"',
254 "@@ -0,0 +1,1 @@",
255 "+hello",
256 "",
257 ].join("\n");
258 const { patch } = toolCallDiff(
259 {
260 fileName: "/w/odd\u0007name.txt",
261 diffStr,
262 status: "completed",
263 changes: [
264 { operation: "add", path: "/w/odd\u0007name.txt" },
265 { operation: "add", path: "/w/z-normal.txt" },
266 ],
267 },
268 "/w",
269 );
270 const rendered = getRenderablePatch(patch);
271 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
272 expect(rendered.files.map(resolveFileDiffPath)).toEqual(["odd\u0007name.txt", "z-normal.txt"]);
273 expect(rendered.files.map((file) => file.additionLines)).toEqual([["hello\n"], ["hello\n"]]);
274 });
275
276 it("keeps multi-file OpenCode patches whole but wraps a lone added file's Index: contents", () => {
277 // Captured from OpenCode 1.19.4 apply_patch.
278 const file = (path: string, hunk = "") =>
279 `Index: ${path}\n${"=".repeat(67)}\n--- ${path}\n+++ ${path}\n${hunk}\n`;
280 const added = file("/w/new.txt", "@@ -0,0 +1,1 @@\n+new\n");
281 const add = { operation: "add", path: "/w/new.txt" };
282 for (const [diffStr, second] of [
283 [added + file("/w/empty.txt"), { operation: "add", path: "/w/empty.txt" }],
284 [
285 added + file("/w/a.txt", "@@ -1 +1 @@\n-old\n+changed\n"),
286 { operation: "move", path: "/w/b.txt", oldPath: "/w/a.txt" },
287 ],
288 [
289 `${added}\nIndex: /w/cut.txt\n${"=".repeat(67)}\n--- /w/cut.txt\n+++ /w/c`,
290 { operation: "add", path: "/w/cut.txt" },
291 ],
292 ] as const) {
293 expect(toolCallDiff({ fileName: add.path, diffStr, changes: [add, second] }).patch).toBe(
294 diffStr,
295 );
296 }
297 expect(toolCallDiff({ fileName: add.path, diffStr: added, changes: [add] }).patch).toContain(
298 "+Index: /w/new.txt\n",
299 );
300 const paths = (patch: string | undefined) => {
301 const rendered = getRenderablePatch(patch);
302 if (rendered?.kind !== "files") throw new Error("Expected a file diff");
303 return rendered.files.map(resolveFileDiffPath);
304 };
305 const multi =
306 file("/w/new.txt", "@@ -1 +1 @@\n--- /w/x\n+++ /w/y\n") +
307 file("/w/second.txt", "@@ -1 +1 @@\n-old\n+new\n") +
308 file("/w/empty.txt");
309 const { patch: relPatch } = toolCallDiff(
310 {
311 fileName: add.path,
312 diffStr: multi,
313 changes: [
314 add,
315 { operation: "update", path: "/w/second.txt" },
316 { operation: "add", path: "/w/empty.txt" },
317 ],
318 },
319 "/w",
320 );
321 expect(paths(relPatch)).toEqual(["new.txt", "second.txt", "empty.txt"]);
322 expect(relPatch).toContain("\n--- /w/x\n+++ /w/y\n");
323 });
324
325 it("keeps a truncated multi-file git patch's complete files when cut inside a later file header", () => {
326 for (const operation of ["add", "delete"] as const) {
327 const firstFile = [
328 'diff --git "a/first.ts" "b/first.ts"',
329 `--- ${operation === "add" ? "/dev/null" : '"a/first.ts"'}`,
330 `+++ ${operation === "add" ? '"b/first.ts"' : "/dev/null"}`,
331 operation === "add" ? "@@ -0,0 +1,1 @@" : "@@ -1,1 +0,0 @@",
332 operation === "add" ? "+first" : "-first",
333 "",
334 ].join("\n");
335 const { patch } = toolCallDiff({
336 fileName: "first.ts",
337 diffStr: `${firstFile}diff --git "a/second.ts" "b/sec\n… output truncated for transport`,
338 changes: [
339 { operation, path: "first.ts" },
340 { operation: "update", path: "second.ts" },
341 ],
342 });
343 expect(patch).toBe(firstFile);
344 }
345 });
346
347 it("wraps one added file whose content repeats its own hunk-less header", () => {
348 const diffStr = ["diff --git a/a.patch b/a.patch", "diff --git a/a.patch b/a.patch", ""].join(
349 "\n",
350 );
351 const { patch } = toolCallDiff({
352 fileName: "a.patch",
353 diffStr,
354 changes: [{ operation: "add", path: "a.patch" }],
355 });
356 expect(patch).toContain("@@ -0,0 +1,2 @@\n+diff --git a/a.patch b/a.patch\n");
357 });
358
359 it("preserves complete patches and unsupported provider output", () => {
360 for (const operation of ["add", "delete"]) {
361 const diffStr = [
362 "diff --git a/a.ts b/a.ts",
363 `--- ${operation === "add" ? "/dev/null" : "a/a.ts"}`,
364 `+++ ${operation === "add" ? "b/a.ts" : "/dev/null"}`,
365 operation === "add" ? "@@ -0,0 +1 @@" : "@@ -1 +0,0 @@",
366 operation === "add" ? "+content" : "-content",
367 "",
368 ].join("\n");
369 expect(
370 toolCallDiff({ fileName: "a.ts", diffStr, changes: [{ operation, path: "a.ts" }] }).patch,
371 ).toBe(diffStr);
372 }
373 for (const diffStr of [
374 undefined,
375 "",
376 "provider output",
377 "--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n",
378 ]) {
379 expect(
380 toolCallDiff({ fileName: "a.ts", ...(diffStr === undefined ? {} : { diffStr }) }).patch,
381 ).toBe(diffStr);
382 }
383 });
384});