Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: check folder access before the first turn

ogsamrat4a138d2b2132
diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
index 468e2f23..f840d1a3 100644
--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx
+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
@@ -85,7 +85,7 @@ import {
messageHasVisibleAssistantOutput,
resolveAdmissionOutcome,
} from "./session-admission-outcome";
-import { describeOpencodeSessionError, interruptedTaskRecoveryPrompt, presentOpencodeSessionError } from "@/react-app/domains/session/sync/session-error";
+import { describeOpencodeSessionError, folderWriteError, interruptedTaskRecoveryPrompt, presentOpencodeSessionError } from "@/react-app/domains/session/sync/session-error";
import { createSessionErrorUIMessage } from "@/react-app/domains/session/sync/usechat-adapter";
import { useLocal } from "@/react-app/kernel/local-provider";
import { resolveAttachmentFileMetadata } from "@/react-app/domains/session/sync/attachment-file-part";
@@ -1033,6 +1033,21 @@ function SessionErrorCard({ error, developerMode, onDismiss, onChangeModel, onOp
{!developerMode && presentation.description ? (
<p className="mt-1 text-sm text-red-11">{presentation.description}</p>
) : null}
+ {presentation.kind === "folder-not-writable" ? (
+ <div className="mt-2 flex flex-wrap gap-2">
+ <button
+ type="button"
+ className="rounded-full border border-dls-border bg-dls-surface px-3 py-1.5 text-xs font-medium text-dls-text transition-colors hover:bg-dls-hover"
+ data-testid="folder-not-writable-choose"
+ onClick={() => {
+ window.dispatchEvent(new CustomEvent("omnirush-open-project-folder"));
+ onDismiss();
+ }}
+ >
+ Choose another folder
+ </button>
+ </div>
+ ) : null}
{error.kind === "model-not-found" ? (
<div className="mt-2 flex flex-wrap gap-2">
{error.suggestions && error.suggestions.length > 0 ? (
@@ -2220,7 +2235,9 @@ export function SessionSurface(props: SessionSurfaceProps) {
}
dispatchQueuedDrain(props.sessionId, { type: "send_error", itemId });
const parsed = parseSessionError(nextError);
- captureAnalyticsEvent("task_send_failed", {});
+ const folderNotWritable = folderWriteError(nextError);
+ captureAnalyticsEvent("task_send_failed", folderNotWritable ? { reason: "folder_not_writable" } : {});
+ if (folderNotWritable) captureAnalyticsEvent("folder_not_writable", { reason: folderNotWritable.reason });
setError(parsed);
useSessionActivityStore.getState().setError(props.workspaceId, props.sessionId, parsed.message);
if (activeSessionOwnerRef.current === sessionOwner) {
diff --git a/apps/app/src/react-app/domains/session/sync/session-error.ts b/apps/app/src/react-app/domains/session/sync/session-error.ts
index dfaa94f2..c5a588a3 100644
--- a/apps/app/src/react-app/domains/session/sync/session-error.ts
+++ b/apps/app/src/react-app/domains/session/sync/session-error.ts
@@ -3,7 +3,7 @@ import type { UIMessage } from "ai";
import { safeStringify } from "../../../../app/utils";
import { normalizeErrorText } from "../../../../lib/error-text";
-export type OpencodeSessionErrorKind = "aborted" | "provider-timeout" | "provider-incomplete" | "free-model-limit" | "disk-full" | "database-error" | "generic";
+export type OpencodeSessionErrorKind = "aborted" | "provider-timeout" | "provider-incomplete" | "free-model-limit" | "disk-full" | "database-error" | "folder-not-writable" | "generic";
/**
* omnirush.ai's stable error object (`error.omnirush` of the gateway's JSON
@@ -284,7 +284,40 @@ function technicalErrorDetails(error: unknown, fallback: string, fields: ReturnT
return normalizeErrorText(serialized && serialized !== "{}" ? serialized : fallback, { cap: 1_500 }).display;
}
+/** The server's refusal of a prompt in a folder the engine cannot write to (apps/server/src/folder-write-check.ts). */
+export type FolderWriteError = { reason: string; message: string; hint: string | null };
+
+export function folderWriteError(error: unknown): FolderWriteError | null {
+ let value: unknown = error instanceof Error ? error.message : error;
+ if (typeof value === "string") {
+ const text = value.trim();
+ if (!text.startsWith("{") || !text.includes("workspace_not_writable")) return null;
+ try {
+ value = JSON.parse(text);
+ } catch {
+ return null;
+ }
+ }
+ const records = [value, recordValue(value, "data")];
+ const source = records.find((record) => recordValue(record, "error") === "workspace_not_writable");
+ const message = recordValue(source, "message");
+ if (!source || typeof message !== "string" || !message.trim()) return null;
+ const reason = recordValue(source, "reason");
+ const hint = recordValue(source, "hint");
+ return { reason: typeof reason === "string" ? reason : "unknown", message: message.trim(), hint: typeof hint === "string" && hint.trim() ? hint.trim() : null };
+}
+
export function presentOpencodeSessionError(error: unknown, fallback = "Session failed"): OpencodeSessionErrorPresentation {
+ const folder = folderWriteError(error);
+ if (folder) {
+ return {
+ kind: "folder-not-writable",
+ title: folder.message,
+ description: folder.hint,
+ technicalDetails: `Reason: ${folder.reason}`,
+ recoveryPrompt: null,
+ };
+ }
const fields = sessionErrorFields(error, fallback);
const kind = sessionErrorKind(fields.name, fields.message, fields.code, fields.responseBody);
const consoleLink = consoleLinkAction(fields.message);
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index f4d6d623..ce51984d 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -3217,6 +3217,13 @@ export function SessionRoute() {
const folder = singlePickedDirectory(await pickDirectory({ title: t("onboarding.authorize_folder") }));
await handleCreateWorkspace("starter", folder);
}, [checkDesktopRestriction, handleCreateWorkspace, restrictionNotice, workspaces.length]);
+ // "Choose another folder" on a chat stopped because its folder is not writable (session-surface.tsx).
+ useEffect(() => {
+ if (!platform.capabilities.nativeFilePicker || !canCreateWorkspaces()) return;
+ const open = () => void openProjectFolder().catch(() => undefined);
+ window.addEventListener("omnirush-open-project-folder", open);
+ return () => window.removeEventListener("omnirush-open-project-folder", open);
+ }, [openProjectFolder, platform.capabilities.nativeFilePicker]);
const newTaskComposerWithProjects = useMemo<NewTaskComposerContext | null>(() => newTaskComposerContext && {
...newTaskComposerContext,
projectPicker: {
diff --git a/apps/app/tests/folder-write-error.test.ts b/apps/app/tests/folder-write-error.test.ts
new file mode 100644
index 00000000..f605ad24
--- /dev/null
+++ b/apps/app/tests/folder-write-error.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from "bun:test"
+
+import { folderWriteError, presentOpencodeSessionError } from "../src/react-app/domains/session/sync/session-error"
+
+const body = {
+ error: "workspace_not_writable",
+ reason: "protected_folder",
+ message: "OmniRush can't write to C:\\Users\\sam\\Documents\\OmniRushTest: Windows Security's Controlled folder access blocks the change (EPERM).",
+ hint: "Open Windows Security → Virus & threat protection → Ransomware protection → Allow an app through Controlled folder access.",
+}
+
+describe("folder not writable", () => {
+ test("read from the serialized SDK error, a thrown Error and a nested data record", () => {
+ for (const value of [JSON.stringify(body), new Error(JSON.stringify(body)), body, { name: "Error", data: body }]) {
+ expect(folderWriteError(value)).toEqual({ reason: "protected_folder", message: body.message, hint: body.hint })
+ }
+ expect(folderWriteError("Failed to send prompt.")).toBeNull()
+ expect(folderWriteError(JSON.stringify({ error: "omnirush_account_required", message: "Sign in" }))).toBeNull()
+ })
+
+ test("presented with the folder, the reason and the fix", () => {
+ const presentation = presentOpencodeSessionError(JSON.stringify(body))
+ expect(presentation.kind).toBe("folder-not-writable")
+ expect(presentation.title).toBe(body.message)
+ expect(presentation.description).toBe(body.hint)
+ expect(presentation.recoveryPrompt).toBeNull()
+ })
+})
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 55b2c657..728c9a4a 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -11,6 +11,7 @@ import { managedDesktopPolicy } from "./managed-desktop-policy.js";
import { mkdir } from "node:fs/promises";
import { dirname } from "node:path";
import { setToolsRoot } from "./box/box.js";
+import { setWriteCheckEngine } from "./folder-write-check.js";
import { resolveServerConfig, type CliArgs } from "./config.js";
import {
buildEngineAuthProbeHeader,
@@ -231,6 +232,7 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
// The Linux sandbox's helpers ship beside the engine (sidecars/box/): known before the server plans any box.
const engineBin = options.opencodeBin || process.env.OMNIRUSH_OPENCODE_BIN;
if (engineBin?.trim()) setToolsRoot(dirname(engineBin.trim()));
+ setWriteCheckEngine(engineBin);
server = await duringStartup(() => startServer(config));
config.port = server.port;
const serverUrl = `http://${config.host === "0.0.0.0" ? "127.0.0.1" : config.host}:${server.port}`;
diff --git a/apps/server/src/folder-write-check.test.ts b/apps/server/src/folder-write-check.test.ts
new file mode 100644
index 00000000..b690f4b6
--- /dev/null
+++ b/apps/server/src/folder-write-check.test.ts
@@ -0,0 +1,164 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { chmodSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import {
+ checkFolderWritable,
+ classifyFailure,
+ controlledFolderAccessOn,
+ folderWriteGate,
+ probeInProcess,
+ readOnlyPrompt,
+ resetFolderWriteGate,
+ type FolderProbeOutcome,
+} from "./folder-write-check.js";
+
+const fail = (code: string | null, message = "", step = "create"): Extract<FolderProbeOutcome, { ok: false }> => ({ ok: false, step, code, errno: null, message });
+
+const winEnv = {
+ ProgramFiles: "C:\\Program Files",
+ "ProgramFiles(x86)": "C:\\Program Files (x86)",
+ SystemRoot: "C:\\Windows",
+ ProgramData: "C:\\ProgramData",
+ OneDrive: "C:\\Users\\sam\\OneDrive",
+};
+
+afterEach(() => resetFolderWriteGate());
+
+describe("classifyFailure", () => {
+ test("POSIX codes", () => {
+ expect(classifyFailure(fail("EACCES"), { platform: "linux", dir: "/srv/x" })).toBe("permission");
+ expect(classifyFailure(fail("EPERM"), { platform: "linux", dir: "/srv/x" })).toBe("permission");
+ expect(classifyFailure(fail("EROFS"), { platform: "linux", dir: "/mnt/ro" })).toBe("read_only_volume");
+ expect(classifyFailure(fail("ENOSPC", "", "write"), { platform: "linux", dir: "/x" })).toBe("disk_full");
+ expect(classifyFailure(fail("ENOENT"), { platform: "linux", dir: "/gone" })).toBe("missing");
+ expect(classifyFailure(fail("EIO"), { platform: "linux", dir: "/x" })).toBe("unknown");
+ });
+
+ test("macOS privacy-protected folders and volumes", () => {
+ const ctx = { platform: "darwin" as const, home: "/Users/sam" };
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "/Users/sam/Desktop/proj" })).toBe("macos_privacy");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "/Users/sam/Documents" })).toBe("macos_privacy");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "/Users/sam/Downloads/a" })).toBe("macos_privacy");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "/Volumes/USB/proj" })).toBe("macos_privacy");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "/Users/sam/code" })).toBe("permission");
+ expect(classifyFailure(fail("EACCES"), { ...ctx, dir: "/Users/sam/Desktop" })).toBe("permission");
+ expect(classifyFailure(fail("EROFS"), { ...ctx, dir: "/Volumes/dmg" })).toBe("read_only_volume");
+ });
+
+ test("Windows: Controlled folder access, system folders, read-only attribute, OneDrive, UNC", () => {
+ const ctx = { platform: "win32" as const, env: winEnv };
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "C:\\Users\\sam\\Documents\\OmniRushTest", cfaOn: true })).toBe("protected_folder");
+ expect(classifyFailure(fail("EACCES"), { ...ctx, dir: "C:\\Users\\sam\\Desktop\\x", cfaOn: true })).toBe("protected_folder");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "C:\\Program Files\\Thing" })).toBe("system_folder");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "c:\\windows\\system32" })).toBe("system_folder");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "C:\\" })).toBe("system_folder");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "D:\\proj", readOnlyMode: true })).toBe("read_only_attribute");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "D:\\proj" })).toBe("permission");
+ expect(classifyFailure(fail("UNKNOWN", "UNKNOWN: unknown error, open"), { ...ctx, dir: "C:\\Users\\sam\\OneDrive\\proj" })).toBe("cloud_files");
+ expect(classifyFailure(fail("UNKNOWN", "The cloud file provider is not running."), { ...ctx, dir: "D:\\sync\\proj" })).toBe("cloud_files");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "C:\\Users\\sam\\OneDrive\\proj" })).toBe("cloud_files");
+ expect(classifyFailure(fail("EPERM"), { ...ctx, dir: "C:\\Users\\sam\\OneDrive\\proj", cfaOn: true })).toBe("protected_folder");
+ expect(classifyFailure(fail("EACCES"), { ...ctx, dir: "\\\\nas\\share\\proj" })).toBe("network_folder");
+ expect(classifyFailure(fail("EROFS"), { ...ctx, dir: "E:\\" })).toBe("read_only_volume");
+ });
+});
+
+describe("controlledFolderAccessOn", () => {
+ test("block mode only (1), not audit (2) or off (0)", async () => {
+ const out = (value: string) => async () => `\r\n EnableControlledFolderAccess REG_DWORD ${value}\r\n`;
+ expect(await controlledFolderAccessOn(out("0x1"))).toBe(true);
+ expect(await controlledFolderAccessOn(out("0x2"))).toBe(false);
+ expect(await controlledFolderAccessOn(out("0x0"))).toBe(false);
+ expect(await controlledFolderAccessOn(async () => { throw new Error("not found"); })).toBe(false);
+ });
+});
+
+describe("checkFolderWritable", () => {
+ test("a writable folder passes and leaves nothing behind", async () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "fwc-"));
+ try {
+ expect(probeInProcess(dir)).toEqual({ ok: true });
+ expect(await checkFolderWritable(dir, { engineBin: null })).toEqual({ ok: true, via: "server" });
+ expect(readdirSync(dir)).toEqual([]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test.skipIf(process.platform === "win32" || process.getuid?.() === 0)("a read-only folder fails with permission and the fix", async () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "fwc-ro-"));
+ chmodSync(dir, 0o555);
+ try {
+ const result = await checkFolderWritable(dir, { engineBin: null });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.reason).toBe("permission");
+ expect(result.code).toBe("EACCES");
+ expect(result.message).toBe(`OmniRush can't write to ${dir}: permission denied (EACCES).`);
+ expect(result.hint).toContain("chown");
+ } finally {
+ chmodSync(dir, 0o755);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("simulated Windows Controlled folder access names the engine to allow", async () => {
+ const engine = "C:\\Program Files\\OmniRush\\resources\\sidecars\\opencode.exe";
+ const result = await checkFolderWritable("C:\\Users\\sam\\Documents\\OmniRushTest", {
+ platform: "win32",
+ env: winEnv,
+ engineBin: engine,
+ probeEngine: async () => fail("EPERM", "EPERM: operation not permitted, open"),
+ cfa: async () => true,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.via).toBe("engine");
+ expect(result.reason).toBe("protected_folder");
+ expect(result.message).toContain("Controlled folder access");
+ expect(result.hint).toContain(engine);
+ });
+
+ test("simulated EROFS", async () => {
+ const result = await checkFolderWritable("/mnt/ro", { platform: "linux", engineBin: "/x/opencode", probeEngine: async () => fail("EROFS") });
+ expect(result.ok ? null : result.reason).toBe("read_only_volume");
+ });
+
+ test("the engine probe not running falls back to this process", async () => {
+ let local = 0;
+ const result = await checkFolderWritable("/x", { engineBin: "/x/opencode", probeEngine: async () => null, probeLocal: () => { local += 1; return { ok: true }; } });
+ expect(result).toEqual({ ok: true, via: "server" });
+ expect(local).toBe(1);
+ });
+});
+
+describe("folderWriteGate", () => {
+ test("once per chat and folder after a pass; again at every prompt after a failure", async () => {
+ let probes = 0;
+ let ok = false;
+ const options = { engineBin: "/x/opencode", probeEngine: async (): Promise<FolderProbeOutcome> => { probes += 1; return ok ? { ok: true } : fail("EACCES"); }, platform: "linux" as const };
+ expect((await folderWriteGate("ses_1", "/p", options))?.reason).toBe("permission");
+ expect((await folderWriteGate("ses_1", "/p", options))?.reason).toBe("permission");
+ expect(probes).toBe(2);
+ ok = true;
+ expect(await folderWriteGate("ses_1", "/p", options)).toBeNull();
+ expect(await folderWriteGate("ses_1", "/p", options)).toBeNull();
+ expect(probes).toBe(3);
+ // Another folder for the same chat is checked.
+ expect(await folderWriteGate("ses_1", "/q", options)).toBeNull();
+ expect(probes).toBe(4);
+ });
+
+ test("OMNIRUSH_WRITE_CHECK=off skips it", async () => {
+ expect(await folderWriteGate("ses_2", "/p", { env: { OMNIRUSH_WRITE_CHECK: "off" }, probeEngine: async () => fail("EACCES"), engineBin: "/x" })).toBeNull();
+ });
+
+ test("plan-agent prompts are read-only", () => {
+ expect(readOnlyPrompt({ agent: "plan", parts: [] })).toBe(true);
+ expect(readOnlyPrompt({ agent: "build" })).toBe(false);
+ expect(readOnlyPrompt({})).toBe(false);
+ expect(readOnlyPrompt(null)).toBe(false);
+ });
+});
diff --git a/apps/server/src/folder-write-check.ts b/apps/server/src/folder-write-check.ts
new file mode 100644
index 00000000..bc96352c
--- /dev/null
+++ b/apps/server/src/folder-write-check.ts
@@ -0,0 +1,367 @@
+/**
+ * Write check of a project folder, before the agent's first turn there.
+ *
+ * A folder the engine cannot write to (Windows Controlled folder access, a
+ * OneDrive folder whose files are online-only, a read-only drive or mount, a
+ * system folder, a macOS privacy-protected folder) let the agent run whole
+ * turns, spending tokens, without changing a file. This check creates,
+ * writes, fsyncs, renames and deletes a temporary file in the folder, run by
+ * the engine binary itself (BUN_BE_BUN=1: the same executable, so the same
+ * Defender and macOS privacy decisions as the engine's own writes), and
+ * names the reason and the fix when it fails.
+ *
+ * Kept in step with the CLI (omnirush-cli src/folder-write-check.js).
+ */
+import { execFile, spawn } from "node:child_process";
+import { closeSync, fsyncSync, openSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+export type FolderWriteReason =
+ | "missing"
+ | "not_a_folder"
+ | "read_only_volume"
+ | "read_only_attribute"
+ | "permission"
+ | "protected_folder"
+ | "cloud_files"
+ | "system_folder"
+ | "network_folder"
+ | "macos_privacy"
+ | "disk_full"
+ | "unknown";
+
+export type FolderProbeOutcome =
+ | { ok: true }
+ | { ok: false; step: string; code: string | null; errno: number | null; message: string };
+
+export type FolderWriteResult =
+ | { ok: true; via: "engine" | "server" | "skipped" }
+ | {
+ ok: false;
+ via: "engine" | "server";
+ reason: FolderWriteReason;
+ code: string | null;
+ step: string;
+ /** "OmniRush can't write to <folder>: <why>." */
+ message: string;
+ /** How to fix it, for this platform. */
+ hint: string;
+ };
+
+export const FOLDER_NOT_WRITABLE = "workspace_not_writable";
+
+/**
+ * The probe the engine binary runs (`BUN_BE_BUN=1 <engine> -e <script>`).
+ * Prints one JSON line; never throws.
+ */
+export const PROBE_SCRIPT = [
+ 'const fs=require("node:fs"),p=require("node:path");',
+ "const d=process.env.OMNIRUSH_WRITE_CHECK_DIR;",
+ 'const n=".omnirush-write-check-"+process.pid+"-"+Date.now().toString(36);',
+ 'const a=p.join(d,n+".tmp"),b=p.join(d,n);let step="create",fd;',
+ 'try{fd=fs.openSync(a,"wx");step="write";fs.writeSync(fd,"omnirush write check\\n");step="fsync";fs.fsyncSync(fd);fs.closeSync(fd);fd=undefined;',
+ 'step="rename";fs.renameSync(a,b);step="delete";fs.unlinkSync(b);process.stdout.write(JSON.stringify({ok:true}))}',
+ "catch(e){if(fd!==undefined)try{fs.closeSync(fd)}catch{}for(const f of[a,b])try{fs.unlinkSync(f)}catch{}",
+ "process.stdout.write(JSON.stringify({ok:false,step,code:e&&e.code||null,errno:e&&typeof e.errno===\"number\"?e.errno:null,message:String(e&&e.message||e).slice(0,300)}))}",
+].join("");
+
+/** The same steps in this process (no engine binary, or it could not run). */
+export function probeInProcess(dir: string): FolderProbeOutcome {
+ const name = `.omnirush-write-check-${process.pid}-${Date.now().toString(36)}`;
+ const a = path.join(dir, `${name}.tmp`);
+ const b = path.join(dir, name);
+ let step = "create";
+ let fd: number | undefined;
+ try {
+ fd = openSync(a, "wx");
+ step = "write";
+ writeSync(fd, "omnirush write check\n");
+ step = "fsync";
+ fsyncSync(fd);
+ closeSync(fd);
+ fd = undefined;
+ step = "rename";
+ renameSync(a, b);
+ step = "delete";
+ unlinkSync(b);
+ return { ok: true };
+ } catch (error) {
+ if (fd !== undefined) try { closeSync(fd); } catch { /* closed */ }
+ for (const file of [a, b]) try { unlinkSync(file); } catch { /* not there */ }
+ const e = error as NodeJS.ErrnoException;
+ return { ok: false, step, code: e?.code ?? null, errno: typeof e?.errno === "number" ? e.errno : null, message: String(e?.message ?? e).slice(0, 300) };
+ }
+}
+
+/** The probe run by the engine binary; null when it could not run or said nothing usable. */
+export function probeWithEngine(dir: string, engineBin: string, timeoutMs = 15_000): Promise<FolderProbeOutcome | null> {
+ return new Promise((resolve) => {
+ let out = "";
+ let done = false;
+ const finish = (value: FolderProbeOutcome | null) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ resolve(value);
+ };
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(engineBin, ["-e", PROBE_SCRIPT], {
+ cwd: os.tmpdir(),
+ env: { ...process.env, BUN_BE_BUN: "1", OMNIRUSH_WRITE_CHECK_DIR: dir },
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true,
+ });
+ } catch {
+ resolve(null);
+ return;
+ }
+ const timer = setTimeout(() => {
+ try { child.kill(); } catch { /* gone */ }
+ finish(null);
+ }, timeoutMs);
+ child.stdout?.on("data", (chunk: Buffer) => { out += chunk.toString("utf8"); });
+ child.on("error", () => finish(null));
+ child.on("close", () => {
+ try {
+ const parsed = JSON.parse(out.trim().split("\n").pop() ?? "");
+ if (parsed && typeof parsed.ok === "boolean") return finish(parsed as FolderProbeOutcome);
+ } catch { /* not JSON */ }
+ finish(null);
+ });
+ });
+}
+
+/** Whether Windows Security's Controlled folder access is on (block mode). */
+export function controlledFolderAccessOn(run: (args: string[]) => Promise<string> = regQuery): Promise<boolean> {
+ const keys = [
+ "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Windows Defender Exploit Guard\\Controlled Folder Access",
+ "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Windows Defender Exploit Guard\\Controlled Folder Access",
+ ];
+ return Promise.all(keys.map((key) => run(["query", key, "/v", "EnableControlledFolderAccess"]).catch(() => "")))
+ .then((outs) => outs.some((text) => /EnableControlledFolderAccess\s+REG_DWORD\s+0x0*1\b/i.test(text)));
+}
+
+function regQuery(args: string[]): Promise<string> {
+ return new Promise((resolve, reject) => {
+ execFile("reg", args, { timeout: 3_000, windowsHide: true }, (error, stdout) => (error ? reject(error) : resolve(String(stdout))));
+ });
+}
+
+export type ClassifyContext = {
+ platform: NodeJS.Platform;
+ dir: string;
+ env?: NodeJS.ProcessEnv;
+ home?: string;
+ /** Windows: Controlled folder access is on. */
+ cfaOn?: boolean;
+ /** The folder's mode lacks the owner write bit (Windows: the read-only attribute). */
+ readOnlyMode?: boolean;
+ /** The executable to allow (Controlled folder access). */
+ engineBin?: string | null;
+};
+
+function under(child: string, parent: string | undefined, win: boolean): boolean {
+ if (!parent) return false;
+ const norm = (value: string) => {
+ const resolved = (win ? path.win32 : path.posix).resolve(value);
+ return win ? resolved.toLowerCase() : resolved;
+ };
+ const c = norm(child);
+ const p = norm(parent);
+ const sep = win ? "\\" : "/";
+ return c === p || c.startsWith(p.endsWith(sep) ? p : p + sep);
+}
+
+const CLOUD_TEXT = /cloud (?:file|operation|provider)|0x8007016a|0x80070185|0x8007018[0-9a-f]/i;
+
+/** The reason a failed probe names. */
+export function classifyFailure(outcome: Extract<FolderProbeOutcome, { ok: false }>, ctx: ClassifyContext): FolderWriteReason {
+ const env = ctx.env ?? {};
+ const code = outcome.code ?? "";
+ const win = ctx.platform === "win32";
+ if (code === "ENOENT" && outcome.step === "create") return "missing";
+ if (code === "ENOTDIR") return "not_a_folder";
+ if (code === "ENOSPC" || code === "EDQUOT") return "disk_full";
+ if (code === "EROFS") return "read_only_volume";
+ if (win) {
+ if (/^\\\\/.test(ctx.dir) || /^\/\//.test(ctx.dir)) return "network_folder";
+ const oneDrive = [env.OneDrive, env.OneDriveConsumer, env.OneDriveCommercial].some((root) => under(ctx.dir, root, true));
+ if (CLOUD_TEXT.test(outcome.message) || (oneDrive && !["EPERM", "EACCES"].includes(code) )) return "cloud_files";
+ if (code === "EPERM" || code === "EACCES") {
+ const parsed = path.win32.parse(path.win32.resolve(ctx.dir));
+ const system = [env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramW6432, env.SystemRoot, env.windir, env.ProgramData]
+ .some((root) => under(ctx.dir, root, true));
+ if (system || parsed.root.toLowerCase() === path.win32.resolve(ctx.dir).toLowerCase()) return "system_folder";
+ if (ctx.cfaOn) return "protected_folder";
+ if (ctx.readOnlyMode) return "read_only_attribute";
+ if (oneDrive) return "cloud_files";
+ return "permission";
+ }
+ return oneDrive ? "cloud_files" : "unknown";
+ }
+ if (ctx.platform === "darwin" && code === "EPERM") {
+ const home = ctx.home ?? os.homedir();
+ const tcc = ["Desktop", "Documents", "Downloads", "Library/Mobile Documents", "Library/CloudStorage"].map((name) => path.posix.join(home, name));
+ if (tcc.some((root) => under(ctx.dir, root, false)) || under(ctx.dir, "/Volumes", false)) return "macos_privacy";
+ }
+ if (code === "EACCES" || code === "EPERM") return "permission";
+ return "unknown";
+}
+
+const WHY: Record<FolderWriteReason, string> = {
+ missing: "the folder does not exist any more",
+ not_a_folder: "it is not a folder",
+ read_only_volume: "the drive or mount is read-only",
+ read_only_attribute: "the folder is marked read-only",
+ permission: "permission denied",
+ protected_folder: "Windows Security's Controlled folder access blocks the change",
+ cloud_files: "it is a OneDrive folder whose files are not available on this device",
+ system_folder: "it is a system folder that needs administrator rights",
+ network_folder: "the network folder refused the write or cannot be reached",
+ macos_privacy: "macOS privacy settings do not allow OmniRush to change files there",
+ disk_full: "the disk is full",
+ unknown: "a test file could not be written",
+};
+
+/** How to fix it, for this platform. */
+export function fixHint(reason: FolderWriteReason, platform: NodeJS.Platform, engineBin?: string | null): string {
+ const other = "Or choose another folder.";
+ switch (reason) {
+ case "missing":
+ case "not_a_folder":
+ return "Choose another folder.";
+ case "read_only_volume":
+ return platform === "darwin"
+ ? `The volume is mounted read-only (a disk image, a locked card, a read-only share). Copy the project into your home folder. ${other}`
+ : platform === "win32"
+ ? `Copy the project to a folder on a writable drive (for example C:\\Users\\<you>\\Projects). ${other}`
+ : `Remount it read-write (for example: sudo mount -o remount,rw <mount point>), or copy the project into your home folder. ${other}`;
+ case "read_only_attribute":
+ return `Open the folder's Properties, clear "Read-only" and apply it to all files and subfolders. ${other}`;
+ case "permission":
+ return platform === "win32"
+ ? `Check the folder's Properties → Security permissions for your account, or use a folder under C:\\Users\\<you>. If Controlled folder access is on, allow OmniRush in Windows Security. ${other}`
+ : `Make your user the owner (for example: sudo chown -R "$USER" <folder>) or give it write permission (chmod -R u+w <folder>). ${other}`;
+ case "protected_folder":
+ return `Open Windows Security → Virus & threat protection → Ransomware protection → Allow an app through Controlled folder access, and add ${engineBin ? `"${engineBin}"` : "OmniRush's engine"}. ${other} (outside Documents, Desktop, Pictures, Music and Videos)`;
+ case "cloud_files":
+ return `Make sure OneDrive is running and signed in, then right-click the folder → "Always keep on this device". ${other} (a local one outside OneDrive, for example C:\\Users\\<you>\\Projects)`;
+ case "system_folder":
+ return "Choose a folder in your user folder, for example C:\\Users\\<you>\\Projects. Running OmniRush as administrator is not needed.";
+ case "network_folder":
+ return `Check the network connection and your write access to the share, or copy the project to a local folder. ${other}`;
+ case "macos_privacy":
+ return `Open System Settings → Privacy & Security → Files and Folders (or Full Disk Access) and allow OmniRush, then try again. ${other} (outside Desktop, Documents and Downloads)`;
+ case "disk_full":
+ return `Free some disk space, then try again. ${other}`;
+ default:
+ return `Check that you can create files there, then try again. ${other}`;
+ }
+}
+
+export type CheckOptions = {
+ platform?: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ engineBin?: string | null;
+ probeEngine?: typeof probeWithEngine;
+ probeLocal?: typeof probeInProcess;
+ cfa?: () => Promise<boolean>;
+};
+
+/** Run the write check on a folder. Fails open (ok) only when no probe could run at all. */
+export async function checkFolderWritable(dir: string, options: CheckOptions = {}): Promise<FolderWriteResult> {
+ const platform = options.platform ?? process.platform;
+ const env = options.env ?? process.env;
+ const engineBin = options.engineBin?.trim() || null;
+ let outcome: FolderProbeOutcome | null = null;
+ let via: "engine" | "server" = "engine";
+ if (engineBin) outcome = await (options.probeEngine ?? probeWithEngine)(dir, engineBin);
+ if (!outcome) {
+ via = "server";
+ outcome = (options.probeLocal ?? probeInProcess)(dir);
+ }
+ if (outcome.ok) return { ok: true, via };
+ let readOnlyMode = false;
+ try {
+ const info = statSync(dir);
+ if (!info.isDirectory()) outcome = { ...outcome, code: "ENOTDIR" };
+ readOnlyMode = (info.mode & 0o200) === 0;
+ } catch { /* classified from the probe */ }
+ const code = outcome.code ?? "";
+ const cfaOn = platform === "win32" && (code === "EPERM" || code === "EACCES")
+ ? await (options.cfa ?? (() => controlledFolderAccessOn()))().catch(() => false)
+ : false;
+ const reason = classifyFailure(outcome, { platform, dir, env, cfaOn, readOnlyMode, engineBin });
+ const codeText = outcome.code ? ` (${outcome.code})` : "";
+ return {
+ ok: false,
+ via,
+ reason,
+ code: outcome.code,
+ step: outcome.step,
+ message: `OmniRush can't write to ${dir}: ${WHY[reason]}${codeText}.`,
+ hint: fixHint(reason, platform, engineBin),
+ };
+}
+
+// --- the gate: once per chat and folder, before its first turn ---------------------
+
+let engineBinary: string | null = null;
+/** The engine binary the server starts (embedded.ts); the probe runs it. */
+export function setWriteCheckEngine(bin: string | null | undefined): void {
+ engineBinary = bin?.trim() || null;
+}
+
+const SUCCESS_TTL_MS = 60_000;
+const checkedChats = new Set<string>();
+const recentOk = new Map<string, number>();
+const inFlight = new Map<string, Promise<FolderWriteResult>>();
+
+export function writeCheckDisabled(env: NodeJS.ProcessEnv = process.env): boolean {
+ return /^(?:0|off|false|no)$/i.test((env.OMNIRUSH_WRITE_CHECK ?? "").trim());
+}
+
+/** A prompt for the read-only plan agent edits nothing: it is never held back. */
+export function readOnlyPrompt(body: unknown): boolean {
+ return Boolean(body && typeof body === "object" && (body as { agent?: unknown }).agent === "plan");
+}
+
+/**
+ * The check for a chat's prompt in a folder: null to go on, else the failed
+ * result. A chat that passed in a folder is not checked again there; a failed
+ * folder is checked again at every prompt (the person fixed it, or not).
+ */
+export async function folderWriteGate(sessionId: string, dir: string, options: CheckOptions & { now?: () => number } = {}): Promise<Extract<FolderWriteResult, { ok: false }> | null> {
+ if (writeCheckDisabled(options.env)) return null;
+ const key = `${sessionId}\0${dir}`;
+ if (checkedChats.has(key)) return null;
+ const now = (options.now ?? Date.now)();
+ const recent = recentOk.get(dir);
+ if (recent !== undefined && now - recent < SUCCESS_TTL_MS) {
+ checkedChats.add(key);
+ return null;
+ }
+ let pending = inFlight.get(dir);
+ if (!pending) {
+ pending = checkFolderWritable(dir, { engineBin: engineBinary ?? process.env.OMNIRUSH_OPENCODE_BIN ?? null, ...options })
+ .finally(() => inFlight.delete(dir));
+ inFlight.set(dir, pending);
+ }
+ const result = await pending;
+ if (result.ok) {
+ if (checkedChats.size >= 10_000) checkedChats.clear();
+ recentOk.set(dir, now);
+ checkedChats.add(key);
+ return null;
+ }
+ recentOk.delete(dir);
+ return result;
+}
+
+export function resetFolderWriteGate(): void {
+ checkedChats.clear();
+ recentOk.clear();
+ inFlight.clear();
+}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 7f62c417..79dbe444 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -205,6 +205,7 @@ import { startCaptureService, type CaptureService } from "./capture-client.js";
import type { LateWritesGate } from "./capture-host.js";
import { buildOpencodeProxyUrl, engineTarget, turnsBeforeCapture, type EngineTarget } from "./session-upload-observer.js";
import { claimSteerId, claimedSteerIds, createSteerTracker, steerRecord } from "./turn-steer.js";
+import { FOLDER_NOT_WRITABLE, folderWriteGate, readOnlyPrompt } from "./folder-write-check.js";
import { AutoCompactor, type AutoCompactOutcome } from "./session-archive/auto-compact.js";
import { brokerAutoCompactPolicy, desktopAutoCompactEngine } from "./auto-compact-engine.js";
import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
@@ -922,6 +923,29 @@ export function assertUploadDispatchAllowed(config: ServerConfig, workspace: Wor
}
}
+/**
+ * The project folder's write check (folder-write-check.ts) before a chat's
+ * first turn there: a folder the engine cannot write to stops the prompt with
+ * the reason and the fix instead of letting the agent run turns that change
+ * nothing. Prompts for the read-only plan agent go on.
+ */
+async function folderWriteRefusal(config: ServerConfig, workspace: WorkspaceInfo, sessionId: string, request: Request): Promise<Response | null> {
+ const dir = resolveOpencodeDirectory(workspace) ?? workspace.path;
+ if (!dir) return null;
+ const body: unknown = await request.clone().json().catch(() => null);
+ if (readOnlyPrompt(body)) return null;
+ const failed = await folderWriteGate(sessionId, dir).catch(() => null);
+ if (!failed) return null;
+ createServerLogger(config).log("warn", "Project folder is not writable.", {
+ "folder_write.reason": failed.reason,
+ "folder_write.code": failed.code ?? "",
+ "folder_write.step": failed.step,
+ "folder_write.via": failed.via,
+ });
+ await request.arrayBuffer().catch(() => undefined);
+ return jsonResponse({ error: FOLDER_NOT_WRITABLE, reason: failed.reason, message: failed.message, hint: failed.hint }, 409);
+}
+
// The v2 daemon's dispatch routes, matched on the decoded path like the v1 classifier.
function isUploadV2PromptDispatch(method: string, routePath: string): boolean {
return method === "POST" && /^\/api\/session\/[^/]+\/(?:prompt|prompt_async|command|generate)$/.test(routePath.replace(/\/+$/, ""));
@@ -1769,6 +1793,8 @@ export async function proxyOpencodeV2Request(input: {
await input.request.arrayBuffer().catch(() => undefined);
return jsonResponse({ error: "invalid_session_id", message: "The session identifier is not valid." }, 400);
}
+ const notWritable = await folderWriteRefusal(input.config, input.workspace, sessionId, input.request);
+ if (notWritable) return notWritable;
await awaitOmniRushModelCatalogSettled(input.config);
}
// The agent works from here (the prompt is on its way) until the engine runs no session.
@@ -2200,6 +2226,8 @@ export async function proxyOpencodeRequest(input: {
await input.request.arrayBuffer().catch(() => undefined);
return jsonResponse({ error: "invalid_session_id", message: "The session identifier is not valid." }, 400);
}
+ const notWritable = await folderWriteRefusal(input.config, workspace, uploadSessionId(proxyPath, method) ?? "", input.request);
+ if (notWritable) return notWritable;
// A prompt right after launch waits (briefly) for the first model catalog
// sync: the engine must know the account's models before the turn starts.
await awaitOmniRushModelCatalogSettled(input.config);