diff --git a/packages/session-ui/src/components/session-diff.test.ts b/packages/session-ui/src/components/session-diff.test.ts index 67550635325..d02c862be79 100644 --- a/packages/session-ui/src/components/session-diff.test.ts +++ b/packages/session-ui/src/components/session-diff.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "bun:test" import { parseDiffFromFile } from "@pierre/diffs" +import { createTwoFilesPatch } from "diff" import { completePatchContents, normalize, resolveFileDiff, text } from "./session-diff" const header = "diff --git a/a.ts b/a.ts\nindex 1a2b3c4..5d6e7f8 100644\n--- a/a.ts\n+++ b/a.ts\n" @@ -103,7 +104,10 @@ describe("session diff", () => { }) test.each([ - ["missing final newlines", "@@ -1,2 +1,2 @@\n one\n-two\n\\ No newline at end of file\n+three\n\\ No newline at end of file\n"], + [ + "missing final newlines", + "@@ -1,2 +1,2 @@\n one\n-two\n\\ No newline at end of file\n+three\n\\ No newline at end of file\n", + ], ["an added final newline", "@@ -1,2 +1,2 @@\n one\n-two\n\\ No newline at end of file\n+two\n"], ["CRLF lines", "@@ -1,3 +1,3 @@\n one\r\n-two\r\n+three\r\n four\r\n"], ["a new file", "@@ -0,0 +1,3 @@\n+one\n+two\n+three\n"], @@ -119,13 +123,19 @@ describe("session diff", () => { { name: "a.ts", contents: contents.after }, ) - expect({ ...resolveFileDiff({ file: "a.ts", patch }), cacheKey: undefined }).toEqual({ ...expected, cacheKey: undefined }) + expect({ ...resolveFileDiff({ file: "a.ts", patch }), cacheKey: undefined }).toEqual({ + ...expected, + cacheKey: undefined, + }) }) - test.each(["a\tb.ts", "a\nb.ts", '"quoted"', " padded.ts "])("keeps the exact file name %j for complete patches", (file) => { - expect(resolveFileDiff({ file, patch: `${header}@@ -1,2 +1,2 @@\n one\n-old\n+new\n` }).name).toBe(file) - expect(resolveFileDiff({ file, patch: `${header}@@ -0,0 +0,0 @@\n` }).name).toBe(file) - }) + test.each(["a\tb.ts", "a\nb.ts", '"quoted"', " padded.ts "])( + "keeps the exact file name %j for complete patches", + (file) => { + expect(resolveFileDiff({ file, patch: `${header}@@ -1,2 +1,2 @@\n one\n-old\n+new\n` }).name).toBe(file) + expect(resolveFileDiff({ file, patch: `${header}@@ -0,0 +0,0 @@\n` }).name).toBe(file) + }, + ) test("collapses unchanged runs in complete patches into the hunks of a fresh file diff", () => { const before = Array.from({ length: 40 }, (_, index) => `line ${index}\n`) @@ -188,16 +198,16 @@ describe("session diff", () => { expect(resolveFileDiff({ file: "b.ts", patch }).name).toBe("b.ts") }) - test.each([ - "@@ -1 +1 @@\n-old\n+new\n", - "--- a.ts\t\n+++ a.ts\t\n@@ -1 +1 @@\n-old\n+new\n", - ])("reuses a highlight identity for the same cached patch: %s", (patch) => { - const first = resolveFileDiff({ file: "a.ts", patch }) - expect(first.cacheKey).toBeString() - expect(resolveFileDiff({ file: "a.ts", patch }).cacheKey).toBe(first.cacheKey) - expect(resolveFileDiff({ file: "b.ts", patch }).cacheKey).not.toBe(first.cacheKey) - expect(resolveFileDiff({ file: "a.ts", patch: patch.replace("+new", "+next") }).cacheKey).not.toBe(first.cacheKey) - }) + test.each(["@@ -1 +1 @@\n-old\n+new\n", "--- a.ts\t\n+++ a.ts\t\n@@ -1 +1 @@\n-old\n+new\n"])( + "reuses a highlight identity for the same cached patch: %s", + (patch) => { + const first = resolveFileDiff({ file: "a.ts", patch }) + expect(first.cacheKey).toBeString() + expect(resolveFileDiff({ file: "a.ts", patch }).cacheKey).toBe(first.cacheKey) + expect(resolveFileDiff({ file: "b.ts", patch }).cacheKey).not.toBe(first.cacheKey) + expect(resolveFileDiff({ file: "a.ts", patch: patch.replace("+new", "+next") }).cacheKey).not.toBe(first.cacheKey) + }, + ) test("keys preloaded content diffs by file name and content", () => { const diff = { file: "a.ts", before: "one\n", after: "two\n", additions: 1, deletions: 1 } @@ -212,8 +222,9 @@ describe("session diff", () => { const patch = "@@ -1 +1 @@\n-old\n+new\n" const first = resolveFileDiff({ file: "evicted.ts", patch }) - const keys = Array.from({ length: 20 }, (_, index) => - resolveFileDiff({ file: "evicted.ts", patch: patch.replace("+new", `+new${index}`) }).cacheKey, + const keys = Array.from( + { length: 20 }, + (_, index) => resolveFileDiff({ file: "evicted.ts", patch: patch.replace("+new", `+new${index}`) }).cacheKey, ) expect(keys).not.toContain(first.cacheKey) @@ -266,4 +277,75 @@ describe("session diff", () => { expect(text(view, "deletions")).toBe("") expect(text(view, "additions")).toBe("") }) + + describe("real patches", () => { + const before = Array.from({ length: 30 }, (_, index) => `const line${index} = ${index}\n`).join("") + const after = before.replace("const line3 = 3\n", "const line3 = 33\n").replace("const line25 = 25\n", "") + const sum = 'import { a } from "./a"\n\nexport function sum(x: number, y: number) {\n return x + y\n}\n' + + const git = (header: string) => + `diff --git ${header}\nindex da208dc..e8d3c2d 100644\n--- ${header.split(" ")[0]}\n+++ ${header.split(" ")[1]}\n@@ -1,5 +1,5 @@\n import { a } from "./a"\n \n-export function sum(x: number, y: number) {\n- return x + y\n+export function sum(x: number, y: number, z = 0) {\n+ return x + y + z\n }\n` + + test("reads an edit tool patch as partial hunks", () => { + // The edit and write tools call createTwoFilesPatch with jsdiff's default context and no headers. + const fileDiff = resolveFileDiff({ + file: "src/lines.ts", + patch: createTwoFilesPatch("src/lines.ts", "src/lines.ts", before, after), + }) + + expect(fileDiff.name).toBe("src/lines.ts") + expect(fileDiff.isPartial).toBe(true) + expect( + fileDiff.hunks.map((hunk) => [hunk.deletionStart, hunk.deletionCount, hunk.additionStart, hunk.additionCount]), + ).toEqual([ + [1, 8, 1, 8], + [22, 9, 22, 8], + ]) + expect(fileDiff.deletionLines).toContain("const line3 = 3\n") + expect(fileDiff.additionLines).toContain("const line3 = 33\n") + expect(fileDiff.additionLines).not.toContain("const line25 = 25\n") + }) + + test.each([ + ["an edit", before, after], + ["a new file", "", "one\ntwo\n"], + ["a deleted file", "one\ntwo\n", ""], + ["CRLF lines without a final newline", "one\r\ntwo\r\nthree", "one\r\n2\r\nthree"], + ["an added final newline", "one\ntwo", "one\ntwo\n"], + ])("renders a full-context snapshot patch of %s like a fresh file diff", (_, before, after) => { + const patch = createTwoFilesPatch("a.ts", "a.ts", before, after, "", "", { context: 2_147_483_647 }) + + expect(completePatchContents(patch)).toEqual({ before, after }) + expect({ ...resolveFileDiff({ file: "a.ts", patch }), cacheKey: undefined }).toEqual({ + ...parseDiffFromFile({ name: "a.ts", contents: before }, { name: "a.ts", contents: after }), + cacheKey: undefined, + }) + }) + + test.each(["a/sum.ts b/sum.ts", "sum.ts sum.ts", "i/sum.ts w/sum.ts"])( + "renders a full-context git patch with header %j as a complete diff", + (header) => { + // Git's diff.noprefix and diff.mnemonicPrefix settings change the header, not the hunks. + expect(completePatchContents(git(header))).toEqual({ + before: sum, + after: sum.replace("y: number)", "y: number, z = 0)").replace("x + y\n", "x + y + z\n"), + }) + expect(resolveFileDiff({ file: "sum.ts", patch: git(header) }).isPartial).toBe(false) + }, + ) + + test("keeps a missing final newline from a real CRLF git patch", () => { + const patch = + "diff --git a/crlf.txt b/crlf.txt\nindex bc16163..88fdbd5 100644\n--- a/crlf.txt\n+++ b/crlf.txt\n@@ -1,3 +1,3 @@\n one\r\n-two\r\n+2\r\n three\n\\ No newline at end of file\n" + + expect(completePatchContents(patch)).toEqual({ before: "one\r\ntwo\r\nthree", after: "one\r\n2\r\nthree" }) + }) + + test("ignores an edit tool patch whose hunk lost a line", () => { + const patch = createTwoFilesPatch("a.ts", "a.ts", before, after).replace(" const line1 = 1\n", "") + + expect(resolveFileDiff({ file: "a.ts", patch }).hunks).toEqual([]) + expect(completePatchContents(patch)).toBeUndefined() + }) + }) }) diff --git a/packages/session-ui/src/components/session-diff.ts b/packages/session-ui/src/components/session-diff.ts index abd0ba4d32a..05e2c6cad9f 100644 --- a/packages/session-ui/src/components/session-diff.ts +++ b/packages/session-ui/src/components/session-diff.ts @@ -1,5 +1,4 @@ import { parseDiffFromFile, parsePatchFiles, processFile, type FileDiffMetadata } from "@pierre/diffs" -import { parsePatch } from "diff" import { checksum } from "@opencode/util/encode" import type { FileDiffInfo } from "@opencode/client/promise" import type { PresentationFileDiff } from "../file-presentation" @@ -65,11 +64,10 @@ function fileDiffFromPatch(file: string, patch: string) { } const complete = completePatch(patch) - const input = complete ? undefined : patchInput(file, patch) const value = complete ? fileDiffFromCompletePatch(file, complete) - : ((input ? parsePatchFiles(input)[0]?.files[0] : undefined) ?? emptyFileDiff(file)) + : (partialFileDiff(file, patch) ?? emptyFileDiff(file)) // The patch text fixes both the content and the producer's alignment, so equal keys always mean equal hunks. value.cacheKey = highlightKey(key) @@ -89,64 +87,84 @@ export function completePatchContents(patch: string) { } function completePatch(patch: string) { - try { - const parsed = parsePatch(patch)[0] + const parsed = splitPatch(patch) - if (!parsed || (!parsed.index && !parsed.oldFileName && !parsed.newFileName)) return + if (!parsed) return - // Snapshot and VCS producers request full context. Tool patches use jsdiff's shorter default context. - if (!patch.startsWith("diff --git ") && !/^--- [^\n]*\t\r?\n\+\+\+ [^\n]*\t(?:\r?\n|$)/m.test(patch)) return + // Snapshot and VCS producers request full context. Tool patches use jsdiff's shorter default context. + if (!parsed.header.startsWith("diff --git ") && !/^--- [^\n]*\t\r?\n\+\+\+ [^\n]*\t(?:\r?\n|$)/m.test(parsed.header)) + return - // Full patches collapse into one leading hunk. Separated hunks omit ranges and must stay partial. - if (parsed.hunks.length !== 1) return + // Full patches collapse into one leading hunk. Separated hunks omit ranges and must stay partial. + if (parsed.hunks.length !== 1) return - const hunk = parsed.hunks[0] + const hunk = parsed.hunks[0]! - if (!hunk || hunk.oldStart > 1 || hunk.newStart > 1) return + // An empty side's start names the line before the hunk, so `-1,0` begins after line 1. + if (hunk.deletionStart + (hunk.deletionCount ? 0 : 1) > 1 || hunk.additionStart + (hunk.additionCount ? 0 : 1) > 1) + return - const before: Array<{ text: string; newline: boolean }> = [] - const after: Array<{ text: string; newline: boolean }> = [] - let previous: "-" | "+" | " " | undefined + const lines: string[] = [] + const before: Array<{ text: string; newline: boolean }> = [] + const after: Array<{ text: string; newline: boolean }> = [] + let previous: "-" | "+" | " " | undefined - for (const line of hunk.lines) { - if (line.startsWith("\\")) { - if (previous === "-" || previous === " ") { - const value = before.at(-1) + for (const line of parsed.body.split("\n").slice(1)) { + if (before.length >= hunk.deletionCount && after.length >= hunk.additionCount && !line.startsWith("\\")) break + lines.push(line) - if (value) value.newline = false - } + if (line.startsWith("\\")) { + if (previous === "-" || previous === " ") { + const value = before.at(-1) - if (previous === "+" || previous === " ") { - const value = after.at(-1) - - if (value) value.newline = false - } - - continue + if (value) value.newline = false } - if (line.startsWith("-")) { - before.push({ text: line.slice(1), newline: true }) - previous = "-" - continue + if (previous === "+" || previous === " ") { + const value = after.at(-1) + + if (value) value.newline = false } - if (line.startsWith("+")) { - after.push({ text: line.slice(1), newline: true }) - previous = "+" - continue - } - - if (!line.startsWith(" ")) return - before.push({ text: line.slice(1), newline: true }) - after.push({ text: line.slice(1), newline: true }) - previous = " " + continue } - const text = (lines: Array<{ text: string; newline: boolean }>) => - lines.map((line) => line.text + (line.newline ? "\n" : "")).join("") + if (line.startsWith("-")) { + before.push({ text: line.slice(1), newline: true }) + previous = "-" + continue + } - return { before: text(before), after: text(after), lines: hunk.lines } + if (line.startsWith("+")) { + after.push({ text: line.slice(1), newline: true }) + previous = "+" + continue + } + + before.push({ text: line.slice(1), newline: true }) + after.push({ text: line.slice(1), newline: true }) + previous = " " + } + + const text = (lines: Array<{ text: string; newline: boolean }>) => + lines.map((line) => line.text + (line.newline ? "\n" : "")).join("") + + return { before: text(before), after: text(after), lines } +} + +// Splits a one-file patch at its first hunk. Pierre's strict parser checks the hunks behind a fixed header, so a +// malformed hunk rejects the patch while unusual file headers stay readable. +function splitPatch(patch: string) { + const start = patch.search(/^@@ /m) + const header = start === -1 ? patch : patch.slice(0, start) + const body = start === -1 ? "" : patch.slice(start) + + try { + const hunks = body + ? (processFile(`--- a\n+++ a\n${body}`, { isGitDiff: false, throwOnError: true })?.hunks ?? []) + : [] + + return { header, body, hunks } } catch { return } @@ -237,20 +255,18 @@ function splitHunk(lines: string[]) { .join("\n") } -function patchInput(file: string, patch: string) { - try { - const parsed = parsePatch(patch)[0] +function partialFileDiff(file: string, patch: string) { + const parsed = splitPatch(patch) - if (!parsed) return + if (!parsed) return - if (parsed.index || parsed.oldFileName || parsed.newFileName) return patch + if (/^(?:Index:|diff(?: -r \w+)+|---|\+\+\+)\s/m.test(parsed.header)) return parsePatchFiles(patch)[0]?.files[0] - if (!parsed.hunks.length) return + if (!parsed.hunks.length) return - return `Index: ${file}\n===================================================================\n--- ${file}\t\n+++ ${file}\t\n${patch}` - } catch { - return - } + return parsePatchFiles( + `Index: ${file}\n===================================================================\n--- ${file}\t\n+++ ${file}\t\n${patch}`, + )[0]?.files[0] } function fileDiffFromContent(file: string, before: string, after: string) {