The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 05:45 UTC
fix(server): release the previous session when sending to another instance (#23198)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 2, 2026 at 18:33 UTC
c0ec87a55bbffa437673f037d7b4ca68c6a300f1
2 files changed
+223
-34
apps/server/src/orchestration-v2/Orchestrator.ts
+71
-24
@@ -6241,24 +6241,69 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6241
activeProviderThread.providerInstanceId !== modelSelection.instanceId;
6242
// Account overlays share native history. Selection commands may already
6243
// have updated the app thread, so classify against the native thread's owner.
6244
+ const providerSwitchPlan = isProviderSwitch
6245
+ ? yield* providerSwitchService
6246
+ .plan({
6247
+ projection: {
6248
+ ...projection,
6249
+ thread: {
6250
+ ...projection.thread,
6251
+ modelSelection: {
6252
+ ...projection.thread.modelSelection,
6253
+ instanceId: activeProviderThread.providerInstanceId,
6254
+ },
6255
+ },
6256
+ },
6257
+ targetModelSelection: modelSelection,
6258
+ })
6259
+ .pipe(mapDispatchError(command))
6260
+ : null;
6261
const canResumeAcrossInstances =
6262
isProviderSwitch &&
6263
activeProviderThread.nativeThreadRef !== null &&
6247
- (yield* providerSwitchService
6248
- .plan({
6249
- projection: {
6250
- ...projection,
6251
- thread: {
6252
- ...projection.thread,
6253
- modelSelection: {
6254
- ...projection.thread.modelSelection,
6255
- instanceId: activeProviderThread.providerInstanceId,
6256
- },
6257
- },
6258
- },
6259
- targetModelSelection: modelSelection,
6260
- })
6261
- .pipe(mapDispatchError(command))).transition.type === "restart_and_resume";
6264
+ providerSwitchPlan?.transition.type === "restart_and_resume";
6265
+ const sessionsToDetach = projection.providerSessions.filter(
6266
+ (session) =>
6267
+ providerSwitchPlan?.releaseProviderSessionIds.includes(session.id) &&
6268
+ session.status !== "stopped" &&
6269
+ session.status !== "error",
6270
+ );
6271
+ // Detaching kills background work running inside the provider process.
6272
+ // Probe even with an empty roster: Claude's native subagents never reach
6273
+ // pendingBackgroundTasks. Sessions shared across threads probe per thread.
6274
+ for (const detaching of sessionsToDetach) {
6275
+ const session = yield* providerSessions
6276
+ .get(detaching.id)
6277
+ .pipe(Effect.orElseSucceed(() => Option.none()));
6278
+ if (Option.isNone(session)) {
6279
+ continue;
6280
+ }
6281
+ const runtime = session.value;
6282
+ const probes =
6283
+ !detaching.capabilities.sessions.supportsMultipleProviderThreadsPerSession &&
6284
+ runtime.hasPendingBackgroundWork !== undefined
6285
+ ? [runtime.hasPendingBackgroundWork]
6286
+ : projection.providerThreads.flatMap((providerThread) =>
6287
+ providerThread.providerSessionId === detaching.id &&
6288
+ runtime.hasPendingBackgroundWorkForThread !== undefined
6289
+ ? [runtime.hasPendingBackgroundWorkForThread(providerThread)]
6290
+ : [],
6291
+ );
6292
+ for (const probe of probes) {
6293
+ const stillRunning = yield* probe.pipe(
6294
+ // A failed probe cannot confirm that the work ended.
6295
+ Effect.catchCause(() => Effect.succeed(true)),
6296
+ );
6297
+ if (stillRunning) {
6298
+ return yield* new OrchestratorDispatchError({
6299
+ commandId: command.commandId,
6300
+ commandType: command.type,
6301
+ cause:
6302
+ "The previous provider is still running background agents or commands, and switching would end them. Wait for them to finish, or press Stop, then send the message again.",
6303
+ });
6304
+ }
6305
+ }
6306
+ }
6307
6308
if (
6309
pendingForkTransfer === undefined &&
@@ -7565,30 +7610,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7610
});
7611
}
7612
7568
- if (canResumeAcrossInstances && activeProviderThread.providerSessionId !== null) {
7569
- const previousProviderSessionId = activeProviderThread.providerSessionId;
7613
+ const detachDetail = canResumeAcrossInstances
7614
+ ? "Provider account changed; continuing the native thread."
7615
+ : "Provider or model selection changed.";
7616
+ for (const session of sessionsToDetach) {
7617
yield* emitEvent({
7618
type: "provider-session.detached",
7619
threadId: command.threadId,
7573
- driver: activeProviderThread.driver,
7574
- providerInstanceId: activeProviderThread.providerInstanceId,
7620
+ driver: session.driver,
7621
+ providerInstanceId: session.providerInstanceId,
7622
occurredAt: now,
7623
payload: {
7577
- providerSessionId: previousProviderSessionId,
7624
+ providerSessionId: session.id,
7625
detachedAt: now,
7579
- reason: "Provider account changed; continuing the native thread.",
7626
+ reason: detachDetail,
7627
},
7628
});
7629
yield* Ref.update(effects, (existing) => [
7630
...existing,
7631
{
7585
- id: `effect:${command.commandId}:provider-session.detach:${previousProviderSessionId}`,
7632
+ id: `effect:${command.commandId}:provider-session.detach:${session.id}`,
7633
commandId: command.commandId,
7634
threadId: command.threadId,
7635
request: {
7636
type: "provider-session.detach",
7590
- providerSessionId: previousProviderSessionId,
7591
- detail: "Provider account changed; continuing the native thread.",
7637
+ providerSessionId: session.id,
7638
+ detail: detachDetail,
7639
},
7640
} satisfies PendingOrchestrationEffectV2,
7641
]);
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+152
-10
@@ -119,6 +119,8 @@ function makeTestAdapter(input: {
119
readonly subagentOnlyBackgroundWork?: boolean;
120
readonly holdFirstTurn?: Deferred.Deferred<void>;
121
readonly releaseFirstTurn?: Deferred.Deferred<void>;
122
+ readonly backgroundWork?: Ref.Ref<boolean>;
123
+ readonly closedSessions?: Ref.Ref<ReadonlyArray<string>>;
124
}): ProviderAdapter.ProviderAdapterV2["Service"] {
125
return {
126
instanceId: input.instanceId,
@@ -128,6 +130,12 @@ function makeTestAdapter(input: {
130
openSession: (sessionInput) =>
131
Effect.gen(function* () {
132
const events = yield* PubSub.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
133
+ if (input.closedSessions !== undefined) {
134
+ const closedSessions = input.closedSessions;
135
+ yield* Effect.addFinalizer(() =>
136
+ Ref.update(closedSessions, (ids) => [...ids, sessionInput.providerSessionId]),
137
+ );
138
+ }
139
const now = yield* DateTime.now;
140
const providerSession: OrchestrationV2ProviderSession = {
141
id: sessionInput.providerSessionId,
@@ -162,6 +170,14 @@ function makeTestAdapter(input: {
170
...(input.canReuseContextUsage === undefined
171
? {}
172
: { canReuseContextUsage: input.canReuseContextUsage }),
173
+ ...(input.backgroundWork === undefined
174
+ ? {}
175
+ : {
176
+ // Like Claude: native subagents are visible only to the session-wide
177
+ // probe, never to the per-thread roster probe.
178
+ hasPendingBackgroundWork: Ref.get(input.backgroundWork),
179
+ hasPendingBackgroundWorkForThread: () => Effect.succeed(false),
180
+ }),
181
ensureThread: (threadInput) =>
182
Effect.gen(function* () {
183
const createdAt = yield* DateTime.now;
@@ -748,16 +764,7 @@ describe("orchestration v2 provider switching", () => {
764
yield* wait(3);
765
}
766
if (replaceNative) {
751
- const target = (yield* orchestrator.getThreadProjection(threadId)).providerThreads.find(
752
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
753
- )!;
754
- yield* orchestrator.dispatch({
755
- type: "provider-session.detach",
756
- commandId: CommandId.make("detach-for-native-replacement"),
757
- threadId,
758
- providerSessionId: target.providerSessionId!,
759
- });
760
- yield* worker.drain();
767
+ // Switching back to Codex already released Claude's session.
768
yield* Ref.set(failResumeOnce, true);
769
}
770
if (scenario.includes("retry")) yield* Ref.set(failStartOnce, true);
@@ -2520,6 +2527,141 @@ describe("orchestration v2 provider switching", () => {
2527
),
2528
);
2529
2530
+ // regression: #20343 sending to an instance with separate history must release the old session
2531
+ it.live.each([
2532
+ ["detaches the previous instance's session when a send hands off to another instance", false],
2533
+ ["refuses the hand-off while the previous instance still runs background work", true],
2534
+ ] as const)("%s", ([, backgroundRunning]) =>
2535
+ Effect.scoped(
2536
+ Effect.gen(function* () {
2537
+ const cwd = yield* checkpointWorkspace("handoff-releases-session");
2538
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2539
+ const backgroundWork = yield* Ref.make(backgroundRunning);
2540
+ const closedSessions = yield* Ref.make<ReadonlyArray<string>>([]);
2541
+ const secondSelection: ModelSelection = {
2542
+ ...CLAUDE_MODEL_SELECTION,
2543
+ instanceId: ProviderInstanceId.make("claude-second-account"),
2544
+ };
2545
+ // No shared continuation key: each Claude instance owns its own native history.
2546
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2547
+ makeTestAdapter({
2548
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
2549
+ driver: CLAUDE_DRIVER,
2550
+ capabilities: ClaudeProviderCapabilitiesV2,
2551
+ modelSelection: CLAUDE_MODEL_SELECTION,
2552
+ responseByRunOrdinal: { 1: "First account complete" },
2553
+ capturedTurns,
2554
+ backgroundWork,
2555
+ closedSessions,
2556
+ }),
2557
+ makeTestAdapter({
2558
+ instanceId: secondSelection.instanceId,
2559
+ driver: CLAUDE_DRIVER,
2560
+ capabilities: ClaudeProviderCapabilitiesV2,
2561
+ modelSelection: secondSelection,
2562
+ responseByRunOrdinal: { 2: "Second account complete" },
2563
+ capturedTurns,
2564
+ }),
2565
+ ]);
2566
+ const handoffThreadId = ThreadId.make("thread:handoff-releases-session");
2567
+ yield* Effect.gen(function* () {
2568
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2569
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2570
+ const send = (ordinal: number, modelSelection: ModelSelection, attempt = "") =>
2571
+ orchestrator.dispatch({
2572
+ type: "message.dispatch",
2573
+ createdBy: "user",
2574
+ creationSource: "web",
2575
+ commandId: CommandId.make(`command:handoff-releases-session:${ordinal}${attempt}`),
2576
+ threadId: handoffThreadId,
2577
+ messageId: MessageId.make(`message:handoff-releases-session:${ordinal}${attempt}`),
2578
+ text: `Prompt ${ordinal}`,
2579
+ attachments: [],
2580
+ modelSelection,
2581
+ dispatchMode: { type: "start_immediately" },
2582
+ });
2583
+ yield* orchestrator.dispatch({
2584
+ type: "thread.create",
2585
+ createdBy: "user",
2586
+ creationSource: "web",
2587
+ commandId: CommandId.make("command:handoff-releases-session:create"),
2588
+ threadId: handoffThreadId,
2589
+ projectId: ProjectId.make("project:handoff-releases-session"),
2590
+ title: "Handoff releases session",
2591
+ modelSelection: CLAUDE_MODEL_SELECTION,
2592
+ runtimeMode: "full-access",
2593
+ interactionMode: "default",
2594
+ branch: null,
2595
+ worktreePath: cwd,
2596
+ });
2597
+ yield* send(1, CLAUDE_MODEL_SELECTION);
2598
+ yield* worker.drain();
2599
+ const afterFirst = yield* waitForIdle(handoffThreadId);
2600
+ const firstSession = afterFirst.providerSessions.find(
2601
+ (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
2602
+ );
2603
+ assert.equal(firstSession?.status, "ready");
2604
+
2605
+ if (backgroundRunning) {
2606
+ // Native subagents live only in the adapter's roster, so the projection's
2607
+ // pendingBackgroundTasks stays empty while the probe still reports work.
2608
+ assert.deepEqual(afterFirst.providerThreads[0]?.pendingBackgroundTasks ?? [], []);
2609
+ const refused = yield* send(2, secondSelection, ":refused").pipe(Effect.flip);
2610
+ assert.include(String(refused.cause), "still running background agents or commands");
2611
+ const unchanged = yield* orchestrator.getThreadProjection(handoffThreadId);
2612
+ assert.lengthOf(unchanged.runs, 1);
2613
+ assert.deepEqual(yield* Ref.get(closedSessions), []);
2614
+ assert.equal(unchanged.thread.providerInstanceId, CLAUDE_MODEL_SELECTION.instanceId);
2615
+ assert.deepEqual(
2616
+ unchanged.providerSessions.map((session) => [session.id, session.status]),
2617
+ [[firstSession!.id, "ready"]],
2618
+ );
2619
+ yield* Ref.set(backgroundWork, false);
2620
+ }
2621
+
2622
+ yield* send(2, secondSelection);
2623
+ yield* worker.drain();
2624
+ const afterSecond = yield* waitForIdle(handoffThreadId);
2625
+ yield* worker.drain();
2626
+ const projection = yield* orchestrator.getThreadProjection(handoffThreadId);
2627
+
2628
+ assert.deepEqual(
2629
+ projection.runs.map((run) => [run.providerInstanceId, run.status]),
2630
+ [
2631
+ [CLAUDE_MODEL_SELECTION.instanceId, "completed"],
2632
+ [secondSelection.instanceId, "completed"],
2633
+ ],
2634
+ );
2635
+ assert.lengthOf(afterSecond.contextHandoffs, 1);
2636
+ assert.deepEqual(
2637
+ projection.providerSessions.map((session) => session.providerInstanceId),
2638
+ [secondSelection.instanceId],
2639
+ );
2640
+ // The detached event alone hides the session; the runtime must also close.
2641
+ assert.deepEqual(yield* Ref.get(closedSessions), [firstSession!.id]);
2642
+ }).pipe(
2643
+ Effect.provide(
2644
+ ProviderReplayHarness.layerWithRegistry(
2645
+ {
2646
+ name: "handoff-releases-session",
2647
+ runtimePolicyOverride: {
2648
+ cwd,
2649
+ approvalPolicy: "never",
2650
+ sandboxPolicy: {
2651
+ type: "readOnly",
2652
+ access: { type: "fullAccess" },
2653
+ networkAccess: false,
2654
+ },
2655
+ },
2656
+ },
2657
+ layerRegistry,
2658
+ ),
2659
+ ),
2660
+ );
2661
+ }),
2662
+ ),
2663
+ );
2664
+
2665
// regression: #21314 a queued PR update must follow the provider that took over the thread
2666
it.live.each([
2667
["automatic", "Claude"],