Skip to content

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

Accept .xmind mind maps as attachments, converted to a Markdown outline (#5246)

Krishna Dobhalf44d464f3e55
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 347d744b0c..a142379ad5 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -6,6 +6,7 @@ import {
ATTACHMENTS_DIR, attachmentStorageUsage, clearAttachments, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES,
parseAudioRange, readAttachment, saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,
} from "../attachments.ts";
+import { saveXmindUpload, XMIND_MIME } from "../xmind.ts";
import { deliveredCopy } from "../bot-attachment.ts";
import { memberBot, memberGroup, type Viewer, type VisibleSet } from "../bot-visibility.ts";
import type { ComputerControl } from "../computer-control.ts";
@@ -377,7 +378,9 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
try {
// Returning must not destroy the socket: the caller still sends the 4xx when the byte count crosses the limit.
const chunks = req.iterator({ destroyOnReturn: false }) as AsyncIterable<Buffer>;
- const saved = await saveFile(chunks, name, rawType ?? "", { uploadId, expectedBytes: declaredLength });
+ const saved = rawType?.split(";")[0]!.trim().toLowerCase() === XMIND_MIME
+ ? await saveXmindUpload(chunks, name, { uploadId })
+ : await saveFile(chunks, name, rawType ?? "", { uploadId, expectedBytes: declaredLength });
deps.uploads.note(auth, basename(saved.path));
return json(res, 201, saved);
} catch (error) {
diff --git a/server/xmind.test.ts b/server/xmind.test.ts
new file mode 100644
index 0000000000..edfcf97561
--- /dev/null
+++ b/server/xmind.test.ts
@@ -0,0 +1,157 @@
+import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { buildZip, type ZipFixtureMember } from "./testing/zip-fixture.ts";
+
+const DATA_ROOT = mkdtempSync(join(tmpdir(), "omb-xmind-test-"));
+process.env.OMB_DATA_DIR = join(DATA_ROOT, "data");
+
+const { outlineFromJson, outlineFromXml, saveXmindUpload } = await import("./xmind.ts");
+
+afterAll(() => rmSync(DATA_ROOT, { recursive: true, force: true }));
+
+const UPLOAD_ID = "11111111-1111-4111-8111-111111111111";
+
+const CONTENT_JSON = JSON.stringify([
+ {
+ title: "Iteration 12",
+ rootTopic: {
+ title: "Release\nplan",
+ labels: ["Q4", "core"],
+ markers: [{ markerId: "priority-1" }],
+ notes: { plain: { content: "Ship by Friday.\n\nNo scope creep." } },
+ children: {
+ attached: [
+ { title: "Backend", children: { attached: [{ title: "Migrate <db>", href: "https://example.com/db" }] } },
+ { title: "" },
+ ],
+ detached: [{ title: "Parking lot" }],
+ },
+ },
+ },
+ { title: "", rootTopic: { title: "Risks" } },
+]);
+
+const EXPECTED = [
+ "# Iteration 12",
+ "",
+ "- Release plan (labels: Q4, core; markers: priority-1)",
+ " > Ship by Friday.",
+ " > No scope creep.",
+ " - Backend",
+ " - Migrate <db> (link: https://example.com/db)",
+ " - (untitled)",
+ " - Parking lot (floating)",
+ "",
+ "# Sheet 2",
+ "",
+ "- Risks",
+ "",
+].join("\n");
+
+const CONTENT_XML = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<xmap-content xmlns="urn:xmind:xmap:xmlns:content:2.0" xmlns:xlink="http://www.w3.org/1999/xlink" version="2.0">
+ <!-- a comment with <topic> inside -->
+ <sheet id="s1">
+ <topic id="t1">
+ <title>Release
+plan</title>
+ <labels><label>Q4</label><label>core</label></labels>
+ <marker-refs><marker-ref marker-id="priority-1"/></marker-refs>
+ <notes><plain><![CDATA[Ship by Friday.
+
+No scope creep.]]></plain><html><xhtml:p>Ship by Friday.</xhtml:p></html></notes>
+ <children>
+ <topics type="attached">
+ <topic id="t2"><title>Backend</title>
+ <children><topics type="attached">
+ <topic id="t3" xlink:href="https://example.com/db"><title>Migrate &lt;db&gt;</title></topic>
+ </topics></children>
+ </topic>
+ <topic id="t4"><title/></topic>
+ </topics>
+ <topics type="detached"><topic id="t5"><title>Parking &#108;ot</title></topic></topics>
+ </children>
+ </topic>
+ <title>Iteration 12</title>
+ </sheet>
+ <sheet id="s2"><topic id="t6"><title>Risks</title></topic></sheet>
+</xmap-content>`;
+
+async function* body(bytes: Buffer): AsyncIterable<Uint8Array> {
+ yield bytes.subarray(0, 7);
+ yield bytes.subarray(7);
+}
+
+const archive = (members: ZipFixtureMember[]) => body(buildZip(members));
+const scratchDirs = () => readdirSync(tmpdir()).filter((name) => name.startsWith("omb-xmind-") && !name.startsWith("omb-xmind-test-"));
+
+describe("XMind outlines", () => {
+ it("renders content.json as one section per sheet with notes, labels, markers and floating topics", () => {
+ expect(outlineFromJson(CONTENT_JSON)).toBe(EXPECTED);
+ });
+
+ it("renders the legacy content.xml to the same outline", () => {
+ expect(outlineFromXml(CONTENT_XML)).toBe(EXPECTED);
+ });
+
+ it("keeps summary and callout topics from content.json", () => {
+ const source = JSON.stringify([
+ { rootTopic: { title: "R", children: { attached: [{ title: "A" }], summary: [{ title: "S" }], callout: [{ title: "C" }] } } },
+ ]);
+ expect(outlineFromJson(source)).toBe("# Sheet 1\n\n- R\n - A\n - S\n - C\n");
+ });
+
+ it("reads a long tag with no attributes in linear time", () => {
+ const source = `<xmap-content><sheet><topic ${"x".repeat(400_000)}><title>T</title></topic></sheet></xmap-content>`;
+ const started = performance.now();
+ expect(outlineFromXml(source)).toBe("# Sheet 1\n\n- T\n");
+ expect(performance.now() - started).toBeLessThan(2000);
+ });
+
+ it("refuses a map with more topics or elements than it will hold in memory", () => {
+ const topics = Array.from({ length: 100_001 }, () => ({ title: "a" }));
+ expect(() => outlineFromJson(JSON.stringify([{ rootTopic: { children: { attached: topics } } }]))).toThrow("too many topics");
+ expect(() => outlineFromXml("<a>".repeat(500_001))).toThrow("too many elements");
+ });
+
+ it("refuses content with no sheets", () => {
+ expect(() => outlineFromJson("{}")).toThrow();
+ expect(() => outlineFromXml("<html></html>")).toThrow();
+ });
+});
+
+describe("saveXmindUpload", () => {
+ it("stores the outline as Markdown, never the archive, and answers a retry with the same file", async () => {
+ const before = scratchDirs();
+ const members = [{ name: "metadata.json", data: "{}" }, { name: "content.json", data: CONTENT_JSON }, { name: "content.xml", data: "<stale/>" }];
+ const saved = await saveXmindUpload(archive(members), "Plan.xmind", { uploadId: UPLOAD_ID });
+ expect(saved).toMatchObject({ name: "Plan.xmind.md", mime: "text/markdown" });
+ expect(basename(saved.path)).toBe(`${UPLOAD_ID}.md`);
+ expect(readFileSync(saved.path, "utf8")).toBe(EXPECTED);
+ expect((await saveXmindUpload(archive(members), "Plan.xmind", { uploadId: UPLOAD_ID })).path).toBe(saved.path);
+ expect(scratchDirs()).toEqual(before);
+ });
+
+ it("reads a legacy archive that only has content.xml", async () => {
+ const saved = await saveXmindUpload(archive([{ name: "content.xml", data: CONTENT_XML, method: 0 }]), "Old.xmind");
+ expect(readFileSync(saved.path, "utf8")).toBe(EXPECTED);
+ });
+
+ it("answers 400 for anything that is not a readable mind map, and leaves nothing behind", async () => {
+ const before = scratchDirs();
+ const unreadable = { status: 400, message: "not a readable XMind file" };
+ await expect(saveXmindUpload(body(Buffer.from("not a zip at all")), "a.xmind")).rejects.toMatchObject(unreadable);
+ await expect(saveXmindUpload(archive([{ name: "notes.txt", data: "hi" }]), "a.xmind")).rejects.toMatchObject(unreadable);
+ await expect(saveXmindUpload(archive([{ name: "content.json", data: "{ broken" }]), "a.xmind")).rejects.toMatchObject(unreadable);
+ await expect(saveXmindUpload(archive([{ name: "content.json", data: "[]", declaredBytes: 32 * 1024 * 1024 + 1 }]), "a.xmind"))
+ .rejects.toMatchObject(unreadable);
+ await expect(saveXmindUpload(archive([{ name: "content.json", data: CONTENT_JSON, declaredBytes: 4 }]), "a.xmind"))
+ .rejects.toMatchObject(unreadable);
+ await expect(saveXmindUpload((async function* () {})(), "a.xmind")).rejects.toMatchObject({ status: 400, message: "empty file" });
+ await expect(saveXmindUpload(archive([{ name: "content.json", data: CONTENT_JSON }]), "../a.xmind")).rejects.toMatchObject({ status: 400 });
+ expect(scratchDirs()).toEqual(before);
+ });
+});
diff --git a/server/xmind.ts b/server/xmind.ts
new file mode 100644
index 0000000000..0b67d25dd7
--- /dev/null
+++ b/server/xmind.ts
@@ -0,0 +1,236 @@
+import { createWriteStream } from "node:fs";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pipeline } from "node:stream/promises";
+import { FILE_MAX_BYTES, sanitizeSharedFileName, saveFile, type SavedFile } from "./attachments.ts";
+import { extractZipMember, readZipDirectory } from "./zip-archive.ts";
+
+export const XMIND_MIME = "application/vnd.xmind.workbook";
+
+const MAX_ARCHIVE_ENTRIES = 10_000;
+const MAX_CONTENT_BYTES = 32 * 1024 * 1024;
+const MAX_TOPICS = 100_000;
+const MAX_XML_ELEMENTS = 500_000;
+
+interface Topic {
+ title: string;
+ note: string;
+ labels: string[];
+ markers: string[];
+ href: string;
+ floating: boolean;
+ children: Topic[];
+}
+
+interface Sheet {
+ title: string;
+ root: Topic | null;
+}
+
+function statusError(status: number, message: string): Error & { status: number } {
+ return Object.assign(new Error(message), { status });
+}
+
+const text = (value: unknown): string => (typeof value === "string" ? value : "");
+const list = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
+const record = (value: unknown): Record<string, unknown> =>
+ value && typeof value === "object" ? (value as Record<string, unknown>) : {};
+
+function topicFromJson(raw: unknown, budget: { topics: number }, floating = false): Topic {
+ if (--budget.topics < 0) throw new Error("too many topics");
+ const topic = record(raw);
+ return {
+ title: text(topic.title),
+ note: text(record(record(topic.notes).plain).content),
+ labels: list(topic.labels).map(text).filter(Boolean),
+ markers: list(topic.markers).map((marker) => text(record(marker).markerId)).filter(Boolean),
+ href: text(topic.href),
+ floating,
+ children: Object.entries(record(topic.children)).flatMap(([group, topics]) =>
+ list(topics).map((child) => topicFromJson(child, budget, group === "detached")),
+ ),
+ };
+}
+
+/** `content.json`, the format XMind has written since XMind Zen (2018): an array of sheets, each with a `rootTopic`. */
+export function outlineFromJson(source: string): string {
+ const budget = { topics: MAX_TOPICS };
+ const sheets = list(JSON.parse(source)).map((raw): Sheet => {
+ const sheet = record(raw);
+ return { title: text(sheet.title), root: sheet.rootTopic ? topicFromJson(sheet.rootTopic, budget) : null };
+ });
+ return renderSheets(sheets);
+}
+
+interface XmlNode {
+ name: string;
+ attrs: Record<string, string>;
+ children: XmlNode[];
+ text: string;
+}
+
+const XML_ENTITIES: Readonly<Record<string, string>> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" };
+
+function decodeXml(value: string): string {
+ return value.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(\w+));/gi, (entity, hex: string | undefined, decimal: string | undefined, named: string | undefined) => {
+ if (named) return XML_ENTITIES[named] ?? entity;
+ const code = hex ? Number.parseInt(hex, 16) : Number(decimal);
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity;
+ });
+}
+
+const localName = (name: string): string => name.slice(name.indexOf(":") + 1);
+
+/** Elements, attributes, text and CDATA only, with namespace prefixes dropped; a `>` inside an attribute value ends the
+ * tag early, which XMind never writes (it escapes it). */
+function parseXml(source: string): XmlNode {
+ const root: XmlNode = { name: "", attrs: {}, children: [], text: "" };
+ const stack = [root];
+ let cursor = 0;
+ let elements = 0;
+ while (cursor < source.length) {
+ const top = stack[stack.length - 1]!;
+ const open = source.indexOf("<", cursor);
+ if (open < 0) break;
+ top.text += decodeXml(source.slice(cursor, open));
+ if (source.startsWith("<![CDATA[", open)) {
+ const end = source.indexOf("]]>", open + 9);
+ if (end < 0) break;
+ top.text += source.slice(open + 9, end);
+ cursor = end + 3;
+ continue;
+ }
+ if (source.startsWith("<!--", open)) {
+ const end = source.indexOf("-->", open + 4);
+ if (end < 0) break;
+ cursor = end + 3;
+ continue;
+ }
+ const close = source.indexOf(">", open);
+ if (close < 0) break;
+ const tag = source.slice(open + 1, close);
+ cursor = close + 1;
+ if (tag.startsWith("?") || tag.startsWith("!")) continue;
+ if (tag.startsWith("/")) {
+ if (stack.length > 1) stack.pop();
+ continue;
+ }
+ if (++elements > MAX_XML_ELEMENTS) throw new Error("too many elements");
+ const selfClosing = tag.endsWith("/");
+ const body = selfClosing ? tag.slice(0, -1) : tag;
+ const nameEnd = body.search(/\s/);
+ const node: XmlNode = { name: localName(nameEnd < 0 ? body : body.slice(0, nameEnd)), attrs: {}, children: [], text: "" };
+ if (nameEnd >= 0) {
+ for (const match of body.slice(nameEnd).matchAll(/\s+([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy)) {
+ node.attrs[localName(match[1]!)] = decodeXml(match[2] ?? match[3] ?? "");
+ }
+ }
+ top.children.push(node);
+ if (!selfClosing) stack.push(node);
+ }
+ return root;
+}
+
+const child = (node: XmlNode | undefined, name: string): XmlNode | undefined =>
+ node?.children.find((candidate) => candidate.name === name);
+const children = (node: XmlNode | undefined, name: string): XmlNode[] =>
+ node?.children.filter((candidate) => candidate.name === name) ?? [];
+
+function topicFromXml(node: XmlNode, floating = false): Topic {
+ return {
+ title: child(node, "title")?.text ?? "",
+ note: child(child(node, "notes"), "plain")?.text ?? "",
+ labels: children(child(node, "labels"), "label").map((label) => label.text).filter(Boolean),
+ markers: children(child(node, "marker-refs"), "marker-ref").map((marker) => marker.attrs["marker-id"] ?? "").filter(Boolean),
+ href: node.attrs.href ?? "",
+ floating,
+ children: children(child(node, "children"), "topics").flatMap((group) =>
+ children(group, "topic").map((topic) => topicFromXml(topic, group.attrs.type === "detached")),
+ ),
+ };
+}
+
+/** `content.xml`, the format of XMind 8 and earlier: `xmap-content` holding `sheet` elements, each with one root `topic`. */
+export function outlineFromXml(source: string): string {
+ const sheets = children(child(parseXml(source), "xmap-content"), "sheet").map((sheet): Sheet => {
+ const root = child(sheet, "topic");
+ return { title: child(sheet, "title")?.text ?? "", root: root ? topicFromXml(root) : null };
+ });
+ return renderSheets(sheets);
+}
+
+const oneLine = (value: string): string => value.replace(/\s+/g, " ").trim();
+
+function renderTopic(topic: Topic, depth: number, lines: string[]): void {
+ const indent = " ".repeat(depth);
+ const details = [
+ topic.floating ? "floating" : "",
+ topic.labels.length ? `labels: ${topic.labels.map(oneLine).join(", ")}` : "",
+ topic.markers.length ? `markers: ${topic.markers.map(oneLine).join(", ")}` : "",
+ topic.href ? `link: ${oneLine(topic.href)}` : "",
+ ].filter(Boolean).join("; ");
+ lines.push(`${indent}- ${oneLine(topic.title) || "(untitled)"}${details ? ` (${details})` : ""}`);
+ for (const line of topic.note.split(/\r?\n/)) {
+ if (line.trim()) lines.push(`${indent} > ${line.trim()}`);
+ }
+ for (const next of topic.children) renderTopic(next, depth + 1, lines);
+}
+
+function renderSheets(sheets: Sheet[]): string {
+ if (!sheets.length) throw new Error("no sheets");
+ return sheets.map((sheet, index) => {
+ const lines = [`# ${oneLine(sheet.title) || `Sheet ${index + 1}`}`, ""];
+ if (sheet.root) renderTopic(sheet.root, 0, lines);
+ return lines.join("\n");
+ }).join("\n\n") + "\n";
+}
+
+async function outlineFromArchive(archive: string, scratch: string): Promise<string> {
+ const members = await readZipDirectory(archive, MAX_ARCHIVE_ENTRIES);
+ const member = members.find((entry) => entry.name === "content.json") ?? members.find((entry) => entry.name === "content.xml");
+ if (!member || member.uncompressedBytes > MAX_CONTENT_BYTES) throw new Error("no readable content");
+ const extracted = join(scratch, "content");
+ await extractZipMember(archive, member, extracted, 0o600);
+ const source = await readFile(extracted, "utf8");
+ return member.name === "content.json" ? outlineFromJson(source) : outlineFromXml(source);
+}
+
+/** An uploaded `.xmind` is a ZIP, which the attachment store never holds: what is saved is its Markdown outline, under
+ * the upload's name plus `.md`. The archive itself only ever exists in a temporary folder removed before returning. */
+export async function saveXmindUpload(
+ chunks: AsyncIterable<Uint8Array>,
+ originalName: string,
+ options: { uploadId?: string } = {},
+): Promise<SavedFile> {
+ const name = `${originalName}.md`;
+ sanitizeSharedFileName(name, "text/markdown");
+ const scratch = await mkdtemp(join(tmpdir(), "omb-xmind-"));
+ try {
+ const archive = join(scratch, "map.xmind");
+ let bytes = 0;
+ await pipeline(
+ chunks,
+ async function* (source: AsyncIterable<Uint8Array>) {
+ for await (const chunk of source) {
+ bytes += chunk.byteLength;
+ if (bytes > FILE_MAX_BYTES) throw statusError(413, `file exceeds ${FILE_MAX_BYTES} bytes`);
+ yield chunk;
+ }
+ },
+ createWriteStream(archive, { mode: 0o600 }),
+ );
+ if (bytes === 0) throw statusError(400, "empty file");
+ let outline: string;
+ try {
+ outline = await outlineFromArchive(archive, scratch);
+ } catch {
+ throw statusError(400, "not a readable XMind file");
+ }
+ return await saveFile((async function* () { yield Buffer.from(outline, "utf8"); })(), name, "text/markdown", {
+ uploadId: options.uploadId,
+ });
+ } finally {
+ await rm(scratch, { recursive: true, force: true });
+ }
+}
diff --git a/src/lib/composer-attachments.ts b/src/lib/composer-attachments.ts
index 18f025b7d7..ff8e1fc683 100644
--- a/src/lib/composer-attachments.ts
+++ b/src/lib/composer-attachments.ts
@@ -178,6 +178,7 @@ const DOCUMENT_MIMES: Readonly<Record<string, string>> = {
odt: "application/vnd.oasis.opendocument.text",
ods: "application/vnd.oasis.opendocument.spreadsheet",
odp: "application/vnd.oasis.opendocument.presentation",
+ xmind: "application/vnd.xmind.workbook",
};
const ACCEPTED_DOCUMENT_MIMES = new Set(Object.values(DOCUMENT_MIMES));
diff --git a/src/lib/intake-files.test.ts b/src/lib/intake-files.test.ts
index e207cd28aa..15440a495d 100644
--- a/src/lib/intake-files.test.ts
+++ b/src/lib/intake-files.test.ts
@@ -37,6 +37,21 @@ describe("intakeFiles", () => {
fetch.mockRestore();
}
});
+ it("uploads a mind map as an XMind workbook though the browser gives it no type", async () => {
+ const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({
+ path: "/private/attachments/id.md", name: "Plan.xmind.md", bytes: 9,
+ }), { status: 201, headers: { "content-type": "application/json" } }));
+ try {
+ const out = await intakeFiles([new File(["PK"], "Plan.xmind", { type: "" })], {
+ allowImages: true, getPath: onDisk, uploadImage: async () => null,
+ });
+ expect(fetch.mock.calls[0]![1]).toMatchObject({ headers: { "content-type": "application/vnd.xmind.workbook" } });
+ expect(out.attachments).toEqual([expect.objectContaining({ kind: "file", name: "Plan.xmind.md", path: "/private/attachments/id.md" })]);
+ expect(out.problems).toEqual([]);
+ } finally {
+ fetch.mockRestore();
+ }
+ });
it("uploads images and keeps ordinary files as paths", async () => {
const out = await intakeFiles([file("shot.png", "image/png"), file("notes.txt", "text/plain")], {
allowImages: true,