Skip to content

🤯 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.

✨ feat(chat): add input history navigation (#16446)

YuTengjingcdc188149487
diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.md
index 88784493c8e..fec14c48346 100644
--- a/.agents/skills/typescript/SKILL.md
+++ b/.agents/skills/typescript/SKILL.md
@@ -58,11 +58,12 @@ user-invocable: false
## Performance
-- Reuse existing utils in `packages/utils` or installed npm packages
- Query only required columns from database
-## Time Consistency
+## Reusability
+- Reuse existing utils in `packages/utils` or installed npm packages
+- Do not hand-roll reusable record/object-map guards such as `typeof value === 'object' && value !== null`; import helpers like `isRecord`, `isPlainRecord`, `isObjectLike`, `toRecord`, `pickString`, `UnknownRecord`, etc. from `@lobechat/utils/object`.
- Assign `Date.now()` to a constant once and reuse for consistency
## Logging
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index f4d3efc5369..49a8e5fab81 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -35,6 +35,7 @@ import {
import { useAgentId } from '../hooks/useAgentId';
import { useChatInputDraft } from '../hooks/useChatInputDraft';
+import { useChatInputHistory } from '../hooks/useChatInputHistory';
import { useChatInputStore, useStoreApi } from '../store';
import {
INSERT_ACTION_TAG_COMMAND,
@@ -71,6 +72,7 @@ const InputEditor = memo<{
expand,
slashPlacement,
isInputCompletionEnabled,
+ isInputHistoryEnabled,
isMentionEnabled,
isSlashEnabled,
] = useChatInputStore((s) => [
@@ -81,6 +83,7 @@ const InputEditor = memo<{
s.expand,
s.slashPlacement ?? 'top',
s.feature?.inputCompletion ?? true,
+ s.feature?.inputHistory ?? true,
s.feature?.mention ?? true,
s.feature?.slash ?? true,
]);
@@ -96,6 +99,16 @@ const InputEditor = memo<{
const { compositionProps, isComposingRef } = useIMECompositionEvent();
const shouldSendOnEnter = useEnterToSend();
+ const getMarkdownContent = useCallback(
+ () => storeApi.getState().getMarkdownContent(),
+ [storeApi],
+ );
+ const inputHistory = useChatInputHistory({
+ editor,
+ enabled: isInputHistoryEnabled,
+ getMarkdownContent,
+ isComposingRef,
+ });
// --- Category-based mention system ---
const categories = useMentionCategories();
@@ -475,10 +488,12 @@ const InputEditor = memo<{
onInit={handleEditorInit}
onBlur={() => {
disableScope(HotkeyEnum.AddUserMessage);
+ inputHistory.handleEditorBlur();
saveDraftDebounced.flush();
}}
onChange={() => {
updateMarkdownContent();
+ inputHistory.handleEditorChange();
saveDraftDebounced();
}}
onCompositionStart={({ event }) => {
@@ -507,6 +522,9 @@ const InputEditor = memo<{
onFocus={() => {
enableScope(HotkeyEnum.AddUserMessage);
}}
+ onKeyDown={({ event }) => {
+ if (inputHistory.handleKeyDown(event)) return true;
+ }}
onPressEnter={({ event: e }) => {
if (e.shiftKey || isComposingRef.current) return;
// when user like alt + enter to add ai message
diff --git a/src/features/ChatInput/hooks/useChatInputHistory.test.ts b/src/features/ChatInput/hooks/useChatInputHistory.test.ts
new file mode 100644
index 00000000000..d25fa704de3
--- /dev/null
+++ b/src/features/ChatInput/hooks/useChatInputHistory.test.ts
@@ -0,0 +1,230 @@
+import type { IEditor } from '@lobehub/editor';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { addInputHistory } from '../inputHistoryStorage';
+import {
+ createInputHistoryNavigator,
+ shouldIgnoreInputHistoryKeyDown,
+ useChatInputHistory,
+} from './useChatInputHistory';
+
+const createKeyDownEvent = (key: string, init?: KeyboardEventInit) =>
+ new KeyboardEvent('keydown', { key, ...init });
+
+beforeEach(() => {
+ localStorage.clear();
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ callback(0);
+ return 0;
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('createInputHistoryNavigator', () => {
+ it('does not enter history mode when the editor already has input', () => {
+ const applyEntry = vi.fn();
+ const navigator = createInputHistoryNavigator({
+ applyEntry,
+ clearInput: vi.fn(),
+ getEntries: () => [{ createdAt: 1, markdown: 'previous prompt' }],
+ getMarkdownContent: () => 'line 1\nline 2',
+ });
+
+ expect(navigator.handleKeyDown(createKeyDownEvent('ArrowUp'))).toBe(false);
+ expect(applyEntry).not.toHaveBeenCalled();
+ });
+
+ it('navigates older and newer entries after starting from an empty input', () => {
+ const applyEntry = vi.fn();
+ const clearInput = vi.fn();
+ const navigator = createInputHistoryNavigator({
+ applyEntry,
+ clearInput,
+ getEntries: () => [
+ { createdAt: 3, markdown: 'third prompt' },
+ { createdAt: 2, markdown: 'second prompt' },
+ { createdAt: 1, markdown: 'first prompt' },
+ ],
+ getMarkdownContent: () => '',
+ });
+
+ expect(navigator.handleKeyDown(createKeyDownEvent('ArrowUp'))).toBe(true);
+ expect(applyEntry).toHaveBeenLastCalledWith({ createdAt: 3, markdown: 'third prompt' });
+
+ expect(navigator.handleKeyDown(createKeyDownEvent('ArrowUp'))).toBe(true);
+ expect(applyEntry).toHaveBeenLastCalledWith({ createdAt: 2, markdown: 'second prompt' });
+
+ expect(navigator.handleKeyDown(createKeyDownEvent('ArrowDown'))).toBe(true);
+ expect(applyEntry).toHaveBeenLastCalledWith({ createdAt: 3, markdown: 'third prompt' });
+
+ expect(navigator.handleKeyDown(createKeyDownEvent('ArrowDown'))).toBe(true);
+ expect(clearInput).toHaveBeenCalledTimes(1);
+ });
+
+ it('resets history mode on unrelated keys', () => {
+ const applyEntry = vi.fn();
+ const clearInput = vi.fn();
+ const navigator = createInputHistoryNavigator({
+ applyEntry,
+ clearInput,
+ getEntries: () => [{ createdAt: 1, markdown: 'previous prompt' }],
+ getMarkdownContent: () => '',
+ });
+
+ expect(navigator.handleKeyDown(createKeyDownEvent('ArrowUp'))).toBe(true);
+ expect(navigator.handleKeyDown(createKeyDownEvent('a'))).toBe(false);
+ expect(navigator.handleKeyDown(createKeyDownEvent('ArrowDown'))).toBe(false);
+ expect(clearInput).not.toHaveBeenCalled();
+ });
+});
+
+describe('shouldIgnoreInputHistoryKeyDown', () => {
+ it('ignores composing and modified keyboard events', () => {
+ expect(
+ shouldIgnoreInputHistoryKeyDown(createKeyDownEvent('ArrowUp', { altKey: true }), false),
+ ).toBe(true);
+ expect(
+ shouldIgnoreInputHistoryKeyDown(createKeyDownEvent('ArrowUp', { metaKey: true }), false),
+ ).toBe(true);
+ expect(
+ shouldIgnoreInputHistoryKeyDown(createKeyDownEvent('ArrowUp', { shiftKey: true }), false),
+ ).toBe(true);
+ expect(shouldIgnoreInputHistoryKeyDown(createKeyDownEvent('ArrowUp'), true)).toBe(true);
+ });
+
+ it('ignores events that another editor plugin already consumed', () => {
+ const event = createKeyDownEvent('ArrowUp', { cancelable: true });
+ event.preventDefault();
+
+ expect(shouldIgnoreInputHistoryKeyDown(event, false)).toBe(true);
+ });
+
+ it('allows plain arrow key events', () => {
+ expect(shouldIgnoreInputHistoryKeyDown(createKeyDownEvent('ArrowUp'), false)).toBe(false);
+ });
+});
+
+describe('useChatInputHistory', () => {
+ it('preserves the history cursor when restoring an entry briefly blurs the editor', () => {
+ addInputHistory({ markdown: 'older prompt' });
+ addInputHistory({ markdown: 'latest prompt' });
+
+ const frameCallbacks: FrameRequestCallback[] = [];
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frameCallbacks.push(callback);
+ return frameCallbacks.length;
+ });
+
+ let markdown = '';
+ const editor = {
+ cleanDocument: vi.fn(),
+ focus: vi.fn(),
+ setDocument: vi.fn((type: string, value: string) => {
+ if (type === 'markdown') markdown = value;
+ }),
+ } as unknown as IEditor;
+ const isComposingRef = { current: false };
+
+ const { result } = renderHook(() =>
+ useChatInputHistory({
+ editor,
+ enabled: true,
+ getMarkdownContent: () => markdown,
+ isComposingRef,
+ }),
+ );
+
+ act(() => {
+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));
+ result.current.handleEditorBlur();
+ });
+
+ act(() => {
+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));
+ });
+
+ expect(editor.setDocument).toHaveBeenLastCalledWith('markdown', 'older prompt', {
+ keepHistory: true,
+ });
+
+ act(() => {
+ frameCallbacks.forEach((callback) => callback(0));
+ });
+
+ expect(editor.focus).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps editor focus after restoring and clearing history entries', () => {
+ const editorData = { root: { children: [{ text: 'previous prompt' }] } };
+ addInputHistory({ json: editorData, markdown: 'previous prompt' });
+
+ const editor = {
+ cleanDocument: vi.fn(),
+ focus: vi.fn(),
+ setDocument: vi.fn(),
+ } as unknown as IEditor;
+ const isComposingRef = { current: false };
+
+ const { result } = renderHook(() =>
+ useChatInputHistory({
+ editor,
+ enabled: true,
+ getMarkdownContent: () => '',
+ isComposingRef,
+ }),
+ );
+
+ act(() => {
+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));
+ });
+
+ expect(editor.setDocument).toHaveBeenCalledWith('json', editorData, { keepHistory: true });
+ expect(editor.focus).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ result.current.handleKeyDown(createKeyDownEvent('ArrowDown'));
+ });
+
+ expect(editor.cleanDocument).toHaveBeenCalledTimes(1);
+ expect(editor.focus).toHaveBeenCalledTimes(2);
+ });
+
+ it('falls back to markdown when saved JSON cannot be restored', () => {
+ const incompatibleEditorData = { root: { children: [{ text: 'item', type: 'list' }] } };
+ addInputHistory({ json: incompatibleEditorData, markdown: '- fallback prompt' });
+
+ const editor = {
+ cleanDocument: vi.fn(),
+ focus: vi.fn(),
+ setDocument: vi.fn((type: string) => {
+ if (type === 'json') throw new Error('unknown node type');
+ }),
+ } as unknown as IEditor;
+ const isComposingRef = { current: false };
+
+ const { result } = renderHook(() =>
+ useChatInputHistory({
+ editor,
+ enabled: true,
+ getMarkdownContent: () => '',
+ isComposingRef,
+ }),
+ );
+
+ act(() => {
+ expect(result.current.handleKeyDown(createKeyDownEvent('ArrowUp'))).toBe(true);
+ });
+
+ expect(editor.setDocument).toHaveBeenNthCalledWith(1, 'json', incompatibleEditorData, {
+ keepHistory: true,
+ });
+ expect(editor.setDocument).toHaveBeenNthCalledWith(2, 'markdown', '- fallback prompt', {
+ keepHistory: true,
+ });
+ expect(editor.focus).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/ChatInput/hooks/useChatInputHistory.ts b/src/features/ChatInput/hooks/useChatInputHistory.ts
new file mode 100644
index 00000000000..d07c4e01e15
--- /dev/null
+++ b/src/features/ChatInput/hooks/useChatInputHistory.ts
@@ -0,0 +1,229 @@
+import type { IEditor } from '@lobehub/editor';
+import type { RefObject } from 'react';
+import { useCallback, useEffect, useRef } from 'react';
+
+import type { ChatInputHistoryEntry } from '../inputHistoryStorage';
+import { getInputHistory } from '../inputHistoryStorage';
+
+interface InputHistoryNavigatorOptions {
+ applyEntry: (entry: ChatInputHistoryEntry) => void;
+ clearInput: () => void;
+ getEntries: () => ChatInputHistoryEntry[];
+ getMarkdownContent: () => string;
+}
+
+export interface InputHistoryNavigator {
+ handleKeyDown: (event: KeyboardEvent) => boolean;
+ reset: () => void;
+}
+
+export const createInputHistoryNavigator = ({
+ applyEntry,
+ clearInput,
+ getEntries,
+ getMarkdownContent,
+}: InputHistoryNavigatorOptions): InputHistoryNavigator => {
+ let entries: ChatInputHistoryEntry[] = [];
+ let cursor = -1;
+
+ const reset = () => {
+ entries = [];
+ cursor = -1;
+ };
+
+ const applyCurrentEntry = () => {
+ const entry = entries[cursor];
+ if (!entry) return false;
+
+ applyEntry(entry);
+ return true;
+ };
+
+ const showOlderEntry = () => {
+ if (cursor === -1) {
+ // Empty input is the only entry point. Once history mode starts, users can
+ // keep pressing ArrowUp/ArrowDown even though restored entries are non-empty.
+ // Example: with "line 1\nline 2" in the editor, ArrowUp should move the
+ // cursor up instead of replacing the draft with the previous prompt.
+ if (getMarkdownContent().trim().length > 0) return false;
+
+ entries = getEntries();
+ if (entries.length === 0) return false;
+
+ cursor = 0;
+ return applyCurrentEntry();
+ }
+
+ cursor = Math.min(cursor + 1, entries.length - 1);
+ return applyCurrentEntry();
+ };
+
+ const showNewerEntry = () => {
+ if (cursor === -1) return false;
+
+ if (cursor === 0) {
+ reset();
+ clearInput();
+ return true;
+ }
+
+ cursor -= 1;
+ return applyCurrentEntry();
+ };
+
+ return {
+ handleKeyDown: (event) => {
+ if (event.key === 'ArrowUp') return showOlderEntry();
+ if (event.key === 'ArrowDown') return showNewerEntry();
+
+ reset();
+ return false;
+ },
+ reset,
+ };
+};
+
+export const shouldIgnoreInputHistoryKeyDown = (
+ event: KeyboardEvent,
+ isComposing: boolean,
+): boolean =>
+ event.defaultPrevented ||
+ event.isComposing ||
+ isComposing ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.shiftKey;
+
+interface UseChatInputHistoryOptions {
+ editor?: IEditor;
+ enabled: boolean;
+ getMarkdownContent: () => string;
+ isComposingRef: RefObject<boolean>;
+}
+
+const HISTORY_SET_DOCUMENT_OPTIONS = { keepHistory: true };
+
+const focusEditorAfterHistoryNavigation = (editor: IEditor, onFocusRestored: () => void) => {
+ requestAnimationFrame(() => {
+ // setDocument/cleanDocument can make the Lexical root lose focus; keep
+ // keyboard navigation active so ArrowUp can continue walking prompt history.
+ editor.focus();
+ onFocusRestored();
+ });
+};
+
+const restoreHistoryEntryDocument = (editor: IEditor, entry: ChatInputHistoryEntry) => {
+ if (!entry.json) {
+ editor.setDocument('markdown', entry.markdown, HISTORY_SET_DOCUMENT_OPTIONS);
+ return;
+ }
+
+ try {
+ editor.setDocument('json', entry.json, HISTORY_SET_DOCUMENT_OPTIONS);
+ } catch {
+ // Example: a rich-input list/code node can fail after rich input is disabled;
+ // markdown stays portable across different chat input plugin sets.
+ editor.setDocument('markdown', entry.markdown, HISTORY_SET_DOCUMENT_OPTIONS);
+ }
+};
+
+export const useChatInputHistory = ({
+ editor,
+ enabled,
+ getMarkdownContent,
+ isComposingRef,
+}: UseChatInputHistoryOptions) => {
+ const navigatorRef = useRef<InputHistoryNavigator | null>(null);
+ const skipNextBlurResetRef = useRef(false);
+ const skipNextChangeResetRef = useRef(false);
+
+ const runHistoryDocumentMutation = useCallback(
+ (mutation: (editor: IEditor) => void) => {
+ if (!editor) return;
+
+ skipNextBlurResetRef.current = true;
+ skipNextChangeResetRef.current = true;
+
+ mutation(editor);
+ focusEditorAfterHistoryNavigation(editor, () => {
+ skipNextBlurResetRef.current = false;
+ });
+ },
+ [editor],
+ );
+
+ const restoreEntry = useCallback(
+ (entry: ChatInputHistoryEntry) => {
+ runHistoryDocumentMutation((editor) => {
+ restoreHistoryEntryDocument(editor, entry);
+ });
+ },
+ [runHistoryDocumentMutation],
+ );
+
+ const clearInput = useCallback(() => {
+ runHistoryDocumentMutation((editor) => {
+ editor.cleanDocument();
+ });
+ }, [runHistoryDocumentMutation]);
+
+ const getNavigator = useCallback(() => {
+ if (!navigatorRef.current) {
+ navigatorRef.current = createInputHistoryNavigator({
+ applyEntry: restoreEntry,
+ clearInput,
+ getEntries: getInputHistory,
+ getMarkdownContent,
+ });
+ }
+
+ return navigatorRef.current;
+ }, [clearInput, getMarkdownContent, restoreEntry]);
+
+ useEffect(() => {
+ navigatorRef.current = null;
+ }, [getNavigator]);
+
+ const reset = useCallback(() => {
+ navigatorRef.current?.reset();
+ }, []);
+
+ const handleEditorBlur = useCallback(() => {
+ if (skipNextBlurResetRef.current) {
+ // Example: restoring "latest" may briefly blur Lexical before rAF focus;
+ // keep the cursor so the next ArrowUp can continue to "older".
+ skipNextBlurResetRef.current = false;
+ return;
+ }
+
+ reset();
+ }, [reset]);
+
+ const handleEditorChange = useCallback(() => {
+ if (skipNextChangeResetRef.current) {
+ skipNextChangeResetRef.current = false;
+ return;
+ }
+
+ reset();
+ }, [reset]);
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent) => {
+ if (!enabled || !editor) return false;
+
+ if (shouldIgnoreInputHistoryKeyDown(event, isComposingRef.current)) return false;
+
+ return getNavigator().handleKeyDown(event);
+ },
+ [editor, enabled, getNavigator, isComposingRef],
+ );
+
+ return {
+ handleEditorBlur,
+ handleEditorChange,
+ handleKeyDown,
+ reset,
+ };
+};
diff --git a/src/features/ChatInput/inputHistoryStorage.test.ts b/src/features/ChatInput/inputHistoryStorage.test.ts
new file mode 100644
index 00000000000..cd2c4838238
--- /dev/null
+++ b/src/features/ChatInput/inputHistoryStorage.test.ts
@@ -0,0 +1,92 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ addInputHistory,
+ CHAT_INPUT_HISTORY_STORAGE_KEY,
+ getInputHistory,
+} from './inputHistoryStorage';
+
+describe('inputHistoryStorage', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('saves and reads input history back in newest-first order', () => {
+ vi.spyOn(Date, 'now').mockReturnValueOnce(1000).mockReturnValueOnce(2000);
+
+ addInputHistory({ markdown: 'first prompt' });
+ addInputHistory({
+ json: { root: { children: [{ text: 'second prompt' }] } },
+ markdown: 'second prompt',
+ });
+
+ expect(getInputHistory()).toEqual([
+ {
+ createdAt: 2000,
+ json: { root: { children: [{ text: 'second prompt' }] } },
+ markdown: 'second prompt',
+ },
+ { createdAt: 1000, markdown: 'first prompt' },
+ ]);
+ });
+
+ it('ignores empty markdown', () => {
+ addInputHistory({ markdown: ' ' });
+
+ expect(localStorage.getItem(CHAT_INPUT_HISTORY_STORAGE_KEY)).toBeNull();
+ expect(getInputHistory()).toEqual([]);
+ });
+
+ it('deduplicates by trimmed markdown and keeps the latest editor state', () => {
+ vi.spyOn(Date, 'now').mockReturnValueOnce(1000).mockReturnValueOnce(2000);
+
+ addInputHistory({ json: { v: 1 }, markdown: 'same prompt' });
+ addInputHistory({ json: { v: 2 }, markdown: ' same prompt ' });
+
+ expect(getInputHistory()).toEqual([
+ { createdAt: 2000, json: { v: 2 }, markdown: ' same prompt ' },
+ ]);
+ });
+
+ it('evicts the oldest entries beyond the 50 item cap', () => {
+ let now = 0;
+ vi.spyOn(Date, 'now').mockImplementation(() => (now += 1000));
+
+ for (let i = 0; i < 55; i += 1) {
+ addInputHistory({ markdown: `prompt-${i}` });
+ }
+
+ const history = getInputHistory();
+
+ expect(history).toHaveLength(50);
+ expect(history[0].markdown).toBe('prompt-54');
+ expect(history.at(-1)?.markdown).toBe('prompt-5');
+ });
+
+ it('treats corrupt storage as empty and recovers on next write', () => {
+ localStorage.setItem(CHAT_INPUT_HISTORY_STORAGE_KEY, '{not json');
+
+ expect(getInputHistory()).toEqual([]);
+
+ addInputHistory({ markdown: 'recovered prompt' });
+
+ expect(getInputHistory()[0].markdown).toBe('recovered prompt');
+ });
+
+ it('drops malformed entries when reading', () => {
+ localStorage.setItem(
+ CHAT_INPUT_HISTORY_STORAGE_KEY,
+ JSON.stringify([
+ { createdAt: 1, markdown: 'good prompt' },
+ { createdAt: 2, markdown: ' ' },
+ { createdAt: 3, json: 'bad json', markdown: 'bad prompt' },
+ ]),
+ );
+
+ expect(getInputHistory()).toEqual([{ createdAt: 1, markdown: 'good prompt' }]);
+ });
+});
diff --git a/src/features/ChatInput/inputHistoryStorage.ts b/src/features/ChatInput/inputHistoryStorage.ts
new file mode 100644
index 00000000000..5933b521c57
--- /dev/null
+++ b/src/features/ChatInput/inputHistoryStorage.ts
@@ -0,0 +1,75 @@
+import type { UnknownRecord } from '@lobechat/utils/object';
+import { isRecord } from '@lobechat/utils/object';
+
+export const CHAT_INPUT_HISTORY_STORAGE_KEY = 'lobechat:chat-input-history:v1';
+
+export const MAX_INPUT_HISTORY_ITEMS = 50;
+
+export interface ChatInputHistoryEntry {
+ createdAt: number;
+ json?: UnknownRecord;
+ markdown: string;
+}
+
+interface AddInputHistoryParams {
+ json?: UnknownRecord;
+ markdown: string;
+}
+
+const isHistoryEntry = (value: unknown): value is ChatInputHistoryEntry => {
+ if (!isRecord(value)) return false;
+
+ const { createdAt, json, markdown } = value;
+
+ return (
+ typeof createdAt === 'number' &&
+ typeof markdown === 'string' &&
+ markdown.trim().length > 0 &&
+ (json === undefined || isRecord(json))
+ );
+};
+
+const readAll = (): ChatInputHistoryEntry[] => {
+ if (typeof window === 'undefined') return [];
+
+ try {
+ const raw = window.localStorage.getItem(CHAT_INPUT_HISTORY_STORAGE_KEY);
+ if (!raw) return [];
+
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+
+ return parsed.filter(isHistoryEntry).slice(0, MAX_INPUT_HISTORY_ITEMS);
+ } catch {
+ return [];
+ }
+};
+
+const writeAll = (items: ChatInputHistoryEntry[]): boolean => {
+ if (typeof window === 'undefined') return false;
+
+ try {
+ window.localStorage.setItem(CHAT_INPUT_HISTORY_STORAGE_KEY, JSON.stringify(items));
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+export const getInputHistory = (): ChatInputHistoryEntry[] => readAll();
+
+export const addInputHistory = ({ json, markdown }: AddInputHistoryParams): void => {
+ const normalizedMarkdown = markdown.trim();
+ if (!normalizedMarkdown) return;
+
+ const createdAt = Date.now();
+ const nextEntry: ChatInputHistoryEntry = {
+ createdAt,
+ markdown,
+ ...(json ? { json } : {}),
+ };
+
+ const dedupedItems = readAll().filter((item) => item.markdown.trim() !== normalizedMarkdown);
+
+ writeAll([nextEntry, ...dedupedItems].slice(0, MAX_INPUT_HISTORY_ITEMS));
+};
diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.ts
index c6c51e8a6da..0f76d92f5ba 100644
--- a/src/features/ChatInput/store/action.test.ts
+++ b/src/features/ChatInput/store/action.test.ts
@@ -1,8 +1,15 @@
-import { describe, expect, it } from 'vitest';
+import type { IEditor } from '@lobehub/editor';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { getInputHistory } from '../inputHistoryStorage';
import { createStore, selectors } from '.';
describe('ChatInput store actions', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.restoreAllMocks();
+ });
+
it('clears the autocomplete breaker when dismissing its error', () => {
const store = createStore();
@@ -16,4 +23,58 @@ describe('ChatInput store actions', () => {
expect(selectors.inputCompletionPaused(store.getState())).toBe(false);
expect(selectors.inputCompletionErrorVisible(store.getState())).toBeUndefined();
});
+
+ it('records non-empty sent input in local history before the editor is cleared', () => {
+ const editorData = { root: { children: [{ text: 'Hello' }] } };
+ const editor = {
+ cleanDocument: vi.fn(),
+ focus: vi.fn(),
+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : editorData)),
+ };
+ const store = createStore({
+ editor: editor as unknown as IEditor,
+ onSend: ({ clearContent }) => {
+ clearContent();
+ },
+ });
+
+ store.getState().handleSendButton();
+
+ expect(getInputHistory()[0]).toMatchObject({
+ json: editorData,
+ markdown: 'Hello',
+ });
+ });
+
+ it('does not record history when the input history feature is disabled', () => {
+ const editor = {
+ cleanDocument: vi.fn(),
+ focus: vi.fn(),
+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),
+ };
+ const store = createStore({
+ editor: editor as unknown as IEditor,
+ feature: { inputCompletion: true, inputHistory: false, mention: true, slash: true },
+ onSend: vi.fn(),
+ });
+
+ store.getState().handleSendButton();
+
+ expect(getInputHistory()).toEqual([]);
+ });
+
+ it('does not record history when no send handler is configured', () => {
+ const editor = {
+ cleanDocument: vi.fn(),
+ focus: vi.fn(),
+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),
+ };
+ const store = createStore({
+ editor: editor as unknown as IEditor,
+ });
+
+ store.getState().handleSendButton();
+
+ expect(getInputHistory()).toEqual([]);
+ });
});
diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.ts
index 5ae771ab0d1..259f7ba3432 100644
--- a/src/features/ChatInput/store/action.ts
+++ b/src/features/ChatInput/store/action.ts
@@ -1,6 +1,7 @@
import { type StateCreator } from 'zustand/vanilla';
import { removeDraft } from '../draftStorage';
+import { addInputHistory } from '../inputHistoryStorage';
import { type PublicState, type State } from './initialState';
import { initialState } from './initialState';
@@ -48,13 +49,21 @@ export const store: CreateStore = (publicState) => (set, get) => ({
if (!editor) return;
if (get().sendButtonProps?.disabled) return;
- get().onSend?.({
+ const onSend = get().onSend;
+ const markdown = get().getMarkdownContent();
+ const json = get().getJSONState();
+
+ onSend?.({
clearContent: () => editor?.cleanDocument(),
editor: editor!,
getEditorData: get().getJSONState,
getMarkdownContent: get().getMarkdownContent,
});
+ if (onSend && (get().feature?.inputHistory ?? true)) {
+ addInputHistory({ json, markdown });
+ }
+
const { draftKey } = get();
if (draftKey) removeDraft(draftKey);
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index 8545535af1a..bc23643c7b4 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -34,6 +34,7 @@ export interface ContextWindowMessage {
export interface ChatInputFeature {
inputCompletion?: boolean;
+ inputHistory?: boolean;
mention?: boolean;
slash?: boolean;
}
@@ -47,6 +48,7 @@ export interface InputCompletionError {
export const DEFAULT_CHAT_INPUT_FEATURE = {
inputCompletion: true,
+ inputHistory: true,
mention: true,
slash: true,
} as const satisfies Required<ChatInputFeature>;