Skip to content

Commit 7794550

Browse files
fix(provider-grok): close background shells when Grok 1.0.50 finishes them
Grok 1.0.50 reports task_backgrounded and task_completed on _x.ai/session/update, and names the shell call-<uuid>-N. T3 still listened only for x.ai/task_* and only accepted bare UUID task ids, so the shell stayed in progress and deferred finalize never closed the turn.
1 parent ec80933 commit 7794550

4 files changed

Lines changed: 370 additions & 38 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { applyTerminalProjectedToolStatus } from "./adapter.ts";
4+
import type { AcpToolCallState } from "./runtimeModel.ts";
5+
6+
const backgroundShell: AcpToolCallState = {
7+
toolCallId: "call-3e89cd85-00b8-4678-acaf-d4d13afe3289-36",
8+
status: "inProgress",
9+
data: {
10+
rawOutput: {
11+
type: "BackgroundTaskStarted",
12+
task_id: "call-3e89cd85-00b8-4678-acaf-d4d13afe3289-36",
13+
},
14+
},
15+
};
16+
17+
describe("applyTerminalProjectedToolStatus", () => {
18+
it("keeps a terminal projection when normalize left the shell running", () => {
19+
expect(applyTerminalProjectedToolStatus(backgroundShell, "failed").status).toBe("failed");
20+
expect(applyTerminalProjectedToolStatus(backgroundShell, "completed").status).toBe("completed");
21+
expect(applyTerminalProjectedToolStatus(backgroundShell, "failed").data).toBe(
22+
backgroundShell.data,
23+
);
24+
});
25+
26+
it("leaves non-terminal projections to normalize", () => {
27+
expect(applyTerminalProjectedToolStatus(backgroundShell, undefined)).toBe(backgroundShell);
28+
expect(applyTerminalProjectedToolStatus(backgroundShell, "interrupted")).toBe(backgroundShell);
29+
expect(applyTerminalProjectedToolStatus(backgroundShell, "running")).toBe(backgroundShell);
30+
});
31+
});

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

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,6 +1065,22 @@ function toolStatus(
10651065

10661066
type ProjectedToolStatus = ReturnType<typeof toolStatus> | "interrupted";
10671067

1068+
/**
1069+
* A terminal projection is the caller's decision that the tool ended.
1070+
* Grok's normalize forces a `BackgroundTaskStarted` shell back to inProgress;
1071+
* storing that leaves deferred finalize holding the turn after `task_completed`.
1072+
* `interrupted` stays off the stored status: turn teardown already projects it,
1073+
* and the ACP tool state has no interrupted variant.
1074+
*/
1075+
export function applyTerminalProjectedToolStatus(
1076+
toolCall: AcpToolCallState,
1077+
projectedStatus: ProjectedToolStatus | undefined,
1078+
): AcpToolCallState {
1079+
if (projectedStatus !== "completed" && projectedStatus !== "failed") return toolCall;
1080+
if (toolCall.status === projectedStatus) return toolCall;
1081+
return { ...toolCall, status: projectedStatus };
1082+
}
1083+
10681084
function nodeStatus(status: ProjectedToolStatus): OrchestrationV2ExecutionNode["status"] {
10691085
return status === "pending" ? "running" : status;
10701086
}
@@ -3100,7 +3116,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
31003116
yield* closeTextStream(context, "user");
31013117
const previous = context.tools.get(incoming.toolCallId);
31023118
const merged = mergeToolCallState(previous, incoming);
3103-
const toolCall = flavor.normalizeToolCall?.(merged) ?? merged;
3119+
const toolCall = applyTerminalProjectedToolStatus(
3120+
flavor.normalizeToolCall?.(merged) ?? merged,
3121+
projectedStatus,
3122+
);
31043123
context.tools.set(toolCall.toolCallId, toolCall);
31053124
const backgroundTaskId = flavor.extractBackgroundTaskId?.(toolCall);
31063125
if (backgroundTaskId !== undefined) {
@@ -3209,7 +3228,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
32093228
backgroundCompletion.appendOutput,
32103229
)
32113230
: { ...target, status: nextStatus };
3212-
yield* emitTool(context, hydrated);
3231+
yield* emitTool(
3232+
context,
3233+
hydrated,
3234+
// Empty TaskOutput keeps the start-ACK rawOutput, and normalize
3235+
// would put the shell back to inProgress. The poll's terminal
3236+
// status has to stick or the row spins after the command ended.
3237+
nextStatus === "failed" || nextStatus === "completed" ? nextStatus : undefined,
3238+
);
32133239
}
32143240
}
32153241

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

Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,78 @@ describe("XAiAcpExtension", () => {
704704
]);
705705
});
706706

