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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: add message jsonl export (#9614)
Maheswar Kumar5f31df8b80de
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex b5406481b92..ec784dfaa8b 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -294,6 +294,7 @@ type NavRowDef = {type ConversationExportFormat =| "raw-jsonl"+ | "messages-jsonl"| "csv"| "sharegpt-jsonl"| typeof CONVERSATION_MARKDOWN_FORMAT;@@ -342,7 +343,8 @@ const CHAT_EXPORT_OPTIONS: Array<{label: string;format: ConversationExportFormat;}> = [- { label: "Raw JSONL", format: "raw-jsonl" },+ { label: "Training JSONL", format: "raw-jsonl" },+ { label: "Message JSONL", format: "messages-jsonl" },{ label: "CSV", format: "csv" },{ label: "ShareGPT JSONL", format: "sharegpt-jsonl" },{ label: CONVERSATION_MARKDOWN_LABEL, format: CONVERSATION_MARKDOWN_FORMAT },@@ -358,6 +360,8 @@ async function exportConversationByFormat(switch (format) {case "raw-jsonl":return exports.exportConversationRawJsonl(threadId);+ case "messages-jsonl":+ return exports.exportConversationMessagesJsonl(threadId);case "csv":return exports.exportConversationCsv(threadId);case "sharegpt-jsonl":diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 0c8351c8980..d41dd96d92f 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -101,6 +101,7 @@ import {PromptStorageDialog,exportConversationShareGPT,exportConversationRawJsonl,+ exportConversationMessagesJsonl,exportConversationCsv,exportConversationMarkdown,} from "@/features/chat/prompt-storage/prompt-storage-dialog";@@ -5940,7 +5941,17 @@ const ComposerToolsMenu: FC<{});}}>- Raw JSONL+ Training JSONL+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={() => {+ if (!activeThreadId) return;+ exportConversationMessagesJsonl(activeThreadId).catch((error) => {+ if (!isDownloadCancelled(error)) toast.error("Export failed.");+ });+ }}+ >+ Message JSONL</DropdownMenuItem><DropdownMenuItemonSelect={() => {diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex a39a992d296..d4fbf0a62d4 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -1140,6 +1140,7 @@ function createThreadNonce(): string {// Chat export formats, mirroring the sidebar chat menu.type ProjectChatExportFormat =| "raw-jsonl"+ | "messages-jsonl"| "csv"| "sharegpt-jsonl"| typeof CONVERSATION_MARKDOWN_FORMAT;@@ -1147,7 +1148,8 @@ const PROJECT_CHAT_EXPORT_OPTIONS: Array<{label: string;format: ProjectChatExportFormat;}> = [- { label: "Raw JSONL", format: "raw-jsonl" },+ { label: "Training JSONL", format: "raw-jsonl" },+ { label: "Message JSONL", format: "messages-jsonl" },{ label: "CSV", format: "csv" },{ label: "ShareGPT JSONL", format: "sharegpt-jsonl" },{@@ -1162,6 +1164,8 @@ async function exportProjectConversation(): Promise<void> {const exports = await import("./prompt-storage/prompt-storage-dialog");if (format === "raw-jsonl") return exports.exportConversationRawJsonl(threadId);+ if (format === "messages-jsonl")+ return exports.exportConversationMessagesJsonl(threadId);if (format === "csv") return exports.exportConversationCsv(threadId);if (format === CONVERSATION_MARKDOWN_FORMAT)return exports.exportConversationMarkdown(threadId);diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 158b6b4fad7..e83627a5819 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -287,6 +287,7 @@ export {CONVERSATION_MARKDOWN_LABEL,} from "./utils/conversation-markdown";export {+ COMBINED_EXPORT_FORMATS_LIST,EXPORT_FORMATS_LIST,buildFineTuneJsonl,bulkExportConversationsByScope,diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsxindex 54e13302705..f3e300ed28d 100644--- a/studio/frontend/src/features/chat/projects-page.tsx+++ b/studio/frontend/src/features/chat/projects-page.tsx@@ -58,6 +58,7 @@ import { MoreHorizontalIcon } from "lucide-react";import { useNavigate } from "@tanstack/react-router";import { useEffect, useMemo, useRef, useState } from "react";import {+ COMBINED_EXPORT_FORMATS_LIST,exportProjectConversations,exportBulkConversationsMerged,exportBulkConversationsSeparate,@@ -458,7 +459,7 @@ export function ProjectsPage() {<DropdownMenuLabel className="pb-1 pt-2 text-ui-11 font-medium">Combined</DropdownMenuLabel>- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (<DropdownMenuItem key={`ap-m-${fmt}`} onSelect={() => void handleBulkProjectExport("projects", fmt, true)}>{label}</DropdownMenuItem>@@ -484,7 +485,7 @@ export function ProjectsPage() {<DropdownMenuLabel className="pb-1 pt-2 text-ui-11 font-medium">Combined</DropdownMenuLabel>- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (<DropdownMenuItem key={`all-m-${fmt}`} onSelect={() => void handleBulkProjectExport("all", fmt, true)}>{label}</DropdownMenuItem>@@ -665,7 +666,7 @@ export function ProjectsPage() {<span>Export</span></DropdownMenuSubTrigger><DropdownMenuSubContent className="w-52">- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (<DropdownMenuItemkey={fmt}onSelect={(e) => {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.tsxindex d62e09bd213..88e5f03cacc 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@@ -65,6 +65,13 @@ import {createConversationMarkdownExporter,} from "../utils/conversation-markdown-export";import { parseCsv } from "../utils/csv-parse";+import {+ canMergeConversationExport,+ conversationJsonlBody,+ exportFormatIncludesSiblings,+ type ConversationJsonlLayout,+} from "../utils/ndjson";+import { orderByParentChain } from "../utils/message-order";import { unwrapPastedTextContent } from "../utils/pasted-text.ts";import {buildConversationMarkdown,@@ -198,52 +205,17 @@ function contentBlocksToText(content: unknown): string {return parts.join("\n\n");}-// Order via parentId chain: createdAt misorders turns (GPT response slots-// predate the user's next message); the parent chain is timestamp-independent.-type _Msg = { id: string; parentId?: string | null; createdAt?: number };--function orderByParentChain<T extends _Msg>(- messages: T[],+async function loadConversationMessages(+ threadId: string,options: {- /** Append messages off the selected chain (abandoned branches) at the- * end. Full exports keep everything; fine-tune conversion must not,- * since alternate replies would merge into one conversation. */+ emptyMessage?: string;includeSiblings?: boolean;} = {},-): T[] {- const { includeSiblings = true } = options;- const byId = new Map<string, T>(messages.map((m) => [m.id, m]));- const childrenOf = new Map<string | null, T[]>();- for (const m of messages) {- const pid = m.parentId ?? null;- if (!childrenOf.has(pid)) childrenOf.set(pid, []);- childrenOf.get(pid)!.push(m);- }-- const result: T[] = [];- let cur: string | null = null;- while (childrenOf.has(cur)) {- const children: T[] = childrenOf.get(cur)!;- const next: T = children.reduce((a: T, b: T) =>- (a.createdAt ?? 0) >= (b.createdAt ?? 0) ? a : b,- );- result.push(next);- cur = next.id;- byId.delete(next.id);- }-- if (includeSiblings) {- for (const [, m] of byId) result.push(m);- }- return result;-}--async function loadConversationMessages(- threadId: string,- // Every other caller here is an export; the project-sources save is not, and- // reporting an export to someone who never asked for one is confusing.- emptyMessage = "No messages in this conversation to export.",) {+ const {+ emptyMessage = "No messages in this conversation to export.",+ includeSiblings = true,+ } = options;const raw = await listStoredChatMessages(threadId);if (raw.length === 0) {toast.info(emptyMessage);@@ -253,7 +225,7 @@ async function loadConversationMessages(// chain would invert order, so keep raw order.const hasParentIds = raw.some((m) => (m as { parentId?: unknown }).parentId != null);if (!hasParentIds) return raw;- return orderByParentChain(raw) as typeof raw;+ return orderByParentChain(raw, { includeSiblings }) as typeof raw;}function exportTs(): string {@@ -353,6 +325,8 @@ function messageToOpenAI(msg: { role: unknown; content: unknown; attachments?: u} else if (p.type === "reasoning" || p.type === "thinking") {const t = typeof p.thinking === "string" ? p.thinking : typeof p.text === "string" ? p.text : "";if (t) textParts.push(`<thinking>\n${t}\n</thinking>`);+ } else if (p.type === "image" && typeof p.image === "string" && p.image) {+ textParts.push("[image attachment]");} else if (p.type === "tool-call") {const id = typeof p.toolCallId === "string" ? p.toolCallId : `call_${toolCalls.length}`;const name = typeof p.toolName === "string" ? p.toolName : "unknown";@@ -423,14 +397,29 @@ export async function exportConversationShareGPT(threadId: string): Promise<void// OpenAI/ChatML JSONL: {"messages": [{"role","content"}, ...]} per conversation;// Unsloth reads this as a ChatML dataset.export async function exportConversationRawJsonl(threadId: string): Promise<void> {- const messages = await loadConversationMessages(threadId);+ return exportConversationJsonl(threadId, "training");+}++export async function exportConversationMessagesJsonl(threadId: string): Promise<void> {+ return exportConversationJsonl(threadId, "messages");+}++async function exportConversationJsonl(+ threadId: string,+ layout: ConversationJsonlLayout,+): Promise<void> {+ const messages = await loadConversationMessages(threadId, {+ includeSiblings: exportFormatIncludesSiblings(+ layout === "training" ? "jsonl-raw" : "jsonl-messages",+ ),+ });if (!messages) return;const oaiMsgs: OAIMessage[] = messages.flatMap((msg) => messageToOpenAI(msg));if (oaiMsgs.length === 0) { toast.info("No exportable content."); return; }await downloadBlob(- JSON.stringify({ messages: oaiMsgs }),- "conversation-" + exportTs() + ".jsonl",+ conversationJsonlBody(oaiMsgs, layout),+ `conversation${layout === "messages" ? "-messages" : ""}-${exportTs()}.jsonl`,"application/x-ndjson",);}@@ -479,10 +468,9 @@ async function saveConversationAsProjectSource(projectId: string,title: string,): Promise<SaveSourceOutcome> {- const messages = await loadConversationMessages(- threadId,- "No messages in this conversation to save.",- );+ const messages = await loadConversationMessages(threadId, {+ emptyMessage: "No messages in this conversation to save.",+ });if (!messages) return "skipped";const markdown = buildConversationMarkdown(messages.map((msg) => ({@@ -548,10 +536,11 @@ export async function buildChatItemMarkdown(item: {);}-export type ConvExportFormat = "jsonl-raw" | "csv" | "sharegpt";+export type ConvExportFormat = "jsonl-raw" | "jsonl-messages" | "csv" | "sharegpt";const EXPORT_FORMAT_LABELS: Record<ConvExportFormat, string> = {- "jsonl-raw": "Raw JSONL",+ "jsonl-raw": "Training JSONL",+ "jsonl-messages": "Message JSONL",csv: "CSV",sharegpt: "ShareGPT JSONL",};@@ -560,18 +549,26 @@ export const EXPORT_FORMATS_LIST = (Object.keys(EXPORT_FORMAT_LABELS) as ConvExportFormat[]).map((fmt) => ({ fmt, label: EXPORT_FORMAT_LABELS[fmt] }));+export const COMBINED_EXPORT_FORMATS_LIST = EXPORT_FORMATS_LIST.filter(+ ({ fmt }) => canMergeConversationExport(fmt),+);+async function buildThreadContent(threadId: string,format: ConvExportFormat,): Promise<string | null> {- const messages = await loadConversationMessages(threadId);+ const messages = await loadConversationMessages(threadId, {+ includeSiblings: exportFormatIncludesSiblings(format),+ });if (!messages) return null;- if (format === "jsonl-raw") {- // OpenAI/ChatML: Unsloth reads the "messages" key as ChatML.+ if (format === "jsonl-raw" || format === "jsonl-messages") {const oaiMsgs: OAIMessage[] = messages.flatMap((msg) => messageToOpenAI(msg));if (oaiMsgs.length === 0) return null;- return JSON.stringify({ messages: oaiMsgs });+ return conversationJsonlBody(+ oaiMsgs,+ format === "jsonl-messages" ? "messages" : "training",+ );}if (format === "sharegpt") {@@ -612,6 +609,10 @@ export async function exportBulkConversationsMerged(basename: string,): Promise<void> {if (threadIds.length === 0) { toast.info("No conversations to export."); return; }+ if (!canMergeConversationExport(format) && threadIds.length > 1) {+ toast.info("Message JSONL is available per chat.");+ return;+ }const parts: string[] = [];const header = csvHeader(format);diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex b4b9a6d2041..bd47afc76f3 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -89,6 +89,7 @@ import {PromptStorageDialog,exportConversationShareGPT,exportConversationRawJsonl,+ exportConversationMessagesJsonl,exportConversationCsv,exportConversationMarkdown,} from "./prompt-storage/prompt-storage-dialog";@@ -2031,7 +2032,8 @@ export function SharedComposer({className="unsloth-plus-menu w-[208px]">{[- { label: "Raw JSONL", fn: exportConversationRawJsonl },+ { label: "Training JSONL", fn: exportConversationRawJsonl },+ { label: "Message JSONL", fn: exportConversationMessagesJsonl },{ label: "CSV", fn: exportConversationCsv },{ label: "ShareGPT JSONL", fn: exportConversationShareGPT },{diff --git a/studio/frontend/src/features/chat/thread-sidebar.tsx b/studio/frontend/src/features/chat/thread-sidebar.tsxindex 73551643189..30ae5da3682 100644--- a/studio/frontend/src/features/chat/thread-sidebar.tsx+++ b/studio/frontend/src/features/chat/thread-sidebar.tsx@@ -55,11 +55,13 @@ import {import type { SidebarItem } from "./hooks/use-chat-sidebar-items";import {exportConversationRawJsonl,+ exportConversationMessagesJsonl,exportConversationCsv,exportConversationShareGPT,exportConversationMarkdown,exportBulkConversationsMerged,exportBulkConversationsSeparate,+ COMBINED_EXPORT_FORMATS_LIST,EXPORT_FORMATS_LIST,type ConvExportFormat,} from "./prompt-storage/prompt-storage-dialog";@@ -68,7 +70,8 @@ import {} from "./utils/chat-history-storage";const EXPORT_FORMATS = [- { label: "Raw JSONL", fn: exportConversationRawJsonl },+ { label: "Training JSONL", fn: exportConversationRawJsonl },+ { label: "Message JSONL", fn: exportConversationMessagesJsonl },{ label: "CSV", fn: exportConversationCsv },{ label: "ShareGPT JSONL", fn: exportConversationShareGPT },{ label: CONVERSATION_MARKDOWN_LABEL, fn: exportConversationMarkdown },@@ -224,7 +227,7 @@ export function ThreadSidebar({Export Recents</DropdownMenuSubTrigger><DropdownMenuSubContent avoidCollisions={false} className="w-52">- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (<DropdownMenuItem key={`r-m-${fmt}`} onSelect={() => void handleBulkExport("recents", fmt, true)}>{label} — combined</DropdownMenuItem>@@ -243,7 +246,7 @@ export function ThreadSidebar({Export Recents + Projects</DropdownMenuSubTrigger><DropdownMenuSubContent avoidCollisions={false} className="w-52">- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (<DropdownMenuItem key={`a-m-${fmt}`} onSelect={() => void handleBulkExport("all", fmt, true)}>{label} — combined</DropdownMenuItem>diff --git a/studio/frontend/src/features/chat/utils/chat-import.ts b/studio/frontend/src/features/chat/utils/chat-import.tsindex ea5a1643ffc..80dff64bf29 100644--- a/studio/frontend/src/features/chat/utils/chat-import.ts+++ b/studio/frontend/src/features/chat/utils/chat-import.ts@@ -25,6 +25,10 @@ import {isOpenWebUIRecord,openWebUIRecordToConversation,} from "./openwebui-import";+import {+ isOpenAIMessageRecord,+ messageJsonlConversationRecord,+} from "./ndjson";/** CSV has no record framing to stream on, so it is still read whole. */const CSV_MAX_BYTES = 64 * 1024 * 1024;@@ -109,6 +113,32 @@ export function nativeImportSource(handle: {// role:"tool" results are absorbed into the preceding assistant tool-call// part's `result` field rather than becoming separate records.+function oaiContentToParts(raw: unknown): unknown[] {+ if (!Array.isArray(raw)) {+ return typeof raw === "string" && raw.trim()+ ? [{ type: "text", text: raw }]+ : [];+ }++ return raw.flatMap((value): unknown[] => {+ if (typeof value !== "object" || value === null) return [];+ const part = value as Record<string, unknown>;+ if (part.type === "text" && typeof part.text === "string") {+ return [{ type: "text", text: part.text }];+ }+ if (part.type === "image_url") {+ const imageUrl =+ typeof part.image_url === "object" && part.image_url !== null+ ? (part.image_url as Record<string, unknown>).url+ : undefined;+ return typeof imageUrl === "string" && imageUrl+ ? [{ type: "image", image: imageUrl }]+ : [];+ }+ return [];+ });+}+function oaiMessagesToRecords(oaiMsgs: unknown[],threadId: string,@@ -136,10 +166,7 @@ function oaiMessagesToRecords(let content: unknown[];if (role === "assistant") {- const parts: unknown[] = [];- if (typeof msg.content === "string" && msg.content.trim()) {- parts.push({ type: "text", text: msg.content });- }+ const parts = oaiContentToParts(msg.content);if (Array.isArray(msg.tool_calls)) {for (const tc of msg.tool_calls) {const tcObj = tc as Record<string, unknown>;@@ -164,22 +191,7 @@ function oaiMessagesToRecords(}content = parts;} else {- const raw = msg.content;- if (Array.isArray(raw)) {- content = raw.flatMap((p): unknown[] => {- const part = p as Record<string, unknown>;- if (part.type === "text" && typeof part.text === "string") {- return [{ type: "text", text: part.text }];- }- if (part.type === "image_url") {- const iu = (part.image_url as Record<string, unknown>) ?? {};- return [{ type: "image", image: typeof iu.url === "string" ? iu.url : "" }];- }- return [];- });- } else {- content = typeof raw === "string" && raw.trim() ? [{ type: "text", text: raw }] : [];- }+ content = oaiContentToParts(msg.content);}if (content.length === 0) continue;@@ -188,7 +200,7 @@ function oaiMessagesToRecords(id,threadId,parentId: prevId,- role: role as MessageRecord["role"],+ role: (role === "developer" ? "system" : role) as MessageRecord["role"],content: content as MessageRecord["content"],createdAt: baseTs + idx,});@@ -298,6 +310,7 @@ export function parseImportText(}const results: ParsedConversation[] = [];+ const messageRecords: Record<string, unknown>[] = [];let index = 0;for (const line of text.split(/\r?\n/)) {if (!line.trim()) continue;@@ -307,8 +320,17 @@ export function parseImportText(} catch {continue;}- const parsed = recordToConversation(record, `${basename} ${index + 1}`);index++;+ if (isOpenAIMessageRecord(record)) {+ messageRecords.push(record);+ continue;+ }+ const parsed = recordToConversation(record, `${basename} ${index}`);+ if (parsed) results.push(parsed);+ }+ const messageConversation = messageJsonlConversationRecord(messageRecords);+ if (messageConversation) {+ const parsed = recordToConversation(messageConversation, basename);if (parsed) results.push(parsed);}return results;@@ -366,6 +388,7 @@ export async function importConversationsFromSource(}const inFlight = new Set<Promise<void>>();+ const messageRecords: Record<string, unknown>[] = [];let index = 0;let failure: unknown;let reportedBytes = 0;@@ -384,8 +407,12 @@ export async function importConversationsFromSource(progress.failed++;},})) {- const conversation = recordToConversation(record, `${basename} ${index + 1}`);index++;+ if (isOpenAIMessageRecord(record)) {+ messageRecords.push(record);+ continue;+ }+ const conversation = recordToConversation(record, `${basename} ${index}`);if (!conversation) continue;const task = writeConversation(conversation, projectId)@@ -408,6 +435,21 @@ export async function importConversationsFromSource(failure = error;}+ if (failure === undefined) {+ const messageConversation = messageJsonlConversationRecord(messageRecords);+ const conversation = messageConversation+ ? recordToConversation(messageConversation, basename)+ : null;+ if (conversation) {+ try {+ await writeConversation(conversation, projectId);+ progress.imported++;+ } catch {+ progress.failed++;+ }+ }+ }+await Promise.allSettled(inFlight);// Those chats have to reach the sidebar even when the read failed, or the UI// stays empty until a reload and a retry duplicates every one of them.diff --git a/studio/frontend/src/features/chat/utils/message-order.ts b/studio/frontend/src/features/chat/utils/message-order.tsnew file mode 100644index 00000000000..7f25c83b37b--- /dev/null+++ b/studio/frontend/src/features/chat/utils/message-order.ts@@ -0,0 +1,91 @@+// 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 ParentLinkedMessage = {+ id: string;+ parentId?: string | null;+ createdAt?: number;+ role?: string;+};++const ROLE_ORDER: Record<string, number> = { system: 0, user: 1, assistant: 2 };++export function orderBySelectedBranch<T extends ParentLinkedMessage>(+ messages: T[],+): T[] {+ const sorted = messages.slice().sort((a, b) => {+ const createdAtDelta = (a.createdAt ?? 0) - (b.createdAt ?? 0);+ if (createdAtDelta !== 0) {+ return createdAtDelta;+ }+ const roleDelta =+ (ROLE_ORDER[a.role ?? ""] ?? 99) - (ROLE_ORDER[b.role ?? ""] ?? 99);+ if (roleDelta !== 0) {+ return roleDelta;+ }+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;+ });++ const byId = new Map<string, T>();+ const parentOf = new Map<string, string | null>();+ let previousId: string | null = null;+ for (const message of sorted) {+ byId.set(message.id, message);+ parentOf.set(message.id, message.parentId ?? previousId);+ previousId = message.id;+ }++ const chain: T[] = [];+ const seen = new Set<string>();+ let currentId: string | null = sorted.at(-1)?.id ?? null;+ while (currentId != null && !seen.has(currentId)) {+ seen.add(currentId);+ const message = byId.get(currentId);+ if (!message) {+ break;+ }+ chain.push(message);+ currentId = parentOf.get(currentId) ?? null;+ }+ return chain.reverse();+}++// follow the newest parent chain because response slots can predate the next user message.+export function orderByParentChain<T extends ParentLinkedMessage>(+ messages: T[],+ options: { includeSiblings?: boolean } = {},+): T[] {+ const { includeSiblings = true } = options;+ if (!includeSiblings) {+ return orderBySelectedBranch(messages);+ }+ const byId = new Map<string, T>(+ messages.map((message) => [message.id, message]),+ );+ const childrenOf = new Map<string | null, T[]>();+ for (const message of messages) {+ const parentId = message.parentId ?? null;+ const children = childrenOf.get(parentId) ?? [];+ children.push(message);+ childrenOf.set(parentId, children);+ }++ const result: T[] = [];+ let currentId: string | null = null;+ while (childrenOf.has(currentId)) {+ const children: T[] = childrenOf.get(currentId) ?? [];+ const next: T = children.reduce((latest: T, candidate: T) =>+ (latest.createdAt ?? 0) >= (candidate.createdAt ?? 0)+ ? latest+ : candidate,+ );+ result.push(next);+ currentId = next.id;+ byId.delete(next.id);+ }++ for (const message of byId.values()) {+ result.push(message);+ }+ return result;+}diff --git a/studio/frontend/src/features/chat/utils/ndjson.ts b/studio/frontend/src/features/chat/utils/ndjson.tsnew file mode 100644index 00000000000..97be7e7be59--- /dev/null+++ b/studio/frontend/src/features/chat/utils/ndjson.ts@@ -0,0 +1,51 @@+// 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 ConversationJsonlLayout = "training" | "messages";++export function canMergeConversationExport(format: string): boolean {+ return format !== "jsonl-messages";+}++export function exportFormatIncludesSiblings(format: string): boolean {+ return format !== "jsonl-raw" && format !== "jsonl-messages";+}++const OPENAI_MESSAGE_ROLES = new Set([+ "system",+ "developer",+ "user",+ "assistant",+ "tool",+]);++export function isOpenAIMessageRecord(+ record: unknown,+): record is Record<string, unknown> {+ if (typeof record !== "object" || record === null || Array.isArray(record)) {+ return false;+ }+ const message = record as Record<string, unknown>;+ return (+ typeof message.role === "string" &&+ OPENAI_MESSAGE_ROLES.has(message.role) &&+ ("content" in message || Array.isArray(message.tool_calls))+ );+}++export function messageJsonlConversationRecord(+ records: readonly unknown[],+): { messages: Record<string, unknown>[] } | null {+ if (records.length === 0 || !records.every(isOpenAIMessageRecord)) {+ return null;+ }+ return { messages: [...records] };+}++export function conversationJsonlBody(+ messages: readonly unknown[],+ layout: ConversationJsonlLayout,+): string {+ const records = layout === "training" ? [{ messages }] : messages;+ return records.map((record) => JSON.stringify(record)).join("\n");+}diff --git a/studio/frontend/src/features/settings/components/manage-chats-view.tsx b/studio/frontend/src/features/settings/components/manage-chats-view.tsxindex ab51c943fc0..c4e1cf6f556 100644--- a/studio/frontend/src/features/settings/components/manage-chats-view.tsx+++ b/studio/frontend/src/features/settings/components/manage-chats-view.tsx@@ -21,6 +21,7 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import {+ COMBINED_EXPORT_FORMATS_LIST,type ConvExportFormat,EXPORT_FORMATS_LIST,type SidebarItem,@@ -329,7 +330,7 @@ export function ManageChatsView() {</Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-56">- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (<DropdownMenuItemkey={`m-${fmt}`}onSelect={() => void handleExport(fmt, true)}diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsxindex 00ab0c25388..bf3af3333ef 100644--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx@@ -24,6 +24,7 @@ import { Spinner } from "@/components/ui/spinner";import { Switch } from "@/components/ui/switch";import { usePlatformStore } from "@/config/env";import {+ COMBINED_EXPORT_FORMATS_LIST,EXPORT_FORMATS_LIST,type FineTuneFormat,archiveAllChatItems,@@ -834,7 +835,7 @@ export function DataTab() {{t(`settings.chat.${label}`)}</DropdownMenuSubTrigger><DropdownMenuSubContent className="w-56">- {EXPORT_FORMATS_LIST.map(({ fmt, label: fmtLabel }) => (+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label: fmtLabel }) => (<DropdownMenuItemkey={`${scope}-m-${fmt}`}onSelect={() =>diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex c30f63aaf01..6e44d2ae874 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1360,7 +1360,7 @@ export const ar = {exportingAction: "جارٍ التصدير...",exportConversations: "تصدير العناصر الأخيرة والمشاريع",exportConversationsDescription:- "نزّل العناصر الأخيرة وحدها أو مع محادثات المشاريع بصيغة JSONL خام أو CSV أو ShareGPT JSONL، في ملف مجمّع أو في ملف لكل محادثة.",+ "نزّل العناصر الأخيرة وحدها أو مع محادثات المشاريع بصيغة Training JSONL أو CSV أو ShareGPT JSONL، في ملف مجمّع أو في ملف لكل محادثة. يتوفر Message JSONL لكل محادثة فقط.",exportConversationsAction: "تصدير",exportScopeRecents: "العناصر الأخيرة",exportScopeAll: "العناصر الأخيرة + المشاريع",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 329be2e0f52..344e2771abd 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1397,7 +1397,7 @@ export const de = {exportingAction: "Wird exportiert...",exportConversations: "„Zuletzt verwendet“ und Projekte exportieren",exportConversationsDescription:- "Laden Sie Chats aus „Zuletzt verwendet“ oder zusätzlich auch Projekt-Chats als Raw JSONL, CSV oder ShareGPT JSONL herunter, kombiniert oder einzeln pro Chat.",+ "Laden Sie Chats aus „Zuletzt verwendet“ oder zusätzlich auch Projekt-Chats als Training JSONL, CSV oder ShareGPT JSONL herunter, kombiniert oder einzeln pro Chat. Message JSONL ist nur einzeln pro Chat verfügbar.",exportConversationsAction: "Exportieren",exportScopeRecents: "Zuletzt verwendet",exportScopeAll: "Zuletzt verwendet + Projekte",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 98da0ec5607..fe56f86cdc3 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1361,7 +1361,7 @@ export const en = {exportingAction: "Exporting...",exportConversations: "Export Recents and Projects",exportConversationsDescription:- "Download Recents or Recents plus project chats as Raw JSONL, CSV, or ShareGPT JSONL, combined or per chat.",+ "Download Recents or Recents plus project chats as Training JSONL, CSV, or ShareGPT JSONL, combined or per chat. Message JSONL is available per chat.",exportConversationsAction: "Export",exportScopeRecents: "Recents",exportScopeAll: "Recents + Projects",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 181a1440280..d999cf667ef 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1388,7 +1388,7 @@ export const es = {exportingAction: "Exportando...",exportConversations: "Exportar Recientes y Proyectos",exportConversationsDescription:- "Descarga Recientes, o Recientes más los chats de proyectos, como JSONL sin procesar, CSV o JSONL de ShareGPT, combinados o por chat.",+ "Descarga Recientes, o Recientes más los chats de proyectos, como Training JSONL, CSV o JSONL de ShareGPT, combinados o por chat. Message JSONL solo está disponible por chat.",exportConversationsAction: "Exportar",exportScopeRecents: "Recientes",exportScopeAll: "Recientes + Proyectos",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 0d0f91a7d8f..f860ea10805 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1394,7 +1394,7 @@ export const fr = {exportingAction: "Exportation...",exportConversations: "Exporter Récents et Projets",exportConversationsDescription:- "Télécharger Récents ou Récents plus les discussions de projet au format JSONL brut, CSV ou JSONL ShareGPT, combinés ou par discussion.",+ "Télécharger Récents ou Récents plus les discussions de projet au format Training JSONL, CSV ou JSONL ShareGPT, combinés ou par discussion. Message JSONL est disponible uniquement par discussion.",exportConversationsAction: "Exporter",exportScopeRecents: "Récents",exportScopeAll: "Récents + Projets",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 5c78ff6613b..41948879027 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1366,7 +1366,7 @@ export const hi = {exportingAction: "एक्सपोर्ट हो रहा है...",exportConversations: "हाल के और प्रोजेक्ट एक्सपोर्ट करें",exportConversationsDescription:- "हाल के या हाल के और प्रोजेक्ट चैट को Raw JSONL, CSV या ShareGPT JSONL के रूप में डाउनलोड करें, एक संयुक्त फ़ाइल में या हर चैट के लिए अलग-अलग।",+ "हाल के या हाल के और प्रोजेक्ट चैट को Training JSONL, CSV या ShareGPT JSONL के रूप में डाउनलोड करें, एक संयुक्त फ़ाइल में या हर चैट के लिए अलग-अलग। Message JSONL केवल हर चैट के लिए अलग फ़ाइल में उपलब्ध है।",exportConversationsAction: "एक्सपोर्ट करें",exportScopeRecents: "हाल के",exportScopeAll: "हाल के + प्रोजेक्ट",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 3f33a16cfba..7761ee7f3f6 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1361,7 +1361,7 @@ export const it = {exportingAction: "Esportazione...",exportConversations: "Esporta Recenti e Progetti",exportConversationsDescription:- "Scarica i Recenti, oppure i Recenti più le chat dei progetti, in JSONL grezzo, CSV o JSONL ShareGPT, in un unico file o uno per chat.",+ "Scarica i Recenti, oppure i Recenti più le chat dei progetti, in Training JSONL, CSV o JSONL ShareGPT, in un unico file o uno per chat. Message JSONL è disponibile solo per singola chat.",exportConversationsAction: "Esporta",exportScopeRecents: "Recenti",exportScopeAll: "Recenti + Progetti",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex c6b229cd4e4..02135261ef7 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1347,7 +1347,7 @@ export const ja = {exportingAction: "エクスポート中...",exportConversations: "履歴とプロジェクトをエクスポート",exportConversationsDescription:- "履歴、または履歴とプロジェクトのチャットを、Raw JSONL、CSV、ShareGPT JSONL のいずれかで、一括またはチャットごとにダウンロードします。",+ "履歴、または履歴とプロジェクトのチャットを、Training JSONL、CSV、ShareGPT JSONL のいずれかで、一括またはチャットごとにダウンロードします。Message JSONL はチャットごとのみ利用できます。",exportConversationsAction: "エクスポート",exportScopeRecents: "履歴",exportScopeAll: "履歴 + プロジェクト",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 5ea36641a6d..96b18c57413 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1359,7 +1359,7 @@ export const ko = {exportingAction: "내보내는 중...",exportConversations: "최근 항목 및 프로젝트 내보내기",exportConversationsDescription:- "최근 항목 또는 최근 항목과 프로젝트 채팅을 Raw JSONL, CSV 또는 ShareGPT JSONL로, 통합하거나 채팅별로 다운로드합니다.",+ "최근 항목 또는 최근 항목과 프로젝트 채팅을 Training JSONL, CSV 또는 ShareGPT JSONL로, 통합하거나 채팅별로 다운로드합니다. Message JSONL은 채팅별로만 사용할 수 있습니다.",exportConversationsAction: "내보내기",exportScopeRecents: "최근 항목",exportScopeAll: "최근 항목 + 프로젝트",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 86b5f878716..26f6500c0d6 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1376,7 +1376,7 @@ export const ptBR = {exportingAction: "Exportando...",exportConversations: "Exportar Recentes e Projetos",exportConversationsDescription:- "Baixe os chats de Recentes ou de Recentes e Projetos como JSONL bruto, CSV ou JSONL do ShareGPT, em um arquivo combinado ou em arquivos separados por chat.",+ "Baixe os chats de Recentes ou de Recentes e Projetos como Training JSONL, CSV ou JSONL do ShareGPT, em um arquivo combinado ou em arquivos separados por chat. Message JSONL está disponível apenas por chat.",exportConversationsAction: "Exportar",exportScopeRecents: "Recentes",exportScopeAll: "Recentes + Projetos",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex b718bf04e1a..e268527cc66 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1372,7 +1372,7 @@ export const ru = {exportingAction: "Экспорт…",exportConversations: "Экспортировать «Недавние» и проекты",exportConversationsDescription:- "Скачать «Недавние» или «Недавние» вместе с чатами проектов в формате Raw JSONL, CSV или ShareGPT JSONL, объединённо или по чатам.",+ "Скачать «Недавние» или «Недавние» вместе с чатами проектов в формате Training JSONL, CSV или ShareGPT JSONL, объединённо или по чатам. Message JSONL доступен только по отдельным чатам.",exportConversationsAction: "Экспорт",exportScopeRecents: "Недавние",exportScopeAll: "Недавние + проекты",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 418ed0fc86d..56e5fe03baf 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1332,7 +1332,7 @@ export const zhCN = {exportingAction: "导出中...",exportConversations: "导出最近对话与项目",exportConversationsDescription:- "将最近对话(或加上项目内对话)导出为 Raw JSONL、CSV 或 ShareGPT JSONL,可合并为单个文件或每个对话一个文件。",+ "将最近对话(或加上项目内对话)导出为 Training JSONL、CSV 或 ShareGPT JSONL,可合并为单个文件或每个对话一个文件。Message JSONL 仅支持每个对话单独导出。",exportConversationsAction: "导出",exportScopeRecents: "最近对话",exportScopeAll: "最近对话 + 项目",diff --git a/studio/frontend/tests/message-jsonl-import.test.ts b/studio/frontend/tests/message-jsonl-import.test.tsnew file mode 100644index 00000000000..af9adb5aac7--- /dev/null+++ b/studio/frontend/tests/message-jsonl-import.test.ts@@ -0,0 +1,114 @@+// 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 { readFileSync } from "node:fs";+import vm from "node:vm";+import { after, before, test } from "node:test";+import ts from "typescript";+import { type ViteDevServer, createServer } from "vite";+import type { ParsedConversation } from "../src/features/chat/types.ts";++let vite: ViteDevServer;+let parseImportText: (text: string, filename: string) => ParsedConversation[];+let messageToOpenAI: (message: {+ role: unknown;+ content: unknown;+ attachments?: unknown;+}) => unknown[];++function loadMessageToOpenAI(): typeof messageToOpenAI {+ const source = readFileSync(+ new URL(+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ const start = source.indexOf("type OAIContentPart =");+ const end = source.indexOf("// ShareGPT training JSONL", start);+ assert.notEqual(start, -1, "message serializer start marker must exist");+ assert.notEqual(end, -1, "message serializer end marker must exist");+ const exactSerializer =+ source.slice(start, end) ++ "\nglobalThis.__messageToOpenAI = messageToOpenAI;\n";+ const javascript = ts.transpileModule(exactSerializer, {+ compilerOptions: {+ module: ts.ModuleKind.None,+ target: ts.ScriptTarget.ES2022,+ },+ }).outputText;+ const context = {+ unwrapPastedTextContent: (text: string) => text,+ toolResultModelText: (result: unknown) => result,+ } as Record<string, unknown>;+ vm.runInNewContext(javascript, context);+ return context.__messageToOpenAI as typeof messageToOpenAI;+}++before(async () => {+ vite = await createServer({+ appType: "custom",+ server: { middlewareMode: true },+ });+ const loaded = await vite.ssrLoadModule(+ "/src/features/chat/utils/chat-import.ts",+ );+ parseImportText = loaded.parseImportText as typeof parseImportText;+ messageToOpenAI = loadMessageToOpenAI();+});++after(async () => {+ await vite.close();+});++test("message JSONL imports as one conversation", () => {+ const conversations = parseImportText(+ '{"role":"user","content":"Hello"}\n' ++ '{"role":"assistant","content":"Hi"}',+ "conversation-messages.jsonl",+ );++ assert.equal(conversations.length, 1);+ assert.equal(conversations[0].title, "conversation-messages");+ assert.deepEqual(+ conversations[0].messages.map(({ role }) => role),+ ["user", "assistant"],+ );+});++test("developer and assistant array content survive message JSONL import", () => {+ const image = "data:image/png;base64,QUFBQQ==";+ const [conversation] = parseImportText(+ '{"role":"developer","content":"Follow policy"}\n' ++ '{"role":"assistant","content":[{"type":"text","text":"Done"},{"type":"image_url","image_url":{"url":"' ++ image ++ '"}}]}',+ "conversation-messages.jsonl",+ );++ assert.deepEqual(+ conversation.messages.map(({ role }) => role),+ ["system", "assistant"],+ );+ assert.deepEqual(conversation.messages[1].content, [+ { type: "text", text: "Done" },+ { type: "image", image },+ ]);+});++test("assistant images are represented explicitly in JSONL exports", () => {+ const exported = structuredClone(+ messageToOpenAI({+ role: "assistant",+ content: [+ { type: "text", text: "Chart" },+ { type: "image", image: "data:image/png;base64,QUFBQQ==" },+ ],+ }),+ );+ assert.deepEqual(+ exported,+ [{ role: "assistant", content: "Chart\n\n[image attachment]" }],+ );+});diff --git a/studio/frontend/tests/ndjson-body.test.ts b/studio/frontend/tests/ndjson-body.test.tsnew file mode 100644index 00000000000..f390c3f4c5e--- /dev/null+++ b/studio/frontend/tests/ndjson-body.test.ts@@ -0,0 +1,96 @@+// 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 { orderByParentChain } from "../src/features/chat/utils/message-order.ts";+import {+ canMergeConversationExport,+ conversationJsonlBody,+ exportFormatIncludesSiblings,+ isOpenAIMessageRecord,+ messageJsonlConversationRecord,+} from "../src/features/chat/utils/ndjson.ts";++const messages = [+ { role: "user", content: "Hello" },+ { role: "assistant", content: "Hi" },+];++test("training JSONL keeps one conversation per record", () => {+ assert.equal(+ conversationJsonlBody(messages, "training"),+ '{"messages":[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"}]}',+ );+});++test("message JSONL writes one message per record", () => {+ const body = conversationJsonlBody(messages, "messages");+ assert.equal(+ body,+ '{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi"}',+ );+ assert.deepEqual(+ body.split("\n").map((line) => JSON.parse(line)),+ messages,+ );+});++test("empty conversations produce an empty body", () => {+ assert.equal(conversationJsonlBody([], "training"), '{"messages":[]}');+ assert.equal(conversationJsonlBody([], "messages"), "");+});++test("message JSONL records form one importable conversation", () => {+ assert.equal(isOpenAIMessageRecord(messages[0]), true);+ assert.equal(+ isOpenAIMessageRecord({ role: "developer", content: "Follow policy" }),+ true,+ );+ assert.equal(isOpenAIMessageRecord({ messages }), false);+ assert.deepEqual(messageJsonlConversationRecord(messages), { messages });+});++test("message JSONL cannot merge conversations without losing boundaries", () => {+ assert.equal(canMergeConversationExport("jsonl-messages"), false);+ assert.equal(canMergeConversationExport("jsonl-raw"), true);+});++test("both JSONL layouts export only the displayed branch", () => {+ assert.equal(exportFormatIncludesSiblings("jsonl-raw"), false);+ assert.equal(exportFormatIncludesSiblings("jsonl-messages"), false);+ assert.equal(exportFormatIncludesSiblings("csv"), true);+ assert.equal(exportFormatIncludesSiblings("sharegpt"), true);+});++test("training order excludes abandoned response branches", () => {+ const branched = [+ { id: "user", parentId: null, createdAt: 1 },+ { id: "old-reply", parentId: "user", createdAt: 2 },+ { id: "new-reply", parentId: "user", createdAt: 3 },+ { id: "follow-up", parentId: "new-reply", createdAt: 4 },+ ];+ assert.deepEqual(+ orderByParentChain(branched, { includeSiblings: false }).map(+ ({ id }) => id,+ ),+ ["user", "new-reply", "follow-up"],+ );+});++test("training order follows the displayed branch ancestor chain", () => {+ const branched = [+ { id: "user-1", parentId: null, createdAt: 1, role: "user" },+ { id: "selected", parentId: "user-1", createdAt: 2, role: "assistant" },+ { id: "abandoned", parentId: "user-1", createdAt: 5, role: "assistant" },+ { id: "user-2", parentId: "selected", createdAt: 6, role: "user" },+ { id: "answer", parentId: "user-2", createdAt: 7, role: "assistant" },+ ];++ assert.deepEqual(+ orderByParentChain(branched, { includeSiblings: false }).map(+ ({ id }) => id,+ ),+ ["user-1", "selected", "user-2", "answer"],+ );+});