Skip to content

Commit 820ac9c

Browse files
committed
fix(grok): background commands with call-id task IDs no longer hold the run open
1 parent d36b7da commit 820ac9c

4 files changed

Lines changed: 213 additions & 12 deletions

File tree

‎apps/server/scripts/acp-mock-agent.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ const emitPlanThenHang = process.env.T3_ACP_EMIT_PLAN_THEN_HANG === "1";
4949
const emitActiveToolThenHang = process.env.T3_ACP_EMIT_ACTIVE_TOOL_THEN_HANG === "1";
5050
const emitGrokMonitorPostTurnPoll = process.env.T3_ACP_EMIT_GROK_MONITOR_POST_TURN_POLL === "1";
5151
const emitGrokBackgroundTaskStarted = process.env.T3_ACP_EMIT_GROK_BACKGROUND_TASK_STARTED === "1";
52+
const emitGrokBackgroundTaskPoll = process.env.T3_ACP_GROK_BACKGROUND_TASK_COMPLETION === "poll";
5253
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
5354
const waitForResumeRelease = process.env.T3_ACP_WAIT_FOR_RESUME_RELEASE === "1";
5455
const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1";
@@ -1678,13 +1679,15 @@ const program = Effect.gen(function* () {
16781679
return yield* Effect.never;
16791680
}
16801681

1681-
if (emitGrokBackgroundTaskStarted) {
1682-
const toolCallId = "call-fb9d0000-0000-0000-0000-000000000026";
1682+
if (emitGrokBackgroundTaskStarted || emitGrokBackgroundTaskPoll) {
1683+
const toolCallId = !emitGrokBackgroundTaskPoll
1684+
? "call-fb9d0000-0000-0000-0000-000000000026"
1685+
: "call-fb9d0000-0000-0000-0000-000000000026-29";
16831686
const command = "sleep 40; echo done-a";
16841687
writeJsonRpcNotification("session/update", {
16851688
sessionId: requestedSessionId,
16861689
update: {
1687-
sessionUpdate: "tool_call",
1690+
sessionUpdate: !emitGrokBackgroundTaskPoll ? "tool_call" : "tool_call_update",
16881691
toolCallId,
16891692
title: "run_terminal_command",
16901693
kind: "execute",
@@ -1707,6 +1710,46 @@ const program = Effect.gen(function* () {
17071710
},
17081711
},
17091712
});
1713+
if (emitGrokBackgroundTaskPoll) {
1714+
writeJsonRpcNotification("session/update", {
1715+
sessionId: requestedSessionId,
1716+
update: {
1717+
sessionUpdate: "tool_call_update",
1718+
toolCallId: "call-background-poll",
1719+
title: "get_command_or_subagent_output",
1720+
kind: "other",
1721+
status: "completed",
1722+
rawOutput: {
1723+
type: "TaskOutput",
1724+
Result: {
1725+
task_id: toolCallId,
1726+
command,
1727+
status: "completed",
1728+
exit_code: 0,
1729+
output: "done-a",
1730+
},
1731+
},
1732+
},
1733+
});
1734+
1735+
yield* agent.client.sessionUpdate({
1736+
sessionId: requestedSessionId,
1737+
update: {
1738+
sessionUpdate: "agent_message_chunk",
1739+
content: { type: "text", text: "The background command finished." },
1740+
},
1741+
});
1742+
writeJsonRpcNotification("_x.ai/session/update", {
1743+
sessionId: requestedSessionId,
1744+
update: {
1745+
sessionUpdate: "turn_completed",
1746+
prompt_id: promptIdFromRequestMeta(request),
1747+
stop_reason: "end_turn",
1748+
},
1749+
});
1750+
// Neither the prompt RPC nor the process ends, matching the Grok incident.
1751+
return yield* Effect.never;
1752+
}
17101753
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
17111754
sessionId: requestedSessionId,
17121755
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",

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

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3992,6 +3992,95 @@ describe("AcpAdapterV2", () => {
39923992
}).pipe(Effect.provide(layerTest)),
39933993
);
39943994

3995+
// Oracle: Grok incident frames. Command completion must release the turn even
3996+
// when the CLI keeps the prompt RPC and process alive. Command polls stay visible.
3997+
it.live(
3998+
"completes a structured Grok background command from poll with an unanswered prompt RPC",
3999+
() =>
4000+
Effect.gen(function* () {
4001+
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4002+
const path = yield* Path.Path;
4003+
const mockAgentPath = yield* path.fromFileUrl(
4004+
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
4005+
);
4006+
const instanceId = ProviderInstanceId.make("grok-background-completion");
4007+
const adapter = yield* makeGrokAdapterV2({
4008+
instanceId,
4009+
settings: DEFAULT_GROK_SETTINGS,
4010+
environment: {},
4011+
hostPlatform: yield* HostProcess.Platform,
4012+
selfInvocation: yield* resolveSelfInvocation(),
4013+
makeRuntime: (input) =>
4014+
makeMockRuntime({
4015+
childProcessSpawner,
4016+
mockAgentPath,
4017+
environment: { T3_ACP_GROK_BACKGROUND_TASK_COMPLETION: "poll" },
4018+
})(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)),
4019+
});
4020+
const threadId = ThreadId.make("grok-background-completion");
4021+
const modelSelection = { instanceId, model: "default" } as const;
4022+
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4023+
runtimeMode: "full-access",
4024+
interactionMode: "default",
4025+
cwd: process.cwd(),
4026+
});
4027+
const runtime = yield* adapter.openSession({
4028+
threadId,
4029+
providerSessionId: ProviderSessionId.make("grok-background-completion"),
4030+
modelSelection,
4031+
runtimePolicy,
4032+
});
4033+
const providerThread = yield* runtime.ensureThread({
4034+
threadId,
4035+
modelSelection,
4036+
runtimePolicy,
4037+
});
4038+
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
4039+
yield* runtime.events.pipe(
4040+
Stream.runForEach((event) => Queue.offer(events, event)),
4041+
Effect.forkScoped,
4042+
);
4043+
yield* runtime.startTurn(
4044+
makeTurnInput({
4045+
threadId,
4046+
providerThread,
4047+
instanceId,
4048+
runtimePolicy,
4049+
now: yield* DateTime.now,
4050+
}),
4051+
);
4052+
const observed = yield* Stream.fromQueue(events).pipe(
4053+
Stream.takeUntil((event) => event.type === "turn.terminal"),
4054+
Stream.runCollect,
4055+
Effect.timeout("15 seconds"),
4056+
);
4057+
const allEvents = [...observed];
4058+
let next = yield* Queue.poll(events);
4059+
while (Option.isSome(next)) {
4060+
allEvents.push(next.value);
4061+
next = yield* Queue.poll(events);
4062+
}
4063+
const terminals = allEvents.filter((event) => event.type === "turn.terminal");
4064+
assert.deepEqual(
4065+
terminals.map((event) => event.status),
4066+
["completed"],
4067+
);
4068+
const items = allEvents.flatMap((event) =>
4069+
event.type === "turn_item.updated" ? [event.turnItem] : [],
4070+
);
4071+
assert.isFalse(items.some((item) => item.type === "subagent"));
4072+
const command = items.findLast(
4073+
(item) => item.nativeItemRef?.nativeId === "call-fb9d0000-0000-0000-0000-000000000026-29",
4074+
);
4075+
assert.equal(command?.type, "command_execution");
4076+
assert.equal(command?.status, "completed");
4077+
assert.isTrue(
4078+
items.some((item) => item.nativeItemRef?.nativeId === "call-background-poll"),
4079+
"command TaskOutput must retain its normal tool frame",
4080+
);
4081+
}).pipe(Effect.provide(layerTest), Effect.scoped),
4082+
);
4083+
39954084
it.effect.each(["grok-build", "composer-2"])(
39964085
"Grok configures the native session for %s",
39974086
(model) =>

‎packages/provider-grok/src/server/xaiAcpExtension.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,68 @@ describe("XAiAcpExtension", () => {
664664
]);
665665
});
666666

