Skip to content
TypeScript

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

shivam0b68a4a9c36e
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index edaafff081e..868e7fa0bd6 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -1035,6 +1035,7 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
@@ -1196,6 +1197,7 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functio
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
@@ -1317,6 +1319,7 @@ describe("ClaudeAdapterV2 resume compaction", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
@@ -1544,6 +1547,7 @@ describe("ClaudeAdapterV2 attachments", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
@@ -1690,6 +1694,7 @@ describe("ClaudeAdapterV2 attachments", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
@@ -1786,6 +1791,7 @@ describe("ClaudeAdapterV2 native fork", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
@@ -2079,6 +2085,7 @@ describe("ClaudeAdapterV2 native session identity", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
@@ -2340,6 +2347,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
readonly stopTask?: (
taskId: string,
) => Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
+ readonly backgroundTasks?: (
+ toolUseId: string,
+ ) => Effect.Effect<boolean, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
readonly environment?: NodeJS.ProcessEnv;
readonly subagentLaunchToolUseId?: string;
readonly nativeSessionId?: string;
@@ -2420,6 +2430,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
stopTask: options?.stopTask ?? (() => Effect.void),
interrupt: Effect.void,
close: Queue.shutdown(processMessages),
@@ -2460,6 +2471,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
Effect.sync(() => {
permissionModeChanges.push(mode);
}),
+ backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
stopTask: options?.stopTask ?? (() => Effect.void),
interrupt: options?.interrupt ?? Effect.void,
close: options?.close?.(sdkMessages) ?? Effect.void,
@@ -5014,6 +5026,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
// The first CLI process keeps streaming until the test ends
@@ -5275,6 +5288,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Queue.shutdown(queue),
@@ -10367,6 +10381,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
// End this process stream so openQuery can replace it.
@@ -10555,6 +10570,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Queue.shutdown(sdkMessages),
@@ -10795,6 +10811,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Queue.shutdown(sdkMessages),
@@ -10994,6 +11011,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Queue.shutdown(sdkMessages),
@@ -11175,6 +11193,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Queue.shutdown(sdkMessages),
@@ -11312,6 +11331,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Queue.shutdown(sdkMessages),
@@ -13910,6 +13930,298 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect.each([
+ { backgrounding: "succeeds" },
+ { backgrounding: "fails" },
+ { backgrounding: "never answers" },
+ { backgrounding: "answers after the steer went out" },
+ { backgrounding: "answers after the turn ended" },
+ { backgrounding: "answers after the subagent ran again" },
+ ] as const)(
+ "moves the root's foreground subagents to the background before a steer ($backgrounding)",
+ ({ backgrounding }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const FOREGROUND_TOOL_USE_ID = "toolu-steer-foreground";
+ const NESTED_TOOL_USE_ID = "toolu-steer-nested";
+ const FINISHED_TOOL_USE_ID = "toolu-steer-finished";
+ const calls: Array<string> = [];
+ // What happens while the move is still unanswered.
+ let beforeAnswer: Effect.Effect<void> = Effect.void;
+ const harness = yield* makeWakeHarnessWithOptions({
+ backgroundTasks: (toolUseId) =>
+ Effect.sync(() => calls.push(toolUseId)).pipe(
+ Effect.andThen(
+ backgrounding === "answers after the turn ended" ||
+ backgrounding === "answers after the subagent ran again"
+ ? Effect.suspend(() => beforeAnswer).pipe(Effect.as(true))
+ : backgrounding === "fails"
+ ? Effect.fail(
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
+ method: "backgroundTasks",
+ cause: new Error("Background tasks are disabled in this session."),
+ }),
+ )
+ : backgrounding === "never answers"
+ ? Effect.never
+ : backgrounding === "answers after the steer went out"
+ ? Effect.sleep("6 seconds").pipe(Effect.as(true))
+ : Effect.succeed(true),
+ ),
+ ),
+ });
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ const attemptId = RunAttemptId.make("attempt-steer-foreground-subagent");
+ const input = makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId,
+ text: "Audit the repo with a subagent.",
+ attachments: [],
+ });
+ yield* harness.runtime.startTurn(input);
+ if (backgrounding === "answers after the turn ended") {
+ beforeAnswer = Queue.offer(
+ harness.sdkMessages,
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a10", result: "Done." }),
+ ).pipe(
+ Effect.andThen(awaitUntil(() => harness.terminalEvents().length === 1, "turn end")),
+ );
+ }
+ const foregroundTaskStarted = (task: {
+ readonly spawnDepth?: number;
+ readonly taskId: string;
+ readonly toolUseId: string;
+ readonly uuid: string;
+ }) =>
+ claudeSdkFrame({
+ type: "system",
+ subtype: "task_started",
+ task_id: task.taskId,
+ tool_use_id: task.toolUseId,
+ description: task.taskId,
+ subagent_type: "general-purpose",
+ is_backgrounded: false,
+ task_type: "local_agent",
+ prompt: "Audit.",
+ ...(task.spawnDepth === undefined ? {} : { spawn_depth: task.spawnDepth }),
+ uuid: task.uuid,
+ session_id: WAKE_NATIVE_SESSION,
+ });
+ for (const frame of [
+ foregroundTaskStarted({
+ taskId: "task-steer-finished",
+ toolUseId: FINISHED_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000a01",
+ }),
+ makeSubagentNotificationFrame({
+ taskId: "task-steer-finished",
+ toolUseId: FINISHED_TOOL_USE_ID,
+ summary: "Finished before the steer.",
+ uuid: "00000000-0000-4000-8000-000000000a02",
+ }),
+ foregroundTaskStarted({
+ taskId: "task-steer-foreground",
+ toolUseId: FOREGROUND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000a03",
+ }),
+ claudeSdkFrame({
+ type: "assistant",
+ message: {
+ model: "claude-sonnet-4-6",
+ id: "msg_steer_nested_launch",
+ type: "message",
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: NESTED_TOOL_USE_ID,
+ name: "Agent",
+ input: { description: "Nested check", prompt: "Check." },
+ },
+ ],
+ },
+ parent_tool_use_id: FOREGROUND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000a04",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ foregroundTaskStarted({
+ taskId: "task-steer-nested",
+ toolUseId: NESTED_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000a05",
+ }),
+ // Nested too, though its launch never reached the adapter.
+ foregroundTaskStarted({
+ taskId: "task-steer-deep",
+ toolUseId: "toolu-steer-deep",
+ spawnDepth: 2,
+ uuid: "00000000-0000-4000-8000-000000000a11",
+ }),
+ ]) {
+ yield* Queue.offer(harness.sdkMessages, frame);
+ }
+ const latestSubagent = (taskId: string) =>
+ harness.events
+ .flatMap((event) =>
+ event.type === "subagent.updated" &&
+ event.subagent.nativeTaskRef?.nativeId === taskId
+ ? [event.subagent]
+ : [],
+ )
+ .at(-1);
+ yield* awaitUntil(
+ () =>
+ latestSubagent("task-steer-nested")?.status === "running" &&
+ latestSubagent("task-steer-deep")?.status === "running" &&
+ latestSubagent("task-steer-foreground")?.status === "running" &&
+ latestSubagent("task-steer-finished")?.status === "completed",
+ "subagents registered",
+ );
+
+ const offered = harness.offeredMessages.length;
+ const steer = harness.runtime.steerTurn({
+ threadId: harness.threadId,
+ runId: input.runId,
+ providerThread: harness.providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${attemptId}`,
+ }),
+ message: {
+ createdBy: "user",
+ creationSource: "web",
+ messageId: MessageId.make("message-steer-foreground-subagent"),
+ text: "Also check the docs.",
+ attachments: [],
+ },
+ });
+ const RERUN_TOOL_USE_ID = "toolu-steer-rerun";
+ if (backgrounding === "answers after the subagent ran again") {
+ // It ends and a SendMessage runs it again, in the foreground.
+ beforeAnswer = harness
+ .offerAndWait(
+ makeSubagentNotificationFrame({
+ taskId: "task-steer-foreground",
+ toolUseId: FOREGROUND_TOOL_USE_ID,
+ summary: "First run done.",
+ uuid: "00000000-0000-4000-8000-000000000a12",
+ }),
+ )
+ .pipe(
+ Effect.andThen(
+ harness.offerAndWait(
+ foregroundTaskStarted({
+ taskId: "task-steer-foreground",
+ toolUseId: RERUN_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000a13",
+ }),
+ ),
+ ),
+ );
+ }
+ const steering = yield* Effect.forkScoped(steer);
+ if (
+ backgrounding === "never answers" ||
+ backgrounding === "answers after the steer went out"
+ ) {
+ yield* awaitUntil(() => calls.length === 1, "background request");
+ assert.equal(harness.offeredMessages.length, offered);
+ yield* TestClock.adjust("5 seconds");
+ }
+ const steered = yield* Fiber.await(steering);
+
+ // Only the root's running subagent moves: the nested ones follow
+ // their owner and the finished one has nothing left to move.
+ assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
+ if (backgrounding === "answers after the turn ended") {
+ // The steer is refused, so the orchestrator starts its follow-up turn.
+ assert.isTrue(Exit.isFailure(steered));
+ assert.equal(harness.offeredMessages.length, offered);
+ return;
+ }
+ // A refused or unanswered move still lets the steer through.
+ assert.isTrue(Exit.isSuccess(steered));
+ assert.equal(harness.offeredMessages.length, offered + 1);
+ assert.equal(harness.offeredMessages.at(-1)?.priority, "now");
+ if (backgrounding === "never answers") {
+ // Later steers wait on the move still in flight instead of
+ // piling up another request for the same run.
+ for (let repeat = 1; repeat <= 2; repeat++) {
+ const again = yield* Effect.forkScoped(steer);
+ // The steer's 5 second wait starts once it reaches it; move the
+ // clock until the steer has gone out.
+ for (let tick = 0; tick < 100 && again.pollUnsafe() === undefined; tick++) {
+ yield* TestClock.adjust("1 second");
+ yield* Effect.yieldNow;
+ }
+ assert.isTrue(Exit.isSuccess(yield* Fiber.await(again)));
+ assert.equal(harness.offeredMessages.length, offered + 1 + repeat);
+ }
+ assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]);
+ }
+ if (backgrounding === "answers after the steer went out") {
+ yield* TestClock.adjust("1 second");
+ } else if (
+ backgrounding !== "succeeds" &&
+ backgrounding !== "answers after the subagent ran again"
+ ) {
+ return;
+ }
+ // The move answered for the first run; the second runs in the
+ // foreground, so its end is the parent's tool result, not a wake.
+ const reran = backgrounding === "answers after the subagent ran again";
+
+ // The moved subagent outlives the steered turn. When it ends during
+ // the user's next turn, Claude's wake after that turn names it.
+ for (const frame of [
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000a06",
+ result: "",
+ terminalReason: "aborted_tools",
+ }),
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a07", result: "Docs too." }),
+ ]) {
+ yield* Queue.offer(harness.sdkMessages, frame);
+ }
+ yield* awaitUntil(() => harness.terminalEvents().length === 1, "steered turn terminal");
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-steer-next-turn"),
+ text: "Anything else?",
+ attachments: [],
+ providerTurnOrdinal: 2,
+ }),
+ );
+ for (const frame of [
+ makeSubagentNotificationFrame({
+ taskId: "task-steer-foreground",
+ toolUseId: reran ? RERUN_TOOL_USE_ID : FOREGROUND_TOOL_USE_ID,
+ summary: "AUDITED",
+ uuid: "00000000-0000-4000-8000-000000000a08",
+ }),
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a09", result: "No." }),
+ ]) {
+ yield* Queue.offer(harness.sdkMessages, frame);
+ }
+ yield* awaitUntil(() => harness.terminalEvents().length === 2, "next turn terminal");
+ yield* Queue.offer(harness.sdkMessages, wakeTurnInit);
+ yield* awaitUntil(() => harness.continuationRequests.length === 1, "subagent wake");
+ assert.equal(
+ harness.continuationRequests[0]?.notification?.summary,
+ reran ? undefined : 'Subagent "task-steer-foreground" finished',
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ ),
+ );
+
describe("native goals", () => {
const syntheticFrame = (uuid: string, text: string) =>
claudeSdkFrame({
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
index c8fa9e25b94..9f75ffb90ee 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
@@ -243,6 +243,7 @@ interface ClaudeSubagentFoundFrame {
type ClaudeOutboundFrame =
| { readonly type: "query.stop_task"; readonly taskId: string }
+ | { readonly type: "query.background_tasks"; readonly toolUseId: string }
| ClaudeQueryOpenFrame
| ClaudePromptOfferFrame
| ClaudeQuerySetModelFrame
@@ -843,6 +844,10 @@ function makeReplayQueryRunner(
replayEffect(() => {
assertNextOutboundFrame({ type: "query.stop_task", taskId });
}),
+ backgroundTasks: (toolUseId) =>
+ replayEffect(() => {
+ assertNextOutboundFrame({ type: "query.background_tasks", toolUseId });
+ }).pipe(Effect.as(true)),
interrupt: replayEffect(() => {
assertNextOutboundFrame({ type: "query.interrupt" });
}),
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index c84aff8913c..92c3b44ec58 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -96,6 +96,7 @@ import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
+import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -425,6 +426,10 @@ export interface ClaudeAgentSdkQuerySession {
mode: PermissionMode,
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly stopTask: (taskId: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
+ /** Moves the foreground task one tool call started to the background; false when none matched. */
+ readonly backgroundTasks: (
+ toolUseId: string,
+ ) => Effect.Effect<boolean, ClaudeAgentSdkQueryRunnerError>;
readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
}
@@ -588,6 +593,14 @@ export type ClaudeAgentSdkProtocolLogEvent =
readonly taskId: string;
};
}
+ | {
+ readonly direction: "outgoing";
+ readonly stage: "decoded";
+ readonly payload: {
+ readonly type: "query.background_tasks";
+ readonly toolUseId: string;
+ };
+ }
| {
readonly direction: "outgoing";
readonly stage: "decoded";
@@ -921,6 +934,19 @@ export const layerQueryRunner: Layer.Layer<
}),
),
),
+ backgroundTasks: (toolUseId) =>
+ Effect.tryPromise({
+ try: () => queryRuntime.backgroundTasks(toolUseId),
+ catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
+ }).pipe(
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: { type: "query.background_tasks", toolUseId },
+ }),
+ ),
+ ),
interrupt: Effect.tryPromise({
try: () => queryRuntime.interrupt(),
catch: (cause) => queryRunnerError(cause, "interrupt"),
@@ -3604,6 +3630,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
// the turn that launched the subagent (wake drain, later turns) resolve
// their subagent through this index into sessionSubagentsByTaskId.
const sessionSubagentTaskIdsByToolUseId = yield* Ref.make(new Map<string, string>());
+ // Requests that move a running subagent to the background before a
+ // steer, by the tool call that started its run. Claude may never
+ // answer one, so a later steer waits on it rather than asking again.
+ const backgroundMovesByToolUseId = new Map<string, Fiber.Fiber<void>>();
// A subagent's tool calls can outlive the turn that started them, so
// they live here rather than on a turn context: a turn that ends while
// one runs neither fails it nor hides it from the turn that follows.
@@ -9007,6 +9037,82 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
),
);
+ // A steer is sent with priority "now", which cancels the root turn's
+ // running tool calls. A subagent the root launched in the foreground is
+ // one of them, so it moves to the background first and keeps running;
+ // its result arrives as a task notification like any background agent.
+ // Subagents a subagent launched stay put: they follow their owner.
+ const backgroundForegroundSubagents = Effect.fnUntraced(function* (
+ live: ClaudeLiveQueryContext,
+ ) {
+ const foreground: Array<{
+ readonly taskId: string;
+ readonly toolUseId: string;
+ }> = [];
+ for (const [taskId, subagent] of yield* Ref.get(sessionSubagentsByTaskId)) {
+ const toolUseId = subagent.runToolUseId;
+ if (
+ toolUseId === null ||
+ subagent.task.status !== "running" ||
+ subagent.task.parentNodeId !== subagent.rootNodeId ||
+ live.subagentsFromEarlierProcesses.has(subagent) ||
+ // A nested launch whose owner was not known yet falls back to
+ // the root as its parent node; its spawn depth still marks it.
+ (yield* isNestedSubagentTask(taskId))
+ ) {
+ continue;
+ }
+ foreground.push({ taskId, toolUseId });
+ }
+ // Backgrounding is refused when the session disables background
+ // tasks, and the SDK puts no deadline on the request. Either way the
+ // steer still goes through, as it did before. A move answered after
+ // the steer stopped waiting for it still marks the subagent, and a
+ // later steer waits on that same move instead of asking again.
+ for (const [toolUseId, move] of backgroundMovesByToolUseId) {
+ if (move.pollUnsafe() !== undefined) backgroundMovesByToolUseId.delete(toolUseId);
+ }
+ const moves: Array<Fiber.Fiber<void>> = [];
+ for (const { taskId, toolUseId } of foreground) {
+ const inFlight = backgroundMovesByToolUseId.get(toolUseId);
+ if (inFlight !== undefined) {
+ moves.push(inFlight);
+ continue;
+ }
+ const move = yield* live.query.backgroundTasks(toolUseId).pipe(
+ // Now a background subagent: its end wakes the root like one
+ // Claude started in the background. One that already ended
+ // while the move was answered has nothing left to report.
+ Effect.flatMap((moved) =>
+ moved
+ ? Ref.get(sessionSubagentsByTaskId).pipe(
+ Effect.flatMap((registry) =>
+ registry.get(taskId)?.task.status === "running" &&
+ // Not a later run of it that started meanwhile.
+ registry.get(taskId)?.runToolUseId === toolUseId
+ ? Ref.update(backgroundedSubagentTaskIds, (current) =>
+ new Set(current).add(taskId),
+ )
+ : Effect.void,
+ ),
+ )
+ : Effect.void,
+ ),
+ Effect.catch((cause) =>
+ Effect.logWarning("orchestration-v2.claude-steer-background-subagent-failed", {
+ taskId,
+ toolUseId,
+ cause,
+ }),
+ ),
+ Effect.forkIn(sessionScope),
+ );
+ backgroundMovesByToolUseId.set(toolUseId, move);
+ moves.push(move);
+ }
+ yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption("5 seconds"));
+ });
+
const steerTurn = Effect.fn("ClaudeAdapterV2.steerTurn")(
function* (turnInput: ProviderAdapter.ProviderAdapterV2SteerInput) {
const existing = yield* Ref.get(queryContext);
@@ -9034,6 +9140,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
fileSystem,
skillNames: yield* userInvocableSkillNames(currentTurn.input.runtimePolicy.cwd),
});
+ yield* backgroundForegroundSubagents(existing);
+ // The turn can end while the moves are answered. A steer offered
+ // then would start a new turn the orchestrator never asked for, so
+ // the steer fails and the orchestrator starts the follow-up turn.
+ if (
+ (yield* Ref.get(activeTurn))?.providerTurnId !== turnInput.providerTurnId ||
+ (yield* Ref.get(queryContext)) !== existing
+ ) {
+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({
+ driver: CLAUDE_PROVIDER,
+ detail: `Claude provider turn ${turnInput.providerTurnId} ended before the steer was sent.`,
+ });
+ }
yield* Ref.update(steeredTurns, (current) => {
const next = new Set(current);
next.add(turnInput.providerTurnId);
diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
index 3fd034abe4f..308c02fef03 100644
--- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
@@ -161,6 +161,7 @@ it.effect.each(["child completion", "scheduled message", "user steering"] as con
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.die("automatic delivery must never interrupt"),
close: Effect.void,
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index c7b322f2c49..a0e1c1fc788 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -4079,10 +4079,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
});
- // A selection the provider applies on its next turn restarts the run when
- // the provider can restart it. Otherwise the steer joins the running turn
- // and the selection waits for the next one, rather than failing the steer.
- const turnCapabilities = session.providerSession.capabilities.turns;
+ // A selection the provider applies on its next turn joins the running
+ // turn as a steer and waits for the next turn. Restarting the turn for it
+ // would end the turn's native subagents, which a steer must never do.
const selectionMustApplyNow =
selectionChanged &&
(providerInstanceChanged || selectionTransition?.type !== "apply_on_next_turn");
@@ -4092,12 +4091,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
threadId: input.command.threadId,
providerInstanceId: targetRun.providerInstanceId,
capabilities: session.providerSession.capabilities,
- forceRestart:
- input.forceRestart ||
- selectionMustApplyNow ||
- (selectionChanged &&
- turnCapabilities.supportsInterrupt &&
- turnCapabilities.supportsSteeringByInterruptRestart),
+ forceRestart: input.forceRestart || selectionMustApplyNow,
}),
);
diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
index 730b72feea6..f99328d1fc6 100644
--- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
@@ -405,8 +405,9 @@ it.effect.each(
),
);
-// Claude and Pi steer live but cannot interrupt-and-restart, so a changed
-// selection waits for the next turn as the thread's saved selection.
+// A changed selection the provider applies on its next turn waits there as the
+// thread's saved selection. That holds for a provider that can restart the
+// turn (Codex) too: restarting it would end the turn's native subagents.
const runSelection = {
instanceId,
model: "test-model",
@@ -417,7 +418,10 @@ const composerSelection = {
options: [...runSelection.options, { id: "fastMode", value: false }],
};
-const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (name: string) {
+const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (
+ name: string,
+ canRestart = false,
+) {
const cwd = yield* checkpointWorkspace(name);
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
@@ -427,7 +431,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
turns: {
...CodexProviderCapabilitiesV2.turns,
supportsActiveSteering: true,
- supportsSteeringByInterruptRestart: false,
+ supportsSteeringByInterruptRestart: canRestart,
},
};
const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
@@ -560,79 +564,82 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
return { events, started, steered, layer, startFirstTurn };
});
-it.effect("steers a changed turn-scoped selection into a provider that cannot restart", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
- "steering-selection-change",
- );
- yield* Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const threadId = yield* startFirstTurn;
- const steer = (id: string, selection: ModelSelection) =>
- orchestrator
- .dispatch({
- type: "message.dispatch",
- commandId: CommandId.make(id),
- threadId,
- messageId: MessageId.make(`message:${id}`),
- text: id,
- attachments: [],
- modelSelection: selection,
- dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
- createdBy: "user",
- creationSource: "web",
- })
- .pipe(Effect.andThen(worker.drain()));
+it.effect.each([{ canRestart: false }, { canRestart: true }])(
+ "steers a changed turn-scoped selection into the running turn (canRestart=$canRestart)",
+ ({ canRestart }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
+ `steering-selection-change-${canRestart}`,
+ canRestart,
+ );
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const threadId = yield* startFirstTurn;
+ const steer = (id: string, selection: ModelSelection) =>
+ orchestrator
+ .dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(id),
+ threadId,
+ messageId: MessageId.make(`message:${id}`),
+ text: id,
+ attachments: [],
+ modelSelection: selection,
+ dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
+ createdBy: "user",
+ creationSource: "web",
+ })
+ .pipe(Effect.andThen(worker.drain()));
- yield* steer("steer-changed", composerSelection);
- const changed = yield* orchestrator.getThreadProjection(threadId);
- assert.deepEqual(steered, ["steer-changed"]);
- assert.equal(started.length, 1);
- assert.lengthOf(changed.attempts, 1);
- assert.equal(changed.runs[0]?.status, "running");
- assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
- assert.deepEqual(changed.thread.modelSelection, composerSelection);
+ yield* steer("steer-changed", composerSelection);
+ const changed = yield* orchestrator.getThreadProjection(threadId);
+ assert.deepEqual(steered, ["steer-changed"]);
+ assert.equal(started.length, 1);
+ assert.lengthOf(changed.attempts, 1);
+ assert.equal(changed.runs[0]?.status, "running");
+ assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
+ assert.deepEqual(changed.thread.modelSelection, composerSelection);
- // Choosing the running run's selection again replaces the saved choice.
- yield* steer("steer-reverted", runSelection);
- const reverted = yield* orchestrator.getThreadProjection(threadId);
- assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
- assert.lengthOf(reverted.attempts, 1);
- assert.deepEqual(reverted.thread.modelSelection, runSelection);
+ // Choosing the running run's selection again replaces the saved choice.
+ yield* steer("steer-reverted", runSelection);
+ const reverted = yield* orchestrator.getThreadProjection(threadId);
+ assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
+ assert.lengthOf(reverted.attempts, 1);
+ assert.deepEqual(reverted.thread.modelSelection, runSelection);
- // The saved choice moves to another instance while the run keeps going.
- // Steering with the run's selection brings the thread's instance back too.
- const otherSelection = {
- instanceId: ProviderInstanceId.make("codex-work"),
- model: "other",
- };
- const sink = yield* EventSink.EventSinkV2;
- yield* sink.write({
- events: [
- {
- id: EventId.make("switched-away"),
- type: "thread.provider-switched",
- threadId,
- providerInstanceId: otherSelection.instanceId,
- occurredAt: yield* DateTime.now,
- payload: {
- ...reverted.thread,
+ // The saved choice moves to another instance while the run keeps going.
+ // Steering with the run's selection brings the thread's instance back too.
+ const otherSelection = {
+ instanceId: ProviderInstanceId.make("codex-work"),
+ model: "other",
+ };
+ const sink = yield* EventSink.EventSinkV2;
+ yield* sink.write({
+ events: [
+ {
+ id: EventId.make("switched-away"),
+ type: "thread.provider-switched",
+ threadId,
providerInstanceId: otherSelection.instanceId,
- modelSelection: otherSelection,
+ occurredAt: yield* DateTime.now,
+ payload: {
+ ...reverted.thread,
+ providerInstanceId: otherSelection.instanceId,
+ modelSelection: otherSelection,
+ },
},
- },
- ],
- });
- yield* steer("steer-back", runSelection);
- const back = yield* orchestrator.getThreadProjection(threadId);
- assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
- assert.equal(back.thread.providerInstanceId, instanceId);
- assert.deepEqual(back.thread.modelSelection, runSelection);
- }).pipe(Effect.provide(layer));
- }),
- ),
+ ],
+ });
+ yield* steer("steer-back", runSelection);
+ const back = yield* orchestrator.getThreadProjection(threadId);
+ assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
+ assert.equal(back.thread.providerInstanceId, instanceId);
+ assert.deepEqual(back.thread.modelSelection, runSelection);
+ }).pipe(Effect.provide(layer));
+ }),
+ ),
);
it.effect("starts a steer that missed the turn on the saved next-turn selection", () =>