A desktop coding agent with free access to frontier models.
TypeScript
fix(engine2): defer location reloads while a session runs
ogsamratc6e5e665be93
diff --git a/apps/server/src/engine2/facade.test.ts b/apps/server/src/engine2/facade.test.tsindex 4a072724..3132c045 100644--- a/apps/server/src/engine2/facade.test.ts+++ b/apps/server/src/engine2/facade.test.ts@@ -20,6 +20,8 @@ let upstream: ReturnType<typeof Bun.serve>;let facade: EngineFacade;let configDir = "";const written: unknown[] = [];+/** Sessions the mock engine reports running (`/api/session/active`). */+let activeSessions: Record<string, unknown> = {};const auth = { authorization: `Basic ${Buffer.from("user:secret").toString("base64")}`, "x-opencode-directory": encodeURIComponent(DIRECTORY) };const get = (path: string) => fetch(`${facade.url}${path}`, { headers: auth });@@ -64,7 +66,7 @@ beforeAll(async () => {const end = start + limit;return json({ data: messages.slice(start, end), cursor: { next: end < messages.length ? btoa(JSON.stringify([order, end])) : null } });}- if (url.pathname === "/api/session/active") return json({ data: {} });+ if (url.pathname === "/api/session/active") return json({ data: activeSessions });if (url.pathname === "/api/session" && request.method === "POST") return json({ data: { ...tree.session, id: "ses_new", title: undefined } });if (url.pathname === "/api/permission/request") {return json({ location: { directory: DIRECTORY }, data: [{ id: "per_1", sessionID: SESSION, action: "shell", resources: ["rm -rf build"], metadata: {} }] });@@ -86,6 +88,7 @@ beforeAll(async () => {writeEngineConfig: async (config) => {written.push(config);},+ reloadPollMs: 50,});});@@ -313,3 +316,53 @@ describe("revert events", () => {expect(out.map((item) => item.event.type)).toEqual(["message.removed", "session.updated"]);});});++describe("location reloads (/instance/dispose)", () => {+ const reloads = () => recorded.filter((entry) => entry.method === "POST" && entry.path === "/api/location/reload").length;+ const waitFor = async (check: () => boolean, ms = 3_000) => {+ const deadline = Date.now() + ms;+ while (!check() && Date.now() < deadline) await Bun.sleep(20);+ return check();+ };++ test("an idle engine reloads at once", async () => {+ activeSessions = {};+ const before = reloads();+ expect((await post("/instance/dispose", {})).status).toBe(200);+ expect(reloads()).toBe(before + 1);+ });++ test("a reload asked while a session runs waits until no session runs", async () => {+ // A 2.x location reload closes every location: the running step's tool+ // calls (a subagent start among them) would be declined with+ // "Interaction cancelled because the location shut down".+ activeSessions = { [SESSION]: { type: "running" } };+ const before = reloads();+ const configsBefore = written.length;+ expect((await post("/instance/dispose", {})).status).toBe(200);+ expect(written.length).toBe(configsBefore + 1); // the config is re-rendered at once+ expect((await post("/instance/dispose", {})).status).toBe(200);+ await Bun.sleep(200);+ expect(reloads()).toBe(before);+ activeSessions = {};+ expect(await waitFor(() => reloads() === before + 1)).toBe(true);+ await Bun.sleep(200);+ expect(reloads()).toBe(before + 1); // both requests are served by one reload+ });++ test("the next prompt runs a deferred reload first once the engine is idle", async () => {+ activeSessions = { other: { type: "running" } };+ const before = reloads();+ expect((await post("/instance/dispose", {})).status).toBe(200);+ activeSessions = {};+ const sent = recorded.length;+ expect((await post(`/session/${SESSION}/prompt_async`, { parts: [{ type: "text", text: "next" }] })).status).toBe(204);+ const after = recorded.slice(sent).map((entry) => `${entry.method} ${entry.path}`);+ const reloadAt = after.indexOf("POST /api/location/reload");+ const promptAt = after.indexOf(`POST /api/session/${SESSION}/prompt`);+ expect(reloadAt).toBeGreaterThanOrEqual(0);+ expect(promptAt).toBeGreaterThan(reloadAt);+ await Bun.sleep(200);+ expect(reloads()).toBe(before + 1);+ });+});diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.tsindex 7a7385fe..956fcec0 100644--- a/apps/server/src/engine2/facade.ts+++ b/apps/server/src/engine2/facade.ts@@ -64,6 +64,8 @@ export type EngineFacadeOptions = {fetch?: typeof globalThis.fetch;/** How long a prompt waits for the engine to serve its model (see ensureModelServed). */modelWaitMs?: number;+ /** How often a location reload deferred behind a running session checks for an idle engine. */+ reloadPollMs?: number;};export type EngineFacade = {@@ -263,6 +265,72 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Eif (options.writeEngineConfig) await options.writeEngineConfig(buildEngine2Config({ v1: v1ConfigCache, apiKeys, plugins: options.plugins }));};+ // ---- location reloads ---------------------------------------------------+ /*+ * `/instance/dispose` is a 2.x `location/reload`, which closes every cached+ * location, not just the requested one. A step running when its location+ * closes keeps the old services, whose permission service now declines+ * every request: each tool call of that step fails with "Interaction+ * cancelled because the location shut down" (a subagent call fails before+ * it creates its child session). So a reload asked while any session runs+ * waits until no session runs: it is retried on a timer, and the next+ * prompt runs it first when the engine is idle by then. The config itself+ * is re-rendered at once; the engine applies config changes live.+ */+ const reloadPollMs = options.reloadPollMs ?? 500;+ let reloadPending = false;+ let reloadTimer: ReturnType<typeof setTimeout> | null = null;+ let reloadChain: Promise<void> = Promise.resolve();+ let facadeClosed = false;+ /** Whether any session runs; an unreadable answer counts as running. */+ const engineBusy = async (): Promise<boolean> => {+ try {+ const active = unwrap(await call("GET", "/api/session/active"));+ return isRecord(active) && Object.keys(active).length > 0;+ } catch {+ return true;+ }+ };+ /** Reloads now; reloads are serialized so a later request never joins one that read older config. */+ const reloadLocations = (directory?: string): Promise<void> => {+ reloadPending = false;+ const run = reloadChain.then(() => call("POST", "/api/location/reload", { directory, body: {} }).then(() => undefined, () => undefined));+ reloadChain = run;+ return run;+ };+ const scheduleDeferredReload = () => {+ if (reloadTimer || facadeClosed) return;+ reloadTimer = setTimeout(() => {+ reloadTimer = null;+ void (async () => {+ if (!reloadPending || facadeClosed) return;+ if (await engineBusy()) {+ scheduleDeferredReload();+ return;+ }+ if (reloadPending) await reloadLocations();+ })();+ }, reloadPollMs);+ reloadTimer.unref?.();+ };+ /** `/instance/dispose`: reloads now when no session runs, else once none does. */+ const requestLocationReload = async (directory: string): Promise<"reloaded" | "deferred"> => {+ if (await engineBusy()) {+ if (!reloadPending) log("location reload deferred while a session runs", { directory });+ reloadPending = true;+ scheduleDeferredReload();+ return "deferred";+ }+ await reloadLocations(directory);+ return "reloaded";+ };+ /** Before a prompt: a deferred reload runs now if the engine went idle. */+ const settleDeferredReload = async (): Promise<void> => {+ if (!reloadPending) return;+ if (await engineBusy()) return;+ if (reloadPending) await reloadLocations();+ };+// ---- sessions & messages -----------------------------------------------const sessionInfo = async (sessionID: string, directory?: string): Promise<JsonRecord | null> => {const info = v1Session(await call("GET", `/api/session/${encodeURIComponent(sessionID)}`), { version: options.version, directory });@@ -491,6 +559,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E/** Applies a 1.x prompt's model, agent and system prompt to the session before it is sent. */const prepareSession = async (sessionID: string, body: JsonRecord, directory: string): Promise<void> => {+ await settleDeferredReload();const current = selected.get(sessionID) ?? {};const model = modelRefFromBody(body);if (model) {@@ -934,6 +1003,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Ecase "shell": {if (method !== "POST") break;const body = ((await readBody(req)) ?? {}) as JsonRecord;+ await settleDeferredReload();await commitRevert(encoded);await call("POST", `/api/session/${encoded}/shell`, { body: { command: String(body.command ?? "") } });json(res, 200, { id: "", sessionID, role: "assistant" });@@ -1318,7 +1388,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E}if (method === "POST" && (path === "/instance/dispose" || path === "/global/dispose")) {await refreshConfig();- await call("POST", "/api/location/reload", { directory: dir, body: {} }).catch(() => undefined);+ await requestLocationReload(dir);json(res, 200, true);return;}@@ -1370,6 +1440,9 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Eurl,refreshConfig,close: async () => {+ facadeClosed = true;+ if (reloadTimer) clearTimeout(reloadTimer);+ reloadTimer = null;streamController.abort();// Event streams stay open until ended; end them so the server can close.for (const subscriber of subscribers) {diff --git a/apps/server/src/engine2/subagent-location-reload.e2e.test.ts b/apps/server/src/engine2/subagent-location-reload.e2e.test.tsnew file mode 100644index 00000000..2813fb09--- /dev/null+++ b/apps/server/src/engine2/subagent-location-reload.e2e.test.ts@@ -0,0 +1,167 @@+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import { createManagedOpencodeServer, type ManagedOpencodeServer } from "../managed-opencode.js";+import { buildOmniRushRuntimeConfigObjectFromSnapshot } from "../omnirush-runtime-config.js";++/**+ * A reload (`/instance/dispose`) that lands while the model is still writing+ * the reply that starts a sub-agent, on the real 2.x engine (the bundled+ * sidecar behind the 1.x adapter) with the desktop's runtime config and a+ * mock provider.+ *+ * A 2.x location reload closes the location under the running step, and+ * every tool call of that step is then declined with "Interaction cancelled+ * because the location shut down": the subagent call failed before it made+ * its child session. The adapter now defers the reload until no session+ * runs, so the sub-agent starts as a child of the main session.+ *+ * Skipped when the sidecar binary is not present (prepare:sidecar not run).+ */++const repoRoot = resolve(import.meta.dir, "../../../..");+const sidecarDir = join(repoRoot, "apps/desktop/resources/sidecars");+function findSidecar(): string | null {+ const arch = process.arch === "arm64" ? "aarch64" : "x86_64";+ const name = process.platform === "darwin" ? `opencode-${arch}-apple-darwin` : process.platform === "linux" ? `opencode-${arch}-unknown-linux-gnu` : "";+ const candidate = join(sidecarDir, name);+ return name && existsSync(candidate) ? candidate : null;+}+const enginePath = findSidecar();+const describeMaybe = enginePath ? describe : describe.skip;++type Body = { messages?: Array<{ role: string; content: unknown }>; tools?: Array<{ type: string; function: { name: string } }> };+type V1Part = { type: string; tool?: string; text?: string; state?: { status?: string; error?: string; output?: string } };+type V1Message = { info: { id: string; role: string; time?: { completed?: number } }; parts: V1Part[] };++const CHILD_MARK = "CHILD-RELOAD-51c2";++function text(content: unknown): string {+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content.map((part) => (part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "")).join("\n");+}+function sse(chunks: object[]): Response {+ const frame = (payload: object) => `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m", ...payload })}\n\n`;+ const body = chunks.map((choice) => frame({ choices: [choice] })).join("")+ + frame({ choices: [], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } })+ + "data: [DONE]\n\n";+ return new Response(body, { headers: { "content-type": "text/event-stream" } });+}+const say = (content: string) => sse([{ index: 0, delta: { role: "assistant", content } }, { index: 0, delta: {}, finish_reason: "stop" }]);+const callSubagent = () => sse([+ { index: 0, delta: { role: "assistant", content: "" } },+ { index: 0, delta: { tool_calls: [{ index: 0, id: "call_sub_1", type: "function", function: { name: "subagent", arguments: JSON.stringify({ agent: "general", description: "Inspect", prompt: `${CHILD_MARK}: reply with one word.` }) } }] } },+ { index: 0, delta: {}, finish_reason: "tool_calls" },+]);++describeMaybe("a reload while a sub-agent starts (2.x engine, mock provider)", () => {+ let engine: ManagedOpencodeServer;+ let provider: ReturnType<typeof Bun.serve>;+ let work = "";+ let data = "";+ /** Set while the mock provider holds the main reply that starts the sub-agent. */+ let mainReplyHeld = false;++ const engineFetch = async (path: string, init?: RequestInit) => {+ const headers = new Headers(init?.headers);+ headers.set("authorization", `Basic ${Buffer.from(`${engine.username}:${engine.password}`).toString("base64")}`);+ headers.set("x-opencode-directory", encodeURIComponent(work));+ if (init?.body) headers.set("content-type", "application/json");+ return fetch(`${engine.url}${path}`, { ...init, headers });+ };+ const getJson = async <T>(path: string): Promise<T> => (await (await engineFetch(path)).json()) as T;+ const waitFor = async <T>(read: () => Promise<T | null | undefined | false> | T | null | undefined | false, label: string, ms = 60_000): Promise<T> => {+ const deadline = Date.now() + ms;+ while (Date.now() < deadline) {+ const value = await Promise.resolve(read()).catch(() => null);+ if (value) return value as T;+ await Bun.sleep(100);+ }+ throw new Error(`timed out waiting for ${label}`);+ };++ beforeAll(async () => {+ work = mkdtempSync(join(tmpdir(), "subagent-reload-ws-"));+ data = mkdtempSync(join(tmpdir(), "subagent-reload-data-"));+ provider = Bun.serve({+ port: 0,+ async fetch(request) {+ const url = new URL(request.url);+ const body = request.method === "POST" ? ((await request.json().catch(() => ({}))) as Body) : {};+ if (url.pathname.startsWith("/managed-policy")) return Response.json({ allowed: true, approvalMode: "guarded" });+ if (!url.pathname.startsWith("/v1/")) return Response.json({});+ if (!Array.isArray(body.tools) || body.tools.length === 0) return say("Reload title");+ const messages = body.messages ?? [];+ if (messages.some((message) => message.role === "user" && text(message.content).includes(CHILD_MARK))) return say("child done");+ if (messages.at(-1)?.role === "tool") return say("All done.");+ mainReplyHeld = true;+ await Bun.sleep(2_500);+ mainReplyHeld = false;+ return callSubagent();+ },+ });+ const base = `http://127.0.0.1:${provider.port}`;+ // The desktop's own runtime config (guarded approvals, the omnirush agent and plugins) with a mock provider.+ const config = buildOmniRushRuntimeConfigObjectFromSnapshot({+ provider: {+ mock: { name: "Mock", npm: "@ai-sdk/openai-compatible", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "mock-model": { name: "Mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },+ },+ }, undefined, {});+ const configPath = join(data, "runtime-opencode-config.json");+ writeFileSync(configPath, JSON.stringify({ ...config, model: "mock/mock-model" }));+ engine = await createManagedOpencodeServer({+ bin: enginePath!,+ cwd: work,+ env: {+ OPENCODE_CONFIG: configPath,+ OPENCODE_DISABLE_MODELS_FETCH: "1",+ OMNIRUSH_ENGINE2_CONFIG_DIR: join(data, "engine2"),+ OMNIRUSH_SERVER_URL: base,+ OMNIRUSH_POLICY_TOKEN: "policy",+ OMNIRUSH_SERVER_TOKEN: "server",+ HOME: join(data, "home"),+ OPENCODE_TEST_HOME: join(data, "home"),+ XDG_DATA_HOME: join(data, "xdg-data"),+ XDG_CONFIG_HOME: join(data, "xdg-config"),+ XDG_STATE_HOME: join(data, "xdg-state"),+ XDG_CACHE_HOME: join(data, "xdg-cache"),+ },+ });+ await waitFor(async () => (await engineFetch("/session")).ok, "engine");+ }, 120_000);++ afterAll(async () => {+ await engine?.close();+ provider?.stop(true);+ rmSync(work, { recursive: true, force: true });+ rmSync(data, { recursive: true, force: true });+ }, 30_000);++ test("the sub-agent starts as a child session and its task completes", async () => {+ const session = (await (await engineFetch("/session", { method: "POST", body: "{}" })).json()) as { id: string };+ const sent = await engineFetch(`/session/${session.id}/prompt_async`, { method: "POST", body: JSON.stringify({ parts: [{ type: "text", text: "inspect it" }] }) });+ expect(sent.status).toBe(204);++ await waitFor(() => mainReplyHeld, "the main reply");+ await Bun.sleep(300);+ // What a provider sync, a skill change or an idle sweep sends mid-turn.+ expect((await engineFetch("/instance/dispose", { method: "POST" })).status).toBe(200);++ const done = await waitFor(async () => {+ const list = await getJson<V1Message[]>(`/session/${session.id}/message`);+ const last = list.at(-1);+ return last?.info.role === "assistant" && last.info.time?.completed && last.parts.some((part) => part.type === "text" && part.text === "All done.") ? list : null;+ }, "the main turn");+ const task = done.flatMap((message) => message.parts).find((part) => part.type === "tool" && part.tool === "task");+ expect(task?.state?.error ?? "").not.toContain("location shut down");+ expect(task?.state?.status).toBe("completed");+ expect(task?.state?.output ?? "").toContain("child done");++ const sessions = await getJson<Array<{ id: string; parentID?: string }>>("/session");+ const children = sessions.filter((entry) => entry.parentID === session.id);+ expect(children).toHaveLength(1);+ }, 120_000);+});