The best way to control Claude Code, Codex and more from any computer or phone
fix(server): delegates finish when their leftover work settles, and Grok commands stop holding runs open (#22709)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Fuksss <fuxik12345@gmail.com>
Theo Browne committed
Oct 21, 2026 at 00:20 UTC
163bdeaa119f32bf92f25d2841048b808df542a5
7 files changed
+764
-15
apps/server/scripts/acp-mock-agent.ts
+122
-3
@@ -46,9 +46,11 @@ const emitXAiAskUserQuestionThenHang =
46
process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION_THEN_HANG === "1";
47
const emitContentThenHang = process.env.T3_ACP_EMIT_CONTENT_THEN_HANG === "1";
48
const emitPlanThenHang = process.env.T3_ACP_EMIT_PLAN_THEN_HANG === "1";
49
+const grokKillTaskShape = process.env.T3_ACP_GROK_KILL_TASK_SHAPE;
50
const emitActiveToolThenHang = process.env.T3_ACP_EMIT_ACTIVE_TOOL_THEN_HANG === "1";
51
const emitGrokMonitorPostTurnPoll = process.env.T3_ACP_EMIT_GROK_MONITOR_POST_TURN_POLL === "1";
52
const emitGrokBackgroundTaskStarted = process.env.T3_ACP_EMIT_GROK_BACKGROUND_TASK_STARTED === "1";
53
+const emitGrokBackgroundTaskPoll = process.env.T3_ACP_GROK_BACKGROUND_TASK_COMPLETION === "poll";
54
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
55
const waitForResumeRelease = process.env.T3_ACP_WAIT_FOR_RESUME_RELEASE === "1";
56
const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1";
@@ -461,6 +463,71 @@ function modelState(): AcpCompat.SessionModelState {
463
};
464
}
465
466
+function emitGrokKillTaskScenario(
467
+ sessionId: string,
468
+ promptId: string | undefined,
469
+ shape: string,
470
+): void {
471
+ const taskId = "call-fb9d0000-0000-0000-0000-000000000026-29";
472
+ const outcome =
473
+ shape === "already_exited" || shape === "known_failure" ? "already_exited" : "killed";
474
+ writeJsonRpcNotification("session/update", {
475
+ sessionId,
476
+ update: {
477
+ sessionUpdate: "tool_call_update",
478
+ toolCallId: "kill-target-command",
479
+ title: "run_terminal_command",
480
+ kind: "execute",
481
+ status: "in_progress",
482
+ rawInput: { command: "sleep 40" },
483
+ },
484
+ });
485
+ writeJsonRpcNotification("session/update", {
486
+ sessionId,
487
+ update: {
488
+ sessionUpdate: "tool_call_update",
489
+ toolCallId: "kill-target-command",
490
+ status: "completed",
491
+ rawOutput: {
492
+ type: "BackgroundTaskStarted",
493
+ task_id: taskId,
494
+ task_type: "bash",
495
+ command: "sleep 40",
496
+ },
497
+ },
498
+ });
499
+ if (shape === "known_failure") {
500
+ writeJsonRpcNotification("_x.ai/task_completed", {
501
+ sessionId,
502
+ update: {
503
+ sessionUpdate: "task_completed",
504
+ task_snapshot: { task_id: taskId, kind: "bash", exit_code: 7, output: "known failure\n" },
505
+ },
506
+ });
507
+ }
508
+ writeJsonRpcNotification("session/update", {
509
+ sessionId,
510
+ update: {
511
+ sessionUpdate: "tool_call_update",
512
+ toolCallId: "kill-command",
513
+ title: `kill ${taskId} (${outcome})`,
514
+ kind: "other",
515
+ status: "completed",
516
+ rawInput: {
517
+ task_id: taskId,
518
+ ...(shape === "output_only" ? {} : { variant: "KillTask" }),
519
+ },
520
+ ...(shape === "variant_only" ? {} : { rawOutput: { type: "KillTask", outcome } }),
521
+ },
522
+ });
523
+ writeJsonRpcNotification("_x.ai/session/prompt_complete", {
524
+ sessionId,
525
+ promptId,
526
+ stopReason: "end_turn",
527
+ agentResult: null,
528
+ });
529
+}
530
+
531
const program = Effect.gen(function* () {
532
const agent = yield* EffectAcpAgent.AcpAgent;
533
const resumeRelease = yield* Deferred.make<void>();
@@ -1498,6 +1565,16 @@ const program = Effect.gen(function* () {
1565
return yield* Effect.never;
1566
}
1567
1568
+ if (grokKillTaskShape !== undefined) {
1569
+ emitGrokKillTaskScenario(
1570
+ requestedSessionId,
1571
+ promptIdFromRequestMeta(request),
1572
+ grokKillTaskShape,
1573
+ );
1574
+ // Keep the prompt RPC and peer alive after the kill result.
1575
+ return yield* Effect.never;
1576
+ }
1577
+
1578
if (emitPlanThenHang) {
1579
yield* agent.client.sessionUpdate({
1580
sessionId: requestedSessionId,
@@ -1685,13 +1762,15 @@ const program = Effect.gen(function* () {
1762
return yield* Effect.never;
1763
}
1764
1688
- if (emitGrokBackgroundTaskStarted) {
1689
- const toolCallId = "call-fb9d0000-0000-0000-0000-000000000026";
1765
+ if (emitGrokBackgroundTaskStarted || emitGrokBackgroundTaskPoll) {
1766
+ const toolCallId = !emitGrokBackgroundTaskPoll
1767
+ ? "call-fb9d0000-0000-0000-0000-000000000026"
1768
+ : "call-fb9d0000-0000-0000-0000-000000000026-29";
1769
const command = "sleep 40; echo done-a";
1770
writeJsonRpcNotification("session/update", {
1771
sessionId: requestedSessionId,
1772
update: {
1694
- sessionUpdate: "tool_call",
1773
+ sessionUpdate: !emitGrokBackgroundTaskPoll ? "tool_call" : "tool_call_update",
1774
toolCallId,
1775
title: "run_terminal_command",
1776
kind: "execute",
@@ -1714,6 +1793,46 @@ const program = Effect.gen(function* () {
1793
},
1794
},
1795
});
1796
+ if (emitGrokBackgroundTaskPoll) {
1797
+ writeJsonRpcNotification("session/update", {
1798
+ sessionId: requestedSessionId,
1799
+ update: {
1800
+ sessionUpdate: "tool_call_update",
1801
+ toolCallId: "call-background-poll",
1802
+ title: "get_command_or_subagent_output",
1803
+ kind: "other",
1804
+ status: "completed",
1805
+ rawOutput: {
1806
+ type: "TaskOutput",
1807
+ Result: {
1808
+ task_id: toolCallId,
1809
+ command,
1810
+ status: "completed",
1811
+ exit_code: 0,
1812
+ output: "done-a",
1813
+ },
1814
+ },
1815
+ },
1816
+ });
1817
+
1818
+ yield* agent.client.sessionUpdate({
1819
+ sessionId: requestedSessionId,
1820
+ update: {
1821
+ sessionUpdate: "agent_message_chunk",
1822
+ content: { type: "text", text: "The background command finished." },
1823
+ },
1824
+ });
1825
+ writeJsonRpcNotification("_x.ai/session/update", {
1826
+ sessionId: requestedSessionId,
1827
+ update: {
1828
+ sessionUpdate: "turn_completed",
1829
+ prompt_id: promptIdFromRequestMeta(request),
1830
+ stop_reason: "end_turn",
1831
+ },
1832
+ });
1833
+ // Neither the prompt RPC nor the process ends, matching the Grok incident.
1834
+ return yield* Effect.never;
1835
+ }
1836
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
1837
sessionId: requestedSessionId,
1838
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+189
@@ -63,6 +63,8 @@ import {
63
} from "@t3tools/provider-acp/server/sessionConfig";
64
import {
65
extractXAiAcpSubagentUpdate,
66
+ makeGrokAdapterV2,
67
+ makeXAiPromptCompletionRuntime,
68
normalizeXAiAcpToolCallState,
69
registerXAiBackgroundTaskTracking,
70
} from "@t3tools/provider-grok/testing";
@@ -3079,6 +3081,193 @@ describe("AcpAdapterV2", () => {
3081
}).pipe(Effect.provide(layerTest), Effect.scoped),
3082
);
3083
3084
+ // Oracle: Grok incident frames. Command completion must release the turn even
3085
+ // when the CLI keeps the prompt RPC and process alive. Command polls stay visible.
3086
+ it.live(
3087
+ "completes a structured Grok background command from poll with an unanswered prompt RPC",
3088
+ () =>
3089
+ Effect.gen(function* () {
3090
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
3091
+ const path = yield* Path.Path;
3092
+ const mockAgentPath = yield* path.fromFileUrl(
3093
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
3094
+ );
3095
+ const instanceId = ProviderInstanceId.make("grok-background-completion");
3096
+ const adapter = yield* makeGrokAdapterV2({
3097
+ instanceId,
3098
+ settings: DEFAULT_GROK_SETTINGS,
3099
+ environment: {},
3100
+ hostPlatform: yield* HostProcess.Platform,
3101
+ selfInvocation: yield* resolveSelfInvocation(),
3102
+ makeRuntime: (input) =>
3103
+ makeMockRuntime({
3104
+ childProcessSpawner,
3105
+ mockAgentPath,
3106
+ environment: { T3_ACP_GROK_BACKGROUND_TASK_COMPLETION: "poll" },
3107
+ })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)),
3108
+ });
3109
+ const threadId = ThreadId.make("grok-background-completion");
3110
+ const modelSelection = { instanceId, model: "default" } as const;
3111
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
3112
+ runtimeMode: "full-access",
3113
+ interactionMode: "default",
3114
+ cwd: process.cwd(),
3115
+ });
3116
+ const runtime = yield* adapter.openSession({
3117
+ threadId,
3118
+ providerSessionId: ProviderSessionId.make("grok-background-completion"),
3119
+ modelSelection,
3120
+ runtimePolicy,
3121
+ });
3122
+ const providerThread = yield* runtime.ensureThread({
3123
+ threadId,
3124
+ modelSelection,
3125
+ runtimePolicy,
3126
+ });
3127
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3128
+ yield* runtime.events.pipe(
3129
+ Stream.runForEach((event) => Queue.offer(events, event)),
3130
+ Effect.forkScoped,
3131
+ );
3132
+ yield* runtime.startTurn(
3133
+ makeTurnInput({
3134
+ threadId,
3135
+ providerThread,
3136
+ instanceId,
3137
+ runtimePolicy,
3138
+ now: yield* DateTime.now,
3139
+ }),
3140
+ );
3141
+ const observed = yield* Stream.fromQueue(events).pipe(
3142
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
3143
+ Stream.runCollect,
3144
+ );
3145
+ const allEvents = [...observed];
3146
+ let next = yield* Queue.poll(events);
3147
+ while (Option.isSome(next)) {
3148
+ allEvents.push(next.value);
3149
+ next = yield* Queue.poll(events);
3150
+ }
3151
+ const terminals = allEvents.filter((event) => event.type === "turn.terminal");
3152
+ assert.deepEqual(
3153
+ terminals.map((event) => event.status),
3154
+ ["completed"],
3155
+ );
3156
+ const items = allEvents.flatMap((event) =>
3157
+ event.type === "turn_item.updated" ? [event.turnItem] : [],
3158
+ );
3159
+ assert.isFalse(items.some((item) => item.type === "subagent"));
3160
+ const command = items.findLast(
3161
+ (item) => item.nativeItemRef?.nativeId === "call-fb9d0000-0000-0000-0000-000000000026-29",
3162
+ );
3163
+ assert.equal(command?.type, "command_execution");
3164
+ assert.equal(command?.status, "completed");
3165
+ assert.isTrue(
3166
+ items.some((item) => item.nativeItemRef?.nativeId === "call-background-poll"),
3167
+ "command TaskOutput must retain its normal tool frame",
3168
+ );
3169
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
3170
+ );
3171
+
3172
+ // Oracle: #15888 KillTask reports. Command completion must release the turn even
3173
+ // when the CLI keeps the prompt RPC and process alive. Kill calls stay visible.
3174
+ it.live.each([
3175
+ { shape: "output_only", expectedCommand: { type: "command_execution", status: "completed" } },
3176
+ { shape: "variant_only", expectedCommand: { type: "command_execution", status: "completed" } },
3177
+ { shape: "killed", expectedCommand: { type: "command_execution", status: "completed" } },
3178
+ {
3179
+ shape: "already_exited",
3180
+ expectedCommand: { type: "command_execution", status: "completed" },
3181
+ },
3182
+ {
3183
+ shape: "known_failure",
3184
+ expectedCommand: { type: "command_execution", status: "failed", output: "known failure\n" },
3185
+ },
3186
+ ] as const)(
3187
+ "completes a Grok KillTask command ($shape) and preserves any known result",
3188
+ ({ shape, expectedCommand }) =>
3189
+ Effect.gen(function* () {
3190
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
3191
+ const path = yield* Path.Path;
3192
+ const mockAgentPath = yield* path.fromFileUrl(
3193
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
3194
+ );
3195
+ const instanceId = ProviderInstanceId.make("grok-kill-completion");
3196
+ const adapter = yield* makeGrokAdapterV2({
3197
+ instanceId,
3198
+ settings: DEFAULT_GROK_SETTINGS,
3199
+ environment: {},
3200
+ hostPlatform: yield* HostProcess.Platform,
3201
+ selfInvocation: yield* resolveSelfInvocation(),
3202
+ makeRuntime: (input) =>
3203
+ makeMockRuntime({
3204
+ childProcessSpawner,
3205
+ mockAgentPath,
3206
+ environment: { T3_ACP_GROK_KILL_TASK_SHAPE: shape },
3207
+ })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)),
3208
+ });
3209
+ const threadId = ThreadId.make("grok-kill-completion");
3210
+ const modelSelection = { instanceId, model: "default" } as const;
3211
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
3212
+ runtimeMode: "full-access",
3213
+ interactionMode: "default",
3214
+ cwd: process.cwd(),
3215
+ });
3216
+ const runtime = yield* adapter.openSession({
3217
+ threadId,
3218
+ providerSessionId: ProviderSessionId.make("grok-kill-completion"),
3219
+ modelSelection,
3220
+ runtimePolicy,
3221
+ });
3222
+ const providerThread = yield* runtime.ensureThread({
3223
+ threadId,
3224
+ modelSelection,
3225
+ runtimePolicy,
3226
+ });
3227
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3228
+ yield* runtime.events.pipe(
3229
+ Stream.runForEach((event) => Queue.offer(events, event)),
3230
+ Effect.forkScoped,
3231
+ );
3232
+ yield* runtime.startTurn(
3233
+ makeTurnInput({
3234
+ threadId,
3235
+ providerThread,
3236
+ instanceId,
3237
+ runtimePolicy,
3238
+ now: yield* DateTime.now,
3239
+ }),
3240
+ );
3241
+ const observed = yield* Stream.fromQueue(events).pipe(
3242
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
3243
+ Stream.runCollect,
3244
+ );
3245
+ const allEvents = [...observed];
3246
+ let next = yield* Queue.poll(events);
3247
+ while (Option.isSome(next)) {
3248
+ allEvents.push(next.value);
3249
+ next = yield* Queue.poll(events);
3250
+ }
3251
+ const terminals = allEvents.filter((event) => event.type === "turn.terminal");
3252
+ assert.deepEqual(
3253
+ terminals.map((event) => event.status),
3254
+ ["completed"],
3255
+ );
3256
+ const items = allEvents.flatMap((event) =>
3257
+ event.type === "turn_item.updated" ? [event.turnItem] : [],
3258
+ );
3259
+ assert.isFalse(items.some((item) => item.type === "subagent"));
3260
+ const command = items.findLast(
3261
+ (item) => item.nativeItemRef?.nativeId === "kill-target-command",
3262
+ );
3263
+ assert.deepInclude(command, expectedCommand);
3264
+ assert.isTrue(
3265
+ items.some((item) => item.nativeItemRef?.nativeId === "kill-command"),
3266
+ "KillTask must retain its normal tool frame",
3267
+ );
3268
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
3269
+ );
3270
+
3271
it.effect("keeps an agent's empty-valued default choice selectable", () =>
3272
Effect.gen(function* () {
3273
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+220
@@ -2402,4 +2402,224 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {
2402
);
2403
}),
2404
);
2405
+
2406
+ it.effect.each(["a background command", "a nested subagent"] as const)(
2407
+ "finalizes a child whose run ended before %s settled",
2408
+ (blocker) =>
2409
+ Effect.gen(function* () {
2410
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2411
+ const sink = yield* EventSink.EventSinkV2;
2412
+ const now = yield* DateTime.now;
2413
+ const key = blocker === "a background command" ? "command" : "nested";
2414
+ const threadId = ThreadId.make(`late-settle-parent-${key}`);
2415
+ const runId = RunId.make(`late-settle-parent-run-${key}`);
2416
+ const rootNodeId = NodeId.make(`late-settle-parent-root-${key}`);
2417
+ yield* seedParentWithTerminalTask({
2418
+ threadId,
2419
+ projectId: ProjectId.make(`late-settle-project-${key}`),
2420
+ runId,
2421
+ rootNodeId,
2422
+ taskId: NodeId.make(`late-settle-seed-task-${key}`),
2423
+ deliveryState: "acknowledged",
2424
+ now,
2425
+ });
2426
+ // A delegated child with a running task on the parent and a running run of its own.
2427
+ const delegate = (name: string) =>
2428
+ Effect.gen(function* () {
2429
+ const taskId = NodeId.make(`node:late-settle-${key}-${name}`);
2430
+ const childThreadId = ThreadId.make(`thread:late-settle-${key}-${name}`);
2431
+ const run = runEvent({
2432
+ threadId: childThreadId,
2433
+ runId: RunId.make(`run:late-settle-${key}-${name}`),
2434
+ ordinal: 1,
2435
+ status: "running",
2436
+ now,
2437
+ });
2438
+ yield* sink.write({
2439
+ events: [
2440
+ {
2441
+ id: EventId.make(`event:late-settle-${key}-${name}:thread`),
2442
+ type: "thread.created",
2443
+ threadId: childThreadId,
2444
+ occurredAt: now,
2445
+ payload: {
2446
+ createdBy: "agent",
2447
+ creationSource: "server",
2448
+ id: childThreadId,
2449
+ projectId: ProjectId.make(`late-settle-project-${key}`),
2450
+ title: name,
2451
+ providerInstanceId: modelSelection.instanceId,
2452
+ modelSelection,
2453
+ runtimeMode: "full-access",
2454
+ interactionMode: "default",
2455
+ branch: null,
2456
+ worktreePath: null,
2457
+ activeProviderThreadId: null,
2458
+ lineage: {
2459
+ parentThreadId: threadId,
2460
+ relationshipToParent: "subagent",
2461
+ rootThreadId: threadId,
2462
+ },
2463
+ forkedFrom: { type: "node", nodeId: taskId },
2464
+ createdAt: now,
2465
+ updatedAt: now,
2466
+ archivedAt: null,
2467
+ settledOverride: null,
2468
+ settledAt: null,
2469
+ lastVisitedAt: null,
2470
+ deletedAt: null,
2471
+ },
2472
+ },
2473
+ {
2474
+ id: EventId.make(`event:late-settle-${key}-${name}:task`),
2475
+ type: "subagent.updated",
2476
+ threadId,
2477
+ runId,
2478
+ nodeId: taskId,
2479
+ driver,
2480
+ providerInstanceId: modelSelection.instanceId,
2481
+ occurredAt: now,
2482
+ payload: {
2483
+ id: taskId,
2484
+ threadId,
2485
+ runId,
2486
+ parentNodeId: rootNodeId,
2487
+ origin: "app_owned",
2488
+ createdBy: "agent",
2489
+ driver,
2490
+ providerInstanceId: modelSelection.instanceId,
2491
+ providerThreadId: null,
2492
+ childThreadId,
2493
+ nativeTaskRef: null,
2494
+ prompt: `Run ${name}.`,
2495
+ title: null,
2496
+ model: null,
2497
+ completionWake: "always",
2498
+ status: "running",
2499
+ result: null,
2500
+ startedAt: now,
2501
+ completedAt: null,
2502
+ updatedAt: now,
2503
+ },
2504
+ },
2505
+ run,
2506
+ ],
2507
+ });
2508
+ return { task: { id: taskId }, childThreadId, run: run.payload };
2509
+ });
2510
+ const settled = (taskId: NodeId, afterSequence: number) =>
2511
+ sink.stream({ afterSequence, eventType: "subagent.updated" }).pipe(
2512
+ Stream.filter(
2513
+ (stored) =>
2514
+ stored.event.type === "subagent.updated" &&
2515
+ stored.event.payload.id === taskId &&
2516
+ stored.event.payload.status === "completed",
2517
+ ),
2518
+ Stream.take(1),
2519
+ Stream.runDrain,
2520
+ );
2521
+ const blocked = yield* delegate("blocked");
2522
+ const barrier = yield* delegate("barrier");
2523
+ const providerThread = {
2524
+ id: ProviderThreadId.make(`provider-thread:late-settle-child-${key}`),
2525
+ driver,
2526
+ providerInstanceId: modelSelection.instanceId,
2527
+ providerSessionId: null,
2528
+ appThreadId: blocked.childThreadId,
2529
+ ownerNodeId: null,
2530
+ nativeThreadRef: null,
2531
+ nativeConversationHeadRef: null,
2532
+ status: "idle" as const,
2533
+ firstRunOrdinal: 1,
2534
+ lastRunOrdinal: 1,
2535
+ handoffIds: [],
2536
+ forkedFrom: null,
2537
+ createdAt: now,
2538
+ updatedAt: now,
2539
+ };
2540
+ const nested = {
2541
+ id: NodeId.make(`late-settle-nested-${key}`),
2542
+ threadId: blocked.childThreadId,
2543
+ runId: blocked.run.id,
2544
+ parentNodeId: NodeId.make(`late-settle-child-root-${key}`),
2545
+ origin: "provider_native" as const,
2546
+ createdBy: "agent" as const,
2547
+ driver,
2548
+ providerInstanceId: modelSelection.instanceId,
2549
+ providerThreadId: null,
2550
+ childThreadId: null,
2551
+ nativeTaskRef: null,
2552
+ prompt: "Nested work",
2553
+ title: null,
2554
+ model: null,
2555
+ status: "running" as const,
2556
+ result: null,
2557
+ startedAt: now,
2558
+ completedAt: null,
2559
+ updatedAt: now,
2560
+ };
2561
+ const blockerEvent = (open: boolean) =>
2562
+ blocker === "a background command"
2563
+ ? {
2564
+ id: EventId.make(`event:late-settle-roster-${key}-${open}`),
2565
+ type: "provider-thread.updated" as const,
2566
+ threadId: blocked.childThreadId,
2567
+ driver,
2568
+ providerInstanceId: modelSelection.instanceId,
2569
+ occurredAt: now,
2570
+ payload: {
2571
+ ...providerThread,
2572
+ pendingBackgroundTasks: open
2573
+ ? [{ taskId: "sleep-900", kind: "command" as const }]
2574
+ : [],
2575
+ },
2576
+ }
2577
+ : {
2578
+ id: EventId.make(`event:late-settle-nested-${key}-${open}`),
2579
+ type: "subagent.updated" as const,
2580
+ threadId: blocked.childThreadId,
2581
+ runId: blocked.run.id,
2582
+ nodeId: nested.id,
2583
+ driver,
2584
+ providerInstanceId: modelSelection.instanceId,
2585
+ occurredAt: now,
2586
+ payload: open
2587
+ ? nested
2588
+ : { ...nested, status: "completed" as const, result: "done", completedAt: now },
2589
+ };
2590
+ const ended = (child: typeof blocked) => ({
2591
+ ...runEvent({
2592
+ threadId: child.childThreadId,
2593
+ runId: child.run.id,
2594
+ ordinal: child.run.ordinal,
2595
+ status: "completed",
2596
+ now,
2597
+ }),
2598
+ payload: { ...child.run, status: "completed" as const, startedAt: now, completedAt: now },
2599
+ });
2600
+
2601
+ const beforeEnd = yield* sink.latestSequence();
2602
+ yield* sink.write({ events: [blockerEvent(true)] });
2603
+ yield* sink.write({ events: [ended(blocked)] });
2604
+ yield* sink.write({ events: [ended(barrier)] });
2605
+ // Run updates are handled in order, so the barrier settling means the blocked child's
2606
+ // run end was handled too, while its work still ran.
2607
+ yield* settled(barrier.task.id, beforeEnd);
2608
+ assert.equal(
2609
+ (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
2610
+ (task) => task.id === blocked.task.id,
2611
+ )?.status,
2612
+ "running",
2613
+ );
2614
+
2615
+ const beforeSettle = yield* sink.latestSequence();
2616
+ yield* sink.write({ events: [blockerEvent(false)] });
2617
+ yield* settled(blocked.task.id, beforeSettle);
2618
+ const finished = (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
2619
+ (task) => task.id === blocked.task.id,
2620
+ );
2621
+ assert.equal(finished?.status, "completed");
2622
+ assert.notEqual(finished?.completionDelivery?.state, "disposed");
2623
+ }),
2624
+ );
2625
});
apps/server/src/orchestration-v2/Orchestrator.ts
+42
@@ -11826,6 +11826,48 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11826
Effect.forkDetach,
11827
);
11828
11829
+ // A child whose run ends while its background tasks or its own subagents still run has no
11830
+ // result yet. When that work settles there is no run update to finalize it, so these events
11831
+ // do it (#17512). A background roster counts once it empties after it was seen non-empty.
11832
+ const providerThreadsWithBackgroundWork = new Set<string>();
11833
+ const settlesChildWork = (stored: OrchestrationV2StoredEvent) => {
11834
+ const { event } = stored;
11835
+ if (event.type === "subagent.updated")
11836
+ return !isOrchestrationV2WorkActive(event.payload.status);
11837
+ if (event.type !== "provider-thread.updated") return false;
11838
+ if ((event.payload.pendingBackgroundTasks?.length ?? 0) > 0) {
11839
+ providerThreadsWithBackgroundWork.add(event.payload.id);
11840
+ return false;
11841
+ }
11842
+ return providerThreadsWithBackgroundWork.delete(event.payload.id);
11843
+ };
11844
+ yield* Stream.merge(
11845
+ eventSink.stream({
11846
+ afterSequence: terminalEventsAfterSequence,
11847
+ eventType: "provider-thread.updated",
11848
+ }),
11849
+ eventSink.stream({ afterSequence: terminalEventsAfterSequence, eventType: "subagent.updated" }),
11850
+ ).pipe(
11851
+ Stream.filter(settlesChildWork),
11852
+ Stream.runForEach((stored) =>
11853
+ Effect.gen(function* () {
11854
+ const childThreadId = stored.event.threadId;
11855
+ const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId);
11856
+ if (parentThreadId === undefined) return;
11857
+ yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(childThreadId));
11858
+ }).pipe(
11859
+ Effect.catchCause((cause) =>
11860
+ Effect.logWarning("Failed to finalize a delegated child after its work settled", {
11861
+ threadId: stored.event.threadId,
11862
+ sequence: stored.sequence,
11863
+ cause,
11864
+ }),
11865
+ ),
11866
+ ),
11867
+ ),
11868
+ Effect.forkDetach,
11869
+ );
11870
+
11871
const recoverDelegatedTasks = Effect.gen(function* () {
11872
yield* projectionStore.getRecoveryThreadIds("subagent-results").pipe(
11873
Effect.tap((threadIds) =>
packages/provider-acp/src/server/adapter.ts
+11
@@ -3555,6 +3555,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3555
backgroundCompletion.appendOutput,
3556
)
3557
: { ...target, status: nextStatus };
3558
+ // BackgroundTaskStarted normalization can reopen this row, so keep the
3559
+ // completion for settlement when no task_completed recorded one.
3560
+ if (
3561
+ backgroundCompletion.status !== "running" &&
3562
+ context.backgroundCommands.get(backgroundCompletion.taskId) === null
3563
+ ) {
3564
+ context.backgroundCommands.set(backgroundCompletion.taskId, {
3565
+ status: backgroundCompletion.status,
3566
+ output: toolOutputText(hydrated),
3567
+ });
3568
+ }
3569
yield* emitTool(context, hydrated);
3570
}
3571
}
packages/provider-grok/src/server/xaiAcpExtension.test.ts
+148
@@ -484,6 +484,73 @@ describe("XAiAcpExtension", () => {
484
expect(normalized.status).toBe("inProgress");
485
});
486
487
+ it("completes structured command TaskOutput ids without treating them as subagents", () => {
488
+ // Oracle: BackgroundTaskStarted and TaskOutput from the Grok hang incident.
489
+ const toolCall: AcpToolCallState = {
490
+ toolCallId: "call-poll",
491
+ title: "get_command_or_subagent_output",
492
+ status: "completed",
493
+ data: {
494
+ rawInput: {
495
+ variant: "TaskOutput",
496
+ task_ids: ["call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29"],
497
+ },
498
+ rawOutput: {
499
+ type: "TaskOutput",
500
+ Result: {
501
+ task_id: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
502
+ status: "completed",
503
+ exit_code: 0,
504
+ output: "done",
505
+ },
506
+ },
507
+ },
508
+ };
509
+ expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([
510
+ {
511
+ taskId: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
512
+ status: "completed",
513
+ appendOutput: "done",
514
+ },
515
+ ]);
516
+ expect(extractXAiAcpSubagentUpdate(toolCall)).toBeUndefined();
517
+ });
518
+
519
+ it("keeps the normal tool frame for a command result from a mixed-ID poll", () => {
520
+ // Oracle: review 4325739061 requires the result ID to override requested subagent IDs.
521
+ const toolCall: AcpToolCallState = {
522
+ toolCallId: "call-mixed-poll",
523
+ title: "get_command_or_subagent_output",
524
+ status: "completed",
525
+ data: {
526
+ rawInput: {
527
+ variant: "TaskOutput",
528
+ task_ids: [
529
+ "019f44a6-4820-7402-925d-bc862ee711dd",
530
+ "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
531
+ ],
532
+ },
533
+ rawOutput: {
534
+ type: "TaskOutput",
535
+ Result: {
536
+ task_id: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
537
+ status: "completed",
538
+ exit_code: 0,
539
+ output: "done",
540
+ },
541
+ },
542
+ },
543
+ };
544
+ expect(extractXAiAcpSubagentUpdate(toolCall)).toBeUndefined();
545
+ expect(extractXAiBackgroundTaskCompletion(toolCall)).toEqual([
546
+ {
547
+ taskId: "call-7c835a60-7bf5-4284-a5c7-cf42a4212ece-29",
548
+ status: "completed",
549
+ appendOutput: "done",
550
+ },
551
+ ]);
552
+ });
553
+
554
it("hydrates monitor completion from a standalone TaskOutput frame without rawInput", () => {
555
// Post-settle shape observed live (2026-07-12): the final
556
// get_command_or_subagent_output update carries only rawOutput; the frame
@@ -615,6 +682,87 @@ describe("XAiAcpExtension", () => {
682
]);
683
});
684
685
+ // Oracle: #15888 reports KillTask replies with killed and already_exited outcomes.
686
+ it.each([
687
+ { rawInput: { task_id: "call-bg-1" }, rawOutput: { type: "KillTask" } },
688
+ { rawInput: { task_id: "call-bg-1" }, rawOutput: { type: "KillTask", outcome: "killed" } },
689
+ { rawInput: { variant: "KillTask", task_id: "call-bg-1" } },
690
+ {
691
+ rawInput: { variant: "KillTask", task_id: "call-bg-1" },
692
+ rawOutput: { type: "KillTask", outcome: "already_exited" },
693
+ },
694
+ ])("closes a background command from structured KillTask fields: %j", (data) => {
695
+ expect(
696
+ extractXAiKilledBackgroundTasks({
697
+ toolCallId: "call-kill",
698
+ title: "kill call-bg-1 (killed)",
699
+ status: "completed",
700
+ data,
701
+ }),
702
+ ).toEqual([{ taskId: "call-bg-1", status: "completed", appendOutput: "" }]);
703
+ expect(
704
+ extractXAiAcpSubagentUpdate({
705
+ toolCallId: "call-kill",
706
+ title: "kill call-bg-1 (killed)",
707
+ status: "completed",
708
+ data,
709
+ }),
710
+ ).toBeUndefined();
711
+ });
712
+
713
+ // Native child status still comes from its lifecycle/result path, not the kill RPC.
714
+ it.each(["Kill", "KillTask"])(
715
+ "keeps %s aimed at a native child out of child result parsing",
716
+ (variant) => {
717
+ expect(
718
+ extractXAiAcpSubagentUpdate({
719
+ toolCallId: "call-kill-child",
720
+ title: "kill 019f44b8-8e98-7c80-a40e-df1e26a5f9e3 (killed)",
721
+ status: "completed",
722
+ data: {
723
+ rawInput: { variant, task_id: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3" },
724
+ rawOutput: { type: "KillTask", outcome: "killed" },
725
+ },
726
+ }),
727
+ ).toBeUndefined();
728
+ },
729
+ );
730
+
731
+ // A successful RPC is not proof of a successful kill when its outcome says otherwise.
732
+ it.each([
733
+ { type: "KillTask", outcome: "failed" },
734
+ { type: "KillTask", Result: { task_id: "call-bg-1", outcome: "error" } },
735
+ ])("ignores a KillTask whose outcome is not a kill: %j", (rawOutput) => {
736
+ expect(
737
+ extractXAiKilledBackgroundTasks({
738
+ toolCallId: "call-kill",
739
+ title: "kill call-bg-1 (failed)",
740
+ status: "completed",
741
+ data: {
742
+ rawInput: { variant: "KillTask", task_id: "call-bg-1" },
743
+ rawOutput,
744
+ },
745
+ }),
746
+ ).toEqual([]);
747
+ });
748
+
749
+ it.each(["failed", "inProgress"] as const)(
750
+ "does not close the target of a %s KillTask call",
751
+ (status) => {
752
+ expect(
753
+ extractXAiKilledBackgroundTasks({
754
+ toolCallId: "call-kill",
755
+ title: "kill call-bg-1 (killed)",
756
+ status,
757
+ data: {
758
+ rawInput: { variant: "KillTask", task_id: "call-bg-1" },
759
+ rawOutput: { type: "KillTask", outcome: "killed" },
760
+ },
761
+ }),
762
+ ).toEqual([]);
763
+ },
764
+ );
765
+
766
it("tombstones confirmed kills and ignores failed kill calls", () => {
767
expect(
768
extractXAiKilledBackgroundTasks({
packages/provider-grok/src/server/xaiAcpExtension.ts
+32
-12
@@ -272,8 +272,8 @@ export function isXAiMonitorTool(toolCall: AcpToolCallState): boolean {
272
* A shell command Grok runs in the background (asked for, or moved there after
273
* its auto-background timeout) acknowledges with
274
* `{ 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.
277
*/
278
export function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined {
279
const rawOutput = unknownRecord(toolCall.data.rawOutput);
@@ -333,7 +333,9 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState):
333
const appendOutput = resultFromGetOutputTool(toolCall, text) ?? "";
334
// Prefer the completed identity from the result/header over the request list
335
// (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);
339
if (resultTaskId !== undefined) {
340
return [{ taskId: resultTaskId, status, appendOutput }];
341
}
@@ -355,8 +357,8 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState):
357
358
/**
359
* A finished kill_command_or_subagent call is the genuine end signal for every
358
- * task id it names: the Grok CLI emits no `x.ai/task_completed` for a killed
359
- * task. A failed kill is not proof the target stopped, so leave the existing
360
+ * task id it names, even without a separate `x.ai/task_completed` notification.
361
+ * A failed kill is not proof the target stopped, so leave the existing
362
* task state unchanged until a genuine terminal signal arrives.
363
*/
364
export function extractXAiKilledBackgroundTasks(toolCall: AcpToolCallState): ReadonlyArray<{
@@ -366,9 +368,15 @@ export function extractXAiKilledBackgroundTasks(toolCall: AcpToolCallState): Rea
368
}> {
369
const title = titleKey(toolCall);
370
const rawInput = unknownRecord(toolCall.data.rawInput);
371
+ const rawOutput = unknownRecord(toolCall.data.rawOutput);
372
const variant = nonEmptyString(rawInput?.variant)?.toLowerCase();
370
- if (!title.includes("kill_command_or_subagent") && variant !== "kill") return [];
373
+ const legacy = title.includes("kill_command_or_subagent") || variant === "kill";
374
+ if (!legacy && variant !== "killtask" && rawOutput?.type !== "KillTask") return [];
375
if (toolCall.status !== "completed") return [];
376
+ // Grok nests the outcome under Result; only a missing, killed or already_exited one ends the task.
377
+ const outcome = rawOutput?.outcome ?? unknownRecord(rawOutput?.Result)?.outcome;
378
+ if (!legacy && outcome !== undefined && outcome !== "killed" && outcome !== "already_exited")
379
+ return [];
380
const taskIds: string[] = [];
381
const push = (value: unknown) => {
382
const id = nonEmptyString(value);
@@ -742,17 +750,22 @@ function taskIdsFromGetOutputTool(
750
return [...new Set(ids)];
751
}
752
745
-function resultTaskIdFromGetOutputTool(
746
- toolCall: AcpToolCallState,
747
- output: string | undefined,
748
-): string | undefined {
753
+function structuredTaskIdFromGetOutputTool(toolCall: AcpToolCallState): string | undefined {
754
const rawOutput = unknownRecord(toolCall.data.rawOutput);
755
const result = unknownRecord(rawOutput?.Result) ?? unknownRecord(rawOutput?.result);
751
- const structured =
756
+ return (
757
nonEmptyString(result?.task_id) ??
758
nonEmptyString(result?.taskId) ??
759
nonEmptyString(rawOutput?.task_id) ??
755
- nonEmptyString(rawOutput?.taskId);
760
+ nonEmptyString(rawOutput?.taskId)
761
+ );
762
+}
763
+
764
+function resultTaskIdFromGetOutputTool(
765
+ toolCall: AcpToolCallState,
766
+ output: string | undefined,
767
+): string | undefined {
768
+ const structured = structuredTaskIdFromGetOutputTool(toolCall);
769
if (structured !== undefined && new RegExp(`^${XAI_UUID_RE}$`, "i").test(structured)) {
770
return structured;
771
}
@@ -831,6 +844,13 @@ export function extractXAiAcpSubagentUpdate(
844
const output = xAiToolOutputText(toolCall);
845
846
if (isXAiGetSubagentOutputTool(toolCall, rawInput)) {
847
+ const structuredTaskId = structuredTaskIdFromGetOutputTool(toolCall);
848
+ if (
849
+ structuredTaskId !== undefined &&
850
+ !new RegExp(`^${XAI_UUID_RE}$`, "i").test(structuredTaskId)
851
+ ) {
852
+ return undefined;
853
+ }
854
const taskIds = taskIdsFromGetOutputTool(toolCall, rawInput);
855
const childSessionId =
856
resultTaskIdFromGetOutputTool(toolCall, output) ??