Skip to content
TypeScript

fix(provider-acp): retain Grok command completion before prompt settles (#19938)

3xcalibure294a38a106a
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index cbc0ee419ea..c01ee82e55f 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -92,7 +92,7 @@ import {
type AcpAdapterV2SubagentUpdate,
} from "@t3tools/provider-acp/server/adapter";
-import { makeGrokAdapterV2 } from "@t3tools/provider-grok/testing";
+import { makeGrokAdapterV2, makeGrokAcpAdapterFlavor } from "@t3tools/provider-grok/testing";
import {
acpRegistryPromptFailure,
registerMistralVibeAcpExtensions,
@@ -11899,6 +11899,227 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
+ it.effect.each([
+ { status: "completed" as const, exitCode: 0 },
+ { status: "failed" as const, exitCode: 1 },
+ ])(
+ "retains early Grok $status command completion across sparse notifications and replayed ACKs",
+ ({ status, exitCode }) =>
+ Effect.gen(function* () {
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const path = yield* Path.Path;
+ const selfInvocation = yield* resolveSelfInvocation();
+ const mockAgentPath = yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
+ );
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
+ let taskCompleted:
+ | ((payload: unknown) => Effect.Effect<void, EffectAcpErrors.AcpError>)
+ | undefined;
+ const promptStarted = yield* Deferred.make<void>();
+ const promptGate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
+ const promptHeld = yield* Deferred.make<void>();
+ const finalizeScheduled = yield* Deferred.make<Duration.Input>();
+ const continuationOffered = yield* Deferred.make<void>();
+ const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
+ [];
+ const instanceId = ProviderInstanceId.make("acp-test");
+ const grokFlavor = makeGrokAcpAdapterFlavor(
+ {
+ instanceId,
+ settings: DEFAULT_GROK_SETTINGS,
+ environment: {},
+ hostPlatform: yield* HostProcess.Platform,
+ selfInvocation,
+ },
+ yield* HostProcess.HomeDirectory,
+ );
+ const adapter = yield* makeAcpAdapterV2({
+ instanceId,
+ selfInvocation,
+ testHooks: {
+ afterPromptSettledWithBackgroundWork: () =>
+ Deferred.succeed(promptHeld, undefined).pipe(Effect.asVoid),
+ onDeferredFinalizeScheduled: (debounce) =>
+ Deferred.succeed(finalizeScheduled, debounce).pipe(Effect.asVoid),
+ },
+ flavor: {
+ driver: ACP_TEST_DRIVER,
+ capabilities: AcpProviderCapabilitiesV2,
+ enablePostSettleContinuation: true,
+ deferFinalizeForBackgroundWork: true,
+ normalizeToolCall: grokFlavor.normalizeToolCall!,
+ extractBackgroundTaskId: grokFlavor.extractBackgroundTaskId!,
+ isBackgroundCommandTool: grokFlavor.isBackgroundCommandTool!,
+ registerExtensions: ({ runtime, applyBackgroundTaskMutation }) =>
+ registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation),
+ makeRuntime: makeMockRuntime({
+ childProcessSpawner,
+ mockAgentPath,
+ wrapRuntime: (runtime) => ({
+ ...runtime,
+ handleSessionUpdate: (handler) =>
+ Effect.sync(() => {
+ sessionUpdateHandler = handler;
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
+ handleExtNotification: (method, schema, handler) =>
+ Effect.sync(() => {
+ if (method === "x.ai/task_completed") {
+ taskCompleted = (payload) =>
+ handler(Schema.decodeUnknownSync(schema)(payload));
+ }
+ }).pipe(Effect.andThen(runtime.handleExtNotification(method, schema, handler))),
+ prompt: () =>
+ Deferred.succeed(promptStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(promptGate)),
+ ),
+ }),
+ }),
+ },
+ continuationRequests: {
+ offer: (request) =>
+ Effect.sync(() => continuationRequests.push(request)).pipe(
+ Effect.andThen(Deferred.succeed(continuationOffered, undefined)),
+ Effect.asVoid,
+ ),
+ },
+ });
+ const threadId = ThreadId.make("thread-acp-early-command");
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: process.cwd(),
+ });
+ const modelSelection = { instanceId, model: "default" } as const;
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-acp-early-command"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
+ yield* runtime.events.pipe(
+ Stream.runForEach((event) => Queue.offer(events, event)),
+ Effect.forkScoped,
+ );
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ const now = yield* DateTime.now;
+ yield* runtime
+ .startTurn(
+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
+ )
+ .pipe(Effect.forkScoped);
+ yield* Deferred.await(promptStarted);
+ assert.isDefined(sessionUpdateHandler);
+ assert.isDefined(taskCompleted);
+ const update = (update: EffectAcpSchema.SessionUpdate) =>
+ sessionUpdateHandler!({ sessionId: "mock-session-1", update });
+ const complete = (taskId: string, snapshot?: { output?: string; exit_code?: number }) =>
+ taskCompleted!({
+ sessionId: "mock-session-1",
+ update: { sessionUpdate: "task_completed", task_id: taskId, task_snapshot: snapshot },
+ });
+ for (const taskId of ["early", "blocker"]) {
+ yield* update({
+ sessionUpdate: "tool_call",
+ toolCallId: taskId,
+ title: `Run ${taskId}`,
+ kind: "execute",
+ status: "completed",
+ rawInput: { command: `echo ${taskId}` },
+ rawOutput: { type: "BackgroundTaskStarted", task_id: taskId },
+ });
+ }
+ // Progress removes the ACK carrying the task identity before a reportless completion.
+ yield* update({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "early",
+ status: "in_progress",
+ rawOutput: { type: "Text", text: "Command progress" },
+ });
+ yield* complete("early", { exit_code: exitCode, output: "EARLY_BG_DONE\n" });
+ // The real decoder treats this exit-code-free duplicate as completed, even after failure.
+ yield* complete("early");
+ assert.lengthOf(continuationRequests, 0);
+
+ let backgroundItem: ProviderAdapter.ProviderAdapterV2Event | undefined;
+ let checkpoint = 0;
+ const assertCommand = Effect.fnUntraced(function* (expectedStatus: string, output: string) {
+ const title = `Checkpoint ${++checkpoint}`;
+ // A later tool event fences the emitted updates without waiting for a terminal that may never come.
+ yield* update({ sessionUpdate: "tool_call_update", toolCallId: "blocker", title });
+ while (true) {
+ const event = yield* Queue.take(events);
+ if (event.type !== "turn_item.updated") continue;
+ if (event.turnItem.nativeItemRef?.nativeId === "early") backgroundItem = event;
+ if (
+ event.turnItem.nativeItemRef?.nativeId === "blocker" &&
+ event.turnItem.title === title
+ )
+ break;
+ }
+ assert.equal(backgroundItem?.type, "turn_item.updated");
+ if (backgroundItem?.type !== "turn_item.updated") return;
+ assert.equal(backgroundItem.turnItem.status, expectedStatus);
+ assert.equal(backgroundItem.turnItem.type, "command_execution");
+ if (backgroundItem.turnItem.type === "command_execution") {
+ assert.equal(backgroundItem.turnItem.output ?? "", output);
+ }
+ });
+ yield* Deferred.succeed(promptGate, { stopReason: "end_turn" });
+ yield* Deferred.await(promptHeld);
+ yield* assertCommand(status, "EARLY_BG_DONE\n");
+ assert.lengthOf(continuationRequests, 0, "the other command still holds the root open");
+
+ const replayAck = () =>
+ update({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "early",
+ status: "completed",
+ rawOutput: { type: "BackgroundTaskStarted", task_id: "early" },
+ });
+ yield* replayAck();
+ yield* assertCommand(status, "EARLY_BG_DONE\n");
+ // Sparse ACP updates must retain the command result after projection replaces the ACK.
+ for (const sparseStatus of ["completed", "in_progress"] as const) {
+ yield* update({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "early",
+ status: sparseStatus,
+ });
+ yield* assertCommand(status, "EARLY_BG_DONE\n");
+ }
+ if (status === "completed") {
+ for (const output of ["", "UPDATED_OUTPUT\n"]) {
+ yield* complete("early", { output });
+ yield* replayAck();
+ yield* assertCommand(status, output);
+ }
+ }
+ yield* complete("blocker", { exit_code: 0, output: "BLOCKER_DONE\n" });
+ yield* TestClock.adjust(yield* Deferred.await(finalizeScheduled));
+ while (true) {
+ const event = yield* Queue.take(events);
+ if (event.type !== "turn.terminal") continue;
+ assert.equal(event.status, "completed");
+ break;
+ }
+ yield* Deferred.await(continuationOffered);
+ yield* complete("early");
+ yield* complete("blocker");
+ assert.lengthOf(
+ continuationRequests,
+ 1,
+ "duplicate completions must not offer another continuation",
+ );
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
it.effect("empty-drain continuation turn waits the quiet window so late frames can attach", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 3c145c3ac96..c229e7e3143 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -299,6 +299,8 @@ export interface AcpAdapterV2Flavor {
readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState;
readonly extractProposedPlanMarkdown?: (toolCall: AcpToolCallState) => string | undefined;
readonly extractBackgroundTaskId?: (toolCall: AcpToolCallState) => string | undefined;
+ /** Distinguishes commands from monitors when lifecycle notifications omit their kind. */
+ readonly isBackgroundCommandTool?: (toolCall: AcpToolCallState) => boolean;
readonly extractBackgroundToolMutation?: (text: string) => ReadonlyArray<{
readonly taskId: string;
readonly status: "running" | "completed" | "failed";
@@ -1028,13 +1030,18 @@ interface ActiveAcpTurn {
| undefined;
contextUsage: ThreadTokenUsageSnapshot | null;
nativeMetadata: OrchestrationV2ProviderThreadNativeMetadata | null;
- readonly tools: Map<string, AcpToolCallState>;
+ readonly tools: Map<string, AcpToolCallState & { readonly backgroundCommandTaskId?: string }>;
readonly toolUpdatesSkipped: Map<string, number>;
readonly toolStartedAt: Map<string, DateTime.Utc>;
readonly subagents: Map<string, ActiveAcpSubagent>;
readonly subagentsBySessionId: Map<string, ActiveAcpSubagent>;
readonly pendingSubagentNotifications: Map<string, Array<EffectAcpSchema.SessionNotification>>;
readonly toolCallIdsByBackgroundTaskId: Map<string, string>;
+ /** Command ACKs register null; terminal results wait here for prompt settlement. */
+ readonly backgroundCommands: Map<
+ string,
+ { readonly status: "completed" | "failed"; readonly output?: string } | null
+ >;
readonly persistentBackgroundTaskIds: Set<string>;
/**
* Monitor end events often only say "use get_command…"; keep the turn open
@@ -3402,8 +3409,38 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* closeTextStream(context, "user");
const previous = context.tools.get(incoming.toolCallId);
const merged = mergeToolCallState(previous, incoming);
- const toolCall = flavor.normalizeToolCall?.(merged) ?? merged;
- context.tools.set(toolCall.toolCallId, toolCall);
+ const normalized = flavor.normalizeToolCall?.(merged) ?? merged;
+ const backgroundTaskId = flavor.extractBackgroundTaskId?.(normalized);
+ const backgroundCommandTaskId =
+ flavor.isBackgroundCommandTool?.(normalized) === true
+ ? backgroundTaskId
+ : previous?.backgroundCommandTaskId;
+ if (
+ backgroundCommandTaskId !== undefined &&
+ !context.backgroundCommands.has(backgroundCommandTaskId)
+ ) {
+ context.backgroundCommands.set(backgroundCommandTaskId, null);
+ }
+ const completion =
+ context.promptSettled && backgroundCommandTaskId !== undefined
+ ? (context.backgroundCommands.get(backgroundCommandTaskId) ?? undefined)
+ : undefined;
+ // Preserve hydrated output; only a replayed start ACK needs its output restored.
+ const toolCall =
+ completion === undefined
+ ? normalized
+ : {
+ ...(backgroundTaskId === undefined || completion.output === undefined
+ ? normalized
+ : setToolOutputText(normalized, completion.output)),
+ status: completion.status,
+ };
+ context.tools.set(
+ toolCall.toolCallId,
+ backgroundCommandTaskId === undefined
+ ? toolCall
+ : { ...toolCall, backgroundCommandTaskId },
+ );
if (
followsAgentWorkState &&
projectedStatus === undefined &&
@@ -3412,7 +3449,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* rearmDeferredFinalize(context);
return;
}
- const backgroundTaskId = flavor.extractBackgroundTaskId?.(toolCall);
if (backgroundTaskId !== undefined) {
context.toolCallIdsByBackgroundTaskId.set(backgroundTaskId, toolCall.toolCallId);
if (flavor.isPersistentBackgroundTool?.(toolCall) === true) {
@@ -4107,8 +4143,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
}
});
- // A structured task end (Grok `task_completed`) is authoritative for the
- // tool that registered the task: its own updates only ever say running.
+ // Structured task ends are authoritative, but emitting before prompt
+ // settlement marks the result handled and suppresses its continuation.
const finishRegisteredBackgroundTool = Effect.fnUntraced(function* (mutation: {
readonly taskId: string;
readonly status: "completed" | "failed";
@@ -4120,7 +4156,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const tool = toolCallId === undefined ? undefined : context.tools.get(toolCallId);
if (tool === undefined) return;
const status = toolStatus(tool.status);
- if (status !== "pending" && status !== "running") return;
+ if (
+ status !== "pending" &&
+ status !== "running" &&
+ !context.backgroundCommands.has(mutation.taskId)
+ ) {
+ return;
+ }
context.awaitingBackgroundHydration.delete(mutation.taskId);
const finished = { ...tool, status: mutation.status };
yield* emitTool(
@@ -6166,12 +6208,37 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* finishSubagentFromNotice(notice);
}),
).pipe(Effect.asVoid),
- applyBackgroundTaskMutation: (mutation) =>
+ applyBackgroundTaskMutation: (incoming) =>
runRuntimeCallbackAtGeneration(
handlerGeneration,
Effect.gen(function* () {
if (yield* Ref.get(stoppedRunQuarantine)) return;
- if ((yield* Ref.get(activeSessionId)) !== mutation.sessionId) return;
+ if ((yield* Ref.get(activeSessionId)) !== incoming.sessionId) return;
+ const context = yield* Ref.get(activeTurn);
+ let mutation = incoming;
+ if (
+ incoming.status !== "running" &&
+ context !== null &&
+ !context.finalized &&
+ (incoming.report?.kind === "command" ||
+ context.backgroundCommands.has(incoming.taskId))
+ ) {
+ const previous = context.backgroundCommands.get(incoming.taskId);
+ const toolCallId = context.toolCallIdsByBackgroundTaskId.get(incoming.taskId);
+ const tool =
+ toolCallId === undefined ? undefined : context.tools.get(toolCallId);
+ const output =
+ incoming.output ??
+ previous?.output ??
+ (tool === undefined ? undefined : toolOutputText(tool));
+ // Missing exit codes decode as success; they cannot undo a known failure.
+ const completion = {
+ status: previous?.status === "failed" ? "failed" : incoming.status,
+ ...(output === undefined ? {} : { output }),
+ };
+ context.backgroundCommands.set(incoming.taskId, completion);
+ mutation = { ...incoming, ...completion };
+ }
if (
mutation.status !== "running" &&
mutation.report !== undefined &&
@@ -7212,6 +7279,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
subagentsBySessionId: new Map(),
pendingSubagentNotifications: new Map(),
toolCallIdsByBackgroundTaskId: new Map(),
+ backgroundCommands: new Map(),
persistentBackgroundTaskIds: new Set(),
awaitingBackgroundHydration: new Set(),
pendingInjectedReport: new Set(),
@@ -7387,13 +7455,19 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
? "interrupted"
: "cancelled"
: "completed";
+ if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) {
+ context.promptSettled = true;
+ context.promptSettledStatus = status;
+ for (const [taskId, completion] of context.backgroundCommands) {
+ if (completion === null) continue;
+ yield* finishRegisteredBackgroundTool({ taskId, ...completion });
+ }
+ }
if (
flavor.deferFinalizeForBackgroundWork === true &&
!context.interrupted &&
hasDeferredBackgroundWork(context)
) {
- context.promptSettled = true;
- context.promptSettledStatus = status;
yield* closeTextStreams(context);
yield* (
options.testHooks?.afterPromptSettledWithBackgroundWork?.() ?? Effect.void
diff --git a/packages/provider-grok/src/server/adapter.ts b/packages/provider-grok/src/server/adapter.ts
index 6b7ec52ed8e..aafbaeb2d99 100644
--- a/packages/provider-grok/src/server/adapter.ts
+++ b/packages/provider-grok/src/server/adapter.ts
@@ -43,6 +43,7 @@ import {
extractXAiBackgroundTaskCompletion,
extractXAiKilledBackgroundTasks,
extractXAiMonitorTaskId,
+ xAiBackgroundShellTaskId,
isXAiPersistentMonitor,
extractXAiExitPlanMarkdown,
registerXAiSubagentFinished,
@@ -323,6 +324,7 @@ export function makeGrokAcpAdapterFlavor(
homeDirectory,
}),
extractBackgroundTaskId: extractXAiMonitorTaskId,
+ isBackgroundCommandTool: (toolCall) => xAiBackgroundShellTaskId(toolCall) !== undefined,
extractBackgroundToolMutation: extractXAiAcpBackgroundToolMutation,
extractBackgroundTaskCompletion: (toolCall) => [
...extractXAiBackgroundTaskCompletion(toolCall),
diff --git a/packages/provider-grok/src/server/xaiAcpExtension.ts b/packages/provider-grok/src/server/xaiAcpExtension.ts
index 56fe64142d6..2ad11521abb 100644
--- a/packages/provider-grok/src/server/xaiAcpExtension.ts
+++ b/packages/provider-grok/src/server/xaiAcpExtension.ts
@@ -275,7 +275,7 @@ export function isXAiMonitorTool(toolCall: AcpToolCallState): boolean {
* while the process still runs. Like a monitor, it ends only with
* `x.ai/task_completed` for that task id.
*/
-function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined {
+export function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined {
const rawOutput = unknownRecord(toolCall.data.rawOutput);
return nonEmptyString(rawOutput?.type) === "BackgroundTaskStarted"
? nonEmptyString(rawOutput?.task_id)