The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 23:15 UTC
fix(provider-acp): retain Grok command completion before prompt settles (#19938)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
3xcalibur committed
Oct 20, 2026 at 08:56 UTC
e294a38a106acca87933d36789a4e0bd28a6e72a
4 files changed
+310
-13
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+222
-1
@@ -92,7 +92,7 @@ import {
92
type AcpAdapterV2SubagentUpdate,
93
} from "@t3tools/provider-acp/server/adapter";
94
95
-import { makeGrokAdapterV2 } from "@t3tools/provider-grok/testing";
95
+import { makeGrokAdapterV2, makeGrokAcpAdapterFlavor } from "@t3tools/provider-grok/testing";
96
import {
97
acpRegistryPromptFailure,
98
registerMistralVibeAcpExtensions,
@@ -11899,6 +11899,227 @@ describe("AcpAdapterV2", () => {
11899
}).pipe(Effect.provide(layerTest), Effect.scoped),
11900
);
11901
11902
+ it.effect.each([
11903
+ { status: "completed" as const, exitCode: 0 },
11904
+ { status: "failed" as const, exitCode: 1 },
11905
+ ])(
11906
+ "retains early Grok $status command completion across sparse notifications and replayed ACKs",
11907
+ ({ status, exitCode }) =>
11908
+ Effect.gen(function* () {
11909
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
11910
+ const path = yield* Path.Path;
11911
+ const selfInvocation = yield* resolveSelfInvocation();
11912
+ const mockAgentPath = yield* path.fromFileUrl(
11913
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
11914
+ );
11915
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
11916
+ let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
11917
+ let taskCompleted:
11918
+ | ((payload: unknown) => Effect.Effect<void, EffectAcpErrors.AcpError>)
11919
+ | undefined;
11920
+ const promptStarted = yield* Deferred.make<void>();
11921
+ const promptGate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
11922
+ const promptHeld = yield* Deferred.make<void>();
11923
+ const finalizeScheduled = yield* Deferred.make<Duration.Input>();
11924
+ const continuationOffered = yield* Deferred.make<void>();
11925
+ const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
11926
+ [];
11927
+ const instanceId = ProviderInstanceId.make("acp-test");
11928
+ const grokFlavor = makeGrokAcpAdapterFlavor(
11929
+ {
11930
+ instanceId,
11931
+ settings: DEFAULT_GROK_SETTINGS,
11932
+ environment: {},
11933
+ hostPlatform: yield* HostProcess.Platform,
11934
+ selfInvocation,
11935
+ },
11936
+ yield* HostProcess.HomeDirectory,
11937
+ );
11938
+ const adapter = yield* makeAcpAdapterV2({
11939
+ instanceId,
11940
+ selfInvocation,
11941
+ testHooks: {
11942
+ afterPromptSettledWithBackgroundWork: () =>
11943
+ Deferred.succeed(promptHeld, undefined).pipe(Effect.asVoid),
11944
+ onDeferredFinalizeScheduled: (debounce) =>
11945
+ Deferred.succeed(finalizeScheduled, debounce).pipe(Effect.asVoid),
11946
+ },
11947
+ flavor: {
11948
+ driver: ACP_TEST_DRIVER,
11949
+ capabilities: AcpProviderCapabilitiesV2,
11950
+ enablePostSettleContinuation: true,
11951
+ deferFinalizeForBackgroundWork: true,
11952
+ normalizeToolCall: grokFlavor.normalizeToolCall!,
11953
+ extractBackgroundTaskId: grokFlavor.extractBackgroundTaskId!,
11954
+ isBackgroundCommandTool: grokFlavor.isBackgroundCommandTool!,
11955
+ registerExtensions: ({ runtime, applyBackgroundTaskMutation }) =>
11956
+ registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation),
11957
+ makeRuntime: makeMockRuntime({
11958
+ childProcessSpawner,
11959
+ mockAgentPath,
11960
+ wrapRuntime: (runtime) => ({
11961
+ ...runtime,
11962
+ handleSessionUpdate: (handler) =>
11963
+ Effect.sync(() => {
11964
+ sessionUpdateHandler = handler;
11965
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
11966
+ handleExtNotification: (method, schema, handler) =>
11967
+ Effect.sync(() => {
11968
+ if (method === "x.ai/task_completed") {
11969
+ taskCompleted = (payload) =>
11970
+ handler(Schema.decodeUnknownSync(schema)(payload));
11971
+ }
11972
+ }).pipe(Effect.andThen(runtime.handleExtNotification(method, schema, handler))),
11973
+ prompt: () =>
11974
+ Deferred.succeed(promptStarted, undefined).pipe(
11975
+ Effect.andThen(Deferred.await(promptGate)),
11976
+ ),
11977
+ }),
11978
+ }),
11979
+ },
11980
+ continuationRequests: {
11981
+ offer: (request) =>
11982
+ Effect.sync(() => continuationRequests.push(request)).pipe(
11983
+ Effect.andThen(Deferred.succeed(continuationOffered, undefined)),
11984
+ Effect.asVoid,
11985
+ ),
11986
+ },
11987
+ });
11988
+ const threadId = ThreadId.make("thread-acp-early-command");
11989
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
11990
+ runtimeMode: "full-access",
11991
+ interactionMode: "default",
11992
+ cwd: process.cwd(),
11993
+ });
11994
+ const modelSelection = { instanceId, model: "default" } as const;
11995
+ const runtime = yield* adapter.openSession({
11996
+ threadId,
11997
+ providerSessionId: ProviderSessionId.make("provider-session-acp-early-command"),
11998
+ modelSelection,
11999
+ runtimePolicy,
12000
+ });
12001
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
12002
+ yield* runtime.events.pipe(
12003
+ Stream.runForEach((event) => Queue.offer(events, event)),
12004
+ Effect.forkScoped,
12005
+ );
12006
+ const providerThread = yield* runtime.ensureThread({
12007
+ threadId,
12008
+ modelSelection,
12009
+ runtimePolicy,
12010
+ });
12011
+ const now = yield* DateTime.now;
12012
+ yield* runtime
12013
+ .startTurn(
12014
+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
12015
+ )
12016
+ .pipe(Effect.forkScoped);
12017
+ yield* Deferred.await(promptStarted);
12018
+ assert.isDefined(sessionUpdateHandler);
12019
+ assert.isDefined(taskCompleted);
12020
+ const update = (update: EffectAcpSchema.SessionUpdate) =>
12021
+ sessionUpdateHandler!({ sessionId: "mock-session-1", update });
12022
+ const complete = (taskId: string, snapshot?: { output?: string; exit_code?: number }) =>
12023
+ taskCompleted!({
12024
+ sessionId: "mock-session-1",
12025
+ update: { sessionUpdate: "task_completed", task_id: taskId, task_snapshot: snapshot },
12026
+ });
12027
+ for (const taskId of ["early", "blocker"]) {
12028
+ yield* update({
12029
+ sessionUpdate: "tool_call",
12030
+ toolCallId: taskId,
12031
+ title: `Run ${taskId}`,
12032
+ kind: "execute",
12033
+ status: "completed",
12034
+ rawInput: { command: `echo ${taskId}` },
12035
+ rawOutput: { type: "BackgroundTaskStarted", task_id: taskId },
12036
+ });
12037
+ }
12038
+ // Progress removes the ACK carrying the task identity before a reportless completion.
12039
+ yield* update({
12040
+ sessionUpdate: "tool_call_update",
12041
+ toolCallId: "early",
12042
+ status: "in_progress",
12043
+ rawOutput: { type: "Text", text: "Command progress" },
12044
+ });
12045
+ yield* complete("early", { exit_code: exitCode, output: "EARLY_BG_DONE\n" });
12046
+ // The real decoder treats this exit-code-free duplicate as completed, even after failure.
12047
+ yield* complete("early");
12048
+ assert.lengthOf(continuationRequests, 0);
12049
+
12050
+ let backgroundItem: ProviderAdapter.ProviderAdapterV2Event | undefined;
12051
+ let checkpoint = 0;
12052
+ const assertCommand = Effect.fnUntraced(function* (expectedStatus: string, output: string) {
12053
+ const title = `Checkpoint ${++checkpoint}`;
12054
+ // A later tool event fences the emitted updates without waiting for a terminal that may never come.
12055
+ yield* update({ sessionUpdate: "tool_call_update", toolCallId: "blocker", title });
12056
+ while (true) {
12057
+ const event = yield* Queue.take(events);
12058
+ if (event.type !== "turn_item.updated") continue;
12059
+ if (event.turnItem.nativeItemRef?.nativeId === "early") backgroundItem = event;
12060
+ if (
12061
+ event.turnItem.nativeItemRef?.nativeId === "blocker" &&
12062
+ event.turnItem.title === title
12063
+ )
12064
+ break;
12065
+ }
12066
+ assert.equal(backgroundItem?.type, "turn_item.updated");
12067
+ if (backgroundItem?.type !== "turn_item.updated") return;
12068
+ assert.equal(backgroundItem.turnItem.status, expectedStatus);
12069
+ assert.equal(backgroundItem.turnItem.type, "command_execution");
12070
+ if (backgroundItem.turnItem.type === "command_execution") {
12071
+ assert.equal(backgroundItem.turnItem.output ?? "", output);
12072
+ }
12073
+ });
12074
+ yield* Deferred.succeed(promptGate, { stopReason: "end_turn" });
12075
+ yield* Deferred.await(promptHeld);
12076
+ yield* assertCommand(status, "EARLY_BG_DONE\n");
12077
+ assert.lengthOf(continuationRequests, 0, "the other command still holds the root open");
12078
+
12079
+ const replayAck = () =>
12080
+ update({
12081
+ sessionUpdate: "tool_call_update",
12082
+ toolCallId: "early",
12083
+ status: "completed",
12084
+ rawOutput: { type: "BackgroundTaskStarted", task_id: "early" },
12085
+ });
12086
+ yield* replayAck();
12087
+ yield* assertCommand(status, "EARLY_BG_DONE\n");
12088
+ // Sparse ACP updates must retain the command result after projection replaces the ACK.
12089
+ for (const sparseStatus of ["completed", "in_progress"] as const) {
12090
+ yield* update({
12091
+ sessionUpdate: "tool_call_update",
12092
+ toolCallId: "early",
12093
+ status: sparseStatus,
12094
+ });
12095
+ yield* assertCommand(status, "EARLY_BG_DONE\n");
12096
+ }
12097
+ if (status === "completed") {
12098
+ for (const output of ["", "UPDATED_OUTPUT\n"]) {
12099
+ yield* complete("early", { output });
12100
+ yield* replayAck();
12101
+ yield* assertCommand(status, output);
12102
+ }
12103
+ }
12104
+ yield* complete("blocker", { exit_code: 0, output: "BLOCKER_DONE\n" });
12105
+ yield* TestClock.adjust(yield* Deferred.await(finalizeScheduled));
12106
+ while (true) {
12107
+ const event = yield* Queue.take(events);
12108
+ if (event.type !== "turn.terminal") continue;
12109
+ assert.equal(event.status, "completed");
12110
+ break;
12111
+ }
12112
+ yield* Deferred.await(continuationOffered);
12113
+ yield* complete("early");
12114
+ yield* complete("blocker");
12115
+ assert.lengthOf(
12116
+ continuationRequests,
12117
+ 1,
12118
+ "duplicate completions must not offer another continuation",
12119
+ );
12120
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
12121
+ );
12122
+
12123
it.effect("empty-drain continuation turn waits the quiet window so late frames can attach", () =>
12124
Effect.gen(function* () {
12125
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
packages/provider-acp/src/server/adapter.ts
+85
-11
@@ -299,6 +299,8 @@ export interface AcpAdapterV2Flavor {
299
readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState;
300
readonly extractProposedPlanMarkdown?: (toolCall: AcpToolCallState) => string | undefined;
301
readonly extractBackgroundTaskId?: (toolCall: AcpToolCallState) => string | undefined;
302
+ /** Distinguishes commands from monitors when lifecycle notifications omit their kind. */
303
+ readonly isBackgroundCommandTool?: (toolCall: AcpToolCallState) => boolean;
304
readonly extractBackgroundToolMutation?: (text: string) => ReadonlyArray<{
305
readonly taskId: string;
306
readonly status: "running" | "completed" | "failed";
@@ -1028,13 +1030,18 @@ interface ActiveAcpTurn {
1030
| undefined;
1031
contextUsage: ThreadTokenUsageSnapshot | null;
1032
nativeMetadata: OrchestrationV2ProviderThreadNativeMetadata | null;
1031
- readonly tools: Map<string, AcpToolCallState>;
1033
+ readonly tools: Map<string, AcpToolCallState & { readonly backgroundCommandTaskId?: string }>;
1034
readonly toolUpdatesSkipped: Map<string, number>;
1035
readonly toolStartedAt: Map<string, DateTime.Utc>;
1036
readonly subagents: Map<string, ActiveAcpSubagent>;
1037
readonly subagentsBySessionId: Map<string, ActiveAcpSubagent>;
1038
readonly pendingSubagentNotifications: Map<string, Array<EffectAcpSchema.SessionNotification>>;
1039
readonly toolCallIdsByBackgroundTaskId: Map<string, string>;
1040
+ /** Command ACKs register null; terminal results wait here for prompt settlement. */
1041
+ readonly backgroundCommands: Map<
1042
+ string,
1043
+ { readonly status: "completed" | "failed"; readonly output?: string } | null
1044
+ >;
1045
readonly persistentBackgroundTaskIds: Set<string>;
1046
/**
1047
* Monitor end events often only say "use get_command…"; keep the turn open
@@ -3402,8 +3409,38 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3409
yield* closeTextStream(context, "user");
3410
const previous = context.tools.get(incoming.toolCallId);
3411
const merged = mergeToolCallState(previous, incoming);
3405
- const toolCall = flavor.normalizeToolCall?.(merged) ?? merged;
3406
- context.tools.set(toolCall.toolCallId, toolCall);
3412
+ const normalized = flavor.normalizeToolCall?.(merged) ?? merged;
3413
+ const backgroundTaskId = flavor.extractBackgroundTaskId?.(normalized);
3414
+ const backgroundCommandTaskId =
3415
+ flavor.isBackgroundCommandTool?.(normalized) === true
3416
+ ? backgroundTaskId
3417
+ : previous?.backgroundCommandTaskId;
3418
+ if (
3419
+ backgroundCommandTaskId !== undefined &&
3420
+ !context.backgroundCommands.has(backgroundCommandTaskId)
3421
+ ) {
3422
+ context.backgroundCommands.set(backgroundCommandTaskId, null);
3423
+ }
3424
+ const completion =
3425
+ context.promptSettled && backgroundCommandTaskId !== undefined
3426
+ ? (context.backgroundCommands.get(backgroundCommandTaskId) ?? undefined)
3427
+ : undefined;
3428
+ // Preserve hydrated output; only a replayed start ACK needs its output restored.
3429
+ const toolCall =
3430
+ completion === undefined
3431
+ ? normalized
3432
+ : {
3433
+ ...(backgroundTaskId === undefined || completion.output === undefined
3434
+ ? normalized
3435
+ : setToolOutputText(normalized, completion.output)),
3436
+ status: completion.status,
3437
+ };
3438
+ context.tools.set(
3439
+ toolCall.toolCallId,
3440
+ backgroundCommandTaskId === undefined
3441
+ ? toolCall
3442
+ : { ...toolCall, backgroundCommandTaskId },
3443
+ );
3444
if (
3445
followsAgentWorkState &&
3446
projectedStatus === undefined &&
@@ -3412,7 +3449,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3449
yield* rearmDeferredFinalize(context);
3450
return;
3451
}
3415
- const backgroundTaskId = flavor.extractBackgroundTaskId?.(toolCall);
3452
if (backgroundTaskId !== undefined) {
3453
context.toolCallIdsByBackgroundTaskId.set(backgroundTaskId, toolCall.toolCallId);
3454
if (flavor.isPersistentBackgroundTool?.(toolCall) === true) {
@@ -4107,8 +4143,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4143
}
4144
});
4145
4110
- // A structured task end (Grok `task_completed`) is authoritative for the
4111
- // tool that registered the task: its own updates only ever say running.
4146
+ // Structured task ends are authoritative, but emitting before prompt
4147
+ // settlement marks the result handled and suppresses its continuation.
4148
const finishRegisteredBackgroundTool = Effect.fnUntraced(function* (mutation: {
4149
readonly taskId: string;
4150
readonly status: "completed" | "failed";
@@ -4120,7 +4156,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4156
const tool = toolCallId === undefined ? undefined : context.tools.get(toolCallId);
4157
if (tool === undefined) return;
4158
const status = toolStatus(tool.status);
4123
- if (status !== "pending" && status !== "running") return;
4159
+ if (
4160
+ status !== "pending" &&
4161
+ status !== "running" &&
4162
+ !context.backgroundCommands.has(mutation.taskId)
4163
+ ) {
4164
+ return;
4165
+ }
4166
context.awaitingBackgroundHydration.delete(mutation.taskId);
4167
const finished = { ...tool, status: mutation.status };
4168
yield* emitTool(
@@ -6166,12 +6208,37 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6208
yield* finishSubagentFromNotice(notice);
6209
}),
6210
).pipe(Effect.asVoid),
6169
- applyBackgroundTaskMutation: (mutation) =>
6211
+ applyBackgroundTaskMutation: (incoming) =>
6212
runRuntimeCallbackAtGeneration(
6213
handlerGeneration,
6214
Effect.gen(function* () {
6215
if (yield* Ref.get(stoppedRunQuarantine)) return;
6174
- if ((yield* Ref.get(activeSessionId)) !== mutation.sessionId) return;
6216
+ if ((yield* Ref.get(activeSessionId)) !== incoming.sessionId) return;
6217
+ const context = yield* Ref.get(activeTurn);
6218
+ let mutation = incoming;
6219
+ if (
6220
+ incoming.status !== "running" &&
6221
+ context !== null &&
6222
+ !context.finalized &&
6223
+ (incoming.report?.kind === "command" ||
6224
+ context.backgroundCommands.has(incoming.taskId))
6225
+ ) {
6226
+ const previous = context.backgroundCommands.get(incoming.taskId);
6227
+ const toolCallId = context.toolCallIdsByBackgroundTaskId.get(incoming.taskId);
6228
+ const tool =
6229
+ toolCallId === undefined ? undefined : context.tools.get(toolCallId);
6230
+ const output =
6231
+ incoming.output ??
6232
+ previous?.output ??
6233
+ (tool === undefined ? undefined : toolOutputText(tool));
6234
+ // Missing exit codes decode as success; they cannot undo a known failure.
6235
+ const completion = {
6236
+ status: previous?.status === "failed" ? "failed" : incoming.status,
6237
+ ...(output === undefined ? {} : { output }),
6238
+ };
6239
+ context.backgroundCommands.set(incoming.taskId, completion);
6240
+ mutation = { ...incoming, ...completion };
6241
+ }
6242
if (
6243
mutation.status !== "running" &&
6244
mutation.report !== undefined &&
@@ -7212,6 +7279,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7279
subagentsBySessionId: new Map(),
7280
pendingSubagentNotifications: new Map(),
7281
toolCallIdsByBackgroundTaskId: new Map(),
7282
+ backgroundCommands: new Map(),
7283
persistentBackgroundTaskIds: new Set(),
7284
awaitingBackgroundHydration: new Set(),
7285
pendingInjectedReport: new Set(),
@@ -7387,13 +7455,19 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7455
? "interrupted"
7456
: "cancelled"
7457
: "completed";
7458
+ if (flavor.deferFinalizeForBackgroundWork === true && !context.interrupted) {
7459
+ context.promptSettled = true;
7460
+ context.promptSettledStatus = status;
7461
+ for (const [taskId, completion] of context.backgroundCommands) {
7462
+ if (completion === null) continue;
7463
+ yield* finishRegisteredBackgroundTool({ taskId, ...completion });
7464
+ }
7465
+ }
7466
if (
7467
flavor.deferFinalizeForBackgroundWork === true &&
7468
!context.interrupted &&
7469
hasDeferredBackgroundWork(context)
7470
) {
7395
- context.promptSettled = true;
7396
- context.promptSettledStatus = status;
7471
yield* closeTextStreams(context);
7472
yield* (
7473
options.testHooks?.afterPromptSettledWithBackgroundWork?.() ?? Effect.void
packages/provider-grok/src/server/adapter.ts
+2
@@ -43,6 +43,7 @@ import {
43
extractXAiBackgroundTaskCompletion,
44
extractXAiKilledBackgroundTasks,
45
extractXAiMonitorTaskId,
46
+ xAiBackgroundShellTaskId,
47
isXAiPersistentMonitor,
48
extractXAiExitPlanMarkdown,
49
registerXAiSubagentFinished,
@@ -323,6 +324,7 @@ export function makeGrokAcpAdapterFlavor(
324
homeDirectory,
325
}),
326
extractBackgroundTaskId: extractXAiMonitorTaskId,
327
+ isBackgroundCommandTool: (toolCall) => xAiBackgroundShellTaskId(toolCall) !== undefined,
328
extractBackgroundToolMutation: extractXAiAcpBackgroundToolMutation,
329
extractBackgroundTaskCompletion: (toolCall) => [
330
...extractXAiBackgroundTaskCompletion(toolCall),
packages/provider-grok/src/server/xaiAcpExtension.ts
+1
-1
@@ -275,7 +275,7 @@ export function isXAiMonitorTool(toolCall: AcpToolCallState): boolean {
275
* while the process still runs. Like a monitor, it ends only with
276
* `x.ai/task_completed` for that task id.
277
*/
278
-function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined {
278
+export function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined {
279
const rawOutput = unknownRecord(toolCall.data.rawOutput);
280
return nonEmptyString(rawOutput?.type) === "BackgroundTaskStarted"
281
? nonEmptyString(rawOutput?.task_id)