Skip to content

Commit c4434fc

Browse files
committed
fix(codex): say why the Codex app-server exited
The Codex client drained the app-server's stderr and threw it away, so a launcher that dies before initialize showed only "Codex App Server process exited with code 1". A one-click npm update that skips @openai/codex-<platform> leaves exactly that state, and the launcher's own explanation never reached the provider banner. The client now keeps the last 8 KiB of stderr. When the process exits, CodexAppServerProcessExitedError carries the line that names the failure (the last error-labelled line, else the last line), stripped of terminal controls and capped at 512 characters, and appends it to its message.
1 parent a8dba9c commit c4434fc

5 files changed

Lines changed: 226 additions & 18 deletions

File tree

‎packages/effect-codex-app-server/src/_internal/stdio.test.ts‎

Lines changed: 106 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import * as PlatformError from "effect/PlatformError";
44
import { ChildProcessSpawner } from "effect/process";
55

66
import * as CodexError from "../errors.ts";
7-
import { makeTerminationError } from "./stdio.ts";
7+
import { appendStderrTail, makeTerminationError, stderrExcerpt } from "./stdio.ts";
88

99
describe("Codex App Server child process termination", () => {
1010
it.effect("retains the process identifier and exact exit-status cause", () =>
@@ -16,10 +16,13 @@ describe("Codex App Server child process termination", () => {
1616
method: "exitCode",
1717
cause: rootCause,
1818
});
19-
const error = yield* makeTerminationError({
20-
pid: ChildProcessSpawner.ProcessId(52),
21-
exitCode: Effect.fail(cause),
22-
});
19+
const error = yield* makeTerminationError(
20+
{
21+
pid: ChildProcessSpawner.ProcessId(52),
22+
exitCode: Effect.fail(cause),
23+
},
24+
Effect.succeed(""),
25+
);
2326

2427
assert.instanceOf(error, CodexError.CodexAppServerTransportError);
2528
assert.equal(error.pid, 52);
@@ -31,4 +34,102 @@ describe("Codex App Server child process termination", () => {
3134
assert.notInclude(error.message, rootCause.message);
3235
}),
3336
);
37+
38+
it.effect("names the stderr error line when the process exits", () =>
39+
Effect.gen(function* () {
40+
const error = yield* makeTerminationError(
41+
{
42+
pid: ChildProcessSpawner.ProcessId(53),
43+
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
44+
},
45+
Effect.succeed("Error: Missing optional dependency @openai/codex-darwin-arm64.\n"),
46+
);
47+
48+
assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
49+
assert.equal(error.stderr, "Error: Missing optional dependency @openai/codex-darwin-arm64.");
50+
assert.equal(
51+
error.message,
52+
"Codex App Server process exited with code 1: Error: Missing optional dependency @openai/codex-darwin-arm64.",
53+
);
54+
}),
55+
);
56+
57+
it.effect("keeps the bare exit message when stderr is empty", () =>
58+
Effect.gen(function* () {
59+
const error = yield* makeTerminationError(
60+
{
61+
pid: ChildProcessSpawner.ProcessId(54),
62+
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
63+
},
64+
Effect.succeed(" \n\n"),
65+
);
66+
67+
assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
68+
assert.isUndefined(error.stderr);
69+
assert.equal(error.message, "Codex App Server process exited with code 1");
70+
}),
71+
);
72+
});
73+
74+
describe("Codex App Server stderr excerpt", () => {
75+
it.each([
76+
{
77+
name: "Node launcher missing its platform package",
78+
stderr: [
79+
"file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:107",
80+
" throw new Error(",
81+
" ^",
82+
"",
83+
"Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",
84+
" at findCodexExecutable (file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:107:9)",
85+
" at file:///usr/local/lib/node_modules/@openai/codex/bin/codex.js:112:20",
86+
"",
87+
"Node.js v26.8.2",
88+
"",
89+
].join("\n"),
90+
excerpt:
91+
"Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",
92+
},
93+
{
94+
name: "Node error with a code",
95+
stderr:
96+
"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",
97+
excerpt: "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'x'",
98+
},
99+
{
100+
name: "Rust CLI error",
101+
stderr: "error: unexpected argument 'app-server' found\n\nUsage: codex [OPTIONS]\n",
102+
excerpt: "error: unexpected argument 'app-server' found",
103+
},
104+
{
105+
name: "unlabelled message",
106+
stderr: "WARNING: proceeding without PATH aliases\nMissing OpenAI API key.\n",
107+
excerpt: "Missing OpenAI API key.",
108+
},
109+
{
110+
name: "ANSI color, carriage returns and repeated whitespace",
111+
stderr: "\u001b[31m Error:\t config.toml is invalid \u001b[0m\r\n",
112+
excerpt: "Error: config.toml is invalid",
113+
},
114+
{
115+
name: "oversized line",
116+
stderr: `Error: ${"x".repeat(1_000)}`,
117+
excerpt: `Error: ${"x".repeat(504)}…`,
118+
},
119+
])("$name", ({ stderr, excerpt }) => {
120+
assert.equal(stderrExcerpt(stderr), excerpt);
121+
assert.isAtMost(excerpt.length, 512);
122+
});
123+
124+
it("returns nothing for blank stderr", () => {
125+
assert.isUndefined(stderrExcerpt("\n \t\r\n\u001b[0m\n"));
126+
});
127+
128+
it("keeps only the newest stderr", () => {
129+
const tail = appendStderrTail("a".repeat(8_000), `${"b".repeat(400)}\nError: last`);
130+
131+
assert.equal(tail.length, 8_192);
132+
assert.isTrue(tail.endsWith("Error: last"));
133+
assert.equal(stderrExcerpt(tail), "Error: last");
134+
});
34135
});

