diff --git a/packages/app/src/utils/tool-call-parsers.test.ts b/packages/app/src/utils/tool-call-parsers.test.ts index 9fb7f66c8e..0591afa445 100644 --- a/packages/app/src/utils/tool-call-parsers.test.ts +++ b/packages/app/src/utils/tool-call-parsers.test.ts @@ -62,6 +62,20 @@ describe("tool-call-parsers", () => { expect(parsed.find((entry) => entry.type === "add")?.content).toBe("+new"); }); + it("keeps changed lines that start with two diff markers", () => { + const parsed = parseUnifiedDiff( + ["--- a/counter.ts", "+++ b/counter.ts", "@@ -1 +1 @@", "---counter;", "+++counter;"].join( + "\n", + ), + ); + + expect(parsed).toEqual([ + { type: "header", content: "@@ -1 +1 @@" }, + { type: "remove", content: "---counter;" }, + { type: "add", content: "+++counter;" }, + ]); + }); + it("keeps file headers in multi-file diffs", () => { const parsed = parseUnifiedDiff( [ diff --git a/packages/app/src/utils/tool-call-parsers.ts b/packages/app/src/utils/tool-call-parsers.ts index c57829a16b..bc0bbe9e7d 100644 --- a/packages/app/src/utils/tool-call-parsers.ts +++ b/packages/app/src/utils/tool-call-parsers.ts @@ -162,47 +162,53 @@ export function parseUnifiedDiff(diffText?: string): DiffLine[] { const fileHeaders = lines.filter((line) => line.startsWith("diff --git ")); const hasMultipleFiles = fileHeaders.length > 1; const diff: DiffLine[] = []; + let oldLinesRemaining = 0; + let newLinesRemaining = 0; for (const line of lines) { - if (!line.length) { - diff.push({ type: "context", content: line }); + if (line.startsWith("diff --git ")) { + oldLinesRemaining = 0; + newLinesRemaining = 0; + if (hasMultipleFiles) diff.push({ type: "header", content: line }); continue; } - const isFileHeader = hasMultipleFiles && line.startsWith("diff --git "); - if (line.startsWith("@@") || isFileHeader) { + if (line.startsWith("@@")) { + const range = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line); + oldLinesRemaining = Number(range?.[1] ?? 1); + newLinesRemaining = Number(range?.[2] ?? 1); diff.push({ type: "header", content: line }); continue; } + const inHunk = oldLinesRemaining > 0 || newLinesRemaining > 0; if (line.startsWith("+")) { - if (!line.startsWith("+++")) { + if (inHunk || !line.startsWith("+++")) { diff.push({ type: "add", content: line }); + newLinesRemaining--; } continue; } if (line.startsWith("-")) { - if (!line.startsWith("---")) { + if (inHunk || !line.startsWith("---")) { diff.push({ type: "remove", content: line }); + oldLinesRemaining--; } continue; } - if ( - line.startsWith("diff --git") || - line.startsWith("index ") || - line.startsWith("---") || - line.startsWith("+++") - ) { - continue; - } + if (line.startsWith("index ")) continue; if (line.startsWith("\\ No newline")) { diff.push({ type: "header", content: line }); continue; } + if (line.startsWith(" ")) { + oldLinesRemaining--; + newLinesRemaining--; + } diff.push({ type: "context", content: line }); }