Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Make shared composer drafts opt-in (#16548)
Lee Jacksonaec995241be6
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 493fe5caa2d..ee5ac46a0d5 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -357,8 +357,10 @@ import {shouldAbortPendingQueueForSettingsChange,resolveDeferredQueuedModelSettings,snapshotQueuedChatRunSettings,- adoptLegacyDraft,+ flushComposerDraft,latestDraft,+ NEW_CHAT_DRAFT_ID,+ stageComposerDraft,latestPasteDraft,publishDraft,subscribeDraft,@@ -374,7 +376,6 @@ import {dictationFailed,dictationProducedClip,dictationProducedTranscript,- readComposerDraft,type PromptQueueUIEntry,type PromptQueueUIItem,type PromptQueueUIItemStatus,@@ -4132,33 +4133,78 @@ const Composer: FC<{const canQueueAttachmentPrompt =hasAttachments && !attachmentsAreQueueableText && composerAcceptsQueueing;- // 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();+ const shareDraft = useChatPreferencesStore((s) => s.shareComposerDraft);+ // Route and active IDs can lead the runtime switch; drafts belong to the composer on screen.+ const draftThreadId = threadListItemRemoteId ?? NEW_CHAT_DRAFT_ID;+ const restoredDraftScopeRef = useRef<string | undefined>(undefined);+ const previousDraftIdentityRef = useRef({+ draftThreadId,+ threadListItemId,+ incognito,+ });+ const draftKey = composerDraftKey(draftThreadId, shareDraft);+ const draftScope = incognito+ ? INCOGNITO_DRAFT_SCOPE+ : `${draftKey}:${threadListItemId}`;// Text that came from Compare, 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);+ const pasteKeyShownRef = useRef<string | null>(incognito ? null : draftKey);// unsent pasted File objects need a separate slot because they exist only in memory- const pasteDraftKey = composerPasteDraftKey();+ const pasteDraftKey = composerPasteDraftKey(draftThreadId, shareDraft);const lastDraftScopeRef = useRef(draftScope);// save only after this chat's paste restore finishes to avoid premature clearingconst 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.+ const pendingDraftRef = useRef<{ key: string; text: string } | null>(null);+ // The key flips before the runtime swaps threads: until the restore shows, the text is the last chat's.+ const awaitingRestoreRef = useRef<{ scope: string; stale: string; text: string } | null>(null);useEffect(() => {+ const previous = previousDraftIdentityRef.current;+ previousDraftIdentityRef.current = {+ draftThreadId,+ threadListItemId,+ incognito,+ };const composer = aui.composer();if (!composer.getState().isEditing) return;+ if (+ restoredDraftScopeRef.current === draftScope &&+ previous.threadListItemId === threadListItemId+ ) return;+ restoredDraftScopeRef.current = draftScope;+ // First persistence names the same conversation; navigation must still restore its own draft.+ if (+ !incognito &&+ !previous.incognito &&+ !shareDraft &&+ previous.draftThreadId === NEW_CHAT_DRAFT_ID &&+ aui.threadListItem().getState().remoteId === draftThreadId &&+ previous.threadListItemId === threadListItemId &&+ previous.draftThreadId !== draftThreadId+ ) {+ const previousKey = composerDraftKey(previous.draftThreadId);+ const previousPasteKey = composerPasteDraftKey(previous.draftThreadId);+ if (justSentRef.current?.draftKey === previousKey) {+ justSentRef.current = { ...justSentRef.current, draftKey };+ }+ const text = latestDraft(previousKey);+ writeComposerDraft(draftKey, text);+ stageComposerDraft(draftKey, text);+ writePasteDraft(pasteDraftKey, latestPasteDraft(previousPasteKey));+ writeComposerDraft(previousKey, "");+ writePasteDraft(previousPasteKey, []);+ pasteKeyShownRef.current = draftKey;+ }if (draftScope === INCOGNITO_DRAFT_SCOPE) {composer.setText("");return;}- const draft = adoptLegacyDraft(draftScope)- ? (readComposerDraft(draftKey) ?? "")- : latestDraft();+ remoteDraftRef.current = null;+ const draft = latestDraft(draftKey);// A save that raced the send still holds the sent text, so restoring it// would undo the clear. Clear rather than return early, which would leave// the previous thread's text on screen under this one.@@ -4169,21 +4215,32 @@ const Composer: FC<{draftSaveTimerRef.current = null;}writeComposerDraft(draftKey, "");+ awaitingRestoreRef.current = { scope: draftScope, stale: composer.getState().text, text: "" };composer.setText("");return;}+ awaitingRestoreRef.current = { scope: draftScope, stale: composer.getState().text, text: draft };composer.setText(draft);- }, [draftScope, draftKey, aui]);+ }, [+ draftScope,+ draftKey,+ pasteDraftKey,+ shareDraft,+ draftThreadId,+ threadListItemId,+ incognito,+ aui,+ ]);// Compare's composer, so whichever is on screen shows the latest draft.useEffect(() => {- if (draftScope === INCOGNITO_DRAFT_SCOPE) return;+ if (!shareDraft || 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]);+ }, [draftScope, draftSource, shareDraft, aui]);// The saved-prompt menu and the prompt storage dialog fill the composer// directly, bypassing the guard. Text appearing after the send was put there// deliberately, so retire. Read live, or a@@ -4200,10 +4257,7 @@ const Composer: FC<{const composer = aui.composer();if (!composer.getState().isEditing) return;if (restoredPasteScopeRef.current === draftScope) return;- if (- (pasteScopeShownRef.current === INCOGNITO_DRAFT_SCOPE) !==- (draftScope === INCOGNITO_DRAFT_SCOPE)- ) {+ if (pasteKeyShownRef.current !== (incognito ? null : draftKey)) {const pasted = composer.getState().attachments.filter(@@ -4218,7 +4272,7 @@ const Composer: FC<{return;}}- pasteScopeShownRef.current = draftScope;+ pasteKeyShownRef.current = incognito ? null : draftKey;if (draftScope === INCOGNITO_DRAFT_SCOPE) {restoredPasteScopeRef.current = draftScope;return;@@ -4231,7 +4285,7 @@ const Composer: FC<{const text = pastedTextOf((attachment as { file?: File }).file);return text === undefined ? [] : [text];});- const missing = latestPasteDraft().filter((text) => {+ const missing = latestPasteDraft(pasteDraftKey).filter((text) => {const at = shown.indexOf(text);if (at === -1) return true;shown.splice(at, 1);@@ -4246,16 +4300,25 @@ const Composer: FC<{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.+ const restoredFiles = missing.map(createPastedTextFile);void Promise.all(- missing.map((text) => composer.addAttachment(createPastedTextFile(text))),+ restoredFiles.map((file) => composer.addAttachment(file)),).finally(() => {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;+ } else {+ // An adapter finishing after navigation reinserts its file; drop only this restore's files.+ for (const attachment of composer.getState().attachments) {+ const file = (attachment as { file?: File }).file;+ if (file && restoredFiles.includes(file)) {+ void composer.attachment({ id: attachment.id }).remove();+ }+ }}});- }, [draftScope, pasteDraftKey, composerAttachmentSignature, aui]);+ }, [draftScope, draftKey, incognito, 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(() => {@@ -4282,18 +4345,42 @@ const Composer: FC<{return;}if (draftScope === INCOGNITO_DRAFT_SCOPE) return;+ if (composerText !== aui.composer().getState().text) return;+ const awaiting = awaitingRestoreRef.current;+ if (awaiting?.scope === draftScope) {+ if (composerText === awaiting.stale && composerText !== awaiting.text) return;+ awaitingRestoreRef.current = null;+ }if (composerText === remoteDraftRef.current) return;remoteDraftRef.current = null;- publishDraft(composerText, draftSource);- const t = setTimeout(() => writeComposerDraft(draftKey, composerText), 300);+ if (shareDraft) publishDraft(composerText, draftSource);+ if (!shareDraft) {+ pendingDraftRef.current = { key: draftKey, text: composerText };+ stageComposerDraft(draftKey, composerText);+ }+ const t = setTimeout(() => {+ writeComposerDraft(draftKey, composerText);+ pendingDraftRef.current = null;+ }, 300);draftSaveTimerRef.current = t;return () => clearTimeout(t);- }, [composerText, draftScope, draftKey, draftSource]);+ }, [composerText, draftScope, draftKey, draftSource, shareDraft, aui]);+ useEffect(() => () => {+ const pending = pendingDraftRef.current;+ if (pending && !sentTextGuardBlocksDraft(justSentRef.current, pending.text, pending.key)) {+ flushComposerDraft(pending.key, pending.text);+ }+ pendingDraftRef.current = null;+ }, [draftScope]);const draftScopeRef = useRef(draftScope);+ const pasteDraftKeyRef = useRef(pasteDraftKey);+ const shareDraftRef = useRef(shareDraft);useEffect(() => {draftKeyRef.current = draftKey;draftScopeRef.current = draftScope;- }, [draftKey, draftScope]);+ pasteDraftKeyRef.current = pasteDraftKey;+ shareDraftRef.current = shareDraft;+ }, [draftKey, draftScope, pasteDraftKey, shareDraft]);// Call wherever the composer is emptied because its text left as a message.const armJustSent = useCallback((...texts: string[]) => {justSentRef.current = armSentTextGuard(@@ -4306,15 +4393,16 @@ const Composer: FC<{setIsWritingExpanded(false);}, [imeSessionOpenRef]);const clearStoredDraft = useCallback(() => {+ pendingDraftRef.current = null;if (draftSaveTimerRef.current !== null) {clearTimeout(draftSaveTimerRef.current);draftSaveTimerRef.current = null;}// A temporary chat's send was never the stored draft.if (draftScopeRef.current === INCOGNITO_DRAFT_SCOPE) return;- publishDraft("", draftSource);- writeComposerDraft(composerDraftKey(), "");- writePasteDraft(composerPasteDraftKey(), []);+ if (shareDraftRef.current) publishDraft("", draftSource);+ if (draftKeyRef.current) writeComposerDraft(draftKeyRef.current, "");+ writePasteDraft(pasteDraftKeyRef.current, []);}, [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 anddiff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 03cfdf96e94..93bc03c419e 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -1388,6 +1388,8 @@ const LoraCompareContent = memo(function LoraCompareContent({const [loraThreadId, setLoraThreadId] = useState<string>();const [pairLoraModelId, setPairLoraModelId] = useState<string>();const [threadsSettled, setThreadsSettled] = useState(false);+ const [pairSaved, setPairSaved] = useState<boolean>();+ const [submittedPairId, setSubmittedPairId] = useState<string | null>(null);const markInitialHistoryReady = useCompareReloadReadiness(pairId);const active = useChatActive();const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);@@ -1403,6 +1405,7 @@ const LoraCompareContent = memo(function LoraCompareContent({const listedPairRef = useRef<string | null>(null);useEffect(() => {+ if (listedPairRef.current !== pairId) setPairSaved(undefined);if (anyRunning && listedPairRef.current === pairId) return;listedPairRef.current = pairId;let isActive = true;@@ -1415,6 +1418,7 @@ const LoraCompareContent = memo(function LoraCompareContent({const loraThread = threads.find((t) => t.modelType === "lora");setBaseThreadId(baseThread?.id);setLoraThreadId(loraThread?.id);+ setPairSaved(Boolean(baseThread || loraThread));setPairLoraModelId(loraThread?.modelId?.trim() || baseThread?.modelId?.trim() || undefined,);@@ -1459,6 +1463,10 @@ const LoraCompareContent = memo(function LoraCompareContent({composer={active ? (<SharedComposer+ draftId={pairId}+ pairSaved={pairSaved}+ pairSubmitted={submittedPairId === pairId}+ onPairSubmitted={() => setSubmittedPairId(pairId)}handlesRef={handlesRef}onExitCompare={onExitCompare}model1ThreadId={baseThreadId}@@ -1644,6 +1652,8 @@ const GeneralCompareContent = memo(function GeneralCompareContent({const [model1ThreadId, setModel1ThreadId] = useState<string>();const [model2ThreadId, setModel2ThreadId] = useState<string>();const [threadsSettled, setThreadsSettled] = useState(false);+ const [pairSaved, setPairSaved] = useState<boolean>();+ const [submittedPairId, setSubmittedPairId] = useState<string | null>(null);const markInitialHistoryReady = useCompareReloadReadiness(pairId);const globalCheckpoint = useChatRuntimeStore((s) => s.params.checkpoint);@@ -1728,6 +1738,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({);useEffect(() => {+ if (listedPairRef.current !== pairId) setPairSaved(undefined);if ((anyRunning || comparing) && listedPairRef.current === pairId) return;listedPairRef.current = pairId;let isActive = true;@@ -1738,6 +1749,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({const pair = resolveComparePaneThreadIds(threads);setModel1ThreadId(pair.first);setModel2ThreadId(pair.second);+ setPairSaved(Boolean(pair.first || pair.second));}).catch((error) => {if (!isExpectedBackgroundChatStorageError(error)) {@@ -1775,6 +1787,10 @@ const GeneralCompareContent = memo(function GeneralCompareContent({composer={active ? (<SharedComposer+ draftId={pairId}+ pairSaved={pairSaved}+ pairSubmitted={submittedPairId === pairId}+ onPairSubmitted={() => setSubmittedPairId(pairId)}handlesRef={handlesRef}model1={model1}model2={model2}diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.tsindex 97f4294d478..bcd96a256cf 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts@@ -17,7 +17,11 @@ import {updateStoredChatThread,} from "../utils/chat-history-storage";import { clearBranchHead } from "../utils/branch-head";-import { clearComposerDraft } from "../utils/composer-draft";+import {+ clearComposerDraft,+ closeComposerDraft,+ reopenComposerDraft,+} from "../utils/composer-draft";import { offerToDeleteKeptSandboxes } from "../utils/offer-kept-sandbox-files";import { stopChatThread } from "../utils/stop-chat-thread";import {@@ -328,7 +332,8 @@ export async function deleteChatItems(}// clear composer drafts so deleted threads leave no orphan keys.- for (const id of threadIds) clearComposerDraft(id);+ const draftIds = [...threadIds, ...items.filter((i) => i.type !== "single").map((i) => i.id)];+ for (const id of draftIds) closeComposerDraft(id);// Quiet until the delete lands: a failed one restores the chats, browser tabs and all.markChatThreadsDeleted(threadIds, { quiet: true });@@ -348,10 +353,12 @@ export async function deleteChatItems(// retain the head until deletion succeeds so a restored chat reopens on the same branch.for (const id of threadIds) clearBranchHead(id);useBookmarkedTurnsStore.getState().forgetThreads(threadIds);+ for (const id of draftIds) clearComposerDraft(id);// offer recovery for sandbox files that outlive a deleted chat and lose their sidebar entry.offerToDeleteKeptSandboxes(kept);} catch (error) {removeChatThreadTombstones(threadIds);+ for (const id of draftIds) reopenComposerDraft(id);notifyChatHistoryUpdated();throw error;}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex fd7868f4655..163cd83f490 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -530,8 +530,11 @@ export {} from "./utils/export-chat-history";export {adoptLegacyDraft,+ flushComposerDraft,latestDraft,latestPasteDraft,+ NEW_CHAT_DRAFT_ID,+ stageComposerDraft,publishDraft,subscribeDraft,composerDraftKey,diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex b91e34ec79f..e28c2e2e847 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -103,7 +103,10 @@ import { insertAtCaret, richPasteMarkdown } from "./utils/rich-paste";import { isPlainPasteChord, plainPasteStillCounts } from "./utils/pasted-text";import {composerDraftKey,+ flushComposerDraft,latestDraft,+ NEW_COMPARE_DRAFT_ID,+ stageComposerDraft,publishDraft,subscribeDraft,writeComposerDraft,@@ -636,6 +639,10 @@ async function waitForBackendLoadToSettle(): Promise<void> {}export function SharedComposer({+ draftId,+ pairSaved,+ pairSubmitted,+ onPairSubmitted,handlesRef,model1,model2,@@ -646,6 +653,10 @@ export function SharedComposer({sendUnavailableReason,requireStableCheckpoint = false,}: {+ draftId: string;+ pairSaved?: boolean;+ pairSubmitted: boolean;+ onPairSubmitted: () => void;handlesRef: CompareHandles;model1?: CompareModelSelection;model2?: CompareModelSelection;@@ -668,48 +679,62 @@ export function SharedComposer({navigate({ to: "/chat" });}, [navigate, onExitCompare]);const incognito = useChatRuntimeStore((s) => s.incognito);+ const shareDraft = useChatPreferencesStore((s) => s.shareComposerDraft);+ const syncDraft = shareDraft && !incognito;+ const unsentPair = pairSaved === false && !pairSubmitted;+ const draftKey = composerDraftKey(unsentPair ? NEW_COMPARE_DRAFT_ID : draftId, shareDraft);+ const draftScope = incognito ? null : draftKey;const [text, setText] = useState(() =>- useChatRuntimeStore.getState().incognito ? "" : latestDraft(),+ incognito ? "" : latestDraft(draftKey),);const [draftSource] = useState(() => Symbol("compare composer"));// Text that came from the chat composer, so it isn't published back.const remoteDraftRef = useRef<string | null>(null);- const unsavedDraftRef = useRef<string | null>(null);- const incognitoBeforeRef = useRef(incognito);+ const unsavedDraftRef = useRef<{ key: string; text: string } | null>(null);+ const draftScopeBeforeRef = useRef(draftScope);+ const draftOwnerBeforeRef = useRef({ draftId, shareDraft, draftKey });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);+ if (draftScopeBeforeRef.current !== draftScope) {+ draftScopeBeforeRef.current = draftScope;+ const before = draftOwnerBeforeRef.current;+ draftOwnerBeforeRef.current = { draftId, shareDraft, draftKey };+ let next = incognito ? "" : latestDraft(draftKey);+ if (!incognito && before.draftId === draftId && before.shareDraft === shareDraft && text) {+ // Same pair, slot decided by its history: what was typed while it loaded wins.+ writeComposerDraft(before.draftKey, "");+ writeComposerDraft(draftKey, text);+ next = text;}+ if (!incognito && !shareDraft) stageComposerDraft(draftKey, next);+ remoteDraftRef.current = next;+ setText(next);return;}if (incognito || text === remoteDraftRef.current) return;remoteDraftRef.current = null;- publishDraft(text, draftSource);+ if (shareDraft) 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(), "");+ writeComposerDraft(draftKey, "");unsavedDraftRef.current = null;return;}- unsavedDraftRef.current = text;+ unsavedDraftRef.current = { key: draftKey, text };+ stageComposerDraft(draftKey, text);const timer = setTimeout(() => {- writeComposerDraft(composerDraftKey(), text);+ writeComposerDraft(draftKey, text);unsavedDraftRef.current = null;}, 300);return () => clearTimeout(timer);- }, [text, incognito, draftSource]);- // Leaving Compare inside the debounce still saves what was typed.+ }, [text, draftScope, draftKey, incognito, shareDraft, draftSource]);useEffect(() => () => {if (unsavedDraftRef.current !== null) {- writeComposerDraft(composerDraftKey(), unsavedDraftRef.current);+ flushComposerDraft(unsavedDraftRef.current.key, unsavedDraftRef.current.text);+ unsavedDraftRef.current = null;}},- [],+ [draftScope],);const shortcutLabels = composerShortcutLabels(sendShortcut, isMacPlatform(), text);const [running, setRunning] = useState(false);@@ -739,12 +764,13 @@ export function SharedComposer({[],);useEffect(() => {- if (incognito) return;+ if (!syncDraft) return;return subscribeDraft(draftSource, (next) => {+ unsavedDraftRef.current = null;remoteDraftRef.current = next;setCurrentText(next);});- }, [incognito, draftSource, setCurrentText]);+ }, [syncDraft, draftSource, setCurrentText]);// Attachments still classifying or converting; a ref so runPromptList reads it synchronously.const attachingRef = useRef(0);useEffect(() => {@@ -1565,6 +1591,11 @@ export function SharedComposer({});};const clearSubmittedDraft = () => {+ if (unsentPair) {+ unsavedDraftRef.current = null;+ if (!shareDraft) writeComposerDraft(draftKey, "");+ }+ onPairSubmitted();setCurrentText("");setIsWritingExpanded(false);setPendingImages([]);diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.tsindex 16db6911cb6..89d4f11c575 100644--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { create } from "zustand";+import { adoptCurrentDraft } from "../utils/composer-draft.ts";import { persist } from "zustand/middleware";import { syncAcrossWindows } from "../../../lib/sync-across-windows.ts";import {@@ -26,6 +27,8 @@ import {} from "../lib/live-generation-stats.ts";export interface ChatPreferencesState {+ shareComposerDraft: boolean;+ setShareComposerDraft: (value: boolean) => void;plainTextComposer: boolean;setPlainTextComposer: (value: boolean) => void;showContextWindowUsage: boolean;@@ -95,6 +98,8 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(persist((set) => ({...normalizeComposerPreferences(null),+ shareComposerDraft: false,+ setShareComposerDraft: (shareComposerDraft) => set({ shareComposerDraft }),setPlainTextComposer: (plainTextComposer) => set({ plainTextComposer }),setShowContextWindowUsage: (showContextWindowUsage) =>set({ showContextWindowUsage }),@@ -169,6 +174,7 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(return {...current,...normalizeComposerPreferences(saved),+ shareComposerDraft: saved?.shareComposerDraft === true,confirmDeleteChats: saved?.confirmDeleteChats ?? true,alwaysDeleteChatFiles: saved?.alwaysDeleteChatFiles ?? false,showResponseModel: saved?.showResponseModel ?? false,@@ -211,3 +217,7 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()();syncAcrossWindows(useChatPreferencesStore);+// Here, not in the setter: another window's switch arrives as a rehydrate, which skips setters.+useChatPreferencesStore.subscribe((state, prev) => {+ if (state.shareComposerDraft && !prev.shareComposerDraft) adoptCurrentDraft();+});diff --git a/studio/frontend/src/features/chat/utils/clear-all-chats.ts b/studio/frontend/src/features/chat/utils/clear-all-chats.tsindex 73dbffeebde..6a986daf1b4 100644--- a/studio/frontend/src/features/chat/utils/clear-all-chats.ts+++ b/studio/frontend/src/features/chat/utils/clear-all-chats.ts@@ -5,7 +5,12 @@ import { useBookmarkedTurnsStore } from "../stores/bookmarked-turns-store";import { useChatRuntimeStore } from "../stores/chat-runtime-store";import { usePinnedChatsStore } from "../stores/pinned-chats-store";import { chatHistoryClearBoundary } from "./chat-history-clear-boundary";-import { clearStoredChats, countStoredChats } from "./chat-history-storage";+import {+ clearStoredChats,+ countStoredChats,+ listStoredChatThreads,+} from "./chat-history-storage";+import { clearComposerDraft } from "./composer-draft";import { requestPromptQueueStop } from "./prompt-queue-boundary";import { stopChatThread } from "./stop-chat-thread";@@ -27,13 +32,31 @@ export async function clearAllChats(options: { deleteFiles?: boolean } = {}) {requestPromptQueueStop();// Snapshot first: a chat another client creates and pins mid-clear survives it.const pinnedBefore = usePinnedChatsStore.getState().pinnedIds;+ // Only finds Compare pairs; an unreachable backend must not stop the clear.+ const threadsBefore = await listStoredChatThreads({+ includeArchived: true,+ }).catch(() => []);const result = await clearStoredChats(options);+ const deleted = new Set(result.deletedThreadIds);+ for (const id of deleted) clearComposerDraft(id);+ // A partially deleted comparison still owns its draft.+ const pairs = new Map<string, string[]>();+ for (const thread of threadsBefore) {+ if (!thread.pairId) continue;+ const ids = pairs.get(thread.pairId) ?? [];+ ids.push(thread.id);+ pairs.set(thread.pairId, ids);+ }+ for (const [pairId, ids] of pairs) {+ if (ids.every((id) => deleted.has(id))) clearComposerDraft(pairId);+ }useBookmarkedTurnsStore.getState().forgetThreads(result.deletedThreadIds);if (result.backend === "cleared") {// Unpin what was cleared, so a never-imported comparison's queued pin cannot block later saves.const failed = new Set(result.failedThreadIds);const removed = pinnedBefore.filter((id) => !failed.has(id));- if (removed.length > 0) usePinnedChatsStore.getState().setPinned(removed, false);+ if (removed.length > 0)+ usePinnedChatsStore.getState().setPinned(removed, false);}return result;}diff --git a/studio/frontend/src/features/chat/utils/composer-draft.ts b/studio/frontend/src/features/chat/utils/composer-draft.tsindex 249f4484bfb..8b3dd84a8df 100644--- a/studio/frontend/src/features/chat/utils/composer-draft.ts+++ b/studio/frontend/src/features/chat/utils/composer-draft.ts@@ -1,22 +1,23 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// 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).+// The chat-draft prefix is what account-transition.ts clears on account switches.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:";+// Unsent New chat and Compare ids are minted per navigation; per-id slots would pile up unread.+export const NEW_CHAT_DRAFT_ID = "__new__";+export const NEW_COMPARE_DRAFT_ID = "__compare_new__";-export function composerDraftKey(): string {- return DRAFT_KEY;+export function composerDraftKey(threadId: string, shared = false): string {+ return shared ? DRAFT_KEY : `${LEGACY_DRAFT_PREFIX}${threadId}`;}// 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(): string {- return PASTE_DRAFT_KEY;+export function composerPasteDraftKey(threadId: string, shared = false): string {+ return shared ? PASTE_DRAFT_KEY : `${LEGACY_PASTE_DRAFT_PREFIX}${threadId}`;}export function readPasteDraft(key: string): string[] {@@ -26,6 +27,10 @@ export function readPasteDraft(key: string): string[] {} catch {return [];}+ return parsePastes(raw);+}++function parsePastes(raw: string | null): string[] {if (!raw) return [];try {const parsed: unknown = JSON.parse(raw);@@ -38,14 +43,24 @@ export function readPasteDraft(key: string): string[] {// This tab's pastes once it saves any, as `latest` is for its text.let latestPastes: string[] | null = null;+const perChatPastes = new Map<string, string[]>();-export function latestPasteDraft(): string[] {- return latestPastes !== null ? [...latestPastes] : readPasteDraft(PASTE_DRAFT_KEY);+export function latestPasteDraft(key = PASTE_DRAFT_KEY): string[] {+ if (key === PASTE_DRAFT_KEY) {+ return latestPastes !== null ? [...latestPastes] : readPasteDraft(key);+ }+ if (!perChatPastes.has(key)) perChatPastes.set(key, readPasteDraft(key));+ return [...perChatPastes.get(key)!];}// A quota error here leaves the text draft untouched, hence separate slots.export function writePasteDraft(key: string, pastes: readonly string[]): void {if (key === PASTE_DRAFT_KEY) latestPastes = [...pastes];+ else {+ if (deletedDraftIds.has(key.slice(LEGACY_PASTE_DRAFT_PREFIX.length))) return;+ perChatPastes.set(key, [...pastes]);+ if (pastes.length > 0) lastTypedDraftId = key.slice(LEGACY_PASTE_DRAFT_PREFIX.length);+ }try {if (pastes.length > 0) {window.localStorage.setItem(key, JSON.stringify(pastes));@@ -66,7 +81,24 @@ export function readComposerDraft(key: string): string | null {}}+// Typing inside the save debounce: this tab's cache shows it at once, so adoption takes it.+export function stageComposerDraft(key: string, text: string): void {+ if (key === DRAFT_KEY || deletedDraftIds.has(key.slice(LEGACY_DRAFT_PREFIX.length))) return;+ perChatDrafts.set(key, text);+ if (text) lastTypedDraftId = key.slice(LEGACY_DRAFT_PREFIX.length);+}++// A staged save whose slot was adopted (or deleted) since must not recreate it.+export function flushComposerDraft(key: string, text: string): void {+ if (key !== DRAFT_KEY && perChatDrafts.get(key) !== text) return;+ writeComposerDraft(key, text);+}+export function writeComposerDraft(key: string, text: string): void {+ if (key !== DRAFT_KEY) {+ if (deletedDraftIds.has(key.slice(LEGACY_DRAFT_PREFIX.length))) return;+ perChatDrafts.set(key, text);+ }try {if (text.length > 0) window.localStorage.setItem(key, text);else window.localStorage.removeItem(key);@@ -77,31 +109,48 @@ export function writeComposerDraft(key: string, text: string): 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 {+export function adoptLegacyDraft(threadId: string | null, overwrite = false): boolean {// Text typed this session and not yet saved is newer than any old slot.- if (latest) return false;+ if (latest && !overwrite) return false;const id = threadId ?? "__new__";try {const storage = window.localStorage;- const text = storage.getItem(`${LEGACY_DRAFT_PREFIX}${id}`);- const pastes = storage.getItem(`${LEGACY_PASTE_DRAFT_PREFIX}${id}`);+ // This tab's copy first: another window may have written its own draft to the same slot since.+ const textKey = `${LEGACY_DRAFT_PREFIX}${id}`;+ const pasteKey = `${LEGACY_PASTE_DRAFT_PREFIX}${id}`;+ const cachedText = perChatDrafts.get(textKey);+ const cachedPastes = perChatPastes.get(pasteKey);+ const text = cachedText !== undefined ? cachedText || null : storage.getItem(textKey);+ const pastes =+ cachedPastes !== undefined+ ? cachedPastes.length > 0 ? JSON.stringify(cachedPastes) : null+ : storage.getItem(pasteKey);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);+ const prevText = storage.getItem(DRAFT_KEY);+ const prevPastes = storage.getItem(PASTE_DRAFT_KEY);+ if (overwrite || (prevText === null && prevPastes === null)) {try {+ if (text !== null) storage.setItem(DRAFT_KEY, text);+ else storage.removeItem(DRAFT_KEY);if (pastes !== null) storage.setItem(PASTE_DRAFT_KEY, pastes);+ else storage.removeItem(PASTE_DRAFT_KEY);} catch (error) {// All or nothing: a text-only copy would make the next try skip, dropping the paste.- storage.removeItem(DRAFT_KEY);+ if (prevText === null) storage.removeItem(DRAFT_KEY);+ else storage.setItem(DRAFT_KEY, prevText);+ if (prevPastes === null) storage.removeItem(PASTE_DRAFT_KEY);+ else storage.setItem(PASTE_DRAFT_KEY, prevPastes);throw error;}adopted = true;+ // Seeded from what was adopted: another window's adoption may already have replaced storage.+ latest = text ?? "";seeded = null;- latestPastes = null;+ latestPastes = parsePastes(pastes);+ // Moved, not copied: a copy left behind would return a prompt sent from the shared slot.+ dropPerChatDraft(id);}- storage.removeItem(`${LEGACY_DRAFT_PREFIX}${id}`);- storage.removeItem(`${LEGACY_PASTE_DRAFT_PREFIX}${id}`);return adopted;} catch {return false;@@ -115,8 +164,20 @@ type DraftListener = (text: string, source: symbol) => void;const draftListeners = new Set<DraftListener>();let latest: string | null = null;let seeded: string | null = null;+const perChatDrafts = new Map<string, string>();+// This tab's last-typed per-chat slot: what sharing adopts, even unmounted (Settings hides chat).+let lastTypedDraftId: string | null = null;-export function latestDraft(): string {+export function adoptCurrentDraft(): boolean {+ // What this tab just typed wins over an older shared draft, including another window's (#15782).+ return lastTypedDraftId !== null && adoptLegacyDraft(lastTypedDraftId, true);+}++export function latestDraft(key = DRAFT_KEY): string {+ if (key !== DRAFT_KEY) {+ if (!perChatDrafts.has(key)) perChatDrafts.set(key, readComposerDraft(key) ?? "");+ return perChatDrafts.get(key)!;+ }if (latest !== null) return latest;seeded ??= readComposerDraft(DRAFT_KEY) ?? "";return seeded;@@ -136,8 +197,27 @@ export function subscribeDraft(source: symbol, listener: (text: string) => void)return () => draftListeners.delete(wrapped);}-// A deleted chat's leftover per-chat draft; never the shared one.+// A deleted chat's pending autosave can land after the delete; its slot stays closed.+const deletedDraftIds = new Set<string>();+export function clearComposerDraft(threadId: string): void {+ deletedDraftIds.add(threadId);+ dropPerChatDraft(threadId);+}++// While a delete is in flight: late writes are dropped, the draft survives a failed delete.+export function closeComposerDraft(threadId: string): void {+ deletedDraftIds.add(threadId);+}++export function reopenComposerDraft(threadId: string): void {+ deletedDraftIds.delete(threadId);+}++function dropPerChatDraft(threadId: string): void {+ if (lastTypedDraftId === threadId) lastTypedDraftId = null;+ perChatDrafts.delete(composerDraftKey(threadId));+ perChatPastes.delete(composerPasteDraftKey(threadId));try {window.localStorage.removeItem(`${LEGACY_DRAFT_PREFIX}${threadId}`);window.localStorage.removeItem(`${LEGACY_PASTE_DRAFT_PREFIX}${threadId}`);diff --git a/studio/frontend/src/features/settings/components/composer-settings.tsx b/studio/frontend/src/features/settings/components/composer-settings.tsxindex d4b604525ef..2061b77b376 100644--- a/studio/frontend/src/features/settings/components/composer-settings.tsx+++ b/studio/frontend/src/features/settings/components/composer-settings.tsx@@ -134,6 +134,16 @@ export function ComposerSettings({ embedded = false }: { embedded?: boolean }) {))}</div></SettingsRow>+ <SettingsRow+ label={t("composerSettings.shareDraft")}+ description={t("composerSettings.shareDraftDescription")}+ >+ <Switch+ aria-label={t("composerSettings.shareDraft")}+ checked={prefs.shareComposerDraft}+ onCheckedChange={prefs.setShareComposerDraft}+ />+ </SettingsRow></div></SettingsSection></div>diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 8afcc3b8cba..a621a228e99 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -665,6 +665,8 @@ export const ar = {keepsRunning: "إغلاق هذه النافذة لا يوقف الإعداد. تظهر نتيجته في الإعدادات > الأمان.",},composerSettings: {+ shareDraft: "مشاركة المسودات بين المحادثات",+ shareDraftDescription: "استخدام مسودة واحدة للمحادثات والمقارنة. معطّل افتراضيًا؛ تحتفظ كل محادثة بمسودتها الخاصة.",title: "كتابة الرسائل",plainText: "محرر نص عادي",plainTextDescription: "إبقاء التعليمات البرمجية وMarkdown والروابط كنص حرفي. عطّل هذا الخيار لعرض معاينة منسقة.",diff --git a/studio/frontend/src/i18n/locales/cs.ts b/studio/frontend/src/i18n/locales/cs.tsindex ccc37e96c20..8cf2323d0f0 100644--- a/studio/frontend/src/i18n/locales/cs.ts+++ b/studio/frontend/src/i18n/locales/cs.ts@@ -749,6 +749,8 @@ export const cs = {"Zavřením tohoto okna se nastavení nezastaví. Jeho výsledek se zobrazí v části Nastavení > Zabezpečení.",},composerSettings: {+ shareDraft: "Sdílet koncepty mezi chaty",+ shareDraftDescription: "Používat jeden koncept pro chaty a porovnání. Ve výchozím stavu vypnuto; každý chat si ponechá vlastní koncept.",title: "Pole zprávy",plainText: "Pole zprávy s prostým textem",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 10707ba53f0..05c54d5cb06 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -665,6 +665,8 @@ export const de = {keepsRunning: "Das Schließen beendet die Einrichtung nicht. Das Ergebnis erscheint unter Einstellungen > Sicherheit.",},composerSettings: {+ shareDraft: "Entwürfe zwischen Chats teilen",+ shareDraftDescription: "Einen Entwurf für Chats und Vergleiche verwenden. Standardmäßig aus; jeder Chat behält seinen eigenen Entwurf.",title: "Nachrichteneingabe",plainText: "Eingabe als Klartext",plainTextDescription: "Code, Markdown und Links als wörtlichen Text anzeigen. Ausschalten, um eine formatierte Vorschau zu sehen.",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 5c487802c00..cb985aa8cae 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -662,6 +662,8 @@ export const en = {keepsRunning: "Closing this does not stop the setup. Its result shows in Settings > Security.",},composerSettings: {+ shareDraft: "Share drafts across chats",+ shareDraftDescription: "Use one draft across chats and Compare. Off by default; each chat keeps its own draft.",title: "Composer",plainText: "Plain text composer",plainTextDescription: "Keep code, Markdown, and links as literal text. Turn off to show a formatted preview.",diff --git a/studio/frontend/src/i18n/locales/es-419.ts b/studio/frontend/src/i18n/locales/es-419.tsindex d9415a8f17d..b9c924baec4 100644--- a/studio/frontend/src/i18n/locales/es-419.ts+++ b/studio/frontend/src/i18n/locales/es-419.ts@@ -752,6 +752,8 @@ export const es419 = {"Cerrar esto no detiene la configuración. El resultado aparece en Configuración > Seguridad.",},composerSettings: {+ shareDraft: "Compartir borradores entre chats",+ shareDraftDescription: "Usa un borrador para los chats y las comparaciones. Desactivado por defecto; cada chat conserva su propio borrador.",title: "Redactor",plainText: "Redactor de texto sin formato",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex de5ead339ba..d1cec5f1558 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -665,6 +665,8 @@ export const es = {keepsRunning: "Cerrar esto no detiene la configuración. El resultado aparece en Ajustes > Seguridad.",},composerSettings: {+ shareDraft: "Compartir borradores entre chats",+ shareDraftDescription: "Usa un borrador para los chats y las comparaciones. Desactivado por defecto; cada chat conserva su propio borrador.",title: "Redacción de mensajes",plainText: "Redactor de texto sin formato",plainTextDescription: "Mantener el código, Markdown y los enlaces como texto literal. Desactívalo para mostrar una vista previa con formato.",diff --git a/studio/frontend/src/i18n/locales/fa.ts b/studio/frontend/src/i18n/locales/fa.tsindex 2558f765d28..1e470a9a3e6 100644--- a/studio/frontend/src/i18n/locales/fa.ts+++ b/studio/frontend/src/i18n/locales/fa.ts@@ -745,6 +745,8 @@ export const fa = {"بستن این پنجره راهاندازی را متوقف نمیکند. نتیجهٔ آن در «تنظیمات > امنیت» نمایش داده میشود.",},composerSettings: {+ shareDraft: "اشتراکگذاری پیشنویسها بین گفتگوها",+ shareDraftDescription: "از یک پیشنویس برای گفتگوها و مقایسه استفاده کنید. بهطور پیشفرض خاموش است؛ هر گفتگو پیشنویس خودش را نگه میدارد.",title: "کادر نوشتن",plainText: "کادر نوشتن متن ساده",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 9dccbcb2c17..0c9a832fafa 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -665,6 +665,8 @@ export const fr = {keepsRunning: "Fermer cette fenêtre n'arrête pas la configuration. Le résultat s'affiche dans Paramètres > Sécurité.",},composerSettings: {+ shareDraft: "Partager les brouillons entre les discussions",+ shareDraftDescription: "Utiliser un seul brouillon pour les discussions et les comparaisons. Désactivé par défaut ; chaque discussion conserve son propre brouillon.",title: "Saisie des messages",plainText: "Saisie en texte brut",plainTextDescription: "Conserver le code, le Markdown et les liens en texte brut. Désactivez pour afficher un aperçu mis en forme.",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 12ada630ea9..56f18ded81b 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -698,6 +698,8 @@ export const he = {"סגירת חלון זה לא עוצרת את ההגדרה. התוצאה תוצג בהגדרות > אבטחה.",},composerSettings: {+ shareDraft: "שיתוף טיוטות בין שיחות",+ shareDraftDescription: "שימוש בטיוטה אחת בשיחות ובהשוואה. כבוי כברירת מחדל; כל שיחה שומרת טיוטה משלה.",title: "עורך ההודעות",plainText: "עורך טקסט פשוט",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex e57781da875..e524036abeb 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -665,6 +665,8 @@ export const hi = {keepsRunning: "इसे बंद करने से सेटअप नहीं रुकता। इसका परिणाम सेटिंग्स > सुरक्षा में दिखता है।",},composerSettings: {+ shareDraft: "चैट के बीच ड्राफ़्ट साझा करें",+ shareDraftDescription: "चैट और तुलना में एक ही ड्राफ़्ट का उपयोग करें। डिफ़ॉल्ट रूप से बंद; हर चैट अपना ड्राफ़्ट रखती है।",title: "संदेश लिखना",plainText: "सादा टेक्स्ट इनपुट",plainTextDescription: "कोड, Markdown और लिंक को मूल टेक्स्ट के रूप में रखें। फ़ॉर्मैट किया हुआ पूर्वावलोकन दिखाने के लिए इसे बंद करें।",diff --git a/studio/frontend/src/i18n/locales/id.ts b/studio/frontend/src/i18n/locales/id.tsindex 6a0b0982369..5e04a1c2964 100644--- a/studio/frontend/src/i18n/locales/id.ts+++ b/studio/frontend/src/i18n/locales/id.ts@@ -746,6 +746,8 @@ export const id = {"Menutup ini tidak menghentikan penyiapan. Hasilnya ditampilkan di Pengaturan > Keamanan.",},composerSettings: {+ shareDraft: "Bagikan draf antarobrolan",+ shareDraftDescription: "Gunakan satu draf untuk obrolan dan perbandingan. Nonaktif secara default; setiap obrolan menyimpan drafnya sendiri.",title: "Kolom pesan",plainText: "Kolom pesan teks biasa",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 9863501eab2..417f81a02ab 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -662,6 +662,8 @@ export const it = {keepsRunning: "Chiudere non interrompe la configurazione. Il risultato compare in Impostazioni > Sicurezza.",},composerSettings: {+ shareDraft: "Condividi le bozze tra chat",+ shareDraftDescription: "Usa una sola bozza per chat e confronti. Disattivato per impostazione predefinita; ogni chat mantiene la propria bozza.",title: "Composizione dei messaggi",plainText: "Composizione in testo semplice",plainTextDescription: "Mantieni codice, Markdown e link come testo letterale. Disattiva per mostrare un’anteprima formattata.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 67bb2e43f47..408fcd14fed 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -666,6 +666,8 @@ export const ja = {keepsRunning: "閉じても設定は止まりません。結果は 設定 > セキュリティ に表示されます。",},composerSettings: {+ shareDraft: "チャット間で下書きを共有",+ shareDraftDescription: "チャットと比較で1つの下書きを使用します。既定ではオフで、各チャットが個別の下書きを保持します。",title: "入力欄",plainText: "プレーンテキスト入力",plainTextDescription: "コード、Markdown、リンクをそのままのテキストで表示します。オフにすると書式付きプレビューを表示します。",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 1cb17cf0338..555e0d9dfd4 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -665,6 +665,8 @@ export const ko = {keepsRunning: "닫아도 설정은 멈추지 않습니다. 결과는 설정 > 보안에 표시됩니다.",},composerSettings: {+ shareDraft: "채팅 간에 초안 공유",+ shareDraftDescription: "채팅과 비교에서 하나의 초안을 사용합니다. 기본적으로 꺼져 있으며 각 채팅은 자체 초안을 유지합니다.",title: "메시지 입력",plainText: "일반 텍스트 입력",plainTextDescription: "코드, Markdown, 링크를 원문 그대로 표시합니다. 끄면 서식 미리보기를 표시합니다.",diff --git a/studio/frontend/src/i18n/locales/nl.ts b/studio/frontend/src/i18n/locales/nl.tsindex b2a488aea7f..402853442b9 100644--- a/studio/frontend/src/i18n/locales/nl.ts+++ b/studio/frontend/src/i18n/locales/nl.ts@@ -753,6 +753,8 @@ export const nl = {"Als je dit sluit, wordt het instellen niet gestopt. Het resultaat wordt weergegeven in Instellingen > Beveiliging.",},composerSettings: {+ shareDraft: "Concepten delen tussen chats",+ shareDraftDescription: "Gebruik één concept voor chats en vergelijkingen. Standaard uit; elke chat bewaart zijn eigen concept.",title: "Invoerveld",plainText: "Invoerveld met platte tekst",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/pl.ts b/studio/frontend/src/i18n/locales/pl.tsindex bcc12371fb6..927aea3ef8e 100644--- a/studio/frontend/src/i18n/locales/pl.ts+++ b/studio/frontend/src/i18n/locales/pl.ts@@ -753,6 +753,8 @@ export const pl = {"Zamknięcie tego okna nie zatrzymuje konfiguracji. Jej wynik pojawi się w sekcji Ustawienia > Bezpieczeństwo.",},composerSettings: {+ shareDraft: "Udostępniaj szkice między czatami",+ shareDraftDescription: "Używaj jednego szkicu w czatach i porównaniach. Domyślnie wyłączone; każdy czat zachowuje własny szkic.",title: "Pole wiadomości",plainText: "Pole wiadomości z czystym tekstem",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 6a7f48de78e..972893d3d71 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -665,6 +665,8 @@ export const ptBR = {keepsRunning: "Fechar isto não interrompe a configuração. O resultado aparece em Configurações > Segurança.",},composerSettings: {+ shareDraft: "Compartilhar rascunhos entre conversas",+ shareDraftDescription: "Use um único rascunho em conversas e comparações. Desativado por padrão; cada conversa mantém seu próprio rascunho.",title: "Composição de mensagens",plainText: "Composição em texto simples",plainTextDescription: "Manter código, Markdown e links como texto literal. Desative para mostrar uma prévia formatada.",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 991adbc3617..47bb1f2b9f2 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -665,6 +665,8 @@ export const ru = {keepsRunning: "Закрытие не останавливает настройку. Результат появится в разделе Настройки > Безопасность.",},composerSettings: {+ shareDraft: "Общий черновик для чатов",+ shareDraftDescription: "Использовать один черновик в чатах и сравнении. По умолчанию выключено; у каждого чата свой черновик.",title: "Ввод сообщений",plainText: "Обычный текст",plainTextDescription: "Показывать код, Markdown и ссылки как обычный текст. Отключите для предпросмотра форматирования.",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex cca9308ac90..a174dc9ca2e 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -707,6 +707,8 @@ export const sv = {"Att stänga detta stoppar inte konfigurationen. Resultatet visas i Inställningar > Säkerhet.",},composerSettings: {+ shareDraft: "Dela utkast mellan chattar",+ shareDraftDescription: "Använd ett utkast för chattar och jämförelser. Av som standard; varje chatt behåller sitt eget utkast.",title: "Skrivfält",plainText: "Skrivfält med oformaterad text",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/th.ts b/studio/frontend/src/i18n/locales/th.tsindex 0f3a45eb1e8..29b4f24331d 100644--- a/studio/frontend/src/i18n/locales/th.ts+++ b/studio/frontend/src/i18n/locales/th.ts@@ -712,6 +712,8 @@ export const th = {"การปิดหน้าต่างนี้จะไม่หยุดการตั้งค่า ผลลัพธ์จะแสดงในการตั้งค่า > ความปลอดภัย",},composerSettings: {+ shareDraft: "แชร์แบบร่างระหว่างแชต",+ shareDraftDescription: "ใช้แบบร่างเดียวกันในแชตและการเปรียบเทียบ ปิดไว้ตามค่าเริ่มต้น โดยแต่ละแชตจะเก็บแบบร่างของตนเอง",title: "ช่องเขียนข้อความ",plainText: "ช่องเขียนข้อความแบบข้อความธรรมดา",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/tr.ts b/studio/frontend/src/i18n/locales/tr.tsindex e76577a510b..1b13e33bc10 100644--- a/studio/frontend/src/i18n/locales/tr.ts+++ b/studio/frontend/src/i18n/locales/tr.ts@@ -747,6 +747,8 @@ export const tr = {"Bunu kapatmak kurulumu durdurmaz. Sonuç, Ayarlar > Güvenlik bölümünde görünür.",},composerSettings: {+ shareDraft: "Taslakları sohbetler arasında paylaş",+ shareDraftDescription: "Sohbetler ve karşılaştırmalar için tek bir taslak kullan. Varsayılan olarak kapalıdır; her sohbet kendi taslağını tutar.",title: "Yazma alanı",plainText: "Düz metin yazma alanı",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/uk.ts b/studio/frontend/src/i18n/locales/uk.tsindex 1e6b8e8cecf..2052c0e7ada 100644--- a/studio/frontend/src/i18n/locales/uk.ts+++ b/studio/frontend/src/i18n/locales/uk.ts@@ -754,6 +754,8 @@ export const uk = {"Закриття цього вікна не зупиняє налаштування. Результат з’явиться в розділі «Налаштування > Безпека».",},composerSettings: {+ shareDraft: "Спільна чернетка для чатів",+ shareDraftDescription: "Використовувати одну чернетку в чатах і порівнянні. Типово вимкнено; кожен чат зберігає власну чернетку.",title: "Поле введення",plainText: "Поле введення простого тексту",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/vi.ts b/studio/frontend/src/i18n/locales/vi.tsindex 933bdd96421..d8a06f983ca 100644--- a/studio/frontend/src/i18n/locales/vi.ts+++ b/studio/frontend/src/i18n/locales/vi.ts@@ -749,6 +749,8 @@ export const vi = {"Đóng cửa sổ này không dừng quá trình thiết lập. Kết quả sẽ hiển thị trong Cài đặt > Bảo mật.",},composerSettings: {+ shareDraft: "Chia sẻ bản nháp giữa các cuộc trò chuyện",+ shareDraftDescription: "Dùng một bản nháp cho các cuộc trò chuyện và chế độ so sánh. Mặc định tắt; mỗi cuộc trò chuyện giữ bản nháp riêng.",title: "Khung soạn thảo",plainText: "Khung soạn thảo văn bản thuần",plainTextDescription:diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 8bf3f5cc897..5271da54524 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -665,6 +665,8 @@ export const zhCN = {keepsRunning: "关闭不会停止设置。结果会显示在 设置 > 安全 中。",},composerSettings: {+ shareDraft: "在聊天之间共享草稿",+ shareDraftDescription: "在聊天和对比中使用同一份草稿。默认关闭;每个聊天保留各自的草稿。",title: "消息输入",plainText: "纯文本输入",plainTextDescription: "将代码、Markdown 和链接保留为原始文本。关闭后显示格式化预览。",diff --git a/studio/frontend/src/i18n/locales/zh-TW.ts b/studio/frontend/src/i18n/locales/zh-TW.tsindex bacfbe42206..7be3fb50adb 100644--- a/studio/frontend/src/i18n/locales/zh-TW.ts+++ b/studio/frontend/src/i18n/locales/zh-TW.ts@@ -708,6 +708,8 @@ export const zhTW = {keepsRunning: "關閉此視窗不會停止設定。結果會顯示在「設定 > 安全性」中。",},composerSettings: {+ shareDraft: "跨聊天共用草稿",+ shareDraftDescription: "在聊天和比較中使用同一份草稿。預設關閉;每個聊天保留各自的草稿。",title: "輸入框",plainText: "純文字輸入框",plainTextDescription:diff --git a/studio/frontend/tests/chat-settings-sections.test.ts b/studio/frontend/tests/chat-settings-sections.test.tsindex f1638ab954d..af07740fdf6 100644--- a/studio/frontend/tests/chat-settings-sections.test.ts+++ b/studio/frontend/tests/chat-settings-sections.test.ts@@ -48,6 +48,7 @@ test("Chat defaults keeps the everyday rows: send and follow-up, scrolling, pastassert.deepEqual(composerLabels(composerBody("ComposerSettings")), ["composerSettings.sendShortcut","composerSettings.followUp",+ "composerSettings.shareDraft",]);});diff --git a/studio/frontend/tests/compare-draft-history.test.ts b/studio/frontend/tests/compare-draft-history.test.tsnew file mode 100644index 00000000000..c3164eb2dc5--- /dev/null+++ b/studio/frontend/tests/compare-draft-history.test.ts@@ -0,0 +1,194 @@+// 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 ts from "@typescript/typescript6";+import { readSrc } from "./helpers/kit.ts";+import {+ composerDraftKey,+ NEW_COMPARE_DRAFT_ID,+} from "../src/features/chat/utils/composer-draft.ts";++const source = ts.createSourceFile(+ "chat-page.tsx",+ readSrc("features/chat/chat-page.tsx"),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);+const composer = ts.createSourceFile(+ "shared-composer.tsx",+ readSrc("features/chat/shared-composer.tsx"),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);++function find(root: ts.Node, predicate: (n: ts.Node) => boolean): ts.Node {+ const nodes: ts.Node[] = [];+ function visit(node: ts.Node) {+ if (predicate(node)) nodes.push(node);+ ts.forEachChild(node, visit);+ }+ visit(root);+ assert.equal(nodes.length, 1);+ return nodes[0];+}++function evaluate(code: string, deps: Record<string, unknown>) {+ const js = ts.transpileModule(code, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ return new Function(...Object.keys(deps), js)(...Object.values(deps));+}++const unsentPair = find(+ composer,+ (n) =>+ ts.isVariableDeclaration(n) && n.name.getText(composer) === "unsentPair",+) as ts.VariableDeclaration;+const draftKey = find(+ composer,+ (n) => ts.isVariableDeclaration(n) && n.name.getText(composer) === "draftKey",+) as ts.VariableDeclaration;++type Thread = { id: string; modelType: string; modelId?: string };+for (const name of ["LoraCompareContent", "GeneralCompareContent"]) {+ const component = find(+ source,+ (n) => ts.isFunctionExpression(n) && n.name?.text === name,+ );+ const effect = find(+ component,+ (n) =>+ ts.isCallExpression(n) &&+ n.expression.getText(source) === "useEffect" &&+ n.arguments[0]+ ?.getText(source)+ .includes("listStoredChatThreads({ pairId })"),+ ) as ts.CallExpression;+ const prop = find(+ component,+ (n) => ts.isJsxAttribute(n) && n.name.getText(source) === "pairSaved",+ ) as ts.JsxAttribute;+ const expression = (prop.initializer as ts.JsxExpression).expression!;++ for (const scenario of [+ "failed",+ "empty",+ "saved",+ "failed-known-empty",+ "failed-known-saved",+ ] as const) {+ test(`${name}: ${scenario} history selects the correct draft scope`, async () => {+ let resolve!: (threads: Thread[]) => void;+ let reject!: (reason: Error) => void;+ const read = new Promise<Thread[]>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ const state: Record<string, unknown> = {+ threadsSettled: false,+ pairSaved:+ scenario === "failed-known-empty"+ ? false+ : scenario === "failed-known-saved"+ ? true+ : undefined,+ baseThreadId: undefined,+ loraThreadId: undefined,+ model1ThreadId: undefined,+ model2ThreadId: undefined,+ };+ const cleanup = evaluate(+ `return (${effect.arguments[0].getText(source)})();`,+ {+ pairId: "saved-pair",+ anyRunning: false,+ comparing: false,+ listedPairRef: {+ current: scenario.startsWith("failed-known") ? "saved-pair" : null,+ },+ listStoredChatThreads: () => read,+ isExpectedBackgroundChatStorageError: () => true,+ resolveComparePaneThreadIds: (threads: Thread[]) => ({+ first: threads.find((t) => t.modelType === "model1")?.id,+ second: threads.find((t) => t.modelType === "model2")?.id,+ }),+ setThreadsSettled: (value: boolean) => {+ state.threadsSettled = value;+ },+ setPairSaved: (value: boolean | undefined) => {+ state.pairSaved = value;+ },+ setBaseThreadId: (value?: string) => {+ state.baseThreadId = value;+ },+ setLoraThreadId: (value?: string) => {+ state.loraThreadId = value;+ },+ setModel1ThreadId: (value?: string) => {+ state.model1ThreadId = value;+ },+ setModel2ThreadId: (value?: string) => {+ state.model2ThreadId = value;+ },+ setPairLoraModelId: () => {},+ },+ );+ if (scenario.startsWith("failed"))+ reject(new Error("history unavailable"));+ else+ resolve(+ scenario === "empty"+ ? []+ : [+ {+ id: "pane",+ modelType: name === "LoraCompareContent" ? "base" : "model1",+ },+ ],+ );+ await read.catch(() => {});+ await Promise.resolve();+ await Promise.resolve();+ const pairSaved = evaluate(+ `return (${expression.getText(source)});`,+ state,+ );+ assert.equal(+ pairSaved,+ scenario === "failed"+ ? undefined+ : scenario === "saved" || scenario === "failed-known-saved",+ );+ const key = evaluate(+ `const unsentPair = ${unsentPair.initializer!.getText(composer)}; return ${draftKey.initializer!.getText(composer)};`,+ {+ pairSaved,+ draftId: "saved-pair",+ sentPairId: null,+ pairSubmitted: false,+ shareDraft: false,+ composerDraftKey,+ NEW_COMPARE_DRAFT_ID,+ },+ );+ assert.equal(+ key,+ composerDraftKey(+ scenario === "empty" || scenario === "failed-known-empty"+ ? NEW_COMPARE_DRAFT_ID+ : "saved-pair",+ ),+ );+ assert.equal(+ state.threadsSettled,+ true,+ "failed history still releases shell readiness",+ );+ cleanup();+ });+ }+}diff --git a/studio/frontend/tests/compare-draft-remount.test.ts b/studio/frontend/tests/compare-draft-remount.test.tsnew file mode 100644index 00000000000..6c79580df43--- /dev/null+++ b/studio/frontend/tests/compare-draft-remount.test.ts@@ -0,0 +1,202 @@+// 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 ts from "@typescript/typescript6";+import { readSrc, installLocalStorageFake } from "./helpers/kit.ts";++const page = ts.createSourceFile(+ "chat-page.tsx",+ readSrc("features/chat/chat-page.tsx"),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);+const composer = ts.createSourceFile(+ "shared-composer.tsx",+ readSrc("features/chat/shared-composer.tsx"),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);+function matches(root: ts.Node, predicate: (n: ts.Node) => boolean) {+ const found: ts.Node[] = [];+ function visit(n: ts.Node) {+ if (predicate(n)) found.push(n);+ ts.forEachChild(n, visit);+ }+ visit(root);+ return found;+}+function variable(root: ts.Node, name: string, file: ts.SourceFile) {+ const found = matches(+ root,+ (n) => ts.isVariableDeclaration(n) && n.name.getText(file).includes(name),+ );+ assert.ok(found.length <= 1, name);+ return found[0] as ts.VariableDeclaration | undefined;+}+function run(code: string, deps: Record<string, unknown>) {+ const { outputText } = ts.transpileModule(code, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ return new Function(...Object.keys(deps), outputText)(...Object.values(deps));+}+const submitted = variable(composer, "sentPairId", composer);+const unsent = variable(composer, "unsentPair", composer)!;+const key = variable(composer, "draftKey", composer)!;+const clear = variable(composer, "clearSubmittedDraft", composer)!;++for (const name of ["LoraCompareContent", "GeneralCompareContent"]) {+ for (const initialSaved of [false, undefined]) {+ test(`${name} (saved=${initialSaved}) keeps the submitted pair scope when its active-only composer remounts`, async () => {+ installLocalStorageFake();+ const drafts = await import(+ `../src/features/chat/utils/composer-draft.ts?remount=${name}`+ );+ const owner = matches(+ page,+ (n) => ts.isFunctionExpression(n) && n.name?.text === name,+ )[0];+ assert.ok(owner);+ const marker = variable(owner, "submittedPairId", page);+ const prop = (name: string) => {+ const node = matches(+ owner,+ (n) => ts.isJsxAttribute(n) && n.name.getText(page) === name,+ )[0] as ts.JsxAttribute | undefined;+ return node+ ? (node.initializer as ts.JsxExpression).expression!.getText(page)+ : "undefined";+ };+ let parentState: unknown = null;+ let childState: unknown = null;+ let pairId = "new-pair";+ let pairSaved = initialSaved;+ const render = () => {+ // The content stays mounted; only its active-only composer gets a fresh state slot.+ const props = run(+ `${marker ? `const ${marker.getText(page)};` : ""}+ return {pairSubmitted: ${prop("pairSubmitted")}, onPairSubmitted: ${prop("onPairSubmitted")}};`,+ {+ pairId,+ useState: () => [+ parentState,+ (value: unknown) => {+ parentState = value;+ },+ ],+ },+ );+ return run(+ `${submitted ? `const ${submitted.getText(composer)};` : ""}+ const ${unsent.getText(composer)};+ const ${key.getText(composer)};+ const ${clear.getText(composer)};+ return {draftKey, clearSubmittedDraft};`,+ {+ ...drafts,+ ...props,+ draftId: pairId,+ pairSaved,+ shareDraft: false,+ useState: () => [+ childState,+ (value: unknown) => {+ childState = value;+ },+ ],+ unsavedDraftRef: { current: null },+ setCurrentText: () => {},+ setIsWritingExpanded: () => {},+ setPendingImages: () => {},+ setPendingAudio: () => {},+ clearPendingAudioStore: () => {},+ textareaRef: { current: null },+ },+ );+ };+ let state = render();+ assert.equal(+ state.draftKey,+ drafts.composerDraftKey(+ initialSaved === false ? drafts.NEW_COMPARE_DRAFT_ID : pairId,+ ),+ );+ drafts.writeComposerDraft(state.draftKey, "first prompt");+ state.clearSubmittedDraft();+ pairSaved = false; // A history read can finish after the first submission.+ state = render();+ assert.equal(state.draftKey, drafts.composerDraftKey(pairId));+ drafts.writeComposerDraft(+ state.draftKey,+ "follow-up during the first run",+ );+ childState = null; // Leaving another page unmounts SharedComposer, not the content owner.+ state = render();+ assert.equal(state.draftKey, drafts.composerDraftKey(pairId));+ assert.equal(+ drafts.latestDraft(state.draftKey),+ "follow-up during the first run",+ );+ pairId = "different-new-pair";+ childState = null;+ assert.equal(+ render().draftKey,+ drafts.composerDraftKey(drafts.NEW_COMPARE_DRAFT_ID),+ );+ });+ }+}++const restoreEffect = matches(+ composer,+ (n) => ts.isCallExpression(n) && n.expression.getText(composer) === "useEffect" &&+ n.arguments[0]?.getText(composer).includes("draftScopeBeforeRef.current"),+)[0] as ts.CallExpression;+assert.ok(restoreEffect);++for (const olderSharedDraft of ["", "older shared draft"]) {+ test(`a reloaded Compare draft is adopted when sharing is enabled (older=${Boolean(olderSharedDraft)})`, async () => {+ const { store } = installLocalStorageFake();+ const drafts = await import(`../src/features/chat/utils/composer-draft.ts?adoption=${Math.random()}`);+ store.set(drafts.composerDraftKey(drafts.NEW_COMPARE_DRAFT_ID), "restored Compare prompt");+ if (olderSharedDraft) store.set(drafts.composerDraftKey("", true), olderSharedDraft);+ let pairSaved: boolean | undefined;+ let shareDraft = false;+ let text = "";+ const remoteDraftRef = { current: null };+ const unsavedDraftRef = { current: null };+ const draftScopeBeforeRef = { current: drafts.composerDraftKey("pair") };+ const draftOwnerBeforeRef = { current: { draftId: "pair", shareDraft: false, draftKey: draftScopeBeforeRef.current } };+ const render = () => {+ // The second commit is the state update caused by restoring the selected slot.+ for (let pass = 0; pass < 5; pass++) {+ const beforeText = text;+ run(`const ${unsent.getText(composer)};+ const ${key.getText(composer)};+ const draftScope = draftKey;+ return (${restoreEffect.arguments[0].getText(composer)})();`, {+ ...drafts, draftId: "pair", pairSaved, pairSubmitted: false, shareDraft,+ incognito: false, text, remoteDraftRef, unsavedDraftRef,+ draftScopeBeforeRef, draftOwnerBeforeRef, draftSource: Symbol("compare"),+ setText: (next: string) => { text = next; },+ setTimeout: () => 0, clearTimeout: () => {},+ });+ if (text === beforeText) return;+ }+ assert.fail("Compare draft restore did not settle");+ };+ render();+ pairSaved = false;+ render();+ assert.equal(text, "restored Compare prompt");+ assert.equal(drafts.adoptCurrentDraft(), true);+ shareDraft = true;+ render();+ assert.equal(text, "restored Compare prompt");+ assert.equal(drafts.latestDraft(), "restored Compare prompt");+ assert.equal(drafts.latestDraft(drafts.composerDraftKey(drafts.NEW_COMPARE_DRAFT_ID)), "");+ });+}diff --git a/studio/frontend/tests/composer-bulk-clear.test.ts b/studio/frontend/tests/composer-bulk-clear.test.tsnew file mode 100644index 00000000000..68667ed3e13--- /dev/null+++ b/studio/frontend/tests/composer-bulk-clear.test.ts@@ -0,0 +1,146 @@+// 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 { installLocalStorageFake } from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++async function setup(+ deletedThreadIds: string[],+ failedThreadIds: string[] = [],+ reject = false,+ createDuringClear = false,+ listFails = false,+) {+ installLocalStorageFake();+ const drafts = await import(+ `../src/features/chat/utils/composer-draft.ts?clear=${Math.random()}`+ );+ const rows = [+ { id: "single" },+ { id: "left", pairId: "pair" },+ { id: "right", pairId: "pair" },+ ];+ const seed = (id: string) => {+ drafts.stageComposerDraft(drafts.composerDraftKey(id), `text ${id}`);+ drafts.flushComposerDraft(drafts.composerDraftKey(id), `text ${id}`);+ drafts.writePasteDraft(drafts.composerPasteDraftKey(id), [`paste ${id}`]);+ };+ const { clearAllChats } = loadWithStubs<{+ clearAllChats: () => Promise<unknown>;+ }>(+ new URL("../src/features/chat/utils/clear-all-chats.ts", import.meta.url),+ {+ "../stores/bookmarked-turns-store": {+ useBookmarkedTurnsStore: { getState: () => ({ forgetThreads() {} }) },+ },+ "../stores/chat-runtime-store": {+ useChatRuntimeStore: {+ getState: () => ({+ runningByThreadId: {},+ cancelByThreadId: {},+ serverCancelByThreadId: {},+ }),+ },+ },+ "../stores/pinned-chats-store": {+ usePinnedChatsStore: {+ getState: () => ({ pinnedIds: [], setPinned() {} }),+ },+ },+ "./chat-history-clear-boundary": {+ chatHistoryClearBoundary: { advance() {} },+ },+ "./chat-history-storage": {+ listStoredChatThreads: async () => {+ if (listFails) throw new Error("backend unreachable");+ return rows;+ },+ countStoredChats: async () => rows.length,+ clearStoredChats: async () => {+ if (createDuringClear) seed("created-during-clear");+ if (reject) throw new Error("clear failed");+ return {+ backend: "cleared",+ legacy: failedThreadIds.length ? "failed" : "cleared",+ deletedThreadIds,+ failedThreadIds,+ sandboxesKept: [],+ };+ },+ },+ "./composer-draft": drafts,+ "./prompt-queue-boundary": { requestPromptQueueStop() {} },+ "./stop-chat-thread": { stopChatThread() {} },+ },+ );+ const assertDraft = (id: string, exists: boolean) => {+ const textKey = drafts.composerDraftKey(id),+ pasteKey = drafts.composerPasteDraftKey(id);+ assert.equal(drafts.latestDraft(textKey), exists ? `text ${id}` : "");+ assert.equal(+ drafts.readComposerDraft(textKey),+ exists ? `text ${id}` : null,+ );+ assert.deepEqual(+ drafts.latestPasteDraft(pasteKey),+ exists ? [`paste ${id}`] : [],+ );+ assert.deepEqual(+ drafts.readPasteDraft(pasteKey),+ exists ? [`paste ${id}`] : [],+ );+ };+ return { drafts, seed, assertDraft, clearAllChats };+}++test("Clear all chats removes deleted drafts and cannot adopt or autosave them afterward", async () => {+ const h = await setup(["single", "left", "right"]);+ h.seed(h.drafts.NEW_CHAT_DRAFT_ID);+ h.seed("pair");+ h.seed("single");+ await h.clearAllChats();+ h.assertDraft("single", false);+ h.assertDraft("pair", false);+ h.assertDraft(h.drafts.NEW_CHAT_DRAFT_ID, true);+ h.seed("single");+ h.assertDraft("single", false);+ assert.equal(h.drafts.adoptLegacyDraft("single", true), false);+ assert.equal(h.drafts.adoptCurrentDraft(), false);+});++test("bulk deletion preserves a new draft created while the clear is pending", async () => {+ const h = await setup(["single"], [], false, true);+ h.seed("single");+ await h.clearAllChats();+ h.assertDraft("single", false);+ h.assertDraft("created-during-clear", true);+ assert.equal(h.drafts.adoptCurrentDraft(), true);+ assert.equal(h.drafts.latestDraft(), "text created-during-clear");+});++test("bulk deletion preserves a failed chat and a Compare pair with a surviving side", async () => {+ const h = await setup(["left"], ["single", "right"]);+ for (const id of ["left", "single", "pair"]) h.seed(id);+ await h.clearAllChats();+ h.assertDraft("left", false);+ h.assertDraft("single", true);+ h.assertDraft("pair", true);+});++test("a rejected bulk deletion preserves drafts", async () => {+ const h = await setup([], [], true);+ h.seed("single");+ h.seed("pair");+ await assert.rejects(h.clearAllChats(), /clear failed/);+ h.assertDraft("single", true);+ h.assertDraft("pair", true);+});++test("an unreachable chat listing still clears the deleted chats' drafts", async () => {+ const h = await setup(["single"], [], false, false, true);+ h.seed("single");+ await h.clearAllChats();+ h.assertDraft("single", false);+});diff --git a/studio/frontend/tests/composer-draft-lifecycle.test.ts b/studio/frontend/tests/composer-draft-lifecycle.test.tsnew file mode 100644index 00000000000..e0f50b092fa--- /dev/null+++ b/studio/frontend/tests/composer-draft-lifecycle.test.ts@@ -0,0 +1,454 @@+// 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 ts from "@typescript/typescript6";+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";+import * as guards from "../src/features/chat/utils/composer-send-guard.ts";++const source = readSrc("components/assistant-ui/thread.tsx");+const start = source.lastIndexOf(+ " const incognito =",+ source.indexOf(" const draftThreadId ="),+);+const end = source.indexOf(" // react-textarea-autosize re-measures", start);+assert.ok(start >= 0 && end > start);+const inputStart = source.indexOf(" const composer = aui.composer();", source.indexOf(" const setComposerText = useCallback("));+const inputEnd = source.indexOf(" },", inputStart);+assert.ok(inputStart >= 0 && inputEnd > inputStart);+const code = ts.transpileModule(+ `return function render(props) {+ const referenceThreadId = props.threadId;+ const threadListItemId = props.runtimeId;+ const threadListItemRemoteId = props.remoteId;+ const composerText = props.text;+ const composerAttachmentSignature = props.attachments.map(a => a.id).join(',');+ const useChatRuntimeStore = select => select({incognito: props.incognito});+ const useChatPreferencesStore = select => select({shareComposerDraft: props.share});+ const NewChatDraftIdContext = null;+ const useContext = () => props.nonce;+ const justSentRef = useRef(null), draftKeyRef = useRef(null), imeSessionOpenRef = useRef(false);+ const setIsWritingExpanded = () => {};+ ${source.slice(start, end)}+ return {send() { armJustSent(props.text); clearStoredDraft(); aui.composer().setText(''); }, input(value) { const nativeEvent = undefined; ${source.slice(inputStart, inputEnd)} }};+}`,+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+).outputText;++type Attachment = { id: string; file: { paste: string } };+type Props = {+ threadId: string | null;+ runtimeId: string;+ remoteId: string | undefined;+ nonce: string | undefined;+ incognito: boolean;+ share: boolean;+ text: string;+ attachments: Attachment[];+};+type Effect = { deps: unknown[]; cleanup?: () => void };++async function harness() {+ installLocalStorageFake();+ const drafts = await import(+ `../src/features/chat/utils/composer-draft.ts?lifecycle=${Math.random()}`+ );+ const props: Props = {+ threadId: null,+ runtimeId: "local-new",+ remoteId: undefined,+ nonce: "nonce-1",+ incognito: false,+ share: false,+ text: "",+ attachments: [],+ };+ const slots: unknown[] = [];+ const timers = new Map<number, () => void>();+ let cursor = 0,+ nextTimer = 0,+ attachmentId = 0;+ let dirty = false;+ let effects: Array<{ slot: Effect; setup: () => void | (() => void) }> = [];+ const composer = {+ getState: () => ({+ isEditing: true,+ text: props.text,+ attachments: props.attachments,+ }),+ setText(text: string) {+ dirty ||= props.text !== text;+ props.text = text;+ },+ async addAttachment(file: Attachment["file"]) {+ props.attachments = [+ ...props.attachments,+ { id: String(++attachmentId), file },+ ];+ dirty = true;+ },+ attachment: ({ id }: { id: string }) => ({+ async remove() {+ props.attachments = props.attachments.filter((a) => a.id !== id);+ dirty = true;+ },+ }),+ };+ const deps = {+ ...drafts,+ ...guards,+ isTextReplacement: () => false,+ isDeliberateWrite: () => false,+ isCompositionWrite: () => false,+ flushResourcesSync: (fn: () => void) => fn(),+ INCOGNITO_DRAFT_SCOPE: "\0incognito",+ pastedTextOf: (file?: Attachment["file"]) => file?.paste,+ createPastedTextFile: (paste: string) => ({ paste }),+ aui: {+ composer: () => composer,+ threadListItem: () => ({+ getState: () => ({ remoteId: props.remoteId }),+ }),+ },+ useRef(value: unknown) {+ const i = cursor++;+ slots[i] ??= { current: value };+ return slots[i];+ },+ useState(value: unknown) {+ const i = cursor++;+ if (!(i in slots))+ slots[i] = typeof value === "function" ? value() : value;+ return [+ slots[i],+ (next: unknown) => {+ slots[i] = next;+ dirty = true;+ },+ ];+ },+ useCallback(fn: unknown) {+ cursor++;+ return fn;+ },+ useEffect(setup: () => void | (() => void), next: unknown[]) {+ const i = cursor++;+ const previous = slots[i] as Effect | undefined;+ if (+ previous &&+ next.every((value, j) => Object.is(value, previous.deps[j]))+ )+ return;+ const slot = { deps: next, cleanup: previous?.cleanup };+ slots[i] = slot;+ effects.push({ slot, setup });+ },+ setTimeout(fn: () => void) {+ timers.set(++nextTimer, fn);+ return nextTimer;+ },+ clearTimeout(id: number) {+ timers.delete(id);+ },+ };+ const render = new Function(...Object.keys(deps), code)(+ ...Object.values(deps),+ );+ let actions: { send: () => void; input: (value: string) => boolean };+ async function update(changes: Partial<Props> = {}) {+ if (changes.share && !props.share) drafts.adoptCurrentDraft();+ Object.assign(props, changes);+ for (let pass = 0; pass < 30; pass++) {+ dirty = false;+ cursor = 0;+ effects = [];+ actions = render({ ...props });+ // Commit cleanups before setups, including the pending debounce flush.+ for (const { slot } of effects) slot.cleanup?.();+ for (const { slot, setup } of effects)+ slot.cleanup = setup() || undefined;+ await Promise.resolve();+ await Promise.resolve();+ if (!dirty) return;+ }+ assert.fail("draft effects did not settle");+ }+ await update();+ return {+ props,+ drafts,+ update,+ async type(text: string) {+ await update({ text });+ },+ async paste(text: string) {+ await composer.addAttachment({ paste: text });+ await update();+ },+ async send() {+ actions.send();+ await update({ attachments: [] });+ },+ async delayedInput(value: string) {+ const accepted = actions.input(value);+ await update();+ return accepted;+ },+ flush() {+ for (const fn of [...timers.values()]) fn();+ timers.clear();+ },+ close() {+ for (const slot of slots) (slot as Effect | undefined)?.cleanup?.();+ },+ };+}++for (const flushed of [false, true]) {+ test(`first save preserves text and pastes, debounce flushed=${flushed}`, async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("first message");+ await h.send();+ await h.type("follow-up");+ await h.paste("follow-up paste");+ if (flushed) h.flush();+ await h.update({ remoteId: "saved" });+ await h.update({ threadId: "saved" });+ assert.equal(h.props.text, "follow-up");+ assert.equal(h.props.attachments[0]?.file.paste, "follow-up paste");+ await h.update({+ threadId: "other",+ runtimeId: "other",+ remoteId: "other",+ nonce: undefined,+ });+ assert.equal(h.props.text, "");+ assert.equal(h.props.attachments.length, 0);+ await h.update({+ threadId: "saved",+ runtimeId: "local-new",+ remoteId: "saved",+ });+ assert.equal(h.props.text, "follow-up");+ assert.equal(h.props.attachments[0]?.file.paste, "follow-up paste");+ assert.equal(+ h.drafts.latestDraft(+ h.drafts.composerDraftKey(h.drafts.NEW_CHAT_DRAFT_ID),+ ),+ "",+ );+ });+}++test("enabling sharing in New chat adopts text and pastes before the debounce", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("new prompt");+ await h.paste("new paste");+ await h.update({ share: true });+ assert.equal(h.props.text, "new prompt");+ assert.equal(h.props.attachments[0]?.file.paste, "new paste");+ await h.update({+ threadId: "other",+ runtimeId: "other",+ remoteId: "other",+ nonce: undefined,+ });+ assert.equal(h.props.text, "new prompt");+ await h.send();+ await h.update({+ threadId: null,+ runtimeId: "local-new",+ remoteId: undefined,+ nonce: "nonce-1",+ share: false,+ });+ assert.equal(h.props.text, "");+ assert.equal(h.props.attachments.length, 0);+});++test("navigation before the runtime switch does not promote the outgoing New chat draft", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.update({ nonce: undefined });+ await h.type("unsent new chat");+ await h.paste("private to new chat");+ h.drafts.writeComposerDraft(+ h.drafts.composerDraftKey("existing"),+ "existing draft",+ );+ await h.update({ threadId: "existing" });+ assert.equal(h.props.text, "unsent new chat");+ await h.update({+ runtimeId: "existing",+ remoteId: "existing",+ text: "",+ attachments: [],+ });+ assert.equal(h.props.text, "existing draft");+ assert.equal(h.props.attachments.length, 0);+ assert.equal(+ h.drafts.latestDraft(h.drafts.composerDraftKey(h.drafts.NEW_CHAT_DRAFT_ID)),+ "unsent new chat",+ );+});++test("unsaved New chat navigation retains the common new-chat slot", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("old new chat");+ await h.paste("old paste");+ await h.update({ nonce: "nonce-2" });+ assert.equal(h.props.text, "old new chat");+ assert.equal(h.props.attachments[0]?.file.paste, "old paste");+});++test("a temporary chat never promotes its draft into a saved chat", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.update({ incognito: true });+ await h.type("temporary");+ await h.paste("temporary paste");+ await h.update({ incognito: false, threadId: "saved", remoteId: "saved" });+ assert.equal(h.props.text, "");+ assert.equal(h.props.attachments.length, 0);+});++test("updating navigation metadata for the same saved chat preserves pending edits", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("follow-up");+ await h.update({ threadId: "saved", remoteId: "saved" });+ await h.type("newer follow-up");+ await h.update({ nonce: undefined });+ assert.equal(h.props.text, "newer follow-up");+});++test("temporary text and pastes survive sharing rehydration from another window", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.update({ incognito: true });+ await h.type("temporary draft");+ await h.paste("temporary paste");+ await h.update({ share: true });+ assert.equal(h.props.text, "temporary draft");+ assert.equal(h.props.attachments[0]?.file.paste, "temporary paste");+ await h.update({ share: false });+ assert.equal(h.props.text, "temporary draft");+ assert.equal(h.props.attachments[0]?.file.paste, "temporary paste");+});++test("sharing after first save adopts the promoted text-only draft", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("follow-up");+ await h.update({ threadId: "saved", remoteId: "saved" });+ await h.update({ share: true });+ assert.equal(h.props.text, "follow-up");+ assert.equal(h.drafts.latestDraft(h.drafts.composerDraftKey("saved")), "");+});++test("switching temporary conversations still clears the old temporary draft", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.update({ incognito: true });+ await h.type("temporary draft");+ await h.update({ runtimeId: "another-temporary-thread" });+ assert.equal(h.props.text, "");+});++test("a saved New chat keeps its follow-up through Compare backgrounding", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("first message");+ await h.send();+ await h.update({ threadId: "saved", remoteId: "saved" });+ await h.type("follow-up");+ await h.paste("follow-up paste");+ await h.update({ threadId: null });+ await h.update({ threadId: "saved" });+ assert.equal(h.props.text, "follow-up");+ assert.equal(h.props.attachments[0]?.file.paste, "follow-up paste");+ assert.equal(+ h.drafts.latestDraft(h.drafts.composerDraftKey("saved")),+ "follow-up",+ );+});++test("a bare chat's uninitialized active ID still uses the common New chat slot", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.update({ threadId: "__LOCALID_first", runtimeId: "__LOCALID_first" });+ await h.type("unfinished bare chat");+ await h.paste("bare chat paste");+ h.flush();+ assert.equal(+ h.drafts.readComposerDraft(+ h.drafts.composerDraftKey(h.drafts.NEW_CHAT_DRAFT_ID),+ ),+ "unfinished bare chat",+ );+ assert.deepEqual(+ h.drafts.readPasteDraft(+ h.drafts.composerPasteDraftKey(h.drafts.NEW_CHAT_DRAFT_ID),+ ),+ ["bare chat paste"],+ );+ await h.update({+ threadId: null,+ runtimeId: "__LOCALID_second",+ text: "",+ attachments: [],+ });+ assert.equal(h.props.text, "unfinished bare chat");+ assert.equal(h.props.attachments[0]?.file.paste, "bare chat paste");+});++test("a route changing before its runtime cannot erase the destination's pasted draft", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.update({ threadId: "A", runtimeId: "A", remoteId: "A" });+ await h.type("draft A");+ await h.paste("paste A");+ h.drafts.writeComposerDraft(h.drafts.composerDraftKey("B"), "draft B");+ h.drafts.writePasteDraft(h.drafts.composerPasteDraftKey("B"), ["paste B"]);+ await h.update({ threadId: "B" });+ await h.update({ runtimeId: "B", remoteId: "B", text: "", attachments: [] });+ assert.equal(h.props.text, "draft B");+ assert.equal(h.props.attachments[0]?.file.paste, "paste B");+ assert.deepEqual(+ h.drafts.latestPasteDraft(h.drafts.composerPasteDraftKey("B")),+ ["paste B"],+ );+});++test("a fresh runtime restores pastes from the same common New chat slot", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("unfinished");+ await h.paste("unsaved paste");+ await h.update({+ runtimeId: "another-new-runtime",+ text: "",+ attachments: [],+ });+ assert.equal(h.props.text, "unfinished");+ assert.equal(h.props.attachments[0]?.file.paste, "unsaved paste");+});++test("first persistence keeps the guard against a delayed submitted-text write", async (t) => {+ const h = await harness();+ t.after(h.close);+ await h.type("submitted prompt");+ await h.send();+ await h.update({ threadId: "saved", remoteId: "saved" });+ assert.equal(await h.delayedInput("submitted prompt"), false);+ h.flush();+ assert.equal(h.props.text, "");+ assert.equal(h.drafts.latestDraft(h.drafts.composerDraftKey("saved")), "");+ await h.update({ threadId: "other", runtimeId: "other", remoteId: "other" });+ assert.equal(await h.delayedInput("submitted prompt"), true);+ assert.equal(h.props.text, "submitted prompt");+});diff --git a/studio/frontend/tests/composer-paste-draft.test.ts b/studio/frontend/tests/composer-paste-draft.test.tsindex a66c23d5266..b5883927645 100644--- a/studio/frontend/tests/composer-paste-draft.test.ts+++ b/studio/frontend/tests/composer-paste-draft.test.ts@@ -31,6 +31,8 @@ const {composerDraftKey,composerPasteDraftKey,latestDraft,+ NEW_CHAT_DRAFT_ID,+ NEW_COMPARE_DRAFT_ID,publishDraft,readComposerDraft,readPasteDraft,@@ -57,8 +59,8 @@ test("a per-chat draft from before the upgrade becomes the shared draft when itsstore.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(readComposerDraft(composerDraftKey("", true)), "unsent");+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("", true)), ["pasted"]);assert.equal(store.has("chat-draft:t1"), false);assert.equal(store.has("chat-draft-pastes:t1"), false);});@@ -66,15 +68,15 @@ test("a per-chat draft from before the upgrade becomes the shared draft when itstest("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");+ assert.equal(readComposerDraft(composerDraftKey("", true)), "unsent");});test("a newer shared draft wins over an old per-chat one", () => {- writeComposerDraft(composerDraftKey(), "newer");+ writeComposerDraft(composerDraftKey("", true), "newer");store.set("chat-draft:t1", "older");adoptLegacyDraft("t1");- assert.equal(readComposerDraft(composerDraftKey()), "newer");- assert.equal(store.has("chat-draft:t1"), false);+ assert.equal(readComposerDraft(composerDraftKey("", true)), "newer");+ assert.equal(store.has("chat-draft:t1"), true);});test("a paste too big to adopt rolls back the text, so the next try still carries both", () => {@@ -82,15 +84,15 @@ test("a paste too big to adopt rolls back the text, so the next try still carriestore.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");+ if (key === composerPasteDraftKey("", true)) throw new Error("QuotaExceededError");setItem(key, value);};assert.equal(adoptLegacyDraft("t1"), false);window.localStorage.setItem = setItem;- assert.equal(readComposerDraft(composerDraftKey()), null);+ assert.equal(readComposerDraft(composerDraftKey("", true)), null);assert.equal(adoptLegacyDraft("t1"), true);- assert.equal(readComposerDraft(composerDraftKey()), "unsent");- assert.deepEqual(readPasteDraft(composerPasteDraftKey()), ["pasted"]);+ assert.equal(readComposerDraft(composerDraftKey("", true)), "unsent");+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("", true)), ["pasted"]);});test("composers hear each other's text, never their own", () => {@@ -111,7 +113,7 @@ const openTab = () =>import(`../src/features/chat/utils/composer-draft.ts?tab=${Math.random()}`);test("a new tab or a reload starts from the saved draft", async () => {- writeComposerDraft(composerDraftKey(), "saved before the reload");+ writeComposerDraft(composerDraftKey("", true), "saved before the reload");const tab = await openTab();assert.equal(tab.latestDraft(), "saved before the reload");});@@ -124,9 +126,9 @@ test("typing or sending in another tab never rewrites this tab's draft", async (// The other tab's debounced save, then its send clearing the slot; the browser// tells this tab about each with a storage event.const otherTabWrites = (text: string) => {- writeComposerDraft(composerDraftKey(), text);+ writeComposerDraft(composerDraftKey("", true), text);for (const listener of windowListeners.get("storage") ?? []) {- listener({ key: composerDraftKey(), newValue: text === "" ? null : text });+ listener({ key: composerDraftKey("", true), newValue: text === "" ? null : text });}};otherTabWrites("typed in the other tab");@@ -139,22 +141,22 @@ test("typing or sending in another tab never rewrites this tab's draft", async (test("this tab keeps its own text after another tab saves", async () => {const tab = await openTab();tab.publishDraft("mine", Symbol("chat"));- writeComposerDraft(composerDraftKey(), "theirs");+ writeComposerDraft(composerDraftKey("", true), "theirs");assert.equal(tab.latestDraft(), "mine");});test("a new tab starts from the saved pastes, then keeps its own", async () => {- writePasteDraft(composerPasteDraftKey(), ["saved paste"]);+ writePasteDraft(composerPasteDraftKey("", true), ["saved paste"]);const tab = await openTab();assert.deepEqual(tab.latestPasteDraft(), ["saved paste"]);- tab.writePasteDraft(tab.composerPasteDraftKey(), []);- writePasteDraft(composerPasteDraftKey(), ["pasted in the other tab"]);+ tab.writePasteDraft(tab.composerPasteDraftKey("", true), []);+ writePasteDraft(composerPasteDraftKey("", true), ["pasted in the other tab"]);assert.deepEqual(tab.latestPasteDraft(), [], "a chat switch here does not pick it up");});test("an adopted per-chat paste reaches the restore", async () => {const tab = await openTab();- tab.writePasteDraft(tab.composerPasteDraftKey(), []);+ tab.writePasteDraft(tab.composerPasteDraftKey("", true), []);store.set("chat-draft-pastes:t1", '["old paste"]');assert.equal(tab.adoptLegacyDraft("t1"), true);assert.deepEqual(tab.latestPasteDraft(), ["old paste"]);@@ -168,7 +170,7 @@ test("a failed adoption keeps the old draft rather than losing it", () => {});test("an unsent paste survives a reload", () => {- const key = composerPasteDraftKey();+ const key = composerPasteDraftKey("", true);const paste = `Deploy log\n${"line\n".repeat(500)}`;writePasteDraft(key, [paste]);@@ -183,37 +185,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(), composerPasteDraftKey());+ assert.notEqual(composerDraftKey("", true), composerPasteDraftKey("", true));});test("deleting a chat drops its old per-chat draft but keeps the shared one", () => {- writeComposerDraft(composerDraftKey(), "typed");- writePasteDraft(composerPasteDraftKey(), ["pasted"]);+ writeComposerDraft(composerDraftKey("", true), "typed");+ writePasteDraft(composerPasteDraftKey("", true), ["pasted"]);store.set("chat-draft:t1", "old");store.set("chat-draft-pastes:t1", '["old"]');clearComposerDraft("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"]);+ assert.equal(readComposerDraft(composerDraftKey("", true)), "typed");+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("", true)), ["pasted"]);});test("the shared draft keeps the prefix the account switch clears", () => {- assert.ok(composerDraftKey().startsWith("chat-draft"));- assert.ok(composerPasteDraftKey().startsWith("chat-draft"));+ assert.ok(composerDraftKey("", true).startsWith("chat-draft"));+ assert.ok(composerPasteDraftKey("", true).startsWith("chat-draft"));});test("a paste too big for the quota does not cost the typed draft", () => {- writeComposerDraft(composerDraftKey(), "typed");+ writeComposerDraft(composerDraftKey("", true), "typed");failWrites = true;- writePasteDraft(composerPasteDraftKey(), ["x".repeat(64)]);- assert.equal(readComposerDraft(composerDraftKey()), "typed");- assert.deepEqual(readPasteDraft(composerPasteDraftKey()), []);+ writePasteDraft(composerPasteDraftKey("", true), ["x".repeat(64)]);+ assert.equal(readComposerDraft(composerDraftKey("", true)), "typed");+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("", true)), []);});test("a corrupt paste slot reads as empty rather than throwing", () => {- const key = composerPasteDraftKey();+ const key = composerPasteDraftKey("", true);for (const raw of ["not json", '{"text":"a"}', "[1,2]", ""]) {store.set(key, raw);assert.deepEqual(readPasteDraft(key), []);@@ -221,3 +223,207 @@ test("a corrupt paste slot reads as empty rather than throwing", () => {store.set(key, JSON.stringify(["keep", 5, null, "also"]));assert.deepEqual(readPasteDraft(key), ["keep", "also"]);});++test("draft text and pastes belong to their chat unless sharing is explicitly enabled", () => {+ const first = composerDraftKey("chat-a");+ const second = composerDraftKey("chat-b");+ writeComposerDraft(first, "unfinished A");+ writePasteDraft(composerPasteDraftKey("chat-a"), ["large paste A"]);+ assert.equal(readComposerDraft(second), null);+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("chat-b")), []);+ writeComposerDraft(second, "unfinished B");+ assert.equal(readComposerDraft(first), "unfinished A");+ clearComposerDraft("chat-b");+ assert.equal(readComposerDraft(first), "unfinished A");+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("chat-a")), ["large paste A"]);+ assert.equal(composerDraftKey("chat-a", true), composerDraftKey("chat-b", true));+ assert.equal(composerPasteDraftKey("chat-a", true), composerPasteDraftKey("chat-b", true));+});++test("every unsent New chat and Compare pair shares one slot, apart from saved chats and the shared draft", () => {+ // Their ids are minted per navigation; per-id slots would never be read or removed again.+ const newChat = composerDraftKey(NEW_CHAT_DRAFT_ID);+ const newPair = composerDraftKey(NEW_COMPARE_DRAFT_ID);+ assert.equal(newChat, "chat-draft:__new__", "the pre-sharing New chat key, so old drafts still load");+ assert.notEqual(newPair, newChat);+ writeComposerDraft(newChat, "left in a New chat");+ writeComposerDraft(composerDraftKey("", true), "shared before upgrade");+ assert.equal(readComposerDraft(newChat), "left in a New chat");+ assert.equal(readComposerDraft(composerDraftKey("saved-chat")), null);+ assert.equal(readComposerDraft(newPair), null);+ assert.equal(readComposerDraft(composerDraftKey("", true)), "shared before upgrade");+});++test("shared publications cannot replace a per-chat draft", () => {+ writeComposerDraft(composerDraftKey("chat-a"), "my local draft");+ publishDraft("from Compare", Symbol("compare"));+ assert.equal(readComposerDraft(composerDraftKey("chat-a")), "my local draft");+ assert.equal(latestDraft(), "from Compare");+});++test("per-chat text and pastes stay isolated from other open tabs", async () => {+ const tab = await openTab();+ const textKey = tab.composerDraftKey("isolated-chat");+ const pasteKey = tab.composerPasteDraftKey("isolated-chat");+ assert.equal(tab.latestDraft(textKey), "");+ assert.deepEqual(tab.latestPasteDraft(pasteKey), []);+ writeComposerDraft(textKey, "other tab's draft");+ writePasteDraft(pasteKey, ["other tab's paste"]);+ assert.equal(tab.latestDraft(textKey), "");+ assert.deepEqual(tab.latestPasteDraft(pasteKey), []);+ tab.writeComposerDraft(textKey, "my draft");+ tab.writePasteDraft(pasteKey, ["my paste"]);+ writeComposerDraft(textKey, "another external edit");+ writePasteDraft(pasteKey, ["another external paste"]);+ assert.equal(tab.latestDraft(textKey), "my draft");+ assert.deepEqual(tab.latestPasteDraft(pasteKey), ["my paste"]);+ const reloaded = await openTab();+ assert.equal(reloaded.latestDraft(textKey), "another external edit");+ assert.deepEqual(reloaded.latestPasteDraft(pasteKey), ["another external paste"]);+});++test("a draft adopted into the shared slot and sent there does not return when sharing is turned off", async () => {+ const tab = await openTab();+ const textKey = tab.composerDraftKey("adopted-chat");+ const pasteKey = tab.composerPasteDraftKey("adopted-chat");+ tab.writeComposerDraft(textKey, "sent from the shared slot");+ tab.writePasteDraft(pasteKey, ["sent paste"]);+ assert.equal(tab.adoptLegacyDraft("adopted-chat"), true);+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "sent from the shared slot");+ tab.publishDraft("", Symbol("chat"));+ tab.writeComposerDraft(tab.composerDraftKey("", true), "");+ tab.writePasteDraft(tab.composerPasteDraftKey("", true), []);+ assert.equal(tab.latestDraft(textKey), "");+ assert.deepEqual(tab.latestPasteDraft(pasteKey), []);+ const reloaded = await openTab();+ assert.equal(reloaded.latestDraft(textKey), "");+ assert.deepEqual(reloaded.latestPasteDraft(pasteKey), []);+});++test("enabling sharing adopts this window's per-chat draft, not another window's later write", async () => {+ const tab = await openTab();+ const textKey = tab.composerDraftKey("two-windows");+ const pasteKey = tab.composerPasteDraftKey("two-windows");+ tab.writeComposerDraft(textKey, "mine");+ tab.writePasteDraft(pasteKey, ["my paste"]);+ store.set(textKey, "theirs");+ store.set(pasteKey, '["their paste"]');+ tab.publishDraft("", Symbol("chat"));+ assert.equal(tab.adoptLegacyDraft("two-windows"), true);+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "mine");+ assert.deepEqual(tab.latestPasteDraft(tab.composerPasteDraftKey("", true)), ["my paste"]);+});++test("an unsent Compare pair's draft is adopted from its own slot", async () => {+ const tab = await openTab();+ tab.writeComposerDraft(tab.composerDraftKey(tab.NEW_COMPARE_DRAFT_ID), "compare prompt");+ assert.equal(tab.adoptLegacyDraft(tab.NEW_COMPARE_DRAFT_ID), true);+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "compare prompt");+ assert.equal(tab.latestDraft(tab.composerDraftKey(tab.NEW_COMPARE_DRAFT_ID)), "");+});++test("switching sharing on adopts the slot this tab last typed into, even with its composer unmounted", async () => {+ const tab = await openTab();+ tab.stageComposerDraft(tab.composerDraftKey("older-chat"), "older");+ tab.writeComposerDraft(tab.composerDraftKey("older-chat"), "older");+ tab.stageComposerDraft(tab.composerDraftKey(tab.NEW_COMPARE_DRAFT_ID), "typed in Compare");+ assert.equal(tab.adoptCurrentDraft(), true);+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "typed in Compare");+ assert.equal(tab.latestDraft(tab.composerDraftKey("older-chat")), "older");+});++test("a paste-only draft is what switching sharing on adopts", async () => {+ const tab = await openTab();+ tab.writeComposerDraft(tab.composerDraftKey("typed-earlier"), "older text");+ tab.writePasteDraft(tab.composerPasteDraftKey("paste-only"), ["a long document"]);+ assert.equal(tab.adoptCurrentDraft(), true);+ assert.deepEqual(tab.latestPasteDraft(tab.composerPasteDraftKey("", true)), ["a long document"]);+ assert.equal(tab.latestDraft(tab.composerDraftKey("typed-earlier")), "older text");+});++test("deleting a comparison clears its pair-scoped draft once the delete holds, and a failed delete reopens it", async () => {+ const { readFileSync } = await import("node:fs");+ const src = readFileSync(new URL("../src/features/chat/hooks/use-chat-sidebar-items.ts", import.meta.url), "utf8");+ const del = src.slice(src.indexOf("export async function deleteChatItems("));+ assert.match(del, /items\.filter\(\(i\) => i\.type !== "single"\)\.map\(\(i\) => i\.id\)/);+ assert.match(del, /for \(const id of draftIds\) clearComposerDraft\(id\)/);+ assert.match(del, /for \(const id of draftIds\) reopenComposerDraft\(id\)/);+});++test("a pending autosave landing after its chat was deleted is dropped", async () => {+ const tab = await openTab();+ const key = tab.composerDraftKey("deleted-chat");+ tab.stageComposerDraft(key, "typed");+ tab.writeComposerDraft(key, "typed");+ tab.clearComposerDraft("deleted-chat");+ tab.writeComposerDraft(key, "late flush");+ tab.writePasteDraft(tab.composerPasteDraftKey("deleted-chat"), ["late paste"]);+ assert.equal(store.has(key), false);+ assert.equal(store.has(tab.composerPasteDraftKey("deleted-chat")), false);+ assert.equal(tab.adoptCurrentDraft(), false);+});++test("what this tab just typed replaces a shared draft another window left", async () => {+ const tab = await openTab();+ tab.stageComposerDraft(tab.composerDraftKey("mine-only"), "this window");+ store.set(composerDraftKey("", true), "other window");+ assert.equal(tab.adoptCurrentDraft(), true);+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "this window");+ assert.equal(store.get(composerDraftKey("", true)), "this window");+});++test("a shared copy that does not fit keeps the saved per-chat draft and the old shared one", async () => {+ const tab = await openTab();+ const key = tab.composerDraftKey("quota-chat");+ tab.stageComposerDraft(key, "saved prompt");+ tab.writeComposerDraft(key, "saved prompt");+ store.set(composerDraftKey("", true), "older shared");+ failWrites = true;+ assert.equal(tab.adoptCurrentDraft(), false);+ failWrites = false;+ assert.equal(store.get(key), "saved prompt");+ assert.equal(store.get(composerDraftKey("", true)), "older shared");+});++test("a delete in flight drops late writes, and a failed delete reopens the slot with its draft", async () => {+ const tab = await openTab();+ const key = tab.composerDraftKey("restored-chat");+ tab.writeComposerDraft(key, "keep me");+ tab.closeComposerDraft("restored-chat");+ tab.writeComposerDraft(key, "late flush");+ assert.equal(store.get(key), "keep me");+ tab.reopenComposerDraft("restored-chat");+ tab.writeComposerDraft(key, "typed after restore");+ assert.equal(store.get(key), "typed after restore");+});++test("typing still inside the save debounce is what sharing adopts, and its late flush is dropped", async () => {+ const tab = await openTab();+ const key = tab.composerDraftKey("debounced-chat");+ tab.writeComposerDraft(key, "saved earlier");+ tab.stageComposerDraft(key, "saved earlier, then typed more");+ assert.equal(tab.adoptCurrentDraft(), true);+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "saved earlier, then typed more");+ tab.flushComposerDraft(key, "saved earlier, then typed more");+ assert.equal(store.has(key), false);+});++test("an adoption keeps its own text when another window adopts right after", async () => {+ const tab = await openTab();+ tab.stageComposerDraft(tab.composerDraftKey("window-a"), "window A draft");+ tab.writePasteDraft(tab.composerPasteDraftKey("window-a"), ["A paste"]);+ assert.equal(tab.adoptCurrentDraft(), true);+ store.set(composerDraftKey("", true), "window B draft");+ store.set(composerPasteDraftKey("", true), '["B paste"]');+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "window A draft");+ assert.deepEqual(tab.latestPasteDraft(tab.composerPasteDraftKey("", true)), ["A paste"]);+});++test("a delayed save of another slot does not take adoption away from the latest edit", async () => {+ const tab = await openTab();+ tab.stageComposerDraft(tab.composerDraftKey("hidden-chat"), "chat text");+ tab.stageComposerDraft(tab.composerDraftKey(tab.NEW_COMPARE_DRAFT_ID), "compare text");+ tab.writeComposerDraft(tab.composerDraftKey("hidden-chat"), "chat text");+ assert.equal(tab.adoptCurrentDraft(), true);+ assert.equal(tab.latestDraft(tab.composerDraftKey("", true)), "compare text");+});diff --git a/studio/frontend/tests/composer-preferences.test.ts b/studio/frontend/tests/composer-preferences.test.tsindex 3a32b75f099..2a9ba0e130d 100644--- a/studio/frontend/tests/composer-preferences.test.ts+++ b/studio/frontend/tests/composer-preferences.test.ts@@ -12,6 +12,8 @@ import {} from "../src/features/chat/utils/composer-preferences.ts";import { installLocalStorageFake } from "./helpers/kit.ts";+const preferenceStorage = installLocalStorageFake();+const enter: ComposerKeyEvent = {key: "Enter",metaKey: false,@@ -178,7 +180,7 @@ test("legacy and malformed saved settings retain usable defaults", () => {}});test("the real preference store persists all controls and restores them on reload", async () => {- const { store } = installLocalStorageFake();+ const { store } = preferenceStorage;const { useChatPreferencesStore: prefs } = await import("../src/features/chat/stores/chat-preferences-store.ts");@@ -203,3 +205,36 @@ test("the real preference store persists all controls and restores them on reloaassert.deepEqual(normalizeComposerPreferences(prefs.getState()), expected);assert.equal(typeof prefs.getState().setFollowUpBehavior, "function");});++test("draft sharing is opt-in for existing preferences and survives an explicit choice", async () => {+ const { store } = preferenceStorage;+ const { useChatPreferencesStore: prefs } = await import(+ "../src/features/chat/stores/chat-preferences-store.ts"+ );+ for (const shareComposerDraft of [undefined, false, "true", 1]) {+ store.set("unsloth_chat_preferences", JSON.stringify({ version: 1, state: { shareComposerDraft } }));+ await prefs.persist.rehydrate();+ assert.equal(prefs.getState().shareComposerDraft, false);+ }+ prefs.getState().setShareComposerDraft(true);+ const saved = store.get("unsloth_chat_preferences")!;+ prefs.getState().setShareComposerDraft(false);+ store.set("unsloth_chat_preferences", saved);+ await prefs.persist.rehydrate();+ assert.equal(prefs.getState().shareComposerDraft, true);+});++test("sharing switched on by another window's rehydrate still adopts this tab's draft", async () => {+ const { store } = preferenceStorage;+ const { useChatPreferencesStore: prefs } = await import(+ "../src/features/chat/stores/chat-preferences-store.ts"+ );+ const drafts = await import("../src/features/chat/utils/composer-draft.ts");+ store.set("unsloth_chat_preferences", JSON.stringify({ version: 1, state: { shareComposerDraft: false } }));+ await prefs.persist.rehydrate();+ drafts.stageComposerDraft(drafts.composerDraftKey("rehydrated-chat"), "typed here");+ store.set("unsloth_chat_preferences", JSON.stringify({ version: 1, state: { shareComposerDraft: true } }));+ await prefs.persist.rehydrate();+ assert.equal(prefs.getState().shareComposerDraft, true);+ assert.equal(drafts.latestDraft(drafts.composerDraftKey("", true)), "typed here");+});diff --git a/studio/frontend/tests/helpers/store-stubs/sidebar-items-deps.ts b/studio/frontend/tests/helpers/store-stubs/sidebar-items-deps.tsindex 33eed1d521e..3f97146f65b 100644--- a/studio/frontend/tests/helpers/store-stubs/sidebar-items-deps.ts+++ b/studio/frontend/tests/helpers/store-stubs/sidebar-items-deps.ts@@ -77,6 +77,8 @@ export function isExpectedBackgroundChatStorageError(): boolean {return false;}export function clearComposerDraft(): void {}+export function closeComposerDraft(): void {}+export function reopenComposerDraft(): void {}export async function offerToDeleteKeptSandboxes(): Promise<void> {}export async function stopChatThread(): Promise<void> {}export function markChatThreadsDeleted(): void {}diff --git a/studio/frontend/tests/saved-branch-head.test.ts b/studio/frontend/tests/saved-branch-head.test.tsindex 9a70f628950..18e23b45f2a 100644--- a/studio/frontend/tests/saved-branch-head.test.ts+++ b/studio/frontend/tests/saved-branch-head.test.ts@@ -108,7 +108,11 @@ function sidebar(deleteResult: () => Promise<string[]>) {},"../utils/chat-history-storage": { deleteStoredChatThreads: deleteResult },"../utils/branch-head": { clearBranchHead: (id: string) => cleared.push(id) },- "../utils/composer-draft": { clearComposerDraft: () => {} },+ "../utils/composer-draft": {+ clearComposerDraft: () => {},+ closeComposerDraft: () => {},+ reopenComposerDraft: () => {},+ },"../utils/offer-kept-sandbox-files": { offerToDeleteKeptSandboxes: () => {} },"../utils/stop-chat-thread": { stopChatThread: () => {} },"../utils/chat-thread-tombstones": {