667+
it("completes structured command TaskOutput ids without treating them as subagents", () => {
668+
// Oracle: BackgroundTaskStarted and TaskOutput from the Grok hang incident.
669+
const toolCall: AcpToolCallState = {
670+
toolCallId: "call-poll",
671+
title: "get_command_or_subagent_output",
672+
status: "completed",
673+
data: {
674+
rawInput: {
675+
variant: "TaskOutput",
676+
task_ids: ["call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29"],
677+
},
678+
rawOutput: {
679+
type: "TaskOutput",
680+
Result: {
681+
task_id: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
682+
status: "completed",
683+
exit_code: 0,
684+
output: "done",
685+
},
686+
},
687+
},
688+
};
689+
expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([
690+
{
691+
taskId: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
692+
status: "completed",
693+
appendOutput: "done",
694+
},
695+
]);
696+
expect(extractXAiAcpSubagentUpdate(toolCall)).toBeUndefined();
697+
});
698+
699+
it.each(["", " "])("ignores an empty structured task id %j", (taskId) => {
700+
// An empty result is not a completion identity, even with a terminal status.
701+
expect(
702+
extractXAiBackgroundTaskCompletion({
703+
toolCallId: "call-empty-poll",
704+
status: "completed",
705+
data: {
706+
rawOutput: { type: "TaskOutput", Result: { task_id: taskId, status: "completed" } },
707+
},
708+
}),
709+
).toEqual([]);
710+
});
711+
712+
it("keeps command ids in free-text task headers UUID-only", () => {
713+
// Only structured ids are trusted; prose must retain the existing UUID contract.
714+
expect(
715+
extractXAiBackgroundTaskCompletion({
716+
toolCallId: "call-text-poll",
717+
title: "get_command_or_subagent_output",
718+
status: "completed",
719+
data: {
720+
rawOutput: {
721+
type: "Text",
722+
text: "=== Task call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29 ===\nStatus: completed\n=== Output ===\ndone",
723+
},
724+
},
725+
}),
726+
).toEqual([]);
727+
});
728+
667729
it("hydrates monitor completion from a standalone TaskOutput frame without rawInput", () => {
668730
// Post-settle shape observed live (2026-07-12): the final
669731
// get_command_or_subagent_output update carries only rawOutput; the frame

‎packages/provider-grok/src/server/xaiAcpExtension.ts‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -272,8 +272,8 @@ export function isXAiMonitorTool(toolCall: AcpToolCallState): boolean {
272272
* A shell command Grok runs in the background (asked for, or moved there after
273273
* its auto-background timeout) acknowledges with
274274
* `{ type: "BackgroundTaskStarted", task_id }` and completes its tool call
275-
* while the process still runs. Like a monitor, it ends only with
276-
* `x.ai/task_completed` for that task id.
275+
* while the process still runs. It ends with a task completion notification
276+
* or completed TaskOutput for that task id.
277277
*/
278278
export function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined {
279279
const rawOutput = unknownRecord(toolCall.data.rawOutput);
@@ -333,7 +333,9 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState):
333333
const appendOutput = resultFromGetOutputTool(toolCall, text) ?? "";
334334
// Prefer the completed identity from the result/header over the request list
335335
// (one call can poll multiple task_ids).
336-
const resultTaskId = resultTaskIdFromGetOutputTool(toolCall, text);
336+
// Command task ids can be `call-<uuid>-<index>`; subagent ids stay UUID-only.
337+
const resultTaskId =
338+
structuredTaskIdFromGetOutputTool(toolCall) ?? resultTaskIdFromGetOutputTool(toolCall, text);
337339
if (resultTaskId !== undefined) {
338340
return [{ taskId: resultTaskId, status, appendOutput }];
339341
}
@@ -742,17 +744,22 @@ function taskIdsFromGetOutputTool(
742744
return [...new Set(ids)];
743745
}
744746

745-
function resultTaskIdFromGetOutputTool(
746-
toolCall: AcpToolCallState,
747-
output: string | undefined,
748-
): string | undefined {
747+
function structuredTaskIdFromGetOutputTool(toolCall: AcpToolCallState): string | undefined {
749748
const rawOutput = unknownRecord(toolCall.data.rawOutput);
750749
const result = unknownRecord(rawOutput?.Result) ?? unknownRecord(rawOutput?.result);
751-
const structured =
750+
return (
752751
nonEmptyString(result?.task_id) ??
753752
nonEmptyString(result?.taskId) ??
754753
nonEmptyString(rawOutput?.task_id) ??
755-
nonEmptyString(rawOutput?.taskId);
754+
nonEmptyString(rawOutput?.taskId)
755+
);
756+
}
757+
758+
function resultTaskIdFromGetOutputTool(
759+
toolCall: AcpToolCallState,
760+
output: string | undefined,
761+
): string | undefined {
762+
const structured = structuredTaskIdFromGetOutputTool(toolCall);
756763
if (structured !== undefined && new RegExp(`^${XAI_UUID_RE}$`, "i").test(structured)) {
757764
return structured;
758765
}

0 commit comments

Comments
 (0)