Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(bot-link): deliver results when local attachments are missing

Afloatbcb485734900
diff --git a/server/bot-link/dial-files.test.ts b/server/bot-link/dial-files.test.ts
new file mode 100644
index 0000000000..d0e6cec851
--- /dev/null
+++ b/server/bot-link/dial-files.test.ts
@@ -0,0 +1,70 @@
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+
+import type { PassedFile } from "../host/handoff-files.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { createDialer } from "./dial.ts";
+import type { BotLink, FileTransfer } from "./link.ts";
+
+const cleanups: Array<() => void> = [];
+afterEach(() => { for (const cleanup of cleanups.splice(0).reverse()) cleanup(); });
+
+function transferUsing(fetch: typeof globalThis.fetch) {
+ let transfer!: FileTransfer;
+ const link = {
+ dial: () => ({ origin: "https://fixture.invalid", token: "fixture-token" }),
+ setTransfer: (next: FileTransfer | null) => { if (next) transfer = next; },
+ onOutgoing: () => () => {}, onWanted: () => () => {},
+ } as unknown as BotLink;
+ const dialer = createDialer({ link, fetch });
+ cleanups.push(() => dialer.close());
+ return transfer;
+}
+
+function file() {
+ const dir = mkdtempSync(join(tmpdir(), "bot-link-missing-file-"));
+ cleanups.push(() => removeTempDir(dir));
+ const path = join(dir, "report.txt"), content = "Completed report";
+ writeFileSync(path, content);
+ const file: PassedFile = { path, name: "report.txt", mime: "text/plain", kind: "file", bytes: Buffer.byteLength(content) };
+ return { dir, file, content };
+}
+
+it.each(["missing", "non-directory"] as const)("marks a %s upload source as unavailable before making a request", async (kind) => {
+ const fixture = file();
+ const missing: PassedFile = { ...fixture.file, path: kind === "missing" ? join(fixture.dir, "deleted.txt") : join(fixture.file.path, "child.txt") };
+ const fetch = vi.fn<typeof globalThis.fetch>();
+ const transfer = transferUsing(fetch);
+ await expect(transfer.push("work", "returned", 0, missing)).rejects.toMatchObject({ gone: true });
+ expect(fetch).not.toHaveBeenCalled();
+});
+
+it("uploads the original bytes and cancels the successful response body", async () => {
+ const fixture = file();
+ let sent: RequestInit | undefined;
+ const cancel = vi.fn();
+ const fetch: typeof globalThis.fetch = async (_input, init) => {
+ sent = init;
+ return new Response(new ReadableStream({ cancel }), { status: 200 });
+ };
+ await transferUsing(fetch).push("work", "returned", 0, fixture.file);
+ expect(sent?.method).toBe("PUT");
+ expect(await (sent!.body as Blob).text()).toBe(fixture.content);
+ expect(cancel).toHaveBeenCalledTimes(1);
+});
+
+it("keeps a temporary HTTP refusal retryable", async () => {
+ const fixture = file();
+ const fetch: typeof globalThis.fetch = async () => Response.json({ error: "try again" }, { status: 503 });
+ await expect(transferUsing(fetch).push("work", "returned", 0, fixture.file)).rejects.toMatchObject({ gone: false, message: "try again" });
+});
+
+it("does not classify an error from the transport as a missing local source", async () => {
+ const fixture = file();
+ const error = Object.assign(new Error("transport interrupted"), { code: "ENOENT" });
+ const fetch: typeof globalThis.fetch = async () => { throw error; };
+ await expect(transferUsing(fetch).push("work", "sent", 0, fixture.file)).rejects.toBe(error);
+ expect(error).not.toHaveProperty("gone");
+});
diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.ts
index 361e41f18e..db55d0036e 100644
--- a/server/bot-link/dial.ts
+++ b/server/bot-link/dial.ts
@@ -60,8 +60,13 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h
},
async push(id, way, index, file) {
const target = cloud();
+ let body: Blob;
+ try { body = await openAsBlob(file.path); } catch (error) {
+ if (typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) throw Object.assign(error, { gone: true });
+ throw error;
+ }
const response = await fetchImpl(fileUrl(target.origin, id, way, index, file.name), { method: "PUT", redirect: "error", signal: AbortSignal.timeout(FILE_MS),
- headers: { ...target.headers, "content-type": "application/octet-stream" }, body: await openAsBlob(file.path) });
+ headers: { ...target.headers, "content-type": "application/octet-stream" }, body });
if (!response.ok) throw await refusedFile(response);
await response.body?.cancel();
},
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.ts
index 1a3010ca0e..bc7c2493fa 100644
--- a/server/bot-link/link.test.ts
+++ b/server/bot-link/link.test.ts
@@ -1,7 +1,7 @@
// Two places, each with a real coordinator over its own data folder, joined by the real routes and the real dialer over
// HTTP on this machine: "the computer" asks, "the Cloud" answers. Only the engines are fake.
import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
@@ -47,6 +47,7 @@ function place(label: string, bots: Bot[], version?: number) {
const runs: Array<{ botId: string; threadId: string; text: string; resumed: boolean; requester: string; origin: unknown }> = [];
const sent: Array<{ recipient: string; threadId: string; roomId?: string }> = [];
const results: Array<{ thread: string; name: string; status: string; result: string }> = [];
+ const resultListeners = new Set<() => void>();
const requests: string[] = [];
const issued = new Map<string, string>();
/** The attachment store and the hand-off file ledger, as handoff-files.ts keeps them. */
@@ -101,7 +102,7 @@ function place(label: string, bots: Bot[], version?: number) {
openThread: (bot, title, opener, brief) => { const id = `${bot.id}-work-${++openedCount}`; threads.add(id); opened.push({ threadId: id, title, from: opener.name, brief }); return id; },
hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam",
sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId, ...(input.roomId ? { roomId: input.roomId } : {}) }); },
- resultRow: (parent, child, name) => { results.push({ thread: parent.threadId, name, status: child.status, result: child.result }); },
+ resultRow: (parent, child, name) => { results.push({ thread: parent.threadId, name, status: child.status, result: child.result }); for (const listener of resultListeners) listener(); },
kick: () => { queueMicrotask(() => { try { coordinator.tick(); } catch { /* closed */ } }); },
revoke: (sessionId) => { for (const [token, id] of issued) if (id === sessionId) issued.delete(token); },
now: () => Date.now() + skew,
@@ -181,6 +182,12 @@ function place(label: string, bots: Bot[], version?: number) {
const api = {
dir, bots, runs, sent, results, requests, opened, boot, listen, unplug, shutdown, handOff, keep, ledger,
+ nextResult(): Promise<void> {
+ return new Promise((resolve) => {
+ const listener = () => { resultListeners.delete(listener); resolve(); };
+ resultListeners.add(listener);
+ });
+ },
failOnce: (match: RegExp, status = 500) => { failing.push({ match, status }); },
/** What an assignment here carries one way: who it is from and each file's name and words. */
carries: (id: string, way: "sent" | "returned") => { const batch = ledger.get(`${id}:${way}`); return batch ? { from: batch.from.name, files: batch.files.map((file) => [file.name, readFileSync(file.path, "utf8")]) } : undefined; },
@@ -722,6 +729,23 @@ describe("the link between a computer and its Cloud", () => {
expect(computer.spooled()).toEqual([]);
});
+ it("returns a completed report when its local attachment was removed before upload", async () => {
+ const { computer, cloud } = await two();
+ computer.engine(async (node) => {
+ computer.attach(node.id, "report.txt", "Attachment contents");
+ const attachment = computer.ledger.get(`${node.id}:returned`)!.files[0]!;
+ rmSync(attachment.path);
+ return { ok: true, text: "Completed report" };
+ });
+ const arrived = cloud.nextResult();
+ const { receipts } = await cloud.handOff("cloud-analyst", call(["Writer"], "Prepare the report"));
+ await arrived;
+ expect(cloud.results).toHaveLength(1);
+ expect(cloud.results[0]).toMatchObject({ status: "completed", result: "Completed report\n\n(The files it attached could not be sent across.)" });
+ expect(cloud.carries(receipts[0]!.requestId!, "returned")).toBeUndefined();
+ expect(cloud.requests.filter((request) => request === "GET /api/bot-link/file?probe")).toHaveLength(1);
+ });
+
it("files wait for a computer that is off, and a file the working side will not take ends the hand-off with the reason", async () => {
const { computer, cloud } = await two();
await computer.dialer.stop();