🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(chat-input): persist unsent input drafts across tab switches (#14992)
Innei7cf561663888
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsxindex 1f275215f0d..0e242f05019 100644--- a/src/features/ChatInput/ChatInputProvider.tsx+++ b/src/features/ChatInput/ChatInputProvider.tsx@@ -16,6 +16,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(agentId,children,contextWindowMessages,+ draftKey,feature = DEFAULT_CHAT_INPUT_FEATURE,leftActions,rightActions,@@ -39,6 +40,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(createStore({allowExpand,contextWindowMessages,+ draftKey,editor,feature,leftActions,@@ -57,6 +59,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(allowExpand={allowExpand}chatInputEditorRef={chatInputEditorRef}contextWindowMessages={contextWindowMessages}+ draftKey={draftKey}feature={feature}getMessages={getMessages}leftActions={leftActions}diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex b696410f51a..741ff67b526 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -26,6 +26,7 @@ import {} from '@/store/user/selectors';import { useAgentId } from '../hooks/useAgentId';+import { useChatInputDraft } from '../hooks/useChatInputDraft';import { useChatInputStore, useStoreApi } from '../store';import {INSERT_ACTION_TAG_COMMAND,@@ -78,6 +79,7 @@ const InputEditor = memo<{]);const storeApi = useStoreApi();+ const { restoreDraft, saveDraftDebounced } = useChatInputDraft();const state = useEditorState(editor);const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));const { enableScope, disableScope } = useHotkeysContext();@@ -140,7 +142,9 @@ const InputEditor = memo<{: undefined;// Heterogeneous agents (e.g. Claude Code) don't yet support @-assigning to other agentsconst showAgentAssignmentHint =- isMentionEnabled && !heterogeneousName && categories.some((category) => category.id === 'agent');+ isMentionEnabled &&+ !heterogeneousName &&+ categories.some((category) => category.id === 'agent');const { handleUploadFiles } = useUploadFiles({ model, provider });// Listen to editor's paste event for file uploads@@ -300,10 +304,10 @@ const InputEditor = memo<{[enableMention, mentionItemsFn, mentionMarkdownWriter, mentionOnSelect, MentionMenuComp],);- const slashOption = useMemo(() => (isSlashEnabled ? { items: slashItems } : undefined), [- isSlashEnabled,- slashItems,- ]);+ const slashOption = useMemo(+ () => (isSlashEnabled ? { items: slashItems } : undefined),+ [isSlashEnabled, slashItems],+ );const richRenderProps = useMemo(() => {const basePlugins = !enableRichRender@@ -353,9 +357,11 @@ const InputEditor = memo<{onCompositionEnd={({ event }) => compositionProps.onCompositionEnd(event)}onBlur={() => {disableScope(HotkeyEnum.AddUserMessage);+ saveDraftDebounced.flush();}}onChange={() => {updateMarkdownContent();+ saveDraftDebounced();}}onCompositionStart={({ event }) => {compositionProps.onCompositionStart(event);@@ -390,7 +396,11 @@ const InputEditor = memo<{requestAnimationFrame(() => {editor.setDocument('json', saved);});+ return;}+ requestAnimationFrame(() => {+ restoreDraft(editor);+ });}}onPressEnter={({ event: e }) => {if (e.shiftKey || isComposingRef.current) return;diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsxindex b847a19f941..d6c0ba21510 100644--- a/src/features/ChatInput/StoreUpdater.tsx+++ b/src/features/ChatInput/StoreUpdater.tsx@@ -19,6 +19,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(agentId,chatInputEditorRef,contextWindowMessages,+ draftKey,feature = DEFAULT_CHAT_INPUT_FEATURE,mobile,sendButtonProps,@@ -38,6 +39,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(useStoreUpdater('agentId', agentId);useStoreUpdater('contextWindowMessages', contextWindowMessages);+ useStoreUpdater('draftKey', draftKey);useStoreUpdater('mobile', mobile!);useStoreUpdater('mentionItems', mentionItems);useStoreUpdater('leftActions', leftActions!);diff --git a/src/features/ChatInput/draftStorage.test.ts b/src/features/ChatInput/draftStorage.test.tsnew file mode 100644index 00000000000..198291bb2c7--- /dev/null+++ b/src/features/ChatInput/draftStorage.test.ts@@ -0,0 +1,71 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { CHAT_INPUT_DRAFTS_STORAGE_KEY, getDraft, removeDraft, saveDraft } from './draftStorage';++describe('draftStorage', () => {+ beforeEach(() => {+ localStorage.clear();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('saves and reads a draft back', () => {+ saveDraft('main_a_new', { root: { children: [] } });+ expect(getDraft('main_a_new')).toEqual({ root: { children: [] } });+ });++ it('returns undefined for a missing key', () => {+ expect(getDraft('missing')).toBeUndefined();+ });++ it('ignores empty keys', () => {+ saveDraft('', { root: {} });+ expect(localStorage.getItem(CHAT_INPUT_DRAFTS_STORAGE_KEY)).toBeNull();+ expect(getDraft('')).toBeUndefined();+ });++ it('removes a draft', () => {+ saveDraft('k', { root: {} });+ removeDraft('k');+ expect(getDraft('k')).toBeUndefined();+ });++ it('overwrites an existing draft for the same key', () => {+ saveDraft('k', { v: 1 });+ saveDraft('k', { v: 2 });+ expect(getDraft('k')).toEqual({ v: 2 });+ });++ it('evicts the oldest drafts beyond the 50 entry cap', () => {+ let now = 0;+ vi.spyOn(Date, 'now').mockImplementation(() => (now += 1000));++ for (let i = 0; i < 55; i += 1) {+ saveDraft(`key-${i}`, { i });+ }++ expect(getDraft('key-0')).toBeUndefined();+ expect(getDraft('key-4')).toBeUndefined();+ expect(getDraft('key-5')).toEqual({ i: 5 });+ expect(getDraft('key-54')).toEqual({ i: 54 });+ });++ it('treats corrupt storage as empty and recovers on next write', () => {+ localStorage.setItem(CHAT_INPUT_DRAFTS_STORAGE_KEY, '{not json');+ expect(getDraft('k')).toBeUndefined();++ saveDraft('k', { ok: true });+ expect(getDraft('k')).toEqual({ ok: true });+ });++ it('drops malformed entries when reading', () => {+ localStorage.setItem(+ CHAT_INPUT_DRAFTS_STORAGE_KEY,+ JSON.stringify({ bad: { json: 'nope' }, good: { json: { a: 1 }, updatedAt: 1 } }),+ );+ expect(getDraft('good')).toEqual({ a: 1 });+ expect(getDraft('bad')).toBeUndefined();+ });+});diff --git a/src/features/ChatInput/draftStorage.ts b/src/features/ChatInput/draftStorage.tsnew file mode 100644index 00000000000..d4d29c0b481--- /dev/null+++ b/src/features/ChatInput/draftStorage.ts@@ -0,0 +1,82 @@+export const CHAT_INPUT_DRAFTS_STORAGE_KEY = 'lobechat:chat-input-drafts:v1';++const MAX_DRAFTS = 50;++export interface ChatInputDraftEntry {+ json: Record<string, unknown>;+ updatedAt: number;+}++type DraftMap = Record<string, ChatInputDraftEntry>;++const isDraftEntry = (value: unknown): value is ChatInputDraftEntry =>+ !!value &&+ typeof value === 'object' &&+ typeof (value as ChatInputDraftEntry).updatedAt === 'number' &&+ !!(value as ChatInputDraftEntry).json &&+ typeof (value as ChatInputDraftEntry).json === 'object';++const readAll = (): DraftMap => {+ if (typeof window === 'undefined') return {};++ try {+ const raw = window.localStorage.getItem(CHAT_INPUT_DRAFTS_STORAGE_KEY);+ if (!raw) return {};++ const parsed = JSON.parse(raw);+ if (!parsed || typeof parsed !== 'object') return {};++ const result: DraftMap = {};+ for (const [key, value] of Object.entries(parsed)) {+ if (isDraftEntry(value)) result[key] = value;+ }+ return result;+ } catch {+ return {};+ }+};++const writeAll = (map: DraftMap): boolean => {+ if (typeof window === 'undefined') return false;++ try {+ window.localStorage.setItem(CHAT_INPUT_DRAFTS_STORAGE_KEY, JSON.stringify(map));+ return true;+ } catch {+ return false;+ }+};++export const getDraft = (key: string): Record<string, unknown> | undefined => {+ if (!key) return undefined;+ return readAll()[key]?.json;+};++export const saveDraft = (key: string, json: Record<string, unknown>): void => {+ if (!key) return;++ const map = readAll();+ map[key] = { json, updatedAt: Date.now() };++ const keys = Object.keys(map);+ if (keys.length > MAX_DRAFTS) {+ keys+ .sort((a, b) => map[a].updatedAt - map[b].updatedAt)+ .slice(0, keys.length - MAX_DRAFTS)+ .forEach((staleKey) => {+ delete map[staleKey];+ });+ }++ writeAll(map);+};++export const removeDraft = (key: string): void => {+ if (!key) return;++ const map = readAll();+ if (!(key in map)) return;++ delete map[key];+ writeAll(map);+};diff --git a/src/features/ChatInput/hooks/useChatInputDraft.test.tsx b/src/features/ChatInput/hooks/useChatInputDraft.test.tsxnew file mode 100644index 00000000000..bbc5fa766e8--- /dev/null+++ b/src/features/ChatInput/hooks/useChatInputDraft.test.tsx@@ -0,0 +1,43 @@+import type { IEditor } from '@lobehub/editor';+import { act, renderHook } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getDraft } from '../draftStorage';+import { createStore, Provider } from '../store';+import { useChatInputDraft } from './useChatInputDraft';++describe('useChatInputDraft', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ localStorage.clear();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('flushes the pending debounced draft save on unmount', () => {+ const draftJson = { root: { children: [{ text: 'latest edit' }] } };+ const editor = {+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'latest edit' : draftJson)),+ } as unknown as IEditor;+ const store = createStore({ draftKey: 'main_agent_topic', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );++ const { result, unmount } = renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ result.current.saveDraftDebounced();+ });++ expect(getDraft('main_agent_topic')).toBeUndefined();++ unmount();++ expect(getDraft('main_agent_topic')).toEqual(draftJson);+ });+});diff --git a/src/features/ChatInput/hooks/useChatInputDraft.ts b/src/features/ChatInput/hooks/useChatInputDraft.tsnew file mode 100644index 00000000000..740feba93fa--- /dev/null+++ b/src/features/ChatInput/hooks/useChatInputDraft.ts@@ -0,0 +1,44 @@+import type { IEditor } from '@lobehub/editor';+import { debounce } from 'es-toolkit/compat';+import { useCallback, useEffect, useMemo } from 'react';++import { getDraft, removeDraft, saveDraft } from '../draftStorage';+import { useStoreApi } from '../store';++const SAVE_DEBOUNCE_MS = 500;++export const useChatInputDraft = () => {+ const storeApi = useStoreApi();++ const saveDraftDebounced = useMemo(+ () =>+ debounce(() => {+ const { draftKey, editor, getMarkdownContent, getJSONState } = storeApi.getState();+ if (!draftKey || !editor) return;++ if (getMarkdownContent().trim().length === 0) {+ removeDraft(draftKey);+ return;+ }++ const json = getJSONState();+ if (json) saveDraft(draftKey, json);+ }, SAVE_DEBOUNCE_MS),+ [storeApi],+ );++ useEffect(() => () => saveDraftDebounced.flush(), [saveDraftDebounced]);++ const restoreDraft = useCallback(+ (editor: IEditor) => {+ const { draftKey } = storeApi.getState();+ if (!draftKey) return;++ const draft = getDraft(draftKey);+ if (draft) editor.setDocument('json', draft);+ },+ [storeApi],+ );++ return { restoreDraft, saveDraftDebounced };+};diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex 98b73b26c0b..692429c69c5 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -1,5 +1,6 @@import { type StateCreator } from 'zustand/vanilla';+import { removeDraft } from '../draftStorage';import { type PublicState, type State } from './initialState';import { initialState } from './initialState';@@ -42,6 +43,10 @@ export const store: CreateStore = (publicState) => (set, get) => ({getEditorData: get().getJSONState,getMarkdownContent: get().getMarkdownContent,});++ const { draftKey } = get();+ if (draftKey) removeDraft(draftKey);+if (get().expand) {set({ _savedEditorState: undefined, expand: false });}diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex de9a1879c1f..407b2a6e923 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -48,6 +48,7 @@ export interface PublicState {agentId?: string;allowExpand?: boolean;contextWindowMessages?: ContextWindowMessage[];+ draftKey?: string;expand?: boolean;feature?: ChatInputFeature;getMessages?: () => OpenAIChatMessage[];diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex bac70258f07..d2b89586ea6 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -17,6 +17,7 @@ import {} from '@/features/ChatInput/store/initialState';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { fileChatSelectors, useFileStore } from '@/store/file';import WideScreenContainer from '../../WideScreenContainer';@@ -161,6 +162,7 @@ const ChatInput = memo<ChatInputProps>(// ConversationStore stateconst context = useConversationStore((s) => s.context);+ const draftKey = useMemo(() => messageMapKey(context), [context]);const [agentId, inputMessage, sendMessage, stopGenerating] = useConversationStore((s) => [s.context.agentId,s.inputMessage,@@ -337,6 +339,7 @@ const ChatInput = memo<ChatInputProps>(agentId={agentId}allowExpand={allowExpand}contextWindowMessages={contextWindowMessages}+ draftKey={draftKey}feature={feature}getMessages={getMessages}leftActions={leftActions}