fix(server): reclaim ACP listing providers after launcher exit

This commit is contained in:
paseo-bot[bot]
2026-11-25 08:47:48 +00:00
parent e504877752
commit 42a7cf0a16
3 changed files with 186 additions and 25 deletions
@@ -3013,6 +3013,107 @@ describe("ACPAgentClient import listing deadlines", () => {
}).listImportableSessions({ limit: 1 });
}
test.runIf(process.platform !== "win32")(
"reclaims the stalled listing provider after its launcher exits",
async () => {
const fixtureDir = await mkdtemp(path.join(tmpdir(), "paseo-acp-listing-"));
const fixturePath = path.join(fixtureDir, "launcher.cjs");
const readyPath = path.join(fixtureDir, "listing-ready");
const pidsPath = path.join(fixtureDir, "pids.json");
await writeFile(
fixturePath,
`
const { spawn } = require("node:child_process");
const { writeFileSync } = require("node:fs");
const { createInterface } = require("node:readline");
if (process.argv[4] === "provider") {
process.on("SIGTERM", () => {});
createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method } = JSON.parse(line);
if (method === "initialize") {
console.log(JSON.stringify({ jsonrpc: "2.0", id, result: {
protocolVersion: ${PROTOCOL_VERSION},
agentCapabilities: { sessionCapabilities: { list: {} } },
}}));
}
if (method === "session/list") {
writeFileSync(process.argv[2], "ready");
setInterval(() => {}, 1000);
}
});
} else {
const child = spawn(process.execPath, [...process.argv.slice(1), "provider"], {
stdio: "inherit",
});
writeFileSync(process.argv[3], JSON.stringify({
launcher: process.pid, provider: child.pid,
}));
}
`,
);
const client = new ACPAgentClient({
provider: "test-acp",
logger: createTestLogger(),
defaultCommand: [process.execPath, fixturePath, readyPath, pidsPath],
defaultModes: [],
});
const isRunning = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
return false;
}
};
const readPids = async (): Promise<{ launcher: number; provider: number }> =>
JSON.parse(await readFile(pidsPath, "utf8"));
vi.useFakeTimers({ now: 0, toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
let responseReceived = false;
const listing = listSessionsThroughManager(client).then((response) => {
responseReceived = true;
return response;
});
try {
await vi.waitFor(() => readFile(readyPath, "utf8"), { timeout: 3000 });
const { launcher, provider } = await readPids();
expect(isRunning(launcher)).toBe(true);
expect(isRunning(provider)).toBe(true);
// waitFor advances the fake clock while starting the real processes.
await vi.advanceTimersByTimeAsync(89_999 - Date.now());
expect(responseReceived).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await expect(listing).resolves.toEqual({
sessions: [],
providerErrors: [
{
provider: "test-acp",
message:
"Timed out listing importable sessions for provider 'test-acp' after 90000ms",
},
],
});
await vi.waitFor(() => expect(isRunning(launcher)).toBe(false));
await vi.waitFor(
() => expect(isRunning(provider), "provider outlived launcher cleanup").toBe(false),
{ timeout: 3500 },
);
} finally {
vi.useRealTimers();
const pids = await readPids().catch(() => ({}));
for (const pid of Object.values(pids)) {
if (isRunning(pid)) process.kill(pid, "SIGKILL");
}
await rm(fixtureDir, { recursive: true, force: true });
}
},
10_000,
);
test("accepts a listing that finishes within the daemon's provider deadline", async () => {
vi.useFakeTimers();
const probe = createBlockedListing("session/list");
@@ -560,12 +560,14 @@ export interface SpawnedACPProcess {
stderrChunks?: string[];
}
type UninitializedACPProcess = Omit<SpawnedACPProcess, "initialize"> & {
type ACPProbeProcess = SpawnedACPProcess & { ownsProcessGroup?: boolean };
type UninitializedACPProcess = Omit<ACPProbeProcess, "initialize"> & {
initialize?: InitializeResponse;
};
interface ACPProcessTransport {
child: ChildProcessWithoutNullStreams;
ownsProcessGroup?: boolean;
connection: ClientSideConnection;
stderrChunks: string[];
spawnReady: Promise<void>;
@@ -1362,6 +1364,7 @@ export class ACPAgentClient implements AgentClient {
const probe = await this.spawnProcess(PROBE_ENV, {
signal,
deferCleanupOnError: true,
ownsProcessGroup: true,
client: this.buildProbeClient((params) => history.accept(params)),
});
try {
@@ -1553,8 +1556,9 @@ export class ACPAgentClient implements AgentClient {
client?: ACPClient;
signal?: AbortSignal;
deferCleanupOnError?: boolean;
ownsProcessGroup?: boolean;
},
): Promise<SpawnedACPProcess> {
): Promise<ACPProbeProcess> {
const configuredOptions = ACPProviderOptionsSchema.parse(options?.providerOptions ?? {});
const signal = options?.signal;
signal?.throwIfAborted();
@@ -1562,25 +1566,28 @@ export class ACPAgentClient implements AgentClient {
let closePromise: Promise<void> | undefined;
const closeTransport = (): Promise<void> => {
if (!transport) return Promise.resolve();
closePromise ??= terminateChildProcess(transport.child, 2_000, this.terminateProcess);
closePromise ??= terminateChildProcess(transport, 2_000, this.terminateProcess);
return closePromise;
};
try {
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;
}),
this.spawnTransport(launchEnv, options?.client, options?.ownsProcessGroup).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,
ownsProcessGroup: spawned.ownsProcessGroup,
connection: spawned.connection,
stderrChunks: spawned.stderrChunks,
};
@@ -1594,7 +1601,7 @@ export class ACPAgentClient implements AgentClient {
configuredOptions.clientCapabilities,
),
);
const initializedProbe: SpawnedACPProcess = {
const initializedProbe: ACPProbeProcess = {
...probe,
initialize,
};
@@ -1624,10 +1631,13 @@ export class ACPAgentClient implements AgentClient {
protected async spawnTransport(
launchEnv?: Record<string, string>,
client: ACPClient = this.buildProbeClient(),
ownsProcessGroup = false,
): Promise<ACPProcessTransport> {
const { command, args } = await this.resolveLaunchCommand();
const detached = ownsProcessGroup && process.platform !== "win32";
const child = spawnProcess(command, args, {
cwd: process.cwd(),
detached,
...createProviderEnvSpec({
runtimeSettings: this.runtimeSettings,
overlays: [launchEnv],
@@ -1657,6 +1667,7 @@ export class ACPAgentClient implements AgentClient {
return {
child,
ownsProcessGroup: detached,
connection,
stderrChunks,
spawnReady: spawnReadyPromise,
@@ -1740,7 +1751,7 @@ export class ACPAgentClient implements AgentClient {
} catch (error) {
this.logger.debug({ err: error, sessionId }, "ACP probe closeSession failed during cleanup");
} finally {
await terminateChildProcess(probe.child, 2_000, this.terminateProcess);
await terminateChildProcess(probe, 2_000, this.terminateProcess);
}
}
@@ -4548,12 +4559,16 @@ function coerceSessionConfigMetadata(
}
async function terminateChildProcess(
child: ChildProcessWithoutNullStreams,
{ child, ownsProcessGroup }: Pick<ACPProbeProcess, "child" | "ownsProcessGroup">,
timeoutMs: number,
terminate: ProcessTerminator,
): Promise<void> {
try {
await terminate(child, { gracefulTimeoutMs: timeoutMs, forceTimeoutMs: timeoutMs });
await terminate(child, {
gracefulTimeoutMs: timeoutMs,
forceTimeoutMs: timeoutMs,
ownsProcessGroup,
});
} finally {
child.stdin.destroy();
child.stdout.destroy();
+53 -8
View File
@@ -14,6 +14,8 @@ export interface TerminateWithTreeKillOptions {
gracefulTimeoutMs: number;
forceTimeoutMs?: number;
onForceSignal?: () => void;
/** Only set for a process spawned as the leader of its own POSIX process group. */
ownsProcessGroup?: boolean;
}
export type TerminateWithTreeKillResult =
@@ -33,24 +35,67 @@ export async function terminateWithTreeKill(
child: TreeKillTarget,
options: TerminateWithTreeKillOptions,
): Promise<TerminateWithTreeKillResult> {
if (isProcessExited(child)) {
const processGroupId =
options.ownsProcessGroup && child.pid !== undefined && child.pid > 1 ? child.pid : undefined;
const launcherExited = isProcessExited(child);
if (launcherExited && (processGroupId === undefined || !signalGroup(processGroupId, 0))) {
return "already-exited";
}
const exitPromise = waitForProcessExit(child);
await signalProcessTree(child, options.gracefulSignal ?? "SIGTERM");
if (await waitForExitOrTimeout(exitPromise, options.gracefulTimeoutMs)) {
const waitForExit = createExitWaiter(child, processGroupId);
const gracefulSignal = options.gracefulSignal ?? "SIGTERM";
if (launcherExited && processGroupId !== undefined) {
signalGroup(processGroupId, gracefulSignal);
} else {
await signalProcessTree(child, gracefulSignal);
}
if (await waitForExit(options.gracefulTimeoutMs)) {
return "terminated";
}
options.onForceSignal?.();
await signalProcessTree(child, options.forceSignal ?? "SIGKILL");
const forceSignal = options.forceSignal ?? "SIGKILL";
await signalProcessTree(child, forceSignal);
if (processGroupId !== undefined) {
// The tree walk loses sight of children once their launcher exits.
signalGroup(processGroupId, forceSignal);
}
if (options.forceTimeoutMs === undefined) {
return "killed";
}
return (await waitForExitOrTimeout(exitPromise, options.forceTimeoutMs))
? "killed"
: "kill-timeout";
return (await waitForExit(options.forceTimeoutMs)) ? "killed" : "kill-timeout";
}
function createExitWaiter(
child: TreeKillTarget,
processGroupId: number | undefined,
): (timeoutMs: number) => Promise<boolean> {
if (processGroupId !== undefined) {
return (timeoutMs) => waitForProcessGroupExit(processGroupId, timeoutMs);
}
const exitPromise = waitForProcessExit(child);
return (timeoutMs) => waitForExitOrTimeout(exitPromise, timeoutMs);
}
function signalGroup(groupId: number, signal: NodeJS.Signals | 0): boolean {
try {
process.kill(-groupId, signal);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ESRCH") return false;
throw error;
}
}
async function waitForProcessGroupExit(groupId: number, timeoutMs: number): Promise<boolean> {
const deadline = performance.now() + timeoutMs;
while (signalGroup(groupId, 0)) {
const remainingMs = deadline - performance.now();
if (remainingMs <= 0) return false;
await new Promise<void>((resolve) => setTimeout(resolve, Math.min(50, remainingMs)));
}
return true;
}
export function signalProcessTree(child: TreeKillTarget, signal: NodeJS.Signals): Promise<void> {