diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..5cbb4975e5e57 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1327,6 +1327,16 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); yield* startTurn(1, false); yield* throughPromptSettled; + // Progress keeps a command past the post-settle hold bound, which counts silence only. + for (const minute of [10, 20, 30]) { + yield* TestClock.adjust("10 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "in_progress", + rawOutput: { output: `fetched ${minute} pages` }, + }); + } yield* TestClock.adjust("10 minutes"); yield* send({ sessionUpdate: "tool_call_update", @@ -1349,6 +1359,115 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // A command whose terminal update never arrives would hold the run in Working forever with + // an empty pending list and a finished reply above Stop. + it.effect("settles a silent background command after the post-settle hold timeout", () => + Effect.gen(function* () { + const { command, offers, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + const prompt = yield* throughPromptSettled; + + // A running tool keeps the inactivity watchdog re-armed, so 20 silent minutes do not + // settle this run on their own. + yield* TestClock.adjust("20 minutes"); + yield* TestClock.adjust("11 minutes"); + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal( + terminal?.type === "turn.terminal" && terminal.status, + "completed", + "the bounded hold finalizes the turn instead of leaving it running forever", + ); + assert.equal(terminal?.type === "turn.terminal" && terminal.failure, null); + assert.lengthOf(offers, 0, "a silent command produces no wake on its own"); + const commandItem = [...prompt, ...run].findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.isTrue( + commandItem?.type === "turn_item.updated" && commandItem.turnItem.status === "completed", + "the silent command is no longer left as live activity on a settled run", + ); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps a silent scheduled wake in its run past the command hold bound", () => + Effect.gen(function* () { + const { usage, offers, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + initialToolCalls: [ + { + sessionUpdate: "tool_call", + toolCallId: "call_schedule", + kind: "other", + title: "Run schedule", + status: "in_progress", + rawInput: { DurationSeconds: 3600, Prompt: "Continue the task" }, + }, + ], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("61 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call_schedule", + status: "completed", + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Picked the task back up." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include( + JSON.stringify(run), + "Picked the task back up.", + "the wake reply stays in the run", + ); + assert.lengthOf(offers, 0); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps an unanswered question open past the command hold bound", () => + Effect.gen(function* () { + const { command, usage, send, startTurn, until, throughPromptSettled, requestPermission } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + yield* throughPromptSettled; + const question = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { toolCallId: "interaction_1", kind: "other", title: "Which port?" }, + options: [ + { optionId: "3000", name: "3000", kind: "allow_once" }, + { optionId: "8080", name: "8080", kind: "allow_once" }, + ], + }, + { requestId: "question-1", method: "session/request_permission" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* TestClock.adjust("31 minutes"); + yield* Fiber.interrupt(question); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include(JSON.stringify(run), "Here is the chart.", "the question kept the run open"); + }).pipe(Effect.provide(layerSession)), + ); + // Command 2 finishes during reply 1; agy dequeues command 2 after reply 1's usage_update and // needs >3 s before streaming reply 2. Wait for reply 2 (bounded by the 2-minute quiet limit), // but still finalize at 3 s when both commands were batched into reply 1. diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..c20afa04e31b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -41,6 +41,7 @@ import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTur import { antigravityApprovalOptions, antigravityToolOutlivesPrompt, + antigravityCommandOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, @@ -244,6 +245,12 @@ export function makeAntigravityAcpAdapterFlavor( wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, toolOutlivesPrompt: antigravityToolOutlivesPrompt, + // agy sometimes loses the terminal update or wake for a background command, which would + // hold the turn in Working forever. 30 minutes still leaves long commands room. + postSettleCommandHold: { + timeout: "30 minutes", + isCommand: antigravityCommandOutlivesPrompt, + }, // session/cancel ends the agent's running commands, so only Stop sends it once the prompt // has ended. A message sent while a command runs leaves the command alone. preserveRuntimeOnSettledInterrupt: true, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index c718667dcf42e..2e59a78e376b4 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -55,6 +55,12 @@ const ANTIGRAVITY_SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"] */ export function antigravityToolOutlivesPrompt(toolCall: AcpToolCallState): boolean { if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return true; + return antigravityCommandOutlivesPrompt(toolCall); +} + +/** A non-daemon command the agent awaits; unlike a schedule, it reports progress while it runs. */ +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean { + if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return false; const input = toolCall.data.rawInput; return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true); } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 21fe311588906..908c99e4eaeb3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2742,7 +2751,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4274,11 +4288,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8835,6 +8853,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -9265,6 +9316,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9665,6 +9717,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else {