From 270d4a184c175a41514d117c6e6989499ef9fe60 Mon Sep 17 00:00:00 2001 From: Hannes Lenz Date: Tue, 17 Nov 2026 16:27:33 +0100 Subject: [PATCH 1/5] fix(server): queue a provider switch sent while a Claude turn runs Sending a message with another provider selected while a Claude turn was running failed with "Claude cannot redirect an active run. Stop it first, then send the message." A provider switch needs a new turn, and Claude cannot restart its turn with new input, so the forced restart was rejected. Queue such a switch behind the running turn instead, like a steer to a provider that cannot steer either way. It starts on the selected provider, with the usual context handoff, when the turn ends. Providers that can restart a turn for new input keep switching immediately. --- .../orchestration-v2/CommandPolicy.test.ts | 47 +++++++ .../src/orchestration-v2/CommandPolicy.ts | 22 ++- .../src/orchestration-v2/Orchestrator.ts | 1 + .../ProviderSwitch.integration.test.ts | 129 ++++++++++++++++++ 4 files changed, 192 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index 087b24646ef4..4c6670c41682 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -213,6 +213,53 @@ it("queues a steer for a provider that cannot steer either way", () => { ); }); +it("queues a provider switch the running provider cannot apply by restarting its turn", () => { + const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const withProvider = ( + sessionCapabilities: OrchestrationV2ProviderCapabilities, + providerInstanceId: ProviderInstanceId, + ) => { + const projection = dispatchProjection(sessionCapabilities); + return { + ...projection, + runs: projection.runs.map((run) => ({ ...run, providerInstanceId })), + } as OrchestrationV2ThreadProjection; + }; + const claude = withProvider(ClaudeProviderCapabilitiesV2, claudeInstanceId); + for (const deliveryIntent of ["auto", "steer"] as const) { + assert.deepEqual( + CommandPolicy.resolveMessageDispatchIntent( + claude, + { type: "start_immediately" }, + deliveryIntent, + codexInstanceId, + ), + { type: "queue_after_active" }, + ); + // The same provider still steers its running turn. + assert.deepEqual( + CommandPolicy.resolveMessageDispatchIntent( + claude, + { type: "start_immediately" }, + deliveryIntent, + claudeInstanceId, + ), + { type: "steer_active", targetRunId: activeRunId }, + ); + } + // A provider that restarts its turn for new input still switches immediately. + assert.deepEqual( + CommandPolicy.resolveMessageDispatchIntent( + withProvider(baseCapabilities, codexInstanceId), + { type: "start_immediately" }, + "steer", + claudeInstanceId, + ), + { type: "steer_active", targetRunId: activeRunId }, + ); +}); + // regression: #27014 a Grok follow-up cancels the foreground tool the user wanted to finish it("does not steer a Grok follow-up by interrupting its running turn", () => { const grok = makeGrokAcpAdapterFlavor( diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 69c5497d3b87..4b0b9dc2bd30 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -94,6 +94,8 @@ export function resolveMessageDispatchIntent( projection: OrchestrationV2ThreadProjection, requestedMode: MessageDispatchMode, deliveryIntent?: "auto" | "steer" | "restart", + /** The provider instance the message selects, when it names one. */ + requestedInstanceId?: ProviderInstanceId, ): MessageDispatchMode { const mode = resolveDeliveryIntent(projection, requestedMode, deliveryIntent); if (mode.type !== "steer_active") return mode; @@ -103,17 +105,23 @@ export function resolveMessageDispatchIntent( if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) { return { type: "queue_after_active" }; } - // A provider that can neither steer nor restart its turn takes the message after the turn. const turns = target === undefined || !isActiveRun(target) ? undefined : providerTurnCapabilities(projection, target); - return turns !== undefined && - !turns.supportsActiveSteering && - !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) && - turns.supportsQueuedMessages - ? { type: "queue_after_active" } - : mode; + if ( + turns === undefined || + !turns.supportsQueuedMessages || + (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ) { + return mode; + } + // A provider that can neither steer nor restart its turn takes the message after the turn. + // A provider switch needs a new turn, so a provider that cannot restart its turn takes + // the switch after the turn too. + const switchesProvider = + requestedInstanceId !== undefined && requestedInstanceId !== target?.providerInstanceId; + return !turns.supportsActiveSteering || switchesProvider ? { type: "queue_after_active" } : mode; } /** A run that still owns the thread's provider turn. */ diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 933676e23d99..dac3d4507494 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7094,6 +7094,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection, command.dispatchMode, command.deliveryIntent, + command.modelSelection?.instanceId, ); if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 7aa0a1a2631f..ec2570a9b85c 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -2497,6 +2497,135 @@ describe("orchestration v2 provider switching", () => { }), ); + it.live("queues a provider switch sent as a steer into a running Claude turn", () => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("steer-provider-switch-queues"); + const capturedTurns = yield* Ref.make>([]); + const started = yield* Deferred.make(); + const steerThreadId = ThreadId.make("thread:steer-provider-switch-queues"); + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + holdFirstTurn: started, + }), + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: {}, + capturedTurns, + }), + ]); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const eventSink = yield* EventSink.EventSinkV2; + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:steer-provider-switch-queues:create"), + threadId: steerThreadId, + projectId: ProjectId.make("project:steer-provider-switch-queues"), + title: "Steer provider switch", + modelSelection: CLAUDE_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:steer-provider-switch-queues:first"), + threadId: steerThreadId, + messageId: MessageId.make("message:steer-provider-switch-queues:first"), + text: "Current Claude turn", + attachments: [], + modelSelection: CLAUDE_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }); + yield* Deferred.await(started); + yield* worker.drain(); + const [claudeRun] = (yield* orchestrator.getThreadProjection(steerThreadId)).runs; + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make("event:steer-provider-switch-queues:first-turn-running"), + type: "provider-turn.updated", + threadId: steerThreadId, + runId: claudeRun!.id, + nodeId: claudeRun!.rootNodeId!, + driver: CLAUDE_DRIVER, + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId, + occurredAt: now, + payload: { + id: ProviderTurnId.make("provider-turn:steer-provider-switch-queues:first"), + providerThreadId: claudeRun!.providerThreadId!, + nodeId: claudeRun!.rootNodeId!, + runAttemptId: claudeRun!.activeAttemptId!, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }, + ], + }); + // Claude cannot restart its turn for new input, so the switch waits for the turn. + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:steer-provider-switch-queues:codex"), + threadId: steerThreadId, + messageId: MessageId.make("message:steer-provider-switch-queues:codex"), + text: "Continue with Codex", + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + deliveryIntent: "steer", + dispatchMode: { type: "start_immediately" }, + }); + const projection = yield* orchestrator.getThreadProjection(steerThreadId); + assert.deepEqual( + projection.runs.map((run) => [run.status, run.providerInstanceId]), + [ + ["running", CLAUDE_MODEL_SELECTION.instanceId], + ["queued", CODEX_MODEL_SELECTION.instanceId], + ], + ); + assert.deepEqual(projection.thread.modelSelection, CLAUDE_MODEL_SELECTION); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: "steer-provider-switch-queues", + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); + it.live("hands completed Grok steering context to earlier queued Codex and later Claude", () => Effect.gen(function* () { const cwd = yield* checkpointWorkspace("queued-steer-provider-switch"); From f1378e8a3dabbb59c7699e6d3b39b684c72aec19 Mon Sep 17 00:00:00 2001 From: Hannes Lenz Date: Tue, 17 Nov 2026 17:01:21 +0100 Subject: [PATCH 2/5] fix(server): keep Stop and early-run windows for a queued provider switch Move the provider-switch rule after the Stop checks, so an explicit steer that Stop already reached is still refused instead of queued. Before the provider session starts, use the adapter's capabilities, so an early switch becomes an ordinary queued run rather than a deferred steer that fails later. Tests cover a running turn, a turn with no provider session yet, and Stop, and follow the queued switch until Codex answers with the handed-off context. --- .../orchestration-v2/CommandPolicy.test.ts | 54 +-- .../src/orchestration-v2/CommandPolicy.ts | 34 +- .../src/orchestration-v2/Orchestrator.ts | 27 +- .../ProviderSwitch.integration.test.ts | 333 ++++++++++++------ 4 files changed, 270 insertions(+), 178 deletions(-) diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index 4c6670c41682..29d1e9be5036 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -213,50 +213,16 @@ it("queues a steer for a provider that cannot steer either way", () => { ); }); -it("queues a provider switch the running provider cannot apply by restarting its turn", () => { - const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const withProvider = ( - sessionCapabilities: OrchestrationV2ProviderCapabilities, - providerInstanceId: ProviderInstanceId, - ) => { - const projection = dispatchProjection(sessionCapabilities); - return { - ...projection, - runs: projection.runs.map((run) => ({ ...run, providerInstanceId })), - } as OrchestrationV2ThreadProjection; - }; - const claude = withProvider(ClaudeProviderCapabilitiesV2, claudeInstanceId); - for (const deliveryIntent of ["auto", "steer"] as const) { - assert.deepEqual( - CommandPolicy.resolveMessageDispatchIntent( - claude, - { type: "start_immediately" }, - deliveryIntent, - codexInstanceId, - ), - { type: "queue_after_active" }, - ); - // The same provider still steers its running turn. - assert.deepEqual( - CommandPolicy.resolveMessageDispatchIntent( - claude, - { type: "start_immediately" }, - deliveryIntent, - claudeInstanceId, - ), - { type: "steer_active", targetRunId: activeRunId }, - ); - } - // A provider that restarts its turn for new input still switches immediately. - assert.deepEqual( - CommandPolicy.resolveMessageDispatchIntent( - withProvider(baseCapabilities, codexInstanceId), - { type: "start_immediately" }, - "steer", - claudeInstanceId, - ), - { type: "steer_active", targetRunId: activeRunId }, +it("runs a provider switch after the turn only when the provider cannot restart it", () => { + assert.isTrue(CommandPolicy.providerSwitchWaitsForTurn(ClaudeProviderCapabilitiesV2.turns)); + assert.isFalse(CommandPolicy.providerSwitchWaitsForTurn(CodexProviderCapabilitiesV2.turns)); + assert.isFalse(CommandPolicy.providerSwitchWaitsForTurn(CursorProviderCapabilitiesV2.turns)); + // Without a queue the switch keeps failing as before instead of being dropped. + assert.isFalse( + CommandPolicy.providerSwitchWaitsForTurn({ + ...ClaudeProviderCapabilitiesV2.turns, + supportsQueuedMessages: false, + }), ); }); diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 4b0b9dc2bd30..d435ccad7d0b 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -94,8 +94,6 @@ export function resolveMessageDispatchIntent( projection: OrchestrationV2ThreadProjection, requestedMode: MessageDispatchMode, deliveryIntent?: "auto" | "steer" | "restart", - /** The provider instance the message selects, when it names one. */ - requestedInstanceId?: ProviderInstanceId, ): MessageDispatchMode { const mode = resolveDeliveryIntent(projection, requestedMode, deliveryIntent); if (mode.type !== "steer_active") return mode; @@ -105,23 +103,17 @@ export function resolveMessageDispatchIntent( if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) { return { type: "queue_after_active" }; } + // A provider that can neither steer nor restart its turn takes the message after the turn. const turns = target === undefined || !isActiveRun(target) ? undefined : providerTurnCapabilities(projection, target); - if ( - turns === undefined || - !turns.supportsQueuedMessages || - (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) - ) { - return mode; - } - // A provider that can neither steer nor restart its turn takes the message after the turn. - // A provider switch needs a new turn, so a provider that cannot restart its turn takes - // the switch after the turn too. - const switchesProvider = - requestedInstanceId !== undefined && requestedInstanceId !== target?.providerInstanceId; - return !turns.supportsActiveSteering || switchesProvider ? { type: "queue_after_active" } : mode; + return turns !== undefined && + !turns.supportsActiveSteering && + !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) && + turns.supportsQueuedMessages + ? { type: "queue_after_active" } + : mode; } /** A run that still owns the thread's provider turn. */ @@ -143,7 +135,17 @@ export function followUpOwnerRun( ); } -function providerTurnCapabilities( +/** A provider that cannot restart its turn for new input runs a provider switch after the turn. */ +export function providerSwitchWaitsForTurn( + turns: OrchestrationV2ProviderCapabilities["turns"], +): boolean { + return ( + turns.supportsQueuedMessages && + !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ); +} + +export function providerTurnCapabilities( projection: OrchestrationV2ThreadProjection, run: OrchestrationV2Run, ) { diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index dac3d4507494..a90a4151fcbb 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -117,6 +117,8 @@ import { goalCommandStopsActiveRun, isActiveRun, isNativeMaintenanceCommand, + providerSwitchWaitsForTurn, + providerTurnCapabilities, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; @@ -7094,7 +7096,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection, command.dispatchMode, command.deliveryIntent, - command.modelSelection?.instanceId, ); if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; @@ -7145,6 +7146,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } + // A steer that switches provider needs a new turn. A provider that cannot restart its + // turn for new input takes it after the turn, like a provider that cannot steer at all. + // An explicit steer that Stop reached still fails below. + if (dispatchMode.type === "steer_active" && command.modelSelection !== undefined) { + const targetRunId = dispatchMode.targetRunId; + const target = projection.runs.find((run) => run.id === targetRunId); + if ( + target !== undefined && + isActiveRun(target) && + target.providerInstanceId !== command.modelSelection.instanceId && + !(yield* stopReachedRun(command, command.threadId, target.id)) + ) { + // Before the provider session starts, the adapter's capabilities stand in for its own. + const turns = + providerTurnCapabilities(projection, target) ?? + (yield* providerAdapters.get(target.providerInstanceId).pipe( + Effect.flatMap((adapter) => adapter.getCapabilities()), + mapDispatchError(command), + )).turns; + if (providerSwitchWaitsForTurn(turns)) { + dispatchMode = { type: "queue_after_active" }; + } + } + } // Native goal commands must not steer an existing turn. const parsedGoalCommand = parseGoalCommand(command); const goalCommand = diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index ec2570a9b85c..9d0cc888d946 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -2497,132 +2497,231 @@ describe("orchestration v2 provider switching", () => { }), ); - it.live("queues a provider switch sent as a steer into a running Claude turn", () => + const steerProviderSwitchHarness = Effect.fn("steerProviderSwitchHarness")(function* ( + key: string, + ) { + const cwd = yield* checkpointWorkspace(`steer-provider-switch-${key}`); + const capturedTurns = yield* Ref.make>([]); + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const threadId = ThreadId.make(`thread:steer-provider-switch:${key}`); + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { 1: "Claude finished the current turn" }, + capturedTurns, + holdFirstTurn: started, + releaseFirstTurn: release, + }), + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { 2: "Codex continued" }, + capturedTurns, + }), + ]); + const layer = ProviderReplayHarness.layerWithRegistry( + { + name: `steer-provider-switch-${key}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ); + const startClaudeTurn = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:steer-provider-switch:${key}:create`), + threadId, + projectId: ProjectId.make(`project:steer-provider-switch:${key}`), + title: "Steer provider switch", + modelSelection: CLAUDE_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:steer-provider-switch:${key}:first`), + threadId, + messageId: MessageId.make(`message:steer-provider-switch:${key}:first`), + text: "Current Claude turn", + attachments: [], + modelSelection: CLAUDE_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }); + }); + const markClaudeTurnRunning = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const [claudeRun] = (yield* orchestrator.getThreadProjection(threadId)).runs; + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`event:steer-provider-switch:${key}:first-turn-running`), + type: "provider-turn.updated", + threadId, + runId: claudeRun!.id, + nodeId: claudeRun!.rootNodeId!, + driver: CLAUDE_DRIVER, + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId, + occurredAt: now, + payload: { + // The adapter's own turn id, so its completion ends this turn. + id: ProviderTurnId.make(`provider-turn:${CLAUDE_DRIVER}:${threadId}:1`), + providerThreadId: claudeRun!.providerThreadId!, + nodeId: claudeRun!.rootNodeId!, + runAttemptId: claudeRun!.activeAttemptId!, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }, + ], + }); + }); + const steerToCodex = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + return yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:steer-provider-switch:${key}:codex`), + threadId, + messageId: MessageId.make(`message:steer-provider-switch:${key}:codex`), + text: "Continue with Codex", + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + deliveryIntent: "steer", + dispatchMode: { type: "start_immediately" }, + }); + }); + return { + threadId, + started, + release, + capturedTurns, + layer, + startClaudeTurn, + markClaudeTurnRunning, + steerToCodex, + }; + }); + + it.live.each(["running", "has no provider session yet"] as const)( + "runs a provider switch steered into a Claude turn that %s after that turn", + (phase) => + Effect.gen(function* () { + const harness = yield* steerProviderSwitchHarness( + phase === "running" ? "running" : "before-session", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const waitForRun = (ordinal: number) => + orchestrator.streamStoredEvents.pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.threadId === harness.threadId && + event.payload.ordinal === ordinal && + event.payload.status === "completed", + ), + Stream.runHead, + Effect.andThen(worker.drain()), + ); + yield* harness.startClaudeTurn; + if (phase === "running") { + yield* Deferred.await(harness.started); + yield* worker.drain(); + yield* harness.markClaudeTurnRunning; + } else { + const beforeSession = yield* orchestrator.getThreadProjection(harness.threadId); + assert.include(["preparing", "starting"], beforeSession.runs[0]?.status); + assert.lengthOf(beforeSession.providerSessions, 0); + } + // Claude cannot restart its turn for new input, so the switch waits for the turn. + yield* harness.steerToCodex; + const queued = (yield* orchestrator.getThreadProjection(harness.threadId)).runs.at(-1); + assert.equal(queued?.status, "queued"); + assert.equal(queued?.providerInstanceId, CODEX_MODEL_SELECTION.instanceId); + assert.isUndefined(queued?.steerWhenReadyRunId); + + yield* Deferred.await(harness.started); + yield* Deferred.succeed(harness.release, undefined); + yield* waitForRun(1); + yield* waitForRun(2); + const projection = yield* orchestrator.getThreadProjection(harness.threadId); + assert.deepEqual( + projection.runs.map((run) => [run.status, run.providerInstanceId]), + [ + ["completed", CLAUDE_MODEL_SELECTION.instanceId], + ["completed", CODEX_MODEL_SELECTION.instanceId], + ], + ); + assert.deepEqual(projection.thread.modelSelection, CODEX_MODEL_SELECTION); + const handoff = projection.contextHandoffs.find( + (candidate) => candidate.id === projection.runs[1]?.contextHandoffId, + ); + assert.isDefined(handoff); + const codexTurn = (yield* Ref.get(harness.capturedTurns)).at(-1)!; + assert.include(codexTurn.text, "Continue with Codex"); + assert.include(codexTurn.text, "Current Claude turn"); + assert.include(codexTurn.text, "Claude finished the current turn"); + }).pipe(Effect.provide(harness.layer)); + }), + ); + + // regression: #32891 a steer that Stop already reached is refused, not queued + it.live("refuses a provider switch steered into a Claude turn that Stop reached", () => Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("steer-provider-switch-queues"); - const capturedTurns = yield* Ref.make>([]); - const started = yield* Deferred.make(); - const steerThreadId = ThreadId.make("thread:steer-provider-switch-queues"); - const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ - makeTestAdapter({ - instanceId: CLAUDE_MODEL_SELECTION.instanceId, - driver: CLAUDE_DRIVER, - capabilities: ClaudeProviderCapabilitiesV2, - modelSelection: CLAUDE_MODEL_SELECTION, - responseByRunOrdinal: {}, - capturedTurns, - holdFirstTurn: started, - }), - makeTestAdapter({ - instanceId: CODEX_MODEL_SELECTION.instanceId, - driver: CODEX_DRIVER, - capabilities: CodexProviderCapabilitiesV2, - modelSelection: CODEX_MODEL_SELECTION, - responseByRunOrdinal: {}, - capturedTurns, - }), - ]); + const harness = yield* steerProviderSwitchHarness("after-stop"); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const eventSink = yield* EventSink.EventSinkV2; - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:steer-provider-switch-queues:create"), - threadId: steerThreadId, - projectId: ProjectId.make("project:steer-provider-switch-queues"), - title: "Steer provider switch", - modelSelection: CLAUDE_MODEL_SELECTION, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - }); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:steer-provider-switch-queues:first"), - threadId: steerThreadId, - messageId: MessageId.make("message:steer-provider-switch-queues:first"), - text: "Current Claude turn", - attachments: [], - modelSelection: CLAUDE_MODEL_SELECTION, - dispatchMode: { type: "start_immediately" }, - }); - yield* Deferred.await(started); + yield* harness.startClaudeTurn; + yield* Deferred.await(harness.started); yield* worker.drain(); - const [claudeRun] = (yield* orchestrator.getThreadProjection(steerThreadId)).runs; - const now = yield* DateTime.now; - yield* eventSink.write({ - events: [ - { - id: EventId.make("event:steer-provider-switch-queues:first-turn-running"), - type: "provider-turn.updated", - threadId: steerThreadId, - runId: claudeRun!.id, - nodeId: claudeRun!.rootNodeId!, - driver: CLAUDE_DRIVER, - providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId, - occurredAt: now, - payload: { - id: ProviderTurnId.make("provider-turn:steer-provider-switch-queues:first"), - providerThreadId: claudeRun!.providerThreadId!, - nodeId: claudeRun!.rootNodeId!, - runAttemptId: claudeRun!.activeAttemptId!, - nativeTurnRef: null, - ordinal: 1, - status: "running", - startedAt: now, - completedAt: null, - }, - }, - ], - }); - // Claude cannot restart its turn for new input, so the switch waits for the turn. + yield* harness.markClaudeTurnRunning; + const [claudeRun] = (yield* orchestrator.getThreadProjection(harness.threadId)).runs; + // The worker has not delivered the interrupt yet, so the run still reads as running. yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:steer-provider-switch-queues:codex"), - threadId: steerThreadId, - messageId: MessageId.make("message:steer-provider-switch-queues:codex"), - text: "Continue with Codex", - attachments: [], - modelSelection: CODEX_MODEL_SELECTION, - deliveryIntent: "steer", - dispatchMode: { type: "start_immediately" }, + type: "run.interrupt", + commandId: CommandId.make("command:steer-provider-switch:after-stop:stop"), + threadId: harness.threadId, + runId: claudeRun!.id, }); - const projection = yield* orchestrator.getThreadProjection(steerThreadId); + const error = yield* harness.steerToCodex.pipe(Effect.flip); + assert.instanceOf(error, Orchestrator.OrchestratorDispatchError); assert.deepEqual( - projection.runs.map((run) => [run.status, run.providerInstanceId]), - [ - ["running", CLAUDE_MODEL_SELECTION.instanceId], - ["queued", CODEX_MODEL_SELECTION.instanceId], - ], - ); - assert.deepEqual(projection.thread.modelSelection, CLAUDE_MODEL_SELECTION); - }).pipe( - Effect.provide( - ProviderReplayHarness.layerWithRegistry( - { - name: "steer-provider-switch-queues", - runtimePolicyOverride: { - cwd, - approvalPolicy: "never", - sandboxPolicy: { - type: "readOnly", - access: { type: "fullAccess" }, - networkAccess: false, - }, - }, - }, - layerRegistry, + (yield* orchestrator.getThreadProjection(harness.threadId)).runs.map( + (run) => run.providerInstanceId, ), - ), - ); + [CLAUDE_MODEL_SELECTION.instanceId], + ); + yield* Deferred.succeed(harness.release, undefined); + }).pipe(Effect.provide(harness.layer)); }), ); From 87b81f6077205e2c9e79516a17840574682d72cf Mon Sep 17 00:00:00 2001 From: Hannes Lenz Date: Tue, 17 Nov 2026 17:21:31 +0100 Subject: [PATCH 3/5] fix(server): decide a queued provider switch after /goal handling An explicit steer_active /goal without a delivery intent that switched provider was turned into a plain queued send before the goal check, so it no longer stopped the running turn. Decide the provider switch after the goal, notification and delegated-completion checks instead. --- .../src/orchestration-v2/Orchestrator.ts | 48 +++++++++---------- .../ProviderSwitch.integration.test.ts | 42 ++++++++++++++++ 2 files changed, 66 insertions(+), 24 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index a90a4151fcbb..7d1248cebd41 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7146,30 +7146,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // A steer that switches provider needs a new turn. A provider that cannot restart its - // turn for new input takes it after the turn, like a provider that cannot steer at all. - // An explicit steer that Stop reached still fails below. - if (dispatchMode.type === "steer_active" && command.modelSelection !== undefined) { - const targetRunId = dispatchMode.targetRunId; - const target = projection.runs.find((run) => run.id === targetRunId); - if ( - target !== undefined && - isActiveRun(target) && - target.providerInstanceId !== command.modelSelection.instanceId && - !(yield* stopReachedRun(command, command.threadId, target.id)) - ) { - // Before the provider session starts, the adapter's capabilities stand in for its own. - const turns = - providerTurnCapabilities(projection, target) ?? - (yield* providerAdapters.get(target.providerInstanceId).pipe( - Effect.flatMap((adapter) => adapter.getCapabilities()), - mapDispatchError(command), - )).turns; - if (providerSwitchWaitsForTurn(turns)) { - dispatchMode = { type: "queue_after_active" }; - } - } - } // Native goal commands must not steer an existing turn. const parsedGoalCommand = parseGoalCommand(command); const goalCommand = @@ -7265,6 +7241,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio taskIds: delivery.taskIds, }; } + // A steer that switches provider needs a new turn. A provider that cannot restart its + // turn for new input takes it after the turn, like a provider that cannot steer at all. + // An explicit steer that Stop reached still fails below. + if (dispatchMode.type === "steer_active" && command.modelSelection !== undefined) { + const targetRunId = dispatchMode.targetRunId; + const target = projection.runs.find((run) => run.id === targetRunId); + if ( + target !== undefined && + isActiveRun(target) && + target.providerInstanceId !== command.modelSelection.instanceId && + !(yield* stopReachedRun(command, command.threadId, target.id)) + ) { + // Before the provider session starts, the adapter's capabilities stand in for its own. + const turns = + providerTurnCapabilities(projection, target) ?? + (yield* providerAdapters.get(target.providerInstanceId).pipe( + Effect.flatMap((adapter) => adapter.getCapabilities()), + mapDispatchError(command), + )).turns; + if (providerSwitchWaitsForTurn(turns)) { + dispatchMode = { type: "queue_after_active" }; + } + } + } // A provider that can stop a turn but not restart it with new input runs a // restart as the next turn: first in the queue, with the running turn stopped. if (dispatchMode.type === "restart_active" && !isNativeMaintenanceCommand(command)) { diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 9d0cc888d946..b548d315386f 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -2693,6 +2693,48 @@ describe("orchestration v2 provider switching", () => { }), ); + it.live("stops a Claude turn for a /goal steered into it with another provider", () => + Effect.gen(function* () { + const harness = yield* steerProviderSwitchHarness("goal"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* harness.startClaudeTurn; + yield* Deferred.await(harness.started); + yield* worker.drain(); + yield* harness.markClaudeTurnRunning; + const [claudeRun] = (yield* orchestrator.getThreadProjection(harness.threadId)).runs; + // An explicit steer without a delivery intent, as thread tools send it. + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:steer-provider-switch:goal:codex"), + threadId: harness.threadId, + messageId: MessageId.make("message:steer-provider-switch:goal:codex"), + text: "/goal all tests pass", + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + dispatchMode: { type: "steer_active", targetRunId: claudeRun!.id }, + }); + const projection = yield* orchestrator.getThreadProjection(harness.threadId); + assert.isTrue( + projection.turnItems.some( + (item) => item.type === "run_interrupt_request" && item.runId === claudeRun!.id, + ), + ); + assert.deepEqual( + projection.runs.map((run) => [run.status, run.providerInstanceId]), + [ + ["running", CLAUDE_MODEL_SELECTION.instanceId], + ["queued", CODEX_MODEL_SELECTION.instanceId], + ], + ); + yield* Deferred.succeed(harness.release, undefined); + }).pipe(Effect.provide(harness.layer)); + }), + ); + // regression: #32891 a steer that Stop already reached is refused, not queued it.live("refuses a provider switch steered into a Claude turn that Stop reached", () => Effect.gen(function* () { From e71d10995e27baceb2ae5822fd8c8aa0ac149542 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 16:45:06 +0000 Subject: [PATCH 4/5] refactor(server): share the provider-switch queue check and trim tests Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/CommandPolicy.test.ts | 13 ------------- apps/server/src/orchestration-v2/CommandPolicy.ts | 5 +---- .../testkit/ProviderSwitch.integration.test.ts | 6 +++--- 3 files changed, 4 insertions(+), 20 deletions(-) diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index 29d1e9be5036..087b24646ef4 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -213,19 +213,6 @@ it("queues a steer for a provider that cannot steer either way", () => { ); }); -it("runs a provider switch after the turn only when the provider cannot restart it", () => { - assert.isTrue(CommandPolicy.providerSwitchWaitsForTurn(ClaudeProviderCapabilitiesV2.turns)); - assert.isFalse(CommandPolicy.providerSwitchWaitsForTurn(CodexProviderCapabilitiesV2.turns)); - assert.isFalse(CommandPolicy.providerSwitchWaitsForTurn(CursorProviderCapabilitiesV2.turns)); - // Without a queue the switch keeps failing as before instead of being dropped. - assert.isFalse( - CommandPolicy.providerSwitchWaitsForTurn({ - ...ClaudeProviderCapabilitiesV2.turns, - supportsQueuedMessages: false, - }), - ); -}); - // regression: #27014 a Grok follow-up cancels the foreground tool the user wanted to finish it("does not steer a Grok follow-up by interrupting its running turn", () => { const grok = makeGrokAcpAdapterFlavor( diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index d435ccad7d0b..c49d229949a7 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -108,10 +108,7 @@ export function resolveMessageDispatchIntent( target === undefined || !isActiveRun(target) ? undefined : providerTurnCapabilities(projection, target); - return turns !== undefined && - !turns.supportsActiveSteering && - !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) && - turns.supportsQueuedMessages + return turns !== undefined && !turns.supportsActiveSteering && providerSwitchWaitsForTurn(turns) ? { type: "queue_after_active" } : mode; } diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index b548d315386f..69975c01cd6c 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -2629,12 +2629,12 @@ describe("orchestration v2 provider switching", () => { }; }); - it.live.each(["running", "has no provider session yet"] as const)( + it.live.each(["is running", "has no provider session yet"] as const)( "runs a provider switch steered into a Claude turn that %s after that turn", (phase) => Effect.gen(function* () { const harness = yield* steerProviderSwitchHarness( - phase === "running" ? "running" : "before-session", + phase === "is running" ? "running" : "before-session", ); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -2652,7 +2652,7 @@ describe("orchestration v2 provider switching", () => { Effect.andThen(worker.drain()), ); yield* harness.startClaudeTurn; - if (phase === "running") { + if (phase === "is running") { yield* Deferred.await(harness.started); yield* worker.drain(); yield* harness.markClaudeTurnRunning; From 8bbaa2c3eb730a0a78369f36d11f6c6f4db4dcf0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 17:00:39 +0000 Subject: [PATCH 5/5] test(server): hold the Claude session open in the no-session provider-switch case Co-Authored-By: Claude Opus 5.5 --- .../testkit/ProviderSwitch.integration.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 69975c01cd6c..e1b2572d8d1a 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -123,6 +123,7 @@ function makeTestAdapter(input: { readonly subagentOnlyBackgroundWork?: boolean; readonly holdFirstTurn?: Deferred.Deferred; readonly releaseFirstTurn?: Deferred.Deferred; + readonly holdOpenSession?: Deferred.Deferred; /** A tool call the held turn reports running before it holds. */ readonly heldRunningToolCall?: { readonly id: TurnItemId; @@ -141,6 +142,7 @@ function makeTestAdapter(input: { planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (sessionInput) => Effect.gen(function* () { + if (input.holdOpenSession !== undefined) yield* Deferred.await(input.holdOpenSession); const events = yield* PubSub.unbounded(); if (input.closedSessions !== undefined) { const closedSessions = input.closedSessions; @@ -2499,6 +2501,7 @@ describe("orchestration v2 provider switching", () => { const steerProviderSwitchHarness = Effect.fn("steerProviderSwitchHarness")(function* ( key: string, + holdOpenSession?: Deferred.Deferred, ) { const cwd = yield* checkpointWorkspace(`steer-provider-switch-${key}`); const capturedTurns = yield* Ref.make>([]); @@ -2515,6 +2518,7 @@ describe("orchestration v2 provider switching", () => { capturedTurns, holdFirstTurn: started, releaseFirstTurn: release, + ...(holdOpenSession === undefined ? {} : { holdOpenSession }), }), makeTestAdapter({ instanceId: CODEX_MODEL_SELECTION.instanceId, @@ -2633,8 +2637,11 @@ describe("orchestration v2 provider switching", () => { "runs a provider switch steered into a Claude turn that %s after that turn", (phase) => Effect.gen(function* () { + const sessionGate = yield* Deferred.make(); + if (phase === "is running") yield* Deferred.succeed(sessionGate, undefined); const harness = yield* steerProviderSwitchHarness( phase === "is running" ? "running" : "before-session", + sessionGate, ); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -2668,6 +2675,7 @@ describe("orchestration v2 provider switching", () => { assert.equal(queued?.providerInstanceId, CODEX_MODEL_SELECTION.instanceId); assert.isUndefined(queued?.steerWhenReadyRunId); + yield* Deferred.succeed(sessionGate, undefined); yield* Deferred.await(harness.started); yield* Deferred.succeed(harness.release, undefined); yield* waitForRun(1);