707+
it("hydrates a Grok 1.0.50 background shell whose task id is the tool call id", () => {
708+
// Recorded from Grok 1.0.50 `_x.ai/session/update` plus the following
709+
// TaskOutput (session 01a11ff6-ad09). The id is `call-<uuid>-<n>`, not a
710+
// bare UUID, and the shell's own tool update stays a start ACK.
711+
const taskId = "call-3e89cd85-00b8-4678-acaf-d4d13afe3289-36";
712+
const started = {
713+
toolCallId: taskId,
714+
title: "Run schema and file MIME tests",
715+
status: "completed" as const,
716+
data: {
717+
rawOutput: {
718+
type: "BackgroundTaskStarted",
719+
task_id: taskId,
720+
},
721+
},
722+
};
723+
expect(extractXAiMonitorTaskId(started)).toBe(taskId);
724+
expect(normalizeXAiAcpToolCallState(started).status).toBe("inProgress");
725+
const polled = {
726+
toolCallId: "call-get-shell",
727+
title: "get_command_or_subagent_output",
728+
status: "completed" as const,
729+
data: {
730+
rawInput: {
731+
variant: "TaskOutput",
732+
task_id: taskId,
733+
},
734+
rawOutput: {
735+
type: "TaskOutput",
736+
Result: {
737+
task_id: taskId,
738+
status: "failed",
739+
exit_code: 101,
740+
output: "error: could not compile `forward`\n",
741+
},
742+
},
743+
},
744+
};
745+
expect(extractXAiBackgroundTaskCompletion(polled)).toEqual([
746+
{
747+
taskId,
748+
status: "failed",
749+
appendOutput: "error: could not compile `forward`",
750+
},
751+
]);
752+
// A shell poll must not open a phantom subagent for the tool-call id.
753+
expect(extractXAiAcpSubagentUpdate(polled)).toBeUndefined();
754+
expect(
755+
extractXAiBackgroundTaskCompletion({
756+
...polled,
757+
data: {
758+
rawOutput: {
759+
type: "Text",
760+
text: [
761+
`=== Task ${taskId} ===`,
762+
"Status: failed",
763+
"Exit Code: 101",
764+
"=== Output ===",
765+
"error: could not compile",
766+
].join("\n"),
767+
},
768+
},
769+
}),
770+
).toEqual([
771+
{
772+
taskId,
773+
status: "failed",
774+
appendOutput: "error: could not compile",
775+
},
776+
]);
777+
});
778+
707779
it("hydrates every requested monitor when TaskOutput has no result task_id", () => {
708780
expect(
709781
extractXAiBackgroundTaskCompletion({
@@ -1571,6 +1643,142 @@ describe("XAiAcpExtension", () => {
15711643
}),
15721644
);
15731645

1646+
it.effect(
1647+
"finishes background shells from _x.ai/session/update without dropping subagent_finished",
1648+
() =>
1649+
Effect.gen(function* () {
1650+
const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();
1651+
let capturedMeta: Record<string, unknown> | null | undefined;
1652+
const hungPrompt = yield* Deferred.make<never>();
1653+
const baseRuntime = {
1654+
start: () =>
1655+
Effect.succeed({
1656+
sessionId: "root-session",
1657+
initializeResult: {},
1658+
sessionSetupResult: {},
1659+
modelConfigId: undefined,
1660+
}),
1661+
prompt: (payload: { readonly _meta?: Record<string, unknown> | null }) => {
1662+
capturedMeta = payload._meta ?? null;
1663+
return Deferred.await(hungPrompt);
1664+
},
1665+
cancel: Effect.void,
1666+
handleExtNotification: (
1667+
method: string,
1668+
_schema: unknown,
1669+
handler: (notification: unknown) => Effect.Effect<void>,
1670+
) => {
1671+
handlers.set(method, handler);
1672+
return Effect.void;
1673+
},
1674+
} as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"];
1675+
const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime);
1676+
const mutations: Array<unknown> = [];
1677+
const notices: Array<unknown> = [];
1678+
// Same order as registerGrokAcpExtensions. The second registration must
1679+
// not replace the first, and a schema miss in one must not skip the other.
1680+
yield* registerXAiBackgroundTaskTracking(runtime, (mutation) =>
1681+
Effect.sync(() => mutations.push(mutation)),
1682+
);
1683+
yield* registerXAiSubagentFinished(runtime, (notice) =>
1684+
Effect.sync(() => notices.push(notice)),
1685+
);
1686+
const sessionUpdate = handlers.get("_x.ai/session/update")!;
1687+
const taskId = "call-3e89cd85-00b8-4678-acaf-d4d13afe3289-36";
1688+
1689+
yield* sessionUpdate({
1690+
sessionId: "root-session",
1691+
update: {
1692+
sessionUpdate: "subagent_finished",
1693+
child_session_id: "child-session",
1694+
status: "completed",
1695+
output: "SUBAGENT_DONE",
1696+
// Poison for the task schema only. Excess on the subagent schema.
1697+
task_snapshot: { exit_code: "nope" },
1698+
},
1699+
});
1700+
expect(notices).toEqual([
1701+
{
1702+
sessionId: "root-session",
1703+
childSessionId: "child-session",
1704+
status: "completed",
1705+
result: "SUBAGENT_DONE",
1706+
},
1707+
]);
1708+
expect(mutations).toEqual([]);
1709+
1710+
yield* sessionUpdate({
1711+
sessionId: "root-session",
1712+
update: {
1713+
sessionUpdate: "task_backgrounded",
1714+
tool_call_id: taskId,
1715+
task_id: taskId,
1716+
command: "cargo test -p forward --lib",
1717+
cwd: "/tmp/worktree",
1718+
output_file: "/tmp/cargo.log",
1719+
description: "Run schema and file MIME tests",
1720+
},
1721+
});
1722+
yield* sessionUpdate({
1723+
sessionId: "root-session",
1724+
update: {
1725+
sessionUpdate: "task_completed",
1726+
will_wake: false,
1727+
task_snapshot: {
1728+
task_id: taskId,
1729+
command: "cargo test -p forward --lib",
1730+
cwd: "/tmp/worktree",
1731+
start_time: { secs_since_epoch: 1791537832, nanos_since_epoch: 0 },
1732+
end_time: { secs_since_epoch: 1791537905, nanos_since_epoch: 0 },
1733+
output: "error: could not compile `forward`\n",
1734+
output_file: "/tmp/cargo.log",
1735+
truncated: true,
1736+
output_total_bytes: 47221,
1737+
exit_code: 101,
1738+
signal: null,
1739+
completed: true,
1740+
kind: "bash",
1741+
block_waited: true,
1742+
explicitly_killed: false,
1743+
kill_result_delivered: false,
1744+
owner_session_id: "root-session",
1745+
description: "Run schema and file MIME tests",
1746+
is_backgrounded: true,
1747+
},
1748+
},
1749+
});
1750+
expect(mutations).toMatchObject([
1751+
{ sessionId: "root-session", taskId, status: "running" },
1752+
{
1753+
sessionId: "root-session",
1754+
taskId,
1755+
status: "failed",
1756+
output: "error: could not compile `forward`\n",
1757+
report: { kind: "command", exitCode: 101 },
1758+
},
1759+
]);
1760+
1761+
const promptFiber = yield* runtime
1762+
.prompt({ prompt: [{ type: "text", text: "hi" }] })
1763+
.pipe(Effect.forkChild);
1764+
yield* Effect.yieldNow;
1765+
yield* sessionUpdate({
1766+
sessionId: "root-session",
1767+
update: {
1768+
sessionUpdate: "turn_completed",
1769+
prompt_id: capturedMeta?.promptId,
1770+
stop_reason: "end_turn",
1771+
usage: { inputTokens: 1, outputTokens: 2, totalTokens: 3 },
1772+
elapsed_ms: 10,
1773+
},
1774+
});
1775+
const response = yield* Fiber.join(promptFiber);
1776+
expect(response.stopReason).toBe("end_turn");
1777+
expect(notices).toHaveLength(1);
1778+
expect(mutations).toHaveLength(2);
1779+
}),
1780+
);
1781+
15741782
it.effect("settles a hung prompt from _x.ai/session/update turn_completed", () =>
15751783
Effect.gen(function* () {
15761784
const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();

0 commit comments

Comments
 (0)