Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions apps/server/src/provider/acp/AntigravityEditLocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,26 @@ function snippetHunks(
})?.hunks;
}

/**
* The hunks of a whole-file diff, made from the uncut texts: tool text bounding keeps only the
* tail of a long text, which loses every line number.
*/
export function antigravityWholeFilePatch(
path: string,
oldText: string,
newText: string,
): string | undefined {
if (oldText.length > PRE_EDIT_FILE_LIMIT || newText.length > PRE_EDIT_FILE_LIMIT)
return undefined;
const patch = structuredPatch(path, path, oldText, newText, undefined, undefined, {
context: 3,
maxEditLength: EDIT_DIFF_BUDGET,
});
return patch === undefined || patch.hunks.length === 0
? undefined
: formatPatch(patch, FILE_HEADERS_ONLY);
}

const changedLines = (hunks: ReadonlyArray<StructuredPatchHunk>) =>
hunks.reduce(
(total, hunk) =>
Expand Down
113 changes: 112 additions & 1 deletion apps/server/src/provider/acp/AntigravityProtocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -419,6 +419,117 @@ describe("Antigravity tool results", () => {
expect(toolCall.data.content).toMatchObject([{ patch: { format: "omitted" } }]);
expect(acpToolCallDiffPatch(toolCall.data.content)).toBeUndefined();
}
// Older runtimes send the edit's snippets as the diff. Over 8 KB they are cut, and a patch
// made from them would number the hunk from the snippet's first line instead of the file's.
const rows = (changed: string) =>
Array.from({ length: 150 }, (_, i) =>
(i === 75 ? changed : `row ${i + 1} `).padEnd(82, "x"),
).join("\n");
const snippets = {
TargetContent: rows("old "),
ReplacementContent: rows("new "),
TargetFile: path,
StartLine: 201,
EndLine: 350,
};
const pending = frame(snippets, 201);
const snippetDiff = normalizeAntigravityToolCall(
parseToolUpdate({
...pending,
update: {
...pending.update,
content: [
{
type: "diff",
path,
oldText: snippets.TargetContent,
newText: snippets.ReplacementContent,
},
],
},
}).toolCall,
);
expect(snippetDiff.data.content).toMatchObject([{ patch: { format: "omitted" } }]);
});

