diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5cbb4975e5e57..1d95f625a409c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1778,6 +1778,10 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { Effect.gen(function* () { const { session, providerThread, startTurn, throughPromptSettled } = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + assert.isTrue( + session.providerSession.capabilities.tools.supportsBackgroundWait, + "Antigravity must advertise supportsBackgroundWait so t3_background_wait is exposed", + ); yield* startTurn(1, false); yield* throughPromptSettled; const taskIds = ["mock-session-1/task-2"]; @@ -1791,6 +1795,63 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // `waiting=false` lets the run end while the command keeps running, as with a daemon. + it.effect("ends the run when t3_background_wait releases a running command", () => + Effect.gen(function* () { + const { session, providerThread, command, offers, send, startTurn, ...run } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + const beforeRelease = yield* run.throughPromptSettled; + const originalCommandItem = beforeRelease.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.isDefined(originalCommandItem); + const taskIds = ["mock-session-1/task-2"]; + const released = yield* session.awaitBackgroundTasks!({ + providerThread, + taskIds, + awaited: false, + }); + assert.deepEqual(released.matched, taskIds); + yield* TestClock.adjust("5 seconds"); + const settledEvents = yield* run.throughTerminal; + const terminal = settledEvents.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + const itemAtSettle = [...beforeRelease, ...settledEvents].findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.equal( + itemAtSettle?.type === "turn_item.updated" && itemAtSettle.turnItem.status, + "running", + "releasing a running command must not mark its tool row completed before it finishes", + ); + + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + const completedUpdate = (yield* run.until( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId && + event.turnItem.status === "completed", + )).at(-1); + assert.equal( + completedUpdate?.type === "turn_item.updated" && completedUpdate.turnItem.id, + originalCommandItem?.type === "turn_item.updated" && originalCommandItem.turnItem.id, + "eventual completion must update the released command's original row", + ); + assert.include(JSON.stringify(completedUpdate), "Command exited with code 0."); + assert.lengthOf(offers, 1, "the released command still wakes the thread when it ends"); + }).pipe(Effect.provide(layerSession)), + ); + // agy 1.5.11 reads a prompt sent mid-turn as a steer: it answers the running prompt end_turn // and goes on under the new one. session/cancel would end its running commands and subagents. it.effect("steers a running prompt with the next one and leaves its work running", () => diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index c20afa04e31b8..55fa6452bc501 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -69,6 +69,7 @@ const AntigravityProviderCapabilitiesV2 = { tools: { ...AcpProviderCapabilitiesV2.tools, supportsMcpTools: true, + supportsBackgroundWait: true, }, subagents: { ...AcpProviderCapabilitiesV2.subagents, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 908c99e4eaeb3..778a6cdd5f940 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1693,6 +1693,7 @@ interface ActiveAcpTurn { { readonly status: "completed" | "failed"; readonly output?: string } | null >; readonly persistentBackgroundTaskIds: Set; + readonly unawaitedToolCallIds: Set; /** Monitor end notices lack output; wait for hydration or the safety timeout. */ readonly awaitingBackgroundHydration: Set; readonly pendingInjectedReport: Set; @@ -2646,6 +2647,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const detachedBackgroundCommands = yield* Ref.make>( new Map(), ); + // Released outliving tool calls without a background task id → the completed turn that owns their row. + const detachedUnawaitedTools = yield* Ref.make>( + new Map(), + ); const endedDetachedBackgroundCommandLimit = 16; const detachedBackgroundCommandTurn = (taskId: string) => Ref.get(detachedBackgroundCommands).pipe(Effect.map((turns) => turns.get(taskId))); @@ -2656,8 +2661,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const active = yield* Ref.get(activeTurn); return active?.finalized === false ? active : undefined; }); - const detachBackgroundCommands = (context: ActiveAcpTurn) => - Ref.update(detachedBackgroundCommands, (current) => { + const detachBackgroundCommands = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + yield* Ref.update(detachedBackgroundCommands, (current) => { const next = new Map(current); for (const taskId of context.backgroundCommands.keys()) next.set(taskId, context); const ended = [...next].filter(([taskId, turn]) => { @@ -2671,6 +2676,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return next; }); + if (context.unawaitedToolCallIds.size > 0) { + yield* Ref.update(detachedUnawaitedTools, (current) => { + const next = new Map(current); + for (const toolCallId of context.unawaitedToolCallIds) { + if (context.tools.has(toolCallId)) next.set(toolCallId, context); + } + const ended = [...next].filter(([toolCallId, turn]) => { + const tool = turn.tools.get(toolCallId); + const status = tool === undefined ? "completed" : toolStatus(tool.status); + return status !== "pending" && status !== "running"; + }); + for (const [toolCallId] of ended.slice(0, -endedDetachedBackgroundCommandLimit)) { + next.delete(toolCallId); + } + return next; + }); + } + }); // Tombstones prevent mid-stream exit_code 0 and stale monitor events from resurrecting ended tasks. const endedBackgroundTaskIds = yield* Ref.make>(new Set()); const endedBackgroundTaskIdLimit = 128; @@ -4297,7 +4320,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // 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)) + if ( + toolStatus(tool.status) === "running" && + !context.unawaitedToolCallIds.has(tool.toolCallId) && + flavor.toolOutlivesPrompt(tool) + ) return true; } } @@ -5395,6 +5422,25 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return true; }); + // A released outliving tool keeps its original row updated when its real completion arrives. + const projectDetachedUnawaitedTool = Effect.fnUntraced(function* ( + notification: EffectAcpSchema.SessionNotification, + active: ActiveAcpTurn | null, + ) { + const update = notification.update; + if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { + return false; + } + if (active?.finalized === false && active.tools.has(update.toolCallId)) return false; + if (notification.sessionId !== (yield* Ref.get(activeSessionId))) return false; + const owner = (yield* Ref.get(detachedUnawaitedTools)).get(update.toolCallId); + if (owner === undefined) return false; + for (const event of parseSessionUpdateEvent(notification).events) { + if (event._tag === "ToolCallUpdated") yield* emitTool(owner, event.toolCall); + } + return true; + }); + const bufferPostSettleWake = Effect.fnUntraced(function* ( notification: EffectAcpSchema.SessionNotification, ) { @@ -5420,11 +5466,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( stopProcessing: false, }; } + const projectedDetachedUnawaitedTool = yield* projectDetachedUnawaitedTool( + notification, + null, + ); if (!acpPostSettleWakeEvidence(notification, flavor)) { return { buffered: false, offerContinuation: false, - stopProcessing: false, + stopProcessing: projectedDetachedUnawaitedTool, }; } const update = notification.update; @@ -5468,6 +5518,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( let buffered = false; if ( !alreadyHandledToolUpdate && + !projectedDetachedUnawaitedTool && !isInTurnHandledAgentChatter && acpPostSettleWakeShouldBuffer(notification, backgroundWorkRunning) ) { @@ -5775,6 +5826,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; if (yield* projectAgentTerminalUpdate(notification, context)) return; if (yield* projectDetachedBackgroundCommand(notification, context)) return; + if ( + context !== null && + !context.finalized && + (yield* projectDetachedUnawaitedTool(notification, context)) + ) + return; if (flavor.replyEndsWithUsageUpdate === true) { if (context === null) { // A reply can end before its continuation run starts; replay its end with its output. @@ -8011,6 +8068,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(continuationRequested, false); yield* Ref.set(runningBackgroundTaskIds, new Set()); yield* Ref.set(detachedBackgroundCommands, new Map()); + yield* Ref.set(detachedUnawaitedTools, new Map()); yield* Ref.set(endedBackgroundTaskIds, new Set()); yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); yield* Ref.set(handledBackgroundTaskIdsInActiveTurn, new Set()); @@ -8534,6 +8592,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( options?: { readonly unstartedOnly?: boolean }, ) { for (const tool of context.tools.values()) { + if (status === "completed" && context.unawaitedToolCallIds.has(tool.toolCallId)) { + continue; + } if (!acpCompletedTurnShouldTerminalizeTool(tool, { ...flavor, extractSubagentUpdate })) continue; if (options?.unstartedOnly === true && tool.status !== "pending") continue; @@ -8575,6 +8636,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(continuationRequested, false); yield* Ref.set(runningBackgroundTaskIds, new Set()); yield* Ref.set(detachedBackgroundCommands, new Map()); + yield* Ref.set(detachedUnawaitedTools, new Map()); yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); yield* Ref.set(carryoverSubagents, null); yield* Ref.set(lastTurnRoute, null); @@ -9555,6 +9617,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( toolCallIdsByBackgroundTaskId: new Map(), backgroundCommands: new Map(), persistentBackgroundTaskIds: new Set(), + unawaitedToolCallIds: new Set(), awaitingBackgroundHydration: new Set(), pendingInjectedReport: new Set(), earlyInjectedReportObserved: false, @@ -10239,19 +10302,38 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( awaitBackgroundTasks: Effect.fn("AcpAdapterV2.awaitBackgroundTasks")(function* ({ providerThread, taskIds, + awaited, }) { const outlives = flavor.toolOutlivesPrompt; const context = yield* Ref.get(activeTurn); - const holdsCommand = - outlives !== undefined && - defersFinalizeForBackgroundWork && - context !== null && - !context.finalized && - context.nativeThreadId === providerThread.nativeThreadRef?.nativeId && - [...context.tools.values()].some( - (tool) => toolStatus(tool.status) === "running" && outlives(tool), - ); - return { matched: holdsCommand ? [...new Set(taskIds)] : [] }; + if ( + outlives === undefined || + !defersFinalizeForBackgroundWork || + context === null || + context.finalized || + context.nativeThreadId !== providerThread.nativeThreadRef?.nativeId + ) { + return { matched: [] }; + } + const runningOutliving = [...context.tools.values()].filter( + (tool) => toolStatus(tool.status) === "running" && outlives(tool), + ); + if (awaited) { + if (runningOutliving.length === 0) return { matched: [] }; + for (const tool of runningOutliving) { + context.unawaitedToolCallIds.delete(tool.toolCallId); + } + return { matched: [...new Set(taskIds)] }; + } + const held = runningOutliving.filter( + (tool) => !context.unawaitedToolCallIds.has(tool.toolCallId), + ); + if (held.length === 0) return { matched: [] }; + for (const tool of held) { + context.unawaitedToolCallIds.add(tool.toolCallId); + } + yield* rearmDeferredFinalize(context); + return { matched: [...new Set(taskIds)] }; }), }), interruptTurn: Effect.fn("AcpAdapterV2.interruptTurn")(