Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: format on save asks before running project code

ogsamrat03fa01a6ae0a
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index 52e7d7dd..a490ccf9 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -2858,14 +2858,27 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
timeoutMs: 10_000,
}),
- /** The project's formatter on the editor's text (a user action): the formatted text, or null when none is set up. */
- editorFormat: (workspaceId: string, path: string, text: string, timeoutMs = 3_000) =>
- requestJson<{ formatter: string | null; text: string | null }>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/format`, {
+ /**
+ * The project's formatter on the editor's text (a user action). It runs only once trusted for the project:
+ * without `trust` the answer may be a prompt (`trust: "ask"`, the exact command and a configuration hash).
+ */
+ editorFormat: (
+ workspaceId: string,
+ path: string,
+ text: string,
+ options: { trust?: "once" | "always" | "never"; hash?: string; timeoutMs?: number } = {},
+ ) =>
+ requestJson<
+ | { formatter: null; text: null }
+ | { formatter: string; trust: "ask"; command: string; hash: string; sandbox: boolean }
+ | { formatter: string; trust: "denied" }
+ | { formatter: string; text: string; sandbox: boolean }
+ >(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/format`, {
token,
hostToken,
method: "POST",
- body: { path, text },
- timeoutMs,
+ body: { path, text, ...(options.trust ? { trust: options.trust, hash: options.hash } : {}) },
+ timeoutMs: options.timeoutMs ?? 3_000,
}),
/** An image file's bytes for the editor's image preview (image types only, capped by the server). */
diff --git a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
index 6f331592..b41c2a9a 100644
--- a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
+++ b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
@@ -81,6 +81,7 @@ import { MarkdownPreview } from "./markdown-preview";
import { openDesktopUrl } from "@/app/lib/desktop";
import { useGroupRef } from "react-resizable-panels";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
/** What the main group shows: a text file or diff (Monaco), a Markdown preview, or an image. */
type PanelSurface = SurfaceDoc | { kind: "preview"; key: string; doc: FileDoc } | { kind: "image"; key: string; path: string };
@@ -1062,30 +1063,58 @@ export default function EditorPanel(props: EditorPanelProps) {
* Format on save: the project's own formatter on the buffer's text, applied as one undoable edit before writing.
* A formatter that fails or takes longer than 3 s never blocks the save: the file is saved as it is.
*/
- const formatBeforeSave = useCallback(async (path: string) => {
+ /** The trust prompt for running a project's formatter ("Run `<command>` from this project …?"). */
+ const [formatPrompt, setFormatPrompt] = useState<{ formatter: string; command: string; sandbox: boolean; answer: (choice: "once" | "always" | "never" | null) => void } | null>(null);
+ const askFormatTrust = (formatter: string, command: string, sandbox: boolean) =>
+ new Promise<"once" | "always" | "never" | null>((resolve) => {
+ setFormatPrompt({ formatter, command, sandbox, answer: (choice) => {
+ setFormatPrompt(null);
+ resolve(choice);
+ } });
+ });
+ const formatBeforeSave = useCallback(async (path: string, trigger: "manual" | "focus") => {
const doc = docs.get(path);
if (!doc) return;
const model = doc.model;
const version = model.getAlternativeVersionId();
const extension = path.includes(".") ? path.slice(path.lastIndexOf(".")) : path;
try {
- const outcome = await client.editorFormat(workspaceId, path, model.getValue(), 3_000);
- if (outcome.formatter === null || outcome.text === null) {
+ let outcome = await client.editorFormat(workspaceId, path, model.getValue());
+ if (outcome.formatter !== null && "trust" in outcome && outcome.trust === "ask") {
+ // The project's formatter is the project's code: it runs only after the person says so, and never from an
+ // automatic save (that saves the file as it is and says how to choose).
+ if (trigger !== "manual") {
+ if (!noFormatterNoted.current.has(`trust:${extension}`)) {
+ noFormatterNoted.current.add(`trust:${extension}`);
+ toast(`Saved without formatting: ${outcome.formatter} has not been allowed for this project yet. Save with ${/Mac/i.test(navigator.platform) ? "⌘S" : "Ctrl+S"} to choose.`);
+ }
+ return;
+ }
+ const choice = await askFormatTrust(outcome.formatter, outcome.command, outcome.sandbox);
+ if (!choice) return;
+ outcome = await client.editorFormat(workspaceId, path, model.getValue(), { trust: choice, hash: outcome.hash });
+ if ("trust" in outcome && outcome.trust === "ask") {
+ toast("The formatter's settings changed while you chose; saved as is. Save again to see the new command.");
+ return;
+ }
+ }
+ if (outcome.formatter === null) {
if (!noFormatterNoted.current.has(extension)) {
noFormatterNoted.current.add(extension);
toast(`No formatter set up for ${extension} files in this project; saved as is.`);
}
return;
}
+ if (!("text" in outcome) || typeof outcome.text !== "string") return;
// Typed while the formatter ran: that text wins, unformatted. Line endings alone are no change.
const lf = (text: string) => text.replace(/\r\n/g, "\n");
if (model.getAlternativeVersionId() !== version || lf(outcome.text) === lf(model.getValue())) return;
model.pushStackElement();
model.pushEditOperations([], [{ range: model.getFullModelRange(), text: outcome.text }], () => null);
model.pushStackElement();
- toast(`Formatted with ${outcome.formatter}`, { duration: 1500 });
- } catch {
- toast("Couldn't format this file; it was saved as is.");
+ toast(`Formatted with ${outcome.formatter}${outcome.sandbox ? " (in the sandbox)" : ""}`, { duration: 1500 });
+ } catch (error) {
+ toast(`Couldn't format this file; it was saved as is.${error instanceof Error && error.message ? ` ${error.message}` : ""}`);
}
}, [client, docs, workspaceId]);
@@ -1098,7 +1127,7 @@ export default function EditorPanel(props: EditorPanelProps) {
const doc = docs.get(path);
if (!doc) return;
if (trigger !== "manual" && (doc.conflict || !docs.isDirty(doc))) return;
- if (useEditorSettings.getState().formatOnSave && trigger !== "delay") await formatBeforeSave(path);
+ if (useEditorSettings.getState().formatOnSave && trigger !== "delay") await formatBeforeSave(path, trigger);
const result = await docs.save(path, { sessionId, source: "editor", force: options.force });
if (result.ok) {
void refreshFileDiagnostics(path);
@@ -1899,6 +1928,24 @@ export default function EditorPanel(props: EditorPanelProps) {
) : null}
</ResizablePanelGroup>
</div>
+ <Dialog open={Boolean(formatPrompt)} onOpenChange={(open) => !open && formatPrompt?.answer(null)}>
+ <DialogContent className="max-w-lg" data-editor-format-trust>
+ <DialogHeader>
+ <DialogTitle>Run this project's formatter?</DialogTitle>
+ <DialogDescription>
+ Format on save would run {formatPrompt?.formatter} from this project{formatPrompt?.sandbox ? ", in the project's sandbox" : " on this computer"}. It is the
+ project's own code (and its settings and plugins), so only allow it for projects you trust.
+ </DialogDescription>
+ </DialogHeader>
+ <code className="block break-all rounded-md border border-border bg-muted px-3 py-2 font-mono text-xs" data-editor-format-command>{formatPrompt?.command}</code>
+ <p className="text-xs text-muted-foreground">You are asked again if the formatter or its settings change.</p>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => formatPrompt?.answer("never")}>No</Button>
+ <Button variant="outline" onClick={() => formatPrompt?.answer("once")}>Allow once</Button>
+ <Button onClick={() => formatPrompt?.answer("always")}>Always for this project</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
{quickOpen ? (
<QuickOpen
files={files}
diff --git a/apps/app/src/react-app/domains/settings/pages/editor-settings-view.tsx b/apps/app/src/react-app/domains/settings/pages/editor-settings-view.tsx
index 7daca19f..a3d4dab9 100644
--- a/apps/app/src/react-app/domains/settings/pages/editor-settings-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/editor-settings-view.tsx
@@ -196,7 +196,7 @@ export function EditorSettingsView(props: { client: OmniRushServerClient | null;
<label htmlFor="editor-format-on-save">Format on save</label>
</LayoutSectionItemTitle>
<LayoutSectionItemDescription>
- Runs the project's own formatter (Prettier, gofmt, ruff, …) when you save with Cmd/Ctrl+S or leave the editor; never a built-in one.
+ Runs the project's own formatter (Prettier, gofmt, Ruff, …) when you save with Cmd/Ctrl+S or leave the editor; never a built-in one. It is the project's code: the first time in each project you are shown the exact command and asked (again whenever it changes). With the sandbox on, it runs in the sandbox.
{" "}<span data-editor-formatter>{formatterNote}</span>
</LayoutSectionItemDescription>
<LayoutSectionItemHeaderActions>
diff --git a/apps/server/src/editor-format.e2e.test.ts b/apps/server/src/editor-format.e2e.test.ts
index 86696c91..2cdab5ac 100644
--- a/apps/server/src/editor-format.e2e.test.ts
+++ b/apps/server/src/editor-format.e2e.test.ts
@@ -1,11 +1,12 @@
-import { afterEach, expect, test } from "bun:test";
+import { afterEach, describe, expect, test } from "bun:test";
import { existsSync, readdirSync } from "node:fs";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { createRequire } from "node:module";
-import { formatterFor, projectFormatters, runFormatter } from "./routes/editor-format.js";
+import { boxKey, recordFile } from "./box/common.js";
+import { FormatTrustStore, formatRequest, formatterEnvironment, formatterFor, projectFormatters, runFormatter } from "./routes/editor-format.js";
const roots: string[] = [];
afterEach(async () => {
@@ -64,3 +65,66 @@ test("a formatter that rejects the text is an error, not an empty file", async (
if (!formatter) return;
await expect(runFormatter(formatter, root, "export const = = ;\n")).rejects.toThrow();
});
+
+describe("format on save asks before running project code", () => {
+ async function prettierProject() {
+ 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");
+ return formatterFor(root, join(root, "src/a.ts")) ? root : null;
+ }
+
+ test("ask first, then once / always / never, and ask again when the configuration changes", async () => {
+ const root = await prettierProject();
+ if (!root) return;
+ 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 });
+ 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>");
+ // 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" });
+ // 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" });
+ // 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 });
+ 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" });
+ // 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" });
+ });
+
+ test("the formatter's environment has no app tokens, engine password or other keys", () => {
+ const env = formatterEnvironment({ PATH: "/usr/bin", HOME: "/home/u", LANG: "C.UTF-8", OMNIRUSH_TOKEN: "x", OPENCODE_SERVER_PASSWORD: "y", GITHUB_TOKEN: "z", AWS_SECRET_ACCESS_KEY: "w", LC_ALL: "C" }, "linux");
+ expect(env).toEqual({ PATH: "/usr/bin", HOME: "/home/u", LANG: "C.UTF-8", LC_ALL: "C" });
+ });
+
+ test("a project that uses the sandbox never formats on this computer when its box is not running", async () => {
+ const root = await prettierProject();
+ if (!root) return;
+ const home = await mkdtemp(join(tmpdir(), "omnirush-boxhome-"));
+ roots.push(home);
+ const key = boxKey(root);
+ await mkdir(join(home, "boxes"), { recursive: true });
+ const record = { v: 1, key, root, croot: root, container: "c", backend: "docker", runtime: "docker", runtime_args: [], host: "127.0.0.1", port: 0, token: "", state: "starting", error: "", uid: 0, gid: 0, home: "/root", shell: "/bin/sh", path_prefix: "", env_file: "", updated: 0, pid: 0 };
+ 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 });
+ 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/);
+ });
+});
diff --git a/apps/server/src/routes/editor-format.ts b/apps/server/src/routes/editor-format.ts
index 5832a384..cc2461cb 100644
--- a/apps/server/src/routes/editor-format.ts
+++ b/apps/server/src/routes/editor-format.ts
@@ -1,13 +1,26 @@
/**
- * The desktop editor's "Format on save": the project's own formatter, run as the user on the editor's text (stdin
- * in, stdout out; nothing is written here). Only formatters the project sets up itself are used, never a built-in
- * one: Prettier when the project depends on it and has it installed (run with Node from PATH), gofmt, Ruff or Black
- * when pyproject.toml configures them, rustfmt for Cargo projects. A user action only: not an agent tool.
+ * The desktop editor's "Format on save": the project's own formatter on the editor's text (stdin in, stdout out;
+ * nothing is written to the project). Only formatters the project sets up itself are used, never a built-in one:
+ * Prettier when the project depends on it and has it installed (run with Node), gofmt, Ruff or Black when
+ * pyproject.toml configures them, rustfmt for Cargo projects. A user action only: not an agent tool.
+ *
+ * A formatter is the project's code running on this computer, so it never runs until the person trusts it for this
+ * project: the first request answers with the exact command and a hash of the formatter's configuration, and runs
+ * only with a trust answer ("once", or "always", remembered per project folder and configuration hash; "never" is
+ * remembered too). A changed configuration asks again. When the project uses the sandbox, the formatter runs in
+ * its box (never on this computer, and not at all when the box is not running); otherwise it runs here with only
+ * the basic environment a local MCP server gets (no app tokens, no engine password, no other keys).
*/
import { spawn } from "node:child_process";
-import { existsSync, readFileSync } from "node:fs";
-import { dirname, extname, join, relative, resolve, sep } from "node:path";
+import { createHash, randomBytes } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
+import { boxHome, boxKey, canonicalRoot, readRecord, runDir, RUN_DIR, type BoxRecord } from "../box/common.js";
+import { exec as boxExec } from "../box/client.js";
+import { mapToBox } from "../box/launch.js";
import { ApiError } from "../errors.js";
+import { mcpServerEnvironment } from "../mcp-allow/mcp-allow.mjs";
import type { ServerConfig, TokenScope, WorkspaceInfo } from "../types.js";
import { addRoute, type RequestContext, type Route } from "./registry.js";
import { findOnPath } from "./editor-search.js";
@@ -21,7 +34,21 @@ const PRETTIER_EXTENSIONS = new Set([
".html", ".vue", ".svelte", ".md", ".mdx", ".yaml", ".yml", ".graphql", ".gql", ".hbs", ".handlebars",
]);
-export type Formatter = { name: string; command: string; args: string[] };
+export type Formatter = {
+ name: string;
+ /** On this computer: the program and its arguments. */
+ command: string;
+ args: string[];
+ /** In the project's box: the program (found on the box's PATH) and its arguments, project paths absolute here. */
+ boxArgv: string[];
+ /** What the trust prompt shows: the command with project-relative paths. */
+ display: string;
+ /** Files whose content decides what the formatter does (its configuration, its version): hashed for trust. */
+ configFiles: string[];
+};
+
+export type TrustDecision = "always" | "never";
+type TrustEntry = { decision: TrustDecision; hash: string; command: string; at: number };
type RegisterOptions = {
routes: Route[];
@@ -41,6 +68,15 @@ function readText(path: string): string | null {
}
}
+/** Files in `dir` named like a formatter's configuration. */
+function configFilesIn(dir: string, pattern: RegExp): string[] {
+ try {
+ return readdirSync(dir).filter((name) => pattern.test(name)).sort().map((name) => join(dir, name));
+ } catch {
+ return [];
+ }
+}
+
/** 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);
@@ -75,23 +111,39 @@ function prettierScript(dir: string, root: string): string | null {
export function formatterFor(root: string, file: string, env: NodeJS.ProcessEnv = process.env): Formatter | null {
const ext = extname(file).toLowerCase();
const rel = relative(root, file).split(sep).join("/");
+ const show = (path: string) => relative(root, path).split(sep).join("/");
if (PRETTIER_EXTENSIONS.has(ext)) {
const dir = prettierRoot(root, file);
const script = dir ? prettierScript(dir, root) : null;
const node = findOnPath("node", env);
- if (script && node) return { name: "Prettier", command: node, args: [script, "--stdin-filepath", rel] };
- return null;
+ if (!dir || !script || !node) return null;
+ const pattern = /^(?:\.prettierrc(?:\..+)?|prettier\.config\..+|\.prettierignore|\.editorconfig|package\.json)$/;
+ 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")])],
+ };
}
if (ext === ".go") {
const gofmt = findOnPath("gofmt", env);
- return gofmt ? { name: "gofmt", command: gofmt, args: [] } : null;
+ return gofmt ? { name: "gofmt", command: gofmt, args: [], boxArgv: ["gofmt"], display: "gofmt", configFiles: [] } : null;
}
if (ext === ".py" || ext === ".pyi") {
const pyproject = readText(join(root, "pyproject.toml")) ?? "";
+ const files = configFilesIn(root, /^(?:pyproject\.toml|\.?ruff\.toml)$/);
const ruff = /\[tool\.ruff/.test(pyproject) || /["']ruff[>=<~\s"']/.test(pyproject) ? findOnPath("ruff", env) : null;
- if (ruff) return { name: "Ruff", command: ruff, args: ["format", "--stdin-filename", rel, "-"] };
+ 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 black = /\[tool\.black/.test(pyproject) ? findOnPath("black", env) : null;
- if (black) return { name: "Black", command: black, args: ["-q", "--stdin-filename", rel, "-"] };
+ 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 };
+ }
return null;
}
if (ext === ".rs") {
@@ -99,11 +151,24 @@ export function formatterFor(root: string, file: string, env: NodeJS.ProcessEnv
const rustfmt = cargo !== null ? findOnPath("rustfmt", env) : null;
if (!rustfmt) return null;
const edition = /edition\s*=\s*"(\d{4})"/.exec(cargo ?? "")?.[1] ?? "2021";
- return { name: "rustfmt", command: rustfmt, args: ["--emit", "stdout", "--edition", edition] };
+ 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 null;
}
+/** The trust hash: what runs and every configuration file's content (a change asks again). */
+export function formatterHash(formatter: Formatter): string {
+ const hash = createHash("sha256");
+ hash.update(`${formatter.name}\0${formatter.command}\0${formatter.args.slice(0, 1).join(" ")}\0`);
+ for (const file of formatter.configFiles) {
+ hash.update(`${basename(file)}\0`);
+ hash.update(readText(file) ?? "\u0000missing");
+ hash.update("\0");
+ }
+ return hash.digest("hex").slice(0, 32);
+}
+
/** Which formatters the project has, for Settings → Editor. */
export function projectFormatters(root: string, env: NodeJS.ProcessEnv = process.env): string[] {
const names: string[] = [];
@@ -115,9 +180,19 @@ export function projectFormatters(root: string, env: NodeJS.ProcessEnv = process
return names;
}
-export function runFormatter(formatter: Formatter, cwd: string, text: string, timeoutMs = FORMAT_TIMEOUT_MS): Promise<string> {
+/** The environment a formatter gets on this computer: the basics a local MCP server gets, nothing else. */
+export function formatterEnvironment(env: NodeJS.ProcessEnv = process.env, platform = process.platform): Record<string, string> {
+ const cleared = mcpServerEnvironment(env, {}, [], platform);
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(env)) {
+ if (typeof value === "string" && !Object.hasOwn(cleared, key)) out[key] = value;
+ }
+ return out;
+}
+
+export function runFormatter(formatter: Formatter, cwd: string, text: string, timeoutMs = FORMAT_TIMEOUT_MS, env: Record<string, string> = formatterEnvironment()): Promise<string> {
return new Promise((resolvePromise, reject) => {
- const child = spawn(formatter.command, formatter.args, { cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
+ const child = spawn(formatter.command, formatter.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
const out: Buffer[] = [];
let err = "";
const timer = setTimeout(() => {
@@ -143,8 +218,115 @@ export function runFormatter(formatter: Formatter, cwd: string, text: string, ti
});
}
+/** The project's box when the project uses the sandbox (a box record exists), whatever its state. */
+export function projectBox(root: string, env: NodeJS.ProcessEnv = process.env): BoxRecord | null {
+ return readRecord(boxHome(env), boxKey(root));
+}
+
+/** Runs the formatter in the project's box: the text goes through the box's run folder, never through the project. */
+export async function runFormatterInBox(formatter: Formatter, root: string, record: BoxRecord, text: string, env: NodeJS.ProcessEnv = process.env, timeoutMs = FORMAT_TIMEOUT_MS): Promise<string> {
+ if (record.state !== "ready" || !record.port || !record.token) {
+ throw new ApiError(409, "sandbox_not_running", "The project's sandbox is not running, so the formatter did not run");
+ }
+ const name = `format-${randomBytes(8).toString("hex")}.in`;
+ const hostDir = runDir(boxHome(env), record.key);
+ mkdirSync(hostDir, { recursive: true });
+ const hostFile = join(hostDir, name);
+ writeFileSync(hostFile, text, { mode: 0o600 });
+ try {
+ const argv = formatter.boxArgv.map((arg) => (arg.startsWith(root + sep) ? mapToBox(arg, record.root, record.croot) : arg));
+ const result = await boxExec(
+ { host: record.host, port: record.port, token: record.token },
+ ["sh", "-c", 'exec "$@" < "$FORMAT_INPUT"', "sh", ...argv],
+ { cwd: mapToBox(root, record.root, record.croot), env: { FORMAT_INPUT: `${RUN_DIR}/${name}`, OMNIRUSH_LEDGER_OFF: "1" }, timeoutMs },
+ );
+ if (result.code === 127) throw new ApiError(422, "format_failed", `${formatter.name} is not installed in the project's sandbox`);
+ if (result.code !== 0 || (!result.stdout.length && text.length)) {
+ throw new ApiError(422, "format_failed", (result.stderr.trim() || `${formatter.name} exited with ${result.code}`).slice(0, 400));
+ }
+ return result.stdout;
+ } finally {
+ rmSync(hostFile, { force: true });
+ }
+}
+
+/** Trust decisions, per project folder (canonical), in a file next to the server's config. */
+export class FormatTrustStore {
+ constructor(private file: string) {}
+
+ private read(): Record<string, TrustEntry> {
+ try {
+ const value = JSON.parse(readFileSync(this.file, "utf8")) as Record<string, TrustEntry>;
+ return value && typeof value === "object" ? value : {};
+ } catch {
+ return {};
+ }
+ }
+
+ get(root: string): TrustEntry | null {
+ return this.read()[canonicalRoot(root)] ?? null;
+ }
+
+ set(root: string, entry: TrustEntry): void {
+ const all = this.read();
+ all[canonicalRoot(root)] = entry;
+ mkdirSync(dirname(this.file), { recursive: true });
+ const tmp = `${this.file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;
+ writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 0o600 });
+ // Renamed over the old file: never a half-written one.
+ renameSync(tmp, this.file);
+ }
+}
+
+export function formatTrustFile(config: ServerConfig): string {
+ const base = config.configPath ? dirname(config.configPath) : join(homedir(), ".config", "omnirush");
+ return join(base, "format-trust.json");
+}
+
+export type FormatOutcome =
+ | { formatter: null; text: null }
+ | { formatter: string; trust: "ask"; command: string; hash: string; sandbox: boolean }
+ | { formatter: string; trust: "denied" }
+ | { formatter: string; text: string; sandbox: boolean };
+
+/** One format request: never runs without trust for this project and configuration. */
+export async function formatRequest(options: {
+ root: string;
+ path: string;
+ text: string;
+ trust: "once" | "always" | "never" | null;
+ hash: string | null;
+ store: FormatTrustStore;
+ env?: NodeJS.ProcessEnv;
+ now?: () => number;
+}): Promise<FormatOutcome> {
+ const env = options.env ?? process.env;
+ const root = options.root;
+ const file = resolve(root, options.path);
+ 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 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.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) };
+ } 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) };
+}
+
export function registerEditorFormatRoutes(options: RegisterOptions): void {
const { routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope } = 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);
return jsonResponse({ formatters: projectFormatters(resolve(workspace.path)) });
@@ -154,15 +336,12 @@ export function registerEditorFormatRoutes(options: RegisterOptions): void {
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
- const root = resolve(workspace.path);
const body = await readJsonBody(ctx.request);
const path = typeof body.path === "string" ? body.path : "";
const text = typeof body.text === "string" ? body.text : null;
if (!path || text === null || text.length > MAX_TEXT) throw new ApiError(400, "invalid_payload", "A path and the text to format are required");
- const file = resolve(root, path);
- if (file !== root && !file.startsWith(root + sep)) throw new ApiError(400, "invalid_path", "The file is outside the project");
- const formatter = formatterFor(root, file);
- if (!formatter) return jsonResponse({ formatter: null, text: null });
- return jsonResponse({ formatter: formatter.name, text: await runFormatter(formatter, root, text) });
+ 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 }));
});
}