it("places a 1.5 edit_file edit while it runs and from the completion's whole-file texts", () => {
const path = "/workspace/app.ts";
// An insert above its anchor: the target still matches once in the written file, a line late.
const rawInput = {
Path: path,
Target: "import x from 'x';",
Replacement: "import w from 'w';\nimport x from 'x';",
};
const fileOf = (lines: number, anchor: string) =>
Array.from({ length: lines }, (_, i) =>
i === lines - 3 ? anchor : `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;
// Whole-file texts over 8 KB are cut to their tails, which no longer hold the line.
// The runtime does not wait for T3, so the file may or may not be written when T3 reads it.
for (const [lines, written] of [
[5, false],
[5, true],
[400, true],
] as const) {
const readFile = () => fileOf(lines, written ? rawInput.Replacement : rawInput.Target);
let toolCall = normalizeAntigravityToolCall(
parseToolUpdate(frame(lines, "in_progress")).toolCall,
readFile,
);
expect(acpToolCallDiffPatch(toolCall.data.content)).toBe(
`--- ${path}\n+++ ${path}\n@@ -${lines - 2},1 +${lines - 2},2 @@\n+import w from 'w';\n import x from 'x';\n`,
);
toolCall = normalizeAntigravityToolCall(
mergeToolCallState(toolCall, parseToolUpdate(frame(lines, "completed")).toolCall),
readFile,
);
expect(acpToolCallSnippetEdit(toolCall.data.content)).toBeUndefined();
const context = Math.min(3, lines - 3);
expect(acpToolCallDiffPatch(toolCall.data.content)).toContain(
`@@ -${lines - 2 - context},${context + 3} +${lines - 2 - context},${context + 4} @@\n`,
);
expect(acpToolCallDiffPatch(toolCall.data.content)).toContain(
`\n+import w from 'w';\n import x from 'x';\n`,
);
}
// A file that does not say whether the edit was written leaves the edit unplaced.
const twoAnchors = `${rawInput.Target}\nconst between = 1;\n${rawInput.Replacement}\n`;
for (const readFile of [() => undefined, () => twoAnchors]) {
const unplaced = normalizeAntigravityToolCall(
parseToolUpdate(frame(5, "in_progress")).toolCall,
readFile,
);
expect(acpToolCallSnippetEdit(unplaced.data.content)).toEqual({
oldStr: rawInput.Target,
newStr: rawInput.Replacement,
});
}
});

it.each([
Expand Down
129 changes: 122 additions & 7 deletions apps/server/src/provider/acp/AntigravityProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel
import {
ANTIGRAVITY_EDIT_DIFF_OMITTED,
antigravityEditPatch,
antigravityWholeFilePatch,
isAntigravitySnippetPatch,
readAntigravityPreEditFile,
} from "./AntigravityEditLocation.ts";
Expand Down Expand Up @@ -340,6 +341,36 @@ export function makeAntigravityReadRepair() {
};
}

const WHOLE_FILE_PATCH_META_KEY = "t3code.wholeFilePatch";
const decodeEditFileInput = Schema.decodeUnknownOption(
Schema.Struct({ Target: Schema.String, Replacement: Schema.String }),
);

/**
* 1.5 runtimes complete `edit_file` with the whole file before and after it; over 8 KB both are
* cut. Any other diff may hold the edit's snippets, whose lines are not the file's.
*/
function wholeFilePatchBeforeCut(
update: { readonly status?: string | null; readonly rawInput?: unknown },
entry: EffectAcpSchema.ToolCallContent,
budget: ToolPayloadBudget,
): string | undefined {
if (
update.status !== "completed" ||
Option.isNone(decodeEditFileInput(update.rawInput)) ||
entry.type !== "diff" ||
!("path" in entry) ||
typeof entry.oldText !== "string" ||
(entry.oldText.length <= TOOL_TEXT_LIMIT && entry.newText.length <= TOOL_TEXT_LIMIT)
)
return undefined;
const patch = antigravityWholeFilePatch(entry.path, entry.oldText, entry.newText);
if (patch === undefined || patch.length > Math.min(TOOL_TEXT_LIMIT, budget.text))
return undefined;
budget.text -= patch.length;
return patch;
}

export function normalizeAntigravitySessionUpdate(
notification: EffectAcpSchema.SessionNotification,
): EffectAcpSchema.SessionNotification {
Expand All @@ -348,13 +379,24 @@ export function normalizeAntigravitySessionUpdate(
return notification;
}
const contentBudget = { nodes: 512, text: 32_000 };
const wholeFilePatches: Record<string, string> = {};
const content = update.content?.flatMap((entry) => {
const patch = wholeFilePatchBeforeCut(update, entry, contentBudget);
if (patch !== undefined && "path" in entry) wholeFilePatches[entry.path] = patch;
const decoded = Option.getOrUndefined(
decodeToolCallContent(sanitizeToolValue(entry, contentBudget, 0)),
);
return decoded === undefined ? [] : [decoded];
});
const meta = sanitizeAntigravityToolPayload(update._meta);
const receivedMeta = sanitizeAntigravityToolPayload(update._meta);
// A v1 diff has no patch field, so the patches travel in the update's metadata.
const meta =
Object.keys(wholeFilePatches).length === 0
? receivedMeta
: {
...(Predicate.isObject(receivedMeta) ? receivedMeta : {}),
[WHOLE_FILE_PATCH_META_KEY]: wholeFilePatches,
};
return {
...notification,
update: {
Expand All @@ -367,7 +409,9 @@ export function normalizeAntigravitySessionUpdate(
? { rawOutput: sanitizeAntigravityToolPayload(update.rawOutput) }
: {}),
...(update.content !== undefined ? { content: content ?? [] } : {}),
...(update._meta !== undefined ? { _meta: isJsonRecord(meta) ? meta : null } : {}),
...(update._meta !== undefined || meta !== receivedMeta
? { _meta: isJsonRecord(meta) ? meta : null }
: {}),
},
};
}
Expand Down Expand Up @@ -403,10 +447,21 @@ function withAntigravityEditPatches(
content: ReadonlyArray<unknown>,
data: Record<string, unknown>,
readPreEditFile: ((path: string) => string | undefined) | undefined,
wholeFilePatches: unknown,
) {
return content.map((entry) => {
if (!Predicate.isObject(entry) || entry.type !== "diff" || typeof entry.path !== "string")
return entry;
return content.map((received) => {
if (
!Predicate.isObject(received) ||
received.type !== "diff" ||
typeof received.path !== "string"
)
return received;
const wholeFilePatch =
received.patch === undefined && Predicate.isObject(wholeFilePatches)
? wholeFilePatches[received.path]
: undefined;
const entry: Record<string, unknown> =
wholeFilePatch === undefined ? received : { ...received, patch: { text: wholeFilePatch } };
// Keep the first patch: once the edit runs, the file no longer holds the old text. A later
// update's shared text budget can cut or drop it, and a cut patch would misplace the hunk.
if (entry.patch !== undefined) {
Expand All @@ -422,7 +477,7 @@ function withAntigravityEditPatches(
if ([data.rawInput, entry.oldText, entry.newText].some(hasTruncatedText))
return { ...entry, patch: { format: "omitted" } };
const text = antigravityEditPatch({
path: entry.path,
path: received.path,
rawInput: data.rawInput,
locations: data.locations,
readPreEditFile,
Expand All @@ -441,6 +496,58 @@ function withAntigravityEditPatches(
});
}

/**
* The file as it was before a running `edit_file`, which the runtime may already have applied.
* Undefined when the file does not say which: the target and the replacement can each be part of
* the other, or already be in the file elsewhere.
*/
function preEditFileOfRunningEdit(
file: string | undefined,
edit: { readonly Target: string; readonly Replacement: string },
): string | undefined {
const target = edit.Target.replaceAll("\r\n", "\n");
const replacement = edit.Replacement.replaceAll("\r\n", "\n");
if (file === undefined || target === "" || replacement === "") return undefined;
const text = file.replaceAll("\r\n", "\n");
const targets = text.split(target).length - 1;
const replacements = text.split(replacement).length - 1;
const unwritten = targets === 1 && (replacements === 0 || target.includes(replacement));
if (unwritten) return text;
const written =
replacements === 1 &&
(replacement.includes(target) ? targets === 1 : targets === 0 && !target.includes(replacement));
return written ? text.replace(replacement, () => target) : undefined;
}

/**
* 1.5 runtimes announce `edit_file` already running, with its arguments and no diff. An edit
* the file cannot place shows as an unplaced snippet.
*/
function announcedEditDiff(
data: Record<string, unknown>,
readFile: ((path: string) => string | undefined) | undefined,
) {
const omitted = { type: "diff", patch: { format: "omitted" } };
const location: unknown = Array.isArray(data.locations) ? data.locations[0] : undefined;
const path = Predicate.isObject(location) ? location.path : undefined;
const edit = Option.getOrUndefined(decodeEditFileInput(data.rawInput));
if (typeof path !== "string" || edit === undefined || hasTruncatedText(edit)) return omitted;
const preEditFile = preEditFileOfRunningEdit(readFile?.(path), edit);
const text = antigravityEditPatch({
path,
rawInput: { TargetContent: edit.Target, ReplacementContent: edit.Replacement },
readPreEditFile: preEditFile === undefined ? undefined : () => preEditFile,
});
if (typeof text !== "string" || text.length > TOOL_TEXT_LIMIT) return omitted;
return {
type: "diff",
path,
oldText: edit.Target,
newText: edit.Replacement,
patch: isAntigravitySnippetPatch(text) ? { format: "snippet", text } : { text },
};
}

export function normalizeAntigravityToolCall(
toolCall: AcpToolCallState,
readPreEditFile = readAntigravityPreEditFile,
Expand Down Expand Up @@ -477,6 +584,10 @@ export function normalizeAntigravityToolCall(
if (command !== undefined) data.command = command;
if (cwd !== undefined) data.cwd = cwd;
if (imagePath !== undefined) data.imagePath = imagePath;
const { [WHOLE_FILE_PATCH_META_KEY]: wholeFilePatches, ...meta } = Predicate.isObject(data.meta)
? data.meta
: {};
if (wholeFilePatches !== undefined) data.meta = meta;
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.
Expand All @@ -485,8 +596,12 @@ export function normalizeAntigravityToolCall(
content,
data,
toolCall.status === "pending" ? readPreEditFile : undefined,
wholeFilePatches,
)
: [...content, { type: "diff", patch: { format: "omitted" } }];
: [
...content,
announcedEditDiff(data, toolCall.status === "inProgress" ? readPreEditFile : undefined),
];
}
if (kind === "execute") {
data.item = {
Expand Down
Loading