🤯 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: keep terminal topic status out of stale list cache (#19663)
YuTengjingfd7c7791848c
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex f1df40c87a8..f7d297278d2 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -717,22 +717,44 @@ export class ChatTopicActionImpl {* Returns the row to trust: the fetched one, or the fetched one with the* pending status re-applied when it predates the write.*/- #applyPendingStatusWrite = (item: ChatTopic): ChatTopic => {+ #applyPendingStatusWrite = (item: ChatTopic, confirmMatchingStatus = true): ChatTopic => {const pending = this.#pendingTopicStatusWrites.get(item.id);if (!pending) return item;- if (pending.expiresAt <= Date.now() || item.status === pending.status) {+ if (pending.expiresAt <= Date.now()) {this.#pendingTopicStatusWrites.delete(item.id);return item;}+ if (item.status === pending.status) {+ if (confirmMatchingStatus) this.#pendingTopicStatusWrites.delete(item.id);+ return item;+ }return { ...item, status: pending.status };};- #reconcileFetchedTopics = (items: ChatTopic[], currentItems?: ChatTopic[]): ChatTopic[] => {- let next = items;+ /**+ * Apply pending terminal statuses before a fetched topic list enters SWR.+ *+ * Reconciling only in `onData` keeps Zustand correct but is too late for the+ * persisted cache: SWR has already accepted the older raw response and can+ * flush `running` to IndexedDB. After the 15-second pin expires, remounting+ * the sidebar restores that stale spinner. This step deliberately+ * handles statuses only; client-only optimistic rows are still added later by+ * {@link #reconcileFetchedTopics} and never enter the persisted response.+ */+ #applyPendingStatusWrites = (+ items: ChatTopic[],+ options?: { confirmMatchingStatus?: boolean },+ ): ChatTopic[] => {+ if (this.#pendingTopicStatusWrites.size === 0) return items;+ return items.map((item) => this.#applyPendingStatusWrite(item, options?.confirmMatchingStatus));+ };- if (this.#pendingTopicStatusWrites.size > 0) {- next = next.map((item) => this.#applyPendingStatusWrite(item));- }+ #reconcileFetchedTopics = (+ items: ChatTopic[],+ currentItems?: ChatTopic[],+ options?: { confirmMatchingStatus?: boolean },+ ): ChatTopic[] => {+ let next = this.#applyPendingStatusWrites(items, options);// In-flight first-send optimistic rows are client-only, so any refetch// landing mid-send (e.g. the fire-and-forget refreshTopic after a previous@@ -1200,7 +1222,7 @@ export class ChatTopicActionImpl {this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: false });}- return result;+ return { ...result, items: this.#applyPendingStatusWrites(result.items) };},{// onData: responsible for state updates (fires for both cached and fresh data)@@ -1210,7 +1232,11 @@ export class ChatTopicActionImpl {const { total: totalCount } = result;const currentData = this.#get().topicDataMap[containerKey];- const topics = this.#reconcileFetchedTopics(result.items, currentData?.items);+ const topics = this.#reconcileFetchedTopics(result.items, currentData?.items, {+ // `result` can be a cached response or a list already normalized by+ // the fetcher. Neither proves the server observed the pending write.+ confirmMatchingStatus: false,+ });// Fire BEFORE the no-change early return below: on a cold boot the// cached list arrives with no `currentData`, and that first deliverydiff --git a/src/store/chat/slices/topic/topicListCache.integration.test.ts b/src/store/chat/slices/topic/topicListCache.integration.test.tsindex 06863220173..73a49251a93 100644--- a/src/store/chat/slices/topic/topicListCache.integration.test.ts+++ b/src/store/chat/slices/topic/topicListCache.integration.test.ts@@ -84,6 +84,7 @@ describe('persisted topic list across a reload', () => {afterEach(async () => {await localDataCache.clearScope(SCOPE);+ vi.restoreAllMocks();vi.clearAllMocks();});@@ -91,8 +92,9 @@ describe('persisted topic list across a reload', () => {// --- session 1: the list is fetched while the run is still going ---------vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);+ const provider1 = makeProvider();const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {- wrapper: wrapper(makeProvider()),+ wrapper: wrapper(provider1),});await waitFor(() => expect(session1.result.current.data?.items).toHaveLength(1));@@ -130,4 +132,76 @@ describe('persisted topic list across a reload', () => {session2.unmount();});++ it('keeps a terminal status after an older list request lands and the pending pin expires', async () => {+ const now = Date.now();+ const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now);++ vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);++ const provider1 = makeProvider();+ const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {+ wrapper: wrapper(provider1),+ });++ await waitFor(() => expect(session1.result.current.data?.items).toHaveLength(1));+ await waitFor(async () => expect(await cachedTopicStatus()).toBe('running'));++ // The terminal write wins in Zustand and the persisted cache first.+ act(() => {+ useChatStore.getState().internal_pinTopicStatus({+ agentId: AGENT_ID,+ status: 'active',+ topicId: runningTopic.id,+ });+ });+ await waitFor(async () => expect(await cachedTopicStatus()).toBe('active'));+ const cacheSetSpy = vi.spyOn(localDataCache, 'set');++ // A list request that started before the terminal write returns afterwards.+ // The pending-status pin keeps the mounted sidebar correct, but the raw SWR+ // response must not put `running` back into IndexedDB behind it.+ await act(async () => {+ await session1.result.current.mutate();+ });+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('active');+ await waitFor(() => expect(cacheSetSpy).toHaveBeenCalled());+ await Promise.all(cacheSetSpy.mock.results.map(({ value }) => value));+ expect(await cachedTopicStatus()).toBe('active');++ // The normalized first response must not be mistaken for server+ // confirmation. A second older response can still be in flight and must be+ // pinned too.+ cacheSetSpy.mockClear();+ await act(async () => {+ await session1.result.current.mutate();+ });+ await waitFor(() => expect(cacheSetSpy).toHaveBeenCalled());+ await Promise.all(cacheSetSpy.mock.results.map(({ value }) => value));+ expect(await cachedTopicStatus()).toBe('active');+ session1.unmount();++ // Regression: after the 15-second pending pin elapsed, navigating away and+ // back remounted the sidebar from that stale IndexedDB snapshot and restored+ // the yellow running spinner until the network response arrived.+ nowSpy.mockReturnValue(now + 16_000);+ act(() => {+ useChatStore.setState({ topicDataMap: {} });+ });+ vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);++ const provider2 = makeProvider();+ await provider2.hydrateScope?.();++ const session2 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {+ wrapper: wrapper(provider2),+ });++ await waitFor(() =>+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items).toHaveLength(1),+ );+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('active');++ session2.unmount();+ });});