diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 3dd9c17c1eca..e373515514ac 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -9543,6 +9543,156 @@ describe("CodexAdapterV2 post-settle continuation", () => { ], }); + const computerUseItem = (input: { + readonly threadId: string; + readonly turnId: string; + }): ReadonlyArray => + (["inProgress", "completed"] as const).map((status) => ({ + type: "emit_inbound", + label: `computer-use/${status}`, + frame: { + method: status === "inProgress" ? "item/started" : "item/completed", + params: { + item: { + type: "mcpToolCall", + id: "call-codex-computer-use", + server: "cua_repl", + tool: "js", + status, + arguments: { code: 'let app = await cua.getApp("Calculator")' }, + }, + threadId: input.threadId, + turnId: input.turnId, + }, + }, + })); + + it.effect.each(["root", "subagent"] as const)( + "asks to unload promptly until every thread that used Computer Use (%s) is unloaded", + (usedBy) => + Effect.gen(function* () { + const unsubscribed: Array = []; + const unsubscribe = ( + id: number, + threadId: string, + ): CodexReplay.CodexAppServerReplayEntry[] => [ + { + type: "expect_outbound", + label: `unsubscribe ${threadId}`, + frame: { id, method: "thread/unsubscribe", params: { threadId } }, + }, + { + type: "emit_inbound", + label: `unsubscribed ${threadId}`, + frame: { id, result: { status: "unsubscribed" } }, + }, + ]; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-computer-use-prompt-unload", + entries: [ + ...codexReplayPreamble({ + nativeThreadId: RESUME_NATIVE_THREAD, + nativeTurnId: RESUME_NATIVE_TURN, + prompt: RESUME_PROMPT, + }), + ...(usedBy === "root" + ? computerUseItem({ threadId: RESUME_NATIVE_THREAD, turnId: RESUME_NATIVE_TURN }) + : [ + { + type: "emit_inbound" as const, + label: "item/completed/subAgentActivity-started", + frame: { + method: "item/completed", + params: { + item: { + type: "subAgentActivity", + id: "call-codex-resume-spawn", + kind: "started", + agentThreadId: RESUME_CHILD_THREAD, + agentPath: "/root/resume_agent", + }, + threadId: RESUME_NATIVE_THREAD, + turnId: RESUME_NATIVE_TURN, + }, + }, + }, + childTurnStarted(RESUME_CHILD_TURN_1), + ...computerUseItem({ + threadId: RESUME_CHILD_THREAD, + turnId: RESUME_CHILD_TURN_1, + }), + childTurnCompleted(RESUME_CHILD_TURN_1), + ]), + { + type: "emit_inbound", + label: "turn/completed/root", + frame: { + method: "turn/completed", + params: { + threadId: RESUME_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: RESUME_NATIVE_TURN, status: "completed" }), + }, + }, + }, + ...unsubscribe(4, RESUME_NATIVE_THREAD), + ...(usedBy === "subagent" ? unsubscribe(5, RESUME_CHILD_THREAD) : []), + ], + }), + undefined, + (method, params) => + Effect.sync(() => { + if (method === "thread/unsubscribe") { + unsubscribed.push((params as { readonly threadId: string }).threadId); + } + }), + ); + const shouldUnloadPromptly = () => + harness.runtime.shouldUnloadThreadPromptly!(harness.providerThread); + assert.isFalse(yield* shouldUnloadPromptly()); + + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-codex-computer-use"), + text: RESUME_PROMPT, + }), + ); + yield* harness.firstTerminal; + assert.isTrue(yield* shouldUnloadPromptly()); + + yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); + if (usedBy === "subagent") { + // Unloading the parent leaves the child loaded, so the manager must unload it too. + assert.isTrue(yield* shouldUnloadPromptly()); + const child = harness.events.findLast( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.nativeThreadRef?.nativeId === RESUME_CHILD_THREAD, + ); + assert(child?.type === "provider_thread.updated"); + assert.isTrue(yield* harness.runtime.shouldUnloadThreadPromptly!(child.providerThread)); + yield* harness.runtime.unloadThread!({ providerThread: child.providerThread }); + } + assert.isFalse(yield* shouldUnloadPromptly()); + assert.deepEqual( + unsubscribed, + usedBy === "root" ? [RESUME_NATIVE_THREAD] : [RESUME_NATIVE_THREAD, RESUME_CHILD_THREAD], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("wakes the parent when a native child finishes after the parent's turn", () => Effect.gen(function* () { const entries = resumeSubagentTranscript.entries; @@ -9579,12 +9729,19 @@ describe("CodexAdapterV2 post-settle continuation", () => { yield* harness.awaitTerminal(1); assert.equal(harness.terminalEvents()[0]?.status, "completed"); assert.lengthOf(harness.continuationRequests, 0); + // The running child must keep the parent loaded once its own turn has settled. + assert.isTrue( + yield* harness.runtime.hasPendingBackgroundWorkForThread!(harness.providerThread), + ); yield* TestClock.adjust("60 seconds"); yield* harness.until( () => harness.subagentUpdates().at(-1)?.subagent.result === "NATIVE_CHILD_16900_DONE", ); assert.equal(harness.subagentUpdates().at(-1)?.subagent.status, "completed"); + assert.isFalse( + yield* harness.runtime.hasPendingBackgroundWorkForThread!(harness.providerThread), + ); assert.lengthOf(harness.continuationRequests, 1); assert.include(harness.continuationRequests[0]?.detail, "NATIVE_CHILD_16900_DONE"); assert.equal(harness.continuationRequests[0]?.delivery, "message_text"); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 5b594563efa5..437568793465 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1460,6 +1460,17 @@ const isDescendantCodexTurn = ( return false; }; +const isCodexTurnOnThread = ( + context: ActiveCodexTurnContext, + providerThreadId: OrchestrationV2ProviderThread["id"], +): boolean => { + for (let turn: ActiveCodexTurnContext | undefined = context; turn !== undefined;) { + if (turn.providerThread.id === providerThreadId) return true; + turn = turn.subagent?.parentContext; + } + return false; +}; + interface PendingCodexSubagentTurnStarted { readonly nativeTurnId: string; readonly startedAt: DateTime.Utc; @@ -2227,6 +2238,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); /** Completed by thread/closed after this connection unsubscribes from the native thread. */ const threadClosings = new Map>(); + // On macOS the Computer Use service outlives its turn until the thread's MCP servers exit. + // Keyed by the native thread that ran it (a subagent's own), valued by its root provider thread. + const computerUseNativeThreads = new Map(); /** Codex acceptForSession covers only the exact command or patch, not future commands. */ const sessionApprovals = new Map< string, @@ -4316,6 +4330,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const projection = yield* projectCodexDynamicToolItem(item).pipe( Effect.provideService(Digest.Digest, digest), ); + const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId; + if (projection.toolSurface === "computer" && nativeThreadId != null) { + computerUseNativeThreads.set( + nativeThreadId, + approvalOwnerCodexTurn(context).owner.providerThread.id, + ); + } const node: OrchestrationV2ExecutionNode = { id: nodeId, threadId: context.projectionThreadId, @@ -5428,6 +5449,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.gen(function* () { const closing = threadClosings.get(payload.threadId); threadClosings.delete(payload.threadId); + computerUseNativeThreads.delete(payload.threadId); if (closing !== undefined) yield* Deferred.succeed(closing, undefined); const completedAt = yield* DateTime.now; for (const context of (yield* Ref.get(settledTurns)).values()) { @@ -8039,12 +8061,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(yield* Ref.get(activeTurns)).values(), ...(yield* Ref.get(settledTurns)).values(), ]; - const roots = contexts.filter( - (context) => context.providerThread.id === providerThread.id, - ); for (const context of contexts) { - if (!roots.some((root) => context === root || isDescendantCodexTurn(context, root))) - continue; + // Walk the lineage, so a child still running after its parent's turn settled counts. + if (!isCodexTurnOnThread(context, providerThread.id)) continue; if (yield* turnHasRetainedBackgroundWork(context.nativeTurnId)) return true; if ( context.subagent !== null && @@ -8052,8 +8071,25 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) return true; } + // A spawned child counts before its first turn/started arrives. + for (const subagent of (yield* Ref.get(subagentThreads)).values()) { + if ( + subagent.task.status === "running" && + isCodexTurnOnThread(subagent.parentContext, providerThread.id) + ) + return true; + } return false; }), + // A root stays prompt while a native subagent that used Computer Use is still loaded. + shouldUnloadThreadPromptly: (providerThread) => + Effect.sync(() => { + const nativeThreadId = providerThread.nativeThreadRef?.nativeId; + return ( + (nativeThreadId != null && computerUseNativeThreads.has(nativeThreadId)) || + Array.from(computerUseNativeThreads.values()).includes(providerThread.id) + ); + }), ensureThread: (threadInput) => ensureInitialized.pipe( Effect.andThen( @@ -8365,6 +8401,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } yield* client.request("thread/unsubscribe", { threadId: nativeThreadId }); } + computerUseNativeThreads.delete(nativeThreadId); // No turn/completed arrives for an unloaded thread, so a Stop Codex never // confirmed would otherwise keep its turn open for the life of the session. const interrupting = yield* Ref.get(interruptingNativeTurns); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 280c899882ba..aaaedca7e8ec 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -454,7 +454,7 @@ const makeNativeChildFixture = Effect.fnUntraced(function* () { modelSelection, runtimePolicy, }); - return { manager, parent, resumeChild }; + return { manager, parent, runtime, resumeChild }; }); function unimplemented(detail: string) { @@ -482,6 +482,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( }) => Effect.Effect; readonly hasPendingBackgroundWork?: Effect.Effect; readonly hasPendingBackgroundWorkForThread?: Effect.Effect; + readonly shouldUnloadThreadPromptly?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; readonly startTurn?: Effect.Effect; @@ -601,6 +602,11 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( : { hasPendingBackgroundWorkForThread: () => options.hasPendingBackgroundWorkForThread!, }), + ...(options.shouldUnloadThreadPromptly === undefined + ? {} + : { + shouldUnloadThreadPromptly: () => options.shouldUnloadThreadPromptly!, + }), ensureThread: () => unimplemented("ensureThread unused in test"), resumeThread: (threadInput) => Ref.update(state, (current) => ({ @@ -670,6 +676,7 @@ function layerTest(input: { }; readonly hasPendingBackgroundWork?: Effect.Effect; readonly hasPendingBackgroundWorkForThread?: Effect.Effect; + readonly shouldUnloadThreadPromptly?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; readonly startTurn?: Effect.Effect; @@ -718,6 +725,9 @@ function layerTest(input: { ...(input.hasPendingBackgroundWorkForThread === undefined ? {} : { hasPendingBackgroundWorkForThread: input.hasPendingBackgroundWorkForThread }), + ...(input.shouldUnloadThreadPromptly === undefined + ? {} + : { shouldUnloadThreadPromptly: input.shouldUnloadThreadPromptly }), ...(input.backgroundTasksEndWithProcess === undefined ? {} : { backgroundTasksEndWithProcess: input.backgroundTasksEndWithProcess }), @@ -5309,6 +5319,78 @@ it.effect( }), ); +it.effect( + "ProviderSessionManagerV2 promptly unloads an unattached native child after its parent", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const unloads = yield* Queue.unbounded(); + yield* Effect.gen(function* () { + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const { parent, runtime } = yield* makeNativeChildFixture(); + const now = yield* DateTime.now; + const providerThread = makeProviderThread({ idAllocator, ...parent, now }); + const runId = idAllocator.derive.run({ threadId: parent.threadId, ordinal: 1 }); + yield* runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(parent.threadId)).thread, + threadId: parent.threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ + threadId: parent.threadId, + ordinal: 1, + }), + text: "Delegate to a child that uses the computer", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const subscription = yield* runtime.subscribeEvents!; + yield* Queue.offer( + (yield* Ref.get(state)).eventQueues.get(String(parent.providerSessionId))!, + { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: "native-parent-turn", + }), + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }, + ); + yield* subscription.events.pipe(Stream.runHead); + + yield* TestClock.adjust("5 seconds"); + assert.equal(yield* Queue.take(unloads), "unload:native-thread"); + assert.equal(yield* Queue.take(unloads), "unload:native-child-thread"); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 30 * 60 * 1000, + unloads, + shouldUnloadThreadPromptly: Effect.succeed(true), + hasPendingBackgroundWork: Effect.succeed(true), + }), + ), + Effect.scoped, + ); + }), +); + it.effect.each([ { keptOpen: true, archive: "succeeds" }, { keptOpen: false, archive: "succeeds" }, @@ -5472,6 +5554,148 @@ it.effect.each([ }), ); +it.effect.each([ + "prompt", + "idle", + "prompt after pending work", + "prompt once a child finishes", +] as const)( + "ProviderSessionManagerV2 unloads an idle thread after a short delay only when its runtime asks (%s)", + (scenario) => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const unloads = yield* Queue.unbounded(); + const pendingWork = yield* Ref.make(scenario === "prompt after pending work"); + const prompt = yield* Ref.make( + scenario === "prompt" || scenario === "prompt after pending work", + ); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-prompt-unload"); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ threadId, ordinal: 1 }), + text: "Use the computer", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const subscription = yield* runtime.subscribeEvents!; + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId))!; + yield* Queue.offer(queue, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: "native-turn-prompt-unload", + }), + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* subscription.events.pipe(Stream.runHead); + + yield* TestClock.adjust("5 seconds"); + if (scenario === "prompt once a child finishes") { + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + // The child first used Computer Use after the parent's 30 minute timer started. + yield* Ref.set(prompt, true); + const childFinished = yield* runtime.subscribeEvents!; + yield* Queue.offer(queue, { + type: "subagent.updated", + driver: CODEX_DRIVER, + subagent: { + id: idAllocator.derive.nodeFromProviderItem({ + driver: CODEX_DRIVER, + nativeItemId: "native-child-task", + }), + threadId, + runId, + parentNodeId: idAllocator.derive.rootNode({ runId }), + origin: "provider_native", + createdBy: "agent", + driver: CODEX_DRIVER, + providerInstanceId: modelSelection.instanceId, + providerThreadId: null, + childThreadId: null, + nativeTaskRef: { + driver: CODEX_DRIVER, + nativeId: "native-child-task", + strength: "strong", + }, + prompt: "Use the computer", + title: null, + model: null, + status: "completed", + result: "done", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }); + yield* childFinished.events.pipe(Stream.runHead); + yield* TestClock.adjust("5 seconds"); + } else if (scenario !== "prompt") { + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + yield* Ref.set(pendingWork, false); + // A deferred prompt unload rechecks after the short delay, not the idle timeout. + yield* TestClock.adjust(scenario === "idle" ? "30 minutes" : "5 seconds"); + } + assert.equal(yield* Queue.take(unloads), "unload:native-thread"); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 30 * 60 * 1000, + unloads, + shouldUnloadThreadPromptly: Ref.get(prompt), + hasPendingBackgroundWorkForThread: Ref.get(pendingWork), + // Another thread's work keeps the session open, so only the thread unloads. + hasPendingBackgroundWork: Effect.succeed(true), + }), + ), + ); + }), +); + it.effect( "ProviderSessionManagerV2 re-attaching a thread waits for its in-flight unload, then reloads it", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index a495ec7be163..50955ec8c257 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -69,6 +69,7 @@ import * as ProjectionStore from "./ProjectionStore.ts"; const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000; +const PROMPT_THREAD_UNLOAD_MS = 5 * 1000; const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000; /** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */ export const PROVIDER_INTERRUPT_TIMEOUT_MS = 15 * 1000; @@ -1984,8 +1985,34 @@ export const layerWithOptions = ( }, ); + const unloadsPromptly = ( + runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, + providerThread: OrchestrationV2ProviderThread, + ) => + runtime.shouldUnloadThreadPromptly === undefined + ? Effect.succeed(false) + : runtime + .shouldUnloadThreadPromptly(providerThread) + .pipe(Effect.catchCause(() => Effect.succeed(false))); + + const idleThreadUnloadDelay = Effect.fn("ProviderSessionManager.idleThreadUnloadDelay")( + function* ( + runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, + providerThread: OrchestrationV2ProviderThread, + ) { + return (yield* unloadsPromptly(runtime, providerThread)) + ? Math.min(PROMPT_THREAD_UNLOAD_MS, idleTimeoutMs) + : idleTimeoutMs; + }, + ); + const scheduleThreadUnload = Effect.fn("ProviderSessionManager.scheduleThreadUnload")( - function* (providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId) { + function* ( + providerSessionId: ProviderSessionId, + providerThreadId: ProviderThreadId, + /** Arms only if this record is still current, so a reschedule cannot time a newer hold. */ + expected?: IdleThreadUnload, + ) { const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId)); if (entry === undefined || hasBusyTurn(entry, providerThreadId)) return; const tracked = Array.from(entry.idleThreadUnloads).find( @@ -1993,19 +2020,29 @@ export const layerWithOptions = ( ); if (tracked === undefined) return; const [threadId, pending] = tracked; + if (expected !== undefined && pending !== expected) return; const generation = pending.generation + 1; - const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const delayMs = yield* idleThreadUnloadDelay(entry.runtime, pending.providerThread); + const fiber = yield* Effect.sleep(Duration.millis(delayMs)).pipe( Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })), Effect.forkIn(layerScope), ); + // By identity: a detach and reattach during the probe can reuse the generation number. const previous = yield* updateIdleThreadUnload(providerSessionId, threadId, (current) => - current?.generation === pending.generation - ? { ...current, generation, fiber } - : current, - ); - yield* cancelIdleFiber( - previous?.generation === pending.generation ? previous.fiber : fiber, + current === pending ? { ...current, generation, fiber } : current, ); + yield* cancelIdleFiber(previous === pending ? previous.fiber : fiber); + }, + ); + + // A native child can first use a prompt-unload resource after its parent's timer started. + const rescheduleParentUnload = Effect.fn("ProviderSessionManager.rescheduleParentUnload")( + function* (providerSessionId: ProviderSessionId, threadId: ThreadId) { + const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId)); + const pending = entry?.idleThreadUnloads.get(threadId); + if (entry === undefined || pending === undefined || pending.fiber === null) return; + if (!(yield* unloadsPromptly(entry.runtime, pending.providerThread))) return; + yield* scheduleThreadUnload(providerSessionId, pending.providerThread.id, pending); }, ); @@ -2040,6 +2077,81 @@ export const layerWithOptions = ( (effect) => effect.pipe(Effect.orElseSucceed(() => undefined)), ); + /** Locks each owner so a provider thread another attached app thread holds stays loaded. */ + const unloadUnattachedProviderThreads = Effect.fn( + "ProviderSessionManager.unloadUnattachedProviderThreads", + )(function* (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; + readonly unloadThread: NonNullable< + ProviderAdapter.ProviderAdapterV2SessionRuntime["unloadThread"] + >; + readonly providerThreads: ReadonlyArray; + readonly failureLog: string; + }) { + const key = sessionKey(input.providerSessionId); + for (const providerThread of input.providerThreads) { + if (providerThread.nativeThreadRef === null) continue; + const ownerThreadId = providerThread.appThreadId ?? input.threadId; + yield* threadAttachment.withLock( + threadAttachmentKey({ + providerSessionId: input.providerSessionId, + threadId: ownerThreadId, + }), + Effect.gen(function* () { + const entry = (yield* Ref.get(sessions)).get(key); + if (entry?.runtime !== input.runtime || entry.attachedThreadIds.has(ownerThreadId)) { + return; + } + yield* input.unloadThread({ providerThread }).pipe( + Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), + Effect.catchCause((cause) => + Effect.logWarning(input.failureLog, { + providerSessionId: input.providerSessionId, + threadId: ownerThreadId, + providerThreadId: providerThread.id, + cause, + }), + ), + ); + }), + ); + } + }); + + // Unloading a parent leaves its native children loaded; release those the runtime wants gone. + const unloadPromptNativeChildren = Effect.fn( + "ProviderSessionManager.unloadPromptNativeChildren", + )(function* (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly parent: OrchestrationV2ProviderThread; + readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; + readonly unloadThread: NonNullable< + ProviderAdapter.ProviderAdapterV2SessionRuntime["unloadThread"] + >; + }) { + if (input.runtime.shouldUnloadThreadPromptly === undefined) return; + const projection = yield* Effect.option( + projectionStore.getThreadRecords(input.threadId, ["providerThreads"]), + ); + if (Option.isNone(projection)) return; + const providerThreads = yield* Effect.filter(projection.value.providerThreads, (thread) => + thread.providerSessionId === input.providerSessionId && thread.id !== input.parent.id + ? unloadsPromptly(input.runtime, thread) + : Effect.succeed(false), + ); + yield* unloadUnattachedProviderThreads({ + providerSessionId: input.providerSessionId, + threadId: input.threadId, + runtime: input.runtime, + unloadThread: input.unloadThread, + providerThreads, + failureLog: "orchestration-v2.driver-session.idle-child-unload-failed", + }); + }); + const unloadIdleThread = Effect.fn("ProviderSessionManager.unloadIdleThread")( function* (input: { readonly providerSessionId: ProviderSessionId; @@ -2136,12 +2248,32 @@ export const layerWithOptions = ( }), ), ); - return "unloaded" as const; + return { + parent: pending.providerThread, + runtime: entry.runtime, + unloadThread, + } as const; }), ); - // Wait outside the lock so the next attach is not blocked. + // Wait and unload children outside the lock so the next attach is not blocked. + if (typeof outcome === "object") { + yield* unloadPromptNativeChildren({ + providerSessionId: input.providerSessionId, + threadId: input.threadId, + ...outcome, + }); + return; + } if (outcome === "deferred" && input.archiveOnly !== true) { - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); + const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId)); + const pending = entry?.idleThreadUnloads.get(input.threadId); + yield* Effect.sleep( + Duration.millis( + entry === undefined || pending === undefined + ? idleTimeoutMs + : yield* idleThreadUnloadDelay(entry.runtime, pending.providerThread), + ), + ); return yield* unloadIdleThread(input); } }, @@ -2876,6 +3008,12 @@ export const layerWithOptions = ( ? persistProviderSessionUpdate(entry, event) : Effect.void, ), + Effect.andThen( + event.type === "subagent.updated" && + !isOrchestrationV2WorkActive(event.subagent.status) + ? rescheduleParentUnload(entry.runtime.providerSessionId, event.subagent.threadId) + : Effect.void, + ), Effect.andThen( Effect.gen(function* () { if ( @@ -3433,38 +3571,15 @@ export const layerWithOptions = ( } const unloadThread = detached.value.exposedRuntime.unloadThread; if (detached.value.supportsMultipleProviderThreads && unloadThread !== undefined) { - // The projection includes native children owned by other app threads; - // lock each owner so an attached child stays loaded and later attaches wait. - for (const providerThread of detachedProviderThreads) { - if (providerThread.nativeThreadRef === null) continue; - const ownerThreadId = providerThread.appThreadId ?? input.threadId; - yield* threadAttachment.withLock( - threadAttachmentKey({ - providerSessionId: input.providerSessionId, - threadId: ownerThreadId, - }), - Effect.gen(function* () { - const entry = (yield* Ref.get(sessions)).get(key); - if ( - entry?.runtime !== detached.value.runtime || - entry.attachedThreadIds.has(ownerThreadId) - ) { - return; - } - yield* unloadThread({ providerThread }).pipe( - Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.detach-unload-failed", { - providerSessionId: input.providerSessionId, - threadId: ownerThreadId, - providerThreadId: providerThread.id, - cause, - }), - ), - ); - }), - ); - } + // The projection includes native children owned by other app threads. + yield* unloadUnattachedProviderThreads({ + providerSessionId: input.providerSessionId, + threadId: input.threadId, + runtime: detached.value.runtime, + unloadThread, + providerThreads: detachedProviderThreads, + failureLog: "orchestration-v2.driver-session.detach-unload-failed", + }); } yield* scheduleIdleRelease(input.providerSessionId); }, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 1157d66b05f8..e3ef72a81518 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -813,6 +813,10 @@ export interface ProviderAdapterV2SessionRuntime { /** Also hide it from the provider's own clients where it can; resuming it must restore it. */ readonly archive?: boolean; }) => Effect.Effect; + /** True when the loaded thread holds a resource that only unloading releases, such as Computer Use. */ + readonly shouldUnloadThreadPromptly?: ( + providerThread: OrchestrationV2ProviderThread, + ) => Effect.Effect; readonly respondToRuntimeRequest: ( input: ProviderAdapterV2RuntimeRequestResponseInput, ) => Effect.Effect;