@devries-cameron20 / t3code-1 / commits / 0597532f16
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): queue a provider switch sent while a Claude turn runs (#38216)

Co-authored-by: Hannes Lenz <hlenz@esic-sarida.cloud> Co-authored-by: Julius Marminge <julius0216@outlook.com>

VendettaGhub committed Nov 17, 2026 at 18:21 UTC 0597532f16d54189c4a696a249cc66c6d44c7ab5
3 files changed +316 -5
apps/server/src/orchestration-v2/CommandPolicy.ts
+12 -5
@@ -108,10 +108,7 @@ export function resolveMessageDispatchIntent(
108 target === undefined || !isActiveRun(target)
109 ? undefined
110 : providerTurnCapabilities(projection, target);
111 - return turns !== undefined &&
112 - !turns.supportsActiveSteering &&
113 - !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) &&
114 - turns.supportsQueuedMessages
111 + return turns !== undefined && !turns.supportsActiveSteering && providerSwitchWaitsForTurn(turns)
112 ? { type: "queue_after_active" }
113 : mode;
114 }
@@ -135,7 +132,17 @@ export function followUpOwnerRun(
132 );
133 }
134
138 -function providerTurnCapabilities(
135 +/** A provider that cannot restart its turn for new input runs a provider switch after the turn. */
136 +export function providerSwitchWaitsForTurn(
137 + turns: OrchestrationV2ProviderCapabilities["turns"],
138 +): boolean {
139 + return (
140 + turns.supportsQueuedMessages &&
141 + !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart)
142 + );
143 +}
144 +
145 +export function providerTurnCapabilities(
146 projection: OrchestrationV2ThreadProjection,
147 run: OrchestrationV2Run,
148 ) {
apps/server/src/orchestration-v2/Orchestrator.ts
+26
@@ -117,6 +117,8 @@ import {
117 goalCommandStopsActiveRun,
118 isActiveRun,
119 isNativeMaintenanceCommand,
120 + providerSwitchWaitsForTurn,
121 + providerTurnCapabilities,
122 resolveMessageDispatchIntent,
123 } from "./CommandPolicy.ts";
124 import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts";
@@ -7239,6 +7241,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7241 taskIds: delivery.taskIds,
7242 };
7243 }
7244 + // A steer that switches provider needs a new turn. A provider that cannot restart its
7245 + // turn for new input takes it after the turn, like a provider that cannot steer at all.
7246 + // An explicit steer that Stop reached still fails below.
7247 + if (dispatchMode.type === "steer_active" && command.modelSelection !== undefined) {
7248 + const targetRunId = dispatchMode.targetRunId;
7249 + const target = projection.runs.find((run) => run.id === targetRunId);
7250 + if (
7251 + target !== undefined &&
7252 + isActiveRun(target) &&
7253 + target.providerInstanceId !== command.modelSelection.instanceId &&
7254 + !(yield* stopReachedRun(command, command.threadId, target.id))
7255 + ) {
7256 + // Before the provider session starts, the adapter's capabilities stand in for its own.
7257 + const turns =
7258 + providerTurnCapabilities(projection, target) ??
7259 + (yield* providerAdapters.get(target.providerInstanceId).pipe(
7260 + Effect.flatMap((adapter) => adapter.getCapabilities()),
7261 + mapDispatchError(command),
7262 + )).turns;
7263 + if (providerSwitchWaitsForTurn(turns)) {
7264 + dispatchMode = { type: "queue_after_active" };
7265 + }
7266 + }
7267 + }
7268 // A provider that can stop a turn but not restart it with new input runs a
7269 // restart as the next turn: first in the queue, with the running turn stopped.
7270 if (dispatchMode.type === "restart_active" && !isNativeMaintenanceCommand(command)) {
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+278
@@ -123,6 +123,7 @@ function makeTestAdapter(input: {
123 readonly subagentOnlyBackgroundWork?: boolean;
124 readonly holdFirstTurn?: Deferred.Deferred<void>;
125 readonly releaseFirstTurn?: Deferred.Deferred<void>;
126 + readonly holdOpenSession?: Deferred.Deferred<void>;
127 /** A tool call the held turn reports running before it holds. */
128 readonly heldRunningToolCall?: {
129 readonly id: TurnItemId;
@@ -141,6 +142,7 @@ function makeTestAdapter(input: {
142 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
143 openSession: (sessionInput) =>
144 Effect.gen(function* () {
145 + if (input.holdOpenSession !== undefined) yield* Deferred.await(input.holdOpenSession);
146 const events = yield* PubSub.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
147 if (input.closedSessions !== undefined) {
148 const closedSessions = input.closedSessions;
@@ -2497,6 +2499,282 @@ describe("orchestration v2 provider switching", () => {
2499 }),
2500 );
2501
2502 + const steerProviderSwitchHarness = Effect.fn("steerProviderSwitchHarness")(function* (
2503 + key: string,
2504 + holdOpenSession?: Deferred.Deferred<void>,
2505 + ) {
2506 + const cwd = yield* checkpointWorkspace(`steer-provider-switch-${key}`);
2507 + const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2508 + const started = yield* Deferred.make<void>();
2509 + const release = yield* Deferred.make<void>();
2510 + const threadId = ThreadId.make(`thread:steer-provider-switch:${key}`);
2511 + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2512 + makeTestAdapter({
2513 + instanceId: CLAUDE_MODEL_SELECTION.instanceId,
2514 + driver: CLAUDE_DRIVER,
2515 + capabilities: ClaudeProviderCapabilitiesV2,
2516 + modelSelection: CLAUDE_MODEL_SELECTION,
2517 + responseByRunOrdinal: { 1: "Claude finished the current turn" },
2518 + capturedTurns,
2519 + holdFirstTurn: started,
2520 + releaseFirstTurn: release,
2521 + ...(holdOpenSession === undefined ? {} : { holdOpenSession }),
2522 + }),
2523 + makeTestAdapter({
2524 + instanceId: CODEX_MODEL_SELECTION.instanceId,
2525 + driver: CODEX_DRIVER,
2526 + capabilities: CodexProviderCapabilitiesV2,
2527 + modelSelection: CODEX_MODEL_SELECTION,
2528 + responseByRunOrdinal: { 2: "Codex continued" },
2529 + capturedTurns,
2530 + }),
2531 + ]);
2532 + const layer = ProviderReplayHarness.layerWithRegistry(
2533 + {
2534 + name: `steer-provider-switch-${key}`,
2535 + runtimePolicyOverride: {
2536 + cwd,
2537 + approvalPolicy: "never",
2538 + sandboxPolicy: {
2539 + type: "readOnly",
2540 + access: { type: "fullAccess" },
2541 + networkAccess: false,
2542 + },
2543 + },
2544 + },
2545 + layerRegistry,
2546 + );
2547 + const startClaudeTurn = Effect.gen(function* () {
2548 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2549 + yield* orchestrator.dispatch({
2550 + type: "thread.create",
2551 + createdBy: "user",
2552 + creationSource: "web",
2553 + commandId: CommandId.make(`command:steer-provider-switch:${key}:create`),
2554 + threadId,
2555 + projectId: ProjectId.make(`project:steer-provider-switch:${key}`),
2556 + title: "Steer provider switch",
2557 + modelSelection: CLAUDE_MODEL_SELECTION,
2558 + runtimeMode: "full-access",
2559 + interactionMode: "default",
2560 + branch: null,
2561 + worktreePath: cwd,
2562 + });
2563 + yield* orchestrator.dispatch({
2564 + type: "message.dispatch",
2565 + createdBy: "user",
2566 + creationSource: "web",
2567 + commandId: CommandId.make(`command:steer-provider-switch:${key}:first`),
2568 + threadId,
2569 + messageId: MessageId.make(`message:steer-provider-switch:${key}:first`),
2570 + text: "Current Claude turn",
2571 + attachments: [],
2572 + modelSelection: CLAUDE_MODEL_SELECTION,
2573 + dispatchMode: { type: "start_immediately" },
2574 + });
2575 + });
2576 + const markClaudeTurnRunning = Effect.gen(function* () {
2577 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2578 + const eventSink = yield* EventSink.EventSinkV2;
2579 + const [claudeRun] = (yield* orchestrator.getThreadProjection(threadId)).runs;
2580 + const now = yield* DateTime.now;
2581 + yield* eventSink.write({
2582 + events: [
2583 + {
2584 + id: EventId.make(`event:steer-provider-switch:${key}:first-turn-running`),
2585 + type: "provider-turn.updated",
2586 + threadId,
2587 + runId: claudeRun!.id,
2588 + nodeId: claudeRun!.rootNodeId!,
2589 + driver: CLAUDE_DRIVER,
2590 + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId,
2591 + occurredAt: now,
2592 + payload: {
2593 + // The adapter's own turn id, so its completion ends this turn.
2594 + id: ProviderTurnId.make(`provider-turn:${CLAUDE_DRIVER}:${threadId}:1`),
2595 + providerThreadId: claudeRun!.providerThreadId!,
2596 + nodeId: claudeRun!.rootNodeId!,
2597 + runAttemptId: claudeRun!.activeAttemptId!,
2598 + nativeTurnRef: null,
2599 + ordinal: 1,
2600 + status: "running",
2601 + startedAt: now,
2602 + completedAt: null,
2603 + },
2604 + },
2605 + ],
2606 + });
2607 + });
2608 + const steerToCodex = Effect.gen(function* () {
2609 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2610 + return yield* orchestrator.dispatch({
2611 + type: "message.dispatch",
2612 + createdBy: "user",
2613 + creationSource: "web",
2614 + commandId: CommandId.make(`command:steer-provider-switch:${key}:codex`),
2615 + threadId,
2616 + messageId: MessageId.make(`message:steer-provider-switch:${key}:codex`),
2617 + text: "Continue with Codex",
2618 + attachments: [],
2619 + modelSelection: CODEX_MODEL_SELECTION,
2620 + deliveryIntent: "steer",
2621 + dispatchMode: { type: "start_immediately" },
2622 + });
2623 + });
2624 + return {
2625 + threadId,
2626 + started,
2627 + release,
2628 + capturedTurns,
2629 + layer,
2630 + startClaudeTurn,
2631 + markClaudeTurnRunning,
2632 + steerToCodex,
2633 + };
2634 + });
2635 +
2636 + it.live.each(["is running", "has no provider session yet"] as const)(
2637 + "runs a provider switch steered into a Claude turn that %s after that turn",
2638 + (phase) =>
2639 + Effect.gen(function* () {
2640 + const sessionGate = yield* Deferred.make<void>();
2641 + if (phase === "is running") yield* Deferred.succeed(sessionGate, undefined);
2642 + const harness = yield* steerProviderSwitchHarness(
2643 + phase === "is running" ? "running" : "before-session",
2644 + sessionGate,
2645 + );
2646 + yield* Effect.gen(function* () {
2647 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2648 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2649 + const waitForRun = (ordinal: number) =>
2650 + orchestrator.streamStoredEvents.pipe(
2651 + Stream.filter(
2652 + ({ event }) =>
2653 + event.type === "run.updated" &&
2654 + event.threadId === harness.threadId &&
2655 + event.payload.ordinal === ordinal &&
2656 + event.payload.status === "completed",
2657 + ),
2658 + Stream.runHead,
2659 + Effect.andThen(worker.drain()),
2660 + );
2661 + yield* harness.startClaudeTurn;
2662 + if (phase === "is running") {
2663 + yield* Deferred.await(harness.started);
2664 + yield* worker.drain();
2665 + yield* harness.markClaudeTurnRunning;
2666 + } else {
2667 + const beforeSession = yield* orchestrator.getThreadProjection(harness.threadId);
2668 + assert.include(["preparing", "starting"], beforeSession.runs[0]?.status);
2669 + assert.lengthOf(beforeSession.providerSessions, 0);
2670 + }
2671 + // Claude cannot restart its turn for new input, so the switch waits for the turn.
2672 + yield* harness.steerToCodex;
2673 + const queued = (yield* orchestrator.getThreadProjection(harness.threadId)).runs.at(-1);
2674 + assert.equal(queued?.status, "queued");
2675 + assert.equal(queued?.providerInstanceId, CODEX_MODEL_SELECTION.instanceId);
2676 + assert.isUndefined(queued?.steerWhenReadyRunId);
2677 +
2678 + yield* Deferred.succeed(sessionGate, undefined);
2679 + yield* Deferred.await(harness.started);
2680 + yield* Deferred.succeed(harness.release, undefined);
2681 + yield* waitForRun(1);
2682 + yield* waitForRun(2);
2683 + const projection = yield* orchestrator.getThreadProjection(harness.threadId);
2684 + assert.deepEqual(
2685 + projection.runs.map((run) => [run.status, run.providerInstanceId]),
2686 + [
2687 + ["completed", CLAUDE_MODEL_SELECTION.instanceId],
2688 + ["completed", CODEX_MODEL_SELECTION.instanceId],
2689 + ],
2690 + );
2691 + assert.deepEqual(projection.thread.modelSelection, CODEX_MODEL_SELECTION);
2692 + const handoff = projection.contextHandoffs.find(
2693 + (candidate) => candidate.id === projection.runs[1]?.contextHandoffId,
2694 + );
2695 + assert.isDefined(handoff);
2696 + const codexTurn = (yield* Ref.get(harness.capturedTurns)).at(-1)!;
2697 + assert.include(codexTurn.text, "Continue with Codex");
2698 + assert.include(codexTurn.text, "Current Claude turn");
2699 + assert.include(codexTurn.text, "Claude finished the current turn");
2700 + }).pipe(Effect.provide(harness.layer));
2701 + }),
2702 + );
2703 +
2704 + it.live("stops a Claude turn for a /goal steered into it with another provider", () =>
2705 + Effect.gen(function* () {
2706 + const harness = yield* steerProviderSwitchHarness("goal");
2707 + yield* Effect.gen(function* () {
2708 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2709 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2710 + yield* harness.startClaudeTurn;
2711 + yield* Deferred.await(harness.started);
2712 + yield* worker.drain();
2713 + yield* harness.markClaudeTurnRunning;
2714 + const [claudeRun] = (yield* orchestrator.getThreadProjection(harness.threadId)).runs;
2715 + // An explicit steer without a delivery intent, as thread tools send it.
2716 + yield* orchestrator.dispatch({
2717 + type: "message.dispatch",
2718 + createdBy: "user",
2719 + creationSource: "web",
2720 + commandId: CommandId.make("command:steer-provider-switch:goal:codex"),
2721 + threadId: harness.threadId,
2722 + messageId: MessageId.make("message:steer-provider-switch:goal:codex"),
2723 + text: "/goal all tests pass",
2724 + attachments: [],
2725 + modelSelection: CODEX_MODEL_SELECTION,
2726 + dispatchMode: { type: "steer_active", targetRunId: claudeRun!.id },
2727 + });
2728 + const projection = yield* orchestrator.getThreadProjection(harness.threadId);
2729 + assert.isTrue(
2730 + projection.turnItems.some(
2731 + (item) => item.type === "run_interrupt_request" && item.runId === claudeRun!.id,
2732 + ),
2733 + );
2734 + assert.deepEqual(
2735 + projection.runs.map((run) => [run.status, run.providerInstanceId]),
2736 + [
2737 + ["running", CLAUDE_MODEL_SELECTION.instanceId],
2738 + ["queued", CODEX_MODEL_SELECTION.instanceId],
2739 + ],
2740 + );
2741 + yield* Deferred.succeed(harness.release, undefined);
2742 + }).pipe(Effect.provide(harness.layer));
2743 + }),
2744 + );
2745 +
2746 + // regression: #32891 a steer that Stop already reached is refused, not queued
2747 + it.live("refuses a provider switch steered into a Claude turn that Stop reached", () =>
2748 + Effect.gen(function* () {
2749 + const harness = yield* steerProviderSwitchHarness("after-stop");
2750 + yield* Effect.gen(function* () {
2751 + const orchestrator = yield* Orchestrator.OrchestratorV2;
2752 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2753 + yield* harness.startClaudeTurn;
2754 + yield* Deferred.await(harness.started);
2755 + yield* worker.drain();
2756 + yield* harness.markClaudeTurnRunning;
2757 + const [claudeRun] = (yield* orchestrator.getThreadProjection(harness.threadId)).runs;
2758 + // The worker has not delivered the interrupt yet, so the run still reads as running.
2759 + yield* orchestrator.dispatch({
2760 + type: "run.interrupt",
2761 + commandId: CommandId.make("command:steer-provider-switch:after-stop:stop"),
2762 + threadId: harness.threadId,
2763 + runId: claudeRun!.id,
2764 + });
2765 + const error = yield* harness.steerToCodex.pipe(Effect.flip);
2766 + assert.instanceOf(error, Orchestrator.OrchestratorDispatchError);
2767 + assert.deepEqual(
2768 + (yield* orchestrator.getThreadProjection(harness.threadId)).runs.map(
2769 + (run) => run.providerInstanceId,
2770 + ),
2771 + [CLAUDE_MODEL_SELECTION.instanceId],
2772 + );
2773 + yield* Deferred.succeed(harness.release, undefined);
2774 + }).pipe(Effect.provide(harness.layer));
2775 + }),
2776 + );
2777 +
2778 it.live("hands completed Grok steering context to earlier queued Codex and later Claude", () =>
2779 Effect.gen(function* () {
2780 const cwd = yield* checkpointWorkspace("queued-steer-provider-switch");