Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions packages/provider-bridge-acp/src/bridge/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5658,6 +5658,152 @@ describe("acp bridge: busy agents, restored sessions and stop reasons", () => {
}
});

const lostSessionErrors = [
{
agent: "an agent using the ACP resource-not-found code",
error: { code: -32002, message: "Resource not found" },
},
{
agent: "OpenCode",
error: {
code: -32602,
message: "Invalid params: session not found: ses_lost",
data: { sessionId: "ses_lost" },
},
},
{
agent: "Copilot",
error: { code: -32602, message: "Session ses_lost not found" },
},
{
agent: "Cursor",
error: {
code: -32603,
message: "Internal error",
data: { details: "Session ses_lost not found" },
},
},
{
agent: "Copilot with a stuck session lock",
error: {
code: -32603,
message: "Internal error",
data: {
details:
"session lock unavailable during is_session_generation_current: acquisition timed out",
},
},
},
];

function lostSessionAgentEnv(error: object): {
envVars: Record<string, string>;
launchCount: () => number;
requestLog: string;
} {
const launchLog = join(workspaceDir, "launches.log");
const requestLog = join(workspaceDir, "requests.log");
return {
envVars: {
FAKE_ACP_LOAD_SESSION: "1",
FAKE_ACP_LOST_SESSION_ERROR: JSON.stringify(error),
FAKE_ACP_LOST_SESSION_FILE: join(workspaceDir, "lost-session"),
FAKE_ACP_LAUNCH_LOG: launchLog,
FAKE_ACP_REQUEST_LOG: requestLog,
},
launchCount: () =>
readFileSync(launchLog, "utf8").split("\n").filter(Boolean).length,
requestLog,
};
}

async function turnStatus(
providerThreadId: string,
input: unknown[],
): Promise<unknown> {
const completedBefore = threadEventsOfType("turn/completed").length;
const turnId = sendTurnRequest("turn/start", providerThreadId, { input });
expect((await waitForResponse(turnId)).error).toBeUndefined();
const completed = await waitFor(
() => threadEventsOfType("turn/completed")[completedBefore],
"next turn/completed thread event",
);
return completed["status"];
}

it.each(lostSessionErrors)(
"rebuilds the session before the next turn after $agent reports it lost",
async ({ error }) => {
const agent = lostSessionAgentEnv(error);
const { providerThreadId } = await startThread({
envVars: agent.envVars,
});
const text = (value: string) => [
{ type: "text", text: value, mentions: [] },
];

expect(await turnStatus(providerThreadId, text("first"))).toBe("failed");
expect(await turnStatus(providerThreadId, text("second"))).toBe(
"completed",
);

expect(agentMessageTexts()).toEqual(["echo:second"]);
expect(agent.launchCount()).toBe(2);
expect(
loggedAcpRequests(agent.requestLog).filter(
(request) => request.method === "session/load",
),
).toEqual([
expect.objectContaining({
params: expect.objectContaining({ sessionId: providerThreadId }),
}),
]);
expect(notifications("session/replaced")).toHaveLength(1);
expect(notifications("session/replaced")[0]?.params).toMatchObject({
providerThreadId,
reason:
"The ACP agent lost its session; the session was rebuilt before continuing.",
contextLost: false,
});
},
);

it("rebuilds the session before the next turn after a compaction finds it lost", async () => {
const agent = lostSessionAgentEnv(lostSessionErrors[1]!.error);
const { providerThreadId } = await startThread({ envVars: agent.envVars });

expect(await turnStatus(providerThreadId, compactCommandInput())).toBe(
"failed",
);
expect(
await turnStatus(providerThreadId, [
{ type: "text", text: "after compaction", mentions: [] },
]),
).toBe("completed");

expect(agentMessageTexts()).toEqual(["echo:after compaction"]);
expect(agent.launchCount()).toBe(2);
expect(notifications("session/replaced")).toHaveLength(1);
});

it("keeps the session when a prompt fails for another reason", async () => {
const agent = lostSessionAgentEnv({
code: -32603,
message: "Internal error",
data: { details: "upstream model overloaded" },
});
const { providerThreadId } = await startThread({ envVars: agent.envVars });
const text = (value: string) => [
{ type: "text", text: value, mentions: [] },
];

expect(await turnStatus(providerThreadId, text("first"))).toBe("failed");
expect(await turnStatus(providerThreadId, text("second"))).toBe("failed");

expect(agent.launchCount()).toBe(1);
expect(notifications("session/replaced")).toEqual([]);
});

