Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: windows sandbox setup and fallback record

ogsamrat4b95d3c8638f
diff --git a/apps/server/src/box/PARITY.sha256 b/apps/server/src/box/PARITY.sha256
index 8242423a..32203a0e 100644
--- a/apps/server/src/box/PARITY.sha256
+++ b/apps/server/src/box/PARITY.sha256
@@ -8,4 +8,4 @@ fd7531323e200f2133cdf66ed8608d04af3a38049cfeb01a0a285cbd72813c4d wsl.json
ec1c7507cd3919a1066c870e3f7018424bdca8641fbf34fec9c4eefd9def1d29 host-builds.json
fe040597bec7f113721071097906380c51198d0cc785747c3891b754e55f34a2 retention.mjs
e0478a8e95284a9f1713ee695dd5a2a7123991b2ab2d45297a09369cce037da7 retention.d.mts
-aaea65133667e6d4033b3ffcbf30ba1e9ccf8fefc32426ae57adb440a2a27382 required.json
+9175d3ce53049291eb2cf2a6641fd2fc15263769f9a2b6256c2744581a60dfde required.json
diff --git a/apps/server/src/box/box-ports.test.ts b/apps/server/src/box/box-ports.test.ts
index fce32bb7..d8d7e46e 100644
--- a/apps/server/src/box/box-ports.test.ts
+++ b/apps/server/src/box/box-ports.test.ts
@@ -255,7 +255,20 @@ describe("box ports on this computer", () => {
}
});
- test("boxRun: forwards only for a backend with its own network, unless OMNIRUSH_BOX_PORTS=off; closed with the run", async () => {
+ test("boxRun: no port forwards without the required sandbox (as before), whatever the backend", () => {
+ const box = { ready: true, error: null, endpoint: { host: "127.0.0.1", port: 1, token: "t" }, setTurn() {} };
+ const made: PortForwardOptions[] = [];
+ const stub = (opts: PortForwardOptions): PortForwards => { made.push(opts); return { tick: async () => {}, ports: () => [], close() {} }; };
+ for (const backend of ["docker", "podman", "apple", "wslc"]) {
+ const home = mkdtempSync(path.join(os.tmpdir(), "box-ports-"));
+ mkdirSync(path.join(home, "boxes"), { recursive: true });
+ const plan = { box: { key: "k1", home, root: "/p", runtime: { name: backend, backend, bin: "/x/rt" } }, notice: null, shell: "/x/boxsh", phase: "ready", start: async () => box as unknown as Box } as unknown as ReadyPlan;
+ boxRun(plan, { forwards: stub, env: {}, ping: (async () => ({})) as never }).close();
+ }
+ expect(made.length).toBe(0);
+ });
+
+ test("boxRun under required: forwards only for a backend with its own network, unless OMNIRUSH_BOX_PORTS=off; closed with the run", async () => {
const box = { ready: true, error: null, endpoint: { host: "127.0.0.1", port: 1, token: "t" }, setTurn() {} };
const plan = (backend: string): ReadyPlan => {
const home = mkdtempSync(path.join(os.tmpdir(), "box-ports-"));
@@ -269,7 +282,7 @@ describe("box ports on this computer", () => {
return { tick: async () => {}, ports: () => [4000], close() { entry.closed = true; } };
};
const said: unknown[] = [];
- const docker = boxRun(plan("docker"), { forwards: stub, env: {}, ping: (async () => ({})) as never, onPort: (e) => said.push(e) });
+ const docker = boxRun(plan("docker"), { forwards: stub, env: {}, ping: (async () => ({})) as never, onPort: (e) => said.push(e), required: true });
expect(made.length).toBe(1);
await docker.ready();
expect(made[0]!.opts.endpoint()).toEqual(box.endpoint);
@@ -279,9 +292,9 @@ describe("box ports on this computer", () => {
docker.close();
expect(made[0]!.closed).toBe(true);
expect(made[0]!.opts.endpoint()).toBeNull();
- boxRun(plan("bwrap"), { forwards: stub, env: {} }).close();
- boxRun(plan("wsl"), { forwards: stub, env: {} }).close();
- boxRun(plan("podman"), { forwards: stub, env: { OMNIRUSH_BOX_PORTS: "off" } }).close();
+ boxRun(plan("bwrap"), { forwards: stub, env: {}, required: true }).close();
+ boxRun(plan("wsl"), { forwards: stub, env: {}, required: true }).close();
+ boxRun(plan("podman"), { forwards: stub, env: { OMNIRUSH_BOX_PORTS: "off" }, required: true }).close();
expect(made.length).toBe(1);
});
});
diff --git a/apps/server/src/box/box-required-service.test.ts b/apps/server/src/box/box-required-service.test.ts
index 30fc6a10..5fa32543 100644
--- a/apps/server/src/box/box-required-service.test.ts
+++ b/apps/server/src/box/box-required-service.test.ts
@@ -92,10 +92,10 @@ describe("required sandbox: the desktop's projects", () => {
expect(status.setup).toMatchObject({ need: process.platform === "linux" ? "runtime" : expect.any(String), fallback: "native", declined: false });
// No step this app can run here (no backend at all): the chat runs here, as cannot_run (the CLI's reason too).
expect(await boxes.beforePrompt("ses_req_none1", workspace)).toBeNull();
- expect(await boxes.planOutcome("ses_req_none1", workspace)).toMatchObject({ native: true, source: "required", reason: "cannot_run", required: true, fallback: "native" });
+ expect(await boxes.planOutcome("ses_req_none1", workspace)).toMatchObject({ native: true, source: "required", reason: "cannot_run", required: true, capable: false, fallback: "native" });
});
- test("a box that fails to start under required reports the fallback in force", async () => {
+ test("a box that fails to start under required is a machine that can't run it: fallback native (counted in full)", async () => {
const stateDir = await temp("state");
const root = await temp("project");
const workspace: BoxWorkspace = { id: "ws_fail", path: root, workspaceType: "local" };
@@ -103,7 +103,7 @@ describe("required sandbox: the desktop's projects", () => {
const boxes = service({ stateDir, workspaces: [workspace], env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), ...NO_RUNTIME } });
const projects: Map<string, unknown> = Reflect.get(boxes, "projects");
projects.set(boxKey(root), { run: { ...fakeRun(root, []), native: true }, notice: null, planning: null, nextPlanAt: Date.now() + 60_000, waitingImage: false });
- expect(await boxes.planOutcome("ses_req_fail1", workspace)).toEqual({ native: true, source: "required", reason: "box_failed", required: true, fallback: "native_uncounted" });
+ expect(await boxes.planOutcome("ses_req_fail1", workspace)).toEqual({ native: true, source: "required", reason: "box_failed", required: true, capable: false, fallback: "native" });
});
test("planBox under required: a backend slow to answer (a VM booting) is waited for, not \"did not answer in time\"", async () => {
@@ -142,8 +142,8 @@ describe("required sandbox: the desktop's projects", () => {
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 });
- expect(await boxes.planOutcome("ses_req_new1", workspace)).toEqual({ native: false, source: "required", reason: "box", required: true });
+ 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, capable: true });
expect(JSON.parse(await readFile(join(home, DESKTOP_PROJECTS_FILE), "utf8")).native_chats).toEqual(["ses_req_old1"]);
});
@@ -178,7 +178,7 @@ describe("required sandbox: the desktop's projects", () => {
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 });
+ expect(await off.planOutcome("ses_req_env1", workspace)).toEqual({ native: true, source: "env", reason: "env_off", required: true, capable: true, fallback: "native" });
const mac = await temp("macproject");
await mkdir(join(mac, "App.xcodeproj"));
@@ -187,7 +187,7 @@ describe("required sandbox: the desktop's projects", () => {
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 });
+ 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");
diff --git a/apps/server/src/box/box-required.test.ts b/apps/server/src/box/box-required.test.ts
index aa4059e4..93fa2679 100644
--- a/apps/server/src/box/box-required.test.ts
+++ b/apps/server/src/box/box-required.test.ts
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
-import { desktopText, hostOnlyProject, requiredFallback, whyText } from "./required.js";
+import { desktopText, hostOnlyProject, requiredFallback, requiredLaunch, whyText } from "./required.js";
describe("required sandbox rules", () => {
test("fallback and texts", () => {
@@ -34,4 +34,12 @@ describe("required sandbox rules", () => {
writeFileSync(path.join(swift, "Package.swift"), "let package = Package(name: \"x\")");
expect(hostOnlyProject(swift, { platform: "darwin" })).toBeNull();
});
+
+ test("launch record: a machine that can't run the box says so (fallback native, counted); turned off or declined gets the server's fallback (CLI: the same)", () => {
+ expect(requiredLaunch("box", { native: false })).toEqual({ required: true, capable: true });
+ for (const reason of ["cannot_run", "box_failed", "setup_needed", "planning", "downloading"]) expect(requiredLaunch(reason, { native: true, serverFallback: "native_uncounted" })).toEqual({ required: true, capable: false, fallback: "native" });
+ for (const reason of ["env_off", "setup_declined"]) expect(requiredLaunch(reason, { native: true, serverFallback: "native_uncounted" })).toEqual({ required: true, capable: true, fallback: "native_uncounted" });
+ expect(requiredLaunch("env_off", { native: true, serverFallback: "bogus" }).fallback).toBe("native");
+ for (const reason of ["kept_old_chat", "host_only"]) expect(requiredLaunch(reason, { native: true, serverFallback: "native_uncounted" })).toEqual({ required: true, fallback: "native" });
+ });
});
diff --git a/apps/server/src/box/box-setup.test.ts b/apps/server/src/box/box-setup.test.ts
index e6881c22..845afa3c 100644
--- a/apps/server/src/box/box-setup.test.ts
+++ b/apps/server/src/box/box-setup.test.ts
@@ -1,11 +1,12 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import path, { join } from "node:path";
import type { RunCommand } from "./run.js";
import { ENABLE_HINT, probeWslDistro, withoutWsl1Notes } from "./backends/wsl.js";
-import { blockedWhy, classifySetup, elevatedArgs, installLogFile, linuxAllow, linuxAllowScript, parseInstallLog, recentlyDeclined, resumeWinSetup, runOnceArgs, saveSetupState, setupDecision, setupState, windowsBuild, windowsInstall } from "./setup.js";
+import { RESUME_UPDATE_WAIT_MS, blockedWhy, classifySetup, elevatedArgs, installLogFile, linuxAllow, linuxAllowScript, parseInstallLog, recentlyDeclined, resumeWinSetup, runOnceArgs, saveSetupState, setupDecision, setupState, windowsBuild, windowsInstall } from "./setup.js";
+import { REQUIRED_RULES } from "./required.js";
const dirs: string[] = [];
afterEach(async () => {
@@ -67,8 +68,10 @@ describe("sandbox setup: what is needed", () => {
expect(setupDecision({ ...checks, firmware: false, model: "innotek GmbH VirtualBox" })).toEqual({ ok: false, why: "nested_vm" });
expect(setupDecision(null)).toEqual({ ok: true });
expect(parseInstallLog("\uFEFFInstalling\r\nThe operation completed successfully.\r\ndone\r\n")).toEqual({ result: "installed" });
- expect(parseInstallLog("Error: 0x80370102 Please enable the Virtual Machine Platform\r\ndone")).toEqual({ result: "blocked", why: "firmware_off" });
- expect(parseInstallLog("This feature is blocked by group policy\r\ndone")).toEqual({ result: "blocked", why: "policy" });
+ expect(parseInstallLog("Error: 0x80370102 Please enable the Virtual Machine Platform\r\nfailed 1")).toEqual({ result: "blocked", why: "firmware_off" });
+ expect(parseInstallLog("This feature is blocked by group policy\r\nfailed 1")).toEqual({ result: "blocked", why: "policy" });
+ // wsl --install said "enable the Virtual Machine Platform", the DISM route then turned it on: installed (CLI: the same).
+ expect(parseInstallLog("Please enable the Virtual Machine Platform Windows feature and ensure virtualization is enabled in the BIOS.\r\nThe operation completed successfully.\r\ndone\r\n")).toEqual({ result: "installed" });
expect(parseInstallLog("Error: access denied")).toEqual({ result: "failed", line: "Error: access denied" });
});
@@ -84,18 +87,27 @@ describe("sandbox setup: what is needed", () => {
const home = await temp("home");
const calls: string[] = [];
let script = "";
+ let scriptPath = "";
const run: RunCommand = async (bin, args) => {
calls.push(bin.split(/[\\/]/).pop() ?? bin);
const m = /-File "([^"]+)" "([^"]+)"/.exec(args.at(-1) ?? "");
if (m?.[1] && m[2]) {
+ scriptPath = m[1];
script = await readFile(m[1], "utf8");
await writeFile(m[2], "Installing: Virtual Machine Platform\r\ndone\r\n");
}
return ok;
};
- const entry = await windowsInstall({ home, env: { SystemRoot: "C:\\Windows" }, run, exe: "C:\\App\\OmniRush.ai.exe", tmpDir: await temp("tmp"), checks });
+ const tmpDir = await temp("tmp");
+ const entry = await windowsInstall({ home, env: { SystemRoot: "C:\\Windows" }, run, exe: "C:\\App\\OmniRush.ai.exe", tmpDir, checks });
+ // The script sat in a folder made for this run only (random name), never at a name known in advance; gone after.
+ expect(scriptPath.split(/[\\/]/).pop()).toBe("setup.ps1");
+ expect(path.basename(path.dirname(scriptPath))).toMatch(/^omnirush-wsl-setup-[A-Za-z0-9]{6}$/);
+ expect(path.dirname(path.dirname(scriptPath))).toBe(tmpDir);
+ expect(await readdir(tmpDir)).toEqual([]);
expect(entry.state).toBe("restart");
- expect(script).toContain("wsl.exe --install --no-distribution");
+ expect(script).toContain("Invoke-Native 'wsl.exe' @('--install', '--no-distribution')");
+ expect(script).toBe(`${REQUIRED_RULES.setup.win32.install_script.join("\r\n")}\r\n`);
expect(script.endsWith("\r\n")).toBe(true);
expect(calls).toEqual(["powershell.exe", "reg.exe"]);
expect(setupState(home).win?.state).toBe("restart");
@@ -161,11 +173,11 @@ describe("sandbox setup: what is needed", () => {
return ok;
};
const vm = { ...checks, build: 26100, hypervisor: true, model: "QEMU Standard PC (Q35 + ICH9, 2009)" };
- expect(await windowsInstall({ home, run: install("Error code: Wsl/0x80370102\r\ndone\r\n"), exe: null, tmpDir, checks: vm })).toMatchObject({ state: "blocked", why: "nested_vm" });
+ expect(await windowsInstall({ home, run: install("Error code: Wsl/0x80370102\r\ndism exit 50 50\r\nfailed 1\r\n"), exe: null, tmpDir, checks: vm })).toMatchObject({ state: "blocked", why: "nested_vm" });
expect(await readFile(installLogFile(home), "utf8")).toContain("0x80370102");
expect(installLogFile(home)).toBe(join(home, "setup-win.log"));
expect(await readdir(tmpDir)).toEqual([]);
- expect(await windowsInstall({ home, run: install("Error code: Wsl/0x80370102\r\ndone\r\n"), exe: null, tmpDir, checks: { ...vm, model: "LENOVO 20XW" } })).toMatchObject({ state: "blocked", why: "firmware_off" });
+ expect(await windowsInstall({ home, run: install("Error code: Wsl/0x80370102\r\nfailed 1\r\n"), exe: null, tmpDir, checks: { ...vm, model: "LENOVO 20XW" } })).toMatchObject({ state: "blocked", why: "firmware_off" });
const failed = await windowsInstall({ home, run: install("Error: access denied\r\n"), exe: null, tmpDir, checks: vm });
expect(failed).toMatchObject({ state: "failed" });
expect(failed.message).toBe(`The WSL install did not finish: Error: access denied (log: ${installLogFile(home)})`);
@@ -209,4 +221,36 @@ describe("sandbox setup: what is needed", () => {
expect(script).toContain('"$parser" -r "$prof"');
expect(script).not.toContain("sysctl");
});
+
+ test("resume: a slow `wsl --update` is waited for a short while, then goes on in the background and finishes the setup (CLI: the same)", async () => {
+ const home = await temp("home");
+ saveSetupState(home, "win", { state: "restart" });
+ let finish: () => void = () => {};
+ let updated = false;
+ const run: RunCommand = async (_bin, args) => {
+ if (args[0] === "--update") { await new Promise<void>((resolve) => { finish = resolve; }); updated = true; return ok; }
+ if (args[0] === "--status") return updated ? { code: 0, stdout: "Default Version: 2\n", stderr: "" } : { code: 1, stdout: "WSL 2 requires an update to its kernel component. Run 'wsl --update'.\n", stderr: "" };
+ return ok;
+ };
+ let ready: unknown = null;
+ const alive = setInterval(() => {}, 1_000);
+ const started = Date.now();
+ const res = await resumeWinSetup({ home, bin: "wsl.exe", run, bootedAt: Date.now() + 60_000, updateWaitMs: 50, onReady: (r) => { ready = r; } });
+ expect(res).toEqual({ ok: false, state: "updating" });
+ expect(Date.now() - started).toBeLessThan(5_000);
+ expect(setupState(home).win?.state).toBe("restart");
+ finish();
+ for (let i = 0; i < 50 && !ready; i += 1) await new Promise((r) => setTimeout(r, 10));
+ clearInterval(alive);
+ expect(ready).toEqual({ ok: true, state: "ready" });
+ expect(setupState(home).win).toBeUndefined();
+ expect(RESUME_UPDATE_WAIT_MS).toBe(120_000);
+ });
+
+ test("install script: every native call guarded (PowerShell 5.1 stops on a redirected stderr line under Stop); done only after it worked", () => {
+ const script = REQUIRED_RULES.setup.win32.install_script;
+ for (const line of script.filter((l) => /\b(?:wsl|dism)\.exe\b/.test(l))) expect(line).toMatch(/Invoke-Native '(?:wsl|dism)\.exe'/);
+ expect(script.every((line) => !/2>&1/.test(line) || /try \{/.test(line))).toBe(true);
+ expect(script.at(-1)).toBe("if ($code -eq 0) { Add-Log 'done' } else { Add-Log \"failed $code\" }");
+ });
});
diff --git a/apps/server/src/box/required.json b/apps/server/src/box/required.json
index 74ce5e49..a3b246f0 100644
--- a/apps/server/src/box/required.json
+++ b/apps/server/src/box/required.json
@@ -7,6 +7,12 @@
"fallbacks": ["native", "native_uncounted"],
"default_fallback": "native"
},
+ "launch_record": {
+ "about": "What client.launch `box` says under required: {required: true, reason, fallback, capable}. In the box: capable true, no fallback. cannot_run: this machine can't run the box (no virtualization, setup not possible or not done yet, a box that failed to start): capable false, fallback native (counted in full). opted_out: it could, but the box was turned off (--no-sandbox / OMNIRUSH_BOX=0) or the setup declined: capable true, fallback = the server's required_fallback. kept: an old chat or a host-only project, on this machine as before: fallback native, capable not checked (absent). Any other reason on this machine reads as cannot_run.",
+ "cannot_run": ["cannot_run", "box_failed", "setup_needed"],
+ "opted_out": ["env_off", "setup_declined"],
+ "kept": ["kept_old_chat", "host_only"]
+ },
"reasons": {
"required": "box",
"kept_old_chat": "kept_old_chat",
@@ -74,17 +80,25 @@
},
"win32": {
"min_build": 19041,
- "virtualization_errors": "0x80370102|0x80370114|HCS_E_HYPERV_NOT_INSTALLED|Please enable the Virtual Machine Platform|virtualization is enabled in the BIOS|WSL_E_VM_MODE_INVALID_STATE",
+ "virtualization_errors": "0x80370102|0x80370114|HCS_E_HYPERV_NOT_INSTALLED|Please enable the Virtual Machine Platform|virtualization is enabled in the BIOS|WSL_E_VM_MODE_INVALID_STATE|virtualization is not enabled on this machine",
"install_script": [
"$ErrorActionPreference = 'Stop'",
"$log = $args[0]",
- "try { & wsl.exe --install --no-distribution 2>&1 | Out-File -Append -Encoding utf8 $log; $code = $LASTEXITCODE } catch { $code = 1 }",
+ "function Add-Log([string]$line) { try { $line | Out-File -Append -Encoding utf8 $log } catch {} }",
+ "function Invoke-Native([string]$exe, [string[]]$argv) {",
+ " $ErrorActionPreference = 'Continue'",
+ " $global:LASTEXITCODE = 1",
+ " try { & $exe @argv 2>&1 | ForEach-Object { Add-Log \"$_\" } } catch { Add-Log \"${exe}: $_\" }",
+ " return [int]$global:LASTEXITCODE",
+ "}",
+ "$code = Invoke-Native 'wsl.exe' @('--install', '--no-distribution')",
"if ($code -ne 0) {",
- " dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart | Out-File -Append -Encoding utf8 $log",
- " dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart | Out-File -Append -Encoding utf8 $log",
- " & wsl.exe --update --web-download 2>&1 | Out-File -Append -Encoding utf8 $log",
+ " $a = Invoke-Native 'dism.exe' @('/online', '/enable-feature', '/featurename:Microsoft-Windows-Subsystem-Linux', '/all', '/norestart')",
+ " $b = Invoke-Native 'dism.exe' @('/online', '/enable-feature', '/featurename:VirtualMachinePlatform', '/all', '/norestart')",
+ " $null = Invoke-Native 'wsl.exe' @('--update', '--web-download')",
+ " if (($a -eq 0 -or $a -eq 3010) -and ($b -eq 0 -or $b -eq 3010)) { $code = 0 } else { Add-Log \"dism exit $a $b\" }",
"}",
- "'done' | Out-File -Append -Encoding utf8 $log"
+ "if ($code -eq 0) { Add-Log 'done' } else { Add-Log \"failed $code\" }"
],
"resume_run_once": "OmniRushSandboxSetup"
},
@@ -123,7 +137,8 @@
"setup_needed": "Setting up the sandbox ({step})…",
"cannot_run": "The sandbox can't run on this computer: {why}. This chat runs on {machine}.",
"win_setup": "The sandbox needs WSL 2. Run `omnirush sandbox setup` (one Windows admin prompt, then a restart).",
- "win_restart": "WSL 2 is installed; restart Windows to finish. OmniRush finishes the setup on its next start."
+ "win_restart": "WSL 2 is installed; restart Windows to finish. OmniRush finishes the setup on its next start.",
+ "win_updating": "WSL is updating for the sandbox in the background; this chat runs on this PC, the next one in the sandbox."
},
"desktop": {
"required_line": "New chats run in the OmniRush sandbox, set up for you.",
diff --git a/apps/server/src/box/required.ts b/apps/server/src/box/required.ts
index ac5729a4..c54e534c 100644
--- a/apps/server/src/box/required.ts
+++ b/apps/server/src/box/required.ts
@@ -28,6 +28,24 @@ export function requiredFallback(value: unknown): RequiredFallback {
return value === "native" || value === "native_uncounted" ? value : "native";
}
+/** The required part of a chat's launch record (required.json launch_record). */
+export type RequiredLaunch = { required: true; capable?: boolean; fallback?: RequiredFallback };
+
+/**
+ * The required part of a chat's box.plan outcome (required.json
+ * launch_record; CLI: required.js requiredLaunch): { required, capable,
+ * fallback } so the server can tell a machine that can't run the box
+ * (counted in full, fallback native) from one where it was turned off or
+ * the setup declined (the server's required_fallback).
+ */
+export function requiredLaunch(reason: string, { native, serverFallback }: { native: boolean; serverFallback?: unknown }): RequiredLaunch {
+ const record = rules.launch_record;
+ if (!native) return { required: true, capable: true };
+ if (record.kept.includes(reason)) return { required: true, fallback: "native" };
+ if (record.opted_out.includes(reason)) return { required: true, capable: true, fallback: requiredFallback(serverFallback) };
+ return { required: true, capable: false, fallback: "native" };
+}
+
/** A desktop text of required.json with its `{name}` parts filled in. */
export function desktopText(key: keyof typeof rules.texts.desktop, vars: Record<string, string> = {}): string {
return fill(rules.texts.desktop[key], vars);
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index 6b089c1a..ee4a9897 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -26,7 +26,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { boxHome, boxKey, boxSnapshotsDir, containerName, installShell, listBoxes, mountReplaced, readRecord, resetBox, savedTurns, type BoxLabel, type BoxLog } from "./box.js";
-import { LABELS, OPT_IN, backendsFor, driverFor } from "./backends/index.js";
+import { LABELS, OPT_IN, REQUIRED_FIRST, backendsFor, driverFor } from "./backends/index.js";
import { limaHome } from "./backends/lima.js";
import type { BoxExec } from "./backends/types.js";
import type { BoxEndpoint } from "./client.js";
@@ -34,7 +34,7 @@ import { hostBuilds, hostBuildsNotice, hostBuildThings, hostRules } from "./host
import { detectStack, imageFor, type BoxImage } from "./images.js";
import { portLine } from "./ports.js";
import { askedBackend, boxRun, planBox, pullActivityAt, pullLog, pullMarker, pulling, pullInBackground, setupWait, resolveMode, saveBackend, serverBackends, serverDefault, serverRequired, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";
-import { desktopText, hostOnlyProject, shadowsApply, shadowsNotice, type RequiredFallback } from "./required.js";
+import { desktopText, hostOnlyProject, requiredLaunch, shadowsApply, shadowsNotice, type RequiredFallback } from "./required.js";
import { cachedWindowsChecks, classifySetup, linuxAllow, resumeWinSetup, saveSetupState, setupState, windowsInstall, windowsRestart, windowsUpdate, type BoxSetup } from "./setup.js";
import type { BoxInstallLogPaths } from "./install-log.js";
import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";
@@ -145,7 +145,9 @@ export type BoxBackendView = {
/** The backend choices of a platform: auto, the ranked ids there, the opt-in ones, native. */
export function backendChoices(platform: NodeJS.Platform = process.platform): Array<{ id: string; label: string }> {
const optIn = (OPT_IN[platform] ?? []).map((id) => ({ id, label: `${LABELS[id] ?? id} (opt-in)` }));
- return [{ id: "auto", label: "Automatic" }, ...backendsFor(platform).map((id) => ({ id, label: LABELS[id] ?? id })), ...optIn, { id: "native", label: "Off (this computer)" }];
+ // macOS' own VM: first under the required sandbox, else chosen by name only.
+ const first = (REQUIRED_FIRST[platform] ?? []).map((id) => ({ id, label: LABELS[id] ?? id }));
+ return [{ id: "auto", label: "Automatic" }, ...first, ...backendsFor(platform).map((id) => ({ id, label: LABELS[id] ?? id })), ...optIn, { id: "native", label: "Off (this computer)" }];
}
export type BoxServiceOptions = {
@@ -177,7 +179,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 }; required?: true; fallback?: RequiredFallback };
+export type BoxPlanOutcome = { native: boolean; source: string | null; reason: string; runtime?: { name: string | null; code: string | null }; required?: true; capable?: boolean; 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 } {
@@ -268,12 +270,12 @@ export class BoxService {
* 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" | "preferShadows"> {
+ private detectOptions(): Pick<DetectOptions, "asked" | "allow" | "preferShadows" | "required"> {
const asked = askedBackend({ env: this.env, stateDir: this.options.stateDir });
const required = this.required().required;
const backend = asked.source === "setting" && asked.backend === "native" && required ? "auto" : asked.backend;
// Under required on macOS / Windows the backends that give the box its own build folders (shadows) come first.
- return { asked: backend, allow: serverBackends(this.options.stateDir), ...(required && shadowsApply(this.platform, this.env) ? { preferShadows: true } : {}) };
+ return { asked: backend, allow: serverBackends(this.options.stateDir), ...(required && shadowsApply(this.platform, this.env) ? { preferShadows: true } : {}), ...(required ? { required: true } : {}) };
}
private detect(extra: DetectOptions = {}): Promise<RuntimeResult> {
@@ -451,6 +453,8 @@ export class BoxService {
project.run?.close();
project.run = boxRun(plan, {
log: this.log,
+ // Box ports on this computer's 127.0.0.1: only under the required sandbox.
+ required: this.required().required,
pkglog: this.installLog ? { root: this.installLog.root, bin: this.installLog.bin, py: this.installLog.py } : null,
tmpRoot: join(this.home, "pending"),
// boxd stopped while the app ran: started again (installs kept), or once why not and what to do.
@@ -680,13 +684,17 @@ export class BoxService {
*/
async resumeSetup(): Promise<boolean> {
if (this.platform !== "win32" || setupState(this.home).win?.state !== "restart") return false;
- const resumed = await resumeWinSetup({ home: this.home, env: this.env, log: (level, message) => this.log(level, message) }).catch(() => null);
+ // A slow `wsl --update` goes on in the background (setup.ts RESUME_UPDATE_WAIT_MS) and finishes the same way.
+ const ready = async (): Promise<void> => {
+ this.alternatives = null;
+ await this.detect({ fresh: true }).catch(() => null);
+ void this.ensureAll();
+ void this.prefetch().catch(() => false);
+ };
+ const resumed = await resumeWinSetup({ home: this.home, env: this.env, log: (level, message) => this.log(level, message), onReady: () => { this.log("info", "sandbox setup resume", { state: "ready" }); void ready(); } }).catch(() => null);
this.log("info", "sandbox setup resume", { state: resumed?.state ?? "failed" });
if (!resumed?.ok) return false;
- this.alternatives = null;
- await this.detect({ fresh: true }).catch(() => null);
- void this.ensureAll();
- void this.prefetch().catch(() => false);
+ await ready();
return true;
}
@@ -860,13 +868,12 @@ export class BoxService {
const mode = await this.mode(workspace).catch(() => null);
if (!mode) return { native: true, source: null, reason: "plan_failed" };
const { fallback } = this.required();
- // Required: every outcome says so; a chat that runs here by the fallback rule (the box cannot run, setup
- // needed or declined, a box that failed to start) names the fallback the server set (as the CLI's launch event).
- const required = mode.required ? { required: true as const } : {};
- const byFallback = new Set(["cannot_run", "setup_needed", "setup_declined", "box_failed"]);
- const native = (reason: string, extra: Partial<BoxPlanOutcome> = {}): BoxPlanOutcome => ({ native: true, source: mode.source, reason, ...required, ...(mode.required && byFallback.has(reason) ? { fallback } : {}), ...extra });
+ // Required (required.ts requiredLaunch, as the CLI's launch event): whether this machine can run the box and,
+ // on this machine, the fallback in force: `native` where it can't (counted in full), the server's
+ // required_fallback where the box was turned off (OMNIRUSH_BOX=0) or the setup declined.
+ const native = (reason: string, extra: Partial<BoxPlanOutcome> = {}): BoxPlanOutcome => ({ native: true, source: mode.source, reason, ...(mode.required ? requiredLaunch(reason, { native: true, serverFallback: 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 (this.boxedChats.has(sessionId)) return { native: false, source: mode.source, reason: "box", ...(mode.required ? requiredLaunch("box", { native: false }) : {}) };
if (!mode.on) {
if (mode.required && mode.source === "env") return native("env_off");
if (mode.source === "host-only") return native("host_only");
diff --git a/apps/server/src/box/setup.ts b/apps/server/src/box/setup.ts
index 7608b5c9..f7519034 100644
--- a/apps/server/src/box/setup.ts
+++ b/apps/server/src/box/setup.ts
@@ -27,7 +27,7 @@
// Never edits .wslconfig.
import { createHash } from "node:crypto";
-import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -144,6 +144,8 @@ export function classifySetup({ runtime, platform, checks = null, state = {}, fa
}
if (platform === "win32") {
if (entry?.state === "blocked" && entry.why) return cannot(entry.why);
+ // Before the restart WSL says what a PC without virtualization says: the restart step first (CLI: the same).
+ if (entry?.state === "restart" && said.some((reason) => VIRTUALIZATION.test(reason) || /WSL 2 is not enabled/.test(reason))) return { ...base, need: "win_restart" };
if (said.some((reason) => VIRTUALIZATION.test(reason))) return cannot(blockedWhy(checks));
const decision = checks ? setupDecision(checks) : { ok: true as const };
if (!decision.ok) return cannot(decision.why);
@@ -230,15 +232,17 @@ export function setupDecision(checks: Partial<WindowsChecks> | null, { minBuild
}
/**
- * What the elevated install's log says: installed (it got to its last
- * line), blocked (virtualization, policy) or failed with a line.
+ * What the elevated install's log says: installed (its last line is `done`:
+ * the install, or the DISM route after it, worked; a virtualization message
+ * wsl.exe printed on the way does not undo that), blocked (virtualization,
+ * policy) or failed with a line. CLI: win-setup.js, the same.
*/
export function parseInstallLog(text: string): { result: "installed" } | { result: "blocked"; why: CannotRunWhy } | { result: "failed"; line: string } {
const clean = String(text ?? "").replace(/^\uFEFF/, "").replace(/\u0000/g, "");
- if (VIRTUALIZATION.test(clean)) return { result: "blocked", why: "firmware_off" };
- if (POLICY.test(clean)) return { result: "blocked", why: "policy" };
const lines = clean.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
if (lines.at(-1) === "done") return { result: "installed" };
+ if (VIRTUALIZATION.test(clean)) return { result: "blocked", why: "firmware_off" };
+ if (POLICY.test(clean)) return { result: "blocked", why: "policy" };
const failed = [...lines].reverse().find((l) => /error|failed|denied/i.test(l));
return { result: "failed", line: (failed ?? lines.at(-1) ?? "no output").slice(0, 240) };
}
@@ -268,20 +272,21 @@ export async function windowsInstall({ home, env = process.env, run = runCommand
const checks = given ?? await windowsChecks({ run, env, release });
const decision = setupDecision(checks);
if (!decision.ok) return saved({ state: "blocked", why: decision.why });
- const base = path.join(tmpDir, `omnirush-wsl-setup-${process.pid}-${now}`);
- const ps1 = `${base}.ps1`;
- const logFile = `${base}.log`;
- writeFileSync(ps1, `${WIN.install_script.join("\r\n")}\r\n`, "utf8");
- writeFileSync(logFile, "", "utf8");
+ // The elevated script: in a new folder of its own (a random name, made only for this run) and
+ // created there exclusively, so nothing else can put its own script in its place first.
+ const dir = mkdtempSync(path.join(tmpDir, "omnirush-wsl-setup-"));
+ const ps1 = path.join(dir, "setup.ps1");
+ const logFile = path.join(dir, "setup.log");
let text = "";
let res: Awaited<ReturnType<RunCommand>> | null = null;
try {
+ writeFileSync(ps1, `${WIN.install_script.join("\r\n")}\r\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
+ writeFileSync(logFile, "", { encoding: "utf8", flag: "wx", mode: 0o600 });
res = await run(powershellExe(env), elevatedArgs(ps1, logFile), { env, timeoutMs: 30 * 60_000 });
try { text = readFileSync(logFile, "utf8"); } catch { text = ""; }
try { if (text.trim()) writeFileSync(installLogFile(home), text, "utf8"); } catch { /* best effort */ }
} finally {
- rmSync(ps1, { force: true });
- rmSync(logFile, { force: true });
+ rmSync(dir, { recursive: true, force: true });
}
// No log at all and a failed Start-Process: the admin prompt was answered "No" (or never shown).
if (!text.trim() && res?.code !== 0) return saved({ state: "declined", message: "The administrator prompt was cancelled; nothing changed." });
@@ -306,38 +311,54 @@ export function windowsRestart({ run = runCommand }: { run?: RunCommand } = {}):
* as unable, with why (nested_vm when this PC is a VM, else firmware_off).
* WSL 1 notes in `wsl --status` are not "WSL 2 off".
*/
-export async function resumeWinSetup({ home, env = process.env, run = runCommand, log = () => {}, now = Date.now(), bin: given = null, checks = null, bootedAt = now - os.uptime() * 1000 }: { home: string; env?: NodeJS.ProcessEnv; run?: RunCommand; log?: (level: "info" | "warn", message: string) => void; now?: number; bin?: string | null; checks?: Partial<WindowsChecks> | null; bootedAt?: number }): Promise<{ ok: boolean; state: "none" | "restart" | "blocked" | "ready"; why?: CannotRunWhy }> {
+export async function resumeWinSetup({ home, env = process.env, run = runCommand, log = () => {}, now = Date.now(), bin: given = null, checks = null, bootedAt = now - os.uptime() * 1000, updateWaitMs = RESUME_UPDATE_WAIT_MS, onReady = () => {} }: { home: string; env?: NodeJS.ProcessEnv; run?: RunCommand; log?: (level: "info" | "warn", message: string) => void; now?: number; bin?: string | null; checks?: Partial<WindowsChecks> | null; bootedAt?: number; updateWaitMs?: number; onReady?: (result: ResumeResult) => void }): Promise<ResumeResult> {
const marker = setupState(home).win;
if (marker?.state !== "restart") return { ok: false, state: "none" };
// Before the restart WSL says the same as on a PC that cannot run a VM: only after it does that mean "cannot".
const restarted = !Number.isFinite(Number(marker.at)) || bootedAt > Number(marker.at);
const bin = given ?? wslExe({ env });
if (!bin) return { ok: false, state: "restart" };
- let status = await wslCall(bin, ["--status"], { run, env, timeoutMs: 30_000 });
- let said = withoutWsl1Notes(`${status.stdout}\n${status.stderr}`);
- if (/wsl --update|requires an update|kernel (?:file|component)|update the wsl/i.test(said)) {
- log("info", "sandbox setup resume: wsl --update");
- await wslCall(bin, ["--update", "--web-download"], { run, env, timeoutMs: 10 * 60_000 });
- status = await wslCall(bin, ["--status"], { run, env, timeoutMs: 30_000 });
- said = withoutWsl1Notes(`${status.stdout}\n${status.stderr}`);
- }
- const noVm = VIRTUALIZATION.test(said) || NO_VM_START.test(said);
- if (restarted && noVm) {
- const why = blockedWhy(checks ?? await windowsChecks({ run, env }).catch(() => null));
- saveSetupState(home, "win", { state: "blocked", why }, { now });
- log("info", `sandbox setup resume: WSL 2 cannot start a VM here (${why})`);
- return { ok: false, state: "blocked", why };
- }
- if ((!restarted && noVm) || /not installed|is not enabled|optional component|WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED/i.test(said)) {
- log("info", "sandbox setup resume: WSL 2 not on yet (restart pending)");
- return { ok: false, state: "restart" };
- }
- saveSetupState(home, "win", null, { now });
- await run("reg.exe", ["delete", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "/v", WIN.resume_run_once, "/f"], { env, timeoutMs: 15_000 });
- log("info", "sandbox setup resumed: WSL 2 ready");
- return { ok: true, state: "ready" };
+ const status = async (): Promise<string> => {
+ const res = await wslCall(bin, ["--status"], { run, env, timeoutMs: 30_000 });
+ return withoutWsl1Notes(`${res.stdout}\n${res.stderr}`);
+ };
+ const decide = async (said: string): Promise<ResumeResult> => {
+ const noVm = VIRTUALIZATION.test(said) || NO_VM_START.test(said);
+ if (restarted && noVm) {
+ const why = blockedWhy(checks ?? await windowsChecks({ run, env }).catch(() => null));
+ saveSetupState(home, "win", { state: "blocked", why }, { now });
+ log("info", `sandbox setup resume: WSL 2 cannot start a VM here (${why})`);
+ return { ok: false, state: "blocked", why };
+ }
+ if ((!restarted && noVm) || /not installed|is not enabled|optional component|WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED/i.test(said)) {
+ log("info", "sandbox setup resume: WSL 2 not on yet (restart pending)");
+ return { ok: false, state: "restart" };
+ }
+ saveSetupState(home, "win", null, { now });
+ await run("reg.exe", ["delete", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "/v", WIN.resume_run_once, "/f"], { env, timeoutMs: 15_000 });
+ log("info", "sandbox setup resumed: WSL 2 ready");
+ return { ok: true, state: "ready" };
+ };
+ const said = await status();
+ if (!/wsl --update|requires an update|kernel (?:file|component)|update the wsl/i.test(said)) return decide(said);
+ // `wsl --update` can take minutes (a download): waited for up to updateWaitMs, then it goes on in
+ // the background and finishes the setup itself (onReady). CLI: win-setup.js, the same.
+ log("info", "sandbox setup resume: wsl --update");
+ const finishing = wslCall(bin, ["--update", "--web-download"], { run, env, timeoutMs: 10 * 60_000 }).then(async () => decide(await status()));
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const waited = await Promise.race([finishing.then((result) => ({ result })), new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), updateWaitMs); timer.unref?.(); })]);
+ if (timer) clearTimeout(timer);
+ if (waited) return waited.result;
+ log("info", "sandbox setup resume: wsl --update goes on in the background");
+ finishing.then((result) => { if (result.ok) { try { onReady(result); } catch { /* the caller's */ } } }).catch((error) => log("warn", `sandbox setup resume failed: ${error instanceof Error ? error.message : String(error)}`));
+ return { ok: false, state: "updating" };
}
+export type ResumeResult = { ok: boolean; state: "none" | "restart" | "blocked" | "ready" | "updating"; why?: CannotRunWhy };
+
+/** How long the resume waits for its `wsl --update` before it goes on in the background. */
+export const RESUME_UPDATE_WAIT_MS = 2 * 60_000;
+
// --- Linux (CLI: backends/bwrap.js enableBwrap) ----------------------------------------------
/**