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: import Open WebUI chat exports (#8643)

oobabooga42c86719bcc3
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 1a62a61e316..7bee6b990f6 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -209,9 +209,17 @@ export {
buildFineTuneJsonl,
bulkExportConversationsByScope,
exportFineTuneJsonl,
- importConversationsFromFile,
type FineTuneFormat,
} from "./prompt-storage/prompt-storage-dialog";
+export {
+ fileImportSource,
+ importConversationsFromFile,
+ importConversationsFromSource,
+ nativeImportSource,
+ type ImportProgress,
+ type ImportResult,
+ type ImportSource,
+} from "./utils/chat-import";
export {
archiveAllChatItems,
archiveChatItem,
diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsx
index 192c4e2331c..e06f9c250b0 100644
--- a/studio/frontend/src/features/chat/projects-page.tsx
+++ b/studio/frontend/src/features/chat/projects-page.tsx
@@ -61,10 +61,15 @@ import {
exportProjectConversations,
exportBulkConversationsMerged,
exportBulkConversationsSeparate,
- importConversationsFromFile,
EXPORT_FORMATS_LIST,
type ConvExportFormat,
} from "./prompt-storage/prompt-storage-dialog";
+import {
+ fileImportSource,
+ importConversationsFromSource,
+ nativeImportSource,
+ type ImportSource,
+} from "./utils/chat-import";
import {
listStoredChatThreads,
} from "./utils/chat-history-storage";
@@ -130,28 +135,65 @@ export function ProjectsPage() {
const globalImportRef = useRef<HTMLInputElement>(null);
const projectImportRefs = useRef<Map<string, HTMLInputElement>>(new Map());
- const [importFile, setImportFile] = useState<File | null>(null);
+ const [importFile, setImportFile] = useState<ImportSource | null>(null);
+ // A second pick mid-import would interleave two streams into one history.
+ const [importing, setImporting] = useState(false);
// null = Recents
const [importTargetId, setImportTargetId] = useState<string | null>(null);
- async function handleImport(file: File, projectId: string | null) {
+ async function handleImport(source: ImportSource, projectId: string | null) {
+ // Counts up while it runs: a large export takes minutes of writes.
+ setImporting(true);
+ const toastId = toast.loading("Importing chats...");
try {
- const count = await importConversationsFromFile(file, projectId);
- if (count === 0) {
- toast.info("No conversations found in file.");
- } else {
- const dest = projectId
- ? (projects.find((p) => p.id === projectId)?.name ?? "project")
- : "Recents";
- toast.success(`Imported ${count} conversation${count === 1 ? "" : "s"} to ${dest}.`);
+ const { imported, failed } = await importConversationsFromSource(
+ source,
+ projectId,
+ {
+ onProgress: ({ imported: done, bytesRead, totalBytes }) => {
+ const percent = totalBytes
+ ? Math.min(100, Math.round((bytesRead / totalBytes) * 100))
+ : 0;
+ toast.loading(`Importing chats: ${done} so far (${percent}%)...`, {
+ id: toastId,
+ });
+ },
+ },
+ );
+ if (imported === 0 && failed === 0) {
+ toast.info("No conversations found in file.", { id: toastId });
+ return;
+ }
+ if (imported === 0) {
+ // Nothing was created, so however the count is phrased this is a failure.
+ toast.error("Import failed.", {
+ id: toastId,
+ description: `${failed} conversation${failed === 1 ? "" : "s"} could not be saved.`,
+ });
+ return;
}
- } catch {
- toast.error("Import failed.");
+ const dest = projectId
+ ? (projects.find((p) => p.id === projectId)?.name ?? "project")
+ : "Recents";
+ toast.success(
+ failed > 0
+ ? `Imported ${imported} conversation${imported === 1 ? "" : "s"} to ${dest}; ${failed} could not be saved.`
+ : `Imported ${imported} conversation${imported === 1 ? "" : "s"} to ${dest}.`,
+ { id: toastId },
+ );
+ } catch (error) {
+ toast.error("Import failed.", {
+ id: toastId,
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ setImporting(false);
}
}
async function selectGlobalImportFile() {
+ if (importing) return;
if (!isTauri) {
globalImportRef.current?.click();
return;
@@ -160,7 +202,7 @@ export function ProjectsPage() {
const selected = await pickNativeChatImport();
if (!selected) return;
setImportTargetId(projects[0]?.id ?? null);
- setImportFile(new File([selected.content], selected.name));
+ setImportFile(nativeImportSource(selected));
} catch (error) {
toast.error("Import failed.", {
description: error instanceof Error ? error.message : String(error),
@@ -169,6 +211,7 @@ export function ProjectsPage() {
}
async function selectProjectImportFile(projectId: string) {
+ if (importing) return;
if (!isTauri) {
projectImportRefs.current.get(projectId)?.click();
return;
@@ -176,7 +219,7 @@ export function ProjectsPage() {
try {
const selected = await pickNativeChatImport();
if (!selected) return;
- await handleImport(new File([selected.content], selected.name), projectId);
+ await handleImport(nativeImportSource(selected), projectId);
} catch (error) {
toast.error("Import failed.", {
description: error instanceof Error ? error.message : String(error),
@@ -339,13 +382,13 @@ export function ProjectsPage() {
<input
ref={globalImportRef}
type="file"
- accept=".jsonl,.ndjson,.csv"
+ accept=".json,.jsonl,.ndjson,.csv"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
setImportTargetId(projects[0]?.id ?? null);
- setImportFile(file);
+ setImportFile(fileImportSource(file));
}
e.target.value = "";
}}
@@ -513,7 +556,7 @@ export function ProjectsPage() {
<input
key={`import-${project.id}`}
type="file"
- accept=".jsonl,.ndjson,.csv"
+ accept=".json,.jsonl,.ndjson,.csv"
className="hidden"
ref={(el) => {
if (el) projectImportRefs.current.set(project.id, el);
@@ -521,7 +564,7 @@ export function ProjectsPage() {
}}
onChange={(e) => {
const file = e.target.files?.[0];
- if (file) void handleImport(file, project.id);
+ if (file) void handleImport(fileImportSource(file), project.id);
e.target.value = "";
}}
/>
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 f2c3017f91b..bdd70e4c1ac 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
@@ -60,6 +60,7 @@ import { toolResultModelText } 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 { parseCsv } from "../utils/csv-parse";
import { unwrapPastedTextContent } from "../utils/pasted-text.ts";
import {
contentBlocksToMarkdownBlocks,
@@ -817,234 +818,6 @@ export async function exportFineTuneJsonl(
return conversations;
}
-// role:"tool" results are absorbed into the preceding assistant tool-call
-// part's `result` field rather than becoming separate records.
-function oaiMessagesToRecords(
- oaiMsgs: unknown[],
- threadId: string,
- baseTs: number,
-): MessageRecord[] {
- const toolResults = new Map<string, string>();
- for (const m of oaiMsgs) {
- const msg = m as Record<string, unknown>;
- if (msg.role === "tool" && typeof msg.tool_call_id === "string") {
- toolResults.set(msg.tool_call_id, typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content ?? ""));
- }
- }
-
- const records: MessageRecord[] = [];
- let prevId: string | null = null;
- let idx = 0;
-
- for (const m of oaiMsgs) {
- const msg = m as Record<string, unknown>;
- const role = msg.role as string;
- if (role === "tool") continue;
-
- const id = crypto.randomUUID();
-
- let content: unknown[];
-
- if (role === "assistant") {
- const parts: unknown[] = [];
- if (typeof msg.content === "string" && msg.content.trim()) {
- parts.push({ type: "text", text: msg.content });
- }
- if (Array.isArray(msg.tool_calls)) {
- for (const tc of msg.tool_calls) {
- const tcObj = tc as Record<string, unknown>;
- const fn = (tcObj.function as Record<string, unknown>) ?? {};
- const tcId = typeof tcObj.id === "string" ? tcObj.id : crypto.randomUUID();
- const name = typeof fn.name === "string" ? fn.name : "unknown";
- const argsStr = typeof fn.arguments === "string" ? fn.arguments : "{}";
- let args: unknown = {};
- try { args = JSON.parse(argsStr); } catch { /* keep empty */ }
- const result = toolResults.get(tcId);
- parts.push({
- type: "tool-call",
- toolCallId: tcId,
- toolName: name,
- args,
- argsText: argsStr,
- ...(result !== undefined ? { result } : {}),
- });
- }
- }
- 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 }] : [];
- }
- }
-
- if (content.length === 0) continue;
-
- records.push({
- id,
- threadId,
- parentId: prevId,
- role: role as MessageRecord["role"],
- content: content as MessageRecord["content"],
- createdAt: baseTs + idx,
- });
- prevId = id;
- idx++;
- }
-
- return records;
-}
-
-function sharegptToRecords(
- conversations: unknown[],
- threadId: string,
- baseTs: number,
-): MessageRecord[] {
- const records: MessageRecord[] = [];
- let prevId: string | null = null;
- let idx = 0;
- for (const c of conversations) {
- const conv = c as Record<string, unknown>;
- const from = typeof conv.from === "string" ? conv.from : "";
- const value = typeof conv.value === "string" ? conv.value : "";
- if (!value.trim()) continue;
- const role: MessageRecord["role"] = from === "human" ? "user" : from === "system" ? "system" : "assistant";
- const id = crypto.randomUUID();
- records.push({
- id,
- threadId,
- parentId: prevId,
- role,
- content: [{ type: "text", text: value }] as MessageRecord["content"],
- createdAt: baseTs + idx,
- });
- 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; a naive per-line split would break those records.
- const rows = parseCsv(csvText).slice(1);
- const records: MessageRecord[] = [];
- let prevId: string | null = null;
- let idx = 0;
- for (const row of rows) {
- if (row.length < 2) continue;
- const role = row[0].trim();
- const content = row.slice(1).join(",");
- if (!content.trim()) continue;
- const validRole = role === "user" || role === "assistant" || role === "system" ? role : "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,
- });
- prevId = id;
- idx++;
- }
- return records;
-}
-
-interface ParsedConversation {
- title: string;
- threadId: string;
- messages: MessageRecord[];
-}
-
-function parseImportText(text: string, filename: string): ParsedConversation[] {
- const results: ParsedConversation[] = [];
- const basename = filename.replace(/\.[^.]+$/, "");
-
- const isJsonl = /\.(jsonl|ndjson)$/i.test(filename);
- const isCsv = /\.csv$/i.test(filename);
-
- if (isCsv) {
- const threadId = crypto.randomUUID();
- const messages = csvToRecords(text, threadId, Date.now());
- if (messages.length > 0) {
- results.push({ title: basename, threadId, messages });
- }
- return results;
- }
-
- if (isJsonl) {
- const lines = text.split(/\r?\n/).filter((l) => l.trim());
- lines.forEach((line, lineIdx) => {
- let obj: Record<string, unknown>;
- try { obj = JSON.parse(line); } catch { return; }
-
- // Fresh ID: reusing the exported thread_id would clobber an existing
- // thread on import.
- const threadId = crypto.randomUUID();
- const title = typeof obj.title === "string" ? obj.title : `${basename} ${lineIdx + 1}`;
- const baseTs = typeof obj.created_at === "number" ? obj.created_at : Date.now() + lineIdx;
-
- let messages: MessageRecord[] = [];
-
- if (Array.isArray(obj.messages)) {
- messages = oaiMessagesToRecords(obj.messages, threadId, baseTs);
- } else if (Array.isArray(obj.conversations)) {
- messages = sharegptToRecords(obj.conversations, threadId, baseTs);
- }
-
- if (messages.length > 0) {
- results.push({ title, threadId, messages });
- }
- });
- return results;
- }
-
- // Unknown extension: retry as JSONL.
- return parseImportText(text, filename + ".jsonl");
-}
-
-export async function importConversationsFromFile(
- file: File,
- projectId: string | null = null,
-): Promise<number> {
- const text = await file.text();
- const parsed = parseImportText(text, file.name);
- if (parsed.length === 0) return 0;
-
- const now = Date.now();
- await Promise.all(
- parsed.map(async ({ title, threadId, messages }) => {
- const thread: ThreadRecord = {
- id: threadId,
- title,
- modelType: "base",
- projectId: projectId ?? null,
- archived: false,
- createdAt: messages[0]?.createdAt ?? now,
- };
- await saveStoredChatThread(thread);
- await syncStoredChatMessages(threadId, messages, { pruneMissing: false });
- }),
- );
-
- notifyChatHistoryUpdated();
- return parsed.length;
-}
-
// ShareGPT training exports: prompt → one record (human turn + empty gpt slot);
// list → one multi-turn record, each item a human turn.
function exportPromptTrainingJsonl(entry: PromptEntry): Promise<void> {
@@ -1100,62 +873,6 @@ function exportListsTrainingJsonl(entries: PromptListEntry[]): Promise<void> {
return downloadBlob(lines, "prompt-lists-training.jsonl", "application/x-ndjson");
}
-// RFC 4180 CSV parser: handles quoted fields with embedded newlines/commas.
-function parseCsv(text: string): string[][] {
- const rows: string[][] = [];
- let row: string[] = [];
- let i = 0;
-
- function finishRow() {
- rows.push(row);
- row = [];
- }
-
- while (i < text.length) {
- if (text[i] === '"') {
- i++;
- let cell = "";
- while (i < text.length) {
- if (text[i] === '"') {
- if (text[i + 1] === '"') {
- cell += '"';
- i += 2;
- } else {
- i++;
- break;
- }
- } else {
- cell += text[i++];
- }
- }
- row.push(cell);
- if (text[i] === ",") { i++; }
- else if (text[i] === "\r") { i++; if (text[i] === "\n") i++; finishRow(); }
- else if (text[i] === "\n") { i++; finishRow(); }
- } else if (text[i] === "\r") {
- i++;
- if (text[i] === "\n") i++;
- row.push("");
- finishRow();
- } else if (text[i] === "\n") {
- i++;
- row.push("");
- finishRow();
- } else {
- let cell = "";
- while (i < text.length && text[i] !== "," && text[i] !== "\r" && text[i] !== "\n") {
- cell += text[i++];
- }
- row.push(cell);
- if (text[i] === ",") { i++; }
- else if (text[i] === "\r") { i++; if (text[i] === "\n") i++; finishRow(); }
- else if (text[i] === "\n") { i++; finishRow(); }
- }
- }
- if (row.length > 0) rows.push(row);
- return rows;
-}
-
async function importPromptsFromText(text: string, isCsv: boolean): Promise<{ count: number; skipped: number }> {
const entries: PromptEntry[] = [];
let skipped = 0;
diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.ts
index 111510d925d..470fe0cbbe6 100644
--- a/studio/frontend/src/features/chat/types.ts
+++ b/studio/frontend/src/features/chat/types.ts
@@ -78,3 +78,13 @@ export interface MessageRecord {
metadata?: Record<string, unknown>;
createdAt: number;
}
+
+/** One conversation parsed out of an import file, before it is written to storage. */
+export interface ParsedConversation {
+ title: string;
+ threadId: string;
+ messages: MessageRecord[];
+ /** Open WebUI exports carry the flag; other formats leave it unset. */
+ archived?: boolean;
+ createdAt?: number;
+}
diff --git a/studio/frontend/src/features/chat/utils/chat-import.ts b/studio/frontend/src/features/chat/utils/chat-import.ts
new file mode 100644
index 00000000000..6bd76b77f36
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/chat-import.ts
@@ -0,0 +1,436 @@
+// 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 Open WebUI JSON arrays, OpenAI/ShareGPT JSONL, and role/content CSV.
+ * JSON records stream individually so large exports never become one JS string.
+ */
+
+import { notifyChatHistoryUpdated } from "../api/chat-api";
+import type { MessageRecord, ParsedConversation, ThreadRecord } from "../types";
+import {
+ deleteStoredChatThreads,
+ saveStoredChatThread,
+ syncStoredChatMessages,
+} from "./chat-history-storage";
+import { parseCsv } from "./csv-parse";
+import {
+ decodeTextChunks,
+ fileImportSource,
+ readAllText,
+ streamJsonRecords,
+ type ImportSource,
+} from "./json-record-stream";
+import {
+ isOpenWebUIRecord,
+ openWebUIRecordToConversation,
+} from "./openwebui-import";
+
+/** CSV has no record framing to stream on, so it is still read whole. */
+const CSV_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;
+
+/** Limit concurrent writes for exports that may contain thousands of chats. */
+const WRITE_CONCURRENCY = 6;
+
+/**
+ * Report progress at least this often by bytes as well as by conversations. A
+ * count-only cadence leaves the toast reading "0 so far (0%)" for the entire
+ * read of an export made of a few very large chats, which is the case the
+ * progress toast exists for.
+ */
+const PROGRESS_BYTES = 4 * 1024 * 1024;
+
+export interface ImportProgress {
+ /** Conversations written so far. */
+ imported: number;
+ /** Conversations whose write failed; the import continues past them. */
+ failed: number;
+ bytesRead: number;
+ totalBytes?: number;
+}
+
+export interface ImportOptions {
+ onProgress?: (progress: ImportProgress) => void;
+}
+
+export interface ImportResult {
+ imported: number;
+ failed: number;
+}
+
+export { fileImportSource, type ImportSource };
+
+async function* nativeBytes(handle: {
+ name: string;
+ size: number;
+ token: string;
+}): AsyncGenerator<Uint8Array> {
+ const { readNativeChatImportChunk } = await import("@/lib/native-files");
+ let offset = 0;
+ while (offset < handle.size) {
+ const bytes = await readNativeChatImportChunk(
+ handle.token,
+ offset,
+ // Never past the size the picker recorded: bytes appended to a file that
+ // is still being written are not part of the export that was chosen.
+ Math.min(NATIVE_CHUNK_BYTES, handle.size - offset),
+ );
+ // The picker recorded the size, so a short read means the file shrank since
+ // then. Stopping quietly would pass a partial export off as the whole one.
+ if (bytes.byteLength === 0) {
+ throw new Error(
+ `${handle.name} ended after ${offset} of ${handle.size} bytes; it changed after it was picked.`,
+ );
+ }
+ offset += bytes.byteLength;
+ yield bytes;
+ }
+}
+
+/** Desktop: the file stays on disk and is redeemed one range at a time. */
+export function nativeImportSource(handle: {
+ name: string;
+ size: number;
+ token: string;
+}): ImportSource {
+ return {
+ name: handle.name,
+ size: handle.size,
+ // Decoding is fatal here because the native reader it replaced rejected
+ // invalid UTF-8 outright rather than saving a chat full of U+FFFD.
+ chunks: () => decodeTextChunks(nativeBytes(handle), true),
+ };
+}
+
+// Record conversion
+
+// role:"tool" results are absorbed into the preceding assistant tool-call
+// part's `result` field rather than becoming separate records.
+function oaiMessagesToRecords(
+ oaiMsgs: unknown[],
+ threadId: string,
+ baseTs: number,
+): MessageRecord[] {
+ const toolResults = new Map<string, string>();
+ for (const m of oaiMsgs) {
+ const msg = m as Record<string, unknown>;
+ if (msg.role === "tool" && typeof msg.tool_call_id === "string") {
+ toolResults.set(msg.tool_call_id, typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content ?? ""));
+ }
+ }
+
+ const records: MessageRecord[] = [];
+ let prevId: string | null = null;
+ let idx = 0;
+
+ for (const m of oaiMsgs) {
+ const msg = m as Record<string, unknown>;
+ const role = msg.role as string;
+ if (role === "tool") continue;
+
+ const id = crypto.randomUUID();
+
+ let content: unknown[];
+
+ if (role === "assistant") {
+ const parts: unknown[] = [];
+ if (typeof msg.content === "string" && msg.content.trim()) {
+ parts.push({ type: "text", text: msg.content });
+ }
+ if (Array.isArray(msg.tool_calls)) {
+ for (const tc of msg.tool_calls) {
+ const tcObj = tc as Record<string, unknown>;
+ const fn = (tcObj.function as Record<string, unknown>) ?? {};
+ const tcId = typeof tcObj.id === "string" ? tcObj.id : crypto.randomUUID();
+ const name = typeof fn.name === "string" ? fn.name : "unknown";
+ const argsStr = typeof fn.arguments === "string" ? fn.arguments : "{}";
+ let args: unknown = {};
+ try { args = JSON.parse(argsStr); } catch { /* keep empty */ }
+ const result = toolResults.get(tcId);
+ parts.push({
+ type: "tool-call",
+ toolCallId: tcId,
+ toolName: name,
+ args,
+ argsText: argsStr,
+ ...(result !== undefined ? { result } : {}),
+ });
+ }
+ }
+ 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 }] : [];
+ }
+ }
+
+ if (content.length === 0) continue;
+
+ records.push({
+ id,
+ threadId,
+ parentId: prevId,
+ role: role as MessageRecord["role"],
+ content: content as MessageRecord["content"],
+ createdAt: baseTs + idx,
+ });
+ prevId = id;
+ idx++;
+ }
+
+ return records;
+}
+
+function sharegptToRecords(
+ conversations: unknown[],
+ threadId: string,
+ baseTs: number,
+): MessageRecord[] {
+ const records: MessageRecord[] = [];
+ let prevId: string | null = null;
+ let idx = 0;
+ for (const c of conversations) {
+ const conv = c as Record<string, unknown>;
+ const from = typeof conv.from === "string" ? conv.from : "";
+ const value = typeof conv.value === "string" ? conv.value : "";
+ if (!value.trim()) continue;
+ const role: MessageRecord["role"] = from === "human" ? "user" : from === "system" ? "system" : "assistant";
+ const id = crypto.randomUUID();
+ records.push({
+ id,
+ threadId,
+ parentId: prevId,
+ role,
+ content: [{ type: "text", text: value }] as MessageRecord["content"],
+ createdAt: baseTs + idx,
+ });
+ 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);
+ const records: MessageRecord[] = [];
+ let prevId: string | null = null;
+ let idx = 0;
+ for (const row of rows) {
+ if (row.length < 2) continue;
+ const role = row[0]?.trim().toLowerCase();
+ const content = row.slice(1).join(",");
+ if (!content.trim()) continue;
+ const validRole = role === "user" || role === "assistant" || role === "system" ? role : "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,
+ });
+ prevId = id;
+ idx++;
+ }
+ return records;
+}
+
+/** One streamed record -> one conversation, or null when it holds no messages. */
+export function recordToConversation(
+ record: unknown,
+ fallbackTitle: string,
+): ParsedConversation | null {
+ if (isOpenWebUIRecord(record)) {
+ return openWebUIRecordToConversation(record, fallbackTitle);
+ }
+
+ if (typeof record !== "object" || record === null) return null;
+ const obj = record as Record<string, unknown>;
+
+ // Fresh ID: reusing the exported thread_id would clobber an existing
+ // thread on import.
+ const threadId = crypto.randomUUID();
+ const title = typeof obj.title === "string" ? obj.title : fallbackTitle;
+ const baseTs = typeof obj.created_at === "number" ? obj.created_at : Date.now();
+
+ let messages: MessageRecord[] = [];
+ if (Array.isArray(obj.messages)) {
+ messages = oaiMessagesToRecords(obj.messages, threadId, baseTs);
+ } else if (Array.isArray(obj.conversations)) {
+ messages = sharegptToRecords(obj.conversations, threadId, baseTs);
+ }
+
+ if (messages.length === 0) return null;
+ return { title, threadId, messages };
+}
+
+/** Kept for the CSV path and for callers that already hold the whole text. */
+export function parseImportText(
+ text: string,
+ filename: string,
+): ParsedConversation[] {
+ const basename = filename.replace(/\.[^.]+$/, "");
+ if (/\.csv$/i.test(filename)) {
+ const threadId = crypto.randomUUID();
+ const messages = csvToRecords(text, threadId, Date.now());
+ return messages.length > 0 ? [{ title: basename, threadId, messages }] : [];
+ }
+
+ const results: ParsedConversation[] = [];
+ let index = 0;
+ for (const line of text.split(/\r?\n/)) {
+ if (!line.trim()) continue;
+ let record: unknown;
+ try {
+ record = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ const parsed = recordToConversation(record, `${basename} ${index + 1}`);
+ index++;
+ if (parsed) results.push(parsed);
+ }
+ return results;
+}
+
+// Persistence
+
+async function writeConversation(
+ conversation: ParsedConversation,
+ projectId: string | null,
+): Promise<void> {
+ const { title, threadId, messages } = conversation;
+ const thread: ThreadRecord = {
+ id: threadId,
+ title,
+ modelType: "base",
+ projectId: projectId ?? null,
+ archived: conversation.archived ?? false,
+ createdAt: messages[0]?.createdAt ?? conversation.createdAt ?? Date.now(),
+ };
+ await saveStoredChatThread(thread);
+ try {
+ await syncStoredChatMessages(threadId, messages, { pruneMissing: false });
+ } catch (error) {
+ // The thread row is already in the sidebar. Left behind it is a blank chat
+ // the user has to delete by hand, and a retry adds another one.
+ await deleteStoredChatThreads([threadId]).catch(() => {});
+ throw error;
+ }
+}
+
+export async function importConversationsFromSource(
+ source: ImportSource,
+ projectId: string | null = null,
+ options: ImportOptions = {},
+): Promise<ImportResult> {
+ const basename = source.name.replace(/\.[^.]+$/, "");
+ const progress: ImportProgress = {
+ imported: 0,
+ failed: 0,
+ bytesRead: 0,
+ totalBytes: source.size,
+ };
+ const report = () => options.onProgress?.({ ...progress });
+
+ if (/\.csv$/i.test(source.name)) {
+ const text = await readAllText(source, CSV_MAX_BYTES, "CSV");
+ for (const conversation of parseImportText(text, source.name)) {
+ await writeConversation(conversation, projectId);
+ progress.imported++;
+ }
+ if (progress.imported > 0) notifyChatHistoryUpdated();
+ report();
+ return { imported: progress.imported, failed: progress.failed };
+ }
+
+ const inFlight = new Set<Promise<void>>();
+ let index = 0;
+ let failure: unknown;
+ let reportedBytes = 0;
+
+ try {
+ for await (const record of streamJsonRecords(source.chunks(), {
+ onBytes: (bytes) => {
+ progress.bytesRead += bytes;
+ if (progress.bytesRead - reportedBytes >= PROGRESS_BYTES) {
+ reportedBytes = progress.bytesRead;
+ report();
+ }
+ },
+ // Count a malformed record and continue with the rest of the export.
+ onMalformed: () => {
+ progress.failed++;
+ },
+ })) {
+ const conversation = recordToConversation(record, `${basename} ${index + 1}`);
+ index++;
+ if (!conversation) continue;
+
+ const task = writeConversation(conversation, projectId)
+ .then(() => {
+ progress.imported++;
+ })
+ .catch(() => {
+ // Keep importing after one conversation fails to save.
+ progress.failed++;
+ })
+ .finally(() => {
+ inFlight.delete(task);
+ if ((progress.imported + progress.failed) % 25 === 0) report();
+ });
+ inFlight.add(task);
+ if (inFlight.size >= WRITE_CONCURRENCY) await Promise.race(inFlight);
+ }
+ } catch (error) {
+ // A read that dies partway still leaves earlier chats saved.
+ failure = error;
+ }
+
+ 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.
+ if (progress.imported > 0) notifyChatHistoryUpdated();
+ report();
+
+ if (failure !== undefined) {
+ const reason = failure instanceof Error ? failure.message : String(failure);
+ throw new Error(
+ progress.imported > 0
+ ? `${reason} ${progress.imported} conversation${progress.imported === 1 ? " was" : "s were"} imported before it stopped.`
+ : reason,
+ );
+ }
+ return { imported: progress.imported, failed: progress.failed };
+}
+
+export async function importConversationsFromFile(
+ file: File,
+ projectId: string | null = null,
+ options: ImportOptions = {},
+): Promise<ImportResult> {
+ return importConversationsFromSource(
+ fileImportSource(file),
+ projectId,
+ options,
+ );
+}
diff --git a/studio/frontend/src/features/chat/utils/csv-parse.ts b/studio/frontend/src/features/chat/utils/csv-parse.ts
new file mode 100644
index 00000000000..dc9f59162f5
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/csv-parse.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// RFC 4180 CSV parser: handles quoted fields with embedded newlines/commas.
+export function parseCsv(text: string): string[][] {
+ const rows: string[][] = [];
+ let row: string[] = [];
+ let i = 0;
+
+ function finishRow() {
+ rows.push(row);
+ row = [];
+ }
+
+ while (i < text.length) {
+ if (text[i] === '"') {
+ i++;
+ let cell = "";
+ while (i < text.length) {
+ if (text[i] === '"') {
+ if (text[i + 1] === '"') {
+ cell += '"';
+ i += 2;
+ } else {
+ i++;
+ break;
+ }
+ } else {
+ cell += text[i++];
+ }
+ }
+ row.push(cell);
+ if (text[i] === ",") { i++; }
+ else if (text[i] === "\r") { i++; if (text[i] === "\n") i++; finishRow(); }
+ else if (text[i] === "\n") { i++; finishRow(); }
+ } else if (text[i] === "\r") {
+ i++;
+ if (text[i] === "\n") i++;
+ row.push("");
+ finishRow();
+ } else if (text[i] === "\n") {
+ i++;
+ row.push("");
+ finishRow();
+ } else {
+ let cell = "";
+ while (i < text.length && text[i] !== "," && text[i] !== "\r" && text[i] !== "\n") {
+ cell += text[i++];
+ }
+ row.push(cell);
+ if (text[i] === ",") { i++; }
+ else if (text[i] === "\r") { i++; if (text[i] === "\n") i++; finishRow(); }
+ else if (text[i] === "\n") { i++; finishRow(); }
+ }
+ }
+ if (row.length > 0) rows.push(row);
+ return rows;
+}
diff --git a/studio/frontend/src/features/chat/utils/json-record-stream.ts b/studio/frontend/src/features/chat/utils/json-record-stream.ts
new file mode 100644
index 00000000000..1f4e645a8e1
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/json-record-stream.ts
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Text arriving from a file, with the byte count that produced it. */
+export interface TextChunk {
+ text: string;
+ bytes: number;
+}
+
+/** A browser or desktop source that can be read incrementally. */
+export interface ImportSource {
+ name: string;
+ size?: number;
+ /** Decoded text and its source byte count for progress reporting. */
+ chunks(): AsyncIterable<TextChunk>;
+}
+
+/**
+ * Decode byte ranges into text. `fatal` rejects invalid UTF-8 instead of
+ * substituting replacement characters, which the desktop path requires.
+ */
+export async function* decodeTextChunks(
+ byteChunks: AsyncIterable<Uint8Array>,
+ fatal = false,
+): AsyncGenerator<TextChunk> {
+ const decoder = new TextDecoder("utf-8", { fatal });
+ for await (const bytes of byteChunks) {
+ if (!bytes.byteLength) continue;
+ // Preserve UTF-8 characters split across chunks.
+ yield { text: decoder.decode(bytes, { stream: true }), bytes: bytes.byteLength };
+ }
+ const tail = decoder.decode();
+ if (tail) yield { text: tail, bytes: 0 };
+}
+
+async function* fileBytes(file: File): AsyncGenerator<Uint8Array> {
+ const reader = file.stream().getReader();
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value) yield value;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+export function fileImportSource(file: File): ImportSource {
+ return {
+ name: file.name,
+ size: file.size,
+ // Browser imports stay lenient about invalid UTF-8, as `file.text()` was.
+ chunks: () => decodeTextChunks(fileBytes(file)),
+ };
+}
+
+/**
+ * Read a whole source. The bound is the bytes read, not the length of the
+ * decoded string: multibyte text is longer in bytes than in UTF-16 units.
+ */
+export async function readAllText(
+ source: ImportSource,
+ maxBytes: number,
+ format: string,
+): Promise<string> {
+ let text = "";
+ let bytes = 0;
+ for await (const chunk of source.chunks()) {
+ text += chunk.text;
+ bytes += chunk.bytes;
+ if (bytes > maxBytes) {
+ throw new Error(
+ `${source.name} is too large to import as ${format} (maximum ${Math.floor(maxBytes / 1024 / 1024)} MiB).`,
+ );
+ }
+ }
+ return text;
+}
+
+/**
+ * Stream top-level records from a JSON array or JSONL/NDJSON, including
+ * records formatted across multiple lines.
+ */
+export interface StreamJsonOptions {
+ onBytes?: (bytes: number) => void;
+ /** A framed record that does not parse. The stream continues past it. */
+ onMalformed?: (text: string) => void;
+}
+
+interface Salvage {
+ records: unknown[];
+ damaged: string[];
+}
+
+/** A line-leading `{`/`[` that follows a finished value: the next record. */
+const NEW_RECORD_LINE = /[^\s:,[{]\s*\n[[{]/;
+
+/**
+ * Recover records after an unclosed JSONL row. Until line framing is proven,
+ * only unindented object or array lines qualify as record boundaries.
+ */
+function salvageLines(region: string, proven: boolean): Salvage {
+ const records: unknown[] = [];
+ const damaged: string[] = [];
+ for (const line of region.split("\n")) {
+ const text = line.trim();
+ if (!text) continue;
+ if (!proven && (/^\s/.test(line) || !/^[[{]/.test(text))) {
+ damaged.push(text);
+ continue;
+ }
+ try {
+ records.push(JSON.parse(text));
+ } catch {
+ damaged.push(text);
+ }
+ }
+ return { records, damaged };
+}
+
+export async function* streamJsonRecords(
+ chunks: AsyncIterable<TextChunk>,
+ options: StreamJsonOptions = {},
+): AsyncGenerator<unknown> {
+ const QUOTE = 34; // "
+ const BACKSLASH = 92; // \
+ const OPEN_BRACE = 123; // {
+ const CLOSE_BRACE = 125; // }
+ const OPEN_BRACKET = 91; // [
+ const CLOSE_BRACKET = 93; // ]
+ const SPACE = 32;
+ const TAB = 9;
+ const NEWLINE = 10;
+ const RETURN = 13;
+
+ let buffer = "";
+ let scan = 0;
+ let start = -1;
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+ let sawArrayStart = false;
+ let sawArrayEnd = false;
+ // True while every emitted record has occupied one line.
+ let emittedRecord = false;
+ let lineFramed = false;
+
+ for await (const chunk of chunks) {
+ options.onBytes?.(chunk.bytes);
+ // Retain only the record still being read.
+ const consumed = start >= 0 ? start : scan;
+ try {
+ buffer = consumed > 0 ? buffer.slice(consumed) + chunk.text : buffer + chunk.text;
+ } catch (error) {
+ // Records are dropped from the buffer as they are emitted, so the only way
+ // to reach the engine's maximum string length is ONE record that long.
+ // Untranslated, that surfaces as a bare "Invalid string length".
+ if (error instanceof RangeError) {
+ throw new RangeError(
+ "One chat in this export is too large to read in a single piece. " +
+ "Split the export and import the pieces separately.",
+ );
+ }
+ throw error;
+ }
+ scan -= consumed;
+ if (start >= 0) start = 0;
+
+ // Recovery can replace the buffer and request another scan.
+ let rescan = true;
+ while (rescan) {
+ rescan = false;
+
+ while (scan < buffer.length) {
+ const code = buffer.charCodeAt(scan);
+
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (code === BACKSLASH) escaped = true;
+ else if (code === QUOTE) inString = false;
+ scan++;
+ continue;
+ }
+
+ if (start < 0) {
+ // Past the array's own close, only whitespace belongs to the file. A
+ // record after it means this is not the single export it claims to
+ // be, and importing it would take in data from who knows where.
+ if (sawArrayEnd) {
+ if (code !== SPACE && code !== TAB && code !== NEWLINE && code !== RETURN) {
+ throw new SyntaxError(
+ "The export continues after its closing bracket, so it is not one JSON array.",
+ );
+ }
+ scan++;
+ continue;
+ }
+ // Between records: the array's own brackets, separators and whitespace.
+ if (code === OPEN_BRACKET && !sawArrayStart) {
+ sawArrayStart = true;
+ scan++;
+ continue;
+ }
+ if (code !== OPEN_BRACE && code !== OPEN_BRACKET) {
+ // The array's own closing bracket: the file is complete from here on.
+ if (code === CLOSE_BRACKET && sawArrayStart) sawArrayEnd = true;
+ // Commas, newlines, and any stray scalar between records: nothing to import.
+ scan++;
+ continue;
+ }
+ start = scan;
+ depth = 0;
+ }
+
+ if (code === QUOTE) inString = true;
+ else if (code === OPEN_BRACE || code === OPEN_BRACKET) depth++;
+ else if (code === CLOSE_BRACE || code === CLOSE_BRACKET) depth--;
+ scan++;
+
+ if (depth === 0) {
+ const text = buffer.slice(start, scan);
+ start = -1;
+ // Framing is intact, so a parse failure affects only this record.
+ let record: unknown;
+ try {
+ record = JSON.parse(text);
+ } catch {
+ options.onMalformed?.(text);
+ continue;
+ }
+ lineFramed = emittedRecord
+ ? lineFramed && !text.includes("\n")
+ : !text.includes("\n");
+ emittedRecord = true;
+ yield record;
+ }
+ }
+
+ // A pending record is damaged once a later line starts a record of its
+ // own. That is a line-leading `{` or `[` which JSON could not continue
+ // the pending text with: after a finished value another value is a new
+ // record, while after `:` `,` `[` `{` it is this record's own nesting.
+ // Deciding it that way keeps the outcome independent of where the chunk
+ // boundary fell, and recovering here rather than only at end of input
+ // keeps a file whose first row is broken from buffering whole.
+ if (!sawArrayStart && start >= 0) {
+ const lastNewline = buffer.lastIndexOf("\n");
+ const boundary =
+ lastNewline > start ? NEW_RECORD_LINE.exec(buffer.slice(start, lastNewline)) : null;
+ if (boundary) {
+ // Only the text before the boundary is damaged. The scanner resumes
+ // from the boundary itself, so a pretty-printed record after a broken
+ // row is framed by its nesting rather than shredded into lines.
+ const at = start + boundary.index + boundary[0].length - 1;
+ const damaged = buffer.slice(start, at).trim();
+ if (damaged) options.onMalformed?.(damaged);
+ buffer = buffer.slice(at);
+ scan = 0;
+ start = -1;
+ depth = 0;
+ inString = false;
+ escaped = false;
+ rescan = true;
+ }
+ }
+ }
+ }
+
+ const tail = start >= 0 ? buffer.slice(start).trim() : "";
+ if (tail) {
+ if (sawArrayStart) {
+ // Arrays have no line boundary on which to recover a truncated record.
+ // The failure is the same one the closing-bracket check below reports, so
+ // it says so in the same words rather than surfacing the engine's own
+ // "Unterminated string in JSON at position ..." to the user.
+ let record: unknown;
+ try {
+ record = JSON.parse(tail);
+ } catch {
+ throw new SyntaxError(
+ "The JSON array ends in the middle of a record, so the export is incomplete.",
+ );
+ }
+ yield record;
+ } else {
+ // Recover complete JSONL rows after a broken one.
+ const salvaged = salvageLines(tail, lineFramed);
+ if (salvaged.records.length === 0) {
+ // Report one truncated record instead of each of its lines.
+ options.onMalformed?.(tail);
+ } else {
+ for (const text of salvaged.damaged) options.onMalformed?.(text);
+ yield* salvaged.records;
+ }
+ }
+ }
+
+ // A download cut between two records leaves every record read so far intact,
+ // so the missing bracket is the only sign that the rest never arrived.
+ if (sawArrayStart && !sawArrayEnd) {
+ throw new SyntaxError(
+ "The JSON array ends before its closing bracket, so the export is incomplete.",
+ );
+ }
+}
diff --git a/studio/frontend/src/features/chat/utils/openwebui-import.ts b/studio/frontend/src/features/chat/utils/openwebui-import.ts
new file mode 100644
index 00000000000..ecc0c7890a6
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/openwebui-import.ts
@@ -0,0 +1,687 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Converts Open WebUI exports to Studio conversations. `history.messages` is
+ * the authoritative DAG and `currentId` selects its active branch; flat
+ * `messages` is a legacy fallback. Both modern output items and legacy details
+ * blocks are converted to Studio message parts.
+ */
+
+import type { MessageRecord, ParsedConversation } from "../types";
+
+type Dict = Record<string, unknown>;
+
+interface Node {
+ id: string;
+ parentId: string | null;
+ raw: Dict;
+}
+
+/** A cyclic parent chain would otherwise spin forever; no real chat is deeper. */
+const MAX_MESSAGES_PER_CHAT = 200_000;
+
+function isDict(value: unknown): value is Dict {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function str(value: unknown): string | null {
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+
+/** The largest instant `Date` accepts; past it every stamp renders "Invalid Date". */
+const MAX_EPOCH_MS = 8.64e15;
+
+/** Open WebUI stores seconds on the record and milliseconds on `chat.timestamp`. */
+function epochMs(value: unknown): number | null {
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
+ return null;
+ }
+ const ms = value < 1e12 ? Math.round(value * 1000) : Math.round(value);
+ // An out-of-range stamp (nanoseconds mistaken for milliseconds, say) has to be
+ // discarded rather than carried: past 2^53 `previousTs + 1` stops advancing, so
+ // every later message collapses onto one createdAt and the depth-first order
+ // below no longer survives the reload it exists to survive.
+ return ms > MAX_EPOCH_MS ? null : ms;
+}
+
+/** The chat blob: under `chat` on an exported record, or the record itself on a legacy bare chat. */
+function chatBlob(record: unknown): Dict | null {
+ if (!isDict(record)) return null;
+ if (isDict(record.chat)) return record.chat;
+ return record;
+}
+
+/** Distinguish Open WebUI turns from plain OpenAI role/content messages. */
+function looksLikeOpenWebUIMessage(value: unknown): boolean {
+ if (!isDict(value)) return false;
+ if (typeof value.role !== "string") return false;
+ return (
+ "parentId" in value ||
+ "childrenIds" in value ||
+ "modelName" in value ||
+ "modelIdx" in value ||
+ "done" in value ||
+ "output" in value ||
+ // A timestamp alone is generic enough for an OpenAI JSONL conversation to
+ // carry one; alongside a message id it is Open WebUI's own shape.
+ ("timestamp" in value && typeof value.id === "string")
+ );
+}
+
+/** A Chat Completions tool turn: the OpenAI JSONL format we already import. */
+function looksLikeOpenAIToolMessage(value: unknown): boolean {
+ if (!isDict(value)) return false;
+ return value.role === "tool" || "tool_calls" in value || "tool_call_id" in value;
+}
+
+export function isOpenWebUIRecord(value: unknown): boolean {
+ if (!isDict(value)) return false;
+ // The wrapper is unambiguous: nothing else we import nests a chat blob.
+ if (isDict(value.chat)) {
+ const chat = value.chat;
+ return (
+ isDict(chat.history) || Array.isArray(chat.messages) || "models" in chat
+ );
+ }
+ const blob = chatBlob(value);
+ if (!blob) return false;
+ if (isDict(blob.history) && isDict(blob.history.messages)) return true;
+ if (!Array.isArray(blob.messages)) return false;
+ // One tool turn settles it: Open WebUI keeps tool calls in the message body,
+ // never as sibling Chat Completions turns.
+ if (blob.messages.some(looksLikeOpenAIToolMessage)) return false;
+ return blob.messages.some(looksLikeOpenWebUIMessage);
+}
+
+// Content
+
+// A closed fence first, then an opener that never closed: an answer cut off
+// inside a code block still quotes code, not an Open WebUI construct. The
+// unclosed form is anchored to the start of a line, which is where markdown
+// requires a block fence to begin. Unanchored, a single stray ``` mid-sentence
+// swallowed the whole rest of the message, so every tool call after it was
+// rendered as literal markup and lost.
+const FENCED_CODE =
+ /```[\s\S]*?```|~~~[\s\S]*?~~~|(?:^|\n)[ \t]{0,3}(?:```|~~~)[\s\S]*$/g;
+const DETAILS_BLOCK = /<details\b([^>]*)>([\s\S]*?)<\/details>/gi;
+const ATTRIBUTE = /([\w-]+)="([^"]*)"/g;
+
+/** `&#39;` and `&#x27;` are both an apostrophe, and exports carry either. */
+function numericEntity(digits: string, radix: number): string | null {
+ const code = Number.parseInt(digits, radix);
+ if (!Number.isFinite(code) || code < 0 || code > 0x10ffff) return null;
+ // Lone surrogates are not code points `fromCodePoint` accepts.
+ if (code >= 0xd800 && code <= 0xdfff) return null;
+ return String.fromCodePoint(code);
+}
+
+function unescapeHtml(value: string): string {
+ return value
+ // Numeric escapes first, and `&amp;` last, so a doubly-escaped `&amp;#39;`
+ // survives one pass as the literal text `&#39;` rather than an apostrophe.
+ .replace(/&#x([0-9a-f]+);/gi, (whole, hex: string) => numericEntity(hex, 16) ?? whole)
+ .replace(/&#(\d+);/g, (whole, dec: string) => numericEntity(dec, 10) ?? whole)
+ .replace(/&lt;/g, "<")
+ .replace(/&gt;/g, ">")
+ .replace(/&quot;/g, '"')
+ .replace(/&amp;/g, "&");
+}
+
+function detailsAttributes(rawAttributes: string): Record<string, string> {
+ const attributes: Record<string, string> = {};
+ ATTRIBUTE.lastIndex = 0;
+ let match = ATTRIBUTE.exec(rawAttributes);
+ while (match !== null) {
+ attributes[match[1]] = unescapeHtml(match[2]);
+ match = ATTRIBUTE.exec(rawAttributes);
+ }
+ return attributes;
+}
+
+function parseJsonLoose(value: string | undefined): unknown {
+ if (!value) return {};
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+}
+
+/**
+ * `args` is typed as an object on a tool-call part, and the renderer indexes it.
+ * A malformed `arguments` attribute parses loosely to a bare string, so the raw
+ * text is kept where a reader can still see it instead of being passed off as
+ * a structured argument object.
+ */
+function toolArgs(value: unknown): Dict {
+ if (isDict(value)) return value;
+ if (typeof value === "string" && value) return { arguments: value };
+ return {};
+}
+
+/** Body text of a `<details>`, minus its `<summary>`. */
+function detailsBody(body: string, stripQuoteMarkers = false): string {
+ const withoutSummary = body.replace(/<summary>[\s\S]*?<\/summary>/i, "");
+ if (!stripQuoteMarkers) return withoutSummary.trim();
+ // Open WebUI writes reasoning as a blockquote; a tool result keeps its own lines.
+ return withoutSummary
+ .split("\n")
+ .map((line) => line.replace(/^\s*>\s?/, ""))
+ .join("\n")
+ .trim();
+}
+
+function pushText(parts: unknown[], text: string): void {
+ const trimmed = text.trim();
+ if (!trimmed) return;
+ const last = parts.at(-1) as Dict | undefined;
+ // Text either side of a details block belongs to one bubble, not two.
+ if (last && last.type === "text") {
+ last.text = `${last.text as string}\n\n${trimmed}`;
+ return;
+ }
+ parts.push({ type: "text", text: trimmed });
+}
+
+/** Byte ranges of fenced code in `content`, as [start, end) pairs. */
+function fencedRanges(content: string): Array<[number, number]> {
+ const ranges: Array<[number, number]> = [];
+ FENCED_CODE.lastIndex = 0;
+ let match = FENCED_CODE.exec(content);
+ while (match !== null) {
+ ranges.push([match.index, match.index + match[0].length]);
+ match = FENCED_CODE.exec(content);
+ }
+ return ranges;
+}
+
+/**
+ * Convert details blocks while preserving blocks quoted inside code fences.
+ * A real tool result may itself contain fenced code.
+ */
+function contentWithDetailsToParts(content: string): unknown[] {
+ const parts: unknown[] = [];
+ const fences = fencedRanges(content);
+ const quotedInFence = (start: number, end: number) =>
+ fences.some(([from, to]) => start >= from && end <= to);
+
+ let cursor = 0;
+ DETAILS_BLOCK.lastIndex = 0;
+ let match = DETAILS_BLOCK.exec(content);
+ while (match !== null) {
+ const start = match.index;
+ const end = start + match[0].length;
+ if (quotedInFence(start, end)) {
+ match = DETAILS_BLOCK.exec(content);
+ continue;
+ }
+
+ pushText(parts, content.slice(cursor, start));
+ cursor = end;
+
+ const attributes = detailsAttributes(match[1]);
+ const body = detailsBody(match[2], attributes.type === "reasoning");
+ if (attributes.type === undefined) {
+ // A plain <details> the model wrote is formatting, not an Open WebUI
+ // construct, so it keeps its markup.
+ pushText(parts, match[0]);
+ } else if (attributes.type === "tool_calls") {
+ const result =
+ attributes.result !== undefined ? parseJsonLoose(attributes.result) : body || undefined;
+ parts.push({
+ type: "tool-call",
+ toolCallId: attributes.id || crypto.randomUUID(),
+ toolName: attributes.name || "unknown",
+ args: toolArgs(parseJsonLoose(attributes.arguments)),
+ ...(result !== undefined ? { result } : {}),
+ });
+ } else if (attributes.type === "reasoning") {
+ if (body) parts.push({ type: "reasoning", text: body });
+ } else if (body) {
+ // code_interpreter and any future block: keep the text, drop the markup.
+ pushText(parts, body);
+ }
+
+ match = DETAILS_BLOCK.exec(content);
+ }
+ pushText(parts, content.slice(cursor));
+
+ return parts;
+}
+
+/** Addressable outside Open WebUI: inline data or an absolute url. */
+const PORTABLE_IMAGE = /^(?:https?:|data:)/i;
+
+/** The three names a Responses content part uses for its text. */
+const TEXT_PART_TYPES = new Set(["input_text", "output_text", "text"]);
+
+/** The text of a Responses reasoning source (`summary` or `content`). */
+function reasoningText(source: unknown): string {
+ if (!Array.isArray(source)) return "";
+ return source
+ .map((part) => (isDict(part) && typeof part.text === "string" ? part.text : ""))
+ .join("")
+ .trim();
+}
+
+/** Built-ins studio names differently from the Responses item they arrive in. */
+const BUILTIN_TOOL_NAMES: Record<string, string> = { shell: "code_execution" };
+
+/** Modern assistant turns: Responses-API items stored on `message.output`. */
+function outputItemsToParts(output: unknown[]): { parts: unknown[]; sawMessage: boolean } {
+ const parts: unknown[] = [];
+ const toolCallIndex = new Map<string, Dict>();
+ // Whether an output message item carried the assistant's own answer.
+ let sawMessage = false;
+
+ for (const item of output) {
+ if (!isDict(item)) continue;
+
+ if (item.type === "reasoning") {
+ // `summary` is an empty array whenever summaries are off, so the source
+ // is whichever of the two actually holds text rather than whichever the
+ // item happens to carry.
+ const summary = reasoningText(item.summary);
+ const text = summary || reasoningText(item.content);
+ if (text) parts.push({ type: "reasoning", text });
+ continue;
+ }
+
+ if (item.type === "message") {
+ const content = Array.isArray(item.content) ? item.content : [];
+ const text = content
+ .map((part) =>
+ isDict(part) && part.type === "output_text" && typeof part.text === "string"
+ ? part.text
+ : "",
+ )
+ .join("");
+ if (text.trim()) sawMessage = true;
+ pushText(parts, text);
+ continue;
+ }
+
+ if (item.type === "image_generation_call") {
+ // The item carries the generated image itself as base64. The call id is
+ // an OpenAI session reference that means nothing outside the export, so
+ // only the image comes over.
+ const encoded = str(item.result) ?? str(item.b64_json);
+ if (encoded) {
+ const format = str(item.output_format) ?? "png";
+ // A url is already addressable. Wrapping one in a base64 data url makes
+ // a permanently broken image out of something that might have rendered.
+ parts.push({
+ type: "image",
+ image: PORTABLE_IMAGE.test(encoded) ? encoded : `data:image/${format};base64,${encoded}`,
+ });
+ }
+ continue;
+ }
+
+ if (item.type === "function_call") {
+ const callId = str(item.call_id) ?? crypto.randomUUID();
+ const part: Dict = {
+ type: "tool-call",
+ toolCallId: callId,
+ toolName: str(item.name) ?? "unknown",
+ args: toolArgs(
+ parseJsonLoose(typeof item.arguments === "string" ? item.arguments : undefined),
+ ),
+ };
+ if (isDict(item.arguments)) {
+ part.args = item.arguments;
+ }
+ toolCallIndex.set(callId, part);
+ parts.push(part);
+ continue;
+ }
+
+ // Built-in Responses tools (`web_search_call`, `shell_call`, ...) follow the
+ // same `<tool>_call` / `<tool>_call_output` pair as a function call, so they
+ // become the same portable tool part rather than being dropped.
+ const builtin = typeof item.type === "string" ? /^(\w+)_call$/.exec(item.type) : null;
+ if (builtin) {
+ const callId = str(item.call_id) ?? str(item.id) ?? crypto.randomUUID();
+ const part: Dict = {
+ type: "tool-call",
+ toolCallId: callId,
+ toolName: BUILTIN_TOOL_NAMES[builtin[1]] ?? builtin[1],
+ args: isDict(item.action) ? item.action : {},
+ };
+ toolCallIndex.set(callId, part);
+ parts.push(part);
+ continue;
+ }
+
+ if (typeof item.type === "string" && item.type.endsWith("_call_output")) {
+ const callId = str(item.call_id);
+ // `output` is a plain string for most tools and a content array only when
+ // the tool returned images or files.
+ const outputParts = Array.isArray(item.output) ? item.output : [];
+ let resultText = typeof item.output === "string" ? item.output : "";
+ const images: string[] = [];
+ for (const part of outputParts) {
+ if (!isDict(part)) continue;
+ // The backend normalizer accepts all three names for tool result text.
+ if (TEXT_PART_TYPES.has(part.type as string) && typeof part.text === "string") {
+ resultText += part.text;
+ } else if (part.type === "input_image") {
+ const url = str(part.image_url);
+ if (url) images.push(url);
+ }
+ }
+ const target = callId ? toolCallIndex.get(callId) : undefined;
+ if (target) {
+ // A tool that returned only images has no result text, and its images
+ // are pushed as their own parts below. ToolFallbackResult renders
+ // nothing at all for an undefined result but draws a "Result:" heading
+ // over an empty block for "", which reads as "it returned nothing".
+ if (resultText) target.result = resultText;
+ } else if (resultText.trim()) {
+ pushText(parts, resultText);
+ }
+ // A tool that returned images: keep them as image parts so they still
+ // render. A bare `/api/v1/files/<id>` is dead outside Open WebUI, but an
+ // absolute url resolves anywhere the chat is opened.
+ for (const image of images) {
+ if (PORTABLE_IMAGE.test(image)) parts.push({ type: "image", image });
+ }
+ }
+ }
+
+ return { parts, sawMessage };
+}
+
+/**
+ * Keep inline images. Keep document names without extracted text, which would
+ * otherwise be resent to the model on the next turn.
+ */
+function filesToParts(files: unknown): { parts: unknown[]; attachments: unknown[] } {
+ const parts: unknown[] = [];
+ const attachments: unknown[] = [];
+ if (!Array.isArray(files)) return { parts, attachments };
+
+ for (const file of files) {
+ if (!isDict(file)) continue;
+ const url = str(file.url);
+ if (file.type === "image") {
+ // A bare `/api/v1/files/<id>` url is dead outside Open WebUI; only inline data survives.
+ if (url?.startsWith("data:")) parts.push({ type: "image", image: url });
+ continue;
+ }
+ const name = str(file.name) ?? str((isDict(file.file) ? file.file.filename : null)) ?? "file";
+ attachments.push({
+ id: str(file.id) ?? crypto.randomUUID(),
+ type: "document",
+ name,
+ contentType: str(file.content_type) ?? "application/octet-stream",
+ content: [],
+ status: { type: "complete" },
+ });
+ }
+
+ return { parts, attachments };
+}
+
+/**
+ * Chat Completions multimodal content: `[{type:"text"}, {type:"image_url"}]`.
+ * Detection cannot be perfect, so a record that lands here carrying the OpenAI
+ * array shape has to keep its turns rather than lose them: reading only string
+ * `content` dropped the whole message.
+ */
+function arrayContentToParts(raw: unknown[]): unknown[] {
+ return raw.flatMap((entry): unknown[] => {
+ if (!isDict(entry)) return [];
+ if (entry.type === "text" && typeof entry.text === "string") {
+ return entry.text.trim() ? [{ type: "text", text: entry.text }] : [];
+ }
+ if (entry.type === "image_url") {
+ const url = str((isDict(entry.image_url) ? entry.image_url.url : null));
+ return url ? [{ type: "image", image: url }] : [];
+ }
+ return [];
+ });
+}
+
+function messageParts(
+ message: Dict,
+ role: MessageRecord["role"],
+): { content: unknown[]; attachments: unknown[] } {
+ const parts: unknown[] = [];
+ let sawMessage = false;
+
+ if (Array.isArray(message.output)) {
+ const converted = outputItemsToParts(message.output);
+ parts.push(...converted.parts);
+ sawMessage = converted.sawMessage;
+ }
+
+ if (!sawMessage && Array.isArray(message.content)) {
+ parts.push(...arrayContentToParts(message.content));
+ }
+
+ const content = typeof message.content === "string" ? message.content : "";
+ // `content` mirrors the answer an output message item already carries, so it
+ // is used whenever no such item produced text. A tool result left over from
+ // an earlier turn is not that answer.
+ if (content && !sawMessage) {
+ // Open WebUI writes those details blocks into its own assistant output. The
+ // same markup in a prompt is text the user typed, not reasoning or a call.
+ if (role === "assistant") parts.push(...contentWithDetailsToParts(content));
+ // Literal prompt text: leading whitespace can be a markdown code block.
+ else if (content.trim()) parts.push({ type: "text", text: content });
+ }
+
+ const { parts: fileParts, attachments } = filesToParts(message.files);
+ parts.push(...fileParts);
+
+ return { content: parts, attachments };
+}
+
+// Message graph
+
+/** Message ids from `currentId` back to the root: the branch the user had open. */
+function activePath(byId: Map<string, Node>, currentId: unknown): Set<string> {
+ const path = new Set<string>();
+ let cursor = str(currentId);
+ while (cursor) {
+ if (path.has(cursor)) break; // cycle
+ const node = byId.get(cursor);
+ if (!node) break;
+ path.add(cursor);
+ cursor = node.parentId;
+ }
+ return path;
+}
+
+function collectNodes(chat: Dict): Node[] {
+ const history = isDict(chat.history) ? chat.history : null;
+ const historyMessages = history && isDict(history.messages) ? history.messages : null;
+
+ const byId = new Map<string, Node>();
+ for (const [id, raw] of Object.entries(historyMessages ?? {})) {
+ if (!isDict(raw)) continue;
+ byId.set(id, { id, parentId: str(raw.parentId), raw });
+ }
+
+ // An empty or unusable DAG is damage like a missing one: the flat branch is
+ // then the only copy of the conversation left.
+ if (byId.size === 0) {
+ // No DAG: the flat active branch is all that survived.
+ const flat = Array.isArray(chat.messages) ? chat.messages : [];
+ const nodes: Node[] = [];
+ const seen = new Set<string>();
+ let previousId: string | null = null;
+ for (const raw of flat) {
+ if (!isDict(raw)) continue;
+ if (nodes.length >= MAX_MESSAGES_PER_CHAT) break;
+ const id = str(raw.id) ?? crypto.randomUUID();
+ if (seen.has(id)) continue; // duplicate ids after a bad merge
+ seen.add(id);
+ nodes.push({ id, parentId: previousId, raw });
+ previousId = id;
+ }
+ return nodes;
+ }
+
+ // Re-derive children from parentId: `childrenIds` goes stale on edits, and an
+ // orphan parent (deleted message) has to fall back to being a root.
+ const children = new Map<string, Node[]>();
+ const roots: Node[] = [];
+ for (const node of byId.values()) {
+ const parent = node.parentId ? byId.get(node.parentId) : undefined;
+ if (!parent || parent.id === node.id) {
+ node.parentId = null;
+ roots.push(node);
+ continue;
+ }
+ const siblings = children.get(parent.id);
+ if (siblings) siblings.push(node);
+ else children.set(parent.id, [node]);
+ }
+
+ const path = activePath(byId, history?.currentId);
+ const ordered: Node[] = [];
+ const visited = new Set<string>();
+
+ // Depth-first, active branch last: studio restores the head from the final
+ // message, so the branch the user had open is the one that opens here too.
+ // The traversal is iterative because a long chat is a chain thousands of
+ // messages deep, which overflows the call stack long before the cap above.
+ const walk = (root: Node): void => {
+ const stack: Node[] = [root];
+ while (stack.length > 0) {
+ const node = stack.pop() as Node;
+ if (visited.has(node.id)) continue;
+ if (ordered.length >= MAX_MESSAGES_PER_CHAT) return;
+ visited.add(node.id);
+ ordered.push(node);
+ const kids = children.get(node.id) ?? [];
+ const rest = kids.filter((kid) => !path.has(kid.id));
+ const active = kids.filter((kid) => path.has(kid.id));
+ // Pushed back to front, so they pop in that same order.
+ for (let index = active.length - 1; index >= 0; index--) stack.push(active[index]);
+ for (let index = rest.length - 1; index >= 0; index--) stack.push(rest[index]);
+ }
+ };
+
+ // What the roots can reach, before emitting any of it: the rest is trapped in
+ // a cycle and has to be walked between the other branches and the selected
+ // one, so the selected branch is still the last message studio reopens on.
+ const reachable = new Set<string>();
+ const pending = [...roots];
+ while (pending.length > 0) {
+ const node = pending.pop() as Node;
+ if (reachable.has(node.id)) continue;
+ reachable.add(node.id);
+ for (const kid of children.get(node.id) ?? []) pending.push(kid);
+ }
+
+ const rootRest = roots.filter((node) => !path.has(node.id));
+ const rootActive = roots.filter((node) => path.has(node.id));
+ for (const node of rootRest) walk(node);
+ for (const node of byId.values()) {
+ if (!reachable.has(node.id) && !visited.has(node.id)) walk(node);
+ }
+ for (const node of rootActive) walk(node);
+ // A selected branch trapped in a cycle has no root to have been walked from.
+ for (const node of byId.values()) {
+ if (!visited.has(node.id)) walk(node);
+ }
+
+ return ordered;
+}
+
+/** A legacy chat can carry per-message times and no chat-level date at all. */
+function earliestTimestamp(nodes: Node[]): number | null {
+ let earliest: number | null = null;
+ for (const node of nodes) {
+ const ts = epochMs(node.raw.timestamp);
+ if (ts !== null && (earliest === null || ts < earliest)) earliest = ts;
+ }
+ return earliest;
+}
+
+function roleOf(raw: Dict): MessageRecord["role"] {
+ const role = typeof raw.role === "string" ? raw.role : "";
+ if (role === "user") return "user";
+ if (role === "system") return "system";
+ return "assistant";
+}
+
+/**
+ * Convert one exported Open WebUI chat. Returns null when it holds no message
+ * we can render (an empty chat, or one whose turns were all blank).
+ */
+export function openWebUIRecordToConversation(
+ record: unknown,
+ fallbackTitle: string,
+): ParsedConversation | null {
+ const chat = chatBlob(record);
+ if (!chat) return null;
+ const outer = isDict(record) ? record : {};
+
+ const threadId = crypto.randomUUID();
+ const nodes = collectNodes(chat);
+ // The first message is a better start than `updated_at`, which is the end of
+ // the conversation and would drag every message in it up to that moment.
+ const createdAt =
+ epochMs(outer.created_at) ??
+ epochMs(chat.timestamp) ??
+ earliestTimestamp(nodes) ??
+ epochMs(outer.updated_at) ??
+ Date.now();
+
+ const messages: MessageRecord[] = [];
+ // Studio sorts stored messages by createdAt, so the timeline has to be
+ // strictly increasing or the depth-first order above would not survive a
+ // reload. Real timestamps are kept whenever they already increase.
+ let previousTs = createdAt - 1;
+ const keptIdByOriginal = new Map<string, string>();
+
+ for (const node of nodes) {
+ const role = roleOf(node.raw);
+ const { content, attachments } = messageParts(node.raw, role);
+ // A message that renders to nothing (a failed turn holding only an error)
+ // is dropped, and its children relink to the nearest ancestor that stayed.
+ // A user turn that uploaded a file and typed nothing still renders, as
+ // studio shows attachments on user messages.
+ const renders = content.length > 0 || (role === "user" && attachments.length > 0);
+ const parentId = node.parentId ? (keptIdByOriginal.get(node.parentId) ?? null) : null;
+ if (!renders) {
+ if (node.parentId) {
+ const inherited = keptIdByOriginal.get(node.parentId);
+ if (inherited) keptIdByOriginal.set(node.id, inherited);
+ }
+ continue;
+ }
+
+ const id = crypto.randomUUID();
+ keptIdByOriginal.set(node.id, id);
+ const ts = Math.max(previousTs + 1, epochMs(node.raw.timestamp) ?? 0);
+ previousTs = ts;
+
+ messages.push({
+ id,
+ threadId,
+ parentId,
+ role,
+ content: content as MessageRecord["content"],
+ ...(attachments.length > 0
+ ? { attachments: attachments as MessageRecord["attachments"] }
+ : {}),
+ createdAt: ts,
+ });
+ }
+
+ if (messages.length === 0) return null;
+
+ return {
+ title: str(chat.title) ?? str(outer.title) ?? fallbackTitle,
+ threadId,
+ messages,
+ archived: outer.archived === true,
+ createdAt,
+ };
+}
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index 19136ea91c2..1ed90977a24 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -33,7 +33,10 @@ import {
downloadArchivedChatExport,
downloadChatExport,
exportFineTuneJsonl,
- importConversationsFromFile,
+ importConversationsFromSource,
+ nativeImportSource,
+ fileImportSource,
+ type ImportSource,
offerToDeleteKeptSandboxes,
useChatPreferencesStore,
useChatRuntimeStore,
@@ -230,21 +233,59 @@ export function DataTab() {
};
const importInputRef = useRef<HTMLInputElement>(null);
- const handleImport = async (file: File) => {
+ const [importing, setImporting] = useState(false);
+ const handleImport = async (source: ImportSource) => {
+ setImporting(true);
+ // A years-long export is minutes of writes, so the toast counts up rather
+ // than leaving the window looking hung.
+ const toastId = toast.loading(
+ t("settings.chat.importingChats", { count: 0, percent: 0 }),
+ );
try {
- const imported = await importConversationsFromFile(file, null);
+ const { imported, failed } = await importConversationsFromSource(
+ source,
+ null,
+ {
+ onProgress: ({ imported: done, bytesRead, totalBytes }) => {
+ const percent = totalBytes
+ ? Math.min(100, Math.round((bytesRead / totalBytes) * 100))
+ : 0;
+ toast.loading(
+ t("settings.chat.importingChats", { count: done, percent }),
+ { id: toastId },
+ );
+ },
+ },
+ );
+ if (imported === 0 && failed === 0) {
+ toast.info(t("settings.chat.importNoConversations"), { id: toastId });
+ return;
+ }
if (imported === 0) {
- toast.info(t("settings.chat.importNoConversations"));
- } else {
- toast.success(
- imported === 1
+ // Nothing was created, so however the count is phrased this is a failure.
+ toast.error(t("settings.chat.importFailed"), {
+ id: toastId,
+ description: t("settings.chat.importedChatCountPartial", { count: 0, failed }),
+ });
+ return;
+ }
+ toast.success(
+ failed > 0
+ ? t("settings.chat.importedChatCountPartial", { count: imported, failed })
+ : imported === 1
? t("settings.chat.importedOneChat")
: t("settings.chat.importedChatCount", { count: imported }),
- );
- setCount(await countAllChats().catch(() => count));
- }
- } catch {
- toast.error(t("settings.chat.importFailed"));
+ { id: toastId },
+ );
+ } catch (error) {
+ toast.error(t("settings.chat.importFailed"), {
+ id: toastId,
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ setImporting(false);
+ // Chats saved before a failed read still changed the count.
+ setCount(await countAllChats().catch(() => count));
}
};
@@ -258,7 +299,7 @@ export function DataTab() {
if (!selected) {
return;
}
- await handleImport(new File([selected.content], selected.name));
+ await handleImport(nativeImportSource(selected));
} catch (error) {
toast.error(t("settings.chat.importFailed"), {
description: error instanceof Error ? error.message : String(error),
@@ -789,19 +830,26 @@ export function DataTab() {
variant="outline"
size="sm"
onClick={() => void handleImportClick()}
+ // A second pick mid-import would interleave two streams into one
+ // history, and on desktop it retires the running import's handle.
+ disabled={importing}
>
- <HugeiconsIcon icon={Upload01Icon} className="size-3.5 mr-1.5" />
+ {importing ? (
+ <Spinner className="size-3.5 mr-1.5" />
+ ) : (
+ <HugeiconsIcon icon={Upload01Icon} className="size-3.5 mr-1.5" />
+ )}
{t("settings.chat.importChatsAction")}
</Button>
<input
ref={importInputRef}
type="file"
- accept=".jsonl,.ndjson,.csv"
+ accept=".json,.jsonl,.ndjson,.csv"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
e.target.value = "";
- if (file) void handleImport(file);
+ if (file) void handleImport(fileImportSource(file));
}}
/>
</SettingsRow>
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 155005d17c8..f1f453d69b4 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -959,12 +959,14 @@ export const ar = {
exportPerChatSuffix: "(لكل محادثة)",
importChats: "استيراد المحادثات",
importChatsDescription:
- "استيراد ملف بصيغة JSONL أو NDJSON أو CSV إلى العناصر الأخيرة.",
+ "استيراد ملف تصدير من Open WebUI أو JSONL أو NDJSON أو CSV إلى الأخيرة.",
importChatsAction: "استيراد",
importNoConversations: "لم يُعثر على محادثات في الملف.",
importedOneChat: "تم استيراد محادثة واحدة إلى العناصر الأخيرة.",
importedChatCount:
"تم استيراد المحادثات إلى العناصر الأخيرة. العدد: {count}.",
+ importingChats: "جارٍ استيراد المحادثات: {count} حتى الآن ({percent}%)...",
+ importedChatCountPartial: "تم استيراد {count} محادثة إلى الأخيرة؛ تعذّر حفظ {failed} منها.",
importFailed: "فشل الاستيراد.",
clearHistory: "مسح سجل المحادثات",
clearHistoryDescription: "حذف سجل المحادثات من هذا الجهاز.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index fb281027dc5..c641de2b263 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -993,12 +993,14 @@ export const de = {
exportPerChatSuffix: "(pro Chat)",
importChats: "Chats importieren",
importChatsDescription:
- "Importieren Sie einen JSONL-, NDJSON- oder CSV-Export in „Zuletzt verwendet“.",
+ "Einen Open-WebUI-, JSONL-, NDJSON- oder CSV-Export in Zuletzt importieren.",
importChatsAction: "Importieren",
importNoConversations: "Keine Konversationen in der Datei gefunden.",
importedOneChat: "1 Konversation in „Zuletzt verwendet“ importiert.",
importedChatCount:
"{count} Konversationen in „Zuletzt verwendet“ importiert.",
+ importingChats: "Chats werden importiert: bisher {count} ({percent}%)...",
+ importedChatCountPartial: "{count} Unterhaltungen in Zuletzt importiert; {failed} konnten nicht gespeichert werden.",
importFailed: "Import fehlgeschlagen.",
clearHistory: "Chatverlauf löschen",
clearHistoryDescription: "Chatverlauf von diesem Gerät löschen.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 2e69535c3c3..c90fb91e820 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -953,11 +953,13 @@ export const en = {
exportPerChatSuffix: "(per chat)",
importChats: "Import chats",
importChatsDescription:
- "Import a JSONL, NDJSON, or CSV export into Recents.",
+ "Import an Open WebUI, JSONL, NDJSON, or CSV export into Recents.",
importChatsAction: "Import",
importNoConversations: "No conversations found in file.",
importedOneChat: "Imported 1 conversation to Recents.",
importedChatCount: "Imported {count} conversations to Recents.",
+ importingChats: "Importing chats: {count} so far ({percent}%)...",
+ importedChatCountPartial: "Imported {count} conversations to Recents; {failed} could not be saved.",
importFailed: "Import failed.",
clearHistory: "Clear chat history",
clearHistoryDescription: "Delete chat history from this device.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 8f8bcd6fde1..e8fc2af7e54 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -984,11 +984,13 @@ export const es = {
exportPerChatSuffix: "(por chat)",
importChats: "Importar chats",
importChatsDescription:
- "Importa una exportación JSONL, NDJSON o CSV a Recientes.",
+ "Importa una exportación de Open WebUI, JSONL, NDJSON o CSV a Recientes.",
importChatsAction: "Importar",
importNoConversations: "No se encontraron conversaciones en el archivo.",
importedOneChat: "Se importó 1 conversación a Recientes.",
importedChatCount: "Se importaron {count} conversaciones a Recientes.",
+ importingChats: "Importando chats: {count} hasta ahora ({percent}%)...",
+ importedChatCountPartial: "Se importaron {count} conversaciones a Recientes; {failed} no se pudieron guardar.",
importFailed: "La importación falló.",
clearHistory: "Borrar historial de chat",
clearHistoryDescription: "Elimina el historial de chat de este dispositivo.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 1c821611e07..908a53d8e26 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -990,11 +990,13 @@ export const fr = {
exportPerChatSuffix: "(par discussion)",
importChats: "Importer des discussions",
importChatsDescription:
- "Importer un export JSONL, NDJSON ou CSV dans Récents.",
+ "Importez un export Open WebUI, JSONL, NDJSON ou CSV dans Récents.",
importChatsAction: "Importer",
importNoConversations: "Aucune conversation trouvée dans le fichier.",
importedOneChat: "1 conversation importée dans Récents.",
importedChatCount: "{count} conversations importées dans Récents.",
+ importingChats: "Import des discussions : {count} jusqu'ici ({percent}%)...",
+ importedChatCountPartial: "{count} conversations importées dans Récents ; {failed} n'ont pas pu être enregistrées.",
importFailed: "Échec de l'importation.",
clearHistory: "Effacer l'historique des discussions",
clearHistoryDescription:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 04b61076add..d80acacb844 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -965,12 +965,14 @@ export const hi = {
exportPerChatSuffix: "(प्रति चैट)",
importChats: "चैट इंपोर्ट करें",
importChatsDescription:
- "JSONL, NDJSON या CSV एक्सपोर्ट को हाल के सेक्शन में इंपोर्ट करें।",
+ "Open WebUI, JSONL, NDJSON या CSV एक्सपोर्ट को Recents में इंपोर्ट करें।",
importChatsAction: "इंपोर्ट करें",
importNoConversations: "फ़ाइल में कोई वार्तालाप नहीं मिला।",
importedOneChat: "1 वार्तालाप हाल के सेक्शन में इंपोर्ट किया गया।",
importedChatCount:
"{count} वार्तालाप हाल के सेक्शन में इंपोर्ट किए गए।",
+ importingChats: "चैट इंपोर्ट हो रही हैं: अब तक {count} ({percent}%)...",
+ importedChatCountPartial: "{count} बातचीत Recents में इंपोर्ट की गईं; {failed} सेव नहीं हो सकीं।",
importFailed: "इंपोर्ट विफल रहा।",
clearHistory: "चैट इतिहास साफ़ करें",
clearHistoryDescription: "इस डिवाइस से चैट इतिहास हटाएं।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 344b9e9a6e8..b057956fe13 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -956,11 +956,13 @@ export const it = {
exportPerChatSuffix: "(uno per chat)",
importChats: "Importa chat",
importChatsDescription:
- "Importa nei Recenti un'esportazione JSONL, NDJSON o CSV.",
+ "Importa un export Open WebUI, JSONL, NDJSON o CSV in Recenti.",
importChatsAction: "Importa",
importNoConversations: "Nessuna conversazione trovata nel file.",
importedOneChat: "1 conversazione importata nei Recenti.",
importedChatCount: "{count} conversazioni importate nei Recenti.",
+ importingChats: "Importazione chat: {count} finora ({percent}%)...",
+ importedChatCountPartial: "Importate {count} conversazioni in Recenti; {failed} non sono state salvate.",
importFailed: "Importazione non riuscita.",
clearHistory: "Cancella la cronologia delle chat",
clearHistoryDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 3e9a01caf0c..82f997bcbe4 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -945,11 +945,13 @@ export const ja = {
exportCombinedSuffix: "(一括)",
exportPerChatSuffix: "(チャットごと)",
importChats: "チャットをインポート",
- importChatsDescription: "JSONL、NDJSON、または CSV のエクスポートファイルを履歴にインポートします。",
+ importChatsDescription: "Open WebUI、JSONL、NDJSON、または CSV のエクスポートファイルを履歴にインポートします。",
importChatsAction: "インポート",
importNoConversations: "ファイル内に会話が見つかりませんでした。",
importedOneChat: "1 件の会話を履歴にインポートしました。",
importedChatCount: "{count} 件の会話を履歴にインポートしました。",
+ importingChats: "チャットをインポート中: 現在 {count} 件({percent}%)...",
+ importedChatCountPartial: "{count} 件の会話を最近のチャットにインポートしました。{failed} 件は保存できませんでした。",
importFailed: "インポートに失敗しました。",
clearHistory: "チャット履歴を消去",
clearHistoryDescription: "このデバイスからチャット履歴を削除します。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index bb777890b0d..cd751b15a0b 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -958,11 +958,13 @@ export const ko = {
exportPerChatSuffix: "(채팅별)",
importChats: "채팅 가져오기",
importChatsDescription:
- "JSONL, NDJSON 또는 CSV 내보내기 파일을 최근 항목으로 가져옵니다.",
+ "Open WebUI, JSONL, NDJSON 또는 CSV 내보내기 파일을 최근 항목으로 가져옵니다.",
importChatsAction: "가져오기",
importNoConversations: "파일에서 대화를 찾을 수 없습니다.",
importedOneChat: "1개의 대화를 최근 항목으로 가져왔습니다.",
importedChatCount: "{count}개의 대화를 최근 항목으로 가져왔습니다.",
+ importingChats: "채팅 가져오는 중: 현재 {count}개({percent}%)...",
+ importedChatCountPartial: "{count}개의 대화를 최근 항목으로 가져왔습니다. {failed}개는 저장하지 못했습니다.",
importFailed: "가져오기에 실패했습니다.",
clearHistory: "채팅 기록 지우기",
clearHistoryDescription: "이 기기에서 채팅 기록을 삭제합니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 884fb41e89f..07ac46fc884 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -972,11 +972,13 @@ export const ptBR = {
exportPerChatSuffix: "(por chat)",
importChats: "Importar chats",
importChatsDescription:
- "Importe um arquivo exportado em JSONL, NDJSON ou CSV para Recentes.",
+ "Importe um export do Open WebUI, JSONL, NDJSON ou CSV para Recentes.",
importChatsAction: "Importar",
importNoConversations: "Nenhuma conversa encontrada no arquivo.",
importedOneChat: "1 conversa foi importada para Recentes.",
importedChatCount: "{count} conversas foram importadas para Recentes.",
+ importingChats: "Importando chats: {count} até agora ({percent}%)...",
+ importedChatCountPartial: "{count} conversas importadas para Recentes; {failed} não puderam ser salvas.",
importFailed: "Falha na importação.",
clearHistory: "Limpar histórico de chat",
clearHistoryDescription: "Exclui o histórico de chat deste dispositivo.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index d10c440c93f..e885c3f01f7 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -969,11 +969,13 @@ export const ru = {
exportPerChatSuffix: "(по чатам)",
importChats: "Импортировать чаты",
importChatsDescription:
- "Импортировать файл экспорта в формате JSONL, NDJSON или CSV в раздел «Недавние».",
+ "Импортируйте экспорт Open WebUI, JSONL, NDJSON или CSV в Недавние.",
importChatsAction: "Импорт",
importNoConversations: "В файле не найдено диалогов.",
importedOneChat: "Импортирован 1 диалог в «Недавние».",
importedChatCount: "Импортировано диалогов в «Недавние»: {count}.",
+ importingChats: "Импорт чатов: пока {count} ({percent}%)...",
+ importedChatCountPartial: "Импортировано {count} бесед в Недавние; {failed} не удалось сохранить.",
importFailed: "Импорт не удался.",
clearHistory: "Очистить историю чатов",
clearHistoryDescription: "Удалить историю чатов с этого устройства.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index eb32e5ba3d7..81e2f47b7a2 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -935,11 +935,13 @@ export const zhCN = {
exportPerChatSuffix: "(每个对话)",
importChats: "导入对话",
importChatsDescription:
- "从 JSONL、NDJSON 或 CSV 导出文件将对话导入到最近对话。",
+ "将 Open WebUI、JSONL、NDJSON 或 CSV 导出文件导入到最近对话。",
importChatsAction: "导入",
importNoConversations: "文件中未找到对话。",
importedOneChat: "已导入 1 个对话到最近对话。",
importedChatCount: "已导入 {count} 个对话到最近对话。",
+ importingChats: "正在导入对话:已完成 {count} 个({percent}%)...",
+ importedChatCountPartial: "已将 {count} 个对话导入到最近对话;{failed} 个未能保存。",
importFailed: "导入失败。",
clearHistory: "清除聊天记录",
clearHistoryDescription: "从此设备删除本地聊天记录。",
diff --git a/studio/frontend/src/lib/native-files.ts b/studio/frontend/src/lib/native-files.ts
index e4e06c21ffc..ddc002dc0c8 100644
--- a/studio/frontend/src/lib/native-files.ts
+++ b/studio/frontend/src/lib/native-files.ts
@@ -30,7 +30,27 @@ export interface NativeImportedTextFile {
content: string;
}
-export type NativeChatImport = NativeImportedTextFile;
+/** Handle for a native chat import read in bounded ranges. */
+export interface NativeChatImport {
+ name: string;
+ size: number;
+ token: string;
+}
+
+export async function readNativeChatImportChunk(
+ token: string,
+ offset: number,
+ length: number,
+): Promise<Uint8Array> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const bytes = await invoke<ArrayBuffer | number[]>(
+ "read_native_chat_import_chunk",
+ { token, offset, length },
+ );
+ return bytes instanceof ArrayBuffer
+ ? new Uint8Array(bytes)
+ : new Uint8Array(bytes);
+}
function browserDownload(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
diff --git a/studio/frontend/tests/json-record-stream.test.ts b/studio/frontend/tests/json-record-stream.test.ts
new file mode 100644
index 00000000000..ed783ed6316
--- /dev/null
+++ b/studio/frontend/tests/json-record-stream.test.ts
@@ -0,0 +1,429 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Covers JSON framing and UTF-8 boundaries without reading the entire export.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ decodeTextChunks,
+ fileImportSource,
+ readAllText,
+ streamJsonRecords,
+ type TextChunk,
+} from "../src/features/chat/utils/json-record-stream.ts";
+
+async function* asChunks(text: string, size: number): AsyncGenerator<TextChunk> {
+ for (let index = 0; index < text.length; index += size) {
+ const slice = text.slice(index, index + size);
+ yield { text: slice, bytes: Buffer.byteLength(slice) };
+ }
+}
+
+async function drain(chunks: AsyncIterable<unknown>): Promise<void> {
+ for await (const chunk of chunks) void chunk;
+}
+
+async function collect(text: string, size: number): Promise<unknown[]> {
+ const out: unknown[] = [];
+ for await (const record of streamJsonRecords(asChunks(text, size))) out.push(record);
+ return out;
+}
+
+const TRICKY = [
+ { id: 1, title: 'braces } and ] inside a string' },
+ { id: 2, title: 'an escaped quote \\" then a brace {' },
+ { id: 3, nested: { deep: [{ deeper: ["{", "}", "[", "]"] }] } },
+ { id: 4, title: "backslash at the end \\\\" },
+];
+
+test("an array is cut into records at every chunk size, including one character at a time", async () => {
+ const text = JSON.stringify(TRICKY);
+ for (const size of [1, 2, 7, 64, text.length, text.length * 2]) {
+ assert.deepEqual(await collect(text, size), TRICKY, `chunk size ${size}`);
+ }
+});
+
+test("pretty-printed and single-line arrays parse the same", async () => {
+ assert.deepEqual(await collect(JSON.stringify(TRICKY, null, 2), 13), TRICKY);
+});
+
+test("JSONL, NDJSON with blank lines, and a bare object all yield their records", async () => {
+ const jsonl = TRICKY.map((record) => JSON.stringify(record)).join("\n");
+ assert.deepEqual(await collect(jsonl, 9), TRICKY);
+ assert.deepEqual(await collect(`\n\n${jsonl}\n\n`, 9), TRICKY);
+ assert.deepEqual(await collect(JSON.stringify(TRICKY[0]), 3), [TRICKY[0]]);
+});
+
+test("an empty file and an empty array yield nothing rather than throwing", async () => {
+ assert.deepEqual(await collect("", 4), []);
+ assert.deepEqual(await collect("[]", 1), []);
+ assert.deepEqual(await collect(" \n ", 2), []);
+});
+
+test("a record far larger than the chunk size is reassembled whole", async () => {
+ const big = { id: "big", blob: "x".repeat(500_000) };
+ const [record] = await collect(JSON.stringify([big, { id: "after" }]), 4096);
+ assert.deepEqual(record, big);
+});
+
+test("truncated JSON fails loudly instead of importing a half-read chat", async () => {
+ await assert.rejects(collect('[{"id":1},{"id":', 4), SyntaxError);
+});
+
+test("one mangled record is skipped, not treated as the end of the file", async () => {
+ // Balanced framing lets the scanner skip only the damaged record.
+ const text = '[{"id":1},{bad},{"id":3}]';
+ for (const size of [1, 5, 64, text.length]) {
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ for await (const record of streamJsonRecords(asChunks(text, size), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(record);
+ }
+ assert.deepEqual(out, [{ id: 1 }, { id: 3 }], `chunk size ${size}`);
+ assert.deepEqual(malformed, ["{bad}"], `chunk size ${size}`);
+ }
+
+ // Same for JSONL, which is where the old importer's leniency was visible.
+ const jsonl = ['{"id":1}', "{bad}", '{"id":3}'].join("\n");
+ assert.deepEqual(await collect(jsonl, 3), [{ id: 1 }, { id: 3 }]);
+});
+
+test("a row that loses its closing brace does not swallow the rows after it", async () => {
+ // Recover later rows using JSONL boundaries.
+ const jsonl = ['{"id":1}', '{"id":2', '{"id":3}', '{"id":4}'].join("\n");
+ for (const size of [1, 6, 64, jsonl.length]) {
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ for await (const record of streamJsonRecords(asChunks(jsonl, size), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(record);
+ }
+ assert.deepEqual(out, [{ id: 1 }, { id: 3 }, { id: 4 }], `chunk size ${size}`);
+ assert.deepEqual(malformed, ['{"id":2'], `chunk size ${size}`);
+ }
+
+ // Windows line endings frame records the same way.
+ const crlf = ['{"id":1}', '{"id":2', '{"id":3}'].join("\r\n");
+ assert.deepEqual(await collect(crlf, 5), [{ id: 1 }, { id: 3 }]);
+});
+
+test("a broken first row is recovered even though nothing framed the file yet", async () => {
+ // With no prior record, only unindented objects establish line framing.
+ const jsonl = ['{"id":1', '{"id":2}', '{"id":3}'].join("\n");
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ for await (const record of streamJsonRecords(asChunks(jsonl, 5), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(record);
+ }
+ assert.deepEqual(out, [{ id: 2 }, { id: 3 }]);
+ assert.deepEqual(malformed, ['{"id":1']);
+});
+
+test("a multi-line record still frames by nesting, so a pretty-printed file is not shredded", async () => {
+ // Recovery must not fire on input that is merely formatted across lines.
+ const pretty = JSON.stringify({ id: 1, nested: { rows: [1, 2, 3] } }, null, 2);
+ assert.deepEqual(await collect(pretty, 7), [{ id: 1, nested: { rows: [1, 2, 3] } }]);
+ assert.deepEqual(await collect(JSON.stringify(TRICKY, null, 4), 11), TRICKY);
+});
+
+test("a pretty-printed record whose inner lines parse on their own stays one record", async () => {
+ // Parseable inner values must not be mistaken for JSONL records.
+ const record = {
+ id: "c1",
+ tags: ["kept-tag"],
+ messages: [
+ { role: "user", content: `data:image/png;base64,${"A".repeat(400)}` },
+ { role: "assistant", content: "done" },
+ ],
+ };
+ const pretty = JSON.stringify(record, null, 2);
+ for (const size of [1, 16, 512, pretty.length]) {
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ for await (const parsed of streamJsonRecords(asChunks(pretty, size), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(parsed);
+ }
+ assert.deepEqual(out, [record], `chunk size ${size}`);
+ assert.deepEqual(malformed, [], `chunk size ${size}`);
+ }
+
+ // Damaged rows after such a record are still recovered at end of input.
+ const mixed = `${pretty}\n{"id":"after"\n{"id":"tail"}`;
+ const after: unknown[] = [];
+ const afterBad: string[] = [];
+ for await (const parsed of streamJsonRecords(asChunks(mixed, 16), {
+ onMalformed: (bad) => afterBad.push(bad),
+ })) {
+ after.push(parsed);
+ }
+ assert.deepEqual(after, [record, { id: "tail" }]);
+ assert.deepEqual(afterBad, ['{"id":"after"']);
+});
+
+test("a file that stops inside one record reports it once, not as a pile of fragments", async () => {
+ // Indented inner lines, one of which parses alone, must not become records.
+ const truncated = '{\n "id": 1,\n "tags": [\n "kept-tag"\n ]';
+ const malformed: string[] = [];
+ const out: unknown[] = [];
+ for await (const record of streamJsonRecords(asChunks(truncated, 5), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(record);
+ }
+ assert.deepEqual(out, []);
+ assert.deepEqual(malformed, [truncated]);
+});
+
+test("byte counts are reported for progress, not decoded character counts", async () => {
+ // Four bytes each in UTF-8, two UTF-16 units each in the decoded string.
+ const text = JSON.stringify([{ id: "🦥🦥🦥" }]);
+ let bytes = 0;
+ await drain(
+ streamJsonRecords(asChunks(text, 8), {
+ onBytes: (n) => {
+ bytes += n;
+ },
+ }),
+ );
+ assert.equal(bytes, Buffer.byteLength(text));
+ assert.ok(bytes > text.length);
+});
+
+/** A File stub that emits fixed-size byte chunks. */
+function chunkedFile(text: string, name: string, chunkBytes: number): File {
+ const bytes = Buffer.from(text, "utf-8");
+ return {
+ name,
+ size: bytes.byteLength,
+ stream: () =>
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (let at = 0; at < bytes.byteLength; at += chunkBytes) {
+ controller.enqueue(new Uint8Array(bytes.subarray(at, at + chunkBytes)));
+ }
+ controller.close();
+ },
+ }),
+ } as unknown as File;
+}
+
+test("multi-byte characters split across File reads decode intact, not as replacement chars", async () => {
+ // Every read boundary lands mid-character: 3-byte characters, chunks of 64 bytes + 1.
+ const title = "日本語のプロンプト設計".repeat(400);
+ const records = [{ id: "unicode", title }, { id: "after", title: "🦥 sloth" }];
+ const file = chunkedFile(JSON.stringify(records), "chat-export.json", 65);
+
+ const out: unknown[] = [];
+ let bytes = 0;
+ for await (const record of streamJsonRecords(fileImportSource(file).chunks(), {
+ onBytes: (n) => {
+ bytes += n;
+ },
+ })) {
+ out.push(record);
+ }
+
+ assert.deepEqual(out, records);
+ assert.equal(bytes, file.size);
+ assert.ok(!JSON.stringify(out).includes("�"));
+});
+
+test("an array that ends between records fails instead of reporting a complete import", async () => {
+ // An interrupted download stops on a record boundary as often as inside one,
+ // and every chat after the cut is missing either way.
+ for (const truncated of ['[{"id":1}', '[{"id":1},', '[{"id":1},\n', "[", '[{"id":1},{"id":2}']) {
+ await assert.rejects(collect(truncated, 3), SyntaxError, truncated);
+ }
+
+ // The closing bracket is what makes it complete, at every chunk size.
+ for (const size of [1, 4, 64]) {
+ assert.deepEqual(await collect('[{"id":1},{"id":2}]', size), [{ id: 1 }, { id: 2 }]);
+ assert.deepEqual(await collect('[{"id":1}]\n', size), [{ id: 1 }]);
+ }
+
+ // JSONL has no closing delimiter to require.
+ assert.deepEqual(await collect('{"id":1}\n{"id":2}', 5), [{ id: 1 }, { id: 2 }]);
+ assert.deepEqual(await collect('{"id":1}\n{"id":2}\n', 5), [{ id: 1 }, { id: 2 }]);
+});
+
+test("invalid UTF-8 is rejected on the desktop path and tolerated on the browser path", async () => {
+ async function* bytes(): AsyncGenerator<Uint8Array> {
+ yield new Uint8Array([0x7b, 0x22, 0x61, 0x22, 0x3a, 0x22]); // {"a":"
+ yield new Uint8Array([0xff]); // not a UTF-8 sequence
+ yield new Uint8Array([0x22, 0x7d]); // "}
+ }
+
+ const lenient: string[] = [];
+ for await (const chunk of decodeTextChunks(bytes())) lenient.push(chunk.text);
+ assert.equal(lenient.join(""), '{"a":"�"}');
+
+ await assert.rejects(drain(decodeTextChunks(bytes(), true)), TypeError);
+
+ // A file that stops mid-character is a truncated read, not valid text.
+ const cutShort = (async function* () {
+ yield new Uint8Array([0xe6, 0x97]); // first two bytes of a 3-byte character
+ })();
+ await assert.rejects(drain(decodeTextChunks(cutShort, true)), TypeError);
+});
+
+test("the whole-file read is bounded by bytes, not by decoded string length", async () => {
+ // Three bytes per character, one UTF-16 unit each: a length check would pass a
+ // file three times the limit.
+ const text = "日".repeat(64);
+ const source = {
+ name: "chats.csv",
+ async *chunks() {
+ for (const chunk of [text, text]) {
+ yield { text: chunk, bytes: Buffer.byteLength(chunk) };
+ }
+ },
+ };
+
+ assert.equal((await readAllText(source, 512, "CSV")).length, 128);
+ await assert.rejects(readAllText(source, 300, "CSV"), /chats\.csv is too large to import as CSV/);
+});
+
+test("a pretty-printed record following a single-line one survives every chunk boundary", async () => {
+ // Recovery used to fire on the first newline of the pending record, so the
+ // same file imported differently depending on where the chunks fell.
+ const record = { id: 2, tags: ["a", "b"], nested: { rows: [1, 2] } };
+ const mixed = `{"id":1}\n${JSON.stringify(record, null, 2)}\n`;
+ for (const size of [1, 5, 12, 64, mixed.length]) {
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ for await (const parsed of streamJsonRecords(asChunks(mixed, size), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(parsed);
+ }
+ assert.deepEqual(out, [{ id: 1 }, record], `chunk size ${size}`);
+ assert.deepEqual(malformed, [], `chunk size ${size}`);
+ }
+});
+
+test("a broken first row is recovered while the file streams, not held until the end", async () => {
+ // With nothing emitted yet there is no proven framing, and waiting for end of
+ // input to recover would buffer the whole export.
+ const rows = `{"id":1\n${Array.from({ length: 60 }, (_, i) => `{"id":${i + 2}}`).join("\n")}\n`;
+ let pulled = 0;
+ async function* counted(): AsyncGenerator<TextChunk> {
+ for (let at = 0; at < rows.length; at += 16) {
+ pulled++;
+ const slice = rows.slice(at, at + 16);
+ yield { text: slice, bytes: Buffer.byteLength(slice) };
+ }
+ }
+
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ let pulledAtFirstRecord = Number.POSITIVE_INFINITY;
+ for await (const record of streamJsonRecords(counted(), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ if (out.length === 0) pulledAtFirstRecord = pulled;
+ out.push(record);
+ }
+
+ assert.equal(out.length, 60);
+ assert.deepEqual(malformed, ['{"id":1']);
+ assert.ok(
+ pulledAtFirstRecord < pulled,
+ `first record arrived only after ${pulledAtFirstRecord} of ${pulled} chunks`,
+ );
+});
+
+test("a nested value at column 0 does not end the record that contains it", async () => {
+ // JSON cannot continue `{"nested":` with anything but a value, so the brace
+ // below it is nesting; after a finished value it would be the next record.
+ const nested = '{"nested":\n{"id":2}\n}';
+ for (const size of [1, 4, 9, 17, nested.length]) {
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ for await (const record of streamJsonRecords(asChunks(`{"id":1}\n${nested}\n`, size), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(record);
+ }
+ assert.deepEqual(out, [{ id: 1 }, { nested: { id: 2 } }], `chunk size ${size}`);
+ assert.deepEqual(malformed, [], `chunk size ${size}`);
+ }
+});
+
+test("a pretty-printed conversation after a damaged row is framed, not shredded into lines", async () => {
+ // Line-parsing the region behind the boundary lost the whole record when it
+ // arrived in one chunk, and emitted its nested objects as records when it did
+ // not, so the outcome again depended on the chunk size.
+ const conversation = {
+ id: "c2",
+ messages: [
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "hello" },
+ ],
+ };
+ const text = `{"id":1\n${JSON.stringify(conversation, null, 2)}\n{"id":3}\n`;
+ for (const size of [1, 7, 40, 200, text.length]) {
+ const out: unknown[] = [];
+ const malformed: string[] = [];
+ for await (const record of streamJsonRecords(asChunks(text, size), {
+ onMalformed: (bad) => malformed.push(bad),
+ })) {
+ out.push(record);
+ }
+ assert.deepEqual(out, [conversation, { id: 3 }], `chunk size ${size}`);
+ assert.deepEqual(malformed, ['{"id":1'], `chunk size ${size}`);
+ }
+});
+
+test("an array cut mid-record explains itself instead of quoting the JSON engine", async () => {
+ // The records before the cut are still yielded, so the caller can report how
+ // many were saved; only the message the user sees changes.
+ const truncated = '[{"id":1},{"id":2},{"title":"half a chat';
+ for (const size of [1, 5, 64, 4096]) {
+ const seen: unknown[] = [];
+ let message = "";
+ try {
+ for await (const record of streamJsonRecords(asChunks(truncated, size))) seen.push(record);
+ } catch (error) {
+ message = error instanceof Error ? error.message : String(error);
+ }
+ assert.deepEqual(seen, [{ id: 1 }, { id: 2 }], `records lost at chunk ${size}`);
+ assert.match(message, /ends in the middle of a record/);
+ assert.doesNotMatch(message, /Unterminated string|position \d+/);
+ }
+});
+
+test("an array cut between records still names the missing bracket", async () => {
+ for (const truncated of ['[{"id":1},{"id":2},', '[{"id":1},{"id":2}']) {
+ let message = "";
+ try {
+ await drain(streamJsonRecords(asChunks(truncated, 3)));
+ } catch (error) {
+ message = error instanceof Error ? error.message : String(error);
+ }
+ assert.match(message, /ends before its closing bracket/);
+ }
+});
+
+test("a complete array is unaffected by the truncation handling", async () => {
+ const records = await collect('[{"id":1},{"id":2}]', 2);
+ assert.deepEqual(records, [{ id: 1 }, { id: 2 }]);
+});
+
+test("a record after the array's closing bracket is refused, not imported", async () => {
+ // A concatenated or corrupted export must not pass as one array's worth.
+ for (const size of [1, 6, 64]) {
+ await assert.rejects(collect('[{"id":1}]\n{"id":2}\n', size), SyntaxError, `chunk size ${size}`);
+ await assert.rejects(collect('[{"id":1}] garbage', size), SyntaxError, `chunk size ${size}`);
+ // Trailing whitespace is still just the end of the file.
+ assert.deepEqual(await collect('[{"id":1}] \n\t\n', size), [{ id: 1 }], `chunk size ${size}`);
+ }
+});
diff --git a/studio/frontend/tests/openwebui-import.test.ts b/studio/frontend/tests/openwebui-import.test.ts
new file mode 100644
index 00000000000..160f60bb5d6
--- /dev/null
+++ b/studio/frontend/tests/openwebui-import.test.ts
@@ -0,0 +1,1108 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Covers branch restoration, old and new tool-call formats, and damaged graphs.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ isOpenWebUIRecord,
+ openWebUIRecordToConversation,
+} from "../src/features/chat/utils/openwebui-import.ts";
+
+type Part = { type: string; [key: string]: unknown };
+
+function parts(conversation: { messages: { content: unknown }[] }, index: number): Part[] {
+ return conversation.messages[index].content as Part[];
+}
+
+function text(conversation: { messages: { content: unknown }[] }, index: number): string {
+ return parts(conversation, index)
+ .filter((part) => part.type === "text")
+ .map((part) => part.text as string)
+ .join("\n");
+}
+
+function chatRecord(chat: Record<string, unknown>, outer: Record<string, unknown> = {}) {
+ return { id: "rec", user_id: "u", title: "t", chat, created_at: 1_700_000_000, ...outer };
+}
+
+function historyOf(messages: Record<string, unknown>[], currentId: string | null) {
+ const map: Record<string, unknown> = {};
+ for (const message of messages) map[message.id as string] = message;
+ return { messages: map, currentId };
+}
+
+test("detection separates an Open WebUI record from the OpenAI and ShareGPT lines we already import", () => {
+ assert.equal(isOpenWebUIRecord(chatRecord({ history: historyOf([], null) })), true);
+ // Legacy bare chat: the record IS the chat blob.
+ assert.equal(
+ isOpenWebUIRecord({
+ id: "c",
+ title: "old",
+ messages: [{ id: "m", role: "user", content: "hi", timestamp: 1 }],
+ }),
+ true,
+ );
+ // Plain OpenAI/ShareGPT JSONL lines must not be mistaken for one.
+ assert.equal(
+ isOpenWebUIRecord({ messages: [{ role: "user", content: "hi" }] }),
+ false,
+ );
+ assert.equal(
+ isOpenWebUIRecord({ conversations: [{ from: "human", value: "hi" }] }),
+ false,
+ );
+ assert.equal(isOpenWebUIRecord(null), false);
+});
+
+test("the branch the user had open is imported last, so the thread reopens where they left it", () => {
+ // one user turn, three assistant replies; currentId points at the middle one.
+ const record = chatRecord({
+ title: "regens",
+ history: historyOf(
+ [
+ { id: "u1", parentId: null, childrenIds: ["a1", "a2", "a3"], role: "user", content: "q", timestamp: 100 },
+ { id: "a1", parentId: "u1", childrenIds: [], role: "assistant", content: "first", timestamp: 101 },
+ { id: "a2", parentId: "u1", childrenIds: [], role: "assistant", content: "kept", timestamp: 102 },
+ { id: "a3", parentId: "u1", childrenIds: [], role: "assistant", content: "third", timestamp: 103 },
+ ],
+ "a2",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 4);
+ assert.equal(text(conversation, 3), "kept");
+ // Every sibling is kept as a branch off the same user turn, not flattened away.
+ const userId = conversation.messages[0].id;
+ assert.deepEqual(
+ conversation.messages.slice(1).map((message) => message.parentId),
+ [userId, userId, userId],
+ );
+ // Strictly increasing timestamps: studio sorts by createdAt, so equal stamps would reshuffle them.
+ const stamps = conversation.messages.map((message) => message.createdAt);
+ assert.deepEqual([...stamps].sort((a, b) => a - b), stamps);
+ assert.equal(new Set(stamps).size, stamps.length);
+});
+
+test("a parent cycle and a dangling currentId are imported instead of hanging or dropping the chat", () => {
+ const cycle = chatRecord({
+ history: historyOf(
+ [
+ { id: "a", parentId: "b", childrenIds: ["b"], role: "user", content: "one", timestamp: 1 },
+ { id: "b", parentId: "a", childrenIds: ["a"], role: "assistant", content: "two", timestamp: 2 },
+ ],
+ "b",
+ ),
+ });
+ const fromCycle = openWebUIRecordToConversation(cycle, "fallback");
+ assert.ok(fromCycle);
+ assert.equal(fromCycle.messages.length, 2);
+
+ const dangling = chatRecord({
+ history: historyOf(
+ [
+ { id: "u", parentId: null, childrenIds: ["a"], role: "user", content: "q", timestamp: 1 },
+ { id: "a", parentId: "u", childrenIds: [], role: "assistant", content: "a", timestamp: 2 },
+ ],
+ "does-not-exist",
+ ),
+ });
+ const fromDangling = openWebUIRecordToConversation(dangling, "fallback");
+ assert.ok(fromDangling);
+ assert.equal(fromDangling.messages.length, 2);
+});
+
+test("a message whose parent was deleted becomes a root rather than vanishing", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [{ id: "orphan", parentId: "gone", childrenIds: [], role: "assistant", content: "kept", timestamp: 5 }],
+ "orphan",
+ ),
+ });
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 1);
+ assert.equal(conversation.messages[0].parentId, null);
+});
+
+test("a turn that renders to nothing is dropped and its children relink to the surviving ancestor", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ { id: "u1", parentId: null, childrenIds: ["err"], role: "user", content: "q", timestamp: 1 },
+ // A failed turn: Open WebUI keeps the row with empty content and an error blob.
+ { id: "err", parentId: "u1", childrenIds: ["u2"], role: "assistant", content: "", error: { content: "boom" }, timestamp: 2 },
+ { id: "u2", parentId: "err", childrenIds: [], role: "user", content: "retry", timestamp: 3 },
+ ],
+ "u2",
+ ),
+ });
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 2);
+ assert.equal(conversation.messages[1].parentId, conversation.messages[0].id);
+});
+
+test("older assistant turns keep their inlined tool call and reasoning as real parts", () => {
+ const content =
+ '<details type="reasoning" done="true" duration="7">\n<summary>Thought for 7 seconds</summary>\n> weighing options\n</details>\n' +
+ '<details type="tool_calls" done="true" id="call_1" name="get_weather" arguments="{&quot;city&quot;: &quot;Lisbon&quot;}" result="{&quot;c&quot;: 21}">\n<summary>Tool Executed</summary>\n</details>\n' +
+ "It is 21 degrees.";
+ const record = chatRecord({
+ history: historyOf(
+ [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const [reasoning, toolCall, body] = parts(conversation, 0);
+ assert.deepEqual(reasoning, { type: "reasoning", text: "weighing options" });
+ assert.equal(toolCall.type, "tool-call");
+ assert.equal(toolCall.toolCallId, "call_1");
+ assert.equal(toolCall.toolName, "get_weather");
+ assert.deepEqual(toolCall.args, { city: "Lisbon" });
+ assert.deepEqual(toolCall.result, { c: 21 });
+ assert.deepEqual(body, { type: "text", text: "It is 21 degrees." });
+});
+
+test("a tool result that contains a code fence is still lifted into a tool-call part", () => {
+ // The newer details format puts the result in the block body, and a result is
+ // usually JSON, so the fence sits between the opening and closing tags.
+ const content =
+ "Here is what the tool said.\n" +
+ '<details type="tool_calls" done="true" id="call_7" name="run_python">\n' +
+ "<summary>Tool Executed</summary>\n" +
+ "```json\n{\"rows\": 3}\n```\n" +
+ "</details>\n" +
+ "So there are three rows.";
+ const record = chatRecord({
+ history: historyOf(
+ [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const [before, toolCall, after] = parts(conversation, 0);
+ assert.deepEqual(before, { type: "text", text: "Here is what the tool said." });
+ assert.equal(toolCall.type, "tool-call");
+ assert.equal(toolCall.toolName, "run_python");
+ assert.ok(String(toolCall.result).includes('{"rows": 3}'));
+ assert.deepEqual(after, { type: "text", text: "So there are three rows." });
+ // The markup must not survive as text alongside the part it became.
+ assert.ok(!text(conversation, 0).includes("<details"));
+});
+
+test("a details block quoted inside a code fence stays text, because the chat is about the markup", () => {
+ const content =
+ "Look at this:\n\n```html\n" +
+ '<details type="tool_calls" done="true" name="not_a_call">\n<summary>example</summary>\n</details>\n' +
+ "```\n\nThat is the markup.";
+ const record = chatRecord({
+ history: historyOf(
+ [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(parts(conversation, 0).every((part) => part.type === "text"), true);
+ assert.ok(text(conversation, 0).includes('<details type="tool_calls"'));
+ assert.ok(text(conversation, 0).includes("That is the markup."));
+});
+
+test("modern assistant turns rebuild their tool call from the output items, result included", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ childrenIds: [],
+ role: "assistant",
+ content: "Lisbon is sunny.",
+ timestamp: 1,
+ output: [
+ { type: "reasoning", id: "rs_1", summary: [{ type: "output_text", text: "check the tool" }] },
+ { type: "function_call", call_id: "call_9", name: "web_search", arguments: '{"query":"lisbon"}' },
+ {
+ type: "function_call_output",
+ call_id: "call_9",
+ output: [
+ { type: "input_text", text: "sunny, 21C" },
+ { type: "input_image", image_url: "data:image/png;base64,AAAA" },
+ ],
+ },
+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const [reasoning, toolCall, image, body] = parts(conversation, 0);
+ assert.equal(reasoning.type, "reasoning");
+ assert.equal(toolCall.type, "tool-call");
+ assert.deepEqual(toolCall.args, { query: "lisbon" });
+ assert.equal(toolCall.result, "sunny, 21C");
+ assert.deepEqual(image, { type: "image", image: "data:image/png;base64,AAAA" });
+ assert.deepEqual(body, { type: "text", text: "Lisbon is sunny." });
+ // `content` mirrors the final output message, so it must not be appended twice.
+ assert.equal(parts(conversation, 0).filter((part) => part.type === "text").length, 1);
+});
+
+test("an inline image survives; a document keeps its name but not the text Open WebUI extracted", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "u",
+ parentId: null,
+ childrenIds: [],
+ role: "user",
+ content: "what is in these?",
+ timestamp: 1,
+ files: [
+ { type: "image", url: "data:image/png;base64,IMG" },
+ // A file url is a dead Open WebUI route once exported, so the bytes are gone either way.
+ { type: "image", url: "/api/v1/files/abc" },
+ {
+ type: "file",
+ id: "f1",
+ name: "spec.pdf",
+ url: "/api/v1/files/f1",
+ file: { filename: "spec.pdf", data: { content: "SECRET EXTRACTED TEXT" } },
+ },
+ ],
+ },
+ ],
+ "u",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const content = parts(conversation, 0);
+ assert.deepEqual(
+ content.filter((part) => part.type === "image"),
+ [{ type: "image", image: "data:image/png;base64,IMG" }],
+ );
+
+ const attachments = conversation.messages[0]
+ .attachments as unknown as Array<Record<string, unknown>>;
+ assert.equal(attachments.length, 1);
+ assert.equal(attachments[0].name, "spec.pdf");
+ // Replaying the extracted text into attachment content would resend a whole PDF on the next turn.
+ assert.deepEqual(attachments[0].content, []);
+ assert.ok(!JSON.stringify(conversation.messages).includes("SECRET EXTRACTED TEXT"));
+});
+
+test("a chat with no history falls back to the flat active branch, and archived carries over", () => {
+ const record = chatRecord(
+ {
+ title: "flat",
+ messages: [
+ { id: "m1", role: "user", content: "q", timestamp: 10 },
+ { id: "m2", role: "assistant", content: "a", timestamp: 11 },
+ ],
+ },
+ { archived: true },
+ );
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.title, "flat");
+ assert.equal(conversation.archived, true);
+ assert.equal(conversation.messages.length, 2);
+ assert.equal(conversation.messages[1].parentId, conversation.messages[0].id);
+});
+
+test("an empty chat imports as nothing rather than as a blank thread", () => {
+ assert.equal(openWebUIRecordToConversation(chatRecord({ history: historyOf([], null) }), "x"), null);
+ assert.equal(openWebUIRecordToConversation(chatRecord({}), "x"), null);
+});
+
+test("epoch seconds on the record and milliseconds on the blob both land in the same era", () => {
+ const seconds = openWebUIRecordToConversation(
+ chatRecord({ history: historyOf([{ id: "m", parentId: null, role: "user", content: "hi" }], "m") }, { created_at: 1_700_000_000 }),
+ "x",
+ );
+ assert.ok(seconds);
+ assert.equal(seconds.createdAt, 1_700_000_000_000);
+
+ const millis = openWebUIRecordToConversation(
+ {
+ chat: {
+ timestamp: 1_700_000_000_000,
+ history: historyOf([{ id: "m", parentId: null, role: "user", content: "hi" }], "m"),
+ },
+ },
+ "x",
+ );
+ assert.ok(millis);
+ assert.equal(millis.createdAt, 1_700_000_000_000);
+});
+
+test("a tool result stored as a plain string is kept, not flattened to nothing", () => {
+ // The Responses API documents `output` as a string OR a content array, and a
+ // string is what a tool returning text produces.
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ childrenIds: [],
+ role: "assistant",
+ content: "Lisbon is sunny.",
+ timestamp: 1,
+ output: [
+ { type: "function_call", call_id: "call_1", name: "web_search", arguments: '{"query":"lisbon"}' },
+ { type: "function_call_output", call_id: "call_1", output: '{"temp":"21C"}' },
+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const toolCall = parts(conversation, 0).find((part) => part.type === "tool-call");
+ assert.ok(toolCall);
+ assert.equal(toolCall.result, '{"temp":"21C"}');
+
+ // An orphan string output, with no call to attach it to, still shows as text.
+ const orphan = openWebUIRecordToConversation(
+ chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ output: [{ type: "function_call_output", call_id: "call_gone", output: "21C" }],
+ },
+ ],
+ "a",
+ ),
+ }),
+ "fallback",
+ );
+ assert.ok(orphan);
+ assert.equal(text(orphan, 0), "21C");
+});
+
+test("a user turn that uploaded a file without typing survives, and keeps its descendants", () => {
+ // Open WebUI sends an empty prompt with a file attached, so real exports
+ // contain turns whose only content is the upload.
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "u",
+ parentId: null,
+ childrenIds: ["a"],
+ role: "user",
+ content: "",
+ timestamp: 1,
+ files: [{ type: "file", id: "f1", name: "spec.pdf", url: "/api/v1/files/f1" }],
+ },
+ { id: "a", parentId: "u", childrenIds: [], role: "assistant", content: "It is a spec.", timestamp: 2 },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 2);
+ const attachments = conversation.messages[0]
+ .attachments as unknown as Array<Record<string, unknown>>;
+ assert.equal(attachments[0].name, "spec.pdf");
+ // The reply hangs off the upload, not off the root.
+ assert.equal(conversation.messages[1].parentId, conversation.messages[0].id);
+
+ // A turn that renders nothing at all is still dropped.
+ const failed = openWebUIRecordToConversation(
+ chatRecord({
+ history: historyOf([{ id: "u", parentId: null, role: "user", content: "", timestamp: 1 }], "u"),
+ }),
+ "fallback",
+ );
+ assert.equal(failed, null);
+});
+
+test("a chat thousands of messages deep converts instead of exhausting the call stack", () => {
+ // A long-running chat is one long parent chain, and a recursive walk of it
+ // throws RangeError, which would abort the whole export mid-stream.
+ const messages = Array.from({ length: 20_000 }, (_, index) => ({
+ id: `m${index}`,
+ parentId: index === 0 ? null : `m${index - 1}`,
+ role: index % 2 === 0 ? "user" : "assistant",
+ content: `turn ${index}`,
+ timestamp: index + 1,
+ }));
+ const conversation = openWebUIRecordToConversation(
+ chatRecord({ history: historyOf(messages, "m19999") }),
+ "fallback",
+ );
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 20_000);
+ assert.equal(text(conversation, 0), "turn 0");
+ assert.equal(text(conversation, 19_999), "turn 19999");
+});
+
+test("details markup a user typed stays text rather than becoming reasoning", () => {
+ const typed =
+ 'Why does this render oddly?\n<details type="reasoning" done="true">\n<summary>Thought</summary>\n> a plan\n</details>';
+ const conversation = openWebUIRecordToConversation(
+ chatRecord({
+ history: historyOf(
+ [
+ { id: "u", parentId: null, role: "user", content: typed, timestamp: 1 },
+ { id: "a", parentId: "u", role: "assistant", content: typed, timestamp: 2 },
+ ],
+ "a",
+ ),
+ }),
+ "fallback",
+ );
+ assert.ok(conversation);
+ assert.deepEqual(parts(conversation, 0), [{ type: "text", text: typed }]);
+ // The same markup written by Open WebUI's own assistant output still converts.
+ assert.equal(parts(conversation, 1).some((part) => part.type === "reasoning"), true);
+});
+
+test("a legacy flat chat drops repeated ids without rescanning what it already collected", () => {
+ const flat = Array.from({ length: 20_000 }, (_, index) => ({
+ id: `f${index % 19_000}`,
+ role: index % 2 === 0 ? "user" : "assistant",
+ content: `turn ${index}`,
+ timestamp: index + 1,
+ }));
+ const conversation = openWebUIRecordToConversation(chatRecord({ messages: flat }), "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 19_000);
+ assert.equal(conversation.messages[1].parentId, conversation.messages[0].id);
+});
+
+test("a prompt keeps the whitespace it was written with", () => {
+ // Leading indentation is a markdown code block, so trimming rewrites the prompt.
+ const indented = " const x = 1;\n const y = 2;\n";
+ const conversation = openWebUIRecordToConversation(
+ chatRecord({
+ history: historyOf(
+ [{ id: "u", parentId: null, role: "user", content: indented, timestamp: 1 }],
+ "u",
+ ),
+ }),
+ "fallback",
+ );
+ assert.ok(conversation);
+ assert.deepEqual(parts(conversation, 0), [{ type: "text", text: indented }]);
+});
+
+test("a legacy chat with no chat-level date is dated from its earliest message", () => {
+ const bare = {
+ title: "legacy",
+ history: historyOf(
+ [
+ { id: "m1", parentId: null, role: "user", content: "q", timestamp: 1_600_000_000 },
+ { id: "m2", parentId: "m1", role: "assistant", content: "a", timestamp: 1_600_000_060 },
+ ],
+ "m2",
+ ),
+ };
+
+ const conversation = openWebUIRecordToConversation(bare, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.createdAt, 1_600_000_000_000);
+ assert.equal(conversation.messages[0].createdAt, 1_600_000_000_000);
+ assert.equal(conversation.messages[1].createdAt, 1_600_000_060_000);
+});
+
+test("the assistant answer survives next to a tool result no call in this turn matched", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content: "It is sunny in Lisbon.",
+ // The call itself was recorded on the previous turn.
+ output: [{ type: "function_call_output", call_id: "call_earlier", output: "sunny, 21C" }],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.ok(text(conversation, 0).includes("sunny, 21C"));
+ assert.ok(text(conversation, 0).includes("It is sunny in Lisbon."));
+});
+
+test("an updated-only chat is still dated from its first message, not its last edit", () => {
+ const bare = {
+ updated_at: 1_600_100_000,
+ history: historyOf(
+ [
+ { id: "m1", parentId: null, role: "user", content: "q", timestamp: 1_600_000_000 },
+ { id: "m2", parentId: "m1", role: "assistant", content: "a", timestamp: 1_600_000_060 },
+ ],
+ "m2",
+ ),
+ };
+
+ const conversation = openWebUIRecordToConversation(bare, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.createdAt, 1_600_000_000_000);
+ assert.equal(conversation.messages[1].createdAt, 1_600_000_060_000);
+});
+
+test("a timestamped OpenAI conversation is not mistaken for an Open WebUI chat", () => {
+ // `timestamp` alone is generic; routing this record here would drop tool_calls.
+ const oaiToolConversation = {
+ messages: [
+ { role: "user", content: "weather?", timestamp: 1 },
+ { role: "assistant", content: "", tool_calls: [{ id: "c1", function: { name: "w", arguments: "{}" } }], timestamp: 2 },
+ { role: "tool", tool_call_id: "c1", content: "21C", timestamp: 3 },
+ ],
+ };
+ assert.equal(isOpenWebUIRecord(oaiToolConversation), false);
+ // Even when the exporter gave every message an id of its own.
+ assert.equal(
+ isOpenWebUIRecord({
+ messages: oaiToolConversation.messages.map((message, index) => ({ ...message, id: `m${index}` })),
+ }),
+ false,
+ );
+ // Open WebUI's own fields still identify a flat legacy chat.
+ assert.equal(
+ isOpenWebUIRecord({
+ messages: [{ role: "user", content: "hi", parentId: null, childrenIds: [], timestamp: 1 }],
+ }),
+ true,
+ );
+});
+
+test("a generated image comes over as an image, not as a dropped output item", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content: "Here it is.",
+ output: [
+ { type: "image_generation_call", id: "img_1", result: "AAAA", output_format: "png" },
+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Here it is." }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.deepEqual(
+ parts(conversation, 0).filter((part) => part.type === "image"),
+ [{ type: "image", image: "data:image/png;base64,AAAA" }],
+ );
+});
+
+test("a plain details block the model wrote keeps its markup", () => {
+ const answer = "Here:\n<details><summary>Spoiler</summary>secret</details>\nDone.";
+ const conversation = openWebUIRecordToConversation(
+ chatRecord({
+ history: historyOf(
+ [{ id: "a", parentId: null, role: "assistant", content: answer, timestamp: 1 }],
+ "a",
+ ),
+ }),
+ "fallback",
+ );
+ assert.ok(conversation);
+ assert.ok(text(conversation, 0).includes("<summary>Spoiler</summary>"));
+ assert.ok(text(conversation, 0).includes("Done."));
+});
+
+test("an empty history map falls back to the flat branch instead of dropping the chat", () => {
+ for (const messages of [{}, { m1: "not an object" }]) {
+ const conversation = openWebUIRecordToConversation(
+ chatRecord({
+ history: { messages, currentId: "m1" },
+ messages: [
+ { id: "m1", role: "user", content: "q", timestamp: 1 },
+ { id: "m2", role: "assistant", content: "a", timestamp: 2 },
+ ],
+ }),
+ "fallback",
+ );
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 2);
+ assert.equal(conversation.messages[1].parentId, conversation.messages[0].id);
+ }
+});
+
+test("built-in Responses tools import as tool parts rather than disappearing", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content: "Lisbon is sunny.",
+ output: [
+ {
+ type: "web_search_call",
+ id: "ws_1",
+ status: "completed",
+ action: { type: "search", query: "lisbon weather" },
+ },
+ { type: "shell_call", call_id: "sh_1", action: { type: "exec", commands: ["ls -la"] } },
+ { type: "shell_call_output", call_id: "sh_1", output: "total 0" },
+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const calls = parts(conversation, 0).filter((part) => part.type === "tool-call");
+ assert.deepEqual(
+ calls.map((call) => call.toolName),
+ ["web_search", "code_execution"],
+ );
+ assert.deepEqual(calls[0].args, { type: "search", query: "lisbon weather" });
+ assert.deepEqual(calls[1].args, { type: "exec", commands: ["ls -la"] });
+ assert.equal(calls[1].result, "total 0");
+});
+
+test("a multimodal turn keeps its text and image when detection routes it here", () => {
+ // Chat Completions records that carry a per-message id and timestamp satisfy
+ // isOpenWebUIRecord, and reading only string content dropped the whole turn.
+ const record = {
+ title: "vision",
+ messages: [
+ {
+ id: "1",
+ role: "user",
+ timestamp: 1_700_000_000,
+ content: [
+ { type: "text", text: "what is this" },
+ { type: "image_url", image_url: { url: "data:image/png;base64,AAA" } },
+ ],
+ },
+ { id: "2", role: "assistant", timestamp: 1_700_000_001, content: "a cat" },
+ ],
+ };
+
+ assert.equal(isOpenWebUIRecord(record), true);
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 2);
+ assert.equal(text(conversation, 0), "what is this");
+ assert.deepEqual(
+ parts(conversation, 0).map((part) => part.type),
+ ["text", "image"],
+ );
+ assert.equal(parts(conversation, 0)[1].image, "data:image/png;base64,AAA");
+ assert.equal(text(conversation, 1), "a cat");
+});
+
+test("hex and decimal character references in details attributes are decoded", () => {
+ // Open WebUI decodes these with a full html-entities pass, so an apostrophe
+ // arrives as &#x27; as readily as &#39; and both have to survive.
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content:
+ '<details type="tool_calls" done="true" id="c1" name="ask" ' +
+ 'arguments="{&quot;q&quot;: &quot;it&#x27;s ok&quot;}" ' +
+ 'result="{&quot;a&quot;: &quot;it&#39;s done&quot;}">\n' +
+ "<summary>Tool executed</summary>\n</details>\nfinished",
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const call = parts(conversation, 0).find((part) => part.type === "tool-call");
+ assert.ok(call);
+ assert.deepEqual(call.args, { q: "it's ok" });
+ assert.deepEqual(call.result, { a: "it's done" });
+});
+
+test("a doubly escaped ampersand survives one decoding pass as literal text", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content:
+ '<details type="tool_calls" done="true" id="c" name="n" ' +
+ 'arguments="{&quot;raw&quot;: &quot;&amp;#39;&quot;}">\n</details>',
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const call = parts(conversation, 0).find((part) => part.type === "tool-call");
+ assert.ok(call);
+ assert.deepEqual(call.args, { raw: "&#39;" });
+});
+
+test("an out of range timestamp is discarded rather than freezing the clock", () => {
+ // Past 2^53 `previousTs + 1` stops advancing, so every later message would
+ // land on one createdAt and the depth-first order would not survive a reload.
+ for (const stamp of [1e16, 1.7e18, Number.MAX_VALUE]) {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ { id: "u", parentId: null, role: "user", content: "q", timestamp: stamp },
+ { id: "a1", parentId: "u", role: "assistant", content: "one", timestamp: 0 },
+ { id: "a2", parentId: "a1", role: "user", content: "two", timestamp: 0 },
+ { id: "a3", parentId: "a2", role: "assistant", content: "three", timestamp: 0 },
+ ],
+ "a3",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const stamps = conversation.messages.map((message) => message.createdAt);
+ assert.equal(new Set(stamps).size, stamps.length, `duplicate stamps for ${stamp}`);
+ for (let i = 1; i < stamps.length; i++) {
+ assert.ok(stamps[i] > stamps[i - 1], `not increasing for ${stamp}`);
+ }
+ const last = stamps[stamps.length - 1];
+ assert.ok(
+ Number.isSafeInteger(last) && last <= 8.64e15,
+ `outside Date's range for ${stamp}`,
+ );
+ }
+
+ // A stamp inside the range is still honoured.
+ const ok = chatRecord({
+ history: historyOf(
+ [{ id: "u", parentId: null, role: "user", content: "q", timestamp: 1_700_000_000 }],
+ "u",
+ ),
+ });
+ const inRange = openWebUIRecordToConversation(ok, "f");
+ assert.ok(inRange);
+ assert.equal(inRange.messages[0].createdAt, 1_700_000_000_000);
+});
+
+test("a generated image given as a url is not wrapped into a broken data url", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ content: "",
+ timestamp: 1,
+ output: [
+ { type: "image_generation_call", result: "https://example.com/a.png" },
+ { type: "message", content: [{ type: "output_text", text: "there" }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const image = parts(conversation, 0).find((part) => part.type === "image");
+ assert.ok(image);
+ assert.equal(image.image, "https://example.com/a.png");
+});
+
+test("malformed tool arguments stay readable instead of posing as an args object", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content:
+ '<details type="tool_calls" done="true" id="c" name="n" arguments="not json">\n</details>',
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const call = parts(conversation, 0).find((part) => part.type === "tool-call");
+ assert.ok(call);
+ assert.equal(typeof call.args, "object");
+ assert.deepEqual(call.args, { arguments: "not json" });
+});
+
+test("a tool that returned only images carries no empty result body", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ content: "",
+ timestamp: 1,
+ output: [
+ { type: "function_call", call_id: "c1", name: "plot", arguments: "{}" },
+ {
+ type: "function_call_output",
+ call_id: "c1",
+ output: [{ type: "input_image", image_url: "data:image/png;base64,BBB" }],
+ },
+ { type: "message", content: [{ type: "output_text", text: "done" }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const call = parts(conversation, 0).find((part) => part.type === "tool-call");
+ assert.ok(call);
+ assert.equal(call.result, undefined);
+ assert.ok(parts(conversation, 0).some((part) => part.type === "image"));
+});
+
+test("a tool result keeps its text under any of the three part names, and portable image urls", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ output: [
+ { type: "function_call", call_id: "c1", name: "lookup", arguments: "{}" },
+ {
+ type: "function_call_output",
+ call_id: "c1",
+ output: [
+ { type: "output_text", text: "first" },
+ { type: "text", text: " second" },
+ { type: "input_text", text: " third" },
+ { type: "input_image", image_url: "https://example.com/chart.png" },
+ { type: "input_image", image_url: "/api/v1/files/local-only" },
+ ],
+ },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const [call] = parts(conversation, 0).filter((part) => part.type === "tool-call");
+ assert.equal(call.result, "first second third");
+ // The absolute url resolves anywhere; the Open WebUI route does not.
+ assert.deepEqual(
+ parts(conversation, 0).filter((part) => part.type === "image"),
+ [{ type: "image", image: "https://example.com/chart.png" }],
+ );
+});
+
+test("details markup inside a fence that was never closed stays code", () => {
+ // An answer interrupted mid-block still quotes the markup, it does not use it.
+ const cut =
+ 'Like this:\n```markdown\n<details type="reasoning" done="true">\n<summary>Thought</summary>\n> not mine\n</details>\n';
+ const conversation = openWebUIRecordToConversation(
+ chatRecord({
+ history: historyOf(
+ [{ id: "a", parentId: null, role: "assistant", content: cut, timestamp: 1 }],
+ "a",
+ ),
+ }),
+ "fallback",
+ );
+ assert.ok(conversation);
+ assert.equal(parts(conversation, 0).some((part) => part.type === "reasoning"), false);
+ assert.ok(text(conversation, 0).includes('<details type="reasoning"'));
+});
+
+test("a disconnected cycle does not displace the branch the user had open", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ { id: "u", parentId: null, role: "user", content: "question", timestamp: 1 },
+ { id: "a", parentId: "u", role: "assistant", content: "the answer", timestamp: 2 },
+ // A component reachable only through its own cycle.
+ { id: "c1", parentId: "c2", role: "user", content: "orphaned one", timestamp: 3 },
+ { id: "c2", parentId: "c1", role: "assistant", content: "orphaned two", timestamp: 4 },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.equal(conversation.messages.length, 4);
+ // Studio reopens on the last message, so it has to be the selected branch.
+ assert.equal(text(conversation, conversation.messages.length - 1), "the answer");
+});
+
+test("a stray inline fence does not swallow the tool calls after it", () => {
+ // Markdown opens a block fence only at the start of a line. Treating any
+ // unclosed ``` as one made a single mid-sentence backtick run quote the rest
+ // of the message, so every tool call after it was lost as literal markup.
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content:
+ "let me compute ```\n" +
+ '<details type="tool_calls" done="true" id="c1" name="calculator" ' +
+ 'arguments="{}" result="7">\n<summary>Tool Executed</summary>\n</details>\n' +
+ "the answer is 7",
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ const call = parts(conversation, 0).find((part) => part.type === "tool-call");
+ assert.ok(call, "the tool call was swallowed by the stray fence");
+ assert.equal(call.toolName, "calculator");
+ assert.equal(call.result, 7);
+});
+
+test("a reasoning block quoting one backtick run keeps the next tool call", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ content:
+ '<details type="reasoning" done="true">\n<summary>Thought</summary>\n' +
+ "> the user asked about ```\n</details>\n" +
+ '<details type="tool_calls" done="true" id="c9" name="real_tool" ' +
+ 'arguments="{}" result="42">\n<summary>Tool Executed</summary>\n</details>\n' +
+ "final answer",
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.deepEqual(
+ parts(conversation, 0).map((part) => part.type),
+ ["reasoning", "tool-call", "text"],
+ );
+});
+
+test("reasoning survives an empty summary next to populated content", () => {
+ const record = chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ output: [
+ // Summaries off: the array is present but empty.
+ { type: "reasoning", id: "rs_1", summary: [], content: [{ type: "reasoning_text", text: "weighed it up" }] },
+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Done." }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ });
+
+ const conversation = openWebUIRecordToConversation(record, "fallback");
+ assert.ok(conversation);
+ assert.deepEqual(
+ parts(conversation, 0).filter((part) => part.type === "reasoning"),
+ [{ type: "reasoning", text: "weighed it up" }],
+ );
+ // A populated summary still wins over content.
+ const both = openWebUIRecordToConversation(
+ chatRecord({
+ history: historyOf(
+ [
+ {
+ id: "a",
+ parentId: null,
+ role: "assistant",
+ timestamp: 1,
+ output: [
+ { type: "reasoning", summary: [{ type: "summary_text", text: "the summary" }], content: [{ type: "reasoning_text", text: "the raw trace" }] },
+ ],
+ },
+ ],
+ "a",
+ ),
+ }),
+ "fallback",
+ );
+ assert.ok(both);
+ assert.deepEqual(parts(both, 0), [{ type: "reasoning", text: "the summary" }]);
+});
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index c6ad268faf1..dc86906b7bc 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -1519,6 +1519,7 @@ fn main() {
.manage(new_backend_state())
.manage(process::new_shutdown_flag())
.manage(update::new_update_state())
+ .manage(native_file_dialogs::ChatImportRegistry::default())
.invoke_handler(tauri::generate_handler![
set_training_active,
set_renderer_activity,
@@ -1552,6 +1553,7 @@ fn main() {
native_file_dialogs::save_native_file,
native_file_dialogs::save_native_file_from_url,
native_file_dialogs::pick_native_chat_import,
+ native_file_dialogs::read_native_chat_import_chunk,
native_file_dialogs::pick_native_training_config,
native_intents::drain_native_intents,
native_intents::register_native_model_path,
diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rs
index e4ef7d03db7..562be94dd79 100644
--- a/studio/src-tauri/src/native_file_dialogs.rs
+++ b/studio/src-tauri/src/native_file_dialogs.rs
@@ -3,16 +3,20 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use serde::Serialize;
use std::borrow::Cow;
use std::fs::{self, File};
-use std::io::{Read, Write};
+use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
use std::time::Duration;
-use tauri::{AppHandle, WebviewWindow};
+use tauri::{AppHandle, Manager, State, WebviewWindow};
use tauri_plugin_dialog::DialogExt;
-const MAX_CHAT_IMPORT_BYTES: u64 = 64 * 1024 * 1024;
const MAX_TRAINING_CONFIG_BYTES: u64 = 1024 * 1024;
+/// Per redeemed range, not per file: the frontend streams a large import in
+/// 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] = &["jsonl", "ndjson", "csv"];
+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 TRAINING_CONFIG_EXTENSIONS: &[&str] = &["yaml", "yml"];
#[derive(Debug, Serialize)]
@@ -22,6 +26,49 @@ pub struct NativeImportedFile {
content: String,
}
+/// A picked chat import addressed by an opaque token instead of a path.
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NativeChatImport {
+ name: String,
+ size: u64,
+ token: String,
+}
+
+/// Keep active handles valid while bounding registry growth.
+const CHAT_IMPORT_HANDLE_LIMIT: usize = 8;
+
+#[derive(Default)]
+pub struct ChatImportRegistry {
+ /// Oldest first, so the eviction below drops the least recent pick.
+ files: Mutex<Vec<(String, PathBuf, Arc<Mutex<File>>)>>,
+}
+
+impl ChatImportRegistry {
+ /// Holds the file the picker opened, not just its path. Resolving a path
+ /// again per range would read whatever occupies it by then, so a file
+ /// replaced mid-import could splice its bytes into the stream.
+ fn register(&self, path: PathBuf, file: File) -> String {
+ let token: String = (0..4)
+ .map(|_| format!("{:016x}", rand::random::<u64>()))
+ .collect();
+ let mut files = self.files.lock().expect("chat import registry poisoned");
+ files.push((token.clone(), path, Arc::new(Mutex::new(file))));
+ while files.len() > CHAT_IMPORT_HANDLE_LIMIT {
+ files.remove(0);
+ }
+ token
+ }
+
+ fn resolve(&self, token: &str) -> Option<(PathBuf, Arc<Mutex<File>>)> {
+ let files = self.files.lock().expect("chat import registry poisoned");
+ files
+ .iter()
+ .find(|(candidate, _, _)| candidate == token)
+ .map(|(_, path, file)| (path.clone(), Arc::clone(file)))
+ }
+}
+
fn default_file_name(suggested_name: &str) -> String {
Path::new(suggested_name)
.file_name()
@@ -245,17 +292,48 @@ fn read_selected_text_import(
Ok(Some(NativeImportedFile { name, content }))
}
-fn read_selected_import(
+/// Register a picked file for bounded range reads through an opaque token.
+fn open_selected_import(
+ registry: &ChatImportRegistry,
selected_path: Option<PathBuf>,
-) -> Result<Option<NativeImportedFile>, String> {
- read_selected_text_import(
- selected_path,
- "Chat import",
- CHAT_IMPORT_EXTENSIONS,
- ".jsonl, .ndjson, or .csv",
- "chat-import",
- MAX_CHAT_IMPORT_BYTES,
- )
+) -> Result<Option<NativeChatImport>, String> {
+ let Some(path) = selected_path else {
+ return Ok(None);
+ };
+ let extension = path
+ .extension()
+ .and_then(|extension| extension.to_str())
+ .map(str::to_ascii_lowercase)
+ .ok_or_else(|| CHAT_IMPORT_TYPE_ERROR.to_string())?;
+ if !CHAT_IMPORT_EXTENSIONS.contains(&extension.as_str()) {
+ return Err(CHAT_IMPORT_TYPE_ERROR.to_string());
+ }
+
+ let metadata = fs::metadata(&path)
+ .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?;
+ if !metadata.is_file() {
+ return Err(format!("Chat import is not a file: {}", path.display()));
+ }
+
+ let name = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .map(str::to_string)
+ .unwrap_or_else(|| format!("chat-import.{extension}"));
+ let file =
+ File::open(&path).map_err(|error| format!("Failed to open {}: {error}", path.display()))?;
+ // Size from the handle the token keeps, not from the path: a file swapped in
+ // between the two describes a different object, and this number is what
+ // bounds the streamed read.
+ let opened = file
+ .metadata()
+ .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?;
+ if !opened.is_file() {
+ return Err(format!("Chat import is not a file: {}", path.display()));
+ }
+ let size = opened.len();
+ let token = registry.register(path, file);
+ Ok(Some(NativeChatImport { name, size, token }))
}
fn read_selected_training_config(
@@ -383,11 +461,56 @@ async fn stream_url_to_path(url: &str, path: &Path, read_timeout: Duration) -> R
Ok(())
}
+fn read_range(
+ handle: &Arc<Mutex<File>>,
+ path: &Path,
+ offset: u64,
+ length: usize,
+) -> Result<Vec<u8>, String> {
+ // Clamped here rather than only at the call site, so the bound holds for
+ // every caller: `take` was reading past it while only the allocation was
+ // capped, which left the read itself unbounded.
+ let length = length.min(MAX_CHAT_IMPORT_CHUNK_BYTES);
+ let mut file = handle
+ .lock()
+ .map_err(|_| format!("Failed to read {}: handle poisoned", path.display()))?;
+ file.seek(SeekFrom::Start(offset))
+ .map_err(|error| format!("Failed to read {}: {error}", path.display()))?;
+ let mut bytes = Vec::with_capacity(length);
+ Read::by_ref(&mut *file)
+ .take(length as u64)
+ .read_to_end(&mut bytes)
+ .map_err(|error| format!("Failed to read {}: {error}", path.display()))?;
+ Ok(bytes)
+}
+
+/// Read raw bytes so the frontend can decode UTF-8 across range boundaries.
+#[tauri::command]
+pub async fn read_native_chat_import_chunk(
+ app: AppHandle,
+ token: String,
+ offset: u64,
+ length: usize,
+) -> Result<tauri::ipc::Response, String> {
+ let registry = app.state::<ChatImportRegistry>();
+ let (path, handle) = registry
+ .resolve(&token)
+ .ok_or_else(|| "That import is no longer available -- pick the file again.".to_string())?;
+
+ let length = length.min(MAX_CHAT_IMPORT_CHUNK_BYTES);
+ // Off the async runtime: an import is tens of these reads back to back.
+ let bytes = tokio::task::spawn_blocking(move || read_range(&handle, &path, offset, length))
+ .await
+ .map_err(|error| format!("Failed to read the import: {error}"))??;
+ Ok(tauri::ipc::Response::new(bytes))
+}
+
#[tauri::command]
pub async fn pick_native_chat_import(
window: WebviewWindow,
app: AppHandle,
-) -> Result<Option<NativeImportedFile>, String> {
+ registry: State<'_, ChatImportRegistry>,
+) -> Result<Option<NativeChatImport>, String> {
crate::native_intents::ensure_main_window(&window)?;
let (tx, rx) = tokio::sync::oneshot::channel();
app.dialog()
@@ -402,7 +525,7 @@ pub async fn pick_native_chat_import(
.map_err(|_| "Import dialog closed unexpectedly.".to_string())?
.map(local_dialog_path)
.transpose()?;
- read_selected_import(selected_path)
+ open_selected_import(&registry, selected_path)
}
#[tauri::command]
@@ -458,7 +581,8 @@ mod tests {
#[test]
fn cancellation_is_quiet_for_save_and_import() {
assert!(save_selected_file(None, b"x").unwrap().is_none());
- assert!(read_selected_import(None).unwrap().is_none());
+ let registry = ChatImportRegistry::default();
+ assert!(open_selected_import(&registry, None).unwrap().is_none());
}
#[test]
@@ -733,20 +857,26 @@ mod tests {
}
#[test]
- fn reads_supported_import_and_rejects_other_extensions() {
+ fn opens_supported_imports_and_rejects_other_extensions() {
+ let registry = ChatImportRegistry::default();
let jsonl_path = temp_path("allowed").with_extension("JSONL");
fs::write(&jsonl_path, "{\"messages\":[]}").unwrap();
- let imported = read_selected_import(Some(jsonl_path.clone()))
+ let opened = open_selected_import(&registry, Some(jsonl_path.clone()))
.unwrap()
.unwrap();
- assert_eq!(imported.content, "{\"messages\":[]}");
+ assert_eq!(opened.size, 15);
+ assert_eq!(registry.resolve(&opened.token).unwrap().0, jsonl_path);
+
+ // An Open WebUI export is a .json array, so that extension has to be accepted now.
+ let json_path = temp_path("openwebui").with_extension("json");
+ fs::write(&json_path, "[{\"chat\":{}}]").unwrap();
+ assert!(open_selected_import(&registry, Some(json_path.clone()))
+ .unwrap()
+ .is_some());
- let json_path = temp_path("unsupported").with_extension("json");
- fs::write(&json_path, "{}").unwrap();
- assert!(read_selected_import(Some(json_path.clone())).is_err());
let txt_path = temp_path("denied").with_extension("txt");
fs::write(&txt_path, "no").unwrap();
- assert!(read_selected_import(Some(txt_path.clone()))
+ assert!(open_selected_import(&registry, Some(txt_path.clone()))
.unwrap_err()
.contains(".json"));
let _ = fs::remove_file(jsonl_path);
@@ -777,21 +907,106 @@ mod tests {
}
#[test]
- fn read_limit_and_utf8_errors_are_concrete() {
- let oversized = temp_path("oversized").with_extension("csv");
- let file = File::create(&oversized).unwrap();
- file.set_len(MAX_CHAT_IMPORT_BYTES + 1).unwrap();
- assert!(read_selected_import(Some(oversized.clone()))
- .unwrap_err()
- .contains("too large"));
+ fn a_large_import_is_opened_rather_than_read_into_memory() {
+ // The 64 MiB read cap is what turned a real Open WebUI export away; a
+ // file past it must now open, because the frontend streams it in ranges.
+ let registry = ChatImportRegistry::default();
+ let huge = temp_path("huge").with_extension("json");
+ let file = File::create(&huge).unwrap();
+ file.set_len(600 * 1024 * 1024).unwrap();
+ let opened = open_selected_import(&registry, Some(huge.clone()))
+ .unwrap()
+ .unwrap();
+ assert_eq!(opened.size, 600 * 1024 * 1024);
- let invalid = temp_path("invalid-utf8").with_extension("jsonl");
- fs::write(&invalid, [0xff]).unwrap();
- assert!(read_selected_import(Some(invalid.clone()))
+ let directory = temp_path("import-directory").with_extension("json");
+ fs::create_dir(&directory).unwrap();
+ assert!(open_selected_import(&registry, Some(directory.clone()))
.unwrap_err()
- .contains("UTF-8"));
- let _ = fs::remove_file(oversized);
- let _ = fs::remove_file(invalid);
+ .starts_with("Chat import is not a file:"));
+ let _ = fs::remove_file(huge);
+ let _ = fs::remove_dir(directory);
+ }
+
+ fn register_for_test(registry: &ChatImportRegistry, path: &Path) -> String {
+ registry.register(path.to_path_buf(), File::open(path).unwrap())
+ }
+
+ #[test]
+ fn ranges_are_readable_only_through_a_token_the_picker_issued() {
+ let registry = ChatImportRegistry::default();
+ let path = temp_path("ranges").with_extension("jsonl");
+ fs::write(&path, "0123456789").unwrap();
+
+ let token = register_for_test(&registry, &path);
+ let (resolved, handle) = registry.resolve(&token).unwrap();
+ assert_eq!(resolved, path);
+ assert!(registry.resolve("not-a-token").is_none());
+
+ // Ranges are cut on byte boundaries, so a character split across two of
+ // them is the frontend decoder's problem, not a truncated read here.
+ assert_eq!(read_range(&handle, &path, 0, 4).unwrap(), b"0123");
+ assert_eq!(read_range(&handle, &path, 4, 4).unwrap(), b"4567");
+ assert_eq!(read_range(&handle, &path, 8, 4).unwrap(), b"89");
+ assert!(read_range(&handle, &path, 10, 4).unwrap().is_empty());
+
+ // Picking again must not invalidate the earlier handle: that import can
+ // still be streaming, and its next range read would fail mid-history.
+ let second = temp_path("ranges-2").with_extension("jsonl");
+ fs::write(&second, "abc").unwrap();
+ let newer = register_for_test(&registry, &second);
+ assert_eq!(registry.resolve(&token).unwrap().0, path);
+ assert_eq!(registry.resolve(&newer).unwrap().0, second);
+ assert_ne!(token, newer);
+
+ // A hostile length cannot read past one chunk, whatever the caller passes.
+ let big = temp_path("ranges-clamp").with_extension("jsonl");
+ fs::write(&big, vec![b'x'; MAX_CHAT_IMPORT_CHUNK_BYTES + 4096]).unwrap();
+ let big_token = register_for_test(&registry, &big);
+ let (big_path, big_handle) = registry.resolve(&big_token).unwrap();
+ assert_eq!(
+ read_range(&big_handle, &big_path, 0, usize::MAX)
+ .unwrap()
+ .len(),
+ MAX_CHAT_IMPORT_CHUNK_BYTES
+ );
+ let _ = fs::remove_file(big);
+
+ // The map is bounded, so a long session cannot accumulate handles.
+ for index in 0..CHAT_IMPORT_HANDLE_LIMIT {
+ let filler = temp_path(&format!("ranges-fill-{index}")).with_extension("jsonl");
+ fs::write(&filler, "x").unwrap();
+ register_for_test(&registry, &filler);
+ let _ = fs::remove_file(filler);
+ }
+ assert!(registry.resolve(&token).is_none());
+
+ let _ = fs::remove_file(path);
+ let _ = fs::remove_file(second);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_file_swapped_under_the_path_mid_import_cannot_reach_the_stream() {
+ // Reopening the path per range would splice a replacement file into the
+ // export, and a same-size swap leaves no short read to catch it.
+ let registry = ChatImportRegistry::default();
+ let path = temp_path("swapped").with_extension("jsonl");
+ fs::write(&path, "original--").unwrap();
+ let token = register_for_test(&registry, &path);
+
+ let replacement = temp_path("swapped-other").with_extension("jsonl");
+ fs::write(&replacement, "replaced--").unwrap();
+ fs::rename(&replacement, &path).unwrap();
+
+ let (resolved, handle) = registry.resolve(&token).unwrap();
+ assert_eq!(
+ read_range(&handle, &resolved, 0, 10).unwrap(),
+ b"original--"
+ );
+ assert_eq!(fs::read(&path).unwrap(), b"replaced--");
+
+ let _ = fs::remove_file(path);
}
#[cfg(unix)]
@@ -810,8 +1025,11 @@ mod tests {
if fs::write(&path, "role,content\nuser,hello\n").is_err() {
return;
}
- let imported = read_selected_import(Some(path.clone())).unwrap().unwrap();
- assert_eq!(imported.name, "chat-import.csv");
+ let registry = ChatImportRegistry::default();
+ let opened = open_selected_import(&registry, Some(path.clone()))
+ .unwrap()
+ .unwrap();
+ assert_eq!(opened.name, "chat-import.csv");
let _ = fs::remove_file(path);
}
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index 946e80c1187..cb249d74d0d 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -199,10 +199,11 @@ def test_file_actions_route_through_native_commands_only_in_tauri():
assert "if (!isTauri)" in projects
# Browser builds retain the existing hidden-input route.
assert 'type="file"' in data_tab
- assert 'accept=".jsonl,.ndjson,.csv"' in data_tab
+ # Open WebUI exports are .json arrays, so the picker takes that too.
+ assert 'accept=".json,.jsonl,.ndjson,.csv"' in data_tab
native_dialogs = NATIVE_DIALOGS.read_text(encoding = "utf-8")
- assert 'CHAT_IMPORT_EXTENSIONS: &[&str] = &["jsonl", "ndjson", "csv"]' in native_dialogs
+ assert 'CHAT_IMPORT_EXTENSIONS: &[&str] = &["json", "jsonl", "ndjson", "csv"]' in native_dialogs
assert "InvokeBody::Raw" in native_dialogs
assert ".tempfile_in(parent)" in native_dialogs