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.

✨ feat(chat): load pre-window history with a round cursor (#19014)

Arvin Xudc64d76955e8
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 1fb1f1d12b2..6adee7558e2 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -433,6 +433,10 @@ export const messageRouter = router({
.input(
z.object({
agentId: z.string().nullish(),
+ // Round-cursor for loading older history: only rows strictly older than
+ // this (createdAt, id) tuple, round-aligned like page 0. See
+ // `QueryMessageParams.before`.
+ before: z.object({ createdAt: z.date(), id: z.string() }).optional(),
current: z.number().optional(),
groupId: z.string().nullish(),
// Opt-in for `file` work summaries in the payload. Absent → the legacy
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 62d36f821bb..21cced2cb40 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -97,6 +97,7 @@
"backgroundActivity.unavailable": "Resource data is unavailable. Displayed values may be out of date.",
"beforeUnload.confirmLeave": "A request is still running. Leave anyway?",
"builtinCopilot": "Built-in Copilot",
+ "chatList.earlierHistoryError": "Couldn't load earlier messages",
"chatList.expandMessage": "Expand Message",
"chatList.longMessageDetail": "View Details",
"chatList.refreshError": "Couldn't refresh messages",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 392430a4556..399bee0529e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -97,6 +97,7 @@
"backgroundActivity.unavailable": "暂时无法获取资源数据,已显示的数据可能已过期。",
"beforeUnload.confirmLeave": "你有正在生成中的请求,确定要离开吗?",
"builtinCopilot": "内置 Copilot",
+ "chatList.earlierHistoryError": "未能加载更早的消息",
"chatList.expandMessage": "展开消息",
"chatList.longMessageDetail": "查看详情",
"chatList.refreshError": "未能刷新消息",
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 79aededec4a..10b9b6ed87e 100644
--- a/packages/database/src/models/__tests__/messages/message.query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts
@@ -662,6 +662,204 @@ describe('MessageModel Query Tests', () => {
});
});
+ describe('round-cursor before pages (LOBE-13716)', () => {
+ // Like seedRounds, but with a per-round step count so one round can dwarf
+ // the page size — the shape that amplifies the round-start trim.
+ const seedVariableRounds = async (topicId: string, stepsPerRound: number[]) => {
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+ const rows: any[] = [];
+ let seq = 0;
+ let prevId: string | null = null;
+ stepsPerRound.forEach((steps, index) => {
+ const r = index + 1;
+ const uid = `${topicId}-u${r}`;
+ rows.push({
+ id: uid,
+ userId,
+ topicId,
+ role: 'user',
+ parentId: prevId,
+ content: `q${r}`,
+ createdAt: new Date(2023, 0, 1, 0, seq),
+ });
+ seq += 1;
+ prevId = uid;
+ for (let step = 1; step <= steps; step += 1) {
+ const sid = `${topicId}-a${r}-${step}`;
+ rows.push({
+ id: sid,
+ userId,
+ topicId,
+ role: 'assistant',
+ parentId: prevId,
+ content: `a${r}.${step}`,
+ createdAt: new Date(2023, 0, 1, 0, seq),
+ });
+ seq += 1;
+ prevId = sid;
+ }
+ });
+ await serverDB.insert(messages).values(rows);
+ return { allIds: rows.map((row) => row.id as string) };
+ };
+
+ const cursorOf = (message: { createdAt: Date | number | string; id: string }) => ({
+ createdAt: new Date(message.createdAt),
+ id: message.id,
+ });
+
+ it('reproduces the amplified trim: a giant mid-topic round shrinks page 0 to the last round', async () => {
+ const topicId = 't-lobe13716-repro';
+ // Rounds of 4 / 12 / 4 messages; page size 10. The newest 10 rows cut
+ // into the giant round 2, and the round-start trim jumps all the way to
+ // round 3 — page 0 keeps only 4 of the 20 messages.
+ await seedVariableRounds(topicId, [3, 11, 3]);
+
+ const page0 = await messageModel.query({ topicId, pageSize: 10 });
+
+ expect(page0).toHaveLength(4);
+ expect(page0[0].id).toBe(`${topicId}-u3`);
+ expect(page0.at(-1)!.id).toBe(`${topicId}-a3-3`);
+ });
+
+ it('walks the full history through before cursors with no gaps or duplicates', async () => {
+ const topicId = 't-lobe13716-walk';
+ const { allIds } = await seedVariableRounds(topicId, [3, 11, 3]);
+
+ const pageSize = 10;
+ const page0 = await messageModel.query({ topicId, pageSize });
+
+ // Page 1: the giant round's tail. A full page with no user message in
+ // view is kept whole (oversized-round guard), mid-round top and all.
+ const page1 = await messageModel.query({
+ topicId,
+ pageSize,
+ before: cursorOf(page0[0]),
+ });
+ expect(page1).toHaveLength(10);
+ // Contiguous join: page 1's newest row is the parent of page 0's oldest.
+ expect(page0[0].parentId).toBe(page1.at(-1)!.id);
+
+ // Page 2: everything left (6 rows < pageSize) — no trim on a partial page.
+ const page2 = await messageModel.query({
+ topicId,
+ pageSize,
+ before: cursorOf(page1[0]),
+ });
+ expect(page2).toHaveLength(6);
+ expect(page2[0].id).toBe(`${topicId}-u1`);
+ expect(page1[0].parentId).toBe(page2.at(-1)!.id);
+
+ // The three pages reassemble the exact full transcript, in order.
+ const walked = [...page2, ...page1, ...page0].map((m) => m.id);
+ expect(walked).toEqual(allIds);
+
+ // Walking past the beginning returns an empty page (the client's
+ // exhaustion signal alongside `page.length < pageSize`).
+ const page3 = await messageModel.query({
+ topicId,
+ pageSize,
+ before: cursorOf(page2[0]),
+ });
+ expect(page3).toHaveLength(0);
+ });
+
+ it('breaks createdAt ties by id so equal-timestamp rows are neither skipped nor duplicated', async () => {
+ const topicId = 't-lobe13716-tie';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+ const createdAt = new Date(2023, 0, 1, 0, 0);
+ await serverDB.insert(messages).values([
+ { id: `${topicId}-m1`, userId, topicId, role: 'user', content: 'q', createdAt },
+ { id: `${topicId}-m2`, userId, topicId, role: 'assistant', content: 'a1', createdAt },
+ { id: `${topicId}-m3`, userId, topicId, role: 'assistant', content: 'a2', createdAt },
+ ]);
+
+ const page0 = await messageModel.query({ topicId, pageSize: 2 });
+ expect(page0.map((m) => m.id)).toEqual([`${topicId}-m2`, `${topicId}-m3`]);
+
+ const page1 = await messageModel.query({
+ topicId,
+ pageSize: 2,
+ before: cursorOf(page0[0]),
+ });
+ expect(page1.map((m) => m.id)).toEqual([`${topicId}-m1`]);
+ });
+
+ it('windows group nodes to the before page instead of refetching the whole topic', async () => {
+ const topicId = 't-lobe13716-group';
+ await seedVariableRounds(topicId, [3, 11, 3]);
+
+ // One group inside the first before page's time window (minute 7.5) and
+ // one inside page 0's window (minute 18.5), each with a hidden member.
+ await serverDB.insert(messageGroups).values([
+ {
+ id: `${topicId}-g-old`,
+ content: 'old summary',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date(2023, 0, 1, 0, 7, 30),
+ },
+ {
+ id: `${topicId}-g-new`,
+ content: 'new summary',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date(2023, 0, 1, 0, 18, 30),
+ },
+ ]);
+ await serverDB.insert(messages).values([
+ {
+ id: `${topicId}-gm-old`,
+ userId,
+ topicId,
+ role: 'assistant',
+ content: 'grouped old',
+ messageGroupId: `${topicId}-g-old`,
+ createdAt: new Date(2023, 0, 1, 0, 7, 15),
+ },
+ {
+ id: `${topicId}-gm-new`,
+ userId,
+ topicId,
+ role: 'assistant',
+ content: 'grouped new',
+ messageGroupId: `${topicId}-g-new`,
+ createdAt: new Date(2023, 0, 1, 0, 18, 15),
+ },
+ ]);
+
+ const pageSize = 10;
+ const page0 = await messageModel.query({ topicId, pageSize });
+ // Page 0 keeps its existing behavior: every group node of the topic.
+ expect(page0.filter((m) => m.id.startsWith(`${topicId}-g-`)).map((m) => m.id)).toEqual([
+ `${topicId}-g-old`,
+ `${topicId}-g-new`,
+ ]);
+
+ const mainline = page0.find((m) => !m.id.startsWith(`${topicId}-g-`));
+ const page1 = await messageModel.query({
+ topicId,
+ pageSize,
+ before: cursorOf(mainline!),
+ });
+ const page1GroupIds = page1
+ .filter((m) => m.id.startsWith(`${topicId}-g-`))
+ .map((m) => m.id);
+ // Only the group inside this page's time window — not the whole topic's.
+ expect(page1GroupIds).toEqual([`${topicId}-g-old`]);
+
+ const page1Mainline = page1.find((m) => !m.id.startsWith(`${topicId}-g-`));
+ const page2 = await messageModel.query({
+ topicId,
+ pageSize,
+ before: cursorOf(page1Mainline!),
+ });
+ expect(page2.some((m) => m.id.startsWith(`${topicId}-g-`))).toBe(false);
+ });
+ });
+
describe('query with messageQueries', () => {
it('should include ragQuery, ragQueryId and ragRawQuery in query results', async () => {
// Create test data
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 7ebf9d127a6..c2d603478ae 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -59,6 +59,7 @@ import {
inArray,
isNotNull,
isNull,
+ lt,
lte,
ne,
not,
@@ -224,6 +225,11 @@ export interface QueryMessagesOptions {
* true }`).
*/
allowShareVisitor?: boolean;
+ /**
+ * Round-cursor for loading older history (see `QueryMessageParams.before`):
+ * only rows strictly older than this `(createdAt, id)` tuple are fetched.
+ */
+ before?: { createdAt: Date; id: string };
/**
* Current page number (0-indexed)
*/
@@ -1121,6 +1127,7 @@ export class MessageModel {
query = async (
{
agentId,
+ before,
current = 0,
includeFileWorks,
pageSize = 1000,
@@ -1221,6 +1228,7 @@ export class MessageModel {
const threadScopeCondition = topicId ? this.matchTopic(topicId) : agentCondition;
const messageItems = await this.queryWithWhere({
allowShareVisitor: effectiveIncludeVisitor,
+ before,
current,
includeFileWorks,
pageSize,
@@ -1250,6 +1258,7 @@ export class MessageModel {
const messageItems = await this.queryWithWhere({
allowShareVisitor: effectiveIncludeVisitor,
+ before,
current,
includeFileWorks,
pageSize,
@@ -1283,6 +1292,7 @@ export class MessageModel {
const messageItems = await this.queryWithWhere({
allowShareVisitor: effectiveIncludeVisitor,
+ before,
current,
includeFileWorks,
pageSize,
@@ -1466,6 +1476,7 @@ export class MessageModel {
queryWithWhere = async (options: QueryMessagesOptions = {}): Promise<UIChatMessage[]> => {
const {
where,
+ before,
current = 0,
includeFileWorks,
pageSize = 1000,
@@ -1483,6 +1494,16 @@ export class MessageModel {
const scope =
allowShareVisitor || this.includeShareVisitor ? this.workspaceScope() : this.ownership();
+ // Round-cursor paging: only rows strictly older than the `(createdAt, id)`
+ // tuple. The id tie-break mirrors the sort order below, so rows sharing a
+ // createdAt with the cursor are neither skipped nor duplicated.
+ const beforeCondition = before
+ ? or(
+ lt(messages.createdAt, before.createdAt),
+ and(eq(messages.createdAt, before.createdAt), lt(messages.id, before.id)),
+ )
+ : undefined;
+
// 1. get basic messages with joins, excluding messages that belong to MessageGroups
const result = await runTimedStage(
timing,
@@ -1558,6 +1579,7 @@ export class MessageModel {
// Filter out messages that belong to MessageGroups
isNull(messages.messageGroupId),
where,
+ beforeCondition,
),
)
.leftJoin(messagePlugins, eq(messagePlugins.id, messages.id))
@@ -1592,15 +1614,14 @@ export class MessageModel {
// round with no user message in view is kept whole (the proper fix for those
// is lazy step loading). Thread queries pass no `topicId` and are untouched.
//
- // Scope: this only serves the single "most recent page" load (`current === 0`),
- // which is the only page the chat read path ever requests — `current`/`pageSize`
- // offset paging is dead code here (the very premise of). The trim is
- // deliberately NOT offset-exact: the rows it drops from page 0 also fall outside
- // page 1's `offset = pageSize` window, so a hypothetical offset walk would skip
- // them. That is acceptable because nothing offset-walks this path; loading older
- // history is round-cursor based (see the follow-up), which supersedes offset
- // paging entirely and closes that gap by construction.
- if (topicId && current === 0 && result.length >= pageSize) {
+ // Scope: this serves the single "most recent page" load (`current === 0`)
+ // and the round-cursor `before` pages that walk older history — the only
+ // shapes the chat read path requests; `current`/`pageSize` offset paging is
+ // dead code here (the very premise of). The trim is deliberately NOT
+ // offset-exact: rows dropped from one page reappear at the TOP of the next
+ // `before` page (its cursor is the trimmed page's oldest kept row), so the
+ // round-cursor walk loses nothing by construction.
+ if (topicId && (current === 0 || before) && result.length >= pageSize) {
const firstRoundStart = result.findIndex((message) => message.role === 'user');
if (firstRoundStart > 0) result.splice(0, firstRoundStart);
}
@@ -1610,6 +1631,7 @@ export class MessageModel {
const messageGroupNodesPromise = this.queryMessageGroupNodesForPage({
allowShareVisitor: allowShareVisitor || this.includeShareVisitor,
current,
+ hasBeforeCursor: !!before,
postProcessUrl,
result,
timing,
@@ -1785,6 +1807,7 @@ export class MessageModel {
private queryMessageGroupNodesForPage = async ({
allowShareVisitor,
current,
+ hasBeforeCursor,
postProcessUrl,
result,
timing,
@@ -1801,6 +1824,13 @@ export class MessageModel {
*/
allowShareVisitor?: boolean;
current: number;
+ /**
+ * The page was fetched with a round-cursor (`before`): scope group nodes to
+ * the page's time window instead of the whole topic — page 0 already
+ * returned every group node, so an unwindowed fetch here would only
+ * duplicate them.
+ */
+ hasBeforeCursor?: boolean;
postProcessUrl?: (
path: string | null,
file: { fileType: string; id?: string | null },
@@ -1812,7 +1842,7 @@ export class MessageModel {
if (!topicId) return [];
if (result.length === 0) {
- if (current !== 0) return [];
+ if (current !== 0 || hasBeforeCursor) return [];
return runTimedStage(
timing,
@@ -1825,7 +1855,7 @@ export class MessageModel {
);
}
- if (current === 0) {
+ if (current === 0 && !hasBeforeCursor) {
return runTimedStage(
timing,
'db.message.queryWithWhere.messageGroups',
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index a75f0282fa8..dd7a3745c55 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -166,6 +166,7 @@ export default {
'backToBottom': 'Jump to latest',
'beforeUnload.confirmLeave': 'A request is still running. Leave anyway?',
'builtinCopilot': 'Built-in Copilot',
+ 'chatList.earlierHistoryError': "Couldn't load earlier messages",
'chatList.expandMessage': 'Expand Message',
'chatList.longMessageDetail': 'View Details',
'chatList.refreshError': "Couldn't refresh messages",
diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.ts
index d47b2e1f6f0..cdfd9f40676 100644
--- a/packages/types/src/message/db/params.ts
+++ b/packages/types/src/message/db/params.ts
@@ -24,6 +24,13 @@ import type { UIChatMessage } from '../ui';
export interface QueryMessageParams {
agentId?: string | null;
+ /**
+ * Round-cursor for loading older history: only rows strictly older than this
+ * `(createdAt, id)` tuple are returned, newest-first windowed like the main
+ * page. Callers pass the oldest already-loaded mainline message so pages join
+ * contiguously; offset paging (`current`) is unused by the chat read path.
+ */
+ before?: { createdAt: Date; id: string };
current?: number;
groupId?: string | null;
/**
diff --git a/src/features/Conversation/ChatList/components/EarlierHistoryError.tsx b/src/features/Conversation/ChatList/components/EarlierHistoryError.tsx
new file mode 100644
index 00000000000..e11901b5fc9
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/EarlierHistoryError.tsx
@@ -0,0 +1,46 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+
+import { useConversationStore } from '../../store';
+
+/**
+ * Inline failure row shown above the messages when a page of pre-window
+ * history failed to load. Scroll gestures stop re-firing the request while it
+ * stands, so Retry is the explicit way back. A retry clears the error as it
+ * starts, handing the row over to the skeleton.
+ *
+ * Like `EarlierHistorySkeleton`, it subscribes to the store itself: virtua
+ * caches the leading row's element, so a prop passed from the list would never
+ * repaint it.
+ */
+const EarlierHistoryError = memo(() => {
+ const { t } = useTranslation('chat');
+ const error = useConversationStore((s) => s.earlierMessagesError);
+ const loadEarlierMessages = useConversationStore((s) => s.loadEarlierMessages);
+
+ const handleRetry = useCallback(() => {
+ void loadEarlierMessages({ retry: true });
+ }, [loadEarlierMessages]);
+
+ if (error === undefined) return null;
+
+ return (
+ <Flexbox horizontal align={'center'} aria-live={'polite'} justify={'center'} role={'status'}>
+ <AsyncError
+ error={error}
+ title={t('chatList.earlierHistoryError')}
+ variant={'inline'}
+ onRetry={handleRetry}
+ />
+ </Flexbox>
+ );
+});
+
+EarlierHistoryError.displayName = 'EarlierHistoryError';
+
+export default EarlierHistoryError;
diff --git a/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx b/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx
new file mode 100644
index 00000000000..1620c7867d5
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx
@@ -0,0 +1,24 @@
+'use client';
+
+import { memo } from 'react';
+
+import SkeletonList from '../../components/SkeletonList';
+import { useConversationStore } from '../../store';
+
+/**
+ * The conversation skeleton shown above the messages while a page of
+ * pre-window history is in flight.
+ *
+ * It subscribes to the loading flag itself instead of taking it as a prop:
+ * virtua caches the element it rendered for an unchanged row, so the leading
+ * row would never repaint on a flag change passed down from the list.
+ */
+const EarlierHistorySkeleton = memo(() => {
+ const isLoading = useConversationStore((s) => s.isLoadingEarlierMessages);
+
+ return isLoading ? <SkeletonList /> : null;
+});
+
+EarlierHistorySkeleton.displayName = 'EarlierHistorySkeleton';
+
+export default EarlierHistorySkeleton;
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index e7cfb2d8480..230d21469ca 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -1,7 +1,14 @@
'use client';
import isEqual from 'fast-deep-equal';
-import type { KeyboardEvent, PointerEvent, ReactElement, ReactNode } from 'react';
+import type {
+ KeyboardEvent,
+ PointerEvent,
+ ReactElement,
+ ReactNode,
+ TouchEvent,
+ WheelEvent,
+} from 'react';
import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef } from 'react';
import type { VListHandle } from 'virtua';
import { VList } from 'virtua';
@@ -23,6 +30,7 @@ import {
CONVERSATION_SPACER_TRANSITION_MS,
useConversationScroll,
} from '../hooks/useConversationScroll';
+import { useEarlierHistoryTrigger } from '../hooks/useEarlierHistoryTrigger';
import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';
import { useTopicScrollPersist } from '../hooks/useTopicScrollPersist';
import type { ResolvedMessageDeepLink } from '../utils/messageDeepLink';
@@ -30,11 +38,22 @@ import AutoScroll from './AutoScroll';
import { AT_BOTTOM_THRESHOLD } from './AutoScroll/const';
import { useAutoScrollEnabled } from './AutoScroll/useAutoScrollEnabled';
import BackBottom from './BackBottom';
+import EarlierHistoryError from './EarlierHistoryError';
+import EarlierHistorySkeleton from './EarlierHistorySkeleton';
const DebugInspector = lazy(() => import('./AutoScroll/DebugInspector'));
const CONVERSATION_FOOTER_ID = '__conversation_footer__';
const CONVERSATION_HEADER_ID = '__conversation_header__';
+// One synthetic leading row always precedes the messages: it holds the
+// header slot and, while a page of pre-window history is in flight, the
+// conversation skeleton. Keeping it permanent matters because virtua keys
+// rows by index — inserting a row on load start would shift every index
+// and remount each message, dropping local UI state such as an expanded
+// workflow fold. All index-based APIs exposed to the store (and the hooks
+// that talk to virtua directly) work in MESSAGE index space; this offset
+// translates at the virtua boundary.
+const LEADING_ROWS = 1;
const USER_SCROLL_INTENT_TTL_MS = 500;
const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']);
@@ -58,14 +77,6 @@ const VirtualizedList = memo<VirtualizedListProps>(
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastUserScrollIntentAtRef = useRef(0);
- // A header slot prepends one synthetic row to the VList, shifting every
- // virtua row index off the message index. All index-based APIs exposed to
- // the store (and the hooks that talk to virtua directly) work in MESSAGE
- // index space; this offset translates at the virtua boundary.
- const headerOffset = headerSlot ? 1 : 0;
- const headerOffsetRef = useRef(headerOffset);
- headerOffsetRef.current = headerOffset;
-
// Per-topic scroll restoration. Provider does not remount on topic switch,
// so we key the scroll snapshot by the message-map key derived from
// ConversationStore's `context`.
@@ -74,7 +85,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
contextKey,
containerRef,
dataSourceLength: dataSource.length,
- headerOffset,
+ headerOffset: LEADING_ROWS,
messageDeepLink,
virtuaRef,
});
@@ -95,7 +106,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
} = useConversationScroll({
contextKey,
dataSource,
- headerOffset,
+ headerOffset: LEADING_ROWS,
isSecondLastMessageFromUser,
virtuaRef,
});
@@ -109,12 +120,15 @@ const VirtualizedList = memo<VirtualizedListProps>(
const isSelectionMode = useConversationStore(messageStateSelectors.isSelectionMode);
// Store actions
+ const loadEarlierMessages = useConversationStore((s) => s.loadEarlierMessages);
const registerVirtuaScrollMethods = useConversationStore((s) => s.registerVirtuaScrollMethods);
const setScrollState = useConversationStore((s) => s.setScrollState);
const resetVisibleItems = useConversationStore((s) => s.resetVisibleItems);
const setActiveIndex = useConversationStore((s) => s.setActiveIndex);
const activeIndex = useConversationStore(virtuaListSelectors.activeIndex);
+ const earlierHistory = useEarlierHistoryTrigger({ loadEarlierMessages, virtuaRef });
+
const markUserScrollIntent = useCallback(() => {
lastUserScrollIntentAtRef.current = Date.now();
}, []);
@@ -133,8 +147,25 @@ const VirtualizedList = memo<VirtualizedListProps>(
if (SCROLL_KEYS.has(event.key)) {
markUserScrollIntent();
}
+ earlierHistory.onKeyDown(event);
},
- [markUserScrollIntent],
+ [earlierHistory, markUserScrollIntent],
+ );
+
+ const handleWheel = useCallback(
+ (event: WheelEvent<HTMLDivElement>) => {
+ markUserScrollIntent();
+ earlierHistory.onWheel(event);
+ },
+ [earlierHistory, markUserScrollIntent],
+ );
+
+ const handleTouchMove = useCallback(
+ (event: TouchEvent<HTMLDivElement>) => {
+ markUserScrollIntent();
+ earlierHistory.onTouchMove(event);
+ },
+ [earlierHistory, markUserScrollIntent],
);
// Check if at bottom based on scroll position
@@ -160,7 +191,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
// (the header row clamps to the first message).
const activeFromFind =
typeof activeFromFindRaw === 'number' && activeFromFindRaw >= 0
- ? Math.max(0, activeFromFindRaw - headerOffsetRef.current)
+ ? Math.max(0, activeFromFindRaw - LEADING_ROWS)
: null;
if (activeFromFind !== activeIndex) setActiveIndex(activeFromFind);
@@ -173,6 +204,9 @@ const VirtualizedList = memo<VirtualizedListProps>(
const hasUserScrollIntent =
Date.now() - lastUserScrollIntentAtRef.current <= USER_SCROLL_INTENT_TTL_MS;
onScrollOffset(ref.scrollOffset, hasUserScrollIntent);
+
+ // Programmatic mount/restore scrolls carry no intent and never fetch.
+ if (hasUserScrollIntent) earlierHistory.onUserScroll();
}
// Check if at bottom
@@ -192,7 +226,15 @@ const VirtualizedList = memo<VirtualizedListProps>(
scrollEndTimerRef.current = setTimeout(() => {
setScrollState({ isScrolling: false });
}, 150);
- }, [activeIndex, checkAtBottom, onScrollOffset, recordScroll, setActiveIndex, setScrollState]);
+ }, [
+ activeIndex,
+ checkAtBottom,
+ earlierHistory,
+ onScrollOffset,
+ recordScroll,
+ setActiveIndex,
+ setScrollState,
+ ]);
const handleScrollEnd = useCallback(() => {
setScrollState({ isScrolling: false });
@@ -205,22 +247,21 @@ const VirtualizedList = memo<VirtualizedListProps>(
// Index-based methods accept MESSAGE indices; the header slot row is a
// private implementation detail translated away right here.
registerVirtuaScrollMethods({
- getItemOffset: (index) => ref.getItemOffset(index + headerOffsetRef.current),
- getItemSize: (index) => ref.getItemSize(index + headerOffsetRef.current),
+ getItemOffset: (index) => ref.getItemOffset(index + LEADING_ROWS),
+ getItemSize: (index) => ref.getItemSize(index + LEADING_ROWS),
getScrollOffset: () => ref.scrollOffset,
getScrollSize: () => ref.scrollSize,
getTotalCount: () => totalCountRef.current,
getViewportSize: () => ref.viewportSize,
scrollTo: (offset) => ref.scrollTo(offset),
- scrollToIndex: (index, options) =>
- ref.scrollToIndex(index + headerOffsetRef.current, options),
+ scrollToIndex: (index, options) => ref.scrollToIndex(index + LEADING_ROWS, options),
});
// Seed active index once on mount (avoid requiring user scroll)
const initialActiveRaw = ref.findItemIndex(ref.scrollOffset + ref.viewportSize * 0.25);
const initialActive =
typeof initialActiveRaw === 'number' && initialActiveRaw >= 0
- ? Math.max(0, initialActiveRaw - headerOffsetRef.current)
+ ? Math.max(0, initialActiveRaw - LEADING_ROWS)
: null;
setActiveIndex(initialActive);
}
@@ -285,17 +326,32 @@ const VirtualizedList = memo<VirtualizedListProps>(
const paddingBottom = Math.max(24, overlayHeight + 12);
const dataWithSlots = useMemo(
- () => [
- ...(headerSlot ? [CONVERSATION_HEADER_ID] : []),
- ...listData,
- ...(footerSlot ? [CONVERSATION_FOOTER_ID] : []),
- ],
- [footerSlot, headerSlot, listData],
+ () => [CONVERSATION_HEADER_ID, ...listData, ...(footerSlot ? [CONVERSATION_FOOTER_ID] : [])],
+ [footerSlot, listData],
);
+ // Prepend detection for virtua: when pre-window history loads, the former
+ // first message moves down the list. Passing `shift` for exactly that
+ // render keeps the viewport anchored on the rows the user was reading
+ // instead of snapping to the (new) top. Removals and topic switches drop
+ // the previous first id from the list entirely and stay unshifted.
+ const firstMessageId = listData[0] as string | undefined;
+ const prevFirstMessageIdRef = useRef(firstMessageId);
+ const prevFirstMessageId = prevFirstMessageIdRef.current;
+ const shift =
+ prevFirstMessageId !== undefined &&
+ firstMessageId !== prevFirstMessageId &&
+ listData.includes(prevFirstMessageId);
+ useEffect(() => {
+ prevFirstMessageIdRef.current = firstMessageId;
+ });
+
+ // The leading row is pinned: it is zero-height while idle, and virtua
+ // excludes a zero-height row at the top from its render range, so it
+ // would never mount to show the skeleton it hosts.
const keepMountedIndicesWithSlots = useMemo(
- () => (headerSlot ? keepMountedIndices.map((index) => index + 1) : keepMountedIndices),
- [headerSlot, keepMountedIndices],
+ () => [0, ...keepMountedIndices.map((index) => index + LEADING_ROWS)],
+ [keepMountedIndices],
);
// Mirror the latest data length into a ref so the scroll-methods registered
@@ -303,8 +359,8 @@ const VirtualizedList = memo<VirtualizedListProps>(
// but excluding the leading header row — the count stays in the same
// message-index space as the registered scrollToIndex) without
// re-registering on every render.
- const totalCountRef = useRef(dataWithSlots.length - headerOffset);
- totalCountRef.current = dataWithSlots.length - headerOffset;
+ const totalCountRef = useRef(dataWithSlots.length - LEADING_ROWS);
+ totalCountRef.current = dataWithSlots.length - LEADING_ROWS;
return (
<div
@@ -313,8 +369,9 @@ const VirtualizedList = memo<VirtualizedListProps>(
onKeyDownCapture={handleKeyDown}
onPointerDownCapture={markUserScrollIntent}
onPointerMoveCapture={handlePointerMove}
- onTouchMoveCapture={markUserScrollIntent}
- onWheelCapture={markUserScrollIntent}
+ onTouchMoveCapture={handleTouchMove}
+ onTouchStartCapture={earlierHistory.onTouchStart}
+ onWheelCapture={handleWheel}
>
{/* Pinned to the list viewport top; only renders while multi-selecting */}
<MessageForwardSelectToHere />
@@ -329,6 +386,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
data={dataWithSlots}
keepMounted={keepMountedIndicesWithSlots}
ref={virtuaRef}
+ shift={shift}
style={{ height: '100%', overflowAnchor: 'none', paddingBottom }}
onScroll={handleScroll}
onScrollEnd={handleScrollEnd}
@@ -338,6 +396,8 @@ const VirtualizedList = memo<VirtualizedListProps>(
return (
<WideScreenContainer key={messageId} style={{ position: 'relative' }}>
{headerSlot}
+ <EarlierHistorySkeleton />
+ <EarlierHistoryError />
</WideScreenContainer>
);
}
@@ -374,7 +434,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
}
const isAgentCouncil = messageId.includes('agentCouncil');
- const messageIndex = headerSlot ? index - 1 : index;
+ const messageIndex = index - LEADING_ROWS;
const isLastItem = messageIndex === dataSource.length - 1;
const content = itemContent(messageIndex, messageId);
diff --git a/src/features/Conversation/ChatList/hooks/useEarlierHistoryTrigger.test.ts b/src/features/Conversation/ChatList/hooks/useEarlierHistoryTrigger.test.ts
new file mode 100644
index 00000000000..b233cd40d32
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useEarlierHistoryTrigger.test.ts
@@ -0,0 +1,83 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import type { KeyboardEvent, RefObject, TouchEvent, WheelEvent } from 'react';
+import type { VListHandle } from 'virtua';
+import { describe, expect, it, vi } from 'vitest';
+
+import { EARLIER_HISTORY_TRIGGER_PX, useEarlierHistoryTrigger } from './useEarlierHistoryTrigger';
+
+const refOf = (scrollOffset: number): RefObject<VListHandle | null> => ({
+ current: { scrollOffset } as unknown as VListHandle,
+});
+
+const wheel = (deltaY: number) => ({ deltaY }) as WheelEvent<HTMLElement>;
+const key = (value: string) => ({ key: value }) as KeyboardEvent<HTMLElement>;
+const touchAt = (clientY: number) =>
+ ({ touches: [{ clientY }] }) as unknown as TouchEvent<HTMLElement>;
+
+const setup = (scrollOffset: number) => {
+ const loadEarlierMessages = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ useEarlierHistoryTrigger({ loadEarlierMessages, virtuaRef: refOf(scrollOffset) }),
+ );
+ return { loadEarlierMessages, trigger: result.current };
+};
+
+describe('useEarlierHistoryTrigger', () => {
+ it('loads on a wheel-up over a list too short to scroll', () => {
+ // A long topic whose last round collapses into one workflow block renders
+ // shorter than the viewport: scrollOffset stays 0 and no scroll event ever
+ // fires, so the wheel itself must be the trigger.
+ const { loadEarlierMessages, trigger } = setup(0);
+
+ trigger.onWheel(wheel(-120));
+
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores a wheel-down and any gesture away from the top', () => {
+ const atTop = setup(0);
+ atTop.trigger.onWheel(wheel(120));
+ expect(atTop.loadEarlierMessages).not.toHaveBeenCalled();
+
+ const farDown = setup(EARLIER_HISTORY_TRIGGER_PX);
+ farDown.trigger.onWheel(wheel(-120));
+ farDown.trigger.onUserScroll();
+ farDown.trigger.onKeyDown(key('PageUp'));
+ expect(farDown.loadEarlierMessages).not.toHaveBeenCalled();
+ });
+
+ it('loads on a user scroll that reaches the top region', () => {
+ const { loadEarlierMessages, trigger } = setup(EARLIER_HISTORY_TRIGGER_PX - 1);
+
+ trigger.onUserScroll();
+
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it('loads on upward navigation keys only', () => {
+ const { loadEarlierMessages, trigger } = setup(0);
+
+ trigger.onKeyDown(key('ArrowDown'));
+ trigger.onKeyDown(key('End'));
+ expect(loadEarlierMessages).not.toHaveBeenCalled();
+
+ trigger.onKeyDown(key('ArrowUp'));
+ trigger.onKeyDown(key('PageUp'));
+ trigger.onKeyDown(key('Home'));
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(3);
+ });
+
+ it('loads when a touch drags downward (content scrolls up), not upward', () => {
+ const { loadEarlierMessages, trigger } = setup(0);
+
+ trigger.onTouchStart(touchAt(300));
+ trigger.onTouchMove(touchAt(250));
+ expect(loadEarlierMessages).not.toHaveBeenCalled();
+
+ trigger.onTouchMove(touchAt(360));
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useEarlierHistoryTrigger.ts b/src/features/Conversation/ChatList/hooks/useEarlierHistoryTrigger.ts
new file mode 100644
index 00000000000..674b1c14417
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useEarlierHistoryTrigger.ts
@@ -0,0 +1,75 @@
+import type { KeyboardEvent, RefObject, TouchEvent, WheelEvent } from 'react';
+import { useCallback, useMemo, useRef } from 'react';
+import type { VListHandle } from 'virtua';
+
+/**
+ * Distance from the very top (px) under which an upward gesture fetches one
+ * round-aligned page of history older than the server's newest-first window.
+ * `loadEarlierMessages` self-guards against duplicate and exhausted loads, so
+ * firing it per gesture is safe.
+ */
+export const EARLIER_HISTORY_TRIGGER_PX = 200;
+
+const UPWARD_KEYS = new Set(['ArrowUp', 'Home', 'PageUp']);
+
+interface UseEarlierHistoryTriggerOptions {
+ loadEarlierMessages: () => Promise<void>;
+ virtuaRef: RefObject<VListHandle | null>;
+}
+
+/**
+ * Fetch pre-window history on upward *intent* near the top, not only on scroll
+ * events. A long topic's last round often collapses into a single workflow
+ * block, leaving a list shorter than its viewport: it can never scroll, so a
+ * scroll-only trigger would leave the older history unreachable. Wheel, touch
+ * pull, and upward navigation keys fire whether or not the list moves. After a
+ * failed page the action ignores these gestures until the inline Retry runs.
+ */
+export const useEarlierHistoryTrigger = ({
+ loadEarlierMessages,
+ virtuaRef,
+}: UseEarlierHistoryTriggerOptions) => {
+ const touchStartYRef = useRef<number | null>(null);
+
+ const requestIfNearTop = useCallback(() => {
+ const ref = virtuaRef.current;
+ if (!ref || ref.scrollOffset >= EARLIER_HISTORY_TRIGGER_PX) return;
+ void loadEarlierMessages();
+ }, [loadEarlierMessages, virtuaRef]);
+
+ /** A scroll event that carries real user intent (programmatic mount/restore scrolls do not). */
+ const onUserScroll = requestIfNearTop;
+
+ const onWheel = useCallback(
+ (event: WheelEvent<HTMLElement>) => {
+ if (event.deltaY < 0) requestIfNearTop();
+ },
+ [requestIfNearTop],
+ );
+
+ const onKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLElement>) => {
+ if (UPWARD_KEYS.has(event.key)) requestIfNearTop();
+ },
+ [requestIfNearTop],
+ );
+
+ const onTouchStart = useCallback((event: TouchEvent<HTMLElement>) => {
+ touchStartYRef.current = event.touches[0]?.clientY ?? null;
+ }, []);
+
+ const onTouchMove = useCallback(
+ (event: TouchEvent<HTMLElement>) => {
+ const startY = touchStartYRef.current;
+ const currentY = event.touches[0]?.clientY;
+ // Dragging the finger downward scrolls the content up, toward older history.
+ if (startY !== null && currentY !== undefined && currentY > startY) requestIfNearTop();
+ },
+ [requestIfNearTop],
+ );
+
+ return useMemo(
+ () => ({ onKeyDown, onTouchMove, onTouchStart, onUserScroll, onWheel }),
+ [onKeyDown, onTouchMove, onTouchStart, onUserScroll, onWheel],
+ );
+};
diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.ts
index e0892396fe4..04368efbefe 100644
--- a/src/features/Conversation/store/initialState.ts
+++ b/src/features/Conversation/store/initialState.ts
@@ -87,9 +87,11 @@ export const initialState: State = {
export const createEphemeralResetState = (): Partial<State> => ({
activeIndex: null,
atBottom: true,
+ earlierMessagesError: undefined,
heteroOverloadRetryAttempts: {},
heteroOverloadWaitOpIds: {},
inputMessage: '',
+ isLoadingEarlierMessages: false,
isScrolling: false,
messageEditingIds: [],
messageLoadingIds: [],
diff --git a/src/features/Conversation/store/selectors.test.ts b/src/features/Conversation/store/selectors.test.ts
index 000d568276a..0555b5a4635 100644
--- a/src/features/Conversation/store/selectors.test.ts
+++ b/src/features/Conversation/store/selectors.test.ts
@@ -37,6 +37,7 @@ const createMockState = (overrides: Partial<State> = {}): State => ({
dbMessages: [],
displayMessages: [],
hooks: {},
+ isLoadingEarlierMessages: false,
messagesInit: false,
operationState: DEFAULT_OPERATION_STATE,
skipFetch: false,
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
index b9a8c242ce5..9fce176a9c8 100644
--- a/src/features/Conversation/store/slices/data/action.test.ts
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -1,6 +1,6 @@
import type { UIChatMessage } from '@lobechat/types';
import { act, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { messageService } from '@/services/message';
@@ -13,6 +13,7 @@ import { useChatStore } from '@/store/chat';
import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { createStore } from '../../index';
+import { createEphemeralResetState } from '../../initialState';
import { dataSelectors } from './selectors';
// Mock conversation-flow parse function
@@ -31,6 +32,7 @@ vi.mock('@lobechat/conversation-flow', () => ({
// Mock messageService
vi.mock('@/services/message', () => ({
messageService: {
+ getEarlierMessages: vi.fn(),
getMessages: vi.fn(),
updateMessageMetadata: vi.fn().mockResolvedValue({ success: true, messages: [] }),
},
@@ -246,6 +248,167 @@ describe('DataSlice', () => {
});
});
+ describe('loadEarlierMessages', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ clearMessageListClientCacheState();
+ });
+
+ const windowMessages: UIChatMessage[] = [
+ { id: 'u2', content: 'q2', role: 'user', createdAt: 1000, updatedAt: 1000 } as any,
+ { id: 'a2', content: 'a2', role: 'assistant', createdAt: 2000, updatedAt: 2000 } as any,
+ ];
+ const earlierPage: UIChatMessage[] = [
+ { id: 'u1', content: 'q1', role: 'user', createdAt: 100, updatedAt: 100 } as any,
+ { id: 'a1', content: 'a1', role: 'assistant', createdAt: 200, updatedAt: 200 } as any,
+ ];
+
+ it('prepends the fetched round page below the live window rows', async () => {
+ const store = createStore({
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-1', threadId: null },
+ });
+ store.getState().replaceMessages(windowMessages);
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce(earlierPage);
+
+ await store.getState().loadEarlierMessages();
+
+ expect(messageService.getEarlierMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-earlier', topicId: 'topic-earlier-1' }),
+ { createdAt: new Date(1000), id: 'u2' },
+ );
+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u1', 'a1', 'u2', 'a2']);
+ expect(store.getState().isLoadingEarlierMessages).toBe(false);
+ });
+
+ it('stops fetching once a page comes back empty (beginning reached)', async () => {
+ const store = createStore({
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-2', threadId: null },
+ });
+ store.getState().replaceMessages(windowMessages);
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValue([]);
+
+ await store.getState().loadEarlierMessages();
+ await store.getState().loadEarlierMessages();
+
+ expect(messageService.getEarlierMessages).toHaveBeenCalledTimes(1);
+ 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: null },
+ });
+ 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: null },
+ } as any);
+ return earlierPage;
+ });
+
+ await store.getState().loadEarlierMessages();
+
+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u2', 'a2']);
+ expect(store.getState().isLoadingEarlierMessages).toBe(false);
+ });
+
+ it('surfaces a failed page fetch as state and only retries on explicit request', async () => {
+ const store = createStore({
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-4', threadId: null },
+ });
+ store.getState().replaceMessages(windowMessages);
+ const failure = new Error('network down');
+ vi.mocked(messageService.getEarlierMessages)
+ .mockRejectedValueOnce(failure)
+ .mockResolvedValueOnce(earlierPage);
+
+ await expect(store.getState().loadEarlierMessages()).resolves.toBeUndefined();
+ expect(store.getState().isLoadingEarlierMessages).toBe(false);
+ expect(store.getState().earlierMessagesError).toBe(failure);
+
+ // Scroll gestures must not silently re-fire the failing request.
+ await store.getState().loadEarlierMessages();
+ expect(messageService.getEarlierMessages).toHaveBeenCalledTimes(1);
+
+ await store.getState().loadEarlierMessages({ retry: true });
+
+ expect(messageService.getEarlierMessages).toHaveBeenCalledTimes(2);
+ expect(store.getState().earlierMessagesError).toBeUndefined();
+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u1', 'a1', 'u2', 'a2']);
+ });
+
+ it('clears the failure on conversation switch', async () => {
+ const store = createStore({
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-6', threadId: null },
+ });
+ store.getState().replaceMessages(windowMessages);
+ vi.mocked(messageService.getEarlierMessages).mockRejectedValueOnce(new Error('boom'));
+
+ await store.getState().loadEarlierMessages();
+ expect(store.getState().earlierMessagesError).toBeDefined();
+
+ store.setState({
+ ...createEphemeralResetState(),
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-7', threadId: null },
+ } as any);
+ expect(store.getState().earlierMessagesError).toBeUndefined();
+ });
+
+ it('merges the page into messages that changed while it was in flight', async () => {
+ const store = createStore({
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-8', threadId: null },
+ });
+ store.getState().replaceMessages(windowMessages);
+ const streamed = {
+ id: 'a2',
+ content: 'a2 streamed',
+ role: 'assistant',
+ createdAt: 2000,
+ updatedAt: 2500,
+ } as any;
+ const appended = {
+ id: 'u3',
+ content: 'q3',
+ role: 'user',
+ createdAt: 3000,
+ updatedAt: 3000,
+ } as any;
+ vi.mocked(messageService.getEarlierMessages).mockImplementationOnce(async () => {
+ // Same conversation keeps updating: an edit/stream and a new message.
+ store.getState().replaceMessages([windowMessages[0], streamed, appended]);
+ return earlierPage;
+ });
+
+ await store.getState().loadEarlierMessages();
+
+ const { dbMessages } = store.getState();
+ expect(dbMessages.map((m) => m.id)).toEqual(['u1', 'a1', 'u2', 'a2', 'u3']);
+ expect(dbMessages.find((m) => m.id === 'a2')?.content).toBe('a2 streamed');
+ });
+
+ it('does not clear the loading flag of the next conversation on late settle', async () => {
+ const store = createStore({
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-5', threadId: null },
+ });
+ store.getState().replaceMessages(windowMessages);
+ vi.mocked(messageService.getEarlierMessages).mockImplementationOnce(async () => {
+ store.setState({
+ ...createEphemeralResetState(),
+ context: { agentId: 'agent-earlier', topicId: 'topic-earlier-next', threadId: null },
+ } as any);
+ // The next conversation starts its own page load while ours is in flight.
+ store.setState({ isLoadingEarlierMessages: true });
+ return earlierPage;
+ });
+
+ await store.getState().loadEarlierMessages();
+
+ expect(store.getState().isLoadingEarlierMessages).toBe(true);
+ });
+ });
+
describe('replaceMessages', () => {
it('should replace all messages with new data', () => {
const store = createTestStore();
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index 551d339a8de..d90f36ed649 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -7,7 +7,9 @@ import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { messageService } from '@/services/message';
import {
+ getEarlierHistoryStatus,
getMessageListFetchPolicy,
+ loadEarlierMessagePage,
messageListKey,
runMessageListQuery,
} from '@/services/message/cache';
@@ -75,6 +77,19 @@ export interface DataAction {
*/
internal_dispatchMessage: (payload: MessageDispatch) => void;
+ /**
+ * Load one round-aligned page of history older than the server's
+ * newest-first window (LOBE-13716) and prepend it to the transcript.
+ * Self-guarding: no-ops while a page is in flight, once the beginning has
+ * been reached, or when the conversation has no server-backed messages yet.
+ *
+ * Never rejects: a failure is kept in `earlierMessagesError` for the inline
+ * error row. While that error stands, gesture-driven calls no-op so scrolling
+ * does not silently re-fire a failing request; pass `{ retry: true }` from the
+ * explicit Retry action to try again.
+ */
+ loadEarlierMessages: (options?: { retry?: boolean }) => Promise<void>;
+
/**
* Replace all messages with new data
* Used for syncing after database operations (optimistic update pattern)
@@ -188,6 +203,66 @@ export const dataSlice: StateCreator<
get().onMessagesChange?.(newDbMessages, get().context);
},
+ loadEarlierMessages: async (options) => {
+ const context = get().context;
+ if (!context.agentId || !context.topicId) return;
+ if (get().earlierMessagesError !== undefined && !options?.retry) return;
+ const status = getEarlierHistoryStatus(context);
+ if (status.loading || status.exhausted) return;
+
+ set(
+ { earlierMessagesError: undefined, isLoadingEarlierMessages: true },
+ false,
+ 'loadEarlierMessages/start',
+ );
+ try {
+ const merged = await loadEarlierMessagePage(
+ context,
+ // Read on demand: the cursor comes from the transcript at request time,
+ // while the merge runs against the transcript at completion — a stream
+ // or edit may have changed it meanwhile. A conversation switch yields
+ // `undefined` so the other conversation's rows are never merged.
+ () => (isSameConversationContext(context, get().context) ? get().dbMessages : undefined),
+ (before) =>
+ messageService.getEarlierMessages(
+ {
+ agentId: context.agentId,
+ agentShareId: context.agentShareId,
+ groupId: context.groupId,
+ threadId: context.threadId,
+ topicId: context.topicId,
+ topicShareId: context.topicShareId,
+ },
+ before,
+ ),
+ );
+ // `undefined` → nothing to prepend (no cursor, already loading, the
+ // beginning was reached, or the request went stale while in flight).
+ if (!merged) return;
+
+ log(
+ '[loadEarlierMessages] prepended | contextKey=%s | mergedCount=%d',
+ messageMapKey(context),
+ merged.length,
+ );
+ get().replaceMessages(merged, { expectedContext: context });
+ } catch (error) {
+ log('[loadEarlierMessages] failed | contextKey=%s | %O', messageMapKey(context), error);
+ // The list fires this without awaiting, so the failure is surfaced
+ // through state (inline error row with Retry) instead of a rejection.
+ if (isSameConversationContext(context, get().context)) {
+ set({ earlierMessagesError: error }, false, 'loadEarlierMessages/error');
+ }
+ } finally {
+ // 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)) {
+ set({ isLoadingEarlierMessages: false }, false, 'loadEarlierMessages/end');
+ }
+ }
+ },
+
replaceMessages: (messages, options) => {
const currentContext = get().context;
const contextKey = messageMapKey(currentContext);
diff --git a/src/features/Conversation/store/slices/data/initialState.ts b/src/features/Conversation/store/slices/data/initialState.ts
index 6bb9b9b9af5..f0cef9929f3 100644
--- a/src/features/Conversation/store/slices/data/initialState.ts
+++ b/src/features/Conversation/store/slices/data/initialState.ts
@@ -13,6 +13,19 @@ export interface DataState {
*/
displayMessages: UIChatMessage[];
+ /**
+ * The last round-cursor page fetch failed (LOBE-13716). Drives the inline
+ * error row with Retry at the top of the list; cleared when a retry starts
+ * and on conversation switch.
+ */
+ earlierMessagesError?: unknown;
+
+ /**
+ * A round-cursor fetch for history older than the server's newest-first
+ * window is in flight (LOBE-13716). Drives the top-of-list loading hint.
+ */
+ isLoadingEarlierMessages: boolean;
+
/**
* Whether messages have been initialized
*/
@@ -27,5 +40,6 @@ export interface DataState {
export const dataInitialState: DataState = {
dbMessages: [],
displayMessages: [],
+ isLoadingEarlierMessages: false,
messagesInit: false,
};
diff --git a/src/services/message/cache.test.ts b/src/services/message/cache.test.ts
index 7fe79a545e7..796ca3608e8 100644
--- a/src/services/message/cache.test.ts
+++ b/src/services/message/cache.test.ts
@@ -5,9 +5,11 @@ import { MESSAGE_CACHE_VERSION } from '@/libs/swr/keys';
import {
clearMessageListClientCacheState,
+ getEarlierHistoryStatus,
getMessageListFetchPolicy,
invalidateMessageListClientState,
isMessageListServerVerified,
+ loadEarlierMessagePage,
MESSAGE_LIST_VERIFICATION_INTERVAL,
messageListKey,
runMessageListQuery,
@@ -245,3 +247,197 @@ describe('message list client cache', () => {
expect(isMessageListServerVerified({ agentId: 'agent-1', topicId: 'topic-500' })).toBe(true);
});
});
+
+describe('earlier history (round-cursor pages, LOBE-13716)', () => {
+ const message = (id: string, createdAt: number, role = 'assistant') =>
+ ({ content: id, createdAt, id, role, updatedAt: createdAt }) as unknown as UIChatMessage;
+
+ const ids = (list: UIChatMessage[] | undefined) => list?.map((item) => item.id);
+
+ it('fetches a page older than the oldest mainline row and returns the merged transcript', async () => {
+ const window = [message('u2', 10, 'user'), message('a2', 11)];
+ const fetcher = vi.fn().mockResolvedValue([message('u1', 1, 'user'), message('a1', 2)]);
+
+ const merged = await loadEarlierMessagePage(context, () => window, fetcher);
+
+ expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10), id: 'u2' });
+ expect(ids(merged)).toEqual(['u1', 'a1', 'u2', 'a2']);
+ });
+
+ it('never uses a synthetic group node as the round cursor', async () => {
+ const window = [message('group-1', 5, 'compressedGroup'), message('u2', 10, 'user')];
+ const fetcher = vi.fn().mockResolvedValue([message('u1', 1, 'user')]);
+
+ await loadEarlierMessagePage(context, () => window, fetcher);
+
+ expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10), id: 'u2' });
+ });
+
+ it('re-attaches loaded history to later revalidations of the same identity', async () => {
+ const window = [message('u2', 10, 'user'), message('a2', 11)];
+ await loadEarlierMessagePage(
+ context,
+ () => window,
+ async () => [message('u1', 1, 'user')],
+ );
+
+ const revalidated = await runMessageListQuery(context, async () => window);
+
+ expect(ids(revalidated)).toEqual(['u1', 'u2', 'a2']);
+ });
+
+ it('drops cached pages when the fresh window slid past the join point', async () => {
+ const window = [message('u2', 10, 'user'), message('a2', 11)];
+ await loadEarlierMessagePage(
+ context,
+ () => window,
+ async () => [message('u1', 1, 'user')],
+ );
+
+ // The window moved forward: u2 (the join point) fell out of it. Merging
+ // would leave an invisible gap, so the transcript collapses to the window.
+ const slidWindow = [message('u3', 20, 'user'), message('a3', 21)];
+ const revalidated = await runMessageListQuery(context, async () => slidWindow);
+
+ expect(revalidated).toBe(slidWindow);
+ });
+
+ it('deduplicates rows the fresh window already contains', async () => {
+ const window = [message('u2', 10, 'user'), message('a2', 11)];
+ await loadEarlierMessagePage(
+ context,
+ () => window,
+ async () => [message('u1', 1, 'user'), message('a1', 2)],
+ );
+
+ // A later window that reaches further back overlaps the cached page.
+ const extendedWindow = [message('a1', 2), message('u2', 10, 'user'), message('a2', 11)];
+ const revalidated = await runMessageListQuery(context, async () => extendedWindow);
+
+ expect(ids(revalidated)).toEqual(['u1', 'a1', 'u2', 'a2']);
+ });
+
+ it('marks the identity exhausted only on an empty page and stops fetching', async () => {
+ const window = [message('u1', 10, 'user')];
+ const fetcher = vi.fn().mockResolvedValue([]);
+
+ const merged = await loadEarlierMessagePage(context, () => window, fetcher);
+
+ expect(merged).toBeUndefined();
+ expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
+
+ await loadEarlierMessagePage(context, () => window, fetcher);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores a second load while one page is in flight', async () => {
+ const window = [message('u2', 10, 'user')];
+ const firstPage = deferred<UIChatMessage[]>();
+ const fetcher = vi.fn().mockReturnValue(firstPage.promise);
+
+ const first = loadEarlierMessagePage(context, () => window, fetcher);
+ const second = await loadEarlierMessagePage(context, () => window, fetcher);
+
+ expect(second).toBeUndefined();
+ expect(fetcher).toHaveBeenCalledTimes(1);
+
+ firstPage.resolve([message('u1', 1, 'user')]);
+ expect(ids(await first)).toEqual(['u1', 'u2']);
+ });
+
+ it('merges the page into the latest transcript, not the one at request time', async () => {
+ let current = [message('u2', 10, 'user')];
+ const page = deferred<UIChatMessage[]>();
+
+ const pending = loadEarlierMessagePage(
+ context,
+ () => current,
+ () => page.promise,
+ );
+ // A stream appends a reply while the page is in flight.
+ current = [message('u2', 10, 'user'), message('a2', 11)];
+ page.resolve([message('u1', 1, 'user')]);
+
+ expect(ids(await pending)).toEqual(['u1', 'u2', 'a2']);
+ });
+
+ it('discards a page whose identity was invalidated while in flight', async () => {
+ const window = [message('u2', 10, 'user')];
+ const page = deferred<UIChatMessage[]>();
+
+ const pending = loadEarlierMessagePage(
+ context,
+ () => window,
+ () => page.promise,
+ );
+ invalidateMessageListClientState(() => true);
+ page.resolve([message('u1', 1, 'user')]);
+
+ expect(await pending).toBeUndefined();
+ const revalidated = await runMessageListQuery(context, async () => window);
+ expect(revalidated).toBe(window);
+ });
+
+ it('skips the merge when the caller no longer has a transcript to extend', async () => {
+ let current: UIChatMessage[] | undefined = [message('u2', 10, 'user')];
+ const page = deferred<UIChatMessage[]>();
+
+ const pending = loadEarlierMessagePage(
+ context,
+ () => current,
+ () => page.promise,
+ );
+ current = undefined;
+ page.resolve([message('u1', 1, 'user')]);
+
+ expect(await pending).toBeUndefined();
+ // The page is still remembered for the next revalidation of this identity.
+ const revalidated = await runMessageListQuery(context, async () => [message('u2', 10, 'user')]);
+ expect(ids(revalidated)).toEqual(['u1', 'u2']);
+ });
+
+ it('clears cached history on invalidation so stale rows cannot resurrect', async () => {
+ const window = [message('u2', 10, 'user')];
+ await loadEarlierMessagePage(
+ context,
+ () => window,
+ async () => [message('u1', 1, 'user')],
+ );
+
+ invalidateMessageListClientState(() => true);
+
+ const revalidated = await runMessageListQuery(context, async () => window);
+ expect(revalidated).toBe(window);
+ });
+
+ it('evicts the least-recently-used identity once the earlier-history cache is full', async () => {
+ const window = [message('u2', 10, 'user')];
+ const oldest = { ...context, topicId: 'topic-evicted' };
+ // Exhaust the first identity, then flood the cache with 30 more.
+ await loadEarlierMessagePage(
+ oldest,
+ () => window,
+ async () => [],
+ );
+ expect(getEarlierHistoryStatus(oldest).exhausted).toBe(true);
+
+ for (let i = 0; i < 30; i++) {
+ await loadEarlierMessagePage(
+ { ...context, topicId: `topic-fill-${i}` },
+ () => window,
+ async () => [message('u1', 1, 'user')],
+ );
+ }
+
+ // The exhausted marker was evicted with the entry: the identity fetches again.
+ expect(getEarlierHistoryStatus(oldest).exhausted).toBe(false);
+ const fetcher = vi.fn().mockResolvedValue([]);
+ await loadEarlierMessagePage(oldest, () => window, fetcher);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+
+ // The most recent identity survives: its cached page still re-attaches.
+ const survivor = { ...context, topicId: 'topic-fill-29' };
+ const revalidated = await runMessageListQuery(survivor, async () => window);
+ expect(ids(revalidated)).toEqual(['u1', 'u2']);
+ });
+});
diff --git a/src/services/message/cache.ts b/src/services/message/cache.ts
index b8244255eb3..9e86abff9d8 100644
--- a/src/services/message/cache.ts
+++ b/src/services/message/cache.ts
@@ -30,6 +30,156 @@ interface MessageListClientState {
const messageListClientStates = new Map<string, MessageListClientState>();
+/**
+ * Client-held pages of history OLDER than the server's newest-first window
+ * (LOBE-13716). The chat read path only ever fetches the newest round-aligned
+ * page; when the user walks back past it, the older pages are fetched once via
+ * a round cursor and kept here so every later revalidation of the same
+ * identity re-merges them instead of collapsing the view back to the window.
+ */
+interface EarlierHistoryState {
+ /**
+ * The oldest mainline row of the live window when history was first
+ * extended — the join point. A fresh window that no longer contains this id
+ * has slid past the cached pages (a gap), so the cache is dropped rather
+ * than merged.
+ */
+ anchorId: string;
+ cacheScope: string;
+ context: CanonicalMessageListContext;
+ /** A `before` page came back empty: the very beginning has been reached. */
+ exhausted: boolean;
+ loading: boolean;
+ /** Ascending rows strictly older than `anchorId`. */
+ messages: UIChatMessage[];
+}
+
+const earlierHistoryStates = new Map<string, EarlierHistoryState>();
+
+/**
+ * Each entry can hold thousands of full message rows, so the cap is much
+ * tighter than `MAX_MESSAGE_LIST_CLIENT_STATES`. Insertion order doubles as
+ * recency: `touchEarlierHistoryState` re-appends on every merge, and pruning
+ * evicts the least-recently-merged identities that are not mid-fetch.
+ */
+const MAX_EARLIER_HISTORY_STATES = 30;
+
+const touchEarlierHistoryState = (identity: string, state: EarlierHistoryState) => {
+ earlierHistoryStates.delete(identity);
+ earlierHistoryStates.set(identity, state);
+};
+
+const pruneEarlierHistoryStates = () => {
+ if (earlierHistoryStates.size <= MAX_EARLIER_HISTORY_STATES) return;
+ for (const [identity, state] of earlierHistoryStates.entries()) {
+ if (earlierHistoryStates.size <= MAX_EARLIER_HISTORY_STATES) return;
+ if (state.loading) continue;
+ earlierHistoryStates.delete(identity);
+ }
+};
+
+/** Synthetic MessageGroup nodes are injected by the query, not DB rows — they
+ * can never serve as a round cursor. */
+const isSyntheticGroupNode = (message: UIChatMessage) =>
+ message.role === 'compressedGroup' || message.role === 'compareGroup';
+
+const byCreatedAtAscending = (a: UIChatMessage, b: UIChatMessage) =>
+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
+
+const mergeEarlierHistory = (identity: string, fresh: UIChatMessage[]): UIChatMessage[] => {
+ const state = earlierHistoryStates.get(identity);
+ if (!state || state.messages.length === 0) return fresh;
+
+ if (!fresh.some((message) => message.id === state.anchorId)) {
+ // The window slid past the join point — merging would hide an invisible
+ // gap in the middle of the transcript. Collapse back to the window; the
+ // user can walk back again from the new boundary.
+ earlierHistoryStates.delete(identity);
+ return fresh;
+ }
+
+ const freshIds = new Set(fresh.map((message) => message.id));
+ const prefix = state.messages.filter((message) => !freshIds.has(message.id));
+ touchEarlierHistoryState(identity, state);
+ // Stable sort: group nodes carried by the fresh window can predate the whole
+ // prefix, and rows inside each list keep their relative order.
+ return [...prefix, ...fresh].sort(byCreatedAtAscending);
+};
+
+export const getEarlierHistoryStatus = (context: MessageListQueryContext) => {
+ const state = earlierHistoryStates.get(getMessageListCacheIdentity(context));
+ return { exhausted: state?.exhausted ?? false, loading: state?.loading ?? false };
+};
+
+/**
+ * Fetch one round-aligned page of history older than the oldest mainline row
+ * of `getCurrentMessages()`, remember it for future revalidation merges, and
+ * return the full merged transcript — or `undefined` when there is nothing to
+ * apply (no cursor, already loading, the beginning was reached, or the request
+ * went stale while in flight).
+ *
+ * `getCurrentMessages` is read twice: once for the cursor, and again AFTER the
+ * page arrives so the merge lands on the latest transcript rather than a
+ * snapshot taken before the await (a stream or an edit may have changed it
+ * meanwhile). Return `undefined` from it to skip the merge, e.g. after the
+ * caller switched conversations; the page itself is still cached.
+ */
+export const loadEarlierMessagePage = async (
+ context: MessageListQueryContext,
+ getCurrentMessages: () => UIChatMessage[] | undefined,
+ fetcher: (before: { createdAt: Date; id: string }) => Promise<UIChatMessage[]>,
+): Promise<UIChatMessage[] | undefined> => {
+ const identity = getMessageListCacheIdentity(context);
+ const existing = earlierHistoryStates.get(identity);
+ if (existing?.exhausted || existing?.loading) return undefined;
+
+ const cursor = getCurrentMessages()?.find((message) => !isSyntheticGroupNode(message));
+ if (!cursor) return undefined;
+
+ const state: EarlierHistoryState = existing ?? {
+ anchorId: cursor.id,
+ cacheScope: getCacheScope(),
+ context: normalizeMessageListQueryContext(context),
+ exhausted: false,
+ loading: false,
+ messages: [],
+ };
+ state.loading = true;
+ touchEarlierHistoryState(identity, state);
+ pruneEarlierHistoryStates();
+
+ try {
+ const page = await fetcher({ createdAt: new Date(cursor.createdAt), id: cursor.id });
+
+ // An invalidation (edit/delete refresh) dropped this identity while the
+ // page was in flight: its rows may be exactly what changed, so discard it.
+ if (earlierHistoryStates.get(identity) !== state) return undefined;
+
+ if (page.length === 0) {
+ // `length < pageSize` is NOT a reliable end signal — the round-start trim
+ // legitimately shortens full pages — so only an empty page marks the top.
+ state.exhausted = true;
+ return undefined;
+ }
+
+ const pageIds = new Set(page.map((message) => message.id));
+ state.messages = [
+ ...page,
+ ...state.messages.filter((message) => !pageIds.has(message.id)),
+ ].sort(byCreatedAtAscending);
+
+ const latest = getCurrentMessages();
+ if (!latest) return undefined;
+
+ const merged = mergeEarlierHistory(identity, latest);
+ // No join point in the latest transcript (it slid or was replaced): there
+ // is nothing to prepend, and returning `latest` would only echo it back.
+ return merged === latest ? undefined : merged;
+ } finally {
+ state.loading = false;
+ }
+};
+
export const messageListKey = (context: MessageListQueryContext) => messageKeys.list(context);
export const getMessageListCacheIdentity = (
@@ -139,7 +289,10 @@ const startCurrentGenerationQuery = (
state.verifiedAt = Date.now();
touchState(state);
pruneClientStates();
- return messages;
+ // Re-attach client-held older history (loaded via round cursor) so a
+ // revalidation doesn't collapse an extended transcript back to the
+ // newest-first window.
+ return mergeEarlierHistory(state.identity, messages);
})
.finally(() => {
state.activeRequestGenerations.delete(requestGeneration);
@@ -185,8 +338,18 @@ export const invalidateMessageListClientState = (
state.generation += 1;
state.verifiedAt = undefined;
}
+
+ // A force refresh signals the persisted rows may have changed (edits or
+ // deletes can target rounds inside the extended range). Cached older pages
+ // could resurrect stale rows through the merge, so drop them; the user can
+ // walk back again from the refreshed window.
+ for (const [identity, state] of earlierHistoryStates.entries()) {
+ if (state.cacheScope !== cacheScope || !predicate(state.context)) continue;
+ earlierHistoryStates.delete(identity);
+ }
};
export const clearMessageListClientCacheState = () => {
messageListClientStates.clear();
+ earlierHistoryStates.clear();
};
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 6d088d43ea7..52868ab70d0 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -216,6 +216,30 @@ export class MessageService {
>;
};
+ /**
+ * Load one round-aligned page of history strictly OLDER than `before` (the
+ * oldest already-loaded mainline message). Intentionally outside the
+ * `runMessageListQuery` client-cache policy: older pages are additive and
+ * merged by the earlier-history layer in `services/message/cache`.
+ */
+ getEarlierMessages = async (
+ params: MessageReadQueryContext,
+ before: { createdAt: Date; id: string },
+ ): Promise<UIChatMessage[]> => {
+ // Agent-share pages read through `shareChat.getMessages`, which has no
+ // round cursor. An empty page marks the history exhausted, so the shared
+ // view keeps its current window instead of hitting the authed endpoint.
+ if (params.agentShareId) return [];
+
+ const data = await lambdaClient.message.getMessages.query({
+ ...params,
+ before,
+ includeFileWorks: true,
+ });
+
+ return data as unknown as UIChatMessage[];
+ };
+
diagnoseTopic = async (params: { agentId?: string | null; topicId: string }) => {
return lambdaClient.message.diagnoseTopic.query(params);
};