Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: share sandbox setup state with cli

ogsamrat337ae61933d0
diff --git a/apps/server/src/box/box-required.test.ts b/apps/server/src/box/box-required.test.ts
index 6fcd0c67..aa4059e4 100644
--- a/apps/server/src/box/box-required.test.ts
+++ b/apps/server/src/box/box-required.test.ts
@@ -3,9 +3,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
-import { desktopText, hostOnlyProject, parseWindowsFacts, requiredFallback, virtualizationError, whyText, windowsInstallScript, windowsWhy } from "./required.js";
-
-const facts = { build: 22631, hypervisorPresent: false, firmwareEnabled: true, model: "Dell Inc. XPS 13", sMode: false };
+import { desktopText, hostOnlyProject, requiredFallback, whyText } from "./required.js";
describe("required sandbox rules", () => {
test("fallback and texts", () => {
@@ -18,32 +16,6 @@ describe("required sandbox rules", () => {
expect(whyText("nope")).toBeNull();
});
- test("windows: a running hypervisor passes, firmware off, nested VM, S mode, old build, policy", () => {
- expect(windowsWhy(facts)).toBeNull();
- expect(windowsWhy({ ...facts, hypervisorPresent: true, firmwareEnabled: false })).toBeNull();
- expect(windowsWhy({ ...facts, firmwareEnabled: false })).toBe("firmware_off");
- expect(windowsWhy({ ...facts, firmwareEnabled: false, model: "Microsoft Corporation Virtual Machine" })).toBe("nested_vm");
- expect(windowsWhy({ ...facts, model: "innotek GmbH VirtualBox", wslSaid: "Error code: Wsl/Service/CreateInstance/0x80370102" })).toBe("nested_vm");
- expect(windowsWhy({ ...facts, sMode: true })).toBe("s_mode");
- expect(windowsWhy({ ...facts, build: 18363 })).toBe("old_windows");
- expect(windowsWhy({ ...facts, policy: true })).toBe("policy");
- expect(windowsWhy({ build: null, hypervisorPresent: null, firmwareEnabled: null, model: null, sMode: null })).toBeNull();
- expect(virtualizationError("Please enable the Virtual Machine Platform Windows feature")).toBe(true);
- expect(virtualizationError("The operation completed successfully.")).toBe(false);
- });
-
- test("windows facts parse from the PowerShell JSON line", () => {
- expect(parseWindowsFacts('{"build":19045,"hypervisor":false,"firmware":true,"model":" LENOVO 20XW ","smode":false}\r\n')).toEqual({ build: 19045, hypervisorPresent: false, firmwareEnabled: true, model: "LENOVO 20XW", sMode: false });
- expect(parseWindowsFacts("garbage")).toEqual({ build: null, hypervisorPresent: null, firmwareEnabled: null, model: null, sMode: null });
- });
-
- test("the install script is the shared one, CRLF, with its log argument", () => {
- const script = windowsInstallScript();
- expect(script).toContain("wsl.exe --install --no-distribution");
- expect(script).toContain("$log = $args[0]");
- expect(script.endsWith("\r\n")).toBe(true);
- });
-
test("host-only projects: Xcode on macOS, WPF and vcxproj on Windows, never Linux", () => {
const root = mkdtempSync(path.join(os.tmpdir(), "hostonly-"));
mkdirSync(path.join(root, "App.xcodeproj"));
@@ -54,8 +26,8 @@ describe("required sandbox rules", () => {
writeFileSync(path.join(win, "src", "Desk.csproj"), "<Project><PropertyGroup><UseWPF>true</UseWPF></PropertyGroup></Project>");
writeFileSync(path.join(win, "Lib.csproj"), "<Project><PropertyGroup><TargetFramework>net8.0</TargetFramework></PropertyGroup></Project>");
const found = hostOnlyProject(win, { platform: "win32" });
- expect(found?.things).toEqual(["Desk.csproj"]);
- expect(found?.notice).toContain("only builds on Windows (Desk.csproj)");
+ expect(found?.things).toEqual(["src/Desk.csproj"]);
+ expect(found?.notice).toContain("only builds on Windows (src/Desk.csproj)");
const swift = mkdtempSync(path.join(os.tmpdir(), "hostonly-"));
writeFileSync(path.join(swift, "Package.swift"), "let package = Package(name: \"x\", platforms: [.iOS(.v17)])");
expect(hostOnlyProject(swift, { platform: "darwin" })?.things).toEqual(["Package.swift"]);
diff --git a/apps/server/src/box/box-setup.test.ts b/apps/server/src/box/box-setup.test.ts
index 4b536d9a..82acb53d 100644
--- a/apps/server/src/box/box-setup.test.ts
+++ b/apps/server/src/box/box-setup.test.ts
@@ -4,7 +4,7 @@ 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";
+import { classifySetup, elevatedArgs, linuxAllow, linuxAllowScript, parseInstallLog, recentlyDeclined, resumeWinSetup, runOnceArgs, saveSetupState, setupDecision, setupState, windowsBuild, windowsInstall } from "./setup.js";
const dirs: string[] = [];
afterEach(async () => {
@@ -17,59 +17,96 @@ async function temp(name: string): Promise<string> {
}
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 };
+const checks = { build: 22631, hypervisor: false, firmware: true, model: "Dell Inc. XPS", s_mode: false };
+const OFF = "WSL 2 is not enabled on this Windows. One time, in an administrator terminal: `wsl --install --no-distribution`, then restart Windows";
+const ok: Awaited<ReturnType<RunCommand>> = { code: 0, stdout: "", stderr: "" };
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("no backend", ["bubblewrap is blocked; one-time admin fix: Allow the sandbox (one password prompt), or `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 });
+ const docker = { ok: true as const, name: "docker", bin: "docker", version: "1", os: "linux", arch: "amd64", rootless: true, flavor: "", vm: false };
+ expect(classifySetup({ runtime: docker, platform: "linux", fallback: "native", state: { linux: { state: "declined", at: Date.now() } } })).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("Windows: install, restart after it, update, and the cannot-run reasons", () => {
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks, fallback: "native" }).need).toBe("win_install");
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks, fallback: "native", state: { win: { state: "restart", message: "WSL 2 is installed.", at: 1 } } })).toMatchObject({ need: "win_restart", result: { ok: true } });
+ expect(classifySetup({ runtime: fail("WSL needs an update (`wsl --update`)"), platform: "win32", checks, fallback: "native" }).need).toBe("win_update");
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks: { ...checks, firmware: false }, fallback: "native_uncounted" })).toMatchObject({ need: "cannot_run", why: "firmware_off", fallback: "native_uncounted" });
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks: { ...checks, firmware: false, model: "Microsoft Corporation Virtual Machine" }, fallback: "native" }).why).toBe("nested_vm");
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks: { ...checks, hypervisor: true, firmware: false }, fallback: "native" }).need).toBe("win_install");
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks: { ...checks, s_mode: true }, fallback: "native" }).whyText).toBe("Windows in S mode can't run WSL");
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks, fallback: "native", state: { win: { state: "blocked", why: "policy", at: 1 } } }).why).toBe("policy");
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks, fallback: "native", state: { win: { state: "declined", at: Date.now() } } })).toMatchObject({ need: "win_install", declined: true });
+ expect(classifySetup({ runtime: fail(OFF), platform: "win32", checks, fallback: "native", state: { win: { state: "declined", at: 1 } } }).declined).toBe(false);
+ expect(classifySetup({ runtime: fail("no backend"), platform: "darwin", fallback: "native", release: "21.6.0" }).why).toBe("old_macos");
+ expect(classifySetup({ runtime: fail("no backend"), platform: "darwin", fallback: "native", release: "24.1.0", macVm: true }).need).toBe("mac_vm");
+ });
+
+ test("the CLI's checks: build, S mode, a running hypervisor passes, firmware off, a VM guest; the install log", () => {
+ expect(windowsBuild("10.0.19045")).toBe(19045);
+ expect(setupDecision({ ...checks, build: 18363 })).toEqual({ ok: false, why: "old_windows" });
+ expect(setupDecision({ ...checks, s_mode: true })).toEqual({ ok: false, why: "s_mode" });
+ expect(setupDecision({ ...checks, hypervisor: true, firmware: false })).toEqual({ ok: true });
+ 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: access denied")).toEqual({ result: "failed", line: "Error: access denied" });
});
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");
+ const args = elevatedArgs("C:\\Users\\o'neil\\AppData\\Local\\Temp\\s.ps1", "C:\\Users\\o'neil\\AppData\\Local\\Temp\\s.log");
+ expect(args.join(" ").match(/Start-Process/g)?.length).toBe(1);
+ expect(args.at(-1)).toContain("-Verb RunAs -Wait");
+ expect(args.at(-1)).toContain(`-File "C:\\Users\\o''neil\\AppData\\Local\\Temp\\s.ps1" "C:\\Users\\o''neil\\AppData\\Local\\Temp\\s.log"`);
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 () => {
+ test("windows install: the shared script in a temp .ps1; done is a restart (RunOnce set); a cancelled prompt is declined; checks first", 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");
+ let script = "";
+ const run: RunCommand = async (bin, args) => {
+ calls.push(bin.split(/[\\/]/).pop() ?? bin);
+ const m = /-File "([^"]+)" "([^"]+)"/.exec(args.at(-1) ?? "");
+ if (m?.[1] && m[2]) {
+ script = await readFile(m[1], "utf8");
+ await writeFile(m[2], "Installing: Virtual Machine Platform\r\ndone\r\n");
}
- return { code: 0, stdout: "", stderr: "" };
+ return ok;
};
- 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." });
+ const entry = await windowsInstall({ home, env: { SystemRoot: "C:\\Windows" }, run, exe: "C:\\App\\OmniRush.ai.exe", tmpDir: await temp("tmp"), checks });
+ expect(entry.state).toBe("restart");
+ expect(script).toContain("wsl.exe --install --no-distribution");
+ expect(script.endsWith("\r\n")).toBe(true);
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({});
+ expect(setupState(home).win?.state).toBe("restart");
+ const cancelled: RunCommand = async () => ({ code: 1, stdout: "", stderr: "This operation was canceled by the user." });
+ expect((await windowsInstall({ home, run: cancelled, exe: null, tmpDir: await temp("tmp"), checks })).state).toBe("declined");
+ expect(recentlyDeclined(setupState(home).win)).toBe(true);
+ const never: RunCommand = async () => { throw new Error("must not run"); };
+ expect(await windowsInstall({ home, run: never, exe: null, tmpDir: await temp("tmp"), checks: { ...checks, s_mode: true } })).toMatchObject({ state: "blocked", why: "s_mode" });
+ });
+
+ test("resume after the restart: wsl --update when asked, then the marker and the RunOnce value go", async () => {
+ const home = await temp("home");
+ saveSetupState(home, "win", { state: "restart" });
+ const calls: string[] = [];
+ let updated = false;
+ const run: RunCommand = async (bin, args) => {
+ calls.push(`${bin.split(/[\\/]/).pop()} ${args.slice(0, 2).join(" ")}`);
+ if (args[0] === "--status") return { code: updated ? 0 : 1, stdout: updated ? "Default Version: 2" : "WSL needs updating: run wsl --update", stderr: "" };
+ if (args[0] === "--update") updated = true;
+ return ok;
+ };
+ expect(await resumeWinSetup({ home, run, bin: "wsl.exe" })).toEqual({ ok: true, state: "ready" });
+ expect(calls).toEqual(["wsl.exe --status", "wsl.exe --update --web-download", "wsl.exe --status", "reg.exe delete HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce"]);
+ expect(setupState(home)).toEqual({});
+ expect(await resumeWinSetup({ home, run, bin: "wsl.exe" })).toEqual({ ok: false, state: "none" });
});
test("Linux allow: pkexec runs the enable step with the staged bubblewrap and its sha256; dismissed is declined", async () => {
@@ -77,17 +114,20 @@ describe("sandbox setup: what is needed", () => {
const source = join(await temp("bin"), "bwrap");
await writeFile(source, "fake bwrap");
const seen: string[][] = [];
- const ok: RunCommand = async (bin, args) => {
+ const allowed: 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)." });
+ saveSetupState(home, "linux", { state: "declined" });
+ expect(await linuxAllow({ home, env: {}, run: allowed, source })).toEqual({ ok: true, message: "Allowed (installed; AppArmor profile loaded)." });
+ expect(setupState(home)).toEqual({});
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: { OMNIRUSH_BOX_PKEXEC: "/rig/elevate" }, run: async (bin) => ({ code: bin === "/rig/elevate" ? 126 : 1, stdout: "", stderr: "" }), source })).toMatchObject({ ok: false });
+ expect(recentlyDeclined(setupState(home).linux)).toBe(true);
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.");
+ expect(setupState(home).linux?.state).toBe("failed");
});
test("the root step installs only OmniRush's bubblewrap copy and its own AppArmor profile", () => {
diff --git a/apps/server/src/box/required.ts b/apps/server/src/box/required.ts
index 725bc23d..6a6eceab 100644
--- a/apps/server/src/box/required.ts
+++ b/apps/server/src/box/required.ts
@@ -68,98 +68,39 @@ function entries(dir: string, read: (dir: string) => Dirent[]): Dirent[] {
/**
* A project that only builds on this OS (an Xcode project on macOS; a WPF,
- * WinForms or MAUI app, a C++ .vcxproj on Windows): the markers it has (the
- * project root and one level down), else null. Linux: never.
+ * WinForms or MAUI app, a C++ .vcxproj on Windows): its markers, the root
+ * first, then one level down (CLI: required.js hostOnly), else null. Linux:
+ * never. Bounded: a couple of directory reads and a few small files.
*/
-export function hostOnlyProject(root: string, { platform = process.platform, readDir = (dir: string) => readdirSync(dir, { withFileTypes: true }), readHead = head }: { platform?: string; readDir?: (dir: string) => Dirent[]; readHead?: (file: string) => string } = {}): { things: string[]; notice: string } | null {
+export function hostOnlyProject(root: string, { platform = process.platform, readDir = (dir: string) => readdirSync(dir, { withFileTypes: true }), readHead = head, maxFiles = 40 }: { platform?: string; readDir?: (dir: string) => Dirent[]; readHead?: (file: string) => string; maxFiles?: number } = {}): { things: string[]; notice: string } | null {
const table: Record<string, HostOnlyRules> = { darwin: rules.host_only.darwin, win32: rules.host_only.win32 };
const set = table[platform];
if (!set) return null;
const things: string[] = [];
- const look = (dir: string, depth: number) => {
+ let read = 0;
+ const contains = (file: string, pattern: string) => {
+ if (read >= maxFiles) return false;
+ read += 1;
+ return new RegExp(pattern).test(readHead(file));
+ };
+ const check = (dir: string, prefix: string) => {
for (const entry of entries(dir, readDir)) {
- if (things.length >= 3) return;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (set.dirs_suffix.some((suffix) => entry.name.endsWith(suffix))) things.push(entry.name);
- else if (depth === 0 && !entry.name.startsWith(".") && entry.name !== "node_modules") look(full, 1);
- continue;
- }
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory() && set.dirs_suffix.some((suffix) => entry.name.endsWith(suffix))) { things.push(rel); continue; }
if (!entry.isFile()) continue;
- if (set.files.includes(entry.name)) { things.push(entry.name); continue; }
- const pattern = set.file_patterns.find((p) => (p.name ? entry.name === p.name : p.suffix ? entry.name.endsWith(p.suffix) : false));
- if (pattern && new RegExp(pattern.contains).test(readHead(full))) things.push(entry.name);
+ if (set.files.includes(entry.name)) { things.push(rel); continue; }
+ for (const pattern of set.file_patterns) {
+ const named = pattern.name ? entry.name === pattern.name : pattern.suffix ? entry.name.endsWith(pattern.suffix) : false;
+ if (named && contains(path.join(dir, entry.name), pattern.contains)) { things.push(rel); break; }
+ }
}
};
- look(root, 0);
+ check(root, "");
+ for (const entry of entries(root, readDir)) {
+ if (things.length > 0) break;
+ if (entry.isDirectory() && !entry.name.startsWith(".") && !rules.shadows.skip_dirs.includes(entry.name) && !set.dirs_suffix.some((suffix) => entry.name.endsWith(suffix))) check(path.join(root, entry.name), entry.name);
+ }
if (!things.length) return null;
const host = HOST_BUILD_RULES.hosts[platform];
- return { things, notice: desktopText("host_only", { label: host?.label ?? platform, things: things.join(", "), machine: host?.machine ?? "this computer" }) };
-}
-
-/** What a Windows machine says about running WSL 2 (PowerShell CIM, the build, S mode). */
-export type WindowsFacts = {
- build: number | null;
- hypervisorPresent: boolean | null;
- firmwareEnabled: boolean | null;
- /** Win32_ComputerSystem Model / Manufacturer (a VM guest names its hypervisor). */
- model: string | null;
- sMode: boolean | null;
- /** WSL's own output (`wsl --status`, the setup log), checked for a virtualization error. */
- wslSaid?: string | null;
- /** WSL is blocked by policy (the setup log, `wsl` output). */
- policy?: boolean;
-};
-
-const VM_MODEL = /virtual machine|vmware|virtualbox|kvm|qemu|hvm domu|parallels|xen|bochs/i;
-
-/**
- * Why WSL 2 cannot run on this Windows (required.json texts.why keys), or
- * null when nothing rules it out. A running hypervisor is a pass (the
- * firmware flag reads false while Hyper-V runs).
- */
-export function windowsWhy(facts: WindowsFacts): CannotRunWhy | null {
- if (facts.sMode) return "s_mode";
- if (facts.build !== null && facts.build < rules.setup.win32.min_build) return "old_windows";
- if (facts.policy) return "policy";
- const vmError = Boolean(facts.wslSaid && virtualizationError(facts.wslSaid));
- if (facts.hypervisorPresent === true && !vmError) return null;
- if (facts.firmwareEnabled === false || vmError) return facts.model && VM_MODEL.test(facts.model) ? "nested_vm" : "firmware_off";
- return null;
-}
-
-/** Whether WSL's output is one of its "no virtualization" errors. */
-export function virtualizationError(text: string): boolean {
- return new RegExp(rules.setup.win32.virtualization_errors, "i").test(text);
-}
-
-/** The PowerShell that reads the facts windowsWhy needs (one JSON line). */
-export const WINDOWS_FACTS_SCRIPT = [
- "$ErrorActionPreference = 'SilentlyContinue'",
- "$cpu = Get-CimInstance Win32_Processor | Select-Object -First 1",
- "$cs = Get-CimInstance Win32_ComputerSystem",
- "$s = (Get-ItemProperty 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\CI\\Policy' -Name SkuPolicyRequired).SkuPolicyRequired",
- "[pscustomobject]@{ build = [Environment]::OSVersion.Version.Build; hypervisor = $cs.HypervisorPresent; firmware = $cpu.VirtualizationFirmwareEnabled; model = \"$($cs.Manufacturer) $($cs.Model)\"; smode = ($s -eq 1) } | ConvertTo-Json -Compress",
-].join("; ");
-
-/** The facts from WINDOWS_FACTS_SCRIPT's output (unknown fields: null). */
-export function parseWindowsFacts(stdout: string): WindowsFacts {
- let value: Record<string, unknown> = {};
- try {
- const parsed: unknown = JSON.parse(String(stdout).trim().split("\n").pop() ?? "");
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) value = Object.fromEntries(Object.entries(parsed));
- } catch { /* nothing known */ }
- const bool = (v: unknown) => (typeof v === "boolean" ? v : null);
- return {
- build: typeof value.build === "number" ? value.build : null,
- hypervisorPresent: bool(value.hypervisor),
- firmwareEnabled: bool(value.firmware),
- model: typeof value.model === "string" ? value.model.trim() || null : null,
- sMode: bool(value.smode),
- };
-}
-
-/** The elevated setup script (required.json setup.win32.install_script) as a .ps1 file's text. */
-export function windowsInstallScript(): string {
- return `${rules.setup.win32.install_script.join("\r\n")}\r\n`;
+ return { things, notice: desktopText("host_only", { label: host?.label ?? platform, things: things.slice(0, 3).join(", "), machine: host?.machine ?? "this computer" }) };
}
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index 37f8ec3c..3bb5ee85 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -32,7 +32,7 @@ import { hostBuilds, hostBuildsNotice, hostBuildThings, hostRules } from "./host
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 { 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";
import { BUILDATHON_OFFER_NOTICE, buildathonBoxFor, buildathonProjectsFile, LESS_REPRO_NOTICE } from "../buildathon-repro.js";
@@ -613,8 +613,6 @@ export class BoxService {
: 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,
@@ -637,23 +635,29 @@ export class BoxService {
};
}
- /** What the sandbox needs here before it can run (the setup screen); Windows facts are read (and cached) for it. */
+ /** What the sandbox needs here before it can run (the setup screen); this PC's checks are read (and cached) for it on Windows. */
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;
+ const checks = this.platform === "win32" && runtime && !runtime.ok ? await cachedWindowsChecks({ fresh }).catch(() => null) : null;
+ return classifySetup({ runtime, platform: this.platform, checks, state: setupState(this.home), fallback: this.required().fallback });
+ }
+
+ /**
+ * App start on Windows after "Set up (one restart)" (the resume marker):
+ * `wsl --update` when WSL asks for it, then every project is planned (the
+ * distro import and the image download follow). Never throws.
+ */
+ 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);
+ 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);
+ return true;
}
- private updating: Promise<unknown> | null = null;
/**
* Try again now (the card's retry): a box that failed to start, or a
@@ -682,12 +686,13 @@ export class BoxService {
*/
async setup(workspace: BoxWorkspace, action: BoxSetupAction): Promise<BoxStatus> {
const home = this.home;
+ const which = this.platform === "win32" ? "win" : this.platform === "linux" ? "linux" : null;
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_install" && this.platform === "win32") await windowsInstall({ home, env: this.env });
+ else if (action === "win_update" && this.platform === "win32") await windowsUpdate({ env: this.env });
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);
+ else if (action === "decline" && which) saveSetupState(home, which, { state: "declined", message: "Set up later; chats run on this computer meanwhile." });
+ if (action === "check" && this.platform === "win32") await cachedWindowsChecks({ 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);
diff --git a/apps/server/src/box/setup.ts b/apps/server/src/box/setup.ts
index 1de3c5b6..f9ac5f42 100644
--- a/apps/server/src/box/setup.ts
+++ b/apps/server/src/box/setup.ts
@@ -1,24 +1,28 @@
// 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):
+// run by the app for the user. Ported from the CLI (omnirush-cli
+// src/box/setup-state.js, src/box/win-setup.js); keep the shared parts in
+// step: <box home>/setup.json is the same file for both (the CLI and the app
+// share the box home), with the same entries. 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, WSL 2 missing: "Set up (one restart)" checks the build, S mode
+// and virtualization (PowerShell CIM), then runs the shared install script
+// elevated (one UAC prompt: one `Start-Process -Verb RunAs -Wait` with a
+// temp .ps1 and a log). The resume marker (setup.json win: restart) and an
+// HKCU RunOnce value reopen the app after the restart, which finishes the
+// setup (`wsl --update` when WSL asks for it; then 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.
+// without nested virtualization, S mode, an old build, a policy): why,
+// before the install and from WSL's errors after it.
+// - macOS: the OmniRush VM (Lima) is its own backend; until it is in this
+// build a Mac with no running container app reads "runtime" (the card's
+// usual next step). `macVm` is the hook for it.
+// Never edits .wslconfig.
import { createHash } from "node:crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -27,33 +31,29 @@ 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 { wslCall, wslExe } from "./backends/wsl.js";
+import { REQUIRED_RULES, whyText, type CannotRunWhy, type RequiredFallback } 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";
+const WIN = REQUIRED_RULES.setup.win32;
+const VIRTUALIZATION = new RegExp(WIN.virtualization_errors, "i");
+const POLICY = /group policy|blocked by (?:your|the) (?:administrator|organi[sz]ation)|0x800f0950|0x800f0922|0x80070422/i;
+const VM_MODEL = /virtual machine|vmware|virtualbox|kvm|qemu|xen|parallels|hyper-v|bochs/i;
-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;
-};
+// --- setup.json (CLI: setup-state.js) --------------------------------------------------
+
+/** How long a declined setup is not offered again at a chat start. */
+export const DECLINED_QUIET_MS = 7 * 24 * 3_600_000;
-type StepState = { state: "installed" | "allowed" | "failed" | "declined"; at: number; message: string; update?: number };
-export type SetupState = { win?: StepState; linux?: StepState; declinedAt?: number };
+/** One OS's entry: a restart pending, declined, a machine that cannot run it (and why); the app adds the last step's line. */
+export type SetupEntry = { state: "restart" | "declined" | "blocked" | "failed"; why?: CannotRunWhy; message?: string; at: number };
+export type SetupState = { win?: SetupEntry; linux?: SetupEntry };
export function setupFile(home: string): string {
return path.join(home, "setup.json");
}
-export function readSetupState(home: string): SetupState {
+export function setupState(home: string): SetupState {
try {
const value: unknown = JSON.parse(readFileSync(setupFile(home), "utf8"));
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -62,17 +62,48 @@ export function readSetupState(home: string): SetupState {
}
}
-export function writeSetupState(home: string, update: (state: SetupState) => SetupState): SetupState {
- const next = update(readSetupState(home));
+/** Set (or with `entry` null, clear) one OS's entry. */
+export function saveSetupState(home: string, which: "win" | "linux", entry: Omit<SetupEntry, "at"> | null, { now = Date.now() }: { now?: number } = {}): SetupState {
+ const state = setupState(home);
+ if (entry) state[which] = { ...entry, at: now };
+ else delete state[which];
try {
mkdirSync(home, { recursive: true });
- const tmp = `${setupFile(home)}.${process.pid}.tmp`;
- writeFileSync(tmp, JSON.stringify(next), { mode: 0o600 });
- renameSync(tmp, setupFile(home));
+ const file = setupFile(home);
+ if (Object.keys(state).length === 0) {
+ rmSync(file, { force: true });
+ return state;
+ }
+ const tmp = `${file}.${process.pid}.tmp`;
+ writeFileSync(tmp, `${JSON.stringify(state)}\n`, { mode: 0o600 });
+ renameSync(tmp, file);
} catch { /* best effort */ }
- return next;
+ return state;
+}
+
+/** Whether an entry is a decline still within its quiet time. */
+export function recentlyDeclined(entry: SetupEntry | undefined, { now = Date.now(), quietMs = DECLINED_QUIET_MS }: { now?: number; quietMs?: number } = {}): boolean {
+ return entry?.state === "declined" && now - Number(entry.at) < quietMs;
}
+// --- what is needed ----------------------------------------------------------------------
+
+/** 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 said "Not now" (or cancelled the admin prompt) within the last week: 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;
+};
+
/** 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 [];
@@ -80,12 +111,12 @@ function reasons(runtime: RuntimeResult | null): string[] {
}
/**
- * What the sandbox needs here, from the backend probe, this machine's facts
- * (Windows) and the last setup step. Pure.
+ * What the sandbox needs here, from the backend probe, this PC's checks
+ * (Windows) and setup.json. 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 };
+export function classifySetup({ runtime, platform, checks = null, state = {}, fallback, macVm = false, release = os.release(), now = Date.now() }: { runtime: RuntimeResult | null; platform: string; checks?: WindowsChecks | null; state?: SetupState; fallback: RequiredFallback; macVm?: boolean; release?: string; now?: number }): BoxSetup {
+ const entry = platform === "win32" ? state.win : platform === "linux" ? state.linux : undefined;
+ const base = { why: null, whyText: null, declined: recentlyDeclined(entry, { now }), result: entry?.message ? { ok: entry.state === "restart", message: entry.message, at: entry.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 });
@@ -96,111 +127,193 @@ export function classifySetup({ runtime, platform, facts = null, state = {}, fal
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 (entry?.state === "blocked" && entry.why) return cannot(entry.why);
+ if (said.some((reason) => VIRTUALIZATION.test(reason))) return cannot("firmware_off");
+ const decision = checks ? setupDecision(checks) : { ok: true as const };
+ if (!decision.ok) return cannot(decision.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" };
+ if (said.some((reason) => /WSL 2 is not enabled/.test(reason))) return { ...base, need: entry?.state === "restart" ? "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");
+ const darwin = Number(/^(\d+)/.exec(release)?.[1] ?? 0);
+ if (darwin && darwin < 22) return cannot("old_macos");
return { ...base, need: macVm ? "mac_vm" : "runtime" };
}
return { ...base, need: "runtime" };
}
-// --- Windows -------------------------------------------------------------------------------
+// --- Windows (CLI: win-setup.js) -------------------------------------------------------------
-let factsCache: { at: number; facts: WindowsFacts } | null = null;
+/** The Windows build number from os.release() ("10.0.19045" -> 19045), or null. */
+export function windowsBuild(release = os.release()): number | null {
+ const m = /^\d+\.\d+\.(\d+)/.exec(String(release ?? ""));
+ return m ? Number(m[1]) : null;
+}
+
+/** The one PowerShell call that reads what the decision needs, as JSON. */
+export const CHECK_SCRIPT = [
+ "$o = @{}",
+ "try { $p = Get-CimInstance Win32_Processor | Select-Object -First 1; $o.firmware = [bool]$p.VirtualizationFirmwareEnabled } catch {}",
+ "try { $c = Get-CimInstance Win32_ComputerSystem; $o.hypervisor = [bool]$c.HypervisorPresent; $o.model = \"$($c.Manufacturer) $($c.Model)\" } catch {}",
+ "try { $o.s_mode = ((Get-ItemProperty 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\CI\\Policy' -ErrorAction Stop).SkuPolicyRequired -eq 1) } catch { $o.s_mode = $false }",
+ "$o | ConvertTo-Json -Compress",
+].join("; ");
+
+/** powershell.exe, as Windows has it. */
+export function powershellExe(env: NodeJS.ProcessEnv = process.env): string {
+ const root = env.SystemRoot || env.SYSTEMROOT || "C:\\Windows";
+ return path.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
+}
-/** 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;
+export type WindowsChecks = { build: number | null; firmware: boolean | null; hypervisor: boolean | null; model: string | null; s_mode: boolean | null };
+
+/** { build, firmware, hypervisor, model, s_mode } (unknown values null). */
+export async function windowsChecks({ run = runCommand, env = process.env, release = os.release() }: { run?: RunCommand; env?: NodeJS.ProcessEnv; release?: string } = {}): Promise<WindowsChecks> {
+ const out: WindowsChecks = { build: windowsBuild(release), firmware: null, hypervisor: null, model: null, s_mode: null };
+ const res = await run(powershellExe(env), ["-NoProfile", "-NonInteractive", "-Command", CHECK_SCRIPT], { env, timeoutMs: 20_000 }).catch(() => null);
+ try {
+ const value: unknown = JSON.parse(String(res?.stdout ?? "").trim().split(/\r?\n/).pop() || "{}");
+ if (value && typeof value === "object") {
+ const read = (key: string): unknown => Reflect.get(value, key);
+ for (const key of ["firmware", "hypervisor", "s_mode"] as const) {
+ const v = read(key);
+ if (typeof v === "boolean") out[key] = v;
+ }
+ const model = read("model");
+ if (typeof model === "string") out.model = model.trim().slice(0, 120);
+ }
+ } catch { /* unknown: the install tries */ }
+ return out;
}
-/** A PowerShell single-quoted string. */
-function psQuote(value: string): string {
- return `'${value.replace(/'/g, "''")}'`;
+let checksCache: { at: number; checks: WindowsChecks } | null = null;
+
+/** windowsChecks, kept 10 minutes unless `fresh` ("Check again"). */
+export async function cachedWindowsChecks({ fresh = false, now = Date.now(), run = runCommand }: { fresh?: boolean; now?: number; run?: RunCommand } = {}): Promise<WindowsChecks> {
+ if (!fresh && checksCache && now - checksCache.at < 10 * 60_000) return checksCache.checks;
+ const checks = await windowsChecks({ run });
+ checksCache = { at: now, checks };
+ return checks;
}
-/** 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(" ");
+/**
+ * Whether the WSL install can work here: { ok: true } or { ok: false, why }
+ * (old_windows, s_mode, firmware_off, nested_vm). HypervisorPresent=true
+ * passes (the firmware flag reads false under a running Hyper-V); an unknown
+ * answer passes (the install says).
+ */
+export function setupDecision(checks: Partial<WindowsChecks> | null, { minBuild = WIN.min_build }: { minBuild?: number } = {}): { ok: true } | { ok: false; why: CannotRunWhy } {
+ if (Number.isFinite(checks?.build) && Number(checks?.build) < minBuild) return { ok: false, why: "old_windows" };
+ if (checks?.s_mode === true) return { ok: false, why: "s_mode" };
+ if (checks?.hypervisor === true) return { ok: true };
+ if (checks?.firmware === false) return { ok: false, why: VM_MODEL.test(String(checks.model ?? "")) ? "nested_vm" : "firmware_off" };
+ return { ok: true };
+}
+
+/**
+ * What the elevated install's log says: installed (it got to its last
+ * line), blocked (virtualization, policy) or failed with a line.
+ */
+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" };
+ 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) };
+}
+
+/** The Start-Process command line that runs `ps1` elevated, once, waiting for it. */
+export function elevatedArgs(ps1: string, log: string): string[] {
+ const q = (p: string) => p.replace(/'/g, "''");
+ return ["-NoProfile", "-NonInteractive", "-Command",
+ `Start-Process -FilePath powershell.exe -Verb RunAs -Wait -WindowStyle Hidden -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "${q(ps1)}" "${q(log)}"'`];
}
/** 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"];
+ return ["add", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce", "/v", WIN.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.
+ * "Set up (one restart)": the checks, then the shared install script
+ * elevated once. Installed: the resume marker (win: restart) and the RunOnce
+ * value (`exe`: this app). The admin prompt cancelled: 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;
+export async function windowsInstall({ home, env = process.env, run = runCommand, exe = process.versions.electron ? process.execPath : null, tmpDir = os.tmpdir(), checks: given = null, now = Date.now(), release = os.release() }: { home: string; env?: NodeJS.ProcessEnv; run?: RunCommand; exe?: string | null; tmpDir?: string; checks?: WindowsChecks | null; now?: number; release?: string }): Promise<SetupEntry> {
+ const saved = (entry: Omit<SetupEntry, "at">): SetupEntry => {
+ saveSetupState(home, "win", entry, { now });
+ return { ...entry, at: now };
+ };
+ 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");
+ let text = "";
+ let res: Awaited<ReturnType<RunCommand>> | null = null;
+ try {
+ res = await run(powershellExe(env), elevatedArgs(ps1, logFile), { env, timeoutMs: 30 * 60_000 });
+ try { text = readFileSync(logFile, "utf8"); } catch { text = ""; }
+ } finally {
+ rmSync(ps1, { force: true });
+ rmSync(logFile, { 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." });
+ const parsed = parseInstallLog(text);
+ if (parsed.result === "blocked") return saved({ state: "blocked", why: parsed.why });
+ if (parsed.result === "failed") return saved({ state: "failed", message: `The WSL install did not finish: ${parsed.line}` });
+ if (exe) await run("reg.exe", runOnceArgs(exe), { env, timeoutMs: 15_000 });
+ return saved({ state: "restart", message: "WSL 2 is installed. Restart Windows to finish." });
}
-/** Restart Windows now (the screen's "Restart now"; never while a chat runs: the caller checks). */
+/** "Restart now" (never while a chat runs: the route 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 });
+/**
+ * The start after the restart (the resume marker): `wsl --update` when WSL
+ * asks for it, then the marker goes (the box start imports the distro and
+ * downloads the image). WSL still off: the marker stays (no restart yet);
+ * virtualization errors: the machine is marked as unable.
+ */
+export async function resumeWinSetup({ home, env = process.env, run = runCommand, log = () => {}, now = Date.now(), bin: given = null }: { home: string; env?: NodeJS.ProcessEnv; run?: RunCommand; log?: (level: "info" | "warn", message: string) => void; now?: number; bin?: string | null }): Promise<{ ok: boolean; state: "none" | "restart" | "blocked" | "ready" }> {
+ if (setupState(home).win?.state !== "restart") return { ok: false, state: "none" };
+ 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 = `${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 = `${status.stdout}\n${status.stderr}`;
}
+ if (VIRTUALIZATION.test(said)) {
+ saveSetupState(home, "win", { state: "blocked", why: "firmware_off" }, { now });
+ return { ok: false, state: "blocked" };
+ }
+ if (/not installed|is not enabled|optional component|WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED/i.test(said)) 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" };
}
-// --- Linux -------------------------------------------------------------------------------------
+// --- Linux (CLI: backends/bwrap.js enableBwrap) ----------------------------------------------
/**
- * 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.
+ * The root step `sandbox enable` does, 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);
@@ -235,26 +348,43 @@ export function allowSource({ env = process.env, arch = process.arch, exists = e
* "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.
+ * 126 when the prompt was dismissed and 127 when not authorised. Allowed:
+ * the linux entry goes; dismissed: declined; else failed, with the line.
*/
-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;
+export async function linuxAllow({ home, env = process.env, run = runCommand, source = allowSource({ env }), now = Date.now() }: { home: string; env?: NodeJS.ProcessEnv; run?: RunCommand; source?: string | null; now?: number }): Promise<{ ok: boolean; message: string }> {
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}).` };
+ const message = "No bubblewrap to install: install your system's bubblewrap package, then try again.";
+ saveSetupState(home, "linux", { state: "failed", message }, { now });
+ return { ok: false, message };
+ }
+ 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) {
+ saveSetupState(home, "linux", null, { now });
+ return { ok: true, message: said ? `Allowed (${said}).` : "Allowed." };
}
- writeSetupState(home, (state) => ({ ...state, linux: step, ...(step.state === "declined" ? { declinedAt: step.at } : { declinedAt: undefined }) }));
- return step;
+ if (res.code === 126) {
+ const message = "The password prompt was dismissed; nothing changed.";
+ saveSetupState(home, "linux", { state: "declined", message }, { now });
+ return { ok: false, message };
+ }
+ const message = res.error === "ENOENT" ? "pkexec is missing here: run `sudo omnirush sandbox enable` in a terminal instead (OmniRush CLI)."
+ : res.code === 127 ? `Not authorised${said ? `: ${said}` : ""}.`
+ : said || `The step stopped (${res.code}).`;
+ saveSetupState(home, "linux", { state: "failed", message }, { now });
+ return { ok: false, message };
+}
+
+/** "Update WSL" (WSL asks for an update): `wsl --update`, which asks for admin itself when it needs to. */
+export async function windowsUpdate({ env = process.env, run = runCommand }: { env?: NodeJS.ProcessEnv; run?: RunCommand } = {}): Promise<{ ok: boolean }> {
+ const bin = wslExe({ env });
+ if (!bin) return { ok: false };
+ const res = await wslCall(bin, ["--update", "--web-download"], { run, env, timeoutMs: 10 * 60_000 });
+ return { ok: res.code === 0 };
}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 22feb119..672d1003 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1427,6 +1427,8 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
everyMs: BOX_DEFAULT_REFRESH_MS,
});
}
+ // Windows, back after "Set up (one restart)": the setup finishes (WSL update, then the usual box start).
+ void boxes.resumeSetup().catch(() => false);
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);