it("restores a session with session/resume when the agent offers it, without replaying history", async () => {
const requestLog = join(workspaceDir, "requests.log");
const envVars = {
Expand Down
53 changes: 43 additions & 10 deletions packages/provider-bridge-acp/src/bridge/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ import {
type AcpAgentRequestResponder,
} from "./agent-connection.js";
import type { AcpAgentCapabilities } from "../client/capabilities.js";
import { ACP_RESOURCE_NOT_FOUND_CODE } from "../client/acp-client.js";
import {
createAcpSessionModel,
type AcpSessionModel,
Expand Down Expand Up @@ -204,6 +205,8 @@ interface AcpNativeConfigState {
models: AcpSessionModels | undefined;
}

type AcpSessionRebuildCause = "cancel-error" | "lost-session";

interface AcpThreadSession {
bbThreadId: string;
construction: AcpSessionParams;
Expand Down Expand Up @@ -232,7 +235,7 @@ interface AcpThreadSession {
promptRequestPending: boolean;
cancelRequested: boolean;
turnStartedAtMs: number | undefined;
restartAfterCancelError: boolean;
rebuildBeforeNextPrompt: AcpSessionRebuildCause | null;
loading: boolean;
loadingSessionId: string | undefined;
pendingLoadUsageUpdate: AcpUsageUpdate | undefined;
Expand Down Expand Up @@ -296,6 +299,8 @@ const SESSION_BUSY_QUIET_MS = 2_000;
const SESSION_BUSY_MAX_WAITS = 300;
const SESSION_BUSY_MAX_RETRIES = 3;
const ACP_SESSION_BUSY_ERROR_CODE = -32003;
const ACP_LOST_SESSION_MESSAGE =
/\bsession\b(?:\s+\S+)?\s+not found|\bsession lock unavailable\b/i;
const ACP_SESSION_SETUP_TIMEOUT_MS = 300_000;
const ACP_SESSION_CONFIG_TIMEOUT_MS = 60_000;
const ACP_AUTHENTICATE_TIMEOUT_MS = 120_000;
Expand Down Expand Up @@ -2445,7 +2450,7 @@ async function startAgentSession(
promptRequestPending: false,
cancelRequested: false,
turnStartedAtMs: undefined,
restartAfterCancelError: false,
rebuildBeforeNextPrompt: null,
loading: false,
loadingSessionId: undefined,
pendingLoadUsageUpdate: undefined,
Expand Down Expand Up @@ -3135,6 +3140,23 @@ function finishTurn(
});
}

function isLostSessionError(error: unknown): boolean {
return (
error instanceof AcpAgentResponseError &&
(error.code === ACP_RESOURCE_NOT_FOUND_CODE ||
ACP_LOST_SESSION_MESSAGE.test(error.message))
);
}

function scheduleRebuildIfSessionLost(
session: AcpThreadSession,
error: unknown,
): void {
if (isLostSessionError(error)) {
session.rebuildBeforeNextPrompt ??= "lost-session";
}
}

function isSessionBusyError(error: unknown): boolean {
return (
error instanceof AcpAgentResponseError &&
Expand Down Expand Up @@ -3261,7 +3283,10 @@ function runTurn(
}
}
} catch (error) {
session.restartAfterCancelError = session.cancelRequested;
session.rebuildBeforeNextPrompt = session.cancelRequested
? "cancel-error"
: null;
scheduleRebuildIfSessionLost(session, error);
session.promptRequestPending = false;
dropTurnInput(pending, "ACP turn failed before the prompt was sent");
dropQueuedTurnInputs(
Expand Down Expand Up @@ -3384,7 +3409,7 @@ function reconcileExecutionSettings(
launchModelChanged;
const restart =
session.connection.exited ||
session.restartAfterCancelError ||
session.rebuildBeforeNextPrompt !== null ||
launchArgsChanged ||
!isDeepStrictEqual(envVars ?? {}, session.construction.envVars ?? {});
cancelPendingPermissions(session);
Expand Down Expand Up @@ -3442,9 +3467,11 @@ async function rebuildAgentSession(
const previousProviderThreadId = session.providerThreadId;
const reason = session.connection.exited
? "The ACP agent exited unexpectedly; its session was rebuilt before continuing."
: session.restartAfterCancelError
: session.rebuildBeforeNextPrompt === "cancel-error"
? "The ACP agent failed during cancellation; its session was rebuilt before continuing."
: "Execution settings changed; the ACP session was rebuilt to apply them.";
: session.rebuildBeforeNextPrompt === "lost-session"
? "The ACP agent lost its session; the session was rebuilt before continuing."
: "Execution settings changed; the ACP session was rebuilt to apply them.";
const queuedInputs = session.queuedInputs.splice(0);
const continuingTurn = session.activePromptKind === "turn";
if (continuingTurn) {
Expand Down Expand Up @@ -3563,6 +3590,7 @@ function startCompaction(
);
})
.catch((error: unknown) => {
scheduleRebuildIfSessionLost(session, error);
finish({
status: "failed",
error: error instanceof Error ? error.message : String(error),
Expand Down Expand Up @@ -4126,10 +4154,15 @@ async function handleRequest(
const reconciled = reconcileExecutionSettings(session, params.options);
session = reconciled instanceof Promise ? await reconciled : reconciled;
if (params.options.sessionOptions !== undefined) {
await applySessionOptionSelections(
session,
params.options.sessionOptions,
);
try {
await applySessionOptionSelections(
session,
params.options.sessionOptions,
);
} catch (error) {
scheduleRebuildIfSessionLost(session, error);
throw error;
}
}
const pending: AcpPendingTurnInput = {
clientRequestId: params.clientRequestId,
Expand Down
23 changes: 23 additions & 0 deletions packages/provider-bridge-acp/src/bridge/fake-acp-agent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@
* count model-discovery spawns in cache/TTL tests)
* - FAKE_ACP_PROMPT_LOG → append one JSON-encoded prompt text per request
* - FAKE_ACP_PROMPT_ERROR=1 → reject every session/prompt request
* - FAKE_ACP_LOST_SESSION_ERROR
* → JSON-RPC error object; the first launched
* process rejects every session/prompt with it,
* as an agent that lost its session does
* - FAKE_ACP_LOST_SESSION_FILE
* → marker that limits the lost session to the
* first launch
* - FAKE_ACP_GROK_CONTEXT=1 → advertise Grok model _meta.totalContextTokens
* and prompt-result _meta.usage
* - FAKE_ACP_COMPACT_STOP_REASON
Expand Down Expand Up @@ -294,6 +301,16 @@ if (process.env.FAKE_ACP_LAUNCH_LOG) {
appendFileSync(process.env.FAKE_ACP_LAUNCH_LOG, `launch ${process.pid}\n`);
}

let lostSessionError = null;
if (
process.env.FAKE_ACP_LOST_SESSION_ERROR &&
process.env.FAKE_ACP_LOST_SESSION_FILE &&
!existsSync(process.env.FAKE_ACP_LOST_SESSION_FILE)
) {
writeFileSync(process.env.FAKE_ACP_LOST_SESSION_FILE, "");
lostSessionError = JSON.parse(process.env.FAKE_ACP_LOST_SESSION_ERROR);
}

function send(message) {
process.stdout.write(JSON.stringify(message) + "\n");
}
Expand Down Expand Up @@ -614,6 +631,12 @@ async function handlePrompt(message) {
return;
}

if (lostSessionError !== null) {
activePromptId = null;
send({ jsonrpc: "2.0", id: message.id, error: lostSessionError });
return;
}

if (process.env.FAKE_ACP_PROMPT_ERROR === "1") {
activePromptId = null;
send({
Expand Down
44 changes: 44 additions & 0 deletions packages/provider-bridge-acp/src/delta-translation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2114,6 +2114,50 @@ describe("acp delta translation (raw payloads and real results)", () => {
return harness;
}

it("settles a call from updates that send the SDK's null fields", () => {
const harness = startedHarness();
const updates = [
{
sessionUpdate: "tool_call",
toolCallId: "call-null",
title: "`pnpm test`",
kind: "execute",
status: "pending",
rawInput: { command: "pnpm test" },
},
{
sessionUpdate: "tool_call_update",
toolCallId: "call-null",
status: "in_progress",
title: null,
content: null,
locations: null,
},
{
sessionUpdate: "tool_call_update",
toolCallId: "call-null",
status: "failed",
title: null,
locations: null,
content: [
{ type: "content", content: { type: "text", text: "3 failed\n" } },
],
},
];
const events = updates.flatMap((update) =>
harness.translate(updateEvent(update)),
);

expect(completedItems(events)).toEqual([
expect.objectContaining({
type: "commandExecution",
command: "pnpm test",
status: "failed",
aggregatedOutput: "3 failed\n",
}),
]);
});

it("reports the exit code and stderr Cursor sent, not a status guess", () => {
const events = startedHarness().translate(
updateEvent({
Expand Down
Loading
Loading