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.

Studio: restore markdown chat import and bulk export (#12513)

Sourav Rajvi1670be34c783
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 b2419ef75f8..b2ff298704f 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
@@ -69,6 +69,7 @@ import {
savePromptList,
} from "../api/prompts-api";
import {
+ getStoredChatThread,
listStoredChatMessages,
listStoredChatThreads,
saveStoredChatThread,
@@ -97,6 +98,7 @@ import { orderByParentChain } from "../utils/message-order";
import { liveThreadBranch } from "../utils/live-thread-head";
import { unwrapPastedTextContent } from "../utils/pasted-text.ts";
import {
+ CONVERSATION_MARKDOWN_MIME_TYPE,
buildConversationMarkdown,
contentBlocksToMarkdownBlocks,
renderConversationBlocks,
@@ -555,13 +557,19 @@ export async function buildChatItemMarkdown(item: {
);
}
-export type ConvExportFormat = "jsonl-raw" | "jsonl-messages" | "csv" | "sharegpt";
+export type ConvExportFormat =
+ | "jsonl-raw"
+ | "jsonl-messages"
+ | "csv"
+ | "sharegpt"
+ | "markdown";
const EXPORT_FORMAT_LABELS: Record<ConvExportFormat, string> = {
"jsonl-raw": "Training JSONL",
"jsonl-messages": "Message JSONL",
csv: "CSV",
sharegpt: "ShareGPT JSONL",
+ markdown: "Markdown",
};
export const EXPORT_FORMATS_LIST = (
@@ -601,6 +609,10 @@ async function buildThreadContent(
return JSON.stringify({ conversations });
}
+ if (format === "markdown") {
+ return await buildConversationMarkdownForThread(threadId);
+ }
+
const rows: string[] = [];
for (const msg of messages) {
const content = messageToText(msg);
@@ -615,11 +627,15 @@ function csvHeader(format: ConvExportFormat): string {
}
function exportExt(format: ConvExportFormat): string {
- return format === "csv" ? "csv" : "jsonl";
+ if (format === "csv") return "csv";
+ if (format === "markdown") return "md";
+ return "jsonl";
}
function exportMime(format: ConvExportFormat): string {
- return format === "csv" ? CSV_MIME : "application/x-ndjson";
+ if (format === "csv") return CSV_MIME;
+ if (format === "markdown") return CONVERSATION_MARKDOWN_MIME_TYPE;
+ return "application/x-ndjson";
}
export async function exportBulkConversationsMerged(
@@ -633,6 +649,43 @@ export async function exportBulkConversationsMerged(
return;
}
+ if (format === "markdown" && threadIds.length > 1) {
+ const conversations: Array<{ id: string; title: string }> = [];
+ const pairs = new Map<string, ThreadRecord[]>();
+ for (const id of threadIds) {
+ const thread = await getStoredChatThread(id);
+ conversations.push({ id, title: thread?.title?.trim() || id });
+ if (thread?.pairId) {
+ const halves = pairs.get(thread.pairId) ?? [];
+ halves.push(thread);
+ pairs.set(thread.pairId, halves);
+ }
+ }
+ const pairedTitles = new Map<string, string>();
+ for (const [pairId, halves] of pairs) {
+ if (halves.length < 2) continue;
+ const plans = planChatItemSources(
+ { id: pairId, title: halves[0].title?.trim() || pairId, type: "pair" },
+ halves,
+ );
+ for (const plan of plans) pairedTitles.set(plan.id, plan.title);
+ }
+ for (const conversation of conversations) {
+ conversation.title = pairedTitles.get(conversation.id) ?? conversation.title;
+ }
+ const body = await buildNamedConversationsMarkdown(
+ conversations,
+ buildConversationMarkdownForThread,
+ );
+ if (!body) { toast.info("No exportable content."); return; }
+ await downloadBlob(
+ body,
+ `${basename}.md`,
+ CONVERSATION_MARKDOWN_MIME_TYPE,
+ );
+ return;
+ }
+
const parts: string[] = [];
const header = csvHeader(format);
@@ -645,7 +698,9 @@ export async function exportBulkConversationsMerged(
const body = header
? csvDocument([header, ...parts])
- : ndjsonBody(parts);
+ : format === "markdown"
+ ? parts[0] ?? ""
+ : ndjsonBody(parts);
await downloadBlob(
body,
diff --git a/studio/frontend/src/features/chat/utils/chat-import.ts b/studio/frontend/src/features/chat/utils/chat-import.ts
index ce30f862aba..5309c439233 100644
--- a/studio/frontend/src/features/chat/utils/chat-import.ts
+++ b/studio/frontend/src/features/chat/utils/chat-import.ts
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-/** Imports Studio chat backups, Open WebUI JSON arrays, OpenAI/ShareGPT JSONL, and role/content
- * CSV. JSON records stream individually so large exports never become one JS string. */
+/** Imports Studio chat backups, Open WebUI JSON arrays, OpenAI/ShareGPT JSONL, role/content
+ * CSV, and Studio markdown transcripts. JSON records stream individually so large exports
+ * never become one JS string. */
import {
ChatThreadWriteError,
@@ -37,9 +38,10 @@ import {
studioBackupProjects,
studioBackupToConversations,
} from "./studio-backup-import";
+import { parseConversationMarkdownDocument } from "./conversation-markdown-import";
-/** CSV has no record framing to stream on, so it is still read whole. */
-const CSV_MAX_BYTES = 64 * 1024 * 1024;
+/** CSV and markdown have no record framing to stream on, so they are still read whole. */
+const WHOLE_FILE_MAX_BYTES = 64 * 1024 * 1024;
/** Matches MAX_CHAT_IMPORT_CHUNK_BYTES in src-tauri/src/native_file_dialogs.rs. */
const NATIVE_CHUNK_BYTES = 8 * 1024 * 1024;
@@ -273,6 +275,41 @@ function sharegptToRecords(
return records;
}
+function markdownToRecords(
+ messages: Array<{ role: string; content: string }>,
+ threadId: string,
+ baseTs: number,
+): MessageRecord[] {
+ const records: MessageRecord[] = [];
+ let prevId: string | null = null;
+ let idx = 0;
+ for (const { role, content } of messages) {
+ if (!content.trim()) continue;
+ const normalizedRole = role.trim().toLowerCase();
+ const validRole =
+ normalizedRole === "user" ||
+ normalizedRole === "assistant" ||
+ normalizedRole === "system"
+ ? normalizedRole
+ : normalizedRole.length > 0
+ ? normalizedRole
+ : "user";
+ const id = crypto.randomUUID();
+ records.push({
+ id,
+ threadId,
+ parentId: prevId,
+ role: validRole as MessageRecord["role"],
+ content: [{ type: "text", text: content }] as MessageRecord["content"],
+ createdAt: baseTs + idx,
+ metadata: { createdAtEstimated: true },
+ });
+ prevId = id;
+ idx++;
+ }
+ return records;
+}
+
function csvToRecords(csvText: string, threadId: string, baseTs: number): MessageRecord[] {
// parseCsv handles quoted newlines, so multi-line message content round-trips from the exporter.
const rows = parseCsv(csvText).slice(1);
@@ -336,6 +373,16 @@ export function parseImportText(
filename: string,
): ParsedConversation[] {
const basename = filename.replace(/\.[^.]+$/, "");
+ if (/\.(?:md|markdown)$/i.test(filename)) {
+ const baseTs = Date.now();
+ return parseConversationMarkdownDocument(text, basename).flatMap(
+ ({ title, messages }) => {
+ const threadId = crypto.randomUUID();
+ const records = markdownToRecords(messages, threadId, baseTs);
+ return records.length > 0 ? [{ title, threadId, messages: records }] : [];
+ },
+ );
+ }
if (/\.csv$/i.test(filename)) {
const threadId = crypto.randomUUID();
const messages = csvToRecords(text, threadId, Date.now());
@@ -456,12 +503,17 @@ export async function importConversationsFromSource(
const saved = (conversation: { threadId: string; thread?: { pairId?: string } }) =>
options.onSaved?.(conversation.thread?.pairId ?? conversation.threadId);
- if (/\.csv$/i.test(source.name)) {
- const text = await readAllText(source, CSV_MAX_BYTES, "CSV");
+ if (/\.(?:csv|md|markdown)$/i.test(source.name)) {
+ const label = /\.csv$/i.test(source.name) ? "CSV" : "Markdown";
+ const text = await readAllText(source, WHOLE_FILE_MAX_BYTES, label);
for (const conversation of parseImportText(text, source.name)) {
- await writeConversation(conversation, projectId);
- progress.imported++;
- saved(conversation);
+ try {
+ await writeConversation(conversation, projectId);
+ progress.imported++;
+ saved(conversation);
+ } catch {
+ progress.failed++;
+ }
}
if (progress.imported > 0) notifyChatHistoryUpdated();
report();
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
index 2b5228a4b69..dace477ffc0 100644
--- a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
@@ -53,7 +53,9 @@ export function createConversationMarkdownBuilder<
content: stripSearchImageTokens(renderMessage(message)),
}),
);
- return buildConversationMarkdown(normalizedMessages);
+ return buildConversationMarkdown(normalizedMessages, {
+ includeImportMetadata: true,
+ });
};
}
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown-import.ts b/studio/frontend/src/features/chat/utils/conversation-markdown-import.ts
new file mode 100644
index 00000000000..bae49349361
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown-import.ts
@@ -0,0 +1,204 @@
+// 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 { fromMarkdown } from "mdast-util-from-markdown";
+import {
+ CONVERSATION_MARKDOWN_FRAME_PREFIX,
+ type ConversationMarkdownMessage,
+} from "./conversation-markdown.ts";
+
+type MarkdownNode = ReturnType<typeof fromMarkdown>["children"][number];
+
+const LABEL_TO_ROLE = new Map([
+ ["Assistant", "assistant"],
+ ["System", "system"],
+ ["User", "user"],
+ ["Developer", "developer"],
+ ["Message", ""],
+ ["Tool", "tool"],
+]);
+
+const FRAME_END = " -->\n\n";
+const CHAT_SEPARATOR = "\n---\n\n";
+const TITLE_LINE = /^# ([^\n]*)\n\n/;
+const ROLE_LINE = /^## ([^\n]+)\n\n/;
+
+function parseFramedDocument(
+ text: string,
+ fallbackTitle: string,
+): ParsedMarkdownConversation[] | undefined {
+ const conversations: ParsedMarkdownConversation[] = [];
+ let offset = 0;
+ while (offset < text.length) {
+ const title = TITLE_LINE.exec(text.slice(offset));
+ const frameStart = offset + (title?.[0].length ?? 0);
+ if (!text.startsWith(CONVERSATION_MARKDOWN_FRAME_PREFIX, frameStart)) {
+ if (offset === 0) return;
+ throw new Error("Missing Studio Markdown conversation framing.");
+ }
+ const metadataStart =
+ frameStart + CONVERSATION_MARKDOWN_FRAME_PREFIX.length;
+ const metadataEnd = text.indexOf(FRAME_END, metadataStart);
+ let lengths: unknown;
+ try {
+ lengths = JSON.parse(text.slice(metadataStart, metadataEnd));
+ } catch {
+ throw new Error("Invalid Studio Markdown conversation framing.");
+ }
+ if (
+ metadataEnd < 0 ||
+ !Array.isArray(lengths) ||
+ lengths.length === 0 ||
+ !lengths.every((length) => Number.isSafeInteger(length) && length > 0)
+ ) {
+ throw new Error("Invalid Studio Markdown message lengths.");
+ }
+ offset = metadataEnd + FRAME_END.length;
+ const messages: ConversationMarkdownMessage[] = [];
+ for (const [index, length] of lengths.entries()) {
+ const section = text.slice(offset, offset + length);
+ const heading = ROLE_LINE.exec(section);
+ if (section.length !== length || !heading) {
+ throw new Error("Incomplete Studio Markdown message.");
+ }
+ const label = heading[1];
+ messages.push({
+ role:
+ LABEL_TO_ROLE.get(label) ??
+ `${label[0].toLowerCase()}${label.slice(1)}`,
+ content: section.slice(heading[0].length),
+ });
+ offset += length;
+ const separator = index === lengths.length - 1 ? "\n" : "\n\n";
+ if (!text.startsWith(separator, offset)) {
+ throw new Error("Invalid Studio Markdown message boundary.");
+ }
+ offset += separator.length;
+ }
+ conversations.push({ title: title?.[1] ?? fallbackTitle, messages });
+ if (!text.slice(offset).trim()) break;
+ if (!text.startsWith(CHAT_SEPARATOR, offset)) {
+ throw new Error("Invalid Studio Markdown conversation boundary.");
+ }
+ offset += CHAT_SEPARATOR.length;
+ if (offset === text.length) {
+ throw new Error("Missing Studio Markdown conversation framing.");
+ }
+ }
+ return conversations;
+}
+
+function roleHeading(node: MarkdownNode | undefined, text: string) {
+ if (node?.type !== "heading" || node.depth !== 2) return;
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (
+ start === undefined ||
+ end === undefined ||
+ !text.startsWith("## ", start) ||
+ (start > 0 && text.slice(start - 2, start) !== "\n\n") ||
+ text.slice(end, end + 2) !== "\n\n"
+ )
+ return;
+ const role = LABEL_TO_ROLE.get(text.slice(start + 3, end));
+ return role === undefined
+ ? undefined
+ : { role, start, contentStart: end + 2 };
+}
+
+function documentTitle(nodes: MarkdownNode[], index: number, text: string) {
+ const node = nodes[index];
+ if (node?.type !== "heading" || node.depth !== 1) return;
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ const firstMessage = roleHeading(nodes[index + 1], text);
+ if (
+ start === undefined ||
+ end === undefined ||
+ !text.startsWith("# ", start) ||
+ !firstMessage ||
+ text.slice(end, firstMessage.start).trim()
+ )
+ return;
+ return { title: text.slice(start + 2, end).trim(), start };
+}
+
+function messagesFromNodes(
+ text: string,
+ nodes: MarkdownNode[],
+ end: number,
+): ConversationMarkdownMessage[] {
+ if (!roleHeading(nodes[0], text)) return [];
+ // only root headings delimit turns; headings in code, quotes and lists remain content.
+ const headings = nodes.flatMap((node) => {
+ const heading = roleHeading(node, text);
+ return heading ? [heading] : [];
+ });
+ return headings.flatMap(({ role, contentStart }, index) => {
+ const next = headings[index + 1];
+ const contentEnd = next ? next.start - 2 : end;
+ const content = text.slice(contentStart, contentEnd);
+ const value = next ? content : content.replace(/\n$/, "");
+ return value.trim() ? [{ role, content: value }] : [];
+ });
+}
+
+export function parseConversationMarkdownMessages(
+ body: string,
+): ConversationMarkdownMessage[] {
+ const text = body.replace(/\r\n?/g, "\n");
+ const framed = parseFramedDocument(text, "");
+ return framed
+ ? framed.flatMap((conversation) => conversation.messages)
+ : messagesFromNodes(text, fromMarkdown(text).children, text.length);
+}
+
+export type ParsedMarkdownConversation = {
+ title: string;
+ messages: ConversationMarkdownMessage[];
+};
+
+export function parseConversationMarkdownDocument(
+ input: string,
+ fallbackTitle: string,
+): ParsedMarkdownConversation[] {
+ const text = input.replace(/\r\n?/g, "\n").trimStart();
+ const framed = parseFramedDocument(text, fallbackTitle);
+ if (framed) return framed;
+ const nodes = fromMarkdown(text).children;
+ const firstTitle = documentTitle(nodes, 0, text);
+ let title = firstTitle?.title ?? fallbackTitle;
+ let firstNode = firstTitle === undefined ? 0 : 1;
+ const results: ParsedMarkdownConversation[] = [];
+ const append = (endNode: number, end: number) => {
+ const messages = messagesFromNodes(
+ text,
+ nodes.slice(firstNode, endNode),
+ end,
+ );
+ if (messages.length > 0) results.push({ title, messages });
+ };
+
+ for (let index = firstNode; index < nodes.length; index++) {
+ const node = nodes[index];
+ if (firstTitle === undefined || node.type !== "thematicBreak") continue;
+ const nextTitle = documentTitle(nodes, index + 1, text);
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ // bulk exports frame each chat with a rule, title and first role heading.
+ if (
+ start === undefined ||
+ end === undefined ||
+ nextTitle === undefined ||
+ text.slice(start, end) !== "---" ||
+ text.slice(end, nextTitle.start).trim()
+ )
+ continue;
+ append(index, start - 1);
+ title = nextTitle.title;
+ firstNode = index + 2;
+ index++;
+ }
+ append(nodes.length, text.length);
+ return results;
+}
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown.ts b/studio/frontend/src/features/chat/utils/conversation-markdown.ts
index baab285e49b..9f42e95b100 100644
--- a/studio/frontend/src/features/chat/utils/conversation-markdown.ts
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown.ts
@@ -16,6 +16,7 @@ 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";
+export const CONVERSATION_MARKDOWN_FRAME_PREFIX = "<!-- unsloth-chat-v1:";
const ROLE_LABELS: Readonly<Record<string, string>> = {
assistant: "Assistant",
@@ -600,13 +601,22 @@ export function renderConversationBlocks(
export function buildConversationMarkdown(
messages: readonly ConversationMarkdownMessage[],
+ options: { includeImportMetadata?: boolean } = {},
): string {
const sections = messages.flatMap(({ role, content }) => {
if (!content.trim()) {
return [];
}
const label = roleLabel(role);
- return [`## ${label}\n\n${content}`];
+ const text = options.includeImportMetadata
+ ? content.replace(/\r\n?/g, "\n")
+ : content;
+ return [`## ${label}\n\n${text}`];
});
- return sections.length > 0 ? `${sections.join("\n\n")}\n` : "";
+ if (sections.length === 0) return "";
+ const body = `${sections.join("\n\n")}\n`;
+ if (!options.includeImportMetadata) return body;
+ // section lengths distinguish transcript boundaries from identical text inside a message.
+ const lengths = JSON.stringify(sections.map((section) => section.length));
+ return `${CONVERSATION_MARKDOWN_FRAME_PREFIX}${lengths} -->\n\n${body}`;
}
diff --git a/studio/frontend/src/features/chat/utils/import-chats.ts b/studio/frontend/src/features/chat/utils/import-chats.ts
index 67886960409..ba6346e6671 100644
--- a/studio/frontend/src/features/chat/utils/import-chats.ts
+++ b/studio/frontend/src/features/chat/utils/import-chats.ts
@@ -12,7 +12,7 @@ import {
nativeImportSource,
} from "./chat-import";
-export const CHAT_IMPORT_ACCEPT = ".json,.jsonl,.ndjson,.csv";
+export const CHAT_IMPORT_ACCEPT = ".json,.jsonl,.ndjson,.csv,.md,.markdown";
/** Where imported chats land: a project (null for none), optionally filed in a section. */
export interface ChatImportTarget {
diff --git a/studio/frontend/src/features/chat/utils/ndjson.ts b/studio/frontend/src/features/chat/utils/ndjson.ts
index 339ba00bb11..d662b610859 100644
--- a/studio/frontend/src/features/chat/utils/ndjson.ts
+++ b/studio/frontend/src/features/chat/utils/ndjson.ts
@@ -16,7 +16,8 @@ export function exportFormatIncludesSiblings(format: string): boolean {
return (
format !== "jsonl-raw" &&
format !== "jsonl-messages" &&
- format !== "sharegpt"
+ format !== "sharegpt" &&
+ format !== "markdown"
);
}
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index c56d247c13c..9761cd44c1d 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -827,7 +827,7 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {
<input
ref={importInputRef}
type="file"
- accept=".json,.jsonl,.ndjson,.csv"
+ accept=".json,.jsonl,.ndjson,.csv,.md,.markdown"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 049a325510f..84fd7739517 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1934,7 +1934,7 @@ export const en = {
exportingAction: "Exporting...",
exportConversations: "Export Recents and Projects",
exportConversationsDescription:
- "Download Recents or Recents plus project chats as Training JSONL, CSV, or ShareGPT JSONL, combined or per chat. Message JSONL is available per chat.",
+ "Download Recents or Recents plus project chats as Training JSONL, CSV, ShareGPT JSONL, or Markdown, combined or per chat. Message JSONL is available per chat.",
exportConversationsAction: "Export",
exportScopeRecents: "Recents",
exportScopeAll: "Recents + Projects",
@@ -1942,7 +1942,7 @@ export const en = {
exportPerChatSuffix: "(per chat)",
importChats: "Import chats",
importChatsDescription:
- "Import JSON, JSONL, NDJSON, or CSV files into Recents.",
+ "Import JSON, JSONL, NDJSON, CSV, or Markdown files into Recents.",
importChatsAction: "Import",
importNoConversations: "No conversations found in file.",
importedOneChat: "Imported 1 conversation to Recents.",
diff --git a/studio/frontend/tests/conversation-markdown-export.test.ts b/studio/frontend/tests/conversation-markdown-export.test.ts
index 0c7dc61033d..ce89eba7e34 100644
--- a/studio/frontend/tests/conversation-markdown-export.test.ts
+++ b/studio/frontend/tests/conversation-markdown-export.test.ts
@@ -52,7 +52,7 @@ test("downloads a timestamped Markdown conversation", async () => {
assert.deepEqual(downloads, [
{
- content: "## User\n\nHello\n",
+ content: "<!-- unsloth-chat-v1:[14] -->\n\n## User\n\nHello\n",
filename: "conversation-2026-07-31T00-00-00.md",
mimeType: "text/markdown",
},
diff --git a/studio/frontend/tests/conversation-markdown-import.test.ts b/studio/frontend/tests/conversation-markdown-import.test.ts
new file mode 100644
index 00000000000..235378c04d4
--- /dev/null
+++ b/studio/frontend/tests/conversation-markdown-import.test.ts
@@ -0,0 +1,164 @@
+// 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 {
+ buildNamedConversationsMarkdown,
+ createConversationMarkdownBuilder,
+} from "../src/features/chat/utils/conversation-markdown-export.ts";
+import {
+ parseConversationMarkdownDocument,
+ parseConversationMarkdownMessages,
+} from "../src/features/chat/utils/conversation-markdown-import.ts";
+import { buildConversationMarkdown } from "../src/features/chat/utils/conversation-markdown.ts";
+
+test("round-trips a single exported conversation", () => {
+ const messages = [
+ { role: "system", content: "Be concise." },
+ { role: "user", content: "Explain `RED → GREEN`." },
+ { role: "assistant", content: "1. Write a failing test.\n2. Fix it." },
+ ];
+ assert.deepEqual(
+ parseConversationMarkdownDocument(
+ buildConversationMarkdown(messages),
+ "chat",
+ ),
+ [{ title: "chat", messages }],
+ );
+});
+
+test("parses real combined bulk exports with titles and separators", async () => {
+ const conversations = [
+ { id: "first", title: "First chat" },
+ { id: "second", title: "Second chat" },
+ ];
+ const messages = [
+ [{ role: "user", content: "Hi" }],
+ [{ role: "assistant", content: "Hello" }],
+ ];
+ const combined = await buildNamedConversationsMarkdown(
+ conversations,
+ async (id) => buildConversationMarkdown(messages[id === "first" ? 0 : 1]),
+ );
+ assert.deepEqual(parseConversationMarkdownDocument(combined, "export"), [
+ { title: "First chat", messages: messages[0] },
+ { title: "Second chat", messages: messages[1] },
+ ]);
+});
+
+for (const content of [
+ "# Existing heading\n\n> quote",
+ "Intro\n\n## Summary\n\nThe useful answer.",
+ "Intro\n\n## Summary\nThe useful answer.",
+ "First part\n\n---\n\nSecond part",
+ "Example:\n\n```markdown\n## User\n\nexample prompt\n\n## Assistant\n\nexample reply\n```\n\nConclusion",
+ "Example:\n\n~~~~markdown\n## Assistant\n\nexample\n~~~\n\n---\n\n# Example chat\n\n## User\n\nliteral\n~~~~\n\nConclusion",
+ "Quoted:\n\n> ## User\n>\n> literal\n\n- Example\n\n ## Assistant\n\n literal",
+ "Indented code:\n\n ## User\n\n literal\n\nConclusion",
+ "First part\n\n---\n\n# Report\n\n## Summary\n\nSecond part",
+ "Intro\n\n## constructor\n\nA JavaScript method.",
+ " leading spaces\n\ninternal blank lines\n\ntrailing spaces ",
+]) {
+ test(`preserves message markdown: ${JSON.stringify(content)}`, async () => {
+ const messages = [
+ { role: "user", content: "Explain this" },
+ { role: "assistant", content },
+ { role: "user", content: "Thanks" },
+ ];
+ const exported = buildConversationMarkdown(messages);
+ assert.deepEqual(parseConversationMarkdownMessages(exported), messages);
+ assert.deepEqual(parseConversationMarkdownDocument(exported, "chat"), [
+ { title: "chat", messages },
+ ]);
+ const combined = await buildNamedConversationsMarkdown(
+ [
+ { id: "first", title: "First" },
+ { id: "second", title: "Second" },
+ ],
+ async () => exported,
+ );
+ assert.deepEqual(parseConversationMarkdownDocument(combined, "chat"), [
+ { title: "First", messages },
+ { title: "Second", messages },
+ ]);
+ assert.deepEqual(
+ parseConversationMarkdownDocument(
+ combined.replaceAll("\n", "\r\n"),
+ "chat",
+ ),
+ [
+ { title: "First", messages },
+ { title: "Second", messages },
+ ],
+ );
+ });
+}
+
+test("does not import an ordinary markdown document as a conversation", () => {
+ assert.deepEqual(
+ parseConversationMarkdownDocument("## Summary\n\nA report.", "report"),
+ [],
+ );
+});
+
+for (const content of [
+ "Template:\n\n## User\n\nAsk a question.\n\n## Assistant\n\nAnswer it.",
+ "First part\n\n---\n\n# Another chat\n\n## System\n\nStill part of the answer.",
+ "Literal metadata: \n\n<!-- unsloth-chat-v1:[14] -->\n\n## User\n\nHello\n\nDone.",
+ "hello\r",
+ "Unicode 🦥 café\r\n\r\n## User\r\n\r\nA Windows template.",
+]) {
+ test(`framed exports preserve literal transcript boundaries: ${JSON.stringify(content)}`, async () => {
+ const messages = [{ role: "assistant", content }];
+ const expected = [
+ { role: "assistant", content: content.replace(/\r\n?/g, "\n") },
+ ];
+ const build = createConversationMarkdownBuilder({
+ loadMessages: async () => messages,
+ renderMessage: (message) => message.content,
+ });
+ const single = await build("first");
+ assert.ok(single);
+ assert.deepEqual(parseConversationMarkdownDocument(single, "chat"), [
+ { title: "chat", messages: expected },
+ ]);
+ const combined = await buildNamedConversationsMarkdown(
+ [
+ { id: "first", title: "First" },
+ { id: "second", title: "Second" },
+ ],
+ build,
+ );
+ for (const text of [combined, combined.replaceAll("\n", "\r\n")]) {
+ assert.deepEqual(parseConversationMarkdownDocument(text, "chat"), [
+ { title: "First", messages: expected },
+ { title: "Second", messages: expected },
+ ]);
+ }
+ });
+}
+
+test("rejects damaged framed exports rather than importing partial messages", async () => {
+ const build = createConversationMarkdownBuilder({
+ loadMessages: async () => [
+ { role: "assistant", content: "A complete answer." },
+ ],
+ renderMessage: (message) => message.content,
+ });
+ const exported = await build("chat");
+ assert.ok(exported);
+ for (const invalid of [
+ exported.slice(0, -8),
+ exported.replace("unsloth-chat-v1:[", "unsloth-chat-v1:[0,"),
+ exported.replace("unsloth-chat-v1:[", 'unsloth-chat-v1:["x",'),
+ `${exported}unexpected trailing content`,
+ `${exported}\n---\n\n`,
+ `${exported}\n---\n\n# Incomplete chat\n\n## User\n\nHello\n`,
+ ]) {
+ assert.throws(
+ () => parseConversationMarkdownDocument(invalid, "chat"),
+ /Studio Markdown/,
+ );
+ }
+});
diff --git a/studio/frontend/tests/markdown-export-branches.test.ts b/studio/frontend/tests/markdown-export-branches.test.ts
index a84a2c1b48e..9bae7dad2ee 100644
--- a/studio/frontend/tests/markdown-export-branches.test.ts
+++ b/studio/frontend/tests/markdown-export-branches.test.ts
@@ -8,13 +8,21 @@ import ts from "typescript";
import { stripSearchImageTokens } from "../src/features/chat/search-images/search-images.ts";
import {
+ buildNamedConversationsMarkdown,
createConversationMarkdownBuilder,
createConversationMarkdownExporter,
} from "../src/features/chat/utils/conversation-markdown-export.ts";
-import { buildConversationMarkdown } from "../src/features/chat/utils/conversation-markdown.ts";
+import {
+ buildConversationMarkdown,
+ CONVERSATION_MARKDOWN_MIME_TYPE,
+} from "../src/features/chat/utils/conversation-markdown.ts";
import { csvDocument, CSV_MIME } from "../src/features/chat/utils/csv-export.ts";
import * as liveThreadHead from "../src/features/chat/utils/live-thread-head.ts";
import { orderByParentChain } from "../src/features/chat/utils/message-order.ts";
+import { parseConversationMarkdownDocument } from "../src/features/chat/utils/conversation-markdown-import.ts";
+import { canMergeConversationExport } from "../src/features/chat/utils/ndjson.ts";
+import { planChatItemSources } from "../src/features/chat/utils/project-source-plan.ts";
+import type { ThreadRecord } from "../src/features/chat/types.ts";
import { readSrc } from "./helpers/kit.ts";
type StoredMessage = {
@@ -36,6 +44,11 @@ type Exporters = {
title: string,
) => Promise<string>;
exportConversationCsv: (threadId: string) => Promise<void>;
+ exportBulkConversationsMerged: (
+ threadIds: string[],
+ format: "markdown",
+ basename: string,
+ ) => Promise<void>;
};
const SOURCE = readSrc(
@@ -66,6 +79,7 @@ function loadExporters(
stored: StoredMessage[],
downloads: string[],
sources: string[],
+ threads: ThreadRecord[] = [],
) {
const javascript = ts.transpileModule(
[
@@ -77,7 +91,11 @@ function loadExporters(
"export async function exportConversationCsv(",
"export async function saveChatItemAsProjectSource(",
),
- "globalThis.__exporters = { buildConversationMarkdownForThread, exportConversationMarkdown, saveConversationAsProjectSource, exportConversationCsv };",
+ sliceSource(
+ "export async function exportBulkConversationsMerged(",
+ "export async function exportBulkConversationsSeparate(",
+ ),
+ "globalThis.__exporters = { buildConversationMarkdownForThread, exportConversationMarkdown, saveConversationAsProjectSource, exportConversationCsv, exportBulkConversationsMerged };",
].join("\n"),
{
compilerOptions: {
@@ -90,6 +108,12 @@ function loadExporters(
exports: {},
toast: { info: () => {} },
listStoredChatMessages: async () => stored,
+ getStoredChatThread: async (id: string) =>
+ threads.find((thread) => thread.id === id),
+ buildNamedConversationsMarkdown,
+ CONVERSATION_MARKDOWN_MIME_TYPE,
+ canMergeConversationExport,
+ planChatItemSources,
...liveThreadHead,
orderByParentChain,
createConversationMarkdownBuilder,
@@ -154,18 +178,20 @@ const edited = storedMessages([
test("Markdown follows the older reply picked in the branch picker", async () => {
const expected = "## User\n\nName one fruit.\n\n## Assistant\n\nApples.\n";
+ const expectedExport = `<!-- unsloth-chat-v1:[24,21] -->\n\n${expected}`;
assert.deepEqual(await markdownOutputs(regenerated, ["u1", "a1"]), {
- copied: expected,
- downloads: [expected],
+ copied: expectedExport,
+ downloads: [expectedExport],
sources: [expected],
});
});
test("Markdown leaves out the reply a regeneration replaced", async () => {
const expected = "## User\n\nName one fruit.\n\n## Assistant\n\nPears.\n";
+ const expectedExport = `<!-- unsloth-chat-v1:[24,20] -->\n\n${expected}`;
assert.deepEqual(await markdownOutputs(regenerated), {
- copied: expected,
- downloads: [expected],
+ copied: expectedExport,
+ downloads: [expectedExport],
sources: [expected],
});
});
@@ -173,9 +199,10 @@ test("Markdown leaves out the reply a regeneration replaced", async () => {
// Mid-switch the branch on screen is briefly an empty list, which is no opinion about which reply is showing.
test("Markdown still exports while the switched-to chat is loading", async () => {
const expected = "## User\n\nName one fruit.\n\n## Assistant\n\nPears.\n";
+ const expectedExport = `<!-- unsloth-chat-v1:[24,20] -->\n\n${expected}`;
assert.deepEqual(await markdownOutputs(regenerated, []), {
- copied: expected,
- downloads: [expected],
+ copied: expectedExport,
+ downloads: [expectedExport],
sources: [expected],
});
});
@@ -192,15 +219,62 @@ test("CSV still writes both replies while markdown writes one", async () => {
test("Markdown follows the prompt version on screen", async () => {
const older = "## User\n\nName one color.\n\n## Assistant\n\nBlue.\n";
+ const olderExport = `<!-- unsloth-chat-v1:[24,19] -->\n\n${older}`;
assert.deepEqual(await markdownOutputs(edited, ["u1", "a1"]), {
- copied: older,
- downloads: [older],
+ copied: olderExport,
+ downloads: [olderExport],
sources: [older],
});
const newer = "## User\n\nName one animal.\n\n## Assistant\n\nCat.\n";
+ const newerExport = `<!-- unsloth-chat-v1:[25,18] -->\n\n${newer}`;
assert.deepEqual(await markdownOutputs(edited), {
- copied: newer,
- downloads: [newer],
+ copied: newerExport,
+ downloads: [newerExport],
sources: [newer],
});
});
+
+for (const { models, panes, titles } of [
+ {
+ models: ["org/Alpha", "org/Beta"],
+ panes: ["model1", "model2"],
+ titles: ["Compare - Beta", "Standalone", "Compare - Alpha"],
+ },
+ {
+ models: ["org/Alpha", "org/Alpha"],
+ panes: ["base", "lora"],
+ titles: [
+ "Compare - Alpha - fine-tuned",
+ "Standalone",
+ "Compare - Alpha - base",
+ ],
+ },
+]) {
+ test(`combined Markdown names comparison halves: ${panes.join("/")}`, async () => {
+ const threads = [
+ ...models.map((modelId, index) => ({
+ id: `half-${index}`,
+ title: "Compare",
+ pairId: "pair",
+ modelId,
+ modelType: panes[index],
+ createdAt: 1,
+ })),
+ { id: "single", title: "Standalone", modelType: "base", createdAt: 1 },
+ ] as ThreadRecord[];
+ const downloads: string[] = [];
+ const exporters = loadExporters(regenerated, downloads, [], threads);
+ await exporters.exportBulkConversationsMerged(
+ ["half-1", "single", "half-0"],
+ "markdown",
+ "chats",
+ );
+ assert.equal(downloads.length, 1);
+ assert.deepEqual(
+ parseConversationMarkdownDocument(downloads[0], "chats").map(
+ ({ title }) => title,
+ ),
+ titles,
+ );
+ });
+}
diff --git a/studio/frontend/tests/message-jsonl-import.test.ts b/studio/frontend/tests/message-jsonl-import.test.ts
index 766195e13c1..ed308e1bb44 100644
--- a/studio/frontend/tests/message-jsonl-import.test.ts
+++ b/studio/frontend/tests/message-jsonl-import.test.ts
@@ -57,6 +57,32 @@ after(async () => {
await vite.close();
});
+test("markdown transcripts import as conversations", () => {
+ const markdown = [
+ "## User",
+ "",
+ "Hello",
+ "",
+ "## Assistant",
+ "",
+ "Hi there",
+ "",
+ ].join("\n");
+ const conversations = parseImportText(markdown, "my-chat.md");
+ assert.equal(conversations.length, 1);
+ assert.equal(conversations[0].title, "my-chat");
+ assert.deepEqual(
+ conversations[0].messages.map(({ role, content }) => ({
+ role,
+ content: (content as ReadonlyArray<{ text: string }>)[0]?.text,
+ })),
+ [
+ { role: "user", content: "Hello" },
+ { role: "assistant", content: "Hi there" },
+ ],
+ );
+});
+
test("message JSONL imports as one conversation", () => {
const conversations = parseImportText(
'{"role":"user","content":"Hello"}\n' +
diff --git a/studio/frontend/tests/ndjson-body.test.ts b/studio/frontend/tests/ndjson-body.test.ts
index af7a50d9905..a5336ea93a6 100644
--- a/studio/frontend/tests/ndjson-body.test.ts
+++ b/studio/frontend/tests/ndjson-body.test.ts
@@ -83,6 +83,7 @@ test("training formats export only the displayed branch", () => {
assert.equal(exportFormatIncludesSiblings("jsonl-messages"), false);
assert.equal(exportFormatIncludesSiblings("sharegpt"), false);
assert.equal(exportFormatIncludesSiblings("csv"), true);
+ assert.equal(exportFormatIncludesSiblings("markdown"), false);
});
test("training order excludes abandoned response branches", () => {
diff --git a/studio/frontend/tests/studio-backup-import.test.ts b/studio/frontend/tests/studio-backup-import.test.ts
index 7c4f88221b3..8322487a6d0 100644
--- a/studio/frontend/tests/studio-backup-import.test.ts
+++ b/studio/frontend/tests/studio-backup-import.test.ts
@@ -3,6 +3,7 @@
import assert from "node:assert/strict";
import test from "node:test";
+import { fromMarkdown } from "mdast-util-from-markdown";
import type {
MessageRecord,
@@ -10,6 +11,9 @@ import type {
ThreadRecord,
} from "../src/features/chat/types.ts";
import { filterArchivedChatExport } from "../src/features/chat/utils/archived-chat-export.ts";
+import type { ImportOptions } from "../src/features/chat/utils/chat-import.ts";
+import { buildNamedConversationsMarkdown } from "../src/features/chat/utils/conversation-markdown-export.ts";
+import { buildConversationMarkdown } from "../src/features/chat/utils/conversation-markdown.ts";
import { loadWithStubs } from "./helpers/module-stubs.ts";
type ImportSource = {
@@ -33,18 +37,25 @@ type Module = {
importConversationsFromSource: (
source: ImportSource,
projectId?: string | null,
+ options?: ImportOptions,
) => Promise<{ imported: number; failed: number }>;
};
-function harness(existingProjects: ProjectRecord[] = []) {
+function harness(
+ existingProjects: ProjectRecord[] = [],
+ rejectAt?: "thread" | "messages",
+) {
const threads: ThreadRecord[] = [];
const messages = new Map<string, MessageRecord[]>();
const projects = [...existingProjects];
+ const events = { historyUpdated: 0 };
+ const deleted: string[] = [];
const module = loadWithStubs<Module>(
new URL("../src/features/chat/utils/chat-import.ts", import.meta.url),
{
+ "mdast-util-from-markdown": { fromMarkdown },
"../api/chat-api": {
- notifyChatHistoryUpdated: () => {},
+ notifyChatHistoryUpdated: () => { events.historyUpdated++; },
listChatProjects: async () => projects,
saveChatProject: async (project: ProjectRecord) => {
projects.push(project);
@@ -54,6 +65,9 @@ function harness(existingProjects: ProjectRecord[] = []) {
},
"./chat-history-storage": {
saveStoredChatThread: async (thread: ThreadRecord) => {
+ if (rejectAt === "thread" && thread.title === "Rejected") {
+ throw new ChatThreadWriteError("Request failed (500)", 500);
+ }
threads.push(thread);
return thread;
},
@@ -61,19 +75,36 @@ function harness(existingProjects: ProjectRecord[] = []) {
threadId: string,
records: MessageRecord[],
) => {
+ if (
+ rejectAt === "messages" &&
+ threads.find(({ id }) => id === threadId)?.title === "Rejected"
+ ) {
+ throw new Error("Message sync failed");
+ }
messages.set(threadId, records);
return records;
},
- deleteStoredChatThreads: async () => [],
+ deleteStoredChatThreads: async (ids: string[]) => {
+ deleted.push(...ids);
+ for (const id of ids) {
+ const index = threads.findIndex((thread) => thread.id === id);
+ if (index !== -1) threads.splice(index, 1);
+ messages.delete(id);
+ }
+ return ids;
+ },
},
},
{ relativePassthrough: true },
);
- return { module, threads, messages, projects };
+ return { module, threads, messages, projects, events, deleted };
}
function sourceOf(name: string, data: unknown): ImportSource {
- const text = JSON.stringify(data, null, 2);
+ return sourceText(name, JSON.stringify(data, null, 2));
+}
+
+function sourceText(name: string, text: string): ImportSource {
const half = Math.floor(text.length / 2);
return {
name,
@@ -85,6 +116,44 @@ function sourceOf(name: string, data: unknown): ImportSource {
};
}
+for (const rejectAt of ["thread", "messages"] as const) {
+ test(`combined markdown continues after a ${rejectAt} save failure`, async () => {
+ const { module, threads, messages, events, deleted } = harness([], rejectAt);
+ const conversations = ["First", "Rejected", "Last"].map((title) => ({
+ id: title,
+ title,
+ }));
+ const text = await buildNamedConversationsMarkdown(
+ conversations,
+ async (id) => buildConversationMarkdown([{ role: "user", content: id }]),
+ );
+ const saved: string[] = [];
+ const progress: Array<{ imported: number; failed: number }> = [];
+ const result = await module.importConversationsFromSource(
+ sourceText("combined.md", text),
+ null,
+ {
+ onSaved: (id) => saved.push(id),
+ onProgress: ({ imported, failed }) => progress.push({ imported, failed }),
+ },
+ );
+
+ assert.deepEqual(result, { imported: 2, failed: 1 });
+ assert.deepEqual(threads.map(({ title }) => title), ["First", "Last"]);
+ assert.deepEqual(saved, threads.map(({ id }) => id));
+ assert.deepEqual(
+ threads.map(({ id }) => messages.get(id)?.[0]?.content),
+ [
+ [{ type: "text", text: "First" }],
+ [{ type: "text", text: "Last" }],
+ ],
+ );
+ assert.equal(events.historyUpdated, 1);
+ assert.deepEqual(progress.at(-1), { imported: 2, failed: 1 });
+ assert.equal(deleted.length, rejectAt === "messages" ? 1 : 0);
+ });
+}
+
function message(
id: string,
threadId: string,
@@ -412,6 +481,7 @@ test("a settings snapshot this build rejects costs the settings, not the chat",
const module = loadWithStubs<Module>(
new URL("../src/features/chat/utils/chat-import.ts", import.meta.url),
{
+ "mdast-util-from-markdown": { fromMarkdown },
"../api/chat-api": {
notifyChatHistoryUpdated: () => {},
listChatProjects: async () => [],
@@ -535,6 +605,7 @@ test("a backend that is merely down keeps the settings instead of quietly droppi
const module = loadWithStubs<Module>(
new URL("../src/features/chat/utils/chat-import.ts", import.meta.url),
{
+ "mdast-util-from-markdown": { fromMarkdown },
"../api/chat-api": {
notifyChatHistoryUpdated: () => {},
listChatProjects: async () => [],
diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rs
index 924a3b63ae2..a46b672968d 100644
--- a/studio/src-tauri/src/native_file_dialogs.rs
+++ b/studio/src-tauri/src/native_file_dialogs.rs
@@ -15,8 +15,9 @@ const MAX_TRAINING_CONFIG_BYTES: u64 = 1024 * 1024;
/// pieces, and a piece has to fit in one IPC response.
const MAX_CHAT_IMPORT_CHUNK_BYTES: usize = 8 * 1024 * 1024;
const NATIVE_FILE_NAME_HEADER: &str = "x-unsloth-default-name";
-const CHAT_IMPORT_EXTENSIONS: &[&str] = &["json", "jsonl", "ndjson", "csv"];
-const CHAT_IMPORT_TYPE_ERROR: &str = "Chat import must be a .json, .jsonl, .ndjson, or .csv file.";
+const CHAT_IMPORT_EXTENSIONS: &[&str] = &["json", "jsonl", "ndjson", "csv", "md", "markdown"];
+const CHAT_IMPORT_TYPE_ERROR: &str =
+ "Chat import must be a .json, .jsonl, .ndjson, .csv, or .md file.";
const TRAINING_CONFIG_EXTENSIONS: &[&str] = &["yaml", "yml"];
#[derive(Debug, Serialize)]
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index 70865452dd9..ca5e5de31e0 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -267,10 +267,13 @@ def test_file_actions_route_through_native_commands_only_in_tauri():
# Browser builds retain the existing hidden-input route.
assert 'type="file"' in data_tab
# Open WebUI exports are .json arrays, so the picker takes that too.
- assert 'accept=".json,.jsonl,.ndjson,.csv"' in data_tab
+ assert 'accept=".json,.jsonl,.ndjson,.csv,.md,.markdown"' in data_tab
native_dialogs = _ui_source(NATIVE_DIALOGS)
- assert 'CHAT_IMPORT_EXTENSIONS: &[&str] = &["json", "jsonl", "ndjson", "csv"]' in native_dialogs
+ assert (
+ 'CHAT_IMPORT_EXTENSIONS: &[&str] = &["json", "jsonl", "ndjson", "csv", "md", "markdown"]'
+ in native_dialogs
+ )
assert "InvokeBody::Raw" in native_dialogs
assert ".tempfile_in(parent)" in native_dialogs