‎packages/effect-codex-app-server/src/_internal/stdio.ts‎

Lines changed: 70 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import * as Cause from "effect/Cause";
2+
import * as Deferred from "effect/Deferred";
23
import * as Effect from "effect/Effect";
34
import * as Queue from "effect/Queue";
5+
import * as Ref from "effect/Ref";
46
import * as Sink from "effect/Sink";
57
import * as Stdio from "effect/Stdio";
68
import * as Stream from "effect/Stream";
@@ -44,20 +46,82 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
4446
};
4547
});
4648

49+
const STDERR_TAIL_MAX_CHARS = 8_192;
50+
const STDERR_EXCERPT_MAX_CHARS = 512;
51+
// eslint-disable-next-line no-control-regex -- ANSI escape sequences start with ESC.
52+
const TERMINAL_CONTROL_PATTERN = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
53+
// `Error: …`, `TypeError: …`, `Error [ERR_MODULE_NOT_FOUND]: …`, `error: …`
54+
const ERROR_LINE_PATTERN = /^(?:[A-Za-z]*Error|error|fatal)(?: ?\[[^\]]+\])?:\s*\S/;
55+
56+
export const appendStderrTail = (current: string, chunk: string): string => {
57+
const next = `${current}${chunk}`;
58+
return next.length <= STDERR_TAIL_MAX_CHARS ? next : next.slice(-STDERR_TAIL_MAX_CHARS);
59+
};
60+
61+
/**
62+
* The stderr line that names the failure: the last error-labelled line, else the last line.
63+
* A Node launcher prints its thrown error between a source excerpt and the stack frames.
64+
*/
65+
export const stderrExcerpt = (tail: string): string | undefined => {
66+
const lines = tail
67+
.replace(TERMINAL_CONTROL_PATTERN, "")
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 drained = yield* Deferred.make<void>();
85+
yield* stderr.pipe(
86+
Stream.decodeText(),
87+
Stream.runForEach((chunk) => Ref.update(tail, (current) => appendStderrTail(current, chunk))),
88+
Effect.ignore,
89+
Effect.ensuring(Deferred.succeed(drained, undefined)),
90+
Effect.forkScoped,
91+
);
92+
// The exit status can arrive before the last stderr chunk has been read.
93+
return Deferred.await(drained).pipe(
94+
Effect.timeout("250 millis"),
95+
Effect.ignore,
96+
Effect.andThen(Ref.get(tail)),
97+
);
98+
});
99+
47100
type ChildProcessTerminationHandle = Pick<
48101
ChildProcessSpawner.ChildProcessHandle,
49102
"exitCode" | "pid"
50103
>;
51104

