π€― 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: stop a finished topic from flashing the running spinner on reload (#19442)
YuTengjing67aee9947c91
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex b5bda6f8de5..4d442575905 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -2019,6 +2019,86 @@ describe('topic action', () => {expect(topicData.hasMore).toBe(false);});});+ describe('persisted topic-list cache write-through', () => {+ const setupBucket = (agentId: string) => {+ const containerKey = topicMapKey({ agentId });+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ topicDataMap: {+ [containerKey]: {+ currentPage: 0,+ hasMore: false,+ isLoadingMore: false,+ items: [{ id: 'topic-1', status: 'running', title: 'Topic 1' }] as ChatTopic[],+ pageSize: 20,+ total: 1,+ },+ },+ });+ });+ vi.mocked(mutate).mockClear();++ return { containerKey, result };+ };++ it('mirrors a run-end status patch into the cached topic list', () => {+ const { containerKey, result } = setupBucket('agent-write-through');++ act(() => {+ result.current.internal_dispatchTopic({+ id: 'topic-1',+ type: 'updateTopic',+ value: { status: 'unread' },+ });+ });++ expect(mutate).toHaveBeenCalledTimes(1);+ const [matcher, updater, options] = vi.mocked(mutate).mock.calls[0] as [+ (key: unknown) => boolean,+ (cached?: { items: ChatTopic[]; total: number }) => unknown,+ unknown,+ ];++ expect(options).toEqual({ revalidate: false });+ // Only this container's list keys β the agent-view key and other+ // containers keep their own cached pages.+ expect(matcher(['topic:list', containerKey, { pageSize: 20 }])).toBe(true);+ expect(matcher(['topic:list', topicMapKey({ agentId: 'other-agent' }), {}])).toBe(false);+ expect(matcher(['topic:agentView', containerKey, {}])).toBe(false);++ const cached = {+ items: [{ id: 'topic-1', status: 'running', title: 'Topic 1' }] as ChatTopic[],+ total: 1,+ };+ expect(updater(cached)).toMatchObject({+ items: [{ id: 'topic-1', status: 'unread' }],+ total: 1,+ });++ // A cached page without the patched row (or no entry at all) stays as-is,+ // so the mutate cannot create a bogus entry.+ const otherPage = { items: [{ id: 'topic-2', status: 'active' }] as ChatTopic[], total: 1 };+ expect(updater(otherPage)).toBe(otherPage);+ expect(updater(undefined)).toBeUndefined();+ });++ it('does not mirror client-only optimistic rows', () => {+ const { result } = setupBucket('agent-write-through-add');++ act(() => {+ result.current.internal_dispatchTopic({+ optimistic: true,+ type: 'addTopic',+ value: { id: 'topic-optimistic', title: 'New' },+ });+ });++ expect(mutate).not.toHaveBeenCalled();+ });+ });describe('loadMoreAgentTopicsView', () => {it('records a pagination error without clearing existing topics or hasMore', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 6a46523f81d..f1df40c87a8 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -1921,6 +1921,42 @@ export class ChatTopicActionImpl {return topicId;};+ /**+ * Mirror an optimistic topic patch into the PERSISTED topic-list cache.+ *+ * `topic:` keys are persisted to IndexedDB by the tiered SWR provider (see+ * `CACHE_TIERS`), and that cached page is what the sidebar paints on a cold+ * boot, before any revalidation lands. Optimistic dispatches only touched the+ * Zustand maps, so the terminal status a run writes when it ends ('unread' /+ * 'active') never reached the cache: the last FETCHED snapshot β taken while+ * the run was still `running` β stayed there, and a reload repainted a+ * finished topic with the running spinner until the revalidation corrected it+ * a moment later (LOBE-14032). Same write-through idea as+ * `#writeThroughMessageCache` in the message slice.+ *+ * Only `updateTopic` is mirrored. It patches a row a fetch already produced,+ * so it cannot leak a client-only row into a cache that outlives the session+ * β unlike an optimistic `addTopic` / `replaceTopicId`, whose placeholder is+ * reconciled per session by `#reconcileFetchedTopics`. Deletions already go+ * through `refreshTopic`, which revalidates the same keys.+ */+ #writeThroughTopicListCache = (containerKey: string, payload: ChatTopicDispatch): void => {+ if (payload.type !== 'updateTopic') return;++ void mutate(+ (key) => Array.isArray(key) && key[0] === topicKeys.list.root && key[1] === containerKey,+ (cached?: { items: ChatTopic[]; total: number }) => {+ if (!cached?.items) return cached;++ const items = topicReducer(cached.items, payload);+ // `topicReducer` returns the same reference when the patch is a no-op+ // (e.g. the row isn't on this cached page), so the entry stays untouched.+ return items === cached.items ? cached : { ...cached, items };+ },+ { revalidate: false },+ );+ };+/*** Apply a topic reducer to a bucket in `topicDataMap`. Scope on the payload* (`agentId`/`groupId`) wins; otherwise falls back to the currently active@@ -1998,6 +2034,13 @@ export class ChatTopicActionImpl {};}+ // Mirror the patch into the persisted topic-list cache too β see+ // `#writeThroughTopicListCache`. Runs before the unchanged early-return+ // below: the cache can hold rows this bucket never loaded (a cold boot+ // paints from it before any bucket exists), so "nothing changed in the+ // store" says nothing about the cached page.+ this.#writeThroughTopicListCache(key, payload);+// no need to update if all maps are unchangedconst mainChanged = !isEqual(nextItems, currentData?.items);const detailChanged = nextDetailMap !== detailMap;diff --git a/src/store/chat/slices/topic/topicListCache.integration.test.ts b/src/store/chat/slices/topic/topicListCache.integration.test.tsnew file mode 100644index 00000000000..06863220173--- /dev/null+++ b/src/store/chat/slices/topic/topicListCache.integration.test.ts@@ -0,0 +1,133 @@+/**+ * @vitest-environment happy-dom+ *+ * LOBE-14032: after a run ends, a reload briefly repainted the topic row with+ * the running spinner before it vanished again.+ *+ * The chain under test is the real one: `useFetchTopics` β tiered SWR provider+ * β IndexedDB β "reload" (fresh provider) β first paint before the network+ * answers. The run's terminal status is written optimistically (no refetch+ * follows it), so unless that write also reaches the persisted cache, the+ * cached page keeps the `running` snapshot taken mid-run and the sidebar paints+ * a spinner on a finished topic.+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { type Cache, SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { localDataCache } from '@/libs/swr/localDataCache';+import { createCacheProvider } from '@/libs/swr/localStorageProvider';+import { setScopedMutate } from '@/libs/swr/mutate';+import { topicService } from '@/services/topic';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';+import type { ChatTopic } from '@/types/topic';++import { useChatStore } from '../../store';++vi.mock('@/services/topic', () => ({+ topicService: { getTopics: vi.fn() },+}));++const SCOPE = 'topic-cache-user:personal';+const AGENT_ID = 'agent-lobe-14032';+const CONTAINER_KEY = topicMapKey({ agentId: AGENT_ID });++const makeProvider = () =>+ createCacheProvider({+ debounceMs: 5,+ getScope: () => SCOPE,+ idbPatterns: ['topic:'],+ localPatterns: [],+ });++/** Publish the scoped mutate the way `SWRProvider` does in the app. */+const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper =+ (provider: ReturnType<typeof createCacheProvider>) =>+ ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { provider: provider as unknown as (c: Readonly<Cache>) => Cache } },+ createElement(MutateBridge),+ children,+ );++const runningTopic = { id: 'tpc-lobe-14032', status: 'running', title: 'ζε·ζ倩倩ζ°ζ₯θ―’' };++const cachedTopicStatus = async (): Promise<string | undefined> => {+ const entries = await localDataCache.entriesByScope(SCOPE);+ for (const entry of entries) {+ const items = (entry.data as { data?: { items?: ChatTopic[] } })?.data?.items;+ const topic = items?.find((item) => item.id === runningTopic.id);+ if (topic) return topic.status ?? undefined;+ }+ return undefined;+};++describe('persisted topic list across a reload', () => {+ beforeEach(() => {+ act(() => {+ useChatStore.setState({+ activeAgentId: AGENT_ID,+ activeGroupId: undefined,+ topicDataMap: {},+ });+ });+ });++ afterEach(async () => {+ await localDataCache.clearScope(SCOPE);+ vi.clearAllMocks();+ });++ it('paints the runβs terminal status, not the mid-run `running` snapshot', async () => {+ // --- session 1: the list is fetched while the run is still going ---------+ vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);++ const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {+ wrapper: wrapper(makeProvider()),+ });++ await waitFor(() => expect(session1.result.current.data?.items).toHaveLength(1));+ await waitFor(async () => expect(await cachedTopicStatus()).toBe('running'));++ // --- the run ends: an optimistic status write, with no refetch behind it -+ act(() => {+ useChatStore.getState().internal_dispatchTopic({+ id: runningTopic.id,+ type: 'updateTopic',+ value: { status: 'active' },+ });+ });++ await waitFor(async () => expect(await cachedTopicStatus()).toBe('active'));+ session1.unmount();++ // --- session 2 ("reload"): a slow network, so the cached page paints -----+ 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();+ });+});