🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(conversation): let the chat store own every transcript (#20959)
Arvin Xub9a437f389f0
diff --git a/apps/share/src/features/topic/SharedMessageList.tsx b/apps/share/src/features/topic/SharedMessageList.tsxindex 611125d783e..173b6957ca4 100644--- a/apps/share/src/features/topic/SharedMessageList.tsx+++ b/apps/share/src/features/topic/SharedMessageList.tsx@@ -7,8 +7,6 @@ import { memo, type ReactNode, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { ChatList, ConversationProvider, MessageItem } from '@/features/Conversation';-import { useChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';interface SharedMessageListProps {agentId: string | null;@@ -31,25 +29,13 @@ const SharedMessageList = memo<SharedMessageListProps>((props) => {[agentId, groupId, shareId, topicId],);- // Sync messages to chatStore for artifact selectors to work- const chatKey = useMemo(() => messageMapKey(context), [context]);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);-const itemContent = useCallback((index: number, id: string) => <MessageItem disableEditing id={id} index={index} key={id} />,[],);return (- <ConversationProvider- context={context}- hasInitMessages={!!messages}- messages={messages}- onMessagesChange={(messages, ctx, meta) => {- replaceMessages(messages, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context}><ChatListdisableActionsBarheaderSlot={headerSlot}diff --git a/src/features/AgentBuilder/AgentBuilderProvider.tsx b/src/features/AgentBuilder/AgentBuilderProvider.tsxindex 81e768b0e32..4ec1557a039 100644--- a/src/features/AgentBuilder/AgentBuilderProvider.tsx+++ b/src/features/AgentBuilder/AgentBuilderProvider.tsx@@ -5,7 +5,6 @@ import { ConversationProvider } from '@/features/Conversation';import { useOperationState } from '@/hooks/useOperationState';import { useChatStore } from '@/store/chat';import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';interface AgentBuilderProviderProps {agentId: string;@@ -51,28 +50,11 @@ const AgentBuilderProvider = memo<AgentBuilderProviderProps>([agentId, activeTopicId],);- // Get messages from ChatStore based on context- const chatKey = useMemo(- () => (context ? messageMapKey(context) : null),- [context?.agentId, context?.topicId],- );-- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => (chatKey ? s.dbMessagesMap[chatKey] : undefined));-// Get operation state for reactive updatesconst operationState = useOperationState(context);return (- <ConversationProvider- context={context}- hasInitMessages={!!messages}- messages={messages}- operationState={operationState}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context} operationState={operationState}>{children}</ConversationProvider>);diff --git a/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx b/src/features/AgentGoals/GoalChat/GoalChatProvider.tsxindex 940b70ac382..7bd806dd56e 100644--- a/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx+++ b/src/features/AgentGoals/GoalChat/GoalChatProvider.tsx@@ -6,7 +6,6 @@ import { ConversationProvider } from '@/features/Conversation';import { useOperationState } from '@/hooks/useOperationState';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';interface GoalChatProviderProps {/** The goal's responsible agent — the one the user asks about progress. */@@ -60,23 +59,12 @@ export const GoalChatProvider = memo<GoalChatProviderProps>([activeTopicId, agentId, goalId],);- const chatKey = useMemo(() => messageMapKey(context), [context]);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);const operationState = useOperationState(context);if (!initialized) return null;return (- <ConversationProvider- context={context}- hasInitMessages={!!messages}- messages={messages}- operationState={operationState}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context} operationState={operationState}>{children}</ConversationProvider>);diff --git a/src/features/AgentTaskManager/TaskAgentProvider.tsx b/src/features/AgentTaskManager/TaskAgentProvider.tsxindex a069c3036da..0fb9f58b631 100644--- a/src/features/AgentTaskManager/TaskAgentProvider.tsx+++ b/src/features/AgentTaskManager/TaskAgentProvider.tsx@@ -12,7 +12,6 @@ import { useOperationState } from '@/hooks/useOperationState';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { resolveTaskHandoffTopic } from './taskHandoff';@@ -118,24 +117,13 @@ export const TaskAgentProvider = memo<TaskAgentProviderProps>((props) => {[activeTopicId, inboxAgentId, resolvedViewedTaskId, selectedAgentId],);- const chatKey = useMemo(() => messageMapKey(context), [context]);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);const operationState = useOperationState(context);if (!taskAgentId) return <ConversationSegmentSkeleton />;return (<TaskAgentSelectionContext value={selectTaskAgent}>- <ConversationProvider- context={context}- hasInitMessages={!!messages}- messages={messages}- operationState={operationState}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context} operationState={operationState}>{children}</ConversationProvider></TaskAgentSelectionContext>diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsxindex cfe006c5f62..282eca4a466 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx@@ -31,7 +31,6 @@ import { useOperationState } from '@/hooks/useOperationState';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useServerConfigStore } from '@/store/serverConfig';import { serverConfigSelectors } from '@/store/serverConfig/selectors';import { useTaskStore } from '@/store/task';@@ -90,9 +89,6 @@ export const TopicChatDrawerBody = memo<TopicChatDrawerBodyProps>([agentId, topicId],);- const chatKey = messageMapKey(context);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);- const replaceMessages = useChatStore((s) => s.replaceMessages);const operationState = useOperationState(context);const drawerRunningOperation = useTaskStore(@@ -108,15 +104,7 @@ export const TopicChatDrawerBody = memo<TopicChatDrawerBodyProps>();return (- <ConversationProvider- context={context}- hasInitMessages={!!messages}- messages={messages}- operationState={operationState}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context} operationState={operationState}><TaskCardScopeProvider value={true}><Flexbox height={'100%'} style={{ overflow: 'hidden' }}><Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>diff --git a/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.test.ts b/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.test.tsindex 791e6a71e01..8c04994888b 100644--- a/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.test.ts+++ b/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.test.ts@@ -28,7 +28,7 @@ describe('message edit confirmation', () => {);const store = createStore({context: { agentId: 'agent', topicId: 'topic', threadId: null },- initialMessages: ['u1', 'u2'].map((id, index) => ({+ messages: ['u1', 'u2'].map((id, index) => ({id,content: id,role: 'user',diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex d739249639d..a838e02f912 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -125,13 +125,11 @@ const ChatList = memo<ChatListProps>(messageDeepLink,showWelcome,}) => {- // Fetch messages (SWR key is null when skipFetch is true)+ // The chat store owns the transcript; this view keeps its sync mounted.const context = useConversationStore((s) => s.context);const enableUserMemories = useUserStore(settingsSelectors.memoryEnabled);- const [skipFetch, useFetchMessages] = useConversationStore((s) => [- dataSelectors.skipFetch(s),- s.useFetchMessages,- ]);+ const skipFetch = useConversationStore(dataSelectors.skipFetch);+ const useFetchMessages = useChatStore((s) => s.useFetchMessages);const activeAgentId = useChatStore((s) => s.activeAgentId);// Pending cards still refresh during streaming; the data slice merges only// intervention changes so lagging DB snapshots cannot replace live text.diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsxindex fcabd6fc958..18725094c49 100644--- a/src/features/Conversation/ConversationProvider.test.tsx+++ b/src/features/Conversation/ConversationProvider.test.tsx@@ -91,12 +91,28 @@ vi.mock('@/store/agent', () => ({) => selector({ useFetchAgentConfig: chatListMocks.useFetchAgentConfig }),}));+// The chat store holds each conversation's rows; the provider mirrors its bucket.+const chatState = vi.hoisted(() => ({+ activeAgentId: 'agt_old',+ creatingTopicIds: [] as string[],+ dbMessagesMap: {} as Record<string, unknown[]>,+ messagesMap: {} as Record<string, unknown[]>,+ useFetchMessages: vi.fn(() => ({+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: async () => undefined,+ })),+}));+vi.mock('@/store/chat', () => ({- getChatStoreState: () => ({}),+ getChatStoreState: () => chatState,useChatStore: Object.assign(- (selector: (state: { activeAgentId: string; creatingTopicIds: string[] }) => unknown) =>- selector({ activeAgentId: 'agt_old', creatingTopicIds: [] }),- { getState: () => ({}) },+ (selector: (state: typeof chatState) => unknown) => selector(chatState),+ {+ getState: () => chatState,+ subscribe: () => () => {},+ },),}));@@ -171,16 +187,26 @@ const OverlayHeightSetter = () => {return <button onClick={() => setChatInputOverlayHeight(48)}>set overlay height</button>;};-const renderChatList = (messages?: UIChatMessage[]) =>- render(- <ConversationProvider- context={oldContext}- hasInitMessages={messages !== undefined}- messages={messages}- >+/** Seed the chat store bucket of a conversation (`undefined` = not loaded yet). */+const seedBucket = (context: ConversationContext, messages?: UIChatMessage[]) => {+ const key = messageMapKey(context);+ if (messages) {+ chatState.dbMessagesMap[key] = messages;+ chatState.messagesMap[key] = messages;+ } else {+ delete chatState.dbMessagesMap[key];+ delete chatState.messagesMap[key];+ }+};++const renderChatList = (messages?: UIChatMessage[]) => {+ seedBucket(oldContext, messages);+ return render(+ <ConversationProvider context={oldContext}><ChatList welcome={<div>WELCOME</div>} /></ConversationProvider>,);+};describe('ConversationProvider', () => {beforeEach(() => {@@ -188,6 +214,9 @@ describe('ConversationProvider', () => {chatListMocks.isStreaming = false;chatListMocks.refreshError.error = undefined;chatListMocks.refreshError.isRetrying = false;+ chatState.dbMessagesMap = {};+ chatState.messagesMap = {};+ seedBucket(oldContext, oldMessages);});it('keeps the same store instance across context changes', () => {@@ -198,13 +227,13 @@ describe('ConversationProvider', () => {};const { rerender } = render(- <ConversationProvider hasInitMessages context={oldContext} messages={oldMessages}>+ <ConversationProvider context={oldContext}><ApiProbe /></ConversationProvider>,);rerender(- <ConversationProvider context={nextContext} hasInitMessages={false}>+ <ConversationProvider context={nextContext}><ApiProbe /></ConversationProvider>,);@@ -220,7 +249,7 @@ describe('ConversationProvider', () => {};const { rerender } = render(- <ConversationProvider hasInitMessages context={oldContext} messages={oldMessages}>+ <ConversationProvider context={oldContext}><ApiCapture /></ConversationProvider>,);@@ -262,7 +291,7 @@ describe('ConversationProvider', () => {});rerender(- <ConversationProvider context={nextContext} hasInitMessages={false}>+ <ConversationProvider context={nextContext}><ApiCapture /></ConversationProvider>,);@@ -293,13 +322,13 @@ describe('ConversationProvider', () => {const snapshots: Snapshot[] = [];const { rerender } = render(- <ConversationProvider hasInitMessages context={oldContext} messages={oldMessages}>+ <ConversationProvider context={oldContext}><Probe expectedContext={oldContext} snapshots={snapshots} /></ConversationProvider>,);rerender(- <ConversationProvider context={nextContext} hasInitMessages={false}>+ <ConversationProvider context={nextContext}><Probe expectedContext={nextContext} snapshots={snapshots} /></ConversationProvider>,);@@ -342,8 +371,9 @@ describe('ConversationProvider', () => {});it('reserves composer overlay space in the settled empty welcome', () => {+ seedBucket(oldContext, []);const { container } = render(- <ConversationProvider hasInitMessages context={oldContext} messages={[]}>+ <ConversationProvider context={oldContext}><ChatList welcome={<div>WELCOME</div>} /><OverlayHeightSetter /></ConversationProvider>,@@ -362,4 +392,15 @@ describe('ConversationProvider', () => {expect(screen.getByTestId('virtualized-list')).toHaveTextContent('msg_old');});++ it('renders a static transcript without reading the chat store', () => {+ seedBucket(oldContext);+ render(+ <ConversationProvider context={oldContext} messages={oldMessages}>+ <ChatList welcome={<div>WELCOME</div>} />+ </ConversationProvider>,+ );++ expect(screen.getByTestId('virtualized-list')).toHaveTextContent('msg_old');+ });});diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsxindex 962e68e0c69..e287b5c6b64 100644--- a/src/features/Conversation/ConversationProvider.tsx+++ b/src/features/Conversation/ConversationProvider.tsx@@ -18,7 +18,6 @@ import {type ConversationContext,type ConversationHooks,createComposerTarget,- type MessagesChangeMeta,type OperationState,} from './types';@@ -51,35 +50,16 @@ export interface ConversationProviderProps {* Conversation context (data coordinates)*/context: ConversationContext;- /**- * Whether external messages have been initialized- * When false, ChatList will show skeleton loading state- */- hasInitMessages?: boolean;/*** Lifecycle hooks for external behavior injection*/hooks?: ConversationHooks;/**- * External messages to sync into the store- * When provided, these messages will be used as the source of truth+ * A static transcript to render (a render gallery, a share snapshot). It is+ * held by this conversation and never synced. Without it the conversation+ * shows — and syncs — the chat store bucket of `context`.*/messages?: UIChatMessage[];- /**- * Callback when messages are fetched or changed internally- * Use this to sync messages back to external state (e.g., ChatStore)- *- * @param messages - The updated messages array- * @param context - The context that this data belongs to (prevents race conditions)- * @param meta - Set when the messages are a fetched server snapshot; forward- * it as `source` to ChatStore.replaceMessages so the SWR write-through can- * skip fetch echoes (see MessagesChangeMeta)- */- onMessagesChange?: (- messages: UIChatMessage[],- context: ConversationContext,- meta?: MessagesChangeMeta,- ) => void;/*** External operation state (from ChatStore)*@@ -89,6 +69,9 @@ export interface ConversationProviderProps {* When provided, this will be synced into the store for reactive updates.*/operationState?: OperationState;+ /**+ * Do not sync the transcript, e.g. while another flow owns its rows+ */skipFetch?: boolean;}@@ -105,9 +88,7 @@ export const ConversationProvider = memo<ConversationProviderProps>(composerTarget,context,hooks = {},- hasInitMessages,messages,- onMessagesChange,operationState,skipFetch,}) => {@@ -118,10 +99,9 @@ export const ConversationProvider = memo<ConversationProviderProps>();log(- '[Provider] render | contextKey=%s | messagesCount=%d | hasInitMessages=%s | skipFetch=%s',+ '[Provider] render | contextKey=%s | static=%s | skipFetch=%s',contextKey,- messages?.length ?? 0,- hasInitMessages,+ !!messages,skipFetch,);@@ -132,7 +112,7 @@ export const ConversationProvider = memo<ConversationProviderProps>(composerTarget: resolvedComposerTarget,context,hooks,- initialMessages: messages,+ messages,skipFetch,})}@@ -141,12 +121,10 @@ export const ConversationProvider = memo<ConversationProviderProps>(actionsBar={actionsBar}composerTarget={resolvedComposerTarget}context={context}- hasInitMessages={hasInitMessages}hooks={hooks}messages={messages}operationState={operationState}skipFetch={skipFetch}- onMessagesChange={onMessagesChange}/><AssistantTurnSettledWatcher /><ConversationContextPrefetcher context={context} />diff --git a/src/features/Conversation/StoreUpdater.tsx b/src/features/Conversation/StoreUpdater.tsxindex 595caf462b9..d1194d97819 100644--- a/src/features/Conversation/StoreUpdater.tsx+++ b/src/features/Conversation/StoreUpdater.tsx@@ -5,6 +5,7 @@ import debug from 'debug';import { memo, useEffect, useLayoutEffect, useMemo, useRef } from 'react';import { createStoreUpdater } from 'zustand-utils';+import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useConversationStoreApi } from './store';@@ -15,7 +16,6 @@ import {type ConversationContext,type ConversationHooks,createComposerTarget,- type MessagesChangeMeta,type OperationState,} from './types';@@ -28,49 +28,27 @@ export interface StoreUpdaterProps {actionsBar?: ActionsBarConfig;composerTarget?: ComposerTarget;context: ConversationContext;- /**- * Whether external messages have been initialized- */- hasInitMessages?: boolean;hooks?: ConversationHooks;/**- * External messages to sync into the store+ * A static transcript, held by the store instead of the chat store bucket*/messages?: UIChatMessage[];- /**- * Callback when messages are fetched or changed internally- */- onMessagesChange?: (- messages: UIChatMessage[],- context: ConversationContext,- meta?: MessagesChangeMeta,- ) => void;/*** External operation state (from ChatStore)*/operationState?: OperationState;/**- * Skip internal message fetching (when external messages are provided)+ * Do not sync the transcript*/skipFetch?: boolean;}const StoreUpdater = memo<StoreUpdaterProps>(- ({- actionsBar,- composerTarget,- context,- hasInitMessages,- hooks,- messages,- onMessagesChange,- operationState,- skipFetch,- }) => {+ ({ actionsBar, composerTarget, context, hooks, messages, operationState, skipFetch }) => {const storeApi = useConversationStoreApi();const useStoreUpdater = createStoreUpdater(storeApi);- const prevMessagesRef = useRef<UIChatMessage[] | undefined>(undefined);const contextKey = messageMapKey(context);+ const isStatic = !!messages;const resolvedComposerTarget = useMemo(() => composerTarget ?? createComposerTarget(contextKey),[composerTarget, contextKey],@@ -80,71 +58,54 @@ const StoreUpdater = memo<StoreUpdaterProps>(useStoreUpdater('composerTarget', resolvedComposerTarget);useStoreUpdater('context', context);useStoreUpdater('hooks', hooks!);- useStoreUpdater('onMessagesChange', onMessagesChange);useStoreUpdater('operationState', operationState!);- useStoreUpdater('skipFetch', skipFetch!);-- // When external messages are provided, mark as initialized- useStoreUpdater('messagesInit', skipFetch ? true : (hasInitMessages ?? false));// Reset store state before paint when context changes.// useLayoutEffect fires after commit but before browser paint, and React processes// store updates triggered here synchronously — so subscribers re-render before paint.const prevContextKeyRef = useRef(contextKey);useLayoutEffect(() => {- if (prevContextKeyRef.current !== contextKey) {- prevContextKeyRef.current = contextKey;- prevMessagesRef.current = undefined;-- // Update context first so replaceMessages uses the correct context- // when calling onMessagesChange (otherwise writes to the old topic key)- storeApi.setState({- ...createEphemeralResetState(),- // The store shows one conversation: the previous one's replica- // bookkeeping must not describe the next one's rows.- messageReplica: { entries: {}, scope: storeApi.getState().messageReplica.scope },- context,- dbMessages: messages ?? [],- displayMessages: [],- messagesInit: false,- });-- // If messages are already available, sync them immediately.- // skipOnMessagesChange: this is external → internal sync; echoing back- // through onMessagesChange would re-write the SWR cache with the (possibly- // partial) bucket and discard an in-flight switch-time revalidation.- if (messages) {- storeApi.getState().replaceMessages(messages, { skipOnMessagesChange: true });- storeApi.setState({ messagesInit: true });- }- }+ if (prevContextKeyRef.current === contextKey) return;+ prevContextKeyRef.current = contextKey;++ storeApi.setState({+ ...createEphemeralResetState(),+ context,+ dbMessages: [],+ displayMessages: [],+ // A static transcript is always loaded; a chat bucket says so itself.+ messagesInit: isStatic,+ });+ // The mirror below re-reads the next bucket in this same pre-paint pass.+ if (messages) storeApi.getState().replaceMessages(messages);}, [contextKey]); // eslint-disable-line react-hooks/exhaustive-deps- // Sync external messages into store+ // Mirror the chat store bucket: every write to it — a fetch, a stream+ // chunk, an edit from any surface — reaches this store synchronously.+ useLayoutEffect(() => {+ // Set here, not by a post-paint updater: the mirror reads them below.+ storeApi.setState({+ skipFetch: isStatic || !!skipFetch,+ transcriptSource: isStatic ? 'static' : 'chat',+ });+ if (isStatic) return;+ const bucket = contextKey;+ const sync = () => storeApi.getState().internal_syncChatTranscript();+ sync();+ return useChatStore.subscribe((state, prev) => {+ if (+ state.dbMessagesMap[bucket] !== prev.dbMessagesMap[bucket] ||+ state.messagesMap[bucket] !== prev.messagesMap[bucket]+ )+ sync();+ });+ }, [contextKey, isStatic, skipFetch, storeApi]);++ // A static transcript follows its prop.useEffect(() => {- if (messages) {- const prevMessages = prevMessagesRef.current;- const prevCount = prevMessages?.length ?? 0;- const newCount = messages.length;- const isSameReference = prevMessages === messages;- const storeMessages = storeApi.getState().dbMessages;-- log(- '[StoreUpdater] messages effect | contextKey=%s | prevCount=%d | newCount=%d | sameRef=%s | storeCount=%d | messageIds=%o',- contextKey,- prevCount,- newCount,- isSameReference,- storeMessages.length,- messages.slice(0, 5).map((m) => m.id),- );-- prevMessagesRef.current = messages;- // External → internal sync: never echo back through onMessagesChange- // (would poison the SWR cache with the possibly-partial bucket and- // discard an in-flight revalidation — see DataAction.replaceMessages).- storeApi.getState().replaceMessages(messages, { skipOnMessagesChange: true });- }+ if (!messages) return;+ log('[StoreUpdater] static messages | contextKey=%s | count=%d', contextKey, messages.length);+ storeApi.getState().replaceMessages(messages);}, [messages, storeApi, contextKey]);return null;diff --git a/src/features/Conversation/store.test.ts b/src/features/Conversation/store.test.tsindex 4cc445be711..506a9a62db4 100644--- a/src/features/Conversation/store.test.ts+++ b/src/features/Conversation/store.test.ts@@ -10,6 +10,7 @@ import { type ConversationContext, type ConversationHooks } from './types';vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({+ dbMessagesMap: {},messagesMap: {},operations: {},optimisticCreateMessage: vi.fn(),diff --git a/src/features/Conversation/store/action.ts b/src/features/Conversation/store/action.tsindex 1ce6a63cbb5..86b5ce8352d 100644--- a/src/features/Conversation/store/action.ts+++ b/src/features/Conversation/store/action.ts@@ -13,7 +13,7 @@ import {import { type State } from './initialState';import { initialState } from './initialState';import { type DataAction } from './slices/data/action';-import { dataSlice } from './slices/data/action';+import { chatTranscriptState, dataSlice } from './slices/data/action';import { type GenerationAction } from './slices/generation/action';import { generationSlice } from './slices/generation/action';import { type InputAction } from './slices/input/action';@@ -48,21 +48,11 @@ export interface CreateStoreParams {context: ConversationContext;hooks?: ConversationHooks;/**- * Messages to seed the freshly-created store with, already known by the parent- * (ConversationArea reads them from ChatStore's `dbMessagesMap`). Seeding at- * creation — rather than waiting for StoreUpdater's post-mount effect — is what- * keeps a store *mount* from painting an empty/skeleton frame first.- *- * The store instance now survives topic switches (the Provider is not keyed by- * context — StoreUpdater resets state in place instead), so this only covers- * genuine mounts: first navigation to a surface, or hosts that key the whole- * provider themselves (e.g. eval bench). Without a seed such a mount starts- * `messagesInit: false` and only gets populated by a post-paint effect — one- * blank frame, i.e. the "message disappears then reappears" flicker.- * `undefined` means "not fetched yet" (stay uninitialized); `[]` means- * "loaded, empty".+ * A static transcript (a render gallery, a share snapshot). Held by this+ * store and never synced; without it the store mirrors the chat store bucket+ * of `context`, read at creation so a mount paints its rows on the first frame.*/- initialMessages?: UIChatMessage[];+ messages?: UIChatMessage[];skipFetch?: boolean;}@@ -71,24 +61,22 @@ type CreateStore = () => StateCreator<Store, [['zustand/devtools', never]]>;export const createStoreAction: CreateStore =- ({ composerTarget, context, hooks = {}, initialMessages, skipFetch }) =>+ ({ composerTarget, context, hooks = {}, messages, skipFetch }) =>(...params) => ({...initialState,composerTarget: composerTarget ?? createComposerTarget(messageMapKey(context)),context,hooks,- skipFetch,- // Seed known messages so a remount renders content on its first paint instead- // of a blank/skeleton frame. `initialMessages` truthy ([] included) mirrors- // StoreUpdater's `hasInitMessages = !!messages` → messagesInit semantics.- ...(initialMessages+ ...(messages? {- dbMessages: initialMessages,- displayMessages: parse(initialMessages, undefined, { threadId: context.threadId })+ dbMessages: messages,+ displayMessages: parse(messages, undefined, { threadId: context.threadId ?? undefined }).flatList,messagesInit: true,+ skipFetch: true,+ transcriptSource: 'static' as const,}- : {}),+ : { ...chatTranscriptState(context, skipFetch, []), skipFetch }),// ===== Slices =====...dataSlice(...params),...generationSlice(...params),diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.tsindex aaa086e704e..8307f3878b3 100644--- a/src/features/Conversation/store/initialState.ts+++ b/src/features/Conversation/store/initialState.ts@@ -1,11 +1,8 @@-import { type UIChatMessage } from '@lobechat/types';-import {type ActionsBarConfig,type ComposerTarget,type ConversationContext,type ConversationHooks,- type MessagesChangeMeta,type OperationState,} from '../types';import { DEFAULT_OPERATION_STATE } from '../types/operation';@@ -39,19 +36,6 @@ export interface State extends DataState, InputState, MessageStateState, VirtuaL*/hooks: ConversationHooks;- /**- * Callback when messages are fetched or changed internally- * @param messages - The updated messages array- * @param context - The context that this data belongs to (prevents race conditions)- * @param meta - Set when the messages are a fetched server snapshot rather- * than an internal mutation (see MessagesChangeMeta)- */- onMessagesChange?: (- messages: UIChatMessage[],- context: ConversationContext,- meta?: MessagesChangeMeta,- ) => void;-/*** External operation state (from ChatStore)* Used for reactive updates of operation-related UI@@ -73,7 +57,6 @@ export const initialState: State = {topicId: null,},hooks: {},- onMessagesChange: undefined,operationState: DEFAULT_OPERATION_STATE,};@@ -93,9 +76,6 @@ export const createEphemeralResetState = (): Partial<State> => ({heteroOverloadWaitOpIds: {},inputMessage: '',isLoadingEarlierMessages: false,- // The paging of the previous conversation's transcript must not describe- // the next one's rows.- messagePaging: undefined,refreshingRowId: undefined,isScrolling: false,messageEditingIds: [],diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex c93be3e2d90..a5304911fa0 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -1,19 +1,11 @@import type { UIChatMessage } from '@lobechat/types';-import { act, renderHook, waitFor } from '@testing-library/react';+import { act } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { cacheScope } from '@/libs/replica';-import { useClientDataSWR } from '@/libs/swr';import { messageService } from '@/services/message';-import {- clearMessageListClientCacheState,- MESSAGE_LIST_VERIFICATION_INTERVAL,- runMessageListQuery,-} from '@/services/message/cache';-import { conversationMessagesResource } from '@/services/message/replica';+import { clearMessageListClientCacheState, runMessageListQuery } from '@/services/message/cache';import { useChatStore } from '@/store/chat';-import { operationSelectors } from '@/store/chat/selectors';-import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { createStore } from '../../index';import { createEphemeralResetState } from '../../initialState';@@ -66,21 +58,6 @@ vi.mock('@/libs/swr', () => ({}),}));-/** The transcript sync's SWR keys (the replica's hydration read is a separate query). */-const messageSyncKeys = () =>- vi- .mocked(useClientDataSWR)- .mock.calls.map(([key]) => key as any[] | null)- .filter((key) => key?.[0] === 'message:list');--/** `useFetchMessages` is a hook: run it inside a component. */-const fetchMessagesOf =- (store: ReturnType<typeof createStore>) =>- (- ...args: Parameters<ReturnType<ReturnType<typeof createStore>['getState']>['useFetchMessages']>- ) =>- renderHook(() => store.getState().useFetchMessages(...args)).result.current;-// Create a test storeconst createTestStore = () =>createStore({@@ -313,28 +290,21 @@ describe('DataSlice', () => {expect(store.getState().isLoadingEarlierMessages).toBe(false);});- it('hands the extended transcript to the host, so its next sync keeps the older rows', async () => {- const onMessagesChange = vi.fn();+ it('pages into the chat store bucket every surface of the conversation reads', async () => {const context = {agentId: 'agent-earlier',threadId: 'thread-earlier',topicId: 'topic-earlier-host',};const store = createStore({ context });- store.setState({ onMessagesChange });- store.getState().replaceMessages(windowMessages, { skipOnMessagesChange: true });+ store.getState().replaceMessages(windowMessages);vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce({ messages: earlierPage });await store.getState().loadEarlierMessages();- expect(onMessagesChange).toHaveBeenCalledTimes(1);- expect(onMessagesChange.mock.calls[0][0].map((m: UIChatMessage) => m.id)).toEqual([- 'u1',- 'a1',- 'u2',- 'a2',- ]);- expect(onMessagesChange.mock.calls[0][1]).toEqual(context);+ expect(+ useChatStore.getState().dbMessagesMap[messageMapKey(context)].map((m) => m.id),+ ).toEqual(['u1', 'a1', 'u2', 'a2']);});it('stops fetching once a page comes back empty (beginning reached)', async () => {@@ -355,31 +325,36 @@ describe('DataSlice', () => {expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u2', 'a2']);});- it('drops a page that resolves after the store switched conversations', async () => {- const store = createStore({- context: {- agentId: 'agent-earlier',- topicId: 'topic-earlier-3',- threadId: 'thread-earlier',- },- });+ it('lands a page that resolves after a switch in its own conversation only', async () => {+ const context = {+ agentId: 'agent-earlier',+ topicId: 'topic-earlier-3',+ threadId: 'thread-earlier',+ };+ const nextContext = { ...context, topicId: 'topic-earlier-other' };+ const store = createStore({ context });store.getState().replaceMessages(windowMessages);vi.mocked(messageService.getEarlierMessages).mockImplementationOnce(async () => {// Mimic the real switch path (StoreUpdater): ephemeral reset + context.store.setState({...createEphemeralResetState(),- context: {- agentId: 'agent-earlier',- topicId: 'topic-earlier-other',- threadId: 'thread-earlier',- },+ context: nextContext,+ dbMessages: [],+ displayMessages: [],} as any);return { messages: earlierPage };});await store.getState().loadEarlierMessages();- expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u2', 'a2']);+ const { dbMessagesMap } = useChatStore.getState();+ expect(dbMessagesMap[messageMapKey(context)].map((m) => m.id)).toEqual([+ 'u1',+ 'a1',+ 'u2',+ 'a2',+ ]);+ expect(store.getState().dbMessages).toEqual([]);expect(store.getState().isLoadingEarlierMessages).toBe(false);});@@ -560,93 +535,40 @@ describe('DataSlice', () => {});});- it('echoes the committed extended transcript after head revalidation', async () => {- clearMessageListClientCacheState();- const context = { agentId: 'review-agent', topicId: 'review-topic', threadId: null };- const old = { id: 'old', role: 'user', content: 'older', createdAt: 1 } as UIChatMessage;- const head = { id: 'head', role: 'user', content: 'newest', createdAt: 2 } as UIChatMessage;- const cursor = { id: 'head', createdAt: '1970-01-01T00:00:00.002Z' };- await runMessageListQuery(context, async () => ({ messages: [head], olderCursor: cursor }));- const onMessagesChange = vi.fn();- const store = createStore({ context });- store.setState({ onMessagesChange });- store.getState().replaceMessages([head]);- vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce({- messages: [old],- olderCursor: null,- });- await store.getState().loadEarlierMessages();- onMessagesChange.mockClear();- vi.mocked(messageService.getMessageListPage).mockResolvedValueOnce({- messages: [head],- olderCursor: cursor,- });- fetchMessagesOf(store)(context);- await waitFor(() =>- expect(onMessagesChange).toHaveBeenCalledWith([old, head], context, { source: 'fetch' }),- );- expect(store.getState().dbMessages).toEqual([old, head]);- });+ describe('internal_syncChatTranscript', () => {+ it('mirrors the chat store bucket another surface wrote', () => {+ const context = { agentId: 'mirror-agent', threadId: null, topicId: 'mirror-topic' };+ const store = createStore({ context });+ expect(store.getState().messagesInit).toBe(false);+ const rows = [+ { id: 'm1', content: 'hi', role: 'user', createdAt: 1, updatedAt: 1 },+ ] as UIChatMessage[];- it('resets paging after an unpaged replacement but keeps it for an unchanged host echo', () => {- const context = { agentId: 'replace-agent', topicId: 'replace-topic', threadId: null };- const store = createStore({ context });- const rows = ['older', 'head'].map((id, i) => ({- id,- role: 'user',- content: id,- createdAt: i,- })) as UIChatMessage[];- const paging = {- currentPage: 2,- pageSize: 1,- hasMore: true,- anchorId: 'head',- nextCursor: { id: 'older', createdAt: 'old' },- pages: [{ count: 1 }, { count: 1 }],- };- store.setState({ dbMessages: rows, messagePaging: paging });- store.getState().replaceMessages([...rows], { skipOnMessagesChange: true });- expect(store.getState().messagePaging).toEqual(paging);- store.getState().replaceMessages([rows[1]]);- expect(store.getState().messagePaging).toEqual({ currentPage: 0, pageSize: 1, hasMore: true });- });+ useChatStore.getState().replaceMessages(rows, { context });+ store.getState().internal_syncChatTranscript();- describe('transcript persistence', () => {- it('keeps streamed writes in memory and persists once the run settles', async () => {- let running = true;- vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockImplementation(- () => () => running,+ expect(store.getState().dbMessages).toBe(+ useChatStore.getState().dbMessagesMap[messageMapKey(context)],);- vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);- const storageSet = vi- .spyOn(conversationMessagesResource.storage!, 'set')- .mockResolvedValue(undefined);- const store = createStore({- context: { agentId: 'agent-persist', threadId: null, topicId: 'topic-persist' },- });+ expect(store.getState().displayMessages.map((m) => m.id)).toEqual(['m1']);+ expect(store.getState().messagesInit).toBe(true);+ });- for (const id of ['m1', 'm2']) {- store.getState().internal_dispatchMessage({- id,- type: 'createMessage',- value: { content: id, role: 'assistant' } as any,- });- }- await new Promise((resolve) => setTimeout(resolve, 50));- expect(storageSet.mock.calls.some(([, row]) => Array.isArray((row.data as any)?.items))).toBe(- false,- );+ it('keeps a static transcript out of the chat store', () => {+ const context = { agentId: 'static-agent', threadId: null, topicId: 'static-topic' };+ const rows = [+ { id: 's1', content: 'hi', role: 'user', createdAt: 1, updatedAt: 1 },+ ] as UIChatMessage[];+ const store = createStore({ context, messages: rows });- running = false;- store.getState().replaceMessages(store.getState().dbMessages);+ store.getState().internal_dispatchMessage({+ id: 's1',+ type: 'updateMessage',+ value: { content: 'edited' },+ });- // The engine also tracks its stored keys in an index row.- const transcriptWrites = () =>- storageSet.mock.calls.filter(([, row]) => Array.isArray((row.data as any)?.items));- await waitFor(() => expect(transcriptWrites()).toHaveLength(1));- const [[, row]] = transcriptWrites();- expect((row.data as any).items.map((m: UIChatMessage) => m.id)).toEqual(['m1', 'm2']);+ expect(store.getState().dbMessages[0].content).toBe('edited');+ expect(useChatStore.getState().dbMessagesMap[messageMapKey(context)]).toBeUndefined();});});@@ -708,41 +630,20 @@ describe('DataSlice', () => {expect(state.dbMessages).toHaveLength(0);});- it('should sync internal replacements to the external store via onMessagesChange', () => {+ it('writes replacements into the chat store bucket of the conversation', () => {const store = createTestStore();- const onMessagesChange = vi.fn();- store.setState({ onMessagesChange });-const messages: UIChatMessage[] = [{ id: 'msg-1', content: 'Hello', role: 'user', createdAt: 1000, updatedAt: 1000 } as any,];- store.getState().replaceMessages(messages);- expect(onMessagesChange).toHaveBeenCalledWith(messages, store.getState().context);- });-- it('should NOT echo external prop sync back through onMessagesChange (skipOnMessagesChange)', () => {- // Regression: StoreUpdater's external → internal sync used to echo the- // bucket back to ChatStore, whose write-through mutate re-wrote the SWR- // cache with the (possibly partial) bucket and discarded an in-flight- // switch-time revalidation — locking the UI on a partial message list.- const store = createTestStore();- const onMessagesChange = vi.fn();- store.setState({ onMessagesChange });-- const partialBucket: UIChatMessage[] = [- { id: 'msg-first', content: 'seed', role: 'user', createdAt: 1000, updatedAt: 1000 } as any,- ];- store.getState().replaceMessages(partialBucket, { skipOnMessagesChange: true });+ store.getState().replaceMessages(messages);- // State still updates…- expect(store.getState().dbMessages).toHaveLength(1);- expect(store.getState().displayMessages[0].id).toBe('msg-first');- // …but nothing is echoed back to the external store.- expect(onMessagesChange).not.toHaveBeenCalled();+ expect(+ useChatStore.getState().dbMessagesMap[messageMapKey(store.getState().context)],+ ).toEqual(messages);});- it('discards an async replacement when the store has switched conversations', () => {+ it('lands an async replacement in its own conversation, not the one now shown', () => {const oldContext = { agentId: 'agent-1', threadId: null, topicId: 'topic-old' };const currentContext = { agentId: 'agent-1', threadId: null, topicId: 'topic-current' };const currentMessages: UIChatMessage[] = [@@ -754,25 +655,24 @@ describe('DataSlice', () => {updatedAt: 2000,},];- const store = createStore({ context: currentContext, initialMessages: currentMessages });- const onMessagesChange = vi.fn();- store.setState({ onMessagesChange });+ const lateOldMessages: UIChatMessage[] = [+ {+ content: 'late old topic result',+ createdAt: 1000,+ id: 'msg-old',+ role: 'assistant',+ updatedAt: 1000,+ },+ ];+ const store = createStore({ context: currentContext });+ store.getState().replaceMessages(currentMessages);- store.getState().replaceMessages(- [- {- content: 'late old topic result',- createdAt: 1000,- id: 'msg-old',- role: 'assistant',- updatedAt: 1000,- },- ],- { expectedContext: oldContext },- );+ store.getState().replaceMessages(lateOldMessages, { expectedContext: oldContext });expect(store.getState().dbMessages).toEqual(currentMessages);- expect(onMessagesChange).not.toHaveBeenCalled();+ expect(useChatStore.getState().dbMessagesMap[messageMapKey(oldContext)]).toEqual(+ lateOldMessages,+ );});});@@ -1013,876 +913,6 @@ describe('DataSlice', () => {});});- describe('useFetchMessages', () => {- beforeEach(() => {- vi.restoreAllMocks();- vi.clearAllMocks();- clearMessageListClientCacheState();- useChatStore.setState({ voiceMessageUploadMap: {} });- });-- it.each(['approved', 'rejected', 'aborted'] as const)(- 'observes a remote %s while preserving locally streaming content',- async (status) => {- vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);- const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };- const pending: UIChatMessage = {- content: '',- createdAt: 1,- id: 'question',- role: 'tool',- tool_call_id: 'call-1',- updatedAt: 10,- pluginIntervention: { status: 'pending' },- };- const streaming: UIChatMessage = {- content: 'Streaming content that has not been persisted yet',- createdAt: 2,- id: 'assistant',- role: 'assistant',- updatedAt: 10,- };- const answered: UIChatMessage = {- ...pending,- content: 'Remote answer',- updatedAt: 1,- pluginIntervention: { status },- };- const store = createStore({ context });- const onMessagesChange = vi.fn();- store.setState({ dbMessages: [pending, streaming], messagesInit: true, onMessagesChange });- vi.mocked(messageService.getMessages).mockResolvedValue([- answered,- { ...streaming, content: '...' },- ]);-- fetchMessagesOf(store)(context, { refreshInterval: 2000 });-- await waitFor(() => expect(store.getState().dbMessages[0]).toEqual(answered));- expect(store.getState().dbMessages[1]).toBe(streaming);- expect(onMessagesChange).toHaveBeenCalledWith([answered, streaming], context, {- source: 'fetch',- });- expect(useClientDataSWR).toHaveBeenCalledWith(- expect.any(Array),- expect.any(Function),- expect.objectContaining({- dedupingInterval: 1000,- refreshInterval: 2000,- refreshWhenHidden: false,- refreshWhenOffline: false,- }),- );- },- );-- it('settles a remote answer and permits an authoritative rollback at the same timestamp', async () => {- const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };- const pending: UIChatMessage = {- content: '',- createdAt: 1,- id: 'question',- role: 'tool',- tool_call_id: 'call-1',- updatedAt: 10,- pluginIntervention: { status: 'pending' },- };- const answered: UIChatMessage = {- ...pending,- content: 'Remote answer',- updatedAt: 1,- pluginIntervention: { status: 'approved' },- };- const store = createStore({ context });- store.setState({ dbMessages: [pending] });- vi.mocked(messageService.getMessages).mockResolvedValue([answered]);- fetchMessagesOf(store)(context);- await waitFor(() => expect(store.getState().dbMessages).toEqual([answered]));-- clearMessageListClientCacheState();- const rollback = { ...pending, updatedAt: 1 };- vi.mocked(messageService.getMessages).mockResolvedValue([rollback]);- fetchMessagesOf(store)(context);- await act(async () => {- await Promise.resolve();- });- expect(store.getState().dbMessages).toEqual([rollback]);- });-- it('should pass threadId to messageService.getMessages', async () => {- const mockMessages: UIChatMessage[] = [- {- id: 'thread-msg-1',- content: 'Thread message',- role: 'user',- createdAt: 1000,- updatedAt: 1000,- },- ];-- vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: 'test-thread' },- });-- // Call useFetchMessages - this triggers the SWR mock- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: 'test-thread',- });-- await waitFor(() => {- expect(messageService.getMessages).toHaveBeenCalledWith({- agentId: 'test-session',- groupId: null,- projectToolPayloads: false,- threadId: 'test-thread',- topicId: 'test-topic',- });- });- });-- it("tags the onData echo with source 'fetch' so handlers skip the cache write-through", async () => {- // Regression: without the tag, ChatStore.replaceMessages writes the- // echoed (possibly stale) snapshot through the SWR cache at mount, which- // trips SWR's mutation race guard and discards the in-flight- // revalidation — the conversation locks on the stale/partial list.- const mockMessages: UIChatMessage[] = [- { id: 'sync-msg-1', content: 'Synced', role: 'user', createdAt: 1000, updatedAt: 1000 },- ];- vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);-- const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };- const store = createStore({ context });- const onMessagesChange = vi.fn();- store.setState({ onMessagesChange });-- fetchMessagesOf(store)(context);-- await waitFor(() => {- expect(onMessagesChange).toHaveBeenCalledWith(mockMessages, context, { source: 'fetch' });- });- });-- describe('while an agent run is in flight in this conversation', () => {- const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };- const fetched: UIChatMessage[] = [- {- content: 'Run the script',- createdAt: 1000,- id: 'msg-user',- role: 'user',- updatedAt: 1000,- },- ];-- it('still lands the first load, so a parked run does not leave a skeleton (G-05)', async () => {- // A group supervisor parked on a member's approval stays `running`- // indefinitely; dropping the first load there never initializes the list.- const running = vi- .spyOn(operationSelectors, 'isAgentRuntimeRunningByContext')- .mockReturnValue(() => true);- vi.mocked(messageService.getMessages).mockResolvedValue(fetched);- const store = createStore({ context });- store.setState({ messagesInit: false });-- fetchMessagesOf(store)(context);-- await waitFor(() => {- expect(store.getState().messagesInit).toBe(true);- });- expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['msg-user']);- running.mockRestore();- });-- it('keeps loaded rows but lands rows the list has never seen (G-05)', async () => {- // A stale cached first load can miss the parked member's rows; the fresh- // read that follows must still bring them in, without touching the- // rows the stream owns.- const running = vi- .spyOn(operationSelectors, 'isAgentRuntimeRunningByContext')- .mockReturnValue(() => true);- const streamed = {- content: 'streamed so far',- createdAt: 2000,- id: 'msg-supervisor',- role: 'assistant',- updatedAt: 2000,- } as UIChatMessage;- const memberTool = {- content: '',- createdAt: 3000,- id: 'msg-member-tool',- role: 'tool',- updatedAt: 3000,- } as UIChatMessage;- vi.mocked(messageService.getMessages).mockResolvedValue([- ...fetched,- { ...streamed, content: '' },- memberTool,- ]);- const store = createStore({ context });- store.setState({ dbMessages: [...fetched, streamed], messagesInit: true });-- fetchMessagesOf(store)(context);-- await waitFor(() => {- expect(store.getState().dbMessages.map((m) => m.id)).toContain('msg-member-tool');- });- expect(store.getState().dbMessages.find((m) => m.id === 'msg-supervisor')?.content).toBe(- 'streamed so far',- );- running.mockRestore();- });-- it('drops a refetch that brings nothing new', async () => {- const running = vi- .spyOn(operationSelectors, 'isAgentRuntimeRunningByContext')- .mockReturnValue(() => true);- vi.mocked(messageService.getMessages).mockResolvedValue(fetched);- const store = createStore({ context });- const loaded = [{ ...fetched[0], content: 'local' }];- store.setState({ dbMessages: loaded, messagesInit: true });-- fetchMessagesOf(store)(context);-- await waitFor(() => {- expect(messageService.getMessages).toHaveBeenCalled();- });- await new Promise((resolve) => setTimeout(resolve, 0));- expect(store.getState().dbMessages).toBe(loaded);- running.mockRestore();- });- });-- it('discards a fetch result that resolves after switching conversations', async () => {- let resolveFetch!: (messages: UIChatMessage[]) => void;- vi.mocked(messageService.getMessages).mockReturnValue(- new Promise((resolve) => {- resolveFetch = resolve;- }),- );-- const oldContext = { agentId: 'test-session', threadId: null, topicId: 'topic-old' };- const currentContext = { agentId: 'test-session', threadId: null, topicId: 'topic-current' };- const currentMessages: UIChatMessage[] = [- {- content: 'current topic',- createdAt: 2000,- id: 'msg-current',- role: 'user',- updatedAt: 2000,- },- ];- const store = createStore({ context: oldContext });- const onMessagesChange = vi.fn();- store.setState({ onMessagesChange });-- fetchMessagesOf(store)(oldContext);- store.setState({- context: currentContext,- dbMessages: currentMessages,- displayMessages: currentMessages,- messagesInit: true,- });-- await act(async () => {- resolveFetch([- {- content: 'late old topic result',- createdAt: 1000,- id: 'msg-old',- role: 'assistant',- updatedAt: 1000,- },- ]);- await Promise.resolve();- });-- expect(store.getState().dbMessages).toEqual(currentMessages);- expect(onMessagesChange).not.toHaveBeenCalled();- });-- it('should pass null threadId when provided as null', async () => {- const mockMessages: UIChatMessage[] = [- {- id: 'msg-1',- content: 'Regular message',- role: 'user',- createdAt: 1000,- updatedAt: 1000,- },- ];-- vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(messageService.getMessages).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'test-session',- topicId: 'test-topic',- }),- );- });- });-- it('should not fetch when sessionId is empty', () => {- const store = createStore({- context: { agentId: '', topicId: null, threadId: null },- });-- fetchMessagesOf(store)({- agentId: '',- topicId: null,- threadId: null,- });-- // SWR should be called with null key (disabled)- expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(- null,- expect.any(Function),- expect.any(Object),- );- });-- it('should not fetch when topicId is null (new conversation state)', () => {- const store = createStore({- context: { agentId: 'test-session', topicId: null, threadId: null },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: null,- threadId: null,- });-- // SWR should be called with null key when topicId is null- // This prevents fetching empty data that would overwrite local optimistic updates- expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(- null,- expect.any(Function),- expect.any(Object),- );-- // messageService.getMessages should NOT be called- expect(messageService.getMessages).not.toHaveBeenCalled();- });-- it('should not fetch when topicId is undefined (new conversation state)', () => {- const store = createStore({- context: { agentId: 'test-session', topicId: null, threadId: null },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: undefined as any,- threadId: null,- });-- // SWR should be called with null key when topicId is undefined- expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(- null,- expect.any(Function),- expect.any(Object),- );- });-- it('should use different SWR keys for different threadIds', () => {- // The SWR mock runs the fetcher; an unmocked list read rejects after the test.- vi.mocked(messageService.getMessages).mockResolvedValue([]);-- const store1 = createStore({- context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-1' },- });-- fetchMessagesOf(store1)({- agentId: 'session-1',- topicId: 'topic-1',- threadId: 'thread-1',- });-- const firstCallKey = messageSyncKeys()[0];-- const store2 = createStore({- context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-2' },- });-- fetchMessagesOf(store2)({- agentId: 'session-1',- topicId: 'topic-1',- threadId: 'thread-2',- });-- const secondCallKey = messageSyncKeys()[1];-- // Keys should be different because threadIds are different- expect(firstCallKey).not.toEqual(secondCallKey);- expect((firstCallKey as any[])[1].threadId).toBe('thread-1');- expect((secondCallKey as any[])[1].threadId).toBe('thread-2');- });-- it('should use same SWR key structure with Object containing sessionId, topicId, threadId', () => {- // The SWR mock runs the fetcher; an unmocked list read rejects after the test.- vi.mocked(messageService.getMessages).mockResolvedValue([]);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: 'test-thread' },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: 'test-thread',- });-- const swrKey = messageSyncKeys()[0]!;-- // Key should be an array with prefix and context object- expect(Array.isArray(swrKey)).toBe(true);- expect(swrKey[0]).toBe('message:list');- expect(swrKey[1]).toEqual({- agentId: 'test-session',- 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 });- fetchMessagesOf(store)(context);-- expect(vi.mocked(useClientDataSWR)).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[] = [- {- id: 'group-msg-1',- content: 'Group message',- role: 'assistant',- createdAt: 1000,- updatedAt: 1000,- groupId: 'group-123',- agentId: 'worker-agent-1',- },- {- id: 'group-msg-2',- content: 'Another group message',- role: 'assistant',- createdAt: 2000,- updatedAt: 2000,- groupId: 'group-123',- agentId: 'worker-agent-2',- },- ];-- vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);-- const store = createStore({- context: {- agentId: 'supervisor-agent',- topicId: 'test-topic',- threadId: null,- groupId: 'group-123',- },- });-- // Call useFetchMessages with groupId - this triggers the SWR mock- fetchMessagesOf(store)({- agentId: 'supervisor-agent',- topicId: 'test-topic',- threadId: null,- groupId: 'group-123',- });-- await waitFor(() => {- expect(messageService.getMessages).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'supervisor-agent',- groupId: 'group-123',- topicId: 'test-topic',- }),- );- });- });-- it('should not pass groupId when not in group context', async () => {- const mockMessages: UIChatMessage[] = [- {- id: 'msg-1',- content: 'Regular message',- role: 'user',- createdAt: 1000,- updatedAt: 1000,- },- ];-- vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(messageService.getMessages).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'test-session',- topicId: 'test-topic',- }),- );- });- });-- it('should preserve newer local message state when fetched data is stale', async () => {- const localError = {- body: { message: 'Codex CLI was not found' },- message: 'Codex CLI was not found',- type: 'AgentRuntimeError',- } as any;-- vi.mocked(messageService.getMessages).mockResolvedValue([- {- id: 'msg-1',- content: '',- role: 'assistant',- createdAt: 1000,- updatedAt: 1000,- },- ]);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });-- store.setState({- dbMessages: [- {- id: 'msg-1',- content: '',- error: localError,- role: 'assistant',- createdAt: 1000,- updatedAt: 2000,- },- ],- } as any);-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(store.getState().dbMessages[0].error).toEqual(localError);- expect(store.getState().dbMessages[0].updatedAt).toBe(2000);- });- });-- it('should preserve a local-only message that is missing from fetched data', async () => {- const persistedMessage: UIChatMessage = {- id: 'persisted-message',- content: 'Persisted message',- role: 'assistant',- createdAt: 1000,- updatedAt: 1000,- };- const localVoiceMessage: UIChatMessage = {- id: 'tmp-voice-message',- audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],- content: '',- metadata: { scope: LOCAL_MESSAGE_SCOPE },- role: 'user',- createdAt: 2000,- updatedAt: 2000,- };-- vi.mocked(messageService.getMessages).mockResolvedValue([persistedMessage]);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });- store.setState({ dbMessages: [localVoiceMessage] });- useChatStore.setState({- voiceMessageUploadMap: {- [localVoiceMessage.id]: { progress: 50, status: 'uploading' },- },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(store.getState().dbMessages).toEqual([persistedMessage, localVoiceMessage]);- });- });-- it('should keep optimistic send rows when a stale fetch resolves before the server run starts', async () => {- const context = { agentId: 'test-session', topicId: 'test-topic', threadId: null };- const previousReply: UIChatMessage = {- id: 'previous-reply',- content: 'Previous reply',- role: 'assistant',- createdAt: 1000,- updatedAt: 1000,- };- const optimisticUser: UIChatMessage = {- id: 'msg_user',- content: 'Follow-up question',- role: 'user',- createdAt: 2000,- updatedAt: 2000,- };- const optimisticAssistant: UIChatMessage = {- id: 'msg_assistant',- content: '...',- role: 'assistant',- createdAt: 2001,- updatedAt: 2001,- };-- // The fetch was issued before the server persisted the new rows.- vi.mocked(messageService.getMessages).mockResolvedValue([- { ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 },- ]);-- const store = createStore({ context });- store.setState({- dbMessages: [previousReply, optimisticUser, optimisticAssistant],- messagesInit: true,- });-- // `sendMessage` is still waiting for `execAgentTask`; no runtime operation exists yet.- const { operationId } = useChatStore.getState().startOperation({- context: { ...context, messageId: optimisticUser.id },- type: 'sendMessage',- });- useChatStore.getState().associateMessageWithOperation(optimisticUser.id, operationId);- useChatStore.getState().associateMessageWithOperation(optimisticAssistant.id, operationId);-- try {- fetchMessagesOf(store)(context);-- await waitFor(() => {- expect(store.getState().dbMessages[0].content).toBe('Previous reply (fetched)');- });- expect(store.getState().dbMessages.map((message) => message.id)).toEqual([- previousReply.id,- optimisticUser.id,- optimisticAssistant.id,- ]);- } finally {- useChatStore.getState().completeOperation(operationId);- }- });-- it('should keep an earlier local-only voice row ahead of a later fetched message', async () => {- const localVoiceMessage: UIChatMessage = {- id: 'tmp-voice-message',- audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],- content: '',- metadata: { scope: LOCAL_MESSAGE_SCOPE },- role: 'user',- createdAt: 1000,- updatedAt: 1000,- };- const laterFetchedMessage: UIChatMessage = {- id: 'later-message',- content: 'Later text',- role: 'user',- createdAt: 2000,- updatedAt: 2000,- };-- vi.mocked(messageService.getMessages).mockResolvedValue([laterFetchedMessage]);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });- store.setState({ dbMessages: [localVoiceMessage] });- useChatStore.setState({- voiceMessageUploadMap: {- [localVoiceMessage.id]: { progress: 50, status: 'uploading' },- },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(store.getState().dbMessages).toEqual([localVoiceMessage, laterFetchedMessage]);- });- });-- it('should drop a missing local-only message after its voice transaction settles', async () => {- const persistedMessage: UIChatMessage = {- id: 'persisted-message',- content: 'Persisted message',- role: 'assistant',- createdAt: 1000,- updatedAt: 1000,- };- const settledLocalVoiceMessage: UIChatMessage = {- id: 'tmp-settled-voice-message',- audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:stale-voice-preview' }],- content: '',- metadata: { scope: LOCAL_MESSAGE_SCOPE },- role: 'user',- createdAt: 2000,- updatedAt: 2000,- };-- vi.mocked(messageService.getMessages).mockResolvedValue([persistedMessage]);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });- store.setState({ dbMessages: [settledLocalVoiceMessage] });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(store.getState().dbMessages).toEqual([persistedMessage]);- });- });-- it('should let a fetched server row replace a newer local-only row with the same id', async () => {- const fetchedMessage: UIChatMessage = {- id: 'tmp-voice-message',- audioList: [- { alt: 'voice.webm', id: 'persisted-audio', url: 'https://example.com/voice.webm' },- ],- content: 'Persisted message',- role: 'user',- createdAt: 1000,- updatedAt: 1000,- };- const localVoiceMessage: UIChatMessage = {- id: 'tmp-voice-message',- audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],- content: '',- metadata: { scope: LOCAL_MESSAGE_SCOPE },- role: 'user',- createdAt: 1000,- updatedAt: 2000,- };-- vi.mocked(messageService.getMessages).mockResolvedValue([fetchedMessage]);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });- store.setState({ dbMessages: [localVoiceMessage] });- useChatStore.setState({- voiceMessageUploadMap: {- [localVoiceMessage.id]: { progress: 100, status: 'sending' },- },- });-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(store.getState().dbMessages).toEqual([fetchedMessage]);- });- });-- it('should accept fetched message state when server data is newer', async () => {- vi.mocked(messageService.getMessages).mockResolvedValue([- {- id: 'msg-1',- content: '',- error: {- body: { message: 'Persisted error' },- message: 'Persisted error',- type: 'AgentRuntimeError',- } as any,- role: 'assistant',- createdAt: 1000,- updatedAt: 3000,- },- ]);-- const store = createStore({- context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },- });-- store.setState({- dbMessages: [- {- id: 'msg-1',- content: '',- role: 'assistant',- createdAt: 1000,- updatedAt: 2000,- },- ],- } as any);-- fetchMessagesOf(store)({- agentId: 'test-session',- topicId: 'test-topic',- threadId: null,- });-- await waitFor(() => {- expect(store.getState().dbMessages[0].error).toEqual({- body: { message: 'Persisted error' },- message: 'Persisted error',- type: 'AgentRuntimeError',- });- expect(store.getState().dbMessages[0].updatedAt).toBe(3000);- });- });- });-describe('switchMessageBranch', () => {// ROOT CAUSE:// MessageBranch calls this conversation action, which persists metadatadiff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex cb2580bce09..43630c62403 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -1,45 +1,13 @@import { parse } from '@lobechat/conversation-flow';-import { type ChatTopic, type ConversationContext, type UIChatMessage } from '@lobechat/types';+import { type ConversationContext, type UIChatMessage } from '@lobechat/types';import debug from 'debug';-import { useEffect, useMemo, useRef } from 'react';import { type StateCreator } from 'zustand/vanilla';-import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';-import { createReplicaSlice, type ReplicaLens } from '@/libs/replica';-import { messageService } from '@/services/message';-import {- getMessageListCacheIdentity,- getMessageListFetchPolicy,- getMessageListWindowOlderCursor,- runMessageListQuery,- supportsRoundCursor,-} from '@/services/message/cache';-import {- type ConversationMessageFetch,- type ConversationMessagePage,- type ConversationMessageParams,- conversationMessagesKey,- conversationMessagesResource,- toPersistedTranscript,- transcriptOf,-} from '@/services/message/replica';-import { topicService } from '@/services/topic';-import { getChatStoreState, useChatStore } from '@/store/chat';-import { operationSelectors, topicSelectors } from '@/store/chat/selectors';-import {- hasPendingInterventions,- INTERVENTION_REFRESH_INTERVAL,- isInterventionRunActive,- reconcileIntervention,- reconcileStreamingInterventions,-} from '@/store/chat/utils/interventionSync';-import {- isLocalOnlyMessage,- mergeLocalMessagesByCreatedAt,-} from '@/store/chat/utils/localMessages';+import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type Store as ConversationStore } from '../../action';+import { type State } from '../../initialState';import { isSameConversationContext } from '../../utils/contextGuard';import { type MessageDispatch } from './reducer';import { messagesReducer } from './reducer';@@ -48,77 +16,40 @@ import { stabilizeReferences } from './stabilizeReferences';const log = debug('lobe-render:features:Conversation');-interface InterventionSnapshot {- dbMessages: UIChatMessage[];- topic: ChatTopic | null;- topicAtRequest?: ChatTopic;-}--const interventionSync = new WeakMap<- () => ConversationStore,- { pending: Set<string>; snapshots: WeakMap<UIChatMessage[], InterventionSnapshot> }->();--const getInterventionSync = (get: () => ConversationStore) => {- let sync = interventionSync.get(get);- if (!sync) {- sync = { pending: new Set(), snapshots: new WeakMap() };- interventionSync.set(get, sync);- }- return sync;-};-/**- * Merge an idle head fetch into the shown transcript.- *- * A fetch can be issued before a send persists its rows and resolve while- * `sendMessage` is still waiting for the server. That window is not a running- * agent runtime, so the optimistic user and assistant rows must be kept- * explicitly until the server returns them; otherwise the just-sent message- * vanishes until the run settles and refetches.+ * The conversation's rows as the chat store holds them: `dbMessages` is the+ * bucket itself, `displayMessages` its parsed list pinned to the previous+ * render's references (memo bailouts survive a re-parse).*/-const mergeFetchedMessagesWithLocalState = (- fetchedMessages: UIChatMessage[],- localMessages: UIChatMessage[],- activeVoiceMessageIds: ReadonlySet<string>,- creatingMessageIds: ReadonlySet<string>,-): UIChatMessage[] => {- if (localMessages.length === 0) return fetchedMessages;-- const localById = new Map(localMessages.map((message) => [message.id, message]));- const fetchedIds = new Set(fetchedMessages.map((message) => message.id));- let changed = false;-- const mergedMessages = fetchedMessages.map((message) => {- const localMessage = localById.get(message.id);-- if (!localMessage) return message;- const resolved = reconcileIntervention(localMessage, message);- if (resolved) return resolved;- // Once the server returns this id, its persisted row replaces the local-only preview.- if (isLocalOnlyMessage(localMessage)) return message;- if (localMessage.updatedAt <= message.updatedAt) return message;-- changed = true;- return localMessage;- });-- const missingLocalMessages = localMessages.filter(- (message) =>- !fetchedIds.has(message.id) &&- ((isLocalOnlyMessage(message) && activeVoiceMessageIds.has(message.id)) ||- creatingMessageIds.has(message.id)),- );-- if (missingLocalMessages.length === 0) return changed ? mergedMessages : fetchedMessages;-- return mergeLocalMessagesByCreatedAt(mergedMessages, missingLocalMessages);+export const chatTranscriptState = (+ context: ConversationContext,+ skipFetch: boolean | undefined,+ previousDisplayMessages: UIChatMessage[],+): Pick<State, 'dbMessages' | 'displayMessages' | 'messagesInit'> => {+ const chat = useChatStore.getState();+ const bucket = messageMapKey(context);+ const rows = chat.dbMessagesMap[bucket];+ const parsed =+ rows &&+ (chat.messagesMap[bucket] ??+ parse(rows, undefined, { threadId: context.threadId ?? undefined }).flatList);+ return {+ dbMessages: rows ?? [],+ displayMessages: stabilizeReferences(previousDisplayMessages, parsed ?? []),+ // An absent bucket is "not loaded yet"; `[]` is a loaded, empty transcript.+ // A conversation that never syncs has nothing to wait for.+ messagesInit: !!rows || !!skipFetch,+ };};/*** Data Actions*- * Handles message fetching based on conversation context.+ * The rows a conversation shows are its chat store bucket: the chat store+ * fetches, pages and persists them, and this store mirrors the bucket+ * one-way (`internal_syncChatTranscript`). Writes go to the chat store and+ * come back through that mirror. A static transcript (`messages` passed to the+ * provider) is held here instead and never synced.*/export interface DataAction {/**@@ -127,6 +58,9 @@ export interface DataAction {*/internal_dispatchMessage: (payload: MessageDispatch) => void;+ /** Mirror the chat store bucket of the current context into this store. */+ internal_syncChatTranscript: () => void;+/*** Load one round-aligned page of history older than the server's* newest-first window and prepend it to the transcript.@@ -145,19 +79,13 @@ export interface DataAction {* Used for syncing after database operations (optimistic update pattern)** @param messages - New messages array from database- * @param options.expectedContext - Context captured when an async operation started.- * The replacement is discarded if the shared store has since switched context.- * @param options.skipOnMessagesChange - Set when the messages came FROM the- * external store (StoreUpdater prop sync). Echoing them back through- * `onMessagesChange` re-writes the SWR message cache with whatever the- * bucket held at mount — when that bucket is a partial seed (e.g. only the- * topic's first message), the echo's cache mutate lands while the- * switch-time revalidation is in flight and discards its result, locking- * the UI on the partial list.+ * @param options.expectedContext - Context captured when an async operation+ * started. The rows belong to that conversation, so they land in its+ * bucket even when this store has switched to another one since.*/replaceMessages: (messages: UIChatMessage[],- options?: { expectedContext?: ConversationContext; skipOnMessagesChange?: boolean },+ options?: { expectedContext?: ConversationContext },) => void;/**@@ -167,273 +95,35 @@ export interface DataAction {* @param branchIndex - The new branch index to switch to*/switchMessageBranch: (messageId: string, branchIndex: number) => Promise<void>;-- /**- * Fetch messages for this conversation using SWR.- *- * @param context - Conversation context with sessionId and topicId- * @param options.skipFetch - When true, SWR key is null and no fetch occurs- * @param options.revalidateOnFocus - Override SWR's default focus revalidate.- * Pass `false` while a streaming flow owns the in-memory message state so- * a focus refetch doesn't clobber it with a stale DB snapshot.- */- useFetchMessages: (- context: ConversationContext,- options?: {- refreshInterval?: number;- revalidateOnFocus?: boolean;- skipFetch?: boolean;- syncInterventions?: boolean;- },- ) => MessageSyncResult;-}--/** Fetch flags of the transcript sync. The rows live in the store (`dbMessages`). */-export interface MessageSyncResult {- error: unknown;- /** A first fetch is in flight and nothing is on screen yet. */- isLoading: boolean;- isValidating: boolean;- /** Re-run the head sync. */- mutate: () => Promise<unknown>;-}--/** What a head response resolved to, handed from `prepareHead` to the sync's `onSuccess`. */-interface HeadResolution {- completed: boolean;- /** The response changed nothing during a stream: kept off the transcript. */- dropped: boolean;- isStreaming: boolean;- mergedMessages: UIChatMessage[];- ownsTopic: boolean;- snapshot?: InterventionSnapshot;}-const isStreamingContext = (context: ConversationContext) =>- operationSelectors.isAgentRuntimeRunningByContext(context)(useChatStore.getState());-export const dataSlice: StateCreator<ConversationStore,[['zustand/devtools', never]],[],DataAction> = (set, get) => {- const sync = getInterventionSync(get);- /** Head responses resolved by `prepareHead`, read back by the sync's `onSuccess`. */- const headResolutions = new WeakMap<UIChatMessage[], HeadResolution>();-- // ---- transcript view -------------------------------------------------------- // The store holds one conversation: `dbMessages` (rows) + `messagePaging`- // (bookkeeping) are the replica's view of the current context's entry, and- // the parsed `displayMessages` is derived in the same commit.- const NO_PAGING = {} as Omit<ConversationMessagePage, 'items'>;- const views = new WeakMap<UIChatMessage[], WeakMap<object, ConversationMessagePage>>();- const remember = (items: UIChatMessage[], paging: object, view: ConversationMessagePage) => {- let byPaging = views.get(items);- if (!byPaging) views.set(items, (byPaging = new WeakMap()));- byPaging.set(paging, view);- return view;- };- const hasTranscript = (state: ConversationStore) =>- !!state.messagePaging || state.dbMessages.length > 0;-- const transcriptLens: ReplicaLens<ConversationStore, ConversationMessagePage> = {- clear: () => ({ dbMessages: [], displayMessages: [], messagePaging: undefined }),- get: (state, key) => {- if (key !== conversationMessagesKey(state.context) || !hasTranscript(state)) return undefined;- const paging = state.messagePaging ?? NO_PAGING;- return (- views.get(state.dbMessages)?.get(paging) ??- remember(- state.dbMessages,- paging,- state.messagePaging- ? { ...state.messagePaging, items: state.dbMessages }- : transcriptOf(state.dbMessages),- )- );- },- keys: (state) => (hasTranscript(state) ? [conversationMessagesKey(state.context)] : []),- set: (state, key, data) => {- // Late writes for a conversation this store no longer shows are dropped.- if (key !== conversationMessagesKey(state.context)) return {};- if (!data) return { dbMessages: [], displayMessages: [], messagePaging: undefined };- const { items, ...paging } = data;- remember(items, paging, data);- // parse() rebuilds every message/block/tool reference, so pin unchanged- // subtrees back to their previous identity to preserve memo bailouts.- const { flatList } = parse(items, undefined, { threadId: state.context.threadId });- return {- dbMessages: items,- displayMessages: stabilizeReferences(state.displayMessages, flatList),- messagePaging: paging,- };- },- };-- // ---- reads ---------------------------------------------------------------- const fetchHead = async (context: ConversationMessageParams): Promise<UIChatMessage[]> => {- const syncKey = getMessageListCacheIdentity(context);- const dbMessages = get().dbMessages;- const topicAtRequest = context.topicId- ? topicSelectors.getTopicById(context.topicId)(getChatStoreState())- : undefined;- const wasPending = hasPendingInterventions(dbMessages);- let messages = await runMessageListQuery(context, readConversationMessageListPage);- if (!context.syncInterventions || !context.topicId) return messages;- if (wasPending || hasPendingInterventions(messages)) sync.pending.add(syncKey);- if (!sync.pending.has(syncKey) || hasPendingInterventions(messages)) return messages;-- // The decision must precede the liveness read. A startup reservation is- // still live even before runningOperation is published.- const topic = await topicService.getTopicDetail(context.topicId);- if (!isInterventionRunActive(topic)) {- // Read after completion without dropping loaded history or its cursor.- messages = await runMessageListQuery(context, readConversationMessageListPage, {- force: true,- });- }- const result = [...messages];- sync.snapshots.set(result, { dbMessages, topic, topicAtRequest });- return result;- };-- const fetchOlder = async (- context: ConversationMessageParams,- cursor: NonNullable<ConversationMessagePage['nextCursor']>,- ): Promise<ConversationMessageFetch> => {- const page = await messageService.getEarlierMessages(+ /** Hold a static transcript in this store (it has no chat store bucket). */+ const setStaticMessages = (messages: UIChatMessage[], action: string) =>+ set({- agentId: context.agentId,- agentShareId: context.agentShareId,- groupId: context.groupId,- threadId: context.threadId,- topicId: context.topicId,- topicShareId: context.topicShareId,+ dbMessages: messages,+ displayMessages: stabilizeReferences(+ get().displayMessages,+ parse(messages, undefined, { threadId: get().context.threadId ?? undefined }).flatList,+ ),},- cursor,- );- // Without a reported cursor, `length < pageSize` is NOT a reliable end- // signal — the round-start trim legitimately shortens full pages — so only- // an empty page marks the top (`applyNextPage`).- return { items: page.messages, nextCursor: page.olderCursor };- };-- /**- * Fold a fetched head window into the shown transcript the way the- * conversation always has: drop results for a conversation no longer shown,- * keep streamed rows and unanswered interventions during a run, and keep- * client rows the server snapshot cannot know yet.- */- const prepareHead = (- incoming: ConversationMessageFetch,- current: ConversationMessagePage | undefined,- context: ConversationMessageParams,- ): ConversationMessageFetch | undefined => {- if (!Array.isArray(incoming)) return incoming;- if (!context.topicId) return undefined;-- const storeContextKey = messageMapKey(get().context);- if (storeContextKey !== messageMapKey(context)) {- log(- '[useFetchMessages] dropped stale result | requestContextKey=%s | storeContextKey=%s',- messageMapKey(context),- storeContextKey,- );- return undefined;- }-- // DB chunk writes can lag behind pushed content, even at an equal- // updatedAt. Keep streamed rows, but allow answers and unseen rows in.- // A parked run must not block the first load of the conversation.- const prevDbMessages = current?.items ?? get().dbMessages;- const snapshot = sync.snapshots.get(incoming);- sync.snapshots.delete(incoming);- const chat = getChatStoreState();- const currentTopic = topicSelectors.getTopicById(context.topicId)(chat);- const ownsTopic = !!snapshot && currentTopic === snapshot.topicAtRequest;- const completed = ownsTopic && !isInterventionRunActive(snapshot!.topic);- const isStreaming =- get().messagesInit &&- operationSelectors.isAgentRuntimeRunningByContext(context)(chat) &&- !(completed && snapshot!.dbMessages === prevDbMessages);- const activeVoiceMessageIds = new Set(Object.keys(chat.voiceMessageUploadMap));- const creatingMessageIds = new Set(- prevDbMessages- .filter((message) => operationSelectors.isMessageCreating(message.id)(chat))- .map((message) => message.id),- );- const mergedMessages = isStreaming- ? reconcileStreamingInterventions(prevDbMessages, incoming)- : mergeFetchedMessagesWithLocalState(- incoming,- prevDbMessages,- activeVoiceMessageIds,- creatingMessageIds,- );- const dropped = isStreaming && mergedMessages === prevDbMessages;-- headResolutions.set(incoming, {- completed,- dropped,- isStreaming,- mergedMessages,- ownsTopic,- snapshot,- });- if (dropped) return undefined;-- log(- '[useFetchMessages] head | contextKey=%s | prevCount=%d | fetchedCount=%d',- storeContextKey,- prevDbMessages.length,- mergedMessages.length,+ false,+ action,);- return { items: mergedMessages, nextCursor: getMessageListWindowOlderCursor(context) };- };-- const transcript = createReplicaSlice(conversationMessagesResource, {- actionPrefix: 'conversationMessages',- fetcher: (context, cursor) => (cursor ? fetchOlder(context, cursor) : fetchHead(context)),- get,- prepareHead,- set,- stateKey: 'messageReplica',- toPersisted: toPersistedTranscript,- view: transcriptLens,- });-- /** Write rows to the shown transcript (memory only; see `settleTranscript`). */- const writeTranscript = (messages: UIChatMessage[], preservePaging = false) =>- transcript.update(- conversationMessagesKey(get().context),- (current) =>- current &&- (preservePaging ||- (current.items.length === messages.length &&- current.items.every((item, index) => item.id === messages[index].id)))- ? { ...current, items: messages }- : transcriptOf(messages),- { persist: false },- );-- /**- * Persist the shown transcript once it is settled — never per streamed- * chunk; the snapshot written at run end is the one that survives a reload.- */- const settleTranscript = () => {- const context = get().context;- if (isStreamingContext(context)) return;- transcript.persist(conversationMessagesKey(context));- };return {internal_dispatchMessage: (payload) => {- const contextKey = messageMapKey(get().context);+ const { context, transcriptSource } = get();log(- '[dispatchMessage] start | contextKey=%s | type=%s | id=%s',- contextKey,+ '[dispatchMessage] | contextKey=%s | type=%s | id=%s',+ messageMapKey(context),payload.type,'id' in payload ? payload.id : 'ids' in payload ? payload.ids.join(',') : 'N/A',);@@ -458,75 +148,53 @@ export const dataSlice: StateCreator<return;}- const dbMessages = get().dbMessages;-- // Apply array-based reducer - preserves message order- const newDbMessages = messagesReducer(dbMessages, payload);-- // Check if anything changed- if (newDbMessages === dbMessages) {- log('[dispatchMessage] no change | contextKey=%s', contextKey);+ if (transcriptSource === 'chat') {+ useChatStore.getState().internal_dispatchMessage(payload, { conversationContext: context });+ // Read the write back now, whether or not a mounted mirror subscribes.+ get().internal_syncChatTranscript();return;}- log(- '[dispatchMessage] updated | contextKey=%s | prevCount=%d | newCount=%d',- contextKey,- dbMessages.length,- newDbMessages.length,- );-- writeTranscript(newDbMessages, true);- settleTranscript();+ const dbMessages = get().dbMessages;+ const newDbMessages = messagesReducer(dbMessages, payload);+ if (newDbMessages !== dbMessages)+ setStaticMessages(newDbMessages, `dispatchMessage/${payload.type}`);+ },- // Sync changes to external store (ChatStore)- get().onMessagesChange?.(newDbMessages, get().context);+ internal_syncChatTranscript: () => {+ const { context, displayMessages, skipFetch, transcriptSource } = get();+ if (transcriptSource !== 'chat') return;+ const next = chatTranscriptState(context, skipFetch, displayMessages);+ const state = get();+ if (+ next.dbMessages === state.dbMessages &&+ next.displayMessages === state.displayMessages &&+ next.messagesInit === state.messagesInit+ )+ return;+ set(next, false, 'syncChatTranscript');},loadEarlierMessages: async (options) => {- const context = get().context;- if (!context.agentId || !context.topicId) return;+ const { context, transcriptSource } = get();+ if (transcriptSource !== 'chat') return;if (get().earlierMessagesError !== undefined && !options?.retry) return;- const key = conversationMessagesKey(context);- const read = () => transcriptLens.get(get(), key);- const view = read();- if (!view || view.isLoadingMore) return;-- // A transcript seeded by the host (not yet confirmed by this store's own- // sync) pages from the window cursor this session already fetched. A- // cursor rebuilt from a row's millisecond `createdAt` would skip older- // rows sharing that millisecond, so a round-cursor read waits for it.- if (get().messageReplica.entries[key]?.source !== 'server' && view.nextCursor === undefined) {- const windowCursor = getMessageListWindowOlderCursor(context);- if (windowCursor === undefined && supportsRoundCursor(context)) return;- if (windowCursor !== undefined)- transcript.update(- key,- (data) => data && { ...data, hasMore: windowCursor !== null, nextCursor: windowCursor },- { persist: false },- );- }- if (!read()?.hasMore) return;-- set(- { earlierMessagesError: undefined, isLoadingEarlierMessages: true },- false,- 'loadEarlierMessages/start',- );- const before = get().dbMessages;- await transcript.loadMore(key, context);+ const { error, started } = await useChatStore.getState().loadEarlierMessages(context, {+ onStart: () =>+ set(+ { earlierMessagesError: undefined, isLoadingEarlierMessages: true },+ false,+ 'loadEarlierMessages/start',+ ),+ });+ if (!started) return;+ get().internal_syncChatTranscript();// The flag is conversation-wide state: after a context switch it belongs// to the new conversation (reset by createEphemeralResetState), so a// late settle from the previous one must not clear it.if (!isSameConversationContext(context, get().context)) return;- // Hand the extended transcript to the host: its next sync back into this- // store would otherwise replace the rows with the shorter window.- if (get().dbMessages !== before) get().onMessagesChange?.(get().dbMessages, context);- const error = read()?.loadMoreError;- if (error)- log('[loadEarlierMessages] failed | contextKey=%s | %O', messageMapKey(context), error);set({ earlierMessagesError: error ?? undefined, isLoadingEarlierMessages: false },false,@@ -535,38 +203,23 @@ export const dataSlice: StateCreator<},replaceMessages: (messages, options) => {- const currentContext = get().context;- const contextKey = messageMapKey(currentContext);- if (- options?.expectedContext &&- !isSameConversationContext(options.expectedContext, currentContext)- ) {- log(- '[replaceMessages] dropped stale result | requestContextKey=%s | storeContextKey=%s',- messageMapKey(options.expectedContext),- contextKey,- );- return;- }+ const { context, transcriptSource } = get();+ const target = options?.expectedContext ?? context;log(- '[replaceMessages] | contextKey=%s | prevCount=%d | newCount=%d | skipOnMessagesChange=%s | messageIds=%o',- contextKey,- get().dbMessages.length,+ '[replaceMessages] | contextKey=%s | newCount=%d',+ messageMapKey(target),messages.length,- options?.skipOnMessagesChange,- messages.slice(0, 5).map((m) => m.id),);- writeTranscript(messages);- settleTranscript();-- // Sync changes to external store (ChatStore) — skipped for external prop- // sync, which would only echo the external store's own data back and- // poison the SWR cache (see interface doc).- if (!options?.skipOnMessagesChange) {- get().onMessagesChange?.(messages, options?.expectedContext ?? currentContext);+ if (transcriptSource === 'chat') {+ useChatStore.getState().replaceMessages(messages, { context: target });+ get().internal_syncChatTranscript();+ return;}++ if (!isSameConversationContext(target, context)) return;+ setStaticMessages(messages, 'replaceMessages');},switchMessageBranch: async (messageId, branchIndex) => {@@ -577,141 +230,12 @@ export const dataSlice: StateCreator<if (!message || !message.parentId) return;// Invalidate pending automatic recovery before a historical error can mount.- getChatStoreState().revokeHeteroAutoRetry(state.context);+ useChatStore.getState().revokeHeteroAutoRetry(state.context);// Update the parent's metadata.activeBranchIndex// because the branch indicator is on the child message,// but the activeBranchIndex is stored on the parentawait state.updateMessageMetadata(message.parentId, { activeBranchIndex: branchIndex });},-- useFetchMessages: (context, options) => {- const { skipFetch, revalidateOnFocus, refreshInterval = 0 } = options ?? {};- // When skipFetch is true no fetch occurs. This is used when external- // messages are provided (e.g., creating new thread). Also skip when- // topicId is null (new conversation state) - there's no server data,- // only local optimistic updates. Fetching would return empty array and- // overwrite local data.- const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;- const syncKey = getMessageListCacheIdentity(context);- // Shared views use share-authorized services; thread runs do not own the- // topic's main runningOperation marker. Keep their existing refresh path.- const syncContinuation =- !!options?.syncInterventions &&- !context.agentShareId &&- !context.topicShareId &&- !context.threadId;- const onMessagesChange = get().onMessagesChange;- // Stable identity: the poll timer restarts whenever the interval option- // changes, so a fresh function per render would postpone every tick.- const pollInterval = useMemo(- () =>- syncContinuation- ? () => (sync.pending.has(syncKey) ? INTERVENTION_REFRESH_INTERVAL : refreshInterval)- : refreshInterval,- [syncContinuation, syncKey, refreshInterval],- );-- log(- '[useFetchMessages] hook | contextKey=%s | shouldFetch=%s | skipFetch=%s',- messageMapKey(context),- shouldFetch,- skipFetch,- );-- const result = transcript.useSync(- { ...context, syncInterventions: syncContinuation },- {- ...getMessageListFetchPolicy(context),- enabled: shouldFetch,- // Pending cards must observe answers from another device before the- // normal message cache's 30-second verification window expires.- ...((refreshInterval > 0 || sync.pending.has(syncKey)) && { dedupingInterval: 1000 }),- onSuccess: (fetched) => {- const resolution = Array.isArray(fetched) ? headResolutions.get(fetched) : undefined;- if (!resolution || !context.topicId) return;- headResolutions.delete(fetched as UIChatMessage[]);- const { completed, dropped, isStreaming, mergedMessages, ownsTopic, snapshot } =- resolution;-- // Do not replace a topic marker claimed by a local send or newer push.- if (snapshot && !hasPendingInterventions(mergedMessages) && ownsTopic) {- if (completed && !isStreaming) sync.pending.delete(syncKey);- const chat = getChatStoreState();- const currentTopic = topicSelectors.getTopicById(context.topicId)(chat);- const runningOperation = snapshot.topic?.metadata?.runningOperation;- if (- runningOperation &&- currentTopic?.metadata?.runningOperation?.operationId !==- runningOperation.operationId- ) {- // Publish the marker for useGatewayReconnect; it owns connection- // deduplication and retry. Do not open a second socket here.- if (currentTopic) {- chat.internal_dispatchTopic({- agentId: context.agentId,- containerKey: topicSelectors.getTopicContainerKeyById(context.topicId)(chat),- groupId: context.groupId,- id: context.topicId,- type: 'updateTopic',- value: { metadata: { ...currentTopic.metadata, runningOperation } },- });- } else if (snapshot.topic) {- useChatStore.setState({- topicDetailMap: { ...chat.topicDetailMap, [context.topicId]: snapshot.topic },- });- }- }- }- if (dropped) return;- set({ messagesInit: true }, false, 'useFetchMessages/init');-- // Use the callback and context captured when this fetch was- // registered. `source: 'fetch'` marks this as a server-snapshot- // echo: handlers must NOT write it through the SWR cache.- onMessagesChange?.(get().dbMessages, context, { source: 'fetch' });- },- refreshInterval: pollInterval,- refreshWhenHidden: false,- refreshWhenOffline: false,- ...(revalidateOnFocus !== undefined && { revalidateOnFocus }),- },- );-- // Streamed chunks stay in memory; the transcript is persisted once the- // run settles, so a reload restores the finished reply.- const isStreaming = useChatStore(operationSelectors.isAgentRuntimeRunningByContext(context));- const streamingKey = conversationMessagesKey(context);- const wasStreamingRef = useRef({ key: streamingKey, running: isStreaming });- useEffect(() => {- if (- wasStreamingRef.current.key === streamingKey &&- wasStreamingRef.current.running &&- !isStreaming- )- settleTranscript();- wasStreamingRef.current = { key: streamingKey, running: isStreaming };- }, [isStreaming, streamingKey]);-- // A transcript painted from storage before the network answers is- // handed to the host too, so its views (and runs) see the same rows.- const key = conversationMessagesKey(context);- const bridgedKeyRef = useRef<string>(undefined);- useEffect(() => {- if (!result.isHydrated || bridgedKeyRef.current === key) return;- bridgedKeyRef.current = key;- const state = get();- if (state.messageReplica.entries[key]?.source !== 'storage') return;- set({ messagesInit: true }, false, 'useFetchMessages/hydrated');- onMessagesChange?.(state.dbMessages, context, { source: 'fetch' });- }, [result.isHydrated, key]);-- return {- error: result.error,- isLoading: result.isValidating && !get().messagesInit,- isValidating: result.isValidating,- mutate: result.revalidate,- };- },};};diff --git a/src/features/Conversation/store/slices/data/initialState.ts b/src/features/Conversation/store/slices/data/initialState.tsindex 59cdca75cee..c60a75cb101 100644--- a/src/features/Conversation/store/slices/data/initialState.ts+++ b/src/features/Conversation/store/slices/data/initialState.ts@@ -1,8 +1,5 @@import { type UIChatMessage } from '@lobechat/types';-import { createReplicaState, type ReplicaState } from '@/libs/replica';-import { type ConversationMessagePage } from '@/services/message/replica';-export interface DataState {/*** Raw messages from DB (before parsing)@@ -29,18 +26,6 @@ export interface DataState {*/isLoadingEarlierMessages: boolean;- /**- * Paging bookkeeping of the transcript in `dbMessages` (cursor of the next- * older page, loaded depth). Absent until a fetch or hydration lands.- */- messagePaging?: Omit<ConversationMessagePage, 'items'>;-- /**- * Replica bookkeeping of this conversation's transcript (`dbMessages` +- * `messagePaging` are its view).- */- messageReplica: ReplicaState<ConversationMessagePage>;-/*** Whether messages have been initialized*/@@ -54,15 +39,22 @@ export interface DataState {refreshingRowId?: string;/**- * Skip internal message fetching (when external messages are provided)+ * Do not sync the transcript (a static transcript, or a surface that must+ * not read while another flow owns the rows)*/skipFetch?: boolean;++ /**+ * Where the rows live: `chat` mirrors the chat store bucket of `context`+ * (the default); `static` holds a transcript handed to the provider.+ */+ transcriptSource: 'chat' | 'static';}export const dataInitialState: DataState = {dbMessages: [],displayMessages: [],isLoadingEarlierMessages: false,- messageReplica: createReplicaState(),messagesInit: false,+ transcriptSource: 'chat',};diff --git a/src/features/Conversation/store/slices/generation/action.continueGeneration.test.ts b/src/features/Conversation/store/slices/generation/action.continueGeneration.test.tsnew file mode 100644index 00000000000..bfa5a25e7c8--- /dev/null+++ b/src/features/Conversation/store/slices/generation/action.continueGeneration.test.ts@@ -0,0 +1,373 @@+import { act } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { type ConversationContext, type ConversationHooks } from '../../../types';+import { createStore } from '../../index';++vi.mock('@/services/topic', () => ({+ topicService: { branchTopicAtMessage: vi.fn(), cancelRateLimitContinuation: vi.fn() },+}));++// Mock useChatStore+const mockCancelOperations = vi.fn();+const mockCancelOperation = vi.fn();+const mockCancelSendMessageInServer = vi.fn();+const mockRegenerateUserMessage = vi.fn();+const mockRegenerateAssistantMessage = vi.fn();+const mockContinueGenerationMessage = vi.fn();+const mockDeleteMessage = vi.fn();+const mockSwitchMessageBranch = vi.fn();+const mockStartOperation = vi.fn(() => ({ operationId: 'test-op-id' }));+const mockCompleteOperation = vi.fn();+const mockAssociateMessageWithOperation = vi.fn();+const mockFailOperation = vi.fn();+const mockExecuteClientAgent = vi.fn();+const mockIsGatewayModeEnabled = vi.fn(() => false);+const mockExecuteGatewayAgent = vi.fn();+const mockUpdateTopicMetadata = vi.fn();+const mockUpdateTopicStatus = vi.fn();+const mockOpenThreadCreator = vi.fn();+const mockSourceTopic = {+ status: 'scheduled',+ metadata: { scheduledRun: { kind: 'resume_after_rate_limit' } },+};++vi.mock('@/store/chat', () => ({+ useChatStore: {+ getState: vi.fn(() => ({+ dbMessagesMap: {},+ messagesMap: {+ 'session-1-': [+ { id: 'msg-1', role: 'user', content: 'Hello' },+ { id: 'msg-2', role: 'assistant', content: 'Hi there', parentId: 'msg-1' },+ ],+ },+ topicDataMap: {},+ topicDetailMap: { 'source-topic': mockSourceTopic },+ operations: {},+ operationsByMessage: {},++ cancelOperations: mockCancelOperations,+ cancelOperation: mockCancelOperation,+ cancelSendMessageInServer: mockCancelSendMessageInServer,+ regenerateUserMessage: mockRegenerateUserMessage,+ regenerateAssistantMessage: mockRegenerateAssistantMessage,+ continueGenerationMessage: mockContinueGenerationMessage,+ deleteMessage: mockDeleteMessage,+ switchMessageBranch: mockSwitchMessageBranch,+ startOperation: mockStartOperation,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ executeGatewayAgent: mockExecuteGatewayAgent,+ internal_dispatchTopic: vi.fn(),+ openThreadCreator: mockOpenThreadCreator,+ updateTopicMetadata: mockUpdateTopicMetadata,+ updateTopicStatus: mockUpdateTopicStatus,+ })),+ setState: vi.fn(),+ },+}));++describe('Generation Actions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockSourceTopic.status = 'scheduled';+ });++ afterEach(() => {+ vi.clearAllTimers();+ });++ describe('continueGeneration', () => {+ it('should continue generation from assistantGroup message with last child as blockId', async () => {+ // Reset mock to ensure all required functions are available+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({+ dbMessagesMap: {},+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ topicDataMap: {},+ startOperation: mockStartOperation,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ } as any);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ groupId: 'group-1',+ };++ const store = createStore({ context });++ // Set displayMessages with assistantGroup message containing children+ act(() => {+ store.setState({+ displayMessages: [+ {+ id: 'group-msg-1',+ role: 'assistantGroup',+ content: '',+ children: [+ { id: 'child-1', content: 'First response' },+ { id: 'child-2', content: 'Second response' },+ ],+ },+ ],+ } as any);+ });++ await act(async () => {+ await store.getState().continueGeneration('group-msg-1');+ });++ // Should create operation with groupMessageId+ expect(mockStartOperation).toHaveBeenCalledWith({+ context: { ...context, messageId: 'group-msg-1' },+ type: 'continue',+ });++ // Should call executeClientAgent with last child id as parentMessageId+ expect(mockExecuteClientAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ context,+ parentMessageId: 'child-2', // last child's id+ parentMessageType: 'assistantGroup',+ parentOperationId: 'test-op-id',+ }),+ );+ });++ it('should not continue if message is not assistantGroup', async () => {+ // Reset mock to ensure all required functions are available+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({+ dbMessagesMap: {},+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ topicDataMap: {},+ startOperation: mockStartOperation,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ } as any);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: null,+ threadId: null,+ };++ const store = createStore({ context });++ // Set displayMessages with regular assistant message (not assistantGroup)+ act(() => {+ store.setState({+ displayMessages: [{ id: 'msg-1', role: 'assistant', content: 'Hello' }],+ } as any);+ });++ await act(async () => {+ await store.getState().continueGeneration('msg-1');+ });++ // Should not create operation if message is not assistantGroup+ expect(mockStartOperation).not.toHaveBeenCalled();+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();+ });++ it('should not continue if assistantGroup has no children', async () => {+ // Reset mock to ensure all required functions are available+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({+ dbMessagesMap: {},+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ topicDataMap: {},+ startOperation: mockStartOperation,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ } as any);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: null,+ threadId: null,+ };++ const store = createStore({ context });++ // Set displayMessages with assistantGroup but no children+ act(() => {+ store.setState({+ displayMessages: [+ { id: 'group-msg-1', role: 'assistantGroup', content: '', children: [] },+ ],+ } as any);+ });++ await act(async () => {+ await store.getState().continueGeneration('group-msg-1');+ });++ // Should not create operation if no children+ expect(mockStartOperation).not.toHaveBeenCalled();+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();+ });++ it('should call onBeforeContinue hook and respect false return', async () => {+ // Reset mock to ensure all required functions are available+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({+ dbMessagesMap: {},+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ topicDataMap: {},+ startOperation: mockStartOperation,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ } as any);++ const onBeforeContinue = vi.fn().mockResolvedValue(false);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: null,+ threadId: null,+ };+ const hooks: ConversationHooks = { onBeforeContinue };++ const store = createStore({ context, hooks });++ // Set displayMessages with assistantGroup+ act(() => {+ store.setState({+ displayMessages: [+ {+ id: 'group-msg-1',+ role: 'assistantGroup',+ content: '',+ children: [{ id: 'child-1', content: 'Response' }],+ },+ ],+ } as any);+ });++ await act(async () => {+ await store.getState().continueGeneration('group-msg-1');+ });++ expect(onBeforeContinue).toHaveBeenCalledWith('group-msg-1');+ // Should not call executeClientAgent if hook returns false+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();+ });++ it('should call onContinueComplete hook after continuation', async () => {+ // Reset mock to ensure all required functions are available+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({+ dbMessagesMap: {},+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ topicDataMap: {},+ startOperation: mockStartOperation,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent.mockResolvedValue(undefined),+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ } as any);++ const onContinueComplete = vi.fn();++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: null,+ threadId: null,+ };+ const hooks: ConversationHooks = { onContinueComplete };++ const store = createStore({ context, hooks });++ // Set displayMessages with assistantGroup+ act(() => {+ store.setState({+ displayMessages: [+ {+ id: 'group-msg-1',+ role: 'assistantGroup',+ content: '',+ children: [{ id: 'child-1', content: 'Response' }],+ },+ ],+ } as any);+ });++ await act(async () => {+ await store.getState().continueGeneration('group-msg-1');+ });++ expect(onContinueComplete).toHaveBeenCalledWith('group-msg-1');+ });++ it('should not continue if message is not found', async () => {+ // Reset mock to ensure all required functions are available+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({+ dbMessagesMap: {},+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ topicDataMap: {},+ startOperation: mockStartOperation,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ } as any);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: null,+ threadId: null,+ };++ const store = createStore({ context });++ // Set empty displayMessages+ act(() => {+ store.setState({+ displayMessages: [],+ } as any);+ });++ await act(async () => {+ await store.getState().continueGeneration('msg-not-exist');+ });++ // Should not create operation if message not found+ expect(mockStartOperation).not.toHaveBeenCalled();+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();+ });+ });++ // Retrying the failed step of a turn used to be "delete the block, then call+ // continueGeneration and hope it still finds a group". Verified live: it did+ // not. Both shapes below deleted the failed step and then created NO operation+ // at all — the answer was gone and nothing was running, with no toast.+});diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 80f5c47f63a..36def426471 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -46,6 +46,7 @@ const mockSourceTopic = {vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({+ dbMessagesMap: {},messagesMap: {'session-1-': [{ id: 'msg-1', role: 'user', content: 'Hello' },@@ -285,289 +286,6 @@ describe('Generation Actions', () => {});});- describe('continueGeneration', () => {- it('should continue generation from assistantGroup message with last child as blockId', async () => {- // Reset mock to ensure all required functions are available- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- messagesMap: {},- operations: {},- operationsByMessage: {},- topicDataMap: {},- startOperation: mockStartOperation,- associateMessageWithOperation: mockAssociateMessageWithOperation,- completeOperation: mockCompleteOperation,- failOperation: mockFailOperation,- executeClientAgent: mockExecuteClientAgent,- isGatewayModeEnabled: mockIsGatewayModeEnabled,- } as any);-- const context: ConversationContext = {- agentId: 'session-1',- topicId: 'topic-1',- threadId: null,- groupId: 'group-1',- };-- const store = createStore({ context });-- // Set displayMessages with assistantGroup message containing children- act(() => {- store.setState({- displayMessages: [- {- id: 'group-msg-1',- role: 'assistantGroup',- content: '',- children: [- { id: 'child-1', content: 'First response' },- { id: 'child-2', content: 'Second response' },- ],- },- ],- } as any);- });-- await act(async () => {- await store.getState().continueGeneration('group-msg-1');- });-- // Should create operation with groupMessageId- expect(mockStartOperation).toHaveBeenCalledWith({- context: { ...context, messageId: 'group-msg-1' },- type: 'continue',- });-- // Should call executeClientAgent with last child id as parentMessageId- expect(mockExecuteClientAgent).toHaveBeenCalledWith(- expect.objectContaining({- context,- parentMessageId: 'child-2', // last child's id- parentMessageType: 'assistantGroup',- parentOperationId: 'test-op-id',- }),- );- });-- it('should not continue if message is not assistantGroup', async () => {- // Reset mock to ensure all required functions are available- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- messagesMap: {},- operations: {},- operationsByMessage: {},- topicDataMap: {},- startOperation: mockStartOperation,- associateMessageWithOperation: mockAssociateMessageWithOperation,- completeOperation: mockCompleteOperation,- failOperation: mockFailOperation,- executeClientAgent: mockExecuteClientAgent,- isGatewayModeEnabled: mockIsGatewayModeEnabled,- } as any);-- const context: ConversationContext = {- agentId: 'session-1',- topicId: null,- threadId: null,- };-- const store = createStore({ context });-- // Set displayMessages with regular assistant message (not assistantGroup)- act(() => {- store.setState({- displayMessages: [{ id: 'msg-1', role: 'assistant', content: 'Hello' }],- } as any);- });-- await act(async () => {- await store.getState().continueGeneration('msg-1');- });-- // Should not create operation if message is not assistantGroup- expect(mockStartOperation).not.toHaveBeenCalled();- expect(mockExecuteClientAgent).not.toHaveBeenCalled();- });-- it('should not continue if assistantGroup has no children', async () => {- // Reset mock to ensure all required functions are available- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- messagesMap: {},- operations: {},- operationsByMessage: {},- topicDataMap: {},- startOperation: mockStartOperation,- associateMessageWithOperation: mockAssociateMessageWithOperation,- completeOperation: mockCompleteOperation,- failOperation: mockFailOperation,- executeClientAgent: mockExecuteClientAgent,- isGatewayModeEnabled: mockIsGatewayModeEnabled,- } as any);-- const context: ConversationContext = {- agentId: 'session-1',- topicId: null,- threadId: null,- };-- const store = createStore({ context });-- // Set displayMessages with assistantGroup but no children- act(() => {- store.setState({- displayMessages: [- { id: 'group-msg-1', role: 'assistantGroup', content: '', children: [] },- ],- } as any);- });-- await act(async () => {- await store.getState().continueGeneration('group-msg-1');- });-- // Should not create operation if no children- expect(mockStartOperation).not.toHaveBeenCalled();- expect(mockExecuteClientAgent).not.toHaveBeenCalled();- });-- it('should call onBeforeContinue hook and respect false return', async () => {- // Reset mock to ensure all required functions are available- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- messagesMap: {},- operations: {},- operationsByMessage: {},- topicDataMap: {},- startOperation: mockStartOperation,- associateMessageWithOperation: mockAssociateMessageWithOperation,- completeOperation: mockCompleteOperation,- failOperation: mockFailOperation,- executeClientAgent: mockExecuteClientAgent,- isGatewayModeEnabled: mockIsGatewayModeEnabled,- } as any);-- const onBeforeContinue = vi.fn().mockResolvedValue(false);-- const context: ConversationContext = {- agentId: 'session-1',- topicId: null,- threadId: null,- };- const hooks: ConversationHooks = { onBeforeContinue };-- const store = createStore({ context, hooks });-- // Set displayMessages with assistantGroup- act(() => {- store.setState({- displayMessages: [- {- id: 'group-msg-1',- role: 'assistantGroup',- content: '',- children: [{ id: 'child-1', content: 'Response' }],- },- ],- } as any);- });-- await act(async () => {- await store.getState().continueGeneration('group-msg-1');- });-- expect(onBeforeContinue).toHaveBeenCalledWith('group-msg-1');- // Should not call executeClientAgent if hook returns false- expect(mockExecuteClientAgent).not.toHaveBeenCalled();- });-- it('should call onContinueComplete hook after continuation', async () => {- // Reset mock to ensure all required functions are available- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- messagesMap: {},- operations: {},- operationsByMessage: {},- topicDataMap: {},- startOperation: mockStartOperation,- associateMessageWithOperation: mockAssociateMessageWithOperation,- completeOperation: mockCompleteOperation,- failOperation: mockFailOperation,- executeClientAgent: mockExecuteClientAgent.mockResolvedValue(undefined),- isGatewayModeEnabled: mockIsGatewayModeEnabled,- } as any);-- const onContinueComplete = vi.fn();-- const context: ConversationContext = {- agentId: 'session-1',- topicId: null,- threadId: null,- };- const hooks: ConversationHooks = { onContinueComplete };-- const store = createStore({ context, hooks });-- // Set displayMessages with assistantGroup- act(() => {- store.setState({- displayMessages: [- {- id: 'group-msg-1',- role: 'assistantGroup',- content: '',- children: [{ id: 'child-1', content: 'Response' }],- },- ],- } as any);- });-- await act(async () => {- await store.getState().continueGeneration('group-msg-1');- });-- expect(onContinueComplete).toHaveBeenCalledWith('group-msg-1');- });-- it('should not continue if message is not found', async () => {- // Reset mock to ensure all required functions are available- vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- messagesMap: {},- operations: {},- operationsByMessage: {},- topicDataMap: {},- startOperation: mockStartOperation,- associateMessageWithOperation: mockAssociateMessageWithOperation,- completeOperation: mockCompleteOperation,- failOperation: mockFailOperation,- executeClientAgent: mockExecuteClientAgent,- isGatewayModeEnabled: mockIsGatewayModeEnabled,- } as any);-- const context: ConversationContext = {- agentId: 'session-1',- topicId: null,- threadId: null,- };-- const store = createStore({ context });-- // Set empty displayMessages- act(() => {- store.setState({- displayMessages: [],- } as any);- });-- await act(async () => {- await store.getState().continueGeneration('msg-not-exist');- });-- // Should not create operation if message not found- expect(mockStartOperation).not.toHaveBeenCalled();- expect(mockExecuteClientAgent).not.toHaveBeenCalled();- });- });-- // Retrying the failed step of a turn used to be "delete the block, then call- // continueGeneration and hope it still finds a group". Verified live: it did- // not. Both shapes below deleted the failed step and then created NO operation- // at all — the answer was gone and nothing was running, with no toast.describe('retryFailedAssistantStep', () => {const context: ConversationContext = {agentId: 'session-1',@@ -578,6 +296,7 @@ describe('Generation Actions', () => {const mockChatStore = async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},dbMessagesMap: {},operations: {},@@ -763,6 +482,7 @@ describe('Generation Actions', () => {// Re-setup mock to ensure all required functions are availableconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -830,6 +550,7 @@ describe('Generation Actions', () => {// Re-setup mock to track call orderconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -902,6 +623,7 @@ describe('Generation Actions', () => {it('should not proceed if assistant message has no parentId', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -948,6 +670,7 @@ describe('Generation Actions', () => {// this sub-second window and applies to the fresh run instead).let operationCount = 0;const chatState: any = {+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1037,6 +760,7 @@ describe('Generation Actions', () => {resolveDelete = resolve;});const chatState: any = {+ dbMessagesMap: {},dbMessagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },messagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },operations: {},@@ -1100,6 +824,7 @@ describe('Generation Actions', () => {let operationCount = 0;const executeClientAgent = vi.fn().mockRejectedValue(new Error('boom'));const chatState: any = {+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1156,6 +881,7 @@ describe('Generation Actions', () => {// Re-setup mock to ensure startOperation is availableconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1211,6 +937,7 @@ describe('Generation Actions', () => {// Re-setup mock with all required propertiesconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1271,6 +998,7 @@ describe('Generation Actions', () => {// Re-setup mock with all required propertiesconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1322,6 +1050,7 @@ describe('Generation Actions', () => {it('should bail out if the interim op was cancelled during preflight (Stop pressed)', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},// Simulate the user hitting Stop during the preflight awaits: stopGenerating// has already flipped the interim regenerate op to 'cancelled'.@@ -1375,6 +1104,7 @@ describe('Generation Actions', () => {// The op passes the preflight guard as 'running', then a Stop lands while// switchMessageBranch is awaiting — flip it to cancelled inside the mock.const chatState: any = {+ dbMessagesMap: {},messagesMap: {},operations: { 'test-op-id': { id: 'test-op-id', status: 'running' } },operationsByMessage: {},@@ -1424,6 +1154,7 @@ describe('Generation Actions', () => {it('should restore mention-based initialContext when regenerating a user message', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1499,6 +1230,7 @@ describe('Generation Actions', () => {it('should use executeGatewayAgent when gateway mode is enabled', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1571,6 +1303,7 @@ describe('Generation Actions', () => {it('should call onRegenerateComplete hook after gateway regeneration', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1616,6 +1349,7 @@ describe('Generation Actions', () => {it('should fall back to client mode when gateway is disabled', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1659,6 +1393,7 @@ describe('Generation Actions', () => {it('should not regenerate if the message already has a running regenerate op', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {'op-1': {@@ -1703,6 +1438,7 @@ describe('Generation Actions', () => {it('regenerates despite an unrelated running op left on the message', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},dbMessagesMap: {},operations: {@@ -1775,6 +1511,7 @@ describe('Generation Actions', () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -2205,6 +1942,7 @@ describe('Generation Actions', () => {it('returns early without starting an operation or dispatching any runtime', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ dbMessagesMap: {},messagesMap: {},operations: {},operationsByMessage: {},diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.tsindex d5e7a1f3b62..be3ef314b8f 100644--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts@@ -121,6 +121,7 @@ const noop = vi.fn();vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({+ dbMessagesMap: {},operations: {},operationsByMessage: {},@@ -149,7 +150,8 @@ const USER_MESSAGE = { content: 'clean up worktrees', id: 'user-1', role: 'user'* and immediately died on the usage limit. `step-1` is also the group id.*/const buildGroupStore = (children: any[], dbMessages?: any[]) => {- const store = createStore({ context: CONTEXT });+ // A static transcript: the chat store is mocked, so rows are held locally.+ const store = createStore({ context: CONTEXT, messages: [] });act(() => {store.setState({dbMessages: dbMessages ?? [diff --git a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.tsindex ea5e62845ed..7ffae527fc4 100644--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts@@ -83,6 +83,7 @@ const noop = vi.fn();vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({+ dbMessagesMap: {},operations: {},operationsByMessage: {},diff --git a/src/features/Conversation/store/slices/message/action/crud.test.ts b/src/features/Conversation/store/slices/message/action/crud.test.tsindex 8259d77e1ae..52bce7a08ab 100644--- a/src/features/Conversation/store/slices/message/action/crud.test.ts+++ b/src/features/Conversation/store/slices/message/action/crud.test.ts@@ -125,14 +125,11 @@ describe('Message CRUD Actions', () => {},];const store = createTestStore(oldContext);- const onMessagesChange = vi.fn();- store.setState({ onMessagesChange });const createPromise = store.getState().createMessage({content: 'old topic message',role: 'user',});- onMessagesChange.mockClear();store.setState({context: currentContext,dbMessages: currentMessages,@@ -160,7 +157,6 @@ describe('Message CRUD Actions', () => {expect(result).toBeUndefined();expect(store.getState().dbMessages).toEqual(currentMessages);- expect(onMessagesChange).not.toHaveBeenCalled();});});diff --git a/src/features/Conversation/store/slices/message/action/state.test.ts b/src/features/Conversation/store/slices/message/action/state.test.tsindex 04d31b4353a..1d71f6ade74 100644--- a/src/features/Conversation/store/slices/message/action/state.test.ts+++ b/src/features/Conversation/store/slices/message/action/state.test.ts@@ -8,6 +8,9 @@ import { createStore } from '../../../index';const { chatStoreMock } = vi.hoisted(() => ({chatStoreMock: {cancelOperations: vi.fn(),+ dbMessagesMap: {},+ messagesMap: {},+ replaceMessages: vi.fn(),operations: {},operationsByContext: {},},diff --git a/src/features/Conversation/store/slices/tool/action.test.ts b/src/features/Conversation/store/slices/tool/action.test.tsindex 6c624a9e344..97c52aa42f0 100644--- a/src/features/Conversation/store/slices/tool/action.test.ts+++ b/src/features/Conversation/store/slices/tool/action.test.ts@@ -13,6 +13,7 @@ const mockSubmitHeteroIntervention = vi.fn();vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({+ dbMessagesMap: {},messagesMap: {},operations: {},approveToolCalling: mockApproveToolCalling,diff --git a/src/features/Conversation/types/context.ts b/src/features/Conversation/types/context.tsindex e44800a7e96..58a8d1dde38 100644--- a/src/features/Conversation/types/context.ts+++ b/src/features/Conversation/types/context.ts@@ -29,23 +29,6 @@ export interface ConversationContext extends BaseConversationContext {*/export type ConversationMetadata<T = Record<string, any>> = T;-/**- * Metadata passed alongside `onMessagesChange` so the handler can tell WHERE- * the messages came from.- *- * `source: 'fetch'` — a server snapshot delivered by the conversation SWR sync- * (cache hydration or revalidation completion), as opposed to an internal- * mutation (edit / delete / stream dispatch). Handlers forwarding into- * `ChatStore.replaceMessages` must pass this through as `source` so the SWR- * write-through skips it: re-writing the cache with the (possibly stale)- * snapshot while the mount-time revalidation is in flight trips SWR's mutation- * race guard, which discards the fresh result and locks the conversation on- * the stale list.- */-export interface MessagesChangeMeta {- source: 'fetch';-}-/*** Common metadata types*/diff --git a/src/features/DevPanel/RenderGallery/MessageList.tsx b/src/features/DevPanel/RenderGallery/MessageList.tsxindex dc6a6620eec..6ef193488ba 100644--- a/src/features/DevPanel/RenderGallery/MessageList.tsx+++ b/src/features/DevPanel/RenderGallery/MessageList.tsx@@ -170,7 +170,7 @@ const MessageList = memo<MessageListProps>(({ apis, mode }) => {}return (- <ConversationProvider hasInitMessages skipFetch context={context} messages={messages}>+ <ConversationProvider context={context} messages={messages}><InnerList /></ConversationProvider>);diff --git a/src/features/DevPanel/RenderGallery/toolSurfaces.tsx b/src/features/DevPanel/RenderGallery/toolSurfaces.tsxindex 5298453cf7b..0287c69540d 100644--- a/src/features/DevPanel/RenderGallery/toolSurfaces.tsx+++ b/src/features/DevPanel/RenderGallery/toolSurfaces.tsx@@ -168,7 +168,7 @@ const InterventionConversationHost = memo<InterventionConversationHostProps>(}, [api, derived.args, messageId, toolCallId]);return (- <ConversationProvider hasInitMessages skipFetch context={context} messages={messages}>+ <ConversationProvider context={context} messages={messages}>{children}</ConversationProvider>);diff --git a/src/features/FloatingChatPanel/index.test.tsx b/src/features/FloatingChatPanel/index.test.tsxindex b49f3c9fbfa..12b65db2efe 100644--- a/src/features/FloatingChatPanel/index.test.tsx+++ b/src/features/FloatingChatPanel/index.test.tsx@@ -111,19 +111,11 @@ vi.mock('@/features/Conversation', () => ({/>),ChatList: () => null,- ConversationProvider: ({- children,- context,- hooks,- skipFetch,- hasInitMessages,- messages,- }: any) => {+ ConversationProvider: ({ children, context, hooks, skipFetch, messages }: any) => {mergedHooksCaptured.current = hooks;return (<divdata-context={JSON.stringify(context)}- data-has-init-messages={String(hasInitMessages ?? false)}data-has-messages-prop={String(messages !== undefined)}data-skip-fetch={String(skipFetch ?? false)}data-testid="provider"@@ -248,21 +240,14 @@ describe('FloatingChatPanel', () => {});});- it('lets ConversationProvider drive the fetch when the chat store has no slice yet', () => {- const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);- const provider = getByTestId('provider');- expect(provider.dataset.skipFetch).toBe('false');- expect(provider.dataset.hasInitMessages).toBe('false');- });-- it('syncs the chat store slice into ConversationProvider when the topic already has messages', () => {+ it('shows the chat store bucket of its context instead of passing a static transcript', () => {mockChatState.current.dbMessagesMap = {'agent-1:topic-1:null': [{ id: 'msg-1' }],};const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);const provider = getByTestId('provider');- expect(provider.dataset.hasInitMessages).toBe('true');- expect(provider.dataset.hasMessagesProp).toBe('true');+ expect(provider.dataset.skipFetch).toBe('false');+ expect(provider.dataset.hasMessagesProp).toBe('false');});it('forwards title and headerActions to floating panel header', () => {diff --git a/src/features/FloatingChatPanel/index.tsx b/src/features/FloatingChatPanel/index.tsxindex aab8bd2c81a..d40c884ebc2 100644--- a/src/features/FloatingChatPanel/index.tsx+++ b/src/features/FloatingChatPanel/index.tsx@@ -1,6 +1,5 @@'use client';-import { type UIChatMessage } from '@lobechat/types';import { ActionIcon, FloatingSheet, type FloatingSheetProps } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';import { ChevronDown } from 'lucide-react';@@ -14,7 +13,7 @@ import {ConversationProvider,} from '@/features/Conversation';import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';-import { type ConversationContext, type MessagesChangeMeta } from '@/features/Conversation/types';+import { type ConversationContext } from '@/features/Conversation/types';import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConversationHooks';import CopilotToolbar from '@/features/PageEditor/Copilot/Toolbar';import { PageAgentPanelOverrideProvider } from '@/features/PageEditor/RightPanel/OverrideContext';@@ -22,7 +21,6 @@ import { useOperationState } from '@/hooks/useOperationState';import { useActionsBarConfig } from '@/routes/(main)/agent/features/Conversation/useActionsBarConfig';import { useAgentStore } from '@/store/agent';import { chatConfigByIdSelectors } from '@/store/agent/selectors';-import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import ChatBody from './ChatBody';@@ -167,21 +165,6 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(const chatKey = useMemo(() => messageMapKey(context), [context]);- // ConversationProvider runs an isolated message store per panel — read the- // shared chat store's `dbMessagesMap` for this key and wire the standard- // `messages` / `onMessagesChange` sync pattern (mirrors `ConversationArea`- // in the main agent route). Without this loop the lifecycle's- // `chatStore.replaceMessages` after a send wouldn't propagate back into- // the panel's local message slice and the UI would stay empty.- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const handleMessagesChange = useCallback(- (next: UIChatMessage[], ctx: ConversationContext, meta?: MessagesChangeMeta) => {- replaceMessages(next, { context: ctx, source: meta?.source });- },- [replaceMessages],- );-const operationState = useOperationState(context);const defaultActionsBar = useActionsBarConfig();const resolvedActionsBar = actionsBar ?? defaultActionsBar;@@ -271,11 +254,8 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(<ConversationProvideractionsBar={resolvedActionsBar}context={context}- hasInitMessages={!!messages}hooks={mergedHooks}- messages={messages}operationState={operationState}- onMessagesChange={handleMessagesChange}><divclassName={`${styles.panel} ${isEmbedded ? styles.panelEmbedded : ''}`}diff --git a/src/features/GlobalApprovalNotification/ApprovalCard.tsx b/src/features/GlobalApprovalNotification/ApprovalCard.tsxindex a9a3bb7d560..1c4191abec8 100644--- a/src/features/GlobalApprovalNotification/ApprovalCard.tsx+++ b/src/features/GlobalApprovalNotification/ApprovalCard.tsx@@ -1,7 +1,7 @@'use client';import { AGENT_CHAT_TOPIC_URL, GROUP_CHAT_TOPIC_URL, GROUP_CHAT_URL } from '@lobechat/const';-import { agentDisplayName, type UIChatMessage } from '@lobechat/types';+import { agentDisplayName } from '@lobechat/types';import { ActionIcon, Avatar } from '@lobehub/ui/base-ui';import { ArrowUpRight, ChevronUp } from 'lucide-react';import { memo, useCallback, useMemo, useState } from 'react';@@ -12,7 +12,6 @@ import { ConversationProvider } from '@/features/Conversation';import InterventionContent from '@/features/Conversation/InterventionBar/InterventionContent';import InterventionTabBar from '@/features/Conversation/InterventionBar/InterventionTabBar';import MarkdownMessage from '@/features/Conversation/Markdown';-import { type ConversationContext, type MessagesChangeMeta } from '@/features/Conversation/types';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useOperationState } from '@/hooks/useOperationState';@@ -49,13 +48,6 @@ const ApprovalCard = memo<ApprovalCardProps>(({ group, onCollapse }) => {const chatKey = useMemo(() => messageMapKey(context), [context]);const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const handleMessagesChange = useCallback(- (next: UIChatMessage[], ctx: ConversationContext, meta?: MessagesChangeMeta) => {- replaceMessages(next, { context: ctx, source: meta?.source });- },- [replaceMessages],- );const operationState = useOperationState(context);const meta = useAgentStore(agentSelectors.getAgentMetaById(context.agentId));@@ -140,14 +132,7 @@ const ApprovalCard = memo<ApprovalCardProps>(({ group, onCollapse }) => {if (!activeIntervention) return null;return (- <ConversationProvider- skipFetch- context={context}- hasInitMessages={!!messages}- messages={messages}- operationState={operationState}- onMessagesChange={handleMessagesChange}- >+ <ConversationProvider skipFetch context={context} operationState={operationState}><div data-pending-hotkey-scope className={styles.card}><div className={styles.header}><Avatardiff --git a/src/features/PageEditor/PageAgentProvider.tsx b/src/features/PageEditor/PageAgentProvider.tsxindex bceb22416eb..49727bce405 100644--- a/src/features/PageEditor/PageAgentProvider.tsx+++ b/src/features/PageEditor/PageAgentProvider.tsx@@ -10,7 +10,6 @@ import { useOperationState } from '@/hooks/useOperationState';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';interface PageAgentProviderProps {children: ReactNode;@@ -94,11 +93,6 @@ export const PageAgentProvider = memo<PageAgentProviderProps>([selectedAgentId, activeTopicId, pageId, syncActiveAgent],);- // Get messages from ChatStore based on context- const chatKey = useMemo(() => messageMapKey(context), [context]);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => (chatKey ? s.dbMessagesMap[chatKey] : undefined));-// Get operation state for reactive updatesconst operationState = useOperationState(context);@@ -107,15 +101,7 @@ export const PageAgentProvider = memo<PageAgentProviderProps>(if (!pageAgentId) return <SurfaceSkeleton variant={'editor'} />;return (- <ConversationProvider- context={context}- hasInitMessages={!!messages}- messages={messages}- operationState={operationState}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context} operationState={operationState}>{children}</ConversationProvider>);diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsxindex 38f8bd32f82..3fc3e76af59 100644--- a/src/features/Portal/Thread/Chat/index.tsx+++ b/src/features/Portal/Thread/Chat/index.tsx@@ -223,11 +223,6 @@ const ThreadChat = memo(() => {[chatKey, portalThread?.metadata?.sourceToolCallId, threadMetadataResolved],);- // Subscribe directly to dbMessagesMap for reactive updates- // This ensures optimistic updates work (read/write use same key)- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);-// Get operation state for reactive updatesconst operationState = useOperationState(context);@@ -276,14 +271,9 @@ const ThreadChat = memo(() => {actionsBar={actionsBarConfig}composerTarget={composerTarget}context={context}- hasInitMessages={!!messages}hooks={hooks}- messages={messages}operationState={operationState}skipFetch={isCreatingNewThread}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}><ThreadChatContentcomposerWritable={composerTarget.writable}diff --git a/src/features/Portal/Topic/Chat/index.tsx b/src/features/Portal/Topic/Chat/index.tsxindex b6227858638..bb6582a1700 100644--- a/src/features/Portal/Topic/Chat/index.tsx+++ b/src/features/Portal/Topic/Chat/index.tsx@@ -53,8 +53,6 @@ const TopicChat = memo(() => {);const chatKey = useMemo(() => messageMapKey(context), [context]);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);const operationState = useOperationState(context);@@ -88,16 +86,7 @@ const TopicChat = memo(() => {if (!portalTopicId) return null;return (- <ConversationProvider- context={context}- hasInitMessages={!!messages}- hooks={hooks}- messages={messages}- operationState={operationState}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context} hooks={hooks} operationState={operationState}><Suspensefallback={<Flexbox flex={1} height={'100%'}>diff --git a/src/features/ShareModal/ShareImage/ChatList/index.tsx b/src/features/ShareModal/ShareImage/ChatList/index.tsxindex 8ed2b7f2e72..30ba7cc2a8b 100644--- a/src/features/ShareModal/ShareImage/ChatList/index.tsx+++ b/src/features/ShareModal/ShareImage/ChatList/index.tsx@@ -36,15 +36,8 @@ interface ChatListProps {}const ChatList = memo<ChatListProps>(({ context, ids, messages }) => {- const hasInitMessages = messages.length > 0;-return (- <ConversationProvider- context={context}- hasInitMessages={hasInitMessages}- messages={messages}- skipFetch={true}- >+ <ConversationProvider context={context} messages={messages}><ChatListContent ids={ids} /></ConversationProvider>);diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex 179fa01ca47..babfd91d3ba 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -10,11 +10,7 @@ import {const preHydrateTopicListMock = vi.hoisted(() => vi.fn(async () => true));const getSidebarTopicListParamsMock = vi.hoisted(() => vi.fn());-const readPersistedTranscriptMock = vi.hoisted(() => vi.fn());-const chatState = vi.hoisted(() => ({- dbMessagesMap: {} as Record<string, unknown[]>,- replaceMessages: vi.fn(),-}));+const preHydrateMessagesMock = vi.hoisted(() => vi.fn(async () => true));const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);const preHydrateBuiltinAgentMock = vi.hoisted(() => vi.fn(async () => true));@@ -41,14 +37,13 @@ vi.mock('@/store/agent/selectors', () => ({vi.mock('@/store/chat', () => ({useChatStore: {- getState: () => ({ ...chatState, preHydrateTopicList: preHydrateTopicListMock }),+ getState: () => ({+ preHydrateMessages: preHydrateMessagesMock,+ preHydrateTopicList: preHydrateTopicListMock,+ }),},}));-vi.mock('@/services/message/replica', () => ({- readPersistedTranscript: readPersistedTranscriptMock,-}));-const loaderArgs = (aid?: string) => ({ params: aid ? { aid } : {} }) as never;describe('agent chat topic list loader', () => {@@ -125,41 +120,29 @@ describe('agent chat topic list loader', () => {});describe('agent chat transcript pre-hydrate', () => {- const rows = [{ content: 'hi', id: 'msg_1', role: 'user' }];-beforeEach(() => {- chatState.dbMessagesMap = {};- chatState.replaceMessages.mockClear();- readPersistedTranscriptMock.mockReset();- readPersistedTranscriptMock.mockResolvedValue({ items: rows });+ preHydrateMessagesMock.mockClear();});it("seeds the topic's persisted transcript into the chat store before the route commits", async () => {await agentChatTopicListLoader({ params: { aid: 'agt_1', topicId: 'tpc_1' } } as never);- const context = { agentId: 'agt_1', scope: 'main', topicId: 'tpc_1' };- expect(readPersistedTranscriptMock).toHaveBeenCalledWith(context);- expect(chatState.replaceMessages).toHaveBeenCalledWith(rows, {- action: 'preHydrateMessages',- context,- source: 'fetch',+ expect(preHydrateMessagesMock).toHaveBeenCalledWith({+ agentId: 'agt_1',+ scope: 'main',+ topicId: 'tpc_1',});});- it('never replaces rows the chat store already holds', async () => {- chatState.dbMessagesMap = { main_agt_1_tpc_1: [] };-- await preHydrateMessagesForRoute('agt_1', 'tpc_1');+ it('skips a route without a topic', async () => {+ await preHydrateMessagesForRoute('agt_1');- expect(chatState.replaceMessages).not.toHaveBeenCalled();+ expect(preHydrateMessagesMock).not.toHaveBeenCalled();});- it('skips a route without a topic and a miss in storage', async () => {- await preHydrateMessagesForRoute('agt_1');- expect(readPersistedTranscriptMock).not.toHaveBeenCalled();+ it('never rejects the route when the transcript hydrate fails', async () => {+ preHydrateMessagesMock.mockRejectedValueOnce(new Error('storage exploded'));- readPersistedTranscriptMock.mockResolvedValue(undefined);- await preHydrateMessagesForRoute('agt_1', 'tpc_1');- expect(chatState.replaceMessages).not.toHaveBeenCalled();+ await expect(preHydrateMessagesForRoute('agt_1', 'tpc_1')).resolves.toBeUndefined();});});diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex 05c361309f9..819a0d3d119 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -3,11 +3,9 @@ import type { LoaderFunctionArgs } from 'react-router';import { getSidebarTopicListParams } from '@/hooks/chatTopicListQuery';import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';-import { readPersistedTranscript } from '@/services/message/replica';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));@@ -47,7 +45,7 @@ export const preHydrateTopicListForRoute = async (routeAgentId?: string): Promis/*** Seed the persisted transcript of a route's topic into the chat store.*- * The conversation is hosted on the chat store's bucket, so rows landing there+ * The conversation renders the chat store's bucket, so rows landing there* before the route commits reach the Conversation as its first-frame messages:* a topic opened before paints from local data and only revalidates in the* background, instead of painting a skeleton until the network answers.@@ -59,24 +57,10 @@ export const preHydrateMessagesForRoute = async (const agentId = resolveRouteAgentId(routeAgentId);if (!agentId || !topicId) return;- const context = { agentId, scope: 'main' as const, topicId };- const seed = async () => {- const transcript = await readPersistedTranscript(context);- if (!transcript?.items.length) return;-- const chat = useChatStore.getState();- // Rows already in memory (this session's, or streamed) are newer.- if (chat.dbMessagesMap[messageMapKey(context)]) return;- // `source: 'fetch'`: a stored server snapshot, not a local edit — it must- // not be written through as if it were fresh.- chat.replaceMessages(transcript.items, {- action: 'preHydrateMessages',- context,- source: 'fetch',- });- };-- await settleWithin(seed(), PRE_PAINT_HYDRATE_TIMEOUT);+ await settleWithin(+ useChatStore.getState().preHydrateMessages({ agentId, scope: 'main', topicId }),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );};/** Loader for the agent chat routes (`/agent/:aid`, `/agent/:aid/:topicId`). */diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsxindex 5e4fccf9f75..683a1d59a20 100644--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx@@ -2,7 +2,6 @@import { Flexbox } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';-import debug from 'debug';import { memo, Suspense, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -41,8 +40,6 @@ import MessageFromUrl from './MainChatInput/MessageFromUrl';import ThreadHydration from './ThreadHydration';import { useActionsBarConfig } from './useActionsBarConfig';-const log = debug('lobe-render:agent:ConversationArea');-const styles = createStaticStyles(({ css }) => ({// When the chat column is wide enough for the header to float above the// full-bleed list (see Conversation/Header), this in-list spacer keeps the@@ -72,10 +69,6 @@ const Conversation = memo(() => {// Get raw dbMessages from ChatStore for this context// ConversationStore will parse them internally to generate displayMessagesconst chatKey = messageMapKey(context);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);-- log('contextKey %s: %o', chatKey, messages);// Get operation state from ChatStore for reactive updatesconst operationState = useOperationState(context);@@ -134,13 +127,8 @@ const Conversation = memo(() => {<ConversationProvideractionsBar={actionsBarConfig}context={context}- hasInitMessages={!!messages}hooks={hooks}- messages={messages}operationState={operationState}- onMessagesChange={(messages, ctx, meta) => {- replaceMessages(messages, { context: ctx, source: meta?.source });- }}><SplitDropZone><Flexboxdiff --git a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx b/src/routes/(main)/group/features/Conversation/ConversationArea.tsxindex 4d3ada2123f..80bc30f689f 100644--- a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/group/features/Conversation/ConversationArea.tsx@@ -17,8 +17,6 @@ import {MessageForwardFooter,} from '@/features/Conversation/MessageForward';import { useOperationState } from '@/hooks/useOperationState';-import { useChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';import WelcomeChatItem from './AgentWelcome';import ChatHydration from './ChatHydration';@@ -45,9 +43,6 @@ const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {// Get raw dbMessages from ChatStore for this context// ConversationStore will parse them internally to generate displayMessages- const chatKey = messageMapKey(context);- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);// Get operation state from ChatStore for reactive updatesconst operationState = useOperationState(context);@@ -67,12 +62,7 @@ const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {<ConversationProvideractionsBar={actionsBarConfig}context={context}- hasInitMessages={!!messages}- messages={messages}operationState={operationState}- onMessagesChange={(messages, ctx, meta) => {- replaceMessages(messages, { context: ctx, source: meta?.source });- }}><Flexboxflex={1}diff --git a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsxindex ace61bdf4c5..1d1f9461830 100644--- a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx+++ b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx@@ -6,7 +6,6 @@ import { ConversationProvider } from '@/features/Conversation';import { useOperationState } from '@/hooks/useOperationState';import { useChatStore } from '@/store/chat';import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';interface AgentBuilderProviderProps {agentId: string;@@ -43,28 +42,11 @@ const AgentBuilderProvider = memo<AgentBuilderProviderProps>(({ agentId, childre[agentId, activeTopicId, gid],);- // Get messages from ChatStore based on context- const chatKey = useMemo(- () => (context ? messageMapKey(context) : null),- [context?.agentId, context?.groupId, context?.topicId],- );-- const replaceMessages = useChatStore((s) => s.replaceMessages);- const messages = useChatStore((s) => (chatKey ? s.dbMessagesMap[chatKey] : undefined));-// Get operation state for reactive updatesconst operationState = useOperationState(context);return (- <ConversationProvider- context={context}- hasInitMessages={!!messages}- messages={messages}- operationState={operationState}- onMessagesChange={(msgs, ctx, meta) => {- replaceMessages(msgs, { context: ctx, source: meta?.source });- }}- >+ <ConversationProvider context={context} operationState={operationState}>{children}</ConversationProvider>);diff --git a/src/services/message/replica.ts b/src/services/message/replica.tsindex e3a2114e99b..e9f88231922 100644--- a/src/services/message/replica.ts+++ b/src/services/message/replica.ts@@ -10,15 +10,10 @@ import {type ReplicaRow,type ReplicaRowKey,type ReplicaStorage,- ReplicaWriteQueue,} from '@/libs/replica';import { normalizeMessageListQueryContext } from '@/libs/swr/keys';import type { MessageService } from '@/services/message';-import {- getMessageListWindowOlderCursor,- messageListKey,- type MessageRoundCursor,-} from '@/services/message/cache';+import { messageListKey, type MessageRoundCursor } from '@/services/message/cache';import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -53,15 +48,22 @@ const isSyntheticGroupNode = (message: UIChatMessage) =>const isPersistableContext = (context: ConversationContext) => {if (!context.agentId || !context.topicId) return false;if (context.agentShareId || context.topicShareId) return false;- const canonical = messageMapKey({- agentId: context.agentId,- groupId: context.groupId,+ return messageMapKey(context) === canonicalBucketOf(context);+};++const canonicalBucketOf = (context: {+ agentId?: string | null;+ groupId?: string | null;+ threadId?: string | null;+ topicId?: string | null;+}) =>+ messageMapKey({+ agentId: context.agentId ?? '',+ groupId: context.groupId ?? undefined,scope: context.threadId ? 'thread' : context.groupId ? 'group' : 'main',threadId: context.threadId,topicId: context.topicId,});- return messageMapKey(context) === canonical;-};/*** Entry identity of a conversation. Persistable conversations key by the@@ -72,7 +74,18 @@ const isPersistableContext = (context: ConversationContext) => {export const conversationMessagesKey = (context: ConversationContext) =>isPersistableContext(context)? `p:${JSON.stringify(normalizeMessageListQueryContext(context))}`- : `m:${messageMapKey(context)}`;+ : `m:${JSON.stringify({ bucket: messageMapKey(context), threadId: context.threadId ?? null })}`;++/**+ * The chat store bucket (`messageMapKey`) an entry key renders into, and the+ * thread its rows are parsed for. Every key is built by+ * {@link conversationMessagesKey}, so both are recoverable from it.+ */+export const transcriptBucketOf = (key: string): { bucket: string; threadId: string | null } => {+ const value = JSON.parse(key.slice(2));+ if (key.startsWith('p:')) return { bucket: canonicalBucketOf(value), threadId: value.threadId };+ return value;+};const transcriptPaging: ReplicaPagingConfig<UIChatMessage, MessageRoundCursor> = {// Only reached for read paths without round cursors (threads, shared@@ -123,64 +136,6 @@ export const transcriptOf = (items: UIChatMessage[]): ConversationMessagePage =>pageSize: items.length,});-/**- * The transcript persisted for a conversation, read without a store — for the- * route loader, which runs before any Conversation store exists. `undefined`- * when the conversation is kept in memory only or nothing is stored.- */-export const readPersistedTranscript = async (- context: ConversationContext,-): Promise<ConversationMessagePage | undefined> => {- const { persistKey, scope, storage, storageKey } = conversationMessagesResource;- if (!storage || !persistKey(conversationMessagesKey(context))) return undefined;- const row = await storage.get({ queryKey: storageKey(context), scope: scope.get() });- return row?.data;-};--// Terminal host updates also arrive for conversations whose component has unmounted.-const settledTranscriptWrites = new ReplicaWriteQueue(conversationMessagesResource.storage!);--export const persistSettledTranscript = (- context: ConversationContext,- messages: UIChatMessage[],-) => {- const resource = conversationMessagesResource;- const scope = resource.scope.get();- if (!resource.scope.canPersist() || !resource.persistKey(resource.key(context))) return;- const cursor = getMessageListWindowOlderCursor(context);- settledTranscriptWrites.update({ queryKey: resource.storageKey(context), scope }, (current) => {- const previous = current?.data;- const cursorBoundary = cursor ? messages.findIndex((message) => message.id === cursor.id) : -1;- // Threads have no round cursor. The persisted projection still identifies- // their head window, including synthetic nodes sorted before its first row.- const previousIds = new Set(- previous?.items.filter((item) => !isSyntheticGroupNode(item)).map((item) => item.id),- );- const boundary =- cursorBoundary >= 0 ? cursorBoundary : messages.findIndex((item) => previousIds.has(item.id));- const syntheticIds = new Set(- previous?.items.filter(isSyntheticGroupNode).map((item) => item.id),- );- const head =- cursor === null- ? messages- : boundary >= 0- ? messages.filter((item, index) => index >= boundary || syntheticIds.has(item.id))- : previous- ? messages.slice(-previous.items.length)- : messages;- const data = transcriptOf(head);- if (cursor === null || cursorBoundary >= 0) {- data.nextCursor = cursor;- data.hasMore = cursor !== null;- } else if (boundary >= 0 && previous?.items[0]?.id === messages[boundary]?.id) {- data.nextCursor = previous.nextCursor;- data.hasMore = previous.hasMore;- }- return { data: toPersistedTranscript(data), updatedAt: Date.now() };- });-};-// ---- tool result payloads ------------------------------------------------/**diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.tsindex 9293d4e1c45..767e5bb7713 100644--- a/src/store/chat/slices/message/action.test.ts+++ b/src/store/chat/slices/message/action.test.ts@@ -6,7 +6,7 @@ import { type Mock } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope } from '@/libs/replica';-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { mutate } from '@/libs/swr';import { messageService } from '@/services/message';import {clearMessageListClientCacheState,@@ -1323,68 +1323,9 @@ describe('chatMessage actions', () => {).toBe(true);});- it('keeps only the persisted thread head when a run settles after loading older pages', async () => {+ it('persists only the server-backed rows of a conversation', async () => {vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);- const context = {- agentId: 'thread-agent',- topicId: 'thread-topic',- threadId: 'thread-id',- scope: 'thread' as const,- };- const older = { id: 'older', role: 'user', content: 'older history' } as UIChatMessage;- const head = { id: 'head', role: 'user', content: 'latest question' } as UIChatMessage;- const reply = { id: 'reply', role: 'assistant', content: 'finished' } as UIChatMessage;- vi.spyOn(conversationMessagesResource.storage!, 'get').mockResolvedValue({- data: { currentPage: 0, hasMore: true, items: [head], pageSize: 1 },- updatedAt: 1,- });const storageSet = vi.spyOn(conversationMessagesResource.storage!, 'set').mockResolvedValue();- useChatStore.setState({- activeAgentId: context.agentId,- activeTopicId: context.topicId,- activeThreadId: context.threadId,- });- const { operationId } = useChatStore- .getState()- .startOperation({ type: 'execAgentRuntime', context });- useChatStore.getState().replaceMessages([older, head, reply], { context });- useChatStore.getState().completeOperation(operationId);- await waitFor(() =>- expect(storageSet).toHaveBeenCalledWith(- expect.objectContaining({ queryKey: conversationMessagesKey(context) }),- expect.objectContaining({- data: expect.objectContaining({ items: [head, reply], currentPage: 0 }),- }),- ),- );- });-- beforeEach(() => {- (mutate as Mock).mockClear();- });-- it('seeds the message:list SWR cache for the same bucket without revalidating', async () => {- const { result } = renderHook(() => useChatStore());-- const context = { agentId: 'wt-agent', topicId: 'wt-topic' };- const messages = [{ id: 'm1', 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];-- // seeds, never refetches- expect(options).toEqual({ revalidate: false });- expect(dataArg).toEqual(messages);- expect(swrKey).toEqual(messageListKey(context));- expect(isMessageListServerVerified(context)).toBe(false);- });-- it('keeps an active local voice row in memory without writing it to SWR', async () => {- const { result } = renderHook(() => useChatStore());const context = { agentId: 'voice-agent', topicId: 'voice-topic' };const key = messageMapKey(context);const persistedMessage = {@@ -1403,28 +1344,30 @@ describe('chatMessage actions', () => {role: 'user',updatedAt: 2,} as any;-- act(() => {- useChatStore.setState({- dbMessagesMap: { [key]: [localVoiceMessage] },- voiceMessageUploadMap: {- [localVoiceMessage.id]: { progress: 50, status: 'uploading' },- },- });+ useChatStore.setState({+ dbMessagesMap: { [key]: [localVoiceMessage] },+ voiceMessageUploadMap: { [localVoiceMessage.id]: { progress: 50, status: 'uploading' } },});- await act(async () => {- result.current.replaceMessages([persistedMessage], { context });- });+ useChatStore.getState().replaceMessages([persistedMessage], { context });- expect(result.current.dbMessagesMap[key]).toEqual([persistedMessage, localVoiceMessage]);- expect(mutate).toHaveBeenCalledWith(messageListKey(context), [persistedMessage], {- revalidate: false,- });+ // The local voice row stays on screen while its upload runs…+ expect(useChatStore.getState().dbMessagesMap[key]).toEqual([+ persistedMessage,+ localVoiceMessage,+ ]);+ // …but its blob URL never reaches storage.+ await waitFor(() =>+ expect(storageSet).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: conversationMessagesKey(context) }),+ expect.objectContaining({+ data: expect.objectContaining({ items: [persistedMessage] }),+ }),+ ),+ );});- it('keeps an earlier local voice row ahead of a later server snapshot message', async () => {- const { result } = renderHook(() => useChatStore());+ it('keeps an earlier local voice row ahead of a later server snapshot message', () => {const context = { agentId: 'voice-order-agent', topicId: 'voice-order-topic' };const key = messageMapKey(context);const localVoiceMessage = {@@ -1443,25 +1386,20 @@ describe('chatMessage actions', () => {role: 'user',updatedAt: 2,} as any;-- act(() => {- useChatStore.setState({- dbMessagesMap: { [key]: [localVoiceMessage] },- voiceMessageUploadMap: {- [localVoiceMessage.id]: { progress: 50, status: 'uploading' },- },- });+ useChatStore.setState({+ dbMessagesMap: { [key]: [localVoiceMessage] },+ voiceMessageUploadMap: { [localVoiceMessage.id]: { progress: 50, status: 'uploading' } },});- await act(async () => {- result.current.replaceMessages([laterPersistedMessage], { context });- });+ useChatStore.getState().replaceMessages([laterPersistedMessage], { context });- expect(result.current.dbMessagesMap[key]).toEqual([localVoiceMessage, laterPersistedMessage]);+ expect(useChatStore.getState().dbMessagesMap[key]).toEqual([+ localVoiceMessage,+ laterPersistedMessage,+ ]);});- it('drops an inactive local-only row from memory and cache input', async () => {- const { result } = renderHook(() => useChatStore());+ it('drops an inactive local-only row from memory', () => {const context = { agentId: 'inactive-voice-agent', topicId: 'inactive-voice-topic' };const key = messageMapKey(context);const persistedMessage = {@@ -1480,198 +1418,122 @@ describe('chatMessage actions', () => {role: 'user',updatedAt: 2,} as any;-- act(() => {- useChatStore.setState({- dbMessagesMap: { [key]: [inactiveLocalMessage] },- voiceMessageUploadMap: {},- });- });-- await act(async () => {- result.current.replaceMessages([persistedMessage, inactiveLocalMessage], { context });- });-- expect(result.current.dbMessagesMap[key]).toEqual([persistedMessage]);- expect(mutate).toHaveBeenCalledWith(messageListKey(context), [persistedMessage], {- revalidate: 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,+ useChatStore.setState({+ dbMessagesMap: { [key]: [inactiveLocalMessage] },+ voiceMessageUploadMap: {},});- });- it('skips write-through for the useFetchMessages onData sync path', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- result.current.replaceMessages([{ id: 'm2', role: 'user', content: 'hi' }] as any, {- action: 'useFetchMessages',- context: { agentId: 'wt-agent-2', topicId: 'wt-topic-2' },- });- });+ useChatStore+ .getState()+ .replaceMessages([persistedMessage, inactiveLocalMessage], { context });- expect(mutate).not.toHaveBeenCalled();+ expect(useChatStore.getState().dbMessagesMap[key]).toEqual([persistedMessage]);});- it("skips write-through for fetch-sourced echoes (source: 'fetch')", async () => {- // Regression: the Conversation store's SWR onData echoes fetched- // snapshots out through onMessagesChange → replaceMessages. At mount the- // echo carries the STALE cached list while the switch-time revalidation- // is in flight; writing it through the SWR cache trips SWR's mutation- // race guard, which discards the fresh result and locks the conversation- // on the stale/partial list.- const { result } = renderHook(() => useChatStore());+ it.each([+ ['a conversation without a server topic', { agentId: 'wt-agent-new', topicId: null }],+ // Page copilot: `documentId` only exists in the local bucket key.+ [+ 'a page copilot bucket',+ { agentId: 'wt-page-agent', documentId: 'doc-1', scope: 'page', topicId: 'wt-page-topic' },+ ],+ // Group-agent stream: the canonical read drops `subAgentId`.+ [+ 'a group-agent stream',+ {+ agentId: 'wt-supervisor',+ groupId: 'wt-group',+ scope: 'group_agent',+ subAgentId: 'wt-worker',+ topicId: 'wt-group-topic',+ },+ ],+ ])('keeps %s in memory only', async (_, context: any) => {+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const storageSet = vi.spyOn(conversationMessagesResource.storage!, 'set').mockResolvedValue();- await act(async () => {- result.current.replaceMessages([{ id: 'm-echo', role: 'user', content: 'hi' }] as any, {- context: { agentId: 'wt-agent-3', topicId: 'wt-topic-3' },- source: 'fetch',- });- });+ useChatStore+ .getState()+ .replaceMessages([{ id: 'm-local', role: 'user', content: 'hi' }] as any, { context });+ await new Promise((resolve) => setTimeout(resolve, 10));- expect(mutate).not.toHaveBeenCalled();+ expect(useChatStore.getState().dbMessagesMap[messageMapKey(context)]).toHaveLength(1);+ expect(storageSet.mock.calls.some(([, row]) => Array.isArray((row.data as any)?.items))).toBe(+ false,+ );});- it('skips write-through while the context is streaming', async () => {- const { result } = renderHook(() => useChatStore());+ it.each([+ ['group', { agentId: 'wt-sup', groupId: 'wt-grp', scope: 'group', topicId: 'wt-grp-topic' }],+ [+ 'group thread',+ {+ agentId: 'wt-worker',+ groupId: 'wt-grp',+ scope: 'thread',+ threadId: 'wt-thread',+ topicId: 'wt-grp-topic',+ },+ ],+ ])(+ 'persists a representable %s conversation under its canonical key',+ async (_, context: any) => {+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const storageSet = vi+ .spyOn(conversationMessagesResource.storage!, 'set')+ .mockResolvedValue();+ const messages = [{ id: 'm-grp', role: 'user', content: 'hi' }] as any;++ useChatStore.getState().replaceMessages(messages, { context });++ await waitFor(() =>+ expect(storageSet).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: conversationMessagesKey(context) }),+ expect.objectContaining({ data: expect.objectContaining({ items: messages }) }),+ ),+ );+ },+ );+ it('does not persist while the context is streaming', async () => {+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const storageSet = vi.spyOn(conversationMessagesResource.storage!, 'set').mockResolvedValue();const context = { agentId: 'wt-agent-3', topicId: 'wt-topic-3' };+ useChatStore.getState().startOperation({ type: 'execAgentRuntime', context });- await act(async () => {- // A running AI-runtime op marks the context as streaming.- result.current.startOperation({ type: 'execAgentRuntime', context });- });-- (mutate as Mock).mockClear();-- await act(async () => {- result.current.replaceMessages([{ id: 'm3', role: 'user', content: 'hi' }] as any, {- context,- });- });+ useChatStore+ .getState()+ .replaceMessages([{ id: 'm3', role: 'user', content: 'hi' }] as any, { context });+ await new Promise((resolve) => setTimeout(resolve, 10));- expect(mutate).not.toHaveBeenCalled();+ expect(storageSet.mock.calls.some(([, row]) => Array.isArray((row.data as any)?.items))).toBe(+ false,+ );});- it('still seeds the cache when the store-set is a no-op (optimistic echo)', async () => {- const { result } = renderHook(() => useChatStore());-+ it('still persists when the replacement equals the rows in memory (optimistic echo)', async () => {+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const storageSet = vi.spyOn(conversationMessagesResource.storage!, 'set').mockResolvedValue();const context = { agentId: 'wt-noop', topicId: 'wt-noop-topic' };const messages = [{ id: 'm-noop', role: 'user', content: 'hi' }] as any;- const key = messageMapKey(context);-- // An optimistic dispatch already applied this exact state to the in-memory- // store, but never touched the SWR cache.- act(() => {- useChatStore.setState({ dbMessagesMap: { [key]: messages } });- });-- (mutate as Mock).mockClear();+ // An optimistic dispatch already applied this exact state in memory.+ useChatStore.setState({ dbMessagesMap: { [messageMapKey(context)]: messages } });- await act(async () => {- result.current.replaceMessages(messages, {- action: 'optimisticUpdateMessageContent',- context,- });- });+ useChatStore+ .getState()+ .replaceMessages(messages, { action: 'optimisticUpdateMessageContent', context });- // store-set is a no-op (messagesMap bucket never populated)...- expect(result.current.messagesMap[key]).toBeUndefined();- // ...but the cache is still seeded so a later switch-back is not stale- expect(mutate).toHaveBeenCalledTimes(1);- const [swrKey, dataArg, options] = (mutate as Mock).mock.calls[0];- expect(options).toEqual({ revalidate: false });- expect(dataArg).toEqual(messages);- expect(swrKey).toEqual(messageListKey(context));+ await waitFor(() =>+ expect(storageSet).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: conversationMessagesKey(context) }),+ expect.objectContaining({ data: expect.objectContaining({ items: messages }) }),+ ),+ );});});describe('useFetchMessages action', () => {- it('binds the canonical key, coordinated fetcher, and fetched-data sync', async () => {+ it('reads the conversation through the coordinated fetcher into its bucket', 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);@@ -1680,22 +1542,8 @@ describe('chatMessage actions', () => {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,- }),+ await waitFor(() =>+ expect(useChatStore.getState().dbMessagesMap[messageMapKey(context)]).toEqual(messages),);});});@@ -1734,12 +1582,6 @@ describe('chatMessage actions', () => {});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(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 () => {diff --git a/src/store/chat/slices/message/actions/index.ts b/src/store/chat/slices/message/actions/index.tsindex b7dec1145c8..87d73494cc0 100644--- a/src/store/chat/slices/message/actions/index.ts+++ b/src/store/chat/slices/message/actions/index.ts@@ -13,11 +13,14 @@ import { type MessageQueryAction } from './query';import { MessageQueryActionImpl } from './query';import { type MessageRuntimeStateAction } from './runtimeState';import { MessageRuntimeStateActionImpl } from './runtimeState';+import { type MessageTranscriptAction } from './transcript';+import { MessageTranscriptActionImpl } from './transcript';export type ChatMessageAction = MessagePublicApiAction &MessageOptimisticUpdateAction &MessageQueryAction &MessageRuntimeStateAction &+ MessageTranscriptAction &MessageInternalsAction;/**@@ -40,5 +43,6 @@ export const chatMessage: StateCreator<new MessageOptimisticUpdateActionImpl(...params),new MessageQueryActionImpl(...params),new MessageRuntimeStateActionImpl(...params),+ new MessageTranscriptActionImpl(...params),new MessageInternalsActionImpl(...params),]);diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.tsindex 2a0b9463c6c..de25db3b16c 100644--- a/src/store/chat/slices/message/actions/internals.ts+++ b/src/store/chat/slices/message/actions/internals.ts@@ -1,4 +1,3 @@-import { parse } from '@lobechat/conversation-flow';import { type ConversationContext, type TraceEventPayloads } from '@lobechat/types';import debug from 'debug';import isEqual from 'fast-deep-equal';@@ -11,6 +10,7 @@ import { displayMessageSelectors } from '../../../selectors';import { messageMapKey } from '../../../utils/messageMapKey';import { type MessageDispatch } from '../reducer';import { messagesReducer } from '../reducer';+import { getMessageTranscript } from '../transcript';import { reconcileAssistantToolLinks } from '../utils/reconcileTools';const log = debug('lobe-store:message-internals');@@ -64,19 +64,12 @@ export class MessageInternalsActionImpl {// reconcileAssistantToolLinks).const reconciled = reconcileAssistantToolLinks(updatedRawMessages);- const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: reconciled };+ if (isEqual(reconciled, rawMessages)) return;- if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;-- // parse to get display messages- // The key's thread decides which threaded rows render (see conversation-flow `ThreadScope`).- const { flatList } = parse(reconciled, undefined, { threadId: ctx.threadId });- const nextDisplayMap = { ...this.#get().messagesMap, [messagesKey]: flatList };-- this.#set({ dbMessagesMap: nextDbMap, messagesMap: nextDisplayMap }, false, {- payload,- type: `dispatchMessage/${payload.type}`,- });+ log('[internal_dispatchMessage] %s | key=%s', payload.type, messagesKey);+ const transcript = getMessageTranscript(this.#set, this.#get);+ transcript.commit(ctx, reconciled, true);+ transcript.settle(ctx);};internal_traceMessage = async (id: string, payload: TraceEventPayloads): Promise<void> => {diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 8abb3afd8d3..80cc8e22cec 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -1,21 +1,14 @@-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 { readConversationMessageListPage } from '@/helpers/conversationMessageRead';-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { mutate } from '@/libs/swr';import { isMessageListKey } from '@/libs/swr/keys';import {- getMessageListCacheIdentity,- getMessageListFetchPolicy,invalidateMessageListClientState,isMessageListServerVerified,messageListKey,- runMessageListQuery,} from '@/services/message/cache';-import { persistSettledTranscript } from '@/services/message/replica';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { type ChatStore } from '@/store/chat/store';import {@@ -26,6 +19,7 @@ import { type StoreSetter } from '@/store/types';import { type MessageMapKeyInput } from '../../../utils/messageMapKey';import { messageMapKey } from '../../../utils/messageMapKey';+import { getMessageTranscript } from '../transcript';import { reconcileAssistantToolLinks } from '../utils/reconcileTools';/**@@ -33,7 +27,6 @@ import { reconcileAssistantToolLinks } from '../utils/reconcileTools';* Handles fetching, refreshing, and replacing message data*/-const prefetchingMessageKeys = new Set<string>();const log = debug('lobe-client:message-query');type Setter = StoreSetter<ChatStore>;@@ -90,37 +83,16 @@ export class MessageQueryActionImpl {// A client-minted topic with no server row yet (first-send window) would// prefetch an empty list and clobber the optimistic messages on screen.if (this.#get().creatingTopicIds.includes(context.topicId)) return;-- 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 = runMessageListQuery(context, readConversationMessageListPage).then(- (messages) => {- // Re-check at DELIVERY time, not just at start: the user can open this- // topic and submit a follow-up while the request is in flight. Applying- // the pre-run snapshot then would drop the freshly created user/assistant- // rows, and streaming updates targeting those now-missing ids are silent- // no-ops until terminal reconciliation. Mirrors the defense-in-depth gate- // in `useFetchMessages`' onData; the SWR cache seed below is unaffected.- if (!operationSelectors.isAgentRuntimeRunningByContext(context)(this.#get())) {- this.#get().replaceMessages(messages, { action: 'prefetchMessages', context });- }- return messages;- },- );+ // The transcript's own head read: it joins a sync already in flight, and a+ // send landing while it is out keeps its rows (see the head merge).try {- await mutate(messageListKey(context), request, { revalidate: false });- await request;+ await getMessageTranscript(this.#set, this.#get).slice.fetch(context);} catch (error) {// Background warming should never surface an unhandled rejection.- log('Failed to warm the message cache: %O', error);- } finally {- prefetchingMessageKeys.delete(messagesKey);+ log('Failed to warm the message transcript: %O', error);}};@@ -141,16 +113,6 @@ export class MessageQueryActionImpl {* refetch restores them.*/preserveWorks?: boolean;-- /**- * 'fetch' — the messages are a server-snapshot echo from a Conversation- * store's SWR sync (`onMessagesChange` meta). Skips the SWR cache- * write-through: SWR already holds this value, and at mount the echo- * carries the STALE cached list while the revalidation is in flight — a- * cache mutate then trips SWR's mutation race guard and discards the- * fresh result, locking the conversation on the stale/partial list.- */- source?: 'fetch';},): void => {let ctx: MessageMapKeyInput;@@ -232,153 +194,19 @@ export class MessageQueryActionImpl {mergeLocalMessagesByCreatedAt(persistedReconciled, [...activeLocalMessagesById.values()]),);- // Get raw messages from dbMessagesMap and apply reducer- const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: reconciled };-- // Write through BEFORE the equality early-return below. Optimistic flows- // (optimisticUpdateMessageContent / optimisticDeleteMessage[s]) call- // `internal_dispatchMessage` first — which already applies the mutation to- // `dbMessagesMap` WITHOUT touching the SWR cache — and then- // `replaceMessages(result.messages)`. When the server echo equals the- // already-applied in-memory state, the `isEqual` return fires and the- // store-set is correctly skipped; but the SWR/IndexedDB cache was never- // updated by the dispatch, so a later remount would hydrate the- // pre-mutation snapshot (stale content / deleted rows). Seeding here keeps- // the cache correct even on a store no-op.- // Fetch echoes never write through: SWR already holds that exact value, and- // at mount the echo is the STALE cached list racing the in-flight- // revalidation (see `source` doc above).- // Local-only rows can contain blob: URLs and have no durable retry owner after reload. Never- // write them into SWR/IndexedDB; only the server-backed portion belongs in the canonical cache.- if (params?.source !== 'fetch') {- this.#writeThroughMessageCache(ctx, messagesKey, persistedReconciled, params?.action);- }-- if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;-- // Parse messages using conversation-flow- // A thread view's rows are its ancestors plus its replies; scope the parse to that thread- // so the replies are not dropped as a side conversation.- const { flatList } = parse(reconciled, undefined, { threadId: ctx.threadId });-- this.#set(- {- // Store raw messages from backend- dbMessagesMap: nextDbMap,- // Store parsed messages for display- messagesMap: { ...this.#get().messagesMap, [messagesKey]: flatList },- },- false,- params?.action ?? 'replaceMessages',- );- };-- /**- * 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 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 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- * mutate call itself, while replaceMessages only hydrates ChatStore.- * - while the context is streaming — `internal_dispatchMessage` bridges every- * token here via `onMessagesChange`, and a write-through per token would- * thrash. `agent_runtime_end` clears the running flag *before* its final- * `replaceMessages`, so the settled snapshot still writes through.- */- #writeThroughMessageCache = (- ctx: MessageMapKeyInput,- messagesKey: string,- messages: UIChatMessage[],- action?: string,- ): void => {- if (!ctx.agentId || !ctx.topicId) return;- if (operationSelectors.isAgentRuntimeRunningByContext(ctx)(this.#get())) return;- if (action === 'useFetchMessages' || action === 'prefetchMessages') return;-- // 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 });- const active = this.#get();- if (- ctx.agentId !== active.activeAgentId ||- ctx.topicId !== active.activeTopicId ||- (ctx.threadId ?? null) !== (active.activeThreadId ?? null)- ) {- persistSettledTranscript({ ...ctx, agentId: ctx.agentId, topicId: ctx.topicId }, messages);+ const transcript = getMessageTranscript(this.#set, this.#get);+ // An unchanged bucket still settles: an optimistic dispatch may already+ // have applied this exact state in memory while the stored copy is older.+ if (!isEqual(reconciled, currentMessages) || !this.#get().dbMessagesMap[messagesKey]) {+ log(+ '[replaceMessages] %s | key=%s | count=%d',+ params?.action,+ messagesKey,+ reconciled.length,+ );+ transcript.commit(ctx, reconciled);}- };-- useFetchMessages = (- context: ConversationContext,- options?: {- /**- * Skip the fetch entirely (e.g. while another flow owns the data).- * Equivalent to passing a null SWR key.- */- skipFetch?: boolean;- /**- * Revalidate when the window regains focus. Defaults to SWR's- * client-data default (true). Pass `false` to suppress the focus- * refetch — used during streaming so the in-memory stream payload- * (Source of Truth) isn't clobbered by a stale DB read while DB- * fan-out writes are still in flight.- */- revalidateOnFocus?: boolean;- },- ): SWRResponse<UIChatMessage[]> => {- const { skipFetch, revalidateOnFocus } = options ?? {};-- // Skip fetch when skipFetch is true or required fields are missing- const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;-- return useClientDataSWRWithSync<UIChatMessage[]>(- shouldFetch ? messageListKey(context) : null,- () => runMessageListQuery(context, readConversationMessageListPage),- {- ...getMessageListFetchPolicy(context),- onData: (data) => {- if (!data || !context.topicId) return;-- // Use replaceMessages to store the fetched messages- this.#get().replaceMessages(data, { action: 'useFetchMessages', context });- },- ...(revalidateOnFocus !== undefined && { revalidateOnFocus }),- },- );+ transcript.settle(ctx);};}diff --git a/src/store/chat/slices/message/actions/testUtils.ts b/src/store/chat/slices/message/actions/testUtils.tsnew file mode 100644index 00000000000..0549ab04759--- /dev/null+++ b/src/store/chat/slices/message/actions/testUtils.ts@@ -0,0 +1,31 @@+import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import { renderHook } from '@testing-library/react';++import { createReplicaState } from '@/libs/replica';+import { useChatStore } from '@/store/chat';+import { type ChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++/** Drop every transcript the chat store holds. */+export const resetTranscripts = () =>+ useChatStore.setState({+ dbMessagesMap: {},+ messagePagingMap: {},+ messageReplica: createReplicaState(),+ messagesMap: {},+ voiceMessageUploadMap: {},+ });++/** Seed a conversation's loaded rows, as a previous fetch or send left them. */+export const seedRows = (context: ConversationContext, rows: UIChatMessage[]) =>+ useChatStore.setState((state) => ({+ dbMessagesMap: { ...state.dbMessagesMap, [messageMapKey(context)]: rows },+ }));++/** The conversation's rows in the chat store (`undefined` = not loaded). */+export const rowsOf = (context: ConversationContext) =>+ useChatStore.getState().dbMessagesMap[messageMapKey(context)];++/** `useFetchMessages` is a hook: run it inside a component. */+export const syncMessages = (...args: Parameters<ChatStore['useFetchMessages']>) =>+ renderHook(() => useChatStore.getState().useFetchMessages(...args)).result.current;diff --git a/src/features/Conversation/store/slices/data/approvalSync.test.ts b/src/store/chat/slices/message/actions/transcript.approvalSync.test.tssimilarity index 69%rename from src/features/Conversation/store/slices/data/approvalSync.test.tsrename to src/store/chat/slices/message/actions/transcript.approvalSync.test.tsindex 97d900d99f8..d7b17fcc179 100644--- a/src/features/Conversation/store/slices/data/approvalSync.test.ts+++ b/src/store/chat/slices/message/actions/transcript.approvalSync.test.ts@@ -4,8 +4,10 @@ import { createElement, type PropsWithChildren } from 'react';import { SWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createReplicaState } from '@/libs/replica';import { messageService } from '@/services/message';import { clearMessageListClientCacheState } from '@/services/message/cache';+import { conversationMessagesKey } from '@/services/message/replica';import { topicService } from '@/services/topic';import { useChatStore } from '@/store/chat';import { operationSelectors, topicSelectors } from '@/store/chat/selectors';@@ -13,8 +15,7 @@ import {hasPendingInterventions,INTERVENTION_REFRESH_INTERVAL,} from '@/store/chat/utils/interventionSync';--import { createStore } from '../../index';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';vi.mock('@/services/message', () => {const getMessages = vi.fn();@@ -46,6 +47,17 @@ const pending: UIChatMessage = {pluginIntervention: { status: 'pending' },};+const key = messageMapKey(context);+const rows = () => useChatStore.getState().dbMessagesMap[key] ?? [];+/** A conversation whose loaded transcript holds one unanswered approval. */+const seedPending = () =>+ useChatStore.setState({+ dbMessagesMap: { [key]: [pending] },+ messagePagingMap: {},+ messageReplica: createReplicaState(),+ messagesMap: {},+ });+describe('pending approval message polling', () => {beforeEach(() => {vi.useFakeTimers();@@ -65,13 +77,14 @@ describe('pending approval message polling', () => {});const mountPolling = async () => {- const store = createStore({ context });- store.setState({ dbMessages: [pending] });+ seedPending();const cache = new Map();renderHook(() => {- const hasPending = store((state) => hasPendingInterventions(state.dbMessages));- store.getState().useFetchMessages(context, {+ const hasPending = useChatStore((state) =>+ hasPendingInterventions(state.dbMessagesMap[key] ?? []),+ );+ useChatStore.getState().useFetchMessages(context, {refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,syncInterventions: true,});@@ -84,7 +97,6 @@ describe('pending approval message polling', () => {await act(async () => {await Promise.resolve();});- return store;};it('keeps loaded history and its exhausted cursor after the final approval refresh', async () => {@@ -92,7 +104,7 @@ describe('pending approval message polling', () => {messages: await messageService.getMessages(context),olderCursor: { createdAt: new Date(1).toISOString(), id: pending.id },}));- const store = await mountPolling();+ await mountPolling();const older: UIChatMessage = {id: 'older',role: 'user',@@ -105,9 +117,9 @@ describe('pending approval message polling', () => {olderCursor: null,});await act(async () => {- await store.getState().loadEarlierMessages();+ await useChatStore.getState().loadEarlierMessages(context);});- expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['older', 'question']);+ expect(rows().map((m) => m.id)).toEqual(['older', 'question']);const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };const reply: UIChatMessage = {id: 'reply',@@ -120,13 +132,15 @@ describe('pending approval message polling', () => {await act(async () => {await vi.advanceTimersByTimeAsync(2000);});- expect(store.getState().dbMessages).toEqual([older, answered, reply]);- expect(store.getState().messagePaging?.hasMore).toBe(false);+ expect(rows()).toEqual([older, answered, reply]);+ expect(+ useChatStore.getState().messagePagingMap[conversationMessagesKey(context)]?.hasMore,+ ).toBe(false);expect(messageService.getMessageListPage).toHaveBeenCalledTimes(3);});it('waits for a startup reservation and publishes the new operation for the existing reconnect hook', async () => {- const store = await mountPolling();+ await mountPolling();const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };vi.mocked(messageService.getMessages).mockResolvedValue([answered]);vi.mocked(topicService.getTopicDetail).mockResolvedValue({@@ -139,7 +153,7 @@ describe('pending approval message polling', () => {await act(async () => {await vi.advanceTimersByTimeAsync(2000);});- expect(store.getState().dbMessages[0].pluginIntervention?.status).toBe('approved');+ expect(rows()[0].pluginIntervention?.status).toBe('approved');const requests = vi.mocked(messageService.getMessages).mock.calls.length;await act(async () => {await vi.advanceTimersByTimeAsync(10_000);@@ -162,7 +176,7 @@ describe('pending approval message polling', () => {it('reads final messages after the decision and topic, even with a stale local streaming flag', async () => {vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);- const store = await mountPolling();+ await mountPolling();const order: string[] = [];const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };vi.mocked(messageService.getMessages).mockImplementation(async () => {@@ -188,7 +202,7 @@ describe('pending approval message polling', () => {await vi.advanceTimersByTimeAsync(2000);});expect(order).toEqual(['messages', 'topic', 'messages']);- expect(store.getState().dbMessages.at(-1)?.content).toBe('Final reply');+ expect(rows().at(-1)?.content).toBe('Final reply');const requests = vi.mocked(messageService.getMessages).mock.calls.length;await act(async () => {await vi.advanceTimersByTimeAsync(10_000);@@ -197,13 +211,14 @@ describe('pending approval message polling', () => {});it('follows a slow remote continuation after the Ask closes without focus or remount', async () => {- const store = createStore({ context });- store.setState({ dbMessages: [pending] });+ seedPending();const cache = new Map();renderHook(() => {- const hasPending = store((state) => hasPendingInterventions(state.dbMessages));- store.getState().useFetchMessages(context, {+ const hasPending = useChatStore((state) =>+ hasPendingInterventions(state.dbMessagesMap[key] ?? []),+ );+ useChatStore.getState().useFetchMessages(context, {refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,syncInterventions: true,});@@ -226,7 +241,7 @@ describe('pending approval message polling', () => {await act(async () => {await vi.advanceTimersByTimeAsync(2000);});- expect(store.getState().dbMessages[0].pluginIntervention?.status).toBe('approved');+ expect(rows()[0].pluginIntervention?.status).toBe('approved');await act(async () => {await vi.advanceTimersByTimeAsync(60_000);});@@ -244,7 +259,7 @@ describe('pending approval message polling', () => {await act(async () => {await vi.advanceTimersByTimeAsync(2000);});- expect(store.getState().dbMessages.at(-1)?.content).toBe('Late continuation');+ expect(rows().at(-1)?.content).toBe('Late continuation');const requests = vi.mocked(messageService.getMessages).mock.calls.length;await act(async () => {await vi.advanceTimersByTimeAsync(10_000);@@ -255,12 +270,15 @@ describe('pending approval message polling', () => {it.each(['approved', 'rejected', 'aborted'] as const)('updates the mounted peer on remote %s, then stops polling',async (status) => {- const store = createStore({ context });- store.setState({ dbMessages: [pending] });+ seedPending();const usePollingMessages = () => {- const hasPending = store((state) => hasPendingInterventions(state.dbMessages));- const result = store((state) => state.dbMessages[0]?.pluginIntervention?.status);- store.getState().useFetchMessages(context, {+ const hasPending = useChatStore((state) =>+ hasPendingInterventions(state.dbMessagesMap[key] ?? []),+ );+ const result = useChatStore(+ (state) => state.dbMessagesMap[key]?.[0]?.pluginIntervention?.status,+ );+ useChatStore.getState().useFetchMessages(context, {refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,syncInterventions: true,});@@ -286,7 +304,7 @@ describe('pending approval message polling', () => {await vi.advanceTimersByTimeAsync(2000);});expect(result.current).toBe(status);- expect(store.getState().dbMessages).toEqual([answered]);+ expect(rows()).toEqual([answered]);const requests = vi.mocked(messageService.getMessages).mock.calls.length;await act(async () => {await vi.advanceTimersByTimeAsync(10_000);@@ -294,4 +312,57 @@ describe('pending approval message polling', () => {expect(messageService.getMessages).toHaveBeenCalledTimes(requests);},);++ it('polls a card a stream delivered after the first read, within the poll interval', async () => {+ // Regression: the topic's first read ran under the 30s list dedupe window.+ // A card that arrived over the stream afterwards switched the sync to the+ // 2s poll, but every tick was deduped against that first read, so another+ // device's answer only showed up ~30s later.+ useChatStore.setState({+ dbMessagesMap: {},+ messagePagingMap: {},+ messageReplica: createReplicaState(),+ messagesMap: {},+ });+ vi.mocked(messageService.getMessages).mockResolvedValue([]);+ const cache = new Map();+ renderHook(+ () => {+ const hasPending = useChatStore((state) =>+ hasPendingInterventions(state.dbMessagesMap[key] ?? []),+ );+ useChatStore.getState().useFetchMessages(context, {+ refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,+ syncInterventions: true,+ });+ },+ {+ wrapper: ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children),+ },+ );+ await act(async () => {+ await Promise.resolve();+ });+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);++ // The run parks on a question: the card arrives over the stream, and the+ // server still reports it pending for a while.+ vi.mocked(messageService.getMessages).mockResolvedValue([pending]);+ await act(async () => {+ useChatStore.getState().replaceMessages([pending], { context });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(INTERVENTION_REFRESH_INTERVAL + 500);+ });++ // Another device answers; the next poll picks it up.+ const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };+ vi.mocked(messageService.getMessages).mockResolvedValue([answered]);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2 * INTERVENTION_REFRESH_INTERVAL + 500);+ });++ expect(rows()[0].pluginIntervention?.status).toBe('approved');+ });});diff --git a/src/store/chat/slices/message/actions/transcript.paging.test.ts b/src/store/chat/slices/message/actions/transcript.paging.test.tsnew file mode 100644index 00000000000..e660a4185a1--- /dev/null+++ b/src/store/chat/slices/message/actions/transcript.paging.test.ts@@ -0,0 +1,181 @@+import type { UIChatMessage } from '@lobechat/types';+import { waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';+import { messageService } from '@/services/message';+import { clearMessageListClientCacheState, runMessageListQuery } from '@/services/message/cache';+import {+ conversationMessagesKey,+ conversationMessagesResource,+ transcriptOf,+} from '@/services/message/replica';+import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/selectors';++import { resetTranscripts, rowsOf, seedRows, syncMessages } from './testUtils';++vi.mock('@lobechat/conversation-flow', () => ({+ parse: (messages: UIChatMessage[]) => ({+ flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt),+ messageMap: Object.fromEntries(messages.map((m) => [m.id, m])),+ }),+}));++vi.mock('@/services/message', () => {+ const getMessages = vi.fn();+ return {+ messageService: {+ getEarlierMessages: vi.fn(),+ getMessageListPage: vi.fn((params) => getMessages(params)),+ getMessages,+ },+ };+});++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => undefined,+ useActiveWorkspaceId: () => undefined,+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn((key, fetcher, options) => {+ if (key) fetcher?.().then((data: unknown) => options?.onSuccess?.(data));+ return { data: undefined, isValidating: true, mutate: vi.fn() };+ }),+}));++describe('message transcript paging and persistence', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ clearMessageListClientCacheState();+ resetTranscripts();+ });++ it('keeps paged history when the head revalidates', async () => {+ const context = { agentId: 'review-agent', topicId: 'review-topic', threadId: null };+ const old = { id: 'old', role: 'user', content: 'older', createdAt: 1 } as UIChatMessage;+ const head = { id: 'head', role: 'user', content: 'newest', createdAt: 2 } as UIChatMessage;+ const cursor = { id: 'head', createdAt: '1970-01-01T00:00:00.002Z' };+ await runMessageListQuery(context, async () => ({ messages: [head], olderCursor: cursor }));+ useChatStore.getState().replaceMessages([head], { context });+ vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce({+ messages: [old],+ olderCursor: null,+ });+ await useChatStore.getState().loadEarlierMessages(context);+ vi.mocked(messageService.getMessageListPage).mockResolvedValueOnce({+ messages: [head],+ olderCursor: cursor,+ });++ syncMessages(context);++ await waitFor(() => expect(messageService.getMessageListPage).toHaveBeenCalled());+ await waitFor(() => expect(rowsOf(context)).toEqual([old, head]));+ });++ it('resets paging after an unpaged replacement but keeps it for an unchanged one', () => {+ const context = { agentId: 'replace-agent', topicId: 'replace-topic', threadId: null };+ const key = conversationMessagesKey(context);+ const rows = ['older', 'head'].map((id, i) => ({+ id,+ role: 'user',+ content: id,+ createdAt: i,+ })) as UIChatMessage[];+ const paging = {+ currentPage: 2,+ pageSize: 1,+ hasMore: true,+ anchorId: 'head',+ nextCursor: { id: 'older', createdAt: 'old' },+ pages: [{ count: 1 }, { count: 1 }],+ };+ seedRows(context, rows);+ useChatStore.setState({ messagePagingMap: { [key]: paging as any } });++ useChatStore.getState().replaceMessages([...rows], { context });+ expect(useChatStore.getState().messagePagingMap[key]).toEqual(paging);++ useChatStore.getState().replaceMessages([rows[1]], { context });+ expect(useChatStore.getState().messagePagingMap[key]).toEqual({+ currentPage: 0,+ pageSize: 1,+ hasMore: true,+ });+ });++ it('keeps streamed writes in memory and persists once the run settles', async () => {+ let running = true;+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockImplementation(+ () => () => running,+ );+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const storageSet = vi+ .spyOn(conversationMessagesResource.storage!, 'set')+ .mockResolvedValue(undefined);+ const context = { agentId: 'agent-persist', threadId: null, topicId: 'topic-persist' };++ for (const id of ['m1', 'm2']) {+ useChatStore+ .getState()+ .internal_dispatchMessage(+ { id, type: 'createMessage', value: { content: id, role: 'assistant' } as any },+ { conversationContext: context },+ );+ }+ await new Promise((resolve) => setTimeout(resolve, 50));+ // The engine also tracks its stored keys in an index row.+ const transcriptWrites = () =>+ storageSet.mock.calls.filter(([, row]) => Array.isArray((row.data as any)?.items));+ expect(transcriptWrites()).toHaveLength(0);++ running = false;+ useChatStore.getState().internal_settleTranscript(context);++ await waitFor(() => expect(transcriptWrites()).toHaveLength(1));+ const [[, row]] = transcriptWrites();+ expect((row.data as any).items.map((m: UIChatMessage) => m.id)).toEqual(['m1', 'm2']);+ });++ it('persists a settled write to a conversation no view shows', async () => {+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const storageSet = vi+ .spyOn(conversationMessagesResource.storage!, 'set')+ .mockResolvedValue(undefined);+ const context = { agentId: 'agent-bg', threadId: null, topicId: 'topic-bg' };+ const rows = [{ id: 'bg-1', role: 'user', content: 'hi', createdAt: 1 }] as UIChatMessage[];++ useChatStore.getState().replaceMessages(rows, { context });++ await waitFor(() =>+ expect(+ storageSet.mock.calls.some(([, row]) => (row.data as any)?.items?.[0]?.id === 'bg-1'),+ ).toBe(true),+ );+ });++ it('pre-hydrates a stored transcript but never replaces rows already in memory', async () => {+ const stored = [+ { id: 'stored', role: 'user', content: 'stored', createdAt: 1 },+ ] as UIChatMessage[];+ vi.spyOn(conversationMessagesResource.storage!, 'get').mockImplementation(async (key) =>+ key.queryKey === REPLICA_INDEX_KEY ? undefined : { data: transcriptOf(stored), updatedAt: 1 },+ );+ const cold = { agentId: 'agent-pre', scope: 'main' as const, topicId: 'topic-cold' };+ const live = { agentId: 'agent-pre', scope: 'main' as const, topicId: 'topic-live' };+ const liveRows = [+ { id: 'live', role: 'user', content: 'live', createdAt: 2 },+ ] as UIChatMessage[];+ seedRows(live, liveRows);++ await useChatStore.getState().preHydrateMessages(cold);+ await useChatStore.getState().preHydrateMessages(live);++ expect(rowsOf(cold)).toEqual(stored);+ expect(rowsOf(live)).toBe(liveRows);+ });+});diff --git a/src/store/chat/slices/message/actions/transcript.sync.test.ts b/src/store/chat/slices/message/actions/transcript.sync.test.tsnew file mode 100644index 00000000000..a2676496eaa--- /dev/null+++ b/src/store/chat/slices/message/actions/transcript.sync.test.ts@@ -0,0 +1,540 @@+import type { UIChatMessage } from '@lobechat/types';+import { act, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useClientDataSWR } from '@/libs/swr';+import { messageService } from '@/services/message';+import {+ clearMessageListClientCacheState,+ MESSAGE_LIST_VERIFICATION_INTERVAL,+ runMessageListQuery,+} from '@/services/message/cache';+import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/selectors';+import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';++import { resetTranscripts, rowsOf, seedRows, syncMessages } from './testUtils';++vi.mock('@lobechat/conversation-flow', () => ({+ parse: (messages: UIChatMessage[]) => ({+ flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt),+ messageMap: Object.fromEntries(messages.map((m) => [m.id, m])),+ }),+}));++vi.mock('@/services/message', () => {+ const getMessages = vi.fn();+ return {+ messageService: {+ getEarlierMessages: vi.fn(),+ // The list cache reads pages; tests stub the plain list underneath.+ getMessageListPage: vi.fn((params) => getMessages(params)),+ getMessages,+ },+ };+});++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => undefined,+ useActiveWorkspaceId: () => undefined,+}));++// Simulate SWR for testing: fetch once, report success.+vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn((key, fetcher, options) => {+ if (key) fetcher?.().then((data: unknown) => options?.onSuccess?.(data));+ return { data: undefined, isValidating: true, mutate: vi.fn() };+ }),+}));++/** The transcript sync's SWR keys (the replica's hydration read is a separate query). */+const messageSyncKeys = () =>+ vi+ .mocked(useClientDataSWR)+ .mock.calls.map(([key]) => key as any[] | null)+ .filter((key) => key?.[0] === 'message:list');++const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };++describe('useFetchMessages', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ clearMessageListClientCacheState();+ resetTranscripts();+ });++ it.each(['approved', 'rejected', 'aborted'] as const)(+ 'observes a remote %s while preserving locally streaming content',+ async (status) => {+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);+ const pending: UIChatMessage = {+ content: '',+ createdAt: 1,+ id: 'question',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 10,+ pluginIntervention: { status: 'pending' },+ };+ const streaming: UIChatMessage = {+ content: 'Streaming content that has not been persisted yet',+ createdAt: 2,+ id: 'assistant',+ role: 'assistant',+ updatedAt: 10,+ };+ const answered: UIChatMessage = {+ ...pending,+ content: 'Remote answer',+ updatedAt: 1,+ pluginIntervention: { status },+ };+ seedRows(context, [pending, streaming]);+ vi.mocked(messageService.getMessages).mockResolvedValue([+ answered,+ { ...streaming, content: '...' },+ ]);++ syncMessages(context, { refreshInterval: 2000 });++ await waitFor(() => expect(rowsOf(context)?.[0]).toEqual(answered));+ expect(rowsOf(context)?.[1]).toBe(streaming);+ expect(useClientDataSWR).toHaveBeenCalledWith(+ expect.any(Array),+ expect.any(Function),+ // Polling runs on the hook's own timer (see transcript.approvalSync).+ expect.objectContaining({+ dedupingInterval: 1000,+ refreshWhenHidden: false,+ refreshWhenOffline: false,+ }),+ );+ },+ );++ it('settles a remote answer and permits an authoritative rollback at the same timestamp', async () => {+ const pending: UIChatMessage = {+ content: '',+ createdAt: 1,+ id: 'question',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 10,+ pluginIntervention: { status: 'pending' },+ };+ const answered: UIChatMessage = {+ ...pending,+ content: 'Remote answer',+ updatedAt: 1,+ pluginIntervention: { status: 'approved' },+ };+ seedRows(context, [pending]);+ vi.mocked(messageService.getMessages).mockResolvedValue([answered]);+ syncMessages(context);+ await waitFor(() => expect(rowsOf(context)).toEqual([answered]));++ clearMessageListClientCacheState();+ const rollback = { ...pending, updatedAt: 1 };+ vi.mocked(messageService.getMessages).mockResolvedValue([rollback]);+ syncMessages(context);+ await waitFor(() => expect(rowsOf(context)).toEqual([rollback]));+ });++ it('passes threadId to the message read', async () => {+ vi.mocked(messageService.getMessages).mockResolvedValue([]);++ syncMessages({ ...context, threadId: 'test-thread' });++ await waitFor(() => {+ expect(messageService.getMessages).toHaveBeenCalledWith({+ agentId: 'test-session',+ groupId: null,+ projectToolPayloads: false,+ threadId: 'test-thread',+ topicId: 'test-topic',+ });+ });+ });++ it('lands fetched rows in the conversation bucket', async () => {+ const fetched: UIChatMessage[] = [+ { id: 'sync-msg-1', content: 'Synced', role: 'user', createdAt: 1000, updatedAt: 1000 },+ ];+ vi.mocked(messageService.getMessages).mockResolvedValue(fetched);++ const result = syncMessages(context);++ expect(result.isLoading).toBe(true);+ await waitFor(() => expect(rowsOf(context)).toEqual(fetched));+ });++ describe('while an agent run is in flight in this conversation', () => {+ const fetched: UIChatMessage[] = [+ { content: 'Run the script', createdAt: 1000, id: 'msg-user', role: 'user', updatedAt: 1000 },+ ];++ it('still lands the first load, so a parked run does not leave a skeleton (G-05)', async () => {+ // A group supervisor parked on a member's approval stays `running`+ // indefinitely; dropping the first load there never initializes the list.+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);+ vi.mocked(messageService.getMessages).mockResolvedValue(fetched);++ syncMessages(context);++ await waitFor(() => expect(rowsOf(context)?.map((m) => m.id)).toEqual(['msg-user']));+ });++ it('keeps loaded rows but lands rows the list has never seen (G-05)', async () => {+ // A stale cached first load can miss the parked member's rows; the fresh+ // read that follows must still bring them in, without touching the+ // rows the stream owns.+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);+ const streamed = {+ content: 'streamed so far',+ createdAt: 2000,+ id: 'msg-supervisor',+ role: 'assistant',+ updatedAt: 2000,+ } as UIChatMessage;+ const memberTool = {+ content: '',+ createdAt: 3000,+ id: 'msg-member-tool',+ role: 'tool',+ updatedAt: 3000,+ } as UIChatMessage;+ vi.mocked(messageService.getMessages).mockResolvedValue([+ ...fetched,+ { ...streamed, content: '' },+ memberTool,+ ]);+ seedRows(context, [...fetched, streamed]);++ syncMessages(context);++ await waitFor(() => {+ expect(rowsOf(context)?.map((m) => m.id)).toContain('msg-member-tool');+ });+ expect(rowsOf(context)?.find((m) => m.id === 'msg-supervisor')?.content).toBe(+ 'streamed so far',+ );+ });++ it('drops a refetch that brings nothing new', async () => {+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);+ vi.mocked(messageService.getMessages).mockResolvedValue(fetched);+ const loaded = [{ ...fetched[0], content: 'local' }];+ seedRows(context, loaded);++ syncMessages(context);++ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(rowsOf(context)).toBe(loaded);+ });+ });++ it('lands a result that resolves after a switch in its own conversation only', async () => {+ let resolveFetch!: (messages: UIChatMessage[]) => void;+ vi.mocked(messageService.getMessages).mockReturnValue(+ new Promise((resolve) => {+ resolveFetch = resolve;+ }),+ );+ const oldContext = { ...context, topicId: 'topic-old' };+ const currentContext = { ...context, topicId: 'topic-current' };+ const currentMessages: UIChatMessage[] = [+ {+ content: 'current topic',+ createdAt: 2000,+ id: 'msg-current',+ role: 'user',+ updatedAt: 2000,+ },+ ];+ const late: UIChatMessage = {+ content: 'late old topic result',+ createdAt: 1000,+ id: 'msg-old',+ role: 'assistant',+ updatedAt: 1000,+ };++ syncMessages(oldContext);+ seedRows(currentContext, currentMessages);+ await act(async () => {+ resolveFetch([late]);+ await Promise.resolve();+ });++ await waitFor(() => expect(rowsOf(oldContext)).toEqual([late]));+ expect(rowsOf(currentContext)).toBe(currentMessages);+ });++ it.each([+ ['an empty agent id', { agentId: '', threadId: null, topicId: null }],+ ['a null topic id (new conversation state)', { ...context, topicId: null }],+ ['an undefined topic id (new conversation state)', { ...context, topicId: undefined as any }],+ ])('does not fetch with %s', (_, target) => {+ syncMessages(target);++ // A null key disables the read, so local optimistic rows are not overwritten.+ expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(+ null,+ expect.any(Function),+ expect.any(Object),+ );+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });++ it('keys the sync by the canonical read context', () => {+ // The SWR mock runs the fetcher; an unmocked list read rejects after the test.+ vi.mocked(messageService.getMessages).mockResolvedValue([]);++ syncMessages({ ...context, threadId: 'thread-1' });+ syncMessages({ ...context, threadId: 'thread-2' });++ const [first, second] = messageSyncKeys();+ expect(first).not.toEqual(second);+ expect(first![0]).toBe('message:list');+ expect(first![1]).toEqual({+ agentId: 'test-session',+ groupId: null,+ threadId: 'thread-1',+ topicId: 'test-topic',+ });+ expect((second as any[])[1].threadId).toBe('thread-2');+ });++ it('skips switch-time revalidation after a successful server verification', async () => {+ await runMessageListQuery(context, async () => []);+ vi.mocked(messageService.getMessages).mockResolvedValue([]);++ syncMessages(context);++ expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(+ expect.any(Array),+ expect.any(Function),+ expect.objectContaining({+ dedupingInterval: MESSAGE_LIST_VERIFICATION_INTERVAL,+ revalidateIfStale: false,+ }),+ );+ });++ it('passes groupId to the message read for group chat', async () => {+ vi.mocked(messageService.getMessages).mockResolvedValue([]);++ syncMessages({ ...context, agentId: 'supervisor-agent', groupId: 'group-123' });++ await waitFor(() => {+ expect(messageService.getMessages).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'supervisor-agent',+ groupId: 'group-123',+ topicId: 'test-topic',+ }),+ );+ });+ });++ describe('merging a fetch into local rows', () => {+ const localVoice = (overrides: Partial<UIChatMessage>): UIChatMessage => ({+ audioList: [{ alt: 'voice.webm', id: 'tmp-audio', url: 'blob:voice-preview' }],+ content: '',+ createdAt: 2000,+ id: 'tmp-voice-message',+ metadata: { scope: LOCAL_MESSAGE_SCOPE },+ role: 'user',+ updatedAt: 2000,+ ...overrides,+ });++ it('preserves newer local message state when fetched data is stale', async () => {+ const localError = {+ body: { message: 'Codex CLI was not found' },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ } as any;+ vi.mocked(messageService.getMessages).mockResolvedValue([+ { id: 'msg-1', content: '', role: 'assistant', createdAt: 1000, updatedAt: 1000 },+ ]);+ seedRows(context, [+ {+ id: 'msg-1',+ content: '',+ error: localError,+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 2000,+ },+ ]);++ syncMessages(context);++ await waitFor(() => expect(messageService.getMessages).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(rowsOf(context)?.[0].error).toEqual(localError);+ expect(rowsOf(context)?.[0].updatedAt).toBe(2000);+ });++ it('accepts fetched message state when server data is newer', async () => {+ const persistedError = {+ body: { message: 'Persisted error' },+ message: 'Persisted error',+ type: 'AgentRuntimeError',+ } as any;+ vi.mocked(messageService.getMessages).mockResolvedValue([+ {+ id: 'msg-1',+ content: '',+ error: persistedError,+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 3000,+ },+ ]);+ seedRows(context, [+ { id: 'msg-1', content: '', role: 'assistant', createdAt: 1000, updatedAt: 2000 },+ ]);++ syncMessages(context);++ await waitFor(() => {+ expect(rowsOf(context)?.[0].error).toEqual(persistedError);+ expect(rowsOf(context)?.[0].updatedAt).toBe(3000);+ });+ });++ it('preserves a local-only voice row that is missing from fetched data', async () => {+ const persisted: UIChatMessage = {+ id: 'persisted-message',+ content: 'Persisted message',+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 1000,+ };+ const voice = localVoice({});+ vi.mocked(messageService.getMessages).mockResolvedValue([persisted]);+ seedRows(context, [voice]);+ useChatStore.setState({+ voiceMessageUploadMap: { [voice.id]: { progress: 50, status: 'uploading' } },+ });++ syncMessages(context);++ await waitFor(() => expect(rowsOf(context)).toEqual([persisted, voice]));+ });++ it('keeps an earlier local-only voice row ahead of a later fetched message', async () => {+ const voice = localVoice({ createdAt: 1000, updatedAt: 1000 });+ const later: UIChatMessage = {+ id: 'later-message',+ content: 'Later text',+ role: 'user',+ createdAt: 2000,+ updatedAt: 2000,+ };+ vi.mocked(messageService.getMessages).mockResolvedValue([later]);+ seedRows(context, [voice]);+ useChatStore.setState({+ voiceMessageUploadMap: { [voice.id]: { progress: 50, status: 'uploading' } },+ });++ syncMessages(context);++ await waitFor(() => expect(rowsOf(context)).toEqual([voice, later]));+ });++ it('drops a missing local-only message after its voice transaction settles', async () => {+ const persisted: UIChatMessage = {+ id: 'persisted-message',+ content: 'Persisted message',+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 1000,+ };+ vi.mocked(messageService.getMessages).mockResolvedValue([persisted]);+ seedRows(context, [localVoice({ id: 'tmp-settled-voice-message' })]);++ syncMessages(context);++ await waitFor(() => expect(rowsOf(context)).toEqual([persisted]));+ });++ it('lets a fetched server row replace a newer local-only row with the same id', async () => {+ const fetched: UIChatMessage = {+ id: 'tmp-voice-message',+ audioList: [+ { alt: 'voice.webm', id: 'persisted-audio', url: 'https://example.com/voice.webm' },+ ],+ content: 'Persisted message',+ role: 'user',+ createdAt: 1000,+ updatedAt: 1000,+ };+ const voice = localVoice({ createdAt: 1000, updatedAt: 2000 });+ vi.mocked(messageService.getMessages).mockResolvedValue([fetched]);+ seedRows(context, [voice]);+ useChatStore.setState({+ voiceMessageUploadMap: { [voice.id]: { progress: 100, status: 'sending' } },+ });++ syncMessages(context);++ await waitFor(() => expect(rowsOf(context)).toEqual([fetched]));+ });++ it('keeps optimistic send rows when a stale fetch resolves before the server run starts', async () => {+ const previousReply: UIChatMessage = {+ id: 'previous-reply',+ content: 'Previous reply',+ role: 'assistant',+ createdAt: 1000,+ updatedAt: 1000,+ };+ const optimisticUser: UIChatMessage = {+ id: 'msg_user',+ content: 'Follow-up question',+ role: 'user',+ createdAt: 2000,+ updatedAt: 2000,+ };+ const optimisticAssistant: UIChatMessage = {+ id: 'msg_assistant',+ content: '...',+ role: 'assistant',+ createdAt: 2001,+ updatedAt: 2001,+ };+ // The fetch was issued before the server persisted the new rows.+ vi.mocked(messageService.getMessages).mockResolvedValue([+ { ...previousReply, content: 'Previous reply (fetched)', updatedAt: 1500 },+ ]);+ seedRows(context, [previousReply, optimisticUser, optimisticAssistant]);++ // `sendMessage` is still waiting for `execAgentTask`; no runtime operation exists yet.+ const { operationId } = useChatStore.getState().startOperation({+ context: { ...context, messageId: optimisticUser.id },+ type: 'sendMessage',+ });+ useChatStore.getState().associateMessageWithOperation(optimisticUser.id, operationId);+ useChatStore.getState().associateMessageWithOperation(optimisticAssistant.id, operationId);++ try {+ syncMessages(context);++ await waitFor(() => expect(rowsOf(context)?.[0].content).toBe('Previous reply (fetched)'));+ expect(rowsOf(context)?.map((message) => message.id)).toEqual([+ previousReply.id,+ optimisticUser.id,+ optimisticAssistant.id,+ ]);+ } finally {+ useChatStore.getState().completeOperation(operationId);+ }+ });+ });+});diff --git a/src/store/chat/slices/message/actions/transcript.ts b/src/store/chat/slices/message/actions/transcript.tsnew file mode 100644index 00000000000..16edaec071e--- /dev/null+++ b/src/store/chat/slices/message/actions/transcript.ts@@ -0,0 +1,287 @@+import { type ConversationContext } from '@lobechat/types';+import debug from 'debug';+import { useEffect, useRef } from 'react';+import { type StoreApi, useStore } from 'zustand';++import {+ getMessageListCacheIdentity,+ getMessageListFetchPolicy,+ getMessageListWindowOlderCursor,+ supportsRoundCursor,+} from '@/services/message/cache';+import { conversationMessagesResource } from '@/services/message/replica';+import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';+import { type ChatStore } from '@/store/chat/store';+import {+ hasPendingInterventions,+ INTERVENTION_REFRESH_INTERVAL,+} from '@/store/chat/utils/interventionSync';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { type StoreSetter } from '@/store/types';++import { getMessageTranscript } from '../transcript';++const log = debug('lobe-store:message-transcript');++/** Fetch flags of a transcript sync. The rows live in `dbMessagesMap`. */+export interface MessageSyncResult {+ error: unknown;+ /** A first fetch is in flight and nothing is on screen yet. */+ isLoading: boolean;+ isValidating: boolean;+ /** Re-run the head sync. */+ mutate: () => Promise<unknown>;+}++export interface MessageSyncOptions {+ refreshInterval?: number;+ /**+ * Override SWR's default focus revalidate. Pass `false` while a streaming+ * flow owns the in-memory rows so a focus refetch doesn't clobber them with+ * a stale DB snapshot.+ */+ revalidateOnFocus?: boolean;+ /** No read at all (e.g. while another flow owns the data). */+ skipFetch?: boolean;+ /** Re-read the head after a parked intervention run completes (main topics only). */+ syncInterventions?: boolean;+}++type Setter = StoreSetter<ChatStore>;++/**+ * Reads of the transcript replica: the mounted sync, paging older history,+ * pre-paint hydration and run-end persistence.+ */+export class MessageTranscriptActionImpl {+ readonly #api: StoreApi<ChatStore>;+ readonly #get: () => ChatStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => ChatStore, api?: unknown) {+ this.#api = api as StoreApi<ChatStore>;+ this.#set = set;+ this.#get = get;+ }++ get #transcript() {+ return getMessageTranscript(this.#set, this.#get);+ }++ /**+ * Persist a conversation's settled transcript. Runs when an agent run ends,+ * including for a conversation no view shows any more.+ */+ internal_settleTranscript = (context: ConversationContext): void => {+ this.#transcript.settle(context);+ };++ /**+ * Load one round-aligned page of history older than the server's+ * newest-first window and prepend it to the transcript. No-ops while a page+ * is in flight, once the beginning is reached, or before the conversation+ * has server-backed rows. Never rejects: resolves the failure instead.+ * `started` tells whether a page was requested; `onStart` runs right before.+ */+ loadEarlierMessages = async (+ context: ConversationContext,+ options?: { onStart?: () => void },+ ): Promise<{ error?: unknown; started: boolean }> => {+ const skipped = { started: false };+ if (!context.agentId || !context.topicId) return skipped;++ const { slice } = this.#transcript;+ const key = this.#transcript.keyOf(context);+ const read = () => this.#transcript.read(key);+ const view = read();+ if (!view || view.isLoadingMore) return skipped;++ // A transcript not yet confirmed by a sync (seeded by a send, or painted+ // from storage) pages from the window cursor this session already fetched.+ // A cursor rebuilt from a row's millisecond `createdAt` would skip older+ // rows sharing that millisecond, so a round-cursor read waits for it.+ if (+ this.#get().messageReplica.entries[key]?.source !== 'server' &&+ view.nextCursor === undefined+ ) {+ const windowCursor = getMessageListWindowOlderCursor(context);+ if (windowCursor === undefined && supportsRoundCursor(context)) return skipped;+ if (windowCursor !== undefined)+ slice.update(+ key,+ (data) => data && { ...data, hasMore: windowCursor !== null, nextCursor: windowCursor },+ { persist: false },+ );+ }+ if (!read()?.hasMore) return skipped;++ options?.onStart?.();+ await slice.loadMore(key, context);+ const error = read()?.loadMoreError;+ if (error) log('[loadEarlierMessages] failed | key=%s | %O', messageMapKey(context), error);+ return { error: error ?? undefined, started: true };+ };++ /**+ * Seed a conversation's persisted transcript before its route commits, so a+ * topic opened before paints from local data instead of a skeleton. Rows+ * already in memory (this session's, or streamed) are newer and stay.+ */+ preHydrateMessages = async (context: ConversationContext): Promise<boolean> => {+ const { slice } = this.#transcript;+ const scope = conversationMessagesResource.scope.get();+ // The slot may still hold the previous identity's rows (a session that+ // ended before the identity round-trip landed); drop them before seeding.+ slice.ensureScope(scope);+ return slice.hydrate(context, scope);+ };++ /**+ * Keep a conversation's transcript in sync while a view shows it.+ *+ * Main topics also watch parked intervention runs: an answer given on+ * another device settles the pending card, and the run's `runningOperation`+ * marker is published for the gateway reconnect.+ */+ useFetchMessages = (+ context: ConversationContext,+ options?: MessageSyncOptions,+ ): MessageSyncResult => {+ const { slice, headResolutions, pendingInterventions } = this.#transcript;+ const { skipFetch, revalidateOnFocus, refreshInterval = 0 } = options ?? {};+ // No read for a conversation without a server topic yet (new conversation+ // state): there is no server data, only local optimistic rows, and an+ // empty answer would overwrite them.+ const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;+ const syncKey = getMessageListCacheIdentity(context);+ // Shared views use share-authorized services; thread runs do not own the+ // topic's main runningOperation marker. Keep their existing refresh path.+ const syncContinuation =+ !!options?.syncInterventions &&+ !context.agentShareId &&+ !context.topicShareId &&+ !context.threadId;+ const result = slice.useSync(+ { ...context, syncInterventions: syncContinuation },+ {+ ...getMessageListFetchPolicy(context),+ enabled: shouldFetch,+ // Pending cards must observe answers from another device before the+ // normal message cache's 30-second verification window expires.+ ...((refreshInterval > 0 || pendingInterventions.has(syncKey)) && {+ dedupingInterval: 1000,+ }),+ onSuccess: (fetched) => {+ const resolution = Array.isArray(fetched) ? headResolutions.get(fetched) : undefined;+ if (!resolution || !context.topicId) return;+ headResolutions.delete(fetched as never);+ const { completed, isStreaming, mergedMessages, ownsTopic, snapshot } = resolution;++ // Do not replace a topic marker claimed by a local send or newer push.+ if (!snapshot || hasPendingInterventions(mergedMessages) || !ownsTopic) return;+ if (completed && !isStreaming) pendingInterventions.delete(syncKey);+ const chat = this.#get();+ const currentTopic = topicSelectors.getTopicById(context.topicId)(chat);+ const runningOperation = snapshot.topic?.metadata?.runningOperation;+ if (+ !runningOperation ||+ currentTopic?.metadata?.runningOperation?.operationId === runningOperation.operationId+ )+ return;+ // Publish the marker for useGatewayReconnect; it owns connection+ // deduplication and retry. Do not open a second socket here.+ if (currentTopic) {+ chat.internal_dispatchTopic({+ agentId: context.agentId,+ containerKey: topicSelectors.getTopicContainerKeyById(context.topicId)(chat),+ groupId: context.groupId,+ id: context.topicId,+ type: 'updateTopic',+ value: { metadata: { ...currentTopic.metadata, runningOperation } },+ });+ } else if (snapshot.topic) {+ this.#set({+ topicDetailMap: { ...chat.topicDetailMap, [context.topicId]: snapshot.topic },+ });+ }+ },+ refreshWhenHidden: false,+ refreshWhenOffline: false,+ ...(revalidateOnFocus !== undefined && { revalidateOnFocus }),+ },+ );++ // Poll on our own timer rather than SWR's `refreshInterval`: SWR clears a+ // request's dedupe record after the `dedupingInterval` of the key's FIRST+ // render, so a poll that starts after the conversation's first read (a+ // card that arrived over the stream) was deduped for the whole 30s list+ // window and another device's answer showed up that late. Each tick+ // re-reads the interval: the pending set changes without a render.+ const revalidateRef = useRef(result.revalidate);+ revalidateRef.current = result.revalidate;+ const validatingRef = useRef(result.isValidating);+ validatingRef.current = result.isValidating;+ useEffect(() => {+ if (!shouldFetch) return;+ const intervalOf = () =>+ syncContinuation && pendingInterventions.has(syncKey)+ ? INTERVENTION_REFRESH_INTERVAL+ : refreshInterval;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let cancelled = false;+ const next = () => {+ // A read still in flight when the effect re-ran must not restart this chain.+ if (cancelled) return;+ const interval = intervalOf();+ if (interval > 0) timer = setTimeout(tick, interval);+ };+ const tick = () => {+ const visible = typeof document === 'undefined' || document.visibilityState !== 'hidden';+ const online = typeof navigator === 'undefined' || navigator.onLine !== false;+ if (visible && online && !validatingRef.current) {+ void Promise.resolve(revalidateRef.current()).finally(next);+ return;+ }+ next();+ };+ next();+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [shouldFetch, syncContinuation, syncKey, refreshInterval]);++ // Streamed chunks stay in memory; the transcript is persisted once the+ // run settles, so a reload restores the finished reply.+ const isStreaming = useStore(+ this.#api,+ operationSelectors.isAgentRuntimeRunningByContext(context),+ );+ const bucket = messageMapKey(context);+ const wasStreamingRef = useRef({ bucket, running: isStreaming });+ useEffect(() => {+ if (+ wasStreamingRef.current.bucket === bucket &&+ wasStreamingRef.current.running &&+ !isStreaming+ )+ this.#transcript.settle(context);+ wasStreamingRef.current = { bucket, running: isStreaming };+ }, [isStreaming, bucket]);++ const hasRows = useStore(this.#api, (s) => !!s.dbMessagesMap[bucket]);++ return {+ error: result.error,+ isLoading: result.isValidating && !hasRows,+ isValidating: result.isValidating,+ mutate: result.revalidate,+ };+ };+}++export type MessageTranscriptAction = Pick<+ MessageTranscriptActionImpl,+ keyof MessageTranscriptActionImpl+>;diff --git a/src/store/chat/slices/message/initialState.ts b/src/store/chat/slices/message/initialState.tsindex b71612140c9..b55e6fce7b5 100644--- a/src/store/chat/slices/message/initialState.ts+++ b/src/store/chat/slices/message/initialState.ts@@ -1,6 +1,10 @@import { type UIChatMessage } from '@lobechat/types';import { type ChatGroupAgentItem } from '@/database/schemas/chatGroup';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import { type ConversationMessagePage } from '@/services/message/replica';++import { type TranscriptPaging } from './transcript/lens';export interface ChatMessageState {activeAgentId: string;@@ -17,6 +21,17 @@ export interface ChatMessageState {* is the message is editing*/messageEditingIds: string[];+ /**+ * Paging bookkeeping of each transcript entry (cursor of the next older+ * page, loaded depth), keyed by the transcript entry key. The rows are the+ * entry's `dbMessagesMap` bucket.+ */+ messagePagingMap: Record<string, TranscriptPaging>;+ /**+ * Replica bookkeeping of the transcripts (`dbMessagesMap` + `messagesMap` ++ * `messagePagingMap` are its view).+ */+ messageReplica: ReplicaState<ConversationMessagePage>;/*** whether messages have fetched*/@@ -33,6 +48,8 @@ export const initialMessageState: ChatMessageState = {groupAgentMaps: {},isCreatingMessage: false,messageEditingIds: [],+ messagePagingMap: {},+ messageReplica: createReplicaState(),messagesInit: false,messagesMap: {},};diff --git a/src/store/chat/slices/message/transcript/index.ts b/src/store/chat/slices/message/transcript/index.tsnew file mode 100644index 00000000000..9b4167e8887--- /dev/null+++ b/src/store/chat/slices/message/transcript/index.ts@@ -0,0 +1,267 @@+import { type ChatTopic, type ConversationContext, type UIChatMessage } from '@lobechat/types';+import debug from 'debug';++import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';+import { createReplicaSlice } from '@/libs/replica';+import { messageService } from '@/services/message';+import {+ getMessageListCacheIdentity,+ getMessageListWindowOlderCursor,+ runMessageListQuery,+} from '@/services/message/cache';+import {+ type ConversationMessageFetch,+ type ConversationMessagePage,+ type ConversationMessageParams,+ conversationMessagesKey,+ conversationMessagesResource,+ toPersistedTranscript,+ transcriptOf,+} from '@/services/message/replica';+import { topicService } from '@/services/topic';+import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';+import { type ChatStore } from '@/store/chat/store';+import {+ hasPendingInterventions,+ isInterventionRunActive,+ reconcileStreamingInterventions,+} from '@/store/chat/utils/interventionSync';+import { type StoreSetter } from '@/store/types';++import { bucketOfKey, createTranscriptLens } from './lens';+import { mergeFetchedMessagesWithLocalState } from './mergeFetched';++const log = debug('lobe-store:message-transcript');++export interface InterventionSnapshot {+ dbMessages: UIChatMessage[];+ topic: ChatTopic | null;+ topicAtRequest?: ChatTopic;+}++/** What a head response resolved to, handed from `prepareHead` to the sync's `onSuccess`. */+export interface HeadResolution {+ completed: boolean;+ /** The response changed nothing during a stream: kept off the transcript. */+ dropped: boolean;+ isStreaming: boolean;+ mergedMessages: UIChatMessage[];+ ownsTopic: boolean;+ snapshot?: InterventionSnapshot;+}++type TranscriptContext = Partial<ConversationContext> & Pick<ConversationContext, 'agentId'>;++/**+ * The chat store's message replica: one entry per conversation bucket, the+ * only writer of `dbMessagesMap` / `messagesMap`. Every surface showing a+ * conversation reads that bucket; streamed chunks stay in memory and the+ * settled transcript persists, so a reload paints the finished reply.+ */+const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatStore) => {+ /** Main-topic sync keys waiting for a parked intervention run to settle. */+ const pendingInterventions = new Set<string>();+ const snapshots = new WeakMap<UIChatMessage[], InterventionSnapshot>();+ /** Head responses resolved by `prepareHead`, read back by the sync's `onSuccess`. */+ const headResolutions = new WeakMap<UIChatMessage[], HeadResolution>();+ /** The entry key each bucket was last written under. */+ const bucketKeys = new Map<string, string>();++ const lens = createTranscriptLens();++ /**+ * The entry key of a conversation. A write whose context lacks a field the+ * sync carried (a share id) must land in the entry the sync established, so+ * the bucket's current key wins over a recomputed one.+ */+ const keyOf = (context: TranscriptContext) => {+ const key = conversationMessagesKey(context as ConversationContext);+ return bucketKeys.get(bucketOfKey(key).bucket) ?? key;+ };++ const bucketRows = (key: string) => get().dbMessagesMap[bucketOfKey(key).bucket];++ // ---- reads ---------------------------------------------------------------+ const fetchHead = async (context: ConversationMessageParams): Promise<UIChatMessage[]> => {+ const syncKey = getMessageListCacheIdentity(context);+ const dbMessages = bucketRows(conversationMessagesKey(context)) ?? [];+ const topicAtRequest = context.topicId+ ? topicSelectors.getTopicById(context.topicId)(get())+ : undefined;+ const wasPending = hasPendingInterventions(dbMessages);+ let messages = await runMessageListQuery(context, readConversationMessageListPage);+ if (!context.syncInterventions || !context.topicId) return messages;+ if (wasPending || hasPendingInterventions(messages)) pendingInterventions.add(syncKey);+ if (!pendingInterventions.has(syncKey) || hasPendingInterventions(messages)) return messages;++ // The decision must precede the liveness read. A startup reservation is+ // still live even before runningOperation is published.+ const topic = await topicService.getTopicDetail(context.topicId);+ if (!isInterventionRunActive(topic)) {+ // Read after completion without dropping loaded history or its cursor.+ messages = await runMessageListQuery(context, readConversationMessageListPage, {+ force: true,+ });+ }+ const result = [...messages];+ snapshots.set(result, { dbMessages, topic, topicAtRequest });+ return result;+ };++ const fetchOlder = async (+ context: ConversationMessageParams,+ cursor: NonNullable<ConversationMessagePage['nextCursor']>,+ ): Promise<ConversationMessageFetch> => {+ const page = await messageService.getEarlierMessages(+ {+ agentId: context.agentId,+ agentShareId: context.agentShareId,+ groupId: context.groupId,+ threadId: context.threadId,+ topicId: context.topicId,+ topicShareId: context.topicShareId,+ },+ cursor,+ );+ // Without a reported cursor, `length < pageSize` is NOT a reliable end+ // signal — the round-start trim legitimately shortens full pages — so only+ // an empty page marks the top (`applyNextPage`).+ return { items: page.messages, nextCursor: page.olderCursor };+ };++ /**+ * Fold a fetched head window into the bucket the way the conversation always+ * has: keep streamed rows and unanswered interventions during a run, and+ * keep client rows the server snapshot cannot know yet.+ */+ const prepareHead = (+ incoming: ConversationMessageFetch,+ current: ConversationMessagePage | undefined,+ context: ConversationMessageParams,+ ): ConversationMessageFetch | undefined => {+ if (!Array.isArray(incoming)) return incoming;+ if (!context.topicId) return undefined;++ // DB chunk writes can lag behind pushed content, even at an equal+ // updatedAt. Keep streamed rows, but allow answers and unseen rows in.+ // A parked run must not block the first load of the conversation.+ const prevDbMessages = current?.items ?? [];+ const snapshot = snapshots.get(incoming);+ snapshots.delete(incoming);+ const chat = get();+ const currentTopic = topicSelectors.getTopicById(context.topicId)(chat);+ const ownsTopic = !!snapshot && currentTopic === snapshot.topicAtRequest;+ const completed = ownsTopic && !isInterventionRunActive(snapshot!.topic);+ const isStreaming =+ !!current &&+ operationSelectors.isAgentRuntimeRunningByContext(context)(chat) &&+ !(completed && snapshot!.dbMessages === prevDbMessages);+ const activeVoiceMessageIds = new Set(Object.keys(chat.voiceMessageUploadMap));+ const creatingMessageIds = new Set(+ prevDbMessages+ .filter((message) => operationSelectors.isMessageCreating(message.id)(chat))+ .map((message) => message.id),+ );+ const mergedMessages = isStreaming+ ? reconcileStreamingInterventions(prevDbMessages, incoming)+ : mergeFetchedMessagesWithLocalState(+ incoming,+ prevDbMessages,+ activeVoiceMessageIds,+ creatingMessageIds,+ );+ const dropped = isStreaming && mergedMessages === prevDbMessages;++ headResolutions.set(incoming, {+ completed,+ dropped,+ isStreaming,+ mergedMessages,+ ownsTopic,+ snapshot,+ });+ if (dropped) return undefined;++ log(+ '[head] key=%s | prevCount=%d | fetchedCount=%d',+ conversationMessagesKey(context),+ prevDbMessages.length,+ mergedMessages.length,+ );+ return { items: mergedMessages, nextCursor: getMessageListWindowOlderCursor(context) };+ };++ const slice = createReplicaSlice(conversationMessagesResource, {+ actionPrefix: 'messageTranscript',+ fetcher: (context, cursor) => (cursor ? fetchOlder(context, cursor) : fetchHead(context)),+ get,+ prepareHead,+ set,+ stateKey: 'messageReplica',+ toPersisted: toPersistedTranscript,+ view: {+ ...lens,+ set: (state, key, data) => {+ const { bucket } = bucketOfKey(key);+ if (data) bucketKeys.set(bucket, key);+ else if (bucketKeys.get(bucket) === key) bucketKeys.delete(bucket);+ return lens.set(state, key, data);+ },+ },+ });++ /**+ * Write a conversation's rows (memory only). An unchanged id sequence keeps+ * the entry's paging; so does `preservePaging` (a reducer edit of the same+ * window). Anything else is a fresh, unpaged transcript.+ */+ const commit = (context: TranscriptContext, messages: UIChatMessage[], preservePaging = false) =>+ slice.update(+ keyOf(context),+ (current) =>+ current &&+ (preservePaging ||+ (current.items.length === messages.length &&+ current.items.every((item, index) => item.id === messages[index].id)))+ ? { ...current, items: messages }+ : transcriptOf(messages),+ { persist: false },+ );++ /**+ * Persist a conversation once it is settled — never per streamed chunk; the+ * snapshot written at run end is the one that survives a reload.+ */+ const settle = (context: TranscriptContext) => {+ if (operationSelectors.isAgentRuntimeRunningByContext(context as ConversationContext)(get()))+ return;+ const key = keyOf(context);+ if (lens.get(get(), key)) slice.persist(key);+ };++ return {+ commit,+ headResolutions,+ keyOf,+ pendingInterventions,+ /** The entry's current value, as the replica sees it. */+ read: (key: string) => lens.get(get(), key),+ settle,+ slice,+ };+};++export type MessageTranscript = ReturnType<typeof createMessageTranscript>;++const transcripts = new WeakMap<() => ChatStore, MessageTranscript>();++/** The store's one transcript replica, shared by every message action class. */+export const getMessageTranscript = (+ set: StoreSetter<ChatStore>,+ get: () => ChatStore,+): MessageTranscript => {+ let transcript = transcripts.get(get);+ if (!transcript) transcripts.set(get, (transcript = createMessageTranscript(set, get)));+ return transcript;+};diff --git a/src/store/chat/slices/message/transcript/lens.ts b/src/store/chat/slices/message/transcript/lens.tsnew file mode 100644index 00000000000..e71049f061e--- /dev/null+++ b/src/store/chat/slices/message/transcript/lens.ts@@ -0,0 +1,95 @@+import { parse } from '@lobechat/conversation-flow';+import { type UIChatMessage } from '@lobechat/types';++import { type ReplicaLens } from '@/libs/replica';+import {+ type ConversationMessagePage,+ transcriptBucketOf,+ transcriptOf,+} from '@/services/message/replica';+import { type ChatStore } from '@/store/chat/store';++/** Paging bookkeeping of one transcript entry; its rows live in `dbMessagesMap`. */+export type TranscriptPaging = Omit<ConversationMessagePage, 'items'>;++const NO_PAGING = {} as TranscriptPaging;++const buckets = new Map<string, ReturnType<typeof transcriptBucketOf>>();++/** The bucket an entry key renders into (memoized: read on every streamed chunk). */+export const bucketOfKey = (key: string) => {+ let bucket = buckets.get(key);+ if (!bucket) buckets.set(key, (bucket = transcriptBucketOf(key)));+ return bucket;+};++const omitKey = <T>(record: Record<string, T>, key: string) => {+ if (!(key in record)) return record;+ const next = { ...record };+ delete next[key];+ return next;+};++/**+ * The chat store's transcript view: rows stay in `dbMessagesMap[bucket]` where+ * every reader expects them, the parsed `messagesMap[bucket]` is derived in the+ * same commit, and the paging bookkeeping sits beside them per entry key.+ */+export const createTranscriptLens = (): ReplicaLens<ChatStore, ConversationMessagePage> => {+ // Stable value identity per (rows, paging) pair, so repeated reads of an+ // unchanged entry compare equal.+ const views = new WeakMap<UIChatMessage[], WeakMap<object, ConversationMessagePage>>();+ const remember = (items: UIChatMessage[], paging: object, view: ConversationMessagePage) => {+ let byPaging = views.get(items);+ if (!byPaging) views.set(items, (byPaging = new WeakMap()));+ byPaging.set(paging, view);+ return view;+ };++ return {+ clear: (state) => {+ const dbMessagesMap = { ...state.dbMessagesMap };+ const messagesMap = { ...state.messagesMap };+ for (const key of Object.keys(state.messagePagingMap)) {+ const { bucket } = bucketOfKey(key);+ delete dbMessagesMap[bucket];+ delete messagesMap[bucket];+ }+ return { dbMessagesMap, messagePagingMap: {}, messagesMap };+ },+ get: (state, key) => {+ const items = state.dbMessagesMap[bucketOfKey(key).bucket];+ if (!items) return undefined;+ const paging = state.messagePagingMap[key];+ return (+ views.get(items)?.get(paging ?? NO_PAGING) ??+ remember(items, paging ?? NO_PAGING, paging ? { ...paging, items } : transcriptOf(items))+ );+ },+ keys: (state) => Object.keys(state.messagePagingMap),+ set: (state, key, data) => {+ const { bucket, threadId } = bucketOfKey(key);+ if (!data)+ return {+ dbMessagesMap: omitKey(state.dbMessagesMap, bucket),+ messagePagingMap: omitKey(state.messagePagingMap, key),+ messagesMap: omitKey(state.messagesMap, bucket),+ };++ const { items, ...paging } = data;+ remember(items, paging, data);+ const sameRows = state.dbMessagesMap[bucket] === items && !!state.messagesMap[bucket];+ return {+ dbMessagesMap: sameRows ? state.dbMessagesMap : { ...state.dbMessagesMap, [bucket]: items },+ messagePagingMap: { ...state.messagePagingMap, [key]: paging },+ // The key's thread decides which threaded rows render (see conversation-flow `ThreadScope`).+ messagesMap: sameRows+ ? state.messagesMap+ : {+ ...state.messagesMap,+ [bucket]: parse(items, undefined, { threadId: threadId ?? undefined }).flatList,+ },+ };+ },+ };+};diff --git a/src/store/chat/slices/message/transcript/mergeFetched.ts b/src/store/chat/slices/message/transcript/mergeFetched.tsnew file mode 100644index 00000000000..c141c2c4895--- /dev/null+++ b/src/store/chat/slices/message/transcript/mergeFetched.ts@@ -0,0 +1,54 @@+import { type UIChatMessage } from '@lobechat/types';++import { reconcileIntervention } from '@/store/chat/utils/interventionSync';+import {+ isLocalOnlyMessage,+ mergeLocalMessagesByCreatedAt,+} from '@/store/chat/utils/localMessages';++/**+ * Merge an idle head fetch into the shown transcript.+ *+ * A fetch can be issued before a send persists its rows and resolve while+ * `sendMessage` is still waiting for the server. That window is not a running+ * agent runtime, so the optimistic user and assistant rows must be kept+ * explicitly until the server returns them; otherwise the just-sent message+ * vanishes until the run settles and refetches.+ */+export const mergeFetchedMessagesWithLocalState = (+ fetchedMessages: UIChatMessage[],+ localMessages: UIChatMessage[],+ activeVoiceMessageIds: ReadonlySet<string>,+ creatingMessageIds: ReadonlySet<string>,+): UIChatMessage[] => {+ if (localMessages.length === 0) return fetchedMessages;++ const localById = new Map(localMessages.map((message) => [message.id, message]));+ const fetchedIds = new Set(fetchedMessages.map((message) => message.id));+ let changed = false;++ const mergedMessages = fetchedMessages.map((message) => {+ const localMessage = localById.get(message.id);++ if (!localMessage) return message;+ const resolved = reconcileIntervention(localMessage, message);+ if (resolved) return resolved;+ // Once the server returns this id, its persisted row replaces the local-only preview.+ if (isLocalOnlyMessage(localMessage)) return message;+ if (localMessage.updatedAt <= message.updatedAt) return message;++ changed = true;+ return localMessage;+ });++ const missingLocalMessages = localMessages.filter(+ (message) =>+ !fetchedIds.has(message.id) &&+ ((isLocalOnlyMessage(message) && activeVoiceMessageIds.has(message.id)) ||+ creatingMessageIds.has(message.id)),+ );++ if (missingLocalMessages.length === 0) return changed ? mergedMessages : fetchedMessages;++ return mergeLocalMessagesByCreatedAt(mergedMessages, missingLocalMessages);+};diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex 69dee56b0af..d62bfbb9c3e 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -2,7 +2,6 @@ import { nanoid } from '@lobechat/utils';import debug from 'debug';import { produce } from 'immer';-import { persistSettledTranscript } from '@/services/message/replica';import { type ChatStore } from '@/store/chat/store';import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -357,12 +356,8 @@ export class OperationActionsImpl {if (!agentId || !topicId) return;// A run that finishes after the user switched away must still persist to// its own conversation, so rebuild the operation's context with a definite- // agent/topic: `OperationContext` exposes them as optional, but the runtime- // check, the message key and the persist call all need a concrete agentId.- const context = { ...operation.context, agentId, topicId };- if (operationSelectors.isAgentRuntimeRunningByContext(context)(state)) return;- const messages = state.dbMessagesMap[messageMapKey(context)];- if (messages) persistSettledTranscript(context, messages);+ // agent/topic: `OperationContext` exposes them as optional.+ state.internal_settleTranscript({ ...operation.context, agentId, topicId });}};diff --git a/src/store/chat/slices/thread/action.openThreadCreator.test.ts b/src/store/chat/slices/thread/action.openThreadCreator.test.tsnew file mode 100644index 00000000000..c9989d0c497--- /dev/null+++ b/src/store/chat/slices/thread/action.openThreadCreator.test.ts@@ -0,0 +1,282 @@+import { type UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ThreadType } from '@/types/topic';++import { useChatStore } from '../../store';++// Mock @/libs/swr mutate+vi.mock('@/libs/swr', async () => {+ const actual = await vi.importActual('@/libs/swr');+ return {+ ...actual,+ mutate: vi.fn(),+ };+});++// Mock version constants+vi.mock(import('@/const/version'), async (importOriginal) => ({+ ...(await importOriginal()),+ isDeprecatedEdition: false,+ isDesktop: false,+}));++// Mock threadService+vi.mock('@/services/thread', () => ({+ threadService: {+ createThreadWithMessage: vi.fn(),+ getThreads: vi.fn(),+ removeThread: vi.fn(),+ updateThread: vi.fn(),+ },+}));++// Mock chatService+vi.mock('@/services/chat', () => ({+ chatService: {+ fetchPresetTaskResult: vi.fn(),+ },+}));++vi.mock('@/services/aiChat', () => ({+ aiChatService: {+ generateJSON: vi.fn(),+ },+}));++// Mock mutate from SWR+vi.mock('swr', async () => {+ const actual = await vi.importActual('swr');+ return {+ ...actual,+ mutate: vi.fn(),+ };+});++// Mock store helpers+vi.mock('@/store/global/helpers', () => ({+ globalHelpers: {+ getCurrentLanguage: vi.fn(() => 'en-US'),+ },+}));++vi.mock('@/store/session', () => ({+ useSessionStore: {+ getState: vi.fn(() => ({+ triggerSessionUpdate: vi.fn(),+ })),+ },+}));++// Message writes go through the transcript replica, which reads the cache scope.+vi.mock('@/libs/swr/useCacheScope', () => ({+ getCacheScope: () => 'test-scope',+ isScopeTrusted: () => false,+ useCacheScope: () => 'test-scope',+}));++vi.mock('@/store/user', () => ({+ useUserStore: {+ getState: vi.fn(() => ({})),+ },+}));++vi.mock('@/store/user/selectors', () => ({+ systemAgentSelectors: {+ thread: vi.fn(() => ({})),+ },+ userGeneralSettingsSelectors: {+ currentResponseLanguage: vi.fn(() => 'en-US'),+ },+ userProfileSelectors: {+ userAvatar: vi.fn(() => 'avatar-url'),+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+ useChatStore.setState(+ {+ activeAgentId: 'test-session-id',+ activeTopicId: 'test-topic-id',+ isCreatingThread: false,+ isCreatingThreadMessage: false,+ messagesMap: {},+ newThreadMode: ThreadType.Continuation,+ portalThreadId: undefined,+ startToForkThread: undefined,+ threadInputMessage: '',+ threadLoadingIds: [],+ threadMaps: {},+ threadStartMessageId: undefined,+ threadsInit: false,+ },+ false,+ );+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('thread action', () => {+ describe('openThreadCreator', () => {+ it('should set thread creator state and open portal', () => {+ const { result } = renderHook(() => useChatStore());+ const pushPortalViewSpy = vi.spyOn(result.current, 'pushPortalView');++ act(() => {+ result.current.openThreadCreator('message-id');+ });++ expect(result.current.threadStartMessageId).toBe('message-id');+ expect(result.current.portalThreadId).toBeUndefined();+ expect(result.current.startToForkThread).toBe(true);+ expect(pushPortalViewSpy).toHaveBeenCalledWith({+ type: 'thread',+ startMessageId: 'message-id',+ });+ });++ it('should initialize optimistic parent messages from main scope messages', () => {+ const { result } = renderHook(() => useChatStore());++ const mainMessages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'user',+ content: 'first',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ },+ {+ id: 'msg-2',+ role: 'assistant',+ content: 'reply',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ },+ {+ id: 'msg-3',+ role: 'user',+ content: 'second',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ },+ ];++ act(() => {+ useChatStore.setState({+ messagesMap: {+ 'main_test-session-id_test-topic-id': mainMessages,+ },+ });+ });++ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');++ act(() => {+ result.current.openThreadCreator('msg-3');+ });++ // Should call replaceMessages with all 3 parent messages (continuation mode)+ expect(replaceMessagesSpy).toHaveBeenCalledWith(+ mainMessages,+ expect.objectContaining({ action: 'initThreadMessages' }),+ );+ });++ it('should use main scope messages even when activeThreadId is set ()', () => {+ const { result } = renderHook(() => useChatStore());++ const mainMessages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'user',+ content: 'first',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ },+ {+ id: 'msg-2',+ role: 'assistant',+ content: 'reply',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ },+ {+ id: 'msg-3',+ role: 'user',+ content: 'second',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ },+ ];++ const threadMessages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'user',+ content: 'first',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ },+ {+ id: 'thread-msg-1',+ role: 'user',+ content: 'thread msg',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ threadId: 'existing-thread',+ },+ {+ id: 'thread-msg-2',+ role: 'assistant',+ content: 'thread reply',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ agentId: 'test-session-id',+ threadId: 'existing-thread',+ },+ ];++ act(() => {+ useChatStore.setState({+ activeThreadId: 'existing-thread',+ messagesMap: {+ // Main scope has all messages including msg-3+ 'main_test-session-id_test-topic-id': mainMessages,+ // Thread scope does NOT have msg-3+ 'thread_test-session-id_test-topic-id_existing-thread': threadMessages,+ },+ });+ });++ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');++ act(() => {+ // Fork from msg-3 which only exists in main scope+ result.current.openThreadCreator('msg-3');+ });++ // BUG: if openThreadCreator uses activeDisplayMessages (which includes activeThreadId),+ // it gets thread-scoped messages that don't contain msg-3,+ // genParentMessages returns [], and replaceMessages is never called.+ //+ // FIX: openThreadCreator should always use main scope key to get messages.+ expect(replaceMessagesSpy).toHaveBeenCalledWith(+ mainMessages,+ expect.objectContaining({ action: 'initThreadMessages' }),+ );+ });+ });+});diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.tsindex 0abd42701d9..c326b2dea06 100644--- a/src/store/chat/slices/thread/action.test.ts+++ b/src/store/chat/slices/thread/action.test.ts@@ -149,165 +149,6 @@ describe('thread action', () => {});});- describe('openThreadCreator', () => {- it('should set thread creator state and open portal', () => {- const { result } = renderHook(() => useChatStore());- const pushPortalViewSpy = vi.spyOn(result.current, 'pushPortalView');-- act(() => {- result.current.openThreadCreator('message-id');- });-- expect(result.current.threadStartMessageId).toBe('message-id');- expect(result.current.portalThreadId).toBeUndefined();- expect(result.current.startToForkThread).toBe(true);- expect(pushPortalViewSpy).toHaveBeenCalledWith({- type: 'thread',- startMessageId: 'message-id',- });- });-- it('should initialize optimistic parent messages from main scope messages', () => {- const { result } = renderHook(() => useChatStore());-- const mainMessages: UIChatMessage[] = [- {- id: 'msg-1',- role: 'user',- content: 'first',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- },- {- id: 'msg-2',- role: 'assistant',- content: 'reply',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- },- {- id: 'msg-3',- role: 'user',- content: 'second',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- },- ];-- act(() => {- useChatStore.setState({- messagesMap: {- 'main_test-session-id_test-topic-id': mainMessages,- },- });- });-- const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');-- act(() => {- result.current.openThreadCreator('msg-3');- });-- // Should call replaceMessages with all 3 parent messages (continuation mode)- expect(replaceMessagesSpy).toHaveBeenCalledWith(- mainMessages,- expect.objectContaining({ action: 'initThreadMessages' }),- );- });-- it('should use main scope messages even when activeThreadId is set ()', () => {- const { result } = renderHook(() => useChatStore());-- const mainMessages: UIChatMessage[] = [- {- id: 'msg-1',- role: 'user',- content: 'first',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- },- {- id: 'msg-2',- role: 'assistant',- content: 'reply',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- },- {- id: 'msg-3',- role: 'user',- content: 'second',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- },- ];-- const threadMessages: UIChatMessage[] = [- {- id: 'msg-1',- role: 'user',- content: 'first',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- },- {- id: 'thread-msg-1',- role: 'user',- content: 'thread msg',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- threadId: 'existing-thread',- },- {- id: 'thread-msg-2',- role: 'assistant',- content: 'thread reply',- createdAt: Date.now(),- updatedAt: Date.now(),- agentId: 'test-session-id',- threadId: 'existing-thread',- },- ];-- act(() => {- useChatStore.setState({- activeThreadId: 'existing-thread',- messagesMap: {- // Main scope has all messages including msg-3- 'main_test-session-id_test-topic-id': mainMessages,- // Thread scope does NOT have msg-3- 'thread_test-session-id_test-topic-id_existing-thread': threadMessages,- },- });- });-- const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');-- act(() => {- // Fork from msg-3 which only exists in main scope- result.current.openThreadCreator('msg-3');- });-- // BUG: if openThreadCreator uses activeDisplayMessages (which includes activeThreadId),- // it gets thread-scoped messages that don't contain msg-3,- // genParentMessages returns [], and replaceMessages is never called.- //- // FIX: openThreadCreator should always use main scope key to get messages.- expect(replaceMessagesSpy).toHaveBeenCalledWith(- mainMessages,- expect.objectContaining({ action: 'initThreadMessages' }),- );- });- });-describe('openThreadInPortal', () => {it('should set portal thread state and open portal', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/translate/action.test.ts b/src/store/chat/slices/translate/action.test.tsindex 8eeed552cc3..94496e57d47 100644--- a/src/store/chat/slices/translate/action.test.ts+++ b/src/store/chat/slices/translate/action.test.ts@@ -23,6 +23,13 @@ vi.mock('@/services/chat', () => ({},}));+// Message writes go through the transcript replica, which reads the cache scope.+vi.mock('@/libs/swr/useCacheScope', () => ({+ getCacheScope: () => 'test-scope',+ isScopeTrusted: () => false,+ useCacheScope: () => 'test-scope',+}));+vi.mock('@/store/user', () => ({useUserStore: {getState: vi.fn(() => ({})),