Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] b0e8724383 fix(opencode): keep history loads read-only and save the new session id at once
Only an interactive resume replaces a lost OpenCode session, so opening an
archived agent's history no longer creates a native session. A replaced
session reports persistenceUpdatedOnResume, so the agent manager stores
the new id when it registers the session, not after the next prompt.
2026-11-17 07:32:24 +00:00
paseo-bot[bot] b4ae32d77e fix(opencode): continue in a new session when the saved one is gone
Resuming an OpenCode agent reused the saved session id without checking
that OpenCode still had it. When the session was gone, every prompt failed
with NotFoundError "Session not found" and the agent never recovered.

Resume now asks OpenCode for the session first. When OpenCode reports it
missing, the agent starts a new native session on the same server, so the
next prompt runs and the new session id is persisted.
2026-11-17 07:20:32 +00:00
3 changed files with 181 additions and 2 deletions
@@ -0,0 +1,59 @@
import { beforeAll, beforeEach, describe, expect, test } from "vitest";
import pino from "pino";
import type { AgentSession, AgentStreamEvent } from "../agent-sdk-types.js";
import {
canRunRealProvider,
createRealProviderClient,
getRealProviderConfig,
} from "../../daemon-e2e/real-provider-test-config.js";
import { streamSession } from "./test-utils/session-stream-adapter.js";
function isTerminalEvent(event: AgentStreamEvent): boolean {
return (
event.type === "turn_completed" ||
event.type === "turn_failed" ||
event.type === "turn_canceled"
);
}
async function runTurn(session: AgentSession, prompt: string): Promise<AgentStreamEvent> {
for await (const event of streamSession(session, prompt)) {
if (isTerminalEvent(event)) return event;
}
throw new Error("turn ended without a terminal event");
}
describe("opencode agent whose native session is gone (real)", () => {
let canRun = false;
beforeAll(async () => {
canRun = await canRunRealProvider("opencode");
});
beforeEach((context) => {
if (!canRun) context.skip();
});
test("a resumed agent whose OpenCode session no longer exists continues in a new session", async () => {
const client = createRealProviderClient("opencode", pino({ level: "silent" }));
const config = { ...getRealProviderConfig("opencode"), cwd: process.cwd() };
// A non-persistent session deletes its native OpenCode session on close, which
// leaves the handle naming a session OpenCode no longer has.
const lost = await client.createSession(config, undefined, { persistSession: false });
const handle = lost.describePersistence();
await lost.close();
expect(handle).not.toBeNull();
const resumed = await client.resumeSession(handle!, config);
try {
const turn = await runTurn(resumed, "Reply with exactly: OK");
expect(turn).toMatchObject({ type: "turn_completed" });
expect(resumed.describePersistence()?.sessionId).not.toBe(handle!.sessionId);
} finally {
await resumed.close().catch(() => undefined);
}
}, 120_000);
});
@@ -814,6 +814,79 @@ describe("OpenCodeAgentClient adapter smoke tests", () => {
}
});
test("resuming an agent whose OpenCode session is gone continues in a new session", async () => {
const runtime = new TestOpenCodeHarness();
const execution = new TestOpenCodeClient();
execution.sessionGetResponse = {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
execution.sessionCreateResponse = { data: { id: "ses_fresh" } };
execution.sessionPromptAsyncImplementation = async (parameters) => {
const { sessionID } = parameters as { sessionID: string };
if (sessionID === "ses_lost") {
return {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
}
execution.emitEvent({ type: "session.idle", properties: { sessionID } });
return {};
};
runtime.enqueueClient(execution);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const cwd = tmpCwd();
try {
const session = await client.resumeSession({
provider: "opencode",
sessionId: "ses_lost",
metadata: { cwd },
});
try {
const turn = await collectTurnEvents(streamSession(session, "Are you there?"));
expect(turn.turnCompleted).toBe(true);
expect(session.describePersistence()?.sessionId).toBe("ses_fresh");
expect(session.persistenceUpdatedOnResume).toBe(true);
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("loading history of an agent whose OpenCode session is gone creates no session", async () => {
const runtime = new TestOpenCodeHarness();
const execution = new TestOpenCodeClient();
execution.sessionGetResponse = {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
runtime.enqueueClient(execution);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const cwd = tmpCwd();
try {
const session = await client.resumeSession(
{ provider: "opencode", sessionId: "ses_lost", metadata: { cwd } },
undefined,
undefined,
{ purpose: "history" },
);
try {
expect(execution.calls.sessionCreate).toEqual([]);
expect(session.describePersistence()?.sessionId).toBe("ses_lost");
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("fetchCatalog returns models with required fields", async () => {
const runtime = new TestOpenCodeHarness();
const openCodeClient = new TestOpenCodeClient();
@@ -546,6 +546,15 @@ function isOpenCodeNotFoundError(error: unknown): boolean {
);
}
async function isOpenCodeSessionMissing(
client: Pick<OpencodeClient, "session">,
sessionId: string,
directory: string,
): Promise<boolean> {
const response = await client.session.get({ sessionID: sessionId, directory });
return isOpenCodeNotFoundError(response.error);
}
async function abortOpenCodeSession(params: {
client: Pick<OpencodeClient, "session">;
sessionId: string;
@@ -1457,8 +1466,18 @@ export class OpenCodeAgentClient implements AgentClient {
options?: AgentCreateSessionOptions,
): Promise<AgentSession> {
const openCodeConfig = this.assertConfig(config);
const connection = await this.connectServer(openCodeConfig, launchContext);
return this.startNewSession(connection, config, openCodeConfig, launchContext, options);
}
private async startNewSession(
connection: OpenCodeServerConnection,
config: AgentSessionConfig,
openCodeConfig: OpenCodeAgentConfig,
launchContext?: AgentLaunchContext,
options?: AgentCreateSessionOptions,
): Promise<OpenCodeAgentSession> {
const connectServer = this.connectServer.bind(this, openCodeConfig, launchContext);
const connection = await connectServer();
const { client } = connection;
// OpenCode stores permission rules on the session, so they are set here and on resume
@@ -1522,7 +1541,7 @@ export class OpenCodeAgentClient implements AgentClient {
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
_options?: AgentResumeSessionOptions,
options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
const metadata = (handle.metadata ?? {}) as Partial<AgentSessionConfig>;
const cwd = overrides?.cwd ?? metadata.cwd;
@@ -1547,6 +1566,32 @@ export class OpenCodeAgentClient implements AgentClient {
: await connectServer();
const { client } = connection;
// History loads stay read-only, so only an interactive resume replaces a lost session.
let sessionMissing = false;
if ((options?.purpose ?? "interactive") === "interactive") {
try {
sessionMissing = await isOpenCodeSessionMissing(
client,
handle.sessionId,
openCodeConfig.cwd,
);
} catch (error) {
await connection.release();
throw error;
}
}
if (sessionMissing) {
// Every prompt to a session OpenCode no longer has fails, so the agent
// continues in a new native session instead of staying unusable.
this.logger.warn(
{ sessionId: handle.sessionId },
"OpenCode session no longer exists; continuing in a new session",
);
const session = await this.startNewSession(connection, config, openCodeConfig, launchContext);
session.persistenceUpdatedOnResume = true;
return session;
}
try {
await this.applySessionPermissionRules(client, openCodeConfig, handle.sessionId);
await this.populateModelContextWindowCache(client, openCodeConfig.cwd);
@@ -3380,6 +3425,8 @@ interface OpenCodeServerConnection {
}
class OpenCodeAgentSession implements AgentSession {
/** Set when resume replaced a lost native session, so the new handle is saved at once. */
persistenceUpdatedOnResume = false;
readonly provider = "opencode" as const;
readonly capabilities = OPENCODE_CAPABILITIES;
readonly openOptionsPatch: Record<string, unknown>;