A desktop coding agent with free access to frontier models.
TypeScript
fix: sandbox gc keeps boxes it does not own and restarts replaced folders
ogsamrat09b93c9add93
diff --git a/apps/server/src/box/box-ownership.test.ts b/apps/server/src/box/box-ownership.test.tsnew file mode 100644index 00000000..a3f73c72--- /dev/null+++ b/apps/server/src/box/box-ownership.test.ts@@ -0,0 +1,61 @@+// Ported from the CLI (omnirush-cli #216, #217): a box whose folder was replaced+// is restarted, and gc removes only this home's own boxes no other live process uses.+import { describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { gcBoxes, mountReplaced } from "./box.js";++const DAY = 86_400_000;++describe("gcBoxes", () => {+ test("removes only this home's own boxes no other process uses; never another user's, even when its folder looks gone", async () => {+ const home = mkdtempSync(join(tmpdir(), "box-gc-"));+ mkdirSync(join(home, "boxes"), { recursive: true });+ const now = Date.now();+ const dead = 2 ** 22 + 12345;+ const boxes: Record<string, { root: string; rec: Record<string, unknown> | null }> = {+ gone: { root: "/home/me/deleted", rec: { updated: now, pid: dead } },+ idle: { root: "/home/me/old", rec: { updated: now - 40 * DAY, pid: dead } },+ fresh: { root: "/home/me/live", rec: { updated: now, pid: dead } },+ mine: { root: "/home/me/gone-mine", rec: { updated: now, pid: process.pid } },+ other: { root: "/home/alice/proj", rec: null },+ moved: { root: "/home/bob/same-key", rec: { root: "/home/me/elsewhere", updated: now - 40 * DAY, pid: dead } },+ };+ for (const [key, b] of Object.entries(boxes)) {+ if (b.rec) writeFileSync(join(home, "boxes", `${key}.json`), JSON.stringify({ key, root: (b.rec.root as string | undefined) ?? b.root, ...b.rec }));+ }+ const removed: string[] = [];+ const run = async (_bin: string, args: string[]) => {+ if (args[0] === "ps") return { code: 0, stdout: Object.entries(boxes).map(([key, b]) => JSON.stringify({ Names: `omnirush-box-${key}`, Labels: `ai.omnirush.box=1,ai.omnirush.box.key=${key},ai.omnirush.box.root=${b.root}`, Status: "Up 3 hours", Image: "ghcr.io/omnirush-ai/box-base@sha256:x" })).join("\n"), stderr: "" };+ if (args[0] === "rm") { removed.push(String(args.at(-1))); return { code: 0, stdout: "", stderr: "" }; }+ if (args[0] === "images") return { code: 0, stdout: "", stderr: "" };+ return { code: 1, stdout: "", stderr: "unexpected" };+ };+ const exists = (p: string) => !["/home/me/deleted", "/home/me/gone-mine", "/home/alice/proj", "/home/bob/same-key"].includes(p);+ // The desktop's own records carry its own pid: a folder of its own that is gone is still collected.+ const out = await gcBoxes({ name: "docker", backend: "docker", bin: "docker" } as never, { home, run: run as never, exists, now, pins: { images: {} } as never });+ expect(removed.sort()).toEqual(["omnirush-box-gone", "omnirush-box-idle", "omnirush-box-mine"]);+ expect(out.map((r) => `${r.name}:${r.reason}`).sort()).toEqual(["omnirush-box-gone:folder gone", "omnirush-box-idle:unused", "omnirush-box-mine:folder gone"]);+ });+});++describe("mountReplaced", () => {+ const opened = { endpoint: { host: "127.0.0.1", port: 1, token: "t" } };+ const ping = (async () => ({ uid: 1000 })) as never;++ test("a project folder with no links left (deleted, made again) is replaced; asked from /", async () => {+ const seen: Array<{ argv: string[]; cwd?: string }> = [];+ const exec = (async (_way: unknown, argv: string[], opts: { cwd?: string }) => { seen.push({ argv, cwd: opts.cwd }); return { code: 0, stdout: "0\n", stderr: "" }; }) as never;+ expect(await mountReplaced(opened as never, { croot: "/home/u/proj", exec, ping })).toBe(true);+ expect(seen).toEqual([{ argv: ["stat", "-c", "%h", "/home/u/proj"], cwd: "/" }]);+ });++ test("a live folder, a failed stat or no answer is not replaced", async () => {+ expect(await mountReplaced(opened as never, { croot: "/p", exec: (async () => ({ code: 0, stdout: "2\n", stderr: "" })) as never, ping })).toBe(false);+ expect(await mountReplaced(opened as never, { croot: "/p", exec: (async () => ({ code: 1, stdout: "", stderr: "x" })) as never, ping })).toBe(false);+ expect(await mountReplaced(opened as never, { croot: "/p", exec: (async () => { throw new Error("closed"); }) as never, ping })).toBe(false);+ expect(await mountReplaced(opened as never, { croot: "/p", exec: (async () => ({ code: 0, stdout: "0", stderr: "" })) as never, ping: (async () => null) as never, readyMs: 120 })).toBe(false);+ });+});diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.tsindex 3af2e2c9..dfa8e4f1 100644--- a/apps/server/src/box/box.ts+++ b/apps/server/src/box/box.ts@@ -211,8 +211,16 @@ export async function openBox({ root, runtime, env = process.env, platform = protry {box.setState("starting", null, onState);const chosen = asked ?? imageFor(detectStack(projectRoot), { env });- const opened = await driver.open({ key, name, root: projectRoot, croot, runtime, run, home, runFolder, image: chosen, pull, shims, pkglog, env, platform, log, ...(spawnImpl ? { spawnImpl } : {}), ...(onLine ? { onLine } : {}), onPulling: () => box.setState("pulling", null, onState) });- if (!opened.ok) return box.fail(opened.error, onState);+ let opened: Awaited<ReturnType<typeof driver.open>>;+ for (let attempt = 0; ; attempt += 1) {+ opened = await driver.open({ key, name, root: projectRoot, croot, runtime, run, home, runFolder, image: chosen, pull, shims, pkglog, env, platform, log, ...(spawnImpl ? { spawnImpl } : {}), ...(onLine ? { onLine } : {}), onPulling: () => box.setState("pulling", null, onState) });+ if (!opened.ok) return box.fail(opened.error, onState);+ if (opened.created || attempt > 0 || !(await mountReplaced(opened, { croot, readyMs }))) break;+ // The folder was deleted and made again at its path (a new clone) while its box ran:+ // the box still has the old, deleted one, where every command fails. A restart mounts the new one.+ log("info", "box restarted: its folder was replaced since it started", { key });+ await driver.stop(runtime, key, { run, env, home });+ }if (opened.created) writeJson(path.join(home, "chains", key, "image.json"), { ...opened.created, backend: runtime.backend ?? runtime.name, created_at: new Date().toISOString() });// The first address that answers: the published/loopback one, then the box's own (Apple, WSL any).const ways = [opened.endpoint, ...(opened.alternates ?? [])];@@ -264,6 +272,30 @@ async function acquireLock(home: string, key: string, { waitMs = 60_000 }: { wai}}+/**+ * Whether the box's project folder is a deleted one (link count 0): the+ * folder on this machine was removed and made again since the box started.+ * Asks boxd at the first address that answers; false when it cannot tell.+ */+export async function mountReplaced(opened: { endpoint?: BoxEndpoint; alternates?: BoxEndpoint[] }, { croot, readyMs = 15_000, exec = client.exec, ping = client.ping }: { croot: string; readyMs?: number; exec?: typeof client.exec; ping?: typeof client.ping }): Promise<boolean> {+ for (const way of [opened.endpoint, ...(opened.alternates ?? [])]) {+ if (!way) continue;+ const deadline = Date.now() + Math.min(readyMs, 5_000);+ while (Date.now() < deadline) {+ if (await ping(way, { timeoutMs: 1_000 })) {+ try {+ const res = await exec(way, ["stat", "-c", "%h", croot], { cwd: "/", timeoutMs: 5_000 });+ return res.code === 0 && String(res.stdout).trim() === "0";+ } catch {+ return false;+ }+ }+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ }+ return false;+}+function alive(pid: number): boolean {try { process.kill(pid, 0); return true; } catch (error) { return typeof error === "object" && error !== null && "code" in error && error.code === "EPERM"; }}@@ -680,8 +712,11 @@ export async function gcBoxes(runtime: BoxRuntime, { env = process.env, home = bconst removed: Removed = [];const boxes = await driver.list(runtime, { run, env, home });for (const box of boxes) {+ // Only this box home's own boxes (the ones it has a record of), never one another live process uses:+ // a shared engine (rootful Docker) lists every user's boxes, and another user's folder can look gone here.const rec = readRecord(home, box.key);- const idle = rec?.updated ? (now - rec.updated) / 86_400_000 : Infinity;+ if (!rec || (rec.pid && rec.pid !== process.pid && alive(rec.pid)) || (rec.root && box.root && path.resolve(rec.root) !== path.resolve(box.root))) continue;+ const idle = rec.updated ? (now - rec.updated) / 86_400_000 : Infinity;if ((box.root && !exists(box.root)) || idle > maxIdleDays) {const res = await driver.remove(runtime, box.key, { run, env, home });if (res.removed) {