diff --git a/apps/desktop/src/main/services/chat/acpHost/acpDialects/antigravityTurnOutcome.test.ts b/apps/desktop/src/main/services/chat/acpHost/acpDialects/antigravityTurnOutcome.test.ts new file mode 100644 index 0000000000..7066452929 --- /dev/null +++ b/apps/desktop/src/main/services/chat/acpHost/acpDialects/antigravityTurnOutcome.test.ts @@ -0,0 +1,138 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { watchAntigravityTurnOutcome } from "./antigravityTurnOutcome"; + +// A static `node:sqlite` import is rewritten by the test bundler into a missing +// `sqlite` URL; load it at runtime, as readOnlySqlite.ts does. +type TestDatabase = { + exec: (sql: string) => void; + prepare: (sql: string) => { run: (...args: unknown[]) => unknown }; + close: () => void; +}; +const requireForTest = createRequire(path.join(process.cwd(), "antigravity-outcome-test.cjs")); +const { DatabaseSync } = requireForTest("node:sqlite") as { + DatabaseSync: new (dbPath: string) => TestDatabase; +}; + +const tempDirs: string[] = []; + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +function makeSession(sessionId: string): { dir: string; db: TestDatabase } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ade-agy-outcome-")); + tempDirs.push(dir); + fs.mkdirSync(path.join(dir, "conversations"), { recursive: true }); + const db = new DatabaseSync(path.join(dir, "conversations", `${sessionId}.db`)); + db.exec("CREATE TABLE steps(idx INTEGER PRIMARY KEY, step_type INTEGER, step_payload BLOB)"); + return { dir, db }; +} + +function addStep(db: TestDatabase, index: number, type: number, text = ""): void { + db.prepare("INSERT INTO steps (idx, step_type, step_payload) VALUES (?, ?, ?)") + .run(index, type, new TextEncoder().encode(text)); +} + +/** Takes the check before the turn, then adds the turn's steps and reads the outcome. */ +async function outcomeFor(steps: Array<[type: number, text: string]>) { + const sessionId = crypto.randomUUID(); + const { dir, db } = makeSession(sessionId); + try { + addStep(db, 0, 14, "user turn"); + const check = await watchAntigravityTurnOutcome({ sessionId }, dir); + steps.forEach(([type, text], index) => addStep(db, index + 1, type, text)); + return await check({ stopReason: "end_turn" }); + } finally { + db.close(); + fs.rmSync(dir, { recursive: true, force: true }); + const cached = tempDirs.indexOf(dir); + if (cached >= 0) tempDirs.splice(cached, 1); + } +} + +const PLANNER = 15; +const ERROR = 17; + +describe("antigravityTurnOutcome", () => { + it("resumes a 404 that arrives after the model answered, in the Go form", async () => { + const failure = await outcomeFor([ + [PLANNER, "I will read that document."], + [ERROR, "Error 404, Message: Requested entity was not found., Status: NOT_FOUND\nstack trace"], + ]); + + expect(failure).toMatchObject({ + kind: "provider_error", + message: "Requested entity was not found.", + code: "NOT_FOUND", + retryable: true, + resumeWith: "continue", + }); + }); + + it("resumes a 404 in Antigravity 1.5's status form", async () => { + const failure = await outcomeFor([ + [PLANNER, "I will read that document."], + [ERROR, "NOT_FOUND (code 404): Requested entity was not found."], + ]); + + expect(failure).toMatchObject({ + message: "Requested entity was not found.", + code: "NOT_FOUND", + retryable: true, + resumeWith: "continue", + }); + }); + + it("does not resume a 404 that arrives before the model answered", async () => { + const failure = await outcomeFor([ + [ERROR, "NOT_FOUND (code 404): Requested entity was not found."], + ]); + + expect(failure).toMatchObject({ + message: "Requested entity was not found.", + code: "NOT_FOUND", + retryable: false, + }); + expect(failure?.resumeWith).toBeUndefined(); + }); + + it("marks a 5xx retryable without resuming it", async () => { + const failure = await outcomeFor([ + [PLANNER, "I will read that document."], + [ERROR, "Error 500, Message: Internal error., Status: INTERNAL"], + ]); + + expect(failure).toMatchObject({ retryable: true }); + expect(failure?.resumeWith).toBeUndefined(); + }); + + it("keeps quota exhaustion and its reset time unchanged", async () => { + const failure = await outcomeFor([ + [PLANNER, "Working."], + [ERROR, "resource exhausted reason:QUOTA_EXHAUSTED quotaResetDelay:30s ]"], + ]); + + expect(failure).toMatchObject({ kind: "usage_limit", retryable: true }); + expect(failure?.resetAt).toBeTruthy(); + expect(failure?.resumeWith).toBeUndefined(); + }); + + it("keeps an unparseable error generic and non-retryable", async () => { + const failure = await outcomeFor([[ERROR, "something went wrong"]]); + + expect(failure).toMatchObject({ + kind: "provider_error", + code: null, + retryable: false, + }); + expect(failure?.resumeWith).toBeUndefined(); + }); +}); diff --git a/apps/desktop/src/main/services/chat/acpHost/acpDialects/antigravityTurnOutcome.ts b/apps/desktop/src/main/services/chat/acpHost/acpDialects/antigravityTurnOutcome.ts index 90aabb5367..2ff00d37fb 100644 --- a/apps/desktop/src/main/services/chat/acpHost/acpDialects/antigravityTurnOutcome.ts +++ b/apps/desktop/src/main/services/chat/acpHost/acpDialects/antigravityTurnOutcome.ts @@ -27,10 +27,14 @@ import { antigravityCliDir } from "../../../ai/antigravityAuth"; /** CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory. */ const ERROR_STEP_TYPE = 17; +/** CORTEX_STEP_TYPE_PLANNER_RESPONSE: the agent's reply. */ +const PLANNER_RESPONSE_STEP_TYPE = 15; /** The error text leads the payload; a Go stack trace follows it. */ const MAX_ERROR_PAYLOAD_BYTES = 16_384; /** The Go harness's rendering of a Google API error. */ const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s; +/** Antigravity 1.5's Google-account rendering: `NOT_FOUND (code 404): ...`. */ +const STATUS_ERROR = /(? = { const NATIVE_SESSION_ID = /^[\w-]+$/; const ERROR_MESSAGE_LIMIT = 600; -type LastStep = { type: number; payload: Uint8Array | null }; +type LastStep = { + type: number; + payload: Uint8Array | null; + /** A planner response appeared after the turn started: the model answered. */ + reachedModel: boolean; +}; + +/** `[matched, httpStatus, message, status]`, the shape both error renderings share. */ +function apiErrorOf(text: string): [string, string, string, string] | null { + const go = API_ERROR.exec(text); + if (go) return [go[0], go[1] ?? "", go[2] ?? "", go[3] ?? ""]; + const status = STATUS_ERROR.exec(text); + if (!status) return null; + return [status[0], status[2] ?? "", status[3] ?? "", status[1] ?? ""]; +} function antigravityConversationDb(sessionId: string, cliDir = antigravityCliDir()): string | null { if (!NATIVE_SESSION_ID.test(sessionId)) return null; @@ -99,7 +117,14 @@ function lastStepAfter(index: number) { ) .get<{ type?: unknown; payload?: unknown }>(MAX_ERROR_PAYLOAD_BYTES, index); if (typeof row?.type !== "number") return undefined; - return { type: row.type, payload: row.payload instanceof Uint8Array ? row.payload : null }; + const reachedModel = db + .prepare("SELECT 1 FROM steps WHERE idx > ? AND step_type = ? LIMIT 1") + .get(index, PLANNER_RESPONSE_STEP_TYPE) !== undefined; + return { + type: row.type, + payload: row.payload instanceof Uint8Array ? row.payload : null, + reachedModel, + }; }; } @@ -137,7 +162,7 @@ function antigravityTurnFailure( // The agent maps only an exhausted quota to `refusal`. if (errorText === undefined && stopReason !== "refusal") return null; const text = errorText ?? ""; - const apiError = API_ERROR.exec(text); + const apiError = apiErrorOf(text); if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) { return { kind: "usage_limit", @@ -158,12 +183,16 @@ function antigravityTurnFailure( } const [, httpStatus, message, status] = apiError; const rateLimited = httpStatus === "429" || status === "RESOURCE_EXHAUSTED"; + // A 404 after the model answered is a transient edge error; before it, the + // model itself is unknown or unentitled and a resume would only fail again. + const transientNotFound = httpStatus === "404" && step?.reachedModel === true; return { kind: rateLimited ? "usage_limit" : "provider_error", message: bounded(message ?? "") || "Antigravity stopped this turn because of an error.", code: status ?? null, - retryable: rateLimited || Number(httpStatus) >= 500, + retryable: rateLimited || transientNotFound || Number(httpStatus) >= 500, resetAt: resetAtFrom(text, nowMs), + ...(transientNotFound ? { resumeWith: "continue" } : {}), }; } diff --git a/apps/desktop/src/main/services/chat/acpHost/acpHost.test.ts b/apps/desktop/src/main/services/chat/acpHost/acpHost.test.ts index 43b653376f..443c197ab0 100644 --- a/apps/desktop/src/main/services/chat/acpHost/acpHost.test.ts +++ b/apps/desktop/src/main/services/chat/acpHost/acpHost.test.ts @@ -22,6 +22,7 @@ import { normalizeAcpRpcError, normalizeAcpRpcId, normalizeAcpSessionNotification, + type AcpAvailableCommand, type AcpContentBlock, type AcpSessionConfigOption, type AcpSessionUpdate, @@ -213,6 +214,16 @@ describe("dialect capability declarations", () => { expect(acpDialectFor(providerId).advertiseFsCapability).toBe(false); }); + it("shows Antigravity plugin commands and hides only logout", () => { + // ADE runs agy against the user's own ~/.gemini, so plugins installed for + // the Antigravity app load and their skills arrive as available commands. + const dialect = acpDialectFor("antigravity"); + const command = (name: string): AcpAvailableCommand => ({ name, description: name }); + expect(dialect.includeSlashCommand(command("gdocs"))).toBe(true); + expect(dialect.includeSlashCommand(command("antislop"))).toBe(true); + expect(dialect.includeSlashCommand(command("logout"))).toBe(false); + }); + it("qwen owns one process per session because 0.24.0 has no session/close", () => { expect(qwenDialect.closeStyle).toBe("kill_process"); expect(qwenDialect.oneProcessPerSession).toBe(true); @@ -1995,3 +2006,66 @@ describe("MCP injection", () => { // ───────────────────────────────────────────────────────────────────────────── // The run | degrade matrix // ───────────────────────────────────────────────────────────────────────────── + +describe("turn outcome resume", () => { + const resumeFailure = { + kind: "provider_error" as const, + message: "Requested entity was not found.", + code: "NOT_FOUND", + retryable: true, + resetAt: null, + resumeWith: "continue", + }; + + it("resends the resume prompt once and merges the turn's usage", async () => { + let checks = 0; + const dialect: AcpDialect = { + ...acpDialectFor("antigravity"), + turnOutcome: async () => async () => (++checks === 1 ? resumeFailure : null), + }; + const harness = makeHarness(dialect); + const session = await withDeadline("open", harness.open()); + const prompts: string[] = []; + harness.agent.on(ACP_METHOD.sessionPrompt, (params) => { + const blocks = (params as { prompt?: Array<{ type: string; text?: string }> }).prompt ?? []; + prompts.push(blocks.map((block) => (block.type === "text" ? block.text ?? "" : "")).join("")); + return { result: { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 2 } } }; + }); + + const result = await withDeadline("turn", session.prompt({ + turnId: "t1", + blocks: [textPromptBlock("go")], + })); + + expect(prompts).toEqual(["go", "continue"]); + expect(result.failure).toBeNull(); + expect(result.usage).toMatchObject({ inputTokens: 20, outputTokens: 4 }); + }); + + it("fails the turn after one resume when the resumed prompt fails too", async () => { + let checks = 0; + const dialect: AcpDialect = { + ...acpDialectFor("antigravity"), + turnOutcome: async () => async () => (++checks <= 2 ? resumeFailure : null), + }; + const harness = makeHarness(dialect); + const session = await withDeadline("open", harness.open()); + let prompts = 0; + harness.agent.on(ACP_METHOD.sessionPrompt, () => { + prompts += 1; + return { result: { stopReason: "end_turn" } }; + }); + + const result = await withDeadline("turn", session.prompt({ + turnId: "t1", + blocks: [textPromptBlock("go")], + })); + + expect(prompts).toBe(2); + expect(result.failure).toMatchObject({ + message: resumeFailure.message, + code: resumeFailure.code, + retryable: true, + }); + }); +}); diff --git a/apps/desktop/src/main/services/chat/acpHost/acpHostTypes.ts b/apps/desktop/src/main/services/chat/acpHost/acpHostTypes.ts index 532d1d4803..d29cc3c22e 100644 --- a/apps/desktop/src/main/services/chat/acpHost/acpHostTypes.ts +++ b/apps/desktop/src/main/services/chat/acpHost/acpHostTypes.ts @@ -381,6 +381,11 @@ export type AcpTurnFailure = { retryable: boolean; /** ISO instant the limit lifts, when the agent said. */ resetAt: string | null; + /** + * The native session can carry on: the host resends this prompt once before + * failing the turn. Only a transient error after the model answered sets it. + */ + resumeWith?: string; }; /** What background work reports. `agent_reply` is a reply written outside any turn. */ diff --git a/apps/desktop/src/main/services/chat/acpHost/acpSession.ts b/apps/desktop/src/main/services/chat/acpHost/acpSession.ts index 530db8ed4d..1d4152ecaa 100644 --- a/apps/desktop/src/main/services/chat/acpHost/acpSession.ts +++ b/apps/desktop/src/main/services/chat/acpHost/acpSession.ts @@ -88,6 +88,7 @@ import { type AcpMcpServer, type AcpNewSessionResponse, type AcpPromptResponse, + type AcpPromptUsage, type AcpSessionConfigOption, type AcpStopReason, } from "./acpProtocolTypes"; @@ -684,9 +685,43 @@ export async function openAcpSession(args: OpenAcpSessionArgs): Promise null) : null; + // One resume on the same native session. Antigravity reports a + // transient edge 404 after the model answered; the agent's own + // `continue` prompt gets the turn back without the user retyping. + if ( + failure?.resumeWith !== undefined + && !interrupted + && !cancelRequested + && isInterrupted?.() !== true + ) { + try { + permissionBridge.setTurnId(turnId); + turnPhase = "prompting"; + const resumed = await connection.request( + ACP_METHOD.sessionPrompt, + { sessionId, prompt: [textPromptBlock(failure.resumeWith)] }, + { timeoutMs: ACP_PROMPT_NO_TIMEOUT }, + ); + turnPhase = "answered"; + interrupted = cancelRequested || resumed?.stopReason === "cancelled" || isInterrupted?.() === true; + // The resumed prompt's tokens belong to the same turn. + response = { + ...resumed, + usage: mergeAcpPromptUsage(response?.usage, resumed?.usage), + }; + failure = outcomeCheck && !interrupted + ? await outcomeCheck(resumed).catch(() => null) + : null; + } finally { + if (turnPhase === "prompting") turnPhase = "idle"; + permissionBridge.cancelAll("the turn ended"); + permissionBridge.setTurnId(null); + publishSupervision(supervision.endTurn(turnId)); + } + } await waitForSettledUsage(); const usage = readPromptUsage(dialect, response); const local = localUsage @@ -830,6 +865,33 @@ function filterMcpServers( }); } +/** Both prompts of a resumed turn, field by field; the later `_meta` wins. */ +function mergeAcpPromptUsage( + first: AcpPromptUsage | null | undefined, + second: AcpPromptUsage | null | undefined, +): AcpPromptUsage | null { + if (!first) return second ?? null; + if (!second) return first; + const sum = (a: number | null | undefined, b: number | null | undefined): number | undefined => { + const left = typeof a === "number" && Number.isFinite(a) ? a : undefined; + const right = typeof b === "number" && Number.isFinite(b) ? b : undefined; + return left === undefined ? right : right === undefined ? left : left + right; + }; + return { + totalTokens: sum(first.totalTokens, second.totalTokens), + inputTokens: sum(first.inputTokens, second.inputTokens), + outputTokens: sum(first.outputTokens, second.outputTokens), + thoughtTokens: sum(first.thoughtTokens, second.thoughtTokens) ?? null, + cachedReadTokens: sum(first.cachedReadTokens, second.cachedReadTokens) ?? null, + cachedWriteTokens: sum(first.cachedWriteTokens, second.cachedWriteTokens) ?? null, + ...(second._meta !== undefined + ? { _meta: second._meta } + : first._meta !== undefined + ? { _meta: first._meta } + : {}), + }; +} + function readPromptUsage(dialect: AcpDialect, response: AcpPromptResponse | null): AcpUsageSample | null { if (!response) return null; return dialect.usage.behavior({ promptResponse: response, promptUsage: response.usage ?? null });