Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 42a7cf0a16 fix(server): reclaim ACP listing providers after launcher exit 2026-11-25 08:47:48 +00:00
Mohamed Boudra e504877752 Keep pending session imports tied to their original host 2026-11-24 16:03:06 +01:00
paseo-bot[bot]andderek 096de6a1f6 fix(app): scope Import Session results to the selected host
Co-authored-by: derek <174018435+derek-geekdive@users.noreply.github.com>
2026-11-24 15:59:19 +01:00
paseo-bot[bot] 7ee7c2adbf test(server): give Worktrunk integration fixtures time to finish 2026-11-24 15:59:19 +01:00
paseo-bot[bot] 2531ba2542 fix(server): preserve timely ACP initialization errors during listing 2026-11-24 15:59:19 +01:00
paseo-bot[bot] ed21847121 fix(server): preserve timely ACP listing errors during cleanup
A provider error returned within the listing window can still be displayed while its probe shuts down.
2026-11-24 15:59:19 +01:00
paseo-bot[bot] 8ad8c40d67 fix(server): return Import Session results before probe cleanup finishes
A timely ACP listing was discarded when process shutdown crossed the listing deadline. Return the completed rows and let the adapter finish reclaiming the probe.
2026-11-24 15:59:19 +01:00
Chirag Singhal 685a4f2ad2 fix: show import provider errors and retry progress 2026-11-24 15:59:19 +01:00
paseo-bot[bot]andChirag Singhal b8516bb2c1 fix(server): keep the full Import Session deadline
Start ACP probe cleanup when the agent manager stops waiting. Keep the 90-second window for listings that still have time to finish.

