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: stop Export all chats from saving an empty or stale backup (#16930)

Nilay7e0143e1ced9
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 248ab1a712e..0ac363efc66 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1540,7 +1540,11 @@ export async function buildBackendChatExport(): Promise<{
messages: MessageRecord[];
}> {
const response = await authFetch("/api/chat/export");
- return parseJsonOrThrow(response);
+ const data = await parseJsonOrThrow<Awaited<
+ ReturnType<typeof buildBackendChatExport>
+ > | null>(response);
+ if (!data) throw new Error("The chat export did not download completely.");
+ return data;
}
// Server-side legacy-Dexie import ledger, so a studio.db wipe keeps the import recoverable.
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index 8e6a90b713f..55cf98161ab 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -1359,29 +1359,21 @@ export async function buildStoredChatExport(): Promise<ExportedChat> {
const [legacyThreads, legacyMessages] = await readLegacyStore<
[ThreadRecord[], MessageRecord[]]
>(() => Promise.all([db.threads.toArray(), db.messages.toArray()]), [[], []]);
- const hasLegacyData =
- legacyThreads.some((thread) => !isChatThreadDeleted(thread.id)) ||
- legacyMessages.some((message) => !isChatThreadDeleted(message.threadId));
- const backend = await buildBackendChatExport().catch((error) => {
- if (hasLegacyData) {
- return null;
- }
- throw error;
- });
+ const backend = await buildBackendChatExport();
const threadsById = new Map<string, unknown>();
const backendThreadIds = new Set<string>();
const messagesById = new Map<string, unknown>();
- for (const thread of backend?.threads ?? []) {
+ for (const thread of backend.threads) {
if (isChatThreadDeleted(thread.id)) continue;
backendThreadIds.add(thread.id);
threadsById.set(thread.id, thread);
}
- for (const message of backend?.messages ?? []) {
+ for (const message of backend.messages) {
if (isChatThreadDeleted(message.threadId)) continue;
messagesById.set(message.id, message);
}
- const includeLegacyOnly = backend === null || !isLegacyChatImportDone();
+ const includeLegacyOnly = !isLegacyChatImportDone();
for (const thread of legacyThreads as ThreadRecord[]) {
if (
isChatThreadDeleted(thread.id) ||
@@ -1408,7 +1400,7 @@ export async function buildStoredChatExport(): Promise<ExportedChat> {
exportedAt: new Date().toISOString(),
version: 1,
threadCount: threads.length,
- projects: backend?.projects ?? [],
+ projects: backend.projects ?? [],
threads,
messages,
};
diff --git a/studio/frontend/tests/chat-export-unreadable-backend.test.ts b/studio/frontend/tests/chat-export-unreadable-backend.test.ts
new file mode 100644
index 00000000000..d5f0eafabde
--- /dev/null
+++ b/studio/frontend/tests/chat-export-unreadable-backend.test.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { MessageRecord, ThreadRecord } from "../src/features/chat/types";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+import { skillLoadCardEvent } from "../src/features/chat/api/skill-load-event.ts";
+
+function loadChatApi(response: Response) {
+ return loadWithStubs<{ buildBackendChatExport: () => Promise<unknown> }>(
+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
+ {
+ "./skill-load-event": { skillLoadCardEvent },
+ "./thread-read-cache.ts": loadWithStubs(
+ new URL("../src/features/chat/api/thread-read-cache.ts", import.meta.url),
+ {},
+ ),
+ "@/features/auth": { authFetch: async () => response },
+ "@/lib/format-fastapi-error": { formatApiErrorBody: () => null },
+ "../types": {},
+ "../types/api": {},
+ "../utils/chat-history-revision": {
+ notifyChatHistoryUpdated: () => {},
+ isCoalescedHistoryEvent: () => false,
+ },
+ "../utils/openapi-support": { readAdvertisedPatchGuards: () => null },
+ "../utils/load-warning-toast": { showLoadWarning: () => {} },
+ "../lib/load-request": {},
+ "./generation-length.ts": {},
+ "./gguf-variants-request": {},
+ "./padded-response": { assertCompletedPaddedBody: () => {} },
+ "@/features/hf-auth": { prepareHfTokenForUse: async () => undefined },
+ "@/features/igpu-carveout": {
+ dismissCarveoutAdviceForModel: () => {},
+ showCarveoutAdvice: () => {},
+ },
+ "@/features/hub/lib/abort-signals": {
+ disposableTimeoutSignal: () => ({ signal: new AbortController().signal, dispose: () => {} }),
+ },
+ "@/features/hub/lib/hub-token-header": { hubTokenHeader: () => ({}) },
+ "@/features/hub/lib/network": { isHuggingFaceOffline: () => false },
+ "@/features/native-intents/api": { consumeNativePathToken: () => undefined },
+ "@/features/settings/low-disk-check": { checkDiskSpace: () => Promise.resolve() },
+ "@/lib/model-lifecycle-events": {},
+ },
+ );
+}
+
+const legacyThread = { id: "old-legacy", title: "Old browser chat" } as ThreadRecord;
+const legacyMessage = {
+ id: "old-message",
+ threadId: "old-legacy",
+ role: "user",
+ content: [{ type: "text", text: "hi" }],
+ createdAt: 1,
+} as MessageRecord;
+
+function loadStorage(buildBackendChatExport: () => Promise<unknown>) {
+ return loadWithStubs<{ buildStoredChatExport: () => Promise<{ threadCount: number }> }>(
+ new URL("../src/features/chat/utils/chat-history-storage.ts", import.meta.url),
+ {
+ "../api/chat-api": {
+ ChatThreadDeletedError: class extends Error {},
+ buildBackendChatExport,
+ notifyChatHistoryUpdated: () => {},
+ },
+ "../db": {
+ DEXIE_DB_NAME: "unsloth-chat",
+ db: {
+ threads: { toArray: async () => [legacyThread] },
+ messages: { toArray: async () => [legacyMessage] },
+ transaction: async () => undefined,
+ },
+ },
+ "./chat-thread-tombstones": {
+ isChatThreadDeleted: () => false,
+ markChatThreadDeleted: () => {},
+ markChatThreadsDeleted: () => {},
+ },
+ "./thread-record-write-coordinator": {
+ ThreadRecordWriteCoordinator: class {},
+ },
+ "../stores/fork-boundary-store": { setForkBoundary: () => {} },
+ },
+ );
+}
+
+test("a chat export whose body cannot be read fails instead of saving no chats", async () => {
+ const api = loadChatApi(
+ new Response('{"exportedAt":"2026-11-06T00:00:00Z","threads":[{"id":"t1"', {
+ status: 200,
+ }),
+ );
+ await assert.rejects(api.buildBackendChatExport());
+});
+
+test("a failed server export fails instead of saving only old browser chats", async () => {
+ const storage = loadStorage(async () => {
+ throw new Error("Request failed (500)");
+ });
+ await assert.rejects(storage.buildStoredChatExport(), /500/);
+});