Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: complete partial filesystem IO during cloud uploads
Afloatc3d6c5aad83b
diff --git a/electron/cloud-sync-client.mjs b/electron/cloud-sync-client.mjsindex 554d3c73d8..e3f97c911b 100644--- a/electron/cloud-sync-client.mjs+++ b/electron/cloud-sync-client.mjs@@ -83,7 +83,12 @@ export function createSyncClient({ origin, fetch: fetchImpl, power = null, chunkwhile (received < size) {const length = Math.min(chunk, size - received);const buffer = Buffer.alloc(length);- if (readSync(fd, buffer, 0, length, received) !== length) throw new Error("The file changed while it was being sent.");+ let filled = 0;+ while (filled < length) {+ const count = readSync(fd, buffer, filled, length - filled, received + filled);+ if (count === 0) throw new Error("The file changed while it was being sent.");+ filled += count;+ }let response;try {response = await call("PUT", `/api/sync/uploads/${begun.uploadId}?offset=${received}`, { raw: buffer, timeoutMs: 30_000 + Math.ceil(length / SLOWEST) });diff --git a/electron/cloud-sync-short-reads.node-test.mjs b/electron/cloud-sync-short-reads.node-test.mjsnew file mode 100644index 0000000000..0e98e18579--- /dev/null+++ b/electron/cloud-sync-short-reads.node-test.mjs@@ -0,0 +1,48 @@+import assert from "node:assert/strict";+import fs from "node:fs";+import { syncBuiltinESMExports } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { createSyncClient } from "./cloud-sync-client.mjs";++function setup(t, contents, maxRead) {+ const folder = fs.mkdtempSync(join(tmpdir(), "omb-sync-short-read-"));+ const file = join(folder, "upload");+ fs.writeFileSync(file, contents);+ const read = fs.readSync;+ t.mock.method(fs, "readSync", (fd, buffer, offset, length, position) => read(fd, buffer, offset, Math.min(length, maxRead), position));+ syncBuiltinESMExports();+ t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports(); fs.rmSync(folder, { recursive: true, force: true }); });+ return file;+}++test("fills upload parts across short reads, including a resumed offset", async (t) => {+ const contents = Buffer.from("first 世界 last");+ const file = setup(t, contents, 2);+ let received = 3;+ const sent = [];+ const client = createSyncClient({ origin: "https://sync.example.test", chunkBytes: 5, minChunkBytes: 1, fetch: async (url, init) => {+ if (url.endsWith("/uploads")) return Response.json({ uploadId: "id", received });+ if (init.method === "PUT") {+ assert.equal(Number(new URL(url).searchParams.get("offset")), received);+ sent.push(Buffer.from(init.body));+ received += init.body.length;+ return Response.json({ received });+ }+ return Response.json({});+ } });+ assert.deepEqual(await client.upload({ folderId: "f", path: "file", file, size: contents.length, sha256: "s", baseSha256: null }), { ok: true });+ assert.deepEqual(Buffer.concat(sent), contents.subarray(3));+});++test("an actual early EOF fails before sending or committing an incomplete part", async (t) => {+ const file = setup(t, "short", 2);+ let calls = 0;+ const client = createSyncClient({ origin: "https://sync.example.test", fetch: async () => {+ calls++;+ return Response.json({ uploadId: "id", received: 0 });+ } });+ await assert.rejects(client.upload({ folderId: "f", path: "file", file, size: 10, sha256: "s", baseSha256: null }), /file changed/);+ assert.equal(calls, 1);+});diff --git a/server/cloud-sync-partial-writes.test.ts b/server/cloud-sync-partial-writes.test.tsnew file mode 100644index 0000000000..f26ae0bbbd--- /dev/null+++ b/server/cloud-sync-partial-writes.test.ts@@ -0,0 +1,54 @@+import { createHash } from "node:crypto";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, it, vi } from "vitest";+import { createCloudSync, type CloudSync } from "./cloud-sync.ts";++const writes = vi.hoisted(() => ({ limit: Infinity }));+vi.mock("node:fs", async (importOriginal) => {+ const fs = await importOriginal<typeof import("node:fs")>();+ return { ...fs, writeSync: (fd: number, buffer: Buffer, offset: number, length: number, position: number) =>+ fs.writeSync(fd, buffer, offset, Math.min(length, writes.limit), position) };+});+const scratch: string[] = [];+const opened: CloudSync[] = [];+const sha = (value: string) => createHash("sha256").update(value).digest("hex");+function setup() {+ const home = mkdtempSync(join(tmpdir(), "omb-sync-short-write-"));+ scratch.push(home);+ const sync = createCloudSync({ dataDir: join(home, "data"), statfs: () => ({ totalBytes: 10 * 1024 ** 3, freeBytes: 9 * 1024 ** 3 }) });+ opened.push(sync);+ const folder = sync.register({ computerId: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", computerName: "PC", pcPath: "/notes", name: "notes" });+ return { sync, folder };+}+async function* chunks(...texts: string[]) { for (const text of texts) yield Buffer.from(text); }+afterEach(() => {+ writes.limit = Infinity;+ for (const sync of opened.splice(0)) sync.close();+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });+});++it("writes every byte of each upload chunk when the filesystem stops short", async () => {+ const { sync, folder } = setup();+ const text = "first 世界 last";+ const { uploadId } = sync.beginUpload(folder.id, { path: "a.txt", size: Buffer.byteLength(text), sha256: sha(text), baseSha256: null });+ writes.limit = 2;+ expect(await sync.writePart(uploadId, 0, chunks("first "))).toEqual({ received: 6 });+ expect(await sync.writePart(uploadId, 6, chunks("世界", " last"))).toEqual({ received: Buffer.byteLength(text) });+ expect(await sync.commit(uploadId)).toEqual({ sha256: sha(text) });+ expect(readFileSync(join(folder.cloudPath, "a.txt"), "utf8")).toBe(text);+});++it("does not acknowledge a zero-progress write and allows retrying the same offset", async () => {+ const { sync, folder } = setup();+ const text = "retry me";+ const input = { path: "a.txt", size: text.length, sha256: sha(text), baseSha256: null };+ const { uploadId } = sync.beginUpload(folder.id, input);+ writes.limit = 0;+ await expect(sync.writePart(uploadId, 0, chunks(text))).rejects.toThrow(/upload.*written/i);+ expect(sync.beginUpload(folder.id, input)).toEqual({ uploadId, received: 0 });+ writes.limit = 3;+ expect(await sync.writePart(uploadId, 0, chunks(text))).toEqual({ received: text.length });+ expect(await sync.commit(uploadId)).toEqual({ sha256: sha(text) });+});diff --git a/server/cloud-sync.ts b/server/cloud-sync.tsindex 14db9df1d8..92bcf5ae2f 100644--- a/server/cloud-sync.ts+++ b/server/cloud-sync.ts@@ -173,8 +173,13 @@ export function createCloudSync(options: { dataDir: string; root?: string; now?:try {for await (const chunk of body) {if (written + chunk.length > PART_MAX || upload.received + written + chunk.length > upload.size) throw new SyncError(413, { error: "part too large" });- writeSync(fd, chunk, 0, chunk.length, upload.received + written);- written += chunk.length;+ let offset = 0;+ while (offset < chunk.length) {+ const count = writeSync(fd, chunk, offset, chunk.length - offset, upload.received + written);+ if (count === 0) throw new Error("The upload could not be written to My Cloud.");+ offset += count;+ written += count;+ }}} finally { closeSync(fd); }upload.received += written;