Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] eba7d0ca14 fix(server): keep OpenCode parents usable after child worktree removal
OpenCode keeps the child session after its working directory is removed. Skip runtime reconciliation for that child when OpenCode returns LocationNotFoundError so the parent can resume and accept prompts.
2026-12-04 12:34:35 +00:00
5 changed files with 182 additions and 16 deletions
@@ -5,6 +5,8 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { DaemonClient } from "../../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import type { AgentLaunchContext, AgentSession, AgentSessionConfig } from "../agent-sdk-types.js";
import { OpenCodeBridge } from "./opencode/bridge.js";
@@ -315,3 +317,122 @@ describe.each<Mode>(["explicit", "discovered"])("OpenCode v2 %s shared service",
expect((await second!.run(afterClose)).finalText).toBe("RESULT HUB_OK_2");
}, 120_000);
});
test("v2 opens the parent timeline and accepts prompts after a child working directory is removed", async () => {
const fixture = await startFixture("explicit");
const { root, project, service, bridge } = fixture;
const childDirectory = path.join(root, "child");
async function connectToDaemon() {
const provider = new OpenCodeV2AgentClient({
logger: createTestLogger(),
bridge,
settings: {
env: {
[EXTERNAL_SERVER_URL_ENV]: service.url,
[EXTERNAL_SERVER_PASSWORD_ENV]: service.password,
},
},
});
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "daemon"),
staticDir: root,
cleanup: false,
agentClients: { opencode: provider },
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const close = async () => {
await client.close();
await daemon.close();
await provider.shutdown();
};
try {
await client.connect();
return { client, close };
} catch (error) {
await close();
throw error;
}
}
function providerHeaders() {
return {
Authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}`,
};
}
function providerClient() {
return OpenCode.make({ baseUrl: service.url, headers: providerHeaders() });
}
let daemon: Awaited<ReturnType<typeof connectToDaemon>> | undefined;
try {
await mkdir(childDirectory);
daemon = await connectToDaemon();
const initialPrompt = scriptedCall("subagent", {
agent: "general",
description: "Create a child session",
prompt: "Say hello",
});
const parent = await daemon.client.createAgent({
cwd: project,
provider: "opencode",
model: SCRIPTED_MODEL,
initialPrompt,
});
expect((await daemon.client.waitForFinish(parent.id, 30_000)).status).toBe("idle");
const persistedParent = await daemon.client.fetchAgent(parent.id);
const parentSessionId = persistedParent?.agent.persistence?.sessionId;
expect(parentSessionId).toBeDefined();
const opencode = providerClient();
const { data: children } = await opencode.session.list({
parentID: parentSessionId,
limit: 100,
});
expect(children).toHaveLength(1);
const childId = children[0]!.id;
await opencode.session.move({ sessionID: childId, directory: childDirectory });
await expect
.poll(async () => (await opencode.session.get({ sessionID: childId })).location.directory)
.toBe(childDirectory);
const readTimeline = (client: DaemonClient) =>
client.fetchAgentTimeline(parent.id, {
direction: "tail",
limit: 0,
projection: "canonical",
});
const before = await readTimeline(daemon.client);
expect(
before.entries.some(
({ item }) => item.type === "user_message" && item.text === initialPrompt,
),
).toBe(true);
await daemon.close();
daemon = undefined;
await rm(childDirectory, { recursive: true });
await service.restart();
expect((await providerClient().session.get({ sessionID: childId })).id).toBe(childId);
const response = await fetch(new URL(`/api/session/${childId}/permission`, service.url), {
headers: providerHeaders(),
});
expect(response.status).toBe(404);
expect(await response.json()).toMatchObject({ _tag: "LocationNotFoundError" });
daemon = await connectToDaemon();
const after = await readTimeline(daemon.client);
expect(after.entries.map(({ item }) => item)).toEqual(before.entries.map(({ item }) => item));
const followUp = scriptedCall("shell", {
command: "printf parent-resumed",
description: "Confirm the parent can run a new turn",
});
await daemon.client.sendMessage(parent.id, followUp);
expect(await daemon.client.waitForFinish(parent.id, 30_000)).toMatchObject({
status: "idle",
lastMessage: expect.stringContaining("parent-resumed"),
});
expect(service.agentRequests.some(({ transcript }) => transcript.includes(followUp))).toBe(
true,
);
} finally {
await daemon?.close();
await stopFixture(fixture);
}
}, 90_000);
@@ -5,6 +5,7 @@ export class OpenCodeHttpError extends Error {
readonly operation: string,
readonly status: number | undefined,
readonly html: boolean,
readonly errorTag?: string,
) {
const statusLabel = status === undefined ? "" : ` (HTTP ${status})`;
super(
@@ -17,6 +18,15 @@ export class OpenCodeHttpError extends Error {
/** True when OpenCode answered 404, directly or as the cause of the client's transport error. */
export function isOpenCodeNotFound(error: unknown): boolean {
return getOpenCodeHttpError(error)?.status === 404;
}
export function isOpenCodeLocationNotFound(error: unknown): boolean {
const failure = getOpenCodeHttpError(error);
return failure?.status === 404 && failure.errorTag === "LocationNotFoundError";
}
function getOpenCodeHttpError(error: unknown): OpenCodeHttpError | undefined {
const failure = error instanceof OpenCodeHttpError ? error : (error as Error | null)?.cause;
return failure instanceof OpenCodeHttpError && failure.status === 404;
return failure instanceof OpenCodeHttpError ? failure : undefined;
}
@@ -47,9 +47,9 @@ export class ScriptedOpenCodeService {
private constructor(
readonly requests: ScriptedRequest[],
readonly root: string,
readonly url: string,
readonly password: string,
private readonly process: ChildProcess,
public url: string,
public password: string,
private process: ChildProcess,
private readonly llm: Server,
) {}
@@ -105,6 +105,26 @@ export class ScriptedOpenCodeService {
}),
);
await options.beforeStart?.({ configDirectory });
try {
const { url, password, child } = await this.launch(root);
return new ScriptedOpenCodeService(requests, root, url, password, child, llm);
} catch (error) {
llm.close();
await rm(root, { recursive: true, force: true });
throw error;
}
}
async restart() {
await this.stopProcess();
await rm(path.join(this.root, "state", "opencode", "service.json"), { force: true });
const { child, url, password } = await ScriptedOpenCodeService.launch(this.root);
this.process = child;
this.url = url;
this.password = password;
}
private static async launch(root: string) {
const child = spawn(
OPENCODE_V2_COMMAND,
["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"],
@@ -124,11 +144,10 @@ export class ScriptedOpenCodeService {
const parsed = content ? (JSON.parse(content) as { url: string; password: string }) : null;
// The service registers before it serves requests.
if (parsed && (await isReady(parsed.url, parsed.password))) {
return new ScriptedOpenCodeService(requests, root, parsed.url, parsed.password, child, llm);
return { ...parsed, child };
}
if (child.exitCode !== null || Date.now() > deadline) {
llm.close();
await rm(root, { recursive: true, force: true });
child.kill();
throw new Error(`OpenCode v2 service did not register (exit ${child.exitCode})`);
}
await delay(100);
@@ -172,10 +191,17 @@ export class ScriptedOpenCodeService {
}
async stop(): Promise<void> {
await this.stopProcess();
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
await rm(this.root, { recursive: true, force: true });
}
private async stopProcess(): Promise<void> {
const exited = new Promise<void>((resolve) => {
if (this.process.exitCode !== null) resolve();
if (this.process.exitCode !== null || this.process.signalCode !== null) resolve();
else this.process.once("exit", () => resolve());
});
if (this.process.exitCode !== null || this.process.signalCode !== null) return;
if (this.process.pid && process.platform !== "win32") {
try {
process.kill(-this.process.pid, "SIGTERM");
@@ -184,9 +210,8 @@ export class ScriptedOpenCodeService {
}
} else this.process.kill("SIGTERM");
await Promise.race([exited, delay(10_000)]);
if (this.process.exitCode === null) this.process.kill("SIGKILL");
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
await rm(this.root, { recursive: true, force: true });
if (this.process.exitCode === null && this.process.signalCode === null)
this.process.kill("SIGKILL");
}
}
@@ -12,6 +12,7 @@ import type { AgentStreamEvent } from "../../../agent-sdk-types.js";
import type { ProviderSubagentInputEvent } from "../../../provider-subagents/store.js";
import { syncTailMessages } from "./history.js";
import { isOpenCodeLocationNotFound } from "../http-error.js";
import { buildOpenCodeSubagentSubtitle } from "../subagent-presentation.js";
import type { V2Api } from "./api.js";
@@ -63,8 +64,8 @@ export class SessionChildren {
try {
await adoptChild(id);
} catch (error) {
if (!isSessionNotFoundError(error)) throw error;
this.remove(id);
if (isSessionNotFoundError(error)) this.remove(id);
else if (!isOpenCodeLocationNotFound(error)) throw error;
}
}
}
@@ -201,10 +202,16 @@ export class SessionChildren {
});
}
private async reconcileChild(info: SessionInfo, parentID: string) {
await this.options.reconcilePermissions(info.id);
let child = this.children.get(info.id);
try {
await this.options.reconcilePermissions(info.id);
if (!child) await this.options.adoptChild?.(info.id);
} catch (error) {
// A child can outlive its worktree. Its runtime cannot be restored until the location returns.
if (isOpenCodeLocationNotFound(error)) return;
throw error;
}
if (!child) {
await this.options.adoptChild?.(info.id);
child = this.children.get(info.id) ?? { parentID, timeline: new V2Timeline(), history: [] };
this.children.set(info.id, child);
}
@@ -9,6 +9,7 @@ export async function validateOpenCodeResponse(
const html = contentType?.includes("text/html") ?? false;
if (response.ok && !html) return response;
let errorTag: string | undefined;
// The SDK needs the original body to decode the provider's missing-session error.
if (response.status === 404 && !html && contentType?.includes("application/json")) {
const body: unknown = await response
@@ -16,8 +17,10 @@ export async function validateOpenCodeResponse(
.json()
.catch(() => null);
if (isSessionNotFoundError(body)) return response;
if (body && typeof body === "object" && "_tag" in body && typeof body._tag === "string")
errorTag = body._tag;
}
const url = request instanceof Request ? request.url : String(request);
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html);
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html, errorTag);
}