fix(providers): publish catalogue before closing the probe session

A slow session/close pushed the catalogue reply past the refresh deadline,
and a cancel arriving during shutdown was ignored. The reply now goes out
before shutdown, and the abort listener stays until shutdown ends. The
public example also handles a failed read.
This commit is contained in:
Mohamed Boudra
2026-11-26 02:35:51 +01:00
parent 393fed61cb
commit 6f13cb0333
4 changed files with 103 additions and 41 deletions
@@ -289,33 +289,40 @@ async function dispatch(
}
/**
* Runs one request in its own short-lived runtime. Aborting `signal` closes the runtime, which
* terminates its process and fails whatever the request still awaits.
* Runs one request in its own short-lived runtime and publishes its result before shutting the
* runtime down, so a slow session close cannot delay the reply. Aborting `signal` until shutdown
* ends closes the runtime, which terminates its process and fails whatever the request awaits.
*/
async function withRequestRuntime<Result>(
state: AcpConnectionState,
start: { boundarySessionId: string; cwd?: string },
signal: AbortSignal,
run: (runtime: AcpRuntime) => Promise<Result>,
): Promise<Result> {
request: {
boundarySessionId: string;
cwd?: string;
signal: AbortSignal;
run(runtime: AcpRuntime): Promise<Result>;
publish(result: Result): void;
},
): Promise<void> {
const { signal } = request;
const runtime = await AcpRuntime.start({
options: state.options,
launch: state.launch,
boundarySessionId: request.boundarySessionId,
cwd: request.cwd,
env: {},
emit: state.emit,
signal,
...start,
});
const closeOnAbort = () => void runtime.close().catch(() => undefined);
signal.addEventListener("abort", closeOnAbort, { once: true });
try {
signal.throwIfAborted();
const result = await run(runtime);
const result = await request.run(runtime);
signal.throwIfAborted();
return result;
request.publish(result);
} finally {
signal.removeEventListener("abort", closeOnAbort);
await (signal.aborted ? runtime.close() : runtime.closeSession());
signal.removeEventListener("abort", closeOnAbort);
}
}
@@ -324,22 +331,24 @@ async function discover(
state: AcpConnectionState,
signal: AbortSignal,
): Promise<void> {
const catalog = await withRequestRuntime(
state,
{ boundarySessionId: "catalog", cwd: input.cwd },
await withRequestRuntime(state, {
boundarySessionId: "catalog",
cwd: input.cwd,
signal,
async (runtime) => {
let discovered = await runtime.discover(input.cwd);
async run(runtime) {
let catalog = await runtime.discover(input.cwd);
const context = runtime.configContext();
for (const transformer of state.options.transformers ?? []) {
if (transformer.discover) {
discovered = await transformer.discover(discovered, context);
catalog = await transformer.discover(catalog, context);
}
}
return discovered;
return catalog;
},
);
state.emit({ type: "catalog", requestId: input.requestId, catalog });
publish(catalog) {
state.emit({ type: "catalog", requestId: input.requestId, catalog });
},
});
}
async function listSessions(
@@ -347,21 +356,22 @@ async function listSessions(
state: AcpConnectionState,
signal: AbortSignal,
): Promise<void> {
const selected = await withRequestRuntime(
state,
{ boundarySessionId: "sessions" },
await withRequestRuntime(state, {
boundarySessionId: "sessions",
signal,
(runtime) => runtime.listSessions({ cwd: input.cwd, limit: input.limit }),
);
state.emit({
type: "sessions",
requestId: input.requestId,
sessions: selected.map((session) => ({
persistence: nativePersistence(session.sessionId),
cwd: session.cwd,
title: session.title ?? undefined,
updatedAt: session.updatedAt ?? undefined,
})),
run: (runtime) => runtime.listSessions({ cwd: input.cwd, limit: input.limit }),
publish(selected) {
state.emit({
type: "sessions",
requestId: input.requestId,
sessions: selected.map((session) => ({
persistence: nativePersistence(session.sessionId),
cwd: session.cwd,
title: session.title ?? undefined,
updatedAt: session.updatedAt ?? undefined,
})),
});
},
});
}
+32
View File
@@ -1,5 +1,6 @@
import type { ChildProcess } from "node:child_process";
import diagnosticsChannel from "node:diagnostics_channel";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -2347,6 +2348,37 @@ describe("runAcpProvider catalogue requests whose session/new never answers", ()
}
});
it("publishes the catalogue before the probe session starts closing", async () => {
const closeMarker = path.join(
await mkdtemp(path.join(tmpdir(), "paseo-acp-catalog-close-")),
"close-started",
);
temporaryDirectories.push(path.dirname(closeMarker));
// session/close never answers, so the probe's shutdown runs into its close timeout.
const executable = await fakeAcp(`const fs = require("node:fs");
const readline = require("node:readline");
const lines = readline.createInterface({ input: process.stdin });
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
lines.on("line", (line) => {
const message = JSON.parse(line);
if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } });
else if (message.method === "session/new") send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "catalog-native", modes: null, configOptions: [] } });
else if (message.method === "session/close") fs.writeFileSync(${JSON.stringify(closeMarker)}, "started");
});`);
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
let closingWhenPublished: boolean | undefined;
connection.onEvent((event) => {
if (event.type === "catalog") closingWhenPublished = existsSync(closeMarker);
});
try {
await connection.send({ type: "catalog", requestId: "catalog-1" });
await waitForEvent(events, (event) => event.type === "catalog");
expect(closingWhenPublished).toBe(false);
} finally {
await connection.close();
}
});
it("ignores cancellation of a request that already finished", async () => {
const executable = await fakeAcp(basicAgent);
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
+14 -4
View File
@@ -177,10 +177,20 @@ if (input.type === "catalog") {
const controller = new AbortController();
pending.set(input.requestId, controller);
void readCatalog({ signal: controller.signal })
.then((catalog) => {
if (!controller.signal.aborted)
emit({ type: "catalog", requestId: input.requestId, catalog });
})
.then(
(catalog) => {
if (!controller.signal.aborted)
emit({ type: "catalog", requestId: input.requestId, catalog });
},
(error) => {
if (!controller.signal.aborted)
emit({
type: "request.failed",
requestId: input.requestId,
error: { message: String(error) },
});
},
)
.finally(() => pending.delete(input.requestId));
}
if (input.type === "request.cancel") {
+14 -4
View File
@@ -155,10 +155,20 @@ if (input.type === "catalog") {
const controller = new AbortController();
pending.set(input.requestId, controller);
void readCatalog({ signal: controller.signal })
.then((catalog) => {
if (!controller.signal.aborted)
emit({ type: "catalog", requestId: input.requestId, catalog });
})
.then(
(catalog) => {
if (!controller.signal.aborted)
emit({ type: "catalog", requestId: input.requestId, catalog });
},
(error) => {
if (!controller.signal.aborted)
emit({
type: "request.failed",
requestId: input.requestId,
error: { message: String(error) },
});
},
)
.finally(() => pending.delete(input.requestId));
}
if (input.type === "request.cancel") {