fix: bound import listing and clean up ACP probes

This commit is contained in:
Chirag Singhal
2026-11-22 13:07:34 +00:00
committed by paseo-bot[bot]
parent e886aebff3
commit deade99257
4 changed files with 464 additions and 27 deletions
+102
View File
@@ -6560,6 +6560,108 @@ test("fetches scoped recent provider sessions", async () => {
});
});
test.each([
{
scenario: "successful rows after the default RPC deadline",
delayMs: 61_000,
payload: {
requestId: "recent-listing-deadline",
entries: [
{
providerId: "slow-acp",
providerLabel: "Slow ACP",
providerHandleId: "slow-session",
cwd: "/tmp/import-listing",
title: "Slow provider session",
firstPromptPreview: null,
lastPromptPreview: null,
lastActivityAt: "2026-04-30T12:34:56.000Z",
},
],
},
},
{
scenario: "the server's provider timeout after ninety seconds",
delayMs: 90_001,
payload: {
requestId: "recent-listing-deadline",
entries: [],
providerErrors: [
{
provider: "slow-acp",
message: "Timed out listing importable sessions for provider 'slow-acp' after 90000ms",
},
],
},
},
])("recent provider listing receives $scenario", async ({ delayMs, payload }) => {
useHeartbeatClock();
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_import_listing_deadline",
reconnect: { enabled: false },
transportFactory: () => transport.transport,
});
clients.push(client);
const connected = client.connect();
transport.triggerOpen();
await connected;
const outcome = client
.fetchRecentProviderSessions({
requestId: "recent-listing-deadline",
providers: ["slow-acp"],
limit: 1,
})
.then(
(response) => ({ status: "success", response }),
(error: unknown) => ({ status: "error", error }),
);
await vi.advanceTimersByTimeAsync(delayMs);
transport.triggerMessage(
wrapSessionMessage({ type: "fetch_recent_provider_sessions_response", payload }),
);
expect(await outcome).toEqual({ status: "success", response: payload });
expect(client.isConnected).toBe(true);
});
test("recent provider listing still expires when the daemon never answers", async () => {
useHeartbeatClock();
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_import_listing_no_response",
reconnect: { enabled: false },
transportFactory: () => transport.transport,
});
clients.push(client);
const connected = client.connect();
transport.triggerOpen();
await connected;
const errors: unknown[] = [];
const listing = client
.fetchRecentProviderSessions({ providers: ["slow-acp"] })
.catch((error: unknown) => {
errors.push(error);
});
await vi.advanceTimersByTimeAsync(90_001);
expect(errors).toEqual([]);
await vi.advanceTimersByTimeAsync(9_999);
expect(errors).toEqual([
expect.objectContaining({
name: "DaemonConnectionError",
code: "DAEMON_REQUEST_TIMEOUT",
}),
]);
await listing;
expect(client.isConnected).toBe(true);
});
test("imports an agent by provider handle id", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
+3
View File
@@ -1172,6 +1172,8 @@ function toTimeoutError(error: unknown, label: string, timeoutMs: number): Error
const DEFAULT_RECONNECT_BASE_DELAY_MS = 1500;
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30000;
const DEFAULT_SESSION_RPC_TIMEOUT_MS = 60_000;
// The daemon allows 90s per provider; retain its result through the delivery margin.
const RECENT_PROVIDER_SESSIONS_TIMEOUT_MS = 100_000;
const PUSH_TOKEN_REVOCATION_TIMEOUT_MS = 2_000;
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
const DEFAULT_LIVENESS_TIMEOUT_MS = 5000;
@@ -2998,6 +3000,7 @@ export class DaemonClient {
return this.sendRequest({
requestId: resolvedRequestId,
message,
timeout: RECENT_PROVIDER_SESSIONS_TIMEOUT_MS,
options: { skipQueue: true },
select: (msg) => {
if (msg.type !== "fetch_recent_provider_sessions_response") {
@@ -4,6 +4,7 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import path from "node:path";
import { PassThrough, Readable, Writable } from "node:stream";
import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
@@ -2899,6 +2900,275 @@ describe("ACPAgentClient listImportableSessions", () => {
});
});
describe("ACPAgentClient import listing deadlines", () => {
type ListingPhase = "spawn" | "initialize" | "session/list";
const phases: ListingPhase[] = ["initialize", "session/list"];
function createBlockedListing(phase: ListingPhase, terminator = new FakeTerminator()) {
const child = createProbeChildStub();
const clientToAgent = new PassThrough();
const agentToClient = new PassThrough();
child.stdin = clientToAgent;
child.stdout = agentToClient;
child.stderr = new PassThrough();
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
let markStarted!: () => void;
const started = new Promise<void>((resolve) => {
markStarted = resolve;
});
const operations: string[] = [];
const agent: Agent = {
async initialize() {
operations.push("initialize");
if (phase === "initialize") {
markStarted();
await blocked;
}
return {
protocolVersion: PROTOCOL_VERSION,
agentCapabilities: { sessionCapabilities: { list: {} } },
};
},
async listSessions() {
operations.push("session/list");
if (phase === "session/list") {
markStarted();
await blocked;
}
return { sessions: [] };
},
async newSession() {
throw new Error("Import listing must not create a session");
},
async prompt() {
throw new Error("Import listing must not submit a prompt");
},
async authenticate() {},
async cancel() {},
};
const agentConnection = new AgentSideConnection(
() => agent,
ndJsonStream(Writable.toWeb(agentToClient), Readable.toWeb(clientToAgent)),
);
const connection = new ClientSideConnection(
() => ({
async requestPermission() {
return { outcome: { outcome: "cancelled" } };
},
async sessionUpdate() {},
}),
ndJsonStream(Writable.toWeb(clientToAgent), Readable.toWeb(agentToClient)),
);
const processError = new Promise<never>((_resolve, reject) => {
child.once("error", reject);
child.once("close", () => reject(new Error("Import probe exited during cleanup")));
});
class ListingClient extends ACPAgentClient {
protected override async spawnTransport() {
if (phase === "spawn") {
operations.push("spawn");
markStarted();
await blocked;
}
return {
child,
connection,
stderrChunks: [],
spawnReady: Promise.resolve(),
processError,
};
}
}
const client = new ListingClient({
provider: "test-acp",
logger: createTestLogger(),
defaultCommand: ["test-acp"],
defaultModes: [],
terminateProcess: async (target, options) => {
const result = await terminator.terminate(target, options);
child.emit("close", 0, null);
return result;
},
});
return { client, child, agentConnection, terminator, started, release, operations };
}
test.each(phases)("cleans up when import listing stalls in %s", async (phase) => {
vi.useFakeTimers();
const probe = createBlockedListing(phase);
const errors: unknown[] = [];
const listing = probe.client.listImportableSessions({ limit: 1 }).catch((error: unknown) => {
errors.push(error);
return [];
});
try {
await probe.started;
await vi.advanceTimersByTimeAsync(89_999);
expect(errors).toEqual([
expect.objectContaining({ message: expect.stringMatching(/timed out/i) }),
]);
expect(probe.terminator.terminated).toEqual([probe.child]);
expect(probe.child.stdin.destroyed).toBe(true);
expect(probe.child.stdout.destroyed).toBe(true);
expect(probe.child.stderr.destroyed).toBe(true);
} finally {
probe.release();
await listing;
vi.useRealTimers();
}
});
test.each(phases)("cleans up when import listing is aborted in %s", async (phase) => {
vi.useFakeTimers();
const probe = createBlockedListing(phase);
const abort = new AbortController();
const reason = new Error("Import listing cancelled");
const options = { limit: 1, signal: abort.signal };
const errors: unknown[] = [];
const listing = probe.client.listImportableSessions(options).catch((error: unknown) => {
errors.push(error);
return [];
});
try {
await probe.started;
abort.abort(reason);
await vi.advanceTimersByTimeAsync(0);
expect(errors).toEqual([reason]);
expect(probe.terminator.terminated).toEqual([probe.child]);
expect(probe.child.stdin.destroyed).toBe(true);
expect(probe.child.stdout.destroyed).toBe(true);
expect(probe.child.stderr.destroyed).toBe(true);
probe.release();
await listing;
expect(probe.operations).toEqual(
phase === "initialize" ? ["initialize"] : ["initialize", "session/list"],
);
expect(probe.terminator.terminated).toEqual([probe.child]);
} finally {
probe.release();
await listing;
vi.useRealTimers();
}
});
test("closes an import probe that finishes spawning after cancellation", async () => {
const probe = createBlockedListing("spawn");
const abort = new AbortController();
const reason = new Error("Import listing cancelled before spawn completed");
const options = { limit: 1, signal: abort.signal };
const errors: unknown[] = [];
const unhandledRejections: unknown[] = [];
function recordUnhandledRejection(error: unknown): void {
unhandledRejections.push(error);
}
process.on("unhandledRejection", recordUnhandledRejection);
const listing = probe.client.listImportableSessions(options).catch((error: unknown) => {
errors.push(error);
return [];
});
try {
await probe.started;
abort.abort(reason);
await listing;
expect(errors).toEqual([reason]);
expect(probe.terminator.terminated).toEqual([]);
probe.release();
// Node reports unhandled rejections after the cleanup microtasks settle.
await new Promise<void>((resolve) => setImmediate(resolve));
expect(probe.terminator.terminated).toEqual([probe.child]);
expect(probe.child.stdin.destroyed).toBe(true);
expect(probe.child.stdout.destroyed).toBe(true);
expect(probe.child.stderr.destroyed).toBe(true);
expect(probe.operations).toEqual(["spawn"]);
expect(errors).toEqual([reason]);
expect(unhandledRejections).toEqual([]);
} finally {
probe.release();
await listing;
await new Promise<void>((resolve) => setImmediate(resolve));
process.removeListener("unhandledRejection", recordUnhandledRejection);
}
});
test("preserves process failures during import probe initialization", async () => {
vi.useFakeTimers();
const probe = createBlockedListing("initialize");
const failure = new Error("Import probe failed during initialize");
const errors: unknown[] = [];
const listing = probe.client.listImportableSessions({ limit: 1 }).catch((error: unknown) => {
errors.push(error);
return [];
});
try {
await probe.started;
probe.child.emit("error", failure);
await vi.advanceTimersByTimeAsync(0);
expect(errors).toEqual([
expect.objectContaining({ message: "Import probe failed during initialize" }),
]);
expect(probe.operations).toEqual(["initialize"]);
expect(probe.terminator.terminated).toEqual([probe.child]);
expect(probe.child.stdin.destroyed).toBe(true);
expect(probe.child.stdout.destroyed).toBe(true);
expect(probe.child.stderr.destroyed).toBe(true);
} finally {
probe.release();
await listing;
vi.useRealTimers();
}
});
test("waits for owned import probe cleanup before rejecting cancellation", async () => {
vi.useFakeTimers();
const terminator = new FakeTerminator("deferred");
const probe = createBlockedListing("session/list", terminator);
const abort = new AbortController();
const reason = new Error("Import listing cancelled during session/list");
const options = { limit: 1, signal: abort.signal };
const errors: unknown[] = [];
const listing = probe.client.listImportableSessions(options).catch((error: unknown) => {
errors.push(error);
return [];
});
try {
await probe.started;
abort.abort(reason);
await vi.advanceTimersByTimeAsync(0);
expect(terminator.terminated).toEqual([probe.child]);
expect(errors).toEqual([]);
terminator.releaseAll();
await listing;
expect(errors).toEqual([reason]);
expect(probe.child.stdin.destroyed).toBe(true);
expect(probe.child.stdout.destroyed).toBe(true);
expect(probe.child.stderr.destroyed).toBe(true);
} finally {
probe.release();
await vi.advanceTimersByTimeAsync(0);
terminator.releaseAll();
await listing;
vi.useRealTimers();
}
});
});
describe("ACP providers advertise session listing", () => {
// The daemon's agent-manager only queries providers whose
// capabilities.supportsSessionListing is true. Without it, ACP providers
@@ -343,6 +343,8 @@ const ACP_CLOSE_REQUEST_TIMEOUT_MS = 2_000;
const ACP_DISCONNECT_EXIT_GRACE_MS = 1_000;
const ACP_IMPORT_HISTORY_LOAD_TIMEOUT_MS = 30_000;
const ACP_IMPORT_HISTORY_BUDGET_MS = 60_000;
// Reserve time for process-tree cleanup before the manager's 90s listing deadline.
const ACP_IMPORT_LIST_TIMEOUT_MS = 85_000;
/**
* An ACP agent publishes its slash-command inventory incrementally. Wait this
@@ -1354,13 +1356,27 @@ export class ACPAgentClient implements AgentClient {
}
async listImportableSessions(
options?: ListImportableSessionsOptions,
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
): Promise<ImportableProviderSession[]> {
const history = new ACPImportHistoryCollector();
const probe = await this.spawnProcess(PROBE_ENV, {
client: this.buildProbeClient((params) => history.accept(params)),
});
const deadline = new AbortController();
const timeout = setTimeout(
() =>
deadline.abort(
new Error(`ACP import listing timed out after ${ACP_IMPORT_LIST_TIMEOUT_MS}ms`),
),
ACP_IMPORT_LIST_TIMEOUT_MS,
);
const signal = options?.signal
? AbortSignal.any([deadline.signal, options.signal])
: deadline.signal;
let probe: SpawnedACPProcess | undefined;
try {
signal.throwIfAborted();
probe = await this.spawnProcess(PROBE_ENV, {
signal,
client: this.buildProbeClient((params) => history.accept(params)),
});
if (!probe.initialize.agentCapabilities?.sessionCapabilities?.list) {
return [];
}
@@ -1373,10 +1389,16 @@ export class ACPAgentClient implements AgentClient {
let scanned = 0;
let cursor: string | null | undefined;
for (;;) {
const page: ListSessionsResponse = await this.runACPRequest(() =>
probe.connection.listSessions(acpSessionListRequest(cursor, options?.cwd)),
signal.throwIfAborted();
const connection = probe.connection;
const page: ListSessionsResponse = await raceProviderRefreshAbort(
signal,
this.runACPRequest(() =>
connection.listSessions(acpSessionListRequest(cursor, options?.cwd)),
),
);
for (const session of page.sessions) {
signal.throwIfAborted();
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
scanned += 1;
const descriptor = await this.describeImportableSession(
@@ -1385,6 +1407,7 @@ export class ACPAgentClient implements AgentClient {
session,
canLoadHistory,
historyDeadline,
signal,
);
if (descriptor) sessions.push(descriptor);
}
@@ -1393,9 +1416,11 @@ export class ACPAgentClient implements AgentClient {
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
}
signal.throwIfAborted();
return sessions;
} finally {
await this.closeProbe(probe);
clearTimeout(timeout);
if (probe) await this.closeProbe(probe);
}
}
@@ -1405,9 +1430,10 @@ export class ACPAgentClient implements AgentClient {
session: ListSessionsResponse["sessions"][number],
canLoadHistory: boolean,
historyDeadline: number,
signal: AbortSignal,
): Promise<ImportableProviderSession | null> {
const loadedPreviews = canLoadHistory
? await this.loadImportPromptPreviews(probe, history, session, historyDeadline)
? await this.loadImportPromptPreviews(probe, history, session, historyDeadline, signal)
: null;
if (loadedPreviews?.hasConversation === false) return null;
return {
@@ -1425,7 +1451,9 @@ export class ACPAgentClient implements AgentClient {
history: ACPImportHistoryCollector,
session: ListSessionsResponse["sessions"][number],
historyDeadline: number,
signal: AbortSignal,
): Promise<ACPImportPromptPreviews | null> {
signal.throwIfAborted();
const updatedAt = session.updatedAt ?? null;
const cached = this.importPromptCache.get(session.sessionId);
if (updatedAt !== null && cached?.updatedAt === updatedAt) {
@@ -1443,12 +1471,15 @@ export class ACPAgentClient implements AgentClient {
history.begin(session.sessionId);
try {
await withTimeout(
this.runACPRequest(() =>
probe.connection.loadSession({
sessionId: session.sessionId,
cwd: session.cwd,
mcpServers: [],
}),
raceProviderRefreshAbort(
signal,
this.runACPRequest(() =>
probe.connection.loadSession({
sessionId: session.sessionId,
cwd: session.cwd,
mcpServers: [],
}),
),
),
loadTimeoutMs,
`ACP import history load timed out after ${loadTimeoutMs}ms`,
@@ -1460,13 +1491,16 @@ export class ACPAgentClient implements AgentClient {
return previews;
} catch (error) {
history.discard(session.sessionId);
signal.throwIfAborted();
this.logger.debug(
{ err: error, sessionId: session.sessionId },
"ACP import history load failed; keeping the session visible",
);
return null;
} finally {
await this.closeLoadedSession(probe, session.sessionId, historyDeadline);
if (!signal.aborted) {
await this.closeLoadedSession(probe, session.sessionId, historyDeadline, signal);
}
}
}
@@ -1474,6 +1508,7 @@ export class ACPAgentClient implements AgentClient {
probe: SpawnedACPProcess,
sessionId: string,
historyDeadline: number,
signal: AbortSignal,
): Promise<void> {
if (!probe.initialize.agentCapabilities?.sessionCapabilities?.close) return;
const remainingMs = historyDeadline - this.now();
@@ -1481,11 +1516,12 @@ export class ACPAgentClient implements AgentClient {
const closeTimeoutMs = Math.min(ACP_PROBE_CLOSE_TIMEOUT_MS, remainingMs);
try {
await withTimeout(
probe.connection.unstable_closeSession({ sessionId }),
raceProviderRefreshAbort(signal, probe.connection.unstable_closeSession({ sessionId })),
closeTimeoutMs,
`ACP loaded session/close timed out after ${closeTimeoutMs}ms`,
);
} catch (error) {
signal.throwIfAborted();
this.logger.debug({ err: error, sessionId }, "ACP loaded session close failed");
}
}
@@ -1515,21 +1551,47 @@ export class ACPAgentClient implements AgentClient {
providerOptions?: Record<string, unknown>;
onSpawned?: (probe: UninitializedACPProcess) => void;
client?: ACPClient;
signal?: AbortSignal;
},
): Promise<SpawnedACPProcess> {
const configuredOptions = ACPProviderOptionsSchema.parse(options?.providerOptions ?? {});
const transport = await this.spawnTransport(launchEnv, options?.client);
const probe: UninitializedACPProcess = {
child: transport.child,
connection: transport.connection,
stderrChunks: transport.stderrChunks,
const signal = options?.signal;
signal?.throwIfAborted();
let transport: ACPProcessTransport | undefined;
let closePromise: Promise<void> | undefined;
const closeTransport = (): Promise<void> => {
if (!transport) return Promise.resolve();
closePromise ??= terminateChildProcess(transport.child, 2_000, this.terminateProcess);
return closePromise;
};
options?.onSpawned?.(probe);
try {
const initialize = await this.initializeTransport(
transport,
options?.initializeTimeoutMs,
configuredOptions.clientCapabilities,
const spawned = await raceProviderRefreshAbort(
signal,
this.spawnTransport(launchEnv, options?.client).then(async (spawnedTransport) => {
transport = spawnedTransport;
// Cancellation can close the process before initialize observes its failure.
void spawnedTransport.processError.catch(() => undefined);
if (signal?.aborted) {
await closeTransport();
signal.throwIfAborted();
}
return spawnedTransport;
}),
);
const probe: UninitializedACPProcess = {
child: spawned.child,
connection: spawned.connection,
stderrChunks: spawned.stderrChunks,
};
options?.onSpawned?.(probe);
signal?.throwIfAborted();
const initialize = await raceProviderRefreshAbort(
signal,
this.initializeTransport(
spawned,
options?.initializeTimeoutMs,
configuredOptions.clientCapabilities,
),
);
const initializedProbe: SpawnedACPProcess = {
...probe,
@@ -1538,7 +1600,7 @@ export class ACPAgentClient implements AgentClient {
probe.initialize = initialize;
return initializedProbe;
} catch (error) {
await terminateChildProcess(transport.child, 2_000, this.terminateProcess);
await closeTransport();
throw error;
}
}