π€― 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
π hotfix: clear stale topic when switching agents from a topic route (#14231)
Inneideeb97ab5b03
diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsxnew file mode 100644index 00000000000..cfb7ff3f788--- /dev/null+++ b/src/features/Conversation/ConversationProvider.test.tsx@@ -0,0 +1,84 @@+/**+ * @vitest-environment happy-dom+ */+import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import { render } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { ConversationProvider } from './ConversationProvider';+import { dataSelectors, useConversationStore } from './store';++const oldContext = {+ agentId: 'agt_old',+ threadId: null,+ topicId: 'tpc_old',+} satisfies ConversationContext;++const nextContext = {+ agentId: 'agt_next',+ threadId: null,+ topicId: null,+} satisfies ConversationContext;++const oldMessages = [+ {+ content: 'old message',+ createdAt: 1,+ id: 'msg_old',+ role: 'user',+ updatedAt: 1,+ },+] as UIChatMessage[];++interface Snapshot {+ actualContextKey: string;+ displayMessageIds: string[];+ expectedContextKey: string;+}++const Probe = ({+ expectedContext,+ snapshots,+}: {+ expectedContext: ConversationContext;+ snapshots: Snapshot[];+}) => {+ const context = useConversationStore((s) => s.context);+ const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);++ snapshots.push({+ actualContextKey: messageMapKey(context),+ displayMessageIds,+ expectedContextKey: messageMapKey(expectedContext),+ });++ return null;+};++describe('ConversationProvider', () => {+ it('does not expose the previous local conversation store after context changes', () => {+ const snapshots: Snapshot[] = [];++ const { rerender } = render(+ <ConversationProvider hasInitMessages context={oldContext} messages={oldMessages}>+ <Probe expectedContext={oldContext} snapshots={snapshots} />+ </ConversationProvider>,+ );++ rerender(+ <ConversationProvider context={nextContext} hasInitMessages={false}>+ <Probe expectedContext={nextContext} snapshots={snapshots} />+ </ConversationProvider>,+ );++ const mismatchedNextContextSnapshots = snapshots.filter(+ (snapshot) =>+ snapshot.expectedContextKey === messageMapKey(nextContext) &&+ snapshot.actualContextKey !== snapshot.expectedContextKey,+ );++ expect(mismatchedNextContextSnapshots).toEqual([]);+ });+});diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsxindex 3236ab26bee..808a0a2e18e 100644--- a/src/features/Conversation/ConversationProvider.tsx+++ b/src/features/Conversation/ConversationProvider.tsx@@ -92,7 +92,7 @@ export const ConversationProvider = memo<ConversationProviderProps>();return (- <Provider createStore={() => createStore({ context, hooks, skipFetch })}>+ <Provider createStore={() => createStore({ context, hooks, skipFetch })} key={contextKey}><StoreUpdateractionsBar={actionsBar}context={context}diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsxindex c11aaa7794d..87872ac719b 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx@@ -107,7 +107,9 @@ vi.mock('./useDropdownMenu', () => ({useTopicItemDropdownMenu: () => ({ dropdownMenu: [] }),}));vi.mock('../../TopicListContent/ThreadList', () => ({- default: () => <div data-testid="topic-thread-list" />,+ default: ({ topicId }: { topicId: string }) => (+ <div data-testid="topic-thread-list" data-topic-id={topicId} />+ ),}));describe('TopicItem active state', () => {@@ -117,12 +119,13 @@ describe('TopicItem active state', () => {isInTopicContextRoute: true,navigateToTopic: vi.fn(),routeTopicId: 'tpc_test',+ urlTopicId: 'tpc_test',});render(<TopicItem active={false} id="tpc_test" title="Topic" />);expect(screen.getByTestId('nav-item')).toHaveAttribute('data-active', 'true');- expect(screen.getByTestId('topic-thread-list')).toBeInTheDocument();+ expect(screen.getByTestId('topic-thread-list')).toHaveAttribute('data-topic-id', 'tpc_test');});it('does not highlight a stale topic while visiting non-topic agent sub-routes', () => {diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex 1dc090a4fd5..0d63a88a503 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -112,12 +112,15 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metaisInAgentSubRoute,isInTopicContextRoute,routeTopicId,+ urlTopicId,} = useTopicNavigation();const isRouteTopicActive = Boolean(id && routeTopicId === id && isInTopicContextRoute);const isTopicActive = Boolean((active || isRouteTopicActive) && !threadId && (!isInAgentSubRoute || isRouteTopicActive),);+ const shouldShowThreadList = Boolean(id && id === urlTopicId);+const toggleEditing = useCallback((visible?: boolean) => {useChatStore.setState({ topicRenamingId: visible && id ? id : '' });@@ -252,7 +255,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metaonDoubleClick={() => void handleDoubleClick()}/><Editing id={id} title={title} toggleEditing={toggleEditing} />- {isTopicActive && (+ {shouldShowThreadList && (<Suspensefallback={<Flexbox gap={8} paddingBlock={8} paddingInline={24} width={'100%'}>@@ -261,7 +264,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta</Flexbox>}>- <ThreadList />+ <ThreadList topicId={id} /></Suspense>)}</Flexbox>diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsxindex e63f2a99e6e..ec61d694def 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx@@ -7,11 +7,10 @@ import { threadSelectors } from '@/store/chat/selectors';import ThreadItem from './ThreadItem';-const ThreadList = memo(() => {- const [id] = useChatStore((s) => [s.activeTopicId]);- const threads = useChatStore(threadSelectors.getThreadsByTopic(id));+const ThreadList = memo(({ topicId }: { topicId: string }) => {+ const threads = useChatStore(threadSelectors.getThreadsByTopic(topicId));- useFetchThreads(id);+ useFetchThreads(topicId);if (!threads || threads.length === 0) return;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.tsindex 15c153b66d6..47b21bed84f 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts@@ -24,11 +24,14 @@ export const useTopicNavigation = () => {const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);const switchTopic = useChatStore((s) => s.switchTopic);const routeAgentId = params.aid ?? activeAgentId;+ // URL is the source of truth. Sidebar mounts at `/agent/:aid` so `params.topicId`+ // is undefined here β fall back to parsing pathname directly so consumers can compare+ // their item id against the URL's topic id without waiting for store hydration.+ const urlTopicId = params.topicId;const routeTopicId = params.topicId ?? activeTopicId ?? undefined;const topicBasePath =routeAgentId && routeTopicId ? SESSION_CHAT_TOPIC_URL(routeAgentId, routeTopicId) : undefined;- // URL-derived topic path (no store fallback) β used for sub-route detection so a cached- // activeTopicId cannot mask a non-topic page like /agent/:aid/profile.+const urlTopicBasePath =routeAgentId && params.topicId? SESSION_CHAT_TOPIC_URL(routeAgentId, params.topicId)@@ -87,5 +90,6 @@ export const useTopicNavigation = () => {isInTopicContextRoute: isInTopicContextRoute(),navigateToTopic,routeTopicId,+ urlTopicId,};};diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsxindex d3393fbfb1e..0148bf39ca8 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx@@ -15,6 +15,20 @@ const useLocationMock = vi.hoisted(() => vi.fn());const useParamsMock = vi.hoisted(() => vi.fn());const useSearchParamsMock = vi.hoisted(() => vi.fn());+vi.hoisted(() => {+ const storage = {+ clear: vi.fn(),+ getItem: vi.fn(() => null),+ removeItem: vi.fn(),+ setItem: vi.fn(),+ };++ Object.defineProperty(globalThis, 'localStorage', {+ configurable: true,+ value: storage,+ });+});+vi.mock('react-router-dom', async () => {// eslint-disable-next-line @typescript-eslint/consistent-type-importsconst actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');@@ -47,7 +61,7 @@ describe('ChatHydration', () => {);});- it('hydrates legacy topic query params into the store and rewrites them to the topic path', async () => {+ it('ignores topic query params and only hydrates thread from search params', async () => {useParamsMock.mockReturnValue({ aid: 'agt_test' });useLocationMock.mockReturnValue({hash: '#msg_1',@@ -62,16 +76,13 @@ describe('ChatHydration', () => {render(<ChatHydration />);await waitFor(() => {- expect(useChatStore.getState().activeTopicId).toBe('tpc_123');+ expect(useChatStore.getState().activeTopicId).toBeNull();expect(useChatStore.getState().activeThreadId).toBe('thd_456');- expect(navigateMock).toHaveBeenCalledWith(- '/agent/agt_test/tpc_123?thread=thd_456&mode=single#msg_1',- { replace: true },- );+ expect(navigateMock).not.toHaveBeenCalled();});});- it('removes duplicate legacy topic query params when the path already carries topicId', async () => {+ it('hydrates topic from the path even when a stale topic query param exists', async () => {useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_123' });useLocationMock.mockReturnValue({hash: '',@@ -88,9 +99,33 @@ describe('ChatHydration', () => {await waitFor(() => {expect(useChatStore.getState().activeTopicId).toBe('tpc_123');expect(useChatStore.getState().activeThreadId).toBe('thd_456');- expect(navigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_123?thread=thd_456', {- replace: true,- });+ expect(navigateMock).not.toHaveBeenCalled();+ });+ });++ it('clears stale topic and thread state when the route has no topic or thread', async () => {+ useChatStore.setState(+ {+ activeThreadId: 'thd_previous',+ activeTopicId: 'tpc_previous',+ },+ false,+ );++ useParamsMock.mockReturnValue({ aid: 'agt_next' });+ useLocationMock.mockReturnValue({+ hash: '',+ pathname: '/agent/agt_next',+ search: '',+ });+ useSearchParamsMock.mockReturnValue([new URLSearchParams(''), setSearchParamsMock]);++ render(<ChatHydration />);++ await waitFor(() => {+ expect(useChatStore.getState().activeTopicId).toBeNull();+ expect(useChatStore.getState().activeThreadId).toBeNull();+ expect(navigateMock).not.toHaveBeenCalled();});});diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsxindex 5df4deb3fc2..33be2e6bb9f 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx@@ -2,7 +2,6 @@import { memo, useLayoutEffect, useRef } from 'react';import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';-import { createStoreUpdater } from 'zustand-utils';import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';import { useQueryState } from '@/hooks/useQueryParam';@@ -16,17 +15,27 @@ const getSearchSuffix = (searchParams: URLSearchParams) => {// sync outside state to useChatStoreconst ChatHydration = memo(() => {- const useStoreUpdater = createStoreUpdater(useChatStore);const location = useLocation();const navigate = useNavigate();const params = useParams<{ aid?: string; topicId?: string }>();const [searchParams] = useSearchParams();const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });- const routeTopicId = params.topicId ?? searchParams.get('topic');+ const routeTopicId = params.topicId;- useStoreUpdater('activeTopicId', routeTopicId ?? undefined);- useStoreUpdater('activeThreadId', thread!);+ useLayoutEffect(() => {+ const target = routeTopicId ?? null;+ if (useChatStore.getState().activeTopicId !== target) {+ useChatStore.setState({ activeTopicId: target! }, false, 'ChatHydration/syncTopicFromUrl');+ }+ }, [routeTopicId]);++ useLayoutEffect(() => {+ const target = thread ?? null;+ if (useChatStore.getState().activeThreadId !== target) {+ useChatStore.setState({ activeThreadId: target! }, false, 'ChatHydration/syncThreadFromUrl');+ }+ }, [thread]);const locationRef = useRef(location);const paramsRef = useRef(params);@@ -36,31 +45,6 @@ const ChatHydration = memo(() => {paramsRef.current = params;searchParamsRef.current = searchParams;- useLayoutEffect(() => {- const legacyTopicId = searchParams.get('topic');-- if (!params.aid || !legacyTopicId) return;-- const normalizedTopicId = params.topicId ?? legacyTopicId;- const nextSearchParams = new URLSearchParams(searchParams);- nextSearchParams.delete('topic');-- const nextUrl = `${SESSION_CHAT_TOPIC_URL(params.aid, normalizedTopicId)}${getSearchSuffix(nextSearchParams)}${location.hash}`;- const currentUrl = `${location.pathname}${location.search}${location.hash}`;-- if (currentUrl !== nextUrl) {- navigate(nextUrl, { replace: true });- }- }, [- location.hash,- location.pathname,- location.search,- navigate,- params.aid,- params.topicId,- searchParams,- ]);-useLayoutEffect(() => {const unsubscribeTopic = useChatStore.subscribe((s) => s.activeTopicId,@@ -84,7 +68,7 @@ const ChatHydration = memo(() => {const unsubscribeThread = useChatStore.subscribe((s) => s.activeThreadId,(state) => {- setThread(!state ? null : state);+ setThread(state || null);},);diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsxindex 7f60c086679..ac8b452b824 100644--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx@@ -41,6 +41,7 @@ const Conversation = memo(() => {);const replaceMessages = useChatStore((s) => s.replaceMessages);const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);+log('contextKey %s: %o', chatKey, messages);// Get operation state from ChatStore for reactive updatesdiff --git a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsxindex 3a5bcd719d7..00245275af8 100644--- a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx@@ -12,7 +12,13 @@ import FolderTag from './FolderTag';import MemberCountTag from './MemberCountTag';const TitleTags = memo(() => {- const { t } = useTranslation('topic');+ const { t } = useTranslation(['topic', 'chat']);+ const activeThreadId = useChatStore((s) => s.activeThreadId);+ const threadTitle = useChatStore((s) =>+ s.activeThreadId && s.activeTopicId+ ? s.threadMaps[s.activeTopicId]?.find((thread) => thread.id === s.activeThreadId)?.title+ : undefined,+ );const topicTitle = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.title);const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);@@ -24,6 +30,10 @@ const TitleTags = memo(() => {);}+ const displayTitle = activeThreadId+ ? threadTitle || t('thread.title', { ns: 'chat' })+ : topicTitle || t('newTopic');+return (<Flexbox allowShrink horizontal align={'center'} gap={8}><span@@ -38,7 +48,7 @@ const TitleTags = memo(() => {whiteSpace: 'nowrap',}}>- {topicTitle || t('newTopic')}+ {displayTitle}</span><FolderTag /></Flexbox>diff --git a/src/routes/(main)/agent/features/Conversation/useAgentContext.ts b/src/routes/(main)/agent/features/Conversation/useAgentContext.tsindex 11137af8275..ee36c5eaebb 100644--- a/src/routes/(main)/agent/features/Conversation/useAgentContext.ts+++ b/src/routes/(main)/agent/features/Conversation/useAgentContext.ts@@ -17,6 +17,7 @@ export function useAgentContext(): ConversationContext {s.activeTopicId ?? null,s.activeThreadId ?? null,]);+const activeTopicDocumentId = useDocumentStore((s) => {if (!topicId || threadId) return undefined;diff --git a/src/routes/(main)/agent/index.desktop.tsx b/src/routes/(main)/agent/index.desktop.tsxindex c13bc24dc69..172133f787b 100644--- a/src/routes/(main)/agent/index.desktop.tsx+++ b/src/routes/(main)/agent/index.desktop.tsx@@ -2,6 +2,7 @@import { Flexbox } from '@lobehub/ui';import { memo } from 'react';+import { useParams } from 'react-router-dom';import TopicInPopupGuard from '@/features/TopicPopupGuard';import { useTopicInPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';@@ -10,22 +11,21 @@ import { useChatStore } from '@/store/chat';import Conversation from './features/Conversation';import ChatHydration from './features/Conversation/ChatHydration';import PageTitle from './features/PageTitle';-import Portal from './features/Portal';import TelemetryNotification from './features/TelemetryNotification';const ChatPage = memo(() => {+ const { topicId: urlTopicId } = useParams<{ topicId?: string }>();const activeAgentId = useChatStore((s) => s.activeAgentId);- const activeTopicId = useChatStore((s) => s.activeTopicId);const popup = useTopicInPopup({agentId: activeAgentId,- topicId: activeTopicId ?? '',+ topicId: urlTopicId ?? '',});// When the same topic is already hosted in a popup window, avoid// rendering a second (out-of-sync) instance here β guide the user back// to the popup instead.const pageContent =- activeTopicId && popup ? (+ urlTopicId && popup ? (<><PageTitle /><TopicInPopupGuard popup={popup} />@@ -40,7 +40,6 @@ const ChatPage = memo(() => {width={'100%'}><Conversation />- <Portal /></Flexbox><TelemetryNotification mobile={false} /></>