diff --git a/packages/effect-codex-app-server/src/_internal/stdio.test.ts b/packages/effect-codex-app-server/src/_internal/stdio.test.ts index dcb00247b36ac..ad098718e2078 100644 --- a/packages/effect-codex-app-server/src/_internal/stdio.test.ts +++ b/packages/effect-codex-app-server/src/_internal/stdio.test.ts @@ -62,6 +62,28 @@ describe("Codex App Server child process termination", () => { }), ); + it.effect("waits for stderr to drain when the exit status arrives first", () => + Effect.gen(function* () { + const exitObserved = yield* Deferred.make(); + const stderr = Stream.fromEffect(Deferred.await(exitObserved)).pipe( + Stream.as(new TextEncoder().encode("Error: invalid config\n")), + ); + const tail = yield* makeStderrTail(stderr); + const error = yield* makeTerminationError( + { + pid: ChildProcessSpawner.ProcessId(56), + exitCode: Deferred.succeed(exitObserved, undefined).pipe( + Effect.as(ChildProcessSpawner.ExitCode(1)), + ), + }, + tail.read, + ); + + assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError); + assert.equal(error.stderr, "Error: invalid config"); + }), + ); + it.effect("retains the process identifier and exact exit-status cause", () => Effect.gen(function* () { const rootCause = new Error("private process diagnostics"); diff --git a/packages/effect-codex-app-server/src/_internal/stdio.ts b/packages/effect-codex-app-server/src/_internal/stdio.ts index a047d1aa804d4..41e8d25e5e78c 100644 --- a/packages/effect-codex-app-server/src/_internal/stdio.ts +++ b/packages/effect-codex-app-server/src/_internal/stdio.ts @@ -100,9 +100,14 @@ export const makeStderrTail = Effect.fn("makeStderrTail")(function* ( Effect.ignore, Effect.forkScoped, ); + // One bounded wait shared by every caller, so a later read never adds a second delay. + const awaitDrained = yield* Effect.cached( + Fiber.join(drain).pipe(Effect.timeout("250 millis"), Effect.ignore), + ); return { - read: Ref.get(tail), - awaitDrained: Fiber.join(drain).pipe(Effect.timeout("250 millis"), Effect.ignore), + // The exit status can arrive before stderr finishes, so a read waits for the drain. + read: Effect.andThen(awaitDrained, Ref.get(tail)), + awaitDrained, }; });