Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(export): keep later speakers outside unfinished code blocks
Afloatfc72f7f0f6b9
diff --git a/server/headless/export.test.ts b/server/headless/export.test.tsindex edd39fac56..5e8518cf4c 100644--- a/server/headless/export.test.ts+++ b/server/headless/export.test.ts@@ -6,6 +6,7 @@ import type { AddressInfo } from "node:net";import { tmpdir } from "node:os";import { basename, dirname, join } from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { fromMarkdown } from "mdast-util-from-markdown";import { htmlFallbackText } from "../../shared/app.ts";import { parseWidgetInput, widgetToText } from "../../shared/widget.ts";@@ -162,6 +163,45 @@ function checkReportFiles(out: string, result: { files: Array<{ link: string; en}describe("export", () => {+ it.each(["```js\nconst answer = 42;", "~~~js\nconst answer = 42;"])("exports a follow-up after an unfinished code block: %s", async (text) => {+ const previous = messages[LEAD]!;+ messages[LEAD] = [+ { id: "partial", role: "bot", kind: "text", text },+ { id: "follow-up", role: "user", kind: "text", text: "Please use Python instead." },+ ];+ try {+ const out = mkdtempSync(join(dir, "unfinished-code-"));+ const { code } = await run(["export", "--thread", LEAD, "--out", out, "--json"]);+ expect(code).toBe(0);+ const nodes = fromMarkdown(readFileSync(join(out, "transcripts/conversation-lead-thr.md"), "utf8")).children;+ expect(nodes.filter((node) => node.type === "code").map((node) => node.value)).toEqual(["const answer = 42;"]);+ expect(nodes.some((node) => node.type === "paragraph" && node.children.some((child) => child.type === "text" && child.value === "Please use Python instead."))).toBe(true);+ } finally {+ messages[LEAD] = previous;+ }+ });++ it("keeps later messages readable when the transcript limit cuts a complete code block", async () => {+ const previous = messages[LEAD]!;+ const text = `\`\`\`text\n${"a line of output\n".repeat(4_000)}\`\`\``;+ messages[LEAD] = [+ { id: "large-reply", role: "bot", kind: "text", text },+ { id: "follow-up", role: "user", kind: "text", text: "Summarize this output." },+ ];+ try {+ const out = mkdtempSync(join(dir, "truncated-code-"));+ const { code } = await run(["export", "--thread", LEAD, "--out", out, "--json"]);+ expect(code).toBe(0);+ const saved = JSON.parse(readFileSync(join(out, "transcripts/conversation-lead-thr.json"), "utf8")) as { messages: Array<{ text: string }> };+ expect(saved.messages[0]!.text).toBe(`${text.slice(0, 50_000)}…`);+ const nodes = fromMarkdown(readFileSync(join(out, "transcripts/conversation-lead-thr.md"), "utf8")).children;+ expect(nodes.find((node) => node.type === "code")?.value).toBe(fromMarkdown(saved.messages[0]!.text).children.find((node) => node.type === "code")?.value);+ expect(nodes.at(-1)).toMatchObject({ type: "paragraph", children: [{ type: "text", value: "Summarize this output." }] });+ } finally {+ messages[LEAD] = previous;+ }+ });+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);diff --git a/server/headless/export.ts b/server/headless/export.tsindex ff53cd520c..be76a8d2a2 100644--- a/server/headless/export.ts+++ b/server/headless/export.ts@@ -4,6 +4,7 @@ import { Readable, Transform } from "node:stream";import { pipeline } from "node:stream/promises";import type { ReadableStream as WebReadableStream } from "node:stream/web";+import { closeUnfinishedCodeFence } from "../../shared/markdown-code-fence.ts";import { messageFileTargets } from "../message-file.ts";import { EXIT, flag, HeadlessError, parseCount, parseSize, usageError } from "./args.ts";import { readJob, type HeadlessClient } from "./client.ts";@@ -80,7 +81,7 @@ function markdownOf(title: string, messages: readonly Rec[], botName: string): sconst who = message.role === "user"? `${message.sender?.name ?? "User"}${message.via === "api" ? " (via the local API)" : ""}`: message.from?.name ?? botName;- if ((message.kind === "text" || message.kind === "widget" || message.kind === "app") && message.text) lines.push(`**${who}:**`, "", String(message.text), "");+ if ((message.kind === "text" || message.kind === "widget" || message.kind === "app") && message.text) lines.push(`**${who}:**`, "", closeUnfinishedCodeFence(String(message.text)), "");else if (message.kind === "activity" && message.tool) lines.push(`> ${message.tool.name}`, "");else if (message.kind === "screen") lines.push("> [screen capture]", "");else if (message.kind === "options" && message.card) lines.push(`> ${message.card.title}${message.card.answered ? ` — answered: ${message.card.answered}` : ""}`, "");diff --git a/server/routes/threads-export.test.ts b/server/routes/threads-export.test.tsindex 0637e7de38..9e917ab1c8 100644--- a/server/routes/threads-export.test.ts+++ b/server/routes/threads-export.test.ts@@ -2,6 +2,7 @@ import { rmSync } from "node:fs";import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { fromMarkdown } from "mdast-util-from-markdown";import { WIDGET_SAMPLES } from "../../shared/widget-samples.ts";import { createAgentCard, prepareWidgetPress } from "../chat-widgets.ts";@@ -49,6 +50,22 @@ async function serve(store: Store): Promise<string> {}describe("GET /api/threads/:id/export", () => {+ it.each(["```js\nconst answer = 42;", "~~~js\nconst answer = 42;"])("keeps a follow-up outside an unfinished code block: %s", async (text) => {+ const store = new Store(() => sonnet);+ const bot = store.createBot({ name: "Coder" }, { seedMessages: false });+ store.appendMessage(bot.threadId, { role: "bot", kind: "text", text });+ store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "Please use Python instead." });+ const base = await serve(store);++ const response = await fetch(`${base}/api/threads/${bot.threadId}/export`);+ expect(response.status).toBe(200);+ const nodes = fromMarkdown(await response.text()).children;+ expect(nodes.filter((node) => node.type === "code").map((node) => node.value)).toEqual(["const answer = 42;"]);+ expect(nodes.some((node) => node.type === "paragraph" && node.children.some((child) => child.type === "text" && child.value === "Please use Python instead."))).toBe(true);+ const json = await (await fetch(`${base}/api/threads/${bot.threadId}/export?format=json`)).json() as { messages: Array<{ text: string }> };+ expect(json.messages.map((message) => message.text)).toEqual([text, "Please use Python instead."]);+ });+it("exports a widget as its text fallback, between the lines around it", async () => {const store = new Store(() => sonnet);const bot = store.createBot({ name: "Scout" }, { seedMessages: false });diff --git a/server/routes/threads.ts b/server/routes/threads.tsindex 3e01b6da39..3e63276407 100644--- a/server/routes/threads.ts+++ b/server/routes/threads.ts@@ -3,6 +3,7 @@ import { basename, join } from "node:path";import type { BotsResponse, SearchResponse, WireBot, WireGroup } from "../../shared/wire.ts";import { NO_SUCH_BOT } from "../../shared/bot-read.ts";+import { closeUnfinishedCodeFence } from "../../shared/markdown-code-fence.ts";import { KEPT_ORIGINALS_DIR, keptOriginal } from "../attachment-originals.ts";import {ATTACHMENTS_DIR, attachmentStorageUsage, clearAttachments, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES,@@ -591,7 +592,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {const who = msg.role === "user"? msg.via === "api" ? `${sentBy} (via the local API)` : sentBy: (msg.from?.name ?? bot?.name ?? "Bot");- if ((msg.kind === "text" || msg.kind === "widget" || msg.kind === "app") && msg.text) lines.push(`**${who}:**`, "", msg.text, "");+ if ((msg.kind === "text" || msg.kind === "widget" || msg.kind === "app") && msg.text) lines.push(`**${who}:**`, "", closeUnfinishedCodeFence(msg.text), "");else if (msg.kind === "activity" && msg.tool) lines.push(`> ${msg.tool.name}`, "");else if (msg.kind === "screen") lines.push("> [screen capture]", "");else if (msg.kind === "options" && msg.card) {diff --git a/server/transcript-fence-export.e2e.test.ts b/server/transcript-fence-export.e2e.test.tsnew file mode 100644index 0000000000..853f654e52--- /dev/null+++ b/server/transcript-fence-export.e2e.test.ts@@ -0,0 +1,51 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { fromMarkdown } from "mdast-util-from-markdown";+import { expect, it } from "vitest";++import { runControlOmb } from "../scripts/control-omb.ts";+import { launchRestartableServer } from "./testing/restartable-server.ts";++it("keeps a persisted unfinished reply separate from its follow-up in HTTP and CLI Markdown exports", async () => {+ const fixture = await launchRestartableServer();+ const { url, dataDir } = fixture;+ const partial = "Here is the example:\n\n```js\nconst answer = 42;";+ const followUp = "Please use Python instead.";+ try {+ const { bot } = await runControlOmb(["new-bot", "--name", "Coder", "--url", url]) as { bot: { activeTaskId: string } };+ await fixture.stop();+ const db = new DatabaseSync(join(dataDir, "messages.db"));+ try {+ let parentId = db.prepare("SELECT active_leaf_id FROM thread_state WHERE thread_id = ?").get(bot.activeTaskId)?.active_leaf_id ?? null;+ for (const [index, text] of [partial, followUp].entries()) {+ const message = { id: `unfinished-reply-${index}`, at: Date.now() + index, role: index ? "user" : "bot", kind: "text", text, parentId };+ db.prepare("INSERT INTO messages (thread_id, id, at, role, kind, text, json) VALUES (?, ?, ?, ?, ?, ?, ?)")+ .run(bot.activeTaskId, message.id, message.at, message.role, message.kind, message.text, JSON.stringify(message));+ parentId = message.id;+ }+ db.prepare("INSERT INTO thread_state (thread_id, active_leaf_id) VALUES (?, ?) ON CONFLICT(thread_id) DO UPDATE SET active_leaf_id = excluded.active_leaf_id")+ .run(bot.activeTaskId, parentId);+ } finally {+ db.close();+ }+ await fixture.start();+ expect(await runControlOmb(["doctor", "--url", url])).toMatchObject({ ok: true });++ const response = await fetch(`${url}/api/threads/${bot.activeTaskId}/export`);+ expect(response.status).toBe(200);+ const markdown = await response.text();+ const out = join(dataDir, "exported-conversation");+ const exported = await runControlOmb(["export", "--thread", bot.activeTaskId, "--out", out, "--url", url]) as { transcripts: Array<{ file: string }> };+ const file = exported.transcripts[0]!.file;+ const saved = JSON.parse(readFileSync(join(out, file), "utf8")) as { messages: Array<{ text: string }> };+ expect(saved.messages.slice(-2).map((message) => message.text)).toEqual([partial, followUp]);+ for (const content of [markdown, readFileSync(join(out, file.replace(/\.json$/, ".md")), "utf8")]) {+ const nodes = fromMarkdown(content).children;+ expect(nodes.filter((node) => node.type === "code").map((node) => node.value)).toEqual(["const answer = 42;"]);+ expect(nodes.some((node) => node.type === "paragraph" && node.children.some((child) => child.type === "text" && child.value === followUp))).toBe(true);+ }+ } finally {+ await fixture.close();+ }+}, 90_000);diff --git a/shared/markdown-code-fence.test.ts b/shared/markdown-code-fence.test.tsnew file mode 100644index 0000000000..bfb349193f--- /dev/null+++ b/shared/markdown-code-fence.test.ts@@ -0,0 +1,56 @@+import { fromMarkdown } from "mdast-util-from-markdown";+import { describe, expect, it } from "vitest";++import { closeUnfinishedCodeFence } from "./markdown-code-fence.ts";++describe("closeUnfinishedCodeFence", () => {+ it.each([+ ["```js\nconst answer = 42;", "\n```"],+ ["~~~js\nconst answer = 42;", "\n~~~"],+ ["````md\n```js\nconst answer = 42;\n```", "\n````"],+ ["~~~~\n```\n~~~", "\n~~~~"],+ ["```", "\n```"],+ ["~~~", "\n~~~"],+ ["```js\nanswer\n", "```"],+ ["```js\nanswer\n\n", "```"],+ ["```js\r\nanswer\r\n", "```"],+ ["~~~js\ranswer\r", "~~~"],+ [" ```js\n answer", "\n```"],+ ["```js\nanswer\n``` trailing text", "\n```"],+ ["```js\nanswer\n\t```", "\n```"],+ ])("closes only the unfinished block without changing its code: %j", (text, suffix) => {+ const closed = closeUnfinishedCodeFence(text!);+ expect(closed).toBe(text + suffix!);+ const before = fromMarkdown(text!).children.find((node) => node.type === "code")!;+ const after = fromMarkdown(`${closed}\n\n## Next speaker\n\nA follow-up.`).children;+ expect(after.find((node) => node.type === "code")?.value).toBe(before.value);+ expect(after.find((node) => node.type === "heading")).toMatchObject({ depth: 2, children: [{ type: "text", value: "Next speaker" }] });+ });++ it.each([+ "Plain words with `inline code`.",+ " Leading spaces and a hard break \n",+ "```js\nanswer\n```",+ "~~~js\nanswer\n~~~~~ \t\n\n",+ " ````md\n```js\nanswer\n```\n ````\n\n",+ "```js\r\nanswer\r\n```\r\n",+ "~~~js\ranswer\r~~~\r",+ "```js\nanswer\n```\n\nDone.",+ " ```\n indented code\n",+ "<pre>\n```\nHTML contents\n</pre>",+ "```invalid`info\nordinary text",+ ])("preserves complete Markdown byte for byte: %j", (text) => {+ expect(closeUnfinishedCodeFence(text)).toBe(text);+ });++ it.each([+ "> ```js\n> const answer = 42;",+ "- ```js\n const answer = 42;",+ "> - ~~~js\n> const answer = 42;",+ ])("leaves container fences alone when the next speaker ends the container: %j", (text) => {+ expect(closeUnfinishedCodeFence(text)).toBe(text);+ const nodes = fromMarkdown(`${text}\n\n## Next speaker\n\nA follow-up.`).children;+ expect(nodes.find((node) => node.type === "heading")).toMatchObject({ depth: 2, children: [{ type: "text", value: "Next speaker" }] });+ expect(nodes.at(-1)).toMatchObject({ type: "paragraph", children: [{ type: "text", value: "A follow-up." }] });+ });+});diff --git a/shared/markdown-code-fence.ts b/shared/markdown-code-fence.tsnew file mode 100644index 0000000000..04c52a8688--- /dev/null+++ b/shared/markdown-code-fence.ts@@ -0,0 +1,13 @@+import { fromMarkdown } from "mdast-util-from-markdown";++export function closeUnfinishedCodeFence(text: string): string {+ if (!/^ {0,3}(?:`{3,}|~{3,})/m.test(text)) return text;+ const last = fromMarkdown(text).children.at(-1);+ if (last?.type !== "code" || !last.position) return text;+ const lines = text.slice(last.position.start.offset, last.position.end.offset).split(/\r\n?|\n/);+ const fence = /^ {0,3}(`{3,}|~{3,})/.exec(lines[0]!)?.[1];+ if (!fence) return text;+ const closing = /^ {0,3}(`+|~+)[\t ]*$/.exec(lines.at(-1)!)?.[1];+ if (lines.length > 1 && closing?.startsWith(fence)) return text;+ return `${text}${/[\r\n]$/.test(text) ? "" : "\n"}${fence}`;+}diff --git a/src/lib/export-transcript.test.ts b/src/lib/export-transcript.test.tsindex 4efcce52fb..649fa33f04 100644--- a/src/lib/export-transcript.test.ts+++ b/src/lib/export-transcript.test.ts@@ -108,6 +108,22 @@ describe("export-transcript", () => {expect(markdown).toContain("Implementation is in progress.");});+ it.each(["```js\nconst answer = 42;", "~~~js\nconst answer = 42;", "````md\n```js\nconst answer = 42;"])("keeps later speakers outside an unfinished code block: %s", (text) => {+ const markdown = formatTranscriptMarkdown({+ title: "Coder", botName: "Coder", exportedAt: fixedDate,+ messages: [+ { id: "partial", role: "bot", kind: "text", text, at: 1 },+ { id: "follow-up", role: "user", kind: "text", text: "Please use Python instead.", at: 2 },+ ],+ });+ const nodes = fromMarkdown(markdown).children;+ expect(nodes.filter((node) => node.type === "heading")).toHaveLength(3);+ expect(nodes.filter((node) => node.type === "code").map((node) => node.value)).toEqual([+ fromMarkdown(text).children.find((node) => node.type === "code")!.value,+ ]);+ expect(nodes.some((node) => node.type === "paragraph" && node.children.some((child) => child.type === "text" && child.value === "Please use Python instead."))).toBe(true);+ });+it("formats option cards and tool activities cleanly", () => {const messages: Message[] = [{diff --git a/src/lib/export-transcript.ts b/src/lib/export-transcript.tsindex 4d45e09d9f..b7b26567d2 100644--- a/src/lib/export-transcript.ts+++ b/src/lib/export-transcript.ts@@ -1,4 +1,5 @@import type { Message } from "@/state/store";+import { closeUnfinishedCodeFence } from "../../shared/markdown-code-fence";import { splitTranscriptAttachments } from "./composer-attachments";import { copyText } from "./copy-text";@@ -80,7 +81,7 @@ export function formatTranscriptMarkdown(options: ExportTranscriptOptions): striconst userContent = isUser ? splitTranscriptAttachments(message.text ?? "", false, false) : null;const text = userContent?.display ?? message.text;if (text?.trim()) {- messageLines.push(text);+ messageLines.push(closeUnfinishedCodeFence(text));}// Export display names, never private storage paths or actionable image URLs.