🤯 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(store): clear new key data when switchTopic to new state (#11078)
Arvin Xu180ea14b1846
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 597e507e0b9..d5ee9c318aa 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -345,6 +345,160 @@ describe('topic action', () => {// Verify that the refreshMessages was called to update the messagesexpect(refreshMessagesSpy).toHaveBeenCalled();});++ it('should support boolean as second parameter for backward compatibility', async () => {+ const topicId = 'topic-id';+ const { result } = renderHook(() => useChatStore());++ const refreshMessagesSpy = vi.spyOn(result.current, 'refreshMessages');++ // Call with boolean (old API)+ await act(async () => {+ await result.current.switchTopic(topicId, true);+ });++ expect(useChatStore.getState().activeTopicId).toBe(topicId);+ // Should not call refreshMessages when skipRefreshMessage is true+ expect(refreshMessagesSpy).not.toHaveBeenCalled();+ });++ it('should support options object as second parameter', async () => {+ const topicId = 'topic-id';+ const { result } = renderHook(() => useChatStore());++ const refreshMessagesSpy = vi.spyOn(result.current, 'refreshMessages');++ // Call with options object (new API)+ await act(async () => {+ await result.current.switchTopic(topicId, { skipRefreshMessage: true });+ });++ expect(useChatStore.getState().activeTopicId).toBe(topicId);+ expect(refreshMessagesSpy).not.toHaveBeenCalled();+ });++ it('should clear new key data when switching to new state (main scope)', async () => {+ const { result } = renderHook(() => useChatStore());+ const activeAgentId = 'test-agent-id';+ const newKey = messageMapKey({ agentId: activeAgentId, topicId: null });++ // Setup initial state with some messages in the new key+ await act(async () => {+ useChatStore.setState({+ activeAgentId,+ activeTopicId: 'existing-topic',+ dbMessagesMap: {+ [newKey]: [{ id: 'msg-1' }, { id: 'msg-2' }] as any,+ },+ messagesMap: {+ [newKey]: [{ id: 'msg-1' }, { id: 'msg-2' }] as any,+ },+ });+ });++ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');++ // Switch to new state (id = undefined)+ await act(async () => {+ await result.current.switchTopic(undefined, { skipRefreshMessage: true });+ });++ // Verify replaceMessages was called to clear the new key+ expect(replaceMessagesSpy).toHaveBeenCalledWith([], {+ context: {+ agentId: activeAgentId,+ groupId: undefined,+ scope: 'main',+ topicId: null,+ },+ action: expect.any(String),+ });++ // Verify activeTopicId is now null+ expect(useChatStore.getState().activeTopicId).toBeNull();+ });++ it('should clear new key data when switching to new state (group scope)', async () => {+ const { result } = renderHook(() => useChatStore());+ const activeAgentId = 'test-agent-id';+ const activeGroupId = 'test-group-id';++ // Setup initial state with group context+ await act(async () => {+ useChatStore.setState({+ activeAgentId,+ activeGroupId,+ activeTopicId: 'existing-topic',+ });+ });++ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');++ // Switch to new state+ await act(async () => {+ await result.current.switchTopic(undefined, { skipRefreshMessage: true });+ });++ // Verify replaceMessages was called with group scope+ expect(replaceMessagesSpy).toHaveBeenCalledWith([], {+ context: {+ agentId: activeAgentId,+ groupId: activeGroupId,+ scope: 'group',+ topicId: null,+ },+ action: expect.any(String),+ });+ });++ it('should use explicit scope from options when provided', async () => {+ const { result } = renderHook(() => useChatStore());+ const activeAgentId = 'test-agent-id';++ await act(async () => {+ useChatStore.setState({+ activeAgentId,+ activeTopicId: 'existing-topic',+ });+ });++ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');++ // Switch to new state with explicit scope+ await act(async () => {+ await result.current.switchTopic(undefined, { skipRefreshMessage: true, scope: 'group' });+ });++ // Verify replaceMessages was called with explicit scope+ expect(replaceMessagesSpy).toHaveBeenCalledWith([], {+ context: expect.objectContaining({+ scope: 'group',+ }),+ action: expect.any(String),+ });+ });++ it('should not clear new key data when switching to an existing topic', async () => {+ const { result } = renderHook(() => useChatStore());+ const activeAgentId = 'test-agent-id';++ await act(async () => {+ useChatStore.setState({+ activeAgentId,+ activeTopicId: undefined,+ });+ });++ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');++ // Switch to an existing topic (not new state)+ await act(async () => {+ await result.current.switchTopic('existing-topic-id', { skipRefreshMessage: true });+ });++ // replaceMessages should not be called when switching to existing topic+ expect(replaceMessagesSpy).not.toHaveBeenCalled();+ });});describe('removeSessionTopics', () => {it('should remove all topics from the current session and refresh the topic list', async () => {diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex d783207b355..cdbeb2f30b1 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -2,7 +2,7 @@// Note: To make the code more logic and readable, we just disable the auto sort key eslint rule// DON'T REMOVE THE FIRST LINEimport { chainSummaryTitle } from '@lobechat/prompts';-import { TraceNameMap, type UIChatMessage } from '@lobechat/types';+import { type MessageMapScope, TraceNameMap, type UIChatMessage } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { t } from 'i18next';import useSWR, { type SWRResponse } from 'swr';@@ -34,6 +34,22 @@ const n = setNamespace('t');const SWR_USE_FETCH_TOPIC = 'SWR_USE_FETCH_TOPIC';const SWR_USE_SEARCH_TOPIC = 'SWR_USE_SEARCH_TOPIC';+/**+ * Options for switchTopic action+ */+export interface SwitchTopicOptions {+ /**+ * Explicit scope for clearing new key data+ * If not provided, will be inferred from store state (activeGroupId)+ */+ scope?: MessageMapScope;+ /**+ * Skip refreshing messages after switching topic+ * @default false+ */+ skipRefreshMessage?: boolean;+}+export interface ChatTopicAction {closeAllTopicsDrawer: () => void;favoriteTopic: (id: string, favState: boolean) => Promise<void>;@@ -53,7 +69,12 @@ export interface ChatTopicAction {autoRenameTopicTitle: (id: string) => Promise<void>;duplicateTopic: (id: string) => Promise<void>;summaryTopicTitle: (topicId: string, messages: UIChatMessage[]) => Promise<void>;- switchTopic: (id?: string, skipRefreshMessage?: boolean) => Promise<void>;+ /**+ * Switch to a topic or create new topic state+ * @param id - Topic ID to switch to, or undefined/null to switch to "new" state+ * @param options - Options object or boolean for backward compatibility (skipRefreshMessage)+ */+ switchTopic: (id?: string, options?: boolean | SwitchTopicOptions) => Promise<void>;updateTopicTitle: (id: string, title: string) => Promise<void>;useFetchTopics: (enable: boolean,@@ -423,14 +444,37 @@ export const chatTopic: StateCreator<},),- switchTopic: async (id, skipRefreshMessage) => {+ switchTopic: async (id, options) => {+ // Backward compatibility: support both boolean and options object+ const opts: SwitchTopicOptions =+ typeof options === 'boolean' ? { skipRefreshMessage: options } : (options ?? {});++ const { activeAgentId, activeGroupId } = get();++ // When switching to "new" state (id is undefined/null), clear the new key data+ // This prevents stale data from previous conversations showing up+ if (!id && activeAgentId) {+ // Determine scope: use explicit scope from options, or infer from activeGroupId+ const scope = opts.scope ?? (activeGroupId ? 'group' : 'main');++ get().replaceMessages([], {+ context: {+ agentId: activeAgentId,+ groupId: activeGroupId,+ scope,+ topicId: null,+ },+ action: n('clearNewKeyData'),+ });+ }+set({ activeTopicId: !id ? (null as any) : id, activeThreadId: undefined },false,n('toggleTopic'),);- if (skipRefreshMessage) return;+ if (opts.skipRefreshMessage) return;await get().refreshMessages();},// delete