Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(server): settings files survive Windows' transient rename errors

Samrat Talukdar52ca4526749c
diff --git a/apps/server/src/atomic-write.test.ts b/apps/server/src/atomic-write.test.ts
new file mode 100644
index 00000000..3d9ee8f8
--- /dev/null
+++ b/apps/server/src/atomic-write.test.ts
@@ -0,0 +1,240 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdir, mkdtemp, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ AtomicWriteError,
+ RENAME_RETRY_DELAYS_MS,
+ atomicWriteFs,
+ commitTempFile,
+ renameWithRetry,
+ writeFileAtomic,
+ type AtomicWriteFs,
+} from "./atomic-write.js";
+import { readSubagentModelSetting, writeSubagentModelSetting } from "./omnirush-subagent-model.js";
+import type { ServerConfig } from "./types.js";
+
+let root: string;
+
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), "omnirush-atomic-write-"));
+});
+
+afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+});
+
+function errno(code: string): NodeJS.ErrnoException {
+ const error = new Error(`${code}: operation not permitted, rename`) as NodeJS.ErrnoException;
+ error.code = code;
+ return error;
+}
+
+/** A rename that fails with `code` the first `failures` times, then renames for real. */
+function flakyRename(code: string, failures: number) {
+ const calls: Array<[string, string]> = [];
+ const renameFn = async (from: string, to: string) => {
+ calls.push([from, to]);
+ if (calls.length <= failures) throw errno(code);
+ await rename(from, to);
+ };
+ return { calls, rename: renameFn };
+}
+
+function recordingSleep() {
+ const waits: number[] = [];
+ return { waits, sleep: async (ms: number) => { waits.push(ms); } };
+}
+
+describe("writeFileAtomic", () => {
+ test("the default backoff is about 10 attempts over about 2 s", () => {
+ expect(RENAME_RETRY_DELAYS_MS.length + 1).toBe(10);
+ const total = RENAME_RETRY_DELAYS_MS.reduce((sum, ms) => sum + ms, 0);
+ expect(total).toBeGreaterThanOrEqual(1_500);
+ expect(total).toBeLessThanOrEqual(2_500);
+ });
+
+ for (const code of ["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]) {
+ test(`a rename refused with ${code} a few times is retried and the file is saved`, async () => {
+ const target = join(root, "setting.json");
+ await writeFile(target, '{"old":true}\n');
+ const flaky = flakyRename(code, 4);
+ const { waits, sleep } = recordingSleep();
+ await writeFileAtomic(target, '{"new":true}\n', { fs: { rename: flaky.rename, sleep } });
+ expect(await readFile(target, "utf8")).toBe('{"new":true}\n');
+ expect(flaky.calls).toHaveLength(5);
+ expect(waits).toEqual(RENAME_RETRY_DELAYS_MS.slice(0, 4));
+ // Every attempt renamed the same unique temp file next to the target.
+ expect(new Set(flaky.calls.map(([from]) => from)).size).toBe(1);
+ expect(flaky.calls[0]![0].startsWith(`${target}.`)).toBe(true);
+ expect(await readdir(root)).toEqual(["setting.json"]);
+ });
+ }
+
+ test("a rename that never succeeds throws the original code, removes the temp file and keeps the old content", async () => {
+ const target = join(root, "setting.json");
+ await writeFile(target, '{"old":true}\n');
+ const flaky = flakyRename("EPERM", Number.POSITIVE_INFINITY);
+ const { waits, sleep } = recordingSleep();
+ const error = await writeFileAtomic(target, '{"new":true}\n', { fs: { rename: flaky.rename, sleep } }).catch((caught: unknown) => caught);
+ expect(error).toBeInstanceOf(AtomicWriteError);
+ expect((error as AtomicWriteError).code).toBe("EPERM");
+ expect((error as AtomicWriteError).attempts).toBe(10);
+ expect((error as AtomicWriteError).message).toContain("EPERM");
+ expect((error as AtomicWriteError).message).toContain(target);
+ expect(flaky.calls).toHaveLength(10);
+ expect(waits).toEqual([...RENAME_RETRY_DELAYS_MS]);
+ expect(await readdir(root)).toEqual(["setting.json"]);
+ expect(await readFile(target, "utf8")).toBe('{"old":true}\n');
+ });
+
+ test("a temp file that is itself briefly held is still removed after a failed save", async () => {
+ const target = join(root, "setting.json");
+ let removals = 0;
+ const { sleep } = recordingSleep();
+ const error = await writeFileAtomic(target, "x", {
+ retryDelaysMs: [],
+ fs: {
+ rename: flakyRename("EPERM", 99).rename,
+ rm: async (path, options) => {
+ removals += 1;
+ if (removals <= 2) throw errno("EBUSY");
+ await rm(path, options);
+ },
+ sleep,
+ },
+ }).catch((caught: unknown) => caught);
+ expect((error as AtomicWriteError).code).toBe("EPERM");
+ expect(removals).toBe(3);
+ expect(await readdir(root)).toEqual([]);
+ });
+
+ test("an error that is not a busy file is not retried", async () => {
+ const target = join(root, "setting.json");
+ const flaky = flakyRename("EXDEV", Number.POSITIVE_INFINITY);
+ const { waits, sleep } = recordingSleep();
+ const error = await writeFileAtomic(target, "x", { fs: { rename: flaky.rename, sleep } }).catch((caught: unknown) => caught);
+ expect((error as AtomicWriteError).code).toBe("EXDEV");
+ expect(flaky.calls).toHaveLength(1);
+ expect(waits).toEqual([]);
+ expect(await readdir(root)).toEqual([]);
+ });
+
+ test("injected delays replace the default backoff", async () => {
+ const target = join(root, "setting.json");
+ const flaky = flakyRename("EBUSY", Number.POSITIVE_INFINITY);
+ const { waits, sleep } = recordingSleep();
+ const error = await writeFileAtomic(target, "x", { retryDelaysMs: [1, 2], fs: { rename: flaky.rename, sleep } }).catch((caught: unknown) => caught);
+ expect((error as AtomicWriteError).code).toBe("EBUSY");
+ expect((error as AtomicWriteError).attempts).toBe(3);
+ expect(waits).toEqual([1, 2]);
+ expect(await readdir(root)).toEqual([]);
+ });
+
+ test("the data is written, synced and closed before the rename; a failed write leaves no temp file", async () => {
+ const target = join(root, "setting.json");
+ const steps: string[] = [];
+ const fs: Partial<AtomicWriteFs> = {
+ open: async (path, flags, mode) => {
+ const handle = await atomicWriteFs.open(path, flags, mode);
+ return {
+ writeFile: async (data) => { steps.push("write"); return handle.writeFile(data); },
+ chmod: async (value) => { steps.push("chmod"); return handle.chmod(value); },
+ sync: async () => { steps.push("sync"); return handle.sync(); },
+ close: async () => { steps.push("close"); return handle.close(); },
+ };
+ },
+ rename: async (from, to) => { steps.push("rename"); await rename(from, to); },
+ };
+ await writeFileAtomic(target, "hello", { mode: 0o600, fs });
+ expect(steps).toEqual(["write", "chmod", "sync", "close", "rename"]);
+
+ const failing: Partial<AtomicWriteFs> = {
+ open: async (path, flags, mode) => {
+ const handle = await atomicWriteFs.open(path, flags, mode);
+ return { writeFile: async () => { throw errno("ENOSPC"); }, sync: () => handle.sync(), chmod: (value) => handle.chmod(value), close: () => handle.close() };
+ },
+ };
+ const error = await writeFileAtomic(target, "again", { fs: failing }).catch((caught: unknown) => caught);
+ expect((error as AtomicWriteError).code).toBe("ENOSPC");
+ expect(await readdir(root)).toEqual(["setting.json"]);
+ expect(await readFile(target, "utf8")).toBe("hello");
+ });
+
+ test.skipIf(process.platform === "win32")("keeps the mode callers ask for", async () => {
+ const target = join(root, "secret.json");
+ await writeFileAtomic(target, "{}", { mode: 0o600 });
+ expect((await stat(target)).mode & 0o777).toBe(0o600);
+ });
+
+ test("writes buffers", async () => {
+ const target = join(root, "blob.bin");
+ await writeFileAtomic(target, Buffer.from([1, 2, 3]));
+ expect([...await readFile(target)]).toEqual([1, 2, 3]);
+ });
+});
+
+describe("renameWithRetry and commitTempFile", () => {
+ test("renameWithRetry retries a busy file and leaves the source on permanent failure", async () => {
+ const from = join(root, "a.tmp");
+ const to = join(root, "a.json");
+ await writeFile(from, "1");
+ const { sleep } = recordingSleep();
+ await renameWithRetry(from, to, { fs: { rename: flakyRename("EACCES", 2).rename, sleep } });
+ expect(await readFile(to, "utf8")).toBe("1");
+
+ await writeFile(from, "2");
+ const error = await renameWithRetry(from, to, { fs: { rename: flakyRename("EPERM", 99).rename, sleep } }).catch((caught: unknown) => caught);
+ expect((error as AtomicWriteError).code).toBe("EPERM");
+ expect((await readdir(root)).sort()).toEqual(["a.json", "a.tmp"]);
+ });
+
+ test("commitTempFile removes the temp file when the rename keeps failing", async () => {
+ const temp = join(root, "b.json.123.tmp");
+ await writeFile(temp, "x");
+ const { sleep } = recordingSleep();
+ const error = await commitTempFile(temp, join(root, "b.json"), { fs: { rename: flakyRename("EBUSY", 99).rename, sleep } }).catch((caught: unknown) => caught);
+ expect((error as AtomicWriteError).code).toBe("EBUSY");
+ expect(await readdir(root)).toEqual([]);
+ });
+});
+
+describe("the sub-agent picker's setting file", () => {
+ const original = { ...atomicWriteFs };
+ let previousRuntimeDb: string | undefined;
+ let config: ServerConfig;
+
+ beforeEach(async () => {
+ previousRuntimeDb = process.env.OMNIRUSH_RUNTIME_DB;
+ process.env.OMNIRUSH_RUNTIME_DB = join(root, "runtime", "runtime.sqlite");
+ await mkdir(join(root, "runtime"), { recursive: true });
+ config = { configPath: join(root, "server.json") } as unknown as ServerConfig;
+ });
+
+ afterEach(() => {
+ Object.assign(atomicWriteFs, original);
+ if (previousRuntimeDb === undefined) delete process.env.OMNIRUSH_RUNTIME_DB;
+ else process.env.OMNIRUSH_RUNTIME_DB = previousRuntimeDb;
+ });
+
+ test("survives Windows refusing the rename a few times", async () => {
+ const flaky = flakyRename("EPERM", 3);
+ atomicWriteFs.rename = flaky.rename;
+ atomicWriteFs.sleep = async () => undefined;
+ expect(await writeSubagentModelSetting(config, { model: "gpt-6-sol", effort: "high" })).toEqual({ model: "gpt-6-sol", effort: "high" });
+ expect(flaky.calls).toHaveLength(4);
+ expect(await readSubagentModelSetting(config)).toEqual({ model: "gpt-6-sol", effort: "high" });
+ expect((await readdir(join(root, "runtime"))).filter((name) => name.endsWith(".tmp"))).toEqual([]);
+ });
+
+ test("a save that keeps failing throws with the code and keeps the previous setting", async () => {
+ await writeSubagentModelSetting(config, { model: "gpt-6-astra", effort: null });
+ atomicWriteFs.rename = flakyRename("EBUSY", 99).rename;
+ atomicWriteFs.sleep = async () => undefined;
+ const error = await writeSubagentModelSetting(config, { model: "gpt-6-sol", effort: "low" }).catch((caught: unknown) => caught);
+ expect((error as AtomicWriteError).code).toBe("EBUSY");
+ expect(await readSubagentModelSetting(config)).toEqual({ model: "gpt-6-astra", effort: null });
+ expect((await readdir(join(root, "runtime"))).filter((name) => name.endsWith(".tmp"))).toEqual([]);
+ });
+});
diff --git a/apps/server/src/atomic-write.ts b/apps/server/src/atomic-write.ts
new file mode 100644
index 00000000..e2c206d9
--- /dev/null
+++ b/apps/server/src/atomic-write.ts
@@ -0,0 +1,186 @@
+/**
+ * Atomic replacement of small settings and state files.
+ *
+ * Every write goes to a unique temp file next to the target, is flushed to
+ * disk (open, write, fsync, close), then renamed over the target, so a reader
+ * sees either the old content or the new one, never a partial file.
+ *
+ * On Windows, replacing a file fails for a moment while another process has
+ * it (or the new temp file) open without delete sharing: antivirus, the
+ * search indexer, a backup agent, a concurrent reader. The rename then fails
+ * with EPERM, EBUSY or EACCES (ENOTEMPTY for a directory in the way), and
+ * clears on its own within milliseconds to a second or so. The rename is
+ * retried with backoff (about 2 s in all) before giving up, and the temp file
+ * is removed whatever happens.
+ */
+import { randomBytes } from "node:crypto";
+import { open, rename, rm } from "node:fs/promises";
+import { platform } from "node:os";
+
+/** Codes a rename fails with while another process briefly holds the file. */
+export const TRANSIENT_RENAME_CODES: ReadonlySet<string> = new Set(["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]);
+
+/** Waits between rename attempts: 10 attempts over about 2 s. */
+export const RENAME_RETRY_DELAYS_MS: readonly number[] = [20, 40, 80, 120, 180, 250, 330, 430, 550];
+
+/** Waits between attempts to remove a temp file that is itself briefly held. */
+const REMOVE_RETRY_DELAYS_MS: readonly number[] = [20, 50, 100, 200];
+
+type OpenedFile = {
+ writeFile(data: string | Uint8Array): Promise<void>;
+ sync(): Promise<void>;
+ chmod(mode: number): Promise<void>;
+ close(): Promise<void>;
+};
+
+/** The file operations the helper uses; tests swap them to simulate a busy file. */
+export type AtomicWriteFs = {
+ open(path: string, flags: string, mode?: number): Promise<OpenedFile>;
+ rename(from: string, to: string): Promise<void>;
+ rm(path: string, options: { force: boolean }): Promise<void>;
+ sleep(ms: number): Promise<void>;
+};
+
+/**
+ * The process-wide defaults. Tests (and only tests) may replace members to
+ * simulate transient or permanent failures; always restore them afterwards.
+ */
+export const atomicWriteFs: AtomicWriteFs = {
+ open: (path, flags, mode) => open(path, flags, mode),
+ rename: (from, to) => rename(from, to),
+ rm: (path, options) => rm(path, options),
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+};
+
+export type RenameRetryOptions = {
+ /** Waits between attempts; defaults to RENAME_RETRY_DELAYS_MS. */
+ retryDelaysMs?: readonly number[];
+ /** Replaces some of the file operations (tests). */
+ fs?: Partial<AtomicWriteFs>;
+};
+
+export type AtomicWriteOptions = RenameRetryOptions & {
+ /** File mode for the new file (e.g. 0o600 for files holding secrets); applied before the rename. */
+ mode?: number;
+};
+
+/** A write that still failed after the retries; `code` is the original errno code. */
+export class AtomicWriteError extends Error {
+ readonly code: string;
+ readonly path: string;
+ readonly attempts: number;
+
+ constructor(path: string, code: string, attempts: number, cause: unknown) {
+ const detail = cause instanceof Error ? cause.message : String(cause);
+ super(
+ attempts > 1
+ ? `Could not save ${path}: ${code} (the file stayed busy after ${attempts} attempts): ${detail}`
+ : `Could not save ${path}: ${code}: ${detail}`,
+ { cause },
+ );
+ this.name = "AtomicWriteError";
+ this.code = code;
+ this.path = path;
+ this.attempts = attempts;
+ }
+}
+
+export function errorCode(error: unknown): string {
+ if (typeof error === "object" && error !== null && "code" in error && typeof (error as { code: unknown }).code === "string") {
+ return (error as { code: string }).code;
+ }
+ return "EUNKNOWN";
+}
+
+function resolveFs(options: RenameRetryOptions | undefined): AtomicWriteFs {
+ return options?.fs ? { ...atomicWriteFs, ...options.fs } : atomicWriteFs;
+}
+
+/** A unique temp path next to `path` (same directory, so the rename never crosses filesystems). */
+export function atomicTempPath(path: string): string {
+ return `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
+}
+
+async function renameAttempts(from: string, to: string, fs: AtomicWriteFs, delays: readonly number[]): Promise<void> {
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ await fs.rename(from, to);
+ return;
+ } catch (error) {
+ const code = errorCode(error);
+ const delay = delays[attempt];
+ if (delay === undefined || !TRANSIENT_RENAME_CODES.has(code)) {
+ throw new AtomicWriteError(to, code, attempt + 1, error);
+ }
+ await fs.sleep(delay);
+ }
+ }
+}
+
+/** Removes a temp file; the same busy-file errors that stop a rename are retried briefly. Never throws. */
+async function removeTemp(temp: string, fs: AtomicWriteFs): Promise<void> {
+ for (const delay of [...REMOVE_RETRY_DELAYS_MS, undefined]) {
+ try {
+ await fs.rm(temp, { force: true });
+ return;
+ } catch (error) {
+ if (delay === undefined || !TRANSIENT_RENAME_CODES.has(errorCode(error))) return;
+ await fs.sleep(delay);
+ }
+ }
+}
+
+/**
+ * Renames `from` over `to`, retrying while Windows reports the file busy.
+ * Throws AtomicWriteError (with the original code) when it still fails;
+ * `from` is left in place for the caller to clean up or reuse.
+ */
+export async function renameWithRetry(from: string, to: string, options?: RenameRetryOptions): Promise<void> {
+ await renameAttempts(from, to, resolveFs(options), options?.retryDelaysMs ?? RENAME_RETRY_DELAYS_MS);
+}
+
+/**
+ * Moves an already written (and synced) temp file over `path` with retries,
+ * removing the temp file when that fails. For writers that stream their own
+ * temp file.
+ */
+export async function commitTempFile(temp: string, path: string, options?: RenameRetryOptions): Promise<void> {
+ const fs = resolveFs(options);
+ try {
+ await renameAttempts(temp, path, fs, options?.retryDelaysMs ?? RENAME_RETRY_DELAYS_MS);
+ } catch (error) {
+ await removeTemp(temp, fs);
+ throw error;
+ }
+}
+
+/**
+ * Replaces `path` with `data` atomically: unique temp file, fsync, rename
+ * with retry. The parent directory must exist. Throws AtomicWriteError (the
+ * original errno code on `.code`) when it fails; no temp file is left behind.
+ */
+export async function writeFileAtomic(path: string, data: string | Uint8Array, options?: AtomicWriteOptions): Promise<void> {
+ const fs = resolveFs(options);
+ const temp = atomicTempPath(path);
+ try {
+ const handle = await fs.open(temp, "wx", options?.mode);
+ try {
+ await handle.writeFile(data);
+ if (options?.mode !== undefined) {
+ // The process umask may have narrowed the mode; chmod is a no-op on Windows.
+ await handle.chmod(options.mode).catch((error: unknown) => {
+ if (platform() !== "win32") throw error;
+ });
+ }
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+ await renameAttempts(temp, path, fs, options?.retryDelaysMs ?? RENAME_RETRY_DELAYS_MS);
+ } catch (error) {
+ await removeTemp(temp, fs);
+ if (error instanceof AtomicWriteError) throw error;
+ // Creating or writing the temp file failed: no rename was attempted.
+ throw new AtomicWriteError(path, errorCode(error), 0, error);
+ }
+}
diff --git a/apps/server/src/engine-registry.ts b/apps/server/src/engine-registry.ts
index 0c4f278c..5581a178 100644
--- a/apps/server/src/engine-registry.ts
+++ b/apps/server/src/engine-registry.ts
@@ -14,13 +14,13 @@
* prove the port now belongs to someone else.
*/
import { spawnSync } from "node:child_process";
-import { randomUUID } from "node:crypto";
-import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { mkdir, readFile } from "node:fs/promises";
import { basename, join } from "node:path";
import { runtimeStorageDir } from "./runtime-db.js";
import { loopbackFetch } from "./server-fetch.js";
import type { ServerConfig } from "./types.js";
+import { writeFileAtomic } from "./atomic-write.js";
export type EngineInstanceRole = "starting" | "primary" | "draining";
@@ -128,13 +128,9 @@ async function mutateRegistry(
const entries = mutate(await readRegistryFile(path));
const payload: EngineRegistryFile = { version: 1, entries };
await mkdir(runtimeStorageDir(config), { recursive: true });
- const tmp = `${path}.${randomUUID()}.tmp`;
// 0600: the auth probe header embeds this spawn's engine credentials.
- await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
- await rename(tmp, path).catch(async (error) => {
- await rm(tmp, { force: true }).catch(() => undefined);
- throw error;
- });
+ // A failed write leaves no temp file behind and rejects this job only.
+ await writeFileAtomic(path, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
return entries;
};
const previous = registryWriteQueue.get(path) ?? Promise.resolve();
diff --git a/apps/server/src/env-file.ts b/apps/server/src/env-file.ts
index c1d92408..df67df0e 100644
--- a/apps/server/src/env-file.ts
+++ b/apps/server/src/env-file.ts
@@ -1,8 +1,8 @@
import { platform } from "node:os";
-import { chmod, readFile, rename, rm, writeFile } from "node:fs/promises";
-import { dirname, join, resolve } from "node:path";
+import { chmod, readFile } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
import { omnirushEnvStorePath } from "@omnirush/paths";
-
+import { writeFileAtomic } from "./atomic-write.js";
import { ensureDir, exists } from "./utils.js";
// User-level environment variables, persisted so the desktop shell can inject
@@ -119,30 +119,9 @@ async function writeStore(path: string, variables: EnvRecord[]): Promise<void> {
updatedAt: Date.now(),
variables,
};
- const tempPath = join(
- dir,
- `.env.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
- );
- await writeFile(tempPath, JSON.stringify(payload, null, 2) + "\n", {
- encoding: "utf8",
- flag: "wx",
- mode: 0o600,
- });
- try {
- await chmod(tempPath, 0o600);
- } catch (error) {
- // chmod is a no-op on Windows; values may still contain secrets.
- if (platform() !== "win32") {
- await rm(tempPath, { force: true }).catch(() => {});
- throw error;
- }
- }
- try {
- await rename(tempPath, path);
- } catch (error) {
- await rm(tempPath, { force: true }).catch(() => {});
- throw error;
- }
+ // 0600 on the temp file before it replaces the store (values may be
+ // secrets); a failed write leaves no temp file behind.
+ await writeFileAtomic(path, JSON.stringify(payload, null, 2) + "\n", { mode: 0o600 });
try {
await chmod(path, 0o600);
} catch (error) {
diff --git a/apps/server/src/local-managed-mcp.ts b/apps/server/src/local-managed-mcp.ts
index 9d24d611..db05ddcc 100644
--- a/apps/server/src/local-managed-mcp.ts
+++ b/apps/server/src/local-managed-mcp.ts
@@ -7,7 +7,7 @@ import {
randomUUID,
timingSafeEqual,
} from "node:crypto";
-import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { chmod, mkdir, readFile, rename } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import {
OAuthError,
@@ -51,6 +51,7 @@ import {
createLocalManagedMcpGuardedFetch,
LocalManagedMcpPrivateUrlError,
} from "./local-managed-mcp-url-guard.js";
+import { writeFileAtomic } from "./atomic-write.js";
type LocalManagedMcpStatus = "needs_auth" | "connecting" | "connected" | "reconnect_required";
@@ -360,9 +361,7 @@ async function writeVault(
...(lastRecovery ? { lastRecovery } : {}),
};
await mkdir(dirname(path), { recursive: true });
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
- await writeFile(temporary, `${JSON.stringify(file)}\n`, { encoding: "utf8", mode: 0o600 });
- await rename(temporary, path);
+ await writeFileAtomic(path, `${JSON.stringify(file)}\n`, { mode: 0o600 });
await chmod(path, 0o600).catch(() => undefined);
}
diff --git a/apps/server/src/local-workflows.ts b/apps/server/src/local-workflows.ts
index 463759f9..fed9bd7c 100644
--- a/apps/server/src/local-workflows.ts
+++ b/apps/server/src/local-workflows.ts
@@ -1,5 +1,5 @@
import { createHash, randomUUID } from "node:crypto";
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { mkdir, readFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { omnirushServerDataDir } from "@omnirush/paths";
import type { LocalAvailableModel, LocalModelRef, LocalRouteCategory, LocalRouteDecision, LocalRoutingSettings, LocalWorkflow, LocalWorkflowInput, LocalWorkflowRun, LocalWorkflowRunStep, LocalWorkflowState, LocalWorkflowsSnapshot } from "@omnirush/types/local-workflows";
@@ -9,6 +9,7 @@ import { recordAudit } from "./audit.js";
import type { Actor, ServerConfig, WorkspaceInfo } from "./types.js";
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
import type { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
+import { writeFileAtomic } from "./atomic-write.js";
type Engine = ReturnType<typeof createOpencodeClient>;
type EngineFactory = (config: ServerConfig, workspace: WorkspaceInfo, options?: { sessionId?: string }) => Engine;
@@ -114,8 +115,7 @@ export class LocalWorkflowService {
}
private async persist(workspace: WorkspaceInfo, state: LocalWorkflowState): Promise<void> {
const path = this.path(workspace); await mkdir(dirname(path), { recursive: true, mode: 0o700 });
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
- await writeFile(temporary, JSON.stringify(state), { encoding: "utf8", mode: 0o600 }); await rename(temporary, path);
+ await writeFileAtomic(path, JSON.stringify(state), { mode: 0o600 });
}
private async mutate<T>(workspace: WorkspaceInfo, fn: (state: LocalWorkflowState) => T): Promise<T> {
const prior = this.queues.get(workspace.id) ?? Promise.resolve();
diff --git a/apps/server/src/managed-opencode-v2.ts b/apps/server/src/managed-opencode-v2.ts
index d8c9c2dd..22f53da7 100644
--- a/apps/server/src/managed-opencode-v2.ts
+++ b/apps/server/src/managed-opencode-v2.ts
@@ -4,12 +4,13 @@ import type { EnginePermissionRule } from "./managed-policy-rules.js";
// deliberately has no reload/dispose call, unlike managed-opencode.ts and server.ts reloadOpencodeEngine.
import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
-import { chmod, mkdir, rename, writeFile } from "node:fs/promises";
+import { chmod, mkdir } from "node:fs/promises";
import { join } from "node:path";
export { installOpencodeV2Binary } from "./opencode-v2-binary.js";
import { loopbackFetch } from "./server-fetch.js";
+import { writeFileAtomic } from "./atomic-write.js";
export interface OpencodeV2ModelSpec {
id: string;
@@ -215,14 +216,12 @@ export async function createManagedOpencodeV2Server(
};
}
const target = join(configDir, "opencode.json");
- const temporary = `${target}.tmp-${randomBytes(8).toString("hex")}`;
- await writeFile(temporary, `${JSON.stringify({
+ await writeFileAtomic(target, `${JSON.stringify({
$schema: "https://opencode.ai/config.json",
providers: providerConfig,
...(options.permissions ? { permissions: await options.permissions() } : {}),
...(options.env?.OMNIRUSH_SERVER_URL ? { plugins: [managedPolicyPluginPath(true)] } : {}),
}, null, 2)}\n`, { mode: 0o600 });
- await rename(temporary, target);
}
async function close(): Promise<void> {
diff --git a/apps/server/src/omnirush-model-catalog.ts b/apps/server/src/omnirush-model-catalog.ts
index 95fa343e..6e98e21c 100644
--- a/apps/server/src/omnirush-model-catalog.ts
+++ b/apps/server/src/omnirush-model-catalog.ts
@@ -12,12 +12,12 @@
* Without one (first run, offline, or a backend that fails) the engine gets
* the built-in Astra, GPT 6 Sol and GPT-5.6 Sol (the v1.0.9 metadata).
*/
-import { randomUUID } from "node:crypto";
-import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { mkdir, readFile, rm } from "node:fs/promises";
import { join } from "node:path";
import { runtimeStorageDir } from "./runtime-db.js";
import type { ServerConfig } from "./types.js";
+import { writeFileAtomic } from "./atomic-write.js";
/** Every effort a catalog model may list, lowest first. */
export const OMNIRUSH_MODEL_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
@@ -199,9 +199,7 @@ export async function readOmniRushModelCatalog(config: ServerConfig): Promise<Om
export async function writeOmniRushModelCatalog(config: ServerConfig, catalog: OmniRushModelCatalog): Promise<void> {
const path = omnirushModelCatalogPath(config);
await mkdir(runtimeStorageDir(config), { recursive: true });
- const tmp = `${path}.${randomUUID()}.tmp`;
- await writeFile(tmp, `${JSON.stringify({ data: catalog }, null, 2)}\n`, "utf8");
- await rename(tmp, path);
+ await writeFileAtomic(path, `${JSON.stringify({ data: catalog }, null, 2)}\n`);
}
export async function clearOmniRushModelCatalog(config: ServerConfig): Promise<void> {
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index 618f88e0..404949e0 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -15,9 +15,8 @@ import { managedPolicyPluginPath } from "./managed-policy-plugin.js";
* runtime-DB write — unlike the previous OPENCODE_CONFIG_CONTENT env var,
* which was frozen at spawn and reverted MCP state on each dispose.
*/
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
-import { randomUUID } from "node:crypto";
import {
omnirushExtensionsPreviewPluginPath,
omnirushCapabilitiesKnowledgePluginPath,
@@ -54,6 +53,7 @@ import {
readOmniRushModelCatalog,
type OmniRushModelCatalog,
} from "./omnirush-model-catalog.js";
+import { writeFileAtomic } from "./atomic-write.js";
const INTERNAL_PROVIDER_ID = "omnirush";
@@ -151,9 +151,7 @@ async function writeOmniRushRuntimeSkills(config: ServerConfig): Promise<void> {
const content = omnirushSwarmSkillMarkdown();
if ((await readFile(path, "utf8").catch(() => undefined)) === content) return;
await mkdir(directory, { recursive: true });
- const tmp = `${path}.${randomUUID()}.tmp`;
- await writeFile(tmp, content, "utf8");
- await rename(tmp, path);
+ await writeFileAtomic(path, content);
}
export function buildOmniRushRuntimeConfigObjectFromSnapshot(
@@ -301,9 +299,7 @@ export async function writeOmniRushRuntimeConfigFile(
const current = await readFile(path, "utf8").catch(() => undefined);
if (current === content) return { path, changed: false };
await mkdir(runtimeStorageDir(config), { recursive: true });
- const tmp = `${path}.${randomUUID()}.tmp`;
- await writeFile(tmp, content, "utf8");
- await rename(tmp, path);
+ await writeFileAtomic(path, content);
return { path, changed: true };
};
const previous = fileWriteQueue.get(path) ?? Promise.resolve();
diff --git a/apps/server/src/omnirush-subagent-model.ts b/apps/server/src/omnirush-subagent-model.ts
index 7f4fc0eb..aae5d055 100644
--- a/apps/server/src/omnirush-subagent-model.ts
+++ b/apps/server/src/omnirush-subagent-model.ts
@@ -24,10 +24,10 @@
*
* Kept free of engine-plugin imports; the plugin talks to it over HTTP.
*/
-import { randomUUID } from "node:crypto";
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
+import { writeFileAtomic } from "./atomic-write.js";
import {
OMNIRUSH_MODEL_EFFORTS,
type OmniRushModelCatalog,
@@ -119,14 +119,17 @@ export async function readSubagentModelSetting(config: ServerConfig): Promise<Su
}
}
-/** Atomic (temp file + rename), so a resolve never reads a partial file. */
+/**
+ * Atomic (temp file, fsync, rename), so a resolve never reads a partial file.
+ * The rename is retried while Windows reports the file busy; a save that
+ * still fails throws an AtomicWriteError (the errno code on `.code`) and
+ * leaves the previous setting in place.
+ */
export async function writeSubagentModelSetting(config: ServerConfig, setting: SubagentModelSetting): Promise<SubagentModelSetting> {
const clean = sanitizeSubagentModelSetting(setting);
const path = subagentModelSettingPath(config);
await mkdir(runtimeStorageDir(config), { recursive: true });
- const tmp = `${path}.${randomUUID()}.tmp`;
- await writeFile(tmp, `${JSON.stringify(clean, null, 2)}\n`, "utf8");
- await rename(tmp, path);
+ await writeFileAtomic(path, `${JSON.stringify(clean, null, 2)}\n`);
return clean;
}
diff --git a/apps/server/src/routes/workspaces.ts b/apps/server/src/routes/workspaces.ts
index e06a95dd..c67342fe 100644
--- a/apps/server/src/routes/workspaces.ts
+++ b/apps/server/src/routes/workspaces.ts
@@ -1,7 +1,8 @@
-import { readFile, rename, rm, writeFile } from "node:fs/promises";
+import { readFile } from "node:fs/promises";
import { basename, dirname, resolve } from "node:path";
import { recordAudit } from "../audit.js";
import { ApiError } from "../errors.js";
+import { writeFileAtomic } from "../atomic-write.js";
import { inheritWorkspaceOpencodeConnection, resolveWorkspaceOpencodeConnection } from "../opencode-connection.js";
import { externalFetch } from "../server-fetch.js";
import type { ServerConfig, WorkspaceInfo } from "../types.js";
@@ -219,27 +220,6 @@ function serializeWorkspaceConfigEntry(workspace: WorkspaceInfo): Record<string,
};
}
-const RENAME_RETRY_DELAYS_MS = [50, 150, 400, 1_000];
-
-/**
- * Windows refuses to replace a file another process has open for a moment
- * (antivirus, indexer, a concurrent reader): EPERM, EACCES or EBUSY. Those
- * clear on their own; a registry change must not be lost to one.
- */
-async function renameWithRetry(from: string, to: string): Promise<void> {
- for (let attempt = 0; ; attempt += 1) {
- try {
- await rename(from, to);
- return;
- } catch (error) {
- const code = isRecord(error) && typeof error.code === "string" ? error.code : "";
- const delay = RENAME_RETRY_DELAYS_MS[attempt];
- if (delay === undefined || !["EPERM", "EACCES", "EBUSY"].includes(code)) throw error;
- await new Promise((resolveDelay) => setTimeout(resolveDelay, delay));
- }
- }
-}
-
async function persistServerWorkspaceState(config: ServerConfig): Promise<boolean> {
const configPath = config.configPath?.trim() ?? "";
if (!configPath) return false;
@@ -252,18 +232,10 @@ async function persistServerWorkspaceState(config: ServerConfig): Promise<boolea
};
await ensureDir(dirname(configPath));
- const tmpPath = `${configPath}.tmp.${shortId()}`;
- try {
- await writeFile(tmpPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
- await renameWithRetry(tmpPath, configPath);
- return true;
- } finally {
- try {
- await rm(tmpPath);
- } catch {
- // ignore
- }
- }
+ // Retried while Windows (antivirus, indexer, a concurrent reader) holds
+ // the file for a moment: a registry change must not be lost to that.
+ await writeFileAtomic(configPath, `${JSON.stringify(next, null, 2)}\n`);
+ return true;
}
export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions): void {
diff --git a/apps/server/src/session-archive/files.ts b/apps/server/src/session-archive/files.ts
index 681e6905..06891bf9 100644
--- a/apps/server/src/session-archive/files.ts
+++ b/apps/server/src/session-archive/files.ts
@@ -1,6 +1,8 @@
-/** Durable state files for the archiver: every write goes to a temp name, is fsynced, then renamed. */
+/** Durable state files for the archiver: every write goes to a temp name, is fsynced, then renamed (with retry). */
import { createHash, randomBytes } from "node:crypto";
-import { open, readFile, rename, rm } from "node:fs/promises";
+import { open, readFile, rm } from "node:fs/promises";
+
+import { commitTempFile } from "../atomic-write.js";
/** The first 32 hex characters of SHA-256(text): state file names for session ids and root paths. */
export function stateKey(text: string): string {
@@ -42,12 +44,8 @@ export async function writeChunksAtomic(path: string, chunks: Iterable<string>):
throw error;
}
await handle.close();
- try {
- await rename(temp, path);
- } catch (error) {
- await rm(temp, { force: true });
- throw error;
- }
+ // Retried while Windows reports the target busy; the temp file is removed if it still fails.
+ await commitTempFile(temp, path);
}
export function writeJsonAtomic(path: string, value: unknown): Promise<void> {
diff --git a/apps/server/src/turn-diff.ts b/apps/server/src/turn-diff.ts
index 1eb28d14..e1eef2a2 100644
--- a/apps/server/src/turn-diff.ts
+++ b/apps/server/src/turn-diff.ts
@@ -9,8 +9,9 @@
* Everything here runs on the capture worker (see capture-host.ts).
*/
import { createHash } from "node:crypto";
-import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
+import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
+import { writeFileAtomic } from "./atomic-write.js";
/** A file diff is cut at this many bytes (as JSON-encoded in the event). */
export const MAX_TURN_DIFF_FILE_BYTES = 256 * 1024;
@@ -616,8 +617,7 @@ export class TurnBaseStore {
this.saveTail = this.saveTail.then(async () => {
if (generation !== this.generation) return;
await mkdir(dir, { recursive: true, mode: 0o700 });
- await writeFile(join(dir, `${BASE_INDEX_FILE}.tmp`), index, { mode: 0o600 });
- await rename(join(dir, `${BASE_INDEX_FILE}.tmp`), join(dir, BASE_INDEX_FILE));
+ await writeFileAtomic(join(dir, BASE_INDEX_FILE), index, { mode: 0o600 });
}).catch(() => undefined);
return this.saveTail;
}
diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.ts
index c623011f..67ca1431 100644
--- a/apps/server/src/workspace-collector.ts
+++ b/apps/server/src/workspace-collector.ts
@@ -1,7 +1,7 @@
import { createHash, randomBytes } from "node:crypto";
import { execFile, spawn } from "node:child_process";
import { createReadStream, createWriteStream, watch, type FSWatcher, type WriteStream } from "node:fs";
-import { lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
+import { lstat, mkdir, open, readFile, readdir, rename, rm, stat } from "node:fs/promises";
import { release as osRelease, tmpdir } from "node:os";
import nodePath, { basename, dirname, extname, join, relative, resolve, sep, type PlatformPath } from "node:path";
import { promisify } from "node:util";
@@ -12,6 +12,7 @@ import { COLLECT_UPLOAD_BUDGET, collectUploadTimeoutMs, type CollectUploadBudget
import { externalFetch } from "./server-fetch.js";
import { TurnBaseStore, TurnDiffBuilder, type TurnDiffInput } from "./turn-diff.js";
import { SUBAGENT_MODEL_FALLBACK_TRACE } from "./omnirush-swarm.js";
+import { writeFileAtomic } from "./atomic-write.js";
const execFileAsync = promisify(execFile);
@@ -2959,15 +2960,8 @@ function spoolId(counter: number): string {
return `${Date.now().toString(16).padStart(12, "0")}-${counter.toString(16).padStart(6, "0")}-${randomBytes(4).toString("hex")}`;
}
-async function writeFileAtomic(path: string, data: Buffer | string): Promise<void> {
- const temporary = `${path}.${randomBytes(4).toString("hex")}.tmp`;
- await writeFile(temporary, data, { mode: 0o600 });
- try {
- await rename(temporary, path);
- } catch (error) {
- await rm(temporary, { force: true }).catch(() => undefined);
- throw error;
- }
+function writePrivateFileAtomic(path: string, data: Buffer | string): Promise<void> {
+ return writeFileAtomic(path, data, { mode: 0o600 });
}
function parseSpoolMeta(value: unknown): SpoolMeta | null {
@@ -3106,7 +3100,7 @@ export class WorkspaceCollector {
.catch(() => undefined)
.then(async () => {
await mkdir(dirname(this.ledgerPath!), { recursive: true, mode: 0o700 });
- await writeFileAtomic(this.ledgerPath!, snapshot);
+ await writePrivateFileAtomic(this.ledgerPath!, snapshot);
});
await this.ledgerWriteTail;
}
@@ -4795,7 +4789,7 @@ export class WorkspaceCollector {
}
private async writeSpoolMeta(meta: SpoolMeta): Promise<void> {
- await writeFileAtomic(join(this.spoolDir!, `${meta.id}.json`), JSON.stringify(meta));
+ await writePrivateFileAtomic(join(this.spoolDir!, `${meta.id}.json`), JSON.stringify(meta));
}
/**
@@ -4816,7 +4810,7 @@ export class WorkspaceCollector {
try {
await rename(sourcePath, target);
} catch {
- await writeFileAtomic(target, await readFile(sourcePath));
+ await writePrivateFileAtomic(target, await readFile(sourcePath));
}
await this.writeSpoolMeta({ ...meta, id });
await this.enforceSpoolBounds();