Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: follow the server sandbox default while the app runs

ogsamratf75d6efa401a
diff --git a/apps/server/src/box/box.test.ts b/apps/server/src/box/box.test.ts
index fdc341d0..d4023fe8 100644
--- a/apps/server/src/box/box.test.ts
+++ b/apps/server/src/box/box.test.ts
@@ -7,7 +7,7 @@ import { join } from "node:path";
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 { boxRun, engineConfig, gcInBackground, mapToBox, pullInBackground, pullLog, pullMarker, rememberServerDefault, resolveMode, serverDefault, type BoxRun } from "./launch.js";
+import { boxRun, engineConfig, gcInBackground, mapToBox, pullInBackground, pullLog, pullMarker, rememberServerDefault, resolveMode, serverDefault, watchServerDefault, type BoxRun } from "./launch.js";
import { clearLayerSizes, layerSizes, parseManifestSizes, parsePullLog, pullProgress } from "./pull-progress.js";
import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";
import { candidates, detectRuntime, explainFailure, probe, probeWsl, wslLauncher, type RunCommand } from "./runtime.js";
@@ -409,6 +409,63 @@ describe("box service", () => {
expect(frozen.splice(0)).toEqual(["ses_native_r2 turn-1"]);
});
+ test("the server's default turned on while the app runs: chats that ran on this machine stay there, new ones go in the box", async () => {
+ const stateDir = await temp("state");
+ const home = await temp("boxhome");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_l", path: root, workspaceType: "local" };
+ const frozen: string[] = [];
+ let failNext = false;
+ 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}`);
+ if (failNext) { failNext = false; throw new Error("checkpoint failed"); }
+ return { label, turn, copied: 0, carried: 0, save: async () => ({ label, changed: 0, bytes: 0 }), discard: async () => null };
+ },
+ };
+ rememberServerDefault(stateDir, { local_box: { default: "off" } });
+ const boxes = service({ stateDir, workspaces: [workspace], settings: new Map(), env: { OMNIRUSH_BOX_HOME: home } });
+ let on = false;
+ boxes.ensure = async () => (on ? run : null);
+ const listed = async () => JSON.parse(await readFile(join(home, DESKTOP_PROJECTS_FILE), "utf8")).native_chats ?? [];
+ // Before the switch: two turns on this machine (the first chat after it, too, while its image downloads).
+ expect(await boxes.beforePrompt("ses_live_old1", workspace)).toBeNull();
+ expect(await boxes.beforePrompt("ses_live_old1", workspace)).toBeNull();
+ // The app reads the switch (watchServerDefault) and the project's box is ready.
+ rememberServerDefault(stateDir, { local_box: { default: "on" } });
+ on = true;
+ expect(await boxes.beforePrompt("ses_live_old1", workspace)).toBeNull();
+ expect(await listed()).toEqual(["ses_live_old1"]);
+ // A new chat goes in; one whose first checkpoint failed stays in (its commands already ran there).
+ await boxes.beforePrompt("ses_live_new1", workspace);
+ failNext = true;
+ await boxes.beforePrompt("ses_live_new2", workspace);
+ await boxes.beforePrompt("ses_live_new2", workspace);
+ expect(frozen.splice(0)).toEqual(["ses_live_new1 turn-1", "ses_live_new2 turn-1", "ses_live_new2 turn-1"]);
+ expect(await listed()).toEqual(["ses_live_old1"]);
+ });
+
+ test("watchServerDefault reads the server's default again and applies only a change", async () => {
+ const stateDir = await temp("state");
+ rememberServerDefault(stateDir, { local_box: { default: "off" } });
+ const answers: Array<{ local_box?: unknown } | null> = [{ local_box: { default: "off" } }, null, { local_box: { default: "on" } }, { local_box: { default: "on" } }];
+ let applied = 0;
+ const stop = watchServerDefault({ stateDir, read: async () => answers.shift() ?? null, apply: async () => { applied += 1; }, everyMs: 5 });
+ try {
+ for (let i = 0; i < 100 && answers.length > 0; i += 1) await new Promise((resolve) => setTimeout(resolve, 5));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ } finally {
+ stop();
+ }
+ // Unchanged, no answer (the last one stays), then on once.
+ expect(serverDefault(stateDir)).toBe("on");
+ expect(applied).toBe(1);
+ });
+
test("a box on a backend the server no longer allows is planned again", async () => {
const stateDir = await temp("state");
const root = await temp("project");
diff --git a/apps/server/src/box/launch.ts b/apps/server/src/box/launch.ts
index 6f7860c3..e8a4d511 100644
--- a/apps/server/src/box/launch.ts
+++ b/apps/server/src/box/launch.ts
@@ -73,6 +73,27 @@ export function rememberServerDefault(stateDir: string, capabilities: { local_bo
return before !== JSON.stringify([value, backends]);
}
+/**
+ * Reads the server's default again every `everyMs` while the app runs (an app
+ * started before a switch was flipped, or kept open for days, follows it
+ * without a restart) and calls `apply` when it (or its backends allowlist)
+ * changed. One read at a time; a failed one leaves the last answer. Returns
+ * the stop.
+ */
+export function watchServerDefault({ stateDir, read, apply, everyMs }: { stateDir: string; read: () => Promise<{ local_box?: unknown } | null | undefined>; apply: () => Promise<unknown>; everyMs: number }): () => void {
+ let busy = false;
+ const timer = setInterval(() => {
+ if (busy) return;
+ busy = true;
+ void read()
+ .then((capabilities) => (rememberServerDefault(stateDir, capabilities) ? apply() : undefined))
+ .catch(() => undefined)
+ .finally(() => { busy = false; });
+ }, everyMs);
+ timer.unref?.();
+ return () => clearInterval(timer);
+}
+
// --- the backend --------------------------------------------------------------------
/** What the backend setting holds: "auto" (the ranked order), one backend id, or "native" (no box). */
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index 65212dc3..75f94c7c 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -147,6 +147,8 @@ export class BoxService {
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>();
+ /** Chats sent to their project's box in this run (a failed checkpoint included). */
+ private readonly boxedChats = new Set<string>();
private readonly home: string;
private readonly env: NodeJS.ProcessEnv;
private readonly platform: NodeJS.Platform;
@@ -536,19 +538,21 @@ 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;
+ const turnsSoFar = this.chatTurns.get(sessionId) ?? turnsBefore;
+ const chatTurn = capture ? turnsSoFar + 1 : 0;
if (capture) this.chatTurns.set(sessionId, chatTurn);
const run = await this.ensure(workspace).catch(() => null);
if (!run || run.native) return null;
- // A reopened chat with turns but no checkpoint ran on this machine: when only the server's default
+ // A chat with turns but no checkpoint ran on this machine (reopened, or started in this run before the
+ // server's default reached the app, or while the image downloaded): when only the server's default
// turned the box on, it goes on here (new chats get the box); a project turned on by its user moves it.
- if (reopened && !this.turns.has(sessionId) && savedTurns(this.snapshotDir(sessionId)) === 0 && (await this.mode(workspace)).source === "server") {
+ if (capture && turnsSoFar > 0 && !this.nativeChats.has(sessionId) && !this.boxedChats.has(sessionId) && !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;
+ this.boxedChats.add(sessionId);
const turn = (this.turns.get(sessionId) ?? savedTurns(this.snapshotDir(sessionId))) + 1;
const started = Date.now();
try {
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 210ab88a..1eb65a53 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -177,7 +177,7 @@ import {
} from "./omnirush-workspace-config-store.js";
import { boxServiceFor } from "./box/desktop.js";
import { prepareBoxInstallLog } from "./box/install-log.js";
-import { rememberServerDefault } from "./box/launch.js";
+import { rememberServerDefault, watchServerDefault } from "./box/launch.js";
import { normalizeBackend } from "./box/backends/index.js";
import { buildOmniRushRuntimeConfigObject, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";
import { assertMcpAllowed, mcpAllowed, mcpPolicyForConfig, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";
@@ -1150,19 +1150,21 @@ 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));
+ let stopBoxDefaultWatch: () => void = () => {};
if (gatewayBroker.enabled) {
// 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 boxes.serverBackendsChanged();
- await applyBoxEngineConfig(config, "local_box_default");
- await boxes.ensureAll();
- }).catch(() => undefined);
- }
+ if (!inTime) void read.then((changed) => (changed ? applyServerBoxDefault(config, boxes) : undefined)).catch(() => undefined);
+ // Read again while the app stays open (from the capabilities cache: at most one request per its
+ // TTL), so a switch flipped on the server reaches an app started before it without a restart.
+ stopBoxDefaultWatch = watchServerDefault({
+ stateDir: runtimeStorageDir(config),
+ read: () => gatewayBroker.sessionUploadCapabilities(),
+ apply: () => applyServerBoxDefault(config, boxes),
+ everyMs: BOX_DEFAULT_REFRESH_MS,
+ });
}
void boxes.ensureAll();
if (config.clearUploadQueue) {
@@ -1525,6 +1527,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
idleTimeout: 120,
});
} catch (error) {
+ stopBoxDefaultWatch();
bestPracticesReloads.stop();
// First, and synchronously: archive part uploads in flight are aborted now, not after the other shutdown steps.
const captureStopped = capture.stop();
@@ -1614,6 +1617,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// is still stored (an app quit, a restart), never after a sign-out.
// Before them, each chat in a box gets its last checkpoint (bounded; only when chats ran in a
// box this run, and the account answers it is still stored within a second).
+ stopBoxDefaultWatch();
const archiveFinals = accountStillStored();
if (boxes.hasChats() && await Promise.race([archiveFinals.catch(() => false), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_000).unref?.())])) {
await boxes.finals({ budgetMs: 10_000 }).catch(() => []);
@@ -2791,6 +2795,21 @@ function sanitizeProxyResponse(response: Response): Response {
});
}
+/** How often a running app reads the server's sandbox default again. */
+const BOX_DEFAULT_REFRESH_MS = 10 * 60_000;
+
+/**
+ * The server's sandbox default (or its backends allowlist) changed: boxes on a
+ * backend no longer allowed are planned again, the engine gets (or loses) the
+ * box shell and plugin, and every workspace is planned. Chats that already ran
+ * on this machine stay there (box/service.ts beforePrompt); new ones follow it.
+ */
+async function applyServerBoxDefault(config: ServerConfig, boxes: ReturnType<typeof boxServiceFor>): Promise<void> {
+ await boxes.serverBackendsChanged();
+ await applyBoxEngineConfig(config, "local_box_default");
+ await boxes.ensureAll();
+}
+
/**
* The Linux sandbox's engine bits (box/service.ts engineBits) may have
* changed: the engine config file is written again and, when it changed,