Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -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();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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 = /(?<![A-Z_])([A-Z_]+) \(code (\d{3})\): (\P{Cc}+)/u;
const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;
const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;
const GO_DURATION = "((?:\\d+(?:\\.\\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\\s\\]])";
Expand All @@ -52,7 +56,21 @@ const GO_DURATION_UNIT_MS: Record<string, number> = {
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;
Expand Down Expand Up @@ -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,
};
};
}

Expand Down Expand Up @@ -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",
Expand All @@ -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" } : {}),
};
}

Expand Down
74 changes: 74 additions & 0 deletions apps/desktop/src/main/services/chat/acpHost/acpHost.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
normalizeAcpRpcError,
normalizeAcpRpcId,
normalizeAcpSessionNotification,
type AcpAvailableCommand,
type AcpContentBlock,
type AcpSessionConfigOption,
type AcpSessionUpdate,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
});
});
});
5 changes: 5 additions & 0 deletions apps/desktop/src/main/services/chat/acpHost/acpHostTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
Loading
Loading