Co-authored-by: Chirag Singhal <76880977+chirag127@users.noreply.github.com>
2026-11-24 15:59:19 +01:00
Chirag Singhal 0d0aa27584 fix: bound import listing and clean up ACP probes 2026-11-24 15:59:18 +01:00
14 changed files with 1036 additions and 104 deletions
@@ -4,10 +4,15 @@ import { copyFile, mkdir, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { TestInfo } from "@playwright/test";
import type { FetchRecentProviderSessionsRequestMessage } from "@getpaseo/protocol/messages";
import { expect, test, type Page } from "../support/fixtures";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { addConnectedHostAndReload } from "../support/helpers/hosts";
import { ImportSessionFlow } from "../support/helpers/import-session";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import {
connectNewWorkspaceDaemonClient,
loadSessionMessageReaders,
openProjectViaDaemon,
type OpenedProject,
} from "../support/helpers/new-workspace";
@@ -20,16 +25,22 @@ const SCREENSHOT_DIRECTORY = path.join(
const claudeConfigDirectory = mkdtempSync(path.join(tmpdir(), "paseo-import-flow-claude-"));
const brokenProvider = "broken-acp";
const disabledProviders = {
codex: { enabled: false },
copilot: { enabled: false },
omp: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
antigravity: { enabled: false },
muse: { enabled: false },
};
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
codex: { enabled: false },
copilot: { enabled: false },
omp: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
...disabledProviders,
[brokenProvider]: {
extends: "acp",
label: "Broken ACP",
@@ -136,6 +147,120 @@ test("an open Import Session row keeps its age current", async ({ page }) => {
await expect(row).toContainText("4m ago");
});
test("shows listing failure details beside healthy sessions and retries the failed provider", async ({
page,
}, testInfo) => {
const frames = await loadSessionMessageReaders();
const requests: FetchRecentProviderSessionsRequestMessage[] = [];
const completed = new Set<string>();
page.on("websocket", (socket) => {
socket.on("framesent", ({ payload }) => {
const request = frames.client(payload);
if (request?.type === "fetch_recent_provider_sessions_request") {
requests.push(request);
}
});
socket.on("framereceived", ({ payload }) => {
const response = frames.server(payload);
if (response?.type === "fetch_recent_provider_sessions_response") {
completed.add(response.payload.requestId);
}
});
});
const flow = new ImportSessionFlow(page);
for (const width of [1280, 390]) {
await flow.openWorkspace(scenario.project.workspaceId, { width, height: 844 });
await flow.openGlobally();
await flow.expectProviderError("Broken ACP");
const healthySession = page.getByTestId(
`import-session-session-claude-${scenario.importSessionId}`,
);
await expect(healthySession).toBeVisible();
await page.screenshot({ path: testInfo.outputPath(`listing-failure-${width}.png`) });
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
"missing-agent-command",
);
const requestOffset = requests.length;
await flow.retryProvider(brokenProvider, "Broken ACP");
await expect
.poll(() => requests.slice(requestOffset).map((request) => request.providers))
.toEqual([[brokenProvider]]);
const retriedRequest = requests[requestOffset];
if (!retriedRequest) throw new Error("Retry did not send a provider listing request");
await expect.poll(() => completed.has(retriedRequest.requestId)).toBe(true);
await expect(page.getByTestId(`import-session-retry-${brokenProvider}`)).toBeEnabled();
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
"missing-agent-command",
);
await expect(healthySession).toBeVisible();
await page.screenshot({ path: testInfo.outputPath(`listing-failure-retry-${width}.png`) });
await flow.close();
}
});
test("Import Session keeps listings tied to their host during a switch and a pending import", async ({
page,
}) => {
const secondaryHost = await startIsolatedHostDaemon("import-session-secondary", {
config: {
agents: {
providers: {
...disabledProviders,
claude: { enabled: false },
[brokenProvider]: {
extends: "acp",
label: "Broken ACP",
command: ["missing-secondary-command", "acp"],
},
},
},
},
});
try {
const gate = await installDaemonWebSocketGate(page);
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 1280, height: 844 });
await addConnectedHostAndReload(page, {
serverId: secondaryHost.serverId,
port: secondaryHost.port,
label: "Second import host",
primaryLabel: "First import host",
});
await flow.chooseHostForImport("First import host");
await expect(page.getByText(/missing-agent-command/)).toBeVisible();
await flow.close();
await flow.chooseHostForImport("Second import host");
await expect(page.getByText(/missing-secondary-command/)).toBeVisible();
await expect(page.getByText(/missing-agent-command/)).toHaveCount(0);
await flow.close();
await test.step("returning to the original host omits the session imported during the switch", async () => {
const sessionId = "fixture-root-04";
await flow.chooseHostForImport("First import host");
gate.holdNextClientRequest("import_agent_request");
await flow.startImport(sessionId);
await gate.waitForHeldClientRequest();
await flow.close();
await flow.chooseHostForImport("Second import host");
await flow.expectProviderError("Broken ACP");
gate.releaseHeldClientRequest();
await flow.expectClosed();
await flow.chooseHostForImport("First import host");
await flow.revealSession("fixture-worktree");
await flow.expectSessionUnavailable(sessionId);
await flow.close();
await flow.expectTranscript("Review fixture item 4", "Fixture response 4");
});
} finally {
await secondaryHost.close();
}
});
test("captures the compact import-session journey", async ({ page }, testInfo) => {
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 390, height: 844 });
@@ -378,7 +503,13 @@ async function seedClaudeSessions(input: {
unrelatedDirectory: string;
importSessionId: string;
}): Promise<number> {
const sessions = [
const sessions: {
cwd: string;
id: string;
title: string;
prompt: string;
answer?: string;
}[] = [
{
cwd: input.projectRoot,
id: input.importSessionId,
@@ -403,6 +534,7 @@ async function seedClaudeSessions(input: {
id: `fixture-root-${String(index + 1).padStart(2, "0")}`,
title: `Root session ${String(index + 1).padStart(2, "0")}`,
prompt: index === 7 ? "Investigate invoice rendering" : `Review fixture item ${index + 1}`,
...(index === 3 ? { answer: "Fixture response 4" } : {}),
})),
];
const newest = Date.now() - 60_000;
@@ -137,13 +137,22 @@ export class ImportSessionFlow {
await this.expectProviderError(label);
await expect(this.page.getByRole("progressbar")).toHaveCount(0);
}
async importSession(id: string) {
async startImport(id: string) {
await this.revealSession(id);
await this.page.getByTestId(rowTestId(id)).click();
}
async importSession(id: string) {
await this.startImport(id);
await this.expectClosed();
}
async expectClosed() {
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0, {
timeout: 30_000,
});
}
async expectSessionUnavailable(id: string) {
await expect(this.page.getByTestId(rowTestId(id))).toHaveCount(0);
}
async expectTranscript(userText: string, assistantText: string) {
await expect(this.page.getByTestId("user-message").filter({ visible: true })).toContainText(
userText,
@@ -169,6 +178,13 @@ export class ImportSessionFlow {
await this.page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0);
}
async chooseHostForImport(hostLabel: string) {
const panel = await openCommandCenter(this.page);
await panel.getByTestId("command-center-input").fill("import");
await panel.getByText("Import session", { exact: true }).click();
await this.page.getByRole("dialog").getByRole("button", { name: hostLabel }).click();
await this.expectScope(`Sessions on ${hostLabel}`);
}
async expectCommandCenterMatch() {
const panel = await openCommandCenter(this.page);
await panel.getByTestId("command-center-input").fill("import");
@@ -184,7 +184,9 @@ describe("collectProviderErrorRows", () => {
[settled(undefined, { isError: true }), settled({ entries: [] })],
new Map([["claude", "Claude Code"]]),
);
expect(rows).toEqual([{ provider: "claude", label: "Claude Code" }]);
expect(rows).toEqual([
{ provider: "claude", label: "Claude Code", message: null, retrying: false },
]);
});
it("returns a row for a provider the daemon reported as failed in a good response", () => {
@@ -198,7 +200,9 @@ describe("collectProviderErrorRows", () => {
],
new Map([["codex", "Codex"]]),
);
expect(rows).toEqual([{ provider: "codex", label: "Codex" }]);
expect(rows).toEqual([
{ provider: "codex", label: "Codex", message: "timed out", retrying: false },
]);
});
it("uses provider id when the label map has no entry", () => {
@@ -207,7 +211,43 @@ describe("collectProviderErrorRows", () => {
[settled(undefined, { isError: true })],
new Map(),
);
expect(rows).toEqual([{ provider: "codex", label: "codex" }]);
expect(rows).toEqual([{ provider: "codex", label: "codex", message: null, retrying: false }]);
});
it("shows the current request failure instead of an older provider error", () => {
const query = {
...settled(
{ entries: [], providerErrors: [{ provider: "codex", message: "old provider failure" }] },
{ isError: true },
),
error: new Error(" Connection closed. Reconnect the host and retry. "),
};
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
{
provider: "codex",
label: "codex",
message: "Connection closed. Reconnect the host and retry.",
retrying: false,
},
]);
});
it("keeps the provider failure visible while its retry is in flight", () => {
const query = {
...settled({
entries: [],
providerErrors: [{ provider: "codex", message: "Run codex login and retry." }],
}),
isFetching: true,
};
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
{
provider: "codex",
label: "codex",
message: "Run codex login and retry.",
retrying: true,
},
]);
});
});
@@ -39,6 +39,8 @@ export interface SessionsQueryResult {
}
| undefined;
isError: boolean;
error?: Error | null;
isFetching?: boolean;
isLoading: boolean;
isPending: boolean;
isPlaceholderData?: boolean;
@@ -120,6 +122,8 @@ export function hasMoreSessions(
export interface ProviderErrorRow {
provider: string;
label: string;
message: string | null;
retrying: boolean;
}
/**
@@ -140,7 +144,15 @@ export function collectProviderErrorRows(
if (!query || provider === undefined) continue;
const failed = query.isError || (query.data?.providerErrors?.length ?? 0) > 0;
if (!failed) continue;
rows.push({ provider, label: providerLabelById.get(provider) ?? provider });
const failure = query.data?.providerErrors?.find((error) => error.provider === provider);
const failureMessage = query.isError ? query.error?.message : failure?.message;
const message = failureMessage?.trim() || null;
rows.push({
provider,
label: providerLabelById.get(provider) ?? provider,
message,
retrying: query.isFetching === true,
});
}
return rows;
}
@@ -79,15 +79,19 @@ type RecentSessionsResponse = Awaited<
type SessionsQueryKey = ReadonlyArray<string | number | null>;
function buildSessionsQueryRoot(serverId: string | null, cwd: string | null) {
return ["recent-provider-sessions", serverId, cwd] as const;
}
function buildSessionsQueryKey(input: {
serverId: string | null;
cwd: string | null;
query: string;
limit: number;
provider?: string;
}): SessionsQueryKey {
return [
"recent-provider-sessions",
input.cwd,
...buildSessionsQueryRoot(input.serverId, input.cwd),
input.query,
input.limit,
...(input.provider === undefined ? [] : [input.provider]),
@@ -101,6 +105,7 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
refetchOnMount: true;
placeholderData: () => RecentSessionsResponse | undefined;
queryFn: () => Promise<RecentSessionsResponse>;
}
@@ -110,20 +115,23 @@ function buildSessionsQueriesConfig(args: {
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
serverId: string | null;
cwd: string | null;
query: string;
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { queryClient, providersToFetch, visible, client, serverId, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
queryKey: buildSessionsQueryKey({ serverId, cwd, query, limit, provider }),
enabled,
retry: false as const,
// An import can invalidate an inactive host. Refresh its listing when observed again.
refetchOnMount: true as const,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
@@ -131,7 +139,7 @@ function buildSessionsQueriesConfig(args: {
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
buildSessionsQueryKey({ serverId, cwd, query, limit: previousLimit, provider }),
),
queryFn: async () => {
if (!client) {
@@ -217,13 +225,21 @@ function ProviderErrorBannerRow({
const handleRetry = useCallback(() => onRetry(row.provider), [onRetry, row.provider]);
return (
<View style={styles.errorRow}>
<Text style={styles.errorText}>
{t("importSession.status.failedProvider", { provider: row.label })}
</Text>
<View style={styles.errorContent}>
<Text style={styles.errorText}>
{t("importSession.status.failedProvider", { provider: row.label })}
</Text>
{row.message ? (
<Text style={styles.errorDetail} selectable>
{row.message}
</Text>
) : null}
</View>
<Button
variant="ghost"
size="sm"
onPress={handleRetry}
loading={row.retrying}
testID={`import-session-retry-${row.provider}`}
>
{t("common.actions.retry")}
@@ -529,7 +545,10 @@ export function ImportSessionSheet({
[snapshotEntries],
);
const sessionsQueryRoot = useMemo(() => ["recent-provider-sessions", scopeCwd], [scopeCwd]);
const sessionsQueryRoot = useMemo(
() => buildSessionsQueryRoot(serverId, scopeCwd),
[serverId, scopeCwd],
);
const queriesConfig = useMemo(
() =>
@@ -538,12 +557,13 @@ export function ImportSessionSheet({
providersToFetch,
visible,
client,
serverId,
cwd: scopeCwd,
query,
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[queryClient, providersToFetch, visible, client, serverId, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
@@ -682,19 +702,17 @@ export function ImportSessionSheet({
cwd: entry.cwd,
...(target.workspaceId ? { workspaceId: target.workspaceId } : {}),
});
return { agent, target };
},
onSuccess: ({ agent, target }) => {
// A pending import keeps the listing and navigation from the host it was sent to.
void queryClient.invalidateQueries({
queryKey: sessionsQueryRoot,
refetchType: "none",
});
onClose();
if (target.crossWorkspace) {
onImported?.(agent);
} else {
onImportedAgent?.(agent.id);
}
void queryClient.invalidateQueries({
queryKey: sessionsQueryRoot,
refetchType: "none",
});
},
});
@@ -725,10 +743,16 @@ export function ImportSessionSheet({
const handleRetryProvider = useCallback(
(provider: string) => {
void queryClient.refetchQueries({
queryKey: buildSessionsQueryKey({ cwd: scopeCwd, query, limit: pageLimit, provider }),
queryKey: buildSessionsQueryKey({
serverId,
cwd: scopeCwd,
query,
limit: pageLimit,
provider,
}),
});
},
[pageLimit, query, queryClient, scopeCwd],
[pageLimit, query, queryClient, scopeCwd, serverId],
);
const handleShowAll = useCallback(() => setIsShowingAllDirectories(true), []);
@@ -1071,6 +1095,12 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[2],
paddingVertical: theme.spacing[1],
},
errorContent: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
errorText: {
flexShrink: 1,
@@ -1078,6 +1108,10 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.palette.red[300],
fontSize: theme.fontSize.sm,
},
errorDetail: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
emptyState: {
alignItems: "center",
justifyContent: "center",
+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") {
@@ -317,7 +317,7 @@ interface HydrateTimelineOptions {
broadcastTimeline?: boolean;
}
export type ImportablePersistedAgentQueryOptions = ListImportableSessionsOptions & {
export type ImportablePersistedAgentQueryOptions = Omit<ListImportableSessionsOptions, "signal"> & {
/**
* When set, only providers in this set are scanned, in addition to the
* built-in importable allowlist + enabled + non-derived rules.
@@ -1296,9 +1296,11 @@ export class AgentManager {
);
const providerResults = await Promise.all(
providerEntries.map(async ([provider, client]) => {
const cancellation = new AbortController();
try {
const sessions = await withTimeout(
client.listImportableSessions!({
signal: cancellation.signal,
limit: options?.limit,
query: options?.query,
scanLimit: options?.scanLimit,
@@ -1314,6 +1316,7 @@ export class AgentManager {
error: null,
};
} catch (error) {
cancellation.abort(error);
this.logger.warn(
{ err: error, provider },
"Failed to list importable sessions for provider",
@@ -586,6 +586,8 @@ export interface AgentSlashCommand {
}
export interface ListImportableSessionsOptions {
/** Aborts provider work when the caller stops waiting for a listing. */
signal?: AbortSignal;
providerOptions?: ProviderOptions;
limit?: number;
/** Optional case-insensitive descriptor search text. */
@@ -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 {
@@ -37,6 +38,7 @@ import {
summarizeACPRequestError,
} from "./acp-agent.js";
import { createIdleRuntimeCleanup } from "../idle-runtime-cleanup/index.js";
import { AgentManager } from "../agent-manager.js";
import type { ProcessTerminator, TreeKillTarget } from "../../../utils/tree-kill.js";
import {
COPILOT_AGENT_FEATURE_OPTION,
@@ -2899,6 +2901,450 @@ 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(),
responseError?: RequestError,
) {
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;
if (responseError) throw responseError;
}
return {
protocolVersion: PROTOCOL_VERSION,
agentCapabilities: { sessionCapabilities: { list: {} } },
};
},
async listSessions() {
operations.push("session/list");
if (phase === "session/list") {
markStarted();
await blocked;
if (responseError) throw responseError;
}
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 };
}
function listSessionsThroughManager(client: ACPAgentClient) {
return new AgentManager({
clients: { [client.provider]: client },
logger: createTestLogger(),
}).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");
const listing = listSessionsThroughManager(probe.client);
try {
await probe.started;
await vi.advanceTimersByTimeAsync(88_000);
probe.release();
await expect(listing).resolves.toEqual({ sessions: [], providerErrors: [] });
expect(probe.terminator.terminated).toEqual([probe.child]);
} finally {
probe.release();
await listing;
vi.useRealTimers();
}
});
test.each<{ phase: ListingPhase; errorMessage?: string }>([
{ phase: "session/list" },
{ phase: "session/list", errorMessage: "Provider rejected listing" },
{ phase: "initialize", errorMessage: "Sign in to the provider and retry" },
])(
"returns a timely $phase outcome while its probe is still shutting down ($errorMessage)",
async ({ phase, errorMessage }) => {
vi.useFakeTimers();
const terminator = new FakeTerminator("deferred");
const responseError = errorMessage ? new RequestError(-32001, errorMessage) : undefined;
const probe = createBlockedListing(phase, terminator, responseError);
const providerErrors = errorMessage
? [{ provider: "test-acp", message: expect.stringContaining(errorMessage) }]
: [];
const listing = listSessionsThroughManager(probe.client);
try {
await probe.started;
await vi.advanceTimersByTimeAsync(88_000);
probe.release();
await vi.advanceTimersByTimeAsync(2_000);
expect(terminator.terminated.map((child) => child.pid)).toEqual([probe.child.pid]);
expect(probe.child.stdout.destroyed).toBe(false);
await expect(listing).resolves.toEqual({ sessions: [], providerErrors });
terminator.releaseAll();
await vi.advanceTimersByTimeAsync(0);
expect(probe.child.stdout.destroyed).toBe(true);
} finally {
probe.release();
terminator.releaseAll();
await listing;
await vi.advanceTimersByTimeAsync(0);
vi.useRealTimers();
}
},
);
test.each(phases)("cleans up when import listing stalls in %s", async (phase) => {
vi.useFakeTimers();
const probe = createBlockedListing(phase);
const listing = listSessionsThroughManager(probe.client);
try {
await probe.started;
await vi.advanceTimersByTimeAsync(89_999);
expect(probe.terminator.terminated).toEqual([]);
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",
},
],
});
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
@@ -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>;
@@ -1357,57 +1359,84 @@ export class ACPAgentClient implements AgentClient {
options?: ListImportableSessionsOptions,
): Promise<ImportableProviderSession[]> {
const history = new ACPImportHistoryCollector();
const signal = options?.signal ?? new AbortController().signal;
signal.throwIfAborted();
const probe = await this.spawnProcess(PROBE_ENV, {
signal,
deferCleanupOnError: true,
ownsProcessGroup: true,
client: this.buildProbeClient((params) => history.accept(params)),
});
try {
if (!probe.initialize.agentCapabilities?.sessionCapabilities?.list) {
return [];
}
const sessions: ImportableProviderSession[] = [];
const resultLimit = options?.limit ?? Number.POSITIVE_INFINITY;
const scanLimit = Math.min(options?.scanLimit ?? 500, 500);
const canLoadHistory = probe.initialize.agentCapabilities.loadSession === true;
const historyDeadline = this.now() + ACP_IMPORT_HISTORY_BUDGET_MS;
let scanned = 0;
let cursor: string | null | undefined;
for (;;) {
const page: ListSessionsResponse = await this.runACPRequest(() =>
probe.connection.listSessions(acpSessionListRequest(cursor, options?.cwd)),
);
for (const session of page.sessions) {
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
scanned += 1;
const descriptor = await this.describeImportableSession(
probe,
history,
session,
canLoadHistory,
historyDeadline,
);
if (descriptor) sessions.push(descriptor);
}
cursor = page.nextCursor ?? null;
if (!cursor) break;
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
}
return sessions;
return await this.listImportableSessionsFromProbe(probe, history, options, signal);
} finally {
await this.closeProbe(probe);
if (signal.aborted) {
await this.closeProbe(probe);
} else {
this.finishListingProbeCleanup(this.closeProbe(probe));
}
}
}
private async listImportableSessionsFromProbe(
probe: SpawnedACPProcess,
history: ACPImportHistoryCollector,
options: ListImportableSessionsOptions | undefined,
signal: AbortSignal,
): Promise<ImportableProviderSession[]> {
signal.throwIfAborted();
if (!probe.initialize.agentCapabilities?.sessionCapabilities?.list) {
return [];
}
const sessions: ImportableProviderSession[] = [];
const resultLimit = options?.limit ?? Number.POSITIVE_INFINITY;
const scanLimit = Math.min(options?.scanLimit ?? 500, 500);
const canLoadHistory = probe.initialize.agentCapabilities.loadSession === true;
const historyDeadline = this.now() + ACP_IMPORT_HISTORY_BUDGET_MS;
let scanned = 0;
let cursor: string | null | undefined;
for (;;) {
signal.throwIfAborted();
const page: ListSessionsResponse = await raceProviderRefreshAbort(
signal,
this.runACPRequest(() =>
probe.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(
probe,
history,
session,
canLoadHistory,
historyDeadline,
signal,
);
if (descriptor) sessions.push(descriptor);
}
cursor = page.nextCursor ?? null;
if (!cursor) break;
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
}
signal.throwIfAborted();
return sessions;
}
private async describeImportableSession(
probe: SpawnedACPProcess,
history: ACPImportHistoryCollector,
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 +1454,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 +1474,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 +1494,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 +1511,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 +1519,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,41 +1554,90 @@ export class ACPAgentClient implements AgentClient {
providerOptions?: Record<string, unknown>;
onSpawned?: (probe: UninitializedACPProcess) => void;
client?: ACPClient;
signal?: AbortSignal;
deferCleanupOnError?: boolean;
ownsProcessGroup?: boolean;
},
): Promise<SpawnedACPProcess> {
): Promise<ACPProbeProcess> {
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, 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, 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 initializedProbe: SpawnedACPProcess = {
const probe: UninitializedACPProcess = {
child: spawned.child,
ownsProcessGroup: spawned.ownsProcessGroup,
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: ACPProbeProcess = {
...probe,
initialize,
};
probe.initialize = initialize;
return initializedProbe;
} catch (error) {
await terminateChildProcess(transport.child, 2_000, this.terminateProcess);
const cleanup = closeTransport();
if (options?.deferCleanupOnError && !signal?.aborted) {
this.finishListingProbeCleanup(cleanup);
} else {
await cleanup;
}
throw error;
}
}
private finishListingProbeCleanup(cleanup: Promise<void>): void {
// Deliver the provider's result while its probe finishes shutting down.
void cleanup.catch((error) => {
this.logger.warn(
{ err: error, provider: this.provider },
"Failed to close ACP listing probe",
);
});
}
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],
@@ -1579,6 +1667,7 @@ export class ACPAgentClient implements AgentClient {
return {
child,
ownsProcessGroup: detached,
connection,
stderrChunks,
spawnReady: spawnReadyPromise,
@@ -1662,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);
}
}
@@ -4470,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();
@@ -1827,7 +1827,7 @@ export class ClaudeAgentClient implements AgentClient {
}
async listImportableSessions(
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
options?: ListImportableSessionsOptions,
): Promise<ImportableProviderSession[]> {
// Leave time to deliver the provider error before the client RPC expires at 60 seconds.
const deadline = AbortSignal.timeout(45_000);
@@ -365,7 +365,7 @@ export default function contribute(server) {
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
}, 90_000);
test("worktree manager supports decline fallback, rollback delegation, and disabled-plugin fallback on archive and restore", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-fallback-"));
@@ -606,9 +606,7 @@ export default function contribute(server) {
const pending = client.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "concurrent" },
});
// Cleanup closes the client if the marker never arrives.
void pending.catch(() => undefined);
await expect
const managerStarted = expect
.poll(
() =>
stat(path.join(root, "manager-started")).then(
@@ -618,6 +616,12 @@ export default function contribute(server) {
{ timeout: 10_000 },
)
.toBe(true);
await Promise.race([
managerStarted,
pending.then(({ error }) => {
throw new Error(`Worktree creation finished before the manager was released: ${error}`);
}),
]);
const concurrent = path.join(root, "concurrent-manual");
git(repository, ["worktree", "add", "-b", "concurrent", concurrent, "main"]);
await writeFile(path.join(concurrent, "local.txt"), "uncommitted work");
+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> {