Skip to content

Commit 34f58e6

Browse files
fix(provider-acp): retain Grok command completion before prompt settles
1 parent 98bc998 commit 34f58e6

2 files changed

Lines changed: 71 additions & 12 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11679,9 +11679,13 @@ describe("AcpAdapterV2", () => {
1167911679
}).pipe(Effect.provide(layerTest), Effect.scoped),
1168011680
);
1168111681

11682-
it.effect(
11683-
"mid-turn unhandled background completion still offers exactly one continuation after finalize",
11684-
() =>
11682+
it.effect.each([
11683+
{ defer: false, status: "completed" as const },
11684+
{ defer: true, status: "completed" as const },
11685+
{ defer: true, status: "failed" as const },
11686+
])(
11687+
"mid-turn unhandled background completion offers once after finalize: $defer / $status",
11688+
({ defer, status }) =>
1168511689
Effect.gen(function* () {
1168611690
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1168711691
const idAllocator = yield* IdAllocator.IdAllocatorV2;
@@ -11702,6 +11706,8 @@ describe("AcpAdapterV2", () => {
1170211706
readonly sessionId: string;
1170311707
readonly taskId: string;
1170411708
readonly status: "running" | "completed" | "failed";
11709+
readonly output?: string;
11710+
readonly report?: { readonly kind: "command" };
1170511711
}) => Effect.Effect<void>)
1170611712
| null;
1170711713
} = { current: null };
@@ -11712,6 +11718,8 @@ describe("AcpAdapterV2", () => {
1171211718
driver: ACP_TEST_DRIVER,
1171311719
capabilities: AcpProviderCapabilitiesV2,
1171411720
enablePostSettleContinuation: true,
11721+
deferFinalizeForBackgroundWork: defer,
11722+
...(defer ? { normalizeToolCall: normalizeXAiAcpToolCallState } : {}),
1171511723
extractBackgroundTaskId: (toolCall) =>
1171611724
toolCall.toolCallId === "tool-call-monitor-late" ? "task-monitor-late" : undefined,
1171711725
registerExtensions: (context) =>
@@ -11799,6 +11807,9 @@ describe("AcpAdapterV2", () => {
1179911807
sessionUpdate: "tool_call_update",
1180011808
toolCallId: "tool-call-monitor-late",
1180111809
status: "in_progress",
11810+
...(defer
11811+
? { rawOutput: { type: "BackgroundTaskStarted", task_id: "task-monitor-late" } }
11812+
: {}),
1180211813
},
1180311814
});
1180411815
yield* applyMutation({
@@ -11809,7 +11820,9 @@ describe("AcpAdapterV2", () => {
1180911820
yield* applyMutation({
1181011821
sessionId: "mock-session-1",
1181111822
taskId: "task-monitor-late",
11812-
status: "completed",
11823+
status,
11824+
output: "EARLY_BG_DONE\n",
11825+
...(defer ? { report: { kind: "command" as const } } : {}),
1181311826
});
1181411827
assert.lengthOf(
1181511828
continuationRequests,
@@ -11823,13 +11836,30 @@ describe("AcpAdapterV2", () => {
1182311836
nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
1182411837
});
1182511838
let terminalStatus: string | null = null;
11839+
let backgroundItem: ProviderAdapter.ProviderAdapterV2Event | undefined;
1182611840
while (terminalStatus === null) {
1182711841
const event = yield* Queue.take(events);
11842+
if (
11843+
event.type === "turn_item.updated" &&
11844+
event.turnItem.nativeItemRef?.nativeId === "tool-call-monitor-late"
11845+
) {
11846+
backgroundItem = event;
11847+
}
1182811848
if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
1182911849
terminalStatus = event.status;
1183011850
}
1183111851
}
1183211852
assert.equal(terminalStatus, "completed");
11853+
if (defer) {
11854+
assert.equal(backgroundItem?.type, "turn_item.updated");
11855+
if (backgroundItem?.type === "turn_item.updated") {
11856+
assert.equal(backgroundItem.turnItem.status, status);
11857+
assert.equal(backgroundItem.turnItem.type, "command_execution");
11858+
if (backgroundItem.turnItem.type === "command_execution") {
11859+
assert.include(backgroundItem.turnItem.output ?? "", "EARLY_BG_DONE");
11860+
}
11861+
}
11862+
}
1183311863
assert.lengthOf(
1183411864
continuationRequests,
1183511865
1,

‎packages/provider-acp/src/server/adapter.ts‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,11 @@ interface ActiveAcpTurn {
11631163
readonly pendingSubagentNotifications: Map<string, Array<EffectAcpSchema.SessionNotification>>;
11641164
/** Background monitor/task id → toolCallId for synthetic root text updates. */
11651165
readonly toolCallIdsByBackgroundTaskId: Map<string, string>;
1166+
/** Command ends retained until prompt settlement, without marking them reported. */
1167+
readonly backgroundCommandCompletions: Map<
1168+
string,
1169+
{ readonly status: "completed" | "failed"; readonly output?: string }
1170+
>;
11661171
/**
11671172
* Persistent monitors registered this turn. Excluded from deferred-finalize
11681173
* holds so the root turn can settle while they keep streaming post-settle.
@@ -3104,9 +3109,19 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
31043109
yield* closeTextStream(context, "user");
31053110
const previous = context.tools.get(incoming.toolCallId);
31063111
const merged = mergeToolCallState(previous, incoming);
3107-
const toolCall = flavor.normalizeToolCall?.(merged) ?? merged;
3112+
const normalized = flavor.normalizeToolCall?.(merged) ?? merged;
3113+
const backgroundTaskId = flavor.extractBackgroundTaskId?.(normalized);
3114+
const completion =
3115+
context.promptSettled && backgroundTaskId !== undefined
3116+
? context.backgroundCommandCompletions.get(backgroundTaskId)
3117+
: undefined;
3118+
// A start ACK can still normalize to running after the task ended.
3119+
const toolCall =
3120+
completion !== undefined &&
3121+
(normalized.status === "pending" || normalized.status === "inProgress")
3122+
? { ...normalized, status: completion.status }
3123+
: normalized;
31083124
context.tools.set(toolCall.toolCallId, toolCall);
3109-
const backgroundTaskId = flavor.extractBackgroundTaskId?.(toolCall);
31103125
if (backgroundTaskId !== undefined) {
31113126
context.toolCallIdsByBackgroundTaskId.set(backgroundTaskId, toolCall.toolCallId);
31123127
if (flavor.isPersistentBackgroundTool?.(toolCall) === true) {
@@ -3863,10 +3878,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
38633878

38643879
// A structured task end (Grok `task_completed`) is authoritative for the
38653880
// tool that registered the task: its own updates only ever say running.
3866-
// Finish the row while deferred finalize holds a settled root turn open
3867-
// for it, so the turn can settle. While the prompt is still open the
3868-
// agent reports the end itself (TaskOutput hydration), and an unreported
3869-
// end must keep its post-finalize continuation offer.
3881+
// Retain early ends until settlement: closing them via emitTool while
3882+
// the prompt is open would mark an unreported result as handled and
3883+
// suppress its post-finalize continuation.
38703884
const finishRegisteredBackgroundTool = Effect.fnUntraced(function* (mutation: {
38713885
readonly taskId: string;
38723886
readonly status: "completed" | "failed";
@@ -5978,6 +5992,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
59785992
}
59795993
yield* applyLateBackgroundMutation(mutation.sessionId, mutation);
59805994
if (mutation.status !== "running") {
5995+
if (mutation.report?.kind === "command") {
5996+
const context = yield* Ref.get(activeTurn);
5997+
if (context !== null && !context.finalized) {
5998+
context.backgroundCommandCompletions.set(mutation.taskId, {
5999+
status: mutation.status,
6000+
...(mutation.output === undefined ? {} : { output: mutation.output }),
6001+
});
6002+
}
6003+
}
59816004
yield* finishRegisteredBackgroundTool({
59826005
taskId: mutation.taskId,
59836006
status: mutation.status,
@@ -7024,6 +7047,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
70247047
subagentsBySessionId: new Map(),
70257048
pendingSubagentNotifications: new Map(),
70267049
toolCallIdsByBackgroundTaskId: new Map(),
7050+
backgroundCommandCompletions: new Map(),
70277051
persistentBackgroundTaskIds: new Set(),
70287052
awaitingBackgroundHydration: new Set(),
70297053
pendingInjectedReport: new Set(),
@@ -7191,6 +7215,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
71917215
? "interrupted"
71927216
: "cancelled"
71937217
: "completed";
7218+
if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) {
7219+
context.promptSettled = true;
7220+
context.promptSettledStatus = status;
7221+
for (const [taskId, completion] of context.backgroundCommandCompletions) {
7222+
yield* finishRegisteredBackgroundTool({ taskId, ...completion });
7223+
}
7224+
}
71947225
// Grok monitors (and async subagents) keep working after the root
71957226
// prompt RPC returns. Defer finalize so their later updates and
71967227
// wake-turn traffic still project onto this run.
@@ -7199,8 +7230,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
71997230
!context.interrupted &&
72007231
hasDeferredBackgroundWork(context)
72017232
) {
7202-
context.promptSettled = true;
7203-
context.promptSettledStatus = status;
72047233
// The agent finished this prompt's reply. Background work
72057234
// holds the run open, not the text it already sent.
72067235
yield* closeTextStreams(context);

0 commit comments

Comments
 (0)