@devries-cameron20 / t3code Mirror · read-only / commits / 252b2c77b3
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 21, 12:15 UTC

fix(codex): crashed handlers and transport workers no longer hang silently (#31192)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Dmitry Farafonov committed Nov 15, 2026 at 03:30 UTC 252b2c77b373b45b00246570f6a48cffd6c6bd34
4 files changed +225 -3
packages/effect-codex-app-server/src/client.test.ts
+59
@@ -1,5 +1,6 @@
1 import * as Deferred from "effect/Deferred";
2 import * as Exit from "effect/Exit";
3 +import * as Fiber from "effect/Fiber";
4 import * as Layer from "effect/Layer";
5 import * as Logger from "effect/Logger";
6 import * as Path from "effect/Path";
@@ -209,6 +210,64 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
210 assert.notInclude(JSON.stringify(warnings), secret);
211 }),
212 );
213 +
214 + it.effect("a dying notification handler leaves no request waiting on a live app-server", () =>
215 + Effect.gen(function* () {
216 + const handle = yield* makeHandle();
217 + const client = yield* Layer.build(CodexClient.layerChildProcess(handle)).pipe(
218 + Effect.flatMap((context) =>
219 + Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context)),
220 + ),
221 + );
222 + // A Codex error type must still surface as a transport failure, not as Codex's answer.
223 + const handlerFailure = CodexError.CodexAppServerRequestError.internalError("Injected");
224 + yield* client.handleServerNotification("error", () =>
225 + Effect.fail(handlerFailure).pipe(Effect.orDie),
226 + );
227 + const termination = yield* client.awaitTermination.pipe(Effect.flip, Effect.forkScoped);
228 +
229 + // The peer answers right after this notification and stays alive, so only the reader's
230 + // own termination can settle the request.
231 + const failure = yield* client.raw
232 + .request("mock/notifyThenRespond", {
233 + notification: {
234 + method: "error",
235 + params: {
236 + error: {
237 + message: "Fatal error: application network permission was revoked",
238 + codexErrorInfo: "other",
239 + additionalDetails: null,
240 + },
241 + willRetry: false,
242 + threadId: "thread-1",
243 + turnId: "turn-1",
244 + },
245 + },
246 + })
247 + .pipe(
248 + Effect.match({
249 + onFailure: (error) => error,
250 + onSuccess: () => assert.fail("Expected the dead reader to fail the request"),
251 + }),
252 + );
253 +
254 + assert.instanceOf(failure, CodexError.CodexAppServerTransportError);
255 + assert.equal(failure.operation, "read-input-stream");
256 + assert.strictEqual(failure.cause, handlerFailure);
257 + assert.strictEqual(yield* Fiber.join(termination), failure);
258 + assert.strictEqual(
259 + yield* client.raw.request("thread/read", {}).pipe(
260 + Effect.match({
261 + onFailure: (error) => error,
262 + onSuccess: () => assert.fail("Expected the retired transport to reject requests"),
263 + }),
264 + ),
265 + failure,
266 + );
267 + // Retiring the transport closes the app-server's stdin, so it does not live on unread.
268 + assert.equal(yield* handle.exitCode, 0);
269 + }),
270 + );
271 });
272
273 it.live("reports the stderr error when the process exits before initialize", () =>
packages/effect-codex-app-server/src/protocol.test.ts
+123
@@ -1,8 +1,10 @@
1 import * as Deferred from "effect/Deferred";
2 import * as Effect from "effect/Effect";
3 import * as Fiber from "effect/Fiber";
4 +import * as Logger from "effect/Logger";
5 import * as PlatformError from "effect/PlatformError";
6 import * as Queue from "effect/Queue";
7 +import * as References from "effect/References";
8 import * as Schema from "effect/Schema";
9 import * as Sink from "effect/Sink";
10 import * as Stdio from "effect/Stdio";
@@ -510,6 +512,55 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
512 }),
513 );
514
515 + it.effect.each([
516 + { outcome: "dies", method: "item/tool/requestUserInput", logged: "item/tool/requestUserInput" },
517 + { outcome: "throws", method: "codex-handler-secret-sentinel", logged: "unknown" },
518 + ] as const)(
519 + "answers an incoming request whose handler $outcome, keeping its text out of logs",
520 + ({ outcome, method, logged: loggedMethod }) =>
521 + Effect.gen(function* () {
522 + const secret = "codex-handler-secret-sentinel";
523 + const defect = Object.assign(new Error(secret), { name: secret });
524 + const { stdio, input, output } = yield* makeInMemoryStdio();
525 + const logged: Array<string> = [];
526 + yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
527 + stdio,
528 + onRequest: () => {
529 + if (outcome === "throws") throw defect;
530 + return Effect.die(defect);
531 + },
532 + }).pipe(
533 + Effect.provide(
534 + Logger.layer([
535 + Logger.make(({ logLevel, message, fiber }) => {
536 + if (logLevel === "Error") {
537 + logged.push(
538 + String([message].flat()),
539 + JSON.stringify(fiber.getRef(References.CurrentLogAnnotations)),
540 + );
541 + }
542 + }),
543 + ]),
544 + ),
545 + );
546 +
547 + const request = encodeUnknownJsonString({ id: 1, method, params: {} });
548 + yield* Queue.offer(
549 + input,
550 + encoder.encode(`${request}
551 +`),
552 + );
553 +
554 + assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
555 + id: 1,
556 + error: { code: -32603, message: "Internal error" },
557 + });
558 + assert.lengthOf(logged, 2);
559 + assert.notInclude(logged.join(), secret);
560 + assert.include(logged.join(), loggedMethod);
561 + }),
562 + );
563 +
564 it.effect("releases a waiting request handler when Codex resolves its request", () =>
565 Effect.gen(function* () {
566 const { stdio, input, output } = yield* makeInMemoryStdio();
@@ -832,6 +883,78 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
883 }),
884 );
885
886 + it.effect("fails pending requests when the exit status lookup dies", () =>
887 + Effect.gen(function* () {
888 + const { stdio, input, output } = yield* makeInMemoryStdio();
889 + const defect = new Error("Injected exit status defect");
890 + const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
891 + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
892 + stdio,
893 + terminationError: Effect.die(defect),
894 + onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
895 + });
896 + const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
897 + yield* Queue.take(output);
898 +
899 + yield* Queue.end(input);
900 +
901 + const failure = yield* Fiber.join(pending).pipe(
902 + Effect.match({
903 + onFailure: (error) => error,
904 + onSuccess: () => assert.fail("Expected the pending request to fail"),
905 + }),
906 + );
907 + assert.instanceOf(failure, CodexError.CodexAppServerTransportError);
908 + assert.strictEqual(failure.cause, defect);
909 + assert.strictEqual(yield* Deferred.await(terminated), failure);
910 + }),
911 + );
912 +
913 + it.effect("retires the transport after a defect in the writer", () =>
914 + Effect.gen(function* () {
915 + const { stdio: baseStdio } = yield* makeInMemoryStdio();
916 + const defect = new Error("Injected transport defect");
917 + const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
918 + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
919 + stdio: Stdio.make({
920 + ...baseStdio,
921 + stdout: () => Sink.forEach(() => Effect.die(defect)),
922 + }),
923 + onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
924 + });
925 +
926 + const failure = yield* transport.request("thread/read", {}).pipe(
927 + Effect.match({
928 + onFailure: (error) => error,
929 + onSuccess: () => assert.fail("Expected the dead writer to fail the request"),
930 + }),
931 + );
932 + assert.instanceOf(failure, CodexError.CodexAppServerTransportError);
933 + assert.equal(failure.operation, "write-output-stream");
934 + assert.strictEqual(failure.cause, defect);
935 + assert.strictEqual(yield* Deferred.await(terminated), failure);
936 + }),
937 + );
938 +
939 + it.effect("does not report normal scope shutdown as a transport failure", () =>
940 + Effect.gen(function* () {
941 + let terminations = 0;
942 + yield* Effect.gen(function* () {
943 + const { stdio, output } = yield* makeInMemoryStdio();
944 + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
945 + stdio,
946 + onTermination: () =>
947 + Effect.sync(() => {
948 + terminations++;
949 + }),
950 + });
951 + yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
952 + yield* Queue.take(output);
953 + }).pipe(Effect.scoped);
954 + assert.equal(terminations, 0);
955 + }),
956 + );
957 +
958 it.effect("fails pending requests when a write fails while input stays open", () =>
959 Effect.gen(function* () {
960 const { stdio: baseStdio } = yield* makeInMemoryStdio();
packages/effect-codex-app-server/src/protocol.ts
+37 -3
@@ -11,6 +11,7 @@ import * as Schema from "effect/Schema";
11 import * as Stdio from "effect/Stdio";
12 import * as Stream from "effect/Stream";
13
14 +import * as CodexRpc from "./_generated/meta.gen.ts";
15 import * as CodexError from "./errors.ts";
16 import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
17 const isJsonRpcId = Schema.is(JsonRpcId);
@@ -326,7 +327,21 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
327 );
328 }
329
329 - return handler(request).pipe(
330 + return Effect.suspend(() => handler(request)).pipe(
331 + // Adapter handlers end in Effect.orDie; Codex waits for an answer regardless.
332 + Effect.catchDefect(() =>
333 + Effect.logError("Codex request handler failed").pipe(
334 + Effect.annotateLogs({
335 + method:
336 + request.method in CodexRpc.SERVER_REQUEST_PARAMS
337 + ? request.method
338 + : "unknown",
339 + }),
340 + Effect.andThen(
341 + Effect.fail(CodexError.CodexAppServerRequestError.internalError()),
342 + ),
343 + ),
344 + ),
345 Effect.matchEffect({
346 onFailure: (error) =>
347 respondError(
@@ -471,22 +486,41 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
486 duration: EXIT_STATUS_GRACE,
487 orElse: () => Effect.succeed(ended),
488 }),
489 + // A defect here would leave termination marked handled but unfinished.
490 + Effect.catchDefect((cause) =>
491 + Effect.succeed(
492 + new CodexError.CodexAppServerTransportError({
493 + operation: "read-input-stream",
494 + cause,
495 + }),
496 + ),
497 + ),
498 );
499 }),
500 }),
501 ),
502 }),
503 + Effect.catchCause((cause) =>
504 + handleTermination(() =>
505 + Effect.succeed(
506 + new CodexError.CodexAppServerTransportError({
507 + operation: "read-input-stream",
508 + cause: Cause.squash(cause),
509 + }),
510 + ),
511 + ),
512 + ),
513 Effect.forkScoped,
514 );
515
516 yield* Stream.fromQueue(outgoing).pipe(
517 Stream.run(options.stdio.stdout()),
484 - Effect.catch((cause) =>
518 + Effect.catchCause((cause) =>
519 handleTermination(() =>
520 Effect.succeed(
521 new CodexError.CodexAppServerTransportError({
522 operation: "write-output-stream",
489 - cause,
523 + cause: Cause.squash(cause),
524 }),
525 ),
526 ),
packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts
+6
@@ -104,6 +104,12 @@ const handleMethod = (message: Record<string, unknown>) => {
104 });
105 return;
106 }
107 + case "mock/notifyThenRespond": {
108 + const params = message.params as { readonly notification: unknown };
109 + writeMessage(params.notification);
110 + respond(message.id as number | string, { answered: true });
111 + return;
112 + }
113 default: {
114 if (message.id !== undefined) {
115 respondError(message.id as number | string, -32601, `Unhandled request: ${method}`);