🤯 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(chat): improve message refresh cache consistency (#17023)
AmAzing-8e33877dfe00
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex d9ca42b03e6..5bf6ffadf9a 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -61,7 +61,7 @@"builtinCopilot": "Built-in Copilot","chatList.expandMessage": "Expand Message","chatList.longMessageDetail": "View Details",- "chatList.refreshing": "Fetching latest messages...",+ "chatList.refreshError": "Couldn't refresh messages","chatMode.agent": "Agent","chatMode.agentCap.env": "Runtime env","chatMode.agentCap.files": "File access",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex dcf92fa9fbf..1876b3f432a 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -61,7 +61,7 @@"builtinCopilot": "内置 Copilot","chatList.expandMessage": "展开消息","chatList.longMessageDetail": "查看详情",- "chatList.refreshing": "正在获取最新消息...",+ "chatList.refreshError": "未能刷新消息","chatMode.agent": "智能","chatMode.agentCap.env": "运行环境","chatMode.agentCap.files": "文件访问",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 17fce0b475c..80c6cd82bd0 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -69,7 +69,7 @@ export default {'builtinCopilot': 'Built-in Copilot','chatList.expandMessage': 'Expand Message','chatList.longMessageDetail': 'View Details',- 'chatList.refreshing': 'Fetching latest messages...',+ 'chatList.refreshError': "Couldn't refresh messages",'clearCurrentMessages': 'Clear current conversation messages','compressedHistory': 'Compressed History','compression.cancel': 'Uncompress',diff --git a/src/components/AsyncBoundary/index.test.tsx b/src/components/AsyncBoundary/index.test.tsxindex 28414417570..c901091c76d 100644--- a/src/components/AsyncBoundary/index.test.tsx+++ b/src/components/AsyncBoundary/index.test.tsx@@ -1,4 +1,4 @@-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';import AsyncBoundary from './index';@@ -127,4 +127,26 @@ describe('AsyncBoundary', () => {expect(screen.queryByRole('button')).not.toBeInTheDocument();expect(screen.queryByText('EMPTY_ONBOARDING')).not.toBeInTheDocument();});++ it.each(['inline', 'metric'] as const)(+ 'forwards Retry through the %s error variant',+ (errorVariant) => {+ const onRetry = vi.fn();++ render(+ <AsyncBoundary+ data={undefined}+ error={new Error('boom')}+ errorVariant={errorVariant}+ onRetry={onRetry}+ >+ {DATA}+ </AsyncBoundary>,+ );++ fireEvent.click(screen.getByRole('button'));++ expect(onRetry).toHaveBeenCalledTimes(1);+ },+ );});diff --git a/src/components/AsyncError/index.tsx b/src/components/AsyncError/index.tsxindex 5b352516647..c4351ae13c1 100644--- a/src/components/AsyncError/index.tsx+++ b/src/components/AsyncError/index.tsx@@ -31,6 +31,8 @@ export interface AsyncErrorProps {error?: unknown;/** Retry the same request (SWR `mutate` / query refetch). Hidden if absent. */onRetry?: () => void;+ /** Whether an explicit Retry action is currently in flight. */+ retrying?: boolean;/** Override the default title copy. */title?: ReactNode;variant?: AsyncErrorVariant;@@ -64,7 +66,7 @@ const styles = createStaticStyles(({ css }) => ({}));const AsyncError = memo<AsyncErrorProps>(- ({ variant = 'block', error, onRetry, title, description }) => {+ ({ variant = 'block', error, onRetry, retrying = false, title, description }) => {const { t } = useTranslation('error');const { status, retryable } = normalizeAsyncError(error);@@ -84,15 +86,15 @@ const AsyncError = memo<AsyncErrorProps>({t('asyncState.metricLabel')}</Text>{showRetry && (- <Text- aria-label={t('error.retry')}- role={'button'}- style={{ color: cssVar.colorPrimary, cursor: 'pointer' }}- tabIndex={0}+ <Button+ disabled={retrying}+ loading={retrying}+ size={'small'}+ type={'text'}onClick={onRetry}>{t('error.retry')}- </Text>+ </Button>)}</Flexbox>);@@ -107,14 +109,15 @@ const AsyncError = memo<AsyncErrorProps>({heading}</Text>{showRetry && (- <Text- role={'button'}- style={{ color: cssVar.colorPrimary, cursor: 'pointer' }}- tabIndex={0}+ <Button+ disabled={retrying}+ loading={retrying}+ size={'small'}+ type={'text'}onClick={onRetry}>{t('error.retry')}- </Text>+ </Button>)}</Flexbox>);@@ -142,7 +145,13 @@ const AsyncError = memo<AsyncErrorProps>(</Text></Flexbox>{showRetry && (- <Button icon={<Icon icon={RotateCwIcon} />} size={'small'} onClick={onRetry}>+ <Button+ disabled={retrying}+ icon={<Icon icon={RotateCwIcon} />}+ loading={retrying}+ size={'small'}+ onClick={onRetry}+ >{t('error.retry')}</Button>)}diff --git a/src/features/Conversation/ChatList/components/RefreshError.tsx b/src/features/Conversation/ChatList/components/RefreshError.tsxnew file mode 100644index 00000000000..d11fb1bc694--- /dev/null+++ b/src/features/Conversation/ChatList/components/RefreshError.tsx@@ -0,0 +1,53 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';++const styles = createStaticStyles(({ css }) => ({+ row: css`+ flex: none;++ width: 100%;+ min-height: 40px;+ padding-block: 4px;+ padding-inline: 12px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBgContainer};+ `,+}));++interface RefreshErrorProps {+ error: unknown;+ onRetry: () => void;+ retrying: boolean;+}++export const RefreshError = memo<RefreshErrorProps>(({ error, onRetry, retrying }) => {+ const { t } = useTranslation('chat');++ return (+ <Flexbox+ horizontal+ align={'center'}+ aria-live={'polite'}+ className={styles.row}+ justify={'center'}+ role={'status'}+ >+ <AsyncError+ error={error}+ retrying={retrying}+ title={t('chatList.refreshError')}+ variant={'inline'}+ onRetry={onRetry}+ />+ </Flexbox>+ );+});++RefreshError.displayName = 'ConversationRefreshError';diff --git a/src/features/Conversation/ChatList/components/RefreshingHint.tsx b/src/features/Conversation/ChatList/components/RefreshingHint.tsxdeleted file mode 100644index 88fe1b480f5..00000000000--- a/src/features/Conversation/ChatList/components/RefreshingHint.tsx+++ /dev/null@@ -1,49 +0,0 @@-'use client';--import { Flexbox } from '@lobehub/ui';-import { createStaticStyles } from 'antd-style';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';--const styles = createStaticStyles(({ css, cssVar }) => ({- container: css`- pointer-events: none;-- min-height: 16px;- padding-block: 0 24px;-- font-size: 12px;- line-height: 16px;- color: ${cssVar.colorTextTertiary};- `,- loader: css`- opacity: 0.58;- `,-}));--const RefreshingHint = memo(() => {- const { t } = useTranslation('chat');-- return (- <Flexbox- horizontal- align={'center'}- aria-live={'polite'}- className={styles.container}- gap={6}- justify={'center'}- role={'status'}- >- <span className={styles.loader}>- <NeuralNetworkLoading size={12} />- </span>- <span>{t('chatList.refreshing')}</span>- </Flexbox>- );-});--RefreshingHint.displayName = 'ConversationRefreshingHint';--export default RefreshingHint;diff --git a/src/features/Conversation/ChatList/hooks/useMessageRefreshError.test.ts b/src/features/Conversation/ChatList/hooks/useMessageRefreshError.test.tsnew file mode 100644index 00000000000..74775e6ef86--- /dev/null+++ b/src/features/Conversation/ChatList/hooks/useMessageRefreshError.test.ts@@ -0,0 +1,150 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useMessageRefreshError } from './useMessageRefreshError';++const deferred = () => {+ let resolve!: () => void;+ const promise = new Promise<void>((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+};++describe('useMessageRefreshError', () => {+ it('keeps the error stable during SWR automatic revalidation', async () => {+ const error = new Error('offline');+ const mutate = vi.fn(async () => undefined);+ const { result, rerender } = renderHook(+ ({ currentError, isValidating }) =>+ useMessageRefreshError({+ error: currentError,+ identity: 'topic-1',+ isValidating,+ mutate,+ }),+ { initialProps: { currentError: error as unknown, isValidating: false } },+ );++ expect(result.current.error).toBe(error);+ expect(result.current.isRetrying).toBe(false);++ rerender({ currentError: undefined, isValidating: true });+ expect(result.current.error).toBe(error);+ expect(result.current.isRetrying).toBe(false);+ expect(mutate).not.toHaveBeenCalled();++ rerender({ currentError: undefined, isValidating: false });+ await waitFor(() => expect(result.current.error).toBeUndefined());+ });++ it('tracks only an explicit Retry and prevents duplicate clicks', async () => {+ const pending = deferred();+ const mutate = vi.fn(() => pending.promise);+ const error = new Error('offline');+ const { result } = renderHook(() =>+ useMessageRefreshError({+ error,+ identity: 'topic-1',+ isValidating: true,+ mutate,+ }),+ );+ let retryPromise!: Promise<void>;++ act(() => {+ retryPromise = result.current.retry();+ void result.current.retry();+ });++ expect(result.current.isRetrying).toBe(true);+ expect(mutate).toHaveBeenCalledTimes(1);++ await act(async () => {+ pending.resolve();+ await retryPromise;+ });++ expect(result.current.isRetrying).toBe(false);+ });++ it('keeps a repeated Retry failure actionable', async () => {+ const retryError = new Error('still offline');+ const mutate = vi.fn().mockRejectedValue(retryError);+ const { result } = renderHook(() =>+ useMessageRefreshError({+ error: undefined,+ identity: 'topic-1',+ isValidating: false,+ mutate,+ }),+ );++ await act(async () => {+ await result.current.retry();+ });++ expect(result.current.error).toBe(retryError);+ expect(result.current.isRetrying).toBe(false);+ expect(mutate).toHaveBeenCalledTimes(1);+ });++ it('does not leak a retained error into a different message-list identity', () => {+ const error = new Error('topic 1 is offline');+ const mutate = vi.fn(async () => undefined);+ const { result, rerender } = renderHook(+ ({ currentError, identity }) =>+ useMessageRefreshError({+ error: currentError,+ identity,+ isValidating: false,+ mutate,+ }),+ { initialProps: { currentError: error as unknown, identity: 'topic-1' } },+ );++ expect(result.current.error).toBe(error);++ rerender({ currentError: undefined, identity: 'topic-2' });++ expect(result.current.error).toBeUndefined();+ expect(result.current.isRetrying).toBe(false);+ });++ it('ignores an old Retry failure after the message-list identity changes', async () => {+ let rejectRetry!: (error: Error) => void;+ const mutate = vi.fn(+ () =>+ new Promise<void>((_, reject) => {+ rejectRetry = reject;+ }),+ );+ const { result, rerender } = renderHook(+ ({ identity }) =>+ useMessageRefreshError({+ error: undefined,+ identity,+ isValidating: false,+ mutate,+ }),+ { initialProps: { identity: 'topic-1' } },+ );++ let retryPromise!: Promise<void>;+ act(() => {+ retryPromise = result.current.retry();+ });+ rerender({ identity: 'topic-2' });++ await act(async () => {+ rejectRetry(new Error('old topic failed'));+ await retryPromise;+ });++ expect(result.current.error).toBeUndefined();+ expect(result.current.isRetrying).toBe(false);+ });+});diff --git a/src/features/Conversation/ChatList/hooks/useMessageRefreshError.ts b/src/features/Conversation/ChatList/hooks/useMessageRefreshError.tsnew file mode 100644index 00000000000..242c4ba95a4--- /dev/null+++ b/src/features/Conversation/ChatList/hooks/useMessageRefreshError.ts@@ -0,0 +1,98 @@+import debug from 'debug';+import { useCallback, useEffect, useRef, useState } from 'react';++const log = debug('lobe-client:message-refresh');++interface UseMessageRefreshErrorOptions {+ error?: unknown;+ identity: string;+ isValidating: boolean;+ mutate: () => Promise<unknown>;+}++interface RetainedError {+ error?: unknown;+ identity: string;+}++interface RetryRequest {+ identity: string;+ token: symbol;+}++/**+ * Keep a refresh failure visible while SWR performs automatic revalidation,+ * and track only a user-triggered Retry as button progress. SWR's shared+ * `isValidating` flag cannot distinguish those two causes.+ */+export const useMessageRefreshError = ({+ error,+ identity,+ isValidating,+ mutate,+}: UseMessageRefreshErrorOptions) => {+ const [retainedError, setRetainedError] = useState<RetainedError>({ error, identity });+ const [retryingIdentity, setRetryingIdentity] = useState<string>();+ const activeIdentityRef = useRef(identity);+ const retryInFlightRef = useRef<RetryRequest | undefined>(undefined);+ const validationRef = useRef({ identity, isValidating });+ activeIdentityRef.current = identity;++ useEffect(() => {+ const previousValidation = validationRef.current;++ if (previousValidation.identity !== identity) {+ validationRef.current = { identity, isValidating };+ setRetainedError({ error, identity });+ return;+ }++ if (error !== undefined) {+ setRetainedError({ error, identity });+ } else if (+ previousValidation.isValidating &&+ !isValidating &&+ retryInFlightRef.current?.identity !== identity+ ) {+ // An automatic revalidation just settled without an error.+ setRetainedError({ error: undefined, identity });+ }+ validationRef.current = { identity, isValidating };+ }, [error, identity, isValidating]);++ const retry = useCallback(async () => {+ if (retryInFlightRef.current?.identity === identity) return;+ const request = { identity, token: Symbol(identity) };+ retryInFlightRef.current = request;+ setRetryingIdentity(identity);++ try {+ await mutate();+ if (activeIdentityRef.current === identity) {+ setRetainedError({ error: undefined, identity });+ }+ } catch (retryError) {+ if (activeIdentityRef.current === identity) {+ setRetainedError({ error: retryError, identity });+ }+ // The persistent error surface is the user feedback; keep a diagnostic+ // for production debugging without turning the rejected click into an+ // unhandled promise.+ log('Explicit message refresh retry failed: %O', retryError);+ } finally {+ if (retryInFlightRef.current?.token === request.token) {+ retryInFlightRef.current = undefined;+ setRetryingIdentity((current) => (current === identity ? undefined : current));+ }+ }+ }, [identity, mutate]);++ const retainedErrorForIdentity =+ retainedError.identity === identity ? retainedError.error : undefined;++ return {+ error: error ?? retainedErrorForIdentity,+ isRetrying: retryingIdentity === identity,+ retry,+ };+};diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex 2a56f53804e..ab6c94d011d 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -1,11 +1,13 @@'use client';+import { Flexbox } from '@lobehub/ui';import type { ReactNode } from 'react';-import { memo, useCallback, useMemo } from 'react';+import { memo, useCallback } from 'react';import AsyncError from '@/components/AsyncError';import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';import { useFetchNotebookDocuments } from '@/hooks/useFetchNotebookDocuments';+import { getMessageListCacheIdentity } from '@/services/message/cache';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';@@ -20,9 +22,11 @@ import type { WorkflowExpandLevelDefault } from '../Messages/AssistantGroup/compimport { MessageActionProvider } from '../Messages/Contexts/MessageActionProvider';import { dataSelectors, useConversationStore } from '../store';import AgentSignalReceiptList from './components/AgentSignalReceiptList';-import RefreshingHint from './components/RefreshingHint';+import { RefreshError } from './components/RefreshError';import VirtualizedList from './components/VirtualizedList';import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';+import { useMessageRefreshError } from './hooks/useMessageRefreshError';+import { resolveMessageListFeedback } from './resolveMessageListFeedback';export interface ChatListProps {/**@@ -95,6 +99,12 @@ const ChatList = memo<ChatListProps>(const isStreaming = useChatStore(operationSelectors.isAgentRuntimeRunningByContext(context));const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);const messagesSWR = useFetchMessages(context, { revalidateOnFocus: !isStreaming, skipFetch });+ const refreshError = useMessageRefreshError({+ error: messagesSWR.error,+ identity: getMessageListCacheIdentity(context),+ isValidating: messagesSWR.isValidating,+ mutate: messagesSWR.mutate,+ });const displayMessages = useConversationStore(dataSelectors.displayMessages);const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);const latestMessageId = displayMessageIds.at(-1);@@ -156,43 +166,37 @@ const ChatList = memo<ChatListProps>([displayMessageIds.length, defaultWorkflowExpandLevel, receiptsByAnchor],);const messagesInit = useConversationStore(dataSelectors.messagesInit);- // ConversationArea can render store-backed cached messages before SWR has local data.- const showRefreshingHint =- messagesInit && displayMessageIds.length > 0 && messagesSWR.isValidating && !isStreaming;-- const mergedFooterSlot = useMemo(() => {- if (!showRefreshingHint && !footerSlot) return;-- return (- <>- {showRefreshingHint && <RefreshingHint />}- {footerSlot}- </>- );- }, [footerSlot, showRefreshingHint]);// When topicId is null (new conversation), show welcome directly without waiting for fetch// because there's no server data to fetch - only local optimistic updates existconst isNewConversation = !context.topicId;+ const feedback = resolveMessageListFeedback({+ error: refreshError.error,+ isNewConversation,+ isStreaming,+ messagesInit,+ });- if (!messagesInit && !isNewConversation && messagesSWR.error && !messagesSWR.isLoading) {+ // `messagesInit` is the settled-data signal: [] is a valid loaded result.+ // A first-load failure owns the whole surface, while a background failure+ // must preserve either the messages or the welcome state below.+ if (feedback.showFirstLoadError) {return (<AsyncError- error={messagesSWR.error}+ error={refreshError.error}+ retrying={refreshError.isRetrying}variant={'page'}- onRetry={() => {- void messagesSWR.mutate();- }}+ onRetry={refreshError.retry}/>);}- if (!messagesInit && !isNewConversation) {+ if (feedback.showSkeleton) {return <SkeletonList />;}- if ((showWelcome || displayMessageIds.length === 0) && welcome) {- return (+ const content =+ (showWelcome || displayMessageIds.length === 0) && welcome ? (<WideScreenContainerstyle={{height: '100%',@@ -204,18 +208,30 @@ const ChatList = memo<ChatListProps>(>{welcome}</WideScreenContainer>+ ) : (+ <MessageActionProvider withSingletonActionsBar={!disableActionsBar}>+ <VirtualizedList+ dataSource={displayMessageIds}+ footerSlot={footerSlot}+ headerSlot={headerSlot}+ itemContent={itemContent ?? defaultItemContent}+ />+ </MessageActionProvider>);- }return (- <MessageActionProvider withSingletonActionsBar={!disableActionsBar}>- <VirtualizedList- dataSource={displayMessageIds}- footerSlot={mergedFooterSlot}- headerSlot={headerSlot}- itemContent={itemContent ?? defaultItemContent}- />- </MessageActionProvider>+ <Flexbox style={{ height: '100%', minHeight: 0 }}>+ <Flexbox flex={1} style={{ minHeight: 0 }}>+ {content}+ </Flexbox>+ {feedback.showBackgroundError && (+ <RefreshError+ error={refreshError.error}+ retrying={refreshError.isRetrying}+ onRetry={refreshError.retry}+ />+ )}+ </Flexbox>);},);diff --git a/src/features/Conversation/ChatList/resolveMessageListFeedback.test.ts b/src/features/Conversation/ChatList/resolveMessageListFeedback.test.tsnew file mode 100644index 00000000000..648ef076666--- /dev/null+++ b/src/features/Conversation/ChatList/resolveMessageListFeedback.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from 'vitest';++import { resolveMessageListFeedback } from './resolveMessageListFeedback';++describe('resolveMessageListFeedback', () => {+ it.each([+ {+ expected: {+ showBackgroundError: false,+ showFirstLoadError: false,+ showSkeleton: true,+ },+ name: 'first load pending',+ state: {+ error: undefined,+ isNewConversation: false,+ isStreaming: false,+ messagesInit: false,+ },+ },+ {+ expected: {+ showBackgroundError: false,+ showFirstLoadError: true,+ showSkeleton: false,+ },+ name: 'first load failed',+ state: {+ error: new Error('offline'),+ isNewConversation: false,+ isStreaming: false,+ messagesInit: false,+ },+ },+ {+ expected: {+ showBackgroundError: false,+ showFirstLoadError: false,+ showSkeleton: false,+ },+ name: 'settled list validating silently',+ state: { error: undefined, isNewConversation: false, isStreaming: false, messagesInit: true },+ },+ {+ expected: {+ showBackgroundError: true,+ showFirstLoadError: false,+ showSkeleton: false,+ },+ name: 'settled empty list failed in the background',+ state: {+ error: new Error('offline'),+ isNewConversation: false,+ isStreaming: false,+ messagesInit: true,+ },+ },+ {+ expected: {+ showBackgroundError: false,+ showFirstLoadError: false,+ showSkeleton: false,+ },+ name: 'streaming keeps its existing source of truth',+ state: {+ error: new Error('offline'),+ isNewConversation: false,+ isStreaming: true,+ messagesInit: true,+ },+ },+ {+ expected: {+ showBackgroundError: false,+ showFirstLoadError: false,+ showSkeleton: false,+ },+ name: 'new conversation remains on welcome',+ state: {+ error: undefined,+ isNewConversation: true,+ isStreaming: false,+ messagesInit: false,+ },+ },+ ])('$name', ({ expected, state }) => {+ expect(resolveMessageListFeedback(state)).toEqual(expected);+ });+});diff --git a/src/features/Conversation/ChatList/resolveMessageListFeedback.ts b/src/features/Conversation/ChatList/resolveMessageListFeedback.tsnew file mode 100644index 00000000000..c960e681af4--- /dev/null+++ b/src/features/Conversation/ChatList/resolveMessageListFeedback.ts@@ -0,0 +1,21 @@+interface ResolveMessageListFeedbackOptions {+ error?: unknown;+ isNewConversation: boolean;+ isStreaming: boolean;+ messagesInit: boolean;+}++export const resolveMessageListFeedback = ({+ error,+ isNewConversation,+ isStreaming,+ messagesInit,+}: ResolveMessageListFeedbackOptions) => {+ const hasError = error !== undefined && error !== null;++ return {+ showBackgroundError: messagesInit && hasError && !isStreaming,+ showFirstLoadError: !messagesInit && !isNewConversation && hasError,+ showSkeleton: !messagesInit && !isNewConversation && !hasError,+ };+};diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsxindex cfb7ff3f788..6d958aa28f5 100644--- a/src/features/Conversation/ConversationProvider.test.tsx+++ b/src/features/Conversation/ConversationProvider.test.tsx@@ -2,14 +2,127 @@* @vitest-environment happy-dom*/import type { ConversationContext, UIChatMessage } from '@lobechat/types';-import { render } from '@testing-library/react';-import { describe, expect, it } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import ChatList from './ChatList';import { ConversationProvider } from './ConversationProvider';import { dataSelectors, useConversationStore } from './store';+const chatListMocks = vi.hoisted(() => ({+ isStreaming: false,+ refreshError: {+ error: undefined as unknown,+ isRetrying: false,+ retry: vi.fn(),+ },+ swrMutate: vi.fn(),+ useFetchAgentConfig: vi.fn(),+}));++vi.mock('@lobehub/ui/base-ui', () => ({+ Button: ({+ children,+ disabled,+ onClick,+ }: {+ children?: ReactNode;+ disabled?: boolean;+ onClick?: () => void;+ }) => (+ <button disabled={disabled} onClick={onClick}>+ {children}+ </button>+ ),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/features/Conversation/ChatList/components/AgentSignalReceiptList', () => ({+ default: () => null,+}));++vi.mock('@/features/Conversation/ChatList/components/VirtualizedList', () => ({+ default: ({ dataSource }: { dataSource: string[] }) => (+ <div data-testid={'virtualized-list'}>{dataSource.join(',')}</div>+ ),+}));++vi.mock('@/features/Conversation/ChatList/hooks/useAgentSignalReceipts', () => ({+ useAgentSignalReceipts: () => ({ receiptsByAnchor: new Map() }),+}));++vi.mock('@/features/Conversation/ChatList/hooks/useMessageRefreshError', () => ({+ useMessageRefreshError: () => chatListMocks.refreshError,+}));++vi.mock('@/features/Conversation/components/SkeletonList', () => ({+ default: () => <div data-testid={'skeleton-list'} />,+}));++vi.mock('@/features/Conversation/Messages', () => ({+ default: ({ id }: { id: string }) => <div>{id}</div>,+}));++vi.mock('@/features/Conversation/Messages/Contexts/MessageActionProvider', () => ({+ MessageActionProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));++vi.mock('@/features/WideScreenContainer', () => ({+ default: ({ children }: { children?: ReactNode }) => (+ <div data-testid={'welcome'}>{children}</div>+ ),+}));++vi.mock('@/hooks/useFetchAvailableAgents', () => ({ useFetchAvailableAgents: vi.fn() }));+vi.mock('@/hooks/useFetchMemoryForTopic', () => ({ useFetchTopicMemories: vi.fn() }));+vi.mock('@/hooks/useFetchNotebookDocuments', () => ({ useFetchNotebookDocuments: vi.fn() }));++vi.mock('@/libs/swr', () => ({+ useClientDataSWRWithSync: () => ({+ data: undefined,+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: chatListMocks.swrMutate,+ }),+}));++vi.mock('@/libs/swr/useCacheScope', () => ({+ getCacheScope: () => 'user-1:personal',+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (+ selector: (state: { useFetchAgentConfig: typeof chatListMocks.useFetchAgentConfig }) => unknown,+ ) => selector({ useFetchAgentConfig: chatListMocks.useFetchAgentConfig }),+}));++vi.mock('@/store/chat', () => ({+ getChatStoreState: () => ({}),+ useChatStore: (selector: (state: { activeAgentId: string }) => unknown) =>+ selector({ activeAgentId: 'agt_old' }),+}));++vi.mock('@/store/chat/selectors', () => ({+ operationSelectors: {+ isAgentRuntimeRunningByContext: () => () => chatListMocks.isStreaming,+ },+}));++vi.mock('@/store/serverConfig', () => ({+ featureFlagsSelectors: vi.fn(),+ useServerConfigStore: () => ({ enableAgentSelfIteration: false }),+}));++vi.mock('@/store/user', () => ({ useUserStore: () => false }));+vi.mock('@/store/user/selectors', () => ({ authSelectors: {}, settingsSelectors: {} }));+const oldContext = {agentId: 'agt_old',threadId: null,@@ -57,7 +170,25 @@ const Probe = ({return null;};+const renderChatList = (messages?: UIChatMessage[]) =>+ render(+ <ConversationProvider+ context={oldContext}+ hasInitMessages={messages !== undefined}+ messages={messages}+ >+ <ChatList welcome={<div>WELCOME</div>} />+ </ConversationProvider>,+ );+describe('ConversationProvider', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ chatListMocks.isStreaming = false;+ chatListMocks.refreshError.error = undefined;+ chatListMocks.refreshError.isRetrying = false;+ });+it('does not expose the previous local conversation store after context changes', () => {const snapshots: Snapshot[] = [];@@ -81,4 +212,37 @@ describe('ConversationProvider', () => {expect(mismatchedNextContextSnapshots).toEqual([]);});++ it('renders the message skeleton before the first request settles', () => {+ renderChatList();++ expect(screen.getByTestId('skeleton-list')).toBeInTheDocument();+ });++ it('renders a retryable full-surface error when the first request fails', () => {+ chatListMocks.refreshError.error = new Error('offline');++ renderChatList();+ fireEvent.click(screen.getByRole('button', { name: 'error.retry' }));++ expect(chatListMocks.refreshError.retry).toHaveBeenCalledTimes(1);+ expect(screen.queryByTestId('skeleton-list')).not.toBeInTheDocument();+ });++ it('preserves a settled empty welcome while showing a retryable background error', () => {+ chatListMocks.refreshError.error = new Error('offline');++ renderChatList([]);+ fireEvent.click(screen.getByRole('button', { name: 'error.retry' }));++ expect(screen.getByText('WELCOME')).toBeInTheDocument();+ expect(screen.getByRole('status')).toBeInTheDocument();+ expect(chatListMocks.refreshError.retry).toHaveBeenCalledTimes(1);+ });++ it('renders a settled message list through the virtualized list', () => {+ renderChatList(oldMessages);++ expect(screen.getByTestId('virtualized-list')).toHaveTextContent('msg_old');+ });});diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex 31af9c230a4..303473652fb 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -4,6 +4,11 @@ import { describe, expect, it, vi } from 'vitest';import { useClientDataSWRWithSync } from '@/libs/swr';import { messageService } from '@/services/message';+import {+ clearMessageListClientCacheState,+ MESSAGE_LIST_VERIFICATION_INTERVAL,+ runMessageListQuery,+} from '@/services/message/cache';import { createStore } from '../../index';import { dataSelectors } from './selectors';@@ -538,6 +543,7 @@ describe('DataSlice', () => {describe('useFetchMessages', () => {beforeEach(() => {vi.clearAllMocks();+ clearMessageListClientCacheState();});it('should pass threadId to messageService.getMessages', async () => {@@ -567,6 +573,7 @@ describe('DataSlice', () => {await waitFor(() => {expect(messageService.getMessages).toHaveBeenCalledWith({agentId: 'test-session',+ groupId: null,threadId: 'test-thread',topicId: 'test-topic',});@@ -716,11 +723,34 @@ describe('DataSlice', () => {expect(swrKey[0]).toBe('message:list');expect(swrKey[1]).toEqual({agentId: 'test-session',- topicId: 'test-topic',+ groupId: null,threadId: 'test-thread',+ topicId: 'test-topic',});});+ it('skips switch-time revalidation after a successful server verification', async () => {+ const context = {+ agentId: 'test-session',+ topicId: 'test-topic',+ threadId: null,+ };+ await runMessageListQuery(context, async () => []);+ vi.mocked(messageService.getMessages).mockResolvedValue([]);++ const store = createStore({ context });+ store.getState().useFetchMessages(context);++ expect(vi.mocked(useClientDataSWRWithSync)).toHaveBeenCalledWith(+ expect.any(Array),+ expect.any(Function),+ expect.objectContaining({+ dedupingInterval: MESSAGE_LIST_VERIFICATION_INTERVAL,+ revalidateIfStale: false,+ }),+ );+ });+it('should pass groupId to messageService.getMessages for group chat', async () => {const mockMessages: UIChatMessage[] = [{diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex 82176554d4e..9e8395c6b0e 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -5,8 +5,12 @@ import { type SWRResponse } from 'swr';import { type StateCreator } from 'zustand/vanilla';import { useClientDataSWRWithSync } from '@/libs/swr';-import { messageKeys } from '@/libs/swr/keys';import { messageService } from '@/services/message';+import {+ getMessageListFetchPolicy,+ messageListKey,+ runMessageListQuery,+} from '@/services/message/cache';import { getChatStoreState } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -209,11 +213,15 @@ export const dataSlice: StateCreator<);return useClientDataSWRWithSync<UIChatMessage[]>(- shouldFetch ? messageKeys.list(context) : null,+ shouldFetch ? messageListKey(context) : null,- () => messageService.getMessages(context),+ () => runMessageListQuery(context, messageService.getMessages),{+ ...getMessageListFetchPolicy(context),...(revalidateOnFocus !== undefined && { revalidateOnFocus }),+ // Fresh in-memory or prefetched data can render without an immediate+ // switch-time revalidation. Missing cache data still fetches because+ // SWR always loads when `data` is undefined.onData: (data) => {if (!data) return;if (!context.topicId) return;diff --git a/src/libs/swr/cacheProvider.integration.test.tsx b/src/libs/swr/cacheProvider.integration.test.tsxindex 7bea0b09782..ea2e48d33ad 100644--- a/src/libs/swr/cacheProvider.integration.test.tsx+++ b/src/libs/swr/cacheProvider.integration.test.tsx@@ -8,15 +8,16 @@import { renderHook, waitFor } from '@testing-library/react';import type { PropsWithChildren } from 'react';import { createElement } from 'react';-import useSWR, { type Cache, SWRConfig } from 'swr';-import { afterEach, describe, expect, it } from 'vitest';+import useSWR, { type Cache, SWRConfig, unstable_serialize } from 'swr';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { localDataCache } from './localDataCache';+import { LEGACY_MESSAGE_CACHE_VERSION, messageKeys } from './keys';+import { buildLocalDataKey, localDataCache } from './localDataCache';import { createCacheProvider } from './localStorageProvider';-const SCOPE = 'integration-scope';+const SCOPE = 'integration-user:personal';-const makeProvider = () => {+const makeProvider = (idbPatterns = ['MSGS']) => {let resolveHydrated: () => void;const hydrated = new Promise<void>((r) => {resolveHydrated = r;@@ -24,7 +25,7 @@ const makeProvider = () => {const provider = createCacheProvider({debounceMs: 5,getScope: () => SCOPE,- idbPatterns: ['MSGS'],+ idbPatterns,localPatterns: [],onScopeHydrated: () => resolveHydrated(),});@@ -85,4 +86,39 @@ describe('local-first cache chain (SWR + tiered provider + IndexedDB)', () => {resolveSlow!(serverV2);await waitFor(() => expect(r2.result.current.data).toEqual(serverV2));});++ it('hydrates a migrated v1 message row through its canonical v2 key while offline', async () => {+ const legacyOriginalKey = [+ messageKeys.list.root,+ { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ ];+ const legacySerializedKey = unstable_serialize(legacyOriginalKey);+ const cachedMessages = [{ id: 'message-1', text: 'offline history' }];+ await localDataCache.set(+ buildLocalDataKey(SCOPE, legacySerializedKey),+ { _k: legacyOriginalKey, data: cachedMessages },+ '1.0.0',+ );++ const { provider } = makeProvider(['message:']);+ await provider.hydrateScope?.();+ const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });+ const fetcher = vi.fn(() => new Promise<never>(() => {}));+ const result = renderHook(() => useSWR(canonicalKey, fetcher), {+ wrapper: wrapper(provider),+ });++ expect(result.result.current.data).toEqual(cachedMessages);++ const persisted = await localDataCache.entriesByScope(SCOPE);+ expect(persisted.some((entry) => entry.key === legacySerializedKey)).toBe(false);+ expect(persisted).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({ _k: canonicalKey, data: cachedMessages }),+ key: unstable_serialize(canonicalKey),+ }),+ ]);+ result.unmount();+ });});diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 24ebab870be..679c0c98a91 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -41,13 +41,47 @@ interface LocalFilePreviewKeyParams {}// ---- message ------------------------------------------------------------+export interface MessageListQueryContext {+ agentId?: string | null;+ groupId?: string | null;+ threadId?: string | null;+ topicId?: string | null;+ topicShareId?: string;+}++export interface CanonicalMessageListContext {+ agentId: string | null;+ groupId: string | null;+ threadId: string | null;+ topicId: string | null;+ topicShareId?: string;+}+/**- * Message cache schema version. Baked into the message list key so a bump- * invalidates every persisted message cache entry (e.g. after a message shape- * change), without touching other domains. Increment when the cached- * `UIChatMessage[]` shape changes incompatibly.+ * Reduce every UI conversation variant to the fields understood by the+ * message-list server query. Keeping normalization beside the key definition+ * makes key equivalence a property of the registry rather than a caller+ * convention.*/-export const MESSAGE_CACHE_VERSION = 1;+export const normalizeMessageListQueryContext = (+ context: MessageListQueryContext,+): CanonicalMessageListContext => ({+ agentId: context.agentId ?? null,+ groupId: context.groupId ?? null,+ threadId: context.threadId ?? null,+ topicId: context.topicId ?? null,+ ...(context.topicShareId === undefined ? {} : { topicShareId: context.topicShareId }),+});++/** Previous persisted key schema, used only by the targeted v1 → v2 migration. */+export const LEGACY_MESSAGE_CACHE_VERSION = 1;++/**+ * Message cache key schema version. Version 2 canonicalizes query context, so+ * it requires a persisted-key migration even though `UIChatMessage[]` itself+ * did not change.+ */+export const MESSAGE_CACHE_VERSION = 2;export const messageKeys = {/**@@ -55,7 +89,11 @@ export const messageKeys = {* Shared by the conversation store and the chat store so a single fetch* serves both.*/- list: def('message:list', (context: unknown) => ['message:list', context, MESSAGE_CACHE_VERSION]),+ list: def('message:list', (context: MessageListQueryContext) => [+ 'message:list',+ normalizeMessageListQueryContext(context),+ MESSAGE_CACHE_VERSION,+ ]),};// ---- topic --------------------------------------------------------------diff --git a/src/libs/swr/localDataCache.test.ts b/src/libs/swr/localDataCache.test.tsindex 513829d168e..7d588e9194d 100644--- a/src/libs/swr/localDataCache.test.ts+++ b/src/libs/swr/localDataCache.test.ts@@ -59,6 +59,35 @@ describe('localDataCache', () => {expect(await localDataCache.get(key)).toBeUndefined();});+ it('atomically puts replacement rows before deleting their sources', async () => {+ const sourceKey = buildLocalDataKey(scope, 'source');+ const targetKey = buildLocalDataKey(scope, 'target');+ await localDataCache.set(sourceKey, { value: 'legacy' }, '1.0.0');++ await localDataCache.applyBatch({+ deleteKeys: [sourceKey],+ putEntries: [+ {+ data: { value: 'canonical' },+ key: targetKey,+ updatedAt: 123,+ version: '1.0.0',+ },+ ],+ });++ expect(await localDataCache.get(sourceKey)).toBeUndefined();+ expect(await localDataCache.get(targetKey)).toEqual({ value: 'canonical' });+ expect(await localDataCache.entriesByScope(scope)).toEqual([+ {+ data: { value: 'canonical' },+ key: 'target',+ updatedAt: 123,+ version: '1.0.0',+ },+ ]);+ });+it('clearScope removes only the given scope', async () => {const otherScope = 'user-other:personal';const keyA = buildLocalDataKey(scope, 'a');diff --git a/src/libs/swr/localDataCache.ts b/src/libs/swr/localDataCache.tsindex f2a94c9e39d..df12e78f24c 100644--- a/src/libs/swr/localDataCache.ts+++ b/src/libs/swr/localDataCache.ts@@ -36,6 +36,19 @@ export interface ScopeEntry {version?: string;}+export interface LocalDataCachePutEntry {+ data: unknown;+ /** Full composite key, including the identity scope prefix. */+ key: string;+ updatedAt: number;+ version?: string;+}++export interface LocalDataCacheBatch {+ deleteKeys: string[];+ putEntries: LocalDataCachePutEntry[];+}+const DB_NAME = 'lobehub-local-data';const STORE_NAME = 'cache';@@ -67,6 +80,32 @@ export const buildLocalDataKey = (scope: string, swrKey: unknown): string =>`${scopePrefix(scope)}${typeof swrKey === 'string' ? swrKey : JSON.stringify(swrKey)}`;export const localDataCache = {+ /**+ * Atomically replace persisted cache rows.+ *+ * Unlike the best-effort single-row helpers below, migration callers need a+ * rejection when the transaction cannot commit so they can keep and retry+ * the legacy source rows on the next boot.+ */+ applyBatch: async ({ deleteKeys, putEntries }: LocalDataCacheBatch): Promise<void> => {+ const table = await getTable();+ if (!table) return;++ await table.db.transaction('rw', table, async () => {+ if (putEntries.length > 0) {+ await table.bulkPut(+ putEntries.map((entry) => ({+ data: entry.data,+ key: entry.key,+ updatedAt: entry.updatedAt,+ version: entry.version,+ })),+ );+ }+ if (deleteKeys.length > 0) await table.bulkDelete(deleteKeys);+ });+ },+/*** Remove every entry belonging to a scope. Useful on logout / account switch.*/diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex b07ba106a7e..97287b65852 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -26,6 +26,7 @@import { bootTiming } from '@/libs/bootTiming';import { buildLocalDataKey, localDataCache } from './localDataCache';+import { migrateMessageListCache } from './migrations/messageListCache';import { isScopeTrusted } from './useCacheScope';interface CacheEntry<T = unknown> {@@ -259,6 +260,12 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedSlet succeeded = false;try {const entries = await localDataCache.entriesByScope(scope);+ const migratedEntries = await migrateMessageListCache({+ entries,+ onError,+ providerVersion: version,+ scope,+ });// The IndexedDB tier holds read-heavy / write-light business entities// (messages, topics, …): once written, a row rarely changes. We never drop// these by age — a stale row hydrates for an instant first paint and SWR's@@ -267,7 +274,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS// so legacy/unversioned rows (which the age check used to bound) are dropped// and a version bump still evicts everyone. TTL governs the localStorage// tier only (see `loadLocal`).- const valid = entries.filter((e) => e.version === version);+ const valid = migratedEntries.filter((e) => e.version === version);// Map may have changed scope while we awaited; only apply if still current.if (cacheMapInstance && getScope() === scope && hydrationEpoch === epoch) {cacheMapInstance.hydrate(valid.map((e) => [e.key, e.data]));diff --git a/src/libs/swr/migrations/messageListCache.test.ts b/src/libs/swr/migrations/messageListCache.test.tsnew file mode 100644index 00000000000..6222a8a153f--- /dev/null+++ b/src/libs/swr/migrations/messageListCache.test.ts@@ -0,0 +1,394 @@+import { unstable_serialize } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { LEGACY_MESSAGE_CACHE_VERSION, messageKeys } from '../keys';+import { buildLocalDataKey, localDataCache, type ScopeEntry } from '../localDataCache';+import { migrateMessageListCache } from './messageListCache';++const PROVIDER_VERSION = '1.0.0';+const PERSONAL_SCOPE = 'user-1:personal';+const WORKSPACE_SCOPE = 'user-1:workspace-1';+const OTHER_SCOPE = 'user-2:personal';++const messages = [+ {+ agentId: 'agent-1',+ content: 'hello',+ createdAt: 1,+ id: 'message-1',+ role: 'user',+ threadId: null,+ topicId: 'topic-1',+ updatedAt: 1,+ },+];++const createEntry = (+ originalKey: readonly unknown[],+ data = messages,+ updatedAt = 1,+): ScopeEntry => ({+ data: { _k: originalKey, data },+ key: unstable_serialize(originalKey),+ updatedAt,+ version: PROVIDER_VERSION,+});++const seedEntries = async (scope: string, entries: ScopeEntry[]) => {+ await localDataCache.applyBatch({+ deleteKeys: [],+ putEntries: entries.map((entry) => ({+ ...entry,+ key: buildLocalDataKey(scope, entry.key),+ })),+ });+};++describe('migrateMessageListCache', () => {+ beforeEach(async () => {+ await Promise.all(+ [PERSONAL_SCOPE, WORKSPACE_SCOPE, OTHER_SCOPE].map((scope) =>+ localDataCache.clearScope(scope),+ ),+ );+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('moves a v1 workspace row to the canonical v2 key before hydration', async () => {+ const legacyKey = [+ messageKeys.list.root,+ {+ agentId: 'agent-1',+ scope: 'main',+ threadId: null,+ topicId: 'topic-1',+ workspaceSlug: 'workspace',+ },+ LEGACY_MESSAGE_CACHE_VERSION,+ 'workspace-1',+ ];+ const legacyEntry = createEntry(legacyKey);+ await seedEntries(WORKSPACE_SCOPE, [legacyEntry]);++ const result = await migrateMessageListCache({+ entries: await localDataCache.entriesByScope(WORKSPACE_SCOPE),+ providerVersion: PROVIDER_VERSION,+ scope: WORKSPACE_SCOPE,+ });+ const canonicalKey = [+ ...messageKeys.list({ agentId: 'agent-1', threadId: null, topicId: 'topic-1' }),+ 'workspace-1',+ ];+ const canonicalSerializedKey = unstable_serialize(canonicalKey);++ expect(result).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({ _k: canonicalKey, data: messages }),+ key: canonicalSerializedKey,+ }),+ ]);++ const persisted = await localDataCache.entriesByScope(WORKSPACE_SCOPE);+ expect(persisted.some((entry) => entry.key === legacyEntry.key)).toBe(false);+ expect(persisted).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({ _k: canonicalKey, data: messages }),+ key: canonicalSerializedKey,+ }),+ ]);+ });++ it('collapses equivalent legacy variants and keeps the newest snapshot', async () => {+ const older = createEntry(+ [+ messageKeys.list.root,+ { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ ],+ [{ ...messages[0], content: 'old' }],+ 10,+ );+ const newer = createEntry(+ [+ messageKeys.list.root,+ {+ agentId: 'agent-1',+ documentId: undefined,+ threadId: null,+ topicId: 'topic-1',+ },+ LEGACY_MESSAGE_CACHE_VERSION,+ ],+ [{ ...messages[0], content: 'new' }],+ 20,+ );++ const result = await migrateMessageListCache({+ entries: [older, newer],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toHaveLength(1);+ expect(result[0]).toEqual(+ expect.objectContaining({+ data: expect.objectContaining({ data: [{ ...messages[0], content: 'new' }] }),+ updatedAt: 20,+ }),+ );+ });++ it('also migrates historical versionless and message:listLegacy rows', async () => {+ const versionless = createEntry([+ messageKeys.list.root,+ { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ ]);+ const listLegacy = createEntry(+ ['message:listLegacy', { agentId: 'agent-1', topicId: 'topic-1' }],+ [{ ...messages[0], content: 'newest legacy' }],+ 2,+ );++ const result = await migrateMessageListCache({+ entries: [versionless, listLegacy],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toHaveLength(1);+ expect(result[0].data).toEqual(+ expect.objectContaining({ data: [{ ...messages[0], content: 'newest legacy' }] }),+ );+ });++ it('leaves existing v2 and non-message rows unchanged on repeated hydration', async () => {+ const v2 = createEntry(messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' }));+ const topicEntry: ScopeEntry = {+ data: { _k: ['topic:list', 'agent-1'], data: [] },+ key: unstable_serialize(['topic:list', 'agent-1']),+ updatedAt: 2,+ version: PROVIDER_VERSION,+ };+ const batchSpy = vi.spyOn(localDataCache, 'applyBatch');++ const result = await migrateMessageListCache({+ entries: [v2, topicEntry],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toEqual([v2, topicEntry]);+ expect(batchSpy).not.toHaveBeenCalled();+ });++ it('keeps an original-key-less v2 empty snapshot written before a hook mounts', async () => {+ const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });+ const v2WithoutOriginalKey: ScopeEntry = {+ data: { data: [] },+ key: unstable_serialize(canonicalKey),+ updatedAt: 2,+ version: PROVIDER_VERSION,+ };+ const batchSpy = vi.spyOn(localDataCache, 'applyBatch');++ const result = await migrateMessageListCache({+ entries: [v2WithoutOriginalKey],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toEqual([v2WithoutOriginalKey]);+ expect(batchSpy).not.toHaveBeenCalled();+ });++ it('recovers an original-key-less message:listLegacy row from its message identities', async () => {+ const legacyKey = ['message:listLegacy', { agentId: 'agent-1', topicId: 'topic-1' }];+ const legacyWithoutOriginalKey: ScopeEntry = {+ data: { data: messages },+ key: unstable_serialize(legacyKey),+ updatedAt: 2,+ version: PROVIDER_VERSION,+ };++ const result = await migrateMessageListCache({+ entries: [legacyWithoutOriginalKey],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toEqual([+ expect.objectContaining({+ key: unstable_serialize(+ messageKeys.list({ agentId: 'agent-1', threadId: null, topicId: 'topic-1' }),+ ),+ }),+ ]);+ });++ it('recovers an original-key-less workspace row only when every message identity agrees', async () => {+ const legacyKey = [+ messageKeys.list.root,+ { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ 'workspace-1',+ ];+ const legacyWithoutOriginalKey: ScopeEntry = {+ data: { data: messages },+ key: unstable_serialize(legacyKey),+ updatedAt: 2,+ version: PROVIDER_VERSION,+ };++ const result = await migrateMessageListCache({+ entries: [legacyWithoutOriginalKey],+ providerVersion: PROVIDER_VERSION,+ scope: WORKSPACE_SCOPE,+ });++ expect(result).toEqual([+ expect.objectContaining({+ key: unstable_serialize([+ ...messageKeys.list({ agentId: 'agent-1', threadId: null, topicId: 'topic-1' }),+ 'workspace-1',+ ]),+ }),+ ]);+ });++ it('does not let a provider-version-mismatched v2 row block migration', async () => {+ const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });+ const staleV2 = {+ ...createEntry(canonicalKey, [{ ...messages[0], content: 'stale provider' }]),+ version: '0.0.1',+ };+ const legacy = createEntry(+ [+ messageKeys.list.root,+ { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ ],+ [{ ...messages[0], content: 'current provider' }],+ );++ const result = await migrateMessageListCache({+ entries: [staleV2, legacy],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(+ result.find(+ (entry) =>+ entry.key === unstable_serialize(canonicalKey) && entry.version === PROVIDER_VERSION,+ )?.data,+ ).toEqual(expect.objectContaining({ data: [{ ...messages[0], content: 'current provider' }] }));+ });++ it('drops malformed or ambiguous legacy rows instead of guessing a conversation', async () => {+ const malformed = createEntry([messageKeys.list.root, {}, LEGACY_MESSAGE_CACHE_VERSION]);+ const ambiguousKey = [+ messageKeys.list.root,+ { agentId: 'agent-1', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ ];+ const ambiguous: ScopeEntry = {+ data: {+ data: messages.map(({ threadId: _, ...message }) => message),+ },+ key: unstable_serialize(ambiguousKey),+ updatedAt: 2,+ version: PROVIDER_VERSION,+ };++ const result = await migrateMessageListCache({+ entries: [malformed, ambiguous],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toEqual([]);+ });++ it('does not derive a conversation when one row has a null identity', async () => {+ const legacyKey = [+ messageKeys.list.root,+ { agentId: 'agent-1', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ ];+ const mixedIdentity: ScopeEntry = {+ data: { data: [messages[0], { ...messages[0], agentId: null, id: 'message-2' }] },+ key: unstable_serialize(legacyKey),+ updatedAt: 2,+ version: PROVIDER_VERSION,+ };++ const result = await migrateMessageListCache({+ entries: [mixedIdentity],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toEqual([]);+ });++ it('keeps the source persisted when the atomic migration transaction fails', async () => {+ const legacyEntry = createEntry([+ messageKeys.list.root,+ { agentId: 'agent-1', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ ]);+ await seedEntries(PERSONAL_SCOPE, [legacyEntry]);+ const onError = vi.fn();+ const batchSpy = vi+ .spyOn(localDataCache, 'applyBatch')+ .mockRejectedValueOnce(new Error('write failed'));++ const result = await migrateMessageListCache({+ entries: await localDataCache.entriesByScope(PERSONAL_SCOPE),+ onError,+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(result).toEqual([+ expect.objectContaining({+ key: unstable_serialize(messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' })),+ }),+ ]);+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'write failed' }));+ expect(await localDataCache.entriesByScope(PERSONAL_SCOPE)).toEqual([legacyEntry]);++ batchSpy.mockRestore();+ const retried = await migrateMessageListCache({+ entries: await localDataCache.entriesByScope(PERSONAL_SCOPE),+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });+ const canonicalKey = messageKeys.list({ agentId: 'agent-1', topicId: 'topic-1' });++ expect(retried).toEqual([expect.objectContaining({ key: unstable_serialize(canonicalKey) })]);+ expect(await localDataCache.entriesByScope(PERSONAL_SCOPE)).toEqual([+ expect.objectContaining({ key: unstable_serialize(canonicalKey) }),+ ]);+ });++ it('never reads, merges, or deletes another identity scope', async () => {+ const otherEntry = createEntry([+ messageKeys.list.root,+ { agentId: 'agent-1', topicId: 'topic-1' },+ LEGACY_MESSAGE_CACHE_VERSION,+ ]);+ await seedEntries(OTHER_SCOPE, [otherEntry]);++ await migrateMessageListCache({+ entries: [],+ providerVersion: PROVIDER_VERSION,+ scope: PERSONAL_SCOPE,+ });++ expect(await localDataCache.entriesByScope(OTHER_SCOPE)).toEqual([otherEntry]);+ });+});diff --git a/src/libs/swr/migrations/messageListCache.ts b/src/libs/swr/migrations/messageListCache.tsnew file mode 100644index 00000000000..3c39b3fb872--- /dev/null+++ b/src/libs/swr/migrations/messageListCache.ts@@ -0,0 +1,249 @@+import { isRecord, pickString } from '@lobechat/utils/object';+import debug from 'debug';+import { unstable_serialize } from 'swr';++import {+ type CanonicalMessageListContext,+ LEGACY_MESSAGE_CACHE_VERSION,+ MESSAGE_CACHE_VERSION,+ messageKeys,+ type MessageListQueryContext,+ normalizeMessageListQueryContext,+} from '../keys';+import { buildLocalDataKey, localDataCache, type ScopeEntry } from '../localDataCache';++const log = debug('lobe-client:swr-message-migration');++const LEGACY_MESSAGE_LIST_ROOT = 'message:listLegacy';+const legacyMessageListRoots = [messageKeys.list.root, LEGACY_MESSAGE_LIST_ROOT];+const serializedMessageListPrefixes = legacyMessageListRoots.map((root) =>+ unstable_serialize([root]),+);++interface MigrationCandidate {+ source: ScopeEntry;+ target: ScopeEntry;+}++interface MigrateMessageListCacheOptions {+ entries: ScopeEntry[];+ onError?: (error: Error) => void;+ providerVersion: string;+ scope: string;+}++const nullableString = (value: unknown): string | null | undefined =>+ value === null ? null : pickString(value);++const readContext = (value: unknown): MessageListQueryContext | undefined => {+ if (!isRecord(value)) return;++ const context = {+ agentId: nullableString(value.agentId),+ groupId: nullableString(value.groupId),+ threadId: nullableString(value.threadId),+ topicId: nullableString(value.topicId),+ topicShareId: pickString(value.topicShareId),+ };++ if (!context.topicId && !context.topicShareId) return;+ if (!context.agentId && !context.groupId && !context.topicShareId) return;+ return context;+};++/**+ * Recover only personal-conversation coordinates that are encoded consistently+ * in every cached row. Group messages cannot recover the supervisor agent from+ * message authors, and an empty list contains no coordinates, so both remain+ * deliberately unrecoverable instead of being copied to a guessed key.+ */+const deriveContextFromMessages = (state: Record<PropertyKey, unknown>) => {+ if (!Array.isArray(state.data) || state.data.length === 0) return;+ if (!state.data.every(isRecord)) return;++ const rows = state.data;+ if (rows.some((row) => row.groupId !== undefined && row.groupId !== null)) return;+ if (+ !rows.every(+ (row) =>+ Object.hasOwn(row, 'agentId') &&+ Object.hasOwn(row, 'threadId') &&+ Object.hasOwn(row, 'topicId'),+ )+ ) {+ return;+ }++ const agentIds = new Set(rows.map((row) => row.agentId));+ const topicIds = new Set(rows.map((row) => row.topicId));+ const threadValues = new Set(rows.map((row) => row.threadId));++ if (agentIds.size !== 1 || topicIds.size !== 1 || threadValues.size !== 1) return;+ const [agentId] = agentIds;+ const [topicId] = topicIds;+ const [threadId] = threadValues;+ if (typeof agentId !== 'string' || !agentId) return;+ if (typeof topicId !== 'string' || !topicId) return;+ if (threadId !== null && typeof threadId !== 'string') return;++ return normalizeMessageListQueryContext({+ agentId,+ groupId: null,+ threadId,+ topicId,+ });+};++const workspaceSuffixFromScope = (scope: string): string[] => {+ const separatorIndex = scope.lastIndexOf(':');+ if (separatorIndex < 0) return [];+ const workspaceId = scope.slice(separatorIndex + 1);+ return workspaceId && workspaceId !== 'personal' ? [workspaceId] : [];+};++/**+ * SWR may persist data written through `mutate` before a hook mounts. Those+ * states legitimately have no `_k`, so identify an already-canonical v2 row+ * from its serialized version/workspace suffix before attempting legacy+ * recovery. Ambiguous rows must never be destructively treated as legacy.+ */+const isCanonicalSerializedMessageKey = (entry: ScopeEntry, scope: string): boolean => {+ if (+ !serializedMessageListPrefixes[0] ||+ !entry.key.startsWith(serializedMessageListPrefixes[0])+ ) {+ return false;+ }++ const versionSuffix = unstable_serialize([+ MESSAGE_CACHE_VERSION,+ ...workspaceSuffixFromScope(scope),+ ]).slice(1);++ return entry.key.endsWith(versionSuffix);+};++const buildCandidate = (entry: ScopeEntry, scope: string): MigrationCandidate | undefined => {+ if (!isRecord(entry.data)) return;++ const originalKey = entry.data._k;+ let context: CanonicalMessageListContext | undefined;+ let trailingKey: unknown[];++ if (Array.isArray(originalKey)) {+ const root = originalKey[0];+ const isVersionOne =+ root === messageKeys.list.root && originalKey[2] === LEGACY_MESSAGE_CACHE_VERSION;+ const isVersionlessList =+ root === messageKeys.list.root &&+ (originalKey.length === 2 || typeof originalKey[2] === 'string');+ const isLegacyList = root === LEGACY_MESSAGE_LIST_ROOT;+ if (!isVersionOne && !isVersionlessList && !isLegacyList) return;++ const legacyContext = readContext(originalKey[1]);+ if (!legacyContext) return;+ context = normalizeMessageListQueryContext(legacyContext);+ trailingKey = originalKey.slice(isVersionOne ? 3 : 2);+ } else {+ if (!serializedMessageListPrefixes.some((prefix) => entry.key.startsWith(prefix))) return;+ if (isCanonicalSerializedMessageKey(entry, scope)) return;+ context = deriveContextFromMessages(entry.data);+ if (!context) return;+ trailingKey = workspaceSuffixFromScope(scope);+ }++ const canonicalOriginalKey = [...messageKeys.list(context), ...trailingKey];+ const canonicalSerializedKey = unstable_serialize(canonicalOriginalKey);++ // An original-key-less row can already serialize to v2. Never rewrite it.+ if (canonicalSerializedKey === entry.key) return;++ return {+ source: entry,+ target: {+ ...entry,+ data: { ...entry.data, _k: canonicalOriginalKey },+ key: canonicalSerializedKey,+ },+ };+};++const isUnrecoverableLegacyMessageEntry = (entry: ScopeEntry, scope: string): boolean => {+ if (!serializedMessageListPrefixes.some((prefix) => entry.key.startsWith(prefix))) return false;+ if (!isRecord(entry.data)) return true;++ const originalKey = entry.data._k;+ if (Array.isArray(originalKey)) {+ const root = originalKey[0];+ const isVersionOne =+ root === messageKeys.list.root && originalKey[2] === LEGACY_MESSAGE_CACHE_VERSION;+ const isVersionlessList =+ root === messageKeys.list.root &&+ (originalKey.length === 2 || typeof originalKey[2] === 'string');+ const isLegacyList = root === LEGACY_MESSAGE_LIST_ROOT;+ return (isVersionOne || isVersionlessList || isLegacyList) && !readContext(originalKey[1]);+ }++ if (isCanonicalSerializedMessageKey(entry, scope)) return false;+ return !deriveContextFromMessages(entry.data);+};++/**+ * Canonicalize persisted message-list keys before the provider hydrates them.+ * The returned entries are safe to hydrate even when IndexedDB rejects the+ * transaction; the untouched legacy source then remains available for a retry+ * on the next boot.+ */+export const migrateMessageListCache = async ({+ entries,+ onError,+ providerVersion,+ scope,+}: MigrateMessageListCacheOptions): Promise<ScopeEntry[]> => {+ const currentVersionEntries = entries.filter((entry) => entry.version === providerVersion);+ const candidates = currentVersionEntries+ .map((entry) => buildCandidate(entry, scope))+ .filter((candidate): candidate is MigrationCandidate => candidate !== undefined);+ const candidateSources = new Set(candidates.map(({ source }) => source.key));+ const unrecoverable = currentVersionEntries.filter(+ (entry) => !candidateSources.has(entry.key) && isUnrecoverableLegacyMessageEntry(entry, scope),+ );+ const removedKeys = new Set([...candidateSources, ...unrecoverable.map((entry) => entry.key)]);++ const retained = entries.filter((entry) => !removedKeys.has(entry.key));+ const retainedKeys = new Set(+ retained.filter((entry) => entry.version === providerVersion).map((entry) => entry.key),+ );+ const newestByTarget = new Map<string, ScopeEntry>();++ for (const { target } of candidates) {+ if (retainedKeys.has(target.key)) continue;+ const current = newestByTarget.get(target.key);+ if (!current || target.updatedAt > current.updatedAt) newestByTarget.set(target.key, target);+ }++ const migratedEntries = [...newestByTarget.values()];+ const hydratedEntries = [...retained, ...migratedEntries];++ if (removedKeys.size === 0 && migratedEntries.length === 0) return hydratedEntries;++ try {+ await localDataCache.applyBatch({+ deleteKeys: [...removedKeys].map((key) => buildLocalDataKey(scope, key)),+ putEntries: migratedEntries.map((entry) => ({+ ...entry,+ key: buildLocalDataKey(scope, entry.key),+ })),+ });+ } catch (cause) {+ const error = cause instanceof Error ? cause : new Error(String(cause));+ log('Message cache migration will retry after transaction failure: %O', error);+ onError?.(error);+ }++ if (unrecoverable.length > 0) {+ log('Excluded %d unrecoverable legacy message cache rows from hydration', unrecoverable.length);+ }++ return hydratedEntries;+};diff --git a/src/services/message/cache.test.ts b/src/services/message/cache.test.tsnew file mode 100644index 00000000000..7fe79a545e7--- /dev/null+++ b/src/services/message/cache.test.ts@@ -0,0 +1,247 @@+import type { UIChatMessage } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { MESSAGE_CACHE_VERSION } from '@/libs/swr/keys';++import {+ clearMessageListClientCacheState,+ getMessageListFetchPolicy,+ invalidateMessageListClientState,+ isMessageListServerVerified,+ MESSAGE_LIST_VERIFICATION_INTERVAL,+ messageListKey,+ runMessageListQuery,+} from './cache';++const getCacheScopeMock = vi.hoisted(() => vi.fn(() => 'user-1:personal'));++vi.mock('@/libs/swr/useCacheScope', () => ({+ getCacheScope: getCacheScopeMock,+}));++const context = { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' };+const messages = [+ { content: 'hello', createdAt: 1, id: 'message-1', role: 'user', updatedAt: 1 },+] as UIChatMessage[];++const deferred = <T>() => {+ let reject!: (reason?: unknown) => void;+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, reject, resolve };+};++beforeEach(() => {+ clearMessageListClientCacheState();+ getCacheScopeMock.mockReturnValue('user-1:personal');+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('message list client cache', () => {+ it('normalizes equivalent UI contexts to one canonical v2 SWR key', () => {+ const conversationContext = {+ agentId: 'agent-1',+ documentId: undefined,+ scope: 'main',+ threadId: null,+ topicId: 'topic-1',+ workspaceSlug: 'workspace',+ };++ expect(messageListKey(context)).toEqual(messageListKey(conversationContext));+ expect(messageListKey(conversationContext)).toEqual([+ 'message:list',+ {+ agentId: 'agent-1',+ groupId: null,+ threadId: null,+ topicId: 'topic-1',+ },+ MESSAGE_CACHE_VERSION,+ ]);+ });++ it('marks only a successful server query verified for thirty seconds', async () => {+ vi.spyOn(Date, 'now').mockReturnValue(1000);+ const query = vi.fn().mockResolvedValue(messages);+ await expect(runMessageListQuery(context, query)).resolves.toBe(messages);+ const verifiedAt = 1000;++ expect(+ isMessageListServerVerified(context, verifiedAt + MESSAGE_LIST_VERIFICATION_INTERVAL - 1),+ ).toBe(true);+ expect(getMessageListFetchPolicy(context)).toEqual({+ dedupingInterval: MESSAGE_LIST_VERIFICATION_INTERVAL,+ revalidateIfStale: false,+ });+ expect(+ isMessageListServerVerified(context, verifiedAt + MESSAGE_LIST_VERIFICATION_INTERVAL),+ ).toBe(false);+ });++ it('treats a successful empty server result as verified', async () => {+ await expect(runMessageListQuery(context, async () => [])).resolves.toEqual([]);+ expect(isMessageListServerVerified(context)).toBe(true);+ });++ it('clears prior verification when a real revalidation fails', async () => {+ await runMessageListQuery(context, async () => messages);+ expect(isMessageListServerVerified(context)).toBe(true);++ await expect(+ runMessageListQuery(context, async () => {+ throw new Error('offline');+ }),+ ).rejects.toThrow('offline');++ expect(isMessageListServerVerified(context)).toBe(false);+ expect(getMessageListFetchPolicy(context).revalidateIfStale).toBe(true);+ });++ it('isolates verification and in-flight requests by identity cache scope', async () => {+ const firstScope = deferred<UIChatMessage[]>();+ const secondScope = deferred<UIChatMessage[]>();+ const query = vi+ .fn()+ .mockImplementationOnce(() => firstScope.promise)+ .mockImplementationOnce(() => secondScope.promise);++ const first = runMessageListQuery(context, query);+ await Promise.resolve();+ getCacheScopeMock.mockReturnValue('user-1:workspace-2');+ const second = runMessageListQuery(context, query);+ await Promise.resolve();++ expect(query).toHaveBeenCalledTimes(2);+ secondScope.resolve(messages);+ await expect(second).resolves.toBe(messages);+ expect(isMessageListServerVerified(context)).toBe(true);++ getCacheScopeMock.mockReturnValue('user-1:personal');+ expect(isMessageListServerVerified(context)).toBe(false);+ firstScope.resolve(messages);+ await expect(first).resolves.toBe(messages);+ expect(isMessageListServerVerified(context)).toBe(true);+ });++ it('shares one in-flight request across equivalent callers', async () => {+ const pending = deferred<UIChatMessage[]>();+ const query = vi.fn(() => pending.promise);++ const first = runMessageListQuery(context, query);+ const second = runMessageListQuery(+ { agentId: 'agent-1', threadId: null, topicId: 'topic-1' },+ query,+ );++ await Promise.resolve();+ expect(query).toHaveBeenCalledTimes(1);++ pending.resolve(messages);+ await expect(first).resolves.toBe(messages);+ await expect(second).resolves.toBe(messages);+ });++ it('invalidates verification even when no subscriber starts a replacement request', async () => {+ await runMessageListQuery(context, async () => messages);+ expect(isMessageListServerVerified(context)).toBe(true);++ invalidateMessageListClientState((candidate) => candidate.topicId === 'topic-1');++ expect(isMessageListServerVerified(context)).toBe(false);+ expect(getMessageListFetchPolicy(context).revalidateIfStale).toBe(true);+ });++ it('routes an invalidated in-flight caller through the current generation', async () => {+ const oldRequest = deferred<UIChatMessage[]>();+ const currentRequest = deferred<UIChatMessage[]>();+ const query = vi+ .fn()+ .mockImplementationOnce(() => oldRequest.promise)+ .mockImplementationOnce(() => currentRequest.promise);+ const oldMessages = [{ ...messages[0], content: 'old' }];+ const currentMessages = [{ ...messages[0], content: 'current' }];++ const first = runMessageListQuery(context, query);+ await Promise.resolve();+ invalidateMessageListClientState((candidate) => candidate.topicId === 'topic-1');+ const current = runMessageListQuery(context, query);+ await Promise.resolve();++ // Let the current generation finish before the invalidated request. The+ // late request must reuse this settled result instead of starting a third+ // query or publishing its obsolete snapshot.+ currentRequest.resolve(currentMessages);+ await expect(current).resolves.toEqual(currentMessages);+ oldRequest.resolve(oldMessages);++ await expect(first).resolves.toEqual(currentMessages);+ expect(query).toHaveBeenCalledTimes(2);+ expect(isMessageListServerVerified(context)).toBe(true);+ });++ it('replaces an invalidated request even when the old generation fails', async () => {+ const oldRequest = deferred<UIChatMessage[]>();+ const currentRequest = deferred<UIChatMessage[]>();+ const query = vi+ .fn()+ .mockImplementationOnce(() => oldRequest.promise)+ .mockImplementationOnce(() => currentRequest.promise);++ const first = runMessageListQuery(context, query);+ await Promise.resolve();+ invalidateMessageListClientState((candidate) => candidate.topicId === 'topic-1');+ oldRequest.reject(new Error('obsolete failure'));++ await vi.waitFor(() => expect(query).toHaveBeenCalledTimes(2));+ currentRequest.resolve(messages);+ await expect(first).resolves.toBe(messages);+ expect(isMessageListServerVerified(context)).toBe(true);+ });++ it('starts a new retry after a retained current-generation request failed', async () => {+ const oldRequest = deferred<UIChatMessage[]>();+ const failedCurrentRequest = deferred<UIChatMessage[]>();+ const retryRequest = deferred<UIChatMessage[]>();+ const query = vi+ .fn()+ .mockImplementationOnce(() => oldRequest.promise)+ .mockImplementationOnce(() => failedCurrentRequest.promise)+ .mockImplementationOnce(() => retryRequest.promise);++ const oldCaller = runMessageListQuery(context, query);+ await Promise.resolve();+ invalidateMessageListClientState((candidate) => candidate.topicId === 'topic-1');+ const currentCaller = runMessageListQuery(context, query);+ await Promise.resolve();+ failedCurrentRequest.reject(new Error('current failure'));+ await expect(currentCaller).rejects.toThrow('current failure');++ const retryCaller = runMessageListQuery(context, query);+ await vi.waitFor(() => expect(query).toHaveBeenCalledTimes(3));+ retryRequest.resolve(messages);+ await expect(retryCaller).resolves.toBe(messages);++ oldRequest.resolve([{ ...messages[0], content: 'obsolete' }]);+ await expect(oldCaller).resolves.toBe(messages);+ expect(isMessageListServerVerified(context)).toBe(true);+ });++ it('prunes the oldest settled verification state after the client cache reaches its limit', async () => {+ for (let index = 0; index <= 500; index += 1) {+ await runMessageListQuery(+ { agentId: 'agent-1', topicId: `topic-${index}` },+ async () => messages,+ );+ }++ expect(isMessageListServerVerified({ agentId: 'agent-1', topicId: 'topic-0' })).toBe(false);+ expect(isMessageListServerVerified({ agentId: 'agent-1', topicId: 'topic-500' })).toBe(true);+ });+});diff --git a/src/services/message/cache.ts b/src/services/message/cache.tsnew file mode 100644index 00000000000..b8244255eb3--- /dev/null+++ b/src/services/message/cache.ts@@ -0,0 +1,192 @@+import type { UIChatMessage } from '@lobechat/types';++import {+ type CanonicalMessageListContext,+ messageKeys,+ type MessageListQueryContext,+ normalizeMessageListQueryContext,+} from '@/libs/swr/keys';+import { getCacheScope } from '@/libs/swr/useCacheScope';++export const MESSAGE_LIST_VERIFICATION_INTERVAL = 30_000;++const MAX_MESSAGE_LIST_CLIENT_STATES = 500;++interface ActiveMessageListRequest {+ generation: number;+ promise: Promise<UIChatMessage[]>;+ settled: boolean;+}++interface MessageListClientState {+ activeRequestGenerations: Set<number>;+ cacheScope: string;+ context: CanonicalMessageListContext;+ currentRequest?: ActiveMessageListRequest;+ generation: number;+ identity: string;+ verifiedAt?: number;+}++const messageListClientStates = new Map<string, MessageListClientState>();++export const messageListKey = (context: MessageListQueryContext) => messageKeys.list(context);++export const getMessageListCacheIdentity = (+ context: MessageListQueryContext,+ cacheScope = getCacheScope(),+) => `${cacheScope}:${JSON.stringify(normalizeMessageListQueryContext(context))}`;++const touchState = (state: MessageListClientState) => {+ messageListClientStates.delete(state.identity);+ messageListClientStates.set(state.identity, state);+};++const activeRequestCount = (state: MessageListClientState) => state.activeRequestGenerations.size;++const hasOlderActiveRequest = (state: MessageListClientState, generation: number) =>+ [...state.activeRequestGenerations].some((activeGeneration) => activeGeneration < generation);++const pruneClientStates = () => {+ while (messageListClientStates.size > MAX_MESSAGE_LIST_CLIENT_STATES) {+ const removable = [...messageListClientStates.entries()].find(+ ([, state]) => activeRequestCount(state) === 0,+ );+ if (!removable) return;+ messageListClientStates.delete(removable[0]);+ }+};++const getOrCreateState = (+ context: MessageListQueryContext,+ cacheScope = getCacheScope(),+): MessageListClientState => {+ const normalizedContext = normalizeMessageListQueryContext(context);+ const identity = getMessageListCacheIdentity(normalizedContext, cacheScope);+ const existing = messageListClientStates.get(identity);+ if (existing) return existing;++ const state: MessageListClientState = {+ activeRequestGenerations: new Set(),+ cacheScope,+ context: normalizedContext,+ generation: 0,+ identity,+ };+ messageListClientStates.set(identity, state);+ pruneClientStates();+ return state;+};++export const isMessageListServerVerified = (context: MessageListQueryContext, now = Date.now()) => {+ const identity = getMessageListCacheIdentity(context);+ const state = messageListClientStates.get(identity);+ if (state?.verifiedAt === undefined) return false;++ const age = now - state.verifiedAt;+ if (age >= 0 && age < MESSAGE_LIST_VERIFICATION_INTERVAL) return true;++ state.verifiedAt = undefined;+ if (activeRequestCount(state) === 0) messageListClientStates.delete(identity);+ return false;+};++export const getMessageListFetchPolicy = (context: MessageListQueryContext) => ({+ dedupingInterval: MESSAGE_LIST_VERIFICATION_INTERVAL,+ revalidateIfStale: !isMessageListServerVerified(context),+});++type MessageListQuery = (context: CanonicalMessageListContext) => Promise<UIChatMessage[]>;++const startCurrentGenerationQuery = (+ state: MessageListClientState,+ query: MessageListQuery,+ reuseSettledRequest = false,+): Promise<UIChatMessage[]> => {+ const activeRequest = state.currentRequest;+ if (+ activeRequest?.generation === state.generation &&+ (!activeRequest.settled || reuseSettledRequest)+ ) {+ return activeRequest.promise;+ }++ // A verification window describes the last successful server snapshot. Once+ // a real query begins, failure must leave this identity eligible for retry.+ state.verifiedAt = undefined;+ const requestGeneration = state.generation;+ state.activeRequestGenerations.add(requestGeneration);++ const request: Promise<UIChatMessage[]> = Promise.resolve()+ .then(async () => {+ let messages: UIChatMessage[];+ try {+ messages = await query(state.context);+ } catch (error) {+ if (state.generation !== requestGeneration) {+ return startCurrentGenerationQuery(state, query, true);+ }+ throw error;+ }++ // Explicit invalidation won while this request was in flight. Resolve+ // every waiter through the current generation instead of publishing the+ // obsolete snapshot or restoring its verification timestamp.+ if (state.generation !== requestGeneration) {+ return startCurrentGenerationQuery(state, query, true);+ }++ state.verifiedAt = Date.now();+ touchState(state);+ pruneClientStates();+ return messages;+ })+ .finally(() => {+ state.activeRequestGenerations.delete(requestGeneration);++ if (state.currentRequest?.promise === request) state.currentRequest.settled = true;+ if (+ state.currentRequest?.settled &&+ !hasOlderActiveRequest(state, state.currentRequest.generation)+ ) {+ state.currentRequest = undefined;+ }+ if (activeRequestCount(state) === 0 && state.verifiedAt === undefined) {+ messageListClientStates.delete(state.identity);+ }+ });++ state.currentRequest = { generation: requestGeneration, promise: request, settled: false };+ return request;+};++/**+ * Coordinate one server query per identity scope, canonical context, and+ * request generation. Direct MessageService callers intentionally stay outside+ * this client-cache policy.+ */+export const runMessageListQuery = (+ context: MessageListQueryContext,+ query: MessageListQuery,+): Promise<UIChatMessage[]> => startCurrentGenerationQuery(getOrCreateState(context), query);++/**+ * Synchronously invalidate verification and advance the request generation for+ * every known matching query in the current identity scope. This must run+ * before SWR mutate so a no-subscriber refresh still forces the next mount to+ * verify with the server.+ */+export const invalidateMessageListClientState = (+ predicate: (context: CanonicalMessageListContext) => boolean,+ cacheScope = getCacheScope(),+): void => {+ for (const state of messageListClientStates.values()) {+ if (state.cacheScope !== cacheScope || !predicate(state.context)) continue;+ state.generation += 1;+ state.verifiedAt = undefined;+ }+};++export const clearMessageListClientCacheState = () => {+ messageListClientStates.clear();+};diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex 2ee82faccad..6f9901e932d 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -31,6 +31,14 @@ export interface MessageQueryContext {topicShareId?: string;}+interface MessageReadQueryContext {+ agentId?: string | null;+ groupId?: string | null;+ threadId?: string | null;+ topicId?: string | null;+ topicShareId?: string;+}+export type MessageBatchOperation =| {message: CreateMessageParams;@@ -76,7 +84,7 @@ export class MessageService {return lambdaClient.message.createMessage.mutate(params as any);};- getMessages = async (params: MessageQueryContext): Promise<UIChatMessage[]> => {+ getMessages = async (params: MessageReadQueryContext): Promise<UIChatMessage[]> => {const data = await lambdaClient.message.getMessages.query(params);return data as unknown as UIChatMessage[];diff --git a/src/services/message/server.test.ts b/src/services/message/server.test.tsindex 79c6d763860..61ed5b2edba 100644--- a/src/services/message/server.test.ts+++ b/src/services/message/server.test.ts@@ -15,6 +15,35 @@ vi.mock('@/libs/trpc/client', () => ({}));describe('MessageService', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('getMessages', () => {+ const service = new MessageService();++ it('passes read parameters through without applying client cache policy', async () => {+ vi.mocked(lambdaClient.message.getMessages.query).mockResolvedValue([]);+ const params = {+ agentId: 'agent-1',+ topicId: 'topic-1',+ };++ await service.getMessages(params);++ expect(lambdaClient.message.getMessages.query).toHaveBeenCalledWith(params);+ });++ it('keeps independent service reads available to strong-consistency callers', async () => {+ vi.mocked(lambdaClient.message.getMessages.query).mockResolvedValue([]);+ const context = { agentId: 'agent-1', topicId: 'topic-1' };++ await Promise.all([service.getMessages(context), service.getMessages(context)]);++ expect(lambdaClient.message.getMessages.query).toHaveBeenCalledTimes(2);+ });+ });+describe('createMessage', () => {const service = new MessageService();diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.tsindex 1862cf15161..6fd29d92998 100644--- a/src/store/chat/slices/message/action.test.ts+++ b/src/store/chat/slices/message/action.test.ts@@ -5,8 +5,14 @@ import { act, renderHook } from '@testing-library/react';import { type Mock } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { mutate } from '@/libs/swr';+import { mutate, useClientDataSWRWithSync } from '@/libs/swr';import { messageService } from '@/services/message';+import {+ clearMessageListClientCacheState,+ isMessageListServerVerified,+ messageListKey,+ runMessageListQuery,+} from '@/services/message/cache';import { topicService } from '@/services/topic';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -18,6 +24,7 @@ vi.mock('@/libs/swr', async () => {return {...actual,mutate: vi.fn(),+ useClientDataSWRWithSync: vi.fn(),};});@@ -51,6 +58,7 @@ vi.mock('@/services/topic', () => ({}));const realRefreshMessages = useChatStore.getState().refreshMessages;+const realRevalidateMessages = useChatStore.getState().revalidateMessages;// Mock stateconst mockState = {activeAgentId: 'session-id',@@ -64,6 +72,7 @@ const mockState = {beforeEach(() => {vi.clearAllMocks();+ clearMessageListClientCacheState();useChatStore.setState(mockState, false);});@@ -594,12 +603,15 @@ describe('chatMessage actions', () => {});expect(clearSpy).toHaveBeenCalled();- expect(result.current.refreshMessages).toHaveBeenCalled();+ expect(messageService.removeMessagesByAssistant).toHaveBeenCalledWith(+ mockState.activeAgentId,+ mockState.activeTopicId,+ );expect(result.current.refreshTopic).toHaveBeenCalled();expect(switchTopicSpy).toHaveBeenCalled();});- it('should remove messages from the active session and topic, then refresh topics and messages', async () => {+ it('should remove messages from the active session and topic, then refresh topics', async () => {const { result } = renderHook(() => useChatStore());const switchTopicSpy = vi.spyOn(result.current, 'switchTopic');const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');@@ -608,7 +620,6 @@ describe('chatMessage actions', () => {await result.current.clearMessage();});- expect(mockState.refreshMessages).toHaveBeenCalled();expect(refreshTopicSpy).toHaveBeenCalled();expect(switchTopicSpy).toHaveBeenCalled();@@ -627,7 +638,6 @@ describe('chatMessage actions', () => {expect(mockState.activeTopicId).not.toBeUndefined(); // 确保在测试前 activeTopicId 存在expect(refreshTopicSpy).toHaveBeenCalled();- expect(mockState.refreshMessages).toHaveBeenCalled();expect(topicService.removeTopic).toHaveBeenCalledWith(mockState.activeTopicId);expect(switchTopicSpy).toHaveBeenCalled();});@@ -756,19 +766,22 @@ describe('chatMessage actions', () => {const { result } = renderHook(() => useChatStore());const activeAgentId = useChatStore.getState().activeAgentId;const activeTopicId = useChatStore.getState().activeTopicId;+ const context = { agentId: activeAgentId, topicId: activeTopicId };+ await runMessageListQuery(context, async () => []);+ expect(isMessageListServerVerified(context)).toBe(true);await act(async () => {await result.current.refreshMessages();});+ expect(isMessageListServerVerified(context)).toBe(false);+// refreshMessages now mutates with a single matcher targeting the// accurate `message:list` key for this agent+topic.expect(mutate).toHaveBeenCalledTimes(1);const matcher = (mutate as any).mock.calls[0][0];expect(typeof matcher).toBe('function');- expect(matcher(['message:list', { agentId: activeAgentId, topicId: activeTopicId }, 1])).toBe(- true,- );+ expect(matcher(messageListKey(context))).toBe(true);// other domains / other topics are not matchedexpect(matcher(['topic:list', 'container', {}])).toBe(false);expect(matcher(['message:list', { agentId: activeAgentId, topicId: 'other' }, 1])).toBe(@@ -791,6 +804,36 @@ describe('chatMessage actions', () => {// 确保恢复 mutate 的模拟,以免影响其他测试(mutate as Mock).mockReset();});++ it('keeps soft revalidation silent after a successful prefetch verification', async () => {+ useChatStore.setState({ revalidateMessages: realRevalidateMessages });+ const context = { agentId: 'session-id', topicId: 'topic-id' };+ await runMessageListQuery(context, async () => []);++ await act(async () => {+ await useChatStore.getState().revalidateMessages(context);+ });++ expect(isMessageListServerVerified(context)).toBe(true);+ expect(mutate).not.toHaveBeenCalled();+ });++ it('softly revalidates only the exact canonical conversation context', async () => {+ useChatStore.setState({ revalidateMessages: realRevalidateMessages });+ const context = {+ agentId: 'session-id',+ groupId: 'group-id',+ threadId: 'thread-id',+ topicId: 'topic-id',+ };++ await act(async () => {+ await useChatStore.getState().revalidateMessages(context);+ });++ expect(mutate).toHaveBeenCalledTimes(1);+ expect(mutate).toHaveBeenCalledWith(messageListKey(context));+ });});describe('modifyMessageContent', () => {@@ -1247,19 +1290,99 @@ describe('chatMessage actions', () => {});expect(mutate).toHaveBeenCalledTimes(1);- const [matcher, dataArg, options] = (mutate as Mock).mock.calls[0];+ const [swrKey, dataArg, options] = (mutate as Mock).mock.calls[0];// seeds, never refetchesexpect(options).toEqual({ revalidate: false });expect(dataArg).toEqual(messages);+ expect(swrKey).toEqual(messageListKey(context));+ expect(isMessageListServerVerified(context)).toBe(false);+ });- // matcher targets exactly this bucket, not other buckets / domains- expect(typeof matcher).toBe('function');- expect(matcher(['message:list', context, 1])).toBe(true);- // workspace-augmented variant of the same bucket still matches- expect(matcher(['message:list', context, 1, 'workspace-1'])).toBe(true);- expect(matcher(['message:list', { agentId: 'wt-agent', topicId: 'other' }, 1])).toBe(false);- expect(matcher(['topic:list', 'container', {}])).toBe(false);+ it('skips write-through when the conversation has no persisted topic', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ result.current.replaceMessages([{ id: 'm-new', role: 'user', content: 'hi' }] as any, {+ context: { agentId: 'wt-agent-new', topicId: null },+ });+ });++ expect(mutate).not.toHaveBeenCalled();+ });++ it('skips write-through for scoped buckets the server message:list key cannot represent', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ // Page copilot: `documentId` only exists in the local bucket key, so+ // the canonical agent/topic entry must not be created from it.+ result.current.replaceMessages([{ id: 'm-page', role: 'user', content: 'hi' }] as any, {+ context: {+ agentId: 'wt-page-agent',+ documentId: 'doc-1',+ scope: 'page',+ topicId: 'wt-page-topic',+ },+ });++ // Group-agent stream: the canonical key drops `subAgentId`, which+ // would collide with the group main conversation entry.+ result.current.replaceMessages([{ id: 'm-sub', role: 'user', content: 'hi' }] as any, {+ context: {+ agentId: 'wt-supervisor',+ groupId: 'wt-group',+ scope: 'group_agent',+ subAgentId: 'wt-worker',+ topicId: 'wt-group-topic',+ },+ });+ });++ expect(mutate).not.toHaveBeenCalled();+ });++ it('still seeds the canonical entry for a representable group context', async () => {+ const { result } = renderHook(() => useChatStore());++ const context = {+ agentId: 'wt-sup',+ groupId: 'wt-grp',+ scope: 'group' as const,+ topicId: 'wt-grp-topic',+ };+ const messages = [{ id: 'm-grp', role: 'user', content: 'hi' }] as any;++ await act(async () => {+ result.current.replaceMessages(messages, { context });+ });++ expect(mutate).toHaveBeenCalledTimes(1);+ const [swrKey, dataArg, options] = (mutate as Mock).mock.calls[0];+ expect(swrKey).toEqual(messageListKey(context));+ expect(dataArg).toEqual(messages);+ expect(options).toEqual({ revalidate: false });+ });++ it('still seeds the canonical entry for a representable group thread context', async () => {+ const { result } = renderHook(() => useChatStore());++ const context = {+ agentId: 'wt-worker',+ groupId: 'wt-grp',+ scope: 'thread' as const,+ threadId: 'wt-thread',+ topicId: 'wt-grp-topic',+ };+ const messages = [{ id: 'm-thread', role: 'user', content: 'hi' }] as any;++ await act(async () => {+ result.current.replaceMessages(messages, { context });+ });++ expect(mutate).toHaveBeenCalledWith(messageListKey(context), messages, {+ revalidate: false,+ });});it('skips write-through for the useFetchMessages onData sync path', async () => {@@ -1322,10 +1445,40 @@ describe('chatMessage actions', () => {expect(result.current.messagesMap[key]).toBeUndefined();// ...but the cache is still seeded so a later switch-back is not staleexpect(mutate).toHaveBeenCalledTimes(1);- const [matcher, dataArg, options] = (mutate as Mock).mock.calls[0];+ const [swrKey, dataArg, options] = (mutate as Mock).mock.calls[0];expect(options).toEqual({ revalidate: false });expect(dataArg).toEqual(messages);- expect(matcher(['message:list', context, 1])).toBe(true);+ expect(swrKey).toEqual(messageListKey(context));+ });+ });++ describe('useFetchMessages action', () => {+ it('binds the canonical key, coordinated fetcher, and fetched-data sync', async () => {+ const context = { agentId: 'fetch-agent', topicId: 'fetch-topic' };+ const messages = [{ id: 'fetch-message', role: 'user', content: 'hi' }] as any;+ (messageService.getMessages as Mock).mockResolvedValue(messages);++ renderHook(() =>+ useChatStore.getState().useFetchMessages(context, { revalidateOnFocus: false }),+ );++ expect(useClientDataSWRWithSync).toHaveBeenCalledTimes(1);+ const [key, fetcher, options] = (useClientDataSWRWithSync as Mock).mock.calls[0];+ expect(key).toEqual(messageListKey(context));+ await expect(fetcher()).resolves.toEqual(messages);++ act(() => {+ options.onData(messages);+ });++ expect(useChatStore.getState().dbMessagesMap[messageMapKey(context)]).toEqual(messages);+ expect(options).toEqual(+ expect.objectContaining({+ dedupingInterval: expect.any(Number),+ revalidateIfStale: true,+ revalidateOnFocus: false,+ }),+ );});});@@ -1352,17 +1505,61 @@ describe('chatMessage actions', () => {});const key = messageMapKey(context);- expect(messageService.getMessages).toHaveBeenCalledWith(context);+ expect(messageService.getMessages).toHaveBeenCalledWith({+ agentId: 'prefetch-agent',+ groupId: null,+ threadId: null,+ topicId: 'prefetch-topic',+ });expect(result.current.dbMessagesMap[key]).toEqual(messages);expect(result.current.messagesMap[key]).toHaveLength(1);expect(mutate).toHaveBeenCalledTimes(1);const [swrKey, dataArg, options] = (mutate as Mock).mock.calls[0];- expect(swrKey).toEqual(['message:list', context, 1]);+ expect(swrKey).toEqual(messageListKey(context));await expect(dataArg).resolves.toEqual(messages);expect(options).toEqual({ revalidate: false });});+ it('swallows a failed background prefetch and allows the same context to retry', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = {+ agentId: 'prefetch-agent',+ scope: 'main' as const,+ topicId: 'failed-topic',+ };++ (messageService.getMessages as Mock).mockRejectedValueOnce(new Error('offline'));++ await act(async () => {+ await result.current.prefetchMessages(context);+ });++ (messageService.getMessages as Mock).mockResolvedValueOnce([]);+ await act(async () => {+ await result.current.prefetchMessages(context);+ });++ expect(messageService.getMessages).toHaveBeenCalledTimes(2);+ });++ it('skips prefetch when the canonical message cache is fresh', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = {+ agentId: 'prefetch-agent',+ scope: 'main' as const,+ topicId: 'fresh-topic',+ };+ await runMessageListQuery(context, async () => []);++ await act(async () => {+ await result.current.prefetchMessages(context);+ });++ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(mutate).not.toHaveBeenCalled();+ });+it('refreshes an already hydrated bucket with the completed server snapshot', async () => {const { result } = renderHook(() => useChatStore());@@ -1387,7 +1584,12 @@ describe('chatMessage actions', () => {await result.current.prefetchMessages(context);});- expect(messageService.getMessages).toHaveBeenCalledWith(context);+ expect(messageService.getMessages).toHaveBeenCalledWith({+ agentId: 'prefetch-agent',+ groupId: null,+ threadId: null,+ topicId: 'cached-topic',+ });expect(result.current.dbMessagesMap[key]).toEqual(serverMessages);expect(mutate).toHaveBeenCalledTimes(1);});@@ -1412,6 +1614,7 @@ describe('chatMessage actions', () => {const firstPrefetch = result.current.prefetchMessages(context);const secondPrefetch = result.current.prefetchMessages(context);+ await Promise.resolve();expect(messageService.getMessages).toHaveBeenCalledTimes(1);await act(async () => {@@ -1422,6 +1625,37 @@ describe('chatMessage actions', () => {expect(result.current.dbMessagesMap[messageMapKey(context)]).toEqual(messages);});++ it('shares an in-flight prefetch with the mounted canonical query', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = {+ agentId: 'prefetch-agent',+ scope: 'main' as const,+ threadId: 'thread-id',+ topicId: 'mount-topic',+ };+ const mountedContext = { ...context, documentId: 'ui-only-field' };+ const messages = [{ id: 'shared-message', role: 'user', content: 'hi' }] as any;+ let resolveRequest!: (value: UIChatMessage[]) => void;+ const serverRequest = new Promise<UIChatMessage[]>((resolve) => {+ resolveRequest = resolve;+ });+ (messageService.getMessages as Mock).mockReturnValue(serverRequest);++ const prefetchPromise = result.current.prefetchMessages(context);+ const mountedQuery = runMessageListQuery(mountedContext, messageService.getMessages);++ await Promise.resolve();+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);++ await act(async () => {+ resolveRequest(messages);+ await Promise.all([prefetchPromise, mountedQuery]);+ });++ expect(messageService.getMessages).toHaveBeenCalledTimes(1);+ await expect(mountedQuery).resolves.toEqual(messages);+ });});describe('Public API with context parameter', () => {diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 64cf04eeef0..75151920e2a 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -1,11 +1,20 @@import { parse } from '@lobechat/conversation-flow';import { type ConversationContext, type UIChatMessage } from '@lobechat/types';+import debug from 'debug';import isEqual from 'fast-deep-equal';import { type SWRResponse } from 'swr';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';import { messageKeys } from '@/libs/swr/keys';import { messageService } from '@/services/message';+import {+ getMessageListCacheIdentity,+ getMessageListFetchPolicy,+ invalidateMessageListClientState,+ isMessageListServerVerified,+ messageListKey,+ runMessageListQuery,+} from '@/services/message/cache';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { type ChatStore } from '@/store/chat/store';import { type StoreSetter } from '@/store/types';@@ -19,24 +28,8 @@ import { reconcileAssistantToolLinks } from '../utils/reconcileTools';* Handles fetching, refreshing, and replacing message data*/-/**- * Dedupe window for the `message:list` switch-back revalidate.- *- * The Conversation store is recreated on every topic/session switch, which- * remounts `useFetchMessages`. At the `useClientDataSWR` default- * (`dedupingInterval: 0`) that fires a network revalidate on every single- * switch. Message mutations now write through to this cache (see- * `replaceMessages` → `#writeThroughMessageCache`), so a switch-back within- * this window hydrates from a FRESH cache and the refetch is pure redundancy.- *- * 30s covers the typical "switch away, glance at another conversation, switch- * back" loop while keeping cross-device / server-agent updates within an- * acceptable staleness bound — `revalidateOnFocus` (5min throttle) and- * `revalidateOnReconnect` remain the longer-tail backstop, and a running- * conversation keeps its live gateway stream regardless of this window.- */-const MESSAGE_LIST_DEDUPING_INTERVAL = 30 * 1000;const prefetchingMessageKeys = new Set<string>();+const log = debug('lobe-client:message-query');type Setter = StoreSetter<ChatStore>;export const messageQuery = (set: Setter, get: () => ChatStore, _api?: unknown) =>@@ -52,12 +45,30 @@ export class MessageQueryActionImpl {this.#get = get;}+ revalidateMessages = async (context?: Partial<ConversationContext>): Promise<void> => {+ const agentId = context?.agentId ?? this.#get().activeAgentId;+ const topicId = context?.topicId !== undefined ? context.topicId : this.#get().activeTopicId;+ const groupId = context?.groupId !== undefined ? context.groupId : this.#get().activeGroupId;+ const threadId =+ context?.threadId !== undefined ? context.threadId : this.#get().activeThreadId;++ // Topic navigation is a soft ensure: a completed prefetch is already the+ // server snapshot the destination hook needs, while an in-flight prefetch+ // will be shared by the coordinator when the hook mounts.+ if (isMessageListServerVerified({ agentId, groupId, threadId, topicId })) return;++ await mutate(messageListKey({ agentId, groupId, threadId, topicId }));+ };+refreshMessages = async (context?: Partial<ConversationContext>): Promise<void> => {const agentId = context?.agentId ?? this.#get().activeAgentId;const topicId = context?.topicId !== undefined ? context.topicId : this.#get().activeTopicId;- // Invalidate every `message:list` entry for this agent+topic (any scope /- // thread / page-size variant). The key shape is- // `[message:list, ConversationContext, version]`, so match on key[1].++ // A force refresh owns both invalidation layers. Do this synchronously+ // before SWR mutate so an inactive key with no subscriber still loses its+ // verification window and any older in-flight generation.+ invalidateMessageListClientState((ctx) => ctx.agentId === agentId && ctx.topicId === topicId);+await mutate((key) => {if (!Array.isArray(key) || key[0] !== messageKeys.list.root) return false;const ctx = key[1] as ConversationContext | undefined;@@ -68,22 +79,24 @@ export class MessageQueryActionImpl {prefetchMessages = async (context: ConversationContext): Promise<void> => {if (!context.agentId || !context.topicId) return;- const messagesKey = messageMapKey(context);+ const messagesKey = getMessageListCacheIdentity(context);if (operationSelectors.isAgentRuntimeRunningByContext(context)(this.#get())) return;+ if (isMessageListServerVerified(context)) return;if (prefetchingMessageKeys.has(messagesKey)) return;prefetchingMessageKeys.add(messagesKey);- const request = messageService.getMessages(context).then((messages) => {+ const request = runMessageListQuery(context, messageService.getMessages).then((messages) => {this.#get().replaceMessages(messages, { action: 'prefetchMessages', context });return messages;});try {- await mutate(messageKeys.list(context), request, { revalidate: false });+ await mutate(messageListKey(context), request, { revalidate: false });await request;- } catch {+ } catch (error) {// Background warming should never surface an unhandled rejection.+ log('Failed to warm the message cache: %O', error);} finally {prefetchingMessageKeys.delete(messagesKey);}@@ -171,20 +184,27 @@ export class MessageQueryActionImpl {};/**- * Write the settled in-memory messages back into the `message:list` SWR cache- * (and, transitively, the persisted IndexedDB tier) for this exact bucket.+ * Write settled in-memory messages back into the canonical `message:list`+ * SWR cache (and, transitively, the persisted IndexedDB tier).** Why: message mutations otherwise only touch the in-memory store, so the SWR* cache stays stale until a network refetch. Because the Conversation store is* recreated on every topic/session switch and re-hydrates from this cache, a* stale cache is what forces a refetch on every switch. Keeping the cache in- * sync here lets a switch-back hydrate from a FRESH cache.+ * sync here lets a switch-back hydrate immediately while the independent+ * server-verification policy decides whether to revalidate.** Called even when the `replaceMessages` store-set is a no-op (see caller),* because an optimistic dispatch may have already applied this exact state to* the store while leaving the cache stale.*- * Skipped in three cases:+ * Skipped in four cases:+ * - contexts the canonical `message:list` key cannot represent — scoped+ * buckets such as page copilot (`documentId`) or group-agent streams+ * (`subAgentId`) carry a local-only discriminator that+ * `normalizeMessageListQueryContext` drops, so seeding the canonical key+ * would persist the scoped transcript under the ordinary conversation+ * entry and a later mount of THAT conversation would hydrate it.* - `useFetchMessages` onData — SWR already holds that exact value, so* re-writing it would double the IndexedDB persist on every fetch.* - `prefetchMessages` — the exact cache key is seeded by the prefetch@@ -200,21 +220,28 @@ export class MessageQueryActionImpl {messages: UIChatMessage[],action?: string,): void => {- if (action === 'useFetchMessages' || action === 'prefetchMessages') return;+ if (!ctx.agentId || !ctx.topicId) return;if (operationSelectors.isAgentRuntimeRunningByContext(ctx)(this.#get())) return;+ if (action === 'useFetchMessages' || action === 'prefetchMessages') return;- // Match every `message:list` entry whose context resolves to the same bucket- // (any page-size / version / workspace-augmented variant). `revalidate: false`- // seeds the cache without firing a network request.- void mutate(- (key) => {- if (!Array.isArray(key) || key[0] !== messageKeys.list.root) return false;- const keyCtx = key[1] as ConversationContext | undefined;- return !!keyCtx && messageMapKey(keyCtx) === messagesKey;- },- messages,- { revalidate: false },- );+ // The server `message:list` key only carries agentId/groupId/threadId/+ // topicId (see `normalizeMessageListQueryContext`). When the bucket key+ // needs more than those fields (page `documentId`, group-agent+ // `subAgentId`, `isNew`, an isolating `scope`, …) this context cannot be+ // represented by the canonical key — write nothing rather than store the+ // scoped transcript under the ordinary conversation entry.+ const representableBucketKey = messageMapKey({+ agentId: ctx.agentId,+ groupId: ctx.groupId,+ scope: ctx.threadId ? 'thread' : ctx.groupId ? 'group' : 'main',+ threadId: ctx.threadId,+ topicId: ctx.topicId,+ });+ if (messagesKey !== representableBucketKey) return;++ // A concrete canonical key creates the cache entry even when no subscriber+ // has mounted yet, which lets a later conversation switch render locally.+ void mutate(messageListKey(ctx), messages, { revalidate: false });};useFetchMessages = (@@ -241,13 +268,10 @@ export class MessageQueryActionImpl {const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;return useClientDataSWRWithSync<UIChatMessage[]>(- shouldFetch ? messageKeys.list(context) : null,- () => messageService.getMessages(context),+ shouldFetch ? messageListKey(context) : null,+ () => runMessageListQuery(context, messageService.getMessages),{- // Skip the redundant switch-back refetch within this window — the cache- // is kept current by mutation write-through, so a remount hydrates from- // a fresh cache instead of forcing a network revalidate every switch.- dedupingInterval: MESSAGE_LIST_DEDUPING_INTERVAL,+ ...getMessageListFetchPolicy(context),onData: (data) => {if (!data || !context.topicId) return;diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 227e2257d9f..69602e22520 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -839,11 +839,11 @@ describe('topic action', () => {});});describe('switchTopic', () => {- it('should update activeTopicId and call refreshMessages', async () => {+ it('should update activeTopicId and softly revalidate messages', async () => {const topicId = 'topic-id';const { result } = renderHook(() => useChatStore());- const refreshMessagesSpy = vi.spyOn(result.current, 'refreshMessages');+ const revalidateMessagesSpy = vi.spyOn(result.current, 'revalidateMessages');// Call the switchTopic action with the topicIdawait act(async () => {await result.current.switchTopic(topicId);@@ -853,14 +853,14 @@ describe('topic action', () => {expect(useChatStore.getState().activeTopicId).toBe(topicId);// Verify that the refreshMessages was called to update the messages- expect(refreshMessagesSpy).toHaveBeenCalled();+ expect(revalidateMessagesSpy).toHaveBeenCalled();});it('should support options object as second parameter', async () => {const topicId = 'topic-id';const { result } = renderHook(() => useChatStore());- const refreshMessagesSpy = vi.spyOn(result.current, 'refreshMessages');+ const revalidateMessagesSpy = vi.spyOn(result.current, 'revalidateMessages');// Call with options object (new API)await act(async () => {@@ -868,7 +868,7 @@ describe('topic action', () => {});expect(useChatStore.getState().activeTopicId).toBe(topicId);- expect(refreshMessagesSpy).not.toHaveBeenCalled();+ expect(revalidateMessagesSpy).not.toHaveBeenCalled();});it('should clear new key data when switching to null (main scope)', async () => {@@ -1070,9 +1070,11 @@ describe('topic action', () => {expect(useChatStore.getState().activeTopicId).toBe('new-created-topic-id');});- it('should skip refreshMessages for superseded overlapping switches', async () => {+ it('should skip revalidateMessages for superseded overlapping switches', async () => {const { result } = renderHook(() => useChatStore());- const refreshSpy = vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);+ const revalidateSpy = vi+ .spyOn(result.current, 'revalidateMessages')+ .mockResolvedValue(undefined);// Fire two overlapping switches: the sync body of both runs before// either yields, so by the microtask boundary the second has already@@ -1083,7 +1085,7 @@ describe('topic action', () => {await Promise.all([p1, p2]);});- expect(refreshSpy).toHaveBeenCalledTimes(1);+ expect(revalidateSpy).toHaveBeenCalledTimes(1);expect(useChatStore.getState().activeTopicId).toBe('topic-b');});});diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 6bb00169c61..d3208d03627 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -1138,12 +1138,15 @@ export class ChatTopicActionImpl {// Yield a microtask so any switchTopic calls queued behind us can run// their sync bodies (and bump #switchTopicEpoch) before we commit to a- // refresh. On the other side of the yield, an epoch mismatch means a- // newer switch has taken over — skip the redundant SWR mutate.+ // revalidation. On the other side of the yield, an epoch mismatch means a+ // newer switch has taken over — skip the redundant SWR mutate. Navigation+ // uses a soft ensure so a completed or in-flight sidebar prefetch is not+ // invalidated by the switch itself; explicit refresh signals still go+ // through refreshMessages and advance the request generation.await Promise.resolve();if (epoch !== this.#switchTopicEpoch) return;- await this.#get().refreshMessages();+ await this.#get().revalidateMessages();};removeSessionTopics = async (): Promise<void> => {