Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: coordinate upload aliases and clean failed replacements
Afloatcd1dcbe2cdce
diff --git a/server/cloud-send-empty-overlap.test.ts b/server/cloud-send-empty-overlap.test.tsindex 2510ea4f35..c211d5ac4f 100644--- a/server/cloud-send-empty-overlap.test.ts+++ b/server/cloud-send-empty-overlap.test.ts@@ -21,7 +21,7 @@ describe("overlapping empty bot file uploads", () => {it("keeps a verified empty upload available while another empty file finishes", async () => {const firstPath = "workspaces/b1/first.txt";- const secondPath = "workspaces/b1/second.txt";+ const secondPath = "workspaces/b1/another/second.txt";const digest = createHash("sha256").update("").digest("hex");let reached!: () => void;let release!: () => void;diff --git a/server/cloud-send-files.ts b/server/cloud-send-files.tsindex 076f761e7a..4f9db1e51e 100644--- a/server/cloud-send-files.ts+++ b/server/cloud-send-files.ts@@ -89,14 +89,17 @@ const staging = (dataDir: string) => join(dataDir, "tmp", "move-files");const partialPath = (dataDir: string, sha256: string, size: number) => join(staging(dataDir), `${sha256}-${size}.partial`);const publications = new Map<string, Promise<void>>();-/** Keeps this receiver's target check and publication together, releasing waiters on failure too. */async function publishInOrder<T>(target: string, publish: () => Promise<T>): Promise<T> {- const previous = publications.get(target) ?? Promise.resolve();+ const directory = await stat(dirname(target), { bigint: true }).catch(() => null);+ // Directory identity covers case and Unicode aliases without guessing a volume's path rules.+ // Filesystems without a usable identity share a conservative fallback queue.+ const key = directory && directory.ino !== 0n ? `${directory.dev}:${directory.ino}` : "unidentified-directory";+ const previous = publications.get(key) ?? Promise.resolve();const result = previous.then(publish);const settled = result.then(() => {}, () => {});- publications.set(target, settled);+ publications.set(key, settled);try { return await result; }- finally { if (publications.get(target) === settled) publications.delete(target); }+ finally { if (publications.get(key) === settled) publications.delete(key); }}/** Partial files a move left more than a day ago. */@@ -191,11 +194,11 @@ async function takePartAt(deps: MoveFilesDeps, req: IncomingMessage, query: z.inconst received = held + bytes.length;if (received < size) return { status: 200, body: { received } };if (await sha256Of(partial) !== sha256) { await unlink(partial).catch(() => {}); return { status: 422, body: { error: "the file arrived different from what was sent" } }; }+ if (!(await realFolders(deps.dataDir, path))) return { status: 409, body: { conflict: true } };const target = join(deps.dataDir, path);return publishInOrder(target, () => publishPart(deps.dataDir, target, partial, query));}-/** Publishes a verified part after all earlier publications to this target have finished. */async function publishPart(dataDir: string, target: string, partial: string, { path, mode, expect, sha256 }: z.infer<typeof putSchema>): Promise<{ status: number; body: Record<string, unknown> }> {if (!(await realFolders(dataDir, path))) return { status: 409, body: { conflict: true } };const there = await lstat(target).catch(() => null);@@ -204,7 +207,8 @@ async function publishPart(dataDir: string, target: string, partial: string, { pif (mode === "replace" && there && expect && await sha256Of(target) === expect) {const placed = join(staging(dataDir), `${randomUUID()}.placing`);await link(partial, placed);- await rename(placed, target);+ try { await rename(placed, target); }+ finally { await unlink(placed).catch(() => {}); }await unlink(partial).catch(() => {});return { status: 201, body: { stored: true } };}diff --git a/server/cloud-send-publication.test.ts b/server/cloud-send-publication.test.tsindex ff86b44fb1..c2f67f70cf 100644--- a/server/cloud-send-publication.test.ts+++ b/server/cloud-send-publication.test.ts@@ -1,6 +1,6 @@import { createHash } from "node:crypto";-import { mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";-import { link, rename } from "node:fs/promises";+import { createReadStream, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs";+import { link, lstat, rename, stat } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { Readable } from "node:stream";@@ -8,9 +8,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { removeTempDir } from "./testing/cleanup.ts";vi.mock("node:fs/promises", { spy: true });+vi.mock("node:fs", async () => {+ const actual = await vi.importActual<typeof import("node:fs")>("node:fs");+ return { ...actual, createReadStream: vi.fn(actual.createReadStream) };+});vi.resetModules();const { moveFilesRoute } = await import("./cloud-send-files.ts");const realFs = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");+const realSyncFs = await vi.importActual<typeof import("node:fs")>("node:fs");const digest = (text: string) => createHash("sha256").update(text).digest("hex");describe("publishing bot files during a move", () => {@@ -21,7 +26,10 @@ describe("publishing bot files during a move", () => {});afterEach(async () => {vi.mocked(link).mockRestore();+ vi.mocked(lstat).mockRestore();vi.mocked(rename).mockRestore();+ vi.mocked(stat).mockRestore();+ vi.mocked(createReadStream).mockRestore();await removeTempDir(data);});@@ -64,9 +72,15 @@ describe("publishing bot files during a move", () => {expect(await send(path, "")).toEqual({ status: 409, body: { conflict: true } });});- it("checks a queued replacement against the version published before it", async () => {+ it.each([["current.txt", false], ["CURRENT.txt", false], ["CURRENT.txt", true]] as const)("checks a queued replacement through %s with unavailable identity %s", async (secondName, unavailableIdentity) => {const path = "workspaces/b1/current.txt";writeFileSync(join(data, path), "original");+ const alias = join(data, "workspaces/b1/CURRENT.txt");+ const actual = join(data, path);+ vi.mocked(lstat).mockImplementation((file, ...options) => realFs.lstat(file === alias ? actual : file, ...options));+ vi.mocked(createReadStream).mockImplementation((file, options) => realSyncFs.createReadStream(file === alias ? actual : file, options));+ vi.mocked(stat).mockImplementation((file, options) => unavailableIdentity && options?.bigint+ ? Promise.reject(new Error("directory identity unavailable")) : realFs.stat(file, options));let reached!: () => void;let release!: () => void;const waiting = new Promise<void>((resolve) => { reached = resolve; });@@ -78,11 +92,11 @@ describe("publishing bot files during a move", () => {reached();await allowed;}- return realFs.rename(source, target);+ return realFs.rename(source, target === alias ? actual : target);});const first = send(path, "updated", "original");await waiting;- const second = send(path, "", "original");+ const second = send(`workspaces/b1/${secondName}`, "", "original");let timer: ReturnType<typeof setTimeout> | undefined;try {await Promise.race([second, new Promise<void>((resolve) => { timer = setTimeout(resolve, 1000); })]);@@ -102,4 +116,14 @@ describe("publishing bot files during a move", () => {expect(await send(path, "")).toEqual({ status: 201, body: { stored: true } });expect(readFileSync(join(data, path))).toHaveLength(0);});++ it("removes the placed link when replacement fails after staging succeeds", async () => {+ const path = "workspaces/b1/current.txt";+ writeFileSync(join(data, path), "original");+ vi.mocked(rename).mockRejectedValueOnce(new Error("temporary replacement failure"));+ await expect(send(path, "", "original")).rejects.toThrow("temporary replacement failure");+ expect(readdirSync(join(data, "tmp/move-files"))).toEqual([]);+ expect(readFileSync(join(data, path), "utf8")).toBe("original");+ expect(await send(path, "", "original")).toEqual({ status: 201, body: { stored: true } });+ });});