🤯 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
♻️ refactor(thread): move the topic thread list onto @lobechat/replica (#21197)
Arvin Xud5366a2f7a69
diff --git a/src/features/Portal/Thread/Header/Title.tsx b/src/features/Portal/Thread/Header/Title.tsxindex 82e2a99ed2d..6bd5fcaca77 100644--- a/src/features/Portal/Thread/Header/Title.tsx+++ b/src/features/Portal/Thread/Header/Title.tsx@@ -1,6 +1,7 @@import { Skeleton } from '@lobehub/ui';import { useChatStore } from '@/store/chat';+import { threadSelectors } from '@/store/chat/selectors';import ActiveThread from './Active';import NewThread from './New';@@ -8,9 +9,10 @@ import NewThread from './New';const Header = () => {const isInNew = useChatStore((s) => s.startToForkThread);- const isInit = useChatStore((s) => s.threadsInit);+ const isInit = useChatStore(threadSelectors.isCurrentTopicThreadsLoaded);+ const isThreadPending = useChatStore(threadSelectors.isPortalThreadPending);- if (!isInit) return <Skeleton height={22} width={200} />;+ if (!isInit || (!isInNew && isThreadPending)) return <Skeleton height={22} width={200} />;return isInNew ? <NewThread /> : <ActiveThread />;};diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex 2144d4ef9e6..5186f10b0da 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -5,12 +5,14 @@ import { PRE_PAINT_HYDRATE_TIMEOUT } from '@/libs/replica/prePaint';import {agentChatTopicListLoader,preHydrateMessagesForRoute,+ preHydrateThreadsForRoute,preHydrateTopicListForRoute,} from './topicListLoader';const preHydrateTopicListMock = vi.hoisted(() => vi.fn(async () => true));const getSidebarTopicListParamsMock = vi.hoisted(() => vi.fn());const preHydrateMessagesMock = vi.hoisted(() => vi.fn(async () => true));+const preHydrateThreadsMock = vi.hoisted(() => vi.fn(async (_topicId?: string) => true));const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);const preHydrateBuiltinAgentMock = vi.hoisted(() => vi.fn(async () => true));const preHydrateDeviceListMock = vi.hoisted(() => vi.fn(async () => true));@@ -43,6 +45,7 @@ vi.mock('@/store/chat', () => ({getState: () => ({dbMessagesMap: chatState.dbMessagesMap,preHydrateMessages: preHydrateMessagesMock,+ preHydrateThreads: preHydrateThreadsMock,preHydrateTopicList: preHydrateTopicListMock,}),},@@ -212,3 +215,43 @@ describe('agent chat transcript pre-hydrate', () => {await expect(preHydrateMessagesForRoute('agt_1', 'tpc_1')).resolves.toBeUndefined();});});++describe('agent chat thread list pre-hydrate', () => {+ beforeEach(() => {+ preHydrateThreadsMock.mockReset();+ preHydrateThreadsMock.mockResolvedValue(true);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("seeds the route topic's persisted threads before the route commits", async () => {+ await agentChatTopicListLoader({ params: { aid: 'agt_1', topicId: 'tpc_1' } } as never);++ expect(preHydrateThreadsMock).toHaveBeenCalledWith('tpc_1');+ });++ it('skips a route without a topic', async () => {+ await agentChatTopicListLoader(loaderArgs('agt_1'));++ expect(preHydrateThreadsMock).not.toHaveBeenCalled();+ });++ it('does not let a stalled thread read block the route', async () => {+ vi.useFakeTimers();+ preHydrateThreadsMock.mockImplementation(() => new Promise(() => {}));++ const settled = vi.fn();+ void preHydrateThreadsForRoute('tpc_1').then(settled);++ await vi.advanceTimersByTimeAsync(PRE_PAINT_HYDRATE_TIMEOUT);+ expect(settled).toHaveBeenCalled();+ });++ it('never rejects the route when the thread hydrate fails', async () => {+ preHydrateThreadsMock.mockRejectedValueOnce(new Error('storage exploded'));++ await expect(preHydrateThreadsForRoute('tpc_1')).resolves.toBeUndefined();+ });+});diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex 9702dd6926d..de46470b977 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -79,6 +79,16 @@ export const preHydrateMessagesForRoute = async (await settleWithin(seed(), PRE_PAINT_HYDRATE_TIMEOUT);};+/**+ * Seed the persisted sub-thread list of a route's topic, so the topic's thread+ * rows and the thread portal header paint from local data on the first frame.+ */+export const preHydrateThreadsForRoute = async (topicId?: string): Promise<void> => {+ if (!topicId) return;++ await settleWithin(useChatStore.getState().preHydrateThreads(topicId), PRE_PAINT_HYDRATE_TIMEOUT);+};+/*** Seed the persisted device list, so the input bar names the bound device and* resolves its cwd on the first frame instead of after the mount-time hydrate.@@ -104,6 +114,7 @@ export const agentChatTopicListLoader = async ({ params }: LoaderFunctionArgs):await Promise.all([preHydrateTopicListForRoute(params.aid),preHydrateMessagesForRoute(params.aid, params.topicId),+ preHydrateThreadsForRoute(params.topicId),preHydrateDeviceListForRoute(),]);diff --git a/src/store/chat/slices/thread/action.openThreadCreator.test.ts b/src/store/chat/slices/thread/action.openThreadCreator.test.tsindex c9989d0c497..b49cc8acf50 100644--- a/src/store/chat/slices/thread/action.openThreadCreator.test.ts+++ b/src/store/chat/slices/thread/action.openThreadCreator.test.ts@@ -110,7 +110,6 @@ beforeEach(() => {threadLoadingIds: [],threadMaps: {},threadStartMessageId: undefined,- threadsInit: false,},false,);diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.tsindex c326b2dea06..1c9f919023b 100644--- a/src/store/chat/slices/thread/action.test.ts+++ b/src/store/chat/slices/thread/action.test.ts@@ -4,7 +4,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';import { type Mock } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { mutate } from '@/libs/swr';+import { cacheScope, createReplicaState } from '@/libs/replica';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { threadService } from '@/services/thread';@@ -12,6 +12,8 @@ import { type ThreadItem } from '@/types/topic';import { ThreadStatus, ThreadType } from '@/types/topic';import { useChatStore } from '../../store';+import { threadListResource } from './projection';+import { threadSelectors } from './selectors';// Mock @/libs/swr mutatevi.mock('@/libs/swr', async () => {@@ -76,26 +78,55 @@ vi.mock('@/store/session', () => ({},}));-vi.mock('@/store/user', () => ({- useUserStore: {- getState: vi.fn(() => ({})),- },-}));--vi.mock('@/store/user/selectors', () => ({+vi.mock(import('@/store/user/selectors'), async (importOriginal) => ({+ ...(await importOriginal()),systemAgentSelectors: {thread: vi.fn(() => ({})),},userGeneralSettingsSelectors: {currentResponseLanguage: vi.fn(() => 'en-US'),},- userProfileSelectors: {- userAvatar: vi.fn(() => 'avatar-url'),- },}));+const SCOPE = 'thread-test-user:personal';++const makeThread = (id: string, title: string, topicId = 'test-topic-id'): ThreadItem => ({+ createdAt: new Date('2026-10-01T00:00:00Z'),+ id,+ lastActiveAt: new Date('2026-10-01T00:00:00Z'),+ sourceMessageId: 'msg-1',+ status: ThreadStatus.Active,+ title,+ topicId,+ type: ThreadType.Continuation,+ updatedAt: new Date('2026-10-01T00:00:00Z'),+ userId: 'user-1',+});++/** Fetch a topic's threads through the replica and wait until they are persisted. */+const seedPersistedThreads = async (topicId: string, threads: ThreadItem[]) => {+ (threadService.getThreads as Mock).mockResolvedValueOnce(threads);+ await act(async () => {+ await useChatStore.getState().refreshThreads(topicId);+ });+ await waitFor(async () => {+ const row = await threadListResource.storage!.get({ queryKey: topicId, scope: SCOPE });+ expect(row?.data).toEqual(threads);+ });+};++/** Drop everything in memory, as a reload does; only storage survives. */+const simulateReload = () => {+ act(() => {+ useChatStore.setState({ threadListReplica: createReplicaState(), threadMaps: {} });+ });+};+beforeEach(() => {vi.clearAllMocks();+ vi.spyOn(cacheScope, 'get').mockReturnValue(SCOPE);+ vi.spyOn(cacheScope, 'use').mockReturnValue(SCOPE);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);useChatStore.setState({activeAgentId: 'test-session-id',@@ -107,10 +138,10 @@ beforeEach(() => {portalThreadId: undefined,startToForkThread: undefined,threadInputMessage: '',+ threadListReplica: createReplicaState(),threadLoadingIds: [],threadMaps: {},threadStartMessageId: undefined,- threadsInit: false,},false,);@@ -263,83 +294,225 @@ describe('thread action', () => {});describe('useFetchThreads', () => {- it('should fetch threads for a given topic id', async () => {+ it('should fetch threads for a given topic id into threadMaps', async () => {const topicId = 'test-topic-id';- const threads: ThreadItem[] = [- {- createdAt: new Date(),- id: 'thread-1',- lastActiveAt: new Date(),- sourceMessageId: 'msg-1',- status: ThreadStatus.Active,- title: 'Thread 1',- topicId,- type: ThreadType.Continuation,- updatedAt: new Date(),- userId: 'user-1',- },- ];+ const threads = [makeThread('thread-1', 'Thread 1')];(threadService.getThreads as Mock).mockResolvedValue(threads);- const { result } = renderHook(() => useChatStore().useFetchThreads(true, topicId));+ renderHook(() => useChatStore().useFetchThreads(true, topicId));await waitFor(() => {- expect(result.current.data).toEqual(threads);+ expect(useChatStore.getState().threadMaps).toEqual({ [topicId]: threads });});-- expect(useChatStore.getState().threadsInit).toBeTruthy();- expect(useChatStore.getState().threadMaps).toEqual({ [topicId]: threads });+ expect(threadService.getThreads).toHaveBeenCalledWith(topicId);});it('should not fetch when enable is false', async () => {- const topicId = 'test-topic-id';-- const { result } = renderHook(() => useChatStore().useFetchThreads(false, topicId));+ renderHook(() => useChatStore().useFetchThreads(false, 'test-topic-id'));expect(threadService.getThreads).not.toHaveBeenCalled();- expect(result.current.data).toBeUndefined();+ expect(useChatStore.getState().threadMaps).toEqual({});});it('should not fetch when topicId is undefined', async () => {const { result } = renderHook(() => useChatStore().useFetchThreads(true, undefined));expect(threadService.getThreads).not.toHaveBeenCalled();- expect(result.current.data).toBeUndefined();+ expect(result.current.isHydrated).toBe(true);});- });- describe('refreshThreads', () => {- it('should trigger SWR mutate for active topic', async () => {- const { result } = renderHook(() => useChatStore());+ // A reload used to repaint the topic's threads only after the network+ // answered: the list rendered nothing (and the portal header a skeleton)+ // until then. The persisted copy now paints first.+ it('repaints the persisted threads after a reload before the network answers', async () => {+ const topicId = `topic-${Date.now()}`;+ const threads = [makeThread('thread-1', 'Persisted thread')].map((t) => ({ ...t, topicId }));+ (threadService.getThreads as Mock).mockResolvedValue(threads);+ const first = renderHook(() => useChatStore().useFetchThreads(true, topicId));+ await waitFor(() => {+ expect(useChatStore.getState().threadMaps[topicId]).toEqual(threads);+ });+ await waitFor(async () => {+ const row = await threadListResource.storage!.get({ queryKey: topicId, scope: SCOPE });+ expect(row?.data).toEqual(threads);+ });+ first.unmount();++ // Reload: memory is gone, only the persisted projection survives.act(() => {- useChatStore.setState({ activeTopicId: 'test-topic-id' });+ useChatStore.setState({ threadListReplica: createReplicaState(), threadMaps: {} });});+ (threadService.getThreads as Mock).mockImplementation(() => new Promise(() => {}));await act(async () => {- await result.current.refreshThreads();+ await useChatStore.getState().preHydrateThreads(topicId);});- expect(mutate).toHaveBeenCalledWith(['thread:list', 'test-topic-id']);+ expect(useChatStore.getState().threadMaps[topicId]).toEqual(threads);+ expect(+ threadSelectors.isCurrentTopicThreadsLoaded({+ ...useChatStore.getState(),+ activeTopicId: topicId,+ }),+ ).toBe(true);});- it('should not mutate when activeTopicId is undefined', async () => {- const { result } = renderHook(() => useChatStore());+ it('sends one request when several mounts sync the same topic', async () => {+ const topicId = `topic-dedupe-${Date.now()}`;+ (threadService.getThreads as Mock).mockResolvedValue([makeThread('t1', 'T1', topicId)]);++ // ThreadHydration + the sidebar ThreadList both sync the active topic.+ renderHook(() => {+ useChatStore().useFetchThreads(true, topicId);+ useChatStore().useFetchThreads(true, topicId);+ });+ const other = renderHook(() => useChatStore().useFetchThreads(true, topicId));+ await waitFor(() => {+ expect(useChatStore.getState().threadMaps[topicId]).toHaveLength(1);+ });+ other.rerender();+ expect(threadService.getThreads).toHaveBeenCalledTimes(1);+ });++ it('does not show the previous identity threads after a scope switch', async () => {+ const topicId = `topic-scope-${Date.now()}`;+ await seedPersistedThreads(topicId, [makeThread('t1', 'Owned by A', topicId)]);+ simulateReload();++ // Another user / workspace opens the same topic id.+ vi.spyOn(cacheScope, 'get').mockReturnValue('other-user:personal');+ vi.spyOn(cacheScope, 'use').mockReturnValue('other-user:personal');+ (threadService.getThreads as Mock).mockImplementation(() => new Promise(() => {}));++ const { result } = renderHook(() => useChatStore().useFetchThreads(true, topicId));+ await waitFor(() => expect(result.current.isHydrated).toBe(true));++ expect(useChatStore.getState().threadMaps[topicId]).toBeUndefined();+ });++ it('keeps the last good threads when a background refresh fails', async () => {+ const topicId = `topic-offline-${Date.now()}`;+ const threads = [makeThread('t1', 'Last good', topicId)];+ await seedPersistedThreads(topicId, threads);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ (threadService.getThreads as Mock).mockRejectedValue(new Error('offline'));++ await act(async () => {+ await useChatStore.getState().refreshThreads(topicId);+ });++ expect(useChatStore.getState().threadMaps[topicId]).toEqual(threads);+ });+ });++ describe('isPortalThreadPending', () => {+ it('treats a thread missing from a restored snapshot as loading until the server answers', async () => {+ const topicId = `topic-portal-${Date.now()}`;+ await seedPersistedThreads(topicId, [makeThread('old', 'Old', topicId)]);+ simulateReload();+ act(() => {+ useChatStore.setState({ activeTopicId: topicId, portalThreadId: 'created-later' });+ });++ let resolve!: (threads: ThreadItem[]) => void;+ (threadService.getThreads as Mock).mockImplementation(+ () => new Promise<ThreadItem[]>((r) => (resolve = r)),+ );+ renderHook(() => useChatStore().useFetchThreads(true, topicId));+ await waitFor(() => expect(useChatStore.getState().threadMaps[topicId]).toHaveLength(1));++ // Restored, but the snapshot predates the thread: still loading.+ expect(threadSelectors.isPortalThreadPending(useChatStore.getState())).toBe(true);++ await act(async () => {+ resolve([makeThread('old', 'Old', topicId), makeThread('created-later', 'New', topicId)]);+ });+ await waitFor(() =>+ expect(threadSelectors.isPortalThreadPending(useChatStore.getState())).toBe(false),+ );+ });++ it('is settled once the server confirms the thread is gone', async () => {+ const topicId = `topic-gone-${Date.now()}`;+ await seedPersistedThreads(topicId, []);+ act(() => {+ useChatStore.setState({ activeTopicId: topicId, portalThreadId: 'deleted' });+ });++ expect(threadSelectors.isPortalThreadPending(useChatStore.getState())).toBe(false);+ });+ });++ describe('refreshThreads', () => {+ it('should refetch the active topic threads into threadMaps', async () => {+ const threads = [{ id: 'thread-1', title: 'Fresh', topicId: 'test-topic-id' }];+ (threadService.getThreads as Mock).mockResolvedValue(threads);++ await act(async () => {+ await useChatStore.getState().refreshThreads();+ });++ expect(threadService.getThreads).toHaveBeenCalledWith('test-topic-id');+ expect(useChatStore.getState().threadMaps['test-topic-id']).toEqual(threads);+ });++ it('should not fetch when activeTopicId is undefined', async () => {act(() => {useChatStore.setState({ activeTopicId: undefined });});await act(async () => {- await result.current.refreshThreads();+ await useChatStore.getState().refreshThreads();});- expect(mutate).not.toHaveBeenCalled();+ expect(threadService.getThreads).not.toHaveBeenCalled();+ });++ it('never rejects when the refetch fails', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ (threadService.getThreads as Mock).mockRejectedValue(new Error('offline'));++ await expect(useChatStore.getState().refreshThreads()).resolves.toBeUndefined();});});describe('removeThread', () => {+ it('drops the thread from the view and storage even when the refetch fails', async () => {+ const topicId = 'test-topic-id';+ await seedPersistedThreads(topicId, [makeThread('keep', 'Keep'), makeThread('gone', 'Gone')]);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ (threadService.removeThread as Mock).mockResolvedValue(undefined);+ (threadService.getThreads as Mock).mockRejectedValue(new Error('offline'));++ await act(async () => {+ await useChatStore.getState().removeThread('gone');+ });++ expect(useChatStore.getState().threadMaps[topicId]?.map((t) => t.id)).toEqual(['keep']);++ // A reload must not bring the deleted thread back from the local copy.+ simulateReload();+ await act(async () => {+ await useChatStore.getState().preHydrateThreads(topicId);+ });+ expect(useChatStore.getState().threadMaps[topicId]?.map((t) => t.id)).toEqual(['keep']);+ });++ it('restores the thread when the server rejects the delete', async () => {+ const topicId = 'test-topic-id';+ await seedPersistedThreads(topicId, [makeThread('keep', 'Keep'), makeThread('t2', 'T2')]);+ (threadService.removeThread as Mock).mockRejectedValue(new Error('forbidden'));++ await act(async () => {+ await expect(useChatStore.getState().removeThread('t2')).rejects.toThrow('forbidden');+ });++ expect(useChatStore.getState().threadMaps[topicId]?.map((t) => t.id)).toEqual(['keep', 't2']);+ });+it('should remove thread and refresh threads', async () => {const { result } = renderHook(() => useChatStore());@@ -637,24 +810,51 @@ describe('thread action', () => {});describe('internal_updateThread', () => {+ const seedThread = () =>+ act(() => {+ useChatStore.setState({+ threadMaps: {+ 'test-topic-id': [+ {+ createdAt: new Date(),+ id: 'thread-id',+ lastActiveAt: new Date(),+ status: ThreadStatus.Active,+ title: 'Old Title',+ topicId: 'test-topic-id',+ type: ThreadType.Continuation,+ updatedAt: new Date(),+ userId: 'user-1',+ },+ ],+ },+ });+ });+it('should update thread locally and on server', async () => {const { result } = renderHook(() => useChatStore());+ seedThread();- (threadService.updateThread as Mock).mockResolvedValue(undefined);-- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchThread');+ let resolveUpdate: () => void = () => {};+ (threadService.updateThread as Mock).mockImplementation(+ () => new Promise<void>((resolve) => (resolveUpdate = resolve)),+ );const refreshSpy = vi.spyOn(result.current, 'refreshThreads').mockResolvedValue(undefined);const loadingSpy = vi.spyOn(result.current, 'internal_updateThreadLoading');- await act(async () => {- await result.current.internal_updateThread('thread-id', { title: 'Updated Title' });+ let pending: Promise<void> = Promise.resolve();+ act(() => {+ pending = result.current.internal_updateThread('thread-id', { title: 'Updated Title' });});- expect(dispatchSpy).toHaveBeenCalledWith({- id: 'thread-id',- type: 'updateThread',- value: { title: 'Updated Title' },+ // Optimistic: the new title shows while the server call is in flight.+ expect(useChatStore.getState().threadMaps['test-topic-id'][0].title).toBe('Updated Title');++ await act(async () => {+ resolveUpdate();+ await pending;});+expect(threadService.updateThread).toHaveBeenCalledWith('thread-id', {title: 'Updated Title',});@@ -662,6 +862,20 @@ describe('thread action', () => {expect(loadingSpy).toHaveBeenCalledWith('thread-id', true);expect(loadingSpy).toHaveBeenCalledWith('thread-id', false);});++ it('rolls the title back and clears loading when the server rejects', async () => {+ seedThread();+ (threadService.updateThread as Mock).mockRejectedValue(new Error('offline'));++ await act(async () => {+ await expect(+ useChatStore.getState().internal_updateThread('thread-id', { title: 'Updated Title' }),+ ).rejects.toThrow('offline');+ });++ expect(useChatStore.getState().threadMaps['test-topic-id'][0].title).toBe('Old Title');+ expect(useChatStore.getState().threadLoadingIds).not.toContain('thread-id');+ });});describe('internal_dispatchThread', () => {diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.tsindex cd73a54c8db..bf4c4c07128 100644--- a/src/store/chat/slices/thread/action.ts+++ b/src/store/chat/slices/thread/action.ts@@ -13,10 +13,8 @@ import {type UIChatMessage,} from '@lobechat/types';import isEqual from 'fast-deep-equal';-import { type SWRResponse } from 'swr';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { threadKeys } from '@/libs/swr/keys';+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';import { aiChatService } from '@/services/aiChat';import { threadService } from '@/services/thread';import { threadSelectors } from '@/store/chat/selectors';@@ -28,6 +26,7 @@ import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/userimport { setNamespace } from '@/utils/storeDebug';import { PortalViewType } from '../portal/initialState';+import { threadListResource } from './projection';import { type ThreadDispatch } from './reducer';import { threadReducer } from './reducer';import { genParentMessages } from './selectors';@@ -35,17 +34,30 @@ import { genParentMessages } from './selectors';const n = setNamespace('thd');type Setter = StoreSetter<ChatStore>;+/** Window in which mounts syncing the same topic share one request. */+export const THREAD_LIST_DEDUPING_INTERVAL = 10_000;+export const chatThreadMessage = (set: Setter, get: () => ChatStore, _api?: unknown) =>new ChatThreadActionImpl(set, get, _api);export class ChatThreadActionImpl {readonly #get: () => ChatStore;readonly #set: Setter;+ /** Sub-threads per topic, viewed as `threadMaps[topicId]`. */+ readonly #threadList;constructor(set: Setter, get: () => ChatStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#threadList = createReplicaSlice(threadListResource, {+ actionPrefix: n('threadList'),+ fetcher: (topicId) => threadService.getThreads(topicId),+ get,+ set,+ stateKey: 'threadListReplica',+ view: recordLens<ChatStore, ThreadItem[]>('threadMaps'),+ });}updateThreadInputMessage = (message: string): void => {@@ -155,37 +167,62 @@ export class ChatThreadActionImpl {return data;};- useFetchThreads = (enable: boolean, topicId?: string): SWRResponse<ThreadItem[]> => {- return useClientDataSWR<ThreadItem[]>(- enable && !!topicId ? threadKeys.list(topicId) : null,- async ([, topicId]: [string, string]) => threadService.getThreads(topicId),- {- onSuccess: (threads) => {- const nextMap = { ...this.#get().threadMaps, [topicId!]: threads };-- // no need to update map if the threads have been init and the map is the same- if (this.#get().threadsInit && isEqual(nextMap, this.#get().threadMaps)) return;-- this.#set(- { threadMaps: nextMap, threadsInit: true },- false,- n('useFetchThreads(success)', { topicId }),- );- },- },- );+ /**+ * Fetch orchestration for a topic's sub-threads. Hydrates the persisted list,+ * then revalidates; results land in `threadMaps` — read them through+ * `threadSelectors`, never from this hook.+ */+ useFetchThreads = (enable: boolean, topicId?: string): ReplicaSyncResult =>+ // The conversation's ThreadHydration and the sidebar list both sync the+ // active topic; collapse their mounts into one request.+ this.#threadList.useSync(topicId || null, {+ dedupingInterval: THREAD_LIST_DEDUPING_INTERVAL,+ enabled: enable,+ });++ /**+ * Seed a topic's persisted thread list before its first paint (route loader).+ * Best-effort: a miss is not an error, and the caller bounds the wait.+ */+ preHydrateThreads = async (topicId?: string): Promise<boolean> => {+ if (!topicId) return false;++ const scope = threadListResource.scope.get();+ this.#threadList.ensureScope(scope);++ return this.#threadList.hydrate(topicId, scope);};- refreshThreads = async (): Promise<void> => {- const topicId = this.#get().activeTopicId;+ /**+ * Refetch the active topic's threads after a write, whether or not a list is+ * mounted. Fire-and-forget callers rely on it never rejecting.+ */+ refreshThreads = async (topicId = this.#get().activeTopicId): Promise<void> => {if (!topicId) return;- return mutate(threadKeys.list(topicId));+ try {+ await this.#threadList.fetch(topicId, { fresh: true });+ } catch (error) {+ console.error('[refreshThreads] failed to refresh threads:', error);+ }};removeThread = async (id: string): Promise<void> => {- await threadService.removeThread(id);- await this.#get().refreshThreads();+ const topicId = this.#topicIdOfThread(id);++ if (topicId) {+ // Drops the row from the view and the persisted copy at once, so a failed+ // refetch (or a reload) cannot bring it back; rolls back if the server+ // rejects the delete.+ await this.#threadList.optimistic(+ topicId,+ (threads) => threads.filter((thread) => thread.id !== id),+ () => threadService.removeThread(id),+ );+ } else {+ await threadService.removeThread(id);+ }+ await this.#get().refreshThreads(topicId);if (this.#get().activeThreadId === id) {this.#set({ activeThreadId: undefined });@@ -267,22 +304,51 @@ export class ChatThreadActionImpl {};internal_updateThread = async (id: string, data: Partial<ThreadItem>): Promise<void> => {- this.#get().internal_dispatchThread({ type: 'updateThread', id, value: data });+ const topicId = this.#topicIdOfThread(id);+ if (!topicId) return;this.#get().internal_updateThreadLoading(id, true);- await threadService.updateThread(id, data);- await this.#get().refreshThreads();- this.#get().internal_updateThreadLoading(id, false);+ try {+ // Rolls back on its own when the server rejects the update.+ await this.#threadList.optimistic(+ topicId,+ (threads) => threadReducer(threads, { type: 'updateThread', id, value: data }),+ () => threadService.updateThread(id, data),+ );+ await this.#get().refreshThreads(topicId);+ } finally {+ this.#get().internal_updateThreadLoading(id, false);+ }};- internal_dispatchThread = (payload: ThreadDispatch, action?: any): void => {- const nextThreads = threadReducer(threadSelectors.currentTopicThreads(this.#get()), payload);- const nextMap = { ...this.#get().threadMaps, [this.#get().activeTopicId!]: nextThreads };+ /**+ * The topic whose list holds the thread — the one the user is looking at,+ * falling back to the active topic before any list has loaded.+ */+ #topicIdOfThread = (id: string): string | undefined => {+ const { activeTopicId, threadMaps } = this.#get();+ if (activeTopicId && threadMaps[activeTopicId]?.some((thread) => thread.id === id))+ return activeTopicId;++ const owner = Object.entries(threadMaps).find(([, threads]) =>+ threads?.some((thread) => thread.id === id),+ );- // no need to update map if is the same- if (isEqual(nextMap, this.#get().threadMaps)) return;+ return owner?.[0] ?? activeTopicId;+ };- this.#set({ threadMaps: nextMap }, false, action ?? n(`dispatchThread/${payload.type}`));+ /**+ * Transient, in-memory patch of the active topic's threads (e.g. the loading+ * title while a summary generates). Never persisted: confirmed writes go+ * through `internal_updateThread`.+ */+ internal_dispatchThread = (payload: ThreadDispatch, _action?: string): void => {+ const topicId = this.#get().activeTopicId;+ if (!topicId) return;++ this.#threadList.update(topicId, (threads) => threads && threadReducer(threads, payload), {+ persist: false,+ });};}diff --git a/src/store/chat/slices/thread/initialState.ts b/src/store/chat/slices/thread/initialState.tsindex 506113a4897..2179f261069 100644--- a/src/store/chat/slices/thread/initialState.ts+++ b/src/store/chat/slices/thread/initialState.ts@@ -1,6 +1,8 @@import { type IThreadType, type ThreadItem } from '@lobechat/types';import { ThreadType } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+export interface ChatThreadState {activeThreadId?: string;/**@@ -15,9 +17,13 @@ export interface ChatThreadState {startToForkThread?: boolean;threadInputMessage: string;+ threadListReplica: ReplicaState<ThreadItem[]>;threadLoadingIds: string[];+ /**+ * Threads by topic id, written only through the thread list replica. An+ * `undefined` entry means the topic's threads are not loaded yet.+ */threadMaps: Record<string, ThreadItem[]>;- threadsInit?: boolean;/*** when open thread creator, set the message id to it*/@@ -28,7 +34,7 @@ export const initialThreadState: ChatThreadState = {isCreatingThread: false,newThreadMode: ThreadType.Continuation,threadInputMessage: '',+ threadListReplica: createReplicaState<ThreadItem[]>(),threadLoadingIds: [],threadMaps: {},- threadsInit: false,};diff --git a/src/store/chat/slices/thread/projection.ts b/src/store/chat/slices/thread/projection.tsnew file mode 100644index 00000000000..124b6c54e25--- /dev/null+++ b/src/store/chat/slices/thread/projection.ts@@ -0,0 +1,23 @@+import type { ThreadItem } from '@lobechat/types';++import { defineReplica } from '@/libs/replica';++/**+ * Threads persisted for the topics the user opened most recently. Each topic is+ * one row, so this bounds how many rows a long history leaves in storage; the+ * topic on screen is pinned by its mounted `useSync`.+ */+export const MAX_PERSISTED_THREAD_LISTS = 100;++/**+ * Sub-threads of one topic (`threadMaps[topicId]`), so every existing selector+ * keeps reading the same place. A reload repaints the topic's thread list from+ * the local copy and revalidates it in the background.+ */+export const threadListResource = defineReplica<string, ThreadItem[]>({+ key: (topicId) => topicId,+ name: 'threadList',+ persist: { maxEntries: MAX_PERSISTED_THREAD_LISTS },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/chat/slices/thread/selectors/index.ts b/src/store/chat/slices/thread/selectors/index.tsindex dc9a76159b4..95848348123 100644--- a/src/store/chat/slices/thread/selectors/index.ts+++ b/src/store/chat/slices/thread/selectors/index.ts@@ -16,6 +16,29 @@ const currentTopicThreads = (s: ChatStoreState) => {return s.threadMaps[s.activeTopicId] || [];};+/**+ * Whether the active topic's thread list has a value to render — hydrated from+ * the local copy or fetched. With no active topic there is nothing to wait for.+ */+const isCurrentTopicThreadsLoaded = (s: ChatStoreState): boolean =>+ !s.activeTopicId || s.threadMaps[s.activeTopicId] !== undefined;++/**+ * The Portal's thread is missing from a list that was only restored from the+ * local copy. The snapshot may predate the thread, so this is still loading —+ * not "no such thread" — until the server answers.+ */+const isPortalThreadPending = (s: ChatStoreState): boolean => {+ const topicId = s.activeTopicId;+ if (!topicId || !s.portalThreadId) return false;++ const threads = s.threadMaps[topicId];+ if (threads === undefined) return true;+ if (threads.some((thread) => thread.id === s.portalThreadId)) return false;++ return s.threadListReplica?.entries[topicId]?.source === 'storage';+};+const currentPortalThread = (s: ChatStoreState): ThreadItem | undefined => {if (!s.portalThreadId) return undefined;@@ -199,6 +222,8 @@ export const threadSelectors = {getThreadsByTopic,hasThreadBySourceMsgId,isActiveThreadSubagent,+ isCurrentTopicThreadsLoaded,+ isPortalThreadPending,portalAIChats,portalAIChatsWithHistoryConfig,portalDisplayChatsString,