@devries-cameron20 / t3code Mirror · read-only / commits / 7f6e403a88
Fork 0

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 21, 12:15 UTC

fix(provider-acp): Grok runs complete when a background dev server keeps running (#32109)

Julius Marminge committed Nov 14, 2026 at 18:52 UTC 7f6e403a88815e5644efbdb6bc8625246f661095
5 files changed +345 -35
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+265 -18
@@ -10155,8 +10155,6 @@ describe("AcpAdapterV2", () => {
10155 | undefined;
10156 const promptStarted = yield* Deferred.make<void>();
10157 const promptGate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
10158 - const promptHeld = yield* Deferred.make<void>();
10159 - const finalizeScheduled = yield* Deferred.make<Duration.Input>();
10158 const continuationOffered = yield* Deferred.make<void>();
10159 const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
10160 [];
@@ -10174,12 +10172,6 @@ describe("AcpAdapterV2", () => {
10172 const adapter = yield* makeAcpAdapterV2({
10173 instanceId,
10174 selfInvocation,
10177 - testHooks: {
10178 - afterPromptSettledWithBackgroundWork: () =>
10179 - Deferred.succeed(promptHeld, undefined).pipe(Effect.asVoid),
10180 - onDeferredFinalizeScheduled: (debounce) =>
10181 - Deferred.succeed(finalizeScheduled, debounce).pipe(Effect.asVoid),
10182 - },
10175 flavor: {
10176 driver: ACP_TEST_DRIVER,
10177 capabilities: AcpProviderCapabilitiesV2,
@@ -10245,11 +10237,15 @@ describe("AcpAdapterV2", () => {
10237 runtimePolicy,
10238 });
10239 const now = yield* DateTime.now;
10248 - yield* runtime
10249 - .startTurn(
10250 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
10251 - )
10252 - .pipe(Effect.forkScoped);
10240 + const turnInput = makeTurnInput({
10241 + threadId,
10242 + providerThread,
10243 + instanceId,
10244 + runtimePolicy,
10245 + now,
10246 + ordinal: 1,
10247 + });
10248 + yield* runtime.startTurn(turnInput).pipe(Effect.forkScoped);
10249 yield* Deferred.await(promptStarted);
10250 assert.isDefined(sessionUpdateHandler);
10251 assert.isDefined(taskCompleted);
@@ -10308,9 +10304,19 @@ describe("AcpAdapterV2", () => {
10304 }
10305 });
10306 yield* Deferred.succeed(promptGate, { stopReason: "end_turn" });
10311 - yield* Deferred.await(promptHeld);
10307 + while (true) {
10308 + const event = yield* Queue.take(events);
10309 + if (
10310 + event.type === "turn_item.updated" &&
10311 + event.turnItem.nativeItemRef?.nativeId === "early"
10312 + )
10313 + backgroundItem = event;
10314 + if (event.type !== "turn.terminal") continue;
10315 + assert.equal(event.status, "completed", "the running blocker does not hold the root");
10316 + break;
10317 + }
10318 yield* assertCommand(status, "EARLY_BG_DONE\n");
10313 - assert.lengthOf(continuationRequests, 0, "the other command still holds the root open");
10319 + assert.lengthOf(continuationRequests, 0, "the running blocker defers the wake");
10320
10321 const replayAck = () =>
10322 update({
@@ -10338,11 +10344,15 @@ describe("AcpAdapterV2", () => {
10344 }
10345 }
10346 yield* complete("blocker", { exit_code: 0, output: "BLOCKER_DONE\n" });
10341 - yield* TestClock.adjust(yield* Deferred.await(finalizeScheduled));
10347 while (true) {
10348 const event = yield* Queue.take(events);
10344 - if (event.type !== "turn.terminal") continue;
10345 - assert.equal(event.status, "completed");
10349 + if (event.type !== "turn_item.updated") continue;
10350 + if (event.turnItem.nativeItemRef?.nativeId !== "blocker") continue;
10351 + if (event.turnItem.status !== "completed") continue;
10352 + assert.equal(event.turnItem.runId, turnInput.runId, "the row stays on its run");
10353 + if (event.turnItem.type === "command_execution") {
10354 + assert.equal(event.turnItem.output, "BLOCKER_DONE\n");
10355 + }
10356 break;
10357 }
10358 yield* Deferred.await(continuationOffered);
@@ -10356,6 +10366,243 @@ describe("AcpAdapterV2", () => {
10366 }).pipe(Effect.provide(layerTest)),
10367 );
10368
10369 + // A dev server started as a background shell never exits, so it must not hold the root turn.
10370 + const startGrokBackgroundShellTurn = Effect.fnUntraced(function* (name: string) {
10371 + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
10372 + const path = yield* Path.Path;
10373 + const selfInvocation = yield* resolveSelfInvocation();
10374 + const mockAgentPath = yield* path.fromFileUrl(
10375 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
10376 + );
10377 + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
10378 + let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
10379 + let taskCompleted:
10380 + | ((payload: unknown) => Effect.Effect<void, EffectAcpErrors.AcpError>)
10381 + | undefined;
10382 + const promptStarted = yield* Deferred.make<void>();
10383 + const promptGate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
10384 + const promptHeld = yield* Deferred.make<void>();
10385 + const finalizeScheduled = yield* Deferred.make<Duration.Input>();
10386 + const instanceId = ProviderInstanceId.make("acp-test");
10387 + const grokFlavor = makeGrokAcpAdapterFlavor(
10388 + {
10389 + instanceId,
10390 + settings: DEFAULT_GROK_SETTINGS,
10391 + environment: {},
10392 + hostPlatform: yield* HostProcess.Platform,
10393 + selfInvocation,
10394 + },
10395 + yield* HostProcess.HomeDirectory,
10396 + );
10397 + const adapter = yield* makeAcpAdapterV2({
10398 + instanceId,
10399 + selfInvocation,
10400 + testHooks: {
10401 + afterPromptSettledWithBackgroundWork: () =>
10402 + Deferred.succeed(promptHeld, undefined).pipe(Effect.asVoid),
10403 + onDeferredFinalizeScheduled: (debounce) =>
10404 + Deferred.succeed(finalizeScheduled, debounce).pipe(Effect.asVoid),
10405 + },
10406 + flavor: {
10407 + driver: ACP_TEST_DRIVER,
10408 + capabilities: AcpProviderCapabilitiesV2,
10409 + enablePostSettleContinuation: true,
10410 + deferFinalizeForBackgroundWork: grokFlavor.deferFinalizeForBackgroundWork!,
10411 + normalizeToolCall: grokFlavor.normalizeToolCall!,
10412 + extractBackgroundTaskId: grokFlavor.extractBackgroundTaskId!,
10413 + isBackgroundCommandTool: grokFlavor.isBackgroundCommandTool!,
10414 + isPersistentBackgroundTool: grokFlavor.isPersistentBackgroundTool!,
10415 + registerExtensions: ({ runtime, applyBackgroundTaskMutation }) =>
10416 + registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation),
10417 + makeRuntime: makeMockRuntime({
10418 + childProcessSpawner,
10419 + mockAgentPath,
10420 + wrapRuntime: (runtime) => ({
10421 + ...runtime,
10422 + handleSessionUpdate: (handler) =>
10423 + Effect.sync(() => {
10424 + sessionUpdateHandler = handler;
10425 + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
10426 + handleExtNotification: (method, schema, handler) =>
10427 + Effect.sync(() => {
10428 + if (method === "x.ai/task_completed") {
10429 + taskCompleted = (payload) => handler(Schema.decodeUnknownSync(schema)(payload));
10430 + }
10431 + }).pipe(Effect.andThen(runtime.handleExtNotification(method, schema, handler))),
10432 + prompt: () =>
10433 + Deferred.succeed(promptStarted, undefined).pipe(
10434 + Effect.andThen(Deferred.await(promptGate)),
10435 + ),
10436 + }),
10437 + }),
10438 + },
10439 + });
10440 + const threadId = ThreadId.make(`thread-acp-${name}`);
10441 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
10442 + runtimeMode: "full-access",
10443 + interactionMode: "default",
10444 + cwd: process.cwd(),
10445 + });
10446 + const modelSelection = { instanceId, model: "default" } as const;
10447 + const runtime = yield* adapter.openSession({
10448 + threadId,
10449 + providerSessionId: ProviderSessionId.make(`provider-session-acp-${name}`),
10450 + modelSelection,
10451 + runtimePolicy,
10452 + });
10453 + const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
10454 + yield* runtime.events.pipe(
10455 + Stream.runForEach((event) => Queue.offer(events, event)),
10456 + Effect.forkScoped,
10457 + );
10458 + const providerThread = yield* runtime.ensureThread({
10459 + threadId,
10460 + modelSelection,
10461 + runtimePolicy,
10462 + });
10463 + const turnInput = makeTurnInput({
10464 + threadId,
10465 + providerThread,
10466 + instanceId,
10467 + runtimePolicy,
10468 + now: yield* DateTime.now,
10469 + });
10470 + yield* runtime.startTurn(turnInput).pipe(Effect.forkScoped);
10471 + yield* Deferred.await(promptStarted);
10472 + assert.isDefined(sessionUpdateHandler);
10473 + assert.isDefined(taskCompleted);
10474 + const update = (update: EffectAcpSchema.SessionUpdate) =>
10475 + sessionUpdateHandler!({ sessionId: "mock-session-1", update });
10476 + const complete = (taskId: string, snapshot?: { output?: string; exit_code?: number }) =>
10477 + taskCompleted!({
10478 + sessionId: "mock-session-1",
10479 + update: { sessionUpdate: "task_completed", task_id: taskId, task_snapshot: snapshot },
10480 + });
10481 + const startDevServer = Effect.gen(function* () {
10482 + yield* update({
10483 + sessionUpdate: "tool_call",
10484 + toolCallId: "call-dev-server",
10485 + title: "run_terminal_command",
10486 + kind: "execute",
10487 + status: "in_progress",
10488 + rawInput: { command: "vp run dev" },
10489 + });
10490 + yield* update({
10491 + sessionUpdate: "tool_call_update",
10492 + toolCallId: "call-dev-server",
10493 + status: "completed",
10494 + rawOutput: {
10495 + type: "BackgroundTaskStarted",
10496 + task_id: "call-dev-server",
10497 + task_type: "bash",
10498 + status: "running",
10499 + command: "vp run dev",
10500 + },
10501 + });
10502 + });
10503 + /** Settles the prompt and returns the dev server rows emitted up to the turn terminal. */
10504 + const settle = Effect.gen(function* () {
10505 + const rows: Array<OrchestrationV2TurnItem> = [];
10506 + const takeTerminal = Effect.gen(function* () {
10507 + while (true) {
10508 + const event = yield* Queue.take(events);
10509 + if (
10510 + event.type === "turn_item.updated" &&
10511 + event.turnItem.nativeItemRef?.nativeId === "call-dev-server"
10512 + )
10513 + rows.push(event.turnItem);
10514 + if (event.type === "turn.terminal") return event.status;
10515 + }
10516 + });
10517 + yield* Deferred.succeed(promptGate, { stopReason: "end_turn" });
10518 + const status = yield* Effect.raceAll([
10519 + takeTerminal,
10520 + Deferred.await(finalizeScheduled).pipe(
10521 + Effect.flatMap(TestClock.adjust),
10522 + Effect.andThen(takeTerminal),
10523 + ),
10524 + // The hold never ends on its own, so report it instead of waiting forever.
10525 + Deferred.await(promptHeld).pipe(Effect.as("held open by the background shell")),
10526 + ]);
10527 + return { status, rows };
10528 + });
10529 + /** Dev server rows emitted before a usage update fences them. */
10530 + const takeRows = Effect.gen(function* () {
10531 + yield* update({ sessionUpdate: "usage_update", used: 10, size: 100 });
10532 + const rows: Array<OrchestrationV2TurnItem> = [];
10533 + while (true) {
10534 + const event = yield* Queue.take(events);
10535 + if (event.type === "provider_thread.updated") return rows;
10536 + if (
10537 + event.type === "turn_item.updated" &&
10538 + event.turnItem.nativeItemRef?.nativeId === "call-dev-server"
10539 + )
10540 + rows.push(event.turnItem);
10541 + }
10542 + });
10543 + return { update, complete, startDevServer, settle, takeRows, runId: turnInput.runId };
10544 + });
10545 +
10546 + it.effect("completes a settled Grok turn while a background shell keeps running", () =>
10547 + Effect.gen(function* () {
10548 + const harness = yield* startGrokBackgroundShellTurn("grok-dev-server");
10549 + yield* harness.startDevServer;
10550 + yield* harness.update({
10551 + sessionUpdate: "agent_message_chunk",
10552 + content: { type: "text", text: "The dev server is running." },
10553 + });
10554 + assert.equal((yield* harness.settle).status, "completed");
10555 + }).pipe(Effect.provide(layerTest), Effect.scoped),
10556 + );
10557 +
10558 + it.effect("keeps a streaming Grok background shell running on its run after settling", () =>
10559 + Effect.gen(function* () {
10560 + const harness = yield* startGrokBackgroundShellTurn("grok-dev-server-progress");
10561 + yield* harness.startDevServer;
10562 + // Progress replaces the BackgroundTaskStarted output that carried the task identity.
10563 + yield* harness.update({
10564 + sessionUpdate: "tool_call_update",
10565 + toolCallId: "call-dev-server",
10566 + status: "in_progress",
10567 + rawOutput: { type: "Text", text: "VITE ready\n" },
10568 + });
10569 + const settled = yield* harness.settle;
10570 + assert.equal(settled.status, "completed");
10571 + assert.notInclude(
10572 + settled.rows.map((row) => row.status),
10573 + "completed",
10574 + "the running dev server was finalized as a foreground tool",
10575 + );
10576 +
10577 + yield* harness.update({
10578 + sessionUpdate: "tool_call_update",
10579 + toolCallId: "call-dev-server",
10580 + status: "in_progress",
10581 + rawOutput: { type: "Text", text: "VITE ready\nhmr update\n" },
10582 + });
10583 + yield* harness.complete("call-dev-server", { exit_code: 0, output: "DEV_SERVER_DONE\n" });
10584 + const row = (yield* harness.takeRows).at(-1);
10585 + assert.equal(row?.status, "completed");
10586 + assert.equal(row?.runId, harness.runId);
10587 + assert.equal(row?.type === "command_execution" ? row.output : undefined, "DEV_SERVER_DONE\n");
10588 + }).pipe(Effect.provide(layerTest), Effect.scoped),
10589 + );
10590 +
10591 + it.effect("applies a richer Grok background shell failure after a sparse completion", () =>
10592 + Effect.gen(function* () {
10593 + const harness = yield* startGrokBackgroundShellTurn("grok-dev-server-failure");
10594 + yield* harness.startDevServer;
10595 + assert.equal((yield* harness.settle).status, "completed");
10596 +
10597 + yield* harness.complete("call-dev-server");
10598 + yield* harness.complete("call-dev-server", { exit_code: 1, output: "EADDRINUSE\n" });
10599 + const row = (yield* harness.takeRows).at(-1);
10600 + assert.equal(row?.status, "failed");
10601 + assert.equal(row?.runId, harness.runId);
10602 + assert.equal(row?.type === "command_execution" ? row.output : undefined, "EADDRINUSE\n");
10603 + }).pipe(Effect.provide(layerTest), Effect.scoped),
10604 + );
10605 +
10606 it.live("durably poisons start and resume when required hard teardown is unavailable", () =>
10607 Effect.gen(function* () {
10608 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash/input.ts
+1 -1
@@ -12,7 +12,7 @@ export function grokBackgroundBashInput(): OrchestratorFixtureInput {
12 return {
13 steps: [
14 { type: "message", text: GROK_BACKGROUND_BASH_PROMPT },
15 - { type: "finish_held_run", targetRunIndex: 1, status: "completed" },
15 + { type: "await_run_status", targetRunIndex: 1, status: "completed" },
16 { type: "release_replay_gate", label: GROK_BACKGROUND_BASH_WAKE_LABEL },
17 { type: "finish_held_run", targetRunIndex: 2, status: "completed" },
18 ],
apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash/output.ts
+5 -4
@@ -58,14 +58,15 @@ export function assertGrokBackgroundBashOutput(
58 event.payload.id === command?.id &&
59 event.payload.status === "completed",
60 );
61 - const rootCompletedAt = result.domainEvents.findIndex(
61 + // The root turn ends with the prompt; a background shell may be a dev server that never exits.
62 + const rootTurnEndedAt = result.domainEvents.findIndex(
63 (event) =>
64 event.type === "run.updated" &&
65 event.payload.id === rootRun?.id &&
65 - event.payload.status === "completed",
66 + (event.payload.status === "waiting" || event.payload.status === "completed"),
67 );
67 - assert.isAtLeast(commandCompletedAt, 0);
68 - assert.isAbove(rootCompletedAt, commandCompletedAt, "run 1 completed before the command ended");
68 + assert.isAtLeast(rootTurnEndedAt, 0);
69 + assert.isBelow(rootTurnEndedAt, commandCompletedAt, "run 1 waited for the command to end");
70
71 const rootTexts = projection.turnItems.flatMap((item) =>
72 item.runId === rootRun?.id && item.type === "assistant_message" ? [item.text.trim()] : [],
apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash_fast_wake/input.ts
-1
@@ -5,7 +5,6 @@ export function grokBackgroundBashFastWakeInput(): OrchestratorFixtureInput {
5 return {
6 steps: [
7 { type: "message", text: GROK_BACKGROUND_BASH_PROMPT },
8 - { type: "finish_held_run", targetRunIndex: 1, status: "completed" },
8 { type: "finish_held_run", targetRunIndex: 2, status: "completed" },
9 ],
10 };
packages/provider-acp/src/server/adapter.ts
+74 -11
@@ -1671,11 +1671,13 @@ function acpPostSettleMonitorPromptShouldSuppress(
1671 }
1672
1673 export function acpCompletedTurnShouldTerminalizeTool(
1674 - tool: AcpToolCallState,
1674 + tool: AcpToolCallState & { readonly backgroundCommandTaskId?: string },
1675 flavor: Pick<AcpAdapterV2Flavor, "extractBackgroundTaskId" | "extractSubagentUpdate">,
1676 ): boolean {
1677 const status = toolStatus(tool.status);
1678 if (status !== "pending" && status !== "running") return false;
1679 + // Progress output replaces the start ACK, so the registered task id outlives it.
1680 + if (tool.backgroundCommandTaskId !== undefined) return false;
1681 if (flavor.extractBackgroundTaskId?.(tool) !== undefined) return false;
1682 return flavor.extractSubagentUpdate?.(tool) === undefined;
1683 }
@@ -2385,6 +2387,36 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2387 // Grok re-prompts on stale monitor notices; suppress output until a genuine terminal or app turn.
2388 const suppressPostSettleMonitorPrompt = yield* Ref.make(false);
2389 const runningBackgroundTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
2390 + // Background command task id → the completed turn that owns its row. Ended commands stay,
2391 + // bounded, so a later authoritative terminal still corrects the row on its run.
2392 + const detachedBackgroundCommands = yield* Ref.make<ReadonlyMap<string, ActiveAcpTurn>>(
2393 + new Map(),
2394 + );
2395 + const endedDetachedBackgroundCommandLimit = 16;
2396 + const detachedBackgroundCommandTurn = (taskId: string) =>
2397 + Ref.get(detachedBackgroundCommands).pipe(Effect.map((turns) => turns.get(taskId)));
2398 + /** The turn a background task's terminal belongs to: its detached turn, else the live one. */
2399 + const backgroundCommandTurn = Effect.fnUntraced(function* (taskId: string) {
2400 + const detached = yield* detachedBackgroundCommandTurn(taskId);
2401 + if (detached !== undefined) return detached;
2402 + const active = yield* Ref.get(activeTurn);
2403 + return active?.finalized === false ? active : undefined;
2404 + });
2405 + const detachBackgroundCommands = (context: ActiveAcpTurn) =>
2406 + Ref.update(detachedBackgroundCommands, (current) => {
2407 + const next = new Map(current);
2408 + for (const taskId of context.backgroundCommands.keys()) next.set(taskId, context);
2409 + const ended = [...next].filter(([taskId, turn]) => {
2410 + const toolCallId = turn.toolCallIdsByBackgroundTaskId.get(taskId);
2411 + const tool = toolCallId === undefined ? undefined : turn.tools.get(toolCallId);
2412 + const status = tool === undefined ? "completed" : toolStatus(tool.status);
2413 + return status !== "pending" && status !== "running";
2414 + });
2415 + for (const [taskId] of ended.slice(0, -endedDetachedBackgroundCommandLimit)) {
2416 + next.delete(taskId);
2417 + }
2418 + return next;
2419 + });
2420 // Tombstones prevent mid-stream exit_code 0 and stale monitor events from resurrecting ended tasks.
2421 const endedBackgroundTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
2422 const endedBackgroundTaskIdLimit = 128;
@@ -3958,6 +3990,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3990 if (context.pendingInjectedReport.size > 0) return true;
3991 for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) {
3992 if (context.persistentBackgroundTaskIds.has(taskId)) continue;
3993 + // Commands are as often a dev server as a wait; only their wake follows up.
3994 + if (context.backgroundCommands.has(taskId)) continue;
3995 const tool = context.tools.get(toolCallId);
3996 if (tool === undefined) continue;
3997 const status = toolStatus(tool.status);
@@ -4143,14 +4177,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4177 if (backgroundCompletion.status !== "running") {
4178 context.awaitingBackgroundHydration.delete(backgroundCompletion.taskId);
4179 }
4146 - const targetToolCallId = context.toolCallIdsByBackgroundTaskId.get(
4180 + const owner = context.toolCallIdsByBackgroundTaskId.has(backgroundCompletion.taskId)
4181 + ? context
4182 + : ((yield* detachedBackgroundCommandTurn(backgroundCompletion.taskId)) ?? context);
4183 + const targetToolCallId = owner.toolCallIdsByBackgroundTaskId.get(
4184 backgroundCompletion.taskId,
4185 );
4186 if (targetToolCallId !== undefined) {
4187 hydratedRegisteredMonitor = true;
4188 }
4189 const target =
4153 - targetToolCallId !== undefined ? context.tools.get(targetToolCallId) : undefined;
4190 + targetToolCallId !== undefined ? owner.tools.get(targetToolCallId) : undefined;
4191 if (target !== undefined && target.toolCallId !== toolCall.toolCallId) {
4192 const nextStatus =
4193 backgroundCompletion.status === "running"
@@ -4175,14 +4212,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4212 // completion for settlement when no task_completed recorded one.
4213 if (
4214 backgroundCompletion.status !== "running" &&
4178 - context.backgroundCommands.get(backgroundCompletion.taskId) === null
4215 + owner.backgroundCommands.get(backgroundCompletion.taskId) === null
4216 ) {
4180 - context.backgroundCommands.set(backgroundCompletion.taskId, {
4217 + owner.backgroundCommands.set(backgroundCompletion.taskId, {
4218 status: backgroundCompletion.status,
4219 output: toolOutputText(hydrated),
4220 });
4221 }
4185 - yield* emitTool(context, hydrated);
4222 + yield* emitTool(owner, hydrated);
4223 }
4224 }
4225
@@ -4917,8 +4954,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4954 readonly status: "completed" | "failed";
4955 readonly output?: string;
4956 }) {
4920 - const context = yield* Ref.get(activeTurn);
4921 - if (context === null || context.finalized || !context.promptSettled) return;
4957 + const context = yield* backgroundCommandTurn(mutation.taskId);
4958 + if (context === undefined || !context.promptSettled) return;
4959 const toolCallId = context.toolCallIdsByBackgroundTaskId.get(mutation.taskId);
4960 const tool = toolCallId === undefined ? undefined : context.tools.get(toolCallId);
4961 if (tool === undefined) return;
@@ -4940,6 +4977,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4977 yield* rearmDeferredFinalize(context);
4978 });
4979
4980 + // Output and replays for a detached command land on its row, not in the wake buffer.
4981 + const projectDetachedBackgroundCommand = Effect.fnUntraced(function* (
4982 + notification: EffectAcpSchema.SessionNotification,
4983 + active: ActiveAcpTurn | null,
4984 + ) {
4985 + const update = notification.update;
4986 + if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
4987 + return false;
4988 + }
4989 + if (active?.finalized === false && active.tools.has(update.toolCallId)) return false;
4990 + if (notification.sessionId !== (yield* Ref.get(activeSessionId))) return false;
4991 + const owner = [...(yield* Ref.get(detachedBackgroundCommands)).values()].find(
4992 + (turn) => turn.tools.get(update.toolCallId)?.backgroundCommandTaskId !== undefined,
4993 + );
4994 + if (owner === undefined) return false;
4995 + for (const event of parseSessionUpdateEvent(notification).events) {
4996 + if (event._tag === "ToolCallUpdated") yield* emitTool(owner, event.toolCall);
4997 + }
4998 + return true;
4999 + });
5000 +
5001 const bufferPostSettleWake = Effect.fnUntraced(function* (
5002 notification: EffectAcpSchema.SessionNotification,
5003 ) {
@@ -5233,6 +5291,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5291 )
5292 return;
5293 if (yield* projectAgentTerminalUpdate(notification, context)) return;
5294 + if (yield* projectDetachedBackgroundCommand(notification, context)) return;
5295 if (
5296 update.sessionUpdate === "usage_update" ||
5297 update.sessionUpdate === "session_info_update"
@@ -7117,12 +7176,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7176 Effect.gen(function* () {
7177 if (yield* Ref.get(stoppedRunQuarantine)) return;
7178 if ((yield* Ref.get(activeSessionId)) !== incoming.sessionId) return;
7120 - const context = yield* Ref.get(activeTurn);
7179 + const context = yield* backgroundCommandTurn(incoming.taskId);
7180 let mutation = incoming;
7181 if (
7182 incoming.status !== "running" &&
7124 - context !== null &&
7125 - !context.finalized &&
7183 + context !== undefined &&
7184 (incoming.report?.kind === "command" ||
7185 context.backgroundCommands.has(incoming.taskId))
7186 ) {
@@ -7421,6 +7479,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7479 yield* Ref.set(wakeReports, noWakeReports);
7480 yield* Ref.set(continuationRequested, false);
7481 yield* Ref.set(runningBackgroundTaskIds, new Set());
7482 + yield* Ref.set(detachedBackgroundCommands, new Map());
7483 yield* Ref.set(endedBackgroundTaskIds, new Set());
7484 yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set());
7485 yield* Ref.set(handledBackgroundTaskIdsInActiveTurn, new Set());
@@ -7918,6 +7977,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7977 yield* Ref.set(wakeReports, noWakeReports);
7978 yield* Ref.set(continuationRequested, false);
7979 yield* Ref.set(runningBackgroundTaskIds, new Set());
7980 + yield* Ref.set(detachedBackgroundCommands, new Map());
7981 yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set());
7982 yield* Ref.set(carryoverSubagents, null);
7983 yield* Ref.set(lastTurnRoute, null);
@@ -8102,6 +8162,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8162 }
8163 }
8164 yield* Ref.set(activeTurn, null);
8165 + if (settledStatus === "completed" && !directStopQuarantine) {
8166 + yield* detachBackgroundCommands(context);
8167 + }
8168 steerInjections.clear();
8169 if (
8170 postSettleContinuationEnabled &&