fix(session-ui): reuse complete patch diffs instead of re-diffing (#54017)

This commit is contained in:
Luke Parker
2026-10-09 08:49:29 +10:00
committed by GitHub
Unverified
parent b5c43a4409
commit 1a8988efe0
2 changed files with 162 additions and 15 deletions
@@ -1,5 +1,8 @@
import { describe, expect, test } from "bun:test"
import { normalize, resolveFileDiff, text } from "./session-diff"
import { parseDiffFromFile } from "@pierre/diffs"
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"
describe("session diff", () => {
test.each([
@@ -86,6 +89,60 @@ describe("session diff", () => {
expect(fileDiff.additionLines).toEqual(["one\n", "new\n"])
})
test("keeps the producer's line alignment for complete patches", () => {
// Valid but not minimal: diffing the rebuilt files again would keep `b` as unchanged context.
const patch = `${header}@@ -1,3 +1,3 @@\n a\n-b\n-c\n+b\n+d\n`
const fileDiff = resolveFileDiff({ file: "a.ts", patch })
expect(fileDiff.isPartial).toBe(false)
expect(fileDiff.hunks.map((hunk) => [hunk.deletionLines, hunk.additionLines])).toEqual([[2, 2]])
// A content diff of the same files has different hunks, so it must not share the highlight identity.
expect(resolveFileDiff({ file: "a.ts", before: "a\nb\nc\n", after: "a\nb\nd\n" }).cacheKey).not.toBe(
fileDiff.cacheKey,
)
})
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"],
["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"],
["a deleted file", "@@ -1,3 +0,0 @@\n-one\n-two\n-three\n"],
["a leading marker", "@@ -1,1 +1,1 @@\n\\ No newline at end of file\n-old\n+new\n"],
["interleaved changes", "@@ -1,4 +1,4 @@\n keep\n-a\n+b\n-c\n+d\n keep\n"],
])("splits complete patches with %s like a fresh file diff", (_, hunk) => {
const patch = `${header}${hunk}`
const contents = completePatchContents(patch)!
const expected = parseDiffFromFile(
{ name: "a.ts", contents: contents.before },
{ name: "a.ts", contents: contents.after },
)
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("collapses unchanged runs in complete patches into the hunks of a fresh file diff", () => {
const before = Array.from({ length: 40 }, (_, index) => `line ${index}\n`)
const after = before.map((line, index) => (index === 3 || index === 30 ? `changed ${index}\n` : line))
const body = before.map((line, index) => (line === after[index] ? ` ${line}` : `-${line}+${after[index]}`)).join("")
const fileDiff = resolveFileDiff({
file: "a.ts",
patch: `${header}@@ -1,40 +1,40 @@\n${body}`,
})
expect(fileDiff.hunks).toHaveLength(2)
expect(fileDiff.hunks).toEqual(
parseDiffFromFile({ name: "a.ts", contents: before.join("") }, { name: "a.ts", contents: after.join("") }).hunks,
)
})
test("keeps ordinary leading tool patches partial", () => {
const fileDiff = resolveFileDiff({
file: "a.ts",
@@ -1,4 +1,4 @@
import { parseDiffFromFile, parsePatchFiles, type FileDiffMetadata } from "@pierre/diffs"
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"
@@ -31,13 +31,10 @@ const diffCacheLimit = 16
const patchFileDiffCache = new Map<string, FileDiffMetadata>()
export function resolveFileDiff(diff: DiffSource) {
if (typeof diff.patch === "string") return fileDiffFromPatch(diff.file, diff.patch)
// Untyped persisted payloads may carry `patch: null`; those render from their contents.
if (diff.patch != null) return fileDiffFromPatch(diff.file, diff.patch)
return fileDiffFromContent(
diff.file,
typeof diff.before === "string" ? diff.before : "",
typeof diff.after === "string" ? diff.after : "",
)
return fileDiffFromContent(diff.file, diff.before ?? "", diff.after ?? "")
}
export function normalize(diff: ReviewDiff): ViewDiff {
@@ -67,15 +64,15 @@ function fileDiffFromPatch(file: string, patch: string) {
return hit
}
const contents = completePatchContents(patch)
const input = contents ? undefined : patchInput(file, patch)
const complete = completePatch(patch)
const input = complete ? undefined : patchInput(file, patch)
const value = contents
? fileDiffFromContent(file, contents.before, contents.after)
const value = complete
? fileDiffFromCompletePatch(file, complete)
: ((input ? parsePatchFiles(input)[0]?.files[0] : undefined) ?? emptyFileDiff(file))
// Complete patches already carry a content key from fileDiffFromContent; partial patches are keyed by the patch text.
value.cacheKey ??= highlightKey(key)
// The patch text fixes both the content and the producer's alignment, so equal keys always mean equal hunks.
value.cacheKey = highlightKey(key)
patchFileDiffCache.set(key, value)
while (patchFileDiffCache.size > diffCacheLimit) patchFileDiffCache.delete(patchFileDiffCache.keys().next().value!)
@@ -84,6 +81,14 @@ function fileDiffFromPatch(file: string, patch: string) {
}
export function completePatchContents(patch: string) {
const complete = completePatch(patch)
if (!complete) return
return { before: complete.before, after: complete.after }
}
function completePatch(patch: string) {
try {
const parsed = parsePatch(patch)[0]
@@ -141,12 +146,97 @@ export function completePatchContents(patch: string) {
const text = (lines: Array<{ text: string; newline: boolean }>) =>
lines.map((line) => line.text + (line.newline ? "\n" : "")).join("")
return { before: text(before), after: text(after) }
return { before: text(before), after: text(after), lines: hunk.lines }
} catch {
return
}
}
// A complete patch already carries the producer's line diff. Splitting its single full-context hunk at long
// unchanged runs yields, in linear time, the collapsed hunks Pierre would get by diffing the reconstructed files
// again whenever both algorithms choose the same alignment.
function fileDiffFromCompletePatch(file: string, patch: { before: string; after: string; lines: string[] }) {
// Pierre reads names back from header text, so a fixed header keeps tabs, quotes, and newlines in `file` intact.
const value =
processFile(`--- a\n+++ a\n${splitHunk(patch.lines)}`, {
isGitDiff: false,
oldFile: { name: file, contents: patch.before },
newFile: { name: file, contents: patch.after },
}) ?? emptyFileDiff(file)
value.name = file
return value
}
// Pierre's file diffs use jsdiff's default of four context lines; longer unchanged runs end one hunk and start the next.
const hunkContext = 4
function splitHunk(lines: string[]) {
const rows = lines.reduce<{ line: string; marker?: string }[]>((result, line) => {
const previous = result.at(-1)
// A marker annotates the line before it; completePatch ignores a marker with nothing to annotate.
if (line.startsWith("\\")) {
if (previous) previous.marker = line
return result
}
result.push({ line })
return result
}, [])
const changes = rows.flatMap((row, index) => (row.line.startsWith(" ") ? [] : [index]))
const ranges = changes.reduce<{ start: number; end: number }[]>((result, index) => {
const previous = result.at(-1)
const start = Math.max(0, index - hunkContext)
const end = Math.min(rows.length - 1, index + hunkContext)
if (previous && start <= previous.end + 1) {
previous.end = end
return result
}
result.push({ start, end })
return result
}, [])
const positions = rows.reduce<{ old: number; new: number }[]>(
(result, row) => {
const current = result.at(-1)!
result.push({
old: current.old + (row.line.startsWith("+") ? 0 : 1),
new: current.new + (row.line.startsWith("-") ? 0 : 1),
})
return result
},
[{ old: 0, new: 0 }],
)
return ranges
.map((range) => {
const start = positions[range.start]!
const end = positions[range.end + 1]!
const oldCount = end.old - start.old
const newCount = end.new - start.new
const body = rows
.slice(range.start, range.end + 1)
.map((row) => (row.marker ? `${row.line}\n${row.marker}` : row.line))
.join("\n")
return `@@ -${oldCount === 0 ? start.old : start.old + 1},${oldCount} +${newCount === 0 ? start.new : start.new + 1},${newCount} @@\n${body}`
})
.join("\n")
}
function patchInput(file: string, patch: string) {
try {
const parsed = parsePatch(patch)[0]