π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): topic switch locks on stale partial message list (#17789)
Arvin Xu36ce556cb9c6
diff --git a/src/features/AgentBuilder/AgentBuilderProvider.tsx b/src/features/AgentBuilder/AgentBuilderProvider.tsxindex 3c7f80bcbed..81e768b0e32 100644--- a/src/features/AgentBuilder/AgentBuilderProvider.tsx+++ b/src/features/AgentBuilder/AgentBuilderProvider.tsx@@ -69,8 +69,8 @@ const AgentBuilderProvider = memo<AgentBuilderProviderProps>(hasInitMessages={!!messages}messages={messages}operationState={operationState}- onMessagesChange={(msgs, ctx) => {- replaceMessages(msgs, { context: ctx });+ onMessagesChange={(msgs, ctx, meta) => {+ replaceMessages(msgs, { context: ctx, source: meta?.source });}}>{children}diff --git a/src/features/AgentTaskManager/TaskAgentProvider.tsx b/src/features/AgentTaskManager/TaskAgentProvider.tsxindex c08546d185b..cc50b1ffcf2 100644--- a/src/features/AgentTaskManager/TaskAgentProvider.tsx+++ b/src/features/AgentTaskManager/TaskAgentProvider.tsx@@ -112,8 +112,8 @@ export const TaskAgentProvider = memo<TaskAgentProviderProps>(({ children }) =>hasInitMessages={!!messages}messages={messages}operationState={operationState}- onMessagesChange={(msgs, ctx) => {- replaceMessages(msgs, { context: ctx });+ onMessagesChange={(msgs, ctx, meta) => {+ replaceMessages(msgs, { context: ctx, source: meta?.source });}}>{children}diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsxindex 671b6b7d040..a6c5e419d36 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx@@ -85,8 +85,8 @@ export const TopicChatDrawerBody = memo<TopicChatDrawerBodyProps>(hasInitMessages={!!messages}messages={messages}operationState={operationState}- onMessagesChange={(msgs, ctx) => {- replaceMessages(msgs, { context: ctx });+ onMessagesChange={(msgs, ctx, meta) => {+ replaceMessages(msgs, { context: ctx, source: meta?.source });}}><TaskCardScopeProvider value={true}>diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsxindex 8ad2dd5c31f..4e47580088b 100644--- a/src/features/Conversation/ConversationProvider.tsx+++ b/src/features/Conversation/ConversationProvider.tsx@@ -16,6 +16,7 @@ import {type ActionsBarConfig,type ConversationContext,type ConversationHooks,+ type MessagesChangeMeta,type OperationState,} from './types';@@ -63,8 +64,15 @@ export interface ConversationProviderProps {** @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) => void;+ onMessagesChange?: (+ messages: UIChatMessage[],+ context: ConversationContext,+ meta?: MessagesChangeMeta,+ ) => void;/*** External operation state (from ChatStore)*diff --git a/src/features/Conversation/StoreUpdater.tsx b/src/features/Conversation/StoreUpdater.tsxindex 552f27e1412..10f4f1f5b8c 100644--- a/src/features/Conversation/StoreUpdater.tsx+++ b/src/features/Conversation/StoreUpdater.tsx@@ -12,6 +12,7 @@ import {type ActionsBarConfig,type ConversationContext,type ConversationHooks,+ type MessagesChangeMeta,type OperationState,} from './types';@@ -35,7 +36,11 @@ export interface StoreUpdaterProps {/*** Callback when messages are fetched or changed internally*/- onMessagesChange?: (messages: UIChatMessage[], context: ConversationContext) => void;+ onMessagesChange?: (+ messages: UIChatMessage[],+ context: ConversationContext,+ meta?: MessagesChangeMeta,+ ) => void;/*** External operation state (from ChatStore)*/@@ -90,9 +95,12 @@ const StoreUpdater = memo<StoreUpdaterProps>(messagesInit: false,});- // If messages are already available, sync them immediately+ // 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);+ storeApi.getState().replaceMessages(messages, { skipOnMessagesChange: true });storeApi.setState({ messagesInit: true });}}@@ -118,7 +126,10 @@ const StoreUpdater = memo<StoreUpdaterProps>();prevMessagesRef.current = messages;- storeApi.getState().replaceMessages(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 });}}, [messages, storeApi, contextKey]);diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.tsindex 0f8fec39f6d..d5b5ece9274 100644--- a/src/features/Conversation/store/initialState.ts+++ b/src/features/Conversation/store/initialState.ts@@ -4,6 +4,7 @@ import {type ActionsBarConfig,type ConversationContext,type ConversationHooks,+ type MessagesChangeMeta,type OperationState,} from '../types';import { DEFAULT_OPERATION_STATE } from '../types/operation';@@ -36,8 +37,14 @@ export interface State extends DataState, InputState, MessageStateState, VirtuaL* 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) => void;+ onMessagesChange?: (+ messages: UIChatMessage[],+ context: ConversationContext,+ meta?: MessagesChangeMeta,+ ) => void;/*** External operation state (from ChatStore)diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex 303473652fb..42c2ead7548 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -301,6 +301,40 @@ describe('DataSlice', () => {expect(state.displayMessages).toHaveLength(0);expect(state.dbMessages).toHaveLength(0);});++ it('should sync internal replacements to the external store via onMessagesChange', () => {+ 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 });++ // 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();+ });});describe('selectors', () => {@@ -580,6 +614,28 @@ describe('DataSlice', () => {});});+ 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 });++ store.getState().useFetchMessages(context);++ await waitFor(() => {+ expect(onMessagesChange).toHaveBeenCalledWith(mockMessages, context, { source: 'fetch' });+ });+ });+it('should pass null threadId when provided as null', async () => {const mockMessages: UIChatMessage[] = [{diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex 9e8395c6b0e..0a10c68ea59 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -62,8 +62,18 @@ export interface DataAction {* Used for syncing after database operations (optimistic update pattern)** @param messages - New messages array from database+ * @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.*/- replaceMessages: (messages: UIChatMessage[]) => void;+ replaceMessages: (+ messages: UIChatMessage[],+ options?: { skipOnMessagesChange?: boolean },+ ) => void;/*** Switch message branch by updating the parent's activeBranchIndex@@ -158,7 +168,7 @@ export const dataSlice: StateCreator<get().onMessagesChange?.(newDbMessages, get().context);},- replaceMessages: (messages) => {+ replaceMessages: (messages, options) => {const contextKey = messageMapKey(get().context);const prevDbMessages = get().dbMessages;@@ -167,18 +177,21 @@ export const dataSlice: StateCreator<const stableFlatList = stabilizeReferences(get().displayMessages, flatList);log(- '[replaceMessages] | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d | messageIds=%o',+ '[replaceMessages] | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d | skipOnMessagesChange=%s | messageIds=%o',contextKey,prevDbMessages.length,messages.length,stableFlatList.length,+ options?.skipOnMessagesChange,messages.slice(0, 5).map((m) => m.id),);set({ dbMessages: messages, displayMessages: stableFlatList }, false, 'replaceMessages');- // Sync changes to external store (ChatStore)- get().onMessagesChange?.(messages, get().context);+ // 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, get().context);},switchMessageBranch: async (messageId, branchIndex) => {@@ -267,8 +280,13 @@ export const dataSlice: StateCreator<});// Call onMessagesChange callback with the request context (not current context)- // This ensures data is stored to the correct topic even if user switched topics- get().onMessagesChange?.(mergedMessages, context);+ // This ensures data is stored to the correct topic even if user switched topics.+ // `source: 'fetch'` marks this as a server-snapshot echo: handlers must+ // NOT write it through the SWR cache β at mount, this fires with the+ // stale cached list while the revalidation is in flight, and a cache+ // mutate here trips SWR's mutation race guard, discarding the fresh+ // result (conversation locks on the stale/partial list).+ get().onMessagesChange?.(mergedMessages, context, { source: 'fetch' });},},);diff --git a/src/features/Conversation/types/context.ts b/src/features/Conversation/types/context.tsindex 58a8d1dde38..e44800a7e96 100644--- a/src/features/Conversation/types/context.ts+++ b/src/features/Conversation/types/context.ts@@ -29,6 +29,23 @@ 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/FloatingChatPanel/index.tsx b/src/features/FloatingChatPanel/index.tsxindex 8e086f97f4b..ac8455fc87b 100644--- a/src/features/FloatingChatPanel/index.tsx+++ b/src/features/FloatingChatPanel/index.tsx@@ -15,7 +15,7 @@ import {ConversationProvider,} from '@/features/Conversation';import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';-import { type ConversationContext } from '@/features/Conversation/types';+import { type ConversationContext, type MessagesChangeMeta } from '@/features/Conversation/types';import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConversationHooks';import { useOperationState } from '@/hooks/useOperationState';import { useActionsBarConfig } from '@/routes/(main)/agent/features/Conversation/useActionsBarConfig';@@ -162,8 +162,8 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);const replaceMessages = useChatStore((s) => s.replaceMessages);const handleMessagesChange = useCallback(- (next: UIChatMessage[], ctx: ConversationContext) => {- replaceMessages(next, { context: ctx });+ (next: UIChatMessage[], ctx: ConversationContext, meta?: MessagesChangeMeta) => {+ replaceMessages(next, { context: ctx, source: meta?.source });},[replaceMessages],);diff --git a/src/features/GlobalApprovalNotification/ApprovalCard.tsx b/src/features/GlobalApprovalNotification/ApprovalCard.tsxindex efe38628c2a..b4e9cdef3a5 100644--- a/src/features/GlobalApprovalNotification/ApprovalCard.tsx+++ b/src/features/GlobalApprovalNotification/ApprovalCard.tsx@@ -12,7 +12,7 @@ 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 } from '@/features/Conversation/types';+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';@@ -46,8 +46,8 @@ const ApprovalCard = memo<ApprovalCardProps>(({ group }) => {const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);const replaceMessages = useChatStore((s) => s.replaceMessages);const handleMessagesChange = useCallback(- (next: UIChatMessage[], ctx: ConversationContext) => {- replaceMessages(next, { context: ctx });+ (next: UIChatMessage[], ctx: ConversationContext, meta?: MessagesChangeMeta) => {+ replaceMessages(next, { context: ctx, source: meta?.source });},[replaceMessages],);diff --git a/src/features/PageEditor/PageAgentProvider.tsx b/src/features/PageEditor/PageAgentProvider.tsxindex 53e7a8111f5..2c08591a177 100644--- a/src/features/PageEditor/PageAgentProvider.tsx+++ b/src/features/PageEditor/PageAgentProvider.tsx@@ -110,8 +110,8 @@ export const PageAgentProvider = memo<PageAgentProviderProps>(hasInitMessages={!!messages}messages={messages}operationState={operationState}- onMessagesChange={(msgs, ctx) => {- replaceMessages(msgs, { context: ctx });+ onMessagesChange={(msgs, ctx, meta) => {+ replaceMessages(msgs, { context: ctx, source: meta?.source });}}>{children}diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsxindex f85b536fc2f..b35b53b9679 100644--- a/src/features/Portal/Thread/Chat/index.tsx+++ b/src/features/Portal/Thread/Chat/index.tsx@@ -238,8 +238,8 @@ const ThreadChat = memo(() => {messages={messages}operationState={operationState}skipFetch={isCreatingNewThread}- onMessagesChange={(msgs, ctx) => {- replaceMessages(msgs, { context: ctx });+ onMessagesChange={(msgs, ctx, meta) => {+ replaceMessages(msgs, { context: ctx, source: meta?.source });}}><ThreadChatContent isSubagentThread={isSubagentThread} />diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsxindex e27fffcce43..e3b66e5fd21 100644--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx@@ -124,8 +124,8 @@ const Conversation = memo(() => {hooks={hooks}messages={messages}operationState={operationState}- onMessagesChange={(messages, ctx) => {- replaceMessages(messages, { context: ctx });+ onMessagesChange={(messages, ctx, meta) => {+ replaceMessages(messages, { context: ctx, source: meta?.source });}}><Flexboxdiff --git a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx b/src/routes/(main)/group/features/Conversation/ConversationArea.tsxindex 9fd6cb8984e..e0bae4e78c1 100644--- a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/group/features/Conversation/ConversationArea.tsx@@ -55,8 +55,8 @@ const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {hasInitMessages={!!messages}messages={messages}operationState={operationState}- onMessagesChange={(messages, ctx) => {- replaceMessages(messages, { context: ctx });+ onMessagesChange={(messages, ctx, meta) => {+ replaceMessages(messages, { context: ctx, source: meta?.source });}}><Flexboxdiff --git a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsxindex d6584747813..0669319a342 100644--- a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx+++ b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx@@ -50,8 +50,8 @@ const AgentBuilderProvider = memo<AgentBuilderProviderProps>(({ agentId, childrehasInitMessages={!!messages}messages={messages}operationState={operationState}- onMessagesChange={(msgs, ctx) => {- replaceMessages(msgs, { context: ctx });+ onMessagesChange={(msgs, ctx, meta) => {+ replaceMessages(msgs, { context: ctx, source: meta?.source });}}>{children}diff --git a/src/routes/share/t/[id]/SharedMessageList.tsx b/src/routes/share/t/[id]/SharedMessageList.tsxindex 16e8169f25f..52d1ba8e521 100644--- a/src/routes/share/t/[id]/SharedMessageList.tsx+++ b/src/routes/share/t/[id]/SharedMessageList.tsx@@ -44,8 +44,8 @@ const SharedMessageList = memo<SharedMessageListProps>((props) => {context={context}hasInitMessages={!!messages}messages={messages}- onMessagesChange={(messages, ctx) => {- replaceMessages(messages, { context: ctx });+ onMessagesChange={(messages, ctx, meta) => {+ replaceMessages(messages, { context: ctx, source: meta?.source });}}><ChatListdiff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.tsindex 6fd29d92998..7816f6eb98d 100644--- a/src/store/chat/slices/message/action.test.ts+++ b/src/store/chat/slices/message/action.test.ts@@ -1398,6 +1398,25 @@ describe('chatMessage actions', () => {expect(mutate).not.toHaveBeenCalled();});+ 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());++ 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',+ });+ });++ expect(mutate).not.toHaveBeenCalled();+ });+it('skips write-through while the context is streaming', async () => {const { result } = renderHook(() => useChatStore());@@ -1656,6 +1675,56 @@ describe('chatMessage actions', () => {expect(messageService.getMessages).toHaveBeenCalledTimes(1);await expect(mountedQuery).resolves.toEqual(messages);});++ it('drops a prefetch result that resolves after the context started running', async () => {+ // Regression: the running guard only ran when the prefetch STARTED. If the+ // user opened that topic and submitted a follow-up before the request+ // resolved, the pre-run server snapshot overwrote the freshly created+ // user/assistant rows; subsequent streaming updates target ids that are no+ // longer in the bucket and are silently dropped until terminal+ // reconciliation. Mirrors the delivery-time guard `useFetchMessages`+ // onData already applies.+ const { result } = renderHook(() => useChatStore());++ const context = {+ agentId: 'prefetch-agent',+ scope: 'main' as const,+ topicId: 'raced-topic',+ };+ const key = messageMapKey(context);+ const preRunSnapshot = [{ id: 'old-message', role: 'user', content: 'hi' }] as any;+ const liveMessages = [+ ...preRunSnapshot,+ { id: 'new-user-message', role: 'user', content: 'follow-up' },+ { id: 'new-assistant-message', role: 'assistant', content: '' },+ ] as any;++ let resolveRequest!: (value: UIChatMessage[]) => void;+ (messageService.getMessages as Mock).mockReturnValue(+ new Promise<UIChatMessage[]>((resolve) => {+ resolveRequest = resolve;+ }),+ );++ const prefetchPromise = result.current.prefetchMessages(context);+ await Promise.resolve();+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);++ // While the request is in flight: the user opens the topic and sends a+ // follow-up β optimistic rows land in the bucket and a run starts.+ await act(async () => {+ useChatStore.setState({ dbMessagesMap: { [key]: liveMessages } });+ result.current.startOperation({ type: 'execAgentRuntime', context });+ });++ await act(async () => {+ resolveRequest(preRunSnapshot);+ await prefetchPromise;+ });++ // The stale pre-run snapshot must not clobber the in-flight conversation.+ expect(result.current.dbMessagesMap[key]).toEqual(liveMessages);+ });});describe('Public API with context parameter', () => {diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 07ee7f9b400..50b7c6133d5 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -87,7 +87,15 @@ export class MessageQueryActionImpl {prefetchingMessageKeys.add(messagesKey);const request = runMessageListQuery(context, messageService.getMessages).then((messages) => {- this.#get().replaceMessages(messages, { action: 'prefetchMessages', context });+ // 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;});@@ -119,6 +127,16 @@ 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;@@ -189,7 +207,12 @@ export class MessageQueryActionImpl {// 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.- this.#writeThroughMessageCache(ctx, messagesKey, reconciled, params?.action);+ // 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).+ if (params?.source !== 'fetch') {+ this.#writeThroughMessageCache(ctx, messagesKey, reconciled, params?.action);+ }if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 3630202f409..c37cf793900 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -585,6 +585,133 @@ describe('topic action', () => {).toEqual(topics);});+ describe('unread message prefetch', () => {+ // Regression: unread prefetch used to live only in the sidebar item's+ // mount effect, so topics in collapsed groups / outside the virtualized+ // viewport were never warmed β first click rendered the creation-time+ // seed (first message only) until the switch revalidation landed.++ it('prefetches messages for topics that flip to unread in a refetch', async () => {+ const agentId = 'unread-flip-agent';+ const prefetchMessages = vi.fn();+ act(() => {+ useChatStore.setState({+ prefetchMessages,+ topicDataMap: {+ [topicMapKey({ agentId })]: {+ currentPage: 0,+ hasMore: false,+ isInbox: false,+ items: [{ id: 'tpc-flip', status: 'running', title: 'Running' }] as ChatTopic[],+ pageSize: 20,+ total: 1,+ },+ },+ });+ });+ (topicService.getTopics as Mock).mockResolvedValue({+ items: [{ id: 'tpc-flip', status: 'unread', title: 'Done' }],+ total: 1,+ });++ renderHook(() => useChatStore().useFetchTopics(true, { agentId }));++ await waitFor(() => {+ expect(prefetchMessages).toHaveBeenCalledWith({+ agentId,+ scope: 'main',+ topicId: 'tpc-flip',+ });+ });+ });++ it('sweeps already-unread topics on the first list load (app-closed runs)', async () => {+ const agentId = 'unread-boot-agent';+ const prefetchMessages = vi.fn();+ act(() => {+ useChatStore.setState({ prefetchMessages });+ });+ (topicService.getTopics as Mock).mockResolvedValue({+ items: [+ { id: 'tpc-a', status: 'unread', title: 'A' },+ { id: 'tpc-b', status: null, title: 'B' },+ { id: 'tpc-c', status: 'unread', title: 'C' },+ ],+ total: 3,+ });++ renderHook(() => useChatStore().useFetchTopics(true, { agentId }));++ await waitFor(() => {+ expect(prefetchMessages).toHaveBeenCalledTimes(2);+ });+ expect(prefetchMessages).toHaveBeenCalledWith({ agentId, scope: 'main', topicId: 'tpc-a' });+ expect(prefetchMessages).toHaveBeenCalledWith({ agentId, scope: 'main', topicId: 'tpc-c' });+ });++ it('does not re-prefetch topics that were already unread, and caps the fan-out', async () => {+ const agentId = 'unread-cap-agent';+ const prefetchMessages = vi.fn();+ const alreadyUnread = { id: 'tpc-old', status: 'unread', title: 'Old' } as ChatTopic;+ act(() => {+ useChatStore.setState({+ prefetchMessages,+ topicDataMap: {+ [topicMapKey({ agentId })]: {+ currentPage: 0,+ hasMore: false,+ isInbox: false,+ items: [alreadyUnread],+ pageSize: 20,+ total: 1,+ },+ },+ });+ });+ // 1 already-unread + 7 fresh flips β only 5 (the cap) prefetch, none for tpc-old+ (topicService.getTopics as Mock).mockResolvedValue({+ items: [+ alreadyUnread,+ ...Array.from({ length: 7 }, (_, index) => ({+ id: `tpc-new-${index}`,+ status: 'unread',+ title: `New ${index}`,+ })),+ ],+ total: 8,+ });++ renderHook(() => useChatStore().useFetchTopics(true, { agentId }));++ await waitFor(() => {+ expect(prefetchMessages).toHaveBeenCalledTimes(5);+ });+ expect(prefetchMessages).not.toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'tpc-old' }),+ );+ });++ it('skips group topic lists (message buckets are not representable)', async () => {+ const prefetchMessages = vi.fn();+ act(() => {+ useChatStore.setState({ prefetchMessages });+ });+ (topicService.getTopics as Mock).mockResolvedValue({+ items: [{ id: 'tpc-group', status: 'unread', title: 'G' }],+ total: 1,+ });++ renderHook(() => useChatStore().useFetchTopics(true, { groupId: 'grp-1' }));++ await waitFor(() => {+ expect(+ useChatStore.getState().topicDataMap[topicMapKey({ groupId: 'grp-1' })]?.items,+ ).toBeDefined();+ });+ expect(prefetchMessages).not.toHaveBeenCalled();+ });+ });+it('should preserve expanded topic list when first page revalidates after deletion', async () => {const agentId = 'expanded-delete-agent';const pageSize = 20;diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 69d9bcc9335..86af390e906 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -58,6 +58,13 @@ const n = setNamespace('t');const STALE_RUNNING_TOPIC_TIMEOUT = 2 * 60 * 60 * 1000;const STALE_RUNNING_TOPIC_QUERY_PAGE_SIZE = 500;+/**+ * Max message prefetches fired per topic-list fetch for freshly-unread topics.+ * Bounds the fan-out after a long-offline boot; see+ * `#prefetchUnreadTopicMessages`.+ */+const UNREAD_TOPIC_PREFETCH_LIMIT = 5;+type CronTopicsGroupWithJobInfo = {cronJob: unknown;cronJobId: string;@@ -460,6 +467,50 @@ export class ChatTopicActionImpl {return next;};+ /**+ * Warm the message cache for topics whose status just flipped to `unread` in+ * a fetched topic list β i.e. runs that completed remotely / on another+ * device / while the app was closed. Their local message bucket typically+ * holds only the creation-time seed (the first user message), so without a+ * prefetch the first click renders that partial list until the switch-time+ * revalidation lands.+ *+ * Store-level on purpose: the sidebar item's own unread-prefetch effect only+ * fires while that item is MOUNTED, which misses collapsed groups and rows+ * outside the virtualized viewport. Locally-run topics don't need this path β+ * streaming already filled their bucket, and `prefetchMessages`' running+ * guard skips them while the terminal bookkeeping is still in flight.+ *+ * Capped so a boot after days offline doesn't fan out a request storm; the+ * uncapped remainder still self-heals on click via the switch revalidation.+ * `prefetchMessages` itself dedupes concurrent calls and skips+ * server-verified or running contexts, so repeated onData fires are cheap.+ */+ #prefetchUnreadTopicMessages = (+ fetchedTopics: ChatTopic[],+ previousItems: ChatTopic[] | undefined,+ context: { agentId?: string | null; groupId?: string | null },+ ): void => {+ // Message buckets for group scopes key on more than agentId/topicId; the+ // canonical message:list prefetch only represents plain agent topics.+ if (!context.agentId || context.groupId) return;++ const previousStatus = new Map(previousItems?.map((item) => [item.id, item.status]) ?? []);+ // First load (no previous items) sweeps every unread topic β those runs+ // finished while the app was closed and nothing else will warm them.+ const flipped = fetchedTopics.filter(+ (item) => item.status === 'unread' && previousStatus.get(item.id) !== 'unread',+ );++ for (const topic of flipped.slice(0, UNREAD_TOPIC_PREFETCH_LIMIT)) {+ void this.#get().prefetchMessages({+ agentId: context.agentId,+ scope: 'main',+ topicId: topic.id,+ });+ }+ };+/*** Persist the topic's status. Optimistically patches the in-memory map so* the sidebar reflects the change immediately; persistence runs@@ -818,6 +869,11 @@ export class ChatTopicActionImpl {const currentData = this.#get().topicDataMap[containerKey];const topics = this.#reconcileFetchedTopics(result.items, currentData?.items);+ // Fire BEFORE the no-change early return below: on a cold boot the+ // cached list arrives with no `currentData`, and that first delivery+ // is exactly the sweep that must warm app-closed-while-running runs.+ this.#prefetchUnreadTopicMessages(topics, currentData?.items, { agentId, groupId });+const isRefreshingExpandedList =!!currentData &¤tData.currentPage > 0 &&