@devries-cameron20 / t3code Mirror · read-only / commits / 0b68a4a9c3
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 23, 13:00 UTC

fix(server): steering no longer ends running subagents (#19210)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

shivam committed Oct 15, 2026 at 17:36 UTC 0b68a4a9c36e90341491bad07196a8c123fd4e33
6 files changed +520 -82
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+312
@@ -1035,6 +1035,7 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {
1035 setModel: () => Effect.void,
1036 applyFlagSettings: () => Effect.void,
1037 setPermissionMode: () => Effect.void,
1038 + backgroundTasks: () => Effect.succeed(false),
1039 stopTask: () => Effect.void,
1040 interrupt: Effect.void,
1041 close: Effect.void,
@@ -1196,6 +1197,7 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functio
1197 setModel: () => Effect.void,
1198 applyFlagSettings: () => Effect.void,
1199 setPermissionMode: () => Effect.void,
1200 + backgroundTasks: () => Effect.succeed(false),
1201 stopTask: () => Effect.void,
1202 interrupt: Effect.void,
1203 close: Effect.void,
@@ -1317,6 +1319,7 @@ describe("ClaudeAdapterV2 resume compaction", () => {
1319 setModel: () => Effect.void,
1320 applyFlagSettings: () => Effect.void,
1321 setPermissionMode: () => Effect.void,
1322 + backgroundTasks: () => Effect.succeed(false),
1323 stopTask: () => Effect.void,
1324 interrupt: Effect.void,
1325 close: Effect.void,
@@ -1544,6 +1547,7 @@ describe("ClaudeAdapterV2 attachments", () => {
1547 setModel: () => Effect.void,
1548 applyFlagSettings: () => Effect.void,
1549 setPermissionMode: () => Effect.void,
1550 + backgroundTasks: () => Effect.succeed(false),
1551 stopTask: () => Effect.void,
1552 interrupt: Effect.void,
1553 close: Effect.void,
@@ -1690,6 +1694,7 @@ describe("ClaudeAdapterV2 attachments", () => {
1694 setModel: () => Effect.void,
1695 applyFlagSettings: () => Effect.void,
1696 setPermissionMode: () => Effect.void,
1697 + backgroundTasks: () => Effect.succeed(false),
1698 stopTask: () => Effect.void,
1699 interrupt: Effect.void,
1700 close: Effect.void,
@@ -1786,6 +1791,7 @@ describe("ClaudeAdapterV2 native fork", () => {
1791 setModel: () => Effect.void,
1792 applyFlagSettings: () => Effect.void,
1793 setPermissionMode: () => Effect.void,
1794 + backgroundTasks: () => Effect.succeed(false),
1795 stopTask: () => Effect.void,
1796 interrupt: Effect.void,
1797 close: Effect.void,
@@ -2079,6 +2085,7 @@ describe("ClaudeAdapterV2 native session identity", () => {
2085 setModel: () => Effect.void,
2086 applyFlagSettings: () => Effect.void,
2087 setPermissionMode: () => Effect.void,
2088 + backgroundTasks: () => Effect.succeed(false),
2089 stopTask: () => Effect.void,
2090 interrupt: Effect.void,
2091 close: Effect.void,
@@ -2340,6 +2347,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2347 readonly stopTask?: (
2348 taskId: string,
2349 ) => Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
2350 + readonly backgroundTasks?: (
2351 + toolUseId: string,
2352 + ) => Effect.Effect<boolean, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
2353 readonly environment?: NodeJS.ProcessEnv;
2354 readonly subagentLaunchToolUseId?: string;
2355 readonly nativeSessionId?: string;
@@ -2420,6 +2430,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2430 setModel: () => Effect.void,
2431 applyFlagSettings: () => Effect.void,
2432 setPermissionMode: () => Effect.void,
2433 + backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
2434 stopTask: options?.stopTask ?? (() => Effect.void),
2435 interrupt: Effect.void,
2436 close: Queue.shutdown(processMessages),
@@ -2460,6 +2471,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2471 Effect.sync(() => {
2472 permissionModeChanges.push(mode);
2473 }),
2474 + backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
2475 stopTask: options?.stopTask ?? (() => Effect.void),
2476 interrupt: options?.interrupt ?? Effect.void,
2477 close: options?.close?.(sdkMessages) ?? Effect.void,
@@ -5014,6 +5026,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
5026 setModel: () => Effect.void,
5027 applyFlagSettings: () => Effect.void,
5028 setPermissionMode: () => Effect.void,
5029 + backgroundTasks: () => Effect.succeed(false),
5030 stopTask: () => Effect.void,
5031 interrupt: Effect.void,
5032 // The first CLI process keeps streaming until the test ends
@@ -5275,6 +5288,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
5288 setModel: () => Effect.void,
5289 applyFlagSettings: () => Effect.void,
5290 setPermissionMode: () => Effect.void,
5291 + backgroundTasks: () => Effect.succeed(false),
5292 stopTask: () => Effect.void,
5293 interrupt: Effect.void,
5294 close: Queue.shutdown(queue),
@@ -10367,6 +10381,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10381 setModel: () => Effect.void,
10382 applyFlagSettings: () => Effect.void,
10383 setPermissionMode: () => Effect.void,
10384 + backgroundTasks: () => Effect.succeed(false),
10385 stopTask: () => Effect.void,
10386 interrupt: Effect.void,
10387 // End this process stream so openQuery can replace it.
@@ -10555,6 +10570,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10570 setModel: () => Effect.void,
10571 applyFlagSettings: () => Effect.void,
10572 setPermissionMode: () => Effect.void,
10573 + backgroundTasks: () => Effect.succeed(false),
10574 stopTask: () => Effect.void,
10575 interrupt: Effect.void,
10576 close: Queue.shutdown(sdkMessages),
@@ -10795,6 +10811,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10811 setModel: () => Effect.void,
10812 applyFlagSettings: () => Effect.void,
10813 setPermissionMode: () => Effect.void,
10814 + backgroundTasks: () => Effect.succeed(false),
10815 stopTask: () => Effect.void,
10816 interrupt: Effect.void,
10817 close: Queue.shutdown(sdkMessages),
@@ -10994,6 +11011,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11011 setModel: () => Effect.void,
11012 applyFlagSettings: () => Effect.void,
11013 setPermissionMode: () => Effect.void,
11014 + backgroundTasks: () => Effect.succeed(false),
11015 stopTask: () => Effect.void,
11016 interrupt: Effect.void,
11017 close: Queue.shutdown(sdkMessages),
@@ -11175,6 +11193,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11193 setModel: () => Effect.void,
11194 applyFlagSettings: () => Effect.void,
11195 setPermissionMode: () => Effect.void,
11196 + backgroundTasks: () => Effect.succeed(false),
11197 stopTask: () => Effect.void,
11198 interrupt: Effect.void,
11199 close: Queue.shutdown(sdkMessages),
@@ -11312,6 +11331,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11331 setModel: () => Effect.void,
11332 applyFlagSettings: () => Effect.void,
11333 setPermissionMode: () => Effect.void,
11334 + backgroundTasks: () => Effect.succeed(false),
11335 stopTask: () => Effect.void,
11336 interrupt: Effect.void,
11337 close: Queue.shutdown(sdkMessages),
@@ -13910,6 +13930,298 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13930 ),
13931 );
13932
13933 + it.effect.each([
13934 + { backgrounding: "succeeds" },
13935 + { backgrounding: "fails" },
13936 + { backgrounding: "never answers" },
13937 + { backgrounding: "answers after the steer went out" },
13938 + { backgrounding: "answers after the turn ended" },
13939 + { backgrounding: "answers after the subagent ran again" },
13940 + ] as const)(
13941 + "moves the root's foreground subagents to the background before a steer ($backgrounding)",
13942 + ({ backgrounding }) =>
13943 + Effect.scoped(
13944 + Effect.gen(function* () {
13945 + const FOREGROUND_TOOL_USE_ID = "toolu-steer-foreground";
13946 + const NESTED_TOOL_USE_ID = "toolu-steer-nested";
13947 + const FINISHED_TOOL_USE_ID = "toolu-steer-finished";
13948 + const calls: Array<string> = [];
13949 + // What happens while the move is still unanswered.
13950 + let beforeAnswer: Effect.Effect<void> = Effect.void;
13951 + const harness = yield* makeWakeHarnessWithOptions({
13952 + backgroundTasks: (toolUseId) =>
13953 + Effect.sync(() => calls.push(toolUseId)).pipe(
13954 + Effect.andThen(
13955 + backgrounding === "answers after the turn ended" ||
13956 + backgrounding === "answers after the subagent ran again"
13957 + ? Effect.suspend(() => beforeAnswer).pipe(Effect.as(true))
13958 + : backgrounding === "fails"
13959 + ? Effect.fail(
13960 + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
13961 + method: "backgroundTasks",
13962 + cause: new Error("Background tasks are disabled in this session."),
13963 + }),
13964 + )
13965 + : backgrounding === "never answers"
13966 + ? Effect.never
13967 + : backgrounding === "answers after the steer went out"
13968 + ? Effect.sleep("6 seconds").pipe(Effect.as(true))
13969 + : Effect.succeed(true),
13970 + ),
13971 + ),
13972 + });
13973 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
13974 + const attemptId = RunAttemptId.make("attempt-steer-foreground-subagent");
13975 + const input = makeClaudeTestTurnInput({
13976 + threadId: harness.threadId,
13977 + providerThread: harness.providerThread,
13978 + now: yield* DateTime.now,
13979 + attemptId,
13980 + text: "Audit the repo with a subagent.",
13981 + attachments: [],
13982 + });
13983 + yield* harness.runtime.startTurn(input);
13984 + if (backgrounding === "answers after the turn ended") {
13985 + beforeAnswer = Queue.offer(
13986 + harness.sdkMessages,
13987 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a10", result: "Done." }),
13988 + ).pipe(
13989 + Effect.andThen(awaitUntil(() => harness.terminalEvents().length === 1, "turn end")),
13990 + );
13991 + }
13992 + const foregroundTaskStarted = (task: {
13993 + readonly spawnDepth?: number;
13994 + readonly taskId: string;
13995 + readonly toolUseId: string;
13996 + readonly uuid: string;
13997 + }) =>
13998 + claudeSdkFrame({
13999 + type: "system",
14000 + subtype: "task_started",
14001 + task_id: task.taskId,
14002 + tool_use_id: task.toolUseId,
14003 + description: task.taskId,
14004 + subagent_type: "general-purpose",
14005 + is_backgrounded: false,
14006 + task_type: "local_agent",
14007 + prompt: "Audit.",
14008 + ...(task.spawnDepth === undefined ? {} : { spawn_depth: task.spawnDepth }),
14009 + uuid: task.uuid,
14010 + session_id: WAKE_NATIVE_SESSION,
14011 + });
14012 + for (const frame of [
14013 + foregroundTaskStarted({
14014 + taskId: "task-steer-finished",
14015 + toolUseId: FINISHED_TOOL_USE_ID,
14016 + uuid: "00000000-0000-4000-8000-000000000a01",
14017 + }),
14018 + makeSubagentNotificationFrame({
14019 + taskId: "task-steer-finished",
14020 + toolUseId: FINISHED_TOOL_USE_ID,
14021 + summary: "Finished before the steer.",
14022 + uuid: "00000000-0000-4000-8000-000000000a02",
14023 + }),
14024 + foregroundTaskStarted({
14025 + taskId: "task-steer-foreground",
14026 + toolUseId: FOREGROUND_TOOL_USE_ID,
14027 + uuid: "00000000-0000-4000-8000-000000000a03",
14028 + }),
14029 + claudeSdkFrame({
14030 + type: "assistant",
14031 + message: {
14032 + model: "claude-sonnet-4-6",
14033 + id: "msg_steer_nested_launch",
14034 + type: "message",
14035 + role: "assistant",
14036 + content: [
14037 + {
14038 + type: "tool_use",
14039 + id: NESTED_TOOL_USE_ID,
14040 + name: "Agent",
14041 + input: { description: "Nested check", prompt: "Check." },
14042 + },
14043 + ],
14044 + },
14045 + parent_tool_use_id: FOREGROUND_TOOL_USE_ID,
14046 + uuid: "00000000-0000-4000-8000-000000000a04",
14047 + session_id: WAKE_NATIVE_SESSION,
14048 + }),
14049 + foregroundTaskStarted({
14050 + taskId: "task-steer-nested",
14051 + toolUseId: NESTED_TOOL_USE_ID,
14052 + uuid: "00000000-0000-4000-8000-000000000a05",
14053 + }),
14054 + // Nested too, though its launch never reached the adapter.
14055 + foregroundTaskStarted({
14056 + taskId: "task-steer-deep",
14057 + toolUseId: "toolu-steer-deep",
14058 + spawnDepth: 2,
14059 + uuid: "00000000-0000-4000-8000-000000000a11",
14060 + }),
14061 + ]) {
14062 + yield* Queue.offer(harness.sdkMessages, frame);
14063 + }
14064 + const latestSubagent = (taskId: string) =>
14065 + harness.events
14066 + .flatMap((event) =>
14067 + event.type === "subagent.updated" &&
14068 + event.subagent.nativeTaskRef?.nativeId === taskId
14069 + ? [event.subagent]
14070 + : [],
14071 + )
14072 + .at(-1);
14073 + yield* awaitUntil(
14074 + () =>
14075 + latestSubagent("task-steer-nested")?.status === "running" &&
14076 + latestSubagent("task-steer-deep")?.status === "running" &&
14077 + latestSubagent("task-steer-foreground")?.status === "running" &&
14078 + latestSubagent("task-steer-finished")?.status === "completed",
14079 + "subagents registered",
14080 + );
14081 +
14082 + const offered = harness.offeredMessages.length;
14083 + const steer = harness.runtime.steerTurn({
14084 + threadId: harness.threadId,
14085 + runId: input.runId,
14086 + providerThread: harness.providerThread,
14087 + providerTurnId: idAllocator.derive.providerTurn({
14088 + driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
14089 + nativeTurnId: `turn:${attemptId}`,
14090 + }),
14091 + message: {
14092 + createdBy: "user",
14093 + creationSource: "web",
14094 + messageId: MessageId.make("message-steer-foreground-subagent"),
14095 + text: "Also check the docs.",
14096 + attachments: [],
14097 + },
14098 + });
14099 + const RERUN_TOOL_USE_ID = "toolu-steer-rerun";
14100 + if (backgrounding === "answers after the subagent ran again") {
14101 + // It ends and a SendMessage runs it again, in the foreground.
14102 + beforeAnswer = harness
14103 + .offerAndWait(
14104 + makeSubagentNotificationFrame({
14105 + taskId: "task-steer-foreground",
14106 + toolUseId: FOREGROUND_TOOL_USE_ID,
14107 + summary: "First run done.",
14108 + uuid: "00000000-0000-4000-8000-000000000a12",
14109 + }),
14110 + )
14111 + .pipe(
14112 + Effect.andThen(
14113 + harness.offerAndWait(
14114 + foregroundTaskStarted({
14115 + taskId: "task-steer-foreground",
14116 + toolUseId: RERUN_TOOL_USE_ID,
14117 + uuid: "00000000-0000-4000-8000-000000000a13",
14118 + }),
14119 + ),
14120 + ),
14121 + );
14122 + }
14123 + const steering = yield* Effect.forkScoped(steer);
14124 + if (
14125 + backgrounding === "never answers" ||
14126 + backgrounding === "answers after the steer went out"
14127 + ) {
14128 + yield* awaitUntil(() => calls.length === 1, "background request");
14129 + assert.equal(harness.offeredMessages.length, offered);
14130 + yield* TestClock.adjust("5 seconds");
14131 + }
14132 + const steered = yield* Fiber.await(steering);
14133 +
14134 + // Only the root's running subagent moves: the nested ones follow
14135 + // their owner and the finished one has nothing left to move.
14136 + assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
14137 + if (backgrounding === "answers after the turn ended") {
14138 + // The steer is refused, so the orchestrator starts its follow-up turn.
14139 + assert.isTrue(Exit.isFailure(steered));
14140 + assert.equal(harness.offeredMessages.length, offered);
14141 + return;
14142 + }
14143 + // A refused or unanswered move still lets the steer through.
14144 + assert.isTrue(Exit.isSuccess(steered));
14145 + assert.equal(harness.offeredMessages.length, offered + 1);
14146 + assert.equal(harness.offeredMessages.at(-1)?.priority, "now");
14147 + if (backgrounding === "never answers") {
14148 + // Later steers wait on the move still in flight instead of
14149 + // piling up another request for the same run.
14150 + for (let repeat = 1; repeat <= 2; repeat++) {
14151 + const again = yield* Effect.forkScoped(steer);
14152 + // The steer's 5 second wait starts once it reaches it; move the
14153 + // clock until the steer has gone out.
14154 + for (let tick = 0; tick < 100 && again.pollUnsafe() === undefined; tick++) {
14155 + yield* TestClock.adjust("1 second");
14156 + yield* Effect.yieldNow;
14157 + }
14158 + assert.isTrue(Exit.isSuccess(yield* Fiber.await(again)));
14159 + assert.equal(harness.offeredMessages.length, offered + 1 + repeat);
14160 + }
14161 + assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
14162 + }
14163 + if (backgrounding === "answers after the steer went out") {
14164 + yield* TestClock.adjust("1 second");
14165 + } else if (
14166 + backgrounding !== "succeeds" &&
14167 + backgrounding !== "answers after the subagent ran again"
14168 + ) {
14169 + return;
14170 + }
14171 + // The move answered for the first run; the second runs in the
14172 + // foreground, so its end is the parent's tool result, not a wake.
14173 + const reran = backgrounding === "answers after the subagent ran again";
14174 +
14175 + // The moved subagent outlives the steered turn. When it ends during
14176 + // the user's next turn, Claude's wake after that turn names it.
14177 + for (const frame of [
14178 + makeResultFrame({
14179 + uuid: "00000000-0000-4000-8000-000000000a06",
14180 + result: "",
14181 + terminalReason: "aborted_tools",
14182 + }),
14183 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a07", result: "Docs too." }),
14184 + ]) {
14185 + yield* Queue.offer(harness.sdkMessages, frame);
14186 + }
14187 + yield* awaitUntil(() => harness.terminalEvents().length === 1, "steered turn terminal");
14188 + yield* harness.runtime.startTurn(
14189 + makeClaudeTestTurnInput({
14190 + threadId: harness.threadId,
14191 + providerThread: harness.providerThread,
14192 + now: yield* DateTime.now,
14193 + attemptId: RunAttemptId.make("attempt-steer-next-turn"),
14194 + text: "Anything else?",
14195 + attachments: [],
14196 + providerTurnOrdinal: 2,
14197 + }),
14198 + );
14199 + for (const frame of [
14200 + makeSubagentNotificationFrame({
14201 + taskId: "task-steer-foreground",
14202 + toolUseId: reran ? RERUN_TOOL_USE_ID : FOREGROUND_TOOL_USE_ID,
14203 + summary: "AUDITED",
14204 + uuid: "00000000-0000-4000-8000-000000000a08",
14205 + }),
14206 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a09", result: "No." }),
14207 + ]) {
14208 + yield* Queue.offer(harness.sdkMessages, frame);
14209 + }
14210 + yield* awaitUntil(() => harness.terminalEvents().length === 2, "next turn terminal");
14211 + yield* Queue.offer(harness.sdkMessages, wakeTurnInit);
14212 + yield* awaitUntil(() => harness.continuationRequests.length === 1, "subagent wake");
14213 + assert.equal(
14214 + harness.continuationRequests[0]?.notification?.summary,
14215 + reran ? undefined : 'Subagent "task-steer-foreground" finished',
14216 + );
14217 + }).pipe(
14218 + Effect.provide(
14219 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
14220 + ),
14221 + ),
14222 + ),
14223 + );
14224 +
14225 describe("native goals", () => {
14226 const syntheticFrame = (uuid: string, text: string) =>
14227 claudeSdkFrame({
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
+5
@@ -243,6 +243,7 @@ interface ClaudeSubagentFoundFrame {
243
244 type ClaudeOutboundFrame =
245 | { readonly type: "query.stop_task"; readonly taskId: string }
246 + | { readonly type: "query.background_tasks"; readonly toolUseId: string }
247 | ClaudeQueryOpenFrame
248 | ClaudePromptOfferFrame
249 | ClaudeQuerySetModelFrame
@@ -843,6 +844,10 @@ function makeReplayQueryRunner(
844 replayEffect(() => {
845 assertNextOutboundFrame({ type: "query.stop_task", taskId });
846 }),
847 + backgroundTasks: (toolUseId) =>
848 + replayEffect(() => {
849 + assertNextOutboundFrame({ type: "query.background_tasks", toolUseId });
850 + }).pipe(Effect.as(true)),
851 interrupt: replayEffect(() => {
852 assertNextOutboundFrame({ type: "query.interrupt" });
853 }),
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+119
@@ -96,6 +96,7 @@ import * as Deferred from "effect/Deferred";
96 import * as Effect from "effect/Effect";
97 import * as Equal from "effect/Equal";
98 import * as Exit from "effect/Exit";
99 +import * as Fiber from "effect/Fiber";
100 import * as FileSystem from "effect/FileSystem";
101 import * as Layer from "effect/Layer";
102 import * as Option from "effect/Option";
@@ -425,6 +426,10 @@ export interface ClaudeAgentSdkQuerySession {
426 mode: PermissionMode,
427 ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
428 readonly stopTask: (taskId: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
429 + /** Moves the foreground task one tool call started to the background; false when none matched. */
430 + readonly backgroundTasks: (
431 + toolUseId: string,
432 + ) => Effect.Effect<boolean, ClaudeAgentSdkQueryRunnerError>;
433 readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
434 readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
435 }
@@ -588,6 +593,14 @@ export type ClaudeAgentSdkProtocolLogEvent =
593 readonly taskId: string;
594 };
595 }
596 + | {
597 + readonly direction: "outgoing";
598 + readonly stage: "decoded";
599 + readonly payload: {
600 + readonly type: "query.background_tasks";
601 + readonly toolUseId: string;
602 + };
603 + }
604 | {
605 readonly direction: "outgoing";
606 readonly stage: "decoded";
@@ -921,6 +934,19 @@ export const layerQueryRunner: Layer.Layer<
934 }),
935 ),
936 ),
937 + backgroundTasks: (toolUseId) =>
938 + Effect.tryPromise({
939 + try: () => queryRuntime.backgroundTasks(toolUseId),
940 + catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
941 + }).pipe(
942 + Effect.tap(() =>
943 + logProtocolEvent({
944 + direction: "outgoing",
945 + stage: "decoded",
946 + payload: { type: "query.background_tasks", toolUseId },
947 + }),
948 + ),
949 + ),
950 interrupt: Effect.tryPromise({
951 try: () => queryRuntime.interrupt(),
952 catch: (cause) => queryRunnerError(cause, "interrupt"),
@@ -3604,6 +3630,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
3630 // the turn that launched the subagent (wake drain, later turns) resolve
3631 // their subagent through this index into sessionSubagentsByTaskId.
3632 const sessionSubagentTaskIdsByToolUseId = yield* Ref.make(new Map<string, string>());
3633 + // Requests that move a running subagent to the background before a
3634 + // steer, by the tool call that started its run. Claude may never
3635 + // answer one, so a later steer waits on it rather than asking again.
3636 + const backgroundMovesByToolUseId = new Map<string, Fiber.Fiber<void>>();
3637 // A subagent's tool calls can outlive the turn that started them, so
3638 // they live here rather than on a turn context: a turn that ends while
3639 // one runs neither fails it nor hides it from the turn that follows.
@@ -9007,6 +9037,82 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9037 ),
9038 );
9039
9040 + // A steer is sent with priority "now", which cancels the root turn's
9041 + // running tool calls. A subagent the root launched in the foreground is
9042 + // one of them, so it moves to the background first and keeps running;
9043 + // its result arrives as a task notification like any background agent.
9044 + // Subagents a subagent launched stay put: they follow their owner.
9045 + const backgroundForegroundSubagents = Effect.fnUntraced(function* (
9046 + live: ClaudeLiveQueryContext,
9047 + ) {
9048 + const foreground: Array<{
9049 + readonly taskId: string;
9050 + readonly toolUseId: string;
9051 + }> = [];
9052 + for (const [taskId, subagent] of yield* Ref.get(sessionSubagentsByTaskId)) {
9053 + const toolUseId = subagent.runToolUseId;
9054 + if (
9055 + toolUseId === null ||
9056 + subagent.task.status !== "running" ||
9057 + subagent.task.parentNodeId !== subagent.rootNodeId ||
9058 + live.subagentsFromEarlierProcesses.has(subagent) ||
9059 + // A nested launch whose owner was not known yet falls back to
9060 + // the root as its parent node; its spawn depth still marks it.
9061 + (yield* isNestedSubagentTask(taskId))
9062 + ) {
9063 + continue;
9064 + }
9065 + foreground.push({ taskId, toolUseId });
9066 + }
9067 + // Backgrounding is refused when the session disables background
9068 + // tasks, and the SDK puts no deadline on the request. Either way the
9069 + // steer still goes through, as it did before. A move answered after
9070 + // the steer stopped waiting for it still marks the subagent, and a
9071 + // later steer waits on that same move instead of asking again.
9072 + for (const [toolUseId, move] of backgroundMovesByToolUseId) {
9073 + if (move.pollUnsafe() !== undefined) backgroundMovesByToolUseId.delete(toolUseId);
9074 + }
9075 + const moves: Array<Fiber.Fiber<void>> = [];
9076 + for (const { taskId, toolUseId } of foreground) {
9077 + const inFlight = backgroundMovesByToolUseId.get(toolUseId);
9078 + if (inFlight !== undefined) {
9079 + moves.push(inFlight);
9080 + continue;
9081 + }
9082 + const move = yield* live.query.backgroundTasks(toolUseId).pipe(
9083 + // Now a background subagent: its end wakes the root like one
9084 + // Claude started in the background. One that already ended
9085 + // while the move was answered has nothing left to report.
9086 + Effect.flatMap((moved) =>
9087 + moved
9088 + ? Ref.get(sessionSubagentsByTaskId).pipe(
9089 + Effect.flatMap((registry) =>
9090 + registry.get(taskId)?.task.status === "running" &&
9091 + // Not a later run of it that started meanwhile.
9092 + registry.get(taskId)?.runToolUseId === toolUseId
9093 + ? Ref.update(backgroundedSubagentTaskIds, (current) =>
9094 + new Set(current).add(taskId),
9095 + )
9096 + : Effect.void,
9097 + ),
9098 + )
9099 + : Effect.void,
9100 + ),
9101 + Effect.catch((cause) =>
9102 + Effect.logWarning("orchestration-v2.claude-steer-background-subagent-failed", {
9103 + taskId,
9104 + toolUseId,
9105 + cause,
9106 + }),
9107 + ),
9108 + Effect.forkIn(sessionScope),
9109 + );
9110 + backgroundMovesByToolUseId.set(toolUseId, move);
9111 + moves.push(move);
9112 + }
9113 + yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption("5 seconds"));
9114 + });
9115 +
9116 const steerTurn = Effect.fn("ClaudeAdapterV2.steerTurn")(
9117 function* (turnInput: ProviderAdapter.ProviderAdapterV2SteerInput) {
9118 const existing = yield* Ref.get(queryContext);
@@ -9034,6 +9140,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9140 fileSystem,
9141 skillNames: yield* userInvocableSkillNames(currentTurn.input.runtimePolicy.cwd),
9142 });
9143 + yield* backgroundForegroundSubagents(existing);
9144 + // The turn can end while the moves are answered. A steer offered
9145 + // then would start a new turn the orchestrator never asked for, so
9146 + // the steer fails and the orchestrator starts the follow-up turn.
9147 + if (
9148 + (yield* Ref.get(activeTurn))?.providerTurnId !== turnInput.providerTurnId ||
9149 + (yield* Ref.get(queryContext)) !== existing
9150 + ) {
9151 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9152 + driver: CLAUDE_PROVIDER,
9153 + detail: `Claude provider turn ${turnInput.providerTurnId} ended before the steer was sent.`,
9154 + });
9155 + }
9156 yield* Ref.update(steeredTurns, (current) => {
9157 const next = new Set(current);
9158 next.add(turnInput.providerTurnId);
apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+1
@@ -161,6 +161,7 @@ it.effect.each(["child completion", "scheduled message", "user steering"] as con
161 setModel: () => Effect.void,
162 applyFlagSettings: () => Effect.void,
163 setPermissionMode: () => Effect.void,
164 + backgroundTasks: () => Effect.succeed(false),
165 stopTask: () => Effect.void,
166 interrupt: Effect.die("automatic delivery must never interrupt"),
167 close: Effect.void,
apps/server/src/orchestration-v2/Orchestrator.ts
+4 -10
@@ -4079,10 +4079,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4079 });
4080 });
4081
4082 - // A selection the provider applies on its next turn restarts the run when
4083 - // the provider can restart it. Otherwise the steer joins the running turn
4084 - // and the selection waits for the next one, rather than failing the steer.
4085 - const turnCapabilities = session.providerSession.capabilities.turns;
4082 + // A selection the provider applies on its next turn joins the running
4083 + // turn as a steer and waits for the next turn. Restarting the turn for it
4084 + // would end the turn's native subagents, which a steer must never do.
4085 const selectionMustApplyNow =
4086 selectionChanged &&
4087 (providerInstanceChanged || selectionTransition?.type !== "apply_on_next_turn");
@@ -4092,12 +4091,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4091 threadId: input.command.threadId,
4092 providerInstanceId: targetRun.providerInstanceId,
4093 capabilities: session.providerSession.capabilities,
4095 - forceRestart:
4096 - input.forceRestart ||
4097 - selectionMustApplyNow ||
4098 - (selectionChanged &&
4099 - turnCapabilities.supportsInterrupt &&
4100 - turnCapabilities.supportsSteeringByInterruptRestart),
4094 + forceRestart: input.forceRestart || selectionMustApplyNow,
4095 }),
4096 );
4097
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+79 -72
@@ -405,8 +405,9 @@ it.effect.each(
405 ),
406 );
407
408 -// Claude and Pi steer live but cannot interrupt-and-restart, so a changed
409 -// selection waits for the next turn as the thread's saved selection.
408 +// A changed selection the provider applies on its next turn waits there as the
409 +// thread's saved selection. That holds for a provider that can restart the
410 +// turn (Codex) too: restarting it would end the turn's native subagents.
411 const runSelection = {
412 instanceId,
413 model: "test-model",
@@ -417,7 +418,10 @@ const composerSelection = {
418 options: [...runSelection.options, { id: "fastMode", value: false }],
419 };
420
420 -const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (name: string) {
421 +const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (
422 + name: string,
423 + canRestart = false,
424 +) {
425 const cwd = yield* checkpointWorkspace(name);
426 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
427 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
@@ -427,7 +431,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
431 turns: {
432 ...CodexProviderCapabilitiesV2.turns,
433 supportsActiveSteering: true,
430 - supportsSteeringByInterruptRestart: false,
434 + supportsSteeringByInterruptRestart: canRestart,
435 },
436 };
437 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
@@ -560,79 +564,82 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
564 return { events, started, steered, layer, startFirstTurn };
565 });
566
563 -it.effect("steers a changed turn-scoped selection into a provider that cannot restart", () =>
564 - Effect.scoped(
565 - Effect.gen(function* () {
566 - const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
567 - "steering-selection-change",
568 - );
569 - yield* Effect.gen(function* () {
570 - const orchestrator = yield* Orchestrator.OrchestratorV2;
571 - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
572 - const threadId = yield* startFirstTurn;
573 - const steer = (id: string, selection: ModelSelection) =>
574 - orchestrator
575 - .dispatch({
576 - type: "message.dispatch",
577 - commandId: CommandId.make(id),
578 - threadId,
579 - messageId: MessageId.make(`message:${id}`),
580 - text: id,
581 - attachments: [],
582 - modelSelection: selection,
583 - dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
584 - createdBy: "user",
585 - creationSource: "web",
586 - })
587 - .pipe(Effect.andThen(worker.drain()));
567 +it.effect.each([{ canRestart: false }, { canRestart: true }])(
568 + "steers a changed turn-scoped selection into the running turn (canRestart=$canRestart)",
569 + ({ canRestart }) =>
570 + Effect.scoped(
571 + Effect.gen(function* () {
572 + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
573 + `steering-selection-change-${canRestart}`,
574 + canRestart,
575 + );
576 + yield* Effect.gen(function* () {
577 + const orchestrator = yield* Orchestrator.OrchestratorV2;
578 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
579 + const threadId = yield* startFirstTurn;
580 + const steer = (id: string, selection: ModelSelection) =>
581 + orchestrator
582 + .dispatch({
583 + type: "message.dispatch",
584 + commandId: CommandId.make(id),
585 + threadId,
586 + messageId: MessageId.make(`message:${id}`),
587 + text: id,
588 + attachments: [],
589 + modelSelection: selection,
590 + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
591 + createdBy: "user",
592 + creationSource: "web",
593 + })
594 + .pipe(Effect.andThen(worker.drain()));
595
589 - yield* steer("steer-changed", composerSelection);
590 - const changed = yield* orchestrator.getThreadProjection(threadId);
591 - assert.deepEqual(steered, ["steer-changed"]);
592 - assert.equal(started.length, 1);
593 - assert.lengthOf(changed.attempts, 1);
594 - assert.equal(changed.runs[0]?.status, "running");
595 - assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
596 - assert.deepEqual(changed.thread.modelSelection, composerSelection);
596 + yield* steer("steer-changed", composerSelection);
597 + const changed = yield* orchestrator.getThreadProjection(threadId);
598 + assert.deepEqual(steered, ["steer-changed"]);
599 + assert.equal(started.length, 1);
600 + assert.lengthOf(changed.attempts, 1);
601 + assert.equal(changed.runs[0]?.status, "running");
602 + assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
603 + assert.deepEqual(changed.thread.modelSelection, composerSelection);
604
598 - // Choosing the running run's selection again replaces the saved choice.
599 - yield* steer("steer-reverted", runSelection);
600 - const reverted = yield* orchestrator.getThreadProjection(threadId);
601 - assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
602 - assert.lengthOf(reverted.attempts, 1);
603 - assert.deepEqual(reverted.thread.modelSelection, runSelection);
605 + // Choosing the running run's selection again replaces the saved choice.
606 + yield* steer("steer-reverted", runSelection);
607 + const reverted = yield* orchestrator.getThreadProjection(threadId);
608 + assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
609 + assert.lengthOf(reverted.attempts, 1);
610 + assert.deepEqual(reverted.thread.modelSelection, runSelection);
611
605 - // The saved choice moves to another instance while the run keeps going.
606 - // Steering with the run's selection brings the thread's instance back too.
607 - const otherSelection = {
608 - instanceId: ProviderInstanceId.make("codex-work"),
609 - model: "other",
610 - };
611 - const sink = yield* EventSink.EventSinkV2;
612 - yield* sink.write({
613 - events: [
614 - {
615 - id: EventId.make("switched-away"),
616 - type: "thread.provider-switched",
617 - threadId,
618 - providerInstanceId: otherSelection.instanceId,
619 - occurredAt: yield* DateTime.now,
620 - payload: {
621 - ...reverted.thread,
612 + // The saved choice moves to another instance while the run keeps going.
613 + // Steering with the run's selection brings the thread's instance back too.
614 + const otherSelection = {
615 + instanceId: ProviderInstanceId.make("codex-work"),
616 + model: "other",
617 + };
618 + const sink = yield* EventSink.EventSinkV2;
619 + yield* sink.write({
620 + events: [
621 + {
622 + id: EventId.make("switched-away"),
623 + type: "thread.provider-switched",
624 + threadId,
625 providerInstanceId: otherSelection.instanceId,
623 - modelSelection: otherSelection,
626 + occurredAt: yield* DateTime.now,
627 + payload: {
628 + ...reverted.thread,
629 + providerInstanceId: otherSelection.instanceId,
630 + modelSelection: otherSelection,
631 + },
632 },
625 - },
626 - ],
627 - });
628 - yield* steer("steer-back", runSelection);
629 - const back = yield* orchestrator.getThreadProjection(threadId);
630 - assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
631 - assert.equal(back.thread.providerInstanceId, instanceId);
632 - assert.deepEqual(back.thread.modelSelection, runSelection);
633 - }).pipe(Effect.provide(layer));
634 - }),
635 - ),
633 + ],
634 + });
635 + yield* steer("steer-back", runSelection);
636 + const back = yield* orchestrator.getThreadProjection(threadId);
637 + assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
638 + assert.equal(back.thread.providerInstanceId, instanceId);
639 + assert.deepEqual(back.thread.modelSelection, runSelection);
640 + }).pipe(Effect.provide(layer));
641 + }),
642 + ),
643 );
644
645 it.effect("starts a steer that missed the turn on the saved next-turn selection", () =>