From 89cc4e53b9e3e6314795771ee9cfc504239e3379 Mon Sep 17 00:00:00 2001 From: SeongHoon Ryu <4997174+ryush00@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:30:22 +0900 Subject: [PATCH 1/5] fix(server): MCP apps prepare a thread's T3 MCP session before resuming Codex --- .../ProviderSessionManager.test.ts | 172 ++++++++++++++++++ .../ProviderSessionManager.ts | 48 +++++ 2 files changed, 220 insertions(+) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 280c899882bad..4d5b3aea21914 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -492,6 +492,9 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly spawnBeforeOpen?: boolean; readonly scopeCloseReached?: Deferred.Deferred; readonly eventStreamsEnded?: Queue.Queue; + readonly mcpAppConfigs?: Ref.Ref< + ReadonlyArray + >; } = {}, ) { const mcpSessions = yield* McpProviderSessions.McpProviderSessions; @@ -637,6 +640,28 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ), respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => unimplemented("readThreadSnapshot unused in test"), + ...(options.mcpAppConfigs === undefined + ? {} + : (() => { + const recordMcpAppConfig = (providerThread: OrchestrationV2ProviderThread) => + Effect.gen(function* () { + const config = + providerThread.appThreadId === null + ? undefined + : yield* mcpSessions.read(providerThread.appThreadId); + yield* Ref.update(options.mcpAppConfigs!, (configs) => [...configs, config]); + }); + return { + mcpApps: { + listTools: ({ providerThread }) => + recordMcpAppConfig(providerThread).pipe(Effect.as([])), + callTool: ({ providerThread }) => + recordMcpAppConfig(providerThread).pipe(Effect.as({ content: [] })), + readResource: ({ providerThread }) => + recordMcpAppConfig(providerThread).pipe(Effect.as({ contents: [] })), + }, + }; + })()), rollbackThread: () => unimplemented("rollbackThread unused in test"), forkThread: () => unimplemented("forkThread unused in test"), } satisfies ProviderAdapter.ProviderAdapterV2SessionRuntime; @@ -680,6 +705,9 @@ function layerTest(input: { readonly spawnBeforeOpen?: boolean; readonly scopeCloseReached?: Deferred.Deferred; readonly eventStreamsEnded?: Queue.Queue; + readonly mcpAppConfigs?: Ref.Ref< + ReadonlyArray + >; readonly releaseRecorded?: Deferred.Deferred; readonly serverSettingsLayer?: ReturnType; readonly projectServiceLayer?: Layer.Layer; @@ -736,6 +764,7 @@ function layerTest(input: { ...(input.eventStreamsEnded === undefined ? {} : { eventStreamsEnded: input.eventStreamsEnded }), + ...(input.mcpAppConfigs === undefined ? {} : { mcpAppConfigs: input.mcpAppConfigs }), }).pipe(Effect.map(ProviderAdapterRegistry.layerSingle)), ); const layerConfiguredMcpRegistry = @@ -3276,6 +3305,149 @@ it.effect("ProviderSessionManagerV2 terminal detach revokes the thread's MCP cre }), ); +it.effect( + "ProviderSessionManagerV2 prepares a thread's MCP session before mcpApps requests on a shared session", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const unloads = yield* Queue.unbounded(); + const mcpAppConfigs = yield* Ref.make< + ReadonlyArray + >([]); + const ownerTurnHeld = yield* Deferred.make(); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const registry = yield* McpSessionRegistry.McpSessionRegistry; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const now = yield* DateTime.now; + const owner = ThreadId.make("thread-provider-session-manager-mcp-apps-owner"); + const appThread = ThreadId.make("thread-provider-session-manager-mcp-apps-target"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: owner, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: appThread, now }), + ], + }); + const ownerRuntime = yield* manager.open({ + threadId: owner, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const ownerProviderThread = makeProviderThread({ + idAllocator, + threadId: owner, + providerSessionId, + now, + nativeThreadId: "native-mcp-apps-owner", + }); + const appProviderThread = makeProviderThread({ + idAllocator, + threadId: appThread, + providerSessionId, + now, + nativeThreadId: "native-mcp-apps-target", + }); + + // Keep the shared session alive via owner while appThread is still unattached (as after restart). + const ownerRunId = idAllocator.derive.run({ threadId: owner, ordinal: 1 }); + const ownerTurn = yield* ownerRuntime + .startTurn({ + appThread: (yield* projectionStore.getThreadProjection(owner)).thread, + threadId: owner, + providerThread: ownerProviderThread, + runId: ownerRunId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId: ownerRunId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId: ownerRunId }), + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ threadId: owner, ordinal: 1 }), + text: "keep busy", + attachments: [], + }, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.forkChild({ startImmediately: true })); + + assert.isUndefined(yield* mcpSessions.read(appThread)); + const liveRuntime = Option.getOrUndefined(yield* manager.get(providerSessionId)); + assert.isDefined(liveRuntime?.mcpApps); + + yield* Effect.all( + [ + liveRuntime!.mcpApps!.listTools({ + providerThread: appProviderThread, + server: "datadog", + }), + liveRuntime!.mcpApps!.callTool({ + providerThread: appProviderThread, + server: "datadog", + tool: "_dd_guc", + arguments: {}, + }), + liveRuntime!.mcpApps!.readResource({ + providerThread: appProviderThread, + server: "datadog", + uri: "ui://datadog/chart", + }), + ], + { concurrency: "unbounded" }, + ); + + const seen = yield* Ref.get(mcpAppConfigs); + assert.equal(seen.length, 3); + const firstConfig = seen[0]; + assert.isDefined(firstConfig, "mcpApps must prepare the thread's MCP session first"); + for (const config of seen) { + assert.equal(config?.providerSessionId, firstConfig!.providerSessionId); + } + const token = firstConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.equal((yield* registry.resolve(token))?.thread.threadId, appThread); + + // An idle thread loaded by an MCP app request still unloads after idleTimeoutMs. + yield* TestClock.adjust("1 second"); + assert.equal(yield* Queue.take(unloads), "unload:native-mcp-apps-target"); + + // A subsequent turn resume keeps the same credential valid instead of revoking it. + yield* liveRuntime!.resumeThread({ + threadId: appThread, + providerThread: appProviderThread, + }); + assert.equal( + (yield* mcpSessions.read(appThread))?.providerSessionId, + firstConfig!.providerSessionId, + ); + assert.equal((yield* registry.resolve(token))?.thread.threadId, appThread); + + yield* Deferred.succeed(ownerTurnHeld, undefined); + yield* Fiber.join(ownerTurn); + yield* manager.release({ providerSessionId, reason: "manual_shutdown" }); + assert.isUndefined(yield* registry.resolve(token)); + assert.isUndefined(yield* mcpSessions.read(appThread)); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1_000, + unloads, + mcpAppConfigs, + startTurn: Deferred.await(ownerTurnHeld), + }), + ), + ); + }), +); + it.effect( "ProviderSessionManagerV2 stops serving prompt suggestions once a thread is deleted", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index a495ec7be1630..aa62bd9f3913a 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2355,7 +2355,43 @@ export const layerWithOptions = ( >, ): ProviderAdapter.ProviderAdapterV2SessionRuntime => { const providerSessionId = runtime.providerSessionId; + const runtimeMcpApps = runtime.mcpApps; const subscribeEvents = makeEventSubscription(eventSubscribers); + // MCP app views reach a live shared runtime without opening a turn, so attach the thread + // first: Codex resumes unloaded threads on MCP app requests and needs the thread's T3 MCP + // credential before the first `thread/resume` locks in its MCP server set. + const withMcpAppThread = ( + providerThread: OrchestrationV2ProviderThread, + effect: Effect.Effect, + ): Effect.Effect => { + const threadId = providerThread.appThreadId; + if (threadId === null) { + return observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( + Effect.andThen(effect), + ); + } + return observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + Effect.andThen(observeActivity(providerSessionId, touchActivity(providerSessionId))), + Effect.andThen( + Effect.acquireUseRelease( + holdThreadLoaded({ + providerSessionId, + threadId, + providerThread, + }), + () => effect, + () => scheduleThreadUnload(providerSessionId, providerThread.id), + ), + ), + ); + }; const turnMetrics = (operation: string, model?: string) => withMetrics({ counter: providerTurnsTotal, @@ -2597,6 +2633,18 @@ export const layerWithOptions = ( .pipe(turnMetrics("runtime-request-response")), ), ), + ...(runtimeMcpApps === undefined + ? {} + : { + mcpApps: { + listTools: (input) => + withMcpAppThread(input.providerThread, runtimeMcpApps.listTools(input)), + callTool: (input) => + withMcpAppThread(input.providerThread, runtimeMcpApps.callTool(input)), + readResource: (input) => + withMcpAppThread(input.providerThread, runtimeMcpApps.readResource(input)), + }, + }), }; }; From bb1d7a6fe172d3cb2113c6083edc0026d0fd2ecb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 21:51:40 +0000 Subject: [PATCH 2/5] test(server): flatten the MCP app test adapter Co-Authored-By: Claude Opus 5.5 --- .../ProviderSessionManager.test.ts | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 4d5b3aea21914..b65eccae19adc 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -498,6 +498,16 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( } = {}, ) { const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const mcpAppConfigs = options.mcpAppConfigs; + const recordMcpAppConfig = (providerThread: OrchestrationV2ProviderThread) => + Effect.gen(function* () { + if (mcpAppConfigs === undefined) return; + const config = + providerThread.appThreadId === null + ? undefined + : yield* mcpSessions.read(providerThread.appThreadId); + yield* Ref.update(mcpAppConfigs, (configs) => [...configs, config]); + }); const countClose = Effect.addFinalizer(() => Ref.update(state, (current) => ({ ...current, @@ -640,28 +650,18 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ), respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => unimplemented("readThreadSnapshot unused in test"), - ...(options.mcpAppConfigs === undefined + ...(mcpAppConfigs === undefined ? {} - : (() => { - const recordMcpAppConfig = (providerThread: OrchestrationV2ProviderThread) => - Effect.gen(function* () { - const config = - providerThread.appThreadId === null - ? undefined - : yield* mcpSessions.read(providerThread.appThreadId); - yield* Ref.update(options.mcpAppConfigs!, (configs) => [...configs, config]); - }); - return { - mcpApps: { - listTools: ({ providerThread }) => - recordMcpAppConfig(providerThread).pipe(Effect.as([])), - callTool: ({ providerThread }) => - recordMcpAppConfig(providerThread).pipe(Effect.as({ content: [] })), - readResource: ({ providerThread }) => - recordMcpAppConfig(providerThread).pipe(Effect.as({ contents: [] })), - }, - }; - })()), + : { + mcpApps: { + listTools: ({ providerThread }) => + recordMcpAppConfig(providerThread).pipe(Effect.as([])), + callTool: ({ providerThread }) => + recordMcpAppConfig(providerThread).pipe(Effect.as({ content: [] })), + readResource: ({ providerThread }) => + recordMcpAppConfig(providerThread).pipe(Effect.as({ contents: [] })), + }, + }), rollbackThread: () => unimplemented("rollbackThread unused in test"), forkThread: () => unimplemented("forkThread unused in test"), } satisfies ProviderAdapter.ProviderAdapterV2SessionRuntime; From 221d71f3d72e0c395de6df41bb4c11253dc05de8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 22:00:45 +0000 Subject: [PATCH 3/5] fix(server): MCP apps leave a thread's live credential on another instance alone A historical MCP app can route to a live shared runtime on the thread's previous provider instance. Preparing the thread there rotated the credential the thread's current live provider holds, so app requests now pass through when another instance has the thread attached. Co-Authored-By: Claude Opus 5.5 --- .../ProviderSessionManager.test.ts | 93 ++++++++++++++++++- .../ProviderSessionManager.ts | 25 +++-- 2 files changed, 109 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index b65eccae19adc..8a6b5e404c766 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -495,8 +495,10 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly mcpAppConfigs?: Ref.Ref< ReadonlyArray >; + readonly instanceId?: ProviderInstanceId; } = {}, ) { + const instanceId = options.instanceId ?? ProviderInstanceId.make("codex"); const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const mcpAppConfigs = options.mcpAppConfigs; const recordMcpAppConfig = (providerThread: OrchestrationV2ProviderThread) => @@ -526,7 +528,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ).pipe(Effect.andThen(Effect.never)), ); return ProviderAdapter.ProviderAdapterV2.of({ - instanceId: ProviderInstanceId.make("codex"), + instanceId, driver: CODEX_DRIVER, getCapabilities: () => Effect.succeed(options.capabilities ?? CodexCapabilities), planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), @@ -574,7 +576,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( } return { - instanceId: ProviderInstanceId.make("codex"), + instanceId, driver: CODEX_DRIVER, providerSessionId: input.providerSessionId, ...(options.normalizeThreadLoadModelSelection === undefined @@ -708,6 +710,7 @@ function layerTest(input: { readonly mcpAppConfigs?: Ref.Ref< ReadonlyArray >; + readonly secondInstanceId?: ProviderInstanceId; readonly releaseRecorded?: Deferred.Deferred; readonly serverSettingsLayer?: ReturnType; readonly projectServiceLayer?: Layer.Layer; @@ -765,7 +768,16 @@ function layerTest(input: { ? {} : { eventStreamsEnded: input.eventStreamsEnded }), ...(input.mcpAppConfigs === undefined ? {} : { mcpAppConfigs: input.mcpAppConfigs }), - }).pipe(Effect.map(ProviderAdapterRegistry.layerSingle)), + }).pipe( + Effect.flatMap((adapter) => + input.secondInstanceId === undefined + ? Effect.succeed([adapter]) + : makeProviderAdapter(input.state, { instanceId: input.secondInstanceId }).pipe( + Effect.map((second) => [adapter, second]), + ), + ), + Effect.map(ProviderAdapterRegistry.layerFromAdapters), + ), ); const layerConfiguredMcpRegistry = input.pauseResolve === undefined @@ -3448,6 +3460,81 @@ it.effect( }), ); +it.effect( + "ProviderSessionManagerV2 keeps a thread's live credential when a historical MCP app targets another instance", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const mcpAppConfigs = yield* Ref.make< + ReadonlyArray + >([]); + const currentInstanceId = ProviderInstanceId.make("codex-current"); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const registry = yield* McpSessionRegistry.McpSessionRegistry; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const now = yield* DateTime.now; + const owner = ThreadId.make("thread-provider-session-manager-mcp-apps-history-owner"); + const appThread = ThreadId.make("thread-provider-session-manager-mcp-apps-history"); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: owner, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: appThread, now }), + ], + }); + yield* manager.open({ + threadId: appThread, + providerSessionId: idAllocator.derive.providerSession({ + providerInstanceId: currentInstanceId, + }), + modelSelection: { ...modelSelection, instanceId: currentInstanceId }, + runtimePolicy, + }); + const liveConfig = yield* mcpSessions.read(appThread); + assert.isDefined(liveConfig); + + const historicalSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* manager.open({ + threadId: owner, + providerSessionId: historicalSessionId, + modelSelection, + runtimePolicy, + }); + const historicalRuntime = Option.getOrUndefined(yield* manager.get(historicalSessionId)); + yield* historicalRuntime!.mcpApps!.listTools({ + providerThread: makeProviderThread({ + idAllocator, + threadId: appThread, + providerSessionId: historicalSessionId, + now, + nativeThreadId: "native-mcp-apps-history", + }), + server: "datadog", + }); + + assert.deepEqual(yield* mcpSessions.read(appThread), liveConfig); + const token = liveConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.equal( + (yield* registry.resolve(token))?.thread.providerInstanceId, + currentInstanceId, + ); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1_000, + mcpAppConfigs, + secondInstanceId: currentInstanceId, + }), + ), + ); + }), +); + it.effect( "ProviderSessionManagerV2 stops serving prompt suggestions once a thread is deleted", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index aa62bd9f3913a..b7bf546fd44b4 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2365,12 +2365,22 @@ export const layerWithOptions = ( effect: Effect.Effect, ): Effect.Effect => { const threadId = providerThread.appThreadId; - if (threadId === null) { - return observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( - Effect.andThen(effect), - ); - } - return observeActivity( + const passThrough = observeActivity( + providerSessionId, + touchActivity(providerSessionId), + ).pipe(Effect.andThen(effect)); + if (threadId === null) return passThrough; + // A historical app on another instance must not rotate the credential the thread's live provider holds. + const attachedToOtherInstance = Ref.get(sessions).pipe( + Effect.map((current) => + Array.from(current.values()).some( + (entry) => + entry.runtime.instanceId !== runtime.instanceId && + entry.attachedThreadIds.has(threadId), + ), + ), + ); + const prepared = observeActivity( providerSessionId, ensureThreadAttached({ providerSessionId, @@ -2391,6 +2401,9 @@ export const layerWithOptions = ( ), ), ); + return attachedToOtherInstance.pipe( + Effect.flatMap((elsewhere) => (elsewhere ? passThrough : prepared)), + ); }; const turnMetrics = (operation: string, model?: string) => withMetrics({ From 62be3e4a583b6d4e6e5c5cdacc59ed9b1814b538 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 22:17:32 +0000 Subject: [PATCH 4/5] fix(server): check another instance's credential under the MCP prepare lock The ownership check ran before the historical session's attachment lock, so another instance could attach the thread, or start opening it, in between and still lose its credential. prepareMcpSession now re-checks under its per-thread lock, which every instance shares, and also yields to a credential an in-flight open has reserved. Co-Authored-By: Claude Opus 5.5 --- .../ProviderSessionManager.test.ts | 52 ++++++++++++------- .../ProviderSessionManager.ts | 27 +++++++++- 2 files changed, 57 insertions(+), 22 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 8a6b5e404c766..15f53608aed62 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -772,9 +772,10 @@ function layerTest(input: { Effect.flatMap((adapter) => input.secondInstanceId === undefined ? Effect.succeed([adapter]) - : makeProviderAdapter(input.state, { instanceId: input.secondInstanceId }).pipe( - Effect.map((second) => [adapter, second]), - ), + : makeProviderAdapter(input.state, { + instanceId: input.secondInstanceId, + ...(input.mcpAppConfigs === undefined ? {} : { mcpAppConfigs: input.mcpAppConfigs }), + }).pipe(Effect.map((second) => [adapter, second])), ), Effect.map(ProviderAdapterRegistry.layerFromAdapters), ), @@ -3468,7 +3469,11 @@ it.effect( const mcpAppConfigs = yield* Ref.make< ReadonlyArray >([]); - const currentInstanceId = ProviderInstanceId.make("codex-current"); + const mcpConfigs = yield* Ref.make< + ReadonlyArray + >([]); + const duringCurrentOpen = yield* Ref.make | undefined>(undefined); + const historicalInstanceId = ProviderInstanceId.make("codex-historical"); yield* Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -3484,28 +3489,17 @@ it.effect( yield* makeThreadCreatedEvent({ idAllocator, threadId: appThread, now }), ], }); - yield* manager.open({ - threadId: appThread, - providerSessionId: idAllocator.derive.providerSession({ - providerInstanceId: currentInstanceId, - }), - modelSelection: { ...modelSelection, instanceId: currentInstanceId }, - runtimePolicy, - }); - const liveConfig = yield* mcpSessions.read(appThread); - assert.isDefined(liveConfig); - const historicalSessionId = idAllocator.derive.providerSession({ - providerInstanceId: modelSelection.instanceId, + providerInstanceId: historicalInstanceId, }); yield* manager.open({ threadId: owner, providerSessionId: historicalSessionId, - modelSelection, + modelSelection: { ...modelSelection, instanceId: historicalInstanceId }, runtimePolicy, }); const historicalRuntime = Option.getOrUndefined(yield* manager.get(historicalSessionId)); - yield* historicalRuntime!.mcpApps!.listTools({ + const openHistoricalApp = historicalRuntime!.mcpApps!.listTools({ providerThread: makeProviderThread({ idAllocator, threadId: appThread, @@ -3516,11 +3510,24 @@ it.effect( server: "datadog", }); + // First while the thread's current open is in flight, then once it is live. + yield* Ref.set(duringCurrentOpen, openHistoricalApp.pipe(Effect.asVoid, Effect.orDie)); + yield* manager.open({ + threadId: appThread, + providerSessionId: idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }), + modelSelection, + runtimePolicy, + }); + yield* openHistoricalApp; + + const liveConfig = (yield* Ref.get(mcpConfigs)).at(-1); assert.deepEqual(yield* mcpSessions.read(appThread), liveConfig); const token = liveConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); assert.equal( (yield* registry.resolve(token))?.thread.providerInstanceId, - currentInstanceId, + modelSelection.instanceId, ); }).pipe( Effect.provide( @@ -3528,7 +3535,12 @@ it.effect( state, idleTimeoutMs: 1_000, mcpAppConfigs, - secondInstanceId: currentInstanceId, + mcpConfigs, + secondInstanceId: historicalInstanceId, + beforeOpen: () => + Ref.getAndSet(duringCurrentOpen, undefined).pipe( + Effect.flatMap((effect) => effect ?? Effect.void), + ), }), ), ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b7bf546fd44b4..442f98d5a425b 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -566,6 +566,7 @@ export const layerWithOptions = ( const prepareMcpSession = ( threadId: ThreadId, providerInstanceId: ProviderInstanceId, + yieldToOtherInstance = false, ): Effect.Effect => options.configureMcp === false ? mcpSessions @@ -574,6 +575,20 @@ export const layerWithOptions = ( : mcpPrepareLock.withLock( threadId, Effect.gen(function* () { + // Checked under the per-thread lock, which every instance shares, so another + // instance's attach or in-flight open cannot land between this and the rotation. + if (yieldToOtherInstance) { + const current = yield* mcpSessions.read(threadId); + const heldElsewhere = + (current !== undefined && + isMcpCredentialReserved(threadId, current.providerSessionId)) || + Array.from((yield* Ref.get(sessions)).values()).some( + (entry) => + entry.runtime.instanceId !== providerInstanceId && + entry.attachedThreadIds.has(threadId), + ); + if (heldElsewhere) return { mcpCredentialId: undefined, issued: false }; + } // Live providers build MCP clients once; reuse credentials across workspace handoffs. const { browser: browserToolsAvailable, device: deviceToolsAvailable } = yield* agentAccessSettings(threadId); @@ -1780,6 +1795,8 @@ export const layerWithOptions = ( readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; readonly providerInstanceId: ProviderInstanceId; + /** Leave a credential alone that a live session on another instance holds. */ + readonly yieldToOtherInstance?: boolean; }) => Effect.suspend(() => { let attachedTo: ProviderAdapter.ProviderAdapterV2SessionRuntime | undefined; @@ -1799,7 +1816,11 @@ export const layerWithOptions = ( Effect.uninterruptible, ); if (attached !== undefined) { - const prepared = yield* prepareMcpSession(input.threadId, input.providerInstanceId); + const prepared = yield* prepareMcpSession( + input.threadId, + input.providerInstanceId, + input.yieldToOtherInstance, + ); preparedForCleanup = prepared; if (prepared.mcpCredentialId !== undefined) { const mcpCredentialId = prepared.mcpCredentialId; @@ -2370,7 +2391,8 @@ export const layerWithOptions = ( touchActivity(providerSessionId), ).pipe(Effect.andThen(effect)); if (threadId === null) return passThrough; - // A historical app on another instance must not rotate the credential the thread's live provider holds. + // A historical app must not rotate the credential the thread's live provider on another + // instance holds; this skips the attach, and prepareMcpSession re-checks under its lock. const attachedToOtherInstance = Ref.get(sessions).pipe( Effect.map((current) => Array.from(current.values()).some( @@ -2386,6 +2408,7 @@ export const layerWithOptions = ( providerSessionId, threadId, providerInstanceId: runtime.instanceId, + yieldToOtherInstance: true, }), ).pipe( Effect.andThen(observeActivity(providerSessionId, touchActivity(providerSessionId))), From a5a721222c59f62a5ea0eda6c7221223447f3ae9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 22:32:24 +0000 Subject: [PATCH 5/5] fix(server): drop an MCP app attachment that yields its credential A historical session that yielded to another instance's credential kept the thread attached with no credential of its own. That attachment kept the credential alive after the owning session released, and a later app request treated the thread as prepared. Undo the attachment instead, so the next request attaches and prepares again. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/ProviderSessionManager.test.ts | 11 ++++++++--- .../src/orchestration-v2/ProviderSessionManager.ts | 11 ++++++++++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 15f53608aed62..516b2f34aafa8 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3512,11 +3512,12 @@ it.effect( // First while the thread's current open is in flight, then once it is live. yield* Ref.set(duringCurrentOpen, openHistoricalApp.pipe(Effect.asVoid, Effect.orDie)); + const currentSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); yield* manager.open({ threadId: appThread, - providerSessionId: idAllocator.derive.providerSession({ - providerInstanceId: modelSelection.instanceId, - }), + providerSessionId: currentSessionId, modelSelection, runtimePolicy, }); @@ -3529,6 +3530,10 @@ it.effect( (yield* registry.resolve(token))?.thread.providerInstanceId, modelSelection.instanceId, ); + + // The historical session must not keep the thread attached, or it would keep the credential alive. + yield* manager.release({ providerSessionId: currentSessionId, reason: "manual_shutdown" }); + assert.isUndefined(yield* registry.resolve(token)); }).pipe( Effect.provide( layerTest({ diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 442f98d5a425b..3cd499209224f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -541,6 +541,8 @@ export const layerWithOptions = ( interface PreparedMcpCredential { readonly mcpCredentialId: string | undefined; readonly issued: boolean; + /** Another instance holds the thread's credential, so this attachment must not stay. */ + readonly yielded?: true; } /** ACP and OpenCode consume credentials during openSession; reserve them against revocation until publication. */ const mcpCredentialReservations = new Map(); @@ -587,7 +589,9 @@ export const layerWithOptions = ( entry.runtime.instanceId !== providerInstanceId && entry.attachedThreadIds.has(threadId), ); - if (heldElsewhere) return { mcpCredentialId: undefined, issued: false }; + if (heldElsewhere) { + return { mcpCredentialId: undefined, issued: false, yielded: true }; + } } // Live providers build MCP clients once; reuse credentials across workspace handoffs. const { browser: browserToolsAvailable, device: deviceToolsAvailable } = @@ -1822,6 +1826,11 @@ export const layerWithOptions = ( input.yieldToOtherInstance, ); preparedForCleanup = prepared; + if (prepared.yielded === true) { + yield* removeThreadAttachment({ ...input, runtime: attached }); + attachedTo = undefined; + return; + } if (prepared.mcpCredentialId !== undefined) { const mcpCredentialId = prepared.mcpCredentialId; yield* Ref.update(sessions, (current) => {