Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: keep native chats native when the sandbox default turns on

ogsamrat494a6e23d97f
diff --git a/apps/server/src/box/backends/container.ts b/apps/server/src/box/backends/container.ts
index 9576a94e..78b9f5d3 100644
--- a/apps/server/src/box/backends/container.ts
+++ b/apps/server/src/box/backends/container.ts
@@ -162,6 +162,8 @@ export function createArgs({ name, key, root, croot, image, runtime, run: runFol
"-w", croot,
...resourceArgs({ runtime, env }),
...(runtime.name === "podman" ? ["--security-opt", "label=disable"] : []),
+ // Docker on Linux has no host.docker.internal by itself (Docker Desktop and Podman do): services on this machine.
+ ...(runtime.name === "docker" && platform === "linux" && runtime.flavor !== "desktop" ? ["--add-host", "host.docker.internal:host-gateway"] : []),
...(user.uid === 0 ? ["--security-opt", "no-new-privileges"] : []),
"--entrypoint", "/opt/omnirush/bin/boxd",
image,
diff --git a/apps/server/src/box/box.test.ts b/apps/server/src/box/box.test.ts
index 8f9e598d..039a39ee 100644
--- a/apps/server/src/box/box.test.ts
+++ b/apps/server/src/box/box.test.ts
@@ -1,9 +1,9 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { boxKey, containerName, containerRoot, createArgs, credentialPath, filterChanges, helperPath, installShell, parseDiff, parseSize, rt, setToolsRoot, singleFileTar, wslPath } from "./box.js";
+import { Box, boxKey, containerName, containerRoot, createArgs, credentialPath, filterChanges, helperPath, installShell, parseDiff, parseSize, rt, setToolsRoot, singleFileTar, wslPath } from "./box.js";
import { readBoxSettings } from "./desktop.js";
import { detectStack, imageFor } from "./images.js";
import { engineConfig, gcInBackground, mapToBox, rememberServerDefault, resolveMode, serverDefault, type BoxRun } from "./launch.js";
@@ -106,6 +106,23 @@ describe("box core", () => {
expect(args).toContain("127.0.0.1::7777");
expect(args.join(" ")).not.toContain("docker.sock");
expect(args.filter((arg) => arg.startsWith("type=bind")).length).toBe(2);
+ // Docker on Linux: this machine's services as host.docker.internal (Podman and Docker Desktop have it already).
+ const base = { name: "n", key: "k", root: "/p", croot: "/p", image: "img", run: "/h/projects/k", shims: null, token: "t", user: { uid: 1000, gid: 1000 }, env: {} };
+ expect(createArgs({ ...base, runtime: { name: "docker", bin: "docker", vm: false }, platform: "linux" }).join(" ")).toContain("--add-host host.docker.internal:host-gateway");
+ expect(createArgs({ ...base, runtime: { name: "podman", bin: "podman", vm: false }, platform: "linux" })).not.toContain("--add-host");
+ expect(createArgs({ ...base, runtime: { name: "docker", bin: "docker", vm: true, flavor: "desktop" }, platform: "linux" })).not.toContain("--add-host");
+ expect(createArgs({ ...base, runtime: { name: "docker", bin: "docker", vm: true }, platform: "darwin" })).not.toContain("--add-host");
+ });
+
+ test("this machine's git identity is the box's system git config (lowest priority), kept with the env file", async () => {
+ const runFolder = await temp("run");
+ await writeFile(join(runFolder, "env"), "BOXD_PATH_PREFIX=/opt/w\n");
+ const box = new Box({ key: "k", name: "n", root: "/p", croot: "/p", runtime: { name: "docker", bin: "docker" }, home: await temp("home"), runFolder, run: async () => ({ code: 0, stdout: "", stderr: "" }), log: () => {}, platform: "linux", env: {} });
+ box.useGitIdentity(() => ({ name: 'Sam "S" \\ R', email: "[email protected]" }));
+ expect(await readFile(join(runFolder, "env"), "utf8")).toBe("BOXD_PATH_PREFIX=/opt/w\nGIT_CONFIG_SYSTEM=/run/omnirush/gitconfig\n");
+ expect(await readFile(join(runFolder, "gitconfig"), "utf8")).toBe('[user]\n\tname = "Sam \\"S\\" \\\\ R"\n\temail = "[email protected]"\n');
+ box.useGitIdentity(() => ({ name: "", email: "" }));
+ expect(await readFile(join(runFolder, "env"), "utf8")).toBe("BOXD_PATH_PREFIX=/opt/w\n");
});
test("snapshot filter: noise, mounts and credentials out; a folder changed only by them goes too", () => {
@@ -213,6 +230,35 @@ describe("box plugin", () => {
await hooks["shell.env"]({ callID: "c2" }, { env: off });
expect(off).toEqual({});
});
+
+ test("a chat listed as native (and its sub-agents) stays on this machine; other chats of the project use the box", async () => {
+ const home = await temp("boxhome");
+ const root = await temp("project");
+ process.env.OMNIRUSH_BOX_HOME = home;
+ const key = boxKey(root);
+ await mkdir(join(home, "boxes"), { recursive: true });
+ await writeFile(join(home, "boxes", `${key}.json`), JSON.stringify({ state: "ready", uid: 0 }));
+ await writeFile(join(home, DESKTOP_PROJECTS_FILE), JSON.stringify({ keys: [key], native_chats: ["ses_top"] }));
+ const parents: Record<string, string> = { ses_kid: "ses_top", ses_grandkid: "ses_kid" };
+ const asked: string[] = [];
+ const client = { session: { get: async ({ path: { id } }: { path: { id: string } }) => { asked.push(id); return { data: { parentID: parents[id] } }; } } };
+ const hooks = await OmniRushBox({ directory: root, client });
+ const envOf = async (sessionID: string) => {
+ const env: Record<string, string> = {};
+ await hooks["shell.env"]({ callID: "c", sessionID }, { env });
+ return env.OMNIRUSH_BOX_KEY ?? null;
+ };
+ expect(await envOf("ses_top")).toBeNull();
+ expect(await envOf("ses_grandkid")).toBeNull();
+ expect(await envOf("ses_grandkid")).toBeNull();
+ expect(await envOf("ses_new")).toBe(key);
+ // Each chat's parents are asked once.
+ expect(asked).toEqual(["ses_grandkid", "ses_kid", "ses_top", "ses_new"]);
+ await hooks["tool.execute.before"]({ tool: "read", sessionID: "ses_top" }, { args: { filePath: "/etc/hostname" } });
+ const system = ["Platform: darwin"];
+ await hooks["experimental.chat.system.transform"]({ sessionID: "ses_kid" }, { system });
+ expect(system).toEqual(["Platform: darwin"]);
+ });
});
describe("box service", () => {
@@ -305,6 +351,48 @@ describe("box service", () => {
expect(frozen.splice(0)).toEqual(["ses_turns_c1 turn-8 3"]);
});
+ test("a reopened chat that ran on this machine stays there when only the server's default turned the box on", async () => {
+ const stateDir = await temp("state");
+ const home = await temp("boxhome");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_n", path: root, workspaceType: "local" };
+ const settings: Settings = new Map();
+ const frozen: string[] = [];
+ const run: BoxRun = {
+ key: boxKey(root), container: "c", runtimeBin: "docker", runtimeArgs: [], backend: "docker", exec: null, root, native: false, box: null,
+ ready: async () => null,
+ label: () => null,
+ setTurn: () => {},
+ freeze: async (label, { sessionId, turn = null }) => {
+ frozen.push(`${sessionId} ${label}`);
+ return { label, turn, copied: 0, carried: 0, save: async () => ({ label, changed: 0, bytes: 0 }), discard: async () => null };
+ },
+ };
+ rememberServerDefault(stateDir, { local_box: { default: "on" } });
+ const boxes = service({ stateDir, workspaces: [workspace], settings, env: { OMNIRUSH_BOX_HOME: home } });
+ boxes.ensure = async () => run;
+ const listed = async () => JSON.parse(await readFile(join(home, DESKTOP_PROJECTS_FILE), "utf8")).native_chats ?? [];
+ // Reopened with 2 turns and no checkpoint: no checkpoint now either, and the plugin is told to leave it here.
+ expect(await boxes.beforePrompt("ses_native_r1", workspace, { turnsBefore: 2 })).toBeNull();
+ await boxes.beforePrompt("ses_native_r1", workspace);
+ // A new chat and a chat that already has checkpoints go in the box.
+ await boxes.beforePrompt("ses_native_n1", workspace);
+ await mkdir(join(boxes.snapshotsDir, "ses_native_b1"), { recursive: true });
+ await writeFile(join(boxes.snapshotsDir, "ses_native_b1", "turn-1.json"), "{}");
+ await boxes.beforePrompt("ses_native_b1", workspace, { turnsBefore: 3 });
+ expect(frozen.splice(0)).toEqual(["ses_native_n1 turn-1", "ses_native_b1 turn-2"]);
+ expect(await listed()).toEqual(["ses_native_r1"]);
+ // The user turns the project on: the chat moves to the box.
+ boxes.ensure = async () => run;
+ await boxes.setMode(workspace, "on");
+ expect(await listed()).toEqual([]);
+ await boxes.beforePrompt("ses_native_r1", workspace);
+ expect(frozen.splice(0)).toEqual(["ses_native_r1 turn-1"]);
+ // Turned on by the user before it was reopened: it moves at once.
+ await boxes.beforePrompt("ses_native_r2", workspace, { turnsBefore: 4 });
+ expect(frozen.splice(0)).toEqual(["ses_native_r2 turn-1"]);
+ });
+
test("a remote workspace never gets a box", async () => {
const stateDir = await temp("state");
const workspace: BoxWorkspace = { id: "ws_r", path: "/remote", workspaceType: "remote" };
diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.ts
index 96acdca0..77a52001 100644
--- a/apps/server/src/box/box.ts
+++ b/apps/server/src/box/box.ts
@@ -24,6 +24,7 @@
// up (<state>/sandbox/snapshots/<session>/turn-N.{json,tar}, the same
// transport the 2.2.3 sandbox used; record schema 2).
+import { execFileSync } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import os from "node:os";
@@ -232,6 +233,7 @@ export async function openBox({ root, runtime, env = process.env, platform = pro
if (opened.mounts.includes(containerRoot(pkglog.root, platform))) box.useInstallLog(pkglog);
else log("info", "box made before the install log: its wrappers are not in this box (Reset sandbox adds them)", { key });
}
+ try { box.useGitIdentity(); } catch (error) { log("warn", "box git identity not set", { error: error instanceof Error ? error.message : String(error) }); }
box.setState("ready", null, onState);
return box;
} catch (error) {
@@ -422,6 +424,25 @@ export class Box {
this.writeRecord();
}
+ /**
+ * This machine's git identity (`git config --global user.name/email`) as the box's
+ * system git config (<run>/gitconfig, GIT_CONFIG_SYSTEM in the env file): commits in
+ * the box carry the user's name, as on this machine. Lowest priority (the box's own
+ * global or repository config wins); never in a checkpoint. CLI: the same.
+ */
+ useGitIdentity(read: (env: Env) => { name: string; email: string } = hostGitIdentity): void {
+ const { name, email } = read(this.env);
+ const file = path.join(this.runFolder, "env");
+ let lines: string[] = [];
+ try { lines = readFileSync(file, "utf8").split("\n").filter((line) => line && !line.startsWith("GIT_CONFIG_SYSTEM=")); } catch { /* none yet */ }
+ if (name || email) {
+ const quote = (value: string) => `"${value.replace(/[\r\n]/g, " ").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
+ writeFileSync(path.join(this.runFolder, "gitconfig"), `[user]\n${name ? `\tname = ${quote(name)}\n` : ""}${email ? `\temail = ${quote(email)}\n` : ""}`, { mode: 0o644 });
+ lines.push(`GIT_CONFIG_SYSTEM=${RUN_DIR}/gitconfig`);
+ }
+ writeFileSync(file, `${lines.join("\n")}\n`, { mode: 0o644 });
+ }
+
/** The prompt number the package-manager wrappers write into their lines. */
setTurn(turn: number): void {
try { writeFileSync(path.join(this.runFolder, "state", "turn"), `${turn}\n`); } catch { /* best effort */ }
@@ -685,3 +706,15 @@ export function savedTurns(dir: string): number {
return 0;
}
}
+
+/** This machine's `git config --global user.name` and `user.email` (empty when unset or git is missing). */
+export function hostGitIdentity(env: Env = process.env): { name: string; email: string } {
+ const get = (field: string) => {
+ try {
+ return execFileSync("git", ["config", "--global", "--get", field], { encoding: "utf8", timeout: 3_000, env, stdio: ["ignore", "pipe", "ignore"] }).trim();
+ } catch {
+ return "";
+ }
+ };
+ return { name: get("user.name"), email: get("user.email") };
+}
diff --git a/apps/server/src/box/plugin-lib.ts b/apps/server/src/box/plugin-lib.ts
index 73a44586..dd062632 100644
--- a/apps/server/src/box/plugin-lib.ts
+++ b/apps/server/src/box/plugin-lib.ts
@@ -33,16 +33,19 @@ export function record(key: string): { state?: string; uid?: number; croot?: str
*/
export const DESKTOP_PROJECTS_FILE = "desktop-projects.json";
-export function desktopProjects(): { keys: Set<string>; pkglogDir: string | null } {
+export function desktopProjects(): { keys: Set<string>; pkglogDir: string | null; nativeChats: Set<string> } {
+ const strings = (list: unknown) => new Set(Array.isArray(list) ? list.filter((item: unknown): item is string => typeof item === "string") : []);
try {
const value = JSON.parse(readFileSync(path.join(boxHome(), DESKTOP_PROJECTS_FILE), "utf8"));
return {
- keys: new Set(Array.isArray(value?.keys) ? value.keys.filter((key: unknown): key is string => typeof key === "string") : []),
+ keys: strings(value?.keys),
// The install log's raw folder of box chats (box/install-log.ts): the wrappers in the box note calls there.
pkglogDir: typeof value?.pkglog_dir === "string" && value.pkglog_dir ? value.pkglog_dir : null,
+ // Chats that stay on this machine although their project's box is on (they ran here before the server turned it on).
+ nativeChats: strings(value?.native_chats),
};
} catch {
- return { keys: new Set(), pkglogDir: null };
+ return { keys: new Set(), pkglogDir: null, nativeChats: new Set() };
}
}
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index b4bdb1db..3f72786c 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -124,6 +124,8 @@ export class BoxService {
private readonly turns = new Map<string, number>();
/** Each chat's turn number as of its last prompt here (its turns before this run, then one per prompt). */
private readonly chatTurns = new Map<string, number>();
+ /** Chats (and their project's key) that ran on this machine before the server's default turned the box on: they stay here. */
+ private readonly nativeChats = new Map<string, string>();
private readonly home: string;
private readonly env: NodeJS.ProcessEnv;
private log: BoxLog;
@@ -274,7 +276,7 @@ export class BoxService {
const keys = [...this.projects.entries()].filter(([, project]) => project.run && !project.run.native).map(([key]) => key).sort();
const file = join(this.home, DESKTOP_PROJECTS_FILE);
const write = async () => {
- const content = `${JSON.stringify({ keys, ...(this.installLog ? { pkglog_dir: this.installLog.raw } : {}), updated: Date.now() })}\n`;
+ const content = `${JSON.stringify({ keys, ...(this.installLog ? { pkglog_dir: this.installLog.raw } : {}), ...(this.nativeChats.size ? { native_chats: [...this.nativeChats.keys()].sort() } : {}), updated: Date.now() })}\n`;
await mkdir(this.home, { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
await writeFile(tmp, content, { mode: 0o600 });
@@ -299,7 +301,13 @@ export class BoxService {
async setMode(workspace: BoxWorkspace, mode: ProjectBoxMode): Promise<BoxStatus> {
await this.options.writeSettings(workspace.id, { mode, offered: true });
- const project = this.projects.get(boxKey(boxRoot(workspace)));
+ const key = boxKey(boxRoot(workspace));
+ // Turned on by the user: the project's chats that stayed on this machine move to the box too.
+ if (mode === "on" && [...this.nativeChats.values()].includes(key)) {
+ for (const [sessionId, chatKey] of this.nativeChats) if (chatKey === key) this.nativeChats.delete(sessionId);
+ await this.writeProjects();
+ }
+ const project = this.projects.get(key);
if (project) project.nextPlanAt = 0;
// Planned in the background: a missing image starts downloading now.
void this.ensure(workspace).catch(() => null);
@@ -414,11 +422,19 @@ export class BoxService {
// The chat's own turn number, counted with the box on or off: a chat that ran natively
// (reopened, or its box turned on mid-chat) has its first checkpoint (turn-1) before a later
// turn; the checkpoint names it as session_turn (CLI: the same).
+ const reopened = capture && !this.chatTurns.has(sessionId) && turnsBefore > 0;
const chatTurn = capture ? (this.chatTurns.get(sessionId) ?? turnsBefore) + 1 : 0;
if (capture) this.chatTurns.set(sessionId, chatTurn);
const run = await this.ensure(workspace).catch(() => null);
if (!run || run.native) return null;
- if (!capture) return null;
+ // A reopened chat with turns but no checkpoint ran on this machine: when only the server's default
+ // turned the box on, it goes on here (new chats get the box); a project turned on by its user moves it.
+ if (reopened && !this.turns.has(sessionId) && savedTurns(this.snapshotDir(sessionId)) === 0 && (await this.mode(workspace)).source === "server") {
+ this.nativeChats.set(sessionId, run.key);
+ await this.writeProjects();
+ this.log("info", "box: a chat that ran on this machine stays there", { sessionId, turnsBefore });
+ }
+ if (this.nativeChats.has(sessionId) || !capture) return null;
const turn = (this.turns.get(sessionId) ?? savedTurns(this.snapshotDir(sessionId))) + 1;
const started = Date.now();
try {
diff --git a/apps/server/src/opencode-plugins/omnirush-box.ts b/apps/server/src/opencode-plugins/omnirush-box.ts
index f8244f53..0e94084b 100644
--- a/apps/server/src/opencode-plugins/omnirush-box.ts
+++ b/apps/server/src/opencode-plugins/omnirush-box.ts
@@ -25,20 +25,42 @@ import path from "node:path";
import { BOX_NOTE, desktopProjects, engineDirs, FILE_TOOLS, keyOf, record, toolPaths, within } from "../box/plugin-lib.js";
-export const OmniRushBox = async ({ directory }: { directory?: string }) => {
+/** The engine client's one call used here: a chat's parent (a sub-agent's chat has one). */
+type SessionReader = { session: { get: (options: { path: { id: string } }) => Promise<{ data?: { parentID?: string } | null } | undefined> } };
+
+export const OmniRushBox = async ({ directory, client }: { directory?: string; client?: SessionReader }) => {
const root = path.resolve(directory || process.cwd());
const key = keyOf(root);
- const current = () => {
+ // A chat's top chat (sub-agents run in child chats): asked once per chat, at most 8 levels up.
+ const tops = new Map<string, Promise<string>>();
+ const topOf = (id: string): Promise<string> => {
+ const known = tops.get(id);
+ if (known) return known;
+ const found = (async () => {
+ let current = id;
+ for (let level = 0; level < 8 && client; level += 1) {
+ const parent = (await client.session.get({ path: { id: current } }).catch(() => undefined))?.data?.parentID;
+ if (!parent) break;
+ current = parent;
+ }
+ return current;
+ })();
+ tops.set(id, found);
+ return found;
+ };
+ const current = async (sessionID?: string) => {
const listed = desktopProjects();
if (!listed.keys.has(key)) return null;
+ // A chat that ran on this machine before the box was on stays there (with its sub-agents).
+ if (sessionID && listed.nativeChats.size && (listed.nativeChats.has(sessionID) || listed.nativeChats.has(await topOf(sessionID)))) return null;
const rec = record(key);
return rec && rec.state !== "off" ? { ...rec, pkglogDir: listed.pkglogDir } : null;
};
- const active = () => Boolean(current());
+ const active = async (sessionID?: string) => Boolean(await current(sessionID));
const allowed = [root, ...engineDirs()];
return {
"shell.env": async (input: { callID?: string; sessionID?: string }, output: { env: Record<string, string> }) => {
- const rec = current();
+ const rec = await current(input.sessionID);
if (!rec) return;
output.env.OMNIRUSH_BOX_KEY = key;
// Desktop: box chats note installs in their own raw folder (boxsh forwards it into the box).
@@ -46,16 +68,16 @@ export const OmniRushBox = async ({ directory }: { directory?: string }) => {
if (input.callID) output.env.OMNIRUSH_CALL = String(input.callID);
if (input.sessionID) output.env.OMNIRUSH_SESSION = String(input.sessionID);
},
- "tool.execute.before": async (input: { tool: string }, output: { args?: Record<string, unknown> }) => {
- if (!FILE_TOOLS.has(input.tool) || !active()) return;
+ "tool.execute.before": async (input: { tool: string; sessionID?: string }, output: { args?: Record<string, unknown> }) => {
+ if (!FILE_TOOLS.has(input.tool) || !(await active(input.sessionID))) return;
for (const raw of toolPaths(input.tool, output.args ?? {})) {
const full = path.resolve(root, raw);
if (allowed.some((dir) => within(full, dir))) continue;
throw new Error(`${raw} is outside the project folder. This session runs in a sandbox: files outside ${root} live inside the Linux container, not where this tool can see them. Use the shell tool (cat, ls, sed, tee, ...) to read or change them.`);
}
},
- "experimental.chat.system.transform": async (_input: unknown, output: { system?: unknown }) => {
- const rec = current();
+ "experimental.chat.system.transform": async (input: { sessionID?: string }, output: { system?: unknown }) => {
+ const rec = await current(input.sessionID);
if (!rec || !Array.isArray(output.system)) return;
// In place: the engine keeps its own reference to this array.
for (let i = 0; i < output.system.length; i += 1) {
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index c58296c4..f07e2c0d 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1150,14 +1150,20 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// The Linux sandbox (box/): every workspace whose box is on is planned in the background (a missing
// image starts downloading), and the server's default (local_box) is read for the engine config.
const boxes = boxServiceFor(config, (level, message, attributes) => logger.log(level, message, attributes));
- void boxes.ensureAll();
if (gatewayBroker.enabled) {
- void gatewayBroker.sessionUploadCapabilities().then(async (capabilities) => {
- if (!rememberServerDefault(runtimeStorageDir(config), capabilities)) return;
- await applyBoxEngineConfig(config, "local_box_default");
- await boxes.ensureAll();
- }).catch(() => undefined);
+ // Read before the first plan and the engine's first config (at most 1.5 s, else the last answer is
+ // used until it comes): a switch flipped or rolled back on the server applies at this start.
+ const read = gatewayBroker.sessionUploadCapabilities().then((capabilities) => rememberServerDefault(runtimeStorageDir(config), capabilities)).catch(() => false);
+ const inTime = await Promise.race([read.then(() => true), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_500).unref?.())]);
+ if (!inTime) {
+ void read.then(async (changed) => {
+ if (!changed) return;
+ await applyBoxEngineConfig(config, "local_box_default");
+ await boxes.ensureAll();
+ }).catch(() => undefined);
+ }
}
+ void boxes.ensureAll();
if (config.clearUploadQueue) {
// The user signed out: what the last account queued is deleted before anything else runs.
await Promise.race([capture.signOut(), new Promise((resolvePromise) => setTimeout(resolvePromise, 10_000).unref?.())]);