@devries-cameron20 / t3code Mirror · read-only / commits / 2ce31853d6
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 10:45 UTC

fix(codex): say why the Codex app-server exited (#23938)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>

Mantas Kantautas committed Oct 30, 2026 at 23:45 UTC 2ce31853d6545fc71dc3f262e05f78b935243cc8
5 files changed +288 -20
packages/effect-codex-app-server/src/_internal/stdio.test.ts
+171 -5
@@ -1,12 +1,67 @@
1 import { assert, describe, it } from "@effect/vitest";
2 import * as Effect from "effect/Effect";
3 +import * as Deferred from "effect/Deferred";
4 +import * as Fiber from "effect/Fiber";
5 +import * as Queue from "effect/Queue";
6 +import * as Stream from "effect/Stream";
7 +import * as TestClock from "effect/testing/TestClock";
8 import * as PlatformError from "effect/PlatformError";
9 import { ChildProcessSpawner } from "effect/process";
10
11 import * as CodexError from "../errors.ts";
7 -import { makeTerminationError } from "./stdio.ts";
12 +import * as CodexProtocol from "../protocol.ts";
13 +import {
14 + appendStderrTail,
15 + makeTerminationError,
16 + stderrExcerpt,
17 + makeInMemoryStdio,
18 + makeStderrTail,
19 + makeChildStdio,
20 +} from "./stdio.ts";
21
22 describe("Codex App Server child process termination", () => {
23 + it.effect("retains exit diagnostics when stderr stays open after stdout ends", () =>
24 + Effect.gen(function* () {
25 + const { stdio, input, output } = yield* makeInMemoryStdio();
26 + const captured = yield* Deferred.make<void>();
27 + const stderr = Stream.make(new TextEncoder().encode("Error: invalid config\n")).pipe(
28 + Stream.concat(Stream.fromEffect(Deferred.succeed(captured, undefined)).pipe(Stream.drain)),
29 + Stream.concat(Stream.never),
30 + );
31 + const tail = yield* makeStderrTail(stderr);
32 + const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
33 + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
34 + stdio: makeChildStdio({ stdout: stdio.stdin, stdin: stdio.stdout() }, tail.awaitDrained),
35 + terminationError: makeTerminationError(
36 + {
37 + pid: ChildProcessSpawner.ProcessId(55),
38 + exitCode: Deferred.await(exited),
39 + },
40 + tail.read,
41 + ),
42 + });
43 + const pending = yield* transport.request("thread/read", {}).pipe(
44 + Effect.match({
45 + onFailure: (error) => error,
46 + onSuccess: () => assert.fail("Expected the pending request to fail"),
47 + }),
48 + Effect.forkScoped,
49 + );
50 + yield* Queue.take(output);
51 + yield* Deferred.await(captured);
52 + yield* Queue.end(input);
53 + yield* TestClock.adjust("100 millis");
54 + yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(1));
55 + yield* TestClock.adjust("250 millis");
56 + const error = yield* Fiber.join(pending);
57 + assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
58 + assert.equal(
59 + error.message,
60 + "Codex App Server process exited with code 1: Error: invalid config",
61 + );
62 + }),
63 + );
64 +
65 it.effect("retains the process identifier and exact exit-status cause", () =>
66 Effect.gen(function* () {
67 const rootCause = new Error("private process diagnostics");
@@ -16,10 +71,13 @@ describe("Codex App Server child process termination", () => {
71 method: "exitCode",
72 cause: rootCause,
73 });
19 - const error = yield* makeTerminationError({
20 - pid: ChildProcessSpawner.ProcessId(52),
21 - exitCode: Effect.fail(cause),
22 - });
74 + const error = yield* makeTerminationError(
75 + {
76 + pid: ChildProcessSpawner.ProcessId(52),
77 + exitCode: Effect.fail(cause),
78 + },
79 + Effect.succeed(""),
80 + );
81
82 assert.instanceOf(error, CodexError.CodexAppServerTransportError);
83 assert.equal(error.pid, 52);
@@ -31,4 +89,112 @@ describe("Codex App Server child process termination", () => {
89 assert.notInclude(error.message, rootCause.message);
90 }),
91 );
92 +
93 + it.effect("names the stderr error line when the process exits", () =>
94 + Effect.gen(function* () {
95 + const error = yield* makeTerminationError(
96 + {
97 + pid: ChildProcessSpawner.ProcessId(53),
98 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
99 + },
100 + Effect.succeed("Error: Missing optional dependency @openai/codex-darwin-arm64.\n"),
101 + );
102 +
103 + assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
104 + assert.equal(error.stderr, "Error: Missing optional dependency @openai/codex-darwin-arm64.");
105 + assert.equal(
106 + error.message,
107 + "Codex App Server process exited with code 1: Error: Missing optional dependency @openai/codex-darwin-arm64.",
108 + );
109 + }),
110 + );
111 +
112 + it.effect("keeps the bare exit message when stderr is empty", () =>
113 + Effect.gen(function* () {
114 + const error = yield* makeTerminationError(
115 + {
116 + pid: ChildProcessSpawner.ProcessId(54),
117 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
118 + },
119 + Effect.succeed(" \n\n"),
120 + );
121 +
122 + assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
123 + assert.isUndefined(error.stderr);
124 + assert.equal(error.message, "Codex App Server process exited with code 1");
125 + }),
126 + );
127 +});
128 +
129 +describe("Codex App Server stderr excerpt", () => {
130 + it.each([
131 + {
132 + name: "Node launcher missing its platform package",
133 + stderr: [
134 + "file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:107",
135 + " throw new Error(",
136 + " ^",
137 + "",
138 + "Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",
139 + " at findCodexExecutable (file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:107:9)",
140 + " at file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:112:20",
141 + "",
142 + "Node.js v26.8.2",
143 + "",
144 + ].join("\n"),
145 + excerpt:
146 + "Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",
147 + },
148 + {
149 + name: "Node error with a code",
150 + stderr:
151 + "node:internal/modules/esm/resolve:873\n throw new ERR_MODULE_NOT_FOUND(\n\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'x'\n at packageResolve (node:internal/modules/esm/resolve:873:9)\n",
152 + excerpt: "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'x'",
153 + },
154 + {
155 + name: "Rust CLI error",
156 + stderr: "error: unexpected argument 'app-server' found\n\nUsage: codex [OPTIONS]\n",
157 + excerpt: "error: unexpected argument 'app-server' found",
158 + },
159 + {
160 + name: "uppercase error label",
161 + stderr: "ERROR: Missing dependency\nUsage: codex [OPTIONS]\n",
162 + excerpt: "ERROR: Missing dependency",
163 + },
164 + {
165 + name: "unlabelled message",
166 + stderr: "WARNING: proceeding without PATH aliases\nMissing OpenAI API key.\n",
167 + excerpt: "Missing OpenAI API key.",
168 + },
169 + {
170 + name: "ANSI color, carriage returns and repeated whitespace",
171 + stderr: "\u001b[31m Error:\t config.toml is invalid \u001b[0m\r\n",
172 + excerpt: "Error: config.toml is invalid",
173 + },
174 + {
175 + name: "C1 terminal controls",
176 + stderr: "\u009b31mError: invalid config\u009b0m\nUsage: codex [OPTIONS]\n",
177 + excerpt: "Error: invalid config",
178 + },
179 + {
180 + name: "oversized line",
181 + stderr: `Error: ${"x".repeat(1_000)}`,
182 + excerpt: `Error: ${"x".repeat(504)}…`,
183 + },
184 + ])("$name", ({ stderr, excerpt }) => {
185 + assert.equal(stderrExcerpt(stderr), excerpt);
186 + assert.isAtMost(excerpt.length, 512);
187 + });
188 +
189 + it("returns nothing for blank stderr", () => {
190 + assert.isUndefined(stderrExcerpt("\n \t\r\n\u001b[0m\n"));
191 + });
192 +
193 + it("keeps only the newest stderr", () => {
194 + const tail = appendStderrTail("a".repeat(8_000), `${"b".repeat(400)}\nError: last`);
195 +
196 + assert.equal(tail.length, 8_192);
197 + assert.isTrue(tail.endsWith("Error: last"));
198 + assert.equal(stderrExcerpt(tail), "Error: last");
199 + });
200 });
packages/effect-codex-app-server/src/_internal/stdio.ts
+68 -8
@@ -1,6 +1,10 @@
1 +import * as NodeUtil from "node:util";
2 +
3 import * as Cause from "effect/Cause";
4 +import * as Fiber from "effect/Fiber";
5 import * as Effect from "effect/Effect";
6 import * as Queue from "effect/Queue";
7 +import * as Ref from "effect/Ref";
8 import * as Sink from "effect/Sink";
9 import * as Stdio from "effect/Stdio";
10 import * as Stream from "effect/Stream";
@@ -10,10 +14,14 @@ import * as CodexError from "../errors.ts";
14
15 const encoder = new TextEncoder();
16
13 -export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
17 +export const makeChildStdio = (
18 + handle: Pick<ChildProcessSpawner.ChildProcessHandle, "stdin" | "stdout">,
19 + stderrDrained: Effect.Effect<void>,
20 +) =>
21 Stdio.make({
22 args: Effect.succeed([]),
16 - stdin: handle.stdout,
23 + // Finish stderr separately from the protocol's exit-status deadline.
24 + stdin: handle.stdout.pipe(Stream.onEnd(stderrDrained)),
25 stdout: () =>
26 Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
27 typeof chunk === "string" ? encoder.encode(chunk) : chunk,
@@ -44,6 +52,47 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
52 };
53 });
54
55 +const STDERR_TAIL_MAX_CHARS = 8_192;
56 +const STDERR_EXCERPT_MAX_CHARS = 512;
57 +// `Error: …`, `TypeError: …`, `Error [ERR_MODULE_NOT_FOUND]: …`, `error: …`, `ERROR: …`, `fatal: …`
58 +const ERROR_LINE_PATTERN = /^(?:[a-z]*error|fatal)(?: ?\[[^\]]+\])?:\s*\S/i;
59 +
60 +export const appendStderrTail = (current: string, chunk: string): string => {
61 + const next = `${current}${chunk}`;
62 + return next.length <= STDERR_TAIL_MAX_CHARS ? next : next.slice(-STDERR_TAIL_MAX_CHARS);
63 +};
64 +
65 +// Node launchers print the actionable error between a source excerpt and stack frames.
66 +export const stderrExcerpt = (tail: string): string | undefined => {
67 + const lines = NodeUtil.stripVTControlCharacters(tail)
68 + .split(/\r?\n/)
69 + .map((line) => line.trim().replace(/\s+/g, " "))
70 + .filter((line) => line.length > 0);
71 + const line = lines.findLast((candidate) => ERROR_LINE_PATTERN.test(candidate)) ?? lines.at(-1);
72 + if (line === undefined) {
73 + return undefined;
74 + }
75 + return line.length <= STDERR_EXCERPT_MAX_CHARS
76 + ? line
77 + : `${line.slice(0, STDERR_EXCERPT_MAX_CHARS - 1)}…`;
78 +};
79 +
80 +export const makeStderrTail = Effect.fn("makeStderrTail")(function* (
81 + stderr: ChildProcessSpawner.ChildProcessHandle["stderr"],
82 +) {
83 + const tail = yield* Ref.make("");
84 + const drain = yield* stderr.pipe(
85 + Stream.decodeText(),
86 + Stream.runForEach((chunk) => Ref.update(tail, (current) => appendStderrTail(current, chunk))),
87 + Effect.ignore,
88 + Effect.forkScoped,
89 + );
90 + return {
91 + read: Ref.get(tail),
92 + awaitDrained: Fiber.join(drain).pipe(Effect.timeout("250 millis"), Effect.ignore),
93 + };
94 +});
95 +
96 type ChildProcessTerminationHandle = Pick<
97 ChildProcessSpawner.ChildProcessHandle,
98 "exitCode" | "pid"
@@ -51,13 +100,24 @@ type ChildProcessTerminationHandle = Pick<
100
101 export const makeTerminationError = (
102 handle: ChildProcessTerminationHandle,
103 + stderrTail: Effect.Effect<string>,
104 ): Effect.Effect<CodexError.CodexAppServerError> =>
55 - Effect.match(handle.exitCode, {
105 + Effect.matchEffect(handle.exitCode, {
106 onFailure: (cause) =>
57 - new CodexError.CodexAppServerTransportError({
58 - operation: "read-process-exit-status",
59 - pid: handle.pid,
60 - cause,
107 + Effect.succeed(
108 + new CodexError.CodexAppServerTransportError({
109 + operation: "read-process-exit-status",
110 + pid: handle.pid,
111 + cause,
112 + }),
113 + ),
114 + onSuccess: (code) =>
115 + Effect.map(stderrTail, (tail) => {
116 + const stderr = stderrExcerpt(tail);
117 + return new CodexError.CodexAppServerProcessExitedError({
118 + code,
119 + pid: handle.pid,
120 + ...(stderr ? { stderr } : {}),
121 + });
122 }),
62 - onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),
123 });
packages/effect-codex-app-server/src/client.test.ts
+36
@@ -15,6 +15,7 @@ import { assert, expect, it } from "@effect/vitest";
15
16 import * as CodexClient from "./client.ts";
17 import { makeInMemoryStdio } from "./_internal/stdio.ts";
18 +import * as CodexError from "./errors.ts";
19
20 const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
21 path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),
@@ -209,3 +210,38 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
210 }),
211 );
212 });
213 +
214 +it.live("reports the stderr error when the process exits before initialize", () =>
215 + Effect.gen(function* () {
216 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
217 + const handle = yield* spawner.spawn(
218 + ChildProcess.make(process.execPath, [
219 + "-e",
220 + 'throw new Error("Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest")',
221 + ]),
222 + );
223 + const scope = yield* Scope.make();
224 + const context = yield* Layer.buildWithScope(CodexClient.layerChildProcess(handle), scope);
225 +
226 + const error = yield* Effect.gen(function* () {
227 + const client = yield* CodexClient.CodexAppServerClient;
228 + return yield* client.request("initialize", {
229 + clientInfo: {
230 + name: "effect-codex-app-server-test",
231 + title: "Effect Codex App Server Test",
232 + version: "0.0.0",
233 + },
234 + capabilities: {
235 + experimentalApi: true,
236 + optOutNotificationMethods: null,
237 + },
238 + });
239 + }).pipe(Effect.flip, Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
240 +
241 + assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
242 + assert.equal(
243 + error.message,
244 + "Codex App Server process exited with code 1: Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",
245 + );
246 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
247 +);
packages/effect-codex-app-server/src/client.ts
+7 -4
@@ -5,7 +5,6 @@ import * as Layer from "effect/Layer";
5 import * as Schema from "effect/Schema";
6 import * as Scope from "effect/Scope";
7 import * as Stdio from "effect/Stdio";
8 -import * as Stream from "effect/Stream";
8 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9
10 import * as CodexRpc from "./_generated/meta.gen.ts";
@@ -18,7 +17,7 @@ import {
17 encodeOptionalPayload,
18 runHandler,
19 } from "./_internal/shared.ts";
21 -import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
20 +import { makeChildStdio, makeStderrTail, makeTerminationError } from "./_internal/stdio.ts";
21
22 export interface CodexAppServerClientOptions {
23 readonly logIncoming?: boolean;
@@ -311,6 +310,10 @@ export const layerChildProcess = (
310 const makeChildProcessClient = Effect.fn(
311 "effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
312 )(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
314 - yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
315 - return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
313 + const stderrTail = yield* makeStderrTail(handle.stderr);
314 + return yield* make(
315 + makeChildStdio(handle, stderrTail.awaitDrained),
316 + options,
317 + makeTerminationError(handle, stderrTail.read),
318 + );
319 });
packages/effect-codex-app-server/src/errors.ts
+6 -3
@@ -138,13 +138,16 @@ export class CodexAppServerProcessExitedError extends Schema.TaggedError<CodexAp
138 {
139 code: Schema.optional(Schema.Number),
140 pid: Schema.optionalKey(Schema.Int),
141 + stderr: Schema.optionalKey(Schema.String),
142 cause: Schema.optional(Schema.Defect()),
143 },
144 ) {
145 override get message() {
145 - return this.code === undefined
146 - ? "Codex App Server process exited"
147 - : `Codex App Server process exited with code ${this.code}`;
146 + const base =
147 + this.code === undefined
148 + ? "Codex App Server process exited"
149 + : `Codex App Server process exited with code ${this.code}`;
150 + return this.stderr ? `${base}: ${this.stderr}` : base;
151 }
152 }
153