diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index f368ce8322..284fb539f4 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -14,7 +14,8 @@ import { import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, vi } from "@effect/vitest"; -import { Effect, Fiber, Layer, Option, Queue, Stream } from "effect"; +import { Effect, Fiber, Layer, Option, Queue, Scope, Stream } from "effect"; +import * as CodexErrors from "effect-codex-app-server/errors"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; @@ -152,6 +153,41 @@ function makeRuntimeFactory() { }; } +function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolean }) { + const runtimes: Array = []; + const releasedThreadIds: Array = []; + + const factory = vi.fn((runtimeOptions: CodexSessionRuntimeOptions) => + Effect.gen(function* () { + yield* Scope.Scope; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + releasedThreadIds.push(runtimeOptions.threadId); + }), + ); + + if (options?.failConstruction) { + return yield* new CodexErrors.CodexAppServerSpawnError({ + command: `${runtimeOptions.binaryPath} app-server`, + cause: new Error("runtime construction failed"), + }); + } + + const runtime = new FakeCodexRuntime(runtimeOptions); + runtimes.push(runtime); + return runtime; + }), + ); + + return { + factory, + releasedThreadIds, + get lastRuntime(): FakeCodexRuntime | undefined { + return runtimes.at(-1); + }, + }; +} + const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, { upsert: () => Effect.void, getProvider: () => @@ -862,3 +898,73 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { }), ); }); + +const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory(); +const scopedLifecycleLayer = it.layer( + makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ), +); + +scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => { + it.effect("closes the externally owned session scope on stopSession", () => + Effect.gen(function* () { + scopedLifecycleRuntimeFactory.releasedThreadIds.length = 0; + const adapter = yield* CodexAdapter; + + yield* adapter.startSession({ + provider: "codex", + threadId: asThreadId("thread-stop"), + runtimeMode: "full-access", + }); + + const runtime = scopedLifecycleRuntimeFactory.lastRuntime; + assert.ok(runtime); + + yield* adapter.stopSession(asThreadId("thread-stop")); + + assert.equal(runtime.closeImpl.mock.calls.length, 1); + assert.deepStrictEqual(scopedLifecycleRuntimeFactory.releasedThreadIds, [ + asThreadId("thread-stop"), + ]); + assert.equal(yield* adapter.hasSession(asThreadId("thread-stop")), false); + }), + ); +}); + +const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true }); +const scopedFailureLayer = it.layer( + makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ), +); + +scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => { + it.effect("closes the externally owned session scope when startSession fails", () => + Effect.gen(function* () { + scopedFailureRuntimeFactory.releasedThreadIds.length = 0; + const adapter = yield* CodexAdapter; + + const result = yield* adapter + .startSession({ + provider: "codex", + threadId: asThreadId("thread-fail"), + runtimeMode: "full-access", + }) + .pipe(Effect.result); + + assert.equal(result._tag, "Failure"); + assert.equal(result.failure._tag, "ProviderAdapterProcessError"); + assert.deepStrictEqual(scopedFailureRuntimeFactory.releasedThreadIds, [ + asThreadId("thread-fail"), + ]); + assert.equal(yield* adapter.hasSession(asThreadId("thread-fail")), false); + }), + ); +}); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 1c971346a0..8af872ff51 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -21,7 +21,7 @@ import { ThreadId, ProviderSendTurnInput, } from "@t3tools/contracts"; -import { Effect, Fiber, FileSystem, Layer, Queue, Schema, Stream } from "effect"; +import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; import * as CodexErrors from "effect-codex-app-server/errors"; import * as EffectCodexSchema from "effect-codex-app-server/schema"; @@ -56,7 +56,7 @@ export interface CodexAdapterLiveOptions { ) => Effect.Effect< CodexSessionRuntimeShape, CodexSessionRuntimeError, - ChildProcessSpawner.ChildProcessSpawner + ChildProcessSpawner.ChildProcessSpawner | Scope.Scope >; readonly nativeEventLogPath?: string; readonly nativeEventLogger?: EventNdjsonLogger; @@ -64,6 +64,7 @@ export interface CodexAdapterLiveOptions { interface CodexAdapterSessionContext { readonly threadId: ThreadId; + readonly scope: Scope.Closeable; readonly runtime: CodexSessionRuntimeShape; readonly eventFiber: Fiber.Fiber; stopped: boolean; @@ -1328,105 +1329,118 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( const runtimeEventQueue = yield* Queue.unbounded(); const sessions = new Map(); - const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")( - function* (input) { - if (input.provider !== undefined && input.provider !== PROVIDER) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "startSession", - issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + const startSession: CodexAdapterShape["startSession"] = (input) => + Effect.scoped( + Effect.gen(function* () { + if (input.provider !== undefined && input.provider !== PROVIDER) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "startSession", + issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + }); + } + + const existing = sessions.get(input.threadId); + if (existing && !existing.stopped) { + yield* Effect.suspend(() => stopSessionInternal(existing)); + } + + const codexSettings = yield* serverSettingsService.getSettings.pipe( + Effect.map((settings) => settings.providers.codex), + Effect.mapError( + (error) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: error.message, + cause: error, + }), + ), + ); + const runtimeInput: CodexSessionRuntimeOptions = { + threadId: input.threadId, + cwd: input.cwd ?? process.cwd(), + binaryPath: codexSettings.binaryPath, + ...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}), + ...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor) + ? { resumeCursor: input.resumeCursor } + : {}), + runtimeMode: input.runtimeMode, + ...(input.modelSelection?.provider === "codex" + ? { model: input.modelSelection.model } + : {}), + ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode + ? { serviceTier: "fast" } + : {}), + }; + const sessionScope = yield* Scope.make("sequential"); + let sessionScopeTransferred = false; + yield* Effect.addFinalizer(() => + sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void), + ); + const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime; + const runtime = yield* createRuntime(runtimeInput).pipe( + Effect.provideService(Scope.Scope, sessionScope), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), + Effect.mapError( + (cause) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: cause.message, + cause, + }), + ), + ); + + const eventFiber = yield* Stream.runForEach(runtime.events, (event) => + Effect.gen(function* () { + yield* writeNativeEvent(event); + const runtimeEvents = mapToRuntimeEvents(event, event.threadId); + if (runtimeEvents.length === 0) { + yield* Effect.logDebug("ignoring unhandled Codex provider event", { + method: event.method, + threadId: event.threadId, + turnId: event.turnId, + itemId: event.itemId, + }); + return; + } + yield* Queue.offerAll(runtimeEventQueue, runtimeEvents); + }), + ).pipe(Effect.forkChild); + + const started = yield* runtime.start().pipe( + Effect.mapError( + (cause) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: cause.message, + cause, + }), + ), + Effect.onError(() => + runtime.close.pipe( + Effect.andThen(Effect.ignore(Scope.close(sessionScope, Exit.void))), + Effect.andThen(Fiber.interrupt(eventFiber)), + Effect.ignore, + ), + ), + ); + + sessions.set(input.threadId, { + threadId: input.threadId, + scope: sessionScope, + runtime, + eventFiber, + stopped: false, }); - } + sessionScopeTransferred = true; - const existing = sessions.get(input.threadId); - if (existing && !existing.stopped) { - yield* Effect.suspend(() => stopSessionInternal(existing)); - } - - const codexSettings = yield* serverSettingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), - Effect.mapError( - (error) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: error.message, - cause: error, - }), - ), - ); - const runtimeInput: CodexSessionRuntimeOptions = { - threadId: input.threadId, - cwd: input.cwd ?? process.cwd(), - binaryPath: codexSettings.binaryPath, - ...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}), - ...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor) - ? { resumeCursor: input.resumeCursor } - : {}), - runtimeMode: input.runtimeMode, - ...(input.modelSelection?.provider === "codex" - ? { model: input.modelSelection.model } - : {}), - ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode - ? { serviceTier: "fast" } - : {}), - }; - const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime; - const runtime = yield* createRuntime(runtimeInput).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - Effect.mapError( - (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: cause.message, - cause, - }), - ), - ); - - const eventFiber = yield* Stream.runForEach(runtime.events, (event) => - Effect.gen(function* () { - yield* writeNativeEvent(event); - const runtimeEvents = mapToRuntimeEvents(event, event.threadId); - if (runtimeEvents.length === 0) { - yield* Effect.logDebug("ignoring unhandled Codex provider event", { - method: event.method, - threadId: event.threadId, - turnId: event.turnId, - itemId: event.itemId, - }); - return; - } - yield* Queue.offerAll(runtimeEventQueue, runtimeEvents); - }), - ).pipe(Effect.forkChild); - - const started = yield* runtime.start().pipe( - Effect.mapError( - (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: cause.message, - cause, - }), - ), - Effect.onError(() => - runtime.close.pipe(Effect.andThen(Fiber.interrupt(eventFiber)), Effect.ignore), - ), - ); - - sessions.set(input.threadId, { - threadId: input.threadId, - runtime, - eventFiber, - stopped: false, - }); - - return started; - }, - ); + return started; + }), + ); const resolveAttachment = Effect.fn("resolveAttachment")(function* ( input: ProviderSendTurnInput, @@ -1587,6 +1601,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( session.stopped = true; sessions.delete(session.threadId); yield* session.runtime.close.pipe(Effect.ignore); + yield* Effect.ignore(Scope.close(session.scope, Exit.void)); yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore); }); diff --git a/apps/server/src/provider/codex/CodexSessionRuntime.ts b/apps/server/src/provider/codex/CodexSessionRuntime.ts index 4a35e8f7ff..848a5612e8 100644 --- a/apps/server/src/provider/codex/CodexSessionRuntime.ts +++ b/apps/server/src/provider/codex/CodexSessionRuntime.ts @@ -602,11 +602,11 @@ export const makeCodexSessionRuntime = ( ): Effect.Effect< CodexSessionRuntimeShape, CodexErrors.CodexAppServerError, - ChildProcessSpawner.ChildProcessSpawner + ChildProcessSpawner.ChildProcessSpawner | Scope.Scope > => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const runtimeScope = yield* Scope.make("sequential"); + const runtimeScope = yield* Scope.Scope; const events = yield* Queue.unbounded(); const pendingApprovalsRef = yield* Ref.make(new Map()); const approvalCorrelationsRef = yield* Ref.make(new Map());