Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(sync): serialize concurrent cloud file mutations
Sebastian Bfa748e22445b
diff --git a/server/cloud-sync-concurrent.test.ts b/server/cloud-sync-concurrent.test.tsnew file mode 100644index 0000000000..ff67bc3a2a--- /dev/null+++ b/server/cloud-sync-concurrent.test.ts@@ -0,0 +1,203 @@+import { createHash } from "node:crypto";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { setImmediate } from "node:timers/promises";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import * as files from "./cloud-sync-store.ts";+import { createCloudSync, type CloudSync } from "./cloud-sync.ts";++const PC = "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93";+const sha = (text: string) => createHash("sha256").update(text).digest("hex");+let home: string, sync: CloudSync, folder: files.SyncFolder;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "omb-sync-concurrent-"));+ sync = createCloudSync({ dataDir: join(home, "data"), root: join(home, "Synced"), now: () => new Date(2026, 9, 15, 12).getTime() });+ folder = sync.register({ computerId: PC, computerName: "PC", pcPath: "/project", name: "Project" });+});+afterEach(() => {+ vi.restoreAllMocks();+ sync.close();+ rmSync(home, { recursive: true, force: true });+});++async function upload(text: string, baseSha256: string | null, path = "a.txt", folderId = folder.id) {+ const { uploadId } = sync.beginUpload(folderId, { path, size: Buffer.byteLength(text), sha256: sha(text), baseSha256 });+ await sync.writePart(uploadId, 0, (async function* () { yield Buffer.from(text); })());+ return uploadId;+}++function gate() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => { resolve = done; });+ return { promise, resolve };+}++function holdCurrent() {+ const entered = gate(), release = gate();+ const current = sync.store.current.bind(sync.store);+ vi.spyOn(sync.store, "current").mockImplementationOnce(async (...args) => {+ const file = await current(...args);+ entered.resolve();+ await release.promise;+ return file;+ });+ return { entered: entered.promise, release: release.resolve };+}++async function checkedCommit(uploadId: string) {+ const checked = gate();+ const hash = files.sha256File;+ const spy = vi.spyOn(files, "sha256File").mockImplementation(async (path) => {+ const result = await hash(path);+ if (path === join(sync.store.syncDir(), "uploads", `${uploadId}.part`)) checked.resolve();+ return result;+ });+ const outcome = Promise.allSettled([sync.commit(uploadId)]);+ await checked.promise;+ await setImmediate();+ spy.mockRestore();+ return { outcome };+}++it("accepts only one competing commit over the same uncached version", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ const firstId = await upload("first", sha("original")), secondId = await upload("second", sha("original"));+ const held = holdCurrent();+ const first = sync.commit(firstId);+ await held.entered;+ const second = await checkedCommit(secondId);+ held.release();+ expect(await first).toEqual({ sha256: sha("first") });+ expect(await second.outcome).toMatchObject([{ status: "rejected", reason: { status: 409, body: { current: { sha256: sha("first") } } } }]);+ expect(readFileSync(join(folder.cloudPath, "a.txt"), "utf8")).toBe("first");+ expect(sync.trash().entries).toHaveLength(1);+ expect(readFileSync(sync.store.trashEntry(sync.trash().entries[0]!.id)!.file, "utf8")).toBe("original");+ expect(await sync.commit(await upload("third", sha("first")))).toEqual({ sha256: sha("third") });+});++it("checks a competing delete against the committed version", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ const id = await upload("first", sha("original"));+ const held = holdCurrent();+ const committed = sync.commit(id);+ await held.entered;+ const deleted = sync.ops(folder.id, { ops: [{ op: "delete", path: "a.txt", baseSha256: sha("original") }] });+ await setImmediate();+ held.release();+ await committed;+ expect(await deleted).toMatchObject({ results: [{ conflict: true, current: { sha256: sha("first") } }] });+ expect(readFileSync(join(folder.cloudPath, "a.txt"), "utf8")).toBe("first");+});++it("rejects a competing commit after a delete removes its base version", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ const id = await upload("first", sha("original"));+ const held = holdCurrent();+ const deleted = sync.ops(folder.id, { ops: [{ op: "delete", path: "a.txt", baseSha256: sha("original") }] });+ await held.entered;+ const committed = await checkedCommit(id);+ held.release();+ expect(await deleted).toEqual({ results: [{ ok: true }] });+ expect(await committed.outcome).toMatchObject([{ status: "rejected", reason: { status: 409, body: { current: null } } }]);+ expect(existsSync(join(folder.cloudPath, "a.txt"))).toBe(false);+});++it("accepts competing deletes without moving the same file twice", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ const held = holdCurrent();+ const ops = { ops: [{ op: "delete", path: "a.txt", baseSha256: sha("original") }] };+ const first = Promise.allSettled([sync.ops(folder.id, ops)]);+ await held.entered;+ const second = Promise.allSettled([sync.ops(folder.id, ops)]);+ await setImmediate();+ held.release();+ expect(await first).toMatchObject([{ status: "fulfilled", value: { results: [{ ok: true }] } }]);+ expect(await second).toMatchObject([{ status: "fulfilled", value: { results: [{ ok: true }] } }]);+ expect(sync.trash().entries).toHaveLength(1);+});++it("restores beside a commit that was checking an empty destination", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ await sync.ops(folder.id, { ops: [{ op: "delete", path: "a.txt", baseSha256: sha("original") }] });+ const entry = sync.trash().entries[0]!;+ const id = await upload("first", null);+ const held = holdCurrent();+ const committed = sync.commit(id);+ await held.entered;+ const restored = sync.restore(entry.id);+ await setImmediate();+ held.release();+ await committed;+ expect(await restored).toEqual({ folderId: folder.id, path: "a (restored, 15 Oct 2026).txt" });+ expect(readFileSync(join(folder.cloudPath, "a.txt"), "utf8")).toBe("first");+ expect(readFileSync(join(folder.cloudPath, "a (restored, 15 Oct 2026).txt"), "utf8")).toBe("original");+ expect(sync.trash().entries).toEqual([]);+});++it("restores after a competing delete frees the original path", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ await sync.ops(folder.id, { ops: [{ op: "delete", path: "a.txt", baseSha256: sha("original") }] });+ const entry = sync.trash().entries[0]!;+ writeFileSync(join(folder.cloudPath, "a.txt"), "new");+ const held = holdCurrent();+ const deleted = sync.ops(folder.id, { ops: [{ op: "delete", path: "a.txt", baseSha256: sha("new") }] });+ await held.entered;+ const restored = sync.restore(entry.id);+ await setImmediate();+ held.release();+ await deleted;+ expect(await restored).toEqual({ folderId: folder.id, path: "a.txt" });+ expect(readFileSync(join(folder.cloudPath, "a.txt"), "utf8")).toBe("original");+});++it("lets other paths and folders commit while one path is held", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ const id = await upload("first", sha("original"));+ const other = sync.register({ computerId: PC, computerName: "PC", pcPath: "/other", name: "Other" });+ const held = holdCurrent();+ const committed = sync.commit(id);+ await held.entered;+ try {+ await sync.commit(await upload("another path", null, "b.txt"));+ await sync.commit(await upload("another folder", null, "a.txt", other.id));+ expect(readFileSync(join(folder.cloudPath, "b.txt"), "utf8")).toBe("another path");+ expect(readFileSync(join(other.cloudPath, "a.txt"), "utf8")).toBe("another folder");+ } finally { held.release(); await committed; }+});++it("does not restore onto another commit's pending collision path", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ await sync.ops(folder.id, { ops: [{ op: "delete", path: "a.txt", baseSha256: sha("original") }] });+ const entry = sync.trash().entries[0]!;+ writeFileSync(join(folder.cloudPath, "a.txt"), "occupied");+ const path = "a (restored, 15 Oct 2026).txt";+ const id = await upload("first", null, path);+ const held = holdCurrent();+ const committed = sync.commit(id);+ await held.entered;+ const restored = sync.restore(entry.id);+ await setImmediate();+ held.release();+ await committed;+ expect(await restored).toEqual({ folderId: folder.id, path: "a (restored, 15 Oct 2026 2).txt" });+ expect(readFileSync(join(folder.cloudPath, path), "utf8")).toBe("first");+ expect(readFileSync(join(folder.cloudPath, "a (restored, 15 Oct 2026 2).txt"), "utf8")).toBe("original");+});++it("waits for a pending commit before deleting its whole folder", async () => {+ writeFileSync(join(folder.cloudPath, "a.txt"), "original");+ const id = await upload("first", sha("original"));+ const held = holdCurrent();+ const committed = sync.commit(id);+ await held.entered;+ const removed = sync.unregister(folder.id, false);+ await setImmediate();+ held.release();+ expect(await committed).toEqual({ sha256: sha("first") });+ await removed;+ expect(existsSync(folder.cloudPath)).toBe(false);+ const contents = sync.trash().entries.map((entry) => readFileSync(sync.store.trashEntry(entry.id)!.file, "utf8"));+ expect(contents.sort()).toEqual(["first", "original"]);+});diff --git a/server/cloud-sync.test.ts b/server/cloud-sync.test.tsindex a3a2b13d86..fad7f1624c 100644--- a/server/cloud-sync.test.ts+++ b/server/cloud-sync.test.ts@@ -87,7 +87,7 @@ it("answers 410 when a folder's copy is gone, and can delete a folder's copy toexpect(await status(() => sync.files(folder.id))).toBe(410);mkdirSync(folder.cloudPath);writeFileSync(join(folder.cloudPath, "b.txt"), "bye");- sync.unregister(folder.id, false);+ await sync.unregister(folder.id, false);expect(existsSync(folder.cloudPath)).toBe(false);expect(sync.trash().entries.map((entry) => entry.path)).toEqual(["b.txt"]);expect(sync.summary().folders).toEqual([]);@@ -192,7 +192,7 @@ it("restores into a bot folder that emptied, and into a folder no longer synced"expect(await sync.restore(botEntry!.id)).toEqual({ folderId: "bot-owl-t1", path: "report.md" });expect(readFileSync(join(output, "report.md"), "utf8")).toBe("# Q3");await put(sync, folder.id, "a.txt", "keep", null);- sync.unregister(folder.id, false);+ await sync.unregister(folder.id, false);const entry = sync.trash().entries.find((item) => item.path === "a.txt")!;await sync.restore(entry.id);expect(readFileSync(join(folder.cloudPath, "a.txt"), "utf8")).toBe("keep");@@ -203,7 +203,7 @@ it("turning off with delete trashes synced files, keeps what sync never carried,await put(sync, folder.id, "a.txt", "synced", null);mkdirSync(join(folder.cloudPath, ".git"));writeFileSync(join(folder.cloudPath, ".git", "HEAD"), "ref: main");- sync.unregister(folder.id, false);+ await sync.unregister(folder.id, false);expect(existsSync(join(folder.cloudPath, "a.txt"))).toBe(false);expect(readFileSync(join(folder.cloudPath, ".git", "HEAD"), "utf8")).toBe("ref: main");const other = sync.register({ computerId: PC, computerName: "Ash-PC", pcPath: "C:\\Users\\Ash\\Other", name: "Other" });@@ -212,7 +212,7 @@ it("turning off with delete trashes synced files, keeps what sync never carried,writeFileSync(join(outside, "x.txt"), "not synced");rmSync(other.cloudPath, { recursive: true });symlinkSync(outside, other.cloudPath);- sync.unregister(other.id, false);+ await sync.unregister(other.id, false);expect(readFileSync(join(outside, "x.txt"), "utf8")).toBe("not synced");});diff --git a/server/cloud-sync.ts b/server/cloud-sync.tsindex f0a4e753ef..ee06afc804 100644--- a/server/cloud-sync.ts+++ b/server/cloud-sync.ts@@ -38,6 +38,21 @@ export function createCloudSync(options: { dataDir: string; root?: string; now?:let cursor = now();const changes: Array<{ seq: number; folderId: string }> = [];const waiters = new Set<() => void>();+ const mutations = new Map<string, Map<string | null, Promise<unknown>>>();+ const mutate = <T>(folderId: string, path: string | null, work: () => T | Promise<T>): Promise<T> => {+ let pending = mutations.get(folderId);+ if (!pending) mutations.set(folderId, pending = new Map());+ const queue = pending;+ const previous = path === null ? [...queue.values()] : [queue.get(null), queue.get(path)];+ const run = Promise.all(previous).then(work);+ const settled = run.catch(() => undefined);+ queue.set(path, settled);+ void settled.then(() => {+ if (queue.get(path) === settled) queue.delete(path);+ if (!queue.size) mutations.delete(folderId);+ });+ return run;+ };const folderOf = (id: string): SyncFolder => {const folder = store.folder(id);@@ -105,17 +120,19 @@ export function createCloudSync(options: { dataDir: string; root?: string; now?:noteChange(folder.id);return folder;},- unregister(id: string, keepCloudCopy: boolean): void {- const folder = store.unregister(id);- if (!folder) throw new SyncError(404, { error: "no such synced folder" });- // Never through a link; synced files go to the trash, and what sync never carried (.git, node_modules) stays.- if (!keepCloudCopy && lstatSync(folder.cloudPath, { throwIfNoEntry: false })?.isDirectory()) {- let files;- try { files = Array.from(walk(folder.cloudPath)); } catch (error) { unreadable(error); }- for (const entry of files!) store.toTrash(folder, entry.path, join(folder.cloudPath, ...entry.path.split("/")));- pruneEmptyDirectories(folder.cloudPath);- }- noteChange(id);+ async unregister(id: string, keepCloudCopy: boolean): Promise<void> {+ return mutate(id, null, () => {+ const folder = store.unregister(id);+ if (!folder) throw new SyncError(404, { error: "no such synced folder" });+ // Never through a link; synced files go to the trash, and what sync never carried (.git, node_modules) stays.+ if (!keepCloudCopy && lstatSync(folder.cloudPath, { throwIfNoEntry: false })?.isDirectory()) {+ let files;+ try { files = Array.from(walk(folder.cloudPath)); } catch (error) { unreadable(error); }+ for (const entry of files!) store.toTrash(folder, entry.path, join(folder.cloudPath, ...entry.path.split("/")));+ pruneEmptyDirectories(folder.cloudPath);+ }+ noteChange(id);+ });},async files(id: string): Promise<SyncFile[]> {const folder = folderOf(id);@@ -162,20 +179,23 @@ export function createCloudSync(options: { dataDir: string; root?: string; now?:if (upload.received !== upload.size) throw new SyncError(409, { error: "upload incomplete", received: upload.received });const part = uploadFile(uploadId, "part");if (await sha256File(part) !== upload.sha256) { dropUpload(uploadId); throw new SyncError(422, { error: "the file's bytes do not match its hash" }); }- const folder = folderOf(upload.folderId);- const target = fileOf(folder, upload.path);- const current = await store.current(folder, upload.path);- if ((current?.sha256 ?? null) !== upload.baseSha256) { dropUpload(uploadId); throw new SyncError(409, { error: "changed on My Cloud", current }); }- if (current) store.toTrash(folder, upload.path, target);- mkdirSync(dirname(target), { recursive: true, mode: 0o700 });- renameSync(part, target);- // A copy from the person's computer: bots read it, and save their own work in their own folder.- if (folder.kind === "pc") chmodSync(target, 0o444);- dropUpload(uploadId);- const stat = lstatSync(target);- store.remember(folder, { path: upload.path, size: stat.size, mtimeMs: stat.mtimeMs, sha256: upload.sha256 });- noteChange(folder.id);- return { sha256: upload.sha256 };+ return mutate(upload.folderId, upload.path, async () => {+ readUpload(uploadId);+ const folder = folderOf(upload.folderId);+ const target = fileOf(folder, upload.path);+ const current = await store.current(folder, upload.path);+ if ((current?.sha256 ?? null) !== upload.baseSha256) { dropUpload(uploadId); throw new SyncError(409, { error: "changed on My Cloud", current }); }+ if (current) store.toTrash(folder, upload.path, target);+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 });+ renameSync(part, target);+ // A copy from the person's computer: bots read it, and save their own work in their own folder.+ if (folder.kind === "pc") chmodSync(target, 0o444);+ dropUpload(uploadId);+ const stat = lstatSync(target);+ store.remember(folder, { path: upload.path, size: stat.size, mtimeMs: stat.mtimeMs, sha256: upload.sha256 });+ noteChange(folder.id);+ return { sha256: upload.sha256 };+ });},async download(id: string, path: unknown): Promise<{ file: string; size: number; sha256: string }> {const folder = folderOf(id);@@ -191,13 +211,17 @@ export function createCloudSync(options: { dataDir: string; root?: string; now?:const results: Array<{ ok: true } | { conflict: true; current: SyncFile | null }> = [];for (const op of list as Array<Record<string, unknown>>) {if (op?.op === "delete" && typeof op.baseSha256 === "string") {- const file = fileOf(folder, op.path);- const current = await store.current(folder, op.path as string);- if (!current) { results.push({ ok: true }); continue; }- if (current.sha256 !== op.baseSha256) { results.push({ conflict: true, current }); continue; }- store.toTrash(folder, op.path as string, file);- removeEmptyParents(folder, file);- results.push({ ok: true });+ fileOf(folder, op.path);+ await mutate(id, op.path as string, async () => {+ const folder = folderOf(id);+ const file = fileOf(folder, op.path);+ const current = await store.current(folder, op.path as string);+ if (!current) { results.push({ ok: true }); return; }+ if (current.sha256 !== op.baseSha256) { results.push({ conflict: true, current }); return; }+ store.toTrash(folder, op.path as string, file);+ removeEmptyParents(folder, file);+ results.push({ ok: true });+ });} else {throw new SyncError(400, { error: "invalid op" });}@@ -210,19 +234,22 @@ export function createCloudSync(options: { dataDir: string; root?: string; now?:if (!found) throw new SyncError(404, { error: "no such deleted file" });// Its folder may no longer sync (turned off) or list (a bot folder emptied): put it back where it came from.const home = found.cloudPath && [store.root, store.lentRoot(), join(options.dataDir, "task-workspaces")].some((root) => found.cloudPath!.startsWith(root + sep)) ? found.cloudPath : null;- const known = store.folder(found.entry.folderId);- if (!known && !home) throw new SyncError(404, { error: "the folder this file came from is gone" });- if (!known) mkdirSync(home!, { recursive: true, mode: 0o700 });- const folder = known ?? { id: found.entry.folderId, kind: found.entry.folderId.startsWith("bot-") ? "bot" as const : "pc" as const, cloudPath: home! };- if (!lstatSync(folder.cloudPath, { throwIfNoEntry: false })?.isDirectory()) throw new SyncError(410, { error: "this folder is missing on My Cloud" });- let path = found.entry.path;- if (existsSync(fileOf(folder, path))) path = clashPath(path, now(), (candidate) => existsSync(fileOf(folder, candidate)), "restored");- const target = fileOf(folder, path);- mkdirSync(dirname(target), { recursive: true, mode: 0o700 });- renameSync(found.file, target);- store.dropTrash(found.entry.id);- noteChange(folder.id);- return { folderId: folder.id, path };+ return mutate(found.entry.folderId, found.entry.path, () => {+ if (!store.trashEntry(found.entry.id)) throw new SyncError(404, { error: "no such deleted file" });+ const known = store.folder(found.entry.folderId);+ if (!known && !home) throw new SyncError(404, { error: "the folder this file came from is gone" });+ if (!known) mkdirSync(home!, { recursive: true, mode: 0o700 });+ const folder = known ?? { id: found.entry.folderId, kind: found.entry.folderId.startsWith("bot-") ? "bot" as const : "pc" as const, cloudPath: home! };+ if (!lstatSync(folder.cloudPath, { throwIfNoEntry: false })?.isDirectory()) throw new SyncError(410, { error: "this folder is missing on My Cloud" });+ let path = found.entry.path;+ if (existsSync(fileOf(folder, path))) path = clashPath(path, now(), (candidate) => mutations.get(folder.id)?.has(candidate) || existsSync(fileOf(folder, candidate)), "restored");+ const target = fileOf(folder, path);+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 });+ renameSync(found.file, target);+ store.dropTrash(found.entry.id);+ noteChange(folder.id);+ return { folderId: folder.id, path };+ });},trash() {return { entries: store.trash() };diff --git a/server/routes/cloud-sync.ts b/server/routes/cloud-sync.tsindex 81f2fd6a8a..6c82f16a8f 100644--- a/server/routes/cloud-sync.ts+++ b/server/routes/cloud-sync.ts@@ -90,7 +90,7 @@ export function createCloudSyncRoutes(options: {return;}if (method === "DELETE" && (m = match(`/api/sync/folders/${FOLDER}`))) {- s.unregister(m[1]!, url.searchParams.get("keepCloudCopy") !== "0");+ await s.unregister(m[1]!, url.searchParams.get("keepCloudCopy") !== "0");res.writeHead(204).end();return;}