Skip to content

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

fix(cli): keep linked export folders separate

Afloatfc907088e381
diff --git a/server/headless/export.test.ts b/server/headless/export.test.ts
index 02ca91cd90..bd30651cd4 100644
--- a/server/headless/export.test.ts
+++ b/server/headless/export.test.ts
@@ -1,10 +1,10 @@
import "../testing/scrub-ambient-omb-env.ts";
-import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, 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";
-import { join } from "node:path";
+import { basename, dirname, join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir } from "../testing/cleanup.ts";
@@ -20,6 +20,10 @@ const LEAD = "lead-thread-0001";
const PRIYA = "priya-thread-0002";
const KEY = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789";
const BIG = Buffer.alloc(3_000, 7);
+const REPORTS: Record<string, Record<string, string>> = {
+ "project-a/report/": { "index.html": '<!doctype html><link rel="stylesheet" href="style.css"><p>First report</p>', "style.css": "body { color: red; }\n" },
+ "project-b/report/": { "index.html": '<!doctype html><link rel="stylesheet" href="style.css"><p>Second report</p>', "style.css": "body { color: blue; }\n" },
+};
const messages: Record<string, unknown[]> = {
[LEAD]: [
@@ -56,6 +60,19 @@ function answer(req: IncomingMessage, res: ServerResponse, raw: string) {
const file = /^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/file$/.exec(url.pathname);
if (file && req.method === "POST") {
const body = JSON.parse(raw) as { path: string; entry?: string; listFolder?: boolean };
+ if (body.path === "plain/report") {
+ res.writeHead(200, { "content-type": "text/plain", "content-disposition": 'attachment; filename="report"' });
+ return res.end("A standalone report");
+ }
+ const report = REPORTS[body.path];
+ if (report && body.entry && report[body.entry] !== undefined) {
+ const text = report[body.entry]!;
+ res.writeHead(200, { "content-type": "text/plain", "content-length": String(Buffer.byteLength(text)) });
+ return res.end(text);
+ }
+ if (report && body.listFolder) {
+ return send(200, { name: "report", entries: Object.entries(report).map(([name, text]) => ({ name, bytes: Buffer.byteLength(text) })), truncated: false }, { "x-openmausbot-folder": "1" });
+ }
if (body.path === "old.md") {
res.writeHead(200, { "content-type": "text/markdown", "content-length": "3" });
return res.end("old");
@@ -108,7 +125,81 @@ const run = async (argv: string[]) => {
return { code, result: out.length ? JSON.parse(out.join("\n")) : undefined, err };
};
+async function exportReports(out: string, force = false, standalone?: "first" | "last") {
+ const links = Object.keys(REPORTS).map((path) => `[Report](${path})`);
+ if (standalone === "first") links.unshift("[Standalone](plain/report)");
+ if (standalone === "last") links.push("[Standalone](plain/report)");
+ const previous = messages[LEAD]!;
+ messages[LEAD] = [{ id: "reports", role: "bot", kind: "text", text: links.join("\n\n") }];
+ try {
+ return await run(["export", "--thread", LEAD, "--out", out, "--json", ...(force ? ["--force"] : [])]);
+ } finally {
+ messages[LEAD] = previous;
+ }
+}
+
+function checkReportFiles(out: string, result: { files: Array<{ link: string; entry?: string; file: string }> }): string[] {
+ const folders: string[] = [];
+ for (const [link, expected] of Object.entries(REPORTS)) {
+ const files = result.files.filter((file) => file.link === link);
+ expect(files.map((file) => file.entry)).toEqual(Object.keys(expected));
+ for (const file of files) {
+ expect(basename(file.file)).toBe(file.entry);
+ expect(readFileSync(join(out, file.file), "utf8")).toBe(expected[file.entry!]);
+ }
+ const html = files.find((file) => file.entry === "index.html")!;
+ const folder = dirname(html.file);
+ const stylesheet = /href="([^"]+)"/.exec(readFileSync(join(out, html.file), "utf8"))![1]!;
+ expect(readFileSync(join(out, folder, stylesheet), "utf8")).toBe(expected["style.css"]);
+ folders.push(folder);
+ }
+ expect(new Set(folders).size).toBe(2);
+ expect(JSON.parse(readFileSync(join(out, "manifest.json"), "utf8")).files).toEqual(result.files);
+ return folders;
+}
+
describe("export", () => {
+ it("keeps same-named linked report folders and their relative assets separate", async () => {
+ const out = join(dir, "report-folders");
+ const { code, result } = await exportReports(out);
+ expect(code).toBe(0);
+ checkReportFiles(out, result);
+ });
+
+ it.each(["first", "last"] as const)("keeps a same-named standalone file when it is linked %s", async (standalone) => {
+ const out = join(dir, `report-${standalone}`);
+ const { code, result } = await exportReports(out, false, standalone);
+ expect(code).toBe(0);
+ const folders = checkReportFiles(out, result);
+ const file = result.files.find((entry: { link: string }) => entry.link === "plain/report");
+ expect(folders).not.toContain(file.file);
+ expect(readFileSync(join(out, file.file), "utf8")).toBe("A standalone report");
+ });
+
+ it("keeps user files across repeated forced exports of whole report folders", async () => {
+ const out = join(dir, "report-force");
+ const occupied = join(out, "files/conversation-lead-thr/report");
+ mkdirSync(occupied, { recursive: true });
+ writeFileSync(join(occupied, "index.html"), "My existing report");
+ writeFileSync(join(occupied, "style.css"), "My existing stylesheet");
+ const first = await exportReports(out, true);
+ expect(first.code).toBe(0);
+ expect(readFileSync(join(occupied, "index.html"), "utf8")).toBe("My existing report");
+ const firstFolders = checkReportFiles(out, first.result);
+ const again = await exportReports(out, true);
+ expect(again.code).toBe(0);
+ expect(checkReportFiles(out, again.result)).toEqual(firstFolders);
+ const added = join(out, firstFolders[0]!, "notes.txt");
+ writeFileSync(added, "Keep these notes");
+ const updated = await exportReports(out, true);
+ expect(updated.code).toBe(0);
+ expect(checkReportFiles(out, updated.result)).not.toContain(firstFolders[0]);
+ expect(readFileSync(added, "utf8")).toBe("Keep these notes");
+ expect(readFileSync(join(occupied, "index.html"), "utf8")).toBe("My existing report");
+ expect(readFileSync(join(occupied, "style.css"), "utf8")).toBe("My existing stylesheet");
+ expect(readdirSync(join(out, firstFolders[0]!))).toEqual(["notes.txt"]);
+ });
+
it("writes the job, every transcript, the linked files and folders and the screens, within the byte limit", async () => {
const out = join(dir, "first");
const { code, result } = await run(["export", "--thread", LEAD, "--out", out, "--max-bytes", "2KB", "--json"]);
diff --git a/server/headless/export.ts b/server/headless/export.ts
index c12c4b006a..deb517906c 100644
--- a/server/headless/export.ts
+++ b/server/headless/export.ts
@@ -54,6 +54,13 @@ function unused(dir: string, name: string, taken: Set<string>): string {
return candidate;
}
+function unusedFolder(parent: string, name: string, taken: Set<string>): string {
+ let folder = join(parent, name);
+ for (let n = 2; taken.has(folder) || existsSync(folder); n++) folder = join(parent, `${name} (${n})`);
+ taken.add(folder);
+ return folder;
+}
+
export function exportFolder(dir: string, force: boolean): string {
const out = resolve(dir);
if (!existsSync(out) || force) return out;
@@ -185,7 +192,7 @@ export async function exportJob(client: HeadlessClient, options: ExportOptions,
return keep(response, join(out, "files", folder), fileName(response.headers.get("content-disposition"), link), about, files);
}
const listing = await response.json() as Rec;
- const dir = join(out, "files", folder, safeName(String(listing.name ?? "folder")));
+ const dir = unusedFolder(join(out, "files", folder), safeName(String(listing.name ?? "folder")), taken);
for (const entry of Array.isArray(listing.entries) ? listing.entries as Rec[] : []) {
const name = String(entry.name);
const one = { ...about, entry: name };