Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand All @@ -1791,6 +1795,64 @@ 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");
Comment thread
itsthecsguy marked this conversation as resolved.
Resolved
assert.equal(run.cancels(), 0, "releasing a running command must not cancel it");
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", () =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const AntigravityProviderCapabilitiesV2 = {
tools: {
...AcpProviderCapabilitiesV2.tools,
supportsMcpTools: true,
supportsBackgroundWait: true,
Comment thread
itsthecsguy marked this conversation as resolved.
Resolved
},
subagents: {
...AcpProviderCapabilitiesV2.subagents,
Expand Down
113 changes: 99 additions & 14 deletions packages/provider-acp/src/server/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1693,6 +1693,7 @@ interface ActiveAcpTurn {
{ readonly status: "completed" | "failed"; readonly output?: string } | null
>;
readonly persistentBackgroundTaskIds: Set<string>;
readonly unawaitedToolCallIds: Set<string>;
/** Monitor end notices lack output; wait for hydration or the safety timeout. */
readonly awaitingBackgroundHydration: Set<string>;
readonly pendingInjectedReport: Set<string>;
Expand Down Expand Up @@ -2646,6 +2647,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const detachedBackgroundCommands = yield* Ref.make<ReadonlyMap<string, ActiveAcpTurn>>(
new Map(),
);
// Released outliving tool calls without a background task id → the completed turn that owns their row.
const detachedUnawaitedTools = yield* Ref.make<ReadonlyMap<string, ActiveAcpTurn>>(
new Map(),
);
const endedDetachedBackgroundCommandLimit = 16;
const detachedBackgroundCommandTurn = (taskId: string) =>
Ref.get(detachedBackgroundCommands).pipe(Effect.map((turns) => turns.get(taskId)));
Expand All @@ -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]) => {
Expand All @@ -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<ReadonlySet<string>>(new Set());
const endedBackgroundTaskIdLimit = 128;
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -5395,6 +5422,32 @@ 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 (yield* Ref.get(stoppedRunQuarantine)) return false;
if (notification.sessionId !== (yield* Ref.get(activeSessionId))) return false;
const owner =
(active?.finalized === true &&
active.finalizedStatus === "completed" &&
active.unawaitedToolCallIds.has(update.toolCallId) &&
active.tools.has(update.toolCallId)
? active
: undefined) ?? (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,
) {
Expand All @@ -5420,11 +5473,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;
Expand Down Expand Up @@ -5468,6 +5525,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
let buffered = false;
if (
!alreadyHandledToolUpdate &&
!projectedDetachedUnawaitedTool &&
!isInTurnHandledAgentChatter &&
acpPostSettleWakeShouldBuffer(notification, backgroundWorkRunning)
) {
Expand Down Expand Up @@ -5775,6 +5833,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
return;
if (yield* projectAgentTerminalUpdate(notification, context)) return;
if (yield* projectDetachedBackgroundCommand(notification, context)) return;
if (context !== null && (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.
Expand Down Expand Up @@ -8011,6 +8071,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());
Expand Down Expand Up @@ -8534,6 +8595,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;
Expand Down Expand Up @@ -8575,6 +8639,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);
Expand Down Expand Up @@ -9555,6 +9620,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,
Expand Down Expand Up @@ -10239,19 +10305,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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return { matched: [...new Set(taskIds)] };
}),
}),
interruptTurn: Effect.fn("AcpAdapterV2.interruptTurn")(
Expand Down
Loading