π€― 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
β¨ feat(chat-input): popup history picker with ghost preview (#16515)
YuTengjingc0315fddc65e
diff --git a/src/features/ChatInput/InputEditor/InputHistoryPopup.tsx b/src/features/ChatInput/InputEditor/InputHistoryPopup.tsxnew file mode 100644index 00000000000..3d688ef05f9--- /dev/null+++ b/src/features/ChatInput/InputEditor/InputHistoryPopup.tsx@@ -0,0 +1,129 @@+import { createStaticStyles, cx } from 'antd-style';+import { memo, useEffect, useRef } from 'react';+import { createPortal } from 'react-dom';++import type { ChatInputHistoryEntry } from '../inputHistoryStorage';++const styles = createStaticStyles(({ css, cssVar }) => ({+ item: css`+ cursor: pointer;++ overflow: hidden;++ padding-block: 6px;+ padding-inline: 10px;+ border-radius: ${cssVar.borderRadius};++ font-size: 13px;+ line-height: 20px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;++ transition: background 0.1s ${cssVar.motionEaseOut};+ `,+ itemActive: css`+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ `,+ root: css`+ position: absolute;+ z-index: 50;+ inset-block-end: calc(100% + 8px);+ inset-inline: 0;++ overflow-y: auto;++ max-height: 240px;+ padding: 4px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgElevated};+ box-shadow: ${cssVar.boxShadowSecondary};+ `,+}));++/**+ * Normalize a stored markdown prompt into a single-line plain-text preview for+ * both the popup rows and the inline ghost placeholder. Rich-input tags are+ * collapsed to readable mentions so the preview stays scannable.+ */+export const getHistoryPreviewText = (markdown: string): string =>+ markdown+ .replaceAll(/<mention\s[^>]*name="([^"]*)"[^>]*>/g, '@$1')+ .replaceAll(/<refer_topic\s[^>]*name="([^"]*)"[^>]*>/g, '#$1')+ .replaceAll(/<localFile\s[^>]*name="([^"]*)"[^>]*>/g, '$1')+ .replaceAll(/<[^>]+>/g, ' ')+ .replaceAll(/\s+/g, ' ')+ .trim();++interface InputHistoryPopupProps {+ activeIndex: number;+ container: HTMLElement | null;+ entries: ChatInputHistoryEntry[];+ onClose: () => void;+ onHover: (index: number) => void;+ onSelect: (index: number) => void;+ open: boolean;+}++const InputHistoryPopup = memo<InputHistoryPopupProps>(+ ({ activeIndex, container, entries, onClose, onHover, onSelect, open }) => {+ const rootRef = useRef<HTMLDivElement>(null);++ // Close when clicking outside the popup. The editor itself counts as+ // "outside" β clicking back into the editor dismisses history navigation.+ useEffect(() => {+ if (!open) return;+ const handlePointerDown = (event: MouseEvent) => {+ if (rootRef.current?.contains(event.target as Node)) return;+ onClose();+ };+ document.addEventListener('mousedown', handlePointerDown);+ return () => document.removeEventListener('mousedown', handlePointerDown);+ }, [open, onClose]);++ // Keep the highlighted row visible during keyboard navigation.+ useEffect(() => {+ if (!open) return;+ const node = rootRef.current?.querySelector<HTMLElement>(`[data-index="${activeIndex}"]`);+ node?.scrollIntoView({ block: 'nearest' });+ }, [activeIndex, open]);++ if (!open || !container || entries.length === 0) return null;++ // Render the most recent entry nearest the input (bottom of the list that+ // grows upward above the editor).+ const indices = entries.map((_, index) => index).reverse();++ return createPortal(+ <div className={styles.root} ref={rootRef}>+ {indices.map((index) => {+ const entry = entries[index];+ return (+ <div+ className={cx(styles.item, index === activeIndex && styles.itemActive)}+ data-index={index}+ key={`${entry.createdAt}-${index}`}+ onMouseEnter={() => onHover(index)}+ onMouseDown={(event) => {+ // Prevent the editor blur so onSelect can restore content and+ // refocus without a focus flicker.+ event.preventDefault();+ onSelect(index);+ }}+ >+ {getHistoryPreviewText(entry.markdown) || ' '}+ </div>+ );+ })}+ </div>,+ container,+ );+ },+);++InputHistoryPopup.displayName = 'InputHistoryPopup';++export default InputHistoryPopup;diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 8a19fd21cb5..9b4b95ac103 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -45,6 +45,7 @@ import {useSlashActionItems,} from './ActionTag';import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';+import InputHistoryPopup, { getHistoryPreviewText } from './InputHistoryPopup';import { mentionFilledClassName } from './mentionStyle';import Placeholder, { type PlaceholderVariant } from './Placeholder';import { CHAT_INPUT_EMBED_PLUGINS, createChatInputRichPlugins } from './plugins';@@ -61,6 +62,15 @@ const className = cx(mentionFilledClassName,);+// Single-line dimmed preview of the highlighted history entry, shown through the+// editor's placeholder slot while the input is empty (history popup open).+const ghostClassName = css`+ overflow: hidden;+ display: block;+ text-overflow: ellipsis;+ white-space: nowrap;+`;+type MentionOption = ISlashMenuOption | ISlashSectionOption;const InputEditor = memo<{@@ -507,92 +517,115 @@ const InputEditor = memo<{[restoreDraft, storeApi],);+ const ghostMarkdown = inputHistory.ghostMarkdown;+return (- <Editor- autoFocus- pasteAsPlainText- className={className}- content={''}- editable={canCreateContent}- editor={editor}- getPopupContainer={() => (slashMenuRef as any)?.current ?? null}- {...{ slashPlacement }}- {...richRenderProps}- mentionOption={mentionOption}- slashOption={slashOption}- type={'text'}- variant={'chat'}- placeholder={- placeholder ?? (- <Placeholder- heterogeneousName={heterogeneousName}- showAgentAssignmentHint={showAgentAssignmentHint}- variant={placeholderVariant}- />- )- }- style={{- minHeight: defaultRows > 1 ? defaultRows * 23 : undefined,- }}- onCompositionEnd={({ event }) => compositionProps.onCompositionEnd(event)}- onInit={handleEditorInit}- onBlur={() => {- disableScope(HotkeyEnum.AddUserMessage);- inputHistory.handleEditorBlur();- saveDraftDebounced.flush();- }}- onChange={() => {- updateMarkdownContent();- inputHistory.handleEditorChange();- saveDraftDebounced();- }}- onCompositionStart={({ event }) => {- compositionProps.onCompositionStart(event);- // Clear autocomplete placeholder nodes before IME composition starts β- // composing next to placeholder inline nodes freezes the editor.- if (isAutoCompleteEnabled) {- editor?.dispatchCommand(- KEY_ESCAPE_COMMAND,- new KeyboardEvent('keydown', { key: 'Escape' }),- );+ <>+ <InputHistoryPopup+ activeIndex={inputHistory.popup.activeIndex}+ container={(slashMenuRef as any)?.current ?? null}+ entries={inputHistory.popup.entries}+ open={inputHistory.popup.open}+ onClose={inputHistory.close}+ onHover={inputHistory.setActiveIndex}+ onSelect={inputHistory.confirm}+ />+ <Editor+ autoFocus+ pasteAsPlainText+ className={className}+ content={''}+ editable={canCreateContent}+ editor={editor}+ getPopupContainer={() => (slashMenuRef as any)?.current ?? null}+ {...{ slashPlacement }}+ {...richRenderProps}+ mentionOption={mentionOption}+ slashOption={slashOption}+ type={'text'}+ variant={'chat'}+ placeholder={+ ghostMarkdown === undefined ? (+ (placeholder ?? (+ <Placeholder+ heterogeneousName={heterogeneousName}+ showAgentAssignmentHint={showAgentAssignmentHint}+ variant={placeholderVariant}+ />+ ))+ ) : (+ <span className={ghostClassName}>{getHistoryPreviewText(ghostMarkdown)}</span>+ )}- }}- onContextMenu={async ({ event: e, editor }) => {- if (isDesktop) {- e.preventDefault();- const { electronSystemService } = await import('@/services/electron/system');+ style={{+ minHeight: defaultRows > 1 ? defaultRows * 23 : undefined,+ }}+ onCompositionEnd={({ event }) => compositionProps.onCompositionEnd(event)}+ onInit={handleEditorInit}+ onBlur={() => {+ disableScope(HotkeyEnum.AddUserMessage);+ saveDraftDebounced.flush();+ }}+ onChange={() => {+ updateMarkdownContent();+ inputHistory.handleEditorChange();+ saveDraftDebounced();+ }}+ onCompositionStart={({ event }) => {+ compositionProps.onCompositionStart(event);+ // Clear autocomplete placeholder nodes before IME composition starts β+ // composing next to placeholder inline nodes freezes the editor.+ if (isAutoCompleteEnabled) {+ editor?.dispatchCommand(+ KEY_ESCAPE_COMMAND,+ new KeyboardEvent('keydown', { key: 'Escape' }),+ );+ }+ }}+ onContextMenu={async ({ event: e, editor }) => {+ if (isDesktop) {+ e.preventDefault();+ const { electronSystemService } = await import('@/services/electron/system');- const selectionText = editor.getSelectionDocument('markdown') as unknown as string;+ const selectionText = editor.getSelectionDocument('markdown') as unknown as string;- await electronSystemService.showContextMenu('editor', {- selectionText: selectionText || undefined,- });- }- }}- 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- if (e.altKey && hotkey === combineKeys([KeyEnum.Alt, KeyEnum.Enter])) return true;- // In fullscreen mode, Enter inserts newline; only Cmd/Ctrl+Enter sends- if (expand) {- if (isCommandPressed(e)) {+ await electronSystemService.showContextMenu('editor', {+ selectionText: selectionText || undefined,+ });+ }+ }}+ onFocus={() => {+ enableScope(HotkeyEnum.AddUserMessage);+ }}+ onKeyDown={({ event }) => {+ if (inputHistory.handleKeyDown(event)) return true;+ }}+ onPressEnter={({ event: e }) => {+ // While the history popup is open, Enter confirms the highlighted entry+ // instead of sending. onPressEnter runs before onKeyDown for Enter, so+ // returning true here also prevents a newline / send.+ if (inputHistory.popup.open) {+ inputHistory.confirm();+ return true;+ }+ if (e.shiftKey || isComposingRef.current) return;+ // when user like alt + enter to add ai message+ if (e.altKey && hotkey === combineKeys([KeyEnum.Alt, KeyEnum.Enter])) return true;+ // In fullscreen mode, Enter inserts newline; only Cmd/Ctrl+Enter sends+ if (expand) {+ if (isCommandPressed(e)) {+ send();+ return true;+ }+ return;+ }+ if (shouldSendOnEnter(e)) {send();return true;}- return;- }- if (shouldSendOnEnter(e)) {- send();- return true;- }- }}- />+ }}+ />+ </>);});diff --git a/src/features/ChatInput/hooks/useChatInputHistory.test.ts b/src/features/ChatInput/hooks/useChatInputHistory.test.tsindex 2002dfe2971..08e7f895b05 100644--- a/src/features/ChatInput/hooks/useChatInputHistory.test.ts+++ b/src/features/ChatInput/hooks/useChatInputHistory.test.ts@@ -3,15 +3,18 @@ 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';+import { shouldIgnoreInputHistoryKeyDown, useChatInputHistory } from './useChatInputHistory';const createKeyDownEvent = (key: string, init?: KeyboardEventInit) =>new KeyboardEvent('keydown', { key, ...init });+const createEditorMock = (onSetDocument?: (type: string, value: unknown) => void) =>+ ({+ cleanDocument: vi.fn(),+ focus: vi.fn(),+ setDocument: vi.fn((type: string, value: unknown) => onSetDocument?.(type, value)),+ }) as unknown as IEditor;+beforeEach(() => {localStorage.clear();vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {@@ -24,64 +27,6 @@ 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(@@ -109,147 +54,182 @@ describe('shouldIgnoreInputHistoryKeyDown', () => {});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 renderHistory = (overrides: Partial<Parameters<typeof useChatInputHistory>[0]> = {}) => {+ const editor = overrides.editor ?? createEditorMock();const isComposingRef = { current: false };-- const { result } = renderHook(() =>+ const view = renderHook(() =>useChatInputHistory({editor,enabled: true,- getMarkdownContent: () => markdown,+ getMarkdownContent: () => '',isComposingRef,+ ...overrides,}),);+ return { editor, ...view };+ };- act(() => {- result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));- result.current.handleEditorBlur();- });+ it('does not open the popup when the editor already has input', () => {+ addInputHistory({ markdown: 'previous prompt' });+ const { result } = renderHistory({ getMarkdownContent: () => 'line 1\nline 2' });+ let consumed = true;act(() => {- result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ consumed = result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));});- expect(editor.setDocument).toHaveBeenLastCalledWith('markdown', 'older prompt', {- keepHistory: true,- });+ expect(consumed).toBe(false);+ expect(result.current.popup.open).toBe(false);+ });+ it('does not open the popup when there is no history', () => {+ const { result } = renderHistory();++ let consumed = true;act(() => {- frameCallbacks.forEach((callback) => callback(0));+ consumed = result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));});- expect(editor.focus).toHaveBeenCalledTimes(2);+ expect(consumed).toBe(false);+ expect(result.current.popup.open).toBe(false);});- it('keeps editor focus after restoring and clearing history entries', () => {- const editorData = { root: { children: [{ text: 'previous prompt' }] } };- addInputHistory({ json: editorData, markdown: 'previous prompt' });+ it('opens the popup with a ghost preview without mutating the editor', () => {+ addInputHistory({ markdown: 'older prompt' });+ addInputHistory({ markdown: 'latest prompt' });+ const { editor, result } = renderHistory();- const editor = {- cleanDocument: vi.fn(),- focus: vi.fn(),- setDocument: vi.fn(),- } as unknown as IEditor;- const isComposingRef = { current: false };+ act(() => {+ expect(result.current.handleKeyDown(createKeyDownEvent('ArrowUp'))).toBe(true);+ });- const { result } = renderHook(() =>- useChatInputHistory({- editor,- enabled: true,- getMarkdownContent: () => '',- isComposingRef,- }),- );+ expect(result.current.popup.open).toBe(true);+ expect(result.current.popup.activeIndex).toBe(0);+ expect(result.current.ghostMarkdown).toBe('latest prompt');+ expect(editor.setDocument).not.toHaveBeenCalled();+ });++ it('navigates older and newer entries while the popup is open', () => {+ addInputHistory({ markdown: 'first prompt' });+ addInputHistory({ markdown: 'second prompt' });+ addInputHistory({ markdown: 'third prompt' });+ const { result } = renderHistory();act(() => {result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));});+ expect(result.current.ghostMarkdown).toBe('third prompt');- expect(editor.setDocument).toHaveBeenCalledWith('json', editorData, { keepHistory: true });- expect(editor.focus).toHaveBeenCalledTimes(1);+ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });+ expect(result.current.ghostMarkdown).toBe('second prompt');act(() => {result.current.handleKeyDown(createKeyDownEvent('ArrowDown'));});+ expect(result.current.ghostMarkdown).toBe('third prompt');+ });++ it('closes the popup when navigating newer than the most recent entry', () => {+ addInputHistory({ markdown: 'only prompt' });+ const { editor, result } = renderHistory();- expect(editor.cleanDocument).toHaveBeenCalledTimes(1);- expect(editor.focus).toHaveBeenCalledTimes(2);+ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });+ expect(result.current.popup.open).toBe(true);++ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowDown'));+ });+ expect(result.current.popup.open).toBe(false);+ expect(editor.setDocument).not.toHaveBeenCalled();});- it('reads history from the current scope only', () => {- addInputHistory({ agentId: 'agent-1', markdown: 'scoped prompt', userId: 'user-a' });- addInputHistory({ agentId: 'agent-2', markdown: 'other agent prompt', userId: 'user-a' });+ it('closes the popup on Escape without mutating the editor', () => {+ addInputHistory({ markdown: 'only prompt' });+ const { editor, result } = renderHistory();- const editor = {- cleanDocument: vi.fn(),- focus: vi.fn(),- setDocument: vi.fn(),- } as unknown as IEditor;- const isComposingRef = { current: false };+ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ result.current.handleKeyDown(createKeyDownEvent('Escape'));+ });- const { result } = renderHook(() =>- useChatInputHistory({- editor,- enabled: true,- getMarkdownContent: () => '',- isComposingRef,- scope: { agentId: 'agent-1', userId: 'user-a' },- }),- );+ expect(result.current.popup.open).toBe(false);+ expect(editor.setDocument).not.toHaveBeenCalled();+ });++ it('restores the highlighted entry on confirm and refocuses the editor', () => {+ addInputHistory({ markdown: 'older prompt' });+ addInputHistory({ markdown: 'latest prompt' });+ const { editor, result } = renderHistory();act(() => {result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));});+ act(() => {+ result.current.confirm();+ });- expect(editor.setDocument).toHaveBeenCalledWith('markdown', 'scoped prompt', {+ expect(editor.setDocument).toHaveBeenCalledWith('markdown', 'latest prompt', {keepHistory: true,});- expect(editor.setDocument).not.toHaveBeenCalledWith('markdown', 'other agent prompt', {+ expect(editor.focus).toHaveBeenCalledTimes(1);+ expect(result.current.popup.open).toBe(false);+ });++ it('confirms a hovered index via Tab', () => {+ addInputHistory({ markdown: 'older prompt' });+ addInputHistory({ markdown: 'latest prompt' });+ const { editor, result } = renderHistory();++ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });+ act(() => {+ result.current.setActiveIndex(1);+ });+ expect(result.current.ghostMarkdown).toBe('older prompt');++ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('Tab'));+ });++ expect(editor.setDocument).toHaveBeenCalledWith('markdown', 'older prompt', {keepHistory: true,});+ expect(result.current.popup.open).toBe(false);+ });++ it('restores saved JSON when present', () => {+ const editorData = { root: { children: [{ text: 'previous prompt' }] } };+ addInputHistory({ json: editorData, markdown: 'previous prompt' });+ const { editor, result } = renderHistory();++ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });+ act(() => {+ result.current.confirm();+ });++ expect(editor.setDocument).toHaveBeenCalledWith('json', editorData, { keepHistory: true });});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,- }),- );+ const editor = createEditorMock((type) => {+ if (type === 'json') throw new Error('unknown node type');+ });+ const { result } = renderHistory({ editor });act(() => {- expect(result.current.handleKeyDown(createKeyDownEvent('ArrowUp'))).toBe(true);+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });+ act(() => {+ result.current.confirm();});expect(editor.setDocument).toHaveBeenNthCalledWith(1, 'json', incompatibleEditorData, {@@ -258,6 +238,31 @@ describe('useChatInputHistory', () => {expect(editor.setDocument).toHaveBeenNthCalledWith(2, 'markdown', '- fallback prompt', {keepHistory: true,});- expect(editor.focus).toHaveBeenCalledTimes(1);+ });++ it('reads history from the current scope only', () => {+ addInputHistory({ agentId: 'agent-1', markdown: 'scoped prompt', userId: 'user-a' });+ addInputHistory({ agentId: 'agent-2', markdown: 'other agent prompt', userId: 'user-a' });+ const { result } = renderHistory({ scope: { agentId: 'agent-1', userId: 'user-a' } });++ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });++ expect(result.current.popup.entries).toHaveLength(1);+ expect(result.current.ghostMarkdown).toBe('scoped prompt');+ });++ it('does nothing when disabled', () => {+ addInputHistory({ markdown: 'previous prompt' });+ const { result } = renderHistory({ enabled: false });++ let consumed = true;+ act(() => {+ consumed = result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });++ expect(consumed).toBe(false);+ expect(result.current.popup.open).toBe(false);});});diff --git a/src/features/ChatInput/hooks/useChatInputHistory.ts b/src/features/ChatInput/hooks/useChatInputHistory.tsindex 21f64583e43..b971c067396 100644--- a/src/features/ChatInput/hooks/useChatInputHistory.ts+++ b/src/features/ChatInput/hooks/useChatInputHistory.ts@@ -1,87 +1,18 @@import type { IEditor } from '@lobehub/editor';import type { RefObject } from 'react';-import { useCallback, useMemo, useRef } from 'react';+import { useCallback, useRef, useState } from 'react';import type { ChatInputHistoryEntry, ChatInputHistoryScope } 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 interface ChatInputHistoryPopupState {+ /** Index into `entries`; 0 is the most recent prompt. */+ activeIndex: number;+ entries: ChatInputHistoryEntry[];+ open: boolean;}-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,- };-};+const CLOSED_POPUP: ChatInputHistoryPopupState = { activeIndex: 0, entries: [], open: false };export const shouldIgnoreInputHistoryKeyDown = (event: KeyboardEvent,@@ -95,20 +26,11 @@ export const shouldIgnoreInputHistoryKeyDown = (event.metaKey ||event.shiftKey;-interface UseChatInputHistoryOptions {- editor?: IEditor;- enabled: boolean;- getMarkdownContent: () => string;- isComposingRef: RefObject<boolean>;- scope?: ChatInputHistoryScope;-}--const focusEditorAfterHistoryNavigation = (editor: IEditor, onFocusRestored: () => void) => {+const focusEditorAfterHistoryNavigation = (editor: IEditor) => {+ // setDocument can make the Lexical root lose focus; restore it so the user can+ // keep editing the recalled prompt immediately.requestAnimationFrame(() => {- // setDocument/cleanDocument can make the Lexical root lose focus; keep- // keyboard navigation active so ArrowUp can continue walking prompt history.editor.focus();- onFocusRestored();});};@@ -127,6 +49,14 @@ const restoreHistoryEntryDocument = (editor: IEditor, entry: ChatInputHistoryEnt}};+interface UseChatInputHistoryOptions {+ editor?: IEditor;+ enabled: boolean;+ getMarkdownContent: () => string;+ isComposingRef: RefObject<boolean>;+ scope?: ChatInputHistoryScope;+}+export const useChatInputHistory = ({editor,enabled,@@ -134,87 +64,129 @@ export const useChatInputHistory = ({isComposingRef,scope,}: UseChatInputHistoryOptions) => {- 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;- });+ const [popup, setPopup] = useState<ChatInputHistoryPopupState>(CLOSED_POPUP);+ // Mirror of `popup` so the editor keydown closure always reads the latest+ // state synchronously, even between React renders.+ const popupRef = useRef(popup);++ const applyPopup = useCallback((next: ChatInputHistoryPopupState) => {+ popupRef.current = next;+ setPopup(next);+ }, []);++ const close = useCallback(() => {+ if (!popupRef.current.open) return;+ applyPopup(CLOSED_POPUP);+ }, [applyPopup]);++ const setActiveIndex = useCallback(+ (index: number) => {+ const prev = popupRef.current;+ if (!prev.open) return;+ const clamped = Math.max(0, Math.min(index, prev.entries.length - 1));+ if (clamped === prev.activeIndex) return;+ applyPopup({ ...prev, activeIndex: clamped });},- [editor],+ [applyPopup],);- const restoreEntry = useCallback(- (entry: ChatInputHistoryEntry) => {- runHistoryDocumentMutation((editor) => {- restoreHistoryEntryDocument(editor, entry);- });- },- [runHistoryDocumentMutation],- );-- const clearInput = useCallback(() => {- runHistoryDocumentMutation((editor) => {- editor.cleanDocument();- });- }, [runHistoryDocumentMutation]);-- const navigator = useMemo(() => {- return createInputHistoryNavigator({- applyEntry: restoreEntry,- clearInput,- getEntries: () => getInputHistory(scope),- getMarkdownContent,- });- }, [clearInput, getMarkdownContent, restoreEntry, scope]);-- const reset = useCallback(() => {- navigator.reset();- }, [navigator]);+ const confirm = useCallback(+ (index?: number) => {+ const { activeIndex, entries, open } = popupRef.current;+ if (!open) return;- 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;- }+ const entry = entries[index ?? activeIndex];+ // Close first so the onChange fired by setDocument below is a no-op.+ applyPopup(CLOSED_POPUP);- reset();- }, [reset]);+ if (!editor || !entry) return;+ restoreHistoryEntryDocument(editor, entry);+ focusEditorAfterHistoryNavigation(editor);+ },+ [applyPopup, editor],+ );const handleKeyDown = useCallback((event: KeyboardEvent) => {if (!enabled || !editor) return false;-if (shouldIgnoreInputHistoryKeyDown(event, isComposingRef.current)) return false;- return navigator.handleKeyDown(event);+ const state = popupRef.current;++ // Empty input is the only entry point. With non-empty input ArrowUp keeps+ // the editor's native cursor-up behaviour (e.g. moving within multi-line+ // drafts) instead of opening the history popup.+ if (!state.open) {+ if (event.key !== 'ArrowUp') return false;+ if (getMarkdownContent().trim().length > 0) return false;++ const entries = getInputHistory(scope);+ if (entries.length === 0) return false;++ applyPopup({ activeIndex: 0, entries, open: true });+ return true;+ }++ switch (event.key) {+ case 'ArrowUp': {+ setActiveIndex(state.activeIndex + 1);+ return true;+ }+ case 'ArrowDown': {+ // Moving newer than the most recent entry dismisses the popup, leaving+ // the input empty β symmetric with how it was opened.+ if (state.activeIndex === 0) close();+ else setActiveIndex(state.activeIndex - 1);+ return true;+ }+ case 'Tab': {+ confirm(state.activeIndex);+ return true;+ }+ case 'Escape': {+ close();+ return true;+ }+ // Enter is consumed earlier by onPressEnter; handled here defensively.+ case 'Enter': {+ confirm(state.activeIndex);+ return true;+ }+ default: {+ // Any other key (e.g. typing) cancels history and types normally.+ close();+ return false;+ }+ }},- [editor, enabled, isComposingRef, navigator],+ [+ applyPopup,+ close,+ confirm,+ editor,+ enabled,+ getMarkdownContent,+ isComposingRef,+ scope,+ setActiveIndex,+ ],);+ const handleEditorChange = useCallback(() => {+ // Real content changes while the popup is open (e.g. paste) dismiss it.+ if (popupRef.current.open) close();+ }, [close]);++ const ghostMarkdown = popup.open ? popup.entries[popup.activeIndex]?.markdown : undefined;+return {- handleEditorBlur,+ close,+ confirm,+ ghostMarkdown,handleEditorChange,handleKeyDown,- reset,+ popup,+ reset: close,+ setActiveIndex,};};