mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-23 08:45:14 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
440c469e36 | ||
|
|
7b4b92b9d0 | ||
|
|
0c2e1cb64c | ||
|
|
cce85b3f25 | ||
|
|
dd5ed3a0f6 | ||
|
|
65515dc597 | ||
|
|
8fccdfabae | ||
|
|
deade99257 |
@@ -4,10 +4,14 @@ 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 { 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 +24,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 +146,98 @@ 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 shows the selected host's listing error after switching hosts", 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 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);
|
||||
} 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 });
|
||||
|
||||
@@ -169,6 +169,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("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]),
|
||||
@@ -110,18 +114,19 @@ 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,
|
||||
// While Load more fetches the next page, keep showing the page it grew from. React Query's
|
||||
@@ -131,7 +136,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 +222,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 +542,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 +554,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 });
|
||||
@@ -725,10 +742,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 +1094,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 +1107,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",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,349 @@ 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("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
|
||||
|
||||
@@ -1357,57 +1357,83 @@ 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,
|
||||
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 +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,48 @@ export class ACPAgentClient implements AgentClient {
|
||||
providerOptions?: Record<string, unknown>;
|
||||
onSpawned?: (probe: UninitializedACPProcess) => void;
|
||||
client?: ACPClient;
|
||||
signal?: AbortSignal;
|
||||
deferCleanupOnError?: boolean;
|
||||
},
|
||||
): 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,11 +1601,26 @@ export class ACPAgentClient implements AgentClient {
|
||||
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(),
|
||||
|
||||
@@ -1853,7 +1853,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,14 +606,22 @@ export default function contribute(server) {
|
||||
const pending = client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "concurrent" },
|
||||
});
|
||||
await expect
|
||||
.poll(() =>
|
||||
stat(path.join(root, "manager-started")).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
const managerStarted = expect
|
||||
.poll(
|
||||
() =>
|
||||
stat(path.join(root, "manager-started")).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
{ 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");
|
||||
|
||||
Reference in New Issue
Block a user