diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 280c899882bad..516b2f34aafa8 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -492,9 +492,24 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly spawnBeforeOpen?: boolean; readonly scopeCloseReached?: Deferred.Deferred; readonly eventStreamsEnded?: Queue.Queue; + 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) => + 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, @@ -513,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" }), @@ -561,7 +576,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( } return { - instanceId: ProviderInstanceId.make("codex"), + instanceId, driver: CODEX_DRIVER, providerSessionId: input.providerSessionId, ...(options.normalizeThreadLoadModelSelection === undefined @@ -637,6 +652,18 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ), respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => unimplemented("readThreadSnapshot unused in test"), + ...(mcpAppConfigs === undefined + ? {} + : { + 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 +707,10 @@ function layerTest(input: { readonly spawnBeforeOpen?: boolean; readonly scopeCloseReached?: Deferred.Deferred; readonly eventStreamsEnded?: Queue.Queue; + readonly mcpAppConfigs?: Ref.Ref< + ReadonlyArray + >; + readonly secondInstanceId?: ProviderInstanceId; readonly releaseRecorded?: Deferred.Deferred; readonly serverSettingsLayer?: ReturnType; readonly projectServiceLayer?: Layer.Layer; @@ -736,7 +767,18 @@ function layerTest(input: { ...(input.eventStreamsEnded === undefined ? {} : { eventStreamsEnded: input.eventStreamsEnded }), - }).pipe(Effect.map(ProviderAdapterRegistry.layerSingle)), + ...(input.mcpAppConfigs === undefined ? {} : { mcpAppConfigs: input.mcpAppConfigs }), + }).pipe( + Effect.flatMap((adapter) => + input.secondInstanceId === undefined + ? Effect.succeed([adapter]) + : makeProviderAdapter(input.state, { + instanceId: input.secondInstanceId, + ...(input.mcpAppConfigs === undefined ? {} : { mcpAppConfigs: input.mcpAppConfigs }), + }).pipe(Effect.map((second) => [adapter, second])), + ), + Effect.map(ProviderAdapterRegistry.layerFromAdapters), + ), ); const layerConfiguredMcpRegistry = input.pauseResolve === undefined @@ -3276,6 +3318,240 @@ 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 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 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; + 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 }), + ], + }); + const historicalSessionId = idAllocator.derive.providerSession({ + providerInstanceId: historicalInstanceId, + }); + yield* manager.open({ + threadId: owner, + providerSessionId: historicalSessionId, + modelSelection: { ...modelSelection, instanceId: historicalInstanceId }, + runtimePolicy, + }); + const historicalRuntime = Option.getOrUndefined(yield* manager.get(historicalSessionId)); + const openHistoricalApp = historicalRuntime!.mcpApps!.listTools({ + providerThread: makeProviderThread({ + idAllocator, + threadId: appThread, + providerSessionId: historicalSessionId, + now, + nativeThreadId: "native-mcp-apps-history", + }), + 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)); + const currentSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* manager.open({ + threadId: appThread, + providerSessionId: currentSessionId, + 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, + 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({ + state, + idleTimeoutMs: 1_000, + mcpAppConfigs, + mcpConfigs, + secondInstanceId: historicalInstanceId, + beforeOpen: () => + Ref.getAndSet(duringCurrentOpen, undefined).pipe( + Effect.flatMap((effect) => effect ?? Effect.void), + ), + }), + ), + ); + }), +); + 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..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(); @@ -566,6 +568,7 @@ export const layerWithOptions = ( const prepareMcpSession = ( threadId: ThreadId, providerInstanceId: ProviderInstanceId, + yieldToOtherInstance = false, ): Effect.Effect => options.configureMcp === false ? mcpSessions @@ -574,6 +577,22 @@ 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, yielded: true }; + } + } // Live providers build MCP clients once; reuse credentials across workspace handoffs. const { browser: browserToolsAvailable, device: deviceToolsAvailable } = yield* agentAccessSettings(threadId); @@ -1780,6 +1799,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,8 +1820,17 @@ 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.yielded === true) { + yield* removeThreadAttachment({ ...input, runtime: attached }); + attachedTo = undefined; + return; + } if (prepared.mcpCredentialId !== undefined) { const mcpCredentialId = prepared.mcpCredentialId; yield* Ref.update(sessions, (current) => { @@ -2355,7 +2385,58 @@ 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; + const passThrough = observeActivity( + providerSessionId, + touchActivity(providerSessionId), + ).pipe(Effect.andThen(effect)); + if (threadId === null) return passThrough; + // 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( + (entry) => + entry.runtime.instanceId !== runtime.instanceId && + entry.attachedThreadIds.has(threadId), + ), + ), + ); + const prepared = observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId, + providerInstanceId: runtime.instanceId, + yieldToOtherInstance: true, + }), + ).pipe( + Effect.andThen(observeActivity(providerSessionId, touchActivity(providerSessionId))), + Effect.andThen( + Effect.acquireUseRelease( + holdThreadLoaded({ + providerSessionId, + threadId, + providerThread, + }), + () => effect, + () => scheduleThreadUnload(providerSessionId, providerThread.id), + ), + ), + ); + return attachedToOtherInstance.pipe( + Effect.flatMap((elsewhere) => (elsewhere ? passThrough : prepared)), + ); + }; const turnMetrics = (operation: string, model?: string) => withMetrics({ counter: providerTurnsTotal, @@ -2597,6 +2678,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)), + }, + }), }; };