From 3286aa69e5315aa31ee2f287efc878f356a09471 Mon Sep 17 00:00:00 2001 From: NY Date: Tue, 17 Nov 2026 22:37:45 +0800 Subject: [PATCH 1/2] fix: dispatch messages received before the peer ends its stream When the input closed the connection, messages already received were dropped before reaching their handlers. Keep dispatching them; a local close() still stops dispatch. Fixes #346 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RaizxxJBbHnYoG9L4g1u5b --- src/core/jsonrpc.test.ts | 109 ++++++++++++++++++++++++++++++++++++++- src/core/jsonrpc.ts | 25 +++++++-- 2 files changed, 129 insertions(+), 5 deletions(-) diff --git a/src/core/jsonrpc.test.ts b/src/core/jsonrpc.test.ts index 98eb963a..de2e6c19 100644 --- a/src/core/jsonrpc.test.ts +++ b/src/core/jsonrpc.test.ts @@ -8,7 +8,11 @@ import { RequestError, isJsonRpcMessage, } from "./jsonrpc.js"; -import type { AnyMessage, RequestResponder } from "./jsonrpc.js"; +import type { + AnyMessage, + IncomingMessage, + RequestResponder, +} from "./jsonrpc.js"; import type { Stream } from "./stream.js"; type ConnectionInternals = { @@ -887,6 +891,109 @@ describe("JSON-RPC connection rules", () => { }); }); +describe("JSON-RPC end of input", () => { + // A handler ahead of the ones that take the messages, like the typed ones + // the ACP connections register, defers their dispatch past the end of input. + const deferring = { + handleMessage: async (message: IncomingMessage) => { + await new Promise((resolve) => setTimeout(resolve, 0)); + return Handled.no(message); + }, + }; + + function receiving() { + const notified = Promise.withResolvers(); + const requested = Promise.withResolvers(); + const notification = vi.fn(() => notified.resolve()); + const builder = Connection.builder() + .withHandler(deferring) + .onReceiveNotification( + "example/last_notification", + (params) => params, + notification, + ) + .onReceiveRequest( + "example/last_request", + (params) => params, + (_params, responder) => { + requested.resolve(responder.signal); + }, + ); + return { builder, notified, requested, notification }; + } + + const lastMessages: AnyMessage[] = [ + { jsonrpc: "2.0", method: "example/last_notification", params: {} }, + { jsonrpc: "2.0", id: 1, method: "example/last_request", params: {} }, + ]; + + it("dispatches messages received before the peer ended its stream", async () => { + const [connectionStream, peerStream] = memoryStreamPair(); + const { builder, notified, requested } = receiving(); + const connection = builder.connect(connectionStream); + const writer = peerStream.writable.getWriter(); + + // The peer sends its last messages and exits, closing its side. + for (const message of lastMessages) await writer.write(message); + await writer.close(); + + await connection.closed; + await notified.promise; + // The request reaches its handler, which can tell the peer is gone. + expect((await requested.promise).aborted).toBe(true); + }); + + it("dispatches messages received before reading failed", async () => { + const { builder, notified, requested } = receiving(); + const remaining = [...lastMessages]; + const connection = builder.connect({ + readable: new ReadableStream({ + // Each message is read before reading fails. + pull(controller) { + const message = remaining.shift(); + if (message) controller.enqueue(message); + else controller.error(new Error("read failed")); + }, + }), + writable: new WritableStream(), + }); + + await connection.closed; + await notified.promise; + expect((await requested.promise).aborted).toBe(true); + }); + + it("stops dispatching when the connection is closed locally", async () => { + const [connectionStream, peerStream] = memoryStreamPair(); + const { builder, notification } = receiving(); + const connection = builder.connect(connectionStream); + const writer = peerStream.writable.getWriter(); + + await writer.write(lastMessages[0]!); + connection.close(); + await connection.closed; + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(notification).not.toHaveBeenCalled(); + writer.releaseLock(); + }); + + it("stops dispatching when closed locally after the peer ended its stream", async () => { + const [connectionStream, peerStream] = memoryStreamPair(); + const { builder, notification } = receiving(); + const connection = builder.connect(connectionStream); + const writer = peerStream.writable.getWriter(); + + await writer.write(lastMessages[0]!); + await writer.close(); + await connection.closed; + connection.close(); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(notification).not.toHaveBeenCalled(); + }); +}); + describe("JSON-RPC malformed peer messages", () => { it("does not print params of invalid or failed messages", async () => { const secret = "SYNTHETIC_PRIVATE_CREDENTIAL"; diff --git a/src/core/jsonrpc.ts b/src/core/jsonrpc.ts index 6e3139cc..4fb209e4 100644 --- a/src/core/jsonrpc.ts +++ b/src/core/jsonrpc.ts @@ -771,6 +771,10 @@ export class Connection { private retryQueue: IncomingMessage[] = []; private context = new ConnectionContext(this); private receiveReader?: ReadableStreamDefaultReader; + // Whether messages already received are still dispatched after the + // connection closed. Only true when the input closed it (the peer ended + // its stream or reading failed): those messages were sent before the end. + private dispatchAfterClose = false; constructor( requestHandler: RequestHandler, @@ -987,9 +991,15 @@ export class Connection { } /** - * Closes the connection and rejects pending requests. + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. */ close(error?: unknown): void { + this.dispatchAfterClose = false; + this.shutdown(error); + } + + private shutdown(error?: unknown): void { if (this.abortController.signal.aborted) { return; } @@ -1071,7 +1081,10 @@ export class Connection { } catch (error) { closeError = error; } finally { - this.close(closeError); + if (!this.abortController.signal.aborted) { + this.dispatchAfterClose = true; + this.shutdown(closeError); + } } } @@ -1132,10 +1145,14 @@ export class Connection { return Promise.resolve(); } + private dispatchStopped(): boolean { + return this.abortController.signal.aborted && !this.dispatchAfterClose; + } + private async processIncomingMessage( message: IncomingMessage, ): Promise { - if (this.abortController.signal.aborted) { + if (this.dispatchStopped()) { return; } @@ -1148,7 +1165,7 @@ export class Connection { ...this.dynamicHandlers.values(), ...this.fallbackHandlers, ]) { - if (this.abortController.signal.aborted) { + if (this.dispatchStopped()) { return; } From 291a50e72ff710f6a34e7fc72353c78dad4c11da Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Tue, 17 Nov 2026 16:13:46 +0100 Subject: [PATCH 2/2] fix: keep dispatching notifications when close() follows end of input close() is a no-op again once the connection is closed, so the SDK's own close() calls after end of input (runUntil, failed writes, onConnect errors) no longer drop the peer's last notifications. Internal failures close the connection without counting as a local close, and in-process app pairs pass a peer's close along as end of input. Requests received before the close are dropped: no response can reach the peer. Errors from notifications dispatched after the close are logged again. --- src/core/jsonrpc.test.ts | 178 +++++++++++++++++++++++++++++---------- src/core/jsonrpc.ts | 64 ++++++++++---- src/v1/acp.test.ts | 69 +++++++++++++++ src/v1/acp.ts | 25 ++++-- src/v1/stable/acp.ts | 25 ++++-- src/v2/acp.test.ts | 36 ++++++++ src/v2/acp.ts | 23 +++-- src/v2/stable/acp.ts | 23 +++-- 8 files changed, 354 insertions(+), 89 deletions(-) diff --git a/src/core/jsonrpc.test.ts b/src/core/jsonrpc.test.ts index de2e6c19..7b783b38 100644 --- a/src/core/jsonrpc.test.ts +++ b/src/core/jsonrpc.test.ts @@ -902,9 +902,8 @@ describe("JSON-RPC end of input", () => { }; function receiving() { - const notified = Promise.withResolvers(); - const requested = Promise.withResolvers(); - const notification = vi.fn(() => notified.resolve()); + const notification = vi.fn(); + const request = vi.fn(); const builder = Connection.builder() .withHandler(deferring) .onReceiveNotification( @@ -912,85 +911,174 @@ describe("JSON-RPC end of input", () => { (params) => params, notification, ) - .onReceiveRequest( - "example/last_request", - (params) => params, - (_params, responder) => { - requested.resolve(responder.signal); - }, - ); - return { builder, notified, requested, notification }; + .onReceiveRequest("example/last_request", (params) => params, request); + return { builder, notification, request }; } - const lastMessages: AnyMessage[] = [ - { jsonrpc: "2.0", method: "example/last_notification", params: {} }, - { jsonrpc: "2.0", id: 1, method: "example/last_request", params: {} }, - ]; + const lastNotification: AnyMessage = { + jsonrpc: "2.0", + method: "example/last_notification", + params: {}, + }; + const lastRequest: AnyMessage = { + jsonrpc: "2.0", + id: 1, + method: "example/last_request", + params: {}, + }; - it("dispatches messages received before the peer ended its stream", async () => { - const [connectionStream, peerStream] = memoryStreamPair(); - const { builder, notified, requested } = receiving(); - const connection = builder.connect(connectionStream); + // The peer sends its last messages and exits, closing its side. + async function endInput(peerStream: Stream, messages: AnyMessage[]) { const writer = peerStream.writable.getWriter(); - - // The peer sends its last messages and exits, closing its side. - for (const message of lastMessages) await writer.write(message); + for (const message of messages) await writer.write(message); await writer.close(); + } + + // Past the deferred dispatch of every message received so far. + function dispatchSettled() { + return new Promise((resolve) => setTimeout(resolve, 10)); + } + + it("dispatches notifications received before the peer ended its stream", async () => { + const [connectionStream, peerStream] = memoryStreamPair(); + const { builder, notification } = receiving(); + const connection = builder.connect(connectionStream); + await endInput(peerStream, [lastNotification]); await connection.closed; - await notified.promise; - // The request reaches its handler, which can tell the peer is gone. - expect((await requested.promise).aborted).toBe(true); + + await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce()); }); - it("dispatches messages received before reading failed", async () => { - const { builder, notified, requested } = receiving(); - const remaining = [...lastMessages]; + it("dispatches notifications received before reading failed", async () => { + const { builder, notification } = receiving(); + let sent = false; const connection = builder.connect({ readable: new ReadableStream({ - // Each message is read before reading fails. + // The notification is read before reading fails. pull(controller) { - const message = remaining.shift(); - if (message) controller.enqueue(message); - else controller.error(new Error("read failed")); + if (sent) { + controller.error(new Error("read failed")); + } else { + sent = true; + controller.enqueue(lastNotification); + } }, }), writable: new WritableStream(), }); await connection.closed; - await notified.promise; - expect((await requested.promise).aborted).toBe(true); + + await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce()); }); - it("stops dispatching when the connection is closed locally", async () => { + it("drops requests received before the peer ended its stream", async () => { + const [connectionStream, peerStream] = memoryStreamPair(); + const { builder, notification, request } = receiving(); + const connection = builder.connect(connectionStream); + + // No response can reach the peer, so the request is not handled. + await endInput(peerStream, [lastRequest, lastNotification]); + await connection.closed; + + await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce()); + expect(request).not.toHaveBeenCalled(); + }); + + it("keeps dispatching when closed after the peer ended its stream", async () => { const [connectionStream, peerStream] = memoryStreamPair(); const { builder, notification } = receiving(); const connection = builder.connect(connectionStream); - const writer = peerStream.writable.getWriter(); - await writer.write(lastMessages[0]!); + await endInput(peerStream, [lastNotification]); + await connection.closed; connection.close(); + + await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce()); + }); + + it("keeps dispatching when connectWith ends after the peer ended its stream", async () => { + const [connectionStream, peerStream] = memoryStreamPair(); + const { builder, notification } = receiving(); + const result = builder.connectWith( + connectionStream, + () => new Promise(() => {}), + ); + + await endInput(peerStream, [lastNotification]); + await expect(result).rejects.toThrow("ACP connection closed"); + + await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce()); + }); + + it("keeps dispatching when a pending write fails after the peer ended its stream", async () => { + const { builder, notification } = receiving(); + const write = Promise.withResolvers(); + let input!: ReadableStreamDefaultController; + const connection = builder.connect({ + readable: new ReadableStream({ + start(controller) { + input = controller; + }, + }), + writable: new WritableStream({ write: () => write.promise }), + }); + + const sent = connection.sendNotification("example/outgoing", {}); + input.enqueue(lastNotification); + input.close(); await connection.closed; - await new Promise((resolve) => setTimeout(resolve, 10)); + write.reject(new Error("write failed")); + await expect(sent).rejects.toThrow("write failed"); - expect(notification).not.toHaveBeenCalled(); - writer.releaseLock(); + await vi.waitFor(() => expect(notification).toHaveBeenCalledOnce()); }); - it("stops dispatching when closed locally after the peer ended its stream", async () => { + it("logs errors of notifications dispatched after the peer ended its stream", async () => { + const consoleError = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + const [connectionStream, peerStream] = memoryStreamPair(); + const connection = Connection.builder() + .withHandler(deferring) + .onReceiveNotification( + "example/last_notification", + (params) => params, + () => { + throw new Error("handler failed"); + }, + ) + .connect(connectionStream); + + try { + await endInput(peerStream, [lastNotification]); + await connection.closed; + + await vi.waitFor(() => + expect(consoleError).toHaveBeenCalledWith( + "Error handling notification", + expect.objectContaining({ method: "example/last_notification" }), + ), + ); + } finally { + consoleError.mockRestore(); + } + }); + + it("stops dispatching when the connection is closed locally", async () => { const [connectionStream, peerStream] = memoryStreamPair(); const { builder, notification } = receiving(); const connection = builder.connect(connectionStream); const writer = peerStream.writable.getWriter(); - await writer.write(lastMessages[0]!); - await writer.close(); - await connection.closed; + await writer.write(lastNotification); connection.close(); - await new Promise((resolve) => setTimeout(resolve, 10)); + await connection.closed; + await dispatchSettled(); expect(notification).not.toHaveBeenCalled(); + writer.releaseLock(); }); }); diff --git a/src/core/jsonrpc.ts b/src/core/jsonrpc.ts index 4fb209e4..6e7ac4fc 100644 --- a/src/core/jsonrpc.ts +++ b/src/core/jsonrpc.ts @@ -723,6 +723,9 @@ export class ConnectionContext { /** * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. */ get signal(): AbortSignal { return this.connection.signal; @@ -730,6 +733,9 @@ export class ConnectionContext { /** * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. */ get closed(): Promise { return this.connection.closed; @@ -771,10 +777,10 @@ export class Connection { private retryQueue: IncomingMessage[] = []; private context = new ConnectionContext(this); private receiveReader?: ReadableStreamDefaultReader; - // Whether messages already received are still dispatched after the - // connection closed. Only true when the input closed it (the peer ended - // its stream or reading failed): those messages were sent before the end. - private dispatchAfterClose = false; + // Whether `close()` closed the connection. Otherwise the peer ended its + // stream, or reading or writing failed, and the notifications received + // before then are still dispatched: the peer sent them before it went away. + private closedLocally = false; constructor( requestHandler: RequestHandler, @@ -864,7 +870,7 @@ export class Connection { if (this.retryQueue.length > 0) { for (const message of this.retryQueue.splice(0)) { void this.processIncomingMessage(message).catch((error) => - this.close(error), + this.shutdown(error), ); } } @@ -875,6 +881,9 @@ export class Connection { /** * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. */ get signal(): AbortSignal { return this.abortController.signal; @@ -882,6 +891,9 @@ export class Connection { /** * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. */ get closed(): Promise { return this.closedPromise; @@ -992,10 +1004,24 @@ export class Connection { /** * Closes the connection and rejects pending requests. Messages received but - * not yet dispatched are dropped. + * not yet dispatched are dropped. Does nothing once the connection is closed. */ close(error?: unknown): void { - this.dispatchAfterClose = false; + if (this.abortController.signal.aborted) { + return; + } + + this.closedLocally = true; + this.shutdown(error); + } + + /** + * Closes the connection because its peer closed, as when the peer ends its + * stream: notifications already received are still dispatched. + * + * @internal + */ + closeFromPeer(error?: unknown): void { this.shutdown(error); } @@ -1081,10 +1107,7 @@ export class Connection { } catch (error) { closeError = error; } finally { - if (!this.abortController.signal.aborted) { - this.dispatchAfterClose = true; - this.shutdown(closeError); - } + this.shutdown(closeError); } } @@ -1134,7 +1157,7 @@ export class Connection { this.handleProtocolNotification(message); } return this.processIncomingMessage(this.toIncomingMessage(message)).catch( - (error) => this.close(error), + (error) => this.shutdown(error), ); } else if ("id" in message) { this.handleResponse(message); @@ -1145,14 +1168,19 @@ export class Connection { return Promise.resolve(); } - private dispatchStopped(): boolean { - return this.abortController.signal.aborted && !this.dispatchAfterClose; + // Once the connection is closed, a request can no longer be answered, so + // only notifications are still dispatched, unless `close()` closed it. + private dispatchStopped(message: IncomingMessage): boolean { + return ( + this.abortController.signal.aborted && + (this.closedLocally || message.kind === "request") + ); } private async processIncomingMessage( message: IncomingMessage, ): Promise { - if (this.dispatchStopped()) { + if (this.dispatchStopped(message)) { return; } @@ -1165,7 +1193,7 @@ export class Connection { ...this.dynamicHandlers.values(), ...this.fallbackHandlers, ]) { - if (this.dispatchStopped()) { + if (this.dispatchStopped(current)) { return; } @@ -1188,7 +1216,7 @@ export class Connection { ); } } catch (error) { - if (this.abortController.signal.aborted) { + if (this.dispatchStopped(current)) { return; } @@ -1321,7 +1349,7 @@ export class Connection { } }) .catch((error) => { - this.close(error); + this.shutdown(error); throw error; }); return this.writeQueue; diff --git a/src/v1/acp.test.ts b/src/v1/acp.test.ts index 03b4ae8f..cfa56c89 100644 --- a/src/v1/acp.test.ts +++ b/src/v1/acp.test.ts @@ -1049,6 +1049,75 @@ describe("Connection", () => { }); }); + describe("when the agent ends the connection", () => { + const lastUpdate: SessionNotification = { + sessionId: "last-session", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "goodbye" }, + }, + }; + + // Handlers ahead of the one for `session/update` defer its dispatch past + // the end of the connection. + function receivingClient(updates: string[]) { + let app = createClient({ name: "last-update-client" }); + for (let index = 0; index < 20; index++) { + app = app.onNotification( + `_vendor/other_${index}`, + (params) => params, + () => {}, + ); + } + return app.onNotification(CLIENT_METHODS.session_update, (c) => { + updates.push(c.params.sessionId); + }); + } + + it("delivers its last notifications over a stream", async () => { + const updates: string[] = []; + const result = receivingClient(updates).connectWith( + ndJsonStream(clientToAgent.writable, agentToClient.readable), + () => new Promise(() => {}), + ); + + // The agent sends its last update and exits, ending its output. + const writer = agentToClient.writable.getWriter(); + const message = { + jsonrpc: "2.0", + method: CLIENT_METHODS.session_update, + params: lastUpdate, + }; + await writer.write( + new TextEncoder().encode(`${JSON.stringify(message)}\n`), + ); + await writer.close(); + + await expect(result).rejects.toThrow("ACP connection closed"); + await vi.waitFor(() => expect(updates).toEqual(["last-session"])); + }); + + it("delivers its last notifications in process", async () => { + const updates: string[] = []; + const appAgent = createAgent({ name: "last-update-agent" }).onConnect( + async (connection) => { + await connection.client.notify( + CLIENT_METHODS.session_update, + lastUpdate, + ); + connection.close(); + }, + ); + const result = receivingClient(updates).connectWith( + appAgent, + () => new Promise(() => {}), + ); + + await expect(result).rejects.toThrow("ACP connection closed"); + await vi.waitFor(() => expect(updates).toEqual(["last-session"])); + }); + }); + it("normalizes app built-in empty-object handler responses before sending", async () => { const appAgent = createAgent({ name: "empty-agent-responses" }) .onRequest(AGENT_METHODS.session_load, () => {}) diff --git a/src/v1/acp.ts b/src/v1/acp.ts index 3e66f30f..71a02be9 100644 --- a/src/v1/acp.ts +++ b/src/v1/acp.ts @@ -270,16 +270,23 @@ const startActiveSession = Symbol("startActiveSession"); export interface AcpConnection { /** * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. */ readonly signal: AbortSignal; /** * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. */ readonly closed: Promise; /** - * Closes the connection and rejects pending requests. + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. */ close(error?: unknown): void; } @@ -2203,8 +2210,12 @@ export class AgentApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = clientConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => peerConnection.close()); - void peerRawConnection.closed.then(() => state.connection.close()); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); try { target[runClientConnectHandlers](peerConnection); this[runAgentConnectHandlers](state.connection); @@ -2488,8 +2499,12 @@ export class ClientApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = agentConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => peerConnection.close()); - void peerRawConnection.closed.then(() => state.connection.close()); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); try { target[runAgentConnectHandlers](peerConnection); this[runClientConnectHandlers](state.connection); diff --git a/src/v1/stable/acp.ts b/src/v1/stable/acp.ts index a3ea160f..266dab60 100644 --- a/src/v1/stable/acp.ts +++ b/src/v1/stable/acp.ts @@ -234,14 +234,21 @@ const startActiveSession = Symbol("startActiveSession"); export interface AcpConnection { /** * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. */ readonly signal: AbortSignal; /** * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. */ readonly closed: Promise; /** - * Closes the connection and rejects pending requests. + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. */ close(error?: unknown): void; } @@ -1878,8 +1885,12 @@ export class AgentApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = clientConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => peerConnection.close()); - void peerRawConnection.closed.then(() => state.connection.close()); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); try { target[runClientConnectHandlers](peerConnection); this[runAgentConnectHandlers](state.connection); @@ -2144,8 +2155,12 @@ export class ClientApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = agentConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - void state.rawConnection.closed.then(() => peerConnection.close()); - void peerRawConnection.closed.then(() => state.connection.close()); + void state.rawConnection.closed.then(() => + peerRawConnection.closeFromPeer(), + ); + void peerRawConnection.closed.then(() => + state.rawConnection.closeFromPeer(), + ); try { target[runAgentConnectHandlers](peerConnection); this[runClientConnectHandlers](state.connection); diff --git a/src/v2/acp.test.ts b/src/v2/acp.test.ts index 1b5b5627..67c178ab 100644 --- a/src/v2/acp.test.ts +++ b/src/v2/acp.test.ts @@ -1597,6 +1597,42 @@ describe("experimental v2 app API", () => { } }); + it("delivers an in-process agent's last notifications after it closes", async () => { + const received: string[] = []; + const agentApp = testAgent().onConnect(async (connection) => { + await connection.initialized; + await connection.client.notify("_vendor/last_words", { text: "goodbye" }); + connection.close(); + }); + // Handlers ahead of the receiving one defer its dispatch past the close. + let clientApp = client(); + for (let index = 0; index < 20; index++) { + clientApp = clientApp.onNotification( + `_vendor/other_${index}`, + (params) => params, + () => {}, + ); + } + clientApp = clientApp.onNotification( + "_vendor/last_words", + (params) => params as { text: string }, + ({ params }) => { + received.push(params.text); + }, + ); + + await expect( + clientApp.connectWith(agentApp, async (agentContext) => { + await agentContext.request(methods.agent.initialize, { + protocolVersion: PROTOCOL_VERSION, + info: clientInfo, + }); + return new Promise(() => {}); + }), + ).rejects.toThrow("ACP connection closed"); + await vi.waitFor(() => expect(received).toEqual(["goodbye"])); + }); + it("rejects queued peer calls when an in-flight initialize connection closes", async () => { const initializeGate = Promise.withResolvers(); const initializeStarted = Promise.withResolvers(); diff --git a/src/v2/acp.ts b/src/v2/acp.ts index 7ad580fb..62130dd3 100644 --- a/src/v2/acp.ts +++ b/src/v2/acp.ts @@ -918,16 +918,23 @@ export interface AcpConnection { /** * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. */ readonly signal: AbortSignal; /** * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. */ readonly closed: Promise; /** - * Closes the connection and rejects pending requests. + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. */ close(error?: unknown): void; } @@ -3084,12 +3091,12 @@ type ClientConnectionState = { connection: ClientConnection; }; -function bridgeConnectionClose(source: Connection, peer: AcpConnection): void { +function bridgeConnectionClose(source: Connection, peer: Connection): void { void source.closed.then(async () => { if (initializationState(source.getContext()).status === "initialized") { - await peer.initialized.catch(() => {}); + await initializationState(peer.getContext()).initialized.catch(() => {}); } - peer.close(source.signal.reason); + peer.closeFromPeer(source.signal.reason); }); } @@ -3410,8 +3417,8 @@ export class AgentApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = clientConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerConnection); - bridgeConnectionClose(peerRawConnection, state.connection); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); try { target[runClientConnectHandlers](peerConnection); this[runAgentConnectHandlers](state.connection); @@ -3721,8 +3728,8 @@ export class ClientApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = agentConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerConnection); - bridgeConnectionClose(peerRawConnection, state.connection); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); try { target[runAgentConnectHandlers](peerConnection); this[runClientConnectHandlers](state.connection); diff --git a/src/v2/stable/acp.ts b/src/v2/stable/acp.ts index 5c8a58e2..4be29fd9 100644 --- a/src/v2/stable/acp.ts +++ b/src/v2/stable/acp.ts @@ -844,14 +844,21 @@ export interface AcpConnection { readonly initialized: Promise; /** * AbortSignal that aborts when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after the signal aborts. */ readonly signal: AbortSignal; /** * Promise that resolves when the connection closes. + * + * Unless `close()` closed the connection, notifications received before it + * closed can still reach their handlers after this resolves. */ readonly closed: Promise; /** - * Closes the connection and rejects pending requests. + * Closes the connection and rejects pending requests. Messages received but + * not yet dispatched are dropped. Does nothing once the connection is closed. */ close(error?: unknown): void; } @@ -2698,12 +2705,12 @@ type ClientConnectionState = { rawConnection: Connection; connection: ClientConnection; }; -function bridgeConnectionClose(source: Connection, peer: AcpConnection): void { +function bridgeConnectionClose(source: Connection, peer: Connection): void { void source.closed.then(async () => { if (initializationState(source.getContext()).status === "initialized") { - await peer.initialized.catch(() => {}); + await initializationState(peer.getContext()).initialized.catch(() => {}); } - peer.close(source.signal.reason); + peer.closeFromPeer(source.signal.reason); }); } /** @@ -3006,8 +3013,8 @@ export class AgentApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = clientConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerConnection); - bridgeConnectionClose(peerRawConnection, state.connection); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); try { target[runClientConnectHandlers](peerConnection); this[runAgentConnectHandlers](state.connection); @@ -3297,8 +3304,8 @@ export class ClientApp { const peerRawConnection = target[appBuilder]().connect(peerStream); const peerConnection = agentConnection(peerRawConnection); const state = this.openStreamConnection(thisStream); - bridgeConnectionClose(state.rawConnection, peerConnection); - bridgeConnectionClose(peerRawConnection, state.connection); + bridgeConnectionClose(state.rawConnection, peerRawConnection); + bridgeConnectionClose(peerRawConnection, state.rawConnection); try { target[runAgentConnectHandlers](peerConnection); this[runClientConnectHandlers](state.connection);