Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Train H: trim #5439 to the one-line empty-file fix and its two tests
milind-sonie953128da15d
diff --git a/server/cloud-send-empty-overlap.test.ts b/server/cloud-send-empty-overlap.test.tsdeleted file mode 100644index c211d5ac4f..0000000000--- a/server/cloud-send-empty-overlap.test.ts+++ /dev/null@@ -1,56 +0,0 @@-import { createHash } from "node:crypto";-import { mkdtempSync, readFileSync } from "node:fs";-import { link } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { Readable } from "node:stream";-import { afterEach, describe, expect, it, vi } from "vitest";-import { removeTempDir } from "./testing/cleanup.ts";--vi.mock("node:fs/promises", { spy: true });-vi.resetModules();-const { moveFilesRoute } = await import("./cloud-send-files.ts");-const realFs = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");--describe("overlapping empty bot file uploads", () => {- const data = mkdtempSync(join(tmpdir(), "omb-empty-overlap-"));- afterEach(async () => {- vi.mocked(link).mockRestore();- await removeTempDir(data);- });-- it("keeps a verified empty upload available while another empty file finishes", async () => {- const firstPath = "workspaces/b1/first.txt";- const secondPath = "workspaces/b1/another/second.txt";- const digest = createHash("sha256").update("").digest("hex");- let reached!: () => void;- let release!: () => void;- const waiting = new Promise<void>((resolve) => { reached = resolve; });- const allowed = new Promise<void>((resolve) => { release = resolve; });- vi.mocked(link).mockImplementation(async (existing, target) => {- if (target === join(data, firstPath)) { reached(); await allowed; }- return realFs.link(existing, target);- });- const send = async (path: string) => {- let answer: { status: number; body: unknown } | undefined;- const url = new URL(`http://127.0.0.1/api/cloud-send/files?${new URLSearchParams({ path, size: "0", sha256: digest, offset: "0", mode: "new" })}`);- await moveFilesRoute({ dataDir: data, bots: () => [{ id: "b1" }], owner: () => ({ person: "p_owner", name: "Owner" }) }, {- path: "/api/cloud-send/files", method: "POST", url, auth: {} as never,- req: Readable.from([Buffer.alloc(0)]) as never, res: { setHeader() {} } as never,- json: ((_res: unknown, status: number, body: unknown) => { answer = { status, body }; }) as never,- readBody: (async () => null) as never,- });- return answer;- };- const first = send(firstPath).catch((error: unknown) => ({ error }));- try {- await waiting;- expect(await send(secondPath)).toEqual({ status: 201, body: { stored: true } });- } finally {- release();- }- expect(await first).toEqual({ status: 201, body: { stored: true } });- expect(readFileSync(join(data, firstPath))).toHaveLength(0);- expect(readFileSync(join(data, secondPath))).toHaveLength(0);- });-});diff --git a/server/cloud-send-files.ts b/server/cloud-send-files.tsindex 432523bb28..ede593cc5d 100644--- a/server/cloud-send-files.ts+++ b/server/cloud-send-files.ts@@ -87,22 +87,6 @@ function space(dataDir: string): { freeBytes: number; volumeBytes: number } | nuconst 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>>();--async function publishInOrder<T>(target: string, publish: () => Promise<T>): Promise<T> {- 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 = key === "unidentified-directory"- ? Promise.all(publications.values())- : Promise.all([publications.get(key), publications.get("unidentified-directory")]);- const result = previous.then(publish);- const settled = result.then(() => {}, () => {});- publications.set(key, settled);- try { return await result; }- finally { if (publications.get(key) === settled) publications.delete(key); }-}/** Partial files a move left more than a day ago. */async function tidyPartials(dataDir: string, now = Date.now()): Promise<void> {@@ -170,20 +154,11 @@ async function readPart(dataDir: string, { path, offset, length }: z.infer<typeo/** One part of a file: 200 `{ received }` until the last, then 201 `{ stored }`, or 409 `{ conflict }` when the path holds a* file the move may not replace; 409 `{ received }` when the part does not start where My Cloud's copy ends. */async function takePart(deps: MoveFilesDeps, req: IncomingMessage, query: z.infer<typeof putSchema>): Promise<{ status: number; body: Record<string, unknown> }> {- const { path, size, sha256 } = query;+ const { path, size, sha256, offset, mode, expect } = query;const botId = /^(?:workspaces|task-workspaces)\/([\w-]{1,128})\//u.exec(path)?.[1];if (!movedFilePath(path) || !botId) return { status: 400, body: { error: "not a bot file a move carries" } };if (!deps.bots().some((bot) => bot.id === botId)) return { status: 409, body: { error: "This file's bot is not on My Cloud yet." } };- if (size === 0) {- const partial = join(staging(deps.dataDir), `${randomUUID()}.partial`);- try { return await takePartAt(deps, req, query, partial); }- finally { await unlink(partial).catch(() => {}); }- }- return takePartAt(deps, req, query, partialPath(deps.dataDir, sha256, size));-}--async function takePartAt(deps: MoveFilesDeps, req: IncomingMessage, query: z.infer<typeof putSchema>, partial: string): Promise<{ status: number; body: Record<string, unknown> }> {- const { path, size, sha256, offset } = query;+ const partial = partialPath(deps.dataDir, sha256, size);await mkdir(staging(deps.dataDir), { recursive: true, mode: 0o700 });const held = (await stat(partial).catch(() => null))?.size ?? 0;if (offset !== held) { await rawBody(req, 0); return { status: 409, body: { received: held } }; }@@ -196,35 +171,22 @@ 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));-}--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 } };+ if (!(await realFolders(deps.dataDir, path))) return { status: 409, body: { conflict: true } };const there = await lstat(target).catch(() => null);if (there && !there.isFile()) return { status: 409, body: { conflict: true } };if (there && await sha256Of(target) === sha256) { await unlink(partial).catch(() => {}); return { status: 201, body: { stored: false } }; }if (mode === "replace" && there && expect && await sha256Of(target) === expect) {- const placed = join(staging(dataDir), `${randomUUID()}.placing`);+ const placed = join(staging(deps.dataDir), `${randomUUID()}.placing`);await link(partial, placed);- try { await rename(placed, target); }- finally { await unlink(placed).catch(() => {}); }+ await rename(placed, target);await unlink(partial).catch(() => {});return { status: 201, body: { stored: true } };}if (there) return { status: 409, body: { conflict: true } };try { await link(partial, target); }catch (error) {- if ((error as NodeJS.ErrnoException).code === "EEXIST") {- const current = await lstat(target).catch(() => null);- if (current?.isFile() && await sha256Of(target) === sha256) {- await unlink(partial).catch(() => {});- return { status: 201, body: { stored: false } };- }- return { status: 409, body: { conflict: true } };- }+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return { status: 409, body: { conflict: true } };throw error;}await unlink(partial).catch(() => {});diff --git a/server/cloud-send-publication.test.ts b/server/cloud-send-publication.test.tsdeleted file mode 100644index d57a958495..0000000000--- a/server/cloud-send-publication.test.ts+++ /dev/null@@ -1,151 +0,0 @@-import { createHash } from "node:crypto";-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";-import { setImmediate } from "node:timers/promises";-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", () => {- let data: string;- beforeEach(() => {- data = mkdtempSync(join(tmpdir(), "omb-file-publication-"));- mkdirSync(join(data, "workspaces/b1"), { recursive: true });- });- 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);- });-- async function send(path: string, text: string, expected?: string) {- let answer: { status: number; body: unknown } | undefined;- const query = { path, size: String(Buffer.byteLength(text)), sha256: digest(text), offset: "0", mode: expected === undefined ? "new" : "replace",- ...(expected === undefined ? {} : { expect: digest(expected) }) };- const url = new URL(`http://127.0.0.1/api/cloud-send/files?${new URLSearchParams(query)}`);- await moveFilesRoute({ dataDir: data, bots: () => [{ id: "b1" }], owner: () => ({ person: "p_owner", name: "Owner" }) }, {- path: "/api/cloud-send/files", method: "POST", url, auth: {} as never,- req: Readable.from([Buffer.from(text)]) as never, res: { setHeader() {} } as never,- json: ((_res: unknown, status: number, body: unknown) => { answer = { status, body }; }) as never,- readBody: (async () => null) as never,- });- return answer;- }-- it("accepts an identical file that appears between the existence check and publication", async () => {- const path = "workspaces/b1/empty.txt";- vi.mocked(link).mockImplementation(async (source, target) => {- if (target === join(data, path)) writeFileSync(target, "");- return realFs.link(source, target);- });- expect(await send(path, "")).toEqual({ status: 201, body: { stored: false } });- expect(readFileSync(join(data, path))).toHaveLength(0);- });-- it.each(["different file", "directory", "symlink"])("keeps a concurrently created %s as a conflict", async (kind) => {- const path = "workspaces/b1/occupied.txt";- const outside = join(data, "outside.txt");- writeFileSync(outside, "");- vi.mocked(link).mockImplementation(async (source, target) => {- if (target === join(data, path)) {- if (kind === "directory") mkdirSync(target);- else if (kind === "symlink") symlinkSync(outside, target);- else writeFileSync(target, "keep this");- }- return realFs.link(source, target);- });- expect(await send(path, "")).toEqual({ status: 409, body: { conflict: true } });- });-- it.each([- ["current.txt", false, false],- ["CURRENT.txt", false, false],- ["CURRENT.txt", true, true],- ["CURRENT.txt", true, false],- ["CURRENT.txt", false, true],- ] as const)("checks a queued replacement through %s when directory identity is unavailable: %s then %s", async (secondName, firstUnavailable, secondUnavailable) => {- const path = "workspaces/b1/current.txt";- writeFileSync(join(data, path), "original");- const alias = join(data, "workspaces/b1/CURRENT.txt");- const actual = join(data, path);- let paused = false;- let readsWhilePaused = 0;- vi.mocked(lstat).mockImplementation(async (file, options) => realSyncFs.lstatSync(file === alias ? actual : file, { ...options, throwIfNoEntry: true }));- vi.mocked(createReadStream).mockImplementation((file) => {- if (paused && (file === alias || file === actual)) readsWhilePaused++;- return Readable.from([realSyncFs.readFileSync(file === alias ? actual : file)]) as ReturnType<typeof createReadStream>;- });- let identityReads = 0;- let secondIdentity!: () => void;- const secondIdentified = new Promise<void>((resolve) => { secondIdentity = resolve; });- vi.mocked(stat).mockImplementation((file, options) => {- if (!options?.bigint) return realFs.stat(file, options);- const unavailable = identityReads++ === 0 ? firstUnavailable : secondUnavailable;- if (identityReads === 2) secondIdentity();- return unavailable ? Promise.reject(new Error("directory identity unavailable")) : Promise.resolve(realSyncFs.statSync(file, options));- });- let reached!: () => void;- let release!: () => void;- const waiting = new Promise<void>((resolve) => { reached = resolve; });- const allowed = new Promise<void>((resolve) => { release = resolve; });- let firstRename = true;- vi.mocked(rename).mockImplementation(async (source, target) => {- if (target === join(data, path) && firstRename) {- firstRename = false;- paused = true;- reached();- await allowed;- }- return realFs.rename(source, target === alias ? actual : target);- });- const first = send(path, "updated", "original");- await waiting;- const second = send(`workspaces/b1/${secondName}`, "", "original");- try {- await secondIdentified;- await setImmediate();- } finally {- paused = false;- release();- }- const [firstAnswer, secondAnswer] = await Promise.all([first, second]);- expect(readsWhilePaused).toBe(0);- expect(firstAnswer).toEqual({ status: 201, body: { stored: true } });- expect(secondAnswer).toEqual({ status: 409, body: { conflict: true } });- expect(readFileSync(join(data, path), "utf8")).toBe("updated");- });-- it("releases a failed publication so a later retry can finish", async () => {- const path = "workspaces/b1/retry.txt";- vi.mocked(link).mockRejectedValueOnce(new Error("temporary publication failure"));- await expect(send(path, "")).rejects.toThrow("temporary publication failure");- 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 } });- });-});