From e9c40077ddeaa7f141449cd3631527fff93ad3f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=ADas=20Chicao?= Date: Wed, 18 Nov 2026 22:59:19 -0300 Subject: [PATCH 1/4] fix(antigravity): wait for backgrounded foreground commands to settle --- .../Adapters/AntigravityAdapterV2.test.ts | 683 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 53 +- .../provider/acp/AntigravityChildWork.test.ts | 142 ++++ .../src/provider/acp/AntigravityChildWork.ts | 214 ++++++ .../provider/acp/AntigravityProtocol.test.ts | 28 + .../src/provider/acp/AntigravityProtocol.ts | 17 + packages/provider-acp/src/server/adapter.ts | 326 +++++++-- 7 files changed, 1419 insertions(+), 44 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b281ecc16ab84..9a538e1369d71 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off -- fixtures write a native session database. +import * as NodeSqlite from "node:sqlite"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; @@ -1274,3 +1276,684 @@ describe("AntigravityAdapterV2 session system prompt", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 foreground command settlement", () => { + const encodeVarint = (value: number): number[] => { + const out: number[] = []; + let current = value; + while (current >= 0x80) { + out.push((current & 0x7f) | 0x80); + current = Math.floor(current / 0x80); + } + return [...out, current]; + }; + const encodeBytesField = (fieldNumber: number, value: string | Uint8Array): number[] => { + const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; + return [...encodeVarint(fieldNumber * 8 + 2), ...encodeVarint(bytes.length), ...bytes]; + }; + const commandMetadataBlob = (callId: string) => + Uint8Array.from( + encodeBytesField( + 4, + Uint8Array.from([...encodeBytesField(1, callId), ...encodeBytesField(2, "run_command")]), + ), + ); + + const createNativeStepsDb = Effect.fn("createNativeStepsDb")(function* ( + sessionId: string, + rows: ReadonlyArray<{ readonly idx: number; readonly callId: string; readonly status: number }>, + ) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profileDirectory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-ag-fg-profile-", + }); + const conversationsDir = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fileSystem.makeDirectory(conversationsDir, { recursive: true }); + const dbPath = path.join(conversationsDir, `${sessionId}.db`); + const db = new NodeSqlite.DatabaseSync(dbPath); + try { + db.exec( + "CREATE TABLE steps (idx integer PRIMARY KEY, step_type integer NOT NULL DEFAULT 0, status integer NOT NULL DEFAULT 0, metadata blob, step_payload blob, step_format integer NOT NULL DEFAULT 0)", + ); + const insert = db.prepare( + "INSERT INTO steps (idx, step_type, status, metadata, step_payload, step_format) VALUES (?, ?, ?, ?, ?, 0)", + ); + for (const row of rows) { + insert.run(row.idx, 132, row.status, commandMetadataBlob(row.callId), new Uint8Array()); + } + } finally { + db.close(); + } + return { profileDirectory, dbPath }; + }); + + const makeForegroundFixture = Effect.fn("makeForegroundFixture")(function* (input: { + readonly name: string; + readonly profileDirectory: string; + readonly sessionId: string; + readonly foregroundCommandSettlement?: Parameters< + typeof makeAntigravityAdapterV2 + >[0]["foregroundCommandSettlement"]; + readonly onDrainEvents?: () => Effect.Effect; + readonly onPrompt: (args: { + readonly promptIndex: number; + readonly payload: Parameters[0]; + readonly emit: (update: EffectAcpSchema.SessionUpdate) => Effect.Effect; + }) => Effect.Effect; + }) { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: `t3-ag-${input.name}-` }); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + type SessionUpdateHandler = Parameters[0]; + let sessionUpdate: SessionUpdateHandler | undefined; + const receivedPrompts: Array = []; + const instanceId = ProviderInstanceId.make(`antigravity-${input.name}`); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + profileDirectory: input.profileDirectory, + ...(input.foregroundCommandSettlement === undefined + ? {} + : { foregroundCommandSettlement: input.foregroundCommandSettlement }), + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (runtimeInput) => + makeAntigravityAcpRuntime({ + ...runtimeInput, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: runtimeInput.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + start: () => + runtime + .start() + .pipe(Effect.map((started) => ({ ...started, sessionId: input.sessionId }))), + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + drainEvents: + input.onDrainEvents === undefined + ? runtime.drainEvents + : runtime.drainEvents.pipe(Effect.tap(input.onDrainEvents)), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + receivedPrompts.push(JSON.stringify(payload.prompt)); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const emit = (update: EffectAcpSchema.SessionUpdate) => emitUpdate(update); + return yield* input.onPrompt({ + promptIndex: receivedPrompts.length, + payload, + emit, + }); + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + + const emitUpdate = (update: EffectAcpSchema.SessionUpdate): Effect.Effect => { + const send = sessionUpdate; + if (send === undefined) { + return Effect.die(new Error("sessionUpdate handler was not registered")); + } + return send( + normalizeAntigravitySessionUpdate({ + sessionId: input.sessionId, + update, + }), + ).pipe(Effect.orDie); + }; + + const threadId = ThreadId.make(`thread-antigravity-${input.name}`); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make(`provider-session-antigravity-${input.name}`), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const startedTurnId = + yield* Deferred.make< + NonNullable< + Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "turn_item.updated" } + >["turnItem"]["providerTurnId"] + > + >(); + const eventsFiber = yield* session.events.pipe( + Stream.tap((event) => + event.type === "turn_item.updated" && event.turnItem.providerTurnId !== null + ? Deferred.succeed(startedTurnId, event.turnItem.providerTurnId).pipe(Effect.asVoid) + : Effect.void, + ), + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.forkScoped, + ); + const now = yield* DateTime.now; + const startTurn = () => + session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make(`project-antigravity-${input.name}`), + title: `Antigravity ${input.name}`, + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: workspace, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make(`run-antigravity-${input.name}`), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make(`attempt-antigravity-${input.name}`), + rootNodeId: NodeId.make(`node-antigravity-${input.name}`), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`message-antigravity-${input.name}`), + text: "run the build", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + + return { + session, + providerThread, + eventsFiber, + startedTurnId, + receivedPrompts, + startTurn, + emitUpdate, + }; + }); + + it.live( + "waits for a backgrounded foreground command to finish natively, sends one continuation without spinning, and ignores IsDaemon", + () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa1"; + const { profileDirectory, dbPath } = yield* createNativeStepsDb(sessionId, [ + { idx: 45, callId: "call_build", status: 2 }, + ]); + const firstPromptReturned = yield* Deferred.make(); + const fixture = yield* makeForegroundFixture({ + name: "fg-detached-done", + profileDirectory, + sessionId, + onPrompt: ({ promptIndex, emit }) => + Effect.gen(function* () { + if (promptIndex === 1) { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_dev", + title: "Dev server", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run dev", IsDaemon: true }, + }); + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_build", + title: "Build", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run build", IsDaemon: false }, + }); + yield* Deferred.succeed(firstPromptReturned, undefined); + return { stopReason: "end_turn" as const }; + } + // Simulates agy 1.5.11: never re-emits tool_call_update(completed) for call_build. + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Build finished." }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* fixture.startTurn(); + yield* Deferred.await(firstPromptReturned); + // Transition native SQLite step 45 from RUNNING (2) to DONE (3) while detached. + const db = new NodeSqlite.DatabaseSync(dbPath); + try { + db.prepare("UPDATE steps SET status = 3 WHERE idx = 45").run(); + } finally { + db.close(); + } + + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + assert.equal(fixture.receivedPrompts.length, 2); + assert.include(fixture.receivedPrompts[1] ?? "", ""); + assert.include(fixture.receivedPrompts[1] ?? "", "npm run build"); + assert.notInclude(fixture.receivedPrompts[1] ?? "", "npm run dev"); + const assistantText = events + .flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message" + ? [event.turnItem.text ?? ""] + : [], + ) + .join(""); + assert.include(assistantText, "Build finished."); + const terminals = events.filter((event) => event.type === "turn.terminal"); + assert.equal(terminals.length, 1); + assert.equal(terminals[0]?.status, "completed"); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live( + "settles a detached failed foreground command as failed instead of fabricating completed", + () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa2"; + const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ + { idx: 46, callId: "call_fail", status: 7 }, + ]); + const fixture = yield* makeForegroundFixture({ + name: "fg-detached-fail", + profileDirectory, + sessionId, + onPrompt: ({ promptIndex, emit }) => + Effect.gen(function* () { + if (promptIndex === 1) { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_fail", + title: "Tests", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm test", IsDaemon: false }, + }); + return { stopReason: "end_turn" as const }; + } + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Tests failed." }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* fixture.startTurn(); + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + assert.equal(fixture.receivedPrompts.length, 2); + const settledTool = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "call_fail", + ); + assert.equal( + settledTool?.type === "turn_item.updated" ? settledTool.turnItem.status : null, + "failed", + ); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live( + "aborts waiting on a running native foreground command when Stop is requested without re-prompting", + () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa3"; + const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ + { idx: 47, callId: "call_long", status: 2 }, + ]); + const firstPromptReturned = yield* Deferred.make(); + const fixture = yield* makeForegroundFixture({ + name: "fg-stop-waiting", + profileDirectory, + sessionId, + onPrompt: ({ emit }) => + Effect.gen(function* () { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_long", + title: "Long job", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run e2e", IsDaemon: false }, + }); + yield* Deferred.succeed(firstPromptReturned, undefined); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* fixture.startTurn(); + const providerTurnId = yield* Deferred.await(fixture.startedTurnId); + yield* Deferred.await(firstPromptReturned); + yield* fixture.session.interruptTurn({ + providerThread: fixture.providerThread, + providerTurnId, + }); + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + assert.equal(fixture.receivedPrompts.length, 1); + const terminal = events.find((event) => event.type === "turn.terminal"); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "interrupted"); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live( + "still sends one continuation when ACP completes the command after end_turn while waiting", + () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa4"; + const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ + { idx: 48, callId: "call_late_acp", status: 2 }, + ]); + const enteredWait = yield* Deferred.make(); + let firstPromptDone = false; + const fixture = yield* makeForegroundFixture({ + name: "fg-late-acp", + profileDirectory, + sessionId, + onDrainEvents: () => + firstPromptDone + ? Deferred.succeed(enteredWait, undefined).pipe(Effect.asVoid) + : Effect.void, + onPrompt: ({ promptIndex, emit }) => + Effect.gen(function* () { + if (promptIndex === 1) { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_late_acp", + title: "Late ACP command", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run test", IsDaemon: false }, + }); + firstPromptDone = true; + return { stopReason: "end_turn" as const }; + } + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Late ACP result delivered." }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* fixture.startTurn(); + yield* Deferred.await(enteredWait); + yield* Effect.sleep("50 millis"); + // Simulate agy 1.5.11 emitting tool_call_update(completed) after end_turn while adapter waits. + yield* fixture.emitUpdate({ + sessionUpdate: "tool_call_update", + toolCallId: "call_late_acp", + status: "completed", + rawOutput: "OK", + }); + + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + assert.equal(fixture.receivedPrompts.length, 2); + const assistantText = events + .flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message" + ? [event.turnItem.text ?? ""] + : [], + ) + .join(""); + assert.include(assistantText, "Late ACP result delivered."); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live( + "keeps waiting when native status reader throws or returns empty, never mislabels interrupted, and sends still_running continuation on maxWait", + () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa5"; + const fileSystem = yield* FileSystem.FileSystem; + const emptyProfile = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-ag-empty-profile-", + }); + let readerCalls = 0; + const fixture = yield* makeForegroundFixture({ + name: "fg-reader-errors", + profileDirectory: emptyProfile, + sessionId, + foregroundCommandSettlement: { + maxWait: "120 millis", + pollInterval: "25 millis", + maxContinuations: 1, + makeStatusReader: () => () => { + readerCalls += 1; + if (readerCalls === 1) { + return Effect.fail( + new EffectAcpErrors.AcpTransportError({ + detail: "SQLITE_BUSY", + cause: new Error("SQLITE_BUSY"), + }), + ); + } + return Effect.succeed(new Map()); + }, + }, + onPrompt: ({ promptIndex, emit }) => + Effect.gen(function* () { + if (promptIndex === 1) { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_unknown_native", + title: "Opaque command", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run opaque", IsDaemon: false }, + }); + return { stopReason: "end_turn" as const }; + } + yield* emit({ + sessionUpdate: "tool_call_update", + toolCallId: "call_unknown_native", + status: "completed", + rawOutput: "DONE", + }); + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Checked status and finished." }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* fixture.startTurn(); + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + assert.isAtLeast(readerCalls, 2); + assert.equal(fixture.receivedPrompts.length, 2); + assert.include(fixture.receivedPrompts[1] ?? "", "still running"); + const toolStatuses = events + .filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "call_unknown_native", + ) + .map((event) => (event.type === "turn_item.updated" ? event.turnItem.status : null)); + assert.notInclude(toolStatuses, "interrupted"); + assert.equal(toolStatuses.at(-1), "completed"); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live( + "reports both settled and still-running commands on mixed timeout and honestly terminates tracking at maxContinuations cap", + () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa6"; + const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ + { idx: 50, callId: "call_done_a", status: 3 }, + { idx: 51, callId: "call_still_b", status: 2 }, + ]); + const fixture = yield* makeForegroundFixture({ + name: "fg-mixed-cap", + profileDirectory, + sessionId, + foregroundCommandSettlement: { + maxWait: "80 millis", + pollInterval: "20 millis", + maxContinuations: 1, + }, + onPrompt: ({ promptIndex, emit }) => + Effect.gen(function* () { + if (promptIndex === 1) { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_done_a", + title: "Build A", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run build-a", IsDaemon: false }, + }); + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_still_b", + title: "Tests B", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run test-b", IsDaemon: false }, + }); + return { stopReason: "end_turn" as const }; + } + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "A finished; B is still running." }, + }); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* fixture.startTurn(); + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + // Initial prompt + 1 continuation (capped at maxContinuations = 1). + assert.equal(fixture.receivedPrompts.length, 2); + assert.include(fixture.receivedPrompts[1] ?? "", "npm run build-a"); + assert.include(fixture.receivedPrompts[1] ?? "", "npm run test-b"); + + const lastItemOf = (nativeId: string) => { + const last = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + return last?.type === "turn_item.updated" ? last.turnItem : null; + }; + assert.equal(lastItemOf("call_done_a")?.status, "completed"); + // At the cap, B terminates honestly as interrupted with a detached notice (never a permanent spinner or fake completed). + const itemB = lastItemOf("call_still_b"); + assert.equal(itemB?.status, "interrupted"); + assert.include( + itemB?.type === "command_execution" ? (itemB.output ?? "") : "", + "still be running natively", + ); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + + it.live("sums per-turn prompt usage across continuation prompts", () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa7"; + const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ + { idx: 52, callId: "call_usage", status: 3 }, + ]); + const fixture = yield* makeForegroundFixture({ + name: "fg-usage-sum", + profileDirectory, + sessionId, + onPrompt: ({ promptIndex, emit }) => + Effect.gen(function* () { + if (promptIndex === 1) { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_usage", + title: "Build", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run build", IsDaemon: false }, + }); + return { + stopReason: "end_turn" as const, + usage: { + inputTokens: 100, + outputTokens: 40, + totalTokens: 140, + cachedReadTokens: 20, + }, + }; + } + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Done." }, + }); + return { + stopReason: "end_turn" as const, + usage: { + inputTokens: 150, + outputTokens: 60, + totalTokens: 210, + cachedReadTokens: 30, + }, + }; + }), + }); + + yield* fixture.startTurn(); + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + const completedTurn = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepEqual( + completedTurn?.type === "provider_turn.updated" + ? completedTurn.providerTurn.turnTokenUsage + : null, + { + usageScope: "main_agent", + usageStatus: "complete", + hasSubagents: false, + // Gemini usage.inputTokens excludes cachedReadTokens, so TurnTokenUsage sums both: (100+150) + (20+30). + inputTokens: 300, + outputTokens: 100, + cachedInputTokens: 50, + }, + ); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 8566cbb83f9e9..7f14592733c90 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -31,6 +31,7 @@ import { ANTIGRAVITY_SUBAGENT_BATCH_TITLE, antigravitySubagentLaunches, describeAntigravitySubagentLaunches, + makeAntigravityCommandStatusReader, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; @@ -39,6 +40,7 @@ import { antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, + isAntigravityOpenForegroundCommand, makeAntigravityReadRepair, makeAntigravityUserInputResponse, normalizeAntigravityToolCall, @@ -98,6 +100,12 @@ export interface AntigravityAdapterV2Options { readonly continuationRequests?: Parameters[0]["continuationRequests"]; /** The agent's GEMINI_HOME. Its session logs show turns that ended on an upstream error. */ readonly profileDirectory?: string; + readonly foregroundCommandSettlement?: Partial< + Pick< + NonNullable, + "maxWait" | "pollInterval" | "maxContinuations" | "makeStatusReader" + > + >; } /** @@ -186,7 +194,11 @@ export function makeAntigravityAcpAdapterFlavor( ), ), prompt: (payload, promptOptions) => - Effect.sync(reads.reset).pipe(Effect.andThen(runtime.prompt(payload, promptOptions))), + Effect.sync(reads.reset).pipe( + Effect.andThen(runtime.prompt(payload, promptOptions)), + // Wait for any in-flight update/read-repair callback before prompt settlement checks tool state. + Effect.tap(() => updates.withPermit(Effect.void)), + ), handleSessionUpdate: (handler) => { projectUpdate = handler; return runtime.handleSessionUpdate((notification) => @@ -218,6 +230,45 @@ export function makeAntigravityAcpAdapterFlavor( supportsNativeGoals: options.supportsNativeGoals ?? Effect.succeed(false), // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio. mcpOverHttp: true, + foregroundCommandSettlement: { + isOpenForegroundCommand: isAntigravityOpenForegroundCommand, + ...(profileDirectory === undefined + ? {} + : { + makeStatusReader: (sessionId: string) => + makeAntigravityCommandStatusReader(profileDirectory, sessionId), + }), + ...options.foregroundCommandSettlement, + buildContinuationPrompt: ({ settled, stillRunning }) => { + const formatSummary = ( + tools: ReadonlyArray<{ readonly command?: string; readonly title?: string }>, + ) => { + const commands = tools + .map((tool) => tool.command ?? tool.title) + .filter((value): value is string => Boolean(value?.trim())) + .slice(0, 3); + return commands.length > 0 ? ` (${commands.join("; ")})` : ""; + }; + const lines: Array = []; + if (settled.length > 0) { + lines.push( + `The background command${formatSummary(settled)} finished without delivering a final wakeup reply over ACP. Report its verified result without re-running completed commands.`, + ); + } + if (stillRunning.length > 0) { + lines.push( + `The background command${formatSummary(stillRunning)} was still running when your turn ended. Check its status in this turn and report its result once complete.`, + ); + } + lines.push("Finish the user's request once all relevant results are reported."); + return [ + { + type: "text", + text: `\n${lines.join("\n")}\n`, + }, + ]; + }, + }, sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt, makeRuntime, buildAttachmentPrompt: ({ diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index 78927b09d74e3..72a7e67b4b332 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -11,6 +11,7 @@ import { ANTIGRAVITY_SUBAGENT_BATCH_TITLE, antigravitySubagentLaunches, describeAntigravitySubagentLaunches, + makeAntigravityCommandStatusReader, readAntigravityChildWork, } from "./AntigravityChildWork.ts"; import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts"; @@ -341,4 +342,145 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { expect(JSON.stringify(children).length).toBeLessThan(600 * 1024); }), ); + + it.effect("reads native command steps.status values and tracks cached transitions", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-cmd-status-" }); + const conversations = path.join(profile, "antigravity-acp", "conversations"); + yield* fs.makeDirectory(conversations, { recursive: true }); + const dbPath = path.join(conversations, `${ROOT}.db`); + const varint = (value: number): number[] => { + const bytes: number[] = []; + let current = value; + while (current >= 0x80) { + bytes.push((current & 0x7f) | 0x80); + current = Math.floor(current / 0x80); + } + return [...bytes, current]; + }; + const field = (num: number, value: string | Uint8Array) => { + const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; + return [...varint(num * 8 + 2), ...varint(bytes.length), ...bytes]; + }; + const metadataFor = (callId: string) => + Uint8Array.from( + field(4, Uint8Array.from([...field(1, callId), ...field(2, "run_command")])), + ); + const { DatabaseSync } = yield* Effect.promise(() => import("node:sqlite")); + const db = new DatabaseSync(dbPath); + try { + db.exec( + "CREATE TABLE steps (idx integer PRIMARY KEY, step_type integer NOT NULL DEFAULT 0, status integer NOT NULL DEFAULT 0, metadata blob, step_payload blob, step_format integer NOT NULL DEFAULT 0)", + ); + const insert = db.prepare( + "INSERT INTO steps (idx, step_type, status, metadata, step_payload, step_format) VALUES (?, ?, ?, ?, ?, 0)", + ); + const plannerPayload = Uint8Array.from( + field( + 20, + Uint8Array.from( + field( + 7, + Uint8Array.from([...field(1, "call_via_planner"), ...field(2, "run_command")]), + ), + ), + ), + ); + insert.run(9, 15, 3, new Uint8Array(), plannerPayload); + insert.run(10, 132, 2, metadataFor("call_run"), new Uint8Array()); + insert.run(11, 132, 6, metadataFor("call_cancel"), new Uint8Array()); + insert.run(12, 132, 7, metadataFor("call_err"), new Uint8Array()); + insert.run(13, 21, 5, metadataFor("call_cleared"), new Uint8Array()); + insert.run(14, 132, 99, metadataFor("call_unknown"), new Uint8Array()); + insert.run(15, 21, 2, metadataFor("call_via_planner"), new Uint8Array()); + } finally { + db.close(); + } + const readStatuses = makeAntigravityCommandStatusReader(profile, ROOT); + const initial = yield* readStatuses([ + { toolCallId: "call_run" }, + { toolCallId: "call_cancel" }, + { toolCallId: "call_err" }, + { toolCallId: "call_cleared" }, + { toolCallId: "call_unknown" }, + { toolCallId: `${ROOT}:9` }, + { toolCallId: "call_missing" }, + ]); + expect(initial.get("call_run")).toBe("running"); + expect(initial.get("call_cancel")).toBe("cancelled"); + expect(initial.get("call_err")).toBe("failed"); + expect(initial.get("call_cleared")).toBe("cancelled"); + expect(initial.get("call_unknown")).toBeUndefined(); + expect(initial.get(`${ROOT}:9`)).toBe("running"); + expect(initial.get("call_missing")).toBeUndefined(); + + const updateDb = new DatabaseSync(dbPath); + try { + updateDb.prepare("UPDATE steps SET status = 3 WHERE idx = 10").run(); + updateDb + .prepare( + "INSERT INTO steps (idx, step_type, status, metadata, step_payload, step_format) VALUES (16, 132, 3, ?, ?, 0)", + ) + .run(metadataFor("call_late_insert"), new Uint8Array()); + } finally { + updateDb.close(); + } + const next = yield* readStatuses([ + { toolCallId: "call_run" }, + { toolCallId: "call_late_insert" }, + ]); + expect(next.get("call_run")).toBe("completed"); + expect(next.get("call_late_insert")).toBe("completed"); + }), + ); + + it.effect("reads native command statuses from step_payload when metadata column is absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-cmd-nometa-" }); + const conversations = path.join(profile, "antigravity-acp", "conversations"); + yield* fs.makeDirectory(conversations, { recursive: true }); + const dbPath = path.join(conversations, `${ROOT}.db`); + const varint = (value: number): number[] => { + const bytes: number[] = []; + let current = value; + while (current >= 0x80) { + bytes.push((current & 0x7f) | 0x80); + current = Math.floor(current / 0x80); + } + return [...bytes, current]; + }; + const field = (num: number, value: string | Uint8Array) => { + const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; + return [...varint(num * 8 + 2), ...varint(bytes.length), ...bytes]; + }; + const stepPayloadFor = (callId: string) => + Uint8Array.from( + field( + 5, + Uint8Array.from( + field(4, Uint8Array.from([...field(1, callId), ...field(2, "run_command")])), + ), + ), + ); + const { DatabaseSync } = yield* Effect.promise(() => import("node:sqlite")); + const db = new DatabaseSync(dbPath); + try { + db.exec( + "CREATE TABLE steps (idx integer PRIMARY KEY, step_type integer NOT NULL DEFAULT 0, status integer NOT NULL DEFAULT 0, step_payload blob, step_format integer NOT NULL DEFAULT 0)", + ); + db.prepare( + "INSERT INTO steps (idx, step_type, status, step_payload, step_format) VALUES (20, 132, 3, ?, 0)", + ).run(stepPayloadFor("call_nometa")); + } finally { + db.close(); + } + const readStatuses = makeAntigravityCommandStatusReader(profile, ROOT); + const statuses = yield* readStatuses([{ toolCallId: "call_nometa" }]); + expect(statuses.get("call_nometa")).toBe("completed"); + }), + ); }); diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index ea12e0e2b20de..9b45412222d78 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -8,6 +8,7 @@ import type { OrchestrationV2NativeChildStep, OrchestrationV2NativeChildWork, } from "@t3tools/contracts"; +import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; @@ -25,6 +26,24 @@ const STEP_INVOKE_SUBAGENT = 143; const INVOKE_SPECS = 9; const INVOKE_RESULTS = 10; const INVOKE_SUBAGENT_STEP_TYPE = 127; +// Cortex step types for shell commands (exa.cortex_pb): RUN_COMMAND=21, GENERIC=132. +const MAX_COMMAND_SCAN_ROWS = 256; + +export type AntigravityCommandNativeState = "running" | "completed" | "failed" | "cancelled"; + +// CortexStepStatus (exa.cortex_pb, verified against agy 1.5.11 embedded proto descriptor): +// In-flight: PENDING=1, RUNNING=2, GENERATING=8, WAITING=9, QUEUED=11 +// Terminal: DONE=3, INVALID=4, CLEARED=5, CANCELED=6, ERROR=7, INTERRUPTED=12 +// Unlisted/UNSPECIFIED=0 return undefined so unknown future codes are never assumed running. +function decodeNativeCommandStatus(status: number): AntigravityCommandNativeState | undefined { + if (status === 3) return "completed"; + if (status === 5 || status === 6 || status === 12) return "cancelled"; + if (status === 4 || status === 7) return "failed"; + if (status === 1 || status === 2 || status === 8 || status === 9 || status === 11) { + return "running"; + } + return undefined; +} // One open reads at most this much; past any bound the batch view stays as it was. const MAX_STEP_BYTES = 1024 * 1024; @@ -476,3 +495,198 @@ export const readAntigravityChildWork = Effect.fn("readAntigravityChildWork")(fu catch: (cause) => new AntigravityChildWorkReadError({ cause }), }); }); + +/** + * Reads native `steps.status` for Antigravity shell commands, caching `toolCallId -> idx` so + * repeat checks run a single primary-key lookup per command. + */ +export function makeAntigravityCommandStatusReader( + profileDirectory: string, + rootSessionId: string, +) { + const stepIndexByToolCallId = new Map(); + const stepIndexByCallId = new Map(); + const seenUnknownStatuses = new Set(); + let lastScannedMaxIdx = -1; + + const plannerCommandCallIdAt = (database: NodeSqlite.DatabaseSync, plannerIdx: number) => { + const planner = payloadOf( + database + .prepare( + "SELECT step_payload FROM steps WHERE idx = ? AND step_format = 0 AND length(step_payload) <= ?", + ) + .get(plannerIdx, MAX_STEP_BYTES), + ); + if (planner === undefined) return undefined; + const calls = safely((payload) => { + const response = message(payload, STEP_PLANNER_RESPONSE); + if (response === undefined) return []; + return messages(response, PLANNER_TOOL_CALLS).flatMap((call) => { + const id = text(call, 1); + return text(call, 2) === "run_command" && id !== undefined ? [id] : []; + }); + })(planner); + return calls?.length === 1 ? calls[0] : undefined; + }; + + return Effect.fn("readAntigravityCommandStatuses")(function* ( + tools: ReadonlyArray>, + ) { + const result = new Map(); + if (!NATIVE_ID.test(rootSessionId) || tools.length === 0) return result; + const unknownStatuses: Array<{ readonly toolCallId: string; readonly status: number }> = []; + const recordStatus = (toolCallId: string, status: number) => { + const decoded = decodeNativeCommandStatus(status); + if (decoded !== undefined) { + result.set(toolCallId, decoded); + return; + } + const key = `${toolCallId}:${status}`; + if (!seenUnknownStatuses.has(key)) { + seenUnknownStatuses.add(key); + unknownStatuses.push({ toolCallId, status }); + } + }; + const statuses = yield* Effect.tryPromise({ + try: async (): Promise> => { + const root = await antigravityProfileRoot(profileDirectory); + if (root === undefined) return result; + const file = + (await antigravityManagedPath( + root, + ["antigravity-cli", "conversations", `${rootSessionId}.db`], + "file", + )) ?? + (await antigravityManagedPath( + root, + ["antigravity-acp", "conversations", `${rootSessionId}.db`], + "file", + )); + if (file === undefined) return result; + + const database = new NodeSqlite.DatabaseSync(file.path, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const columns = new Set( + database + .prepare("PRAGMA table_info(steps)") + .all() + .flatMap((row) => + row !== null && + typeof row === "object" && + "name" in row && + typeof row.name === "string" + ? [row.name] + : [], + ), + ); + if (!columns.has("status")) return result; + const hasMetadata = columns.has("metadata"); + + const statusByIndex = database.prepare("SELECT status FROM steps WHERE idx = ?"); + const unresolved = new Map(); + for (const { toolCallId } of tools) { + const cachedIdx = stepIndexByToolCallId.get(toolCallId); + if (cachedIdx !== undefined) { + const row = statusByIndex.get(cachedIdx); + if (row !== undefined && typeof row.status === "number") { + recordStatus(toolCallId, row.status); + } + continue; + } + const stepRef = /^(.+):(\d+)$/.exec(toolCallId); + const lookupCallId = + stepRef !== null && stepRef[1] === rootSessionId + ? plannerCommandCallIdAt(database, Number(stepRef[2])) + : toolCallId; + if (lookupCallId === undefined) continue; + const knownIdx = stepIndexByCallId.get(lookupCallId); + if (knownIdx !== undefined) { + stepIndexByToolCallId.set(toolCallId, knownIdx); + const row = statusByIndex.get(knownIdx); + if (row !== undefined && typeof row.status === "number") { + recordStatus(toolCallId, row.status); + } + continue; + } + unresolved.set(lookupCallId, toolCallId); + } + + if (unresolved.size > 0) { + let scannedBytes = 0; + let scannedRows = 0; + let scannedMaxIdx = lastScannedMaxIdx; + let hitScanCap = false; + let sawUnmappedRow = false; + const query = hasMetadata + ? database.prepare( + "SELECT idx, status, CASE WHEN length(metadata) <= ? THEN metadata END AS metadata FROM steps WHERE step_type IN (21, 132) AND step_format = 0 AND idx > ? ORDER BY idx DESC LIMIT ?", + ) + : database.prepare( + "SELECT idx, status, CASE WHEN length(step_payload) <= ? THEN step_payload END AS step_payload FROM steps WHERE step_type IN (21, 132) AND step_format = 0 AND idx > ? ORDER BY idx DESC LIMIT ?", + ); + for (const row of query.iterate( + MAX_STEP_BYTES, + lastScannedMaxIdx, + MAX_COMMAND_SCAN_ROWS, + )) { + scannedRows += 1; + if (typeof row.idx !== "number" || typeof row.status !== "number") continue; + if (row.idx > scannedMaxIdx) scannedMaxIdx = row.idx; + const blob = hasMetadata ? row.metadata : row.step_payload; + if (!(blob instanceof Uint8Array)) { + sawUnmappedRow = true; + continue; + } + scannedBytes += blob.length; + if (scannedBytes > MAX_SCAN_BYTES) { + hitScanCap = true; + break; + } + const callId = hasMetadata + ? safely((data) => text(message(data, METADATA_TOOL_CALL), 1))(blob) + : safely((data) => + text(message(message(data, STEP_METADATA), METADATA_TOOL_CALL), 1), + )(blob); + if (callId === undefined) { + sawUnmappedRow = true; + continue; + } + stepIndexByCallId.set(callId, row.idx); + const ownerToolCallId = unresolved.get(callId); + if (ownerToolCallId === undefined) continue; + stepIndexByToolCallId.set(ownerToolCallId, row.idx); + recordStatus(ownerToolCallId, row.status); + unresolved.delete(callId); + if (unresolved.size === 0) break; + } + // Advance the watermark only when every row above it was scanned and mapped + // without hitting the row/byte caps, so neither >256-row backlogs nor rows whose + // metadata is written asynchronously are skipped permanently. + if ( + unresolved.size > 0 && + !hitScanCap && + !sawUnmappedRow && + scannedRows < MAX_COMMAND_SCAN_ROWS && + scannedMaxIdx > lastScannedMaxIdx + ) { + lastScannedMaxIdx = scannedMaxIdx; + } + } + + return result; + } finally { + database.close(); + } + }, + catch: (cause) => new AntigravityChildWorkReadError({ cause }), + }); + if (unknownStatuses.length > 0) { + yield* Effect.logDebug("antigravity.unknown-command-step-status", { + sessionId: rootSessionId, + unknownStatuses, + }); + } + return statuses; + }); +} diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index a2d7c86f4c2d3..bb042429a0325 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -8,6 +8,7 @@ import { antigravityApprovalOptions, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, + isAntigravityOpenForegroundCommand, isAntigravityUserInputRequest, makeAntigravityUserInputResponse, normalizeAntigravitySessionUpdate, @@ -623,3 +624,30 @@ describe("Antigravity served reads", () => { }); }); }); + +describe("Antigravity foreground command classification", () => { + it("preserves IsDaemon and classifies only open non-daemon execute tools as foreground commands", () => { + const fg = normalizeAntigravityToolCall({ + toolCallId: "call_fg", + kind: "execute", + status: "inProgress", + data: { rawInput: { CommandLine: "npm test", IsDaemon: false } }, + }); + const daemon = normalizeAntigravityToolCall({ + toolCallId: "call_daemon", + kind: "execute", + status: "inProgress", + data: { rawInput: { CommandLine: "npm run dev", IsDaemon: true } }, + }); + const done = normalizeAntigravityToolCall({ + toolCallId: "call_done", + kind: "execute", + status: "completed", + data: { rawInput: { CommandLine: "npm test" } }, + }); + expect(isAntigravityOpenForegroundCommand(fg)).toBe(true); + expect(daemon.data.isDaemon).toBe(true); + expect(isAntigravityOpenForegroundCommand(daemon)).toBe(false); + expect(isAntigravityOpenForegroundCommand(done)).toBe(false); + }); +}); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 5b74756a1de11..cebc082320c62 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -28,6 +28,9 @@ const NativeToolFields = Schema.Struct({ CommandLine: Schema.optional(Schema.String), command_line: Schema.optional(Schema.String), commandLine: Schema.optional(Schema.String), + IsDaemon: Schema.optional(Schema.Boolean), + isDaemon: Schema.optional(Schema.Boolean), + is_daemon: Schema.optional(Schema.Boolean), cwd: Schema.optional(Schema.String), Cwd: Schema.optional(Schema.String), WorkingDirectory: Schema.optional(Schema.String), @@ -439,12 +442,18 @@ export function normalizeAntigravityToolCall( const aggregatedOutput = nativeOutput === undefined ? undefined : boundText(nativeOutput); const exitCode = output?.exitCode ?? output?.exit_code; const imagePath = localImagePath(output?.imagePath); + const isDaemon = + input?.IsDaemon ?? + input?.isDaemon ?? + input?.is_daemon ?? + (toolCall.data.isDaemon === true ? true : undefined); const sanitizedData = sanitizeAntigravityToolPayload(toolCall.data); const data: Record = Predicate.isObject(sanitizedData) ? sanitizedData : {}; const kind = toolCall.kind ?? (command !== undefined ? "execute" : undefined); if (kind !== undefined) data.kind = kind; if (command !== undefined) data.command = command; if (cwd !== undefined) data.cwd = cwd; + if (isDaemon === true) data.isDaemon = true; if (imagePath !== undefined) data.imagePath = imagePath; if (kind === "edit") { const content = Array.isArray(data.content) ? data.content : []; @@ -507,3 +516,11 @@ export function antigravitySubagentOutput(toolCall: AcpToolCallState): string | const output = toolCall.data.rawOutput; return typeof output === "string" && output.trim() ? boundText(output.trim()) : undefined; } + +export function isAntigravityOpenForegroundCommand(toolCall: AcpToolCallState): boolean { + return ( + toolCall.kind === "execute" && + toolCall.data.isDaemon !== true && + (toolCall.status === "pending" || toolCall.status === "inProgress") + ); +} diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index ea0bb5e46f46a..d663a1d75728f 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -339,6 +339,29 @@ export function acpPerTurnPromptUsage( }; } +function mergeAcpPromptUsage( + previous: EffectAcpSchema.Usage | undefined, + incoming: EffectAcpSchema.Usage | null | undefined, +): EffectAcpSchema.Usage | undefined { + if (incoming == null) return previous; + if (previous === undefined) return incoming; + const sumOptional = (left: number | null | undefined, right: number | null | undefined) => + left == null && right == null ? undefined : (left ?? 0) + (right ?? 0); + const cachedReadTokens = sumOptional(previous.cachedReadTokens, incoming.cachedReadTokens); + const cachedWriteTokens = sumOptional(previous.cachedWriteTokens, incoming.cachedWriteTokens); + const thoughtTokens = sumOptional(previous.thoughtTokens, incoming.thoughtTokens); + const _meta = incoming._meta ?? previous._meta; + return { + inputTokens: previous.inputTokens + incoming.inputTokens, + outputTokens: previous.outputTokens + incoming.outputTokens, + totalTokens: previous.totalTokens + incoming.totalTokens, + ...(cachedReadTokens === undefined ? {} : { cachedReadTokens }), + ...(cachedWriteTokens === undefined ? {} : { cachedWriteTokens }), + ...(thoughtTokens === undefined ? {} : { thoughtTokens }), + ...(_meta === undefined ? {} : { _meta }), + }; +} + interface AcpPromptOutcomeFailure { readonly failure: OrchestrationV2ProviderFailure; readonly threadDisposition: "reusable" | "broken"; @@ -632,6 +655,28 @@ export interface AcpAdapterV2Flavor { readonly sessionCarriesPullRequestLinking?: ( initializeResult: EffectAcpSchema.InitializeResponse, ) => boolean; + /** + * Waits for backgrounded foreground commands to settle natively after `end_turn` before + * issuing a bounded continuation prompt, avoiding premature completion and detached spin loops. + */ + readonly foregroundCommandSettlement?: { + readonly isOpenForegroundCommand: (toolCall: AcpToolCallState) => boolean; + readonly makeStatusReader?: ( + sessionId: string, + ) => ( + tools: ReadonlyArray, + ) => Effect.Effect< + ReadonlyMap, + Error + >; + readonly buildContinuationPrompt: (input: { + readonly settled: ReadonlyArray; + readonly stillRunning: ReadonlyArray; + }) => ReadonlyArray; + readonly maxWait?: Duration.Input; + readonly pollInterval?: Duration.Input; + readonly maxContinuations?: number; + }; } function acpSupportsImagePrompts(input: { @@ -1471,8 +1516,8 @@ interface ActiveAcpTurn { readonly startedAt: DateTime.Utc; readonly completed: Deferred.Deferred; readonly itemOrdinals: Map; - readonly outgoingPrompt?: ReadonlyArray | undefined; - consumedPromptMessageId?: string; + outgoingPrompt?: ReadonlyArray | undefined; + consumedPromptMessageId?: string | undefined; readonly user: ActiveTextStream; readonly assistant: ActiveTextStream; readonly reasoning: ActiveTextStream; @@ -1499,6 +1544,7 @@ interface ActiveAcpTurn { { readonly status: "completed" | "failed"; readonly output?: string } | null >; readonly persistentBackgroundTaskIds: Set; + readonly foregroundCommandWaiters: Set>; /** Monitor end notices lack output; wait for hydration or the safety timeout. */ readonly awaitingBackgroundHydration: Set; readonly pendingInjectedReport: Set; @@ -4107,6 +4153,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return next ?? current; }); + const notifyForegroundCommandWaiters = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + ) { + if (context.foregroundCommandWaiters.size === 0) return; + const waiters = [...context.foregroundCommandWaiters]; + context.foregroundCommandWaiters.clear(); + for (const waiter of waiters) { + yield* Deferred.succeed(waiter, undefined).pipe(Effect.ignore); + } + }); + emitTool = Effect.fnUntraced(function* ( context: ActiveAcpTurn, incoming: AcpToolCallState, @@ -4151,6 +4208,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? toolCall : { ...toolCall, backgroundCommandTaskId }, ); + yield* notifyForegroundCommandWaiters(context); if ( followsAgentWorkState && projectedStatus === undefined && @@ -8064,6 +8122,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const threadDisposition = options?.threadDisposition ?? "reusable"; context.finalizedStatus = settledStatus; context.finalized = true; + yield* notifyForegroundCommandWaiters(context); const watchdog = context.inactivityWatchdog; context.inactivityWatchdog = undefined; if (watchdog !== undefined) { @@ -8697,6 +8756,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( toolCallIdsByBackgroundTaskId: new Map(), backgroundCommands: new Map(), persistentBackgroundTaskIds: new Set(), + foregroundCommandWaiters: new Set(), awaitingBackgroundHydration: new Set(), pendingInjectedReport: new Set(), earlyInjectedReportObserved: false, @@ -8862,16 +8922,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return; } - const checkPromptOutcome = - flavor.watchPromptOutcome === undefined - ? undefined - : yield* flavor.watchPromptOutcome(requestedSessionId); const promptGeneration = yield* Ref.get(runtimeCallbackGeneration); const promptOptions = { dispatched: context.promptDispatched, released: context.foregroundIdle, }; - context.promptSentAt = yield* Clock.currentTimeMillis; if (promptInactivityTimeoutMillis !== undefined) { context.inactivityWatchdog = yield* watchPromptInactivity( context, @@ -8882,32 +8937,220 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const compactSession = isCompactionMessage(turnInput.message) ? flavor.compactSession : undefined; - yield* ( - compactSession === undefined - ? sendPromptWhenIdle(context, () => - runtime.prompt({ prompt: promptParts!.prompt }, promptOptions), - ) - : Deferred.succeed(context.promptDispatched, undefined).pipe( - Effect.andThen(compactSession.compact(runtime, requestedSessionId)), - Effect.as({ stopReason: "end_turn" } satisfies EffectAcpSchema.PromptResponse), - ) - ).pipe( - // Settle the wire before the completion callback's permit so a settled-soft - // Stop sees the native return. Capture usage only before finalize: a late - // response must not flip a settled turn. - Effect.tap((result) => - Effect.sync(() => { - if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) { - context.promptUsage = result.usage ?? undefined; - } - }).pipe( - Effect.andThen( - Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid), + const settleDetachedToolStatus = Effect.fnUntraced(function* ( + tool: AcpToolCallState, + nativeState: "completed" | "failed" | "cancelled", + ) { + if (nativeState === "completed") { + yield* emitTool(context, { ...tool, status: "completed" }, "completed"); + } else if (nativeState === "failed") { + yield* emitTool(context, { ...tool, status: "failed" }, "failed"); + } else { + yield* emitTool(context, { ...tool, status: "failed" }, "interrupted"); + } + }); + const runPromptLoop = Effect.gen(function* () { + if (compactSession !== undefined) { + context.promptSentAt = yield* Clock.currentTimeMillis; + yield* Deferred.succeed(context.promptDispatched, undefined); + yield* compactSession.compact(runtime, requestedSessionId); + return { + result: { stopReason: "end_turn" } satisfies EffectAcpSchema.PromptResponse, + hiddenFailure: undefined, + }; + } + const settlement = flavor.foregroundCommandSettlement; + const maxContinuations = settlement?.maxContinuations ?? 2; + const maxWait = settlement?.maxWait ?? "4 minutes"; + const pollInterval = settlement?.pollInterval ?? "1 second"; + const readNativeStatuses = settlement?.makeStatusReader?.(requestedSessionId); + let currentPrompt: ReadonlyArray = promptParts!.prompt; + let isInitialPrompt = true; + let continuations = 0; + + while (true) { + const checkPromptOutcome = + flavor.watchPromptOutcome === undefined + ? undefined + : yield* flavor.watchPromptOutcome(requestedSessionId); + if (context.interrupted || context.finalized) { + return { + result: { stopReason: "cancelled" } satisfies EffectAcpSchema.PromptResponse, + hiddenFailure: undefined, + }; + } + if (!isInitialPrompt) { + context.outgoingPrompt = currentPrompt; + context.consumedPromptMessageId = undefined; + } + context.promptSentAt = yield* Clock.currentTimeMillis; + const result = yield* sendPromptWhenIdle(context, () => + Effect.suspend(() => + context.interrupted || context.finalized + ? Effect.succeed({ + stopReason: "cancelled", + }) + : runtime.prompt( + { prompt: currentPrompt }, + isInitialPrompt ? promptOptions : undefined, + ), ), - ), + ); + isInitialPrompt = false; + if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) { + context.promptUsage = mergeAcpPromptUsage(context.promptUsage, result.usage); + } + const hiddenFailure = + checkPromptOutcome === undefined || + context.interrupted || + result.stopReason === "error" || + result.stopReason === "cancelled" + ? undefined + : yield* checkPromptOutcome(result); + + if ( + settlement === undefined || + context.interrupted || + context.finalized || + hiddenFailure !== undefined || + result.stopReason !== "end_turn" + ) { + return { result, hiddenFailure }; + } + + yield* runtime.drainEvents; + if (context.interrupted || context.finalized) return { result, hiddenFailure }; + + const openTools = () => + [...context.tools.values()].filter(settlement.isOpenForegroundCommand); + const initialOpen = yield* runtimeCallbackPermit.withPermit(Effect.sync(openTools)); + if (initialOpen.length === 0) { + return { result, hiddenFailure }; + } + + const lastKnownNativeStates = new Map< + string, + "running" | "completed" | "failed" | "cancelled" + >(); + const waitLoop = Effect.gen(function* () { + while (!context.interrupted && !context.finalized) { + const pending = yield* runtimeCallbackPermit.withPermit(Effect.sync(openTools)); + if (pending.length === 0) return; + if (readNativeStatuses !== undefined) { + const polled = yield* readNativeStatuses(pending).pipe( + Effect.orElseSucceed(() => undefined), + ); + if (polled !== undefined) { + for (const [toolCallId, state] of polled) { + lastKnownNativeStates.set(toolCallId, state); + } + } + const allSettledNatively = pending.every((tool) => { + const state = lastKnownNativeStates.get(tool.toolCallId); + return state !== undefined && state !== "running"; + }); + if (allSettledNatively) return; + } + const signal = yield* Deferred.make(); + const shouldWait = yield* runtimeCallbackPermit.withPermit( + Effect.sync(() => { + if (context.interrupted || context.finalized || openTools().length === 0) { + return false; + } + context.foregroundCommandWaiters.add(signal); + return true; + }), + ); + if (!shouldWait) return; + if (context.interrupted || context.finalized) { + context.foregroundCommandWaiters.delete(signal); + return; + } + const awaitSignal = + readNativeStatuses !== undefined + ? Deferred.await(signal).pipe( + Effect.timeoutOption(pollInterval), + Effect.asVoid, + ) + : Deferred.await(signal); + yield* awaitSignal.pipe( + Effect.ensuring( + Effect.sync(() => { + context.foregroundCommandWaiters.delete(signal); + }), + ), + ); + } + }); + yield* waitLoop.pipe(Effect.timeoutOption(maxWait), Effect.asVoid); + + if (context.interrupted || context.finalized) return { result, hiddenFailure }; + + const detachedSettled: Array = []; + const stillRunning: Array = []; + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + for (const tool of openTools()) { + const nativeState = lastKnownNativeStates.get(tool.toolCallId); + if (nativeState !== undefined && nativeState !== "running") { + detachedSettled.push(tool); + yield* settleDetachedToolStatus(tool, nativeState); + } else { + stillRunning.push(tool); + } + } + }), + ); + const detachedSettledIds = new Set(detachedSettled.map((tool) => tool.toolCallId)); + const acpSettled = initialOpen.filter((tool) => { + if (detachedSettledIds.has(tool.toolCallId)) return false; + const latest = context.tools.get(tool.toolCallId); + return latest !== undefined && !settlement.isOpenForegroundCommand(latest); + }); + const settled = [...detachedSettled, ...acpSettled]; + + if (continuations >= maxContinuations) { + if (stillRunning.length > 0) { + yield* runtimeCallbackPermit.withPermit( + Effect.forEach( + stillRunning, + (tool) => { + const notice = + lastKnownNativeStates.get(tool.toolCallId) === "running" + ? "\n[T3 stopped waiting after continuation limit; command may still be running natively]" + : "\n[T3 stopped waiting after continuation limit; final command status was not delivered over ACP]"; + return emitTool( + context, + appendToolOutputText({ ...tool, status: "failed" }, notice), + "interrupted", + ); + }, + { discard: true }, + ), + ); + } + return { result, hiddenFailure }; + } + + if (settled.length > 0 || stillRunning.length > 0) { + yield* runtimeCallbackPermit.withPermit(closeTextStreams(context)); + context.lastProgressAt = yield* Clock.currentTimeMillis; + currentPrompt = settlement.buildContinuationPrompt({ settled, stillRunning }); + continuations += 1; + continue; + } + + return { result, hiddenFailure }; + } + }); + yield* runPromptLoop.pipe( + // Settle the wire before the completion callback's permit so a settled-soft + // Stop sees the native return. + Effect.tap(() => + Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid), ), Effect.tap(() => options.testHooks?.afterPromptWireSettled?.() ?? Effect.void), - Effect.flatMap((result) => + Effect.flatMap(({ result, hiddenFailure }) => runRuntimeCallbackAtGeneration( promptGeneration, Effect.gen(function* () { @@ -8947,19 +9190,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); } if (context.finalized || followsAgentWorkState) return; - // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. - const hiddenFailure = - checkPromptOutcome === undefined || - context.interrupted || - result.stopReason === "error" || - result.stopReason === "cancelled" - ? undefined - : yield* checkPromptOutcome(result); - if (hiddenFailure !== undefined) { + const effectiveHiddenFailure = context.interrupted ? undefined : hiddenFailure; + if (effectiveHiddenFailure !== undefined) { yield* Ref.set(runtimeRestartRequired, true); } const failure = - hiddenFailure?.failure ?? + effectiveHiddenFailure?.failure ?? (context.interrupted ? undefined : stopReasonFailure(result.stopReason, result.error)); @@ -8985,9 +9221,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // background tools and subagents keep reporting to this run. yield* finalizeTurn(context, "failed", failure, { childTurnsContinue: hasSurvivingBackgroundWork(context), - ...(hiddenFailure === undefined + ...(effectiveHiddenFailure === undefined ? {} - : { threadDisposition: hiddenFailure.threadDisposition }), + : { threadDisposition: effectiveHiddenFailure.threadDisposition }), }); return; } @@ -9468,7 +9704,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); nativeChildren.clear(); yield* quarantineStoppedRun(); - if (context !== null) context.interrupted = true; + if (context !== null) { + context.interrupted = true; + yield* notifyForegroundCommandWaiters(context); + } yield* cancelPendingRuntimeRequests(); yield* terminalizeCarryoverSubagents(carryover); if (context !== null) { @@ -9645,6 +9884,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const runTransition = Effect.gen(function* () { context.interrupted = true; + yield* notifyForegroundCommandWaiters(context); if (hardRestart || turnInput.requestRuntimeRestart === true) { yield* quarantineStoppedRun(); } From b327ac459c634b39d7f9553659edc4b7500308da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 02:39:13 +0000 Subject: [PATCH 2/4] test(antigravity): trim foreground settlement tests to the regressions they catch Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 193 ------------------ .../provider/acp/AntigravityChildWork.test.ts | 40 ++-- .../src/provider/acp/AntigravityChildWork.ts | 2 +- 3 files changed, 15 insertions(+), 220 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 9a538e1369d71..d21fb4116ff8f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1335,7 +1335,6 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { readonly foregroundCommandSettlement?: Parameters< typeof makeAntigravityAdapterV2 >[0]["foregroundCommandSettlement"]; - readonly onDrainEvents?: () => Effect.Effect; readonly onPrompt: (args: { readonly promptIndex: number; readonly payload: Parameters[0]; @@ -1384,10 +1383,6 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { Effect.sync(() => { sessionUpdate = handler; }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - drainEvents: - input.onDrainEvents === undefined - ? runtime.drainEvents - : runtime.drainEvents.pipe(Effect.tap(input.onDrainEvents)), prompt: (payload, promptOptions) => Effect.gen(function* () { receivedPrompts.push(JSON.stringify(payload.prompt)); @@ -1508,7 +1503,6 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { startedTurnId, receivedPrompts, startTurn, - emitUpdate, }; }); @@ -1585,54 +1579,6 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { }).pipe(Effect.provide(layerSession), Effect.scoped), ); - it.live( - "settles a detached failed foreground command as failed instead of fabricating completed", - () => - Effect.gen(function* () { - const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa2"; - const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ - { idx: 46, callId: "call_fail", status: 7 }, - ]); - const fixture = yield* makeForegroundFixture({ - name: "fg-detached-fail", - profileDirectory, - sessionId, - onPrompt: ({ promptIndex, emit }) => - Effect.gen(function* () { - if (promptIndex === 1) { - yield* emit({ - sessionUpdate: "tool_call", - toolCallId: "call_fail", - title: "Tests", - kind: "execute", - status: "in_progress", - rawInput: { CommandLine: "npm test", IsDaemon: false }, - }); - return { stopReason: "end_turn" as const }; - } - yield* emit({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Tests failed." }, - }); - return { stopReason: "end_turn" as const }; - }), - }); - - yield* fixture.startTurn(); - const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); - assert.equal(fixture.receivedPrompts.length, 2); - const settledTool = events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "call_fail", - ); - assert.equal( - settledTool?.type === "turn_item.updated" ? settledTool.turnItem.status : null, - "failed", - ); - }).pipe(Effect.provide(layerSession), Effect.scoped), - ); - it.live( "aborts waiting on a running native foreground command when Stop is requested without re-prompting", () => @@ -1675,145 +1621,6 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { }).pipe(Effect.provide(layerSession), Effect.scoped), ); - it.live( - "still sends one continuation when ACP completes the command after end_turn while waiting", - () => - Effect.gen(function* () { - const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa4"; - const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ - { idx: 48, callId: "call_late_acp", status: 2 }, - ]); - const enteredWait = yield* Deferred.make(); - let firstPromptDone = false; - const fixture = yield* makeForegroundFixture({ - name: "fg-late-acp", - profileDirectory, - sessionId, - onDrainEvents: () => - firstPromptDone - ? Deferred.succeed(enteredWait, undefined).pipe(Effect.asVoid) - : Effect.void, - onPrompt: ({ promptIndex, emit }) => - Effect.gen(function* () { - if (promptIndex === 1) { - yield* emit({ - sessionUpdate: "tool_call", - toolCallId: "call_late_acp", - title: "Late ACP command", - kind: "execute", - status: "in_progress", - rawInput: { CommandLine: "npm run test", IsDaemon: false }, - }); - firstPromptDone = true; - return { stopReason: "end_turn" as const }; - } - yield* emit({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Late ACP result delivered." }, - }); - return { stopReason: "end_turn" as const }; - }), - }); - - yield* fixture.startTurn(); - yield* Deferred.await(enteredWait); - yield* Effect.sleep("50 millis"); - // Simulate agy 1.5.11 emitting tool_call_update(completed) after end_turn while adapter waits. - yield* fixture.emitUpdate({ - sessionUpdate: "tool_call_update", - toolCallId: "call_late_acp", - status: "completed", - rawOutput: "OK", - }); - - const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); - assert.equal(fixture.receivedPrompts.length, 2); - const assistantText = events - .flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "assistant_message" - ? [event.turnItem.text ?? ""] - : [], - ) - .join(""); - assert.include(assistantText, "Late ACP result delivered."); - }).pipe(Effect.provide(layerSession), Effect.scoped), - ); - - it.live( - "keeps waiting when native status reader throws or returns empty, never mislabels interrupted, and sends still_running continuation on maxWait", - () => - Effect.gen(function* () { - const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa5"; - const fileSystem = yield* FileSystem.FileSystem; - const emptyProfile = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-ag-empty-profile-", - }); - let readerCalls = 0; - const fixture = yield* makeForegroundFixture({ - name: "fg-reader-errors", - profileDirectory: emptyProfile, - sessionId, - foregroundCommandSettlement: { - maxWait: "120 millis", - pollInterval: "25 millis", - maxContinuations: 1, - makeStatusReader: () => () => { - readerCalls += 1; - if (readerCalls === 1) { - return Effect.fail( - new EffectAcpErrors.AcpTransportError({ - detail: "SQLITE_BUSY", - cause: new Error("SQLITE_BUSY"), - }), - ); - } - return Effect.succeed(new Map()); - }, - }, - onPrompt: ({ promptIndex, emit }) => - Effect.gen(function* () { - if (promptIndex === 1) { - yield* emit({ - sessionUpdate: "tool_call", - toolCallId: "call_unknown_native", - title: "Opaque command", - kind: "execute", - status: "in_progress", - rawInput: { CommandLine: "npm run opaque", IsDaemon: false }, - }); - return { stopReason: "end_turn" as const }; - } - yield* emit({ - sessionUpdate: "tool_call_update", - toolCallId: "call_unknown_native", - status: "completed", - rawOutput: "DONE", - }); - yield* emit({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Checked status and finished." }, - }); - return { stopReason: "end_turn" as const }; - }), - }); - - yield* fixture.startTurn(); - const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); - assert.isAtLeast(readerCalls, 2); - assert.equal(fixture.receivedPrompts.length, 2); - assert.include(fixture.receivedPrompts[1] ?? "", "still running"); - const toolStatuses = events - .filter( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "call_unknown_native", - ) - .map((event) => (event.type === "turn_item.updated" ? event.turnItem.status : null)); - assert.notInclude(toolStatuses, "interrupted"); - assert.equal(toolStatuses.at(-1), "completed"); - }).pipe(Effect.provide(layerSession), Effect.scoped), - ); - it.live( "reports both settled and still-running commands on mixed timeout and honestly terminates tracking at maxContinuations cap", () => diff --git a/apps/server/src/provider/acp/AntigravityChildWork.test.ts b/apps/server/src/provider/acp/AntigravityChildWork.test.ts index 72a7e67b4b332..623e57a4bdce3 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.test.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.test.ts @@ -26,6 +26,20 @@ import { transcriptLines, } from "./AntigravityChildWork.testkit.ts"; +const varint = (value: number): number[] => { + const bytes: number[] = []; + let current = value; + while (current >= 0x80) { + bytes.push((current & 0x7f) | 0x80); + current = Math.floor(current / 0x80); + } + return [...bytes, current]; +}; +const field = (num: number, value: string | Uint8Array) => { + const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; + return [...varint(num * 8 + 2), ...varint(bytes.length), ...bytes]; +}; + const read = ( profileDirectory: string, nativeTaskId: string, @@ -351,19 +365,6 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { const conversations = path.join(profile, "antigravity-acp", "conversations"); yield* fs.makeDirectory(conversations, { recursive: true }); const dbPath = path.join(conversations, `${ROOT}.db`); - const varint = (value: number): number[] => { - const bytes: number[] = []; - let current = value; - while (current >= 0x80) { - bytes.push((current & 0x7f) | 0x80); - current = Math.floor(current / 0x80); - } - return [...bytes, current]; - }; - const field = (num: number, value: string | Uint8Array) => { - const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; - return [...varint(num * 8 + 2), ...varint(bytes.length), ...bytes]; - }; const metadataFor = (callId: string) => Uint8Array.from( field(4, Uint8Array.from([...field(1, callId), ...field(2, "run_command")])), @@ -444,19 +445,6 @@ it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => { const conversations = path.join(profile, "antigravity-acp", "conversations"); yield* fs.makeDirectory(conversations, { recursive: true }); const dbPath = path.join(conversations, `${ROOT}.db`); - const varint = (value: number): number[] => { - const bytes: number[] = []; - let current = value; - while (current >= 0x80) { - bytes.push((current & 0x7f) | 0x80); - current = Math.floor(current / 0x80); - } - return [...bytes, current]; - }; - const field = (num: number, value: string | Uint8Array) => { - const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value; - return [...varint(num * 8 + 2), ...varint(bytes.length), ...bytes]; - }; const stepPayloadFor = (callId: string) => Uint8Array.from( field( diff --git a/apps/server/src/provider/acp/AntigravityChildWork.ts b/apps/server/src/provider/acp/AntigravityChildWork.ts index 9b45412222d78..d606c014a0e73 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.ts @@ -26,7 +26,6 @@ const STEP_INVOKE_SUBAGENT = 143; const INVOKE_SPECS = 9; const INVOKE_RESULTS = 10; const INVOKE_SUBAGENT_STEP_TYPE = 127; -// Cortex step types for shell commands (exa.cortex_pb): RUN_COMMAND=21, GENERIC=132. const MAX_COMMAND_SCAN_ROWS = 256; export type AntigravityCommandNativeState = "running" | "completed" | "failed" | "cancelled"; @@ -618,6 +617,7 @@ export function makeAntigravityCommandStatusReader( let scannedMaxIdx = lastScannedMaxIdx; let hitScanCap = false; let sawUnmappedRow = false; + // Shell command step types (exa.cortex_pb): RUN_COMMAND=21, GENERIC=132. const query = hasMetadata ? database.prepare( "SELECT idx, status, CASE WHEN length(metadata) <= ? THEN metadata END AS metadata FROM steps WHERE step_type IN (21, 132) AND step_format = 0 AND idx > ? ORDER BY idx DESC LIMIT ?", From 42166d62cf6198d7cb88ec2e6649baa896937502 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 02:46:58 +0000 Subject: [PATCH 3/4] fix(antigravity): end settlement when the runtime exits and keep late ACP completions at the cap Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 55 ++++++++++++++++++- packages/provider-acp/src/server/adapter.ts | 28 +++++++++- 2 files changed, 77 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index d21fb4116ff8f..6b669b280e097 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1352,6 +1352,7 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; type SessionUpdateHandler = Parameters[0]; let sessionUpdate: SessionUpdateHandler | undefined; + let onTermination: ((error: EffectAcpErrors.AcpError) => Effect.Effect) | undefined; const receivedPrompts: Array = []; const instanceId = ProviderInstanceId.make(`antigravity-${input.name}`); const adapter = yield* makeAntigravityAdapterV2({ @@ -1376,9 +1377,12 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { Effect.map((runtime): RuntimeService => ({ ...runtime, start: () => - runtime - .start() - .pipe(Effect.map((started) => ({ ...started, sessionId: input.sessionId }))), + runtime.start().pipe( + Effect.map((started) => { + onTermination = runtimeInput.onTermination; + return { ...started, sessionId: input.sessionId }; + }), + ), handleSessionUpdate: (handler) => Effect.sync(() => { sessionUpdate = handler; @@ -1503,6 +1507,15 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { startedTurnId, receivedPrompts, startTurn, + terminateRuntime: () => + onTermination === undefined + ? Effect.die(new Error("runtime termination handler was not registered")) + : onTermination( + new EffectAcpErrors.AcpTransportError({ + detail: "agent exited", + cause: new Error("agent exited"), + }), + ), }; }); @@ -1621,6 +1634,42 @@ describe("AntigravityAdapterV2 foreground command settlement", () => { }).pipe(Effect.provide(layerSession), Effect.scoped), ); + it.live("fails the turn instead of waiting when the runtime terminates during settlement", () => + Effect.gen(function* () { + const sessionId = "6063c071-f83e-427d-ab35-6caf4c8dbfa8"; + const { profileDirectory } = yield* createNativeStepsDb(sessionId, [ + { idx: 53, callId: "call_orphan", status: 2 }, + ]); + const firstPromptReturned = yield* Deferred.make(); + const fixture = yield* makeForegroundFixture({ + name: "fg-runtime-exit", + profileDirectory, + sessionId, + onPrompt: ({ emit }) => + Effect.gen(function* () { + yield* emit({ + sessionUpdate: "tool_call", + toolCallId: "call_orphan", + title: "Long job", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "npm run e2e", IsDaemon: false }, + }); + yield* Deferred.succeed(firstPromptReturned, undefined); + return { stopReason: "end_turn" as const }; + }), + }); + + yield* fixture.startTurn(); + yield* Deferred.await(firstPromptReturned); + yield* fixture.terminateRuntime(); + const events = Array.from(yield* Fiber.join(fixture.eventsFiber)); + assert.equal(fixture.receivedPrompts.length, 1); + const terminal = events.find((event) => event.type === "turn.terminal"); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "failed"); + }).pipe(Effect.provide(layerSession), Effect.scoped), + ); + it.live( "reports both settled and still-running commands on mixed timeout and honestly terminates tracking at maxContinuations cap", () => diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 6695c51a0ef05..9c1c308ae2584 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2590,6 +2590,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeGeneration, Effect.gen(function* () { yield* Ref.set(runtimeRestartRequired, true); + const settlingTurn = yield* Ref.get(activeTurn); + if (settlingTurn !== null) yield* notifyForegroundCommandWaiters(settlingTurn); if (!followsAgentWorkState) return; agentWork = { sessionUpdate: "state_update", state: "idle", stopReason: "error" }; for (const child of nativeChildren.values()) { @@ -9053,8 +9055,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return { result, hiddenFailure }; } + // Termination only flags a restart here, so settlement must not prompt a dead runtime. + const terminatedOutcome = { + result, + hiddenFailure: { + failure: makeProviderFailure({ class: "transport_error" }), + threadDisposition: "broken", + } satisfies AcpPromptOutcomeFailure, + }; yield* runtime.drainEvents; if (context.interrupted || context.finalized) return { result, hiddenFailure }; + if (yield* Ref.get(runtimeRestartRequired)) return terminatedOutcome; const openTools = () => [...context.tools.values()].filter(settlement.isOpenForegroundCommand); @@ -9069,6 +9080,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( >(); const waitLoop = Effect.gen(function* () { while (!context.interrupted && !context.finalized) { + if (yield* Ref.get(runtimeRestartRequired)) return; const pending = yield* runtimeCallbackPermit.withPermit(Effect.sync(openTools)); if (pending.length === 0) return; if (readNativeStatuses !== undefined) { @@ -9088,8 +9100,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } const signal = yield* Deferred.make(); const shouldWait = yield* runtimeCallbackPermit.withPermit( - Effect.sync(() => { - if (context.interrupted || context.finalized || openTools().length === 0) { + Effect.gen(function* () { + if ( + context.interrupted || + context.finalized || + openTools().length === 0 || + (yield* Ref.get(runtimeRestartRequired)) + ) { return false; } context.foregroundCommandWaiters.add(signal); @@ -9120,6 +9137,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* waitLoop.pipe(Effect.timeoutOption(maxWait), Effect.asVoid); if (context.interrupted || context.finalized) return { result, hiddenFailure }; + if (yield* Ref.get(runtimeRestartRequired)) return terminatedOutcome; const detachedSettled: Array = []; const stillRunning: Array = []; @@ -9150,13 +9168,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.forEach( stillRunning, (tool) => { + const latest = context.tools.get(tool.toolCallId); + if (latest === undefined || !settlement.isOpenForegroundCommand(latest)) { + return Effect.void; + } const notice = lastKnownNativeStates.get(tool.toolCallId) === "running" ? "\n[T3 stopped waiting after continuation limit; command may still be running natively]" : "\n[T3 stopped waiting after continuation limit; final command status was not delivered over ACP]"; return emitTool( context, - appendToolOutputText({ ...tool, status: "failed" }, notice), + appendToolOutputText({ ...latest, status: "failed" }, notice), "interrupted", ); }, From 6aa7278c9ebf4f8b2743718b0c957b51049135d4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 02:56:20 +0000 Subject: [PATCH 4/4] fix(acp): keep a broken outcome when Stop lands during the outcome check Co-Authored-By: Claude Opus 5.5 --- packages/provider-acp/src/server/adapter.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 9c1c308ae2584..0aa679a61fcc1 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9247,12 +9247,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); } if (context.finalized || followsAgentWorkState) return; - const effectiveHiddenFailure = context.interrupted ? undefined : hiddenFailure; - if (effectiveHiddenFailure !== undefined) { + if (hiddenFailure !== undefined) { yield* Ref.set(runtimeRestartRequired, true); } const failure = - effectiveHiddenFailure?.failure ?? + hiddenFailure?.failure ?? (context.interrupted ? undefined : stopReasonFailure(result.stopReason, result.error)); @@ -9278,9 +9277,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // background tools and subagents keep reporting to this run. yield* finalizeTurn(context, "failed", failure, { childTurnsContinue: hasSurvivingBackgroundWork(context), - ...(effectiveHiddenFailure === undefined + ...(hiddenFailure === undefined ? {} - : { threadDisposition: effectiveHiddenFailure.threadDisposition }), + : { threadDisposition: hiddenFailure.threadDisposition }), }); return; }