Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: required sandbox for new chats

ogsamrata72f929ec4b0
diff --git a/apps/server/src/box/box-required-service.test.ts b/apps/server/src/box/box-required-service.test.ts
new file mode 100644
index 00000000..ff9b05ea
--- /dev/null
+++ b/apps/server/src/box/box-required-service.test.ts
@@ -0,0 +1,192 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { boxKey, setToolsRoot } from "./box.js";
+import { rememberServerDefault, resolveMode, serverRequired, type BoxRun } from "./launch.js";
+import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";
+import { BoxRequiredError, BoxService, type BoxWorkspace } from "./service.js";
+
+const dirs: string[] = [];
+afterEach(async () => {
+ setToolsRoot(null);
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
+});
+
+async function temp(name: string): Promise<string> {
+ const dir = await mkdtemp(join(tmpdir(), `omnirush-boxreq-${name}-`));
+ dirs.push(dir);
+ return dir;
+}
+
+type Settings = Map<string, { mode: "on" | "off" | null; offered: boolean }>;
+function service(input: { stateDir: string; workspaces: BoxWorkspace[]; settings?: Settings; env: NodeJS.ProcessEnv; platform?: NodeJS.Platform }) {
+ const settings = input.settings ?? new Map();
+ return new BoxService({
+ stateDir: input.stateDir,
+ readSettings: async (id) => settings.get(id) ?? { mode: null, offered: false },
+ writeSettings: async (id, update) => {
+ const current = settings.get(id) ?? { mode: null, offered: false };
+ settings.set(id, { mode: update.mode === undefined ? current.mode : update.mode, offered: update.offered ?? current.offered });
+ },
+ workspaces: () => input.workspaces,
+ pluginPath: () => "/plugins/omnirush-box.js",
+ env: input.env,
+ ...(input.platform ? { platform: input.platform } : {}),
+ });
+}
+
+function fakeRun(root: string, frozen: string[]): BoxRun {
+ return {
+ key: boxKey(root), container: "c", runtimeBin: "docker", runtimeArgs: [], backend: "docker", exec: null, root, native: false, box: null,
+ ready: async () => null, label: () => null, setTurn: () => {}, heal: async () => null, close: () => {},
+ freeze: async (label, { sessionId, turn = null }) => {
+ frozen.push(`${sessionId} ${label}`);
+ return { label, turn, copied: 0, carried: 0, save: async () => ({ label, changed: 0, bytes: 0 }), discard: async () => null };
+ },
+ };
+}
+
+const NO_RUNTIME = { PATH: "", OMNIRUSH_BOX_RUNTIME: "/nonexistent/docker" };
+
+describe("required sandbox: the server's answer", () => {
+ test("required, its fallback and prefetch are remembered; keys that first appear with their old meaning are no change", async () => {
+ const state = await temp("state");
+ expect(rememberServerDefault(state, { local_box: { default: "on" } })).toBe(true);
+ // A newer server says the same thing with more keys: nothing to plan again.
+ expect(rememberServerDefault(state, { local_box: { default: "on", required: false, required_fallback: null, setup: { prefetch: true } } })).toBe(false);
+ expect(serverRequired(state)).toEqual({ required: false, fallback: "native", prefetch: true });
+ expect(rememberServerDefault(state, { local_box: { default: "on", required: true, required_fallback: "native", setup: { prefetch: true } } })).toBe(true);
+ expect(serverRequired(state)).toEqual({ required: true, fallback: "native", prefetch: true });
+ expect(rememberServerDefault(state, { local_box: { default: "on", required: true, required_fallback: "native_uncounted", setup: { prefetch: true } } })).toBe(true);
+ expect(rememberServerDefault(state, { local_box: { default: "on", required: true, required_fallback: "native_uncounted", setup: { prefetch: false } } })).toBe(false);
+ expect(JSON.parse(await readFile(join(state, "box-server.json"), "utf8"))).toMatchObject({ default: "on", required: true, required_fallback: "native_uncounted", prefetch: false });
+ // An older server's answer: not required.
+ expect(rememberServerDefault(state, { local_box: { default: "on" } })).toBe(true);
+ expect(serverRequired(state).required).toBe(false);
+ });
+
+ test("resolveMode: required beats the project's off and the buildathon; OMNIRUSH_BOX=0 is the escape and says so", () => {
+ expect(resolveMode({ env: {}, project: "off", server: "on", required: true })).toEqual({ on: true, source: "required", offer: false, required: true });
+ expect(resolveMode({ env: {}, project: null, server: "on", buildathon: "off", required: true })).toEqual({ on: true, source: "required", offer: false, required: true });
+ expect(resolveMode({ env: { OMNIRUSH_BOX: "0" }, project: null, server: "on", required: true })).toEqual({ on: false, source: "env", offer: false, required: true });
+ expect(resolveMode({ env: {}, project: "off", server: "on" })).toEqual({ on: false, source: "project", offer: false });
+ });
+});
+
+describe("required sandbox: the desktop's projects", () => {
+ test("off and the backend Off are refused; the status says required with the texts and what setup is needed", async () => {
+ const stateDir = await temp("state");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_req", path: root, workspaceType: "local" };
+ const settings: Settings = new Map([["ws_req", { mode: "off", offered: true }]]);
+ rememberServerDefault(stateDir, { local_box: { default: "on", required: true, required_fallback: "native" } });
+ const boxes = service({ stateDir, workspaces: [workspace], settings, env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), ...NO_RUNTIME } });
+ await expect(boxes.setMode(workspace, "off")).rejects.toBeInstanceOf(BoxRequiredError);
+ await expect(boxes.setBackend("native")).rejects.toThrow("Required for new chats on this account");
+ const status = await boxes.status(workspace);
+ expect(status).toMatchObject({ on: true, source: "required", required: true, state: "unavailable" });
+ expect(status.requiredText?.optOut).toBe("Required for new chats on this account. Chats started before keep running where they started.");
+ expect(status.setup).toMatchObject({ need: process.platform === "linux" ? "runtime" : expect.any(String), fallback: "native", declined: false });
+ // "Not now": chats run here meanwhile, and say so.
+ const declined = await boxes.setup(workspace, "decline");
+ expect(declined.setup?.declined).toBe(true);
+ expect(await boxes.beforePrompt("ses_req_decl1", workspace)).toBeNull();
+ expect(await boxes.planOutcome("ses_req_decl1", workspace)).toMatchObject({ native: true, source: "required", reason: "setup_declined", required: true, fallback: "native" });
+ });
+
+ test("a new chat goes in the box; a reopened native chat stays here without waiting (kept_old_chat)", async () => {
+ const stateDir = await temp("state");
+ const home = await temp("boxhome");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_new", path: root, workspaceType: "local" };
+ rememberServerDefault(stateDir, { local_box: { default: "on", required: true } });
+ const boxes = service({ stateDir, workspaces: [workspace], env: { OMNIRUSH_BOX_HOME: home } });
+ const frozen: string[] = [];
+ boxes.ensure = async () => fakeRun(root, frozen);
+ expect(await boxes.beforePrompt("ses_req_old1", workspace, { turnsBefore: 3 })).toBeNull();
+ await boxes.beforePrompt("ses_req_new1", workspace);
+ expect(frozen).toEqual(["ses_req_new1 turn-1"]);
+ expect(await boxes.planOutcome("ses_req_old1", workspace)).toEqual({ native: true, source: "chat", reason: "kept_old_chat", required: true, fallback: "native" });
+ expect(await boxes.planOutcome("ses_req_new1", workspace)).toEqual({ native: false, source: "required", reason: "box", required: true });
+ expect(JSON.parse(await readFile(join(home, DESKTOP_PROJECTS_FILE), "utf8")).native_chats).toEqual(["ses_req_old1"]);
+ });
+
+ test("the first prompt waits while the image downloads, then runs in the box", async () => {
+ const stateDir = await temp("state");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_wait", path: root, workspaceType: "local" };
+ rememberServerDefault(stateDir, { local_box: { default: "on", required: true } });
+ const boxes = service({ stateDir, workspaces: [workspace], env: { OMNIRUSH_BOX_HOME: await temp("boxhome") } });
+ const frozen: string[] = [];
+ const projects: unknown = Reflect.get(boxes, "projects");
+ if (!(projects instanceof Map)) throw new Error("no projects map");
+ let tries = 0;
+ boxes.ensure = async () => {
+ tries += 1;
+ if (tries < 3) {
+ projects.set(boxKey(root), { run: null, notice: "downloading", planning: null, nextPlanAt: 0, waitingImage: true, why: { reason: "downloading" } });
+ return null;
+ }
+ return fakeRun(root, frozen);
+ };
+ const started = Date.now();
+ await boxes.beforePrompt("ses_req_wait1", workspace);
+ expect(tries).toBe(3);
+ expect(Date.now() - started).toBeGreaterThanOrEqual(1_500);
+ expect(frozen).toEqual(["ses_req_wait1 turn-1"]);
+ });
+
+ test("OMNIRUSH_BOX=0 is env_off; a host-only project stays here (host_only); the host-builds gate no longer keeps it", async () => {
+ const stateDir = await temp("state");
+ const root = await temp("project");
+ rememberServerDefault(stateDir, { local_box: { default: "on", required: true } });
+ const workspace: BoxWorkspace = { id: "ws_env", path: root, workspaceType: "local" };
+ const off = service({ stateDir, workspaces: [workspace], env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), OMNIRUSH_BOX: "0" } });
+ expect(await off.planOutcome("ses_req_env1", workspace)).toEqual({ native: true, source: "env", reason: "env_off", required: true, fallback: "native" });
+
+ const mac = await temp("macproject");
+ await mkdir(join(mac, "App.xcodeproj"));
+ const macWs: BoxWorkspace = { id: "ws_mac", path: mac, workspaceType: "local" };
+ const boxes = service({ stateDir, workspaces: [macWs], env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), ...NO_RUNTIME }, platform: "darwin" });
+ const status = await boxes.status(macWs);
+ expect(status).toMatchObject({ on: false, source: "host-only", required: true, hostOnly: { things: ["App.xcodeproj"] } });
+ expect(status.notice).toContain("only builds on Mac (App.xcodeproj)");
+ expect(await boxes.planOutcome("ses_req_mac1", macWs)).toEqual({ native: true, source: "host-only", reason: "host_only", required: true, fallback: "native" });
+
+ // A Mac-built node_modules: required puts the chat in the box anyway (no host-builds gate).
+ const built = await temp("builtproject");
+ await mkdir(join(built, "node_modules", "esbuild-darwin-arm64"), { recursive: true });
+ await writeFile(join(built, "node_modules", "esbuild-darwin-arm64", "package.json"), JSON.stringify({ name: "esbuild-darwin-arm64", os: ["darwin"] }));
+ const builtWs: BoxWorkspace = { id: "ws_built", path: built, workspaceType: "local" };
+ const builtBoxes = service({ stateDir, workspaces: [builtWs], env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), ...NO_RUNTIME }, platform: "darwin" });
+ expect(await builtBoxes.status(builtWs)).toMatchObject({ on: true, source: "required", hostBuilds: null });
+ });
+
+ test("an opened project is planned at once; prefetch only when the server asks for it", async () => {
+ const stateDir = await temp("state");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_open", path: root, workspaceType: "local" };
+ rememberServerDefault(stateDir, { local_box: { default: "on", required: true } });
+ const boxes = service({ stateDir, workspaces: [workspace], env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), ...NO_RUNTIME } });
+ const asked: string[] = [];
+ boxes.ensure = async (ws) => { asked.push(ws.id); return null; };
+ boxes.opened(workspace);
+ boxes.opened({ id: "ws_remote", path: root, workspaceType: "remote" });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(asked).toEqual(["ws_open"]);
+ expect(await boxes.prefetch()).toBe(false);
+ });
+
+ test("an older server: unchanged (the project's off still turns it off, no setup, not required)", async () => {
+ const stateDir = await temp("state");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_old", path: root, workspaceType: "local" };
+ rememberServerDefault(stateDir, { local_box: { default: "on" } });
+ const boxes = service({ stateDir, workspaces: [workspace], env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), ...NO_RUNTIME } });
+ const status = await boxes.setMode(workspace, "off");
+ expect(status).toMatchObject({ on: false, source: "project", required: false, requiredText: null, setup: null, hostOnly: null });
+ expect(await boxes.planOutcome("ses_old_srv1", workspace)).toEqual({ native: true, source: "project", reason: "off" });
+ });
+});
diff --git a/apps/server/src/box/box-setup.test.ts b/apps/server/src/box/box-setup.test.ts
new file mode 100644
index 00000000..4b536d9a
--- /dev/null
+++ b/apps/server/src/box/box-setup.test.ts
@@ -0,0 +1,101 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import type { RunCommand } from "./run.js";
+import { classifySetup, elevatedCommand, linuxAllow, linuxAllowScript, readSetupState, runOnceArgs, setupDone, windowsInstall } from "./setup.js";
+
+const dirs: string[] = [];
+afterEach(async () => {
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
+});
+async function temp(name: string): Promise<string> {
+ const dir = await mkdtemp(join(tmpdir(), `omnirush-boxsetup-${name}-`));
+ dirs.push(dir);
+ return dir;
+}
+
+const fail = (reason: string, tried: string[] = []) => ({ ok: false as const, reason, tried: tried.map((r) => ({ reason: r })) });
+const facts = { build: 22631, hypervisorPresent: false, firmwareEnabled: true, model: "Dell Inc. XPS", sMode: false };
+
+describe("sandbox setup: what is needed", () => {
+ test("Linux: AppArmor is the one-click allow; a container without user namespaces cannot run; otherwise the usual next step", () => {
+ expect(classifySetup({ runtime: fail("no backend", ["bubblewrap is blocked; one-time admin fix: `sudo omnirush sandbox enable` (OmniRush CLI)"]), platform: "linux", fallback: "native" }).need).toBe("linux_allow");
+ expect(classifySetup({ runtime: fail("unprivileged user namespaces are off; an admin can allow them, or use Podman or Docker"), platform: "linux", fallback: "native" })).toMatchObject({ need: "cannot_run", why: null });
+ expect(classifySetup({ runtime: fail("podman not found"), platform: "linux", fallback: "native" }).need).toBe("runtime");
+ expect(classifySetup({ runtime: { ok: true, name: "docker", bin: "docker", version: "1", os: "linux", arch: "amd64", rootless: true, flavor: "", vm: false }, platform: "linux", fallback: "native", state: { declinedAt: 1 } })).toMatchObject({ need: "none", declined: false });
+ });
+
+ test("Windows: install, restart after the install, update, and the cannot-run reasons", () => {
+ const off = fail("WSL 2 is not enabled on this Windows. One time, in an administrator terminal: `wsl --install --no-distribution`, then restart Windows");
+ expect(classifySetup({ runtime: off, platform: "win32", facts, fallback: "native" }).need).toBe("win_install");
+ expect(classifySetup({ runtime: off, platform: "win32", facts, fallback: "native", state: { win: { state: "installed", at: 1, message: "ok" } } })).toMatchObject({ need: "win_restart", result: { ok: true } });
+ expect(classifySetup({ runtime: fail("WSL needs an update (`wsl --update`)"), platform: "win32", facts, fallback: "native" }).need).toBe("win_update");
+ expect(classifySetup({ runtime: off, platform: "win32", facts: { ...facts, firmwareEnabled: false }, fallback: "native_uncounted" })).toMatchObject({ need: "cannot_run", why: "firmware_off", fallback: "native_uncounted" });
+ expect(classifySetup({ runtime: off, platform: "win32", facts: { ...facts, firmwareEnabled: false, model: "Microsoft Corporation Virtual Machine" }, fallback: "native" }).why).toBe("nested_vm");
+ expect(classifySetup({ runtime: off, platform: "win32", facts: { ...facts, sMode: true }, fallback: "native" }).whyText).toBe("Windows in S mode can't run WSL");
+ expect(classifySetup({ runtime: off, platform: "win32", facts, fallback: "native", state: { win: { state: "failed", at: 1, message: "Installation blocked by group policy" } } }).why).toBe("policy");
+ expect(classifySetup({ runtime: off, platform: "win32", facts, fallback: "native", state: { declinedAt: 5 } })).toMatchObject({ need: "win_install", declined: true });
+ });
+
+ test("the elevated start is one Start-Process -Verb RunAs -Wait with the .ps1 and its log; RunOnce reopens the app", () => {
+ const cmd = elevatedCommand("C:\\Users\\o'neil\\AppData\\Local\\Temp\\s\\setup.ps1", "C:\\Users\\o'neil\\.omnirush\\box\\setup-wsl.log");
+ expect(cmd.match(/Start-Process/g)?.length).toBe(1);
+ expect(cmd).toContain("-Verb RunAs -Wait -PassThru");
+ expect(cmd).toContain(`'"C:\\Users\\o''neil\\AppData\\Local\\Temp\\s\\setup.ps1"'`);
+ expect(cmd).toContain("exit 1223");
+ expect(runOnceArgs("C:\\Program Files\\OmniRush.ai\\OmniRush.ai.exe")).toEqual(["add", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "/v", "OmniRushSandboxSetup", "/t", "REG_SZ", "/d", "\"C:\\Program Files\\OmniRush.ai\\OmniRush.ai.exe\"", "/f"]);
+ });
+
+ test("windows install: done in the log is installed (RunOnce set), a cancelled prompt is declined", async () => {
+ const home = await temp("home");
+ const calls: string[] = [];
+ const ok: RunCommand = async (bin, args) => {
+ calls.push(bin);
+ if (bin === "powershell.exe") {
+ const log = /'"([^"]+setup-wsl\.log)"'/.exec(args.join(" "))?.[1];
+ if (log) await writeFile(log, "Installing: Virtual Machine Platform\r\nThe requested operation is successful.\r\ndone\r\n");
+ }
+ return { code: 0, stdout: "", stderr: "" };
+ };
+ const step = await windowsInstall({ home, run: ok, exe: "C:\\App\\OmniRush.ai.exe", tmp: await temp("tmp") });
+ expect(step).toMatchObject({ state: "installed", message: "The requested operation is successful." });
+ expect(calls).toEqual(["powershell.exe", "reg.exe"]);
+ expect(readSetupState(home).win?.state).toBe("installed");
+ const cancelled: RunCommand = async () => ({ code: 1223, stdout: "cancelled\n", stderr: "" });
+ expect((await windowsInstall({ home, run: cancelled, exe: null, tmp: await temp("tmp") })).state).toBe("declined");
+ expect(readSetupState(home).declinedAt).toBeGreaterThan(0);
+ const removed: string[] = [];
+ await setupDone(home, { platform: "win32", run: async (bin, args) => { removed.push(`${bin} ${args[0]}`); return { code: 0, stdout: "", stderr: "" }; } });
+ expect(removed).toEqual(["reg.exe delete"]);
+ expect(readSetupState(home)).toEqual({});
+ });
+
+ test("Linux allow: pkexec runs the enable step with the staged bubblewrap and its sha256; dismissed is declined", async () => {
+ const home = await temp("home");
+ const source = join(await temp("bin"), "bwrap");
+ await writeFile(source, "fake bwrap");
+ const seen: string[][] = [];
+ const ok: RunCommand = async (bin, args) => {
+ seen.push([bin, ...args]);
+ expect(await readFile(args[4] ?? "", "utf8")).toBe("fake bwrap");
+ return { code: 0, stdout: "installed; AppArmor profile loaded\n", stderr: "" };
+ };
+ expect(await linuxAllow({ home, env: {}, run: ok, source })).toMatchObject({ state: "allowed", message: "Allowed (installed; AppArmor profile loaded)." });
+ expect(seen[0]?.slice(0, 2)).toEqual(["pkexec", "/bin/sh"]);
+ expect(seen[0]?.[6]).toMatch(/^[0-9a-f]{64}$/);
+ expect(await linuxAllow({ home, env: { OMNIRUSH_BOX_PKEXEC: "/rig/elevate" }, run: async (bin) => ({ code: bin === "/rig/elevate" ? 126 : 1, stdout: "", stderr: "" }), source })).toMatchObject({ state: "declined" });
+ expect(readSetupState(home).declinedAt).toBeGreaterThan(0);
+ expect((await linuxAllow({ home, env: {}, run: async () => ({ code: 127, stdout: "", stderr: "Error executing command as another user: Not authorized" }), source })).message).toBe("Not authorised: Error executing command as another user: Not authorized.");
+ });
+
+ test("the root step installs only OmniRush's bubblewrap copy and its own AppArmor profile", () => {
+ const script = linuxAllowScript();
+ expect(script).toContain("dst=/usr/local/lib/omnirush/bwrap; prof=/etc/apparmor.d/omnirush-bwrap");
+ expect(script).toContain('chown 0:0 "$dst.tmp"');
+ expect(script).toContain("profile omnirush-bwrap /usr/local/lib/omnirush/bwrap flags=(unconfined)");
+ expect(script).toContain('"$parser" -r "$prof"');
+ expect(script).not.toContain("sysctl");
+ });
+});
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index a82fbb5d..37f8ec3c 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -29,13 +29,15 @@ import { LABELS, OPT_IN, backendsFor, driverFor } from "./backends/index.js";
import type { BoxExec } from "./backends/types.js";
import type { BoxEndpoint } from "./client.js";
import { hostBuilds, hostBuildsNotice, hostBuildThings, hostRules } from "./host-builds.js";
-import { detectStack, imageFor } from "./images.js";
-import { askedBackend, boxRun, planBox, pullLog, pullMarker, pulling, pullInBackground, resolveMode, saveBackend, serverBackends, serverDefault, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";
+import { detectStack, imageFor, type BoxImage } from "./images.js";
+import { askedBackend, boxRun, planBox, pullLog, pullMarker, pulling, pullInBackground, resolveMode, saveBackend, serverBackends, serverDefault, serverRequired, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";
+import { desktopText, hostOnlyProject, type RequiredFallback } from "./required.js";
+import { classifySetup, linuxAllow, readSetupState, setupDone, windowsFacts, windowsInstall, windowsRestart, windowsUpdate, writeSetupState, type BoxSetup } from "./setup.js";
import type { BoxInstallLogPaths } from "./install-log.js";
import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";
import { BUILDATHON_OFFER_NOTICE, buildathonBoxFor, buildathonProjectsFile, LESS_REPRO_NOTICE } from "../buildathon-repro.js";
import { layerSizes, pullProgress, type PullProgress } from "./pull-progress.js";
-import { detectRuntime, type BackendAlternative, type DetectOptions, type RuntimeResult } from "./runtime.js";
+import { detectRuntime, type BackendAlternative, type DetectOptions, type RuntimeInfo, type RuntimeResult } from "./runtime.js";
/** What the capture side needs of a chat's box (plain data: it crosses to the capture worker). */
export type BoxCaptureInfo = {
@@ -62,8 +64,11 @@ export type BoxStatus = {
serverDefault: ServerBoxDefault;
/** Whether the project's chats should run in its box. */
on: boolean;
- /** "host-builds": the server's default would put it in the box, but its folder has this computer's builds (macOS, Windows). */
- source: "env" | "project" | "server" | "default" | "host-builds" | "buildathon";
+ /**
+ * "host-builds": the server's default would put it in the box, but its folder has this computer's builds (macOS, Windows).
+ * "required": the server requires the sandbox for new chats. "host-only": required, but the project only builds on this OS.
+ */
+ source: "env" | "project" | "server" | "default" | "host-builds" | "buildathon" | "required" | "host-only";
/** The server offers the box and this project was not offered it yet. */
offer: boolean;
state: "off" | "unavailable" | "downloading" | "starting" | "ready" | "failed";
@@ -89,8 +94,33 @@ export type BoxStatus = {
hostBuilds: { native: boolean; things: string; notice: string } | null;
/** macOS / Windows, while the project's chats run in the box: the one line that says so (null elsewhere). */
boxNotice: string | null;
+ /**
+ * The server requires the sandbox for new chats (local_box.required): the switch and "Off (this
+ * computer)" are disabled with `requiredText.optOut`. False with an older server.
+ */
+ required: boolean;
+ requiredText: { line: string; optOut: string; keptOldChat: string } | null;
+ /** Required, but the project only builds on this OS (an Xcode project, a WPF app): its chats run here. */
+ hostOnly: { things: string[]; notice: string } | null;
+ /** Required and not ready: what the sandbox needs on this computer (the setup screen). Null otherwise. */
+ setup: BoxSetup | null;
};
+/** The setup screen's steps (POST /workspace/:id/box/setup). */
+export const BOX_SETUP_ACTIONS = ["linux_allow", "win_install", "win_restart", "win_update", "decline", "check"] as const;
+export type BoxSetupAction = (typeof BOX_SETUP_ACTIONS)[number];
+export function isBoxSetupAction(value: unknown): value is BoxSetupAction {
+ return BOX_SETUP_ACTIONS.some((action) => action === value);
+}
+
+/** PUT mode "off" (or the backend "native") while the sandbox is required: refused (409 box_required). */
+export class BoxRequiredError extends Error {
+ readonly code = "box_required";
+ constructor() {
+ super(desktopText("opt_out_refused"));
+ }
+}
+
export type BoxBackendView = {
/** The chosen backend's id (null when none works here). */
id: string | null;
@@ -128,7 +158,7 @@ export type BoxServiceOptions = {
};
/** `waitingImage`: planned while its image was downloading (planned again as soon as the image is here). */
-type Project = { run: BoxRun | null; notice: string | null; planning: Promise<BoxRun | null> | null; nextPlanAt: number; waitingImage: boolean; why?: PlanWhy | null };
+type Project = { run: BoxRun | null; notice: string | null; planning: Promise<BoxRun | null> | null; nextPlanAt: number; waitingImage: boolean; why?: PlanWhy | null; pull?: { runtime: RuntimeInfo; image: BoxImage } | null; lastRuntime?: RuntimeResult | null };
/** Why the project's last plan has no box (the `box.plan` reason), with the runtime's failure in safe words. */
type PlanWhy = { reason: "no_runtime" | "helpers_missing" | "downloading"; runtime?: { name: string | null; code: string | null } };
@@ -140,7 +170,7 @@ type PlanWhy = { reason: "no_runtime" | "helpers_missing" | "downloading"; runti
* helpers_missing, downloading, planning; `source`: what turned the box on or
* off (project, server, default, flag, host-builds, chat).
*/
-export type BoxPlanOutcome = { native: boolean; source: string | null; reason: string; runtime?: { name: string | null; code: string | null } };
+export type BoxPlanOutcome = { native: boolean; source: string | null; reason: string; runtime?: { name: string | null; code: string | null }; required?: true; fallback?: RequiredFallback };
/** The backend tried and its failure code (bubblewrap's apparmor, no_bwrap, ...; `timeout`), never its text or a path. */
export function runtimeWhy(runtime: { name?: unknown; code?: unknown; reason?: unknown } | null | undefined): { name: string | null; code: string | null } {
@@ -156,6 +186,10 @@ const REPLAN_MS = 15_000;
const FREEZE_WAIT_MS = 90_000;
/** The full backend check (every backend, for the status card's "others") is reused this long. */
const ALTERNATIVES_MS = 60_000;
+/** Required: a prompt waits this long at most for its project's box (the image download, the start). */
+const REQUIRED_WAIT_MS = 15 * 60_000;
+/** How often a waiting prompt looks again. */
+const REQUIRED_POLL_MS = 1_000;
export function boxRoot(workspace: BoxWorkspace): string {
return workspace.directory?.trim() || workspace.path;
@@ -212,9 +246,19 @@ export class BoxService {
return serverDefault(this.options.stateDir);
}
- /** The backend detection's inputs: the setting (or OMNIRUSH_BOX_BACKEND) and the server's allowlist. */
+ /** The server's `required` for this device (box-server.json), its fallback and prefetch. */
+ required(): ReturnType<typeof serverRequired> {
+ return serverRequired(this.options.stateDir);
+ }
+
+ /**
+ * The backend detection's inputs: the setting (or OMNIRUSH_BOX_BACKEND) and the server's allowlist.
+ * While the sandbox is required, a saved "native" reads as automatic (OMNIRUSH_BOX_BACKEND=native still counts).
+ */
private detectOptions(): Pick<DetectOptions, "asked" | "allow"> {
- return { asked: askedBackend({ env: this.env, stateDir: this.options.stateDir }).backend, allow: serverBackends(this.options.stateDir) };
+ const asked = askedBackend({ env: this.env, stateDir: this.options.stateDir });
+ const backend = asked.source === "setting" && asked.backend === "native" && this.required().required ? "auto" : asked.backend;
+ return { asked: backend, allow: serverBackends(this.options.stateDir) };
}
private detect(extra: DetectOptions = {}): Promise<RuntimeResult> {
@@ -227,6 +271,7 @@ export class BoxService {
* is planned again). Throws for an unknown value.
*/
async setBackend(value: unknown): Promise<string> {
+ if (value === "native" && this.required().required) throw new BoxRequiredError();
const saved = saveBackend(this.options.stateDir, value);
this.alternatives = null;
const now = await this.detect({ fresh: true });
@@ -263,14 +308,30 @@ export class BoxService {
private async mode(workspace: BoxWorkspace) {
const settings = await this.options.readSettings(workspace.id).catch(() => ({ mode: null, offered: false }));
const server = this.serverDefault();
+ const { required } = this.required();
// A buildathon project (the app lists them): the event's `repro.box` comes before the server's default.
const buildathon = workspace.workspaceType === "local" ? this.buildathonBox(boxRoot(workspace)) : null;
- const resolved = resolveMode({ env: this.env, project: settings.mode, server, offered: settings.offered, buildathon });
+ const resolved = resolveMode({ env: this.env, project: settings.mode, server, offered: settings.offered, buildathon, required });
+ // Required: the folder's builds no longer keep it here (the box keeps its own copies); a project that
+ // only builds on this OS (an Xcode project, a WPF app) does.
+ if (resolved.source === "required") {
+ const hostOnly = workspace.workspaceType === "local" ? this.hostOnly(boxRoot(workspace)) : null;
+ if (hostOnly) return { settings, server, ...resolved, on: false, source: "host-only" as const, hostBuilds: null, hostOnly };
+ return { settings, server, ...resolved, hostBuilds: null, hostOnly: null };
+ }
const gate = workspace.workspaceType === "local" ? this.hostGate(boxRoot(workspace), resolved) : null;
// A box already running for the project keeps its chats (builds made since do not move them out).
const running = this.projects.get(boxKey(boxRoot(workspace)))?.run;
- if (gate?.native && !(running && !running.native)) return { settings, server, ...resolved, on: false, source: "host-builds" as const, offer: false, hostBuilds: gate };
- return { settings, server, ...resolved, hostBuilds: gate };
+ if (gate?.native && !(running && !running.native)) return { settings, server, ...resolved, on: false, source: "host-builds" as const, offer: false, hostBuilds: gate, hostOnly: null };
+ return { settings, server, ...resolved, hostBuilds: gate, hostOnly: null };
+ }
+
+ private hostOnly(root: string): { things: string[]; notice: string } | null {
+ try {
+ return hostOnlyProject(root, { platform: this.platform });
+ } catch {
+ return null;
+ }
}
/**
@@ -311,7 +372,7 @@ export class BoxService {
* offer, and the helpers for this machine are installed.
*/
async engineBits(): Promise<{ shell: string; plugin: string } | null> {
- let wanted = this.serverDefault() !== "off" || ["1", "on", "true"].includes(String(this.env.OMNIRUSH_BOX ?? "").trim().toLowerCase());
+ let wanted = this.serverDefault() !== "off" || this.required().required || ["1", "on", "true"].includes(String(this.env.OMNIRUSH_BOX ?? "").trim().toLowerCase());
for (const workspace of this.options.workspaces()) {
if (wanted) break;
if (workspace.workspaceType !== "local") continue;
@@ -358,6 +419,8 @@ export class BoxService {
if (Date.now() < project.nextPlanAt) return null;
const plan = await planBox({ env: this.env, home: this.home, root, log: this.log, shims: shimsDir(this.env), ...this.detectOptions() });
project.waitingImage = !plan.box && plan.downloading === true;
+ project.lastRuntime = plan.box ? null : plan.runtime;
+ project.pull = !plan.box && plan.downloading === true && plan.image && plan.runtime?.ok ? { runtime: plan.runtime, image: plan.image } : null;
project.why = plan.box ? null
: plan.downloading === true ? { reason: "downloading" }
: plan.runtime && !plan.runtime.ok ? { reason: "no_runtime", runtime: runtimeWhy(plan.runtime) }
@@ -403,6 +466,39 @@ export class BoxService {
await Promise.allSettled(this.options.workspaces().map((workspace) => this.ensure(workspace)));
}
+ /**
+ * A workspace was opened, made active or added: its box is planned now, in
+ * the background (a missing image starts downloading, the box starts), so
+ * it is ready before the first prompt. Never throws.
+ */
+ opened(workspace: BoxWorkspace): void {
+ if (workspace.workspaceType !== "local") return;
+ const project = this.projects.get(boxKey(boxRoot(workspace)));
+ if (project && !project.run) project.nextPlanAt = 0;
+ // The box starts as soon as its run exists (boxRun); a missing image starts downloading.
+ void this.ensure(workspace).then((run) => {
+ this.log("info", "box planned for an opened project", { key: boxKey(boxRoot(workspace)), box: Boolean(run && !run.native) });
+ }).catch(() => null);
+ }
+
+ /**
+ * The server asks for images to be fetched ahead (local_box.setup.prefetch):
+ * the base image, in the background, next to the stacks the open projects'
+ * plans download (ensureAll). Skipped on a metered connection (OMNIRUSH_BOX_METERED=1)
+ * and when no backend works. Whether a download started.
+ */
+ async prefetch(): Promise<boolean> {
+ if (!this.required().prefetch || this.env.OMNIRUSH_BOX_METERED === "1") return false;
+ const runtime = await this.detect().catch(() => null);
+ if (!runtime?.ok) return false;
+ const image = imageFor("base", { env: this.env });
+ if (pulling(this.home, runtime, image.pull)) return false;
+ if (await driverFor(runtime).imagePresent(runtime, image, { home: this.home, env: this.env }).catch(() => null)) return false;
+ this.log("info", "box prefetch", { image: image.pull, backend: runtime.backend ?? runtime.name });
+ pullInBackground(runtime, image, this.home, { env: this.env, log: this.log });
+ return true;
+ }
+
/** The projects the plugin routes to their box: on, planned, not gone native. */
private writeProjects(): Promise<void> {
const keys = [...this.projects.entries()].filter(([, project]) => project.run && !project.run.native).map(([key]) => key).sort();
@@ -432,6 +528,7 @@ export class BoxService {
}
async setMode(workspace: BoxWorkspace, mode: ProjectBoxMode): Promise<BoxStatus> {
+ if (mode === "off" && this.required().required) throw new BoxRequiredError();
await this.options.writeSettings(workspace.id, { mode, offered: true });
const key = boxKey(boxRoot(workspace));
// Turned on by the user: the project's chats that stayed on this machine move to the box too.
@@ -453,13 +550,15 @@ export class BoxService {
}
async status(workspace: BoxWorkspace, { fresh = false }: { fresh?: boolean } = {}): Promise<BoxStatus> {
- const { settings, server, on, source, offer, hostBuilds: gate, lessRepro } = await this.mode(workspace);
+ const { settings, server, on, source, offer, hostBuilds: gate, lessRepro, hostOnly, required } = await this.mode(workspace);
// The server's "offer": shown once per folder (CLI: the tip, once per folder).
if (offer && workspace.workspaceType === "local") await this.options.writeSettings(workspace.id, { offered: true }).catch(() => undefined);
const root = boxRoot(workspace);
const key = boxKey(root);
const project = this.projects.get(key);
- const base = { mode: settings.mode, serverDefault: server, on, source, offer, error: null, hostBuilds: gate, boxNotice: null };
+ const needed = required === true;
+ const requiredText = needed ? { line: desktopText("required_line"), optOut: desktopText("opt_out_refused"), keptOldChat: desktopText("kept_old_chat") } : null;
+ const base = { mode: settings.mode, serverDefault: server, on, source, offer, error: null, hostBuilds: gate, boxNotice: null, required: needed, requiredText, hostOnly, setup: null };
const backendSetting = { ...askedBackend({ env: this.env, stateDir: this.options.stateDir }), choices: backendChoices() };
const setting = { value: backendSetting.backend, source: backendSetting.source, choices: backendSetting.choices };
if (workspace.workspaceType !== "local") return { ...base, on: false, offer: false, state: "off", runtime: null, backend: null, backendSetting: setting, image: null, progress: null, container: null, platform: this.platform, notice: "The sandbox is for folders on this computer." };
@@ -513,6 +612,9 @@ export class BoxService {
: run && !run.native ? (run.box?.ready ? "ready" : run.box?.state === "failed" ? "failed" : "starting")
: downloading || (!present && !container?.exists) ? "downloading"
: project?.notice ? "unavailable" : "starting";
+ const setup = needed && on && state !== "ready" ? await this.setupFor(runtime, { fresh }) : null;
+ // Ready: a setup step that led here is finished (its state and the RunOnce value go).
+ if (needed && state === "ready") await setupDone(this.home, { platform: this.platform }).catch(() => undefined);
return {
...base,
state,
@@ -525,14 +627,34 @@ export class BoxService {
platform: this.platform,
notice: on ? project?.notice ?? (runtime.ok ? null : `Sandbox off for now: ${runtime.reason}.`)
: gate?.native ? gate.notice
+ : hostOnly ? hostOnly.notice
: lessRepro ? LESS_REPRO_NOTICE
: offer && source === "buildathon" ? BUILDATHON_OFFER_NOTICE
: null,
error: run?.box?.error ?? (record?.state === "off" || record?.state === "failed" ? record.error || null : null),
boxNotice: on && hostRules(this.platform) ? hostBuildsNotice("box", { platform: this.platform }) : null,
+ setup,
};
}
+ /** What the sandbox needs here before it can run (the setup screen); Windows facts are read (and cached) for it. */
+ async setupFor(runtime: RuntimeResult | null, { fresh = false }: { fresh?: boolean } = {}): Promise<BoxSetup> {
+ const state = readSetupState(this.home);
+ const facts = this.platform === "win32" && runtime && !runtime.ok ? await windowsFacts({ fresh }).catch(() => null) : null;
+ const setup = classifySetup({ runtime, platform: this.platform, facts, state, fallback: this.required().fallback });
+ // Back after the restart, and WSL asks for an update: run it once, in the background.
+ if (setup.need === "win_update" && state.win?.state === "installed" && !state.win.update && !this.updating) {
+ this.updating = windowsUpdate({ home: this.home }).catch(() => null).finally(() => {
+ this.updating = null;
+ this.alternatives = null;
+ void this.ensureAll();
+ });
+ }
+ return setup;
+ }
+
+ private updating: Promise<unknown> | null = null;
+
/**
* Try again now (the card's retry): a box that failed to start, or a
* project that went on without it, is planned again; its container and
@@ -553,6 +675,25 @@ export class BoxService {
return this.status(workspace, { fresh: true });
}
+ /**
+ * One setup step (box/setup.ts), then a fresh look: a step that worked has
+ * the project planned again (and the images fetched ahead), so the box
+ * starts. Only the steps of this OS run; the others are a fresh look.
+ */
+ async setup(workspace: BoxWorkspace, action: BoxSetupAction): Promise<BoxStatus> {
+ const home = this.home;
+ if (action === "linux_allow" && this.platform === "linux") await linuxAllow({ home, env: this.env });
+ else if (action === "win_install" && this.platform === "win32") await windowsInstall({ home });
+ else if (action === "win_update" && this.platform === "win32") await windowsUpdate({ home });
+ else if (action === "win_restart" && this.platform === "win32") await windowsRestart();
+ else if (action === "decline") writeSetupState(home, (state) => ({ ...state, declinedAt: Date.now() }));
+ if (action === "check" && this.platform === "win32") await windowsFacts({ fresh: true }).catch(() => null);
+ if (action === "win_restart") return this.status(workspace);
+ const status = await this.retry(workspace);
+ if (status.setup?.need === "none") void this.prefetch().catch(() => false);
+ return status;
+ }
+
/** Remove the project's container (installs gone); the next chat starts a fresh one. */
async reset(workspace: BoxWorkspace): Promise<{ removed: boolean }> {
const root = boxRoot(workspace);
@@ -599,12 +740,21 @@ export class BoxService {
const turnsSoFar = this.chatTurns.get(sessionId) ?? turnsBefore;
const chatTurn = capture ? turnsSoFar + 1 : 0;
if (capture) this.chatTurns.set(sessionId, chatTurn);
- const run = await this.ensure(workspace).catch(() => null);
+ // Required: a new chat waits for its project's box (the download, the start) instead of starting here;
+ // a chat that already ran on this machine stays here, without waiting.
+ const required = workspace.workspaceType === "local" && (await this.mode(workspace).catch(() => null))?.source === "required";
+ const oldChat = capture && turnsSoFar > 0 && !this.boxedChats.has(sessionId) && !this.turns.has(sessionId) && savedTurns(this.snapshotDir(sessionId)) === 0;
+ if (required && oldChat && !this.nativeChats.has(sessionId)) {
+ this.nativeChats.set(sessionId, boxKey(boxRoot(workspace)));
+ await this.writeProjects();
+ this.log("info", "box: a chat that ran on this machine stays there", { sessionId, turnsBefore, required: true });
+ }
+ const run = required && !this.nativeChats.has(sessionId) ? await this.waitForBox(workspace) : await this.ensure(workspace).catch(() => null);
if (!run || run.native) return null;
// A chat with turns but no checkpoint ran on this machine (reopened, or started in this run before the
// server's default reached the app, or while the image downloaded): when only the server's default
// turned the box on, it goes on here (new chats get the box); a project turned on by its user moves it.
- if (capture && turnsSoFar > 0 && !this.nativeChats.has(sessionId) && !this.boxedChats.has(sessionId) && !this.turns.has(sessionId) && savedTurns(this.snapshotDir(sessionId)) === 0 && ["server", "buildathon"].includes((await this.mode(workspace)).source)) {
+ if (capture && turnsSoFar > 0 && !this.nativeChats.has(sessionId) && !this.boxedChats.has(sessionId) && !this.turns.has(sessionId) && savedTurns(this.snapshotDir(sessionId)) === 0 && ["server", "buildathon", "required"].includes((await this.mode(workspace)).source)) {
this.nativeChats.set(sessionId, run.key);
await this.writeProjects();
this.log("info", "box: a chat that ran on this machine stays there", { sessionId, turnsBefore });
@@ -633,20 +783,56 @@ export class BoxService {
return { key: run.key, root: run.root, croot: box.croot, container: box.container, runtimeBin: run.runtimeBin, runtimeArgs: run.runtimeArgs, backend: run.backend, exec: run.exec, label };
}
+ /**
+ * Required: the project's box, waited for while its image downloads (at
+ * most REQUIRED_WAIT_MS; planned again as soon as the download ends). Null
+ * when it cannot run here (no backend: the setup screen says why; the
+ * chat goes on per the server's required_fallback).
+ */
+ private async waitForBox(workspace: BoxWorkspace): Promise<BoxRun | null> {
+ const key = boxKey(boxRoot(workspace));
+ const until = Date.now() + REQUIRED_WAIT_MS;
+ for (;;) {
+ const run = await this.ensure(workspace).catch(() => null);
+ if (run) return run;
+ const project = this.projects.get(key);
+ if (project?.why?.reason !== "downloading" || Date.now() >= until) return null;
+ await new Promise((resolve) => setTimeout(resolve, REQUIRED_POLL_MS));
+ const pull = project.pull;
+ if (pull && !pulling(this.home, pull.runtime, pull.image.pull)) project.nextPlanAt = 0;
+ }
+ }
+
/** The chat's box.plan outcome, once per chat and app run (null after that, or for a folder not on this computer). */
async planOutcome(sessionId: string, workspace: BoxWorkspace): Promise<BoxPlanOutcome | null> {
if (workspace.workspaceType !== "local" || this.outcomeSent.has(sessionId)) return null;
this.outcomeSent.add(sessionId);
const mode = await this.mode(workspace).catch(() => null);
if (!mode) return { native: true, source: null, reason: "plan_failed" };
- if (this.nativeChats.has(sessionId)) return { native: true, source: "chat", reason: "kept_old_chat" };
- if (this.boxedChats.has(sessionId)) return { native: false, source: mode.source, reason: "box" };
- if (!mode.on) return { native: true, source: mode.source, reason: mode.source === "host-builds" ? "host_builds" : mode.offer ? "offer" : "off" };
+ const { fallback } = this.required();
+ // Required: every outcome says so; a chat that runs here names the fallback the server set.
+ const required = mode.required ? { required: true as const } : {};
+ const native = (reason: string, extra: Partial<BoxPlanOutcome> = {}): BoxPlanOutcome => ({ native: true, source: mode.source, reason, ...required, ...(mode.required ? { fallback } : {}), ...extra });
+ if (this.nativeChats.has(sessionId)) return native("kept_old_chat", { source: "chat" });
+ if (this.boxedChats.has(sessionId)) return { native: false, source: mode.source, reason: "box", ...required };
+ if (!mode.on) {
+ if (mode.required && mode.source === "env") return native("env_off");
+ if (mode.source === "host-only") return native("host_only");
+ return native(mode.source === "host-builds" ? "host_builds" : mode.offer ? "offer" : "off");
+ }
const project = this.projects.get(boxKey(boxRoot(workspace)));
- if (project?.run?.native) return { native: true, source: mode.source, reason: "box_failed" };
- if (project?.why) return { native: true, source: mode.source, reason: project.why.reason, ...(project.why.runtime ? { runtime: project.why.runtime } : {}) };
+ if (project?.run?.native) return native("box_failed");
+ if (project?.why) {
+ const runtime = project.why.runtime ? { runtime: project.why.runtime } : {};
+ if (mode.required && project.why.reason !== "downloading") {
+ const setup = await this.setupFor(project.lastRuntime ?? null).catch(() => null);
+ const reason = setup?.need === "cannot_run" || project.why.reason === "helpers_missing" ? "cannot_run" : setup?.declined ? "setup_declined" : "setup_needed";
+ return native(reason, runtime);
+ }
+ return native(project.why.reason, runtime);
+ }
// Not planned yet (a plan still running, or waiting for its next try).
- return { native: true, source: mode.source, reason: "planning" };
+ return native("planning");
}
/** Whether chats ran in a box during this run (they get a `final` checkpoint at quit). */
diff --git a/apps/server/src/box/setup.ts b/apps/server/src/box/setup.ts
new file mode 100644
index 00000000..1de3c5b6
--- /dev/null
+++ b/apps/server/src/box/setup.ts
@@ -0,0 +1,260 @@
+// The sandbox's one-time setup when it is required (required.json `setup`),
+// run by the app for the user. This module runs in the desktop app's main
+// process (the embedded server):
+//
+// - Linux, AppArmor blocking user namespaces (Ubuntu 23.10+): "Allow the
+// sandbox" runs the CLI's `sandbox enable` step through pkexec (one polkit
+// prompt): OmniRush's bubblewrap copied root-owned to ENABLED_BWRAP and its
+// AppArmor profile loaded. Nothing system-wide changes.
+// - Windows, WSL 2 missing: "Set up (one restart)" runs the shared install
+// script elevated (one UAC prompt: one `Start-Process -Verb RunAs -Wait`
+// with a temp .ps1 and a log), then an HKCU RunOnce value reopens the app
+// after the restart, which finishes the setup (WSL update when it asks for
+// one, the distro import and the image download: the usual box start).
+// - Windows that cannot run WSL 2 (virtualization off in the firmware, a VM
+// without nested virtualization, S mode, an old build, a policy): why, from
+// PowerShell CIM before the install and WSL's errors after it.
+// - macOS: the OmniRush VM (Lima) is a separate backend; until it is in this
+// build, a Mac without a running container app reads "runtime" (the card's
+// usual next step).
+//
+// The state of the last setup step is in <box home>/setup.json.
+
+import { createHash } from "node:crypto";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { GOARCH, helperPath } from "./common.js";
+import { APPARMOR_PROFILE, ENABLED_BWRAP, apparmorProfile } from "./backends/bwrap.js";
+import { REQUIRED_RULES, parseWindowsFacts, virtualizationError, whyText, windowsInstallScript, windowsWhy, WINDOWS_FACTS_SCRIPT, type CannotRunWhy, type RequiredFallback, type WindowsFacts } from "./required.js";
+import { runCommand, type RunCommand, type RuntimeResult } from "./runtime.js";
+
+/** What the sandbox needs on this computer before it can run. */
+export type SetupNeed = "none" | "linux_allow" | "win_install" | "win_restart" | "win_update" | "mac_vm" | "runtime" | "cannot_run";
+
+export type BoxSetup = {
+ need: SetupNeed;
+ /** cannot_run: why (required.json texts.why), and in words. */
+ why: CannotRunWhy | null;
+ whyText: string | null;
+ /** The user cancelled the setup (the admin prompt, or "Not now"): chats run here meanwhile. */
+ declined: boolean;
+ /** The last setup step's answer (the polkit prompt, the install): one line. */
+ result: { ok: boolean; message: string; at: number } | null;
+ /** What a chat does while the sandbox cannot run (the server's required_fallback). */
+ fallback: RequiredFallback;
+};
+
+type StepState = { state: "installed" | "allowed" | "failed" | "declined"; at: number; message: string; update?: number };
+export type SetupState = { win?: StepState; linux?: StepState; declinedAt?: number };
+
+export function setupFile(home: string): string {
+ return path.join(home, "setup.json");
+}
+
+export function readSetupState(home: string): SetupState {
+ try {
+ const value: unknown = JSON.parse(readFileSync(setupFile(home), "utf8"));
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
+ } catch {
+ return {};
+ }
+}
+
+export function writeSetupState(home: string, update: (state: SetupState) => SetupState): SetupState {
+ const next = update(readSetupState(home));
+ try {
+ mkdirSync(home, { recursive: true });
+ const tmp = `${setupFile(home)}.${process.pid}.tmp`;
+ writeFileSync(tmp, JSON.stringify(next), { mode: 0o600 });
+ renameSync(tmp, setupFile(home));
+ } catch { /* best effort */ }
+ return next;
+}
+
+/** Every reason the backend probe gave (the chosen one's and each tried one's). */
+function reasons(runtime: RuntimeResult | null): string[] {
+ if (!runtime || runtime.ok) return [];
+ return [runtime.reason, ...(runtime.tried ?? []).map((tried) => tried.reason)].filter(Boolean);
+}
+
+/**
+ * What the sandbox needs here, from the backend probe, this machine's facts
+ * (Windows) and the last setup step. Pure.
+ */
+export function classifySetup({ runtime, platform, facts = null, state = {}, fallback, macVm = false }: { runtime: RuntimeResult | null; platform: string; facts?: WindowsFacts | null; state?: SetupState; fallback: RequiredFallback; macVm?: boolean }): BoxSetup {
+ const step = platform === "win32" ? state.win : platform === "linux" ? state.linux : undefined;
+ const base = { why: null, whyText: null, declined: Boolean(state.declinedAt), result: step ? { ok: step.state === "installed" || step.state === "allowed", message: step.message, at: step.at } : null, fallback };
+ if (runtime?.ok) return { ...base, need: "none", declined: false };
+ const said = reasons(runtime);
+ const cannot = (why: CannotRunWhy | null, text?: string | null): BoxSetup => ({ ...base, need: "cannot_run", why, whyText: why ? whyText(why) : text ?? null, declined: false });
+ if (platform === "linux") {
+ if (said.some((reason) => /sandbox enable/.test(reason))) return { ...base, need: "linux_allow" };
+ const blocked = said.find((reason) => /user namespaces|inside a container|container engine/i.test(reason));
+ if (blocked && !said.some((reason) => /apt install|usermod|systemctl start/.test(reason))) return cannot(null, blocked);
+ return { ...base, need: "runtime" };
+ }
+ if (platform === "win32") {
+ const why = facts ? windowsWhy({ ...facts, wslSaid: step?.message ?? null, policy: /policy/i.test(step?.message ?? "") }) : null;
+ if (why) return cannot(why);
+ if (said.some((reason) => /wsl --update/.test(reason))) return { ...base, need: "win_update" };
+ if (said.some((reason) => /WSL 2 is not enabled/.test(reason))) return { ...base, need: step?.state === "installed" ? "win_restart" : "win_install" };
+ return { ...base, need: "runtime" };
+ }
+ if (platform === "darwin") {
+ const version = Number(/^(\d+)/.exec(os.release())?.[1] ?? 0);
+ // Darwin 22 is macOS 13.
+ if (version && version < 22) return cannot("old_macos");
+ return { ...base, need: macVm ? "mac_vm" : "runtime" };
+ }
+ return { ...base, need: "runtime" };
+}
+
+// --- Windows -------------------------------------------------------------------------------
+
+let factsCache: { at: number; facts: WindowsFacts } | null = null;
+
+/** This Windows' facts (PowerShell CIM), cached for 10 minutes unless `fresh`. */
+export async function windowsFacts({ run = runCommand, fresh = false, now = Date.now() }: { run?: RunCommand; fresh?: boolean; now?: number } = {}): Promise<WindowsFacts> {
+ if (!fresh && factsCache && now - factsCache.at < 10 * 60_000) return factsCache.facts;
+ const res = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FACTS_SCRIPT], { timeoutMs: 15_000 });
+ const facts = parseWindowsFacts(res.stdout);
+ factsCache = { at: now, facts };
+ return facts;
+}
+
+/** A PowerShell single-quoted string. */
+function psQuote(value: string): string {
+ return `'${value.replace(/'/g, "''")}'`;
+}
+
+/** The one elevated start: the .ps1 with its log path, waited for; exit 1223 when the admin prompt was cancelled. */
+export function elevatedCommand(script: string, log: string): string {
+ return [
+ "try {",
+ `$p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-File',${psQuote(`"${script}"`)},${psQuote(`"${log}"`)}) -Verb RunAs -Wait -PassThru -WindowStyle Hidden;`,
+ "exit $p.ExitCode",
+ "} catch { Write-Output 'cancelled'; exit 1223 }",
+ ].join(" ");
+}
+
+/** The HKCU RunOnce value that reopens the app after the restart. */
+export function runOnceArgs(exe: string): string[] {
+ return ["add", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "/v", REQUIRED_RULES.setup.win32.resume_run_once, "/t", "REG_SZ", "/d", `"${exe}"`, "/f"];
+}
+
+/**
+ * Turn on WSL 2 (the shared install script, elevated once). Installed: the
+ * RunOnce value is set (`exe`: the app) and the state says a restart is
+ * needed; cancelled at the admin prompt: declined.
+ */
+export async function windowsInstall({ home, run = runCommand, exe = process.versions.electron ? process.execPath : null, tmp = os.tmpdir() }: { home: string; run?: RunCommand; exe?: string | null; tmp?: string }): Promise<StepState> {
+ const dir = path.join(tmp, `omnirush-setup-${process.pid}-${Date.now()}`);
+ mkdirSync(dir, { recursive: true });
+ const script = path.join(dir, "setup.ps1");
+ const log = path.join(home, "setup-wsl.log");
+ mkdirSync(home, { recursive: true });
+ writeFileSync(script, windowsInstallScript());
+ writeFileSync(log, "");
+ const res = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", elevatedCommand(script, log)], { timeoutMs: 30 * 60_000 });
+ let said = "";
+ try { said = readFileSync(log, "utf8"); } catch { /* none */ }
+ rmSync(dir, { recursive: true, force: true });
+ const last = said.trim().split(/\r?\n/).filter((line) => line.trim() && line.trim() !== "done").pop()?.trim().slice(0, 300) ?? "";
+ let step: StepState;
+ if (res.code === 1223 || /cancelled/.test(res.stdout)) step = { state: "declined", at: Date.now(), message: "The administrator prompt was cancelled." };
+ else if (/\bdone\b/.test(said) && !virtualizationError(said)) step = { state: "installed", at: Date.now(), message: last || "WSL 2 is installed." };
+ else step = { state: "failed", at: Date.now(), message: last || `The setup stopped (${res.code}).` };
+ if (step.state === "installed" && exe) await run("reg.exe", runOnceArgs(exe), { timeoutMs: 15_000 });
+ writeSetupState(home, (state) => ({ ...state, win: step, ...(step.state === "declined" ? { declinedAt: step.at } : { declinedAt: undefined }) }));
+ return step;
+}
+
+/** Restart Windows now (the screen's "Restart now"; never while a chat runs: the caller checks). */
+export function windowsRestart({ run = runCommand }: { run?: RunCommand } = {}): Promise<unknown> {
+ return run("shutdown.exe", ["/r", "/t", "5", "/c", "OmniRush finishes the sandbox setup after the restart."], { timeoutMs: 15_000 });
+}
+
+/** After the restart, WSL asks for an update: `wsl --update` once (it asks for admin itself when it needs to). */
+export async function windowsUpdate({ home, run = runCommand }: { home: string; run?: RunCommand }): Promise<StepState> {
+ const res = await run("wsl.exe", ["--update", "--web-download"], { timeoutMs: 15 * 60_000, env: { ...process.env, WSL_UTF8: "1" } });
+ const step: StepState = { ...(readSetupState(home).win ?? { state: "installed", at: Date.now(), message: "" }), update: Date.now(), message: res.code === 0 ? "WSL is up to date." : `\`wsl --update\` stopped (${res.code}).` };
+ writeSetupState(home, (state) => ({ ...state, win: step }));
+ return step;
+}
+
+/** The setup finished (the box is ready): the step and the RunOnce value are no longer needed. */
+export async function setupDone(home: string, { platform = process.platform, run = runCommand }: { platform?: string; run?: RunCommand } = {}): Promise<void> {
+ const state = readSetupState(home);
+ if (!state.win && !state.linux && !state.declinedAt) return;
+ writeSetupState(home, () => ({}));
+ if (platform === "win32" && state.win) {
+ await run("reg.exe", ["delete", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "/v", REQUIRED_RULES.setup.win32.resume_run_once, "/f"], { timeoutMs: 15_000 });
+ }
+}
+
+// --- Linux -------------------------------------------------------------------------------------
+
+/**
+ * The root step `sandbox enable` does (CLI src/box/backends/bwrap.js
+ * enableBwrap), as one shell script for pkexec: $1 is the bubblewrap to
+ * install (checked against $2, its sha256), copied root-owned to
+ * ENABLED_BWRAP, and the AppArmor profile for that copy only.
+ */
+export function linuxAllowScript(): string {
+ const dir = path.posix.dirname(ENABLED_BWRAP);
+ return [
+ "set -eu",
+ 'src="$1"; sum="$2"',
+ `dst=${ENABLED_BWRAP}; prof=${APPARMOR_PROFILE}`,
+ `mkdir -p ${dir}`,
+ 'cp "$src" "$dst.tmp"',
+ 'if [ -n "$sum" ] && [ "$(sha256sum "$dst.tmp" | cut -d" " -f1)" != "$sum" ]; then rm -f "$dst.tmp"; echo "checksum mismatch" >&2; exit 3; fi',
+ 'chown 0:0 "$dst.tmp"; chmod 0755 "$dst.tmp"; mv -f "$dst.tmp" "$dst"',
+ `chown 0:0 ${dir}; chmod 0755 ${dir}`,
+ 'parser=""; for p in /sbin/apparmor_parser /usr/sbin/apparmor_parser; do [ -x "$p" ] && parser="$p" && break; done',
+ 'if [ -z "$parser" ] || [ ! -d /etc/apparmor.d ]; then echo "installed; no AppArmor here"; exit 0; fi',
+ `cat > "$prof" <<'OMNIRUSH_PROFILE'`,
+ apparmorProfile(ENABLED_BWRAP).trimEnd(),
+ "OMNIRUSH_PROFILE",
+ 'chmod 0644 "$prof"',
+ '"$parser" -r "$prof"',
+ 'echo "installed; AppArmor profile loaded"',
+ ].join("\n");
+}
+
+/** The bubblewrap "Allow" installs: the one shipped with the app, else the system's. */
+export function allowSource({ env = process.env, arch = process.arch, exists = existsSync }: { env?: NodeJS.ProcessEnv; arch?: string; exists?: (file: string) => boolean } = {}): string | null {
+ const shipped = helperPath("bwrap", { goos: "linux", goarch: GOARCH[arch] || "amd64", env });
+ if (shipped) return shipped;
+ return ["/usr/bin/bwrap", "/usr/local/bin/bwrap"].find((file) => exists(file)) ?? null;
+}
+
+/**
+ * "Allow the sandbox": pkexec (OMNIRUSH_BOX_PKEXEC replaces it in test rigs)
+ * runs linuxAllowScript as root. The bubblewrap is first copied to the box
+ * home (root may not read the app's own mount, an AppImage). pkexec exits
+ * 126 when the prompt was dismissed and 127 when not authorised.
+ */
+export async function linuxAllow({ home, env = process.env, run = runCommand, source = allowSource({ env }) }: { home: string; env?: NodeJS.ProcessEnv; run?: RunCommand; source?: string | null }): Promise<StepState> {
+ let step: StepState;
+ if (!source) {
+ step = { state: "failed", at: Date.now(), message: "No bubblewrap to install: install your system's bubblewrap package, then try again." };
+ } else {
+ const staged = path.join(home, "setup-bwrap");
+ mkdirSync(home, { recursive: true });
+ copyFileSync(source, staged);
+ const sum = createHash("sha256").update(readFileSync(staged)).digest("hex");
+ const pkexec = String(env.OMNIRUSH_BOX_PKEXEC || "").trim() || "pkexec";
+ const res = await run(pkexec, ["/bin/sh", "-c", linuxAllowScript(), "omnirush-sandbox-allow", staged, sum], { timeoutMs: 10 * 60_000 });
+ rmSync(staged, { force: true });
+ const said = `${res.stdout}\n${res.stderr}`.trim().split("\n").filter(Boolean).pop()?.slice(0, 300) ?? "";
+ if (res.code === 0) step = { state: "allowed", at: Date.now(), message: said ? `Allowed (${said}).` : "Allowed." };
+ else if (res.code === 126) step = { state: "declined", at: Date.now(), message: "The password prompt was dismissed." };
+ else if (res.code === 127 || res.error === "ENOENT") step = { state: "failed", at: Date.now(), message: res.error === "ENOENT" ? "pkexec is missing: run `sudo omnirush sandbox enable` in a terminal instead (OmniRush CLI)." : `Not authorised${said ? `: ${said}` : ""}.` };
+ else step = { state: "failed", at: Date.now(), message: said || `The step stopped (${res.code}).` };
+ }
+ writeSetupState(home, (state) => ({ ...state, linux: step, ...(step.state === "declined" ? { declinedAt: step.at } : { declinedAt: undefined }) }));
+ return step;
+}
diff --git a/apps/server/src/routes/workspaces.ts b/apps/server/src/routes/workspaces.ts
index 4ef1971e..ade8ebb6 100644
--- a/apps/server/src/routes/workspaces.ts
+++ b/apps/server/src/routes/workspaces.ts
@@ -39,6 +39,8 @@ interface RegisterWorkspaceRoutesOptions {
* processes, open handles) is released. Best effort; never throws.
*/
stopWorkspaceWork?: (config: ServerConfig, workspace: WorkspaceInfo) => Promise<void>;
+ /** A local workspace was added or made active: its sandbox starts now, in the background (box/service.ts opened). */
+ onWorkspaceOpened?: (config: ServerConfig, workspace: WorkspaceInfo) => void;
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -313,6 +315,7 @@ export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions)
resolveWorkspace,
serializeWorkspace,
syncWorkspaceRuntimeMcp,
+ onWorkspaceOpened,
} = options;
const resolveWorkspaceForRegistry = async (id: string): Promise<WorkspaceInfo> => {
@@ -343,6 +346,7 @@ export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions)
const { workspace, persisted } = await addLocalWorkspace(config, { folderPath, name, preset, actor: ctx.actor });
onWorkspacesChanged();
+ onWorkspaceOpened?.(config, workspace);
return jsonResponse({
activeId: workspace.id,
@@ -509,6 +513,7 @@ export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions)
if (!wasActive && workspace.workspaceType === "local" && resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim()) {
void syncWorkspaceRuntimeMcp(config, workspace).catch(() => undefined);
}
+ if (workspace.workspaceType === "local") onWorkspaceOpened?.(config, workspace);
return jsonResponse({ activeId: workspace.id, workspace: serializeWorkspace(workspace), persisted });
});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index e01ebd9b..22feb119 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -179,6 +179,7 @@ import {
writeOmniRushWorkspaceConfig,
} from "./omnirush-workspace-config-store.js";
import { boxServiceFor } from "./box/desktop.js";
+import { BOX_SETUP_ACTIONS, BoxRequiredError, isBoxSetupAction } from "./box/service.js";
import { boxHome } from "./box/common.js";
import { buildathonProjectsFile, reproStateFromBody, writeReproState } from "./buildathon-repro.js";
import { prepareBoxInstallLog } from "./box/install-log.js";
@@ -1427,6 +1428,8 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
});
}
void boxes.ensureAll();
+ // The server asks for the sandbox images ahead (local_box.setup.prefetch): the base image too, in the background.
+ void boxes.prefetch().catch(() => false);
if (config.clearUploadQueue) {
// The user signed out: what the last account queued stays on disk for it (stamped with it, set aside
// at the next start under another account, sent after its own next sign-in).
@@ -3182,6 +3185,7 @@ async function applyServerBoxDefault(config: ServerConfig, boxes: ReturnType<typ
await boxes.serverBackendsChanged();
await applyBoxEngineConfig(config, "local_box_default");
await boxes.ensureAll();
+ void boxes.prefetch().catch(() => false);
}
/**
@@ -3615,6 +3619,8 @@ function createRoutes(
trigger: "workspace_activate",
}),
stopWorkspaceWork: stopWorkspaceEngineWork,
+ // Opening a project starts its sandbox now (not at its first prompt).
+ onWorkspaceOpened: (routeConfig, workspace) => boxServiceFor(routeConfig).opened(workspace),
});
registerWorkspaceTaskRoutes({
@@ -4256,8 +4262,15 @@ function createRoutes(
if (workspace.workspaceType !== "local") throw new ApiError(400, "box_unsupported", "The sandbox is for folders on this computer");
const boxes = boxServiceFor(config);
const before = JSON.stringify(await boxes.engineBits());
- if (typeof body.backend === "string") await boxes.setBackend(body.backend);
- const status = "mode" in body && (mode === "on" || mode === "off" || mode === null) ? await boxes.setMode(workspace, mode) : await boxes.status(workspace, { fresh: true });
+ // Required for new chats (local_box.required): "off" and the backend "native" are refused.
+ let status: Awaited<ReturnType<typeof boxes.status>>;
+ try {
+ if (typeof body.backend === "string") await boxes.setBackend(body.backend);
+ status = "mode" in body && (mode === "on" || mode === "off" || mode === null) ? await boxes.setMode(workspace, mode) : await boxes.status(workspace, { fresh: true });
+ } catch (error) {
+ if (error instanceof BoxRequiredError) throw new ApiError(409, error.code, error.message);
+ throw error;
+ }
// The engine gets the box shell and plugin when the first workspace turns its box on (and loses them with the last).
const engine = JSON.stringify(await boxes.engineBits()) === before ? { status: "unchanged" as const } : await applyBoxEngineConfig(config, "local_box");
return jsonResponse({ ...status, engine });
@@ -4292,6 +4305,25 @@ function createRoutes(
return jsonResponse(await boxServiceFor(config).retry(workspace));
});
+ // The sandbox's one-time setup when it is required (box/setup.ts): `linux_allow` (pkexec), `win_install`
+ // (one UAC prompt), `win_restart` (refused while a chat runs), `win_update`, `decline` ("Not now": chats
+ // run here meanwhile), `check` (look again). Answers the status after the step.
+ addRoute(routes, "POST", "/workspace/:id/box/setup", "client", async (ctx) => {
+ ensureWritable(config);
+ requireClientScope(ctx, "collaborator");
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ const body = await readJsonBody(ctx.request);
+ const action = body.action;
+ if (Object.keys(body).some((key) => key !== "action") || !isBoxSetupAction(action)) {
+ throw new ApiError(400, "invalid_payload", `action must be one of ${BOX_SETUP_ACTIONS.join(", ")}`);
+ }
+ if (workspace.workspaceType !== "local") throw new ApiError(400, "box_unsupported", "The sandbox is for folders on this computer");
+ if (action === "win_restart" && (await collectBusyEngineSessions(config).catch(() => ({ sessions: [], unknown: 0 }))).sessions.length > 0) {
+ throw new ApiError(409, "chat_running", "A chat is running: restart when it has finished.");
+ }
+ return jsonResponse(await boxServiceFor(config).setup(workspace, action));
+ });
+
addRoute(routes, "POST", "/workspace/:id/box/reset", "client", async (ctx) => {
ensureWritable(config);
requireClientScope(ctx, "collaborator");