diff --git a/apps/server/src/provider/acp/AntigravityEditLocation.test.ts b/apps/server/src/provider/acp/AntigravityEditLocation.test.ts index 23f04f011fd25..1b6d5631b7bc2 100644 --- a/apps/server/src/provider/acp/AntigravityEditLocation.test.ts +++ b/apps/server/src/provider/acp/AntigravityEditLocation.test.ts @@ -37,6 +37,9 @@ describe("antigravityEditPatch", () => { }, // Like the runtime, a present PascalCase value wins, and a 0 line means unspecified. { ...replace, target_content: "const other = 15;", StartLine: 5, EndLine: 0 }, + // 1.5 edit_file names the snippets Target and Replacement. + { Path: path, Target: replace.TargetContent, Replacement: replace.ReplacementContent }, + { path, target: replace.TargetContent, replacement: replace.ReplacementContent }, ]) { expect(antigravityEditPatch({ path, rawInput, readPreEditFile })).toBe(expected); } @@ -129,6 +132,37 @@ describe("antigravityEditPatch", () => { } }); + it("leaves a target that a written replacement still contains unplaced", () => { + const rawInput = { Target: "old\n", Replacement: "added\nold\n" }; + const preview = (written: string) => + antigravityEditPatch({ path, rawInput, readPreEditFile: () => written }); + expect(preview("header\nold\nfooter\n")).toBe(`${header}@@ -2,1 +2,2 @@\n+added\n old\n`); + // After the write, the target's match at line 3 is inside the replacement, not the edit. + expect(preview("header\nadded\nold\nfooter\n")).toBe( + `${header}@@ -1,1 +1,2 @@ snippet, line unknown\n+added\n old\n`, + ); + // A written replacement that ends inside the target's match is as ambiguous. + const swapped = { Target: "a\nb\n", Replacement: "b\na\n" }; + const swap = (written: string) => + antigravityEditPatch({ path, rawInput: swapped, readPreEditFile: () => written }); + expect(swap("h\na\nb\nb\nf\n")).toMatch(/^@@ -2,2 \+2,2 @@$/m); + expect(swap("h\nb\na\nb\nf\n")).toMatch(/ snippet, line unknown$/m); + // Deleting a leading line from line 3 leaves the target matching at line 2 after the write. + const trimmed = { Target: "drop\nkeep\n", Replacement: "keep\n" }; + for (const written of ["header\ndrop\ndrop\nkeep\nfooter\n", "header\ndrop\nkeep\nfooter\n"]) + expect( + antigravityEditPatch({ path, rawInput: trimmed, readPreEditFile: () => written }), + ).toMatch(/ snippet, line unknown$/m); + // A replacement that starts the target, as in a delete, is not a written edit. + expect( + antigravityEditPatch({ + path, + rawInput: { Target: "keep\ndrop\n", Replacement: "keep\n" }, + readPreEditFile: () => "header\nkeep\ndrop\nfooter\n", + }), + ).toBe(`${header}@@ -2,2 +2,1 @@\n keep\n-drop\n`); + }); + it("labels repeated or unmatched snippets instead of placing them at line 1", () => { const snippet = `${header}@@ -1,1 +1,1 @@ snippet, line unknown\n-const target = 10;\n+const target = 100;\n`; for (const readPreEditFile of [ diff --git a/apps/server/src/provider/acp/AntigravityEditLocation.ts b/apps/server/src/provider/acp/AntigravityEditLocation.ts index ff16dd014c97a..6f6d8bd84d0e1 100644 --- a/apps/server/src/provider/acp/AntigravityEditLocation.ts +++ b/apps/server/src/provider/acp/AntigravityEditLocation.ts @@ -39,11 +39,16 @@ const decodeEditInput = Schema.decodeUnknownOption( ]), ); const decodeLocations = Schema.decodeUnknownOption(Schema.Array(Schema.Struct({ line: Line }))); -// The runtime accepts edit arguments in either casing. +// The runtime accepts edit arguments in either casing, and 1.5 edit_file names them Target and +// Replacement. const PASCAL_KEYS: Readonly> = { replacement_chunks: "ReplacementChunks", target_content: "TargetContent", replacement_content: "ReplacementContent", + Target: "TargetContent", + target: "TargetContent", + Replacement: "ReplacementContent", + replacement: "ReplacementContent", start_line: "StartLine", end_line: "EndLine", }; @@ -73,15 +78,15 @@ export function readAntigravityPreEditFile(path: string): string | undefined { } } -/** The line of the snippet's only match starting within `from`..`to`, if it spans whole lines. */ -function uniqueStartLine( +/** The snippet's only match starting within lines `from`..`to`, if it spans whole lines. */ +function uniqueWholeLineMatch( text: string | undefined, snippet: string, from = 1, to = Number.POSITIVE_INFINITY, -): number | undefined { +): { readonly line: number; readonly index: number } | undefined { if (text === undefined || snippet === "") return undefined; - let found: { readonly line: number; readonly whole: boolean } | undefined; + let found: { readonly line: number; readonly index: number; readonly whole: boolean } | undefined; let line = 1; let lineStart = 0; let nextBreak = text.indexOf("\n"); @@ -98,9 +103,21 @@ function uniqueStartLine( // A hunk replaces whole lines. const whole = index === lineStart && (end === text.length || snippet.endsWith("\n") || text[end] === "\n"); - found = { line, whole }; + found = { line, index, whole }; } - return found?.whole === true ? found.line : undefined; + return found?.whole === true ? { line: found.line, index: found.index } : undefined; +} + +/** True when an occurrence of `other` overlaps `text[start, start + length)` other than as its prefix. */ +function straddlesSnippet(text: string, start: number, length: number, other: string): boolean { + const end = start + length; + for ( + let index = text.indexOf(other, Math.max(0, start - other.length + 1)); + index !== -1 && index < end; + index = text.indexOf(other, index + 1) + ) + if (index !== start || index + other.length > end) return true; + return false; } function snippetHunks( @@ -133,7 +150,7 @@ export function antigravityEditPatch(input: { readonly path: string; readonly rawInput: unknown; readonly locations?: unknown; - /** Pass only while the edit is pending, when the file still holds the old text. */ + /** Pass only before the edit runs, when the file still holds the old text. */ readonly readPreEditFile?: ((path: string) => string | undefined) | undefined; }): string | typeof ANTIGRAVITY_EDIT_DIFF_OMITTED | undefined { const edit = Option.getOrUndefined(decodeEditInput(pascalKeys(input.rawInput))); @@ -179,12 +196,21 @@ export function antigravityEditPatch(input: { // Line numbers do not depend on CRLF, so search with LF on both sides. if (!fileRead) file = input.readPreEditFile(input.path)?.replaceAll("\r\n", "\n"); fileRead = true; - start = uniqueStartLine( - file, - chunk.TargetContent.replaceAll("\r\n", "\n"), - chunk.StartLine, - chunk.EndLine, - ); + const target = chunk.TargetContent.replaceAll("\r\n", "\n"); + const replacement = chunk.ReplacementContent.replaceAll("\r\n", "\n"); + const match = uniqueWholeLineMatch(file, target, chunk.StartLine, chunk.EndLine); + // The runtime may write before T3 reads the file. A target overlapped by a replacement + // other than as its prefix could be either state, so it stays unplaced. + if ( + match !== undefined && + file !== undefined && + !straddlesSnippet(file, match.index, target.length, replacement) + ) + start = match.line; + // A lone replacement starts on the same line before and after it, so an already-applied + // edit is placed by its new text. + if (start === undefined && chunks.length === 1 && file?.includes(target) === false) + start = uniqueWholeLineMatch(file, replacement)?.line; } if (start === undefined) snippets.push(...hunks); else placed.push({ start, hunks }); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index de31bcc178959..d1db47d143e8c 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -19,7 +19,7 @@ import { mergeToolCallState, parseSessionUpdateEvent, } from "@t3tools/provider-acp/server/runtimeModel"; -import { acpToolCallDiffPatch } from "@t3tools/provider-acp/server/adapter"; +import { acpToolCallDiffPatch, acpToolCallSnippetEdit } from "@t3tools/provider-acp/server/adapter"; const isSessionNotification = Schema.is(AcpWireSchema.SessionNotification); @@ -358,6 +358,18 @@ describe("Antigravity tool results", () => { `--- ${path}\n+++ ${path}\n@@ -10,1 +10,1 @@\n-const target = 10;\n+const target = 100;\n`, ); } + // An unlocatable edit whose completion resends the snippet diff stays labeled as a snippet. + const resent = parseToolUpdate({ + ...frame(replace), + update: { ...frame(replace).update, sessionUpdate: "tool_call_update", status: "completed" }, + }).toolCall; + const unlocated = normalizeAntigravityToolCall( + mergeToolCallState( + normalizeAntigravityToolCall(parseToolUpdate(frame(replace)).toolCall, () => undefined), + resent, + ), + ); + expect(unlocated.data.content).toMatchObject([{ patch: { format: "snippet" } }]); // Full-access edits arrive path-only; no hunk is offered instead of the tool's status text. let pathOnly = normalizeAntigravityToolCall( parseToolUpdate({ @@ -374,7 +386,7 @@ describe("Antigravity tool results", () => { }).toolCall, ); pathOnly = normalizeAntigravityToolCall(mergeToolCallState(pathOnly, completed)); - expect(pathOnly.data.content).toEqual([{ type: "diff", patch: { format: "omitted" } }]); + expect(pathOnly.data.content).toEqual([{ type: "diff", path, patch: { format: "omitted" } }]); expect(acpToolCallDiffPatch(pathOnly.data.content)).toBeUndefined(); // A captured patch that a later update's shared text budget cut or dropped is omitted. for (const patch of [{ text: "[Earlier output truncated]\n\n@@ -80,1 +80,1 @@" }, {}]) { @@ -421,6 +433,84 @@ describe("Antigravity tool results", () => { } }); + it("locates a 1.5 edit_file edit announced without a diff, through its whole-file completion", () => { + const path = "/workspace/app.ts"; + const rawInput = { + Path: path, + Target: "const target = 10;", + Replacement: "const target = 100;", + }; + const fileOf = (lines: number, target: string) => + Array.from({ length: lines }, (_, i) => + i === lines - 3 ? target : `const line${i + 1} = ${i + 1}; // padding`, + ).join("\n") + "\n"; + // agy 1.5.11 announces in progress with no content, then completes with the whole file. + const frame = (lines: number, status: "in_progress" | "completed") => + ({ + sessionId: "session-1", + update: { + sessionUpdate: status === "in_progress" ? "tool_call" : "tool_call_update", + toolCallId: `edit-${lines}`, + kind: "edit", + status, + title: "File app.ts", + locations: [{ path }], + rawInput, + ...(status === "completed" + ? { + content: [ + { + type: "diff", + path, + oldText: fileOf(lines, rawInput.Target), + newText: fileOf(lines, rawInput.Replacement), + }, + ], + } + : {}), + }, + }) satisfies EffectAcpSchema.SessionNotification; + const located = (line: number) => + `--- ${path}\n+++ ${path}\n@@ -${line},1 +${line},1 @@\n-const target = 10;\n+const target = 100;\n`; + // Over 8 KB, the completion's whole-file texts arrive cut, so only the announcement can place it. + // The runtime does not wait for T3, so the announcement may be read after the write. + for (const [lines, written] of [ + [12, rawInput.Target], + [400, rawInput.Target], + [400, rawInput.Replacement], + ] as const) { + let toolCall = normalizeAntigravityToolCall( + parseToolUpdate(frame(lines, "in_progress")).toolCall, + () => fileOf(lines, written), + ); + expect(acpToolCallDiffPatch(toolCall.data.content)).toBe(located(lines - 2)); + toolCall = normalizeAntigravityToolCall( + mergeToolCallState(toolCall, parseToolUpdate(frame(lines, "completed")).toolCall), + ); + expect(toolCall.status).toBe("completed"); + expect(acpToolCallDiffPatch(toolCall.data.content)).toBe(located(lines - 2)); + } + // A completion that empties content keeps the announcement's located patch. + const announced = normalizeAntigravityToolCall( + parseToolUpdate(frame(12, "in_progress")).toolCall, + () => fileOf(12, rawInput.Target), + ); + const emptied = frame(12, "completed"); + const completed = normalizeAntigravityToolCall( + mergeToolCallState( + announced, + parseToolUpdate({ ...emptied, update: { ...emptied.update, content: [] } }).toolCall, + ), + ); + expect(acpToolCallDiffPatch(completed.data.content)).toBe(located(10)); + // Without a located announcement, uncut whole-file texts still render and cut ones stay hidden. + const small = normalizeAntigravityToolCall(parseToolUpdate(frame(12, "completed")).toolCall); + expect(acpToolCallDiffPatch(small.data.content)).toContain("@@ -7,6 +7,6 @@\n"); + const large = normalizeAntigravityToolCall(parseToolUpdate(frame(400, "completed")).toolCall); + expect(acpToolCallDiffPatch(large.data.content)).toBeUndefined(); + expect(acpToolCallSnippetEdit(large.data.content)).toBeUndefined(); + }); + it.each([ { CommandLine: "pwd", Cwd: "/one" }, { CommandLine: "pwd", WorkingDirectory: "/one" }, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index ce4daef806bab..df69cfc3dc444 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -421,6 +421,13 @@ function withAntigravityEditPatches( // old or new text would render the cut as file content. if ([data.rawInput, entry.oldText, entry.newText].some(hasTruncatedText)) return { ...entry, patch: { format: "omitted" } }; + // An entry without new text stands in for a diff the runtime did not send. After the edit, + // 1.5 runtimes report the whole file before and after it, which needs no placing. + // Older runtimes resend the snippets instead. + const reported = typeof entry.newText === "string"; + const wholeFile = + Predicate.isObject(data.rawInput) && ("Target" in data.rawInput || "target" in data.rawInput); + if (readPreEditFile === undefined && reported && wholeFile) return entry; const text = antigravityEditPatch({ path: entry.path, rawInput: data.rawInput, @@ -433,7 +440,7 @@ function withAntigravityEditPatches( (text !== undefined && text.length > TOOL_TEXT_LIMIT) ) return { ...entry, patch: { format: "omitted" } }; - if (text === undefined) return entry; + if (text === undefined) return reported ? entry : { ...entry, patch: { format: "omitted" } }; return { ...entry, patch: isAntigravitySnippetPatch(text) ? { format: "snippet", text } : { text }, @@ -479,14 +486,21 @@ export function normalizeAntigravityToolCall( if (imagePath !== undefined) data.imagePath = imagePath; if (kind === "edit") { const content = Array.isArray(data.content) ? data.content : []; - // Full-access edits report only a path; without a hunk the checkpoint diff is the review. - data.content = content.some((entry) => Predicate.isObject(entry) && entry.type === "diff") - ? withAntigravityEditPatches( - content, - data, - toolCall.status === "pending" ? readPreEditFile : undefined, - ) - : [...content, { type: "diff", patch: { format: "omitted" } }]; + const location = Array.isArray(data.locations) ? data.locations[0] : undefined; + const path = Predicate.isObject(location) ? location.path : undefined; + const hasDiff = content.some((entry) => Predicate.isObject(entry) && entry.type === "diff"); + // 1.5 runtimes announce an edit with only its path and arguments. Without a hunk, the + // checkpoint diff is the review. + data.content = + hasDiff || typeof path === "string" + ? withAntigravityEditPatches( + hasDiff ? content : [...content, { type: "diff", path }], + data, + toolCall.status === "completed" || toolCall.status === "failed" + ? undefined + : readPreEditFile, + ) + : [...content, { type: "diff", patch: { format: "omitted" } }]; } if (kind === "execute") { data.item = { diff --git a/packages/shared/src/toolActivity.test.ts b/packages/shared/src/toolActivity.test.ts index dbcd0d9fb4c9a..99ddfb33d896f 100644 --- a/packages/shared/src/toolActivity.test.ts +++ b/packages/shared/src/toolActivity.test.ts @@ -34,6 +34,24 @@ describe("toolActivity", () => { ).toEqual({ rawInput: { startLine: 4 } }); }); + it("keeps a located diff patch when a later update resends that diff without one", () => { + const resent = { type: "diff", path: "src/a.ts", oldText: "a\n", newText: "b\n" }; + const merge = (patch: unknown, content: unknown = [resent, { ...resent, path: "src/b.ts" }]) => + mergeToolActivityData({ content: [{ ...resent, patch }] }, { content })?.content; + const located = { text: "@@ -9,1 +9,1 @@\n-a\n+b\n" }; + expect(merge(located)).toEqual([ + { ...resent, patch: located }, + { ...resent, path: "src/b.ts" }, + ]); + // An update that empties content keeps the located diff, and null still clears it. + expect(merge(located, [])).toEqual([{ ...resent, patch: located }]); + expect(merge(located, null)).toBeUndefined(); + for (const patch of [{ format: "snippet", text: located.text }, { format: "omitted" }]) { + expect(merge(patch)).toEqual([resent, { ...resent, path: "src/b.ts" }]); + expect(merge(patch, [])).toEqual([]); + } + }); + it("recognizes computer-use REPL calls before result metadata exists", () => { expect(dynamicToolSurface("cua_repl.js", {})).toBe("computer"); for (const name of ["node_repl.js", "js"]) { diff --git a/packages/shared/src/toolActivity.ts b/packages/shared/src/toolActivity.ts index aae54684c4e5e..fc42099d13ac7 100644 --- a/packages/shared/src/toolActivity.ts +++ b/packages/shared/src/toolActivity.ts @@ -220,6 +220,33 @@ function extractPrimaryPath(data: Record | undefined): string | return collectToolFilePaths(data)[0]; } +/** A diff resent without a patch keeps the located patch an earlier update computed for its path. */ +function withLocatedDiffPatches(previous: unknown, next: ReadonlyArray) { + const located = new Map>(); + for (const entry of Array.isArray(previous) ? previous : []) { + const diff = asRecord(entry); + const patch = asRecord(diff?.patch); + if ( + diff?.type === "diff" && + typeof diff.path === "string" && + patch?.format === undefined && + typeof patch?.text === "string" + ) + located.set(diff.path, diff); + } + if (located.size === 0) return next; + // An update that empties content would drop a patch a later normalizer can no longer compute. + if (next.length === 0) return [...located.values()]; + return next.map((entry) => { + const diff = asRecord(entry); + const patch = + diff?.type === "diff" && diff.patch === undefined && typeof diff.path === "string" + ? located.get(diff.path)?.patch + : undefined; + return patch === undefined ? entry : { ...diff, patch }; + }); +} + /** * A null field clears it (ACP v2) and a nonempty rawInput replaces the previous one. * An empty rawInput keeps the previous one; later ACP updates often resend an empty object. @@ -239,6 +266,9 @@ export function mergeToolActivityData( delete merged[key]; } } + if (Array.isArray(nextRecord.content)) { + merged.content = withLocatedDiffPatches(previousRecord?.content, nextRecord.content); + } if (!previousRecord || nextRecord.rawInput === null) { return merged; }