A desktop coding agent with free access to frontier models.
TypeScript
fix: keep projects on macOS and Windows native when their folder has host builds
ogsamrat41cbf212c8b4
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 1dc3f85a..9413adf1 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -435,7 +435,8 @@ export type OmniRushWorkspaceBox = {mode: "on" | "off" | null;serverDefault: "off" | "offer" | "on";on: boolean;- source: "env" | "project" | "server" | "default";+ /** "host-builds": the server's default would put it in the sandbox, but the folder has this computer's builds. */+ source: "env" | "project" | "server" | "default" | "host-builds";offer: boolean;state: "off" | "unavailable" | "downloading" | "starting" | "ready" | "failed";runtime: { ok: boolean; name: string | null; flavor: string | null; version: string | null; reason: string | null } | null;@@ -459,6 +460,13 @@ export type OmniRushWorkspaceBox = {platform?: string;notice: string | null;error: string | null;+ /**+ * macOS / Windows: the folder has this computer's builds (node_modules, a venv, programs). `native`: its+ * chats stay on this computer; else the sandbox is on by choice and `notice` warns. Older servers: absent.+ */+ hostBuilds?: { native: boolean; things: string; notice: string } | null;+ /** macOS / Windows, while chats run in the sandbox: one line that says so. Older servers: absent. */+ boxNotice?: string | null;};export type OmniRushWorkspaceBoxProgress = {bytesDone: number | null;diff --git a/apps/app/src/react-app/domains/session/surface/composer/sandbox-status-chip.tsx b/apps/app/src/react-app/domains/session/surface/composer/sandbox-status-chip.tsxindex 2df605af..14df533f 100644--- a/apps/app/src/react-app/domains/session/surface/composer/sandbox-status-chip.tsx+++ b/apps/app/src/react-app/domains/session/surface/composer/sandbox-status-chip.tsx@@ -39,6 +39,28 @@ function SandboxChip(props: { client: LinuxSandboxClient; workspaceId: string; oconst chip = "flex h-9 max-h-9 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-sm text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12";if (!box.on && sandbox.pending !== "on") {+ // The server's default left this project on this computer (its folder has this computer's builds): say why.+ if (box.hostBuilds?.native) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={<button type="button" aria-label="Linux sandbox: off for this project" data-testid="sandbox-host-builds-chip" className={chip} onClick={props.onOpenSettings} />}+ >+ <span className="relative">+ <Box className="size-4" aria-hidden />+ <span aria-hidden className={`absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2 ring-dls-surface ${DOT.off}`} />+ </span>+ <span className="hidden whitespace-nowrap @min-[760px]/composer:inline">Sandbox off</span>+ </TooltipTrigger>+ <TooltipContent>+ <div className="flex max-w-64 flex-col">+ <span className="font-medium">Linux sandbox: off for this project</span>+ <span>{box.hostBuilds.notice}</span>+ </div>+ </TooltipContent>+ </Tooltip>+ );+ }if (!box.offer || offerDismissed) return null;return (<div className="flex shrink-0 items-center rounded-md border border-dashed border-gray-6" data-testid="sandbox-offer-chip">diff --git a/apps/app/src/react-app/domains/settings/linux-sandbox.ts b/apps/app/src/react-app/domains/settings/linux-sandbox.tsindex 45e130c2..1345a5f1 100644--- a/apps/app/src/react-app/domains/settings/linux-sandbox.ts+++ b/apps/app/src/react-app/domains/settings/linux-sandbox.ts@@ -104,6 +104,7 @@ export function linuxSandboxView(box: OmniRushWorkspaceBox, pending: LinuxSandboif (pending === "retry") return { ...base, tone: "busy", title: "Trying again…", detail: null };if (!box.on) {if (box.source === "env") return { ...base, tone: "off", title: "Off for this app", detail: "Set by OMNIRUSH_BOX where the app is launched." };+ if (box.hostBuilds?.native) return { ...base, tone: "attention", title: "Off for this project", detail: box.hostBuilds.notice };return { ...base, tone: "off", title: "Off", detail: "Commands run on this computer." };}const using = runtimeLabel(box);@@ -113,7 +114,9 @@ export function linuxSandboxView(box: OmniRushWorkspaceBox, pending: LinuxSandbocase "starting":return { ...base, tone: "busy", title: "Starting the sandbox…", detail: using ? `Using ${using}. This takes a few seconds.` : "This takes a few seconds." };case "ready":- return { ...base, tone: "ready", title: "Ready", detail: using ? `Commands run in a Linux container (${using}).` : "Commands run in a Linux container." };+ // On by choice in a folder with this computer's builds: the warning; on macOS / Windows: that chats run in Linux.+ if (box.hostBuilds && !box.hostBuilds.native) return { ...base, tone: "attention", title: "Ready", detail: box.hostBuilds.notice };+ return { ...base, tone: "ready", title: "Ready", detail: box.boxNotice ?? (using ? `Commands run in a Linux container (${using}).` : "Commands run in a Linux container.") };case "failed":return { ...base, tone: "error", title: "The sandbox could not start", detail: RUNS_HERE, action: { kind: "retry", label: "Try again" }, errorDetail: box.error ?? box.notice };case "unavailable": {diff --git a/apps/app/tests/linux-sandbox-card.test.tsx b/apps/app/tests/linux-sandbox-card.test.tsxindex b00ca03b..0c5b23ea 100644--- a/apps/app/tests/linux-sandbox-card.test.tsx+++ b/apps/app/tests/linux-sandbox-card.test.tsx@@ -156,6 +156,20 @@ describe("Linux sandbox card", () => {expect(linuxSandboxView(box({ ...on, state: "unavailable", notice: "Sandbox off for now: the sandbox did not start in time." }))).toMatchObject({ title: "The sandbox is not running", action: { kind: "retry" }, errorDetail: "the sandbox did not start in time" });});+ test("macOS / Windows: a project kept off for its host builds says why (switch off, one click on); on by choice it warns; a box says it is Linux", () => {+ const kept = "This folder has Mac builds (node_modules, .venv) that won't run in the Linux sandbox, so its chats run on this Mac. Turn the sandbox on for this project to use it anyway.";+ const off = box({ on: false, source: "host-builds", state: "off", notice: kept, hostBuilds: { native: true, things: "node_modules, .venv", notice: kept } });+ expect(linuxSandboxView(off)).toMatchObject({ tone: "attention", title: "Off for this project", detail: kept });+ const markup = card({ box: off });+ expect(switchMarkup(markup)).toContain('aria-checked="false"');+ expect(switchMarkup(markup)).not.toContain('aria-disabled="true"');+ expect(markup).toContain("Mac builds (node_modules, .venv)");+ const warning = "This folder has Mac builds (node_modules) that won't run in the Linux sandbox; rebuilding them there replaces them with Linux builds that won't run on this Mac.";+ expect(linuxSandboxView(box({ ...on, mode: "on", source: "project", state: "ready", hostBuilds: { native: false, things: "node_modules", notice: warning } }))).toMatchObject({ tone: "attention", title: "Ready", detail: warning });+ const line = "Chats here run in a Linux sandbox, not on this Mac; turn it off for this project in Settings to run them here.";+ expect(linuxSandboxView(box({ ...on, state: "ready", boxNotice: line }))).toMatchObject({ tone: "ready", title: "Ready", detail: line });+ });+test("forced by the environment: the switch is locked and says where", () => {const markup = card({ box: box({ source: "env" }) });expect(switchMarkup(markup)).toContain('aria-disabled="true"');diff --git a/apps/server/src/box/PARITY.sha256 b/apps/server/src/box/PARITY.sha256index be700f13..35321fed 100644--- a/apps/server/src/box/PARITY.sha256+++ b/apps/server/src/box/PARITY.sha256@@ -1,4 +1,6 @@# The sandbox image pins: the same files in omnirush-cli (src/box/) and omnirush-gui (apps/server/src/box/).+# host-builds.json: the rules and notices for folders with macOS/Windows builds (host-builds.js / host-builds.ts read it).# A change to one must be ported to the other and this list updated in both (scripts/box/pins.mjs refreshes the pins' list).f4cf889b29e169592863020c6ac2b02c69d8887a8df1502dd01c7939805a9b8a images.jsonfd7531323e200f2133cdf66ed8608d04af3a38049cfeb01a0a285cbd72813c4d wsl.json+ec1c7507cd3919a1066c870e3f7018424bdca8641fbf34fec9c4eefd9def1d29 host-builds.jsondiff --git a/apps/server/src/box/host-builds.json b/apps/server/src/box/host-builds.jsonnew file mode 100644index 00000000..4ea4fe64--- /dev/null+++ b/apps/server/src/box/host-builds.json@@ -0,0 +1,39 @@+{+ "version": 1,+ "about": "Which builds in a project folder only run on the user's macOS or Windows machine (src/box/host-builds.js in the CLI, apps/server/src/box/host-builds.ts in the desktop app read this same file). Linux hosts are never checked.",+ "limits": { "entries": 4000, "ms": 150, "binDepth": 2, "cacheEntries": 200, "cacheMs": 21600000 },+ "hosts": {+ "darwin": {+ "label": "Mac",+ "machine": "this Mac",+ "format": "macho",+ "packages": "(?:^|[-/+])darwin-(?:arm64|x64|64|universal)(?:$|[-@])",+ "venv_home": ["/Library/", "/System/", "/Applications/", "/opt/homebrew/", "/opt/local/", "/usr/local/Cellar/", "/usr/local/opt/", "/usr/local/Frameworks/", "/Users/", "/private/", "/opt/anaconda", "/opt/miniconda", "/opt/miniforge"],+ "venv_home_patterns": []+ },+ "win32": {+ "label": "Windows",+ "machine": "this PC",+ "format": "pe",+ "packages": "(?:^|[-/+])(?:win32|windows)-(?:x64|arm64|ia32|64)(?:$|[-@])",+ "venv_home": ["\\\\"],+ "venv_home_patterns": ["^[A-Za-z]:[\\\\/]"]+ }+ },+ "venv_dirs": [".venv", "venv", "env", ".env"],+ "venv_host_files": ["Scripts/python.exe", "Scripts/pythonw.exe"],+ "build_dirs": ["bin", "build", "target", "dist", "out"],+ "binary_extensions": [".exe", ".dll", ".dylib", ".node", ".so", ".pyd"],+ "notices": {+ "cli": {+ "native": "This folder has {label} builds ({things}) that won't run in the Linux sandbox, so this chat runs on {machine}. `omnirush sandbox on` to use the sandbox here anyway.",+ "explicit": "This chat runs in a Linux sandbox, but this folder has {label} builds ({things}) that won't run there; rebuilding them inside replaces them with Linux builds that won't run on {machine} (`omnirush --no-sandbox` runs it on {machine}).",+ "box": "This chat runs in a Linux sandbox (this folder mounted, installs kept per folder); `omnirush --no-sandbox` or `omnirush sandbox off` runs it on {machine}."+ },+ "desktop": {+ "native": "This folder has {label} builds ({things}) that won't run in the Linux sandbox, so its chats run on {machine}. Turn the sandbox on for this project to use it anyway.",+ "explicit": "This folder has {label} builds ({things}) that won't run in the Linux sandbox; rebuilding them there replaces them with Linux builds that won't run on {machine}.",+ "box": "Chats here run in a Linux sandbox, not on {machine}; turn it off for this project in Settings to run them here."+ }+ }+}diff --git a/apps/server/src/box/host-builds.test.ts b/apps/server/src/box/host-builds.test.tsnew file mode 100644index 00000000..90e48b8d--- /dev/null+++ b/apps/server/src/box/host-builds.test.ts@@ -0,0 +1,183 @@+// macOS / Windows folders with this computer's builds (host-builds.ts, the+// CLI's host-builds.js on the same host-builds.json): a project only the+// server's default would put in the Linux box stays here with one line; one+// the user turned on goes in with a warning. Fixtures carry real Mach-O / PE+// / ELF headers. The CLI's test/box-host-builds.test.js covers the same cases.+import { describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";++import { rememberServerDefault } from "./launch.js";+import { HOST_BUILD_RULES, binaryFormat, hostBuildThings, hostBuilds, hostBuildsNotice, hostPath, scanHostBuilds } from "./host-builds.js";+import { BoxService, type BoxWorkspace } from "./service.js";++const MACHO = Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01, 0, 0, 0, 0, 2, 0, 0, 0]);+const MACHO_FAT = Buffer.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 2, 0x01, 0, 0, 0x07]);+const JAVA_CLASS = Buffer.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0x34]);+const ELF = Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]);+const PE = (() => {+ const buf = Buffer.alloc(0x100);+ buf.write("MZ", 0, "latin1");+ buf.writeUInt32LE(0x80, 0x3c);+ buf.write("PE\0\0", 0x80, "latin1");+ return buf;+})();+const SCRIPT = Buffer.from("#!/usr/bin/env node\nrequire('../lib/cli.js')\n");++function tmp(prefix = "omnirush-hostbuilds-"): string {+ return mkdtempSync(path.join(os.tmpdir(), prefix));+}+function put(root: string, rel: string, content: Buffer | string, mode = 0o644): string {+ const file = path.join(root, rel);+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, content, { mode });+ return file;+}+function darwinNodeProject(root = tmp()): string {+ put(root, "package.json", "{}");+ put(root, "node_modules/esbuild/bin/esbuild", MACHO, 0o755);+ put(root, "node_modules/@esbuild/darwin-arm64/bin/esbuild", MACHO, 0o755);+ put(root, "node_modules/@img/sharp-darwin-arm64/lib/sharp-darwin-arm64.node", MACHO);+ put(root, "node_modules/better-sqlite3/build/Release/better_sqlite3.node", MACHO);+ mkdirSync(path.join(root, "node_modules/.bin"), { recursive: true });+ symlinkSync("../esbuild/bin/esbuild", path.join(root, "node_modules/.bin/esbuild"));+ return root;+}++describe("host builds: detection", () => {+ test("formats: Mach-O (thin, universal), PE, ELF; Java classes and scripts are none", () => {+ expect(binaryFormat(MACHO)).toBe("macho");+ expect(binaryFormat(MACHO_FAT)).toBe("macho");+ expect(binaryFormat(JAVA_CLASS)).toBeNull();+ expect(binaryFormat(PE)).toBe("pe");+ expect(binaryFormat(ELF)).toBe("elf");+ expect(binaryFormat(SCRIPT)).toBeNull();+ });++ test("venv homes: macOS and Windows interpreters are the host's; a box-made /usr/bin one is not", () => {+ expect(hostPath("/Library/Developer/CommandLineTools/usr/bin", "darwin")).toBe(true);+ expect(hostPath("/opt/homebrew/opt/[email protected]/bin", "darwin")).toBe(true);+ expect(hostPath("/usr/bin", "darwin")).toBe(false);+ expect(hostPath("C:\\Users\\sam\\AppData\\Local\\Programs\\Python\\Python312", "win32")).toBe(true);+ expect(hostPath("/Library/Frameworks", "linux")).toBe(false);+ });++ test("macOS: darwin node_modules, a Mac venv and a Mach-O bin/app are named; the box's Linux builds are not", () => {+ const root = darwinNodeProject();+ put(root, ".venv/pyvenv.cfg", "home = /Library/Developer/CommandLineTools/usr/bin\nversion = 3.9.6\n");+ put(root, "bin/app", MACHO, 0o755);+ const r = scanHostBuilds(root, { platform: "darwin" });+ expect(r.hits.map((h) => [h.kind, h.path])).toEqual([["venv", ".venv"], ["node_modules", "node_modules/@esbuild/darwin-arm64"], ["binary", "bin/app"]]);+ expect(hostBuildThings(r)).toBe("node_modules, .venv, bin/app");+ expect(hostBuildsNotice("native", { platform: "darwin", result: r })).toBe("This folder has Mac builds (node_modules, .venv, bin/app) that won't run in the Linux sandbox, so its chats run on this Mac. Turn the sandbox on for this project to use it anyway.");++ const addon = tmp();+ put(addon, "node_modules/better-sqlite3/build/Release/better_sqlite3.node", MACHO);+ expect(scanHostBuilds(addon, { platform: "darwin" }).hits[0]?.why).toBe("native addon");++ const linux = tmp();+ put(linux, "node_modules/@esbuild/linux-arm64/bin/esbuild", ELF, 0o755);+ put(linux, "node_modules/better-sqlite3/build/Release/better_sqlite3.node", ELF);+ put(linux, ".venv/pyvenv.cfg", "home = /usr/bin\nversion = 3.11.2\n");+ put(linux, "bin/app", ELF, 0o755);+ put(linux, "target/debug/deps/app-1", MACHO, 0o755);+ expect(scanHostBuilds(linux, { platform: "darwin" }).found).toBe(false);+ });++ test("Windows: win32 packages, a C:\\ venv or Scripts\\python.exe, PE programs; Mac builds do not count", () => {+ const node = tmp();+ put(node, "node_modules/@esbuild/win32-x64/esbuild.exe", PE);+ expect(scanHostBuilds(node, { platform: "win32" }).hits[0]?.path).toBe("node_modules/@esbuild/win32-x64");+ const venv = tmp();+ put(venv, ".venv/pyvenv.cfg", "home = C:\\Python312\r\n");+ expect(scanHostBuilds(venv, { platform: "win32" }).hits[0]?.kind).toBe("venv");+ const scripts = tmp();+ put(scripts, "venv/pyvenv.cfg", "home = /x\n");+ put(scripts, "venv/Scripts/python.exe", PE);+ expect(scanHostBuilds(scripts, { platform: "win32" }).hits[0]?.why).toBe("Scripts/python.exe");+ const exe = tmp();+ put(exe, "dist/app.exe", PE);+ expect(scanHostBuilds(exe, { platform: "win32" }).hits.map((h) => h.path)).toEqual(["dist/app.exe"]);+ expect(scanHostBuilds(darwinNodeProject(), { platform: "win32" }).found).toBe(false);+ });++ test("Linux is never checked; bounded; cached until a folder it reads changes", () => {+ expect(scanHostBuilds(darwinNodeProject(), { platform: "linux" }).found).toBe(false);+ const big = tmp();+ for (let i = 0; i < 1200; i++) mkdirSync(path.join(big, "node_modules", `pkg-${i}`), { recursive: true });+ put(big, "bin/app", MACHO, 0o755);+ expect(scanHostBuilds(big, { platform: "darwin", limits: { ...HOST_BUILD_RULES.limits, entries: 300 } }).truncated).toBe(true);+ const full = scanHostBuilds(big, { platform: "darwin" });+ expect(full.found).toBe(true);+ expect(full.ms).toBeLessThan(1_000);++ const state = tmp();+ const root = tmp();+ put(root, "bin/app", ELF, 0o755);+ expect(hostBuilds(root, { platform: "darwin", stateDir: state }).found).toBe(false);+ expect(hostBuilds(root, { platform: "darwin", stateDir: state }).cached).toBe(true);+ put(root, "bin/app2", MACHO, 0o755);+ utimesSync(path.join(root, "bin"), new Date(), new Date(Date.now() + 5_000));+ const again = hostBuilds(root, { platform: "darwin", stateDir: state });+ expect(again.cached).toBeUndefined();+ expect(again.found).toBe(true);+ });+});++describe("host builds: the desktop's projects", () => {+ type Settings = Map<string, { mode: "on" | "off" | null; offered: boolean }>;+ function service(stateDir: string, workspace: BoxWorkspace, settings: Settings, platform: NodeJS.Platform, env: NodeJS.ProcessEnv = {}) {+ return new BoxService({+ stateDir,+ readSettings: async (id) => settings.get(id) ?? { mode: null, offered: false },+ writeSettings: async (id, update) => {+ const current = settings.get(id) ?? { mode: null, offered: false };+ settings.set(id, { mode: update.mode === undefined ? current.mode : update.mode, offered: update.offered ?? current.offered });+ },+ workspaces: () => [workspace],+ pluginPath: () => "/plugins/omnirush-box.js",+ env: { OMNIRUSH_BOX_HOME: tmp("boxhome-"), PATH: "", OMNIRUSH_BOX_RUNTIME: "/nonexistent/docker", ...env },+ platform,+ });+ }++ test("the server's default leaves a Mac-built project on this Mac; turned on by the user it goes in, with the warning", async () => {+ const stateDir = tmp("state-");+ const root = darwinNodeProject();+ rememberServerDefault(stateDir, { local_box: { default: "on" } });+ const workspace: BoxWorkspace = { id: "ws_mac", path: root, workspaceType: "local" };+ const settings: Settings = new Map();+ const boxes = service(stateDir, workspace, settings, "darwin");+ const status = await boxes.status(workspace);+ expect(status).toMatchObject({ mode: null, on: false, source: "host-builds", state: "off", boxNotice: null });+ expect(status.hostBuilds).toEqual({ native: true, things: "node_modules", notice: "This folder has Mac builds (node_modules) that won't run in the Linux sandbox, so its chats run on this Mac. Turn the sandbox on for this project to use it anyway." });+ expect(status.notice).toBe(status.hostBuilds!.notice);+ expect(await boxes.ensure(workspace)).toBeNull();+ expect(await boxes.listedProjects()).toEqual([]);+ expect(await boxes.beforePrompt("ses_hostbuilds_1", workspace)).toBeNull();+ // The project's own switch: in the box (none runs here, so "unavailable"), with the warning.+ const on = await boxes.setMode(workspace, "on");+ expect(on).toMatchObject({ mode: "on", on: true, source: "project" });+ expect(on.hostBuilds).toEqual({ native: false, things: "node_modules", notice: "This folder has Mac builds (node_modules) that won't run in the Linux sandbox; rebuilding them there replaces them with Linux builds that won't run on this Mac." });+ expect(on.boxNotice).toBe("Chats here run in a Linux sandbox, not on this Mac; turn it off for this project in Settings to run them here.");+ // OMNIRUSH_BOX=1 is the user's choice too; the off switch for the rule leaves the server's default as it was.+ expect(await service(stateDir, workspace, new Map(), "darwin", { OMNIRUSH_BOX: "1" }).status(workspace)).toMatchObject({ on: true, source: "env", hostBuilds: { native: false } });+ expect(await service(stateDir, workspace, new Map(), "darwin", { OMNIRUSH_BOX_KEEP_NATIVE: "off" }).status(workspace)).toMatchObject({ on: true, source: "server", hostBuilds: null });+ });++ test("a clean project gets the box with the one line on macOS / Windows; Linux is unchanged", async () => {+ const stateDir = tmp("state-");+ const root = tmp();+ put(root, "README.md", "# x\n");+ rememberServerDefault(stateDir, { local_box: { default: "on" } });+ const workspace: BoxWorkspace = { id: "ws_clean", path: root, workspaceType: "local" };+ const mac = await service(stateDir, workspace, new Map(), "darwin").status(workspace);+ expect(mac).toMatchObject({ on: true, source: "server", hostBuilds: null });+ expect(mac.boxNotice).toMatch(/^Chats here run in a Linux sandbox, not on this Mac/);+ expect((await service(stateDir, workspace, new Map(), "win32").status(workspace)).boxNotice).toMatch(/not on this PC/);+ const built = darwinNodeProject();+ const linux = await service(stateDir, { id: "ws_l", path: built, workspaceType: "local" }, new Map(), "linux").status({ id: "ws_l", path: built, workspaceType: "local" });+ expect(linux).toMatchObject({ on: true, source: "server", hostBuilds: null, boxNotice: null });+ });+});diff --git a/apps/server/src/box/host-builds.ts b/apps/server/src/box/host-builds.tsnew file mode 100644index 00000000..ea91df6b--- /dev/null+++ b/apps/server/src/box/host-builds.ts@@ -0,0 +1,294 @@+// Ported from the CLI (omnirush-cli src/box/host-builds.js); keep the two in+// step. host-builds.json (the rules and the notices) is the same file in both,+// listed in PARITY.sha256.+//+// Builds in a project folder that only run on this macOS or Windows machine:+// native packages and addons in node_modules, a venv made from this+// machine's Python, Mach-O / PE programs in the usual output folders. A+// project that only the server's default would put in the Linux box stays on+// this machine when its folder has them (service.ts): they fail in the box,+// and rebuilding them there writes Linux builds into the folder this machine+// uses too. Linux hosts are never checked.+//+// Bounded (entries and time, host-builds.json `limits`) and cached per folder+// with a signature of the folders it reads (mtime + inode).++import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, renameSync, statSync, writeFileSync, type Dirent } from "node:fs";+import path from "node:path";++import rules from "./host-builds.json" with { type: "json" };++export type HostRules = { label: string; machine: string; format: string; packages: string; venv_home: string[]; venv_home_patterns: string[] };+export type HostBuildLimits = { entries: number; ms: number; binDepth: number; cacheEntries: number; cacheMs: number };+export type HostBuildHit = { kind: "node_modules" | "venv" | "binary"; path: string; why: string };+export type HostBuildScan = { host: string; found: boolean; hits: HostBuildHit[]; scanned: number; ms: number; truncated: boolean; cached?: true };+export type HostBuildNotice = "native" | "explicit" | "box";++export const HOST_BUILD_RULES: {+ limits: HostBuildLimits;+ hosts: Record<string, HostRules>;+ venv_dirs: string[];+ venv_host_files: string[];+ build_dirs: string[];+ binary_extensions: string[];+ notices: Record<"cli" | "desktop", Record<HostBuildNotice, string>>;+} = rules;++/** The rules of a host whose builds the Linux box cannot run (darwin, win32), else null. */+export function hostRules(platform: string = process.platform): HostRules | null {+ return HOST_BUILD_RULES.hosts[platform] ?? null;+}++/** "macho", "pe", "elf" or null, from a file's first bytes. */+export function binaryFormat(buf: Buffer | null | undefined): "macho" | "pe" | "elf" | null {+ if (!buf || buf.length < 4) return null;+ const be = buf.readUInt32BE(0);+ if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(be)) return "macho";+ // A universal binary; Java class files share the magic, with a version (45+) where the arch count is.+ if ((be === 0xcafebabe || be === 0xcafebabf) && buf.length >= 8) {+ const count = buf.readUInt32BE(4);+ if (count > 0 && count < 30) return "macho";+ }+ if (be === 0x7f454c46) return "elf";+ if (buf[0] === 0x4d && buf[1] === 0x5a) {+ if (buf.length < 0x40) return null;+ const at = buf.readUInt32LE(0x3c);+ if (at + 4 <= buf.length) return buf.toString("latin1", at, at + 4) === "PE\0\0" ? "pe" : null;+ return "pe";+ }+ return null;+}++function header(file: string, bytes = 1024): Buffer | null {+ let fd: number | undefined;+ try {+ fd = openSync(file, "r");+ const buf = Buffer.alloc(bytes);+ const n = readSync(fd, buf, 0, bytes, 0);+ return buf.subarray(0, n);+ } catch {+ return null;+ } finally {+ if (fd !== undefined) { try { closeSync(fd); } catch { /* closed */ } }+ }+}++/** Whether a venv's interpreter path (pyvenv.cfg `home`, `executable`, its python link) is this host's. */+export function hostPath(value: unknown, platform: string = process.platform): boolean {+ const host = hostRules(platform);+ const text = String(value ?? "").trim();+ if (!host || !text) return false;+ if (host.venv_home.some((prefix) => text.startsWith(prefix))) return true;+ return host.venv_home_patterns.some((pattern) => new RegExp(pattern).test(text));+}++/** pyvenv.cfg's keys (home, executable, base-executable, command, version...). */+export function parseVenvConfig(text: string): Record<string, string> {+ const out: Record<string, string> = {};+ for (const line of String(text ?? "").split(/\r?\n/)) {+ const m = /^\s*([A-Za-z_.-]+)\s*=\s*(.*?)\s*$/.exec(line);+ if (m) out[m[1]!.toLowerCase()] = m[2]!;+ }+ return out;+}++/**+ * Scan `root` for this host's builds: { host, found, hits: [{ kind, path,+ * why }], scanned, ms, truncated }. One hit per kind is enough; the scan+ * stops at the limits (`truncated`).+ */+export function scanHostBuilds(root: string, { platform = process.platform, limits = HOST_BUILD_RULES.limits, now = Date.now }: { platform?: string; limits?: HostBuildLimits; now?: () => number } = {}): HostBuildScan {+ const host = hostRules(platform);+ const started = now();+ const result: HostBuildScan = { host: platform, found: false, hits: [], scanned: 0, ms: 0, truncated: false };+ if (!host) return result;+ const packages = new RegExp(host.packages);+ const over = (): boolean => {+ if (result.scanned > limits.entries || now() - started > limits.ms) result.truncated = true;+ return result.truncated;+ };+ const list = (dir: string): Dirent[] => {+ if (over()) return [];+ result.scanned += 1;+ try {+ const entries = readdirSync(dir, { withFileTypes: true });+ result.scanned += entries.length;+ return entries;+ } catch {+ return [];+ }+ };+ const isHost = (file: string): boolean => {+ result.scanned += 1;+ return binaryFormat(header(file)) === host.format;+ };+ const rel = (p: string) => path.relative(root, p).split(path.sep).join("/");+ const hit = (kind: HostBuildHit["kind"], p: string, why: string) => { result.hits.push({ kind, path: rel(p), why }); };+ const has = (kind: HostBuildHit["kind"]) => result.hits.some((h) => h.kind === kind);++ // A venv made from this machine's Python (pyvenv.cfg's home, or its python link), or a Windows layout.+ for (const name of HOST_BUILD_RULES.venv_dirs) {+ if (has("venv") || over()) break;+ const dir = path.join(root, name);+ let cfg: Record<string, string> | null = null;+ try { cfg = parseVenvConfig(readFileSync(path.join(dir, "pyvenv.cfg"), "utf8").slice(0, 8192)); } catch { /* none */ }+ result.scanned += 1;+ if (!cfg) continue;+ const config = cfg;+ const from = ["home", "executable", "base-executable", "base-prefix"].map((k) => config[k]).find((v) => hostPath(v, platform));+ if (from) { hit("venv", dir, `pyvenv.cfg: ${from}`); continue; }+ if (platform === "win32") {+ const exe = HOST_BUILD_RULES.venv_host_files.find((f) => { try { return statSync(path.join(dir, f)).isFile(); } catch { return false; } });+ if (exe) { hit("venv", dir, exe); continue; }+ }+ for (const py of ["python3", "python"]) {+ let target: string | null = null;+ try { target = readlinkSync(path.join(dir, "bin", py)); } catch { /* not a link */ }+ if (target && path.isAbsolute(target) && hostPath(target, platform)) { hit("venv", dir, `bin/${py} -> ${target}`); break; }+ }+ }++ // node_modules: this host's platform packages (the cheapest sign: names only), then+ // .bin programs; compiled addons (build/Release/*.node) after the output folders.+ const nm = path.join(root, "node_modules");+ const top = list(nm);+ const pkgDirs: string[] = [];+ let binDir: string | null = null;+ for (const entry of top) {+ if (has("node_modules")) break;+ const name = entry.name;+ if (name === ".bin") { binDir = path.join(nm, name); continue; }+ if (name === ".pnpm") {+ const pnpm = list(path.join(nm, name)).find((e) => packages.test(e.name));+ if (pnpm) hit("node_modules", path.join(nm, name, pnpm.name), "platform package");+ continue;+ }+ if (name.startsWith(".") || !(entry.isDirectory() || entry.isSymbolicLink())) continue;+ if (name.startsWith("@")) {+ for (const sub of list(path.join(nm, name))) {+ const full = `${name}/${sub.name}`;+ if (packages.test(full)) { hit("node_modules", path.join(nm, name, sub.name), "platform package"); break; }+ pkgDirs.push(path.join(nm, name, sub.name));+ }+ continue;+ }+ if (packages.test(name)) { hit("node_modules", path.join(nm, name), "platform package"); break; }+ pkgDirs.push(path.join(nm, name));+ }+ if (!has("node_modules") && binDir) {+ for (const entry of list(binDir)) {+ if (over()) break;+ if (/\.(cmd|ps1)$/i.test(entry.name)) continue;+ const file = path.join(binDir, entry.name);+ if (isHost(file)) { hit("node_modules", file, "program"); break; }+ }+ }++ // Programs in the usual output folders, a couple of levels down.+ const exts = new Set(HOST_BUILD_RULES.binary_extensions);+ const walk = (dir: string, depth: number): void => {+ for (const entry of list(dir)) {+ if (has("binary") || over()) return;+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (depth < limits.binDepth && !["node_modules", ".git", "deps", "incremental", ".fingerprint"].includes(entry.name)) walk(full, depth + 1);+ continue;+ }+ if (!entry.isFile()) continue;+ const ext = path.extname(entry.name).toLowerCase();+ let candidate = exts.has(ext);+ if (!candidate && !ext && platform !== "win32") {+ try { candidate = (lstatSync(full).mode & 0o111) !== 0; } catch { candidate = false; }+ }+ if (candidate && isHost(full)) hit("binary", full, host.format);+ }+ };+ for (const name of HOST_BUILD_RULES.build_dirs) {+ if (has("binary") || over()) break;+ walk(path.join(root, name), 1);+ }++ // Compiled addons last: one look per package (the most entries).+ if (!has("node_modules")) {+ outer: for (const dir of pkgDirs) {+ if (over()) break;+ for (const entry of list(path.join(dir, "build", "Release"))) {+ if (!entry.name.endsWith(".node")) continue;+ const file = path.join(dir, "build", "Release", entry.name);+ if (isHost(file)) { hit("node_modules", file, "native addon"); break outer; }+ }+ }+ }++ result.found = result.hits.length > 0;+ result.ms = now() - started;+ return result;+}++/** The folders a scan reads, as mtime + inode: a cached answer holds while none of them changed. */+export function hostBuildsSignature(root: string): string {+ const paths = [".", "node_modules", "node_modules/.bin", "node_modules/.pnpm", ...HOST_BUILD_RULES.venv_dirs.flatMap((d) => [d, `${d}/pyvenv.cfg`]), ...HOST_BUILD_RULES.build_dirs, "target/debug", "target/release", "build/Release"];+ return paths.map((p) => {+ try {+ const st = statSync(path.join(root, p));+ return `${Math.round(st.mtimeMs)}:${st.ino}`;+ } catch {+ return "-";+ }+ }).join(",");+}++function cacheFile(stateDir: string): string {+ return path.join(stateDir, "box-host-builds.json");+}++type CacheEntry = { sig: string; at: number; result: HostBuildScan };++/**+ * scanHostBuilds() with a per-folder cache in <stateDir>/box-host-builds.json+ * (`cached: true` on a hit). OMNIRUSH_BOX_HOST_BUILDS=off: never found.+ */+export function hostBuilds(root: string, { platform = process.platform, stateDir = null, env = process.env, limits = HOST_BUILD_RULES.limits, now = Date.now }: { platform?: string; stateDir?: string | null; env?: NodeJS.ProcessEnv; limits?: HostBuildLimits; now?: () => number } = {}): HostBuildScan {+ if (!hostRules(platform) || String(env.OMNIRUSH_BOX_HOST_BUILDS ?? "").trim().toLowerCase() === "off") return { host: platform, found: false, hits: [], scanned: 0, ms: 0, truncated: false };+ const key = `${platform}:${path.resolve(root)}`;+ const sig = hostBuildsSignature(root);+ let cache: Record<string, CacheEntry> = {};+ if (stateDir) {+ try { cache = JSON.parse(readFileSync(cacheFile(stateDir), "utf8")) ?? {}; } catch { cache = {}; }+ const seen = cache[key];+ if (seen && seen.sig === sig && now() - seen.at < limits.cacheMs && seen.result) return { ...seen.result, cached: true };+ }+ const result = scanHostBuilds(root, { platform, limits, now });+ if (stateDir) {+ try {+ cache[key] = { sig, at: now(), result };+ const keep = Object.entries(cache).sort((a, b) => (b[1]?.at ?? 0) - (a[1]?.at ?? 0)).slice(0, limits.cacheEntries);+ mkdirSync(stateDir, { recursive: true });+ const tmp = `${cacheFile(stateDir)}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(keep)), { mode: 0o600 });+ renameSync(tmp, cacheFile(stateDir));+ } catch { /* best effort */ }+ }+ return result;+}++/** What a scan found, for a notice: "node_modules, .venv, bin/app". */+export function hostBuildThings(result: Pick<HostBuildScan, "hits"> | null | undefined): string {+ const things: string[] = [];+ for (const kind of ["node_modules", "venv", "binary"] as const) {+ const h = result?.hits?.find((x) => x.kind === kind);+ if (!h) continue;+ things.push(kind === "node_modules" ? "node_modules" : h.path);+ }+ return things.join(", ");+}++/**+ * One line: `which` is "native" (kept on this machine), "explicit" (in the+ * box by the user's choice anyway) or "box" (box chats on macOS/Windows);+ * `surface` is "cli" or "desktop".+ */+export function hostBuildsNotice(which: HostBuildNotice, { platform = process.platform, result = null, surface = "desktop" }: { platform?: string; result?: Pick<HostBuildScan, "hits"> | null; surface?: "cli" | "desktop" } = {}): string {+ const host = hostRules(platform) ?? { label: "this machine's", machine: "this machine" };+ return HOST_BUILD_RULES.notices[surface][which].replaceAll("{label}", host.label).replaceAll("{machine}", host.machine).replaceAll("{things}", hostBuildThings(result));+}diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.tsindex 7a9ebc97..65212dc3 100644--- a/apps/server/src/box/service.ts+++ b/apps/server/src/box/service.ts@@ -28,6 +28,7 @@ import { boxHome, boxKey, boxSnapshotsDir, containerName, installShell, listBoxeimport { LABELS, OPT_IN, backendsFor, driverFor } from "./backends/index.js";import type { BoxExec } from "./backends/types.js";import type { BoxEndpoint } from "./client.js";+import { hostBuilds, hostBuildsNotice, hostBuildThings, hostRules } from "./host-builds.js";import { detectStack, imageFor } from "./images.js";import { askedBackend, boxRun, planBox, pullLog, pullMarker, pulling, pullInBackground, resolveMode, saveBackend, serverBackends, serverDefault, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";import type { BoxInstallLogPaths } from "./install-log.js";@@ -60,7 +61,8 @@ export type BoxStatus = {serverDefault: ServerBoxDefault;/** Whether the project's chats should run in its box. */on: boolean;- source: "env" | "project" | "server" | "default";+ /** "host-builds": the server's default would put it in the box, but its folder has this computer's builds (macOS, Windows). */+ source: "env" | "project" | "server" | "default" | "host-builds";/** The server offers the box and this project was not offered it yet. */offer: boolean;state: "off" | "unavailable" | "downloading" | "starting" | "ready" | "failed";@@ -78,6 +80,14 @@ export type BoxStatus = {/** One line for the user (why it is off, that it is downloading). */notice: string | null;error: string | null;+ /**+ * macOS / Windows: the folder has this computer's builds (host-builds.ts). `native`: its chats+ * stay on this computer (only the server's default had it on); else it is on by the user's+ * choice and `notice` warns that rebuilding them in the box replaces them. Null otherwise.+ */+ hostBuilds: { native: boolean; things: string; notice: string } | null;+ /** macOS / Windows, while the project's chats run in the box: the one line that says so (null elsewhere). */+ boxNotice: string | null;};export type BoxBackendView = {@@ -112,6 +122,8 @@ export type BoxServiceOptions = {env?: NodeJS.ProcessEnv;/** Whether a running box's project folder was deleted and made again (box.ts mountReplaced; tests replace it). */folderReplaced?: (box: { endpoint: BoxEndpoint; croot: string }) => Promise<boolean>;+ /** The OS whose builds count as this computer's (host-builds.ts; tests set it). */+ platform?: NodeJS.Platform;};/** `waitingImage`: planned while its image was downloading (planned again as soon as the image is here). */@@ -137,6 +149,7 @@ export class BoxService {private readonly nativeChats = new Map<string, string>();private readonly home: string;private readonly env: NodeJS.ProcessEnv;+ private readonly platform: NodeJS.Platform;private log: BoxLog;private projectsWrite: Promise<void> = Promise.resolve();private installLog: BoxInstallLogPaths | null = null;@@ -147,6 +160,7 @@ export class BoxService {constructor(private readonly options: BoxServiceOptions) {this.folderReplaced = options.folderReplaced ?? (({ endpoint, croot }) => mountReplaced({ endpoint }, { croot, readyMs: 1_000 }));this.env = options.env ?? process.env;+ this.platform = options.platform ?? process.platform;this.home = boxHome(this.env);this.log = options.log ?? (() => {});}@@ -224,7 +238,35 @@ export class BoxService {private async mode(workspace: BoxWorkspace) {const settings = await this.options.readSettings(workspace.id).catch(() => ({ mode: null, offered: false }));const server = this.serverDefault();- return { settings, server, ...resolveMode({ env: this.env, project: settings.mode, server, offered: settings.offered }) };+ const resolved = resolveMode({ env: this.env, project: settings.mode, server, offered: settings.offered });+ const gate = workspace.workspaceType === "local" ? this.hostGate(boxRoot(workspace), resolved) : null;+ // A box already running for the project keeps its chats (builds made since do not move them out).+ const running = this.projects.get(boxKey(boxRoot(workspace)))?.run;+ if (gate?.native && !(running && !running.native)) return { settings, server, ...resolved, on: false, source: "host-builds" as const, offer: false, hostBuilds: gate };+ return { settings, server, ...resolved, hostBuilds: gate };+ }++ /**+ * macOS / Windows: a project folder with this computer's builds (node_modules,+ * a venv, Mach-O / PE programs; host-builds.ts). Only the server's default+ * putting it in the box: its chats stay here (`native`); the user's own+ * choice (the project's switch, OMNIRUSH_BOX=1): in the box, with a warning.+ * Null on Linux, with the box off, or when the folder has none.+ * OMNIRUSH_BOX_KEEP_NATIVE=off or OMNIRUSH_BOX_HOST_BUILDS=off skips it.+ */+ private hostGate(root: string, mode: { on: boolean; source: string }): { native: boolean; things: string; notice: string } | null {+ if (!mode.on || !hostRules(this.platform)) return null;+ if (String(this.env.OMNIRUSH_BOX_KEEP_NATIVE ?? "").trim().toLowerCase() === "off") return null;+ let found;+ try {+ found = hostBuilds(root, { platform: this.platform, stateDir: this.options.stateDir, env: this.env });+ } catch (error) {+ this.log("warn", "host builds check failed", { error: error instanceof Error ? error.message : String(error) });+ return null;+ }+ if (!found.found) return null;+ const native = mode.source === "server";+ return { native, things: hostBuildThings(found), notice: hostBuildsNotice(native ? "native" : "explicit", { platform: this.platform, result: found }) };}/**@@ -260,10 +302,11 @@ export class BoxService {this.projects.set(key, project);if (project.planning) return project.planning;project.planning = (async () => {- const { on } = await this.mode(workspace);+ const { on, hostBuilds: gate } = await this.mode(workspace);if (!on) {+ if (gate?.native && project.notice !== gate.notice) this.log("info", "box: the server's default not applied, the folder has this computer's builds", { key, things: gate.things });project.run = null;- project.notice = null;+ project.notice = gate?.native ? gate.notice : null;await this.writeProjects();return null;}@@ -354,16 +397,16 @@ export class BoxService {}async status(workspace: BoxWorkspace, { fresh = false }: { fresh?: boolean } = {}): Promise<BoxStatus> {- const { settings, server, on, source, offer } = await this.mode(workspace);+ const { settings, server, on, source, offer, hostBuilds: gate } = await this.mode(workspace);// The server's "offer": shown once per folder (CLI: the tip, once per folder).if (offer && workspace.workspaceType === "local") await this.options.writeSettings(workspace.id, { offered: true }).catch(() => undefined);const root = boxRoot(workspace);const key = boxKey(root);const project = this.projects.get(key);- const base = { mode: settings.mode, serverDefault: server, on, source, offer, error: null };+ const base = { mode: settings.mode, serverDefault: server, on, source, offer, error: null, hostBuilds: gate, boxNotice: null };const backendSetting = { ...askedBackend({ env: this.env, stateDir: this.options.stateDir }), choices: backendChoices() };const setting = { value: backendSetting.backend, source: backendSetting.source, choices: backendSetting.choices };- if (workspace.workspaceType !== "local") return { ...base, on: false, offer: false, state: "off", runtime: null, backend: null, backendSetting: setting, image: null, progress: null, container: null, platform: process.platform, notice: "The sandbox is for folders on this computer." };+ if (workspace.workspaceType !== "local") return { ...base, on: false, offer: false, state: "off", runtime: null, backend: null, backendSetting: setting, image: null, progress: null, container: null, platform: this.platform, notice: "The sandbox is for folders on this computer." };// The full check (every backend) on a fresh look or once a minute; the cached choice otherwise.const { asked, allow } = this.detectOptions();const altKey = JSON.stringify([asked, allow]);@@ -423,9 +466,10 @@ export class BoxService {image: { ref: image.pull, stack: image.stack, present, downloading },progress,container,- platform: process.platform,- notice: on ? project?.notice ?? (runtime.ok ? null : `Sandbox off for now: ${runtime.reason}.`) : null,+ platform: this.platform,+ notice: on ? project?.notice ?? (runtime.ok ? null : `Sandbox off for now: ${runtime.reason}.`) : gate?.native ? gate.notice : null,error: run?.box?.error ?? (record?.state === "off" || record?.state === "failed" ? record.error || null : null),+ boxNotice: on && hostRules(this.platform) ? hostBuildsNotice("box", { platform: this.platform }) : null,};}