Skip to content

🤯 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.

⚡️ perf(chat): prefetch unread completed topic messages (#16831)

Arvin Xu5e8e469dc7c5
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
index 547b9ac598e..a1a454cf3b3 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
@@ -1,14 +1,17 @@
/**
* @vitest-environment happy-dom
*/
-import { render, screen } from '@testing-library/react';
+import { render, screen, waitFor } from '@testing-library/react';
import type { CSSProperties, ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import TopicItem from './index';
const useTopicNavigationMock = vi.hoisted(() => vi.fn());
+const prefetchMessagesMock = vi.hoisted(() => vi.fn());
+const agentRuntimeRunningMock = vi.hoisted(() => ({ value: false }));
const runningStartTimeMock = vi.hoisted(() => ({ value: undefined as number | undefined }));
+const topicUnreadCompletedMock = vi.hoisted(() => ({ value: false }));
vi.mock('@lobehub/ui', () => ({
Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
@@ -98,16 +101,21 @@ vi.mock('@/store/agent', () => ({
}));
vi.mock('@/store/chat', () => ({
useChatStore: (
- selector: (state: { topicLoadingIds: string[]; topicRenamingId: string }) => unknown,
- ) => selector({ topicLoadingIds: [], topicRenamingId: '' }),
+ selector: (state: {
+ prefetchMessages: typeof prefetchMessagesMock;
+ topicLoadingIds: string[];
+ topicRenamingId: string;
+ }) => unknown,
+ ) =>
+ selector({ prefetchMessages: prefetchMessagesMock, topicLoadingIds: [], topicRenamingId: '' }),
}));
vi.mock('@/store/chat/selectors', () => ({
operationSelectors: {
getAgentRuntimeStartTimeByContext: () => () => runningStartTimeMock.value,
getVisibleAgentRuntimeStartTimeByContext: () => () => runningStartTimeMock.value,
- isAgentRuntimeRunningByContext: () => () => false,
+ isAgentRuntimeRunningByContext: () => () => agentRuntimeRunningMock.value,
isAgentRuntimeVisiblyRunningByContext: () => () => false,
- isTopicUnreadCompleted: () => () => false,
+ isTopicUnreadCompleted: () => () => topicUnreadCompletedMock.value,
},
}));
vi.mock('@/store/electron', () => ({
@@ -143,7 +151,10 @@ vi.mock('../../TopicListContent/ThreadList', () => ({
describe('TopicItem active state', () => {
afterEach(() => {
+ prefetchMessagesMock.mockClear();
+ agentRuntimeRunningMock.value = false;
runningStartTimeMock.value = undefined;
+ topicUnreadCompletedMock.value = false;
vi.useRealTimers();
});
@@ -209,6 +220,52 @@ describe('TopicItem active state', () => {
expect(screen.getByText('00:33')).toBeInTheDocument();
});
+ it('prefetches messages when a topic is an unread completion', async () => {
+ topicUnreadCompletedMock.value = true;
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+
+ render(<TopicItem id="tpc_test" title="Topic" />);
+
+ await waitFor(() => {
+ expect(prefetchMessagesMock).toHaveBeenCalledWith({
+ agentId: 'agt_test',
+ scope: 'main',
+ topicId: 'tpc_test',
+ });
+ });
+ });
+
+ it('prefetches unread completed messages after the runtime stops', async () => {
+ agentRuntimeRunningMock.value = true;
+ topicUnreadCompletedMock.value = true;
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+
+ const { rerender } = render(<TopicItem id="tpc_test" title="Topic" />);
+
+ expect(prefetchMessagesMock).not.toHaveBeenCalled();
+
+ agentRuntimeRunningMock.value = false;
+ rerender(<TopicItem id="tpc_test" title="Topic done" />);
+
+ await waitFor(() => {
+ expect(prefetchMessagesMock).toHaveBeenCalledWith({
+ agentId: 'agt_test',
+ scope: 'main',
+ topicId: 'tpc_test',
+ });
+ });
+ });
+
it('shows the topic worktree and branch from structured metadata', () => {
useTopicNavigationMock.mockReturnValue({
isInAgentSubRoute: false,
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
index ab97215f1ab..c992040f682 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -198,6 +198,7 @@ const TopicItem = memo<TopicItemProps>(
// topic semantics, so skip the default `#` placeholder icon for their rows.
const isHeterogeneousAgent = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const addTab = useElectronStore((s) => s.addTab);
+ const prefetchMessages = useChatStore((s) => s.prefetchMessages);
const loadingRingColor = isDarkMode
? cssVar.colorWarningBorder
@@ -322,6 +323,12 @@ const TopicItem = memo<TopicItemProps>(
</span>
);
+ useEffect(() => {
+ if (!activeAgentId || !id || !isUnreadCompleted || hasLocalRunningRuntime) return;
+
+ void prefetchMessages({ agentId: activeAgentId, scope: 'main', topicId: id });
+ }, [activeAgentId, hasLocalRunningRuntime, id, isUnreadCompleted, prefetchMessages]);
+
// Surface a WeChat-style red "[Draft]" hint when this topic holds unsent
// input. Drafts live in localStorage keyed by messageMapKey; the default
// topic (no id) maps to the new-topic draft. `useHasDraft` re-renders the
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index 87458b54984..f0e1d06a2f0 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -1348,6 +1348,101 @@ describe('chatMessage actions', () => {
});
});
+ describe('prefetchMessages action', () => {
+ beforeEach(() => {
+ (mutate as Mock).mockClear();
+ useChatStore.setState({ dbMessagesMap: {}, messagesMap: {} });
+ });
+
+ it('fetches messages in the background and hydrates the message cache', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const context = {
+ agentId: 'prefetch-agent',
+ scope: 'main' as const,
+ topicId: 'prefetch-topic',
+ };
+ const messages = [{ id: 'prefetch-message', role: 'user', content: 'hi' }] as any;
+
+ (messageService.getMessages as Mock).mockResolvedValue(messages);
+
+ await act(async () => {
+ await result.current.prefetchMessages(context);
+ });
+
+ const key = messageMapKey(context);
+ expect(messageService.getMessages).toHaveBeenCalledWith(context);
+ expect(result.current.dbMessagesMap[key]).toEqual(messages);
+ expect(result.current.messagesMap[key]).toHaveLength(1);
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ const [swrKey, dataArg, options] = (mutate as Mock).mock.calls[0];
+ expect(swrKey).toEqual(['message:list', context, 1]);
+ await expect(dataArg).resolves.toEqual(messages);
+ expect(options).toEqual({ revalidate: false });
+ });
+
+ it('refreshes an already hydrated bucket with the completed server snapshot', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const context = {
+ agentId: 'prefetch-agent',
+ scope: 'main' as const,
+ topicId: 'cached-topic',
+ };
+ const key = messageMapKey(context);
+ const serverMessages = [{ id: 'server-message', role: 'assistant', content: 'done' }] as any;
+
+ act(() => {
+ useChatStore.setState({
+ dbMessagesMap: {
+ [key]: [{ id: 'cached-message', role: 'user', content: 'hi' }] as any,
+ },
+ });
+ });
+ (messageService.getMessages as Mock).mockResolvedValue(serverMessages);
+
+ await act(async () => {
+ await result.current.prefetchMessages(context);
+ });
+
+ expect(messageService.getMessages).toHaveBeenCalledWith(context);
+ expect(result.current.dbMessagesMap[key]).toEqual(serverMessages);
+ expect(mutate).toHaveBeenCalledTimes(1);
+ });
+
+ it('dedupes simultaneous prefetches for the same message bucket', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const context = {
+ agentId: 'prefetch-agent',
+ scope: 'main' as const,
+ topicId: 'dedupe-topic',
+ };
+ const messages = [{ id: 'deduped-message', role: 'user', content: 'hi' }] as any;
+ let resolveRequest!: (value: unknown) => void;
+
+ (messageService.getMessages as Mock).mockReturnValue(
+ new Promise((resolve) => {
+ resolveRequest = resolve;
+ }),
+ );
+
+ const firstPrefetch = result.current.prefetchMessages(context);
+ const secondPrefetch = result.current.prefetchMessages(context);
+
+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveRequest(messages);
+ await firstPrefetch;
+ await secondPrefetch;
+ });
+
+ expect(result.current.dbMessagesMap[messageMapKey(context)]).toEqual(messages);
+ });
+ });
+
describe('Public API with context parameter', () => {
describe('deleteMessage with context', () => {
it('should pass context to optimisticDeleteMessages', async () => {
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 375534ce4c3..64cf04eeef0 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -36,6 +36,7 @@ import { reconcileAssistantToolLinks } from '../utils/reconcileTools';
* conversation keeps its live gateway stream regardless of this window.
*/
const MESSAGE_LIST_DEDUPING_INTERVAL = 30 * 1000;
+const prefetchingMessageKeys = new Set<string>();
type Setter = StoreSetter<ChatStore>;
export const messageQuery = (set: Setter, get: () => ChatStore, _api?: unknown) =>
@@ -64,6 +65,30 @@ export class MessageQueryActionImpl {
});
};
+ prefetchMessages = async (context: ConversationContext): Promise<void> => {
+ if (!context.agentId || !context.topicId) return;
+
+ const messagesKey = messageMapKey(context);
+ if (operationSelectors.isAgentRuntimeRunningByContext(context)(this.#get())) return;
+ if (prefetchingMessageKeys.has(messagesKey)) return;
+
+ prefetchingMessageKeys.add(messagesKey);
+
+ const request = messageService.getMessages(context).then((messages) => {
+ this.#get().replaceMessages(messages, { action: 'prefetchMessages', context });
+ return messages;
+ });
+
+ try {
+ await mutate(messageKeys.list(context), request, { revalidate: false });
+ await request;
+ } catch {
+ // Background warming should never surface an unhandled rejection.
+ } finally {
+ prefetchingMessageKeys.delete(messagesKey);
+ }
+ };
+
replaceMessages = (
messages: UIChatMessage[],
params?: {
@@ -159,9 +184,11 @@ export class MessageQueryActionImpl {
* because an optimistic dispatch may have already applied this exact state to
* the store while leaving the cache stale.
*
- * Skipped in two cases:
+ * Skipped in three cases:
* - `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
@@ -173,7 +200,7 @@ export class MessageQueryActionImpl {
messages: UIChatMessage[],
action?: string,
): void => {
- if (action === 'useFetchMessages') return;
+ if (action === 'useFetchMessages' || action === 'prefetchMessages') return;
if (operationSelectors.isAgentRuntimeRunningByContext(ctx)(this.#get())) return;
// Match every `message:list` entry whose context resolves to the same bucket