From d0acdad70952e8edbe0a2e080cd936a5335f578d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 20 Nov 2026 11:20:48 +0100 Subject: [PATCH] fix(agents): honor ACP Stop and replay boundaries Identify updates received while cancel is in flight so buffered output cannot reopen the stopped turn. Return to live processing at readiness for sessions with autonomous activity. --- .../src/server/acp-internal/connection.ts | 27 ++++++++-- packages/plugin/src/server/acp.test.ts | 52 +++++++++++++++---- 2 files changed, 64 insertions(+), 15 deletions(-) diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index 5b270ecc42..a47cff59b7 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -350,6 +350,7 @@ async function openSession( capabilities, mutationLane: Promise.resolve(), }); + runtime.startLiveUpdates(); state.emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId }); } catch (error) { await runtime.close(); @@ -417,7 +418,7 @@ class AcpRuntime { >(); /** * Replay updates count as history until the session reports ready. - * Once ready, suppress late replay rows until the first prompt. + * Adapters without autonomous activity can suppress late replay until their first prompt. */ private replayWindow: "replay" | "skip" | null = null; private lastLoadUpdateAt = 0; @@ -427,6 +428,7 @@ class AcpRuntime { private stagedTransformerConfig: ProviderConfigState | null = null; private readonly closeConnector: () => Promise; private notificationLane: Promise = Promise.resolve(); + private interruptWrite: { sent: boolean } | null = null; private autoAccept = false; private readonly outOfTurnActivity: { settleDelayMs: number; quietLimitMs: number } | null; private readonly backgroundToolCalls = new Set(); @@ -520,8 +522,12 @@ class AcpRuntime { : null; const client: Client = { requestPermission: (request) => this.requestPermission(request), - sessionUpdate: (notification) => - this.enqueueNotification(() => this.sessionUpdate(notification)), + sessionUpdate: (notification) => { + const interrupt = this.interruptWrite; + return this.enqueueNotification(() => + this.sessionUpdate(notification, interrupt?.sent === true), + ); + }, }; this.connection = new ClientSideConnection( () => client, @@ -618,6 +624,10 @@ class AcpRuntime { return sessionCapabilities; } + startLiveUpdates(): void { + if (this.outOfTurnActivity) this.replayWindow = null; + } + async discover(cwd?: string): Promise { if (cwd === undefined && this.options.options.acpOptions?.workspaceOnlyCatalog) { return { models: [], modes: [] }; @@ -760,8 +770,11 @@ class AcpRuntime { autonomous.cancelling = true; this.cancelAutonomousSettle(); } + const write = { sent: false }; + if (this.outOfTurnActivity) this.interruptWrite = write; try { await this.call(this.connection.cancel({ sessionId: this.nativeSessionId })); + write.sent = true; } catch (error) { if (active) active.cancelling = false; if (autonomous && this.autonomousTurn === autonomous) { @@ -769,6 +782,8 @@ class AcpRuntime { this.syncAutonomousTimer(); } throw error; + } finally { + this.interruptWrite = null; } // An agent may wait for its outstanding permission replies before ending the prompt. if (active) this.finishTurnPermissions(active.turnId); @@ -1120,10 +1135,12 @@ class AcpRuntime { private async requestPermission( request: RequestPermissionRequest, ): Promise { + const interrupt = this.interruptWrite; await this.notificationLane; if ( this.closing || this.processFailed || + interrupt?.sent || this.toolCalls.get(request.toolCall.toolCallId)?.canceled || this.activePrompt?.cancelling || this.autonomousTurn?.cancelling @@ -1175,10 +1192,10 @@ class AcpRuntime { }); } - private sessionUpdate(notification: SessionNotification): void { + private sessionUpdate(notification: SessionNotification, interrupted: boolean): void { if (notification.sessionId !== this.nativeSessionId || this.processFailed) return; if (this.replayWindow) this.lastLoadUpdateAt = performance.now(); - if (this.replayWindow === "skip") { + if (this.replayWindow === "skip" || interrupted) { const update = notification.update; if ( update.sessionUpdate === "available_commands_update" || diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index 690c87b171..d460611505 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -229,9 +229,14 @@ lines.on("line", (line) => { });`; describe("runAcpProvider", () => { - it.each(["replay", "skip"] as const)( - "handles trailing load updates with %s history", - async (history) => { + it.each([ + ["replay", false], + ["skip", false], + ["replay", true], + ["skip", true], + ] as const)( + "handles trailing load updates with %s history and out-of-turn activity %s", + async (history, outOfTurnActivity) => { const sessionId = "connector-session"; const notifyUpdate = (runtime: ConnectorInstance, update: unknown) => runtime.notify("session/update", { sessionId, update }); @@ -265,6 +270,7 @@ describe("runAcpProvider", () => { waitForInitialCommands: true, initialCommandsTimeoutMs: 10_000, loadReplayQuietPeriodMs: 200, + outOfTurnActivity, }, }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); const events: ProviderEvent[] = []; @@ -276,9 +282,10 @@ describe("runAcpProvider", () => { persistence: { version: 1, data: { sessionId } }, }); await waitForEvent(events, (event) => event.type === "session.ready"); + const postReadyText = "Update after readiness"; notifyUpdate(instances[1], { sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "stale history outside the replay window" }, + content: { type: "text", text: postReadyText }, }); notifyUpdate(instances[1], { sessionUpdate: "available_commands_update", @@ -291,15 +298,32 @@ describe("runAcpProvider", () => { const items = events .filter((event) => event.type === "timeline.item") .map((event) => event.item); - expect(items).toEqual( - history === "skip" - ? [] - : [ + const replayedItems = + history === "replay" + ? [ expect.objectContaining({ type: "user_message", text: "previous question" }), expect.objectContaining({ type: "assistant_message", text: "previous answer" }), - ], + ] + : []; + expect(items).toEqual([ + ...replayedItems, + ...(outOfTurnActivity + ? [expect.objectContaining({ type: "assistant_message", text: postReadyText })] + : []), + ]); + expect(events.filter((event) => event.type === "session.turn")).toEqual( + outOfTurnActivity + ? [ + { + type: "session.turn", + sessionId: "session-1", + turnId: "acp:autonomous:1", + state: "started", + acceptsFollowUp: true, + }, + ] + : [], ); - expect(events.some((event) => event.type === "session.turn")).toBe(false); } finally { await connection.close(); } @@ -2796,6 +2820,14 @@ describe("ACP out-of-turn background activity", () => { it("cancels an active out-of-turn wakeup and clears background work on interrupt", async () => { const { connector, instances } = connectorHarness({ + async afterMessage(instance, message) { + if (!("method" in message) || message.method !== "session/cancel") return; + instance.notify("session/update", { + sessionId: "connector-session", + update: textChunk("Reply chunk during Stop"), + }); + await nextTurn(); + }, promptUpdates: (text) => text === "Start" ? [