Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: format arguments, subfolder config and sandbox switch

ogsamrateca4946f1a98
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index 09100c7f..a82fbb5d 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -446,6 +446,12 @@ export class BoxService {
return this.status(workspace);
}
+ /** Whether the project's work runs in its box (the same decision as status().on, without probing the runtime). */
+ async sandboxOn(workspace: BoxWorkspace): Promise<boolean> {
+ if (workspace.workspaceType !== "local") return false;
+ return (await this.mode(workspace)).on;
+ }
+
async status(workspace: BoxWorkspace, { fresh = false }: { fresh?: boolean } = {}): Promise<BoxStatus> {
const { settings, server, on, source, offer, hostBuilds: gate, lessRepro } = await this.mode(workspace);
// The server's "offer": shown once per folder (CLI: the tip, once per folder).
diff --git a/apps/server/src/editor-format.e2e.test.ts b/apps/server/src/editor-format.e2e.test.ts
index 2cdab5ac..fc948dc8 100644
--- a/apps/server/src/editor-format.e2e.test.ts
+++ b/apps/server/src/editor-format.e2e.test.ts
@@ -82,28 +82,28 @@ describe("format on save asks before running project code", () => {
const store = new FormatTrustStore(join(root, "..", `trust-${Date.now()}.json`));
roots.push(join(root, "..", "trust-placeholder"));
const text = "export const messy={a:1}\n";
- const ask = await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store });
+ const ask = await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false });
expect(ask).toMatchObject({ formatter: "Prettier", trust: "ask" });
if (!("trust" in ask) || ask.trust !== "ask") throw new Error("expected a prompt");
- expect(ask.command).toBe("node node_modules/prettier/bin/prettier.cjs --stdin-filepath <file>");
+ expect(ask.command).toBe("node node_modules/prettier/bin/prettier.cjs --stdin-filepath=<file>");
// Once: runs, remembers nothing.
- expect(await formatRequest({ root, path: "src/a.ts", text, trust: "once", hash: ask.hash, store })).toMatchObject({ text: "export const messy = { a: 1 };\n" });
- expect((await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store })).formatter).toBe("Prettier");
- expect(await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store })).toMatchObject({ trust: "ask" });
+ expect(await formatRequest({ root, path: "src/a.ts", text, trust: "once", hash: ask.hash, store, sandboxOn: false })).toMatchObject({ text: "export const messy = { a: 1 };\n" });
+ expect((await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false })).formatter).toBe("Prettier");
+ expect(await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false })).toMatchObject({ trust: "ask" });
// Always: remembered for this project and configuration.
- await formatRequest({ root, path: "src/a.ts", text, trust: "always", hash: ask.hash, store });
- expect(await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store })).toMatchObject({ text: "export const messy = { a: 1 };\n" });
+ await formatRequest({ root, path: "src/a.ts", text, trust: "always", hash: ask.hash, store, sandboxOn: false });
+ expect(await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false })).toMatchObject({ text: "export const messy = { a: 1 };\n" });
// A changed configuration asks again.
await writeFile(join(root, ".prettierrc"), JSON.stringify({ semi: false }));
- const again = await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store });
+ const again = await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false });
expect(again).toMatchObject({ trust: "ask" });
if (!("trust" in again) || again.trust !== "ask") throw new Error("expected a prompt");
expect(again.hash).not.toBe(ask.hash);
// An answer for an older configuration does not run.
- expect(await formatRequest({ root, path: "src/a.ts", text, trust: "once", hash: ask.hash, store })).toMatchObject({ trust: "ask" });
+ expect(await formatRequest({ root, path: "src/a.ts", text, trust: "once", hash: ask.hash, store, sandboxOn: false })).toMatchObject({ trust: "ask" });
// Never: remembered, nothing runs.
- expect(await formatRequest({ root, path: "src/a.ts", text, trust: "never", hash: again.hash, store })).toMatchObject({ trust: "denied" });
- expect(await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store })).toMatchObject({ trust: "denied" });
+ expect(await formatRequest({ root, path: "src/a.ts", text, trust: "never", hash: again.hash, store, sandboxOn: false })).toMatchObject({ trust: "denied" });
+ expect(await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false })).toMatchObject({ trust: "denied" });
});
test("the formatter's environment has no app tokens, engine password or other keys", () => {
@@ -122,9 +122,64 @@ describe("format on save asks before running project code", () => {
await writeFile(recordFile(home, key), JSON.stringify(record));
const store = new FormatTrustStore(join(home, "trust.json"));
const env = { ...process.env, OMNIRUSH_BOX_HOME: home };
- const ask = await formatRequest({ root, path: "src/a.ts", text: "const a=1\n", trust: null, hash: null, store, env });
+ const ask = await formatRequest({ root, path: "src/a.ts", text: "const a=1\n", trust: null, hash: null, store, env, sandboxOn: true });
expect(ask).toMatchObject({ trust: "ask", sandbox: true });
if (!("trust" in ask) || ask.trust !== "ask") throw new Error("expected a prompt");
- await expect(formatRequest({ root, path: "src/a.ts", text: "const a=1\n", trust: "once", hash: ask.hash, store, env })).rejects.toThrow(/sandbox is not running/);
+ await expect(formatRequest({ root, path: "src/a.ts", text: "const a=1\n", trust: "once", hash: ask.hash, store, env, sandboxOn: true })).rejects.toThrow(/sandbox is not running/);
+ });
+});
+
+describe("format on save: arguments, configuration and the sandbox switch", () => {
+ async function trustedPrettier() {
+ const prettier = repoPrettier();
+ if (!prettier) return null;
+ const root = await project(true);
+ await mkdir(join(root, "node_modules"), { recursive: true });
+ await symlink(prettier, join(root, "node_modules", "prettier"), "dir");
+ if (!formatterFor(root, join(root, "src/a.ts"))) return null;
+ const store = new FormatTrustStore(join(root, "..", `trust-${Math.random().toString(36).slice(2)}.json`));
+ return { root, store };
+ }
+
+ test("a file named like a flag stays a file name (no plugin is loaded)", async () => {
+ const setup = await trustedPrettier();
+ if (!setup) return;
+ const { root, store } = setup;
+ await writeFile(join(root, "..cjs"), "require('fs').writeFileSync(__dirname + '/PWNED', 'x'); module.exports = {};\n");
+ await writeFile(join(root, "--plugin=..cjs"), "const a=1\n");
+ const ask = await formatRequest({ root, path: "--plugin=..cjs", text: "const a=1\n", trust: null, hash: null, store, sandboxOn: false });
+ if (!("trust" in ask) || ask.trust !== "ask") return; // not a Prettier file type here
+ await formatRequest({ root, path: "--plugin=..cjs", text: "const a=1\n", trust: "once", hash: ask.hash, store, sandboxOn: false }).catch(() => null);
+ expect(existsSync(join(root, "PWNED"))).toBe(false);
+ });
+
+ test("a Prettier config added in a subfolder asks again", async () => {
+ const setup = await trustedPrettier();
+ if (!setup) return;
+ const { root, store } = setup;
+ const text = "const a=1\n";
+ const ask = await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false });
+ if (!("trust" in ask) || ask.trust !== "ask") throw new Error("expected a prompt");
+ await formatRequest({ root, path: "src/a.ts", text, trust: "always", hash: ask.hash, store, sandboxOn: false });
+ await writeFile(join(root, "src", ".prettierrc"), JSON.stringify({ plugins: ["./x.cjs"] }));
+ expect(await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false })).toMatchObject({ trust: "ask" });
+ });
+
+ test("with the sandbox on and no box at all, nothing runs; switching the sandbox asks again", async () => {
+ const setup = await trustedPrettier();
+ if (!setup) return;
+ const { root, store } = setup;
+ const home = await mkdtemp(join(tmpdir(), "omnirush-nobox-"));
+ roots.push(home);
+ const env = { ...process.env, OMNIRUSH_BOX_HOME: home };
+ const text = "const a=1\n";
+ const host = await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: false, env });
+ if (!("trust" in host) || host.trust !== "ask") throw new Error("expected a prompt");
+ await formatRequest({ root, path: "src/a.ts", text, trust: "always", hash: host.hash, store, sandboxOn: false, env });
+ // Trusted to run here; with the sandbox switched on it is asked again, and without a box it never runs here.
+ const boxed = await formatRequest({ root, path: "src/a.ts", text, trust: null, hash: null, store, sandboxOn: true, env });
+ expect(boxed).toMatchObject({ trust: "ask", sandbox: true });
+ if (!("trust" in boxed) || boxed.trust !== "ask") throw new Error("expected a prompt");
+ await expect(formatRequest({ root, path: "src/a.ts", text, trust: "once", hash: boxed.hash, store, sandboxOn: true, env })).rejects.toThrow(/sandbox is not running/);
});
});
diff --git a/apps/server/src/routes/editor-format.ts b/apps/server/src/routes/editor-format.ts
index cc2461cb..6f22d99a 100644
--- a/apps/server/src/routes/editor-format.ts
+++ b/apps/server/src/routes/editor-format.ts
@@ -58,6 +58,8 @@ type RegisterOptions = {
resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;
ensureWritable: (config: ServerConfig) => void;
requireClientScope: (ctx: RequestContext, required: TokenScope) => void;
+ /** The project's sandbox switch (the box service's decision). */
+ sandboxOn: (workspace: WorkspaceInfo) => Promise<boolean>;
};
function readText(path: string): string | null {
@@ -77,6 +79,16 @@ function configFilesIn(dir: string, pattern: RegExp): string[] {
}
}
+/** The folders from the file's own up to the project root. */
+function configFoldersUp(root: string, file: string): string[] {
+ const folders: string[] = [];
+ for (let dir = dirname(file); dir === root || dir.startsWith(root + sep); dir = dirname(dir)) {
+ folders.push(dir);
+ if (dir === root) break;
+ }
+ return folders;
+}
+
/** The nearest package.json from the file up to the project root that names Prettier, and its folder. */
function prettierRoot(root: string, file: string): string | null {
let dir = dirname(file);
@@ -117,14 +129,16 @@ export function formatterFor(root: string, file: string, env: NodeJS.ProcessEnv
const script = dir ? prettierScript(dir, root) : null;
const node = findOnPath("node", env);
if (!dir || !script || !node) return null;
- const pattern = /^(?:\.prettierrc(?:\..+)?|prettier\.config\..+|\.prettierignore|\.editorconfig|package\.json)$/;
+ const pattern = /^(?:\.prettierrc(?:\..+)?|prettier\.config\..+|\.prettierignore|\.editorconfig|package\.json|package\.ya?ml)$/;
return {
name: "Prettier",
command: node,
- args: [script, "--stdin-filepath", rel],
- boxArgv: ["node", script, "--stdin-filepath", rel],
- display: `node ${show(script)} --stdin-filepath <file>`,
- configFiles: [...new Set([...configFilesIn(dir, pattern), ...configFilesIn(root, pattern), join(dirname(dirname(script)), "package.json")])],
+ // One argument (`--stdin-filepath=…`): a file named like a flag (`--plugin=x.cjs`) stays a file name.
+ args: [script, `--stdin-filepath=${rel}`],
+ boxArgv: ["node", script, `--stdin-filepath=${rel}`],
+ display: `node ${show(script)} --stdin-filepath=<file>`,
+ // Prettier looks for its configuration from the file's folder up: every folder on the way counts.
+ configFiles: [...new Set([...configFoldersUp(root, file).flatMap((folder) => configFilesIn(folder, pattern)), join(dirname(dirname(script)), "package.json")])],
};
}
if (ext === ".go") {
@@ -136,13 +150,13 @@ export function formatterFor(root: string, file: string, env: NodeJS.ProcessEnv
const files = configFilesIn(root, /^(?:pyproject\.toml|\.?ruff\.toml)$/);
const ruff = /\[tool\.ruff/.test(pyproject) || /["']ruff[>=<~\s"']/.test(pyproject) ? findOnPath("ruff", env) : null;
if (ruff) {
- const args = ["format", "--stdin-filename", rel, "-"];
- return { name: "Ruff", command: ruff, args, boxArgv: ["ruff", ...args], display: "ruff format --stdin-filename <file> -", configFiles: files };
+ const args = ["format", `--stdin-filename=${rel}`, "-"];
+ return { name: "Ruff", command: ruff, args, boxArgv: ["ruff", ...args], display: "ruff format --stdin-filename=<file> -", configFiles: files };
}
const black = /\[tool\.black/.test(pyproject) ? findOnPath("black", env) : null;
if (black) {
- const args = ["-q", "--stdin-filename", rel, "-"];
- return { name: "Black", command: black, args, boxArgv: ["black", ...args], display: "black -q --stdin-filename <file> -", configFiles: files };
+ const args = ["-q", `--stdin-filename=${rel}`, "-"];
+ return { name: "Black", command: black, args, boxArgv: ["black", ...args], display: "black -q --stdin-filename=<file> -", configFiles: files };
}
return null;
}
@@ -152,15 +166,16 @@ export function formatterFor(root: string, file: string, env: NodeJS.ProcessEnv
if (!rustfmt) return null;
const edition = /edition\s*=\s*"(\d{4})"/.exec(cargo ?? "")?.[1] ?? "2021";
const args = ["--emit", "stdout", "--edition", edition];
- return { name: "rustfmt", command: rustfmt, args, boxArgv: ["rustfmt", ...args], display: `rustfmt ${args.join(" ")}`, configFiles: configFilesIn(root, /^(?:Cargo\.toml|\.?rustfmt\.toml)$/) };
+ return { name: "rustfmt", command: rustfmt, args, boxArgv: ["rustfmt", ...args], display: `rustfmt ${args.join(" ")}`, configFiles: configFilesIn(root, /^(?:Cargo\.toml|\.?rustfmt\.toml|rust-toolchain(?:\.toml)?)$/) };
}
return null;
}
/** The trust hash: what runs and every configuration file's content (a change asks again). */
-export function formatterHash(formatter: Formatter): string {
+export function formatterHash(formatter: Formatter, sandbox = false): string {
const hash = createHash("sha256");
- hash.update(`${formatter.name}\0${formatter.command}\0${formatter.args.slice(0, 1).join(" ")}\0`);
+ // Where it runs is part of what was allowed: turning the sandbox off asks again.
+ hash.update(`${formatter.name}\0${formatter.command}\0${formatter.args.slice(0, 1).join(" ")}\0${sandbox ? "box" : "host"}\0`);
for (const file of formatter.configFiles) {
hash.update(`${basename(file)}\0`);
hash.update(readText(file) ?? "\u0000missing");
@@ -297,6 +312,8 @@ export async function formatRequest(options: {
trust: "once" | "always" | "never" | null;
hash: string | null;
store: FormatTrustStore;
+ /** The project's sandbox switch (BoxService.sandboxOn): on, the formatter runs in its box or not at all. */
+ sandboxOn: boolean;
env?: NodeJS.ProcessEnv;
now?: () => number;
}): Promise<FormatOutcome> {
@@ -306,26 +323,34 @@ export async function formatRequest(options: {
if (file === root || !file.startsWith(root + sep)) throw new ApiError(400, "invalid_path", "The file is outside the project");
const formatter = formatterFor(root, file, env);
if (!formatter) return { formatter: null, text: null };
- const hash = formatterHash(formatter);
- const record = projectBox(root, env);
+ const sandbox = options.sandboxOn;
+ const hash = formatterHash(formatter, sandbox);
const stored = options.store.get(root);
const current = stored && stored.hash === hash ? stored : null;
if (options.trust) {
// An answer to a prompt about another configuration (it changed meanwhile) asks again.
- if (options.hash !== hash) return { formatter: formatter.name, trust: "ask", command: formatter.display, hash, sandbox: Boolean(record) };
+ if (options.hash !== hash) return { formatter: formatter.name, trust: "ask", command: formatter.display, hash, sandbox };
if (options.trust !== "once") options.store.set(root, { decision: options.trust, hash, command: formatter.display, at: (options.now ?? Date.now)() });
if (options.trust === "never") return { formatter: formatter.name, trust: "denied" };
} else if (!current) {
- return { formatter: formatter.name, trust: "ask", command: formatter.display, hash, sandbox: Boolean(record) };
+ return { formatter: formatter.name, trust: "ask", command: formatter.display, hash, sandbox };
} else if (current.decision === "never") {
return { formatter: formatter.name, trust: "denied" };
}
- const text = record ? await runFormatterInBox(formatter, root, record, options.text, env) : await runFormatter(formatter, root, options.text, FORMAT_TIMEOUT_MS, formatterEnvironment(env));
- return { formatter: formatter.name, text, sandbox: Boolean(record) };
+ let text: string;
+ if (sandbox) {
+ // On: in the box only. A box that is missing (reset, cleaned up, still downloading) or not running: nothing runs.
+ const record = projectBox(root, env);
+ if (!record) throw new ApiError(409, "sandbox_not_running", "The project's sandbox is not running, so the formatter did not run");
+ text = await runFormatterInBox(formatter, root, record, options.text, env);
+ } else {
+ text = await runFormatter(formatter, root, options.text, FORMAT_TIMEOUT_MS, formatterEnvironment(env));
+ }
+ return { formatter: formatter.name, text, sandbox };
}
export function registerEditorFormatRoutes(options: RegisterOptions): void {
- const { routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope } = options;
+ const { routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope, sandboxOn } = options;
const store = new FormatTrustStore(formatTrustFile(config));
addRoute(routes, "GET", "/workspace/:id/editor/formatters", "client", async (ctx) => {
const workspace = await resolveWorkspace(config, ctx.params.id);
@@ -342,6 +367,8 @@ export function registerEditorFormatRoutes(options: RegisterOptions): void {
if (!path || text === null || text.length > MAX_TEXT) throw new ApiError(400, "invalid_payload", "A path and the text to format are required");
const trust = body.trust === "once" || body.trust === "always" || body.trust === "never" ? body.trust : null;
const hash = typeof body.hash === "string" ? body.hash : null;
- return jsonResponse(await formatRequest({ root: resolve(workspace.path), path, text, trust, hash, store }));
+ // The sandbox decision fails closed: if it cannot be read, the formatter is treated as sandboxed (and needs a box).
+ const inBox = await sandboxOn(workspace).catch(() => true);
+ return jsonResponse(await formatRequest({ root: resolve(workspace.path), path, text, trust, hash, store, sandboxOn: inBox }));
});
}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 9b3f0956..c8497d97 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -4974,7 +4974,7 @@ function createRoutes(
// uploader is tracking adds a "user_edit" / "user_review" trace event to it;
// nothing else in a chat's upload changes (editor-events.ts).
registerEditorSearchRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace });
- registerEditorFormatRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope });
+ registerEditorFormatRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope, sandboxOn: (workspace) => boxServiceFor(config).sandboxOn(workspace) });
registerEditorRoutes({
routes,
config,