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: keep the composer draft across chats, pages and tabs (#13722)

Michael Hanbef17c980237
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index d215e6a7760..52bacd1c1da 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -22,7 +22,6 @@ import {
import {
ChatPage,
type ChatSearch,
- clearNewChatDraft,
hydrateModelDisclaimerPreference,
openFolderAsProject,
startLlamaCppAutoReload,
@@ -509,7 +508,6 @@ function RootLayout() {
incognito?: boolean;
standalone?: boolean;
}) => {
- clearNewChatDraft(); // fresh chat starts empty, no bleed from the last one
const chatRuntime = useChatRuntimeStore.getState();
// The project on screen, which on Chat is the runtime's. The page keeps that in step with the
// route, the inferred ones included: a thread or a compare pair opened without ?project= still
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 8c92e1d143c..38081973035 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -160,7 +160,6 @@ import {
import {
archiveChatItem,
ChatSearchDialog,
- clearNewChatDraft,
canForkChatRow,
EditProjectDialog,
forkChatRow,
@@ -3367,7 +3366,6 @@ export function AppSidebar() {
}
function openNewChat(projectId = activeProjectId) {
- clearNewChatDraft();
setActiveThreadId(null);
useChatRuntimeStore.getState().setActiveProjectId(projectId);
// The normal new-chat affordance is always a saved chat; only the toolbar toggle is temporary.
@@ -3380,7 +3378,6 @@ export function AppSidebar() {
* Marked once the new chat is on screen, so the chat being left is never the one filed. */
function openNewChatInSection(sectionId: string) {
const nonce = createNavigationNonce();
- clearNewChatDraft();
setActiveThreadId(null);
useChatRuntimeStore.getState().setActiveProjectId(null);
useChatRuntimeStore.getState().setIncognito(false);
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index acd19d7fa9c..d488427e43d 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -300,6 +300,10 @@ import {
shouldAbortPendingQueueForSettingsChange,
resolveDeferredQueuedModelSettings,
snapshotQueuedChatRunSettings,
+ adoptLegacyDraft,
+ latestDraft,
+ publishDraft,
+ subscribeDraft,
composerDraftKey,
composerPasteDraftKey,
createPastedTextFile,
@@ -2841,6 +2845,9 @@ function claimPortaledDrop(event: ReactDragEvent): void {
}
}
+// Never a thread id, so entering or leaving a temporary chat counts as a chat switch.
+const INCOGNITO_DRAFT_SCOPE = "\u0000incognito";
+
const Composer: FC<{
disabled?: boolean;
placeholder?: string;
@@ -3909,25 +3916,36 @@ const Composer: FC<{
const canQueueAttachmentPrompt =
hasAttachments && !attachmentsAreQueueableText && composerAcceptsQueueing;
- // mirror each thread's draft to localStorage and restore it on mount
- const draftThreadId = referenceThreadId;
- const draftKey = draftThreadId ? composerDraftKey(draftThreadId) : null;
+ // The shared draft, restored on every chat switch; a temporary chat never reads or writes it.
+ const incognito = useChatRuntimeStore((s) => s.incognito);
+ const draftScope = incognito ? INCOGNITO_DRAFT_SCOPE : referenceThreadId;
+ const draftKey = composerDraftKey();
+ // Text that came from Compare or another tab, so saving it back can't overwrite a newer write.
+ const remoteDraftRef = useRef<string | null>(null);
+ const [draftSource] = useState(() => Symbol("chat composer"));
+ // Whose pastes are on screen: a temporary chat's never cross into the saved draft, nor back.
+ const pasteScopeShownRef = useRef<string | null>(draftScope);
// unsent pasted File objects need a separate slot because they exist only in memory
- const pasteDraftKey = draftThreadId
- ? composerPasteDraftKey(draftThreadId)
- : null;
- const lastDraftKeyRef = useRef(draftKey);
- // save only after this key's paste restore finishes to avoid premature clearing
- const restoredPasteKeyRef = useRef<string | null>(null);
+ const pasteDraftKey = composerPasteDraftKey();
+ const lastDraftScopeRef = useRef(draftScope);
+ // save only after this chat's paste restore finishes to avoid premature clearing
+ const restoredPasteScopeRef = useRef<string | null | undefined>(undefined);
+ const restoringPasteScopeRef = useRef<string | null | undefined>(undefined);
const draftSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // draftScope re-runs the restore on every chat switch, though the key stays the same.
useEffect(() => {
- const draft = draftKey ? (readComposerDraft(draftKey) ?? "") : "";
const composer = aui.composer();
if (!composer.getState().isEditing) return;
+ if (draftScope === INCOGNITO_DRAFT_SCOPE) {
+ composer.setText("");
+ return;
+ }
+ const draft = adoptLegacyDraft(draftScope)
+ ? (readComposerDraft(draftKey) ?? "")
+ : latestDraft();
// A save that raced the send still holds the sent text, so restoring it
- // would undo the clear. Keyed on the sending thread, so another thread's
- // identical draft still restores. Clear rather than return early, which
- // would leave the previous thread's text on screen under this one.
+ // would undo the clear. Clear rather than return early, which would leave
+ // the previous thread's text on screen under this one.
if (sentTextGuardBlocksDraft(justSentRef.current, draft, draftKey)) {
// Written inline rather than via clearStoredDraft, which is declared
// below this effect. Cancel the pending save too, or it rewrites the key.
@@ -3935,16 +3953,25 @@ const Composer: FC<{
clearTimeout(draftSaveTimerRef.current);
draftSaveTimerRef.current = null;
}
- if (draftKey) writeComposerDraft(draftKey, "");
+ writeComposerDraft(draftKey, "");
composer.setText("");
return;
}
composer.setText(draft);
- }, [draftKey, aui]);
+ }, [draftScope, draftKey, aui]);
+ // Compare's composer or another tab, so whichever is on screen shows the latest draft.
+ useEffect(() => {
+ if (draftScope === INCOGNITO_DRAFT_SCOPE) return;
+ return subscribeDraft(draftSource, (text) => {
+ const composer = aui.composer();
+ if (!composer.getState().isEditing) return;
+ remoteDraftRef.current = text;
+ composer.setText(text);
+ });
+ }, [draftScope, draftSource, aui]);
// The saved-prompt menu and the prompt storage dialog fill the composer
- // directly, bypassing the guard. Text appearing while the sending thread is
- // on screen was put there deliberately, so retire; the draftKey check keeps
- // another thread's restored draft from doing the same. Read live, or a
+ // directly, bypassing the guard. Text appearing after the send was put there
+ // deliberately, so retire. Read live, or a
// pending render retires it on stale text. Must stay after the restore
// above, which clears the raced draft this would otherwise retire on.
useEffect(() => {
@@ -3959,28 +3986,72 @@ const Composer: FC<{
useEffect(() => {
const composer = aui.composer();
if (!composer.getState().isEditing) return;
- if (restoredPasteKeyRef.current === pasteDraftKey) return;
- // The composer outlives a thread switch, so restore only into an empty one
- // rather than mixing this thread's draft with whatever the last one left.
- // Changing attachments re-runs this effect, which is how the retry happens.
- if (composer.getState().attachments.length > 0) return;
- const stored = pasteDraftKey ? readPasteDraft(pasteDraftKey) : [];
- if (stored.length === 0) {
- restoredPasteKeyRef.current = pasteDraftKey;
+ if (restoredPasteScopeRef.current === draftScope) return;
+ if (
+ (pasteScopeShownRef.current === INCOGNITO_DRAFT_SCOPE) !==
+ (draftScope === INCOGNITO_DRAFT_SCOPE)
+ ) {
+ const pasted = composer
+ .getState()
+ .attachments.filter(
+ (attachment) =>
+ pastedTextOf((attachment as { file?: File }).file) !== undefined,
+ );
+ if (pasted.length > 0) {
+ // Removing them changes the attachments, which runs this again.
+ for (const attachment of pasted) {
+ void composer.attachment({ id: attachment.id }).remove();
+ }
+ return;
+ }
+ }
+ pasteScopeShownRef.current = draftScope;
+ if (draftScope === INCOGNITO_DRAFT_SCOPE) {
+ restoredPasteScopeRef.current = draftScope;
+ return;
+ }
+ // Only the saved pastes not on screen: the composer can outlive a switch holding
+ // them, and another attachment (a handoff's image) is no sign they were restored.
+ const shown = composer
+ .getState()
+ .attachments.flatMap((attachment) => {
+ const text = pastedTextOf((attachment as { file?: File }).file);
+ return text === undefined ? [] : [text];
+ });
+ const missing = readPasteDraft(pasteDraftKey).filter((text) => {
+ const at = shown.indexOf(text);
+ if (at === -1) return true;
+ shown.splice(at, 1);
+ return false;
+ });
+ if (missing.length === 0) {
+ restoredPasteScopeRef.current = draftScope;
return;
}
- // Claim the key only once the attachments are in, so the save effect
+ // Its own additions re-run this; one pass per scope, or they double up.
+ if (restoringPasteScopeRef.current === draftScope) return;
+ restoringPasteScopeRef.current = draftScope;
+ // Claim the chat only once the attachments are in, so the save effect
// cannot write an empty composer over the draft still being restored.
void Promise.all(
- stored.map((text) => composer.addAttachment(createPastedTextFile(text))),
+ missing.map((text) => composer.addAttachment(createPastedTextFile(text))),
).finally(() => {
- restoredPasteKeyRef.current = pasteDraftKey;
+ restoringPasteScopeRef.current = undefined;
+ // A switch while these were added re-runs the restore for the new scope instead.
+ if (draftScopeRef.current === draftScope) {
+ restoredPasteScopeRef.current = draftScope;
+ }
});
- }, [pasteDraftKey, composerAttachmentSignature, aui]);
+ }, [draftScope, pasteDraftKey, composerAttachmentSignature, aui]);
// Keyed on the paste identities, never their bodies, so typing beside a
// megabyte paste does not rewrite it to localStorage every 300ms.
useEffect(() => {
- if (!pasteDraftKey || restoredPasteKeyRef.current !== pasteDraftKey) return;
+ if (
+ draftScope === INCOGNITO_DRAFT_SCOPE ||
+ restoredPasteScopeRef.current !== draftScope
+ ) {
+ return;
+ }
const pastes = aui
.composer()
.getState()
@@ -3989,26 +4060,27 @@ const Composer: FC<{
return text === undefined ? [] : [text];
});
writePasteDraft(pasteDraftKey, pastes);
- }, [composerAttachmentSignature, pasteDraftKey, aui]);
+ }, [composerAttachmentSignature, draftScope, pasteDraftKey, aui]);
useEffect(() => {
- // After a thread switch composerText can still hold the previous
- // thread's text; skip that cycle so it isn't saved under the new key.
- if (lastDraftKeyRef.current !== draftKey) {
- lastDraftKeyRef.current = draftKey;
- return;
- }
- if (!draftKey) {
+ // After a thread switch composerText can still hold what was on screen
+ // before the restore; skip that cycle so it can't overwrite the draft.
+ if (lastDraftScopeRef.current !== draftScope) {
+ lastDraftScopeRef.current = draftScope;
return;
}
+ if (draftScope === INCOGNITO_DRAFT_SCOPE) return;
+ if (composerText === remoteDraftRef.current) return;
+ remoteDraftRef.current = null;
+ publishDraft(composerText, draftSource);
const t = setTimeout(() => writeComposerDraft(draftKey, composerText), 300);
draftSaveTimerRef.current = t;
return () => clearTimeout(t);
- }, [composerText, draftKey]);
- const pasteDraftKeyRef = useRef(pasteDraftKey);
+ }, [composerText, draftScope, draftKey, draftSource]);
+ const draftScopeRef = useRef(draftScope);
useEffect(() => {
draftKeyRef.current = draftKey;
- pasteDraftKeyRef.current = pasteDraftKey;
- }, [draftKey, pasteDraftKey]);
+ draftScopeRef.current = draftScope;
+ }, [draftKey, draftScope]);
// Call wherever the composer is emptied because its text left as a message.
const armJustSent = useCallback((...texts: string[]) => {
justSentRef.current = armSentTextGuard(
@@ -4025,15 +4097,12 @@ const Composer: FC<{
clearTimeout(draftSaveTimerRef.current);
draftSaveTimerRef.current = null;
}
- const key = draftKeyRef.current;
- if (key) {
- writeComposerDraft(key, "");
- }
- const pasteKey = pasteDraftKeyRef.current;
- if (pasteKey) {
- writePasteDraft(pasteKey, []);
- }
- }, []);
+ // A temporary chat's send was never the stored draft.
+ if (draftScopeRef.current === INCOGNITO_DRAFT_SCOPE) return;
+ publishDraft("", draftSource);
+ writeComposerDraft(composerDraftKey(), "");
+ writePasteDraft(composerPasteDraftKey(), []);
+ }, [draftSource]);
// react-textarea-autosize re-measures only on value change or window resize,
// not on the width swap from expanding, so it keeps the taller height and
// leaves a stray blank row. Nudge a resize whenever input width changes.
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index e34f51b4e5e..ec63b74bb12 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -274,7 +274,6 @@ import {
comparePairReadState,
resolveComparePaneThreadIds,
} from "./utils/compare-pane-threads";
-import { clearNewChatDraft } from "./utils/composer-draft";
import { isChatThreadDeleted } from "./utils/chat-thread-tombstones";
import {
getStoredChatThread,
@@ -2887,7 +2886,6 @@ export function ChatPage({
);
const handleDesktopNewChat = useCallback(() => {
- clearNewChatDraft();
const runtime = useChatRuntimeStore.getState();
runtime.setActiveThreadId(null);
runtime.setActiveProjectId(currentProjectId);
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 7c52fd6693c..cd416dceb1e 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -499,7 +499,10 @@ export {
downloadChatExport,
} from "./utils/export-chat-history";
export {
- clearNewChatDraft,
+ adoptLegacyDraft,
+ latestDraft,
+ publishDraft,
+ subscribeDraft,
composerDraftKey,
composerPasteDraftKey,
readComposerDraft,
diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsx
index 21c7ce36a7a..592e1e3ac23 100644
--- a/studio/frontend/src/features/chat/projects-page.tsx
+++ b/studio/frontend/src/features/chat/projects-page.tsx
@@ -104,7 +104,6 @@ import {
normalizeSectionName,
useSidebarOrganizationStore,
} from "./stores/sidebar-organization-store";
-import { clearNewChatDraft } from "./utils/composer-draft";
import { runChatImport } from "./utils/import-chats";
// Reveal this many more projects each time the user scrolls near the bottom.
@@ -435,9 +434,8 @@ export function ProjectsPage() {
navigate({ to: "/chat", search: { project: projectId } });
}
- // A saved chat with an empty composer, as the sidebar's New chat.
+ // A saved chat, as the sidebar's New chat.
function newChatInProject(projectId: string) {
- clearNewChatDraft();
useChatRuntimeStore.getState().setIncognito(false);
openProject(projectId);
}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 9ceca481876..8ed9edb5213 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -88,6 +88,13 @@ import {
import { modelIdsMatch } from "@/features/hub/lib/model-identity";
import { CONVERSATION_MARKDOWN_LABEL } from "./utils/conversation-markdown";
import { pasteClipboardFiles } from "./utils/clipboard-files";
+import {
+ composerDraftKey,
+ latestDraft,
+ publishDraft,
+ subscribeDraft,
+ writeComposerDraft,
+} from "./utils/composer-draft";
import { confirmStopRunningChatsIfNeeded } from "./utils/confirm-stop-running-chats";
import { requestLocalPromptQueueStop } from "./utils/prompt-queue-boundary";
import {
@@ -641,7 +648,50 @@ export function SharedComposer({
}
navigate({ to: "/chat" });
}, [navigate, onExitCompare]);
- const [text, setText] = useState("");
+ const incognito = useChatRuntimeStore((s) => s.incognito);
+ const [text, setText] = useState(() =>
+ useChatRuntimeStore.getState().incognito ? "" : latestDraft(),
+ );
+ const [draftSource] = useState(() => Symbol("compare composer"));
+ // Text that came from the chat composer or another tab, so it isn't published back.
+ const remoteDraftRef = useRef<string | null>(null);
+ const unsavedDraftRef = useRef<string | null>(null);
+ const incognitoBeforeRef = useRef(incognito);
+ useEffect(() => {
+ // Leaving a temporary chat (Compare can mount just before it resets) restores the saved draft.
+ if (incognitoBeforeRef.current !== incognito) {
+ incognitoBeforeRef.current = incognito;
+ if (!incognito) {
+ remoteDraftRef.current = latestDraft();
+ setText(remoteDraftRef.current);
+ }
+ return;
+ }
+ if (incognito || text === remoteDraftRef.current) return;
+ remoteDraftRef.current = null;
+ publishDraft(text, draftSource);
+ // Emptied (a send, or cleared by hand): gone at once, so a reload can't bring back a sent prompt.
+ if (text === "") {
+ writeComposerDraft(composerDraftKey(), "");
+ unsavedDraftRef.current = null;
+ return;
+ }
+ unsavedDraftRef.current = text;
+ const timer = setTimeout(() => {
+ writeComposerDraft(composerDraftKey(), text);
+ unsavedDraftRef.current = null;
+ }, 300);
+ return () => clearTimeout(timer);
+ }, [text, incognito, draftSource]);
+ // Leaving Compare inside the debounce still saves what was typed.
+ useEffect(
+ () => () => {
+ if (unsavedDraftRef.current !== null) {
+ writeComposerDraft(composerDraftKey(), unsavedDraftRef.current);
+ }
+ },
+ [],
+ );
const shortcutLabels = composerShortcutLabels(sendShortcut, isMacPlatform(), text);
const [running, setRunning] = useState(false);
const [comparing, setComparing] = useState(false);
@@ -669,6 +719,13 @@ export function SharedComposer({
},
[],
);
+ useEffect(() => {
+ if (incognito) return;
+ return subscribeDraft(draftSource, (next) => {
+ remoteDraftRef.current = next;
+ setCurrentText(next);
+ });
+ }, [incognito, draftSource, setCurrentText]);
// Attachments still classifying or converting; a ref so runPromptList reads it synchronously.
const attachingRef = useRef(0);
useEffect(() => {
diff --git a/studio/frontend/src/features/chat/utils/composer-draft.ts b/studio/frontend/src/features/chat/utils/composer-draft.ts
index 60bbb6554e8..0bb4ec92b6d 100644
--- a/studio/frontend/src/features/chat/utils/composer-draft.ts
+++ b/studio/frontend/src/features/chat/utils/composer-draft.ts
@@ -1,23 +1,22 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// Per-thread composer drafts persisted in localStorage. New (unsaved) chats share the
-// NEW_CHAT_DRAFT_ID slot; callers clear it when a fresh chat starts so one new chat's draft
-// never bleeds into the next.
-const DRAFT_PREFIX = "chat-draft:";
-const PASTE_DRAFT_PREFIX = "chat-draft-pastes:";
-const NEW_CHAT_DRAFT_ID = "__new__";
+// One draft shared by every chat, so the last thing typed follows the user. The chat-draft prefix
+// is what the account switch clears (account-transition.ts).
+const DRAFT_KEY = "chat-draft:latest";
+const PASTE_DRAFT_KEY = "chat-draft-pastes:latest";
+// Pre-upgrade per-chat drafts: adopted when their chat opens, removed with their chat.
+const LEGACY_DRAFT_PREFIX = "chat-draft:";
+const LEGACY_PASTE_DRAFT_PREFIX = "chat-draft-pastes:";
-export function composerDraftKey(threadId: string | null | undefined): string {
- return `${DRAFT_PREFIX}${threadId ?? NEW_CHAT_DRAFT_ID}`;
+export function composerDraftKey(): string {
+ return DRAFT_KEY;
}
// Pasted attachments live in their own slot rather than inside the text draft, so typing never
// rewrites a paste that can run to megabytes.
-export function composerPasteDraftKey(
- threadId: string | null | undefined,
-): string {
- return `${PASTE_DRAFT_PREFIX}${threadId ?? NEW_CHAT_DRAFT_ID}`;
+export function composerPasteDraftKey(): string {
+ return PASTE_DRAFT_KEY;
}
// The names are not stored: a pasted file is named from its own text, so recreating it reproduces the name it had.
@@ -71,16 +70,75 @@ export function writeComposerDraft(key: string, text: string): void {
}
}
-export function clearComposerDraft(threadId: string | null | undefined): void {
+// A draft saved per chat before the shared slot existed becomes the shared draft when that chat
+// opens and nothing newer is waiting, so an upgrade never loses unsent text. True if it did.
+export function adoptLegacyDraft(threadId: string | null): boolean {
+ // Text typed this session and not yet saved is newer than any old slot.
+ if (latest) return false;
+ const id = threadId ?? "__new__";
try {
- window.localStorage.removeItem(composerDraftKey(threadId));
- window.localStorage.removeItem(composerPasteDraftKey(threadId));
+ const storage = window.localStorage;
+ const text = storage.getItem(`${LEGACY_DRAFT_PREFIX}${id}`);
+ const pastes = storage.getItem(`${LEGACY_PASTE_DRAFT_PREFIX}${id}`);
+ if (text === null && pastes === null) return false;
+ let adopted = false;
+ if (storage.getItem(DRAFT_KEY) === null && storage.getItem(PASTE_DRAFT_KEY) === null) {
+ if (text !== null) storage.setItem(DRAFT_KEY, text);
+ try {
+ if (pastes !== null) storage.setItem(PASTE_DRAFT_KEY, pastes);
+ } catch (error) {
+ // All or nothing: a text-only copy would make the next try skip, dropping the paste.
+ storage.removeItem(DRAFT_KEY);
+ throw error;
+ }
+ adopted = true;
+ }
+ storage.removeItem(`${LEGACY_DRAFT_PREFIX}${id}`);
+ storage.removeItem(`${LEGACY_PASTE_DRAFT_PREFIX}${id}`);
+ return adopted;
} catch {
- // ignore
+ return false;
}
}
-// Drop the shared new-chat draft so a freshly started chat opens empty.
-export function clearNewChatDraft(): void {
- clearComposerDraft(null);
+// The chat composer stays mounted, hidden, under Compare's, and localStorage tells only other tabs
+// about a write. So every composer publishes its text here as it changes, and hears the others and
+// other tabs here too; `latestDraft` is ahead of the debounced save.
+type DraftListener = (text: string, source: symbol) => void;
+const draftListeners = new Set<DraftListener>();
+let latest: string | null = null;
+const OTHER_TAB = Symbol("other tab");
+
+export function latestDraft(): string {
+ return latest ?? readComposerDraft(DRAFT_KEY) ?? "";
+}
+
+export function publishDraft(text: string, source: symbol): void {
+ if (text === latest) return;
+ latest = text;
+ for (const listener of draftListeners) listener(text, source);
+}
+
+export function subscribeDraft(source: symbol, listener: (text: string) => void): () => void {
+ const wrapped: DraftListener = (text, from) => {
+ if (from !== source) listener(text);
+ };
+ draftListeners.add(wrapped);
+ return () => draftListeners.delete(wrapped);
+}
+
+if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
+ window.addEventListener("storage", (event) => {
+ if (event.key === DRAFT_KEY) publishDraft(event.newValue ?? "", OTHER_TAB);
+ });
+}
+
+// A deleted chat's leftover per-chat draft; never the shared one.
+export function clearComposerDraft(threadId: string): void {
+ try {
+ window.localStorage.removeItem(`${LEGACY_DRAFT_PREFIX}${threadId}`);
+ window.localStorage.removeItem(`${LEGACY_PASTE_DRAFT_PREFIX}${threadId}`);
+ } catch {
+ // ignore
+ }
}
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index 475e1bc4348..edba3f9044d 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -8,7 +8,6 @@ import { useHfEndpoint, useHubSource } from "@/lib/hf-endpoint";
import { usePlatformStore } from "@/config/env";
import {
applyActiveModelStatusToStore,
- clearNewChatDraft,
getInferenceStatus,
isExternalModelId,
isSpeechOnlyStatus,
@@ -1579,7 +1578,6 @@ export function ModelsPage() {
// A new chat opens with the model's run settings, where Load starts it.
const openRunSettingsInChat = useCallback(
(request: ModelConfigHandoffRequest) => {
- clearNewChatDraft();
const chatRuntime = useChatRuntimeStore.getState();
chatRuntime.setActiveThreadId(null);
chatRuntime.setActiveProjectId(null);
diff --git a/studio/frontend/src/features/library/chats/chats-library.tsx b/studio/frontend/src/features/library/chats/chats-library.tsx
index 9783de6777f..eb9dfa68f08 100644
--- a/studio/frontend/src/features/library/chats/chats-library.tsx
+++ b/studio/frontend/src/features/library/chats/chats-library.tsx
@@ -28,7 +28,6 @@ import {
type SidebarCustomSection,
type SidebarItem,
archiveChatItems,
- clearNewChatDraft,
compareModelDisplayName,
deleteChatItems,
deleteChatProject,
@@ -613,7 +612,6 @@ export function ChatsLibrary({
/** Files the new chat on its first send; the sidebar watches for the mark set here. */
const newChatInSection = (sectionId: string) => {
const nonce = crypto.randomUUID();
- clearNewChatDraft();
const runtime = useChatRuntimeStore.getState();
runtime.setActiveThreadId(null);
runtime.setActiveProjectId(null);
@@ -625,7 +623,6 @@ export function ChatsLibrary({
};
const newChatIn = (id: string | null) => {
- clearNewChatDraft();
const runtime = useChatRuntimeStore.getState();
runtime.setActiveThreadId(null);
runtime.setActiveProjectId(id);
diff --git a/studio/frontend/src/features/library/start-chat.ts b/studio/frontend/src/features/library/start-chat.ts
index dde2be3c75b..6d76f3c1803 100644
--- a/studio/frontend/src/features/library/start-chat.ts
+++ b/studio/frontend/src/features/library/start-chat.ts
@@ -5,8 +5,6 @@ import type { useNavigate } from "@tanstack/react-router";
import { getAuthSessionEpoch } from "@/features/auth";
// eslint-disable-next-line no-restricted-imports -- the chat barrel imports the Library back
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
-// eslint-disable-next-line no-restricted-imports -- the chat barrel imports the Library back
-import { clearNewChatDraft } from "@/features/chat/utils/composer-draft";
import { createModelConfigHandoffRequestId } from "@/features/model-picker";
import { translate } from "@/i18n";
import { toast } from "@/lib/toast";
@@ -20,7 +18,6 @@ import { mediaFileName } from "@/lib/prompt-text";
type Navigate = ReturnType<typeof useNavigate>;
export function resetToNewChat(): void {
- clearNewChatDraft();
const runtime = useChatRuntimeStore.getState();
runtime.setActiveThreadId(null);
runtime.setActiveProjectId(null);
diff --git a/studio/frontend/src/features/model-picker/sharing/link-lifecycle.ts b/studio/frontend/src/features/model-picker/sharing/link-lifecycle.ts
index 3ad4c0ae091..d2f50fd8c3e 100644
--- a/studio/frontend/src/features/model-picker/sharing/link-lifecycle.ts
+++ b/studio/frontend/src/features/model-picker/sharing/link-lifecycle.ts
@@ -1,11 +1,7 @@
// 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 {
- type ChatSearch,
- clearNewChatDraft,
- useChatRuntimeStore,
-} from "@/features/chat";
+import { type ChatSearch, useChatRuntimeStore } from "@/features/chat";
import { toast } from "@/lib/toast";
import { modelConfigDraftKey } from "../model-config/model-config-draft";
import {
@@ -132,7 +128,6 @@ export function openRunConfigTarget(
return;
}
if (pending.newChatId === undefined) {
- clearNewChatDraft();
const runtime = useChatRuntimeStore.getState();
runtime.setActiveThreadId(null);
runtime.setActiveProjectId(null);
diff --git a/studio/frontend/tests/composer-paste-draft.test.ts b/studio/frontend/tests/composer-paste-draft.test.ts
index 3b55ed3b423..f5d7b229000 100644
--- a/studio/frontend/tests/composer-paste-draft.test.ts
+++ b/studio/frontend/tests/composer-paste-draft.test.ts
@@ -22,11 +22,15 @@ let failWrites = false;
};
const {
+ adoptLegacyDraft,
clearComposerDraft,
composerDraftKey,
composerPasteDraftKey,
+ latestDraft,
+ publishDraft,
readComposerDraft,
readPasteDraft,
+ subscribeDraft,
writeComposerDraft,
writePasteDraft,
} = await import("../src/features/chat/utils/composer-draft.ts");
@@ -34,10 +38,79 @@ const {
test.beforeEach(() => {
store.clear();
failWrites = false;
+ publishDraft("", Symbol("reset"));
+});
+
+test("unsaved text typed this session beats an old per-chat draft", () => {
+ publishDraft("typed just now", Symbol("chat"));
+ store.set("chat-draft:t1", "older");
+ assert.equal(adoptLegacyDraft("t1"), false);
+ assert.equal(latestDraft(), "typed just now");
+ assert.equal(store.get("chat-draft:t1"), "older", "kept for a later, empty-handed open");
+});
+
+test("a per-chat draft from before the upgrade becomes the shared draft when its chat opens", () => {
+ store.set("chat-draft:t1", "unsent");
+ store.set("chat-draft-pastes:t1", '["pasted"]');
+ adoptLegacyDraft("t1");
+ assert.equal(readComposerDraft(composerDraftKey()), "unsent");
+ assert.deepEqual(readPasteDraft(composerPasteDraftKey()), ["pasted"]);
+ assert.equal(store.has("chat-draft:t1"), false);
+ assert.equal(store.has("chat-draft-pastes:t1"), false);
+});
+
+test("an old new-chat draft is adopted when a new chat opens", () => {
+ store.set("chat-draft:__new__", "unsent");
+ adoptLegacyDraft(null);
+ assert.equal(readComposerDraft(composerDraftKey()), "unsent");
+});
+
+test("a newer shared draft wins over an old per-chat one", () => {
+ writeComposerDraft(composerDraftKey(), "newer");
+ store.set("chat-draft:t1", "older");
+ adoptLegacyDraft("t1");
+ assert.equal(readComposerDraft(composerDraftKey()), "newer");
+ assert.equal(store.has("chat-draft:t1"), false);
+});
+
+test("a paste too big to adopt rolls back the text, so the next try still carries both", () => {
+ store.set("chat-draft:t1", "unsent");
+ store.set("chat-draft-pastes:t1", '["pasted"]');
+ const setItem = window.localStorage.setItem;
+ window.localStorage.setItem = (key: string, value: string) => {
+ if (key === composerPasteDraftKey()) throw new Error("QuotaExceededError");
+ setItem(key, value);
+ };
+ assert.equal(adoptLegacyDraft("t1"), false);
+ window.localStorage.setItem = setItem;
+ assert.equal(readComposerDraft(composerDraftKey()), null);
+ assert.equal(adoptLegacyDraft("t1"), true);
+ assert.equal(readComposerDraft(composerDraftKey()), "unsent");
+ assert.deepEqual(readPasteDraft(composerPasteDraftKey()), ["pasted"]);
+});
+
+test("composers hear each other's text, never their own", () => {
+ const chat = Symbol("chat");
+ const compare = Symbol("compare");
+ const heard: string[] = [];
+ const stop = subscribeDraft(chat, (text) => heard.push(text));
+ publishDraft("from compare", compare);
+ publishDraft("from chat", chat);
+ stop();
+ publishDraft("after stop", compare);
+ assert.deepEqual(heard, ["from compare"]);
+ assert.equal(latestDraft(), "after stop");
+});
+
+test("a failed adoption keeps the old draft rather than losing it", () => {
+ store.set("chat-draft:t1", "unsent");
+ failWrites = true;
+ adoptLegacyDraft("t1");
+ assert.equal(store.get("chat-draft:t1"), "unsent");
});
test("an unsent paste survives a reload", () => {
- const key = composerPasteDraftKey("t1");
+ const key = composerPasteDraftKey();
const paste = `Deploy log\n${"line\n".repeat(500)}`;
writePasteDraft(key, [paste]);
@@ -53,27 +126,37 @@ test("an unsent paste survives a reload", () => {
test("the paste slot is separate from the text draft", () => {
// Typing must never rewrite a paste that can run to megabytes, so the two
// live under different keys.
- assert.notEqual(composerDraftKey("t1"), composerPasteDraftKey("t1"));
- assert.notEqual(composerPasteDraftKey("t1"), composerPasteDraftKey("t2"));
+ assert.notEqual(composerDraftKey(), composerPasteDraftKey());
+});
- writeComposerDraft(composerDraftKey("t1"), "typed");
- writePasteDraft(composerPasteDraftKey("t1"), ["pasted"]);
+test("deleting a chat drops its old per-chat draft but keeps the shared one", () => {
+ writeComposerDraft(composerDraftKey(), "typed");
+ writePasteDraft(composerPasteDraftKey(), ["pasted"]);
+ store.set("chat-draft:t1", "old");
+ store.set("chat-draft-pastes:t1", '["old"]');
clearComposerDraft("t1");
- assert.equal(readComposerDraft(composerDraftKey("t1")), null);
- assert.deepEqual(readPasteDraft(composerPasteDraftKey("t1")), []);
+ assert.equal(store.has("chat-draft:t1"), false);
+ assert.equal(store.has("chat-draft-pastes:t1"), false);
+ assert.equal(readComposerDraft(composerDraftKey()), "typed");
+ assert.deepEqual(readPasteDraft(composerPasteDraftKey()), ["pasted"]);
+});
+
+test("the shared draft keeps the prefix the account switch clears", () => {
+ assert.ok(composerDraftKey().startsWith("chat-draft"));
+ assert.ok(composerPasteDraftKey().startsWith("chat-draft"));
});
test("a paste too big for the quota does not cost the typed draft", () => {
- writeComposerDraft(composerDraftKey("t1"), "typed");
+ writeComposerDraft(composerDraftKey(), "typed");
failWrites = true;
- writePasteDraft(composerPasteDraftKey("t1"), ["x".repeat(64)]);
- assert.equal(readComposerDraft(composerDraftKey("t1")), "typed");
- assert.deepEqual(readPasteDraft(composerPasteDraftKey("t1")), []);
+ writePasteDraft(composerPasteDraftKey(), ["x".repeat(64)]);
+ assert.equal(readComposerDraft(composerDraftKey()), "typed");
+ assert.deepEqual(readPasteDraft(composerPasteDraftKey()), []);
});
test("a corrupt paste slot reads as empty rather than throwing", () => {
- const key = composerPasteDraftKey("t1");
+ const key = composerPasteDraftKey();
for (const raw of ["not json", '{"text":"a"}', "[1,2]", ""]) {
store.set(key, raw);
assert.deepEqual(readPasteDraft(key), []);
diff --git a/studio/frontend/tests/hub-runtime-boundary.test.ts b/studio/frontend/tests/hub-runtime-boundary.test.ts
index d074ea59537..410246e8079 100644
--- a/studio/frontend/tests/hub-runtime-boundary.test.ts
+++ b/studio/frontend/tests/hub-runtime-boundary.test.ts
@@ -191,7 +191,7 @@ test("the Hub routes Run to its owning workflow without owning runtime actions",
assert.match(HUB_RENDER_SOURCES, />\s*Run\s*</);
assert.match(
hubPage,
- /clearNewChatDraft\(\);[\s\S]*?setActiveThreadId\(null\);[\s\S]*?setActiveProjectId\(null\);[\s\S]*?setIncognito\(false\);[\s\S]*?requestModelConfigHandoff\(request\)/,
+ /setActiveThreadId\(null\);[\s\S]*?setActiveProjectId\(null\);[\s\S]*?setIncognito\(false\);[\s\S]*?requestModelConfigHandoff\(request\)/,
);
assert.match(hubPage, /requestModelConfigHandoff\(request\)/);
assert.match(hubPage, /to: "\/chat", search: \{ new: requestId \}/);
diff --git a/studio/frontend/tests/library-chats.test.ts b/studio/frontend/tests/library-chats.test.ts
index 98ed53c1ec1..260f8b99042 100644
--- a/studio/frontend/tests/library-chats.test.ts
+++ b/studio/frontend/tests/library-chats.test.ts
@@ -640,10 +640,9 @@ test("a chat's menu has no Open chat, and its folder sits under Export", () => {
assert.ok(projects.indexOf("<OpenChatFolderItem item={chat} />") > projects.indexOf("Export all chats…"));
});
-test("the Library's New chat is a saved chat with an empty composer, like the sidebar's", () => {
+test("the Library's New chat is a saved chat, like the sidebar's", () => {
const library = readSrc("features/library/chats/chats-library.tsx");
const newChatIn = library.slice(library.indexOf("const newChatIn = "), library.indexOf("async function run("));
- assert.match(newChatIn, /clearNewChatDraft\(\);/);
assert.match(newChatIn, /runtime\.setIncognito\(false\);/);
});
@@ -658,10 +657,9 @@ test("Reset all local preferences clears the Chats library preferences", () => {
assert.match(keys, /LIBRARY_CHATS_PREFS_STORAGE_KEY/);
});
-test("a New chat from a project's menu on the Projects page is a saved chat with an empty composer", () => {
+test("a New chat from a project's menu on the Projects page is a saved chat", () => {
const page = readSrc("features/chat/projects-page.tsx");
const body = page.slice(page.indexOf("function newChatInProject("), page.indexOf("function newChatInProject(") + 300);
- assert.match(body, /clearNewChatDraft\(\);/);
assert.match(body, /setIncognito\(false\)/);
});
diff --git a/studio/frontend/tests/share-run-configs.lifecycle.test.ts b/studio/frontend/tests/share-run-configs.lifecycle.test.ts
index ac685102aa5..36d957b73c0 100644
--- a/studio/frontend/tests/share-run-configs.lifecycle.test.ts
+++ b/studio/frontend/tests/share-run-configs.lifecycle.test.ts
@@ -121,7 +121,6 @@ function harness(loadParser?: () => typeof links | Promise<typeof links>) {
sharing("link-lifecycle.ts"),
{
"@/features/chat": {
- clearNewChatDraft: () => calls.push("clear draft"),
useChatRuntimeStore: { getState: () => runtime },
},
"@/lib/toast": {
@@ -302,7 +301,6 @@ for (const chatSearch of [
assert.equal(app.inbox.take("first", "another draft"), null);
assert.deepEqual(app.calls, [
navigateCall("first"),
- "clear draft",
["thread", null],
["project", null],
["incognito", false],