fix(webui): preserve composer drafts across navigation and reloads (#5912)
* fix(webui): preserve composer drafts when switching sessions * fix(webui): restore ordinary composer drafts after reload * fix(webui): retain draft identity across composer remounts
This commit is contained in:
1 parent
6eccc2859a
commit
9756468a8c
7 files changed
+499
-7
No files matched your search
+11
-2
@@ -19,6 +19,7 @@ import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
|
||||
import type { SidebarDeleteItem } from "@/components/ChatList";
|
||||
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
|
||||
import { StartupShell } from "@/components/StartupShell";
|
||||
import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft";
|
||||
import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
|
||||
@@ -968,6 +969,7 @@ export default function App() {
|
||||
if (cancelled) return;
|
||||
if (isBootstrapAuthRequired(e)) {
|
||||
clearReloadCache();
|
||||
clearStoredComposerDrafts();
|
||||
webuiThreadCache.clear();
|
||||
setState({ status: "auth", failed: !!secret });
|
||||
} else {
|
||||
@@ -994,6 +996,7 @@ export default function App() {
|
||||
} catch (e) {
|
||||
if (isBootstrapAuthRequired(e)) {
|
||||
clearReloadCache();
|
||||
clearStoredComposerDrafts();
|
||||
webuiThreadCache.clear();
|
||||
setState({ status: "auth", failed: !!bootstrapSecretRef.current });
|
||||
}
|
||||
@@ -1044,6 +1047,7 @@ export default function App() {
|
||||
}
|
||||
clearSavedSecret();
|
||||
clearReloadCache();
|
||||
clearStoredComposerDrafts();
|
||||
webuiThreadCache.clear();
|
||||
setState({ status: "auth" });
|
||||
};
|
||||
@@ -1239,6 +1243,7 @@ function Shell({
|
||||
// Pane shells can unmount during navigation. Keep replay state for this app
|
||||
// session, pinning temporary chats because they cannot reload disk history.
|
||||
const retainedTemporaryChatIdsRef = useRef(new Set<string>());
|
||||
const [draftStore] = useState(() => new ComposerDraftStore());
|
||||
const [filePreviewStore] = useState(() => new FilePreviewStore());
|
||||
const [threadMessageCache] = useState(() => new ThreadMessageCache(
|
||||
(key) => retainedTemporaryChatIdsRef.current.has(key),
|
||||
@@ -1249,10 +1254,11 @@ function Shell({
|
||||
if (!retained.has(chatId)) {
|
||||
threadMessageCache.delete(chatId);
|
||||
filePreviewStore.delete(`websocket:${chatId}`);
|
||||
draftStore.delete(`websocket:${chatId}`);
|
||||
}
|
||||
}
|
||||
retainedTemporaryChatIdsRef.current = retained;
|
||||
}, [temporaryChatIds, threadMessageCache, filePreviewStore]);
|
||||
}, [temporaryChatIds, threadMessageCache, filePreviewStore, draftStore]);
|
||||
|
||||
const navigate = useCallback(
|
||||
(route: ShellRoute, options?: { replace?: boolean }) => {
|
||||
@@ -2336,6 +2342,7 @@ function Shell({
|
||||
return;
|
||||
}
|
||||
filePreviewStore.delete(item.key);
|
||||
draftStore.delete(item.key);
|
||||
}
|
||||
setPendingDelete(null);
|
||||
if (deletingActive) {
|
||||
@@ -2348,7 +2355,7 @@ function Shell({
|
||||
} catch (e) {
|
||||
console.error("Failed to delete session", e);
|
||||
}
|
||||
}, [pendingDelete, deleteChat, activeKey, activeTabState, navigate, topicSessions, filePreviewStore]);
|
||||
}, [pendingDelete, deleteChat, activeKey, activeTabState, navigate, topicSessions, filePreviewStore, draftStore]);
|
||||
|
||||
const onRequestDeleteMany = useCallback(async (items: SidebarDeleteItem[]) => {
|
||||
const uniqueItems = Array.from(new Map(items.map((item) => [item.key, item])).values());
|
||||
@@ -2913,6 +2920,7 @@ function Shell({
|
||||
temporaryChatIds={temporaryChatIds}
|
||||
messageCache={threadMessageCache}
|
||||
filePreviewStore={filePreviewStore}
|
||||
draftStore={draftStore}
|
||||
temporaryChatEnabled={temporaryChatEnabled}
|
||||
onTemporaryChatEnabledChange={
|
||||
!activeKey ? onTemporaryChatEnabledChange : undefined
|
||||
@@ -2961,6 +2969,7 @@ function Shell({
|
||||
temporaryChatIds={temporaryChatIds}
|
||||
messageCache={threadMessageCache}
|
||||
filePreviewStore={filePreviewStore}
|
||||
draftStore={draftStore}
|
||||
onToggleSidebar={toggleSidebar}
|
||||
onNewChat={onNewChat}
|
||||
onCreateChat={onCreateChat}
|
||||
|
||||
@@ -121,6 +121,8 @@ import {
|
||||
} from "@/lib/session-drag";
|
||||
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { composerMentionText } from "@/lib/composer-mention-text";
|
||||
import type { ComposerDraftStore } from "@/lib/composer-draft";
|
||||
|
||||
const VOICE_SHORTCUT_CODE = "KeyD";
|
||||
const VOICE_SHORTCUT_ARIA = "Control+Shift+D";
|
||||
@@ -230,6 +232,9 @@ interface ThreadComposerProps {
|
||||
onPickWorkspaceFolder?: () => Promise<string | null>;
|
||||
onWorkspaceScopeChange?: (scope: WorkspaceScopePayload) => void;
|
||||
pendingQueueKey?: string | null;
|
||||
draftKey?: string;
|
||||
draftStore?: ComposerDraftStore;
|
||||
persistDraft?: boolean;
|
||||
transcriptionProvider?: string | null;
|
||||
ingressLimits?: WebUIIngressLimits | null;
|
||||
quotedContext?: string | null;
|
||||
@@ -931,6 +936,9 @@ export function ThreadComposer({
|
||||
onPickWorkspaceFolder,
|
||||
onWorkspaceScopeChange,
|
||||
pendingQueueKey = null,
|
||||
draftKey,
|
||||
draftStore,
|
||||
persistDraft = false,
|
||||
transcriptionProvider = null,
|
||||
ingressLimits = null,
|
||||
quotedContext = null,
|
||||
@@ -938,10 +946,13 @@ export function ThreadComposer({
|
||||
onQuotedContextChange,
|
||||
}: ThreadComposerProps) {
|
||||
const { t } = useTranslation();
|
||||
const [value, setValue] = useState("");
|
||||
const [initialDraft] = useState(() => draftKey ? draftStore?.get(draftKey, persistDraft) : undefined);
|
||||
const [value, setValue] = useState(initialDraft?.text ?? "");
|
||||
const [composerFocused, setComposerFocused] = useState(false);
|
||||
const blurFrame = useRef<number | null>(null);
|
||||
const [selectedSessionMentions, setSelectedSessionMentions] = useState<SessionMention[]>([]);
|
||||
const [selectedSessionMentions, setSelectedSessionMentions] = useState<SessionMention[]>(
|
||||
initialDraft?.sessionMentions ?? [],
|
||||
);
|
||||
const [sessionDragPreview, setSessionDragPreview] = useState<{
|
||||
mention: SessionMention;
|
||||
start: number;
|
||||
@@ -1038,6 +1049,14 @@ export function ThreadComposer({
|
||||
const maxTextBytes = ingressLimits?.message.max_text_bytes ?? 64 * 1024;
|
||||
const { images, enqueue, remove, clear, restoreReadyImages, encoding, full } =
|
||||
useAttachedImages({ ingressLimits });
|
||||
const restoredDraftAttachments = useRef(false);
|
||||
const [draftAttachmentsReady, setDraftAttachmentsReady] = useState(!initialDraft?.files.length);
|
||||
useLayoutEffect(() => {
|
||||
if (restoredDraftAttachments.current) return;
|
||||
restoredDraftAttachments.current = true;
|
||||
if (initialDraft?.files.length) enqueue(initialDraft.files);
|
||||
setDraftAttachmentsReady(true);
|
||||
}, [enqueue, initialDraft]);
|
||||
|
||||
const formatRejection = useCallback(
|
||||
(reason: AttachmentError): string => {
|
||||
@@ -1330,6 +1349,20 @@ export function ThreadComposer({
|
||||
resetKey: pendingQueueKey,
|
||||
});
|
||||
const { rawSelection, replace: replaceMentionInput } = mentionInput;
|
||||
const draftText = composerMentionText(mentionInput.segments).raw;
|
||||
useLayoutEffect(() => {
|
||||
if (!draftKey || !draftStore || !draftAttachmentsReady) return;
|
||||
if (!draftText && images.length === 0 && !quotedContext) {
|
||||
draftStore.delete(draftKey);
|
||||
return;
|
||||
}
|
||||
draftStore.set(draftKey, {
|
||||
text: draftText,
|
||||
files: images.map((image) => image.file),
|
||||
sessionMentions: selectedSessionMentions,
|
||||
quotedContext,
|
||||
}, persistDraft);
|
||||
}, [draftAttachmentsReady, draftKey, draftStore, images, persistDraft, quotedContext, selectedSessionMentions, draftText]);
|
||||
const sessionDragInsertion = sessionDragPreview
|
||||
? mentionInsertion(
|
||||
value,
|
||||
@@ -2035,7 +2068,11 @@ export function ThreadComposer({
|
||||
const isSlashSideChannel = isSideChannelLifecycle(slashLifecycle);
|
||||
const finalizeActiveTurn =
|
||||
slashLifecycle === "finalize_active_turn";
|
||||
const submittedDraft = draftKey ? draftStore?.get(draftKey) : undefined;
|
||||
const finishSend = () => {
|
||||
// A pending send can finish after this composer unmounts and a newer draft is started.
|
||||
if (draftKey && draftStore && draftStore.get(draftKey) !== submittedDraft) return;
|
||||
if (draftKey) draftStore?.delete(draftKey);
|
||||
if (hasTouchPrimaryPointer) textareaRef.current?.blur();
|
||||
setQueuedPrompts([]);
|
||||
// Bubble owns the data URL copy; safe to revoke every staged blob
|
||||
@@ -2073,6 +2110,8 @@ export function ThreadComposer({
|
||||
activeMcpPresetMentions,
|
||||
activeSessionMentions,
|
||||
canSend,
|
||||
draftKey,
|
||||
draftStore,
|
||||
clear,
|
||||
clearComposerText,
|
||||
hasTouchPrimaryPointer,
|
||||
|
||||
@@ -16,6 +16,7 @@ import { PromptNavigator } from "@/components/thread/PromptNavigator";
|
||||
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
|
||||
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
|
||||
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
|
||||
import type { ComposerDraftStore } from "@/lib/composer-draft";
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
import type {
|
||||
ComposerContextUsage,
|
||||
@@ -411,6 +412,7 @@ interface ThreadShellProps {
|
||||
temporaryChatIds?: readonly string[];
|
||||
messageCache?: ThreadMessageCache;
|
||||
filePreviewStore?: FilePreviewStore;
|
||||
draftStore?: ComposerDraftStore;
|
||||
temporaryChatEnabled?: boolean;
|
||||
onTemporaryChatEnabledChange?: (enabled: boolean) => void;
|
||||
onToggleSidebar: () => void;
|
||||
@@ -633,6 +635,7 @@ export function ThreadShell({
|
||||
temporaryChatIds = [],
|
||||
messageCache,
|
||||
filePreviewStore,
|
||||
draftStore,
|
||||
temporaryChatEnabled = false,
|
||||
onTemporaryChatEnabledChange,
|
||||
onToggleSidebar,
|
||||
@@ -739,7 +742,15 @@ export function ThreadShell({
|
||||
const previewOpen = Boolean(activePreview);
|
||||
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
|
||||
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
|
||||
const [quotedContext, setQuotedContext] = useState<string | null>(null);
|
||||
const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
|
||||
const persistDraft = session ? !temporary : !temporaryChatEnabled;
|
||||
const [quote, setQuote] = useState<{ key: string; text: string | null } | null>(null);
|
||||
const quotedContext = quote?.key === draftKey
|
||||
? quote.text
|
||||
: draftStore?.get(draftKey, persistDraft)?.quotedContext ?? null;
|
||||
const setQuotedContext = useCallback((text: string | null) => {
|
||||
setQuote({ key: draftKey, text });
|
||||
}, [draftKey]);
|
||||
const [composerFocusSignal, setComposerFocusSignal] = useState(0);
|
||||
const shellRef = useRef<HTMLElement | null>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -876,7 +887,6 @@ export function ThreadShell({
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
}
|
||||
setClosingPreview(null);
|
||||
setQuotedContext(null);
|
||||
setSubmittedViewportTurnId(null);
|
||||
}, [previewSessionKey]);
|
||||
|
||||
@@ -896,7 +906,7 @@ export function ThreadShell({
|
||||
const handleQuoteSelection = useCallback((text: string) => {
|
||||
setQuotedContext(text);
|
||||
setComposerFocusSignal((value) => value + 1);
|
||||
}, []);
|
||||
}, [setQuotedContext]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1506,6 +1516,7 @@ export function ThreadShell({
|
||||
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
|
||||
setSubmittedViewportTurnId(submitted.turnId);
|
||||
}
|
||||
return submitted !== null;
|
||||
},
|
||||
[chatId, send, withWorkspaceScope],
|
||||
);
|
||||
@@ -1715,6 +1726,10 @@ export function ThreadShell({
|
||||
) : null}
|
||||
{session ? (
|
||||
<ThreadComposer
|
||||
key={draftKey}
|
||||
draftKey={draftKey}
|
||||
draftStore={draftStore}
|
||||
persistDraft={persistDraft}
|
||||
onSend={handleThreadSend}
|
||||
disabled={!chatId}
|
||||
inputAriaLabel={composerInputAriaLabel}
|
||||
@@ -1765,6 +1780,10 @@ export function ThreadShell({
|
||||
/>
|
||||
) : (
|
||||
<ThreadComposer
|
||||
key={draftKey}
|
||||
draftKey={draftKey}
|
||||
draftStore={draftStore}
|
||||
persistDraft={persistDraft}
|
||||
onSend={handleWelcomeSend}
|
||||
disabled={booting}
|
||||
inputAriaLabel={composerInputAriaLabel}
|
||||
@@ -1808,6 +1827,8 @@ export function ThreadShell({
|
||||
onWorkspaceScopeChange={onWorkspaceScopeChange}
|
||||
transcriptionProvider={settingsSnapshot?.transcription?.provider}
|
||||
ingressLimits={ingressLimits}
|
||||
quotedContext={quotedContext}
|
||||
onQuotedContextChange={setQuotedContext}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { SessionMention } from "./types";
|
||||
|
||||
/** Files stay in memory, including unfinished attachments. */
|
||||
export interface ComposerDraft {
|
||||
text: string;
|
||||
files: File[];
|
||||
sessionMentions: SessionMention[];
|
||||
quotedContext: string | null;
|
||||
}
|
||||
|
||||
const STORAGE_PREFIX = "nanobot.composer-draft.v1.";
|
||||
const MAX_STORED_CHARS = 512 * 1024;
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readDraft(raw: string): ComposerDraft | undefined {
|
||||
if (raw.length > MAX_STORED_CHARS) return undefined;
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (!isRecord(value) || typeof value.text !== "string"
|
||||
|| (value.quotedContext !== null && typeof value.quotedContext !== "string")
|
||||
|| !Array.isArray(value.sessionMentions)) return undefined;
|
||||
const sessionMentions = value.sessionMentions.flatMap((item: unknown): SessionMention[] => {
|
||||
if (!isRecord(item) || typeof item.name !== "string"
|
||||
|| !/^[\p{L}\p{N}_-]{1,80}$/u.test(item.name)
|
||||
|| typeof item.session_key !== "string" || !item.session_key.startsWith("websocket:")
|
||||
|| item.session_key.length > 512 || typeof item.title !== "string") return [];
|
||||
return [{
|
||||
name: item.name,
|
||||
session_key: item.session_key,
|
||||
title: item.title.slice(0, 160),
|
||||
...(typeof item.id === "string" && /^handle_[a-f0-9]{32}$/i.test(item.id)
|
||||
? { id: item.id } : {}),
|
||||
}];
|
||||
}).slice(0, 8);
|
||||
return { text: value.text, quotedContext: value.quotedContext, sessionMentions, files: [] };
|
||||
}
|
||||
|
||||
function removeStoredDraft(key: string): void {
|
||||
try { localStorage.removeItem(STORAGE_PREFIX + key); } catch { /* Storage is optional. */ }
|
||||
}
|
||||
|
||||
export function clearStoredComposerDrafts(): void {
|
||||
try {
|
||||
for (let index = localStorage.length - 1; index >= 0; index -= 1) {
|
||||
const key = localStorage.key(index);
|
||||
if (key?.startsWith(STORAGE_PREFIX)) localStorage.removeItem(key);
|
||||
}
|
||||
} catch { /* Storage is optional. */ }
|
||||
}
|
||||
|
||||
export class ComposerDraftStore extends Map<string, ComposerDraft> {
|
||||
override get(key: string, persist = false): ComposerDraft | undefined {
|
||||
const cached = super.get(key);
|
||||
if (cached || !persist) return cached;
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_PREFIX + key);
|
||||
const draft = raw ? readDraft(raw) : undefined;
|
||||
if (draft) super.set(key, draft);
|
||||
return draft;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
override set(key: string, draft: ComposerDraft, persist = false): this {
|
||||
const previous = super.get(key);
|
||||
const unchanged = previous
|
||||
&& previous.text === draft.text
|
||||
&& previous.quotedContext === draft.quotedContext
|
||||
&& previous.files.length === draft.files.length
|
||||
&& previous.files.every((file, index) => file === draft.files[index])
|
||||
&& previous.sessionMentions.length === draft.sessionMentions.length
|
||||
&& previous.sessionMentions.every((mention, index) => mention === draft.sessionMentions[index]);
|
||||
// Restoring a composer is not an edit. Pending sends retain this identity across mounts.
|
||||
super.set(key, unchanged ? previous : draft);
|
||||
if (!persist) return this;
|
||||
if (!draft.text && !draft.quotedContext) {
|
||||
removeStoredDraft(key);
|
||||
return this;
|
||||
}
|
||||
try {
|
||||
const raw = JSON.stringify({
|
||||
text: draft.text,
|
||||
quotedContext: draft.quotedContext,
|
||||
sessionMentions: draft.sessionMentions,
|
||||
});
|
||||
if (raw.length <= MAX_STORED_CHARS) localStorage.setItem(STORAGE_PREFIX + key, raw);
|
||||
else removeStoredDraft(key);
|
||||
} catch {
|
||||
// Keep the in-memory draft, but do not restore an older saved version after refresh.
|
||||
removeStoredDraft(key);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
override delete(key: string): boolean {
|
||||
removeStoredDraft(key);
|
||||
return super.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ComposerDraftStore, clearStoredComposerDrafts, type ComposerDraft } from "@/lib/composer-draft";
|
||||
|
||||
const key = "websocket:draft-storage-test";
|
||||
const storageKey = `nanobot.composer-draft.v1.${key}`;
|
||||
const draft: ComposerDraft = {
|
||||
text: " Keep this draft\n继续编辑",
|
||||
quotedContext: "Quoted answer",
|
||||
sessionMentions: [{ name: "other", title: "Other topic", session_key: "websocket:other" }],
|
||||
files: [new File(["attachment"], "draft.txt", { type: "text/plain" })],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
clearStoredComposerDrafts();
|
||||
});
|
||||
|
||||
describe("composer draft storage", () => {
|
||||
it("restores text, mentions and quotes in a fresh store while keeping files in memory", () => {
|
||||
const store = new ComposerDraftStore();
|
||||
store.set(key, draft, true);
|
||||
expect(store.get(key)).toBe(draft);
|
||||
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
|
||||
expect(new ComposerDraftStore().get("websocket:other", true)).toBeUndefined();
|
||||
expect(localStorage.getItem(storageKey)).not.toContain("files");
|
||||
});
|
||||
|
||||
it("keeps the identity of an unchanged restored draft but advances it for edits", () => {
|
||||
const store = new ComposerDraftStore();
|
||||
store.set(key, draft, true);
|
||||
store.set(key, { ...draft, files: [...draft.files], sessionMentions: [...draft.sessionMentions] }, true);
|
||||
expect(store.get(key)).toBe(draft);
|
||||
const edited = { ...draft, text: "edited draft" };
|
||||
store.set(key, edited, true);
|
||||
expect(store.get(key)).toBe(edited);
|
||||
const reverted = { ...draft };
|
||||
store.set(key, reverted, true);
|
||||
expect(store.get(key)).toBe(reverted);
|
||||
});
|
||||
|
||||
it("requires explicit opt-in for both saving and restoring", () => {
|
||||
const store = new ComposerDraftStore();
|
||||
store.set(key, draft);
|
||||
expect(store.get(key)).toBe(draft);
|
||||
expect(localStorage.getItem(storageKey)).toBeNull();
|
||||
store.set(key, draft, true);
|
||||
expect(new ComposerDraftStore().get(key, false)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("removes saved text when discarded, even if attachments remain", () => {
|
||||
const store = new ComposerDraftStore();
|
||||
store.set(key, draft, true);
|
||||
store.set(key, { ...draft, text: "", quotedContext: null, sessionMentions: [] }, true);
|
||||
expect(store.get(key)?.files).toEqual(draft.files);
|
||||
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("deletes saved drafts without first loading them and clears only drafts on logout", () => {
|
||||
const store = new ComposerDraftStore();
|
||||
store.set(key, draft, true);
|
||||
new ComposerDraftStore().delete(key);
|
||||
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
|
||||
store.set(key, draft, true);
|
||||
store.set("new:chat", draft, true);
|
||||
localStorage.setItem("nanobot.test.other", "keep");
|
||||
clearStoredComposerDrafts();
|
||||
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
|
||||
expect(new ComposerDraftStore().get("new:chat", true)).toBeUndefined();
|
||||
expect(localStorage.getItem("nanobot.test.other")).toBe("keep");
|
||||
localStorage.removeItem("nanobot.test.other");
|
||||
});
|
||||
|
||||
it.each(["{", "null", '{"text":42}', '{"text":"draft","quotedContext":{},"sessionMentions":[]}'])(
|
||||
"ignores malformed saved drafts: %s", (raw) => {
|
||||
localStorage.setItem(storageKey, raw);
|
||||
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it("drops malformed mention records without losing the draft text", () => {
|
||||
localStorage.setItem(storageKey, JSON.stringify({
|
||||
...draft, sessionMentions: [null, { name: 42 }, ...draft.sessionMentions],
|
||||
}));
|
||||
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
|
||||
});
|
||||
|
||||
it("keeps editing usable when storage is unavailable and removes stale saved text", () => {
|
||||
const store = new ComposerDraftStore();
|
||||
store.set(key, draft, true);
|
||||
vi.spyOn(localStorage, "setItem").mockImplementation(() => { throw new Error("quota"); });
|
||||
const updated = { ...draft, text: "latest draft" };
|
||||
store.set(key, updated, true);
|
||||
expect(store.get(key)).toBe(updated);
|
||||
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
|
||||
vi.spyOn(localStorage, "getItem").mockImplementation(() => { throw new Error("disabled"); });
|
||||
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
import { ComposerDraftStore } from "@/lib/composer-draft";
|
||||
import { SESSION_DRAG_TYPE } from "@/lib/session-drag";
|
||||
import type { ChatSummary, CliAppInfo, McpPresetInfo, SlashCommand } from "@/lib/types";
|
||||
|
||||
@@ -3550,3 +3551,121 @@ describe("ThreadComposer", () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
describe("session composer drafts", () => {
|
||||
it("restores independent drafts across session switches and remounts", () => {
|
||||
const draftStore = new ComposerDraftStore();
|
||||
const composer = (key: string) => (
|
||||
<ThreadComposer key={key} draftKey={key} draftStore={draftStore} onSend={vi.fn()} />
|
||||
);
|
||||
const view = render(composer("chat-a"));
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: " draft A\nnext line" } });
|
||||
view.rerender(composer("chat-b"));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("");
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "draft B" } });
|
||||
view.rerender(composer("chat-a"));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue(" draft A\nnext line");
|
||||
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "z", ctrlKey: true });
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue(" draft A\nnext line");
|
||||
view.unmount();
|
||||
render(composer("chat-b"));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("draft B");
|
||||
});
|
||||
|
||||
it("retains in-progress IME text without carrying composition into another chat", () => {
|
||||
const draftStore = new ComposerDraftStore();
|
||||
const composer = (key: string) => (
|
||||
<ThreadComposer key={key} draftKey={key} draftStore={draftStore} onSend={vi.fn()} cliApps={CLI_APPS} />
|
||||
);
|
||||
const view = render(composer("chat-a"));
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: "@gimp " } });
|
||||
fireEvent.compositionStart(input);
|
||||
fireEvent.change(input, { target: { value: "@\u00a0GIMP 草稿" } });
|
||||
view.rerender(composer("chat-b"));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("");
|
||||
view.rerender(composer("chat-a"));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("@\u00a0GIMP 草稿");
|
||||
});
|
||||
|
||||
it.each([true, false])("clears only accepted sends (accepted=%s)", (accepted) => {
|
||||
const draftStore = new ComposerDraftStore();
|
||||
const composer = (key: string) => (
|
||||
<ThreadComposer key={key} draftKey={key} draftStore={draftStore} onSend={() => accepted} />
|
||||
);
|
||||
const view = render(composer("chat-a"));
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "send me" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
view.rerender(composer("chat-b"));
|
||||
view.rerender(composer("chat-a"));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue(accepted ? "" : "send me");
|
||||
});
|
||||
|
||||
it.each([false, true])("clears an accepted draft after restoring it unchanged (attachment=%s)", async (attachment) => {
|
||||
mockBlobUrls();
|
||||
const draftStore = new ComposerDraftStore();
|
||||
let resolveSend!: (accepted: boolean) => void;
|
||||
const onSend = vi.fn(() => new Promise<boolean>((resolve) => { resolveSend = resolve; }));
|
||||
const composer = (key: string) => (
|
||||
<ThreadComposer key={key} draftKey={key} draftStore={draftStore} persistDraft onSend={onSend} />
|
||||
);
|
||||
const view = render(composer("unchanged-draft"));
|
||||
fireEvent.change(screen.getByRole("textbox"), { target: { value: "send once" } });
|
||||
if (attachment) {
|
||||
const file = new File(["image"], "draft.png", { type: "image/png" });
|
||||
fireEvent.change(view.container.querySelector('input[type="file"]')!, { target: { files: [file] } });
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled());
|
||||
}
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
view.rerender(composer("other-draft"));
|
||||
view.rerender(composer("unchanged-draft"));
|
||||
expect(screen.getByRole("textbox")).toHaveValue("send once");
|
||||
if (attachment) await screen.findByText("draft.png");
|
||||
await act(async () => resolveSend(true));
|
||||
view.unmount();
|
||||
expect(new ComposerDraftStore().get("unchanged-draft", true)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not delete a newer draft when an earlier async send completes", async () => {
|
||||
const draftStore = new ComposerDraftStore();
|
||||
let resolveSend!: (accepted: boolean) => void;
|
||||
const onSend = vi.fn(() => new Promise<boolean>((resolve) => { resolveSend = resolve; }));
|
||||
const composer = (key: string) => (
|
||||
<ThreadComposer key={key} draftKey={key} draftStore={draftStore} onSend={onSend} />
|
||||
);
|
||||
const view = render(composer("chat-a"));
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "first" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
view.rerender(composer("chat-b"));
|
||||
view.rerender(composer("chat-a"));
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "newer draft" } });
|
||||
await act(async () => resolveSend(true));
|
||||
view.rerender(composer("chat-b"));
|
||||
view.rerender(composer("chat-a"));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("newer draft");
|
||||
});
|
||||
|
||||
it("restores attachments and quoted context with their original session", async () => {
|
||||
mockBlobUrls();
|
||||
const draftStore = new ComposerDraftStore();
|
||||
const onSend = vi.fn();
|
||||
const composer = (key: string, quote = draftStore.get(key)?.quotedContext) => (
|
||||
<ThreadComposer key={key} draftKey={key} draftStore={draftStore} quotedContext={quote} onSend={onSend} />
|
||||
);
|
||||
const view = render(composer("chat-a", "quoted answer"));
|
||||
const file = new File(["image"], "draft.png", { type: "image/png" });
|
||||
fireEvent.change(view.container.querySelector('input[type="file"]')!, { target: { files: [file] } });
|
||||
view.rerender(composer("chat-b"));
|
||||
expect(screen.queryByText("draft.png")).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("Quoted context")).not.toBeInTheDocument();
|
||||
view.rerender(composer("chat-a"));
|
||||
expect(await screen.findByText("draft.png")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Quoted context")).toHaveTextContent("quoted answer");
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(onSend).toHaveBeenCalledWith("", [expect.objectContaining({
|
||||
media: expect.objectContaining({ name: "draft.png" }),
|
||||
})], { quotedContext: "quoted answer" });
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { ThreadCameraController } from "@/components/thread/thread-camera";
|
||||
import { ThreadShell } from "@/components/thread/ThreadShell";
|
||||
import i18n from "@/i18n";
|
||||
import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft";
|
||||
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
|
||||
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
@@ -474,6 +475,7 @@ function settingsWithFastPreset(): SettingsPayload {
|
||||
describe("ThreadShell", () => {
|
||||
beforeEach(() => {
|
||||
webuiThreadCache.clear();
|
||||
clearStoredComposerDrafts();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue({
|
||||
@@ -484,6 +486,107 @@ describe("ThreadShell", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("clears the welcome draft after a delayed new-chat send and an unchanged round-trip", async () => {
|
||||
const client = makeClient();
|
||||
const store = new ComposerDraftStore();
|
||||
let completeCreate!: (id: string) => void;
|
||||
const onCreateChat = vi.fn(() => new Promise<string>((resolve) => { completeCreate = resolve; }));
|
||||
const shell = (id: string | null) => wrap(client,
|
||||
<ThreadShell session={id ? session(id) : null} title="Draft race" draftStore={store}
|
||||
onToggleSidebar={() => {}} onCreateChat={onCreateChat} />);
|
||||
const view = render(shell(null));
|
||||
fireEvent.change(screen.getByRole("textbox"), { target: { value: "original first message" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(onCreateChat).toHaveBeenCalledTimes(1);
|
||||
view.rerender(shell("other"));
|
||||
view.rerender(shell(null));
|
||||
expect(screen.getByRole("textbox")).toHaveValue("original first message");
|
||||
await act(async () => {
|
||||
view.rerender(shell("created"));
|
||||
completeCreate("created");
|
||||
});
|
||||
await waitFor(() => expect(client.sendMessage).toHaveBeenCalledWith(
|
||||
"created", "original first message", undefined, expect.anything()));
|
||||
view.unmount();
|
||||
expect(new ComposerDraftStore().get("new:chat", true)).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([false, true])("restores regular drafts after reload but excludes temporary chats (temporary=%s)", async (temporary) => {
|
||||
const client = makeClient();
|
||||
let draftStore = new ComposerDraftStore();
|
||||
draftStore.set("websocket:reload-draft", {
|
||||
text: "original", files: [], sessionMentions: [], quotedContext: "quoted answer",
|
||||
});
|
||||
const shell = () => wrap(client, (
|
||||
<ThreadShell session={session("reload-draft")} title="Reload test" temporary={temporary}
|
||||
draftStore={draftStore} onToggleSidebar={() => {}} />
|
||||
));
|
||||
const first = render(shell());
|
||||
fireEvent.change(screen.getByRole("textbox"), { target: { value: " unsent draft\n第二行" } });
|
||||
first.unmount();
|
||||
draftStore = new ComposerDraftStore();
|
||||
const reloaded = render(shell());
|
||||
expect(screen.getByRole("textbox")).toHaveValue(temporary ? "" : " unsent draft\n第二行");
|
||||
if (temporary) {
|
||||
expect(screen.queryByLabelText("Quoted context")).not.toBeInTheDocument();
|
||||
} else {
|
||||
expect(screen.getByLabelText("Quoted context")).toHaveTextContent("quoted answer");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
await waitFor(() => expect(client.sendMessage).toHaveBeenCalled());
|
||||
reloaded.unmount();
|
||||
draftStore = new ComposerDraftStore();
|
||||
render(shell());
|
||||
expect(screen.getByRole("textbox")).toHaveValue("");
|
||||
expect(screen.queryByLabelText("Quoted context")).not.toBeInTheDocument();
|
||||
}
|
||||
await act(async () => {});
|
||||
clearStoredComposerDrafts();
|
||||
});
|
||||
|
||||
it.each([false, true])("persists only ordinary new-topic drafts (temporary=%s)", async (temporary) => {
|
||||
const client = makeClient();
|
||||
const shell = () => wrap(client, (
|
||||
<ThreadShell session={null} title="New topic" temporaryChatEnabled={temporary}
|
||||
draftStore={new ComposerDraftStore()} onToggleSidebar={() => {}} />
|
||||
));
|
||||
const first = render(shell());
|
||||
fireEvent.change(screen.getByRole("textbox"), { target: { value: "new topic draft" } });
|
||||
first.unmount();
|
||||
render(shell());
|
||||
expect(screen.getByRole("textbox")).toHaveValue(temporary ? "" : "new topic draft");
|
||||
await act(async () => {});
|
||||
clearStoredComposerDrafts();
|
||||
});
|
||||
|
||||
it.each([false, true])("keeps text and quote drafts scoped to the session (temporary=%s)", async (temporary) => {
|
||||
const client = makeClient();
|
||||
const draftStore: ComposerDraftStore = new Map([
|
||||
["websocket:draft-a", { text: "draft A", files: [], sessionMentions: [], quotedContext: "quote A" }],
|
||||
["websocket:draft-b", { text: "draft B", files: [], sessionMentions: [], quotedContext: "quote B" }],
|
||||
]);
|
||||
const shell = (chatId: string) => wrap(client, (
|
||||
<ThreadShell session={session(chatId)} title="Draft test" temporary={temporary}
|
||||
draftStore={draftStore} onToggleSidebar={() => {}} />
|
||||
));
|
||||
const view = render(shell("draft-a"));
|
||||
expect(screen.getByRole("textbox")).toHaveValue("draft A");
|
||||
expect(screen.getByLabelText("Quoted context")).toHaveTextContent("quote A");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove quoted context" }));
|
||||
view.rerender(shell("draft-b"));
|
||||
expect(screen.getByRole("textbox")).toHaveValue("draft B");
|
||||
expect(screen.getByLabelText("Quoted context")).toHaveTextContent("quote B");
|
||||
view.rerender(shell("draft-a"));
|
||||
expect(screen.getByRole("textbox")).toHaveValue("draft A");
|
||||
expect(screen.queryByLabelText("Quoted context")).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
await waitFor(() => expect(client.sendMessage).toHaveBeenCalled());
|
||||
view.rerender(shell("draft-b"));
|
||||
view.rerender(shell("draft-a"));
|
||||
expect(screen.getByRole("textbox")).toHaveValue("");
|
||||
expect(draftStore.has("websocket:draft-a")).toBe(false);
|
||||
await act(async () => {});
|
||||
});
|
||||
|
||||
it("surfaces and retries a deferred trace-detail request failure", async () => {
|
||||
const client = makeClient();
|
||||
let detailCalls = 0;
|
||||
|
||||
Reference in new issue
Block a user