From 974423387130fa60502e8b53c47475744582a2d2 Mon Sep 17 00:00:00 2001 From: Taylor Dolezal <117500+onlydole@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:44:34 -0800 Subject: [PATCH 1/7] fix(server): recycle Antigravity ADC runtimes before 60m token expiry and fail silent empty turns In Agent Platform ADC mode, agy acp fails Google OAuth token refresh with "context canceled" once a process reaches 60 minutes. Every subsequent session/prompt writes only USER_INPUT (step_type 14), emits no model output or usage, and resolves cleanly with stopReason "end_turn", leaving T3 Code marking turns completed while keeping the dead process alive. Fix both halves of the failure (fixes #40386): - Proactively recycle Agent Platform ADC runtimes between turns after 45 minutes (when no background work or wake traffic is pending) and resume the session directly via session/resume. - Detect silent USER_INPUT-only end_turn completions with no output or usage in AntigravityTurnOutcome so T3 Code fails the turn with a retryable provider error and restarts the runtime before the next send instead of silently dropping messages. Done by Gemini 4 Neon (High) in Antigravity (via T3 Code). --- .../Adapters/AcpAdapterV2.test.ts | 119 ++++++++++ .../Adapters/AntigravityAdapterV2.test.ts | 203 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 6 + .../Drivers/AntigravityDriver.test.ts | 23 +- .../src/provider/Drivers/AntigravityDriver.ts | 13 ++ .../acp/AntigravityTurnOutcome.test.ts | 49 ++++- .../provider/acp/AntigravityTurnOutcome.ts | 40 +++- packages/provider-acp/src/server/adapter.ts | 134 ++++++++++-- 8 files changed, 559 insertions(+), 28 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 149ffbca030d0..fafb082ef9201 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -13962,6 +13962,125 @@ describe("AcpAdapterV2", () => { assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); }).pipe(Effect.provide(layerTest)), ); + + it.effect( + "recycles a runtime before a new turn once maxRuntimeAgeBeforeTurn elapses and reports output presence to watchPromptOutcome", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-max-runtime-age"); + const threadId = ThreadId.make("thread-acp-max-runtime-age"); + const promptRuntimes: Array = []; + const resumeIds: Array = []; + const receivedOutputs: Array = []; + let emitReplyOnNextPrompt = false; + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => { + let onUpdate: Parameters[0] | undefined; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + onUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (emitReplyOnNextPrompt && onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "ok" }, + }, + }); + } + return { stopReason: "end_turn" as const }; + }), + }; + }, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + watchPromptOutcome: () => + Effect.succeed((_result, options) => + Effect.sync(() => { + receivedOutputs.push(options?.receivedOutput); + return undefined; + }), + ), + makeRuntime: (runtimeInput) => + Effect.sync(() => { + resumeIds.push(runtimeInput.resumeSessionId); + }).pipe(Effect.andThen(baseMakeRuntime(runtimeInput))), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-max-runtime-age"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number, emitReply: boolean) => + Effect.gen(function* () { + emitReplyOnNextPrompt = emitReply; + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + // Turn 1: silent prompt on runtime 1. + yield* runTurn(1, false); + // Turn 2 at +30m (< 45m): reuses runtime 1 and emits assistant output. + yield* TestClock.adjust("30 minutes"); + yield* runTurn(2, true); + // Turn 3 at +50m (>= 45m): proactively recycles to runtime 2 with resumeSessionId. + yield* TestClock.adjust("20 minutes"); + yield* runTurn(3, true); + // Turn 4 at +10m after recycle (< 45m on runtime 2): stays on runtime 2. + yield* TestClock.adjust("10 minutes"); + yield* runTurn(4, false); + + assert.deepEqual(promptRuntimes, [1, 1, 2, 2]); + assert.deepEqual(resumeIds, [undefined, providerThread.nativeThreadRef?.nativeId]); + assert.deepEqual(receivedOutputs, [false, true, true, false]); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 71d8fcfa576ae..68e1f54a821bb 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -5537,3 +5537,206 @@ describe("AntigravityAdapterV2 failed edits", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 silent ADC drop recovery", () => { + it.effect( + "fails a silent USER_INPUT-only turn and restarts the runtime on the next send, and recycles after maxRuntimeAgeBeforeTurn", + () => + Effect.gen(function* () { + 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 profileDirectory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-adc-drop-", + }); + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fileSystem.makeDirectory(conversations, { recursive: true }); + const appendStep = (type: number, status: number, payload: string) => { + const database = new NodeSqlite.DatabaseSync( + path.join(conversations, "mock-session-1.db"), + ); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, step_payload BLOB)", + ); + database + .prepare("INSERT INTO steps (step_type, status, step_payload) VALUES (?, ?, ?)") + .run(type, status, Buffer.from(payload)); + } finally { + database.close(); + } + }; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let runtimeOrdinal = 0; + const promptRuntimes: Array = []; + const resumeIds: Array = []; + const instanceId = ProviderInstanceId.make("antigravity-adc-drop-test"); + const threadId = ThreadId.make("thread-antigravity-adc-drop"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + profileDirectory, + maxRuntimeAgeBeforeTurn: "45 minutes", + makeRuntime: (input) => { + const currentRuntime = ++runtimeOrdinal; + resumeIds.push(input.resumeSessionId); + let sessionUpdate: Parameters[0] | undefined; + return makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptRuntimes.push(currentRuntime); + appendStep(14, 3, `Prompt on runtime ${currentRuntime}`); + // Simulate agy's 60m ADC OAuth failure on runtime 1: only USER_INPUT is + // recorded and session/prompt resolves cleanly with no output or usage. + if (currentRuntime === 1) { + return { stopReason: "end_turn" as const }; + } + yield* sessionUpdate!( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: `Reply from runtime ${currentRuntime}` }, + }, + }), + ); + appendStep(15, 3, `Reply from runtime ${currentRuntime}`); + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 }, + }; + }), + })), + ); + }, + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-adc-drop"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-adc-drop"), + title: "Antigravity ADC drop", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: runtimePolicy.runtimeMode, + interactionMode: runtimePolicy.interactionMode, + branch: null, + worktreePath: null, + 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-adc-drop-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-adc-drop-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-adc-drop-${ordinal}`), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`msg-antigravity-adc-drop-${ordinal}`), + text: `Hello ${ordinal}`, + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + return events.at(-1); + }); + + // Turn 1 hits the silent drop on runtime 1 and fails with a retryable provider error. + const firstTerminal = yield* runTurn(1); + assert.equal(firstTerminal?.type, "turn.terminal"); + assert.equal( + firstTerminal?.type === "turn.terminal" ? firstTerminal.status : null, + "failed", + ); + assert.equal( + firstTerminal?.type === "turn.terminal" && firstTerminal.status === "failed" + ? firstTerminal.failure.retryable + : null, + true, + ); + + // Turn 2 automatically restarts onto runtime 2 (resuming mock-session-1) and succeeds. + const secondTerminal = yield* runTurn(2); + assert.equal( + secondTerminal?.type === "turn.terminal" ? secondTerminal.status : null, + "completed", + ); + + // Turn 3 after 45 minutes proactively recycles onto runtime 3 (resuming mock-session-1). + yield* TestClock.adjust("45 minutes"); + const thirdTerminal = yield* runTurn(3); + assert.equal( + thirdTerminal?.type === "turn.terminal" ? thirdTerminal.status : null, + "completed", + ); + + assert.deepEqual(promptRuntimes, [1, 2, 3]); + assert.deepEqual(resumeIds, [undefined, "mock-session-1", "mock-session-1"]); + }).pipe(Effect.provide(layerSession)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 02323f7741a1e..3d71acb5110db 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -9,6 +9,7 @@ import type { SelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; +import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -116,6 +117,8 @@ 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; + /** Recycles long-lived ACP runtimes before a new turn (used for ADC's 60m token cliff). */ + readonly maxRuntimeAgeBeforeTurn?: Duration.Input; } /** @@ -355,6 +358,9 @@ export function makeAntigravityAcpAdapterFlavor( checksVersionAtHandshake: true, // Antigravity can leave a prompt open without updates; long tools and approvals pause this. promptInactivityTimeout: "15 minutes", + ...(options.maxRuntimeAgeBeforeTurn === undefined + ? {} + : { maxRuntimeAgeBeforeTurn: options.maxRuntimeAgeBeforeTurn }), reportsPerTurnPromptUsage: true, geminiPromptUsage: true, ...(profileDirectory === undefined diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 86f019c0090ce..2616edd22f8ec 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -49,7 +49,7 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter" import { knownProviderFailureMessage } from "@t3tools/provider-core/server/failure"; import { resolveProviderCompatibility } from "../providerCompatibility.ts"; import { writeProviderStatusCache } from "../providerStatusCache.ts"; -import { AntigravityDriver } from "./AntigravityDriver.ts"; +import { AntigravityDriver, antigravityMaxRuntimeAgeBeforeTurn } from "./AntigravityDriver.ts"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as ProviderHostLive from "../ProviderHostLive.ts"; import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; @@ -1129,4 +1129,25 @@ it.layer(layerTest)("AntigravityDriver", (it) => { yield* h.assertClosed; }), ); + + it("enables 45-minute runtime recycling only for Agent Platform ADC auth", () => { + expect(antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "" })).toBe( + "45 minutes", + ); + expect( + antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: " " }), + ).toBe("45 minutes"); + expect( + antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "AIza-test" }), + ).toBeUndefined(); + expect( + antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "oauth-personal", apiKey: "" }), + ).toBeUndefined(); + expect( + antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "oauth-business", apiKey: "" }), + ).toBeUndefined(); + expect( + antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "gemini-api-key", apiKey: "AIza-test" }), + ).toBeUndefined(); + }); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 8527678f0d99c..db346698a445f 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -98,6 +98,17 @@ import { readProviderStatusCache, resolveProviderStatusCachePath } from "../prov import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts"; const DRIVER = ProviderDriverKind.make("antigravity"); +// agy acp in Agent Platform ADC mode fails OAuth refresh with context canceled at 60 minutes; +// recycling between turns at 45 minutes keeps sessions on a fresh token without hitting the cliff. +const ANTIGRAVITY_ADC_MAX_RUNTIME_AGE = "45 minutes" as const; + +export function antigravityMaxRuntimeAgeBeforeTurn( + auth: Pick, +): typeof ANTIGRAVITY_ADC_MAX_RUNTIME_AGE | undefined { + return auth.authMethod === "agent-platform" && !auth.apiKey.trim() + ? ANTIGRAVITY_ADC_MAX_RUNTIME_AGE + : undefined; +} const decodeSettings = Schema.decodeSync(AntigravitySettings); const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); @@ -820,6 +831,7 @@ export const AntigravityDriver: ProviderDriver< ), ); const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel)); + const maxRuntimeAgeBeforeTurn = antigravityMaxRuntimeAgeBeforeTurn(auth); const orchestrationAdapter = yield* makeAntigravityAdapterV2({ instanceId, selfInvocation, @@ -832,6 +844,7 @@ export const AntigravityDriver: ProviderDriver< ), ), profileDirectory, + ...(maxRuntimeAgeBeforeTurn === undefined ? {} : { maxRuntimeAgeBeforeTurn }), onSessionStarted: (started, cwd, session) => provider .onSessionStarted(started, cwd, session) diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index b65c4ff4ec930..be75b7cbbd38b 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -127,7 +127,7 @@ describe("watchAntigravityPromptOutcome", () => { const turn = ( steps: ReadonlyArray, result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" }, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) => Effect.gen(function* () { const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId); @@ -392,6 +392,53 @@ describe("watchAntigravityPromptOutcome", () => { retryable: true, }), ); + // After 60 minutes in Agent Platform ADC mode, agy's OAuth refresh fails with + // context canceled and resolves session/prompt with only USER_INPUT and no output. + assert.deepEqual( + yield* turn([[USER_INPUT, input]], { stopReason: "end_turn" }, { receivedOutput: false }), + reusable({ + class: "provider_error", + message: + "Antigravity ended the turn without contacting the model. T3 Code will restart the agent; send your message again to continue.", + code: null, + retryable: true, + }), + ); + // Local replies, reported usage, inactivity-retired prompts, and steers after a + // model reply must not trip the silent-drop check. + assert.isUndefined( + yield* turn([[USER_INPUT, input]], { stopReason: "end_turn" }, { receivedOutput: true }), + ); + assert.isUndefined( + yield* turn( + [[USER_INPUT, input]], + { + stopReason: "end_turn", + usage: { inputTokens: 10, outputTokens: 2, totalTokens: 12 }, + }, + { receivedOutput: false }, + ), + ); + assert.isUndefined( + yield* turn( + [[USER_INPUT, input]], + { stopReason: "end_turn" }, + { retired: true, receivedOutput: false }, + ), + ); + assert.isUndefined( + yield* steered( + [ + [USER_INPUT, input], + [PLANNER_RESPONSE, reply], + ], + [[USER_INPUT, input]], + ), + ); + assert.equal( + (yield* steered([[USER_INPUT, input]], [[USER_INPUT, input]]))?.failure.retryable, + true, + ); }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 483f0dda864a1..c19a0e0731ff4 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -13,6 +13,8 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; +// CORTEX_STEP_TYPE_USER_INPUT: the prompt was recorded before model execution. +const USER_INPUT_STEP_TYPE = 14; // CORTEX_STEP_TYPE_ERROR_MESSAGE in the native trajectory. const ERROR_STEP_TYPE = 17; // CORTEX_STEP_TYPE_PLANNER_RESPONSE: the model answered within this turn. @@ -206,9 +208,10 @@ function verificationErrorInfo(text: string) { } function turnFailure( - stopReason: EffectAcpSchema.StopReason, + result: EffectAcpSchema.PromptResponse, step: LastStep | undefined, now: DateTime.Utc | undefined, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ): | { readonly failure: OrchestrationV2ProviderFailure; @@ -216,16 +219,37 @@ function turnFailure( readonly resumeWith?: string; } | undefined { + const { stopReason } = result; const errorText = step?.type === ERROR_STEP_TYPE ? new TextDecoder().decode(step.payload ?? new Uint8Array()) : undefined; + const reusable = (failure: OrchestrationV2ProviderFailure) => + ({ failure, threadDisposition: "reusable" }) as const; + // After ~60m in Agent Platform ADC mode, agy's OAuth refresh fails with context canceled + // and session/prompt resolves cleanly with only USER_INPUT recorded and no model output. + if ( + errorText === undefined && + options?.retired !== true && + options?.receivedOutput !== true && + stopReason === "end_turn" && + result.usage === undefined && + step?.type === USER_INPUT_STEP_TYPE && + !step.reachedModel + ) { + return reusable( + makeProviderFailure({ + class: "provider_error", + message: + "Antigravity ended the turn without contacting the model. T3 Code will restart the agent; send your message again to continue.", + retryable: true, + }), + ); + } // The agent maps only the SDK's QUOTA_EXHAUSTED stop reason to `refusal`. if (errorText === undefined && stopReason !== "refusal") return undefined; const text = errorText ?? ""; const apiError = API_ERROR.exec(text) ?? statusError(text); - const reusable = (failure: OrchestrationV2ProviderFailure) => - ({ failure, threadDisposition: "reusable" }) as const; if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) { return reusable( makeProviderFailure({ @@ -289,7 +313,7 @@ const conversationSegments = ["antigravity-acp", "conversations"]; type PromptOutcomeCheck = ( result: EffectAcpSchema.PromptResponse, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) => Effect.Effect | "completed">; interface PromptBaseline { @@ -313,8 +337,8 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w sessionId: string, turnStart?: PromptOutcomeCheck, ) { - const typedOnly: PromptOutcomeCheck = (result) => - DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now))); + const typedOnly: PromptOutcomeCheck = (result, options) => + DateTime.now.pipe(Effect.map((now) => turnFailure(result, undefined, now, options))); if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly; const segments = [...conversationSegments, `${sessionId}.db`]; const before = yield* Effect.tryPromise({ @@ -366,7 +390,7 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w : startIndex; const check: PromptOutcomeCheck = Effect.fn("AntigravityTurnOutcome.check")(function* ( result: EffectAcpSchema.PromptResponse, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) { // The same file as before the prompt, or one this prompt created, still unlinked. const after = yield* Effect.tryPromise({ @@ -388,7 +412,7 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w // A retired prompt's check runs long after the error, so a relative delay has no anchor. const retired = options?.retired === true; const now = retired ? undefined : yield* DateTime.now; - const failure = turnFailure(result.stopReason, step, now); + const failure = turnFailure(result, step, now, options); // The reply finished but session/prompt never answered. const finished = retired && diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 11d4df9e46aa1..504dd8d476fc0 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -449,7 +449,7 @@ interface AcpPromptOutcomeFailure { type AcpPromptOutcomeCheck = ( result: EffectAcpSchema.PromptResponse, - options?: { readonly retired?: boolean }, + options?: { readonly retired?: boolean; readonly receivedOutput?: boolean }, ) => Effect.Effect; export interface AcpAdapterV2Flavor { @@ -793,6 +793,11 @@ export interface AcpAdapterV2Flavor { * agent request, tool or subagent is open, and replaces the agent before the next turn. */ readonly promptInactivityTimeout?: Duration.Input; + /** + * Recycles the live ACP runtime before starting a new turn once its uptime reaches this age, + * provided the agent can resume sessions and no background work or wake traffic is pending. + */ + readonly maxRuntimeAgeBeforeTurn?: Duration.Input; /** Grok can retain task_already_running until process exit. */ readonly restartRuntimeAfterInterrupt?: boolean; /** Prompt failures after which the agent process keeps failing until replaced. */ @@ -2030,6 +2035,8 @@ interface ActiveAcpTurn { promptSequence: number; /** The turn already resent a prompt after a resumable outcome failure. */ outcomeResumed: boolean; + /** Whether the current prompt received any model/tool/plan output update. */ + promptReceivedOutput: boolean; /** Clock millis just before `session/prompt` was handed to the runtime. */ promptSentAt: number | null; /** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */ @@ -2992,6 +2999,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.compactSession !== undefined || flavor.compactViaAdvertisedCommand === true; const runtimeRestartRequired = yield* Ref.make(false); + const runtimeStartedAt = yield* Ref.make(null); const runtimeTeardownState = yield* Ref.make({ _tag: "Idle" }); const runtimeCallbackGeneration = yield* Ref.make(0); const runtimeCallbackGenerationCounter = yield* Ref.make(0); @@ -3465,6 +3473,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.promptInactivityTimeout === undefined ? undefined : Duration.toMillis(flavor.promptInactivityTimeout); + const maxRuntimeAgeBeforeTurnMillis = + flavor.maxRuntimeAgeBeforeTurn === undefined + ? undefined + : Duration.toMillis(flavor.maxRuntimeAgeBeforeTurn); // Each runtime owns its unanswered agent requests, so a dead process's leftovers // and late callbacks never reach its replacement. let openAgentRequests = new Set(); @@ -7562,14 +7574,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return; } - if ( - update.sessionUpdate !== "tool_call_update" && - update.sessionUpdate !== "plan" && - update.sessionUpdate !== "plan_update" && - update.sessionUpdate !== "plan_removed" && - acpRootSessionUpdateIngestsOutput(notification) - ) { - yield* emitProviderRetry(context, "completed"); + if (acpRootSessionUpdateIngestsOutput(notification)) { + context.promptReceivedOutput = true; + if ( + update.sessionUpdate !== "tool_call_update" && + update.sessionUpdate !== "plan" && + update.sessionUpdate !== "plan_update" && + update.sessionUpdate !== "plan_removed" + ) { + yield* emitProviderRetry(context, "completed"); + } } if ( context.outgoingPrompt !== undefined && @@ -9277,6 +9291,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.provideService(AgentScope, agentScope), Effect.provideService(AgentScopeThreadId, threadId ?? undefined), ); + yield* Ref.set(runtimeStartedAt, yield* Clock.currentTimeMillis); }); const startAcpRuntime = Effect.fnUntraced(function* ( @@ -9413,6 +9428,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeScope = replacementScope; runtimeMcpBridge = replacementMcpBridge; openAgentRequests = replacementAgentRequests; + yield* Ref.set(runtimeStartedAt, yield* Clock.currentTimeMillis); yield* Ref.set(runtimeCallbackGeneration, replacementGeneration); prepareTerminalEnvironment( yield* readMcpContext(threadId), @@ -10752,9 +10768,42 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restartRuntimeAfterTeardownIfRequired = Effect.fnUntraced(function* ( threadId: ThreadId | null, + resumeSessionId?: string, ) { const restartRequired = yield* Ref.get(runtimeRestartRequired); - if (!restartRequired) return false; + if (!restartRequired) return undefined; + if (resumeSessionId !== undefined && (canLoadSession || canResumeSession)) { + const initialFailure = yield* Ref.modify(initialSessionActivationFailure, (failure) => + failure?.sessionId === resumeSessionId ? [failure.error, null] : [undefined, failure], + ); + if (initialFailure !== undefined) { + return yield* initialFailure; + } + const mcpContext = yield* readMcpContext(threadId); + prepareTerminalEnvironment(mcpContext, resumeSessionId); + yield* reportStartupPhase("launch"); + yield* reportStartupPhase("resume"); + const activated = yield* startAcpRuntime(threadId, resumeSessionId).pipe( + Effect.onError(() => reportStartupPhase(undefined)), + ); + yield* Ref.set(runtimeRestartRequired, false); + yield* reportStartupPhase(undefined); + yield* Ref.set(activeSessionId, activated.sessionId); + yield* Ref.set(loadingSessionId, null); + yield* setActiveSessionSetup(activated); + rememberTerminalEnvironment(activated.sessionId, yield* readMcpContext(threadId)); + yield* resetPublishedCatalogKey; + yield* Ref.set(activeSelection, null); + yield* Ref.set(activeInteractionMode, null); + // A failed prompt may have been dropped, so the fresh runtime sends T3's notes again. + yield* Ref.set(promptInstructionStates, new Map()); + yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); + yield* Ref.set(compactionMarkers, new Map()); + yield* Ref.set(completedCompactionIds, new Set()); + yield* Ref.set(snapshot, emptySnapshotState()); + return { restarted: true as const, activated }; + } yield* reportStartupPhase("launch"); yield* restartAcpRuntime(threadId).pipe( Effect.onError(() => reportStartupPhase(undefined)), @@ -10772,7 +10821,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(snapshot, emptySnapshotState()); - return true; + return { restarted: true as const, activated: undefined }; }); const commitAcpAppContext = Effect.fnUntraced(function* (input: { @@ -10918,7 +10967,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( result.stopReason === "error" || result.stopReason === "cancelled" ? undefined - : yield* settle.checkPromptOutcome(result); + : yield* settle.checkPromptOutcome(result, { + receivedOutput: context.promptReceivedOutput, + }); const hiddenFailure = outcome === "completed" ? undefined : outcome; const resumeWith = hiddenFailure?.resumeWith; if ( @@ -11099,12 +11150,56 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // load/resume can invoke client methods; install the incoming policy before activation. latestRuntimePolicy = turnInput.runtimePolicy; const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); - const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( + const shouldRecycleStaleRuntime = + maxRuntimeAgeBeforeTurnMillis !== undefined && + (canLoadSession || canResumeSession) && + !(yield* Ref.get(runtimeRestartRequired)) && + !acpIsProviderContinuationMessage(turnInput.message) + ? yield* continuationPermit.withPermit( + Effect.gen(function* () { + const startedAtMillis = yield* Ref.get(runtimeStartedAt); + if ( + startedAtMillis === null || + (yield* Clock.currentTimeMillis) - startedAtMillis < + maxRuntimeAgeBeforeTurnMillis + ) { + return false; + } + const hasIdleOutlivingSubagents = [...idleOutlivingSubagents.values()].some( + (entries) => entries.size > 0, + ); + return ( + !(yield* Ref.get(continuationRequested)) && + (yield* Ref.get(wakeBuffer)).length === 0 && + (yield* Ref.get(runningBackgroundTaskIds)).size === 0 && + (yield* Ref.get(detachedBackgroundCommands)).size === 0 && + (yield* Ref.get(detachedUnawaitedTools)).size === 0 && + (yield* Ref.get(carryoverSubagents)) === null && + !hasIdleOutlivingSubagents + ); + }), + ) + : false; + if (shouldRecycleStaleRuntime) { + yield* Ref.set(runtimeRestartRequired, true); + } + const restartResult = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, + requestedSessionId, ); + const restarted = restartResult !== undefined; const needsSessionActivation = - (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; - if (needsSessionActivation) { + restartResult?.activated === undefined && + ((yield* Ref.get(activeSessionId)) !== requestedSessionId || restarted); + if (restartResult?.activated !== undefined) { + yield* configureSession( + restartResult.activated, + turnInput.modelSelection, + turnInput.runtimePolicy, + ); + yield* Ref.set(activeSelection, turnInput.modelSelection); + yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode); + } else if (needsSessionActivation) { const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(loadingSessionId, null); @@ -11284,6 +11379,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( foregroundIdle: yield* Deferred.make(), promptSequence: 0, outcomeResumed: false, + promptReceivedOutput: false, promptSentAt: null, promptStarted, promptUsage: undefined, @@ -11624,6 +11720,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context.foregroundIdle = yield* Deferred.make(); context.promptSettled = false; context.promptSettledStatus = null; + context.promptReceivedOutput = false; context.backgroundFinalizeGeneration += 1; context.promptSentAt = yield* Clock.currentTimeMillis; const previousPromptSettled = yield* Deferred.isDone(context.promptWireSettled); @@ -11955,9 +12052,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restorePreviousItemIdentity = Effect.sync(() => { itemIdentityVersion = previousItemIdentityVersion; }); - const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( - threadInput.providerThread.appThreadId, - ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); + const restartAfterInterrupt = + (yield* restartRuntimeAfterTeardownIfRequired( + threadInput.providerThread.appThreadId, + ).pipe(Effect.tapError(() => restorePreviousItemIdentity))) !== undefined; if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) { yield* Ref.set(snapshot, emptySnapshotState()); const activated = yield* activateSession( From 34d5b62c2d9a0dc57f650f2d91500aca3fbae4fe Mon Sep 17 00:00:00 2001 From: Taylor Dolezal <117500+onlydole@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:46:26 -0800 Subject: [PATCH 2/7] fix(acp): refine runtime recycle guards and restart snapshot handling Restrict direct-resume restarts to canResumeSession runtimes so load-only agents (e.g. Copilot) keep their session/new -> session/load recovery flow, reset snapshot before startAcpRuntime (and preserve same-session non-load snapshots), ignore ended entries in detached background/unawaited tool maps when checking recycle eligibility, fence retiring runtime callbacks under runtimeCallbackPermit + continuationPermit before teardown, and treat usage: null as absent in AntigravityTurnOutcome. Done by Gemini 4 Neon (High) in Antigravity (via T3 Code). --- .../Adapters/AcpAdapterV2.test.ts | 154 ++++++++++++++++++ .../acp/AntigravityTurnOutcome.test.ts | 8 + .../provider/acp/AntigravityTurnOutcome.ts | 2 +- packages/provider-acp/src/server/adapter.ts | 86 ++++++---- 4 files changed, 219 insertions(+), 31 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index fafb082ef9201..7f86b6c5430ba 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -14072,6 +14072,12 @@ describe("AcpAdapterV2", () => { // Turn 3 at +50m (>= 45m): proactively recycles to runtime 2 with resumeSessionId. yield* TestClock.adjust("20 minutes"); yield* runTurn(3, true); + // Restarting via loadSession keeps the replayed snapshot history intact. + const snapshotAfterRecycle = yield* session.readThreadSnapshot({ providerThread }); + assert.isTrue( + snapshotAfterRecycle.messages.some((message) => message.text.includes("replay")), + "expected replayed snapshot message to survive runtime recycle", + ); // Turn 4 at +10m after recycle (< 45m on runtime 2): stays on runtime 2. yield* TestClock.adjust("10 minutes"); yield* runTurn(4, false); @@ -14081,6 +14087,154 @@ describe("AcpAdapterV2", () => { assert.deepEqual(receivedOutputs, [false, true, true, false]); }).pipe(Effect.provide(layerTest)), ); + + it.effect( + "gates maxRuntimeAgeBeforeTurn recycling on nonterminal detached tools, not ended history", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-detached-recycle"); + const threadId = ThreadId.make("thread-acp-detached-recycle"); + const promptRuntimes: Array = []; + const promptSettledWithBackgroundWork = yield* Queue.unbounded(); + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => { + let onUpdate: Parameters[0] | undefined; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + onUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (_payload, promptOptions) => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + if (promptRuntimes.length === 1 && onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "detached-tool-1", + title: "Background tool", + kind: "execute", + status: "in_progress", + }, + }); + } else if (promptRuntimes.length === 2 && onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "detached-tool-1", + status: "completed", + }, + }); + } + return { stopReason: "end_turn" as const }; + }), + }; + }, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + deferFinalizeForBackgroundWork: true, + toolOutlivesPrompt: () => true, + makeRuntime: baseMakeRuntime, + }, + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Queue.offer(promptSettledWithBackgroundWork, undefined), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-detached-recycle"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* session.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const until = (done: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) => + Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (done(event)) return seen; + } + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const startTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + }); + const awaitTerminal = () => + Effect.gen(function* () { + const seen = yield* until((event) => event.type === "turn.terminal"); + const terminal = seen.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + // Turn 1 leaves a running outliving tool detached via awaitBackgroundTasks(awaited=false). + yield* startTurn(1); + yield* Queue.take(promptSettledWithBackgroundWork); + const released = yield* session.awaitBackgroundTasks!({ + providerThread, + taskIds: ["mock-session-1/task-1"], + awaited: false, + }); + assert.deepEqual(released.matched, ["mock-session-1/task-1"]); + yield* TestClock.adjust("5 seconds"); + yield* awaitTerminal(); + + // At +50m, the still-running detached tool blocks proactive recycling on turn 2. + // Turn 2's prompt then emits its completion, leaving the ended entry in + // detachedUnawaitedTools for late corrections. + yield* TestClock.adjust("50 minutes"); + yield* startTurn(2); + yield* awaitTerminal(); + assert.deepEqual(promptRuntimes, [1, 1]); + + // On turn 3, the ended detached history must no longer block recycling. + yield* startTurn(3); + yield* awaitTerminal(); + assert.deepEqual(promptRuntimes, [1, 1, 2]); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index 4622c2380f3ef..58ef8483227fd 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -463,6 +463,14 @@ describe("watchAntigravityPromptOutcome", () => { retryable: true, }), ); + assert.equal( + (yield* turn( + [[USER_INPUT, input]], + { stopReason: "end_turn", usage: null }, + { receivedOutput: false }, + ))?.failure.retryable, + true, + ); // Local replies, reported usage, inactivity-retired prompts, and steers after a // model reply must not trip the silent-drop check. assert.isUndefined( diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 9f186495a7e00..fef991187b7c8 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -236,7 +236,7 @@ function turnFailure( options?.retired !== true && options?.receivedOutput !== true && stopReason === "end_turn" && - result.usage === undefined && + result.usage == null && step?.type === USER_INPUT_STEP_TYPE && !step.reachedModel ) { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 504dd8d476fc0..a47c33dcd296e 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10772,7 +10772,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { const restartRequired = yield* Ref.get(runtimeRestartRequired); if (!restartRequired) return undefined; - if (resumeSessionId !== undefined && (canLoadSession || canResumeSession)) { + if (resumeSessionId !== undefined && canResumeSession) { const initialFailure = yield* Ref.modify(initialSessionActivationFailure, (failure) => failure?.sessionId === resumeSessionId ? [failure.error, null] : [undefined, failure], ); @@ -10781,6 +10781,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } const mcpContext = yield* readMcpContext(threadId); prepareTerminalEnvironment(mcpContext, resumeSessionId); + // Clear before start when load will replay or switching sessions; keep cached + // history on same-session resume when no replay will arrive. + if ((yield* Ref.get(activeSessionId)) !== resumeSessionId || canLoadSession) { + yield* Ref.set(snapshot, emptySnapshotState()); + } yield* reportStartupPhase("launch"); yield* reportStartupPhase("resume"); const activated = yield* startAcpRuntime(threadId, resumeSessionId).pipe( @@ -10801,7 +10806,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(deliveredAppContext, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); - yield* Ref.set(snapshot, emptySnapshotState()); return { restarted: true as const, activated }; } yield* reportStartupPhase("launch"); @@ -11150,38 +11154,60 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // load/resume can invoke client methods; install the incoming policy before activation. latestRuntimePolicy = turnInput.runtimePolicy; const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); - const shouldRecycleStaleRuntime = + if ( maxRuntimeAgeBeforeTurnMillis !== undefined && (canLoadSession || canResumeSession) && !(yield* Ref.get(runtimeRestartRequired)) && !acpIsProviderContinuationMessage(turnInput.message) - ? yield* continuationPermit.withPermit( - Effect.gen(function* () { - const startedAtMillis = yield* Ref.get(runtimeStartedAt); - if ( - startedAtMillis === null || - (yield* Clock.currentTimeMillis) - startedAtMillis < - maxRuntimeAgeBeforeTurnMillis - ) { - return false; - } - const hasIdleOutlivingSubagents = [...idleOutlivingSubagents.values()].some( - (entries) => entries.size > 0, - ); - return ( - !(yield* Ref.get(continuationRequested)) && - (yield* Ref.get(wakeBuffer)).length === 0 && - (yield* Ref.get(runningBackgroundTaskIds)).size === 0 && - (yield* Ref.get(detachedBackgroundCommands)).size === 0 && - (yield* Ref.get(detachedUnawaitedTools)).size === 0 && - (yield* Ref.get(carryoverSubagents)) === null && - !hasIdleOutlivingSubagents - ); - }), - ) - : false; - if (shouldRecycleStaleRuntime) { - yield* Ref.set(runtimeRestartRequired, true); + ) { + yield* runtimeCallbackPermit.withPermit( + continuationPermit.withPermit( + Effect.gen(function* () { + const startedAtMillis = yield* Ref.get(runtimeStartedAt); + if ( + startedAtMillis === null || + (yield* Clock.currentTimeMillis) - startedAtMillis < + maxRuntimeAgeBeforeTurnMillis + ) { + return; + } + const hasIdleOutlivingSubagents = [...idleOutlivingSubagents.values()].some( + (entries) => entries.size > 0, + ); + const hasActiveDetachedBackgroundCommands = [ + ...(yield* Ref.get(detachedBackgroundCommands)), + ].some(([taskId, turn]) => { + const toolCallId = turn.toolCallIdsByBackgroundTaskId.get(taskId); + const tool = + toolCallId === undefined ? undefined : turn.tools.get(toolCallId); + const status = tool === undefined ? "completed" : toolStatus(tool.status); + return status === "pending" || status === "running"; + }); + const hasActiveDetachedUnawaitedTools = [ + ...(yield* Ref.get(detachedUnawaitedTools)), + ].some(([toolCallId, turn]) => { + const tool = turn.tools.get(toolCallId); + const status = tool === undefined ? "completed" : toolStatus(tool.status); + return status === "pending" || status === "running"; + }); + if ( + !(yield* Ref.get(continuationRequested)) && + (yield* Ref.get(wakeBuffer)).length === 0 && + (yield* Ref.get(runningBackgroundTaskIds)).size === 0 && + agentRequests.size === 0 && + !hasActiveDetachedBackgroundCommands && + !hasActiveDetachedUnawaitedTools && + (yield* Ref.get(carryoverSubagents)) === null && + !hasIdleOutlivingSubagents + ) { + // Fence off callbacks from the retiring runtime before leaving the permit + // so no late root wake can be buffered ahead of teardown. + yield* advanceRuntimeCallbackGeneration; + yield* Ref.set(runtimeRestartRequired, true); + } + }), + ), + ); } const restartResult = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, From ce501135d33b2e2fa629d7368cd5884ae6f4f04a Mon Sep 17 00:00:00 2001 From: Taylor Dolezal <117500+onlydole@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:03:01 -0800 Subject: [PATCH 3/7] fix(acp): harden stale-runtime recycle gate for pending replies and carryover subagents Check flavor.hasPendingReply on the active session before recycling an aged runtime, only block recycling on carryoverSubagents that still have nonterminal or unprojected state, and wrap advanceRuntimeCallbackGeneration + runtimeRestartRequired in Effect.uninterruptible so interruption cannot split the callback fence from the restart marker. Done by Gemini 4 Neon (High) in Antigravity (via T3 Code). --- .../Adapters/AcpAdapterV2.test.ts | 16 ++++++--- packages/provider-acp/src/server/adapter.ts | 35 +++++++++++++++---- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 7f86b6c5430ba..d32b60678092b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -13976,6 +13976,7 @@ describe("AcpAdapterV2", () => { const resumeIds: Array = []; const receivedOutputs: Array = []; let emitReplyOnNextPrompt = false; + let pendingReply = false; const baseMakeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath, @@ -14011,6 +14012,7 @@ describe("AcpAdapterV2", () => { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, maxRuntimeAgeBeforeTurn: "45 minutes", + hasPendingReply: () => Effect.sync(() => pendingReply), watchPromptOutcome: () => Effect.succeed((_result, options) => Effect.sync(() => { @@ -14069,22 +14071,26 @@ describe("AcpAdapterV2", () => { // Turn 2 at +30m (< 45m): reuses runtime 1 and emits assistant output. yield* TestClock.adjust("30 minutes"); yield* runTurn(2, true); - // Turn 3 at +50m (>= 45m): proactively recycles to runtime 2 with resumeSessionId. + // Turn 3 at +50m (>= 45m), but a queued reply defers recycling on runtime 1. yield* TestClock.adjust("20 minutes"); + pendingReply = true; yield* runTurn(3, true); + // Turn 4 once the pending reply clears: proactively recycles to runtime 2 with resumeSessionId. + pendingReply = false; + yield* runTurn(4, true); // Restarting via loadSession keeps the replayed snapshot history intact. const snapshotAfterRecycle = yield* session.readThreadSnapshot({ providerThread }); assert.isTrue( snapshotAfterRecycle.messages.some((message) => message.text.includes("replay")), "expected replayed snapshot message to survive runtime recycle", ); - // Turn 4 at +10m after recycle (< 45m on runtime 2): stays on runtime 2. + // Turn 5 at +10m after recycle (< 45m on runtime 2): stays on runtime 2. yield* TestClock.adjust("10 minutes"); - yield* runTurn(4, false); + yield* runTurn(5, false); - assert.deepEqual(promptRuntimes, [1, 1, 2, 2]); + assert.deepEqual(promptRuntimes, [1, 1, 1, 2, 2]); assert.deepEqual(resumeIds, [undefined, providerThread.nativeThreadRef?.nativeId]); - assert.deepEqual(receivedOutputs, [false, true, true, false]); + assert.deepEqual(receivedOutputs, [false, true, true, true, false]); }).pipe(Effect.provide(layerTest)), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index a47c33dcd296e..4645d6ee739f3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -11190,21 +11190,42 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const status = tool === undefined ? "completed" : toolStatus(tool.status); return status === "pending" || status === "running"; }); - if ( + const carryover = yield* Ref.get(carryoverSubagents); + const hasActiveCarryoverSubagents = + carryover !== null && + carryover.subagents.some( + (subagent) => + !acpSubagentStatusIsTerminal(subagent.task.status) || + !subagent.terminalStatusProjected, + ); + const isIdleInMemory = !(yield* Ref.get(continuationRequested)) && (yield* Ref.get(wakeBuffer)).length === 0 && (yield* Ref.get(runningBackgroundTaskIds)).size === 0 && agentRequests.size === 0 && !hasActiveDetachedBackgroundCommands && !hasActiveDetachedUnawaitedTools && - (yield* Ref.get(carryoverSubagents)) === null && - !hasIdleOutlivingSubagents + !hasActiveCarryoverSubagents && + !hasIdleOutlivingSubagents; + if (!isIdleInMemory) { + return; + } + const currentSessionId = yield* Ref.get(activeSessionId); + if ( + currentSessionId !== null && + flavor.hasPendingReply !== undefined && + (yield* flavor.hasPendingReply(currentSessionId)) ) { - // Fence off callbacks from the retiring runtime before leaving the permit - // so no late root wake can be buffered ahead of teardown. - yield* advanceRuntimeCallbackGeneration; - yield* Ref.set(runtimeRestartRequired, true); + return; } + // Fence off callbacks from the retiring runtime before leaving the permit + // so no late root wake can be buffered ahead of teardown. + yield* Effect.uninterruptible( + Effect.andThen( + advanceRuntimeCallbackGeneration, + Ref.set(runtimeRestartRequired, true), + ), + ); }), ), ); From aa50da54bb02cfadb9990ca0fba014f07c4d7744 Mon Sep 17 00:00:00 2001 From: Taylor Dolezal <117500+onlydole@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:07:41 -0800 Subject: [PATCH 4/7] fix(acp): restore cached snapshot when same-session resume emits no replay Snapshot the prior same-session history before resetting for startAcpRuntime, and restore it afterward if activated.sessionId matches and no replay updates arrived (covering resumeMethod: "resume" on agents that also advertise loadSession). Done by Gemini 4 Neon (High) in Antigravity (via T3 Code). --- .../Adapters/AcpAdapterV2.test.ts | 115 ++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 20 ++- 2 files changed, 130 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index d32b60678092b..503f6525c5082 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -14241,6 +14241,121 @@ describe("AcpAdapterV2", () => { assert.deepEqual(promptRuntimes, [1, 1, 2]); }).pipe(Effect.provide(layerTest)), ); + + it.effect( + "preserves cached snapshot history across a same-session resume that emits no replay", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-resume-no-replay-snapshot"); + const threadId = ThreadId.make("thread-acp-resume-no-replay-snapshot"); + const promptRuntimes: Array = []; + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => { + let onUpdate: Parameters[0] | undefined; + return { + ...runtime, + // Simulate a same-session session/resume that sends no replay updates even + // though the agent advertises both loadSession and sessionCapabilities.resume. + handleSessionUpdate: (handler) => + Effect.sync(() => { + onUpdate = handler; + }).pipe( + Effect.andThen( + runtime.handleSessionUpdate((notification) => + runtimeOrdinal > 1 ? Effect.void : handler(notification), + ), + ), + ), + prompt: (_payload, promptOptions) => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + if (onUpdate !== undefined) { + yield* onUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: `reply-runtime-${runtimeOrdinal}` }, + }, + }); + } + return { stopReason: "end_turn" as const }; + }), + }; + }, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + makeRuntime: baseMakeRuntime, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-resume-no-replay"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + yield* runTurn(1); + yield* TestClock.adjust("50 minutes"); + yield* runTurn(2); + assert.deepEqual(promptRuntimes, [1, 2]); + + const snapshotAfterRecycle = yield* session.readThreadSnapshot({ providerThread }); + assert.isTrue( + snapshotAfterRecycle.messages.some((message) => message.text.includes("reply-runtime-1")), + "expected prior turn reply to remain cached when resume emits no replay", + ); + assert.isTrue( + snapshotAfterRecycle.messages.some((message) => message.text.includes("reply-runtime-2")), + "expected post-recycle reply to appear in snapshot", + ); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 4645d6ee739f3..5a82ccbab5af9 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10781,16 +10781,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } const mcpContext = yield* readMcpContext(threadId); prepareTerminalEnvironment(mcpContext, resumeSessionId); - // Clear before start when load will replay or switching sessions; keep cached - // history on same-session resume when no replay will arrive. - if ((yield* Ref.get(activeSessionId)) !== resumeSessionId || canLoadSession) { - yield* Ref.set(snapshot, emptySnapshotState()); - } + const previousSnapshot = + (yield* Ref.get(activeSessionId)) === resumeSessionId + ? yield* Ref.get(snapshot) + : undefined; + // Clear before start so a load-capable resume starts from a clean replay slate; + // if a same-session resume sends no replay (e.g. resumeMethod: "resume"), restore + // the cached snapshot afterward. + yield* Ref.set(snapshot, emptySnapshotState()); yield* reportStartupPhase("launch"); yield* reportStartupPhase("resume"); const activated = yield* startAcpRuntime(threadId, resumeSessionId).pipe( Effect.onError(() => reportStartupPhase(undefined)), ); + if ( + previousSnapshot !== undefined && + activated.sessionId === resumeSessionId && + (yield* Ref.get(snapshot)).order.length === 0 + ) { + yield* Ref.set(snapshot, previousSnapshot); + } yield* Ref.set(runtimeRestartRequired, false); yield* reportStartupPhase(undefined); yield* Ref.set(activeSessionId, activated.sessionId); From 5c0de25f113bc8510cca5cafbd724fa166f982bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 3 Dec 2026 19:49:28 +0000 Subject: [PATCH 5/7] test(server): trim Antigravity ADC recycle tests to distinct regressions Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 371 +++++++++--------- .../Drivers/AntigravityDriver.test.ts | 9 - .../acp/AntigravityTurnOutcome.test.ts | 8 - 3 files changed, 178 insertions(+), 210 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 68e1f54a821bb..aa3967b079f50 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -5539,204 +5539,189 @@ describe("AntigravityAdapterV2 failed edits", () => { }); describe("AntigravityAdapterV2 silent ADC drop recovery", () => { - it.effect( - "fails a silent USER_INPUT-only turn and restarts the runtime on the next send, and recycles after maxRuntimeAgeBeforeTurn", - () => - Effect.gen(function* () { - 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 profileDirectory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-antigravity-adc-drop-", - }); - const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); - yield* fileSystem.makeDirectory(conversations, { recursive: true }); - const appendStep = (type: number, status: number, payload: string) => { - const database = new NodeSqlite.DatabaseSync( - path.join(conversations, "mock-session-1.db"), + it.effect("fails a silent USER_INPUT-only turn and restarts the runtime on the next send", () => + Effect.gen(function* () { + 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 profileDirectory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-antigravity-adc-drop-", + }); + const conversations = path.join(profileDirectory, "antigravity-acp", "conversations"); + yield* fileSystem.makeDirectory(conversations, { recursive: true }); + const appendStep = (type: number, status: number, payload: string) => { + const database = new NodeSqlite.DatabaseSync(path.join(conversations, "mock-session-1.db")); + try { + database.exec( + "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, step_payload BLOB)", ); - try { - database.exec( - "CREATE TABLE IF NOT EXISTS steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, step_payload BLOB)", - ); - database - .prepare("INSERT INTO steps (step_type, status, step_payload) VALUES (?, ?, ?)") - .run(type, status, Buffer.from(payload)); - } finally { - database.close(); - } - }; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let runtimeOrdinal = 0; - const promptRuntimes: Array = []; - const resumeIds: Array = []; - const instanceId = ProviderInstanceId.make("antigravity-adc-drop-test"); - const threadId = ThreadId.make("thread-antigravity-adc-drop"); - const adapter = yield* makeAntigravityAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - profileDirectory, - maxRuntimeAgeBeforeTurn: "45 minutes", - makeRuntime: (input) => { - const currentRuntime = ++runtimeOrdinal; - resumeIds.push(input.resumeSessionId); - let sessionUpdate: Parameters[0] | undefined; - return makeAntigravityAcpRuntime({ - ...input, - childProcessSpawner, - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, - }, - }).pipe( - Effect.provideService(SecureRandom.SecureRandom, crypto), - Effect.map((runtime): RuntimeService => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdate = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => - Effect.gen(function* () { - promptRuntimes.push(currentRuntime); - appendStep(14, 3, `Prompt on runtime ${currentRuntime}`); - // Simulate agy's 60m ADC OAuth failure on runtime 1: only USER_INPUT is - // recorded and session/prompt resolves cleanly with no output or usage. - if (currentRuntime === 1) { - return { stopReason: "end_turn" as const }; - } - yield* sessionUpdate!( - normalizeAntigravitySessionUpdate({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: `Reply from runtime ${currentRuntime}` }, - }, - }), - ); - appendStep(15, 3, `Reply from runtime ${currentRuntime}`); - return { - stopReason: "end_turn" as const, - usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 }, - }; - }), - })), - ); - }, - withProcess: (_stop, task) => task, - defaultModel: Effect.undefined, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "gemini-test-low" } as const; - const session = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-antigravity-adc-drop"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* session.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const runTurn = (ordinal: number) => - Effect.gen(function* () { - const now = yield* DateTime.now; - yield* session.startTurn({ - appThread: { - createdBy: "user", - creationSource: "web", - id: threadId, - projectId: ProjectId.make("project-antigravity-adc-drop"), - title: "Antigravity ADC drop", - providerInstanceId: instanceId, - modelSelection, - runtimeMode: runtimePolicy.runtimeMode, - interactionMode: runtimePolicy.interactionMode, - branch: null, - worktreePath: null, - 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-adc-drop-${ordinal}`), - runOrdinal: ordinal, - providerTurnOrdinal: ordinal, - attemptId: RunAttemptId.make(`attempt-antigravity-adc-drop-${ordinal}`), - rootNodeId: NodeId.make(`node-antigravity-adc-drop-${ordinal}`), - providerThread, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make(`msg-antigravity-adc-drop-${ordinal}`), - text: `Hello ${ordinal}`, - attachments: [], - }, + database + .prepare("INSERT INTO steps (step_type, status, step_payload) VALUES (?, ?, ?)") + .run(type, status, Buffer.from(payload)); + } finally { + database.close(); + } + }; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let runtimeOrdinal = 0; + const promptRuntimes: Array = []; + const resumeIds: Array = []; + const instanceId = ProviderInstanceId.make("antigravity-adc-drop-test"); + const threadId = ThreadId.make("thread-antigravity-adc-drop"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + profileDirectory, + maxRuntimeAgeBeforeTurn: "45 minutes", + makeRuntime: (input) => { + const currentRuntime = ++runtimeOrdinal; + resumeIds.push(input.resumeSessionId); + let sessionUpdate: Parameters[0] | undefined; + return makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptRuntimes.push(currentRuntime); + appendStep(14, 3, `Prompt on runtime ${currentRuntime}`); + // Simulate agy's 60m ADC OAuth failure on runtime 1: only USER_INPUT is + // recorded and session/prompt resolves cleanly with no output or usage. + if (currentRuntime === 1) { + return { stopReason: "end_turn" as const }; + } + yield* sessionUpdate!( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: `Reply from runtime ${currentRuntime}` }, + }, + }), + ); + appendStep(15, 3, `Reply from runtime ${currentRuntime}`); + return { + stopReason: "end_turn" as const, + usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 }, + }; + }), + })), + ); + }, + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-adc-drop"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-adc-drop"), + title: "Antigravity ADC drop", + providerInstanceId: instanceId, modelSelection, - runtimePolicy, - }); - const events = Array.from( - yield* session.events.pipe( - Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.runCollect, - ), - ); - return events.at(-1); + runtimeMode: runtimePolicy.runtimeMode, + interactionMode: runtimePolicy.interactionMode, + branch: null, + worktreePath: null, + 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-adc-drop-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-adc-drop-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-adc-drop-${ordinal}`), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`msg-antigravity-adc-drop-${ordinal}`), + text: `Hello ${ordinal}`, + attachments: [], + }, + modelSelection, + runtimePolicy, }); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + return events.at(-1); + }); - // Turn 1 hits the silent drop on runtime 1 and fails with a retryable provider error. - const firstTerminal = yield* runTurn(1); - assert.equal(firstTerminal?.type, "turn.terminal"); - assert.equal( - firstTerminal?.type === "turn.terminal" ? firstTerminal.status : null, - "failed", - ); - assert.equal( - firstTerminal?.type === "turn.terminal" && firstTerminal.status === "failed" - ? firstTerminal.failure.retryable - : null, - true, - ); - - // Turn 2 automatically restarts onto runtime 2 (resuming mock-session-1) and succeeds. - const secondTerminal = yield* runTurn(2); - assert.equal( - secondTerminal?.type === "turn.terminal" ? secondTerminal.status : null, - "completed", - ); + // Turn 1 hits the silent drop on runtime 1 and fails with a retryable provider error. + const firstTerminal = yield* runTurn(1); + assert.equal(firstTerminal?.type, "turn.terminal"); + assert.equal(firstTerminal?.type === "turn.terminal" ? firstTerminal.status : null, "failed"); + assert.equal( + firstTerminal?.type === "turn.terminal" && firstTerminal.status === "failed" + ? firstTerminal.failure.retryable + : null, + true, + ); - // Turn 3 after 45 minutes proactively recycles onto runtime 3 (resuming mock-session-1). - yield* TestClock.adjust("45 minutes"); - const thirdTerminal = yield* runTurn(3); - assert.equal( - thirdTerminal?.type === "turn.terminal" ? thirdTerminal.status : null, - "completed", - ); + // Turn 2 automatically restarts onto runtime 2 (resuming mock-session-1) and succeeds. + const secondTerminal = yield* runTurn(2); + assert.equal( + secondTerminal?.type === "turn.terminal" ? secondTerminal.status : null, + "completed", + ); - assert.deepEqual(promptRuntimes, [1, 2, 3]); - assert.deepEqual(resumeIds, [undefined, "mock-session-1", "mock-session-1"]); - }).pipe(Effect.provide(layerSession)), + assert.deepEqual(promptRuntimes, [1, 2]); + assert.deepEqual(resumeIds, [undefined, "mock-session-1"]); + }).pipe(Effect.provide(layerSession)), ); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 2616edd22f8ec..be66518faacc6 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -1134,20 +1134,11 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "" })).toBe( "45 minutes", ); - expect( - antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: " " }), - ).toBe("45 minutes"); expect( antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "agent-platform", apiKey: "AIza-test" }), ).toBeUndefined(); expect( antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "oauth-personal", apiKey: "" }), ).toBeUndefined(); - expect( - antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "oauth-business", apiKey: "" }), - ).toBeUndefined(); - expect( - antigravityMaxRuntimeAgeBeforeTurn({ authMethod: "gemini-api-key", apiKey: "AIza-test" }), - ).toBeUndefined(); }); }); diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index 58ef8483227fd..4622c2380f3ef 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -463,14 +463,6 @@ describe("watchAntigravityPromptOutcome", () => { retryable: true, }), ); - assert.equal( - (yield* turn( - [[USER_INPUT, input]], - { stopReason: "end_turn", usage: null }, - { receivedOutput: false }, - ))?.failure.retryable, - true, - ); // Local replies, reported usage, inactivity-retired prompts, and steers after a // model reply must not trip the silent-drop check. assert.isUndefined( From fecd73d4b3103ebcbf58ae8e48833b363c834129 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 3 Dec 2026 19:54:21 +0000 Subject: [PATCH 6/7] fix(acp): drain replay before restoring cached snapshot on runtime recycle Co-Authored-By: Claude Opus 5.5 --- packages/provider-acp/src/server/adapter.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 5a82ccbab5af9..5176205d4c525 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10792,8 +10792,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* reportStartupPhase("launch"); yield* reportStartupPhase("resume"); const activated = yield* startAcpRuntime(threadId, resumeSessionId).pipe( - Effect.onError(() => reportStartupPhase(undefined)), + Effect.onError(() => + Effect.andThen( + reportStartupPhase(undefined), + previousSnapshot === undefined + ? Effect.void + : Ref.set(snapshot, previousSnapshot), + ), + ), ); + yield* runtime.drainEvents; if ( previousSnapshot !== undefined && activated.sessionId === resumeSessionId && From 570236561c0f80d38ebb14574e71d415e6b0d653 Mon Sep 17 00:00:00 2001 From: Taylor Dolezal <117500+onlydole@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:48:17 -0800 Subject: [PATCH 7/7] fix(acp): preserve restart marker if replacement runtime terminates during restart Clear runtimeRestartRequired and advance runtimeCallbackGeneration under runtimeCallbackPermit before spawning the replacement runtime (inside Effect.uninterruptibleMask with Effect.onExit restoring runtimeRestartRequired, snapshot, and startup phase on failure or interruption), so an immediate termination of the replacement runtime during startup or runtime.drainEvents stays recorded for the next turn. Done by Gemini 4 Neon (High) in Antigravity (via T3 Code). --- .../Adapters/AcpAdapterV2.test.ts | 102 ++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 60 ++++++++--- 2 files changed, 148 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 503f6525c5082..88626fd1ef762 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -14356,6 +14356,108 @@ describe("AcpAdapterV2", () => { ); }).pipe(Effect.provide(layerTest)), ); + + it.effect( + "preserves runtimeRestartRequired when a replacement runtime terminates during restart drain", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-restart-drain-termination"); + const threadId = ThreadId.make("thread-acp-restart-drain-termination"); + const promptRuntimes: Array = []; + const onTerminations = new Map(); + let nextRuntime = 0; + const baseMakeRuntime = makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime, runtimeOrdinal) => ({ + ...runtime, + drainEvents: + runtimeOrdinal === 2 + ? runtime.drainEvents.pipe( + Effect.andThen( + onTerminations.get(2)?.( + new EffectAcpErrors.AcpTransportError({ + detail: "replacement runtime exited during drain", + cause: new Error("exited"), + }), + ) ?? Effect.void, + ), + ) + : runtime.drainEvents, + prompt: (_payload, promptOptions) => + Effect.gen(function* () { + promptRuntimes.push(runtimeOrdinal); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + return { stopReason: "end_turn" as const }; + }), + }), + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + maxRuntimeAgeBeforeTurn: "45 minutes", + makeRuntime: (runtimeInput) => + Effect.sync(() => { + nextRuntime += 1; + onTerminations.set(nextRuntime, runtimeInput.onTermination); + }).pipe(Effect.andThen(baseMakeRuntime(runtimeInput))), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-drain-termination"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + }); + + yield* runTurn(1); + yield* TestClock.adjust("50 minutes"); + // Runtime 2 terminates during drainEvents; Turn 3 must not reuse it. + yield* runTurn(2); + yield* runTurn(3); + assert.deepEqual(promptRuntimes, [1, 2, 3]); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 5176205d4c525..d8185d9de7c6e 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10791,17 +10791,35 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(snapshot, emptySnapshotState()); yield* reportStartupPhase("launch"); yield* reportStartupPhase("resume"); - const activated = yield* startAcpRuntime(threadId, resumeSessionId).pipe( - Effect.onError(() => - Effect.andThen( - reportStartupPhase(undefined), - previousSnapshot === undefined - ? Effect.void - : Ref.set(snapshot, previousSnapshot), - ), - ), + const activated = yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + // Fence off the old runtime and clear the marker before spawning so a + // termination of the new runtime during startup or drain stays recorded. + yield* runtimeCallbackPermit.withPermit( + Effect.andThen( + advanceRuntimeCallbackGeneration, + Ref.set(runtimeRestartRequired, false), + ), + ); + return yield* restore( + startAcpRuntime(threadId, resumeSessionId).pipe( + Effect.tap(() => runtime.drainEvents), + ), + ).pipe( + Effect.onExit((exit) => + Exit.isSuccess(exit) + ? Effect.void + : Effect.gen(function* () { + yield* Ref.set(runtimeRestartRequired, true); + if (previousSnapshot !== undefined) { + yield* Ref.set(snapshot, previousSnapshot); + } + yield* reportStartupPhase(undefined); + }), + ), + ); + }), ); - yield* runtime.drainEvents; if ( previousSnapshot !== undefined && activated.sessionId === resumeSessionId && @@ -10809,7 +10827,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { yield* Ref.set(snapshot, previousSnapshot); } - yield* Ref.set(runtimeRestartRequired, false); yield* reportStartupPhase(undefined); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(loadingSessionId, null); @@ -10827,10 +10844,25 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return { restarted: true as const, activated }; } yield* reportStartupPhase("launch"); - yield* restartAcpRuntime(threadId).pipe( - Effect.onError(() => reportStartupPhase(undefined)), + yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + yield* runtimeCallbackPermit.withPermit( + Effect.andThen( + advanceRuntimeCallbackGeneration, + Ref.set(runtimeRestartRequired, false), + ), + ); + yield* restore(restartAcpRuntime(threadId)).pipe( + Effect.onExit((exit) => + Exit.isSuccess(exit) + ? Effect.void + : Ref.set(runtimeRestartRequired, true).pipe( + Effect.andThen(reportStartupPhase(undefined)), + ), + ), + ); + }), ); - yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); yield* Ref.set(activeSessionSetup, null); yield* resetPublishedCatalogKey;