Skip to content

Commit 52adbf4

Browse files
authored
fix(acp): cancel pending prompts when the bridge shuts down (AI-assisted) (#124068)
* fix(acp): cancel pending prompts on shutdown ACP shutdown now aborts accepted Gateway runs and releases bridge session state rather than leaving prompts pending. * fix(acp): preserve injected store ownership Keep caller-provided ACP session stores generic while disposing only the concrete store created by the agent.
1 parent 49e1ea2 commit 52adbf4

5 files changed

Lines changed: 131 additions & 16 deletions

File tree

‎packages/acp-core/src/session.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ export type AcpSessionStore = {
2121
deleteSession: (sessionId: string) => boolean;
2222
};
2323

24+
type InMemoryAcpSessionStore = AcpSessionStore & {
25+
/** Releases every record when the registry's lifecycle owner shuts down. */
26+
dispose: () => void;
27+
};
28+
2429
type AcpSessionStoreOptions = {
2530
maxSessions?: number;
2631
idleTtlMs?: number;
@@ -31,7 +36,9 @@ const DEFAULT_MAX_SESSIONS = 5_000;
3136
const DEFAULT_IDLE_TTL_MS = 24 * 60 * 60 * 1_000;
3237

3338
/** Creates the bounded in-memory ACP session registry used by local ACP runtime clients. */
34-
export function createInMemorySessionStore(options: AcpSessionStoreOptions = {}): AcpSessionStore {
39+
export function createInMemorySessionStore(
40+
options: AcpSessionStoreOptions = {},
41+
): InMemoryAcpSessionStore {
3542
const maxSessions = resolveIntegerOption(options.maxSessions, DEFAULT_MAX_SESSIONS, { min: 1 });
3643
const idleTtlMs = resolveIntegerOption(options.idleTtlMs, DEFAULT_IDLE_TTL_MS, { min: 1_000 });
3744
const now = options.now ?? Date.now;
@@ -188,6 +195,14 @@ export function createInMemorySessionStore(options: AcpSessionStoreOptions = {})
188195

189196
const deleteSession: AcpSessionStore["deleteSession"] = (sessionId) => removeSession(sessionId);
190197

198+
const dispose: InMemoryAcpSessionStore["dispose"] = () => {
199+
for (const session of sessions.values()) {
200+
session.abortController?.abort();
201+
}
202+
sessions.clear();
203+
runIdToSessionId.clear();
204+
};
205+
191206
return {
192207
createSession,
193208
hasSession,
@@ -197,7 +212,6 @@ export function createInMemorySessionStore(options: AcpSessionStoreOptions = {})
197212
clearActiveRun,
198213
cancelActiveRun,
199214
deleteSession,
215+
dispose,
200216
};
201217
}
202-
203-
export const defaultAcpSessionStore = createInMemorySessionStore();

‎src/acp/server.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ export async function serveAcpGateway(opts: AcpServerOptions = {}): Promise<void
203203
// events can both resume asynchronously, and must not reopen the shared DB.
204204
const activeAgent = agent;
205205
agent = null;
206-
activeAgent?.shutdown();
206+
await activeAgent?.shutdown();
207207
const gatewayStop = gateway.stopAndWait().catch((err: unknown) => {
208208
console.warn(`acp: gateway stop failed during shutdown: ${formatErrorMessage(err)}`);
209209
});

‎src/acp/translator.lifecycle.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type {
22
CloseSessionRequest,
33
InitializeRequest,
44
ListSessionsRequest,
5+
NewSessionRequest,
56
PromptRequest,
67
PromptResponse,
78
ResumeSessionRequest,
@@ -77,6 +78,14 @@ function createPromptRequest(sessionId: string): PromptRequest {
7778
} as PromptRequest;
7879
}
7980

81+
function createNewSessionRequest(): NewSessionRequest {
82+
return {
83+
cwd: "/tmp/openclaw",
84+
mcpServers: [],
85+
_meta: {},
86+
} as NewSessionRequest;
87+
}
88+
8089
function createGatewaySessions(rows: GatewaySessionRow[]) {
8190
return {
8291
ts: Date.now(),
@@ -497,6 +506,64 @@ describe("acp translator stable lifecycle handlers", () => {
497506
expect(sessionStore.hasSession("session-1")).toBe(false);
498507
});
499508

509+
it("drains only its own pending work and sessions during shutdown", async () => {
510+
const sentRunIds: string[] = [];
511+
const requestA = vi.fn(async (method: string, params?: Record<string, unknown>) => {
512+
if (method === "chat.send") {
513+
const runId = params?.idempotencyKey;
514+
if (typeof runId === "string") {
515+
sentRunIds.push(runId);
516+
}
517+
return { runId, status: "started" };
518+
}
519+
if (method === "sessions.list") {
520+
return createGatewaySessions([]);
521+
}
522+
return { ok: true };
523+
});
524+
const requestB = vi.fn(async (method: string) => {
525+
if (method === "sessions.list") {
526+
return createGatewaySessions([]);
527+
}
528+
return { ok: true };
529+
});
530+
const agentA = new AcpGatewayAgent(
531+
createAcpConnection(),
532+
createAcpGateway(requestA as GatewayClient["request"]),
533+
);
534+
const agentB = new AcpGatewayAgent(
535+
createAcpConnection(),
536+
createAcpGateway(requestB as GatewayClient["request"]),
537+
);
538+
const sessionA = await agentA.newSession(createNewSessionRequest());
539+
const sessionB = await agentB.newSession(createNewSessionRequest());
540+
const pending = await startPendingPrompt({
541+
agent: agentA,
542+
sentRunIds,
543+
sessionId: sessionA.sessionId,
544+
});
545+
546+
await agentA.shutdown();
547+
548+
await expect(settlePromptQuickly(pending.promptPromise)).resolves.toEqual({
549+
stopReason: "cancelled",
550+
});
551+
const abortCall = requestA.mock.calls.find(([method]) => method === "chat.abort");
552+
expect(abortCall?.[1]).toEqual({
553+
sessionKey: `acp-bridge:${sessionA.sessionId}`,
554+
runId: pending.runId,
555+
});
556+
await expect(
557+
agentA.closeSession(createCloseSessionRequest(sessionA.sessionId)),
558+
).rejects.toThrow(`Session ${sessionA.sessionId} not found`);
559+
await expect(
560+
agentB.closeSession(createCloseSessionRequest(sessionA.sessionId)),
561+
).rejects.toThrow(`Session ${sessionA.sessionId} not found`);
562+
await expect(
563+
agentB.closeSession(createCloseSessionRequest(sessionB.sessionId)),
564+
).resolves.toEqual({});
565+
});
566+
500567
it("rejects close for missing sessions", async () => {
501568
const sessionStore = createInMemorySessionStore();
502569
const agent = new AcpGatewayAgent(createAcpConnection(), createAcpGateway(), {

‎src/acp/translator.prompt-stream.ts‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ import type { AcpTranslatorSessionUpdates } from "./translator.session-updates.j
2626

2727
// Maximum allowed prompt size (2MB) to prevent DoS via memory exhaustion (CWE-400, GHSA-cxpw-2g23-2vgw)
2828
const MAX_PROMPT_BYTES = 2 * 1024 * 1024;
29+
// Shutdown owns only a brief best-effort abort window so EOF and signals cannot
30+
// inherit the Gateway client's normal request timeout before process teardown.
31+
const ACP_SHUTDOWN_ABORT_TIMEOUT_MS = 1_000;
2932

3033
type ChatSendAck = {
3134
runId?: unknown;
@@ -123,8 +126,20 @@ export class AcpTranslatorPromptStream {
123126
);
124127
}
125128

126-
shutdown(): void {
129+
async shutdown(): Promise<void> {
127130
this.disconnects.shutdown();
131+
await Promise.all(
132+
[...this.pendingPrompts.values()].map((pending) =>
133+
this.cancelSessionWork(
134+
{
135+
sessionId: pending.sessionId,
136+
sessionKey: pending.sessionKey,
137+
activeRunId: pending.idempotencyKey,
138+
},
139+
ACP_SHUTDOWN_ABORT_TIMEOUT_MS,
140+
),
141+
),
142+
);
128143
}
129144

130145
handleGatewayReconnect(): void {
@@ -310,11 +325,14 @@ export class AcpTranslatorPromptStream {
310325
await this.cancelSessionWork(session);
311326
}
312327

313-
async cancelSessionWork(session: {
314-
sessionId: string;
315-
sessionKey: string;
316-
activeRunId: string | null;
317-
}): Promise<void> {
328+
async cancelSessionWork(
329+
session: {
330+
sessionId: string;
331+
sessionKey: string;
332+
activeRunId: string | null;
333+
},
334+
abortTimeoutMs?: number,
335+
): Promise<void> {
318336
// Capture runId before cancelActiveRun clears session.activeRunId.
319337
const activeRunId = session.activeRunId;
320338

@@ -324,10 +342,13 @@ export class AcpTranslatorPromptStream {
324342

325343
if (scopedRunId) {
326344
try {
327-
await this.gateway.request("chat.abort", {
345+
const abortParams = {
328346
sessionKey: session.sessionKey,
329347
runId: scopedRunId,
330-
});
348+
};
349+
await (abortTimeoutMs === undefined
350+
? this.gateway.request("chat.abort", abortParams)
351+
: this.gateway.request("chat.abort", abortParams, { timeoutMs: abortTimeoutMs }));
331352
} catch (err) {
332353
this.log(`cancel error: ${String(err)}`);
333354
}

‎src/acp/translator.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import type {
2424
SetSessionModeRequest,
2525
SetSessionModeResponse,
2626
} from "@agentclientprotocol/sdk";
27-
import { defaultAcpSessionStore, type AcpSessionStore } from "@openclaw/acp-core/session";
27+
import { createInMemorySessionStore, type AcpSessionStore } from "@openclaw/acp-core/session";
2828
import type { AcpServerOptions } from "@openclaw/acp-core/types";
2929
import { resolveIntegerOption } from "@openclaw/normalization-core/number-coercion";
3030
import type { EventFrame } from "../../packages/gateway-protocol/src/index.js";
@@ -60,6 +60,7 @@ export class AcpGatewayAgent implements Agent {
6060
private readonly sessionUpdates: AcpTranslatorSessionUpdates;
6161
private readonly promptStream: AcpTranslatorPromptStream;
6262
private readonly sessionLifecycle: AcpTranslatorSessionLifecycle;
63+
private readonly ownedSessionStore: ReturnType<typeof createInMemorySessionStore> | undefined;
6364
private readonly approvalRelays = new Map<string, AcpPendingApprovalRelay>();
6465
private readonly log: (msg: string) => void;
6566

@@ -69,7 +70,15 @@ export class AcpGatewayAgent implements Agent {
6970
opts: AcpGatewayAgentOptions = {},
7071
) {
7172
this.log = opts.verbose ? (msg: string) => process.stderr.write(`[acp] ${msg}\n`) : () => {};
72-
const sessionStore = opts.sessionStore ?? defaultAcpSessionStore;
73+
// Injected stores remain caller-owned; only the agent-created registry follows shutdown.
74+
let sessionStore: AcpSessionStore;
75+
if (opts.sessionStore === undefined) {
76+
this.ownedSessionStore = createInMemorySessionStore();
77+
sessionStore = this.ownedSessionStore;
78+
} else {
79+
this.ownedSessionStore = undefined;
80+
sessionStore = opts.sessionStore;
81+
}
7382
this.sessionUpdates = new AcpTranslatorSessionUpdates({
7483
connection,
7584
eventLedger: opts.eventLedger ?? createInMemoryAcpEventLedger(),
@@ -115,9 +124,13 @@ export class AcpGatewayAgent implements Agent {
115124
this.log("ready");
116125
}
117126

118-
shutdown(): void {
127+
async shutdown(): Promise<void> {
119128
this.sessionUpdates.stop();
120-
this.promptStream.shutdown();
129+
try {
130+
await this.promptStream.shutdown();
131+
} finally {
132+
this.ownedSessionStore?.dispose();
133+
}
121134
}
122135

123136
handleGatewayReconnect(): void {

0 commit comments

Comments
 (0)