🤯 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): scope input history by user and agent (#16461)
YuTengjingb8595e1fead0
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 49a8e5fab81..327fdb1e385 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -31,6 +31,7 @@ import {labPreferSelectors,settingsSelectors,systemAgentSelectors,+ userProfileSelectors,} from '@/store/user/selectors';import { useAgentId } from '../hooks/useAgentId';@@ -94,7 +95,10 @@ const InputEditor = memo<{const state = useEditorState(editor);const { allowed: canCreateContent } = usePermission('create_content');const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));+ const userId = useUserStore(userProfileSelectors.userId);const { enableScope, disableScope } = useHotkeysContext();+ const agentId = useAgentId();+ const inputHistoryScope = useMemo(() => ({ agentId, userId }), [agentId, userId]);const { compositionProps, isComposingRef } = useIMECompositionEvent();@@ -108,13 +112,13 @@ const InputEditor = memo<{enabled: isInputHistoryEnabled,getMarkdownContent,isComposingRef,+ scope: inputHistoryScope,});// --- Category-based mention system ---const categories = useMentionCategories();// Get agent's model info for vision support check and handle paste upload- const agentId = useAgentId();const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));const heterogeneousType = useAgentStore(diff --git a/src/features/ChatInput/hooks/useChatInputHistory.test.ts b/src/features/ChatInput/hooks/useChatInputHistory.test.tsindex d25fa704de3..2002dfe2971 100644--- a/src/features/ChatInput/hooks/useChatInputHistory.test.ts+++ b/src/features/ChatInput/hooks/useChatInputHistory.test.ts@@ -193,6 +193,39 @@ describe('useChatInputHistory', () => {expect(editor.focus).toHaveBeenCalledTimes(2);});+ 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 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,+ scope: { agentId: 'agent-1', userId: 'user-a' },+ }),+ );++ act(() => {+ result.current.handleKeyDown(createKeyDownEvent('ArrowUp'));+ });++ expect(editor.setDocument).toHaveBeenCalledWith('markdown', 'scoped prompt', {+ keepHistory: true,+ });+ expect(editor.setDocument).not.toHaveBeenCalledWith('markdown', 'other agent prompt', {+ 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' });diff --git a/src/features/ChatInput/hooks/useChatInputHistory.ts b/src/features/ChatInput/hooks/useChatInputHistory.tsindex d07c4e01e15..21f64583e43 100644--- a/src/features/ChatInput/hooks/useChatInputHistory.ts+++ b/src/features/ChatInput/hooks/useChatInputHistory.ts@@ -1,8 +1,8 @@import type { IEditor } from '@lobehub/editor';import type { RefObject } from 'react';-import { useCallback, useEffect, useRef } from 'react';+import { useCallback, useMemo, useRef } from 'react';-import type { ChatInputHistoryEntry } from '../inputHistoryStorage';+import type { ChatInputHistoryEntry, ChatInputHistoryScope } from '../inputHistoryStorage';import { getInputHistory } from '../inputHistoryStorage';interface InputHistoryNavigatorOptions {@@ -100,10 +100,9 @@ interface UseChatInputHistoryOptions {enabled: boolean;getMarkdownContent: () => string;isComposingRef: RefObject<boolean>;+ scope?: ChatInputHistoryScope;}-const HISTORY_SET_DOCUMENT_OPTIONS = { keepHistory: true };-const focusEditorAfterHistoryNavigation = (editor: IEditor, onFocusRestored: () => void) => {requestAnimationFrame(() => {// setDocument/cleanDocument can make the Lexical root lose focus; keep@@ -115,16 +114,16 @@ const focusEditorAfterHistoryNavigation = (editor: IEditor, onFocusRestored: ()const restoreHistoryEntryDocument = (editor: IEditor, entry: ChatInputHistoryEntry) => {if (!entry.json) {- editor.setDocument('markdown', entry.markdown, HISTORY_SET_DOCUMENT_OPTIONS);+ editor.setDocument('markdown', entry.markdown, { keepHistory: true });return;}try {- editor.setDocument('json', entry.json, HISTORY_SET_DOCUMENT_OPTIONS);+ editor.setDocument('json', entry.json, { keepHistory: true });} 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);+ editor.setDocument('markdown', entry.markdown, { keepHistory: true });}};@@ -133,8 +132,8 @@ export const useChatInputHistory = ({enabled,getMarkdownContent,isComposingRef,+ scope,}: UseChatInputHistoryOptions) => {- const navigatorRef = useRef<InputHistoryNavigator | null>(null);const skipNextBlurResetRef = useRef(false);const skipNextChangeResetRef = useRef(false);@@ -168,26 +167,18 @@ export const useChatInputHistory = ({});}, [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 navigator = useMemo(() => {+ return createInputHistoryNavigator({+ applyEntry: restoreEntry,+ clearInput,+ getEntries: () => getInputHistory(scope),+ getMarkdownContent,+ });+ }, [clearInput, getMarkdownContent, restoreEntry, scope]);const reset = useCallback(() => {- navigatorRef.current?.reset();- }, []);+ navigator.reset();+ }, [navigator]);const handleEditorBlur = useCallback(() => {if (skipNextBlurResetRef.current) {@@ -215,9 +206,9 @@ export const useChatInputHistory = ({if (shouldIgnoreInputHistoryKeyDown(event, isComposingRef.current)) return false;- return getNavigator().handleKeyDown(event);+ return navigator.handleKeyDown(event);},- [editor, enabled, getNavigator, isComposingRef],+ [editor, enabled, isComposingRef, navigator],);return {diff --git a/src/features/ChatInput/inputHistoryStorage.test.ts b/src/features/ChatInput/inputHistoryStorage.test.tsindex cd2c4838238..0abe14e8ee0 100644--- a/src/features/ChatInput/inputHistoryStorage.test.ts+++ b/src/features/ChatInput/inputHistoryStorage.test.ts@@ -4,6 +4,7 @@ import {addInputHistory,CHAT_INPUT_HISTORY_STORAGE_KEY,getInputHistory,+ getInputHistoryStorageKey,} from './inputHistoryStorage';describe('inputHistoryStorage', () => {@@ -37,10 +38,31 @@ describe('inputHistoryStorage', () => {it('ignores empty markdown', () => {addInputHistory({ markdown: ' ' });- expect(localStorage.getItem(CHAT_INPUT_HISTORY_STORAGE_KEY)).toBeNull();+ expect(localStorage.getItem(getInputHistoryStorageKey())).toBeNull();expect(getInputHistory()).toEqual([]);});+ it('isolates history by user and agent', () => {+ vi.spyOn(Date, 'now')+ .mockReturnValueOnce(1000)+ .mockReturnValueOnce(2000)+ .mockReturnValueOnce(3000);++ addInputHistory({ agentId: 'agent-1', markdown: 'user A prompt', userId: 'user-a' });+ addInputHistory({ agentId: 'agent-1', markdown: 'user B prompt', userId: 'user-b' });+ addInputHistory({ agentId: 'agent-2', markdown: 'user A agent 2 prompt', userId: 'user-a' });++ expect(getInputHistory({ agentId: 'agent-1', userId: 'user-a' })).toEqual([+ { createdAt: 1000, markdown: 'user A prompt' },+ ]);+ expect(getInputHistory({ agentId: 'agent-1', userId: 'user-b' })).toEqual([+ { createdAt: 2000, markdown: 'user B prompt' },+ ]);+ expect(getInputHistory({ agentId: 'agent-2', userId: 'user-a' })).toEqual([+ { createdAt: 3000, markdown: 'user A agent 2 prompt' },+ ]);+ });+it('deduplicates by trimmed markdown and keeps the latest editor state', () => {vi.spyOn(Date, 'now').mockReturnValueOnce(1000).mockReturnValueOnce(2000);@@ -68,7 +90,7 @@ describe('inputHistoryStorage', () => {});it('treats corrupt storage as empty and recovers on next write', () => {- localStorage.setItem(CHAT_INPUT_HISTORY_STORAGE_KEY, '{not json');+ localStorage.setItem(getInputHistoryStorageKey(), '{not json');expect(getInputHistory()).toEqual([]);@@ -79,7 +101,7 @@ describe('inputHistoryStorage', () => {it('drops malformed entries when reading', () => {localStorage.setItem(- CHAT_INPUT_HISTORY_STORAGE_KEY,+ getInputHistoryStorageKey(),JSON.stringify([{ createdAt: 1, markdown: 'good prompt' },{ createdAt: 2, markdown: ' ' },@@ -89,4 +111,17 @@ describe('inputHistoryStorage', () => {expect(getInputHistory()).toEqual([{ createdAt: 1, markdown: 'good prompt' }]);});++ it('drops the legacy global key instead of reading it', () => {+ const legacyStorageKey = 'lobechat:chat-input-history:v1';++ localStorage.setItem(+ legacyStorageKey,+ JSON.stringify([{ createdAt: 1, markdown: 'legacy prompt' }]),+ );++ expect(getInputHistory({ agentId: 'agent-1', userId: 'user-a' })).toEqual([]);+ expect(localStorage.getItem(legacyStorageKey)).toBeNull();+ expect(localStorage.getItem(CHAT_INPUT_HISTORY_STORAGE_KEY)).toBeNull();+ });});diff --git a/src/features/ChatInput/inputHistoryStorage.ts b/src/features/ChatInput/inputHistoryStorage.tsindex 5933b521c57..f181ccc3148 100644--- a/src/features/ChatInput/inputHistoryStorage.ts+++ b/src/features/ChatInput/inputHistoryStorage.ts@@ -1,7 +1,7 @@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 CHAT_INPUT_HISTORY_STORAGE_KEY = 'lobechat:chat-input-history:v2';export const MAX_INPUT_HISTORY_ITEMS = 50;@@ -11,11 +11,35 @@ export interface ChatInputHistoryEntry {markdown: string;}-interface AddInputHistoryParams {+export interface ChatInputHistoryScope {+ agentId?: string;+ userId?: string;+}++interface AddInputHistoryParams extends ChatInputHistoryScope {json?: UnknownRecord;markdown: string;}+const ANONYMOUS_INPUT_HISTORY_SCOPE = 'anonymous';+const GLOBAL_AGENT_INPUT_HISTORY_SCOPE = 'global';+const LEGACY_GLOBAL_INPUT_HISTORY_STORAGE_KEY = 'lobechat:chat-input-history:v1';++/**+ * Example: user A's prompt must not appear when user B opens another agent and presses ArrowUp.+ */+export const getInputHistoryStorageKey = ({+ agentId,+ userId,+}: ChatInputHistoryScope = {}): string =>+ [+ CHAT_INPUT_HISTORY_STORAGE_KEY,+ 'user',+ encodeURIComponent(userId || ANONYMOUS_INPUT_HISTORY_SCOPE),+ 'agent',+ encodeURIComponent(agentId || GLOBAL_AGENT_INPUT_HISTORY_SCOPE),+ ].join(':');+const isHistoryEntry = (value: unknown): value is ChatInputHistoryEntry => {if (!isRecord(value)) return false;@@ -29,11 +53,21 @@ const isHistoryEntry = (value: unknown): value is ChatInputHistoryEntry => {);};-const readAll = (): ChatInputHistoryEntry[] => {+const removeLegacyGlobalHistory = () => {+ try {+ window.localStorage.removeItem(LEGACY_GLOBAL_INPUT_HISTORY_STORAGE_KEY);+ } catch {+ // Ignore storage failures; scoped history should still work when possible.+ }+};++const readAll = (scope?: ChatInputHistoryScope): ChatInputHistoryEntry[] => {if (typeof window === 'undefined') return [];+ removeLegacyGlobalHistory();+try {- const raw = window.localStorage.getItem(CHAT_INPUT_HISTORY_STORAGE_KEY);+ const raw = window.localStorage.getItem(getInputHistoryStorageKey(scope));if (!raw) return [];const parsed = JSON.parse(raw);@@ -45,23 +79,32 @@ const readAll = (): ChatInputHistoryEntry[] => {}};-const writeAll = (items: ChatInputHistoryEntry[]): boolean => {+const writeAll = (items: ChatInputHistoryEntry[], scope?: ChatInputHistoryScope): boolean => {if (typeof window === 'undefined') return false;+ removeLegacyGlobalHistory();+try {- window.localStorage.setItem(CHAT_INPUT_HISTORY_STORAGE_KEY, JSON.stringify(items));+ window.localStorage.setItem(getInputHistoryStorageKey(scope), JSON.stringify(items));return true;} catch {return false;}};-export const getInputHistory = (): ChatInputHistoryEntry[] => readAll();+export const getInputHistory = (scope?: ChatInputHistoryScope): ChatInputHistoryEntry[] =>+ readAll(scope);-export const addInputHistory = ({ json, markdown }: AddInputHistoryParams): void => {+export const addInputHistory = ({+ agentId,+ json,+ markdown,+ userId,+}: AddInputHistoryParams): void => {const normalizedMarkdown = markdown.trim();if (!normalizedMarkdown) return;+ const scope = { agentId, userId };const createdAt = Date.now();const nextEntry: ChatInputHistoryEntry = {createdAt,@@ -69,7 +112,7 @@ export const addInputHistory = ({ json, markdown }: AddInputHistoryParams): void...(json ? { json } : {}),};- const dedupedItems = readAll().filter((item) => item.markdown.trim() !== normalizedMarkdown);+ const dedupedItems = readAll(scope).filter((item) => item.markdown.trim() !== normalizedMarkdown);- writeAll([nextEntry, ...dedupedItems].slice(0, MAX_INPUT_HISTORY_ITEMS));+ writeAll([nextEntry, ...dedupedItems].slice(0, MAX_INPUT_HISTORY_ITEMS), scope);};diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.tsindex 0f76d92f5ba..02a42c1ddb2 100644--- a/src/features/ChatInput/store/action.test.ts+++ b/src/features/ChatInput/store/action.test.ts@@ -1,12 +1,15 @@import type { IEditor } from '@lobehub/editor';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { useAgentStore } from '@/store/agent';+import { getInputHistory } from '../inputHistoryStorage';import { createStore, selectors } from '.';describe('ChatInput store actions', () => {beforeEach(() => {localStorage.clear();+ useAgentStore.setState({ activeAgentId: undefined });vi.restoreAllMocks();});@@ -32,6 +35,7 @@ describe('ChatInput store actions', () => {getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : editorData)),};const store = createStore({+ agentId: 'agent-1',editor: editor as unknown as IEditor,onSend: ({ clearContent }) => {clearContent();@@ -40,12 +44,35 @@ describe('ChatInput store actions', () => {store.getState().handleSendButton();- expect(getInputHistory()[0]).toMatchObject({+ expect(getInputHistory({ agentId: 'agent-1' })[0]).toMatchObject({json: editorData,markdown: 'Hello',});});+ it('records sent input in the active agent history when no agent id is provided', () => {+ useAgentStore.setState({ activeAgentId: 'active-agent' });++ 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: vi.fn(),+ });++ store.getState().handleSendButton();++ expect(getInputHistory({ agentId: 'active-agent' })[0]).toMatchObject({+ json: editorData,+ markdown: 'Hello',+ });+ expect(getInputHistory()).toEqual([]);+ });+it('does not record history when the input history feature is disabled', () => {const editor = {cleanDocument: vi.fn(),@@ -61,6 +88,7 @@ describe('ChatInput store actions', () => {store.getState().handleSendButton();expect(getInputHistory()).toEqual([]);+ expect(editor.getDocument).not.toHaveBeenCalled();});it('does not record history when no send handler is configured', () => {diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex 259f7ba3432..a8d51c82e75 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -1,5 +1,9 @@import { type StateCreator } from 'zustand/vanilla';+import { useAgentStore } from '@/store/agent';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';+import { removeDraft } from '../draftStorage';import { addInputHistory } from '../inputHistoryStorage';import { type PublicState, type State } from './initialState';@@ -26,6 +30,12 @@ type CreateStore = (initState?: Partial<PublicState>,) => StateCreator<Store, [['zustand/devtools', never]]>;+const getEffectiveAgentId = (agentId?: string): string => {+ // Example: a ChatInput without an agentId prop reads history from activeAgentId,+ // so sending must write history to the same scope.+ return agentId !== undefined ? agentId : useAgentStore.getState().activeAgentId || '';+};+export const store: CreateStore = (publicState) => (set, get) => ({...initialState,...publicState,@@ -50,8 +60,15 @@ export const store: CreateStore = (publicState) => (set, get) => ({if (get().sendButtonProps?.disabled) return;const onSend = get().onSend;- const markdown = get().getMarkdownContent();- const json = get().getJSONState();+ const historyEnabled = !!onSend && (get().feature?.inputHistory ?? true);+ const historySnapshot = historyEnabled+ ? {+ agentId: getEffectiveAgentId(get().agentId),+ json: get().getJSONState(),+ markdown: get().getMarkdownContent(),+ userId: userProfileSelectors.userId(useUserStore.getState()),+ }+ : undefined;onSend?.({clearContent: () => editor?.cleanDocument(),@@ -60,8 +77,8 @@ export const store: CreateStore = (publicState) => (set, get) => ({getMarkdownContent: get().getMarkdownContent,});- if (onSend && (get().feature?.inputHistory ?? true)) {- addInputHistory({ json, markdown });+ if (historySnapshot) {+ addInputHistory(historySnapshot);}const { draftKey } = get();