From e43002eaf11eb6b95f7608537848f493084b0bae Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 27 Mar 2026 17:46:44 -0700 Subject: [PATCH] Propagate ACP child exits through protocol termination - Thread child-process exit codes into protocol shutdown - Distinguish stream end, decode failure, and process exit errors - Add protocol coverage for pending requests and late responses --- packages/effect-acp/src/client.ts | 9 + packages/effect-acp/src/errors.ts | 4 +- packages/effect-acp/src/protocol.test.ts | 191 +++++++++++++++++- packages/effect-acp/src/protocol.ts | 138 +++++++++---- .../effect-acp/test/fixtures/acp-mock-peer.ts | 9 + 5 files changed, 306 insertions(+), 45 deletions(-) diff --git a/packages/effect-acp/src/client.ts b/packages/effect-acp/src/client.ts index 72025a5a81..cc6327ba8e 100644 --- a/packages/effect-acp/src/client.ts +++ b/packages/effect-acp/src/client.ts @@ -284,6 +284,15 @@ export const fromChildProcess = Effect.fnUntraced(function* ( const handlers = options.handlers ?? {}; const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ stdio: makeStdioFromChildProcess(handle), + processExit: handle.exitCode.pipe( + Effect.map(Number), + Effect.mapError( + (cause) => + new AcpError.AcpProcessExitedError({ + cause, + }), + ), + ), serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()), ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}), ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}), diff --git a/packages/effect-acp/src/errors.ts b/packages/effect-acp/src/errors.ts index 496fd01b25..9aa4dbfeb1 100644 --- a/packages/effect-acp/src/errors.ts +++ b/packages/effect-acp/src/errors.ts @@ -22,8 +22,8 @@ export class AcpProcessExitedError extends Schema.TaggedErrorClass(); + const input = yield* Queue.unbounded>(); const output = yield* Queue.unbounded(); return { @@ -41,6 +45,48 @@ function makeInMemoryStdio() { }); } +const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) => + path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"), +); + +const makeHandle = (env?: Record) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], { + cwd: path.join(import.meta.dirname, ".."), + shell: process.platform === "win32", + ...(env ? { env: { ...process.env, ...env } } : {}), + }); + return yield* spawner.spawn(command); + }); + +function makeChildStdio(handle: ChildProcessSpawner.ChildProcessHandle) { + return Stdio.make({ + args: Effect.succeed([]), + stdin: handle.stdout, + stdout: () => + Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) => + typeof chunk === "string" ? encoder.encode(chunk) : chunk, + ), + stderr: () => Sink.drain, + }); +} + +function makeProcessExit( + handle: ChildProcessSpawner.ChildProcessHandle, +): Effect.Effect { + return handle.exitCode.pipe( + Effect.map(Number), + Effect.mapError( + (cause) => + new AcpError.AcpProcessExitedError({ + cause, + }), + ), + ); +} + it.layer(NodeServices.layer)("effect-acp protocol", (it) => { it.effect( "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion", @@ -218,4 +264,147 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => { assert.deepEqual(resolved, { ok: true }); }), ); + + it.effect("cleans up interrupted extension requests before a late response arrives", () => + Effect.gen(function* () { + const { stdio, input, output } = yield* makeInMemoryStdio(); + const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ + stdio, + serverRequestMethods: new Set(), + }); + const lateResponse = yield* Deferred.make(); + + yield* transport.clientProtocol + .run((message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid)) + .pipe(Effect.forkScoped); + + const response = yield* transport + .sendRequest("x/test", { hello: "world" }) + .pipe(Effect.forkScoped); + const outbound = yield* Queue.take(output); + assert.deepEqual(decodeJson(outbound), { + jsonrpc: "2.0", + id: 1, + method: "x/test", + params: { + hello: "world", + }, + headers: [], + }); + + yield* Fiber.interrupt(response); + yield* Queue.offer( + input, + encoder.encode( + `${encodeJson({ + jsonrpc: "2.0", + id: 1, + result: { + ok: true, + }, + })}\n`, + ), + ); + + const message = yield* Deferred.await(lateResponse); + assert.deepEqual(message, { + _tag: "Exit", + requestId: "1", + exit: { + _tag: "Success", + value: { + ok: true, + }, + }, + }); + }), + ); + + it.effect("propagates the real child exit code when the input stream ends", () => + Effect.gen(function* () { + const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" }); + const firstMessage = yield* Deferred.make(); + const processExit = yield* Deferred.make(); + const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ + stdio: makeChildStdio(handle), + processExit: makeProcessExit(handle), + serverRequestMethods: new Set(), + onProcessExit: (error) => Deferred.succeed(processExit, error).pipe(Effect.asVoid), + }); + + yield* transport.clientProtocol + .run((message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid)) + .pipe(Effect.forkScoped); + + const message = yield* Deferred.await(firstMessage); + const exitError = yield* Deferred.await(processExit); + assert.instanceOf(exitError, AcpError.AcpProcessExitedError); + assert.equal(exitError.code, 7); + assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError"); + const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as { + readonly _tag: string; + readonly cause: unknown; + }; + assert.equal(defect._tag, "RpcClientDefect"); + assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError); + assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7); + }), + ); + + it.effect("does not emit a second process-exit error after a decode failure", () => + Effect.gen(function* () { + const handle = yield* makeHandle({ + ACP_MOCK_MALFORMED_OUTPUT: "1", + ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23", + }); + const processExitCalls = yield* Ref.make(0); + const firstMessage = yield* Deferred.make(); + const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ + stdio: makeChildStdio(handle), + processExit: makeProcessExit(handle), + serverRequestMethods: new Set(), + onProcessExit: () => Ref.update(processExitCalls, (count) => count + 1), + }); + + yield* transport.clientProtocol + .run((message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid)) + .pipe(Effect.forkScoped); + + const message = yield* Deferred.await(firstMessage); + assert.equal(yield* Ref.get(processExitCalls), 0); + assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError"); + const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as { + readonly _tag: string; + readonly cause: unknown; + }; + assert.equal(defect._tag, "RpcClientDefect"); + assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError); + }), + ); + + it.effect("fails pending extension requests with the propagated exit code", () => + Effect.gen(function* () { + const { stdio, input, output } = yield* makeInMemoryStdio(); + const transport = yield* AcpProtocol.makeAcpPatchedProtocol({ + stdio, + processExit: Effect.succeed(0), + serverRequestMethods: new Set(), + }); + + const response = yield* transport + .sendRequest("x/test", { hello: "world" }) + .pipe(Effect.forkScoped); + yield* Queue.take(output); + yield* Queue.end(input); + + const error = yield* Fiber.join(response).pipe( + Effect.match({ + onFailure: (error) => error, + onSuccess: () => assert.fail("Expected request to fail after process exit"), + }), + ); + assert.instanceOf(error, AcpError.AcpProcessExitedError); + assert.equal(error.code, 0); + }), + ); }); diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.ts index 35b297ef8f..2eefc1807f 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -42,6 +42,7 @@ export type AcpIncomingNotification = export interface AcpPatchedProtocolOptions { readonly stdio: Stdio.Stdio; + readonly processExit?: Effect.Effect; readonly serverRequestMethods: ReadonlySet; readonly logIncoming?: boolean; readonly logOutgoing?: boolean; @@ -94,6 +95,7 @@ export const makeAcpPatchedProtocol = ( const disconnects = yield* Queue.unbounded(); const outgoing = yield* Queue.unbounded>(); const nextRequestId = yield* Ref.make(1n); + const terminationHandled = yield* Ref.make(false); const extPending = yield* Ref.make( new Map>(), ); @@ -152,6 +154,16 @@ export const makeAcpPatchedProtocol = ( return [onFound(deferred), next] as const; }).pipe(Effect.flatten); + const removeExtPending = (requestId: string) => + Ref.update(extPending, (pending) => { + if (!pending.has(requestId)) { + return pending; + } + const next = new Map(pending); + next.delete(requestId); + return next; + }); + const completeExtPendingFailure = (requestId: string, error: AcpError.AcpError) => resolveExtPending(requestId, (deferred) => Deferred.fail(deferred, error)); @@ -178,6 +190,47 @@ export const makeAcpPatchedProtocol = ( Effect.asVoid, ); + const emitClientProtocolError = (error: AcpError.AcpError) => + Queue.offer(clientQueue, { + _tag: "ClientProtocolError", + error: new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: error.message, + cause: error, + }), + }), + }).pipe(Effect.asVoid); + + const handleTermination = ( + classify: () => Effect.Effect< + | { + readonly error: AcpError.AcpError; + readonly processExitError?: AcpError.AcpProcessExitedError | undefined; + } + | undefined + >, + ) => + Ref.modify(terminationHandled, (handled) => { + if (handled) { + return [Effect.void, true] as const; + } + return [ + Effect.gen(function* () { + yield* Queue.offer(disconnects, 0); + const terminated = yield* classify(); + if (!terminated) { + return; + } + yield* failAllExtPending(terminated.error); + yield* emitClientProtocolError(terminated.error); + if (terminated.processExitError && options.onProcessExit) { + yield* options.onProcessExit(terminated.processExitError); + } + }), + true, + ] as const; + }).pipe(Effect.flatten); + const respondWithSuccess = (requestId: string, value: unknown) => offerOutgoing({ _tag: "Exit", @@ -376,43 +429,46 @@ export const makeAcpPatchedProtocol = ( ), ), ), - Effect.catch((error) => { - const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error) - ? error - : new AcpError.AcpTransportError({ - detail: error instanceof Error ? error.message : String(error), - cause: error, - }); - const rpcClientError = new RpcClientError.RpcClientError({ - reason: new RpcClientError.RpcClientDefect({ - message: normalized.message, - cause: normalized, - }), - }); - return Queue.offer(clientQueue, { - _tag: "ClientProtocolError", - error: rpcClientError, - }).pipe(Effect.asVoid); - }), - Effect.ensuring( - Effect.gen(function* () { - const error = new AcpError.AcpProcessExitedError({}); - yield* Queue.offer(disconnects, 0); - yield* failAllExtPending(error); - yield* Queue.offer(clientQueue, { - _tag: "ClientProtocolError", - error: new RpcClientError.RpcClientError({ - reason: new RpcClientError.RpcClientDefect({ - message: error.message, + Effect.matchEffect({ + onFailure: (error) => { + const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error) + ? error + : new AcpError.AcpTransportError({ + detail: error instanceof Error ? error.message : String(error), cause: error, - }), - }), - }); - if (options.onProcessExit) { - yield* options.onProcessExit(error); - } - }), - ), + }); + return handleTermination(() => Effect.succeed({ error: normalized })); + }, + onSuccess: () => + handleTermination(() => + options.processExit + ? options.processExit.pipe( + Effect.match({ + onFailure: (processExitError) => + ({ + error: processExitError, + processExitError, + }) as const, + onSuccess: (code) => { + const processExitError = + code === null + ? new AcpError.AcpProcessExitedError({}) + : new AcpError.AcpProcessExitedError({ code }); + return { + error: processExitError, + processExitError, + } as const; + }, + }), + ) + : Effect.succeed({ + error: new AcpError.AcpTransportError({ + detail: "ACP input stream ended", + cause: new Error("ACP input stream ended"), + }), + }), + ), + }), Effect.forkScoped, ); @@ -473,14 +529,12 @@ export const makeAcpPatchedProtocol = ( headers: [], }).pipe( Effect.catch((error) => - Ref.update(extPending, (pending) => { - const next = new Map(pending); - next.delete(String(requestId)); - return next; - }).pipe(Effect.andThen(Effect.fail(error))), + removeExtPending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))), ), ); - return yield* Deferred.await(deferred); + return yield* Deferred.await(deferred).pipe( + Effect.onInterrupt(() => removeExtPending(String(requestId))), + ); }); return { diff --git a/packages/effect-acp/test/fixtures/acp-mock-peer.ts b/packages/effect-acp/test/fixtures/acp-mock-peer.ts index e55ed0f6ce..12ea2a4b8f 100644 --- a/packages/effect-acp/test/fixtures/acp-mock-peer.ts +++ b/packages/effect-acp/test/fixtures/acp-mock-peer.ts @@ -5,6 +5,15 @@ const rl = createInterface({ crlfDelay: Infinity, }); +if (process.env.ACP_MOCK_MALFORMED_OUTPUT === "1") { + process.stdout.write("{not-json}\n"); + process.exit(Number(process.env.ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE ?? "0")); +} + +if (process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE !== undefined) { + process.exit(Number(process.env.ACP_MOCK_EXIT_IMMEDIATELY_CODE)); +} + let nextRequestId = 1000; const pending = new Map< number | string,