Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andOuyang Xingyuan 8cc28cd78f fix(app): keep increment and decrement lines in Edit diffs
A changed line inside a hunk can start with the same marker as a file header. Use the hunk ranges to preserve those lines in tool output.

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
2026-11-30 06:46:36 +00:00
Ouyang Xingyuan c45689d1ba fix(server): compact oversized edit diffs before timeline budget truncation 2026-11-30 06:44:47 +00:00
4 changed files with 448 additions and 20 deletions
@@ -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(
[
+20 -14
View File
@@ -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 });
}
@@ -145,4 +145,153 @@ describe("agent timeline content", () => {
});
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("preserves a late-file edit in oversized full-file oldString/newString payloads", () => {
const lines = Array.from(
{ length: 800 },
(_, index) => `export const row_${index} = "${"x".repeat(70)}";`,
);
const oldString = `${lines.join("\n")}\n`;
const updated = [...lines];
updated[760] = 'export const row_760 = "UPDATED_AT_LINE_761";';
const newString = `${updated.join("\n")}\n`;
expect(oldString.length).toBeGreaterThan(64 * 1024);
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "late-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/theoryContentEn.ts",
oldString,
newString,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toContain("row_757");
expect(item.detail.oldString).toContain("row_760");
expect(item.detail.oldString).toContain("row_763");
expect(item.detail.newString).toContain("UPDATED_AT_LINE_761");
expect(item.detail.oldString).not.toContain("row_0");
expect(item.detail.oldString).not.toContain("…[truncated");
expect(item.detail.newString).not.toContain("…[truncated");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("compacts far-apart edits in an oversized file into a multi-hunk unifiedDiff", () => {
const lines = Array.from(
{ length: 900 },
(_, index) => `const entry_${index} = "${"y".repeat(70)}";`,
);
const oldString = `${lines.join("\n")}\n`;
const updated = [...lines];
updated[5] = 'const entry_5 = "EARLY_CHANGE";';
updated[850] = 'const entry_850 = "LATE_CHANGE";';
const newString = `${updated.join("\n")}\n`;
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "scattered-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/large.ts",
oldString,
newString,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toBeUndefined();
expect(item.detail.newString).toBeUndefined();
expect(item.detail.unifiedDiff).toContain("@@ -3,7 +3,7 @@");
expect(item.detail.unifiedDiff).toContain('+const entry_5 = "EARLY_CHANGE";');
expect(item.detail.unifiedDiff).toContain("@@ -848,7 +848,7 @@");
expect(item.detail.unifiedDiff).toContain('+const entry_850 = "LATE_CHANGE";');
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("collapses an identical oversized edit payload to empty strings", () => {
const text = Array.from({ length: 800 }, (_, i) => `line ${i}: ${"z".repeat(80)}`).join("\n");
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "noop-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/same.ts",
oldString: text,
newString: text,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toBe("");
expect(item.detail.newString).toBe("");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("bounds massive full-file rewrites past the Myers distance cap without blowing up", () => {
const oldString = Array.from({ length: 1000 }, (_, i) => `old ${i}: ${"a".repeat(80)}`).join(
"\n",
);
const newString = Array.from({ length: 1000 }, (_, i) => `new ${i}: ${"b".repeat(80)}`).join(
"\n",
);
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "rewrite-edit",
name: "edit",
status: "completed",
error: null,
detail: {
type: "edit",
filePath: "/repo/src/rewrite.ts",
oldString,
newString,
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toContain("old 0:");
expect(item.detail.newString).toContain("new 0:");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("keeps small edit snippets untouched when an oversized error exceeds the budget", () => {
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "small-edit-big-error",
name: "edit",
status: "failed",
error: { message: "e".repeat(100 * 1024) },
detail: {
type: "edit",
filePath: "/repo/src/small.ts",
oldString: "a\nb\nc\nd\ne\nf\ng",
newString: "a\nb\nc\nd\ne\nf\nG",
},
});
if (item.type !== "tool_call" || item.detail.type !== "edit") throw new Error("shape");
expect(item.detail.oldString).toBe("a\nb\nc\nd\ne\nf\ng");
expect(item.detail.newString).toBe("a\nb\nc\nd\ne\nf\nG");
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
});
});
@@ -14,6 +14,8 @@ const MARKER_COST = 32;
// Ids, names, paths and queries stay whole, so an item keeps its identity across passes.
const SHORT_STRING = 1024;
const MAX_DEPTH = 64;
const EDIT_CONTEXT_LINES = 3;
const EDIT_MAX_DIFF_DISTANCE = 256;
// The app registers renderer kinds under the plugin ID rule, so stored kinds must use that format.
export function assertPluginTimelineKind(kind: string): void {
@@ -135,21 +137,278 @@ function cut(value: unknown, depth: number, state: CutState): unknown {
return value;
}
/** Returns the item itself when it fits its budget; otherwise a copy with its largest strings cut. */
export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem {
const budget = item.type === "tool_call" ? TOOL_CALL_BUDGET : ITEM_BUDGET;
type EditToolCallDetail = Extract<
Extract<AgentTimelineItem, { type: "tool_call" }>["detail"],
{ type: "edit" }
>;
interface EditDiffOp {
kind: "eq" | "del" | "add";
oldIdx: number;
newIdx: number;
}
interface EditDiffSpan {
oldLines: readonly string[];
newLines: readonly string[];
start: number;
oldEnd: number;
newEnd: number;
}
function splitEditLines(
oldText: string,
newText: string,
): {
oldLines: string[];
newLines: string[];
} {
let normalizedOld = oldText.replace(/\r\n/g, "\n");
let normalizedNew = newText.replace(/\r\n/g, "\n");
if (normalizedOld.endsWith("\n") && normalizedNew.endsWith("\n")) {
normalizedOld = normalizedOld.slice(0, -1);
normalizedNew = normalizedNew.slice(0, -1);
}
return {
oldLines: normalizedOld.split("\n"),
newLines: normalizedNew.split("\n"),
};
}
interface MyersTrace {
trace: Int32Array[];
distance: number;
offset: number;
}
function shouldMoveDown(v: Int32Array, offset: number, d: number, k: number): boolean {
return k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]);
}
function computeMyersTrace(span: EditDiffSpan): MyersTrace | null {
const { oldLines, newLines, start, oldEnd, newEnd } = span;
const oldLen = oldEnd - start;
const newLen = newEnd - start;
const maxDistance = Math.min(EDIT_MAX_DIFF_DISTANCE, oldLen + newLen);
const offset = maxDistance;
const v = new Int32Array(2 * maxDistance + 1);
const trace: Int32Array[] = [];
for (let d = 0; d <= maxDistance; d += 1) {
trace.push(v.slice());
for (let k = -d; k <= d; k += 2) {
const moveDown = shouldMoveDown(v, offset, d, k);
let x = moveDown ? v[offset + k + 1] : v[offset + k - 1] + 1;
let y = x - k;
while (x < oldLen && y < newLen && oldLines[start + x] === newLines[start + y]) {
x += 1;
y += 1;
}
v[offset + k] = x;
if (x >= oldLen && y >= newLen) {
return { trace, distance: d, offset };
}
}
}
return null;
}
function diffLineSlice(span: EditDiffSpan): EditDiffOp[] | null {
const result = computeMyersTrace(span);
if (!result) return null;
const { start, oldEnd, newEnd } = span;
const { trace, distance, offset } = result;
const reversed: EditDiffOp[] = [];
let x = oldEnd - start;
let y = newEnd - start;
for (let d = distance; d > 0; d -= 1) {
const prev = trace[d];
const k = x - y;
const moveDown = shouldMoveDown(prev, offset, d, k);
const prevK = moveDown ? k + 1 : k - 1;
const prevX = prev[offset + prevK];
const prevY = prevX - prevK;
const midX = moveDown ? prevX : prevX + 1;
const midY = moveDown ? prevY + 1 : prevY;
while (x > midX && y > midY) {
x -= 1;
y -= 1;
reversed.push({ kind: "eq", oldIdx: start + x, newIdx: start + y });
}
reversed.push({
kind: moveDown ? "add" : "del",
oldIdx: start + prevX,
newIdx: start + prevY,
});
x = prevX;
y = prevY;
}
while (x > 0 && y > 0) {
x -= 1;
y -= 1;
reversed.push({ kind: "eq", oldIdx: start + x, newIdx: start + y });
}
reversed.reverse();
return reversed;
}
function buildCompactUnifiedDiff(span: EditDiffSpan): string | null {
const { oldLines, newLines, start, oldEnd, newEnd } = span;
const middleOps = diffLineSlice(span);
if (!middleOps) return null;
const ops: EditDiffOp[] = [];
const leadStart = Math.max(0, start - EDIT_CONTEXT_LINES);
for (let i = leadStart; i < start; i += 1) {
ops.push({ kind: "eq", oldIdx: i, newIdx: i });
}
for (const op of middleOps) ops.push(op);
const trailCount = Math.min(EDIT_CONTEXT_LINES, oldLines.length - oldEnd);
for (let i = 0; i < trailCount; i += 1) {
ops.push({ kind: "eq", oldIdx: oldEnd + i, newIdx: newEnd + i });
}
const output: string[] = [];
let idx = 0;
while (idx < ops.length) {
while (idx < ops.length && ops[idx].kind === "eq") idx += 1;
if (idx >= ops.length) break;
const hunkStart = Math.max(0, idx - EDIT_CONTEXT_LINES);
let lastEdit = idx;
idx += 1;
while (idx < ops.length) {
if (ops[idx].kind !== "eq") {
lastEdit = idx;
idx += 1;
continue;
}
if (idx - lastEdit > EDIT_CONTEXT_LINES * 2) break;
idx += 1;
}
const hunkEnd = Math.min(ops.length, lastEdit + EDIT_CONTEXT_LINES + 1);
const hunkOps = ops.slice(hunkStart, hunkEnd);
let oldCount = 0;
let newCount = 0;
for (const op of hunkOps) {
if (op.kind !== "add") oldCount += 1;
if (op.kind !== "del") newCount += 1;
}
const firstOp = hunkOps[0];
const oldStart = oldCount === 0 ? firstOp.oldIdx : firstOp.oldIdx + 1;
const newStart = newCount === 0 ? firstOp.newIdx : firstOp.newIdx + 1;
output.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
for (const op of hunkOps) {
if (op.kind === "eq") output.push(` ${oldLines[op.oldIdx]}`);
else if (op.kind === "del") output.push(`-${oldLines[op.oldIdx]}`);
else output.push(`+${newLines[op.newIdx]}`);
}
idx = hunkEnd;
}
return output.join("\n");
}
/** Narrow full-file edit payloads before generic prefix cutting drops changes past the cap. */
function compactOversizedEditDetail(
detail: EditToolCallDetail,
maxTextBudget: number,
): EditToolCallDetail | null {
if (detail.unifiedDiff) return null;
const { oldString, newString } = detail;
if (!oldString || !newString) return null;
const { oldLines, newLines } = splitEditLines(oldString, newString);
let start = 0;
let oldEnd = oldLines.length;
let newEnd = newLines.length;
while (start < oldEnd && start < newEnd && oldLines[start] === newLines[start]) {
start += 1;
}
while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) {
oldEnd -= 1;
newEnd -= 1;
}
if (start === oldEnd && start === newEnd) {
return { ...detail, oldString: "", newString: "" };
}
const contextStart = Math.max(0, start - EDIT_CONTEXT_LINES);
const oldContextEnd = Math.min(oldLines.length, oldEnd + EDIT_CONTEXT_LINES);
const newContextEnd = Math.min(newLines.length, newEnd + EDIT_CONTEXT_LINES);
const trimmedOld = oldLines.slice(contextStart, oldContextEnd).join("\n");
const trimmedNew = newLines.slice(contextStart, newContextEnd).join("\n");
if (trimmedOld.length + trimmedNew.length <= maxTextBudget) {
if (trimmedOld.length >= oldString.length && trimmedNew.length >= newString.length) {
return null;
}
return { ...detail, oldString: trimmedOld, newString: trimmedNew };
}
const unifiedDiff = buildCompactUnifiedDiff({ oldLines, newLines, start, oldEnd, newEnd });
if (unifiedDiff && unifiedDiff.length < trimmedOld.length + trimmedNew.length) {
return {
type: "edit",
filePath: detail.filePath,
unifiedDiff,
};
}
if (trimmedOld.length < oldString.length || trimmedNew.length < newString.length) {
return { ...detail, oldString: trimmedOld, newString: trimmedNew };
}
return null;
}
function measureItem(item: AgentTimelineItem): { size: ItemSize; total: number } {
const size: ItemSize = { nodeCost: 0, stringLengths: [], tooDeep: false };
measure(item, 0, size);
let stringTotal = 0;
for (const length of size.stringLengths) stringTotal += length;
if (!size.tooDeep && size.nodeCost + stringTotal <= budget) return item;
return { size, total: size.nodeCost + stringTotal };
}
function computeStringCap(size: ItemSize, budget: number): number {
// Strings get what structure leaves, but at least half the budget, less a margin for JSON
// escaping. Arrays drop the elements that do not fit, which bounds items whose short strings
// or structure alone are too big.
const markerCost =
MARKER_COST * size.stringLengths.filter((length) => length > SHORT_STRING).length;
const available = (budget * 15) / 16 - Math.min(size.nodeCost, budget / 2) - markerCost;
const stringCap = Math.max(SHORT_STRING, findStringCap(size.stringLengths, available));
return cut(item, 0, { stringCap, remaining: budget }) as AgentTimelineItem;
return Math.max(SHORT_STRING, findStringCap(size.stringLengths, available));
}
/** Returns the item itself when it fits its budget; otherwise a copy with its largest strings cut. */
export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem {
const budget = item.type === "tool_call" ? TOOL_CALL_BUDGET : ITEM_BUDGET;
const initial = measureItem(item);
if (!initial.size.tooDeep && initial.total <= budget) return item;
let candidate = item;
let stringCap = computeStringCap(initial.size, budget);
if (item.type === "tool_call" && item.detail.type === "edit") {
const { oldString, newString } = item.detail;
if (
!item.detail.unifiedDiff &&
oldString &&
newString &&
(oldString.length > stringCap || newString.length > stringCap)
) {
const compacted = compactOversizedEditDetail(item.detail, Math.floor((budget * 3) / 4));
if (compacted) {
candidate = { ...item, detail: compacted };
const next = measureItem(candidate);
if (!next.size.tooDeep && next.total <= budget) return candidate;
stringCap = computeStringCap(next.size, budget);
}
}
}
return cut(candidate, 0, { stringCap, remaining: budget }) as AgentTimelineItem;
}