Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Add Markdown conversation export (#7664)

Ben Younesa3129dfa3a91
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index c16a8cc40fe..224405b0d1a 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -132,6 +132,8 @@ import {
usePinnedProjectsStore,
useChatPreferencesStore,
usePromptQueueUI,
+ CONVERSATION_MARKDOWN_FORMAT,
+ CONVERSATION_MARKDOWN_LABEL,
type ProjectRecord,
type SidebarItem,
} from "@/features/chat";
@@ -234,7 +236,11 @@ type NavRowDef = {
children?: ReactNode;
};
-type ConversationExportFormat = "raw-jsonl" | "csv" | "sharegpt-jsonl";
+type ConversationExportFormat =
+ | "raw-jsonl"
+ | "csv"
+ | "sharegpt-jsonl"
+ | typeof CONVERSATION_MARKDOWN_FORMAT;
// A pinned project shows this many recent chats before "Show more".
const PINNED_PROJECT_CHAT_LIMIT = 4;
@@ -246,6 +252,7 @@ const CHAT_EXPORT_OPTIONS: Array<{
{ label: "Raw JSONL", format: "raw-jsonl" },
{ label: "CSV", format: "csv" },
{ label: "ShareGPT JSONL", format: "sharegpt-jsonl" },
+ { label: CONVERSATION_MARKDOWN_LABEL, format: CONVERSATION_MARKDOWN_FORMAT },
];
async function exportConversationByFormat(
@@ -262,6 +269,13 @@ async function exportConversationByFormat(
return exports.exportConversationCsv(threadId);
case "sharegpt-jsonl":
return exports.exportConversationShareGPT(threadId);
+ case CONVERSATION_MARKDOWN_FORMAT:
+ return exports.exportConversationMarkdown(threadId);
+ default: {
+ // Exhaustive: a new format is a build error, not a menu item that does nothing.
+ const unhandled: never = format;
+ throw new Error(`Unhandled export format: ${String(unhandled)}`);
+ }
}
}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index dc9199cfe16..e7b6b781c89 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -75,6 +75,7 @@ import {
exportConversationShareGPT,
exportConversationRawJsonl,
exportConversationCsv,
+ exportConversationMarkdown,
} from "@/features/chat/prompt-storage/prompt-storage-dialog";
import {
listPromptEntries,
@@ -118,6 +119,7 @@ import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";
import {
PLUS_MENU_ORDER,
+ CONVERSATION_MARKDOWN_LABEL,
PROMPT_QUEUE_RUN_FAILED_EVENT,
PROMPT_QUEUE_STOP_EVENT,
addQueuedChatRunSettingsThreadIds,
@@ -4489,6 +4491,16 @@ const ComposerToolsMenu: FC<{
>
ShareGPT JSONL
</DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => {
+ if (!activeThreadId) return;
+ exportConversationMarkdown(activeThreadId).catch((error) => {
+ if (!isDownloadCancelled(error)) toast.error("Export failed.");
+ });
+ }}
+ >
+ {CONVERSATION_MARKDOWN_LABEL}
+ </DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
),
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 4941ef7fbd9..984425e9a3c 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -74,6 +74,10 @@ import { isTauri } from "@/lib/api-base";
import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
+import {
+ CONVERSATION_MARKDOWN_FORMAT,
+ CONVERSATION_MARKDOWN_LABEL,
+} from "./utils/conversation-markdown";
import {
Archive03Icon,
BubbleChatTemporaryIcon,
@@ -1004,7 +1008,11 @@ function createThreadNonce(): string {
}
// Chat export formats, mirroring the sidebar chat menu.
-type ProjectChatExportFormat = "raw-jsonl" | "csv" | "sharegpt-jsonl";
+type ProjectChatExportFormat =
+ | "raw-jsonl"
+ | "csv"
+ | "sharegpt-jsonl"
+ | typeof CONVERSATION_MARKDOWN_FORMAT;
const PROJECT_CHAT_EXPORT_OPTIONS: Array<{
label: string;
format: ProjectChatExportFormat;
@@ -1012,6 +1020,10 @@ const PROJECT_CHAT_EXPORT_OPTIONS: Array<{
{ label: "Raw JSONL", format: "raw-jsonl" },
{ label: "CSV", format: "csv" },
{ label: "ShareGPT JSONL", format: "sharegpt-jsonl" },
+ {
+ label: CONVERSATION_MARKDOWN_LABEL,
+ format: CONVERSATION_MARKDOWN_FORMAT,
+ },
];
async function exportProjectConversation(
@@ -1021,7 +1033,12 @@ async function exportProjectConversation(
const exports = await import("./prompt-storage/prompt-storage-dialog");
if (format === "raw-jsonl") return exports.exportConversationRawJsonl(threadId);
if (format === "csv") return exports.exportConversationCsv(threadId);
- return exports.exportConversationShareGPT(threadId);
+ if (format === CONVERSATION_MARKDOWN_FORMAT)
+ return exports.exportConversationMarkdown(threadId);
+ if (format === "sharegpt-jsonl") return exports.exportConversationShareGPT(threadId);
+ // Was a fallthrough return, so an unhandled format silently exported ShareGPT.
+ const unhandled: never = format;
+ throw new Error(`Unhandled export format: ${String(unhandled)}`);
}
async function exportProjectChatItem(
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index c67f0f9ad6c..9a11bb39eb0 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -164,6 +164,10 @@ export {
readComposerDraft,
writeComposerDraft,
} from "./utils/composer-draft";
+export {
+ CONVERSATION_MARKDOWN_FORMAT,
+ CONVERSATION_MARKDOWN_LABEL,
+} from "./utils/conversation-markdown";
export {
EXPORT_FORMATS_LIST,
buildFineTuneJsonl,
diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
index 078acec59ae..989f64ce7dc 100644
--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
@@ -59,6 +59,11 @@ import { notifyChatHistoryUpdated } from "../api/chat-api";
import { isMcpImageToolResult } from "../api/chat-adapter";
import { usePlusMenuPrefsStore } from "../stores/plus-menu-prefs-store";
import type { ThreadRecord, MessageRecord } from "../types";
+import { createConversationMarkdownExporter } from "../utils/conversation-markdown-export";
+import {
+ contentBlocksToMarkdownBlocks,
+ renderConversationBlocks,
+} from "../utils/conversation-markdown";
function newId(): string {
return crypto.randomUUID().replace(/-/g, "").slice(0, 12);
@@ -253,6 +258,26 @@ function messageToText(msg: { content: unknown; attachments?: unknown }): string
return parts.join("\n\n");
}
+// Markdown counterpart to messageToText: same content and attachments, but each
+// part keeps its shape so the renderer can fence tool calls and collapse thinking.
+function messageToMarkdown(msg: { content: unknown; attachments?: unknown }): string {
+ const normalizeToolResult = (result: unknown): unknown =>
+ isMcpImageToolResult(result) ? result.text : result;
+ const blocks = contentBlocksToMarkdownBlocks(msg.content, normalizeToolResult);
+ if (Array.isArray(msg.attachments)) {
+ for (const attachment of msg.attachments as Array<{ content?: unknown }>) {
+ if (!attachment?.content) continue;
+ blocks.push(
+ ...contentBlocksToMarkdownBlocks(
+ attachment.content,
+ normalizeToolResult,
+ ),
+ );
+ }
+ }
+ return renderConversationBlocks(blocks);
+}
+
// OpenAI messages array (tool-calling + multimodal fine-tuning): tool calls →
// "tool_calls" + separate "role":"tool" messages; images → "image_url" parts;
// audio dropped; thinking kept as a text part.
@@ -402,6 +427,14 @@ export async function exportConversationCsv(threadId: string): Promise<void> {
);
}
+export const exportConversationMarkdown = createConversationMarkdownExporter({
+ loadMessages: loadConversationMessages,
+ renderMessage: messageToMarkdown,
+ download: downloadBlob,
+ exportTimestamp: exportTs,
+ notifyNoContent: () => toast.info("No exportable content."),
+});
+
export type ConvExportFormat = "jsonl-raw" | "csv" | "sharegpt";
const EXPORT_FORMAT_LABELS: Record<ConvExportFormat, string> = {
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 6aef0b8debc..58f15347a9b 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -37,6 +37,7 @@ import { isTauri } from "@/lib/api-base";
import { isDownloadCancelled } from "@/lib/native-files";
import { isMultimodalResponse } from "./types/api";
import { getImageInputUnavailableReason } from "./utils/image-input-support";
+import { CONVERSATION_MARKDOWN_LABEL } from "./utils/conversation-markdown";
import { pasteClipboardFiles } from "./utils/clipboard-files";
import { confirmStopRunningChatsIfNeeded } from "./utils/confirm-stop-running-chats";
import { requestLocalPromptQueueStop } from "./utils/prompt-queue-boundary";
@@ -73,6 +74,7 @@ import {
exportConversationShareGPT,
exportConversationRawJsonl,
exportConversationCsv,
+ exportConversationMarkdown,
} from "./prompt-storage/prompt-storage-dialog";
import { listPromptEntries, type PromptEntry } from "./api/prompts-api";
import { McpComposerButton } from "./mcp-composer-button";
@@ -1805,6 +1807,10 @@ export function SharedComposer({
{ label: "Raw JSONL", fn: exportConversationRawJsonl },
{ label: "CSV", fn: exportConversationCsv },
{ label: "ShareGPT JSONL", fn: exportConversationShareGPT },
+ {
+ label: CONVERSATION_MARKDOWN_LABEL,
+ fn: exportConversationMarkdown,
+ },
].map(({ label, fn }) => (
<DropdownMenuItem
key={label}
diff --git a/studio/frontend/src/features/chat/thread-sidebar.tsx b/studio/frontend/src/features/chat/thread-sidebar.tsx
index bd1fb9d87ce..73551643189 100644
--- a/studio/frontend/src/features/chat/thread-sidebar.tsx
+++ b/studio/frontend/src/features/chat/thread-sidebar.tsx
@@ -46,6 +46,7 @@ import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "sonner";
import { useChatRuntimeStore } from "./stores/chat-runtime-store";
import type { ChatView } from "./types";
+import { CONVERSATION_MARKDOWN_LABEL } from "./utils/conversation-markdown";
import {
deleteChatItem,
renameChatItem,
@@ -56,6 +57,7 @@ import {
exportConversationRawJsonl,
exportConversationCsv,
exportConversationShareGPT,
+ exportConversationMarkdown,
exportBulkConversationsMerged,
exportBulkConversationsSeparate,
EXPORT_FORMATS_LIST,
@@ -69,6 +71,7 @@ const EXPORT_FORMATS = [
{ label: "Raw JSONL", fn: exportConversationRawJsonl },
{ label: "CSV", fn: exportConversationCsv },
{ label: "ShareGPT JSONL", fn: exportConversationShareGPT },
+ { label: CONVERSATION_MARKDOWN_LABEL, fn: exportConversationMarkdown },
] as const;
async function getThreadIdsForItem(item: SidebarItem): Promise<string[]> {
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
new file mode 100644
index 00000000000..63ee6d0ef22
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ CONVERSATION_MARKDOWN_EXTENSION,
+ CONVERSATION_MARKDOWN_MIME_TYPE,
+ type ConversationMarkdownMessage,
+ buildConversationMarkdown,
+} from "./conversation-markdown.ts";
+
+type StoredConversationMessage = {
+ readonly role: unknown;
+};
+
+type ConversationMarkdownExportDependencies<
+ Message extends StoredConversationMessage,
+> = {
+ readonly loadMessages: (
+ threadId: string,
+ ) => Promise<readonly Message[] | null>;
+ readonly renderMessage: (message: Message) => string;
+ readonly download: (
+ content: string,
+ filename: string,
+ mimeType: string,
+ ) => Promise<void>;
+ readonly exportTimestamp: () => string;
+ readonly notifyNoContent: () => void;
+};
+
+export function createConversationMarkdownExporter<
+ Message extends StoredConversationMessage,
+>({
+ loadMessages,
+ renderMessage,
+ download,
+ exportTimestamp,
+ notifyNoContent,
+}: ConversationMarkdownExportDependencies<Message>): (
+ threadId: string,
+) => Promise<void> {
+ return async (threadId) => {
+ const messages = await loadMessages(threadId);
+ if (!messages) {
+ return;
+ }
+ const normalizedMessages: ConversationMarkdownMessage[] = messages.map(
+ (message) => ({
+ role: String(message.role ?? ""),
+ content: renderMessage(message),
+ }),
+ );
+ const markdown = buildConversationMarkdown(normalizedMessages);
+ if (!markdown) {
+ notifyNoContent();
+ return;
+ }
+ await download(
+ markdown,
+ `conversation-${exportTimestamp()}.${CONVERSATION_MARKDOWN_EXTENSION}`,
+ CONVERSATION_MARKDOWN_MIME_TYPE,
+ );
+ };
+}
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown.ts b/studio/frontend/src/features/chat/utils/conversation-markdown.ts
new file mode 100644
index 00000000000..f82b230332c
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown.ts
@@ -0,0 +1,606 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type ConversationMarkdownMessage = {
+ readonly role: string;
+ readonly content: string;
+};
+
+export const CONVERSATION_MARKDOWN_FORMAT = "markdown";
+export const CONVERSATION_MARKDOWN_LABEL = "Markdown";
+export const CONVERSATION_MARKDOWN_EXTENSION = "md";
+export const CONVERSATION_MARKDOWN_MIME_TYPE = "text/markdown";
+
+const ROLE_LABELS: Readonly<Record<string, string>> = {
+ assistant: "Assistant",
+ system: "System",
+ user: "User",
+};
+
+function roleLabel(role: string): string {
+ const knownLabel = ROLE_LABELS[role];
+ if (knownLabel) {
+ return knownLabel;
+ }
+ // Imported transcripts keep their own role strings verbatim, and this one is
+ // interpolated into a ## heading closeOpenBlocks never sees: a line break would
+ // end the heading, a tag would open an element nothing later closes.
+ const label = role.replace(/[\s]+/g, " ").replace(/[<>&\\[\]`*_#]/g, "").trim();
+ return label.length > 0
+ ? `${label[0]?.toUpperCase()}${label.slice(1)}`
+ : "Message";
+}
+
+// A message split into renderable pieces. The JSONL/CSV exports flatten to plain
+// text, leaving tool calls as one-line JSON and thinking as [thinking] markers;
+// markdown is a document format, so each piece renders on its own terms.
+export type ConversationMarkdownBlock =
+ | { readonly kind: "text"; readonly text: string }
+ | { readonly kind: "thinking"; readonly text: string }
+ | {
+ readonly kind: "tool-call";
+ readonly name: string;
+ readonly args?: unknown;
+ readonly result?: unknown;
+ }
+ | { readonly kind: "attachment"; readonly label: string }
+ | { readonly kind: "source"; readonly title: string; readonly url: string };
+
+const GENERATED_IMAGE_PLACEHOLDER = "[generated image omitted]";
+const GENERATED_IMAGE_BYTES_KEY = "image_b64";
+const GENERATED_AUDIO_PLACEHOLDER = "[generated audio omitted]";
+const INLINE_DATA_PLACEHOLDER = "[inline data omitted]";
+const LINE_BREAK_PATTERN = /[\r\n]/;
+// Generated audio is a custom tag holding a base64 data URI: player bytes, not transcript.
+const AUDIO_DATA_URI_PATTERN = /<audio-player\s+src="data:[^"]*"\s*\/>/g;
+// Both ends, not just the closer: reasoning quoting a whole details element would
+// keep its opener and spend this block's closer, hiding every later turn.
+const DETAILS_TAG_PATTERN = /<(\/?)(details)((?:\s[^>]*)?)>/gi;
+// A blank line and a ## heading separate turns, which is enough for the markdown
+// parser but not for the browser: an element left open keeps reading, so a message
+// that forgets a closing fence, comment or tag silently takes every later turn
+// inside it. Each message therefore closes what it opened.
+//
+// This is a line scanner over a fixed tag set, not a parser, and is meant to stay
+// one: it covers what people actually leave open (an unclosed fence, an
+// unterminated comment, a quoted details, a pasted script). A tag left unfinished
+// is neutralised rather than closed, since nothing can close it. Shapes needing a
+// real html tokenizer (processing instructions, self-closing svg or mathml) are
+// repaired best effort or not at all: the export is a document, not a security
+// boundary.
+const FENCE_LINE_PATTERN = /^( {0,3})(`{3,}|~{3,})([\s\S]*)$/;
+const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/;
+// Equal-length delimiters, so a wide span may hold a narrower run: `` `x` `` is
+// one span, not two. CommonMark 6.1 reads a whole contiguous run as one delimiter,
+// so neither end may sit inside a longer one: ```x`` is live text, and masking it
+// would hide the tags it holds. The leading capture pins the opener to the start
+// of its run in place of a lookbehind, which Safari only gained in 16.4 and would
+// take the whole bundle down if unparseable.
+const CODE_SPAN_PATTERN = /(^|[^`])(`+)(?!`)[\s\S]*?\2(?!`)/g;
+// The html tokenizer ends a tag name at whitespace, a solidus or >.
+const TAG_OPEN_PATTERN = /^<(\/?)([A-Za-z][^\s/>]*)/;
+// Block quote markers are structure, not content: a > that opens a quoted line
+// is not the > that finishes a tag left open on the line above.
+const BLOCKQUOTE_PATTERN = /^(?: {0,3}>)+/;
+// CommonMark 6.3: an angle-bracket destination is a url, so [x](<details>) is a
+// link, not an element; reading it as one emits or spends a closer wrongly.
+const LINK_DESTINATION_PATTERN = /\]\(\s*<[^<>]*>/g;
+// An image description becomes the alt attribute, escaped, so a tag in there
+// is text. A link label is not: CommonMark parses raw html inside one.
+const IMAGE_DESCRIPTION_PATTERN = /!\[[^\]]*\]/g;
+// A run left over once a line's closed spans are masked opens a span into the next.
+const OPEN_RUN_PATTERN = /(^|[^`])(`+)(?!`)/;
+// Block structure is read before inlines, so a line starting with a tag begins
+// an html block and ends any span that was still open above it.
+const HTML_BLOCK_START_PATTERN = /^ {0,3}<[A-Za-z!/?]/;
+
+// A run only opens a span if its match arrives: an unmatched run is live text.
+// The search stops where a span would, at a blank line or an html block.
+function runClosesLater(lines: readonly string[], from: number, run: string): boolean {
+ const closer = new RegExp("(^|[^`])(" + run + ")(?!`)");
+ for (let index = from; index < lines.length; index += 2) {
+ const line = lines[index] as string;
+ const content = line.slice((BLOCKQUOTE_PATTERN.exec(line)?.[0] ?? "").length);
+ if (line.trim() === "" || HTML_BLOCK_START_PATTERN.test(content)) return false;
+ if (closer.test(line)) return true;
+ }
+ return false;
+}
+// Comments, processing instructions and cdata sections run to their own
+// terminator, not to a blank line or a tag, so one left open swallows the file.
+// ownLine: a ?> appended to the last line would land inside the instruction.
+const LITERAL_BLOCKS = [
+ { opener: "<!--", terminator: "-->", ownLine: false },
+ { opener: "<?", terminator: "?>", ownLine: true },
+ { opener: "<![CDATA[", terminator: "]]>", ownLine: true },
+] as const;
+// One that opens and closes on the same line is literal text, not an opener.
+const CLOSED_LITERAL_PATTERN = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[[\s\S]*?\]\]>/g;
+// Nothing at all closes plaintext: the browser reads every byte after it as
+// that element's text. The opener itself is the only thing that can be undone.
+const UNCLOSABLE_ELEMENTS: ReadonlySet<string> = new Set(["plaintext"]);
+// Containers need a blank line before their closer or it reads as a lazy
+// continuation; in a raw text element that blank line is content instead.
+const CONTAINER_ELEMENTS: ReadonlySet<string> = new Set(["details", "select"]);
+// Read as text, not markup, until their own end tag, so a </details> inside one
+// must not close a details open outside it. pre is absent: it holds real markup.
+const RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set([
+ "iframe",
+ "noembed",
+ "noframes",
+ "script",
+ "style",
+ "textarea",
+ "title",
+ "xmp",
+]);
+// CommonMark start condition 1: inside one of these the markdown block runs to
+// the end tag, so a fence or an indented code line in there is literal text.
+const CONDITION_1_ELEMENTS: ReadonlySet<string> = new Set([
+ "pre",
+ "script",
+ "style",
+ "textarea",
+]);
+// CommonMark 2.4: a backslash before ascii punctuation makes it literal, so
+// \<script> opens nothing. Only an odd run escapes: an even match length with the <.
+const ESCAPED_LT_PATTERN = /\\+</g;
+
+// Elements a blank line does not close: the browser either reads their content as
+// text or holds them open as a container, so whatever follows is swallowed rather
+// than rendered. GFM's tagfilter lists nearly the same set for the same reason.
+const PERSISTENT_ELEMENTS: ReadonlySet<string> = new Set([
+ "details",
+ "iframe",
+ "noembed",
+ "noframes",
+ "pre",
+ "script",
+ "select",
+ "style",
+ "template",
+ "textarea",
+ "title",
+ "xmp",
+]);
+
+function closeOpenBlocks(text: string): string {
+ // Split keeping the separators, so a repaired line can be put back verbatim.
+ const parts = text.split(/(\r\n|[\r\n])/);
+ let fence: { readonly run: string; readonly indent: string; readonly quoted: boolean } | null =
+ null;
+ let block: (typeof LITERAL_BLOCKS)[number] | null = null;
+ let blankBefore = true;
+ // An indented code block runs through blank lines, so its state outlives its opener.
+ let indented = false;
+ // A code span may cross a soft line break, so an unclosed run keeps masking.
+ let span = "";
+ // Tag starts whose > has not arrived, and the quote a value is inside. Every <
+ // after an unfinished tag is inside it, until that one is neutralised.
+ let unfinished: { readonly part: number; readonly column: number }[] = [];
+ let quote = "";
+ const open: string[] = [];
+ // Openers to neutralise, because no closer would reach them.
+ const escapes: { readonly part: number; readonly column: number }[] = [];
+
+ for (let part = 0; part < parts.length; part += 2) {
+ let line = parts[part] as string;
+ const blankLine = line.trim() === "";
+ const afterBlank = blankBefore;
+ blankBefore = blankLine;
+ if (block !== null) {
+ const end = line.indexOf(block.terminator);
+ if (end === -1) continue;
+ // The rest of the line is live again, so blank what the block held and rescan.
+ const consumed = end + block.terminator.length;
+ line = " ".repeat(consumed) + line.slice(consumed);
+ block = null;
+ }
+ // Fences, indents and tags mean different things inside a block quote, so read
+ // them against the quoted content. Blanking, not slicing, keeps columns intact.
+ const marker = BLOCKQUOTE_PATTERN.exec(line)?.[0] ?? "";
+ const content = line.slice(marker.length);
+ // The quote ending ends the fence, so an unclosed one never reaches the next turn.
+ if (fence !== null && fence.quoted && marker === "") fence = null;
+ const literal = open.some((name) => CONDITION_1_ELEMENTS.has(name));
+ const [, indent = "", run, info = ""] =
+ unfinished.length || literal ? [] : FENCE_LINE_PATTERN.exec(content) ?? [];
+ if (fence !== null) {
+ // A closer repeats the opener's character, is at least as long, and has no info.
+ if (run && run[0] === fence.run[0] && run.length >= fence.run.length && !info.trim()) {
+ fence = null;
+ }
+ continue;
+ }
+ if (run && (run[0] === "~" || !info.includes("`"))) {
+ fence = { run, indent, quoted: marker !== "" };
+ continue;
+ }
+ // A backtick opener with a backtick in its info string is not a fence: the line
+ // is prose and falls through, since its tags are live. Indented code, code spans
+ // and closed comments are literal, so a < in one opens nothing; but indented code
+ // only starts after a blank line, else the line is a lazy continuation and live.
+ if (!unfinished.length && !literal) {
+ indented = indented
+ ? blankLine || INDENTED_CODE_PATTERN.test(content)
+ : afterBlank && INDENTED_CODE_PATTERN.test(content);
+ if (indented) continue;
+ }
+ // A span in progress swallows this line up to its closing run. A blank line
+ // ends it, and so does an html block, which the parser sees first.
+ if (span && (blankLine || HTML_BLOCK_START_PATTERN.test(content))) span = "";
+ if (span) {
+ const closer = new RegExp("(^|[^`])(" + span + ")(?!`)").exec(line);
+ if (closer === null) continue;
+ const consumed = (closer.index ?? 0) + closer[0].length;
+ line = " ".repeat(consumed) + line.slice(consumed);
+ span = "";
+ }
+ // Every substitution below preserves length, so columns still map to the original.
+ let prose = line
+ .replace(BLOCKQUOTE_PATTERN, (marker) => " ".repeat(marker.length))
+ .replace(CODE_SPAN_PATTERN, (span: string, lead: string) =>
+ lead + " ".repeat(span.length - lead.length),
+ )
+ .replace(IMAGE_DESCRIPTION_PATTERN, (alt) => " ".repeat(alt.length))
+ .replace(LINK_DESTINATION_PATTERN, (link) => " ".repeat(link.length))
+ .replace(CLOSED_LITERAL_PATTERN, (span) => " ".repeat(span.length));
+ // The backslash is markdown's, so it holds only where that parser reads inlines.
+ if (!literal) {
+ prose = prose.replace(ESCAPED_LT_PATTERN, (backslashes) =>
+ backslashes.length % 2 === 0 ? `${backslashes.slice(0, -1)} ` : backslashes,
+ );
+ }
+ // A run left after masking closed spans runs on, so the rest of the line is code.
+ const leftover = OPEN_RUN_PATTERN.exec(prose);
+ if (leftover !== null && runClosesLater(parts, part + 2, leftover[2] as string)) {
+ span = leftover[2] as string;
+ const from = (leftover.index ?? 0) + (leftover[1] as string).length;
+ prose = prose.slice(0, from) + " ".repeat(prose.length - from);
+ }
+ // These first: whichever opens last swallows every tag after it.
+ let blockAt = -1;
+ if (!unfinished.length) {
+ for (const candidate of LITERAL_BLOCKS) {
+ const at = prose.lastIndexOf(candidate.opener);
+ if (at > blockAt && at > prose.lastIndexOf(candidate.terminator)) {
+ blockAt = at;
+ block = candidate;
+ }
+ }
+ }
+ const tags = blockAt === -1 ? prose : prose.slice(0, blockAt);
+
+ let at = 0;
+ while (at <= tags.length) {
+ if (!unfinished.length) {
+ const start = tags.indexOf("<", at);
+ if (start === -1) break;
+ if (!TAG_OPEN_PATTERN.test(tags.slice(start))) {
+ at = start + 1;
+ continue;
+ }
+ unfinished = [{ part, column: start }];
+ quote = "";
+ at = start + 1;
+ }
+ // The > only ends a tag outside an attribute value, so an unbalanced quote reads on.
+ let end = at;
+ for (; end < tags.length; end += 1) {
+ const character = tags[end] as string;
+ if (character === "<" && TAG_OPEN_PATTERN.test(tags.slice(end))) {
+ unfinished.push({ part, column: end });
+ } else if (quote) {
+ if (character === quote) quote = "";
+ } else if (character === '"' || character === "'") {
+ quote = character;
+ } else if (character === ">") {
+ break;
+ }
+ }
+ if (end === tags.length) break;
+ const start = unfinished[0] as { part: number; column: number };
+ const [, slash, name = ""] =
+ TAG_OPEN_PATTERN.exec((parts[start.part] as string).slice(start.column)) ?? [];
+ unfinished = [];
+ at = end + 1;
+ const tag = name.toLowerCase();
+ const rawText = [...open].reverse().find((name_) => RAW_TEXT_ELEMENTS.has(name_));
+ if (rawText !== undefined && !(slash && tag === rawText)) continue;
+ if (!slash && UNCLOSABLE_ELEMENTS.has(tag)) {
+ escapes.push(start);
+ continue;
+ }
+ if (!PERSISTENT_ELEMENTS.has(tag)) continue;
+ if (!slash) {
+ open.push(tag);
+ continue;
+ }
+ // Innermost matching opener, so </div></details> still closes the details. A
+ // closer with no opener is inert, so it must not license a later opener.
+ const index = open.lastIndexOf(tag);
+ if (index !== -1) open.splice(index, 1);
+ }
+ }
+
+ // An unfinished tag cannot be closed: the tokenizer is still reading its name or
+ // an attribute value, so a later </script> is swallowed as more of the same tag.
+ // Neutralising the < is the only repair. Last first, so columns do not shift.
+ escapes.push(...unfinished);
+ escapes.sort((a, b) => b.part - a.part || b.column - a.column);
+ for (const { part, column } of escapes) {
+ const line = parts[part] as string;
+ parts[part] = `${line.slice(0, column)}&lt;${line.slice(column + 1)}`;
+ }
+
+ // Close on the body's own line ending. A renderer that ignores bare carriage
+ // returns would read a \n-prefixed closer as a fresh fence instead.
+ const eol = !text.includes("\n") && text.includes("\r") ? "\r" : "\n";
+ let out = parts.join("");
+ if (block !== null) out += block.ownLine ? `${eol}${block.terminator}` : block.terminator;
+ // Indented to the opener's column: at column zero the closer would end its list.
+ if (fence !== null && !fence.quoted) out += `${eol}${fence.indent}${fence.run}`;
+ // Innermost first, so closers nest as the openers did; each on its own line after
+ // a blank one so it is a block, not a lazy continuation of the paragraph above.
+ for (let index = open.length - 1; index >= 0; index -= 1) {
+ const name = open[index] as string;
+ out += CONTAINER_ELEMENTS.has(name)
+ ? `${eol}${eol}</${name}>`
+ : `${eol}</${name}>`;
+ }
+ return out;
+}
+
+// Long enough to not be closed early by backticks inside the body.
+function fence(body: string, language = ""): string {
+ const longestRun = [...body.matchAll(/`+/g)].reduce(
+ (max, [run]) => Math.max(max, run.length),
+ 0,
+ );
+ const ticks = "`".repeat(Math.max(3, longestRun + 1));
+ return `${ticks}${language}\n${body}\n${ticks}`;
+}
+
+function inlineCode(raw: string): string {
+ // A code span cannot hold a line break: it would leave the rest loose as markdown.
+ const value = raw.replace(/[\r\n]+/g, " ");
+ const longestRun = [...value.matchAll(/`+/g)].reduce(
+ (max, [run]) => Math.max(max, run.length),
+ 0,
+ );
+ const ticks = "`".repeat(longestRun + 1);
+ // Padding keeps an edge backtick from closing the span and an empty value from
+ // collapsing into one delimiter run. CommonMark 6.1 also strips one space from each
+ // end of a span padded at both, unless all spaces, so such a value needs a spare pair.
+ const stripped = value.startsWith(" ") && value.endsWith(" ") && value.trim() !== "";
+ const pad = !value || value.startsWith("`") || value.endsWith("`") || stripped ? " " : "";
+ return `${ticks}${pad}${value}${pad}${ticks}`;
+}
+
+// Labels sit inside ** ** and [ ]: a line break ends either and lets the rest out
+// as markdown, a backtick opens a code span, and < starts inline html.
+function escapeMarkdownLabel(value: string): string {
+ // Not _: it cannot emphasise inside a word, so snake_case keys stay readable.
+ return value.replace(/[\r\n]+/g, " ").replace(/([\\[\]*`<])/g, "\\$1");
+}
+
+// A destination is parsed, not copied: CommonMark 6.2 resolves entity references
+// inside it and 2.4 consumes a backslash before ASCII punctuation. Search results
+// are attacker-controllable and both rules move where the link goes:
+// `https://docs.unsloth.ai&commat;evil.test/` decodes to credentials on evil.test.
+// Only an entity-opening ampersand is escaped, so ordinary query separators stay
+// readable, and &amp; not %26 because encoding one folds it into the value before.
+const ENTITY_REFERENCE_PATTERN =
+ /&(?=(?:[A-Za-z][A-Za-z0-9]{1,31}|#\d{1,7}|#[Xx][0-9A-Fa-f]{1,6});)/g;
+
+function escapeMarkdownDestination(url: string): string {
+ // Percent-encoded, not doubled: %5C is what a renderer writes for it anyway.
+ return url
+ .replaceAll("<", "%3C")
+ .replaceAll(">", "%3E")
+ .replaceAll("\\", "%5C")
+ .replace(ENTITY_REFERENCE_PATTERN, "&amp;");
+}
+
+function safeSourceUrl(raw: string): string {
+ const value = raw.trim();
+ if (!value || LINE_BREAK_PATTERN.test(value)) {
+ return "";
+ }
+ try {
+ // encodeURI throws on a lone surrogate, so it stays inside the guard.
+ if (value.startsWith("#")) {
+ return escapeMarkdownDestination(encodeURI(value));
+ }
+ const parsed = new URL(value);
+ return parsed.protocol === "http:" || parsed.protocol === "https:"
+ ? escapeMarkdownDestination(parsed.href)
+ : "";
+ } catch {
+ return "";
+ }
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+// A multi-line string is almost always source, so fence it as-is rather than let it
+// read as a JSON string full of \n. No language tag: guessing wrong is worse than none.
+function renderValue(label: string, value: unknown): string[] {
+ if (value === undefined) return [];
+ const escapedLabel = escapeMarkdownLabel(label);
+ // Scalars as text too: a json fence spends three lines on `10`.
+ if (value === null || typeof value !== "object") {
+ const text = typeof value === "string" ? value : String(value);
+ if (LINE_BREAK_PATTERN.test(text))
+ return [`**${escapedLabel}:**`, fence(text)];
+ // A code span, not escaping: any list of metacharacters to escape misses one.
+ return [`**${escapedLabel}:** ${inlineCode(text)}`];
+ }
+ return [
+ `**${escapedLabel}:**`,
+ fence(JSON.stringify(value, null, 2), "json"),
+ ];
+}
+
+function renderBlock(block: ConversationMarkdownBlock): string {
+ // Verbatim: leading indentation can be code, so trim is only an emptiness test.
+ if (block.kind === "text") {
+ return block.text.trim() ? closeOpenBlocks(block.text) : "";
+ }
+ if (block.kind === "thinking") {
+ if (!block.text.trim()) return "";
+ // A quoted </details> would end the block early; the entity renders the same.
+ const text = closeOpenBlocks(
+ block.text.replace(DETAILS_TAG_PATTERN, "&lt;$1$2$3>"),
+ );
+ // Collapsed so the transcript reads as the conversation first.
+ return `<details>\n<summary>thinking</summary>\n\n${text}\n\n</details>`;
+ }
+ if (block.kind === "attachment") {
+ // Escaped: a link reference definition elsewhere would turn [label] into a link.
+ return escapeMarkdownLabel(block.label);
+ }
+ if (block.kind === "source") {
+ const url = safeSourceUrl(block.url);
+ // Code span, not plain text: a title that is itself a bare url would autolink.
+ return url
+ ? `**source:** [${escapeMarkdownLabel(block.title)}](<${url}>)`
+ : `**source:** ${inlineCode(block.title)}`;
+ }
+ const parts: string[] = [`**tool call:** ${inlineCode(block.name)}`];
+ if (isPlainObject(block.args)) {
+ for (const [key, value] of Object.entries(block.args)) {
+ parts.push(...renderValue(key, value));
+ }
+ } else if (block.args !== undefined) {
+ parts.push(...renderValue("args", block.args));
+ }
+ if (block.result !== undefined) {
+ parts.push(...renderValue("result", block.result));
+ }
+ return parts.join("\n\n");
+}
+
+function withoutGeneratedImageBytes(value: unknown): unknown {
+ if (
+ !isPlainObject(value) ||
+ typeof value[GENERATED_IMAGE_BYTES_KEY] !== "string"
+ ) {
+ return value;
+ }
+ const metadata = Object.fromEntries(
+ Object.entries(value).filter(([key]) => key !== GENERATED_IMAGE_BYTES_KEY),
+ );
+ // Placeholder last: a result carrying its own image key must not shadow it.
+ return { ...metadata, image: GENERATED_IMAGE_PLACEHOLDER };
+}
+
+function withoutInlineDataBytes(
+ part: Record<string, unknown>,
+): Record<string, unknown> {
+ const inlineData = part.inlineData;
+ if (!isPlainObject(inlineData) || typeof inlineData.data !== "string") {
+ return part;
+ }
+ return {
+ ...part,
+ inlineData: { ...inlineData, data: INLINE_DATA_PLACEHOLDER },
+ };
+}
+
+// Gemini keeps a code-execution turn replayable by stashing the raw part in
+// args.google.native_part, base64 inlineData included. Keep metadata, drop bytes.
+function withoutNativePartBytes(args: unknown): unknown {
+ if (!isPlainObject(args) || !isPlainObject(args.google)) return args;
+ const google = args.google;
+ const native = google.native_part;
+ if (!isPlainObject(native)) return args;
+ const cleaned = Array.isArray(native.parts)
+ ? {
+ ...native,
+ parts: native.parts.map((part) =>
+ isPlainObject(part) ? withoutInlineDataBytes(part) : part,
+ ),
+ }
+ : withoutInlineDataBytes(native);
+ return { ...args, google: { ...google, native_part: cleaned } };
+}
+
+function withoutGeneratedAudioBytes(text: string): string {
+ return text.replace(AUDIO_DATA_URI_PATTERN, GENERATED_AUDIO_PLACEHOLDER);
+}
+
+export function contentBlocksToMarkdownBlocks(
+ content: unknown,
+ normalizeToolResult: (result: unknown) => unknown = (result) => result,
+): ConversationMarkdownBlock[] {
+ if (typeof content === "string") {
+ return [{ kind: "text", text: withoutGeneratedAudioBytes(content) }];
+ }
+ // Otherwise a content-less record stringifies to undefined and breaks the export.
+ if (content == null) {
+ return [];
+ }
+ if (!Array.isArray(content)) {
+ return [{ kind: "text", text: JSON.stringify(content) }];
+ }
+
+ const blocks: ConversationMarkdownBlock[] = [];
+ for (const part of content) {
+ if (!part || typeof part !== "object") continue;
+ const p = part as Record<string, unknown>;
+ if (p.type === "text" && typeof p.text === "string") {
+ blocks.push({ kind: "text", text: withoutGeneratedAudioBytes(p.text) });
+ } else if (p.type === "reasoning" || p.type === "thinking") {
+ const thinkText =
+ typeof p.thinking === "string"
+ ? p.thinking
+ : typeof p.text === "string"
+ ? p.text
+ : "";
+ if (thinkText) blocks.push({ kind: "thinking", text: thinkText });
+ } else if (p.type === "tool-call") {
+ blocks.push({
+ kind: "tool-call",
+ name: typeof p.toolName === "string" ? p.toolName : "unknown",
+ args: withoutNativePartBytes(p.args),
+ result: withoutGeneratedImageBytes(normalizeToolResult(p.result)),
+ });
+ } else if (
+ p.type === "source" &&
+ typeof p.title === "string" &&
+ typeof p.url === "string"
+ ) {
+ blocks.push({ kind: "source", title: p.title, url: p.url });
+ } else if (p.type === "image") {
+ blocks.push({ kind: "attachment", label: "[image attachment]" });
+ } else if (p.type === "audio") {
+ blocks.push({ kind: "attachment", label: "[audio attachment]" });
+ }
+ }
+ return blocks;
+}
+
+export function renderConversationBlocks(
+ blocks: readonly ConversationMarkdownBlock[],
+): string {
+ return blocks
+ .map((block) => renderBlock(block))
+ .filter((rendered) => rendered.length > 0)
+ .join("\n\n");
+}
+
+export function buildConversationMarkdown(
+ messages: readonly ConversationMarkdownMessage[],
+): string {
+ const sections = messages.flatMap(({ role, content }) => {
+ if (!content.trim()) {
+ return [];
+ }
+ const label = roleLabel(role);
+ return [`## ${label}\n\n${content}`];
+ });
+ return sections.length > 0 ? `${sections.join("\n\n")}\n` : "";
+}
diff --git a/studio/frontend/tests/conversation-markdown-export.test.ts b/studio/frontend/tests/conversation-markdown-export.test.ts
new file mode 100644
index 00000000000..40eab123994
--- /dev/null
+++ b/studio/frontend/tests/conversation-markdown-export.test.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createConversationMarkdownExporter } from "../src/features/chat/utils/conversation-markdown-export.ts";
+
+type TestMessage = {
+ readonly role: unknown;
+ readonly text: string;
+};
+
+function exporterFor(
+ messages: readonly TestMessage[] | null,
+ downloads: Array<{
+ content: string;
+ filename: string;
+ mimeType: string;
+ }>,
+ notifications: string[],
+) {
+ return createConversationMarkdownExporter<TestMessage>({
+ loadMessages: async (threadId) => {
+ assert.equal(threadId, "thread-1");
+ return messages;
+ },
+ renderMessage: (message) => message.text,
+ download: async (content, filename, mimeType) => {
+ downloads.push({ content, filename, mimeType });
+ },
+ exportTimestamp: () => "2026-07-31T00-00-00",
+ notifyNoContent: () => notifications.push("empty"),
+ });
+}
+
+test("downloads a timestamped Markdown conversation", async () => {
+ const downloads: Array<{
+ content: string;
+ filename: string;
+ mimeType: string;
+ }> = [];
+ const notifications: string[] = [];
+ await exporterFor(
+ [{ role: "user", text: "Hello" }],
+ downloads,
+ notifications,
+ )("thread-1");
+
+ assert.deepEqual(downloads, [
+ {
+ content: "## User\n\nHello\n",
+ filename: "conversation-2026-07-31T00-00-00.md",
+ mimeType: "text/markdown",
+ },
+ ]);
+ assert.deepEqual(notifications, []);
+});
+
+test("does nothing when the conversation does not exist", async () => {
+ const downloads: Array<{
+ content: string;
+ filename: string;
+ mimeType: string;
+ }> = [];
+ const notifications: string[] = [];
+ await exporterFor(null, downloads, notifications)("thread-1");
+ assert.deepEqual(downloads, []);
+ assert.deepEqual(notifications, []);
+});
+
+test("notifies when every message is empty", async () => {
+ const downloads: Array<{
+ content: string;
+ filename: string;
+ mimeType: string;
+ }> = [];
+ const notifications: string[] = [];
+ await exporterFor(
+ [{ role: null, text: " " }],
+ downloads,
+ notifications,
+ )("thread-1");
+ assert.deepEqual(downloads, []);
+ assert.deepEqual(notifications, ["empty"]);
+});
diff --git a/studio/frontend/tests/conversation-markdown.test.ts b/studio/frontend/tests/conversation-markdown.test.ts
new file mode 100644
index 00000000000..9782ffdaffa
--- /dev/null
+++ b/studio/frontend/tests/conversation-markdown.test.ts
@@ -0,0 +1,1123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ buildConversationMarkdown,
+ contentBlocksToMarkdownBlocks,
+ renderConversationBlocks,
+} from "../src/features/chat/utils/conversation-markdown.ts";
+
+test("exports a readable markdown transcript in conversation order", () => {
+ assert.equal(
+ buildConversationMarkdown([
+ { role: "system", content: "Be concise." },
+ { role: "user", content: "Explain `RED → GREEN`." },
+ { role: "assistant", content: "1. Write a failing test.\n2. Fix it." },
+ ]),
+ [
+ "## System",
+ "",
+ "Be concise.",
+ "",
+ "## User",
+ "",
+ "Explain `RED → GREEN`.",
+ "",
+ "## Assistant",
+ "",
+ "1. Write a failing test.\n2. Fix it.",
+ "",
+ ].join("\n"),
+ );
+});
+
+test("omits empty messages without rewriting markdown content", () => {
+ assert.equal(
+ buildConversationMarkdown([
+ { role: "user", content: " " },
+ { role: "assistant", content: "# Existing heading\n\n> quote" },
+ ]),
+ "## Assistant\n\n# Existing heading\n\n> quote\n",
+ );
+});
+
+test("keeps an unknown role label and returns empty output for empty content", () => {
+ assert.equal(
+ buildConversationMarkdown([{ role: "tool", content: "result" }]),
+ "## Tool\n\nresult\n",
+ );
+ assert.equal(
+ buildConversationMarkdown([{ role: "user", content: "\n\t" }]),
+ "",
+ );
+});
+
+test("labels a missing role as a generic message", () => {
+ assert.equal(
+ buildConversationMarkdown([{ role: "", content: "orphaned content" }]),
+ "## Message\n\norphaned content\n",
+ );
+});
+
+test("renders a multi-line arg as code instead of an escaped json string", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "tool-call",
+ name: "render_html",
+ args: {
+ code: "<!DOCTYPE html>\n<html>\n <body>hi</body>\n</html>",
+ title: "Canvas",
+ },
+ result: "Rendered HTML canvas: Canvas.",
+ },
+ ]),
+ [
+ "**tool call:** `render_html`",
+ "",
+ "**code:**",
+ "",
+ "```",
+ "<!DOCTYPE html>",
+ "<html>",
+ " <body>hi</body>",
+ "</html>",
+ "```",
+ "",
+ "**title:** `Canvas`",
+ "",
+ "**result:** `Rendered HTML canvas: Canvas.`",
+ ].join("\n"),
+ );
+});
+
+test("keeps single line markup inert without fencing it", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "tool-call",
+ name: "render_html",
+ args: { code: "<script>alert(1)</script>" },
+ result: "ok",
+ },
+ ]),
+ [
+ "**tool call:** `render_html`",
+ "",
+ "**code:** `<script>alert(1)</script>`",
+ "",
+ "**result:** `ok`",
+ ].join("\n"),
+ );
+});
+
+test("renders markdown syntax in a tool value as its own text", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "tool-call",
+ name: "search",
+ args: { top_hit: "[login](https://phish.test)" },
+ result: "![x](https://evil.test/pixel.png) **bold**",
+ },
+ ]),
+ [
+ "**tool call:** `search`",
+ "",
+ "**top_hit:** `[login](https://phish.test)`",
+ "",
+ "**result:** `![x](https://evil.test/pixel.png) **bold**`",
+ ].join("\n"),
+ );
+});
+
+test("keeps a tool name with a backtick inside its code span", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "tool-call", name: "foo`bar" }]),
+ "**tool call:** ``foo`bar``",
+ );
+});
+
+test("escapes emphasis characters in an arg key", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "tool-call", name: "run", args: { "a*b": "1" } },
+ ]),
+ ["**tool call:** `run`", "", "**a\\*b:** `1`"].join("\n"),
+ );
+});
+
+test("reasoning that quotes a closing details tag stays inside the block", () => {
+ const markdown = renderConversationBlocks([
+ { kind: "thinking", text: "the tag is </details> here" },
+ ]);
+ assert.equal(
+ markdown,
+ [
+ "<details>",
+ "<summary>thinking</summary>",
+ "",
+ "the tag is &lt;/details> here",
+ "",
+ "</details>",
+ ].join("\n"),
+ );
+});
+
+test("widens code spans and fences past backticks in the payload", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "tool-call", name: "run", args: { cmd: "echo ```x```" } },
+ ]),
+ ["**tool call:** `run`", "", "**cmd:** ```` echo ```x``` ````"].join("\n"),
+ );
+
+ const multiline = renderConversationBlocks([
+ { kind: "tool-call", name: "run", args: { script: "```\nx\n```" } },
+ ]);
+ assert.ok(multiline.includes("````\n```\nx\n```\n````"));
+});
+
+test("keeps whitespace that markdown depends on", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: " indented_code_block()\n" },
+ { kind: "thinking", text: " padded reasoning " },
+ { kind: "text", text: " " },
+ ]),
+ [
+ " indented_code_block()\n",
+ "",
+ "<details>",
+ "<summary>thinking</summary>",
+ "",
+ " padded reasoning ",
+ "",
+ "</details>",
+ ].join("\n"),
+ );
+});
+
+test("collapses thinking and leaves prose untouched", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "thinking", text: "weighing options" },
+ { kind: "text", text: "Here is the answer." },
+ { kind: "attachment", label: "[image attachment]" },
+ ]),
+ [
+ "<details>",
+ "<summary>thinking</summary>",
+ "",
+ "weighing options",
+ "",
+ "</details>",
+ "",
+ "Here is the answer.",
+ "",
+ "\\[image attachment\\]",
+ ].join("\n"),
+ );
+});
+
+test("omits generated image bytes while retaining useful result metadata", () => {
+ const blocks = contentBlocksToMarkdownBlocks([
+ {
+ type: "tool-call",
+ toolName: "image_generation",
+ result: {
+ image_b64: "very-large-base64-payload",
+ image_mime: "image/png",
+ size: "1024x1024",
+ },
+ },
+ ]);
+
+ const markdown = renderConversationBlocks(blocks);
+ assert.doesNotMatch(markdown, /very-large-base64-payload/);
+ assert.match(markdown, /generated image omitted/);
+ assert.match(markdown, /image\/png/);
+ assert.match(markdown, /1024x1024/);
+});
+
+test("keeps the placeholder when a result carries its own image key", () => {
+ const markdown = renderConversationBlocks(
+ contentBlocksToMarkdownBlocks([
+ {
+ type: "tool-call",
+ toolName: "image_generation",
+ result: {
+ image_b64: "very-large-base64-payload",
+ image: "thumbnail-that-should-not-win",
+ },
+ },
+ ]),
+ );
+ assert.match(markdown, /generated image omitted/);
+ assert.doesNotMatch(markdown, /thumbnail-that-should-not-win/);
+});
+
+test("omits Gemini inline data bytes while keeping the part metadata", () => {
+ const markdown = renderConversationBlocks(
+ contentBlocksToMarkdownBlocks([
+ {
+ type: "tool-call",
+ toolName: "code_execution",
+ args: {
+ google: {
+ native_part: {
+ parts: [
+ { executableCode: { code: "print(1)", language: "PYTHON" } },
+ {
+ inlineData: {
+ mimeType: "image/png",
+ data: "very-large-base64-payload",
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ ]),
+ );
+ assert.doesNotMatch(markdown, /very-large-base64-payload/);
+ assert.match(markdown, /inline data omitted/);
+ assert.match(markdown, /image\/png/);
+ assert.match(markdown, /print\(1\)/);
+});
+
+test("omits Gemini inline data bytes from a legacy single-object part", () => {
+ const markdown = renderConversationBlocks(
+ contentBlocksToMarkdownBlocks([
+ {
+ type: "tool-call",
+ toolName: "code_execution",
+ args: {
+ google: {
+ native_part: {
+ inlineData: { mimeType: "image/png", data: "legacy-payload" },
+ },
+ },
+ },
+ },
+ ]),
+ );
+ assert.doesNotMatch(markdown, /legacy-payload/);
+ assert.match(markdown, /inline data omitted/);
+});
+
+test("omits generated audio bytes from a text part", () => {
+ const markdown = renderConversationBlocks(
+ contentBlocksToMarkdownBlocks([
+ {
+ type: "text",
+ text: 'Here it is: <audio-player src="data:audio/wav;base64,QUJD" />',
+ },
+ ]),
+ );
+ assert.equal(markdown, "Here it is: [generated audio omitted]");
+});
+
+test("returns no blocks for a message stored without content", () => {
+ assert.deepEqual(contentBlocksToMarkdownBlocks(undefined), []);
+ assert.deepEqual(contentBlocksToMarkdownBlocks(null), []);
+ assert.equal(
+ renderConversationBlocks(contentBlocksToMarkdownBlocks(undefined)),
+ "",
+ );
+});
+
+test("preserves assistant citation sources in markdown exports", () => {
+ assert.equal(
+ renderConversationBlocks(
+ contentBlocksToMarkdownBlocks([
+ {
+ type: "source",
+ title: "Unsloth documentation",
+ url: "https://docs.unsloth.ai/",
+ },
+ ]),
+ ),
+ "**source:** [Unsloth documentation](<https://docs.unsloth.ai/>)",
+ );
+});
+
+test("does not turn unsafe citation schemes into markdown links", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "source", title: "Untrusted source", url: "javascript:alert(1)" },
+ ]),
+ "**source:** `Untrusted source`",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "source",
+ title: "Injected source",
+ url: "https://safe.test/\n[evil](https://evil.test)",
+ },
+ ]),
+ "**source:** `Injected source`",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "source",
+ title: "Parenthesized source",
+ url: "https://en.wikipedia.org/wiki/Foo_(bar)",
+ },
+ {
+ kind: "source",
+ title: "Attempted link injection",
+ url: "https://safe.test/) [evil](https://evil.test",
+ },
+ ]),
+ [
+ "**source:** [Parenthesized source](<https://en.wikipedia.org/wiki/Foo_(bar)>)",
+ "",
+ "**source:** [Attempted link injection](<https://safe.test/)%20[evil](https://evil.test>)",
+ ].join("\n"),
+ );
+});
+
+test("an unclosed fence cannot swallow the message that follows it", () => {
+ assert.equal(
+ buildConversationMarkdown([
+ {
+ role: "user",
+ content: renderConversationBlocks(
+ contentBlocksToMarkdownBlocks([
+ { type: "text", text: "look:\n```js\nvar a = 1;" },
+ ]),
+ ),
+ },
+ { role: "assistant", content: "Done." },
+ ]),
+ [
+ "## User",
+ "",
+ "look:",
+ "```js",
+ "var a = 1;",
+ "```",
+ "",
+ "## Assistant",
+ "",
+ "Done.",
+ "",
+ ].join("\n"),
+ );
+});
+
+test("an unterminated html comment cannot hide the message that follows it", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<!-- note" }]),
+ "<!-- note-->",
+ );
+});
+
+test("reasoning that leaves a fence open still closes its details block", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "thinking", text: "~~~\nsketch" }]),
+ [
+ "<details>",
+ "<summary>thinking</summary>",
+ "",
+ "~~~",
+ "sketch",
+ "~~~",
+ "",
+ "</details>",
+ ].join("\n"),
+ );
+});
+
+test("renders scalar args inline instead of spending a fence on each", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "tool-call",
+ name: "web_search",
+ args: { query: "lora", limit: 10, recursive: true, cursor: null },
+ },
+ ]),
+ [
+ "**tool call:** `web_search`",
+ "",
+ "**query:** `lora`",
+ "",
+ "**limit:** `10`",
+ "",
+ "**recursive:** `true`",
+ "",
+ "**cursor:** `null`",
+ ].join("\n"),
+ );
+});
+
+test("a line break in an arg key cannot end the bold label", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "tool-call",
+ name: "run",
+ args: { "a:**\n\n<img src=x onerror=alert(1)>": "1" },
+ },
+ ]),
+ [
+ "**tool call:** `run`",
+ "",
+ "**a:\\*\\* \\<img src=x onerror=alert(1)>:** `1`",
+ ].join("\n"),
+ );
+});
+
+test("a line break in a citation title cannot end the link label", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "source",
+ title: "ok\n\n<img src=x onerror=alert(1)>",
+ url: "https://good.test/",
+ },
+ ]),
+ "**source:** [ok \\<img src=x onerror=alert(1)>](<https://good.test/>)",
+ );
+});
+
+test("a rejected destination leaves a bare url title unlinkable", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "source", title: "https://evil.test/track", url: "javascript:alert(1)" },
+ ]),
+ "**source:** `https://evil.test/track`",
+ );
+});
+
+test("keeps an attachment label from resolving as a link reference", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "attachment", label: "[audio attachment]" }]),
+ "\\[audio attachment\\]",
+ );
+});
+
+test("renders an empty tool value as a code span, not two bare backticks", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "tool-call", name: "run", args: { k: "" } }]),
+ ["**tool call:** `run`", "", "**k:** ` `"].join("\n"),
+ );
+});
+
+test("fences a value whose only line break is a carriage return", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "tool-call", name: "run", args: { k: "left\rright" } },
+ ]),
+ ["**tool call:** `run`", "", "**k:**", "", "```", "left\rright", "```"].join(
+ "\n",
+ ),
+ );
+});
+
+test("drops a fragment url that cannot be encoded instead of throwing", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "source", title: "Broken", url: "#\ud800" },
+ ]),
+ "**source:** `Broken`",
+ );
+});
+
+test("closes a fence opened in a body that uses bare carriage returns", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "look:\r```js\rvar a = 1;" }]),
+ "look:\r```js\rvar a = 1;\r```",
+ );
+});
+
+test("leaves a paragraph that only looks like a fence alone", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "```a`b" }]),
+ "```a`b",
+ );
+});
+
+test("does not treat a fence closer carrying text as a closer", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "```\nx\n``` trailing" }]),
+ "```\nx\n``` trailing\n```",
+ );
+});
+
+test("leaves a comment inside a fence literal", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "```\n<!-- literal\n```" }]),
+ "```\n<!-- literal\n```",
+ );
+});
+
+test("closes a list-nested fence inside the list, not at column zero", () => {
+ // A closer at column zero ends the list first, opening a top-level fence instead.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "Steps:\n\n- run the install\n\n ```sh\n npm ci" },
+ ]),
+ "Steps:\n\n- run the install\n\n ```sh\n npm ci\n ```",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "- run\n\n ~~~\n x" }]),
+ "- run\n\n ~~~\n x\n ~~~",
+ );
+});
+
+test("closes a raw html block a blank line cannot end", () => {
+ // CommonMark start condition 1: only its own end tag ends the block.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<pre>\nhello" }]),
+ "<pre>\nhello\n</pre>",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: '<SCRIPT src="a.js">\nvar x = 1;' },
+ ]),
+ '<SCRIPT src="a.js">\nvar x = 1;\n</script>',
+ );
+ // Conditions 3, 4 and 5 run to the end of the document just the same.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<?php\necho 1;" }]),
+ "<?php\necho 1;\n?>",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<![CDATA[\nraw" }]),
+ "<![CDATA[\nraw\n]]>",
+ );
+});
+
+test("leaves a raw html block that closes itself alone", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<pre>\nhello\n</pre>" }]),
+ "<pre>\nhello\n</pre>",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<pre>hello</pre>" }]),
+ "<pre>hello</pre>",
+ );
+ // A blank line ends start conditions 6 and 7, and every turn is followed by one.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<div>\nhello" }]),
+ "<div>\nhello",
+ );
+ // Indented four spaces it is a code block, not a raw html block.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: " <pre>\n hello" }]),
+ " <pre>\n hello",
+ );
+});
+
+test("keeps a raw html start inside a fence literal", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "```\n<pre>\nhello\n```" }]),
+ "```\n<pre>\nhello\n```",
+ );
+ // And the other way round: a fence inside a raw html block is not a fence.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<pre>\n```js\nvar a = 1;" }]),
+ "<pre>\n```js\nvar a = 1;\n</pre>",
+ );
+});
+
+test("collapses line breaks inside a code span so it cannot be escaped", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "source",
+ title: "ok\n\n<img src=x onerror=alert(1)>",
+ url: "javascript:alert(1)",
+ },
+ ]),
+ "**source:** `ok <img src=x onerror=alert(1)>`",
+ );
+});
+
+test("reasoning that quotes a whole details element stays inside the block", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "thinking", text: "<details>\n<summary>FAQ</summary>\n\nbody\n\n</details>" },
+ ]),
+ [
+ "<details>",
+ "<summary>thinking</summary>",
+ "",
+ "&lt;details>",
+ "<summary>FAQ</summary>",
+ "",
+ "body",
+ "",
+ "&lt;/details>",
+ "",
+ "</details>",
+ ].join("\n"),
+ );
+});
+
+test("escapes a details opener carrying attributes", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "thinking", text: '<details open class="x">' }]),
+ [
+ "<details>",
+ "<summary>thinking</summary>",
+ "",
+ '&lt;details open class="x">',
+ "",
+ "</details>",
+ ].join("\n"),
+ );
+});
+
+test("a comment delimiter inside a code span opens nothing", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "Prefix it with `<!--` to comment it out." },
+ ]),
+ "Prefix it with `<!--` to comment it out.",
+ );
+});
+
+test("still closes a comment opened mid-line outside a code span", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "see <div><!-- note" }]),
+ "see <div><!-- note-->",
+ );
+});
+
+test("closes an unmatched details element a later turn would fall inside", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<details>\n<summary>Steps</summary>\n\nfirst" },
+ ]),
+ "<details>\n<summary>Steps</summary>\n\nfirst\n\n</details>",
+ );
+ // Mid-line, in the case shape the tokenizer accepts but a <details ...> does not.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "hello <DETAILS/>" }]),
+ "hello <DETAILS/>\n\n</details>",
+ );
+});
+
+test("leaves a details element the message already matched alone", () => {
+ const matched = "<details>\n<summary>FAQ</summary>\n\nbody\n\n</details>";
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: matched }]),
+ matched,
+ );
+ const nested = `<details>\n<summary>outer</summary>\n\n${matched}\n\n</details>`;
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: nested }]),
+ nested,
+ );
+});
+
+test("counts details tags in order so a stray closer licenses no opener", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "</details>\n\n<details>" },
+ ]),
+ "</details>\n\n<details>\n\n</details>",
+ );
+});
+
+test("keeps a details tag inside a fence, a code span or a comment literal", () => {
+ const fenced = "```html\n<details>\n```";
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: fenced }]),
+ fenced,
+ );
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "use `<details>` for this" },
+ ]),
+ "use `<details>` for this",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<!-- <details> -->" }]),
+ "<!-- <details> -->",
+ );
+});
+
+test("keeps a citation destination from decoding into another host", () => {
+ // &commat; is an entity reference in a destination: a viewer resolves this to
+ // [email protected], which is credentials on evil.test.
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "source",
+ title: "Docs",
+ url: "https://docs.unsloth.ai&commat;evil.test/",
+ },
+ ]),
+ "**source:** [Docs](<https://docs.unsloth.ai&amp;commat;evil.test/>)",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "source",
+ title: "Numeric",
+ url: "https://x.test/?a=&#64;evil.test/",
+ },
+ ]),
+ "**source:** [Numeric](<https://x.test/?a=&amp;#64;evil.test/>)",
+ );
+});
+
+test("keeps a backslash in a citation destination from being eaten", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "source", title: "Query", url: "https://x.test/?q=\\*" },
+ ]),
+ "**source:** [Query](<https://x.test/?q=%5C*>)",
+ );
+});
+
+test("leaves an ordinary query separator in a citation readable", () => {
+ assert.equal(
+ renderConversationBlocks([
+ {
+ kind: "source",
+ title: "Search",
+ url: "https://x.test/search?q=lora&page=2&sort=new",
+ },
+ ]),
+ "**source:** [Search](<https://x.test/search?q=lora&page=2&sort=new>)",
+ );
+});
+
+test("neutralises an opener the message never finished writing", () => {
+ // A synthesized </script> after a bare <script> is read as that tag's attributes,
+ // so the element stays open; escaping the < opens nothing at all.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<script" }]),
+ "&lt;script",
+ );
+ // Any tag: an unterminated attribute value runs to the first > in the document.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: '<div class="x' }]),
+ '&lt;div class="x',
+ );
+ // Handing back what an unfinished tag swallowed can reveal an opener, so repeat.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<details\n<script" }]),
+ "&lt;details\n&lt;script",
+ );
+ // plaintext has no end tag in any parser, so it can only be neutralised.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<plaintext>" }]),
+ "&lt;plaintext>",
+ );
+});
+
+test("closes the element that was opened, not the one markdown ended on", () => {
+ // CommonMark 4.6 condition 1 ends the block at any of the four end tags, "it need
+ // not match the start tag"; the tokenizer needs this element's own (WHATWG 13.2.5).
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<script>\nvar x = 1;\n</pre>" },
+ ]),
+ "<script>\nvar x = 1;\n</pre>\n</script>",
+ );
+ // A </script> in a code span renders as escaped <code>: never a closer.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "hello <script> world `</script>`" },
+ ]),
+ "hello <script> world `</script>`\n</script>",
+ );
+});
+
+test("closes a persistent element opened part way through a line", () => {
+ // CommonMark starts no block here, but the browser is in script data to EOF.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "hello <script>" }]),
+ "hello <script>\n</script>",
+ );
+ // The tokenizer's raw text set is wider than condition 1: iframe and xmp too.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<iframe>" }]),
+ "<iframe>\n</iframe>",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "see <xmp>" }]),
+ "see <xmp>\n</xmp>",
+ );
+});
+
+test("leaves an indented code block exactly as the message wrote it", () => {
+ // Four spaces is code, so the delimiter opens nothing and a repair would alter it.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "Template:\n\n <!-- TODO fill this in" },
+ ]),
+ "Template:\n\n <!-- TODO fill this in",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "Example:\n\n <details>" },
+ ]),
+ "Example:\n\n <details>",
+ );
+ // It cannot interrupt a paragraph, so this one really is prose.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "note\n <!-- x" }]),
+ "note\n <!-- x-->",
+ );
+});
+
+test("reads a fence opener whose info string carries a line separator", () => {
+ // U+2028 is ordinary to markdown but a line terminator to a JavaScript dot.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "```js
x\nvar a = 1;" }]),
+ "```js
x\nvar a = 1;\n```",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "~~~a
b\nsketch" }]),
+ "~~~a
b\nsketch\n~~~",
+ );
+});
+
+test("does not read a block quote marker as the end of a tag", () => {
+ // The renderer strips the marker, so its > is not one the tokenizer sees: the start
+ // tag runs on and swallows the message's own </script> as attributes.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "> <script\n> </script>" },
+ ]),
+ "> <script\n> </script>\n</script>",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "> <script>\n> body" }]),
+ "> <script>\n> body\n</script>",
+ );
+});
+
+test("waits for the terminator the raw block is actually waiting for", () => {
+ // The tokenizer ends a bogus comment at the first >, but CommonMark conditions 3
+ // and 5 end at ?> and ]]>: stopping at the > in the php comparison loses the rest.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<?php\nif ($a > $b) { echo 1; }" },
+ ]),
+ "<?php\nif ($a > $b) { echo 1; }\n?>",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<![CDATA[\na > b" }]),
+ "<![CDATA[\na > b\n]]>",
+ );
+ // Condition 4 really does end at a >, and a self-closed block needs nothing.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<!DOCTYPE html>\nhi" }]),
+ "<!DOCTYPE html>\nhi",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<?php echo 1; ?>\nhi" }]),
+ "<?php echo 1; ?>\nhi",
+ );
+});
+
+test("leaves a backslash-escaped tag out of the repair scan", () => {
+ // CommonMark 2.4: \< is a literal <, so it opens nothing and needs no closer.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "\\<script>" }]),
+ "\\<script>",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "\\<!-- note" }]),
+ "\\<!-- note",
+ );
+ // And the element it hid is found again: reading the escape as live markup
+ // swallowed the details opener as raw text.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "\\<script>\n\n<details>\n\nhi" },
+ ]),
+ "\\<script>\n\n<details>\n\nhi\n\n</details>",
+ );
+ // A doubled backslash escapes itself, so the < after it is live.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "\\\\<script>" }]),
+ "\\\\<script>\n</script>",
+ );
+ // The escape is markdown's, so it does not apply where inlines are not read.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "```\n\\<script>" }]),
+ "```\n\\<script>\n```",
+ );
+});
+
+test("closes a template element before emitting the next turn", () => {
+ // Children land in a DocumentFragment that is never rendered, so later turns go too.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<template>" }]),
+ "<template>\n</template>",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "SFC:\n\n<template>\n <div>{{ msg }}</div>" },
+ ]),
+ "SFC:\n\n<template>\n <div>{{ msg }}</div>\n</template>",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<template>\n<td>a</td>\n</template>" },
+ ]),
+ "<template>\n<td>a</td>\n</template>",
+ );
+});
+
+test("keeps scanning the line a literal block ended part way through", () => {
+ // The terminator ends the block, not the line: a details opened after it is live.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<!--\n--> <details>" }]),
+ "<!--\n--> <details>\n\n</details>",
+ );
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<?\n?> <script>" }]),
+ "<?\n?> <script>\n</script>",
+ );
+});
+
+test("reduces an imported role to one line of plain text", () => {
+ // Imported role strings land in a heading closeOpenBlocks never sees.
+ assert.equal(
+ buildConversationMarkdown([{ role: "user\n\n<details>", content: "hi" }]),
+ "## User details\n\nhi\n",
+ );
+ assert.equal(
+ buildConversationMarkdown([{ role: " ", content: "hi" }]),
+ "## Message\n\nhi\n",
+ );
+ // The ordinary roles are untouched.
+ assert.equal(
+ buildConversationMarkdown([{ role: "reviewer", content: "hi" }]),
+ "## Reviewer\n\nhi\n",
+ );
+});
+
+test("keeps every line of an indented code block literal", () => {
+ // Only the first line follows a blank one, so without state the rest is scanned live.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "look:\n\n first\n <script>" },
+ ]),
+ "look:\n\n first\n <script>",
+ );
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "look:\n\n first\n <div class=\"x" },
+ ]),
+ "look:\n\n first\n <div class=\"x",
+ );
+ // A closer in there must not spend the closer of a real open element.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<details>\nreal\n\ntext\n\n a\n </details>" },
+ ]),
+ "<details>\nreal\n\ntext\n\n a\n </details>\n\n</details>",
+ );
+});
+
+test("reads a fence against its block quote rather than the raw line", () => {
+ // The marker keeps FENCE_LINE_PATTERN from matching, so quoted code was scanned live.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "> ```\n> <script>\n> ```" }]),
+ "> ```\n> <script>\n> ```",
+ );
+ // The quote ending ends the fence, so nothing is appended for it.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "> ```js\n> var a = 1;" }]),
+ "> ```js\n> var a = 1;",
+ );
+});
+
+test("treats a backtick run as one delimiter at both ends", () => {
+ // ```x`` has no matching run, so it is live text carrying an opener.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "```<script>``" }]),
+ "```<script>``\n</script>",
+ );
+ // A real span still masks.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "`<script>`" }]),
+ "`<script>`",
+ );
+});
+
+test("reads an angle bracket link destination as a url", () => {
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "[x](<details>)" }]),
+ "[x](<details>)",
+ );
+ // And it must not spend the closer of a real open element either.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<details>\nreal\n\n[x](</details>)" },
+ ]),
+ "<details>\nreal\n\n[x](</details>)\n\n</details>",
+ );
+});
+
+test("reads a closing tag inside a raw text element as text", () => {
+ // </details> there is script data, so it must not spend a real details closer.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<details>\n<script>\n</details>" }]),
+ "<details>\n<script>\n</details>\n</script>\n\n</details>",
+ );
+});
+
+test("keeps the edge spaces of a code span value", () => {
+ // CommonMark 6.1 strips one space from each end of a span padded at both.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "tool-call", name: "t", args: { k: " padded " } },
+ ]),
+ "**tool call:** `t`\n\n**k:** ` padded `",
+ );
+ // All spaces is exempt from the rule, and needs no extra pair.
+ assert.equal(
+ renderConversationBlocks([{ kind: "tool-call", name: "t", args: { k: " " } }]),
+ "**tool call:** `t`\n\n**k:** ` `",
+ );
+});
+
+test("follows a code span across a soft line break", () => {
+ // The span is one inline, so the tag inside it is literal on both lines.
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<details>\nreal\n\nuse `foo\nbar </details>` here" },
+ ]),
+ "<details>\nreal\n\nuse `foo\nbar </details>` here\n\n</details>",
+ );
+ // A run with no match is live text, not an unterminated span.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "`foo\nbar <details> here" }]),
+ "`foo\nbar <details> here\n\n</details>",
+ );
+});
+
+test("reads an image description as alt text", () => {
+ assert.equal(
+ renderConversationBlocks([
+ { kind: "text", text: "<details>\nreal\n\n![caption </details>](image.png)" },
+ ]),
+ "<details>\nreal\n\n![caption </details>](image.png)\n\n</details>",
+ );
+});
+
+test("closes a select the message left open", () => {
+ // The browser stays in select insertion mode and folds the next heading in.
+ assert.equal(
+ renderConversationBlocks([{ kind: "text", text: "<select>\n<option>one" }]),
+ "<select>\n<option>one\n\n</select>",
+ );
+});