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: let a temporary chat be saved to history (#11901)

Michael Han3757ea8b57f4
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 9bb9a093d9c..4df7b3c664d 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -110,6 +110,10 @@ import {
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate } from "@tanstack/react-router";
+import {
+ SaveTemporaryChatButton,
+ TemporaryChatSaveBridge,
+} from "./components/temporary-chat-save";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import {
type CSSProperties,
@@ -4242,6 +4246,9 @@ export function ChatPage({
className="h-[var(--studio-chat-control-height,34px)]"
/>
) : null}
+ {view.mode === "single" && incognito ? (
+ <SaveTemporaryChatButton className="mr-[calc(6px*var(--ui-space-scale,1))] flex size-[calc(30px*var(--ui-space-scale,1))] cursor-pointer items-center justify-center rounded-[10px] text-nav-fg transition-colors hover:bg-nav-surface-hover hover:text-black focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:hover:text-white" />
+ ) : null}
{view.mode === "single" && (
<Tooltip>
<TooltipPrimitive.Trigger asChild={true}>
@@ -4398,6 +4405,7 @@ export function ChatPage({
<NativeAttachmentTargetContext.Provider
value={baseAttachmentTargetKey}
>
+ <TemporaryChatSaveBridge />
<SingleContent
threadId={baseView.threadId}
artifact={selectedArtifact}
diff --git a/studio/frontend/src/features/chat/components/temporary-chat-save.tsx b/studio/frontend/src/features/chat/components/temporary-chat-save.tsx
new file mode 100644
index 00000000000..964945d2eec
--- /dev/null
+++ b/studio/frontend/src/features/chat/components/temporary-chat-save.tsx
@@ -0,0 +1,203 @@
+// 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 {
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Tooltip, TooltipContent } from "@/components/ui/tooltip";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import { useAui, useAuiState } from "@assistant-ui/react";
+import { Bookmark02Icon, Cancel01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Tooltip as TooltipPrimitive } from "radix-ui";
+import { useEffect, useId, useState } from "react";
+import { create } from "zustand";
+import { persistTemporaryThread } from "../runtime-provider";
+import { useChatRuntimeStore } from "../stores/chat-runtime-store";
+import { usePromptQueueUI } from "../stores/prompt-queue-ui-store";
+import { isThreadIncognito } from "../utils/chat-history-storage";
+
+/** Skip the confirmation once the user said so. Per browser. */
+export const SKIP_SAVE_TEMPORARY_CONFIRM_KEY = "unsloth_chat_skip_save_temporary_confirm";
+
+function skipConfirm(): boolean {
+ try {
+ return localStorage.getItem(SKIP_SAVE_TEMPORARY_CONFIRM_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+function rememberSkipConfirm(): void {
+ try {
+ localStorage.setItem(SKIP_SAVE_TEMPORARY_CONFIRM_KEY, "1");
+ } catch {
+ // Private mode: the popup just keeps showing.
+ }
+}
+
+type SaveTarget = {
+ hasMessages: boolean;
+ running: boolean;
+ queued: boolean;
+ save: () => Promise<void>;
+};
+
+/** The open temporary chat, published from inside its runtime for the header, which sits outside. */
+const useSaveTarget = create<{ target: SaveTarget | null }>(() => ({ target: null }));
+
+/** Mount inside the single-chat runtime. */
+export function TemporaryChatSaveBridge() {
+ const aui = useAui();
+ const incognito = useChatRuntimeStore((s) => s.incognito);
+ const remoteId = useAuiState(({ threadListItem }) => threadListItem.remoteId);
+ const hasMessages = useAuiState(({ thread }) => thread.messages.length > 0);
+ const running = useAuiState(({ thread }) => thread.isRunning);
+ // A queue keeps its temporary tag, so leaving a saved chat would still discard it.
+ const queued = usePromptQueueUI((s) =>
+ Object.values(s.byThreadId).some((entry) => entry.temporary),
+ );
+
+ useEffect(() => {
+ if (!incognito) return;
+ useSaveTarget.setState({
+ target: {
+ hasMessages: hasMessages && Boolean(remoteId),
+ running,
+ queued,
+ save: async () => {
+ const threadId = aui.threadListItem().getState().remoteId;
+ if (!threadId || !isThreadIncognito(threadId)) return;
+ await persistTemporaryThread({
+ threadId,
+ modelType: "base",
+ messages: aui.thread().export().messages,
+ });
+ useChatRuntimeStore.getState().setIncognito(false);
+ aui.threadListItem().generateTitle();
+ },
+ },
+ });
+ return () => useSaveTarget.setState({ target: null });
+ }, [aui, incognito, remoteId, hasMessages, running, queued]);
+
+ return null;
+}
+
+/** Header button left of the temporary toggle, shown only in a temporary chat. */
+export function SaveTemporaryChatButton({ className }: { className?: string }) {
+ const target = useSaveTarget((s) => s.target);
+ const [open, setOpen] = useState(false);
+ const [dontShowAgain, setDontShowAgain] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const checkboxId = useId();
+
+ if (!target) return null;
+ const disabledReason = !target.hasMessages
+ ? "Nothing to save yet"
+ : target.running
+ ? "Wait for the response to finish"
+ : target.queued
+ ? "Wait for queued prompts to finish"
+ : null;
+ const label = disabledReason ?? "Save chat to history";
+
+ const save = async () => {
+ setSaving(true);
+ try {
+ await target.save();
+ if (dontShowAgain) rememberSkipConfirm();
+ setOpen(false);
+ toast.success("Chat saved to history");
+ } catch (error) {
+ toast.error("Could not save chat", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <>
+ <Tooltip>
+ <TooltipPrimitive.Trigger asChild={true}>
+ <button
+ type="button"
+ onClick={() => {
+ if (disabledReason || saving) return;
+ if (skipConfirm()) void save();
+ else setOpen(true);
+ }}
+ aria-disabled={Boolean(disabledReason) || saving}
+ className={cn(className, (disabledReason || saving) && "cursor-default opacity-50")}
+ aria-label={label}
+ >
+ <HugeiconsIcon icon={Bookmark02Icon} strokeWidth={1.75} className="size-icon" />
+ </button>
+ </TooltipPrimitive.Trigger>
+ <TooltipContent side="bottom" sideOffset={6} className="tooltip-compact">
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ <AlertDialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!saving) setOpen(next);
+ if (!next) setDontShowAgain(false);
+ }}
+ >
+ <AlertDialogContent size="sm" className="gap-4 py-5">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="absolute top-3 right-3"
+ aria-label="Close"
+ onClick={() => setOpen(false)}
+ disabled={saving}
+ >
+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} />
+ </Button>
+ <AlertDialogHeader>
+ <AlertDialogMedia className="bg-primary/15 text-primary mb-1 size-11">
+ <HugeiconsIcon icon={Bookmark02Icon} strokeWidth={2} className="size-5" />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Save this chat to history?</AlertDialogTitle>
+ <AlertDialogDescription>
+ All messages in this conversation, including earlier messages, will be saved to your
+ chat history. New messages will also be saved.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={saving}>Keep temporary</AlertDialogCancel>
+ <Button onClick={() => void save()} disabled={saving}>
+ {saving ? "Saving…" : "Save chat"}
+ </Button>
+ </AlertDialogFooter>
+ <label
+ htmlFor={checkboxId}
+ className="text-muted-foreground flex cursor-pointer items-center justify-center gap-2 text-sm"
+ >
+ <Checkbox
+ id={checkboxId}
+ checked={dontShowAgain}
+ onCheckedChange={(checked) => setDontShowAgain(checked === true)}
+ disabled={saving}
+ />
+ Don&apos;t show this again
+ </label>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 54632af7eab..0f948e2a00f 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -156,7 +156,9 @@ import {
markThreadIncognito,
saveStoredChatMessage,
saveStoredChatThread,
+ syncStoredChatMessages,
trackStoredChatThreadRecord,
+ unmarkThreadIncognito,
updateStoredChatThread,
} from "./utils/chat-history-storage";
import {
@@ -1250,6 +1252,12 @@ function scheduleGenerationRecovery(
generationRecoveries.set(runId, { promise: recovery, views });
}
+/** What a temporary thread was started with, so saving it later keeps its starting model. */
+const temporaryThreadCreation = new Map<
+ string,
+ { modelId: string; modelGgufVariant: string | null | undefined; createdAt: number }
+>();
+
export async function ensureThreadRecord({
threadId,
modelType,
@@ -1292,8 +1300,14 @@ export async function ensureThreadRecord({
// A temporary chat skips the history list so a storage outage cannot block its first send.
// Gated on the caller knowing the thread is new, not on its id: a `__LOCALID_` id is the
// permanent key of every chat the app creates, so keying on the prefix tagged SAVED chats.
+ const creation = {
+ modelId: modelIdAtInit,
+ modelGgufVariant: modelGgufVariantAtInit,
+ createdAt: createdAtInit,
+ };
if (incognitoAtInit && neverSent) {
markThreadIncognito(threadId);
+ temporaryThreadCreation.set(threadId, creation);
return;
}
// A point lookup, not a listing: this must not scale with how many chats exist.
@@ -1305,6 +1319,7 @@ export async function ensureThreadRecord({
// real chat saving normally when the toggle flips on mid-stream.
if (incognitoAtInit) {
markThreadIncognito(threadId);
+ temporaryThreadCreation.set(threadId, creation);
return;
}
@@ -1335,6 +1350,79 @@ export async function ensureThreadRecord({
}
}
+/** Parents before children, so every saved message's parent already exists. */
+function parentsFirst(
+ items: readonly ExportedMessageRepositoryItem[],
+): ExportedMessageRepositoryItem[] {
+ const byId = new Map(items.map((item) => [item.message.id, item]));
+ const seen = new Set<string>();
+ const ordered: ExportedMessageRepositoryItem[] = [];
+ const visit = (item: ExportedMessageRepositoryItem) => {
+ if (seen.has(item.message.id)) return;
+ seen.add(item.message.id);
+ const parent = item.parentId ? byId.get(item.parentId) : undefined;
+ if (parent) visit(parent);
+ ordered.push(item);
+ };
+ items.forEach(visit);
+ return ordered;
+}
+
+/** Save a temporary chat to history: its row, then every message on every branch in one batch,
+ * after which it saves like any other chat. The batch is one transaction, so a failure leaves at
+ * most an empty row, which a retry reuses; the chat stays temporary until then. */
+export async function persistTemporaryThread({
+ threadId,
+ modelType,
+ messages,
+}: {
+ threadId: string;
+ modelType: ModelType;
+ messages: readonly ExportedMessageRepositoryItem[];
+}): Promise<void> {
+ unmarkThreadIncognito(threadId);
+ try {
+ const times = messages
+ .map(({ message }) => message.createdAt?.getTime?.())
+ .filter((time): time is number => typeof time === "number");
+ const creation = temporaryThreadCreation.get(threadId);
+ await ensureThreadRecord({
+ threadId,
+ modelType,
+ projectId: null,
+ incognito: false,
+ ...(creation && {
+ modelId: creation.modelId,
+ modelGgufVariant: creation.modelGgufVariant,
+ }),
+ createdAt:
+ creation?.createdAt ?? (times.length > 0 ? Math.min(...times) : Date.now()),
+ });
+ const records: MessageRecord[] = parentsFirst(messages).map(({ parentId, message }) => {
+ const attachments =
+ message.role === "user" ? cloneAttachments(message.attachments) : [];
+ const metadata = message.metadata?.custom as
+ | Record<string, unknown>
+ | undefined;
+ return {
+ id: message.id,
+ threadId,
+ parentId: parentId ?? null,
+ role: message.role,
+ content: cloneContent(message.content),
+ ...(attachments.length > 0 && { attachments }),
+ ...(metadata && { metadata }),
+ createdAt: message.createdAt?.getTime?.() ?? Date.now(),
+ };
+ });
+ await syncStoredChatMessages(threadId, records, { pruneMissing: false });
+ temporaryThreadCreation.delete(threadId);
+ } catch (error) {
+ markThreadIncognito(threadId);
+ throw error;
+ }
+}
+
function createStudioDbAdapter(
modelType: ModelType,
pairId?: string,
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 03274858222..710833ba9dd 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -52,6 +52,11 @@ export function markThreadIncognito(threadId: string): void {
incognitoThreadIds.add(threadId);
}
+/** Saving a temporary chat: from here on it persists like any other thread. */
+export function unmarkThreadIncognito(threadId: string): void {
+ incognitoThreadIds.delete(threadId);
+}
+
/** True for a temporary-session thread, which is deliberately never persisted. */
export function isThreadIncognito(threadId: string): boolean {
return incognitoThreadIds.has(threadId);
diff --git a/studio/frontend/tests/save-temporary-chat.test.ts b/studio/frontend/tests/save-temporary-chat.test.ts
new file mode 100644
index 00000000000..04ab56b5a69
--- /dev/null
+++ b/studio/frontend/tests/save-temporary-chat.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Saving a temporary chat to history. runtime-provider.tsx cannot load under stubs, so the
+// ordering helper is run on its own and the rest is pinned on source.
+
+import assert from "node:assert/strict";
+import { stripTypeScriptTypes } from "node:module";
+import test from "node:test";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const provider = readSrc("features/chat/runtime-provider.tsx");
+const storage = readSrc("features/chat/utils/chat-history-storage.ts");
+const button = readSrc("features/chat/components/temporary-chat-save.tsx");
+const page = readSrc("features/chat/chat-page.tsx");
+
+type Item = { parentId: string | null; message: { id: string } };
+const parentsFirst = new Function(
+ `${stripTypeScriptTypes(provider.slice(provider.indexOf("function parentsFirst("), provider.indexOf("/** Save a temporary chat to history")))}\nreturn parentsFirst;`,
+)() as (items: Item[]) => Item[];
+
+const item = (id: string, parentId: string | null = null): Item => ({ parentId, message: { id } });
+const ids = (items: Item[]) => items.map((i) => i.message.id);
+
+function persistBody(): string {
+ const start = provider.indexOf("export async function persistTemporaryThread(");
+ assert.ok(start > 0, "persistTemporaryThread not found");
+ return provider.slice(start, provider.indexOf("function createStudioDbAdapter(", start));
+}
+
+test("every message is saved after its parent, on every branch", () => {
+ // Two replies to u1 (a regenerate), and a child listed before its parent.
+ const ordered = ids(
+ parentsFirst([item("a2", "u2"), item("u1"), item("a1", "u1"), item("u2", "a1"), item("b1", "u1")]),
+ );
+ assert.deepEqual([...ordered].sort(), ["a1", "a2", "b1", "u1", "u2"]);
+ for (const [child, parent] of [["a1", "u1"], ["b1", "u1"], ["u2", "a1"], ["a2", "u2"]]) {
+ assert.ok(ordered.indexOf(parent) < ordered.indexOf(child), `${parent} before ${child}`);
+ }
+});
+
+test("a parent missing from the export does not drop the message", () => {
+ assert.deepEqual(ids(parentsFirst([item("x", "gone"), item("y")])), ["x", "y"]);
+});
+
+test("the thread stops being temporary before writing, and goes back if the save fails", () => {
+ const body = persistBody();
+ assert.match(storage, /export function unmarkThreadIncognito\(threadId: string\): void \{\s*incognitoThreadIds\.delete\(threadId\);/);
+ assert.ok(body.indexOf("unmarkThreadIncognito(threadId)") < body.indexOf("await ensureThreadRecord("));
+ assert.match(body, /\} catch \(error\) \{\s*markThreadIncognito\(threadId\);\s*throw error;/);
+ assert.match(body, /incognito: false,/);
+});
+
+test("messages are written in one batch, so a failure cannot leave a truncated chat", () => {
+ const body = persistBody();
+ assert.match(body, /await syncStoredChatMessages\(threadId, records, \{ pruneMissing: false \}\);/);
+ assert.doesNotMatch(body, /saveStoredChatMessage\(/);
+ // The row comes first, since the batch needs it.
+ assert.ok(body.indexOf("await ensureThreadRecord(") < body.indexOf("await syncStoredChatMessages("));
+});
+
+test("the saved chat keeps the model it started on, not the one loaded at save time", () => {
+ const ensure = provider.slice(
+ provider.indexOf("export async function ensureThreadRecord({"),
+ provider.indexOf("/** Parents before children"),
+ );
+ // Both early returns for a temporary thread keep what it was started with.
+ assert.equal(ensure.match(/markThreadIncognito\(threadId\);\s*temporaryThreadCreation\.set\(threadId, creation\);/g)?.length, 2);
+ const body = persistBody();
+ assert.match(body, /const creation = temporaryThreadCreation\.get\(threadId\);/);
+ assert.match(body, /modelId: creation\.modelId,\s*modelGgufVariant: creation\.modelGgufVariant,/);
+ assert.match(body, /createdAt:\s*creation\?\.createdAt \?\?/);
+});
+
+test("saving waits for queued prompts, whose temporary tag would still discard them", () => {
+ assert.match(button, /Object\.values\(s\.byThreadId\)\.some\(\(entry\) => entry\.temporary\)/);
+ assert.match(button, /: target\.queued\s*\? "Wait for queued prompts to finish"/);
+});
+
+test("the save covers the whole branch tree, not only the visible path", () => {
+ assert.match(button, /messages: aui\.thread\(\)\.export\(\)\.messages/);
+ assert.match(persistBody(), /parentId: parentId \?\? null,/);
+});
+
+test("the button shows only in a temporary single chat and waits for a finished reply", () => {
+ assert.match(page, /view\.mode === "single" && incognito \? \(\s*<SaveTemporaryChatButton/);
+ assert.match(button, /\? "Nothing to save yet"\s*: target\.running\s*\? "Wait for the response to finish"/);
+});
+
+test("Don't show this again is remembered only once a save succeeds", () => {
+ const save = button.slice(button.indexOf("const save = async () => {"), button.indexOf("return (\n"));
+ assert.ok(save.indexOf("await target.save()") < save.indexOf("if (dontShowAgain) rememberSkipConfirm()"));
+ assert.doesNotMatch(save.slice(save.indexOf("catch")), /rememberSkipConfirm/);
+ assert.match(button, /if \(skipConfirm\(\)\) void save\(\);\s*else setOpen\(true\);/);
+});