Compare commits

..
3 Commits
Author SHA1 Message Date
paseo-bot[bot] 175d858e05 test(server): stop terminal fixtures that outlive a crashed worker (#10540)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-23 00:22:43 +00:00
112c4b78e1 Reopen OpenCode sessions after tool definitions change (#10533)
* fix(opencode): replace stale bridge tool definitions instead of failing the bind

The shared bridge plugin keeps tool definitions in an in-memory cache
(state.mjs) that survives OpenCode's plugin reloads. When the Paseo daemon
upgrades and ships a changed tool definition (e.g. the description or input
schema changes), the next bind finds a signature mismatch and throws
"Conflicting Paseo tool definition", leaving every existing session in that
location unable to rebind. This is the upgrade path: the bridge changed, not
a second live bridge.

Treat a changed definition as a refresh, not a conflict: dispose the stale
registration and re-register the new one. Track the whole installed manifest
per location and reconcile on each bind so removed tools also disappear,
instead of letting the first per-tool difference fail the bind.

Add tests covering a definition upgrade (bind succeeds, tool reflects the
new schema) and a manifest drift (a removed tool leaves the registry).

* fix(opencode): resume sessions after bridge tool definitions change

A retired bridge can leave tool definitions cached in a shared OpenCode location. Replace a conflicting definition once the bound sessions confirm that it is unused. Preserve tools that other live sessions still use.

Co-authored-by: Peanut-HZM <34237301+Peanut-HZM@users.noreply.github.com>

* test(server): wait for the worktree manager ready marker

The marker confirms that the plugin entered the create hook. Give the hook the same deadline as the other worktree fixture handshakes, and observe the pending request if teardown closes the client.

---------

Co-authored-by: huazhongmin <peanut_hzm@163.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Peanut-HZM <34237301+Peanut-HZM@users.noreply.github.com>
2026-11-22 19:49:03 +00:00
Mohamed Boudra 8d287e5f56 chore(release): reconcile v0.17.3 (#10535) 2026-11-23 00:50:37 +07:00
4 changed files with 252 additions and 46 deletions
@@ -23,8 +23,8 @@ export async function registerSharedBridge(context) {
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
if (allowMissing && response.status === 404) return null;
const payload = await response.json().catch(() => null);
if (!response.ok) {
const payload = await response.json().catch(() => null);
const detail = formatErrorDetail(payload?.issues ?? payload?.details);
const message = payload?.error ?? `Paseo tool bridge returned HTTP ${response.status}`;
const error = new Error(detail ? `${message}: ${detail}` : message);
@@ -32,7 +32,7 @@ export async function registerSharedBridge(context) {
if (detail) error.details = detail;
throw error;
}
return payload;
return await response.json();
}
async function find(sessionID) {
const seen = new Set();
@@ -44,24 +44,56 @@ export async function registerSharedBridge(context) {
}
return null;
}
async function readBoundContext(sessionID, binding, query = "") {
try {
return await request(
binding,
`/sessions/${encodeURIComponent(sessionID)}/context${query}`,
undefined,
true,
);
} catch (error) {
// A refusal or rejected credentials means this bridge no longer serves the binding.
if (error?.status !== 401 && !isRefused(error)) throw error;
return null;
}
}
async function install(binding) {
const manifest = await request(
binding,
`/tools?sessionID=${encodeURIComponent(binding.sessionID)}`,
);
const conflicts = manifest.tools.filter((tool) => {
const registered = definitions.get(tool.name);
return registered && JSON.stringify(registered) !== JSON.stringify(tool);
});
if (conflicts.length > 0) await retireUnusedDefinitions(conflicts);
for (const definition of manifest.tools) await installDefinition(definition);
}
async function installDefinition(definition) {
const signature = JSON.stringify(definition);
const known = definitions.get(definition.name);
if (known && JSON.stringify(known) !== signature)
throw new Error(`Conflicting Paseo tool definition: ${definition.name}`);
const old = registrations.get(definition.name);
if (old) {
if (old.signature !== signature)
throw new Error(`Conflicting Paseo tool definition: ${definition.name}`);
return;
async function retireUnusedDefinitions(conflicts) {
// A tool name is registered once per location. Another session can still
// use that definition, even when the session being rebound no longer does.
const contexts = await Promise.all(
[...bindings].map(async ([sessionID, binding]) => [
sessionID,
await readBoundContext(sessionID, binding, "?tools"),
]),
);
const inUse = new Set(contexts.flatMap(([, scope]) => (scope ? scope.tools : [])));
for (const { name } of conflicts) {
if (inUse.has(name)) throw new Error(`Conflicting Paseo tool definition: ${name}`);
}
for (const [sessionID, scope] of contexts) {
if (!scope) bindings.delete(sessionID);
}
for (const { name } of conflicts) {
await registrations.get(name)?.dispose();
registrations.delete(name);
definitions.delete(name);
}
}
async function installDefinition(definition) {
if (registrations.has(definition.name)) return;
const registration = await context.tool.transform((editor) => {
editor.add({
name: `paseo_${definition.name}`,
@@ -85,14 +117,12 @@ export async function registerSharedBridge(context) {
},
});
});
registrations.set(definition.name, { signature, registration });
registrations.set(definition.name, registration);
definitions.set(definition.name, definition);
}
async function clearUnusedDefinitions() {
if (bindings.size) return;
await Promise.all(
[...registrations.values()].map(({ registration }) => registration.dispose()),
);
await Promise.all([...registrations.values()].map((registration) => registration.dispose()));
registrations.clear();
definitions.clear();
}
@@ -126,19 +156,7 @@ export async function registerSharedBridge(context) {
previous &&
(previous.baseUrl !== input.baseUrl || previous.token !== input.token)
) {
let active;
try {
active = await request(
previous,
`/sessions/${encodeURIComponent(input.sessionID)}/context`,
undefined,
true,
);
} catch (error) {
// Refusal or rejected credentials mean this endpoint no longer
// serves the previous binding. Other failures are inconclusive.
if (error?.status !== 401 && !isRefused(error)) throw error;
}
const active = await readBoundContext(input.sessionID, previous);
if (active)
return { error: "OpenCode session is already bound to another Paseo bridge" };
bindings.delete(input.sessionID);
@@ -189,9 +207,7 @@ export async function registerSharedBridge(context) {
return async () => {
await filter.dispose();
await rpc.dispose();
await Promise.all(
[...registrations.values()].map(({ registration }) => registration.dispose()),
);
await Promise.all([...registrations.values()].map((registration) => registration.dispose()));
};
}
@@ -18,6 +18,11 @@ interface TestTool {
name: string;
execute(input: { value: string }, call: { sessionID: string }): Promise<unknown>;
}
interface ToolDefinition {
name: string;
description: string;
}
interface TestContext {
sessionID: string;
tools: Record<string, unknown>;
@@ -232,6 +237,147 @@ test("a shared plugin rebinds a session after the previous bridge stops listenin
}
});
function addSession(
bridge: OpenCodeBridge,
sessionId: string,
descriptions: Record<string, string>,
) {
const tools = new Map(
Object.entries(descriptions).map(([name, description]) => [
name,
{ name, description, inputSchema: { value: z.string() } },
]),
);
return bridge.bindSession({
sessionId,
env: {},
tools: {
tools,
getTool: (name) => tools.get(name),
executeTool: async () => ({ content: [] }),
},
});
}
async function registerAtLocation(bridge: OpenCodeBridge, home: string) {
const pluginPath = fileURLToPath(await bridge.materializeV2Plugin());
const plugin = await import(pathToFileURL(path.join(pluginPath, "server.js")).href);
const tools: Record<string, ToolDefinition> = {};
const hooks: Array<(context: TestContext) => Promise<void>> = [];
let rpc: Record<string, (input: Binding) => Promise<unknown>> = {};
const dispose = await plugin.default.setup({
options: {},
location: { directory: home },
rpc: {
register: async (_definition: unknown, handlers: typeof rpc) => {
rpc = handlers;
return { dispose: async () => {} };
},
},
tool: {
transform: async (apply: (editor: { add(item: ToolDefinition): void }) => void) => {
const added: string[] = [];
apply({
add: (item) => {
added.push(item.name);
tools[item.name] = item;
},
});
return {
dispose: async () => {
for (const name of added) delete tools[name];
},
};
},
},
session: {
context: async () => [],
get: async () => ({ parentID: "" }),
hook: async (event: string, handler: (context: TestContext) => Promise<void>) => {
if (event === "context") hooks.push(handler);
return { dispose: async () => {} };
},
},
});
return {
bind: (owner: OpenCodeBridge, sessionID: string) =>
rpc.bind!({ sessionID, ...owner.sharedV2Connection() }),
visible: async (sessionID: string) => {
const context = { sessionID, tools: { ...tools }, system: [] };
for (const hook of hooks) await hook(context);
return context.tools;
},
dispose,
};
}
test.each([false, true])(
"rebinds an existing session after an owner stops and its definition changes (second retained session: %s)",
async (second) => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-upgrade-repro-"));
const old = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
const peer = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
const next = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
let location: Awaited<ReturnType<typeof registerAtLocation>> | undefined;
try {
await old.start();
addSession(old, "first", { echo: "echo v1" });
location = await registerAtLocation(old, home);
await location.bind(old, "first");
expect(await location.visible("first")).toHaveProperty("paseo_echo.description", "echo v1");
if (second) {
addSession(old, "second", { echo: "echo v1" });
await location.bind(old, "second");
}
await peer.start();
addSession(peer, "peer", { extra: "extra" });
await location.bind(peer, "peer");
// The OpenCode location survives, while the old daemon's HTTP service stops.
await old.close();
await next.start();
addSession(next, "first", { echo: "echo v2" });
await expect(location.bind(next, "first")).resolves.toEqual({});
expect(await location.visible("first")).toHaveProperty("paseo_echo.description", "echo v2");
expect(await location.visible("peer")).toHaveProperty("paseo_extra");
} finally {
await location?.dispose();
await old.close();
await next.close();
await peer.close();
await rm(home, { recursive: true, force: true });
}
},
);
test("binding another session at the same location preserves the first session's tools", async () => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-upgrade-scope-repro-"));
const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
let location: Awaited<ReturnType<typeof registerAtLocation>> | undefined;
try {
await bridge.start();
addSession(bridge, "first", { echo: "echo", extra: "extra" });
addSession(bridge, "second", { echo: "echo" });
location = await registerAtLocation(bridge, home);
await location.bind(bridge, "first");
expect(await location.visible("first")).toHaveProperty("paseo_extra");
await location.bind(bridge, "second");
expect(await location.visible("second")).not.toHaveProperty("paseo_extra");
expect(await location.visible("first")).toHaveProperty("paseo_extra");
addSession(bridge, "conflict", { echo: "echo different" });
await expect(location.bind(bridge, "conflict")).rejects.toThrow(
"Conflicting Paseo tool definition: echo",
);
expect(await location.visible("first")).toHaveProperty("paseo_echo.description", "echo");
} finally {
await location?.dispose();
await bridge.close();
await rm(home, { recursive: true, force: true });
}
});
test("a refused connection is the only probe failure that clears a binding", async () => {
const source = new URL("./shared-bridge-plugin.mjs", import.meta.url).href;
const { isRefused } = (await import(source)) as { isRefused: (error: unknown) => boolean };
@@ -606,12 +606,16 @@ 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
.poll(() =>
stat(path.join(root, "manager-started")).then(
() => true,
() => false,
),
.poll(
() =>
stat(path.join(root, "manager-started")).then(
() => true,
() => false,
),
{ timeout: 10_000 },
)
.toBe(true);
const concurrent = path.join(root, "concurrent-manual");
@@ -88,6 +88,20 @@ function nodeTerminalCommand(script: string): { command: string; args: string[]
};
}
const terminalStopFile = ".test-terminal-stop";
const terminalStopDirectories = new Set<string>();
function terminalCommandWithStopFile(cwd: string, script = "") {
terminalStopDirectories.add(cwd);
return nodeTerminalCommand(`
${script}
const { existsSync } = require('node:fs');
setInterval(() => {
if (existsSync('${terminalStopFile}')) process.exit(0);
}, 50);
`);
}
async function waitForCondition(
predicate: () => boolean | Promise<boolean>,
timeoutMs: number,
@@ -217,9 +231,8 @@ function trackTerminal(session: TerminalSession): TerminalSession {
return session;
}
// Processes of workers a test killed. On Windows a killed worker's terminal programs end only
// once its console closes, a moment later, and a temporary dir that is still a live program's
// cwd cannot be removed. afterEach waits for them before it removes the dirs.
// A forcibly stopped worker can leave a terminal program alive with a temporary
// directory as its cwd. Remember the processes until teardown confirms they exited.
const crashedWorkerProcesses: number[] = [];
function crashWorker(record: TerminalWorkerRecord): void {
@@ -255,6 +268,11 @@ afterEach(async () => {
);
await manager?.closeTerminals();
manager = null;
// The stop file reaches fixtures even if the worker and its PTY connection are gone.
for (const cwd of terminalStopDirectories) {
writeFileSync(join(cwd, terminalStopFile), "");
}
terminalStopDirectories.clear();
const crashed = crashedWorkerProcesses.splice(0);
await waitForCondition(() => !crashed.some(isProcessAlive), 10000);
while (temporaryDirs.length > 0) {
@@ -265,6 +283,27 @@ afterEach(async () => {
}
});
it("teardown stops a terminal fixture without a worker connection", async () => {
const cwd = createTemporaryHome();
// Bound the child lifetime if teardown fails to deliver the stop file.
const command = terminalCommandWithStopFile(
cwd,
"process.send('ready'); setTimeout(() => process.exit(0), 15000);",
);
const child = spawn(command.command, command.args, {
cwd,
stdio: ["ignore", "ignore", "ignore", "ipc"],
});
await new Promise<void>((resolve, reject) => {
child.once("message", () => resolve());
child.once("error", reject);
child.once("exit", (code) =>
reject(new Error(`Terminal fixture exited before ready: ${code}`)),
);
});
crashedWorkerProcesses.push(child.pid!);
});
it("retires a killed worker's sessions and shares one replacement across concurrent creates", async () => {
const paseoHome = createTemporaryHome();
manager = await startRealWorkerManager({ paseoHome });
@@ -272,8 +311,9 @@ it("retires a killed worker's sessions and shares one replacement across concurr
const terminal = await manager.createTerminal({
workspaceId: "ws-recovery",
cwd: paseoHome,
...nodeTerminalCommand(
"process.stdin.on('data', chunk => process.stdout.write('echo:' + process.env.QA_RECOVERY_ENV + ':' + chunk)); setInterval(() => {}, 1000)",
...terminalCommandWithStopFile(
paseoHome,
"process.stdin.on('data', chunk => process.stdout.write('echo:' + process.env.QA_RECOVERY_ENV + ':' + chunk));",
),
});
const records = await listTerminalWorkerRecords(paseoHome);
@@ -364,7 +404,7 @@ it.each(["detach", "closeTerminals"] as const)(
await manager.createTerminal({
workspaceId: "ws-stop-recovery",
cwd: paseoHome,
...nodeTerminalCommand("setInterval(() => {}, 1000)"),
...terminalCommandWithStopFile(paseoHome),
});
const [record] = await workerRecords(paseoHome);
crashWorker(record!);
@@ -386,7 +426,7 @@ it.each(["detach", "closeTerminals"] as const)(
const terminal = await manager.createTerminal({
workspaceId: "ws-launch-race",
cwd: paseoHome,
...nodeTerminalCommand("setInterval(() => {}, 1000)"),
...terminalCommandWithStopFile(paseoHome),
});
const [record] = await workerRecords(paseoHome);
crashWorker(record!);
@@ -416,7 +456,7 @@ it.each(["current", "draining"] as const)(
const added = await manager.createTerminal({
workspaceId: "ws-peer",
cwd: seed.cwd,
...nodeTerminalCommand("setInterval(() => {}, 1000)"),
...terminalCommandWithStopFile(seed.cwd),
});
const records = await workerRecords(paseoHome);
const current = records.find((record) =>
@@ -1737,7 +1777,7 @@ async function launchDetachedWorkerWithTerminal(
const session = await worker.createTerminal({
workspaceId: "ws-detached",
cwd,
...nodeTerminalCommand("setInterval(() => {}, 1000);"),
...terminalCommandWithStopFile(cwd),
});
await worker.detach();
return { terminalId: session.id, workerPid: launched.record.pid, cwd };