52105
export const makeTerminationError = (
53106
handle: ChildProcessTerminationHandle,
107+
stderrTail: Effect.Effect<string>,
54108
): Effect.Effect<CodexError.CodexAppServerError> =>
55-
Effect.match(handle.exitCode, {
109+
Effect.matchEffect(handle.exitCode, {
56110
onFailure: (cause) =>
57-
new CodexError.CodexAppServerTransportError({
58-
operation: "read-process-exit-status",
59-
pid: handle.pid,
60-
cause,
111+
Effect.succeed(
112+
new CodexError.CodexAppServerTransportError({
113+
operation: "read-process-exit-status",
114+
pid: handle.pid,
115+
cause,
116+
}),
117+
),
118+
onSuccess: (code) =>
119+
Effect.map(stderrTail, (tail) => {
120+
const stderr = stderrExcerpt(tail);
121+
return new CodexError.CodexAppServerProcessExitedError({
122+
code,
123+
pid: handle.pid,
124+
...(stderr ? { stderr } : {}),
125+
});
61126
}),
62-
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),
63127
});

‎packages/effect-codex-app-server/src/client.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
1010
import { assert, it } from "@effect/vitest";
1111

1212
import * as CodexClient from "./client.ts";
13+
import * as CodexError from "./errors.ts";
1314

1415
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
1516
path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),
@@ -155,4 +156,44 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
155156
assert.equal(initialized.userAgent, "mock-codex-app-server");
156157
}),
157158
);
159+
160+
it.effect("reports the stderr error when the process exits before initialize", () =>
161+
Effect.gen(function* () {
162+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
163+
const handle = yield* spawner.spawn(
164+
ChildProcess.make(process.execPath, [
165+
"-e",
166+
'throw new Error("Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest")',
167+
]),
168+
);
169+
const scope = yield* Scope.make();
170+
const context = yield* Layer.buildWithScope(CodexClient.layerChildProcess(handle), scope);
171+
172+
const error = yield* Effect.gen(function* () {
173+
const client = yield* CodexClient.CodexAppServerClient;
174+
return yield* client.request("initialize", {
175+
clientInfo: {
176+
name: "effect-codex-app-server-test",
177+
title: "Effect Codex App Server Test",
178+
version: "0.0.0",
179+
},
180+
capabilities: {
181+
experimentalApi: true,
182+
optOutNotificationMethods: null,
183+
},
184+
});
185+
}).pipe(
186+
Effect.flip,
187+
Effect.timeout("5 seconds"),
188+
Effect.provide(context),
189+
Effect.ensuring(Scope.close(scope, Exit.void)),
190+
);
191+
192+
assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError);
193+
assert.equal(
194+
error.message,
195+
"Codex App Server process exited with code 1: Error: Missing optional dependency @openai/codex-darwin-arm64. Reinstall Codex: npm install -g @openai/codex@latest",
196+
);
197+
}),
198+
);
158199
});

‎packages/effect-codex-app-server/src/client.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import * as Layer from "effect/Layer";
44
import * as Schema from "effect/Schema";
55
import * as Scope from "effect/Scope";
66
import * as Stdio from "effect/Stdio";
7-
import * as Stream from "effect/Stream";
87
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
98

109
import * as CodexRpc from "./_generated/meta.gen.ts";
@@ -17,7 +16,7 @@ import {
1716
encodeOptionalPayload,
1817
runHandler,
1918
} from "./_internal/shared.ts";
20-
import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
19+
import { makeChildStdio, makeStderrTail, makeTerminationError } from "./_internal/stdio.ts";
2120

2221
export interface CodexAppServerClientOptions {
2322
readonly logIncoming?: boolean;
@@ -270,6 +269,6 @@ export const layerChildProcess = (
270269
const makeChildProcessClient = Effect.fn(
271270
"effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
272271
)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
273-
yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
274-
return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
272+
const stderrTail = yield* makeStderrTail(handle.stderr);
273+
return yield* make(makeChildStdio(handle), options, makeTerminationError(handle, stderrTail));
275274
});

‎packages/effect-codex-app-server/src/errors.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,13 +148,16 @@ export class CodexAppServerProcessExitedError extends Schema.TaggedError<CodexAp
148148
{
149149
code: Schema.optional(Schema.Number),
150150
pid: Schema.optionalKey(Schema.Int),
151+
stderr: Schema.optionalKey(Schema.String),
151152
cause: Schema.optional(Schema.Defect()),
152153
},
153154
) {
154155
override get message() {
155-
return this.code === undefined
156-
? "Codex App Server process exited"
157-
: `Codex App Server process exited with code ${this.code}`;
156+
const base =
157+
this.code === undefined
158+
? "Codex App Server process exited"
159+
: `Codex App Server process exited with code ${this.code}`;
160+
return this.stderr ? `${base}: ${this.stderr}` : base;
158161
}
159162
}
160163

0 commit comments

Comments
 (0)