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.

βͺ️ revert(topic): batch-prefetch transcripts of visible topic rows (#21706)

Neko39104318dac5
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 2c63084f6db..9aa2b283b41 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -42,7 +42,6 @@ import {
assertCreatorTopicTargets,
} from './_helpers/shareVisitorTargetGuard';
import { basicContextSchema } from './_schema/context';
-import { messageBatchProcedures } from './messageBatch';
const { logTiming, runTimedStage } = createTimingHelpers('lobe-server:chat:lobehub:timing');
@@ -565,7 +564,6 @@ export const messageRouter = router({
.input(messagesByCursorInputSchema)
.query(({ ctx, input }) => readMessagesByCursor(ctx, input)),
- ...messageBatchProcedures,
rankModels: messageProcedure.query(async ({ ctx }) => {
return ctx.messageModel.rankModels();
}),
diff --git a/apps/server/src/routers/lambda/messageBatch.ts b/apps/server/src/routers/lambda/messageBatch.ts
deleted file mode 100644
index 003a1e4e2d3..00000000000
--- a/apps/server/src/routers/lambda/messageBatch.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { z } from 'zod';
-
-import { cloudWorkspaceAuth } from '@/business/server/trpc-middlewares/workspaceAuth';
-import { publicProcedure } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-
-import { messagesByCursorInputSchema, readMessagesByCursor } from './_helpers/messagesByCursor';
-
-/**
- * Upper bound on topics per batch read. The batch exists so a sidebar can warm
- * its visible rows with ONE round trip; the cap keeps that request from turning
- * into a fan-out over an arbitrarily long list.
- */
-const MAX_BATCH_TOPIC_COUNT = 8;
-
-const batchItemSchema = messagesByCursorInputSchema
- .pick({ agentId: true, groupId: true })
- .extend({ topicId: z.string().min(1) });
-
-/**
- * Procedures shared by `messageRouter`, split out to keep the router file within
- * its size budget. Registered flat (`message.getMessagesByCursorBatch`).
- */
-export const messageBatchProcedures = {
- /**
- * Batch form of `getMessagesByCursor`, for prefetching a sidebar's visible
- * topic rows.
- *
- * Every item goes through the same `readMessagesByCursor` path as the single
- * read, so guards, context resolution and projection behave identically; only
- * the round trip is shared. One item failing fails the call, which the client
- * treats as "prefetch failed" and re-reads per topic.
- *
- * Backward-only and newest-page-only on purpose: this is a warm-up read, and
- * a caller that needs another cursor can ask for that topic directly.
- */
- getMessagesByCursorBatch: publicProcedure
- .use(cloudWorkspaceAuth)
- .use(serverDatabase)
- .input(
- messagesByCursorInputSchema
- .pick({
- countBudget: true,
- includeFileWorks: true,
- projectToolPayloads: true,
- roundLimit: true,
- skipWorks: true,
- })
- .extend({
- items: z.array(batchItemSchema).min(1).max(MAX_BATCH_TOPIC_COUNT),
- }),
- )
- .query(async ({ ctx, input }) => {
- const { items, ...shared } = input;
-
- // Bounded by the input cap above; a handful of small per-topic reads run
- // in parallel so the client still sees one round trip.
- return Promise.all(
- items.map(async (item) => {
- const page = await readMessagesByCursor(
- { serverDB: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
- {
- ...shared,
- agentId: item.agentId,
- direction: 'backward',
- groupId: item.groupId,
- topicId: item.topicId,
- },
- );
-
- return { ...page, topicId: item.topicId };
- }),
- );
- }),
-};
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index fcf25d4b6f6..7b40484c30a 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -52,7 +52,6 @@ import { userProfileSelectors } from '@/store/user/selectors';
import { markSidebarTopicActivation } from '../../hooks/useScrollActiveTopicIntoView';
import { useTopicNavigation } from '../../hooks/useTopicNavigation';
-import { useVisibleTopicPrefetch } from '../../hooks/useVisibleTopicPrefetch';
import ThreadList from '../../TopicListContent/ThreadList';
import { useTopicListScope } from '../../TopicListScope';
import { useScopedTopic } from '../../useScopedTopics';
@@ -268,9 +267,6 @@ const TopicItemRow = memo<TopicItemRowProps>(
suppressAgentAvatar,
}) => {
const scopedTopic = useScopedTopic(id);
- // Warm this row's transcript as soon as it is on screen, so clicking it is
- // a cache hit instead of a visible load.
- const prefetchRef = useVisibleTopicPrefetch(id);
const scope = useTopicListScope();
const inboxId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const { t } = useTranslation('topic');
@@ -640,12 +636,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
);
return (
- <Flexbox
- data-testid="topic-item"
- data-topic-id={id}
- ref={prefetchRef}
- style={{ position: 'relative' }}
- >
+ <Flexbox data-testid="topic-item" data-topic-id={id} style={{ position: 'relative' }}>
{metaCard ? (
<Popover
arrow={false}
diff --git a/src/features/AgentSidebar/Topic/hooks/useVisibleTopicPrefetch.test.tsx b/src/features/AgentSidebar/Topic/hooks/useVisibleTopicPrefetch.test.tsx
deleted file mode 100644
index f284c965b8a..00000000000
--- a/src/features/AgentSidebar/Topic/hooks/useVisibleTopicPrefetch.test.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import { act, render } from '@testing-library/react';
-import { createElement } from 'react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { resetVisibleTopicPrefetchQueue, useVisibleTopicPrefetch } from './useVisibleTopicPrefetch';
-
-const mocks = vi.hoisted(() => ({
- getState: vi.fn(),
- prefetchTopicMessagesBatch: vi.fn(() => Promise.resolve()),
-}));
-
-vi.mock('@/store/chat', () => ({
- useChatStore: { getState: () => mocks.getState() },
-}));
-
-const Row = ({ topicId }: { topicId?: string }) => {
- const ref = useVisibleTopicPrefetch(topicId);
- return createElement('div', { 'data-testid': 'row', ref });
-};
-
-let callbacks: IntersectionObserverCallback[] = [];
-const disconnect = vi.fn();
-
-const flushQueue = async () => {
- await act(async () => {
- await vi.advanceTimersByTimeAsync(200);
- });
-};
-
-const intersect = async (index: number, isIntersecting = true) => {
- await act(async () => {
- callbacks[index]?.(
- [{ isIntersecting } as IntersectionObserverEntry],
- {} as IntersectionObserver,
- );
- });
-};
-
-describe('useVisibleTopicPrefetch', () => {
- beforeEach(() => {
- callbacks = [];
- disconnect.mockClear();
- vi.useFakeTimers();
- vi.stubGlobal(
- 'IntersectionObserver',
- class {
- constructor(callback: IntersectionObserverCallback) {
- callbacks.push(callback);
- }
-
- disconnect = disconnect;
- observe = vi.fn();
- takeRecords = () => [];
- unobserve = vi.fn();
- },
- );
- mocks.getState.mockReturnValue({
- activeAgentId: 'agent-1',
- activeGroupId: null,
- prefetchTopicMessagesBatch: mocks.prefetchTopicMessagesBatch,
- });
- mocks.prefetchTopicMessagesBatch.mockClear();
- resetVisibleTopicPrefetchQueue();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- vi.unstubAllGlobals();
- });
-
- it('coalesces the rows visible in one paint into a single batch call', async () => {
- render(
- <>
- <Row topicId="topic-a" />
- <Row topicId="topic-b" />
- </>,
- );
-
- await intersect(0);
- await intersect(1);
- await flushQueue();
-
- expect(mocks.prefetchTopicMessagesBatch).toHaveBeenCalledTimes(1);
- expect(mocks.prefetchTopicMessagesBatch).toHaveBeenCalledWith({
- agentId: 'agent-1',
- groupId: null,
- topicIds: ['topic-a', 'topic-b'],
- });
- });
-
- it('stops observing a row once it has been queued', async () => {
- render(<Row topicId="topic-c" />);
-
- await intersect(0);
-
- expect(disconnect).toHaveBeenCalled();
- });
-
- it('ignores rows that never enter the viewport', async () => {
- render(<Row topicId="topic-d" />);
-
- await intersect(0, false);
- await flushQueue();
-
- expect(mocks.prefetchTopicMessagesBatch).not.toHaveBeenCalled();
- });
-
- it('does not observe the default (id-less) topic row', () => {
- render(<Row />);
-
- expect(callbacks).toHaveLength(0);
- });
-});
diff --git a/src/features/AgentSidebar/Topic/hooks/useVisibleTopicPrefetch.ts b/src/features/AgentSidebar/Topic/hooks/useVisibleTopicPrefetch.ts
deleted file mode 100644
index 8174675571c..00000000000
--- a/src/features/AgentSidebar/Topic/hooks/useVisibleTopicPrefetch.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-'use client';
-
-import { useEffect, useRef } from 'react';
-
-import { useChatStore } from '@/store/chat';
-
-/**
- * Coalescing window between "a row became visible" and the prefetch. Rows paint
- * in bursts (initial mount, scrolling a group open, switching agents), so
- * waiting one frame-ish lets a whole screenful become a single batch call
- * instead of one call per row.
- */
-const FLUSH_DELAY = 150;
-
-const pendingTopicIds = new Set<string>();
-let flushTimer: ReturnType<typeof setTimeout> | undefined;
-
-const flush = () => {
- flushTimer = undefined;
- if (pendingTopicIds.size === 0) return;
-
- const topicIds = [...pendingTopicIds];
- pendingTopicIds.clear();
-
- const { activeAgentId, activeGroupId, prefetchTopicMessagesBatch } = useChatStore.getState();
- void prefetchTopicMessagesBatch({ agentId: activeAgentId, groupId: activeGroupId, topicIds });
-};
-
-const enqueue = (topicId: string) => {
- if (pendingTopicIds.has(topicId)) return;
-
- pendingTopicIds.add(topicId);
- flushTimer ??= setTimeout(flush, FLUSH_DELAY);
-};
-
-/** Drop a queued flush β€” test seam; the queue is module-level by design. */
-export const resetVisibleTopicPrefetchQueue = () => {
- pendingTopicIds.clear();
- if (flushTimer !== undefined) clearTimeout(flushTimer);
- flushTimer = undefined;
-};
-
-/**
- * Prefetch a topic's transcript once its row is visible, and stop watching it
- * afterwards.
- *
- * The row registers itself rather than the list walking its children: the same
- * component renders inside the flat / by-time / by-project / by-status
- * groupings and the group sidebar, so one call site covers every mode. The
- * observer uses the viewport as its root (the sidebar is the scroller) and a
- * `rootMargin` so the read starts just before the row is actually on screen.
- *
- * "Is it already local?" is deliberately NOT answered here β€” the store action
- * owns that check, together with the batch cap and the per-topic eligibility
- * rules (client-minted, running, already loaded).
- */
-export const useVisibleTopicPrefetch = <T extends HTMLElement = HTMLDivElement>(
- topicId?: string | null,
-) => {
- const ref = useRef<T>(null);
-
- useEffect(() => {
- const element = ref.current;
- if (!element || !topicId) return;
-
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (!entry?.isIntersecting) return;
-
- enqueue(topicId);
- // One warm-up per mount is enough; a later re-entry finds the rows
- // already in the store.
- observer.disconnect();
- },
- { rootMargin: '200px' },
- );
-
- observer.observe(element);
- return () => observer.disconnect();
- }, [topicId]);
-
- return ref;
-};
diff --git a/src/services/message/roundCursorPage.test.ts b/src/services/message/roundCursorPage.test.ts
index 725577be7c8..670cdf2afab 100644
--- a/src/services/message/roundCursorPage.test.ts
+++ b/src/services/message/roundCursorPage.test.ts
@@ -5,10 +5,8 @@ import { lambdaClient } from '@/libs/trpc/client';
import { MessageService } from './index';
import {
ForwardPagingUnsupportedError,
- isPartialHeadWindow,
primeMessageListPage,
readMessagesForward,
- releaseUnusedPrimedMessageListPage,
SHARED_TOPIC_FIRST_PAGE,
} from './roundCursorPage';
@@ -87,70 +85,6 @@ describe('primeMessageListPage', () => {
expect(result).toEqual({ messages: [{ id: 'group' }], olderCursor: null });
});
- it('drops a page no read took, so a later read goes to the server', async () => {
- query.mockResolvedValueOnce(page('fresh'));
- const context = nextContext();
- const orphaned = listPage('orphaned');
-
- primeMessageListPage(context, orphaned);
- // The head read joined an already in-flight query, so it never took the page.
- releaseUnusedPrimedMessageListPage(context, orphaned);
-
- const result = await service.getMessageListPage(context);
-
- expect(query).toHaveBeenCalledTimes(1);
- expect(result).toEqual({ messages: [{ id: 'fresh' }], olderCursor: null });
- });
-
- it('keeps a page another caller primed for the same conversation', async () => {
- const context = nextContext();
- const replacement = listPage('replacement');
-
- primeMessageListPage(context, listPage('first'));
- releaseUnusedPrimedMessageListPage(context, replacement);
-
- expect(await service.getMessageListPage(context)).toEqual({
- messages: [{ id: 'first' }],
- olderCursor: null,
- });
- expect(query).not.toHaveBeenCalled();
- });
-
- it('marks the conversation partial until a normal head read replaces the window', async () => {
- query.mockResolvedValueOnce(page('fresh'));
- const context = nextContext();
-
- expect(isPartialHeadWindow(context)).toBe(false);
- primeMessageListPage(context, listPage('prefetched'));
- await service.getMessageListPage(context);
-
- expect(isPartialHeadWindow(context)).toBe(true);
-
- await service.getMessageListPage(context);
-
- expect(isPartialHeadWindow(context)).toBe(false);
- });
-
- it('keeps the partial marker when the replacing head read fails', async () => {
- const context = nextContext();
-
- primeMessageListPage(context, listPage('prefetched'));
- await service.getMessageListPage(context);
- expect(isPartialHeadWindow(context)).toBe(true);
-
- query.mockRejectedValueOnce(new Error('offline'));
- await expect(service.getMessageListPage(context)).rejects.toThrow('offline');
-
- // The rows on screen are still the prefetch window: a resume must widen.
- expect(isPartialHeadWindow(context)).toBe(true);
-
- query.mockResolvedValueOnce(page('full'));
- await service.getMessageListPage(context);
-
- // Only a head read that actually landed drops the marker.
- expect(isPartialHeadWindow(context)).toBe(false);
- });
-
it('falls back to a fresh read when the primed request failed', async () => {
query.mockResolvedValueOnce(page('retry'));
const context = nextContext();
diff --git a/src/services/message/roundCursorPage.ts b/src/services/message/roundCursorPage.ts
index 394f7da2f7e..4738ca9885d 100644
--- a/src/services/message/roundCursorPage.ts
+++ b/src/services/message/roundCursorPage.ts
@@ -46,47 +46,6 @@ export const toRoundCursorQueryInput = (
topicShareId: params.topicShareId,
});
-/**
- * Per-topic window warmed by a visible-row prefetch. Deliberately a fraction of
- * `MESSAGE_PAGE_ROW_BUDGET`: the budget is multiplied by the number of rows on
- * screen, and a first paint only needs the newest rounds β€” the returned cursor
- * still pages older history on demand.
- */
-export const PREFETCH_PAGE: ForwardPageSize = { countBudget: 120, roundLimit: 10 };
-
-/** Topics per `getMessagesByCursorBatch` request; matches the server-side cap. */
-export const PREFETCH_BATCH_SIZE = 8;
-
-export interface BatchReadItem {
- agentId?: string | null;
- groupId?: string | null;
- topicId: string;
-}
-
-/**
- * Newest pages for several conversations in one request, keyed by topic.
- *
- * Always whole payloads (no tool-payload projection): a primed page is handed
- * to whichever head read arrives first, and a projected payload would lose tool
- * results for a reader that turns the list into LLM context. The prefetch window
- * is smaller than a normal page, so the page a reader takes here is a faster
- * first paint, not a different read contract.
- */
-export const readMessagesByRoundCursorBatch = async (
- items: BatchReadItem[],
-): Promise<Map<string, MessageListPage>> => {
- if (items.length === 0) return new Map();
-
- const pages = await lambdaClient.message.getMessagesByCursorBatch.query({
- countBudget: PREFETCH_PAGE.countBudget,
- includeFileWorks: true,
- items: items.map(({ agentId, groupId, topicId }) => ({ agentId, groupId, topicId })),
- roundLimit: PREFETCH_PAGE.roundLimit,
- });
-
- return new Map(pages.map((page) => [page.topicId, toMessageListPage(page)]));
-};
-
export type RoundCursorQueryResult = Awaited<
ReturnType<typeof lambdaClient.message.getMessagesByCursor.query>
>;
@@ -100,20 +59,11 @@ export const toMessageListPage = (page: RoundCursorQueryResult): MessageListPage
export const readMessagesByRoundCursor = async (
params: RoundCursorReadParams,
cursor: MessageRoundCursor | null,
-): Promise<MessageListPage> => {
- const page = toMessageListPage(
+): Promise<MessageListPage> =>
+ toMessageListPage(
await lambdaClient.message.getMessagesByCursor.query(toRoundCursorQueryInput(params, cursor)),
);
- // The newest page is the head: a normal-budget head read that LANDED replaces
- // any prefetch window the conversation was painting from. Clear the marker
- // only now β€” a pending or failed refresh leaves the prefetch rows in place, so
- // the next resume still has to widen to get full history.
- if (cursor === null) markFullHeadWindow(params);
-
- return page;
-};
-
/** The `getMessagesByCursor` input for one forward page, starting after `cursor`. */
export const toForwardRoundCursorQueryInput = (
params: MessageListQueryContext,
@@ -212,45 +162,11 @@ export const takePrimedMessageListPage = (
): Promise<MessageListPage> | undefined => {
const key = primeKey(context);
const page = primedPages.get(key);
- if (page) {
- primedPages.delete(key);
- // The reader now paints from a prefetch window, not the normal page budget.
- partialHeadWindows.add(key);
- }
+ if (page) primedPages.delete(key);
return page;
};
-/**
- * Drop a page a caller primed when no head read took it. A read that joins an
- * already in-flight query never consumes the prime, and an unclaimed page would
- * otherwise answer a later, unrelated read with an old window: its snapshot can
- * predate server-confirmed rows the head merge then drops.
- */
-export const releaseUnusedPrimedMessageListPage = (
- context: MessageListQueryContext,
- page: Promise<MessageListPage>,
-): void => {
- const key = primeKey(context);
- if (primedPages.get(key) === page) primedPages.delete(key);
-};
-
-/**
- * Conversations whose loaded head is a prefetch window rather than the normal
- * `MESSAGE_PAGE_ROW_BUDGET` page. Enough to paint a row's first screen, but a
- * consumer that turns the loaded rows into model history (a client-runtime
- * resume) needs the normal window first.
- */
-const partialHeadWindows = new Set<string>();
-
-export const isPartialHeadWindow = (context: MessageListQueryContext): boolean =>
- partialHeadWindows.has(primeKey(context));
-
-/** A full-budget head read replaced the prefetch window with the normal one. */
-const markFullHeadWindow = (context: MessageListQueryContext): void => {
- partialHeadWindows.delete(primeKey(context));
-};
-
/** First forward pages handed over by the document, by conversation. */
const primedForwardPages = new Map<string, Promise<ForwardMessagePage>>();
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 6c00a155b73..11f2be5a49e 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -27,7 +27,6 @@ import {
aiAgentService,
type ResolveAgentInterventionBySourceResult,
} from '@/services/aiAgent';
-import { isPartialHeadWindow } from '@/services/message/roundCursorPage';
import { shareChatService } from '@/services/shareChat';
import { getAgentStoreState } from '@/store/agent';
import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
@@ -791,26 +790,6 @@ export class ConversationControlActionImpl {
}
};
- /**
- * Widen a prefetch-sized head window before a client-runtime resume.
- *
- * A topic opened from the visible-row prefetch paints from a smaller page than
- * a normal head read. The local runtime builds the model's history from the
- * loaded rows, so resuming a parked tool inside such a topic would hand the
- * model only the prefetched rounds and silently drop the older context the
- * normal window carries. Reading the normal head first restores it; a failed
- * read only costs context, never the resume itself.
- */
- #widenPrefetchHeadWindow = async (context: ConversationContext): Promise<void> => {
- if (!isPartialHeadWindow(context)) return;
-
- try {
- await this.#get().refreshMessages(context);
- } catch (error) {
- console.warn('[conversationControl] Failed to widen a prefetched head window:', error);
- }
- };
-
approveToolCalling = async (
toolMessageId: string,
_assistantGroupId: string,
@@ -937,10 +916,6 @@ export class ConversationControlActionImpl {
}
// 3. Get current messages for state construction using context
- // The local runtime resumes from the loaded rows as its history: make sure a
- // prefetch-sized window is widened back to the normal head first.
- await this.#widenPrefetchHeadWindow(effectiveContext);
-
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
const currentRequestMetadata = this.#getRequestMetadataFromMessageChain(
@@ -1350,8 +1325,6 @@ export class ConversationControlActionImpl {
// the agent marketplace picker forks agents directly) β€” the LLM should see the
// tool result, not a fake user turn.
if (!shouldCreateUserMessage) {
- await this.#widenPrefetchHeadWindow(effectiveContext);
-
const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
const requestMetadata = this.#getRequestMetadataFromMessageChain(
toolMessageId,
@@ -1405,8 +1378,6 @@ export class ConversationControlActionImpl {
}
// 2b. Default path: create a user message summarizing the response, resume from user
- await this.#widenPrefetchHeadWindow(effectiveContext);
-
const requestMetadata = this.#getRequestMetadataFromMessageChain(toolMessageId);
const userMessageContent = Object.values(resolvedResponse).join(', ');
const groupId = toolMessage.groupId;
diff --git a/src/store/chat/slices/message/action.prefetchTopicBatch.test.ts b/src/store/chat/slices/message/action.prefetchTopicBatch.test.ts
deleted file mode 100644
index e48a9a3ba62..00000000000
--- a/src/store/chat/slices/message/action.prefetchTopicBatch.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { type Mock } from 'vitest';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type * as RoundCursorPage from '@/services/message/roundCursorPage';
-import { readMessagesByRoundCursorBatch } from '@/services/message/roundCursorPage';
-import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-
-import { useChatStore } from '../../store';
-
-vi.mock('@/libs/swr', async () => {
- const actual = await vi.importActual('@/libs/swr');
- return {
- ...actual,
- mutate: vi.fn(),
- useClientDataSWRWithSync: vi.fn(),
- };
-});
-
-// Keep the real priming helpers: the point under test is that the batched page
-// reaches each topic's own head read through them.
-vi.mock('@/services/message/roundCursorPage', async (importOriginal) => {
- const actual = await importOriginal<typeof RoundCursorPage>();
- return { ...actual, readMessagesByRoundCursorBatch: vi.fn() };
-});
-
-const batchRead = readMessagesByRoundCursorBatch as Mock;
-
-describe('prefetchTopicMessagesBatch', () => {
- beforeEach(() => {
- useChatStore.setState({ dbMessagesMap: {}, messagesMap: {} });
- batchRead.mockReset();
- });
-
- it('warms every visible topic from one batched read', async () => {
- const { result } = renderHook(() => useChatStore());
- const topicIds = ['batch-topic-a', 'batch-topic-b'];
-
- batchRead.mockResolvedValue(
- new Map(
- topicIds.map((topicId) => [
- topicId,
- { messages: [{ id: `msg-${topicId}`, role: 'user', content: topicId }] },
- ]),
- ),
- );
-
- await act(async () => {
- await result.current.prefetchTopicMessagesBatch({ agentId: 'batch-agent', topicIds });
- });
-
- expect(batchRead).toHaveBeenCalledTimes(1);
- expect(batchRead.mock.calls[0][0].map((item: { topicId: string }) => item.topicId)).toEqual(
- topicIds,
- );
-
- for (const topicId of topicIds) {
- const key = messageMapKey({ agentId: 'batch-agent', topicId });
- expect(result.current.dbMessagesMap[key]?.map((message) => message.id)).toEqual([
- `msg-${topicId}`,
- ]);
- }
- });
-
- it('leaves a topic alone once its transcript is already loaded', async () => {
- const { result } = renderHook(() => useChatStore());
- const topicIds = ['warm-topic'];
-
- batchRead.mockResolvedValue(
- new Map([['warm-topic', { messages: [{ id: 'msg-warm', role: 'user', content: 'hi' }] }]]),
- );
-
- await act(async () => {
- await result.current.prefetchTopicMessagesBatch({ agentId: 'batch-agent', topicIds });
- });
- batchRead.mockClear();
-
- await act(async () => {
- await result.current.prefetchTopicMessagesBatch({ agentId: 'batch-agent', topicIds });
- });
-
- // "Visible AND nothing local": the second pass has rows to paint already.
- expect(batchRead).not.toHaveBeenCalled();
- });
-
- it('does nothing without an agent scope', async () => {
- const { result } = renderHook(() => useChatStore());
-
- await act(async () => {
- await result.current.prefetchTopicMessagesBatch({ agentId: null, topicIds: ['a'] });
- });
-
- expect(batchRead).not.toHaveBeenCalled();
- });
-});
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index f1f47972c79..27aed066497 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -9,12 +9,6 @@ import {
isMessageListServerVerified,
} from '@/services/message/cache';
import { revalidateConversationMessages } from '@/services/message/replica';
-import {
- PREFETCH_BATCH_SIZE,
- primeMessageListPage,
- readMessagesByRoundCursorBatch,
- releaseUnusedPrimedMessageListPage,
-} from '@/services/message/roundCursorPage';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { type ChatStore } from '@/store/chat/store';
import {
@@ -35,13 +29,6 @@ import { reconcileAssistantToolLinks } from '../utils/reconcileTools';
const log = debug('lobe-client:message-query');
-/**
- * Topics one visible-row prefetch pass may warm. A viewport renders far fewer
- * rows than this; the cap only stops a long list or a fast scroll from turning
- * one paint into an unbounded fan-out.
- */
-const MAX_PREFETCH_TOPICS_PER_CALL = 24;
-
type Setter = StoreSetter<ChatStore>;
export const messageQuery = (set: Setter, get: () => ChatStore, _api?: unknown) =>
new MessageQueryActionImpl(set, get, _api);
@@ -128,81 +115,6 @@ export class MessageQueryActionImpl {
}
};
- /**
- * Batched form of {@link prefetchMessages} for a list surface: every visible
- * topic the caller hands over is warmed from ONE server read.
- *
- * Each topic still goes through its own transcript head path β€” same merge,
- * cursor and persistence β€” because the batch only hands over the page
- * (`primeMessageListPage`); what changes is that N visible rows cost one
- * request. A page the batch did not return, or a failed batch, leaves that
- * topic on its normal read.
- *
- * Eligibility mirrors the single prefetch: no client-minted topic, nothing
- * running locally, and nothing the store can already paint.
- */
- prefetchTopicMessagesBatch = async (params: {
- agentId?: string | null;
- groupId?: string | null;
- topicIds: string[];
- }): Promise<void> => {
- const { agentId, topicIds } = params;
- if (!agentId || topicIds.length === 0) return;
-
- const chat = this.#get();
- const transcript = getMessageTranscript(this.#set, this.#get);
-
- const contexts = [...new Set(topicIds)]
- .filter((topicId) => !chat.creatingTopicIds.includes(topicId))
- // The active conversation loads through its own sync; warming it here
- // would race that read with the smaller prefetch window.
- .filter((topicId) => topicId !== chat.activeTopicId)
- .map((topicId) => ({
- agentId,
- groupId: params.groupId ?? undefined,
- scope: 'main' as const,
- threadId: null,
- topicId,
- }))
- .filter((context) => !operationSelectors.isAgentRuntimeRunningByContext(context)(chat))
- // "Visible and nothing local" is the whole point: a populated transcript
- // is already what the row would paint on click.
- .filter((context) => !transcript.read(transcript.keyOf(context))?.items.length)
- .slice(0, MAX_PREFETCH_TOPICS_PER_CALL);
-
- for (let index = 0; index < contexts.length; index += PREFETCH_BATCH_SIZE) {
- const chunk = contexts.slice(index, index + PREFETCH_BATCH_SIZE);
- const pages = readMessagesByRoundCursorBatch(chunk);
-
- const primed = chunk.map((context) => {
- const page = pages.then((result) => {
- const batched = result.get(context.topicId!);
- // A topic the batch skipped must not settle as an empty transcript.
- if (!batched) throw new Error(`No batch page for topic ${context.topicId}`);
-
- return batched;
- });
- primeMessageListPage(context, page);
-
- return { context, page };
- });
-
- await Promise.all(
- primed.map(async ({ context, page }) => {
- try {
- await transcript.slice.fetch(context);
- } catch (error) {
- log('Failed to warm the topic transcript %s: %O', context.topicId, error);
- }
- // This fetch joins a read already in flight when one is out, and a
- // joined read never takes the page primed here. Dropping the unused
- // prime keeps an old batch window from answering a later head read.
- releaseUnusedPrimedMessageListPage(context, page);
- }),
- );
- }
- };
-
replaceMessages = (
messages: UIChatMessage[],
params?: {