π€― 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(topic): keep an archived topic's title via a by-id detail cache (#17917)
Arvin Xu93dfbc62fa6e
diff --git a/src/features/RouteMeta/AgentDynamicMeta.tsx b/src/features/RouteMeta/AgentDynamicMeta.tsxindex 153fbcae7cd..2e728e3412d 100644--- a/src/features/RouteMeta/AgentDynamicMeta.tsx+++ b/src/features/RouteMeta/AgentDynamicMeta.tsx@@ -20,9 +20,11 @@ const useTopicTitle = (useChatStore((state) => {if (!agentId || !topicId || routeWorkspaceId === undefined) return undefined;- const topic = state.topicDataMap[topicMapKey({ agentId })]?.items?.find(- (item) => item.id === topicId,- );+ // Archived (completed) topics are excluded from the list fetch β fall back+ // to the by-id detail cache filled by `useFetchTopicDetail`.+ const topic =+ state.topicDataMap[topicMapKey({ agentId })]?.items?.find((item) => item.id === topicId) ??+ state.topicDetailMap[topicId];return topic?.title || undefined;});diff --git a/src/hooks/useFetchActiveTopicDetail.ts b/src/hooks/useFetchActiveTopicDetail.tsnew file mode 100644index 00000000000..d87ed769317--- /dev/null+++ b/src/hooks/useFetchActiveTopicDetail.ts@@ -0,0 +1,26 @@+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';++/**+ * Fetch the active topic's detail when it is missing from the loaded list+ * bucket β e.g. an archived (`completed`) topic that the sidebar fetch+ * excludes via `excludeStatuses`, or a topic opened by URL whose page hasn't+ * been fetched. The result lands in `topicDetailMap`, which+ * `currentActiveTopic` reads as a fallback, so the header keeps the real+ * title instead of degrading to the "new topic" placeholder.+ *+ * Waits for the list bucket to load before deciding the topic is missing, so+ * the common case (topic present in the first page) never fires an extra+ * request.+ */+export const useFetchActiveTopicDetail = () => {+ const [activeTopicId, isMissingFromList, useFetchTopicDetail] = useChatStore((s) => [+ s.activeTopicId,+ !!s.activeTopicId &&+ !!topicSelectors.currentTopicData(s) &&+ !topicSelectors.currentTopics(s)?.some((topic) => topic.id === s.activeTopicId),+ s.useFetchTopicDetail,+ ]);++ useFetchTopicDetail(isMissingFromList ? activeTopicId : undefined);+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 5f0063a7040..9f562e8d8b7 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -124,6 +124,7 @@ export const topicKeys = {containerKey,opts,]),+ detail: def('topic:detail', (topicId: string) => ['topic:detail', topicId]),list: def('topic:list', (containerKey: string, opts: Record<string, unknown>) => ['topic:list',containerKey,diff --git a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsxindex ee2530d1ef7..8c007f28555 100644--- a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx@@ -4,6 +4,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { useAgentContext } from '@/features/Conversation/useAgentContext';+import { useFetchActiveTopicDetail } from '@/hooks/useFetchActiveTopicDetail';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { useSessionStore } from '@/store/session';@@ -25,6 +26,10 @@ const TitleTags = memo(() => {);const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);+ // Archived topics fall out of the sidebar list fetch β pull their detail by+ // id so the title doesn't degrade to the "new topic" placeholder.+ useFetchActiveTopicDetail();+if (isGroupSession) {return (<Flexbox allowShrink horizontal align={'center'} gap={12} style={{ minWidth: 0 }}>diff --git a/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsx b/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsxindex 26714578442..5f86784f3b2 100644--- a/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsx+++ b/src/routes/(mobile)/chat/features/ChatHeader/ChatHeaderTitle.tsx@@ -5,6 +5,7 @@ import { ChevronDown } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { useFetchActiveTopicDetail } from '@/hooks/useFetchActiveTopicDetail';import { useAgentStore } from '@/store/agent';import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -21,6 +22,10 @@ const ChatHeaderTitle = memo(() => {const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);const title = useAgentStore(agentSelectors.currentAgentDisplayName);+ // Archived topics fall out of the sidebar list fetch β pull their detail by+ // id so the title doesn't degrade to the "new topic" placeholder.+ useFetchActiveTopicDetail();+const displayTitle = isInbox ? 'Lobe AI' : title;return (diff --git a/src/routes/(popup)/_layout/index.tsx b/src/routes/(popup)/_layout/index.tsxindex 4bcfd0029f2..dab312b8ed1 100644--- a/src/routes/(popup)/_layout/index.tsx+++ b/src/routes/(popup)/_layout/index.tsx@@ -8,6 +8,7 @@ import { HotkeysProvider } from 'react-hotkeys-hook';import { Outlet } from 'react-router';import ProtocolUrlHandler from '@/features/ProtocolUrlHandler';+import { useFetchActiveTopicDetail } from '@/hooks/useFetchActiveTopicDetail';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';@@ -22,6 +23,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({const PopupLayout: FC = () => {const topicTitle = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.title);+ // Archived topics fall out of the sidebar list fetch β pull their detail by+ // id so the title doesn't degrade to the "new topic" placeholder.+ useFetchActiveTopicDetail();+return (<HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}><Flexboxdiff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex cf39603ad39..5876aa77d2b 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -82,6 +82,7 @@ beforeEach(() => {agentTopicsViewMap: {},searchTopics: [],topicDataMap: {},+ topicDetailMap: {},// ... initial state},false,@@ -624,6 +625,29 @@ describe('topic action', () => {expect(updateSpy).toHaveBeenCalledWith(topicId, { status: 'running' });});});+ describe('useFetchTopicDetail', () => {+ // Regression: an archived (completed) topic is excluded from the sidebar+ // list fetch, so the active topic vanished from topicDataMap and the+ // header degraded to the "new topic" placeholder. The by-id detail fetch+ // caches the row in topicDetailMap, which currentActiveTopic falls back to.+ it('caches the fetched topic in topicDetailMap', async () => {+ const archived = { id: 'archived-topic', status: 'completed', title: 'Archived Topic' };+ (topicService.getTopicDetail as Mock).mockResolvedValue(archived);++ const { result } = renderHook(() => useChatStore().useFetchTopicDetail('archived-topic'));++ await waitFor(() => {+ expect(result.current.data).toEqual(archived);+ });+ expect(useChatStore.getState().topicDetailMap['archived-topic']).toEqual(archived);+ });++ it('does not fetch when no topic id is given', () => {+ renderHook(() => useChatStore().useFetchTopicDetail(undefined));+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();+ });+ });+describe('useFetchTopics', () => {it('should fetch topics for a given session id', async () => {const sessionId = 'test-session-id';@@ -1065,6 +1089,30 @@ describe('topic action', () => {// Verify that the refreshTopic was called to update the stateexpect(refreshTopicSpy).toHaveBeenCalled();});++ it('should update the detail cache when the topic is absent from list buckets', async () => {+ const topicId = 'archived-topic';+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ topicDataMap: {},+ topicDetailMap: {+ [topicId]: { id: topicId, status: 'completed', title: 'Old title' } as ChatTopic,+ },+ });+ });+ vi.spyOn(result.current, 'refreshTopic').mockResolvedValue(undefined);++ await act(async () => {+ await result.current.updateTopicTitle(topicId, 'New title');+ });++ expect(useChatStore.getState().topicDetailMap[topicId]).toMatchObject({+ status: 'completed',+ title: 'New title',+ });+ });});describe('switchTopic', () => {it('should update activeTopicId and softly revalidate messages', async () => {@@ -1407,6 +1455,28 @@ describe('topic action', () => {expect(refreshTopicSpy).toHaveBeenCalled();expect(switchTopicSpy).toHaveBeenCalled();});++ it('should evict a detail-only topic after deletion', async () => {+ const topicId = 'archived-topic';+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ activeAgentId: 'test-session-id',+ topicDataMap: {},+ topicDetailMap: {+ [topicId]: { id: topicId, status: 'completed', title: 'Archived' } as ChatTopic,+ },+ });+ });+ vi.spyOn(result.current, 'refreshTopic').mockResolvedValue(undefined);++ await act(async () => {+ await result.current.removeTopic(topicId);+ });++ expect(useChatStore.getState().topicDetailMap[topicId]).toBeUndefined();+ });it('should forward removeFiles so the topic attachments are deleted', async () => {const topicId = 'topic-1';const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex b327e0497e8..d31cc5ea431 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -953,6 +953,34 @@ export class ChatTopicActionImpl {);};+ /**+ * By-id topic detail fetch, used as a fallback when a topic the UI is+ * anchored on is missing from the loaded list bucket β e.g. an archived+ * (`completed`) topic that the sidebar fetch excludes via `excludeStatuses`,+ * or a topic deep-linked from the Topics management page. The result lands+ * in `topicDetailMap`, which `currentActiveTopic` / `getTopicById` read as+ * a fallback. Pass `undefined` to disable the fetch.+ */+ useFetchTopicDetail = (topicId?: string | null): SWRResponse<ChatTopic | null> =>+ useClientDataSWRWithSync<ChatTopic | null>(+ topicId ? topicKeys.detail(topicId) : null,+ () => topicService.getTopicDetail(topicId!),+ {+ onData: (topic) => {+ if (!topic) return;++ const currentMap = this.#get().topicDetailMap;+ if (isEqual(currentMap[topic.id], topic)) return;++ this.#set(+ { topicDetailMap: { ...currentMap, [topic.id]: topic } },+ false,+ n('useFetchTopicDetail(onData)', { topicId: topic.id }),+ );+ },+ },+ );+/*** Topic fetch dedicated to the Agent Topics management page.* Lives in its own SWR key + state bucket so the heavier `withDetails`@@ -1305,6 +1333,17 @@ export class ChatTopicActionImpl {if (!activeAgentId) return;await topicService.removeTopicsByAgentId(activeAgentId, scope);+ this.#set(+ (state) => ({+ topicDetailMap: Object.fromEntries(+ Object.entries(state.topicDetailMap).filter(+ ([, topic]) => topic.sessionId !== activeAgentId,+ ),+ ),+ }),+ false,+ n('removeSessionTopics/detail'),+ );await refreshTopic();// drop every deleted topic's message cache (all belong to this agent)void evictMessageCache((ctx) => ctx.agentId === activeAgentId);@@ -1320,6 +1359,9 @@ export class ChatTopicActionImpl {const { switchTopic, refreshTopic } = this.#get();await topicService.removeTopicsByGroupId(groupId, scope);+ // Topic detail rows don't carry their group id, so the safe invalidation+ // boundary for a group-wide delete is the whole by-id detail cache.+ this.#set({ topicDetailMap: {} }, false, n('removeGroupTopics/detail'));await refreshTopic();// drop every deleted topic's message cache (all belong to this group)void evictMessageCache((ctx) => ctx.groupId === groupId);@@ -1332,6 +1374,7 @@ export class ChatTopicActionImpl {const { refreshTopic } = this.#get();await topicService.removeAllTopic();+ this.#set({ topicDetailMap: {} }, false, n('removeAllTopics/detail'));await refreshTopic();// every topic is gone β wipe all cached message listsvoid evictMessageCache(() => true);@@ -1362,6 +1405,9 @@ export class ChatTopicActionImpl {.map((topic) => topic.id);await topicService.batchRemoveTopics(topicIds);+ topicIds.forEach((id) =>+ this.#get().internal_dispatchTopic({ type: 'deleteTopic', id }, 'removeUnstarredTopic'),+ );await refreshTopic();// drop the deleted topics' message cachesconst removed = new Set(topicIds);@@ -1606,9 +1652,31 @@ export class ChatTopicActionImpl {const nextViewItems = viewData ? topicReducer(viewData.items, payload) : undefined;const viewChanged = viewData ? !isEqual(nextViewItems, viewData.items) : false;- // no need to update if both maps are unchanged+ const detailMap = this.#get().topicDetailMap ?? {};+ const detailId = payload.type === 'addTopic' ? undefined : payload.id;+ const detailTopic = detailId ? detailMap[detailId] : undefined;+ let nextDetailMap = detailMap;++ if (payload.type === 'updateTopic' && detailTopic) {+ nextDetailMap = {+ ...detailMap,+ [payload.id]: { ...detailTopic, ...payload.value },+ };+ } else if (payload.type === 'deleteTopic' && detailTopic) {+ const { [payload.id]: _deleted, ...remainingDetailMap } = detailMap;+ nextDetailMap = remainingDetailMap;+ } else if (payload.type === 'replaceTopicId' && detailTopic) {+ const { [payload.id]: _replaced, ...remainingDetailMap } = detailMap;+ nextDetailMap = {+ ...remainingDetailMap,+ [payload.nextId]: { ...detailTopic, ...payload.value, id: payload.nextId },+ };+ }++ // no need to update if all maps are unchangedconst mainChanged = !isEqual(nextItems, currentData?.items);- if (!mainChanged && !viewChanged) return;+ const detailChanged = nextDetailMap !== detailMap;+ if (!mainChanged && !viewChanged && !detailChanged) return;const currentTotal = currentData?.total ?? currentData?.items?.length ?? 0;const total =@@ -1620,6 +1688,8 @@ export class ChatTopicActionImpl {const nextState: Record<string, unknown> = {};+ if (detailChanged) nextState.topicDetailMap = nextDetailMap;+if (mainChanged) {nextState.topicDataMap = {...this.#get().topicDataMap,diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.tsindex a81e24c5a86..97c65c6c681 100644--- a/src/store/chat/slices/topic/initialState.ts+++ b/src/store/chat/slices/topic/initialState.ts@@ -69,6 +69,20 @@ export interface ChatTopicState {* Contains items, total count, pagination state, and loading states*/topicDataMap: Record<string, TopicData>;+ /**+ * Per-id topic detail cache, filled by `useFetchTopicDetail` when the active+ * topic is missing from the loaded list bucket β e.g. an archived+ * (`completed`) topic that the sidebar fetch excludes via `excludeStatuses`.+ * `currentActiveTopic` / `getTopicById` read it as a fallback so the header+ * keeps the real title instead of degrading to the "new topic" placeholder.+ */+ topicDetailMap: Record<string, ChatTopic>;+ /**+ * Internal ref-count for topic loading owners. A topic can be loading because+ * the agent is running and because title-summary is streaming at the same time.+ */+ topicLoadingIdCounts: Record<string, number>;+ topicLoadingIds: string[];topicRenamingId?: string;topicSearchKeywords: string;}@@ -82,5 +96,8 @@ export const initialTopicState: ChatTopicState = {isSearchingTopic: false,searchTopics: [],topicDataMap: {},+ topicDetailMap: {},+ topicLoadingIdCounts: {},+ topicLoadingIds: [],topicSearchKeywords: '',};diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.tsindex 610874cb85d..b424929a5e1 100644--- a/src/store/chat/slices/topic/selectors.test.ts+++ b/src/store/chat/slices/topic/selectors.test.ts@@ -165,6 +165,17 @@ describe('topicSelectors', () => {expect(topic).toBeUndefined();});+ it('should tolerate a partial store state without the detail cache', () => {+ const state = {+ activeAgentId: 'test',+ activeTopicId: 'missing-topic',+ topicDataMap: {},+ } as ChatStore;++ expect(topicSelectors.currentActiveTopic(state)).toBeUndefined();+ expect(topicSelectors.getTopicById('missing-topic')(state)).toBeUndefined();+ });+it('should return the current active topic', () => {const state = merge(initialStore, {topicDataMap,@@ -174,6 +185,42 @@ describe('topicSelectors', () => {const topic = topicSelectors.currentActiveTopic(state);expect(topic).toEqual(topicItems[0]);});++ it('should fall back to the detail cache when the topic is missing from the list bucket', () => {+ // An archived (completed) topic is excluded from the sidebar list fetch,+ // so it never lands in topicDataMap β only in the by-id detail cache.+ const archived = { id: 'archived1', title: 'Archived topic', status: 'completed' };+ const state = merge(initialStore, {+ topicDataMap,+ topicDetailMap: { archived1: archived },+ activeAgentId: 'test',+ activeTopicId: 'archived1',+ });+ expect(topicSelectors.currentActiveTopic(state)).toEqual(archived);+ });++ it('should prefer the list bucket row over the detail cache', () => {+ const state = merge(initialStore, {+ topicDataMap,+ topicDetailMap: { topic1: { id: 'topic1', title: 'stale detail' } },+ activeAgentId: 'test',+ activeTopicId: 'topic1',+ });+ expect(topicSelectors.currentActiveTopic(state)).toEqual(topicItems[0]);+ });+ });++ describe('getTopicById', () => {+ it('should fall back to the detail cache when the topic is missing from the list bucket', () => {+ const archived = { id: 'archived1', title: 'Archived topic', status: 'completed' };+ const state = merge(initialStore, {+ topicDataMap,+ topicDetailMap: { archived1: archived },+ activeAgentId: 'test',+ });+ expect(topicSelectors.getTopicById('archived1')(state)).toEqual(archived);+ expect(topicSelectors.getTopicById('topic1')(state)).toEqual(topicItems[0]);+ });});describe('currentUnFavTopics', () => {diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex e8d30d764fb..f68ffcc39d0 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -41,7 +41,12 @@ const currentTopicsWithoutCron = (s: ChatStoreState): ChatTopic[] | undefined =>};const currentActiveTopic = (s: ChatStoreState): ChatTopic | undefined => {- return currentTopics(s)?.find((topic) => topic.id === s.activeTopicId);+ const inList = currentTopics(s)?.find((topic) => topic.id === s.activeTopicId);+ if (inList) return inList;+ // The active topic can be absent from the list bucket β archived (completed)+ // topics are excluded by the sidebar fetch's `excludeStatuses`. Fall back to+ // the by-id detail cache so consumers keep real data (title, metadata, β¦).+ return s.activeTopicId ? s.topicDetailMap?.[s.activeTopicId] : undefined;};const searchTopics = (s: ChatStoreState): ChatTopic[] => s.searchTopics;@@ -68,6 +73,8 @@ const getTopicById =const topic = topicData.items.find((item) => item.id === id);if (topic) return topic;}++ return s.topicDetailMap?.[id];};/**