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): page topic history by round cursor so a fully loaded topic never fetches upward (#20152)

Arvin Xu25fb783eb1c5
diff --git a/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
index 14bc8855466..fa17ba81220 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
@@ -2,6 +2,7 @@
import { type LobeChatDatabase } from '@lobechat/database';
import { messages, sessions, topics } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
+import { ChatErrorType } from '@lobechat/types';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -796,6 +797,135 @@ describe('Message Router Integration Tests', () => {
});
});
+ describe('getMessagesByCursor', () => {
+ const seedTwoRounds = async (topicId: string, workspaceId?: string) => {
+ await serverDB.insert(messages).values(
+ [
+ ['cur-u1', 'user', '2024-01-01T00:00:00.000Z'],
+ ['cur-a1', 'assistant', '2024-01-01T00:00:01.000Z'],
+ ['cur-u2', 'user', '2024-01-01T00:00:02.000Z'],
+ ['cur-a2', 'assistant', '2024-01-01T00:00:03.000Z'],
+ ].map(([id, role, at]) => ({
+ content: id,
+ createdAt: new Date(at),
+ id,
+ role,
+ topicId,
+ userId,
+ workspaceId,
+ })),
+ );
+ };
+
+ it('pages rounds newest-first via nextCursor', async () => {
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ title: 'Cursor Topic', userId })
+ .returning();
+ await seedTwoRounds(topic.id);
+
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const newest = await caller.getMessagesByCursor({ roundLimit: 1, topicId: topic.id });
+ expect(newest.messages.map((m) => m.id)).toEqual(['cur-u2', 'cur-a2']);
+ expect(newest.hasMore).toBe(true);
+
+ const older = await caller.getMessagesByCursor({
+ cursor: newest.nextCursor,
+ roundLimit: 1,
+ topicId: topic.id,
+ });
+ expect(older.messages.map((m) => m.id)).toEqual(['cur-u1', 'cur-a1']);
+ expect(older.hasMore).toBe(false);
+ expect(older.nextCursor).toBeNull();
+ });
+
+ it('requires topicId when no topicShareId is given', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ await expect(caller.getMessagesByCursor({})).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ });
+
+ it.each([
+ { countBudget: 2001 },
+ { countBudget: -1 },
+ { countBudget: 1.5 },
+ { roundLimit: 0 },
+ { roundLimit: 1001 },
+ ])('rejects an out-of-range scan budget %o', async (bounds) => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ await expect(
+ caller.getMessagesByCursor({ ...bounds, topicId: testTopicId }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it.each([
+ { createdAt: 'not-a-date', id: 'cur-u2' },
+ { createdAt: '2024-01-01 00:00:02', id: 'cur-u2' },
+ { createdAt: '2024-01-01T00:00:02.000000Z', id: '' },
+ ])('rejects a malformed cursor %o as BAD_REQUEST', async (cursor) => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ await expect(
+ caller.getMessagesByCursor({ cursor, topicId: testTopicId }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('accepts the microsecond cursor format that nextCursor emits', async () => {
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ title: 'Cursor Format Topic', userId })
+ .returning();
+ await seedTwoRounds(topic.id);
+
+ const caller = messageRouter.createCaller(createTestContext(userId));
+ const newest = await caller.getMessagesByCursor({ roundLimit: 1, topicId: topic.id });
+ expect(newest.nextCursor?.createdAt).toMatch(/\.\d{6}Z$/);
+
+ const older = await caller.getMessagesByCursor({
+ cursor: newest.nextCursor,
+ roundLimit: 1,
+ topicId: topic.id,
+ });
+ expect(older.messages.map((m) => m.id)).toEqual(['cur-u1', 'cur-a1']);
+ });
+
+ it('serves a link share from topicShareId alone, with visitor-safe errors', async () => {
+ const { topicShares } = await import('@/database/schemas');
+
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ title: 'Shared Cursor Topic', userId })
+ .returning();
+ await seedTwoRounds(topic.id);
+ await serverDB
+ .update(messages)
+ .set({ error: { body: { secret: 'provider-key', traceId: 't1' }, type: 'InvalidAPIKey' } })
+ .where(eq(messages.id, 'cur-a2'));
+
+ const [share] = await serverDB
+ .insert(topicShares)
+ .values({ topicId: topic.id, userId, visibility: 'link' })
+ .returning();
+
+ const visitorId = await createTestUser(serverDB);
+ const caller = messageRouter.createCaller(createTestContext(visitorId));
+
+ const page = await caller.getMessagesByCursor({ topicShareId: share.id });
+
+ expect(page.messages.map((m) => m.id)).toEqual(['cur-u1', 'cur-a1', 'cur-u2', 'cur-a2']);
+ expect(page.messages.find((m) => m.id === 'cur-a2')?.error).toEqual({
+ body: { traceId: 't1' },
+ type: ChatErrorType.InternalServerError,
+ });
+
+ await cleanupTestUser(serverDB, visitorId);
+ });
+ });
+
describe('removeMessages', () => {
it('should remove multiple messages', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 6adee7558e2..50dfa9b2eaf 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -40,6 +40,15 @@ import { basicContextSchema } from './_schema/context';
const { logTiming, runTimedStage } = createTimingHelpers('lobe-server:chat:lobehub:timing');
+/**
+ * Upper bound on rounds per `getMessagesByCursor` page. The scan itself is bounded
+ * by `countBudget`; this only lets a caller ask for "as many whole rounds as the
+ * budget holds" (the chat window) without an arbitrary value.
+ */
+const MAX_CURSOR_ROUND_LIMIT = 1000;
+/** Upper bound on rows scanned per `getMessagesByCursor` page (the model's default cap). */
+const MAX_CURSOR_COUNT_BUDGET = 2000;
+
/** Ctx slice consumed by the conversation General-access guards. */
const guardCtx = (ctx: {
serverDB: Parameters<typeof assertCanUseMessageTargets>[0]['db'];
@@ -522,6 +531,105 @@ export const messageRouter = router({
return new MessageService(ctx.serverDB, ctx.userId, wsId).projectToolPayloads(messages);
}),
+ /**
+ * Round-boundary cursor pagination for a topic's mainline conversation. Used by
+ * callers that only DISPLAY history (server-runtime / hetero); legacy client
+ * mode keeps using `getMessages` (full fetch) because it resends the session.
+ * Omit `cursor` for the newest page; pass a prior `nextCursor` to load older.
+ */
+ getMessagesByCursor: publicProcedure
+ .use(cloudWorkspaceAuth)
+ .use(serverDatabase)
+ .input(
+ z.object({
+ agentId: z.string().nullish(),
+ // Bounded at the API boundary: the model turns this into a row LIMIT, so
+ // an unbounded value would let any caller (incl. anonymous share
+ // visitors) force an arbitrarily large scan of a long topic.
+ countBudget: z.number().int().positive().max(MAX_CURSOR_COUNT_BUDGET).optional(),
+ // `createdAt` is cast to `::timestamptz` in SQL, so reject anything that
+ // isn't the UTC ISO timestamp `nextCursor` emits (up to microseconds)
+ // here β€” otherwise malformed input surfaces as a Postgres 500.
+ cursor: z.object({ createdAt: z.string().datetime(), id: z.string().min(1) }).nullish(),
+ groupId: z.string().nullish(),
+ // Same opt-in as `getMessages`: only clients that ship the `file` work
+ // descriptor ask for `file` work summaries.
+ includeFileWorks: z.boolean().optional(),
+ roundLimit: z.number().int().positive().max(MAX_CURSOR_ROUND_LIMIT).optional(),
+ sessionId: z.string().nullish(),
+ skipWorks: z.boolean().optional(),
+ // Optional so share-link callers can page with only `topicShareId`; the
+ // share record supplies the authoritative topic. Required otherwise.
+ topicId: z.string().nullish(),
+ topicShareId: z.string().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const { topicShareId, topicId, ...queryParams } = input;
+
+ // Public access via topicShareId
+ if (topicShareId) {
+ const share = await TopicShareModel.findByShareIdWithAccessCheck(
+ ctx.serverDB,
+ topicShareId,
+ ctx.userId ?? undefined,
+ );
+
+ // Same scoping as `getMessages`: workspace shares carry their workspaceId,
+ // and the classic share link is a creator topic (no visitor scope).
+ const shareWorkspaceId = share.workspaceId ?? undefined;
+ const messageModel = new MessageModel(ctx.serverDB, share.ownerId, shareWorkspaceId);
+ const fileService = new FileService(ctx.serverDB, share.ownerId, shareWorkspaceId);
+
+ const page = await messageModel.queryTopicMessagesByCursor(
+ // Force skipWorks: Work summaries join LIVE task/version state, so serving
+ // them here would leak post-share mutations to anonymous visitors.
+ { ...queryParams, skipWorks: true, topicId: share.topicId },
+ {
+ postProcessUrl: (path, file) =>
+ fileService.getFileAccessUrl({ id: file.id, url: path }),
+ },
+ );
+
+ return { ...page, messages: projectSharedTopicMessages(page.messages) };
+ }
+
+ // Authenticated access - require userId
+ if (!ctx.userId) {
+ throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Authentication required' });
+ }
+
+ if (!topicId) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'topicId is required' });
+ }
+
+ // Same General-access guard `getMessages` applies to a raw client topicId.
+ await assertCanUseTopicTargets(
+ guardCtx({ serverDB: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId }),
+ [topicId],
+ );
+
+ const wsId = ctx.workspaceId ?? undefined;
+ const messageModel = new MessageModel(ctx.serverDB, ctx.userId, wsId);
+ const fileService = new FileService(ctx.serverDB, ctx.userId, wsId);
+
+ const page = await messageModel.queryTopicMessagesByCursor(
+ { ...queryParams, topicId },
+ {
+ postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
+ },
+ );
+
+ // Reads through its own `MessageModel`, so apply the tool view-model step
+ // explicitly β€” same as `getMessages`.
+ return {
+ ...page,
+ messages: await new MessageService(ctx.serverDB, ctx.userId, wsId).projectToolPayloads(
+ page.messages,
+ ),
+ };
+ }),
+
rankModels: messageProcedure.query(async ({ ctx }) => {
return ctx.messageModel.rankModels();
}),
diff --git a/packages/conversation-flow/src/__tests__/deepChain.test.ts b/packages/conversation-flow/src/__tests__/deepChain.test.ts
new file mode 100644
index 00000000000..739eaac891b
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/deepChain.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../parse';
+import type { Message } from '../types';
+
+/**
+ * A long topic is one parentId chain: every step hangs under the previous one.
+ * Paging older history in makes these chains thousands of rows deep, so no
+ * phase of `parse` may recurse once per message.
+ */
+const buildChain = (rounds: number, stepsPerRound: number, withTools = false): Message[] => {
+ const messages: Message[] = [];
+ let parentId: string | undefined;
+ let t = 0;
+ for (let r = 0; r < rounds; r += 1) {
+ const userId = `u${r}`;
+ messages.push({
+ content: `q${r}`,
+ createdAt: ++t,
+ id: userId,
+ meta: {},
+ parentId,
+ role: 'user',
+ updatedAt: t,
+ } as Message);
+ parentId = userId;
+ for (let s = 0; s < stepsPerRound; s += 1) {
+ const id = `a${r}_${s}`;
+ const toolCallId = `call_${r}_${s}`;
+ messages.push({
+ content: `a${r}.${s}`,
+ createdAt: ++t,
+ id,
+ meta: {},
+ parentId,
+ role: 'assistant',
+ tools: withTools
+ ? [
+ {
+ apiName: 'run',
+ arguments: '{}',
+ id: toolCallId,
+ identifier: 'demo',
+ type: 'default',
+ },
+ ]
+ : undefined,
+ updatedAt: t,
+ } as Message);
+ parentId = id;
+ if (withTools) {
+ const toolId = `t${r}_${s}`;
+ messages.push({
+ content: 'ok',
+ createdAt: ++t,
+ id: toolId,
+ meta: {},
+ parentId: id,
+ role: 'tool',
+ tool_call_id: toolCallId,
+ updatedAt: t,
+ } as Message);
+ parentId = toolId;
+ }
+ }
+ }
+ return messages;
+};
+
+// These assert stack depth, not speed: parse still rescans the transcript per
+// chain step, so a loaded parallel run can take several seconds here.
+describe('parse on deep message chains', { timeout: 30_000 }, () => {
+ // The recursive walk overflowed Node's stack from ~2,000 plain / ~3,000
+ // tool-call messages; browsers hit it near 1,200 inside a React render.
+ it('parses a 4,000-message plain chain without overflowing the stack', () => {
+ const messages = buildChain(200, 19);
+
+ const result = parse(messages);
+
+ expect(result.flatList.at(0)?.id).toBe('u0');
+ expect(result.flatList.at(-1)?.id).toBe('a199_18');
+ expect(result.flatList.filter((m) => m.role === 'user')).toHaveLength(200);
+ expect(result.contextTree.filter((node) => node.id.startsWith('u'))).toHaveLength(200);
+ });
+
+ it('parses a 4,000-message tool-call chain without overflowing the stack', () => {
+ const messages = buildChain(200, 10, true);
+
+ const result = parse(messages);
+
+ // Each round folds into one assistant group after its user message.
+ expect(result.flatList.map((m) => m.role)).toEqual(
+ Array.from({ length: 200 }, () => ['user', 'assistantGroup']).flat(),
+ );
+ expect(result.flatList.at(-1)?.children).toHaveLength(10);
+ });
+});
diff --git a/packages/conversation-flow/src/structuring.ts b/packages/conversation-flow/src/structuring.ts
index c970272d36e..24ef3ecc361 100644
--- a/packages/conversation-flow/src/structuring.ts
+++ b/packages/conversation-flow/src/structuring.ts
@@ -11,28 +11,24 @@ import type { HelperMaps, IdNode } from './types';
export function buildIdTree(helperMaps: HelperMaps): IdNode[] {
const { childrenMap, messageMap } = helperMaps;
- // Build tree recursively starting from root messages (parentId = null)
- const buildTree = (messageId: string): IdNode => {
- const childIds = childrenMap.get(messageId) ?? [];
-
- // Filter children to only include those in main flow (not in threads)
- const mainFlowChildIds = childIds.filter((childId) => {
+ const mainFlowChildIds = (parentId: string | null) =>
+ (childrenMap.get(parentId) ?? []).filter((childId) => {
const child = messageMap.get(childId);
return child && !child.threadId;
});
- return {
- children: mainFlowChildIds.map((childId) => buildTree(childId)),
- id: messageId,
- };
- };
-
- // Get root message IDs (messages with parentId = null and no threadId)
- const rootIds = childrenMap.get(null) ?? [];
- const mainFlowRootIds = rootIds.filter((id) => {
- const msg = messageMap.get(id);
- return msg && !msg.threadId;
- });
+ // Built with an explicit stack: a long topic is one parent chain thousands
+ // of messages deep, which a per-message recursion would overflow.
+ const roots: IdNode[] = mainFlowChildIds(null).map((id) => ({ children: [], id }));
+ const stack = [...roots];
+ while (stack.length > 0) {
+ const node = stack.pop()!;
+ for (const childId of mainFlowChildIds(node.id)) {
+ const child: IdNode = { children: [], id: childId };
+ node.children.push(child);
+ stack.push(child);
+ }
+ }
- return mainFlowRootIds.map((rootId) => buildTree(rootId));
+ return roots;
}
diff --git a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
index cab3b0067c8..1108649fb18 100644
--- a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
+++ b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
@@ -45,9 +45,25 @@ export class ContextTreeBuilder {
}
/**
- * Transform a single IdNode and append to contextTree array
+ * Transform an IdNode and everything it continues into, appending to contextTree
*/
private transformToLinear(idNode: IdNode, contextTree: ContextNode[]): void {
+ // A long topic is one parent chain thousands of messages deep. Each step
+ // hands back the nodes it continues with instead of recursing into them;
+ // pushing them in reverse keeps the original depth-first output order.
+ const stack: IdNode[] = [idNode];
+ while (stack.length > 0) {
+ const next: IdNode[] = [];
+ this.transformStep(stack.pop()!, contextTree, next);
+ for (let i = next.length - 1; i >= 0; i -= 1) stack.push(next[i]);
+ }
+ }
+
+ /**
+ * Transform a single IdNode into contextTree and collect, in output order,
+ * the IdNodes the walk continues with.
+ */
+ private transformStep(idNode: IdNode, contextTree: ContextNode[], next: IdNode[]): void {
const message = this.messageMap.get(idNode.id);
if (!message) return;
@@ -68,7 +84,7 @@ export class ContextTreeBuilder {
(child) => child.id === compareNode.activeColumnId,
);
if (activeColumnIdNode && activeColumnIdNode.children.length > 0) {
- this.transformToLinear(activeColumnIdNode.children[0], contextTree);
+ next.push(activeColumnIdNode.children[0]);
}
}
return;
@@ -89,7 +105,7 @@ export class ContextTreeBuilder {
(child) => child.id === compareNode.activeColumnId,
);
if (activeColumnIdNode && activeColumnIdNode.children.length > 0) {
- this.transformToLinear(activeColumnIdNode.children[0], contextTree);
+ next.push(activeColumnIdNode.children[0]);
}
}
return;
@@ -111,7 +127,7 @@ export class ContextTreeBuilder {
// applies the same all-member continuation).
for (const child of idNode.children) {
if (child.children.length > 0) {
- this.transformToLinear(child.children[0], contextTree);
+ next.push(child.children[0]);
}
}
return;
@@ -129,7 +145,7 @@ export class ContextTreeBuilder {
});
for (const nonTaskChild of nonTaskChildren) {
- this.transformToLinear(nonTaskChild, contextTree);
+ next.push(nonTaskChild);
}
// Also check for children of task messages (e.g., summary as child of last task)
@@ -142,7 +158,7 @@ export class ContextTreeBuilder {
for (const taskGrandchild of taskChild.children) {
const taskGrandchildMsg = this.messageMap.get(taskGrandchild.id);
if (taskGrandchildMsg && taskGrandchildMsg.role !== 'task') {
- this.transformToLinear(taskGrandchild, contextTree);
+ next.push(taskGrandchild);
}
}
}
@@ -157,7 +173,7 @@ export class ContextTreeBuilder {
// Find the next message after tools
const nextMessage = this.messageCollector.findNextAfterTools(message, idNode);
if (nextMessage) {
- this.transformToLinear(nextMessage, contextTree);
+ next.push(nextMessage);
}
return;
}
@@ -188,7 +204,7 @@ export class ContextTreeBuilder {
// Continue with single child
if (idNode.children.length === 1) {
- this.transformToLinear(idNode.children[0], contextTree);
+ next.push(idNode.children[0]);
}
}
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 35269c4bdeb..64ca0cb5e04 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -15,11 +15,44 @@ import type { MessageTransformer } from './MessageTransformer';
const isSupervisorMessage = (message: Message | undefined): boolean =>
message?.metadata?.orchestrationRole === 'supervisor' || !!message?.metadata?.isSupervisor;
+/**
+ * One step of the flat-list walk. The walk follows parent chains that are
+ * thousands of messages deep on long topics, so instead of recursing, each
+ * step yields the sub-walk it would have called and `runFlatListWork` resumes
+ * it on an explicit stack. Statement order is unchanged: a yielded sub-walk
+ * finishes before the step that yielded it continues.
+ */
+interface FlatListWork extends Generator<FlatListWork, void, undefined> {}
+
+const runFlatListWork = (root: FlatListWork): void => {
+ const stack: FlatListWork[] = [root];
+ let pendingError: { error: unknown } | undefined;
+
+ while (stack.length > 0) {
+ const current = stack.at(-1)!;
+ let step: IteratorResult<FlatListWork, void>;
+ try {
+ // Rethrow a finished sub-walk's error inside its caller so the caller's
+ // `finally` blocks run exactly as they would around a direct call.
+ step = pendingError ? current.throw(pendingError.error) : current.next();
+ pendingError = undefined;
+ } catch (error) {
+ stack.pop();
+ if (stack.length === 0) throw error;
+ pendingError = { error };
+ continue;
+ }
+
+ if (step.done) stack.pop();
+ else stack.push(step.value);
+ }
+};
+
/**
* FlatListBuilder - Builds flat message list following the active path
*
* Handles:
- * 1. Recursive traversal following active branches
+ * 1. Traversal following active branches (explicit stack, see runFlatListWork)
* 2. Creating virtual messages for Compare and AssistantGroup
* 3. Processing different message types with priority
*/
@@ -80,7 +113,9 @@ export class FlatListBuilder {
}
// Build the active path by traversing from root
- this.buildFlatListRecursive(rootParentId, flatList, processedIds, scopedMessages);
+ runFlatListWork(
+ this.buildFlatListRecursive(rootParentId, flatList, processedIds, scopedMessages),
+ );
// Assistant groups must be assembled before ordering because their members
// are discovered through recursive tool-result chains. That traversal is
@@ -97,12 +132,12 @@ export class FlatListBuilder {
/**
* Recursively build flatList following the active path
*/
- private buildFlatListRecursive(
+ private *buildFlatListRecursive(
parentId: string | null,
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
- ): void {
+ ): FlatListWork {
const children = this.childIdsInScope(parentId);
// Broadcast councils now render in-bubble (a `council` block inside the
@@ -150,11 +185,21 @@ export class FlatListBuilder {
nonTaskChild.tools &&
nonTaskChild.tools.length > 0
) {
- this.processAssistantGroup(nonTaskChild, flatList, processedIds, allMessages);
+ yield this.processAssistantGroup(
+ nonTaskChild,
+ flatList,
+ processedIds,
+ allMessages,
+ );
} else {
flatList.push(nonTaskChild);
processedIds.add(nonTaskChildId);
- this.buildFlatListRecursive(nonTaskChildId, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(
+ nonTaskChildId,
+ flatList,
+ processedIds,
+ allMessages,
+ );
}
}
}
@@ -173,7 +218,12 @@ export class FlatListBuilder {
taskGrandchild.tools &&
taskGrandchild.tools.length > 0
) {
- this.processAssistantGroup(taskGrandchild, flatList, processedIds, allMessages);
+ yield this.processAssistantGroup(
+ taskGrandchild,
+ flatList,
+ processedIds,
+ allMessages,
+ );
} else if (
// Check if it's a supervisor message without tools (content-only)
taskGrandchild.role === 'assistant' &&
@@ -183,7 +233,7 @@ export class FlatListBuilder {
const supervisorMessage = this.createSupervisorContentMessage(taskGrandchild);
flatList.push(supervisorMessage);
processedIds.add(taskGrandchildId);
- this.buildFlatListRecursive(
+ yield this.buildFlatListRecursive(
taskGrandchildId,
flatList,
processedIds,
@@ -192,7 +242,7 @@ export class FlatListBuilder {
} else {
flatList.push(taskGrandchild);
processedIds.add(taskGrandchildId);
- this.buildFlatListRecursive(
+ yield this.buildFlatListRecursive(
taskGrandchildId,
flatList,
processedIds,
@@ -219,7 +269,7 @@ export class FlatListBuilder {
// and therefore do not render as standalone bubbles.
if (message.metadata?.agentDispatch?.visibility === 'internal') {
processedIds.add(message.id);
- this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
continue;
}
@@ -238,7 +288,7 @@ export class FlatListBuilder {
// Continue with active column's children (if any)
if ((compareMessage as any).activeColumnId) {
- this.buildFlatListRecursive(
+ yield this.buildFlatListRecursive(
(compareMessage as any).activeColumnId,
flatList,
processedIds,
@@ -315,11 +365,11 @@ export class FlatListBuilder {
// Surface the supervisor's post-council reply (attached to one member).
if (council) {
for (const memberId of council.memberIds) {
- this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);
}
}
- this.continueAfterAssistantGroup(
+ yield this.continueAfterAssistantGroup(
assistantChain,
allToolMessages,
flatList,
@@ -341,7 +391,7 @@ export class FlatListBuilder {
processedIds.add(message.id);
// Continue with children
- this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
continue;
}
@@ -366,7 +416,7 @@ export class FlatListBuilder {
// Continue with active column's children (if any)
if ((compareMessage as any).activeColumnId) {
- this.buildFlatListRecursive(
+ yield this.buildFlatListRecursive(
(compareMessage as any).activeColumnId,
flatList,
processedIds,
@@ -437,7 +487,7 @@ export class FlatListBuilder {
assistantChain.forEach((m) => processedIds.add(m.id));
allToolMessages.forEach((m) => processedIds.add(m.id));
- this.continueAfterAssistantGroup(
+ yield this.continueAfterAssistantGroup(
assistantChain,
allToolMessages,
flatList,
@@ -455,7 +505,7 @@ export class FlatListBuilder {
processedIds.add(activeBranchId);
// Continue with active branch's children
- this.buildFlatListRecursive(activeBranchId, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(activeBranchId, flatList, processedIds, allMessages);
}
}
continue;
@@ -497,7 +547,7 @@ export class FlatListBuilder {
processedIds.add(activeBranchId);
// Continue with active branch's children
- this.buildFlatListRecursive(activeBranchId, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(activeBranchId, flatList, processedIds, allMessages);
}
continue;
}
@@ -507,7 +557,7 @@ export class FlatListBuilder {
processedIds.add(message.id);
// Continue with children
- this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
}
}
@@ -515,12 +565,12 @@ export class FlatListBuilder {
* Process an assistant message with tools into an AssistantGroup
* Extracted to avoid code duplication in task children handling
*/
- private processAssistantGroup(
+ private *processAssistantGroup(
message: Message,
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
- ): void {
+ ): FlatListWork {
// Collect the entire assistant group chain
const assistantChain: Message[] = [];
const allToolMessages: Message[] = [];
@@ -552,11 +602,11 @@ export class FlatListBuilder {
if (council) {
for (const memberId of council.memberIds) {
- this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);
}
}
- this.continueAfterAssistantGroup(
+ yield this.continueAfterAssistantGroup(
assistantChain,
allToolMessages,
flatList,
@@ -565,13 +615,13 @@ export class FlatListBuilder {
);
}
- private continueAfterAssistantGroup(
+ private *continueAfterAssistantGroup(
assistantChain: Message[],
allToolMessages: Message[],
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
- ): void {
+ ): FlatListWork {
const lastAssistant = assistantChain.at(-1);
if (lastAssistant) {
this.suppressInactiveExplicitContinuations(lastAssistant, allToolMessages, processedIds);
@@ -587,11 +637,16 @@ export class FlatListBuilder {
if (!nextContinuation) break;
if (this.shouldDrainParentContinuations(nextContinuation.parentId, processedIds)) {
- this.buildFlatListRecursive(nextContinuation.parentId, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(
+ nextContinuation.parentId,
+ flatList,
+ processedIds,
+ allMessages,
+ );
continue;
}
- this.buildFlatListRecursiveForChild(
+ yield this.buildFlatListRecursiveForChild(
nextContinuation.parentId,
nextContinuation.child.id,
flatList,
@@ -600,7 +655,12 @@ export class FlatListBuilder {
);
}
- this.continueInterruptedAssistantGroup(assistantChain, flatList, processedIds, allMessages);
+ yield this.continueInterruptedAssistantGroup(
+ assistantChain,
+ flatList,
+ processedIds,
+ allMessages,
+ );
}
/**
@@ -610,12 +670,12 @@ export class FlatListBuilder {
* Recover that user continuation without exposing regenerated assistant
* branches or overriding an explicit branch selection.
*/
- private continueInterruptedAssistantGroup(
+ private *continueInterruptedAssistantGroup(
assistantChain: Message[],
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
- ): void {
+ ): FlatListWork {
const tail = assistantChain.at(-1);
if (!tail) return;
@@ -641,7 +701,7 @@ export class FlatListBuilder {
);
// Explicit indices use all non-tool siblings, not only interruptions.
if (activeId && interruptions.includes(activeId)) {
- this.buildFlatListRecursiveForChild(
+ yield this.buildFlatListRecursiveForChild(
assistant.id,
activeId,
flatList,
@@ -748,18 +808,18 @@ export class FlatListBuilder {
return { memberIds, members: (councilVirtual as { members?: Message[] }).members ?? [] };
}
- private buildFlatListRecursiveForChild(
+ private *buildFlatListRecursiveForChild(
parentId: string,
childId: string,
flatList: Message[],
processedIds: Set<string>,
allMessages: Message[],
- ): void {
+ ): FlatListWork {
const childIds = this.childrenMap.get(parentId) ?? [];
this.childrenMap.set(parentId, [childId]);
try {
- this.buildFlatListRecursive(parentId, flatList, processedIds, allMessages);
+ yield this.buildFlatListRecursive(parentId, flatList, processedIds, allMessages);
} finally {
this.childrenMap.set(parentId, childIds);
}
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index 9c0171034bc..bf74a8461cb 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -175,9 +175,11 @@ export class MessageCollector {
}
/**
- * Recursively collect the entire assistant chain
+ * Collect the entire assistant chain
* (assistant -> tools -> assistant -> tools -> ...)
* Only collects messages from the SAME agent (matching agentId)
+ *
+ * Walked iteratively: a long run is one chain thousands of steps deep.
*/
collectAssistantChain(
currentAssistant: Message,
@@ -186,10 +188,33 @@ export class MessageCollector {
allToolMessages: Message[],
processedIds: Set<string>,
): void {
+ let current: Message | undefined = currentAssistant;
+ while (current) {
+ current = this.collectAssistantChainStep(
+ current,
+ allMessages,
+ assistantChain,
+ allToolMessages,
+ processedIds,
+ );
+ }
+ }
+
+ /**
+ * Append one tool-using step (plus any toolless steps after it) to the chain
+ * and return the next tool-using assistant to continue with.
+ */
+ private collectAssistantChainStep(
+ currentAssistant: Message,
+ allMessages: Message[],
+ assistantChain: Message[],
+ allToolMessages: Message[],
+ processedIds: Set<string>,
+ ): Message | undefined {
if (processedIds.has(currentAssistant.id)) return;
// Mark visited up front so duplicated tool_call_ids (the same tool result
- // reachable from multiple assistants) can't recurse forever.
+ // reachable from multiple assistants) can't loop forever.
processedIds.add(currentAssistant.id);
// Add current assistant to chain
@@ -214,17 +239,8 @@ export class MessageCollector {
);
if (!continuation) return;
- if (continuation.tools && continuation.tools.length > 0) {
- // Continue the chain (recursion marks it processed at the top)
- this.collectAssistantChain(
- continuation,
- allMessages,
- assistantChain,
- allToolMessages,
- processedIds,
- );
- return;
- }
+ // Continue the chain (the next step marks it processed at the top)
+ if (continuation.tools && continuation.tools.length > 0) return continuation;
// Toolless continuations are still part of the same hetero-agent run. The
// model can emit several prose-only progress updates before the next tool
@@ -247,15 +263,7 @@ export class MessageCollector {
);
}
- if (toollessContinuation) {
- this.collectAssistantChain(
- toollessContinuation,
- allMessages,
- assistantChain,
- allToolMessages,
- processedIds,
- );
- }
+ return toollessContinuation;
}
/**
@@ -486,7 +494,7 @@ export class MessageCollector {
}
/**
- * Recursively collect assistant messages for an AssistantGroup (contextTree version)
+ * Collect assistant messages for an AssistantGroup (contextTree version)
* Only collects messages from the SAME agent (matching agentId)
*/
collectAssistantGroupMessages(
@@ -498,6 +506,24 @@ export class MessageCollector {
// Get the agentId of the first assistant in the group (the group owner)
const agentId = groupAgentId ?? message.agentId;
+ // Walked iteratively: a group's chain can be thousands of steps long.
+ let currentMessage: Message | undefined = message;
+ let currentNode: IdNode | undefined = idNode;
+ while (currentMessage && currentNode) {
+ currentNode = this.collectAssistantGroupStep(currentMessage, currentNode, children, agentId);
+ currentMessage = currentNode ? this.messageMap.get(currentNode.id) : undefined;
+ }
+ }
+
+ /**
+ * Append one assistant step to the group and return the next step's IdNode.
+ */
+ private collectAssistantGroupStep(
+ message: Message,
+ idNode: IdNode,
+ children: ContextNode[],
+ agentId: string | undefined,
+ ): IdNode | undefined {
// Get tool message IDs if this assistant has tools
const toolIds = idNode.children
.filter((child) => {
@@ -517,11 +543,7 @@ export class MessageCollector {
children.push(messageNode);
// Find the next step's assistant (dual-form aware, see findChainContinuationNode)
- const nextNode = this.findChainContinuationNode(idNode, agentId);
- if (nextNode) {
- const nextMsg = this.messageMap.get(nextNode.id)!;
- this.collectAssistantGroupMessages(nextMsg, nextNode, children, agentId);
- }
+ return this.findChainContinuationNode(idNode, agentId);
}
/**
@@ -743,8 +765,14 @@ export class MessageCollector {
* continuation or a direct non-tool continuation in the current storage form.
*/
private findLastAssistantNodeInGroup(idNode: IdNode, groupAgentId?: string): IdNode {
- const nextNode = this.findChainContinuationNode(idNode, groupAgentId);
- return nextNode ? this.findLastAssistantNodeInGroup(nextNode, groupAgentId) : idNode;
+ // Iterative: a group's chain can be thousands of steps long.
+ let current = idNode;
+ let nextNode = this.findChainContinuationNode(current, groupAgentId);
+ while (nextNode) {
+ current = nextNode;
+ nextNode = this.findChainContinuationNode(current, groupAgentId);
+ }
+ return current;
}
/**
diff --git a/packages/database/src/models/__tests__/messages/message.cursor-query.test.ts b/packages/database/src/models/__tests__/messages/message.cursor-query.test.ts
new file mode 100644
index 00000000000..a040e41325f
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.cursor-query.test.ts
@@ -0,0 +1,465 @@
+// Regression + behavior tests for MessageModel.queryTopicMessagesByCursor
+// (round-boundary cursor pagination β€” LOBE-12011, stage 2 server layer).
+import { MessageGroupType } from '@lobechat/types';
+import { eq, inArray, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, chatGroups, messageGroups, messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'cursor-query-test';
+const messageModel = new MessageModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.delete(users).where(eq(users.id, userId));
+ await trx.insert(users).values([{ id: userId }]);
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+/**
+ * Seed `rounds` rounds of (1 user + `stepsPerRound` assistant) as one contiguous
+ * mainline parentId chain. Returns the ordered ids (oldest→newest) plus the
+ * round-start user ids.
+ */
+const seedRounds = async (topicId: string, rounds: number, stepsPerRound: number) => {
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+ const rows: any[] = [];
+ const ids: string[] = [];
+ const roundStarts: string[] = [];
+ let seq = 0;
+ let prevId: string | null = null;
+ for (let r = 1; r <= rounds; r += 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;
+ ids.push(uid);
+ roundStarts.push(uid);
+ prevId = uid;
+ for (let step = 1; step <= stepsPerRound; 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;
+ ids.push(sid);
+ prevId = sid;
+ }
+ }
+ await serverDB.insert(messages).values(rows);
+ return { ids, lastId: prevId as string, roundStarts };
+};
+
+describe('MessageModel.queryTopicMessagesByCursor', () => {
+ it('initial load returns the newest N rounds, round-aligned, with the final answer', async () => {
+ const topicId = 't-cursor-initial';
+ const { lastId } = await seedRounds(topicId, 5, 2); // 5 rounds x 3 = 15 msgs
+
+ const page = await messageModel.queryTopicMessagesByCursor({ topicId, roundLimit: 2 });
+
+ // Newest 2 rounds = round 4 (u4..a4-2) + round 5 (u5..a5-2) = 6 messages, asc.
+ expect(page.messages).toHaveLength(6);
+ expect(page.messages[0].id).toBe(`${topicId}-u4`); // round-aligned lower bound
+ expect(page.messages[0].role).toBe('user');
+ expect(page.messages.at(-1)!.id).toBe(lastId); // final answer present
+ expect(page.hasMore).toBe(true);
+ expect(page.nextCursor).toEqual({ createdAt: expect.any(String), id: `${topicId}-u4` });
+ });
+
+ it('walks older pages via nextCursor with no gaps and no splitting a round', async () => {
+ const topicId = 't-cursor-walk';
+ const { ids } = await seedRounds(topicId, 5, 2); // 15 msgs
+
+ const collected: string[][] = [];
+ let cursor: any = null;
+ // Page backwards until exhausted.
+ for (let i = 0; i < 10; i += 1) {
+ const page = await messageModel.queryTopicMessagesByCursor({
+ topicId,
+ roundLimit: 2,
+ cursor,
+ });
+ collected.push(page.messages.map((m) => m.id));
+ if (!page.hasMore) {
+ expect(page.nextCursor).toBeNull();
+ break;
+ }
+ cursor = page.nextCursor;
+ }
+
+ // 5 rounds / 2 per page => pages of [round4,5], [round2,3], [round1].
+ expect(collected).toHaveLength(3);
+ expect(collected[2]).toHaveLength(3); // last page = round 1 only
+
+ // Every page starts on a user message (never mid-round).
+ for (const pageIds of collected) {
+ expect(pageIds[0]).toMatch(/-u\d+$/);
+ }
+
+ // `collected` is newest-page-first and each page is already ascending, so
+ // reversing the page order then flattening rebuilds the full transcript
+ // oldest→newest. It must equal every seeded id exactly — nothing dropped in a
+ // boundary gap, nothing duplicated. This is the property PR1's offset paging
+ // could not hold.
+ const rebuilt = [...collected].reverse().flat();
+ expect(rebuilt).toEqual(ids);
+ expect(new Set(rebuilt).size).toBe(ids.length);
+ });
+
+ it('returns the whole topic when it has fewer rounds than the limit', async () => {
+ const topicId = 't-cursor-short';
+ const { ids } = await seedRounds(topicId, 2, 2); // 6 msgs, 2 rounds
+
+ const page = await messageModel.queryTopicMessagesByCursor({ topicId, roundLimit: 5 });
+
+ expect(page.messages.map((m) => m.id)).toEqual(ids);
+ expect(page.hasMore).toBe(false);
+ expect(page.nextCursor).toBeNull();
+ });
+
+ it('caps the window by countBudget even when roundLimit is larger', async () => {
+ const topicId = 't-cursor-budget';
+ await seedRounds(topicId, 5, 0); // 5 single-message (user-only) rounds
+
+ // Budget 3 forces at most ~3 rows despite roundLimit 10.
+ const page = await messageModel.queryTopicMessagesByCursor({
+ topicId,
+ roundLimit: 10,
+ countBudget: 3,
+ });
+
+ expect(page.messages).toHaveLength(3);
+ expect(page.messages.at(-1)!.id).toBe(`${topicId}-u5`); // newest kept
+ expect(page.messages[0].id).toBe(`${topicId}-u3`); // budget-capped lower bound
+ expect(page.hasMore).toBe(true);
+ });
+
+ it('returns an empty page with no cursor for an empty topic', async () => {
+ const topicId = 't-cursor-empty';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+
+ const page = await messageModel.queryTopicMessagesByCursor({ topicId });
+
+ expect(page.messages).toHaveLength(0);
+ expect(page.hasMore).toBe(false);
+ expect(page.nextCursor).toBeNull();
+ });
+
+ // LOBE-12011 P1: `messages.createdAt` is a timestamptz whose now() default can
+ // carry microseconds. A cursor round-tripped through a millisecond JS Date would
+ // round sub-millisecond boundaries and drop/duplicate rows across pages. Seed
+ // rows that all share ONE millisecond but differ by microseconds and prove the
+ // backward walk still reconstructs the transcript exactly.
+ it('preserves microsecond precision across cursor pages (no leak within a millisecond)', async () => {
+ const topicId = 't-cursor-micros';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+
+ // 3 rounds x (user, assistant) = 6 messages, all within 2023-01-01T00:00:00.000
+ // but 1..6 microseconds apart, ascending in time.
+ const roles = ['user', 'assistant', 'user', 'assistant', 'user', 'assistant'];
+ let prev: string | null = null;
+ const ids: string[] = [];
+ for (let i = 0; i < 6; i += 1) {
+ const id = `${topicId}-m${i + 1}`;
+ const micros = String(i + 1).padStart(6, '0');
+ await serverDB.insert(messages).values({
+ content: `c${i + 1}`,
+ createdAt: sql`${`2023-01-01T00:00:00.${micros}Z`}::timestamptz`,
+ id,
+ parentId: prev,
+ role: roles[i] as any,
+ topicId,
+ userId,
+ });
+ ids.push(id);
+ prev = id;
+ }
+
+ const collected: string[][] = [];
+ let cursor: any = null;
+ for (let i = 0; i < 10; i += 1) {
+ const page = await messageModel.queryTopicMessagesByCursor({
+ topicId,
+ roundLimit: 1,
+ cursor,
+ });
+ collected.push(page.messages.map((m) => m.id));
+ if (!page.hasMore) break;
+ cursor = page.nextCursor;
+ }
+
+ // 3 rounds / 1 per page = 3 pages, and reversing the page order rebuilds all
+ // six ids with none dropped in a sub-millisecond boundary gap and none doubled.
+ expect(collected).toHaveLength(3);
+ const rebuilt = [...collected].reverse().flat();
+ expect(rebuilt).toEqual(ids);
+ expect(new Set(rebuilt).size).toBe(ids.length);
+ });
+
+ // LOBE-12011 P1: the cursor path must constrain MessageGroup assembly to the
+ // page's time window. Otherwise every page eagerly loads (and repeats) the whole
+ // topic's compression groups β€” exactly the compressed history cursor pagination
+ // exists to defer.
+ it('windows out compression groups that fall outside the page range', async () => {
+ const topicId = 't-cursor-groups';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+
+ // Old compressed history (early), then two newer uncompressed mainline rounds.
+ await serverDB.insert(messages).values([
+ {
+ id: `${topicId}-old1`,
+ userId,
+ topicId,
+ role: 'user',
+ content: 'old1',
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: `${topicId}-old2`,
+ userId,
+ topicId,
+ role: 'assistant',
+ content: 'old2',
+ createdAt: new Date('2024-01-01T10:00:01Z'),
+ },
+ {
+ id: `${topicId}-u1`,
+ userId,
+ topicId,
+ role: 'user',
+ content: 'q1',
+ parentId: `${topicId}-old2`,
+ createdAt: new Date('2024-01-01T10:05:00Z'),
+ },
+ {
+ id: `${topicId}-a1`,
+ userId,
+ topicId,
+ role: 'assistant',
+ content: 'a1',
+ parentId: `${topicId}-u1`,
+ createdAt: new Date('2024-01-01T10:05:01Z'),
+ },
+ {
+ id: `${topicId}-u2`,
+ userId,
+ topicId,
+ role: 'user',
+ content: 'q2',
+ parentId: `${topicId}-a1`,
+ createdAt: new Date('2024-01-01T10:06:00Z'),
+ },
+ {
+ id: `${topicId}-a2`,
+ userId,
+ topicId,
+ role: 'assistant',
+ content: 'a2',
+ parentId: `${topicId}-u2`,
+ createdAt: new Date('2024-01-01T10:06:01Z'),
+ },
+ ]);
+
+ // A compression group covering the old messages, dated in the old range.
+ await serverDB.insert(messageGroups).values({
+ id: `${topicId}-cg`,
+ content: 'summary of early conversation',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:00:30Z'),
+ });
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: `${topicId}-cg` })
+ .where(inArray(messages.id, [`${topicId}-old1`, `${topicId}-old2`]));
+
+ // Newest cursor page (round 2 only) is windowed to [10:06:00, now]; the group
+ // at 10:00:30 is outside it and must not be pulled in.
+ const page = await messageModel.queryTopicMessagesByCursor({ topicId, roundLimit: 1 });
+ expect(page.messages.some((m) => m.role === 'compressedGroup')).toBe(false);
+ expect(page.messages.map((m) => m.id)).toEqual([`${topicId}-u2`, `${topicId}-a2`]);
+
+ // The group still exists and the full (client-mode) query surfaces it β€” proving
+ // the cursor page omitted it by windowing, not because it was absent.
+ const full = await messageModel.query({ topicId });
+ expect(full.some((m) => m.role === 'compressedGroup' && m.id === `${topicId}-cg`)).toBe(true);
+
+ // ...and the cursor walk must still reach it: the oldest page leaves the group
+ // window's lower side open, so the group dated before the first remaining
+ // mainline row is emitted exactly once rather than never.
+ const older = await messageModel.queryTopicMessagesByCursor({
+ topicId,
+ roundLimit: 1,
+ cursor: page.nextCursor,
+ });
+ expect(older.hasMore).toBe(false);
+ expect(older.messages.map((m) => m.id)).toEqual([
+ `${topicId}-cg`,
+ `${topicId}-u1`,
+ `${topicId}-a1`,
+ ]);
+ });
+
+ // LOBE-12011 P1: compression can move EVERY message of a topic into a group,
+ // leaving no mainline rows. The cursor path must still surface the synthetic
+ // `compressedGroup` node (as `query` does) instead of an empty transcript.
+ it('returns the compressed group for a topic whose whole history is compressed', async () => {
+ const topicId = 't-cursor-compressed-only';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+ await serverDB.insert(messageGroups).values({
+ id: `${topicId}-cg`,
+ content: 'summary of everything',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T11:00:00Z'),
+ });
+ await serverDB.insert(messages).values([
+ {
+ id: `${topicId}-u1`,
+ userId,
+ topicId,
+ role: 'user',
+ content: 'q1',
+ messageGroupId: `${topicId}-cg`,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: `${topicId}-a1`,
+ userId,
+ topicId,
+ role: 'assistant',
+ content: 'a1',
+ messageGroupId: `${topicId}-cg`,
+ createdAt: new Date('2024-01-01T10:00:01Z'),
+ },
+ ]);
+
+ const page = await messageModel.queryTopicMessagesByCursor({ topicId });
+
+ expect(page.messages.map((m) => ({ id: m.id, role: m.role }))).toEqual([
+ { id: `${topicId}-cg`, role: 'compressedGroup' },
+ ]);
+ expect(page.hasMore).toBe(false);
+ expect(page.nextCursor).toBeNull();
+ });
+
+ // LOBE-12011 P1: a concrete topic is the conversation boundary. A caller passing
+ // its own agentId must still see rows written by another agent in the same topic
+ // (e.g. `callAgent` / delegated replies), matching `query`.
+ it('keeps rows from other agents in the same topic when agentId is given', async () => {
+ const topicId = 't-cursor-mixed-agent';
+ await serverDB.insert(agents).values([
+ { id: 'cursor-agent-main', userId, title: 'Main' },
+ { id: 'cursor-agent-sub', userId, title: 'Sub' },
+ ]);
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+ await serverDB.insert(messages).values([
+ {
+ id: `${topicId}-u1`,
+ userId,
+ topicId,
+ agentId: 'cursor-agent-main',
+ role: 'user',
+ content: 'q1',
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: `${topicId}-a1`,
+ userId,
+ topicId,
+ agentId: 'cursor-agent-sub',
+ role: 'assistant',
+ content: 'delegated reply',
+ parentId: `${topicId}-u1`,
+ createdAt: new Date('2024-01-01T10:00:01Z'),
+ },
+ {
+ id: `${topicId}-a2`,
+ userId,
+ topicId,
+ agentId: 'cursor-agent-main',
+ role: 'assistant',
+ content: 'final',
+ parentId: `${topicId}-a1`,
+ createdAt: new Date('2024-01-01T10:00:02Z'),
+ },
+ ]);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ agentId: 'cursor-agent-main',
+ topicId,
+ });
+
+ expect(page.messages.map((m) => m.id)).toEqual([
+ `${topicId}-u1`,
+ `${topicId}-a1`,
+ `${topicId}-a2`,
+ ]);
+ });
+ it('reads a group chat topic through its group id, like `query`', async () => {
+ const topicId = 't-cursor-group';
+ await serverDB.insert(chatGroups).values([{ id: 'cg-cursor', userId }]);
+ await serverDB.insert(topics).values([{ groupId: 'cg-cursor', id: topicId, userId }]);
+ await serverDB.insert(messages).values([
+ {
+ content: 'q1',
+ createdAt: new Date(2023, 0, 1, 0, 0),
+ groupId: 'cg-cursor',
+ id: `${topicId}-u1`,
+ role: 'user',
+ topicId,
+ userId,
+ },
+ {
+ content: 'a1',
+ createdAt: new Date(2023, 0, 1, 0, 1),
+ groupId: 'cg-cursor',
+ id: `${topicId}-a1`,
+ parentId: `${topicId}-u1`,
+ role: 'assistant',
+ topicId,
+ userId,
+ },
+ ]);
+
+ const page = await messageModel.queryTopicMessagesByCursor({ groupId: 'cg-cursor', topicId });
+
+ expect(page.messages.map((m) => m.id)).toEqual([`${topicId}-u1`, `${topicId}-a1`]);
+ expect(page.hasMore).toBe(false);
+ expect(page.nextCursor).toBeNull();
+ });
+
+ it('fails closed on an agent-share visitor topic, like `query`', async () => {
+ const topicId = 't-cursor-visitor';
+ await seedRounds(topicId, 2, 1);
+ await serverDB.update(topics).set({ senderId: 'visitor-1' }).where(eq(topics.id, topicId));
+
+ const page = await messageModel.queryTopicMessagesByCursor({ topicId });
+
+ expect(page).toEqual({ hasMore: false, messages: [], nextCursor: null });
+ });
+});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index cda2fc13627..96ebfc700b6 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -234,6 +234,16 @@ export interface QueryMessagesOptions {
* Current page number (0-indexed)
*/
current?: number;
+ /**
+ * Constrain MessageGroup assembly to an explicit `[from, before)` time window
+ * instead of loading every group in the topic (or deriving the window from the
+ * fetched rows). Set by cursor pagination so consecutive pages partition the
+ * topic's groups exactly once: a scroll-up page neither repeats group nodes nor
+ * drops the ones dated between (or older than) its mainline rows. Either bound
+ * may be omitted to leave that side open. Bounds are lossless microsecond
+ * timestamp strings compared with a `::timestamptz` cast.
+ */
+ groupNodeWindow?: MessageGroupNodeWindow;
/**
* Opt-in for `file` work summaries in the payload (see
* `QueryMessageParams.includeFileWorks`).
@@ -291,6 +301,64 @@ export interface TopicTranscriptResult {
total: number;
}
+/**
+ * Round-boundary cursor for {@link MessageModel.queryTopicMessagesByCursor}. Points
+ * at a mainline `user` message (a round start); paging older fetches the rounds
+ * strictly before it.
+ */
+export interface MessageRoundCursor {
+ createdAt: string;
+ id: string;
+}
+
+export interface QueryTopicByCursorParams {
+ /**
+ * Ignored: a concrete topic is the conversation boundary and may hold rows
+ * from several agents/sessions (e.g. `callAgent` replies), same as `query`.
+ * Accepted only so callers can forward their usual query params.
+ */
+ agentId?: string | null;
+ /** Hard cap on rows walked when resolving the round window (safety, ~rows). */
+ countBudget?: number;
+ /** Omit for the initial (newest) page; pass a prior `nextCursor` to load older. */
+ cursor?: MessageRoundCursor | null;
+ /** Group chat topic: rows carry the group id, same filter as `query`. */
+ groupId?: string | null;
+ /** See {@link QueryMessageParams.includeFileWorks}. */
+ includeFileWorks?: boolean;
+ /** How many rounds to load per page (the current round is always whole). */
+ roundLimit?: number;
+ /** Ignored for the same reason as `agentId`. */
+ sessionId?: string | null;
+ skipWorks?: boolean;
+ topicId: string;
+}
+
+export interface TopicMessagesByCursorResult {
+ hasMore: boolean;
+ messages: UIChatMessage[];
+ /** Cursor to load the previous (older) page, or null when at the topic start. */
+ nextCursor: MessageRoundCursor | null;
+}
+
+/** Default rounds per cursor page. */
+const DEFAULT_ROUND_LIMIT = 10;
+/** Default safety cap on rows scanned per cursor page. */
+const DEFAULT_ROUND_COUNT_BUDGET = 2000;
+/**
+ * Row ceiling for the cursor path's underlying `queryWithWhere` fetch. The `where`
+ * already bounds rows to the resolved round window; this only prevents an
+ * unbounded scan and keeps `queryWithWhere`'s newest-first trim disabled (the
+ * result stays below `pageSize`, so the trim guard never fires).
+ */
+const CURSOR_PAGE_CEILING = 100_000;
+
+/** Half-open `[from, before)` MessageGroup window; see `groupNodeWindow`. */
+export interface MessageGroupNodeWindow {
+ before?: string | null;
+ from?: string | null;
+}
+
export interface ModelTimingContext extends TimingSink {}
interface MessageRelatedFile {
@@ -1501,6 +1569,7 @@ export class MessageModel {
timing,
allowShareVisitor,
workAccessScope,
+ groupNodeWindow,
} = options;
const totalStartedAt = Date.now();
const offset = current * pageSize;
@@ -1651,6 +1720,7 @@ export class MessageModel {
result,
timing,
topicId,
+ window: groupNodeWindow,
});
const taskMessageIds = result
@@ -1819,6 +1889,191 @@ export class MessageModel {
return allItems;
};
+ /**
+ * Cursor-paginated read of a topic's mainline conversation, aligned to round
+ * boundaries (a mainline `user` message starts a round). Built for callers that
+ * only DISPLAY history and never resend it to the model β€” server-runtime
+ * (gateway) and local hetero agents β€” where eagerly loading the whole transcript
+ * is wasteful on long topics. Legacy client mode keeps using `query` (full
+ * fetch) because it resends the entire session each turn.
+ *
+ * Initial load (`cursor` omitted) returns the newest `roundLimit` rounds, or
+ * fewer if `countBudget` is reached first, but the current round is always
+ * whole. Pass the returned `nextCursor` to load the previous rounds (scroll up).
+ * Unlike offset paging, cursors land on round boundaries, so consecutive pages
+ * are gap-free and never split a round.
+ */
+ queryTopicMessagesByCursor = async (
+ {
+ countBudget = DEFAULT_ROUND_COUNT_BUDGET,
+ cursor,
+ groupId,
+ includeFileWorks,
+ roundLimit = DEFAULT_ROUND_LIMIT,
+ skipWorks,
+ topicId,
+ }: QueryTopicByCursorParams,
+ options: {
+ postProcessUrl?: (
+ path: string | null,
+ file: { fileType: string; id?: string | null },
+ ) => Promise<string>;
+ timing?: ModelTimingContext;
+ } = {},
+ ): Promise<TopicMessagesByCursorResult> => {
+ // Same visitor gate as `query`: a creator's read of an agent-share visitor
+ // topic fails closed, and a verified creator topic skips the per-row check.
+ if ((await this.resolveTopicVisitorScope(topicId)) === 'visitor') {
+ return { hasMore: false, messages: [], nextCursor: null };
+ }
+
+ // Mainline = this topic (and its chat group, if any), not in a thread. Like
+ // the standard `query`, a concrete topic is the conversation boundary: it is
+ // NOT narrowed by agent/session, because a topic may legitimately hold rows
+ // from several agents (e.g. `callAgent` / delegated replies).
+ const mainlineWhere = and(
+ this.matchTopic(topicId),
+ this.matchGroup(groupId),
+ this.matchThread(undefined),
+ );
+
+ const { lowerBound, hasMore } = await this.resolveRoundWindow({
+ countBudget,
+ cursor,
+ mainlineWhere,
+ roundLimit,
+ });
+
+ // MessageGroup nodes (compression / comparison) are partitioned across pages
+ // by the same `[lowerBound, cursor)` window as mainline rows, so each group is
+ // emitted exactly once over a full backward walk. The oldest page (`!hasMore`)
+ // leaves the lower side open so groups dated before the first remaining
+ // mainline row β€” including a topic whose whole history was compressed β€” stay
+ // reachable instead of vanishing.
+ const groupNodeWindow: MessageGroupNodeWindow = {
+ before: cursor?.createdAt ?? null,
+ from: hasMore && lowerBound ? lowerBound.createdAt : null,
+ };
+
+ // No lower bound means no mainline rows remain β€” either the topic has none
+ // (e.g. compression moved every message into a group) or nothing older than
+ // the cursor is left. The page is then group-only: fetch no mainline rows (an
+ // unbounded `where` would wrongly reload the entire topic) but still assemble
+ // the remaining group nodes.
+ //
+ // Otherwise bound the window on BOTH sides: at/after the resolved round start,
+ // and β€” when paging older β€” strictly before the cursor. Without the upper
+ // bound the window would also re-include every newer round already loaded.
+ const where = lowerBound
+ ? and(
+ mainlineWhere,
+ this.messageAtOrAfter(lowerBound),
+ cursor ? this.messageStrictlyBefore(cursor) : undefined,
+ )
+ : sql`false`;
+
+ const messages = await this.queryWithWhere({
+ allowShareVisitor: true,
+ current: 0,
+ includeFileWorks,
+ pageSize: CURSOR_PAGE_CEILING,
+ postProcessUrl: options.postProcessUrl,
+ skipWorks,
+ timing: options.timing,
+ topicId,
+ where,
+ // Only assemble group nodes within this page's window (not the whole topic),
+ // so scroll-up pages don't repeat groups or eagerly load compressed history.
+ groupNodeWindow,
+ });
+
+ // `lowerBound.createdAt` is already the lossless microsecond cursor string.
+ return { hasMore, messages, nextCursor: hasMore && lowerBound ? lowerBound : null };
+ };
+
+ /**
+ * Resolve the round window for a cursor page: walk mainline rows newest-first
+ * and stop at the `roundLimit`-th round boundary (a `user` message) or the
+ * `countBudget` safety cap, whichever comes first. Returns the lower bound (the
+ * oldest included round's start) and whether older rounds remain.
+ */
+ private resolveRoundWindow = async ({
+ countBudget,
+ cursor,
+ mainlineWhere,
+ roundLimit,
+ }: {
+ countBudget: number;
+ cursor?: MessageRoundCursor | null;
+ mainlineWhere: SQL | undefined;
+ roundLimit: number;
+ }): Promise<{ hasMore: boolean; lowerBound: { createdAt: string; id: string } | null }> => {
+ const olderThanCursor = cursor ? this.messageStrictlyBefore(cursor) : undefined;
+
+ const rows = (await this.db
+ .select({
+ // Microsecond-precision UTC string. `createdAt` is a timestamptz whose
+ // now() default can carry microseconds, but a JS Date keeps only
+ // milliseconds β€” a Date-derived cursor would round sub-millisecond
+ // boundaries and let rows leak between adjacent pages. Carry the lossless
+ // value in the cursor and compare it back with a ::timestamptz cast.
+ createdAtIso: sql<string>`to_char(${messages.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
+ id: messages.id,
+ role: messages.role,
+ })
+ .from(messages)
+ .where(and(this.ownership(), isNull(messages.messageGroupId), mainlineWhere, olderThanCursor))
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(countBudget + 1)) as { createdAtIso: string; id: string; role: string }[];
+
+ if (rows.length === 0) return { hasMore: false, lowerBound: null };
+
+ let rounds = 0;
+ let boundaryIndex = -1;
+ for (let i = 0; i < rows.length; i += 1) {
+ if (rows[i].role === 'user') {
+ rounds += 1;
+ boundaryIndex = i;
+ if (rounds >= roundLimit) break;
+ }
+ // Safety cap: once a full budget has been walked and at least one whole
+ // round is captured, stop at the last boundary instead of scanning further.
+ if (i + 1 >= countBudget && rounds >= 1) break;
+ }
+
+ // No `user` turn in the visible window β€” an oversized newest round, or a tail
+ // with no user turn. Fall back to the oldest fetched row; that slice is a
+ // partial round the renderer roots as an orphan chain. Lazy step loading is
+ // the proper fix (a later stage).
+ if (boundaryIndex === -1) boundaryIndex = rows.length - 1;
+
+ const boundaryRow = rows[boundaryIndex];
+ const hasMore = boundaryIndex < rows.length - 1 || rows.length > countBudget;
+
+ return { hasMore, lowerBound: { createdAt: boundaryRow.createdAtIso, id: boundaryRow.id } };
+ };
+
+ /**
+ * `(createdAt, id)` strictly before the cursor β€” the "older than" half-open
+ * bound. Compares against the cursor's lossless microsecond string cast to
+ * `timestamptz`, so sub-millisecond boundaries stay exact.
+ */
+ private messageStrictlyBefore = (cursor: MessageRoundCursor) =>
+ or(
+ sql`${messages.createdAt} < ${cursor.createdAt}::timestamptz`,
+ and(
+ sql`${messages.createdAt} = ${cursor.createdAt}::timestamptz`,
+ lt(messages.id, cursor.id),
+ ),
+ );
+
+ /** `(createdAt, id)` at or after the lower bound β€” the inclusive window start. */
+ private messageAtOrAfter = (bound: { createdAt: string; id: string }) =>
+ or(
+ sql`${messages.createdAt} > ${bound.createdAt}::timestamptz`,
+ and(sql`${messages.createdAt} = ${bound.createdAt}::timestamptz`, gte(messages.id, bound.id)),
+ );
+
private queryMessageGroupNodesForPage = async ({
allowShareVisitor,
current,
@@ -1827,6 +2082,7 @@ export class MessageModel {
result,
timing,
topicId,
+ window,
}: {
/**
* Effective visitor gate resolved by the caller (per-call
@@ -1853,9 +2109,24 @@ export class MessageModel {
result: { createdAt: Date }[];
timing?: ModelTimingContext;
topicId?: string;
+ /** Explicit group window (cursor pagination); overrides the row-derived one. */
+ window?: MessageGroupNodeWindow;
}): Promise<UIChatMessage[]> => {
if (!topicId) return [];
+ if (window) {
+ return runTimedStage(
+ timing,
+ 'db.message.queryWithWhere.messageGroups',
+ () =>
+ this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {
+ allowShareVisitor,
+ window,
+ }),
+ { current, hasMessages: result.length > 0, topicId },
+ );
+ }
+
if (result.length === 0) {
if (current !== 0 || hasBeforeCursor) return [];
@@ -2505,7 +2776,7 @@ export class MessageModel {
file: { fileType: string; id?: string | null },
) => Promise<string>,
timing?: ModelTimingContext,
- options: { allowShareVisitor?: boolean } = {},
+ options: { allowShareVisitor?: boolean; window?: MessageGroupNodeWindow } = {},
): Promise<UIChatMessage[]> => {
// Effective visitor gate β€” see `queryMessageGroupNodesForPage`. Absent
// this predicate, a creator's default `query({ topicId })` on a visitor
@@ -2529,6 +2800,15 @@ export class MessageModel {
);
}
+ // Explicit half-open `[from, before)` window from cursor pagination, compared
+ // against lossless microsecond strings so page boundaries stay exact.
+ if (options.window?.from) {
+ whereConditions.push(sql`${messageGroups.createdAt} >= ${options.window.from}::timestamptz`);
+ }
+ if (options.window?.before) {
+ whereConditions.push(sql`${messageGroups.createdAt} < ${options.window.before}::timestamptz`);
+ }
+
const groups = await runTimedStage(
timing,
'db.message.messageGroups.groups.select',
diff --git a/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx b/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx
index 1620c7867d5..096edff2795 100644
--- a/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx
+++ b/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx
@@ -2,12 +2,15 @@
import { memo } from 'react';
+import { delayed } from '@/components/Skeleton/Delayed';
+
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.
+ * pre-window history is in flight. Held back like a route fallback, so a page
+ * that lands quickly never flashes a block of skeleton over the messages.
*
* 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
@@ -16,7 +19,7 @@ import { useConversationStore } from '../../store';
const EarlierHistorySkeleton = memo(() => {
const isLoading = useConversationStore((s) => s.isLoadingEarlierMessages);
- return isLoading ? <SkeletonList /> : null;
+ return isLoading ? delayed(<SkeletonList />) : null;
});
EarlierHistorySkeleton.displayName = 'EarlierHistorySkeleton';
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
index fd7a17f6602..72de750f229 100644
--- a/src/features/Conversation/store/slices/data/action.test.ts
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -31,13 +31,18 @@ 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: [] }),
- },
-}));
+vi.mock('@/services/message', () => {
+ const getMessages = vi.fn();
+ return {
+ messageService: {
+ getEarlierMessages: vi.fn(),
+ // The list cache reads pages; tests stub the plain list underneath.
+ getMessageListPage: vi.fn((params) => getMessages(params)),
+ getMessages,
+ updateMessageMetadata: vi.fn().mockResolvedValue({ success: true, messages: [] }),
+ },
+ };
+});
// Mock SWR
vi.mock('@/libs/swr', () => ({
@@ -266,16 +271,20 @@ describe('DataSlice', () => {
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 },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-1',
+ threadId: 'thread-earlier',
+ },
});
store.getState().replaceMessages(windowMessages);
- vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce(earlierPage);
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce({ messages: earlierPage });
await store.getState().loadEarlierMessages();
expect(messageService.getEarlierMessages).toHaveBeenCalledWith(
expect.objectContaining({ agentId: 'agent-earlier', topicId: 'topic-earlier-1' }),
- { createdAt: new Date(1000), id: 'u2' },
+ { createdAt: new Date(1000).toISOString(), id: 'u2' },
);
expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u1', 'a1', 'u2', 'a2']);
expect(store.getState().isLoadingEarlierMessages).toBe(false);
@@ -283,10 +292,14 @@ describe('DataSlice', () => {
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 },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-2',
+ threadId: 'thread-earlier',
+ },
});
store.getState().replaceMessages(windowMessages);
- vi.mocked(messageService.getEarlierMessages).mockResolvedValue([]);
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValue({ messages: [] });
await store.getState().loadEarlierMessages();
await store.getState().loadEarlierMessages();
@@ -297,16 +310,24 @@ describe('DataSlice', () => {
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 },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-3',
+ threadId: 'thread-earlier',
+ },
});
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 },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-other',
+ threadId: 'thread-earlier',
+ },
} as any);
- return earlierPage;
+ return { messages: earlierPage };
});
await store.getState().loadEarlierMessages();
@@ -317,13 +338,17 @@ describe('DataSlice', () => {
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 },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-4',
+ threadId: 'thread-earlier',
+ },
});
store.getState().replaceMessages(windowMessages);
const failure = new Error('network down');
vi.mocked(messageService.getEarlierMessages)
.mockRejectedValueOnce(failure)
- .mockResolvedValueOnce(earlierPage);
+ .mockResolvedValueOnce({ messages: earlierPage });
await expect(store.getState().loadEarlierMessages()).resolves.toBeUndefined();
expect(store.getState().isLoadingEarlierMessages).toBe(false);
@@ -342,7 +367,11 @@ describe('DataSlice', () => {
it('clears the failure on conversation switch', async () => {
const store = createStore({
- context: { agentId: 'agent-earlier', topicId: 'topic-earlier-6', threadId: null },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-6',
+ threadId: 'thread-earlier',
+ },
});
store.getState().replaceMessages(windowMessages);
vi.mocked(messageService.getEarlierMessages).mockRejectedValueOnce(new Error('boom'));
@@ -352,14 +381,22 @@ describe('DataSlice', () => {
store.setState({
...createEphemeralResetState(),
- context: { agentId: 'agent-earlier', topicId: 'topic-earlier-7', threadId: null },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-7',
+ threadId: 'thread-earlier',
+ },
} 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 },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-8',
+ threadId: 'thread-earlier',
+ },
});
store.getState().replaceMessages(windowMessages);
const streamed = {
@@ -379,7 +416,7 @@ describe('DataSlice', () => {
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;
+ return { messages: earlierPage };
});
await store.getState().loadEarlierMessages();
@@ -391,17 +428,25 @@ describe('DataSlice', () => {
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 },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-5',
+ threadId: 'thread-earlier',
+ },
});
store.getState().replaceMessages(windowMessages);
vi.mocked(messageService.getEarlierMessages).mockImplementationOnce(async () => {
store.setState({
...createEphemeralResetState(),
- context: { agentId: 'agent-earlier', topicId: 'topic-earlier-next', threadId: null },
+ context: {
+ agentId: 'agent-earlier',
+ topicId: 'topic-earlier-next',
+ threadId: 'thread-earlier',
+ },
} as any);
// The next conversation starts its own page load while ours is in flight.
store.setState({ isLoadingEarlierMessages: true });
- return earlierPage;
+ return { messages: earlierPage };
});
await store.getState().loadEarlierMessages();
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index 58e1539bed5..44ea3206a9e 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -223,7 +223,7 @@ export const dataSlice: StateCreator<
// 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) =>
+ (cursor) =>
messageService.getEarlierMessages(
{
agentId: context.agentId,
@@ -233,7 +233,7 @@ export const dataSlice: StateCreator<
topicId: context.topicId,
topicShareId: context.topicShareId,
},
- before,
+ cursor,
),
);
// `undefined` β†’ nothing to prepend (no cursor, already loading, the
@@ -340,7 +340,7 @@ export const dataSlice: StateCreator<
return useClientDataSWRWithSync<UIChatMessage[]>(
shouldFetch ? messageListKey(context) : null,
- () => runMessageListQuery(context, messageService.getMessages),
+ () => runMessageListQuery(context, messageService.getMessageListPage),
{
...getMessageListFetchPolicy(context),
...(revalidateOnFocus !== undefined && { revalidateOnFocus }),
diff --git a/src/services/message/cache.test.ts b/src/services/message/cache.test.ts
index 796ca3608e8..7b43978bc61 100644
--- a/src/services/message/cache.test.ts
+++ b/src/services/message/cache.test.ts
@@ -12,6 +12,7 @@ import {
loadEarlierMessagePage,
MESSAGE_LIST_VERIFICATION_INTERVAL,
messageListKey,
+ type MessageListPage,
runMessageListQuery,
} from './cache';
@@ -254,34 +255,41 @@ describe('earlier history (round-cursor pages, LOBE-13716)', () => {
const ids = (list: UIChatMessage[] | undefined) => list?.map((item) => item.id);
+ // Threads have no round-cursor read, so their pages derive the cursor from
+ // the oldest loaded row β€” the legacy path these cases pin down.
+ const threadContext = { ...context, threadId: 'thread-1' };
+
+ /** A page from a read path that reports no round cursor (older history unknown). */
+ const asPage = (messages: UIChatMessage[]): MessageListPage => ({ messages });
+
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 fetcher = vi.fn().mockResolvedValue(asPage([message('u1', 1, 'user'), message('a1', 2)]));
- const merged = await loadEarlierMessagePage(context, () => window, fetcher);
+ const merged = await loadEarlierMessagePage(threadContext, () => window, fetcher);
- expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10), id: 'u2' });
+ expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10).toISOString(), 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')]);
+ const fetcher = vi.fn().mockResolvedValue(asPage([message('u1', 1, 'user')]));
- await loadEarlierMessagePage(context, () => window, fetcher);
+ await loadEarlierMessagePage(threadContext, () => window, fetcher);
- expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10), id: 'u2' });
+ expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10).toISOString(), 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,
+ threadContext,
() => window,
- async () => [message('u1', 1, 'user')],
+ async () => asPage([message('u1', 1, 'user')]),
);
- const revalidated = await runMessageListQuery(context, async () => window);
+ const revalidated = await runMessageListQuery(threadContext, async () => window);
expect(ids(revalidated)).toEqual(['u1', 'u2', 'a2']);
});
@@ -289,15 +297,15 @@ describe('earlier history (round-cursor pages, LOBE-13716)', () => {
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,
+ threadContext,
() => window,
- async () => [message('u1', 1, 'user')],
+ async () => asPage([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);
+ const revalidated = await runMessageListQuery(threadContext, async () => slidWindow);
expect(revalidated).toBe(slidWindow);
});
@@ -305,38 +313,38 @@ describe('earlier history (round-cursor pages, LOBE-13716)', () => {
it('deduplicates rows the fresh window already contains', async () => {
const window = [message('u2', 10, 'user'), message('a2', 11)];
await loadEarlierMessagePage(
- context,
+ threadContext,
() => window,
- async () => [message('u1', 1, 'user'), message('a1', 2)],
+ async () => asPage([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);
+ const revalidated = await runMessageListQuery(threadContext, 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 fetcher = vi.fn().mockResolvedValue(asPage([]));
- const merged = await loadEarlierMessagePage(context, () => window, fetcher);
+ const merged = await loadEarlierMessagePage(threadContext, () => window, fetcher);
expect(merged).toBeUndefined();
- expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
+ expect(getEarlierHistoryStatus(threadContext).exhausted).toBe(true);
- await loadEarlierMessagePage(context, () => window, fetcher);
+ await loadEarlierMessagePage(threadContext, () => 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 fetcher = vi.fn().mockReturnValue(firstPage.promise.then(asPage));
- const first = loadEarlierMessagePage(context, () => window, fetcher);
- const second = await loadEarlierMessagePage(context, () => window, fetcher);
+ const first = loadEarlierMessagePage(threadContext, () => window, fetcher);
+ const second = await loadEarlierMessagePage(threadContext, () => window, fetcher);
expect(second).toBeUndefined();
expect(fetcher).toHaveBeenCalledTimes(1);
@@ -350,9 +358,9 @@ describe('earlier history (round-cursor pages, LOBE-13716)', () => {
const page = deferred<UIChatMessage[]>();
const pending = loadEarlierMessagePage(
- context,
+ threadContext,
() => current,
- () => page.promise,
+ () => page.promise.then(asPage),
);
// A stream appends a reply while the page is in flight.
current = [message('u2', 10, 'user'), message('a2', 11)];
@@ -366,15 +374,15 @@ describe('earlier history (round-cursor pages, LOBE-13716)', () => {
const page = deferred<UIChatMessage[]>();
const pending = loadEarlierMessagePage(
- context,
+ threadContext,
() => window,
- () => page.promise,
+ () => page.promise.then(asPage),
);
invalidateMessageListClientState(() => true);
page.resolve([message('u1', 1, 'user')]);
expect(await pending).toBeUndefined();
- const revalidated = await runMessageListQuery(context, async () => window);
+ const revalidated = await runMessageListQuery(threadContext, async () => window);
expect(revalidated).toBe(window);
});
@@ -383,60 +391,140 @@ describe('earlier history (round-cursor pages, LOBE-13716)', () => {
const page = deferred<UIChatMessage[]>();
const pending = loadEarlierMessagePage(
- context,
+ threadContext,
() => current,
- () => page.promise,
+ () => page.promise.then(asPage),
);
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')]);
+ const revalidated = await runMessageListQuery(threadContext, 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,
+ threadContext,
() => window,
- async () => [message('u1', 1, 'user')],
+ async () => asPage([message('u1', 1, 'user')]),
);
invalidateMessageListClientState(() => true);
- const revalidated = await runMessageListQuery(context, async () => window);
+ const revalidated = await runMessageListQuery(threadContext, async () => window);
expect(revalidated).toBe(window);
});
+ describe('with a round cursor reported by the server', () => {
+ const cursorOf = (id: string, createdAt: string) => ({ createdAt, id });
+
+ it('waits for the server cursor instead of deriving one on a cursor-paged topic', async () => {
+ // A window restored from the persisted cache before its revalidation
+ // lands carries no server cursor yet.
+ const window = [message('u2', 10, 'user'), message('a2', 11)];
+ const fetcher = vi.fn();
+
+ expect(await loadEarlierMessagePage(context, () => window, fetcher)).toBeUndefined();
+ expect(fetcher).not.toHaveBeenCalled();
+ expect(getEarlierHistoryStatus(context).exhausted).toBe(false);
+
+ // Once revalidation reports the lossless cursor, the next gesture pages.
+ const windowCursor = cursorOf('u2', '1970-01-01T00:00:00.010123Z');
+ await runMessageListQuery(context, async () => ({
+ messages: window,
+ olderCursor: windowCursor,
+ }));
+ fetcher.mockResolvedValue({ messages: [message('u1', 1, 'user')], olderCursor: null });
+
+ await loadEarlierMessagePage(context, () => window, fetcher);
+ expect(fetcher).toHaveBeenCalledWith(windowCursor);
+ });
+
+ it('never fetches when the window already holds the topic start', async () => {
+ const window = [message('u1', 10, 'user'), message('a1', 11)];
+ await runMessageListQuery(context, async () => ({ messages: window, olderCursor: null }));
+ const fetcher = vi.fn();
+
+ const merged = await loadEarlierMessagePage(context, () => window, fetcher);
+
+ expect(merged).toBeUndefined();
+ expect(fetcher).not.toHaveBeenCalled();
+ expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
+ });
+
+ it("pages from the window's lossless cursor instead of the oldest row", async () => {
+ const window = [message('u2', 10, 'user'), message('a2', 11)];
+ const windowCursor = cursorOf('u2', '1970-01-01T00:00:00.010123Z');
+ await runMessageListQuery(context, async () => ({
+ messages: window,
+ olderCursor: windowCursor,
+ }));
+ const fetcher = vi
+ .fn()
+ .mockResolvedValue({ messages: [message('u1', 1, 'user')], olderCursor: null });
+
+ const merged = await loadEarlierMessagePage(context, () => window, fetcher);
+
+ expect(fetcher).toHaveBeenCalledWith(windowCursor);
+ expect(ids(merged)).toEqual(['u1', 'u2', 'a2']);
+ });
+
+ it('stops after the page that reached the topic start', async () => {
+ const window = [message('u3', 20, 'user')];
+ await runMessageListQuery(context, async () => ({
+ messages: window,
+ olderCursor: cursorOf('u3', '1970-01-01T00:00:00.020Z'),
+ }));
+ const olderCursor = cursorOf('u2', '1970-01-01T00:00:00.010Z');
+ const fetcher = vi
+ .fn()
+ .mockResolvedValueOnce({ messages: [message('u2', 10, 'user')], olderCursor })
+ .mockResolvedValueOnce({ messages: [message('u1', 1, 'user')], olderCursor: null });
+
+ let current: UIChatMessage[] = window;
+ current = (await loadEarlierMessagePage(context, () => current, fetcher)) ?? current;
+ current = (await loadEarlierMessagePage(context, () => current, fetcher)) ?? current;
+ await loadEarlierMessagePage(context, () => current, fetcher);
+
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(fetcher).toHaveBeenLastCalledWith(olderCursor);
+ expect(ids(current)).toEqual(['u1', 'u2', 'u3']);
+ expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
+ });
+ });
+
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' };
+ const oldest = { ...threadContext, topicId: 'topic-evicted' };
// Exhaust the first identity, then flood the cache with 30 more.
await loadEarlierMessagePage(
oldest,
() => window,
- async () => [],
+ async () => asPage([]),
);
expect(getEarlierHistoryStatus(oldest).exhausted).toBe(true);
for (let i = 0; i < 30; i++) {
await loadEarlierMessagePage(
- { ...context, topicId: `topic-fill-${i}` },
+ { ...threadContext, topicId: `topic-fill-${i}` },
() => window,
- async () => [message('u1', 1, 'user')],
+ async () => asPage([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([]);
+ const fetcher = vi.fn().mockResolvedValue(asPage([]));
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 survivor = { ...threadContext, 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 9e86abff9d8..ba91fffa22a 100644
--- a/src/services/message/cache.ts
+++ b/src/services/message/cache.ts
@@ -30,6 +30,54 @@ interface MessageListClientState {
const messageListClientStates = new Map<string, MessageListClientState>();
+/**
+ * Round cursor for paging older history: the `(createdAt, id)` of the oldest
+ * loaded round's start. `createdAt` is the server's lossless microsecond ISO
+ * string, so a page boundary never drops rows sharing a millisecond.
+ */
+export interface MessageRoundCursor {
+ createdAt: string;
+ id: string;
+}
+
+/**
+ * One page of a conversation. `olderCursor` points at the next older page;
+ * `null` means the topic start is already loaded, and `undefined` means the
+ * read path cannot tell (it has no round cursor).
+ */
+export interface MessageListPage {
+ messages: UIChatMessage[];
+ olderCursor?: MessageRoundCursor | null;
+}
+
+/**
+ * A topic's mainline conversation pages by round cursor. Threads and agent-share
+ * visitor topics stay on `getMessages` β€” neither has a round-cursor read.
+ */
+export const supportsRoundCursor = (context: MessageListQueryContext) =>
+ !!context.topicId && !context.threadId && !context.agentShareId;
+
+/**
+ * The older-history cursor each identity's newest window came back with. Kept
+ * apart from `messageListClientStates`, which is dropped once its verification
+ * window lapses, while the rendered window (and so its cursor) stays valid.
+ * Entries are two short strings, so the cap matches the client-state cap.
+ */
+const windowOlderCursors = new Map<string, MessageRoundCursor | null>();
+
+const recordWindowOlderCursor = (
+ identity: string,
+ cursor: MessageRoundCursor | null | undefined,
+) => {
+ windowOlderCursors.delete(identity);
+ if (cursor === undefined) return;
+ windowOlderCursors.set(identity, cursor);
+ if (windowOlderCursors.size > MAX_MESSAGE_LIST_CLIENT_STATES) {
+ const oldest = windowOlderCursors.keys().next().value;
+ if (oldest !== undefined) windowOlderCursors.delete(oldest);
+ }
+};
+
/**
* 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
@@ -47,11 +95,13 @@ interface EarlierHistoryState {
anchorId: string;
cacheScope: string;
context: CanonicalMessageListContext;
- /** A `before` page came back empty: the very beginning has been reached. */
+ /** The topic start has been loaded: nothing older remains to fetch. */
exhausted: boolean;
loading: boolean;
/** Ascending rows strictly older than `anchorId`. */
messages: UIChatMessage[];
+ /** Cursor for the page older than `messages`; `undefined` until a page reports one. */
+ olderCursor?: MessageRoundCursor;
}
const earlierHistoryStates = new Map<string, EarlierHistoryState>();
@@ -106,9 +156,24 @@ const mergeEarlierHistory = (identity: string, fresh: UIChatMessage[]): UIChatMe
return [...prefix, ...fresh].sort(byCreatedAtAscending);
};
+/**
+ * Where the next older page starts: the last loaded page's cursor once history
+ * was extended, otherwise the window's. `null` β†’ the start is loaded;
+ * `undefined` β†’ unknown, derive it from the oldest loaded row.
+ */
+const resolveOlderCursor = (
+ identity: string,
+ state: EarlierHistoryState | undefined,
+): MessageRoundCursor | null | undefined =>
+ state && state.messages.length > 0 ? state.olderCursor : windowOlderCursors.get(identity);
+
export const getEarlierHistoryStatus = (context: MessageListQueryContext) => {
- const state = earlierHistoryStates.get(getMessageListCacheIdentity(context));
- return { exhausted: state?.exhausted ?? false, loading: state?.loading ?? false };
+ const identity = getMessageListCacheIdentity(context);
+ const state = earlierHistoryStates.get(identity);
+ return {
+ exhausted: (state?.exhausted ?? false) || resolveOlderCursor(identity, state) === null,
+ loading: state?.loading ?? false,
+ };
};
/**
@@ -127,17 +192,33 @@ export const getEarlierHistoryStatus = (context: MessageListQueryContext) => {
export const loadEarlierMessagePage = async (
context: MessageListQueryContext,
getCurrentMessages: () => UIChatMessage[] | undefined,
- fetcher: (before: { createdAt: Date; id: string }) => Promise<UIChatMessage[]>,
+ fetcher: (cursor: MessageRoundCursor) => Promise<MessageListPage>,
): 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 knownCursor = resolveOlderCursor(identity, existing);
+ // The window (or the last page) already reached the topic start.
+ if (knownCursor === null) return undefined;
+ // A cursor-paged conversation shown from the persisted cache before its
+ // revalidation lands has no server cursor yet. A cursor rebuilt from the
+ // oldest row's millisecond `createdAt` would skip older rows sharing that
+ // millisecond, so wait for the window's lossless cursor instead; the next
+ // upward gesture after revalidation pages normally.
+ if (knownCursor === undefined && supportsRoundCursor(context)) return undefined;
+
+ const oldest = getCurrentMessages()?.find((message) => !isSyntheticGroupNode(message));
+ if (!oldest) return undefined;
+
+ // A read path without round cursors: page from the oldest loaded row.
+ const cursor = knownCursor ?? {
+ createdAt: new Date(oldest.createdAt).toISOString(),
+ id: oldest.id,
+ };
const state: EarlierHistoryState = existing ?? {
- anchorId: cursor.id,
+ anchorId: oldest.id,
cacheScope: getCacheScope(),
context: normalizeMessageListQueryContext(context),
exhausted: false,
@@ -149,18 +230,18 @@ export const loadEarlierMessagePage = async (
pruneEarlierHistoryStates();
try {
- const page = await fetcher({ createdAt: new Date(cursor.createdAt), id: cursor.id });
+ const { messages: page, olderCursor } = await fetcher(cursor);
// 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;
- }
+ // Without a reported cursor, `length < pageSize` is NOT a reliable end
+ // signal β€” the round-start trim legitimately shortens full pages β€” so only
+ // an empty page marks the top.
+ if (page.length === 0 || olderCursor === null) state.exhausted = true;
+ state.olderCursor = olderCursor ?? undefined;
+ if (page.length === 0) return undefined;
const pageIds = new Set(page.map((message) => message.id));
state.messages = [
@@ -246,7 +327,9 @@ export const getMessageListFetchPolicy = (context: MessageListQueryContext) => (
revalidateIfStale: !isMessageListServerVerified(context),
});
-type MessageListQuery = (context: CanonicalMessageListContext) => Promise<UIChatMessage[]>;
+type MessageListQuery = (
+ context: CanonicalMessageListContext,
+) => Promise<MessageListPage | UIChatMessage[]>;
const startCurrentGenerationQuery = (
state: MessageListClientState,
@@ -269,9 +352,9 @@ const startCurrentGenerationQuery = (
const request: Promise<UIChatMessage[]> = Promise.resolve()
.then(async () => {
- let messages: UIChatMessage[];
+ let result: MessageListPage | UIChatMessage[];
try {
- messages = await query(state.context);
+ result = await query(state.context);
} catch (error) {
if (state.generation !== requestGeneration) {
return startCurrentGenerationQuery(state, query, true);
@@ -286,6 +369,9 @@ const startCurrentGenerationQuery = (
return startCurrentGenerationQuery(state, query, true);
}
+ const { messages, olderCursor } = Array.isArray(result) ? { messages: result } : result;
+ recordWindowOlderCursor(state.identity, olderCursor);
+
state.verifiedAt = Date.now();
touchState(state);
pruneClientStates();
@@ -352,4 +438,5 @@ export const invalidateMessageListClientState = (
export const clearMessageListClientCacheState = () => {
messageListClientStates.clear();
earlierHistoryStates.clear();
+ windowOlderCursors.clear();
};
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 52868ab70d0..b32b0e699cf 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -21,6 +21,8 @@ import pMap from 'p-map';
import { lambdaClient } from '@/libs/trpc/client';
import { abortableRequest } from '../utils/abortableRequest';
+import type { MessageListPage, MessageRoundCursor } from './cache';
+import { supportsRoundCursor } from './cache';
/**
* Query context for message operations
@@ -50,6 +52,12 @@ interface MessageReadQueryContext {
topicShareId?: string;
}
+/**
+ * Rows walked per round-cursor page: whole rounds up to this many mainline rows,
+ * matching the newest-first window `getMessages` serves.
+ */
+const MESSAGE_PAGE_ROW_BUDGET = 1000;
+
export type MessageBatchOperation =
| {
message: CreateMessageParams;
@@ -217,27 +225,67 @@ export class MessageService {
};
/**
- * Load one round-aligned page of history strictly OLDER than `before` (the
- * oldest already-loaded mainline message). Intentionally outside the
+ * The newest window of a conversation for the message-list cache. Topic
+ * conversations read it by round cursor so the page also says whether any
+ * older history exists (`olderCursor: null` β†’ the topic start is loaded, and
+ * scrolling up must not fetch). Other contexts return the plain list, whose
+ * older history is unknown.
+ */
+ getMessageListPage = async (
+ params: MessageReadQueryContext,
+ ): Promise<MessageListPage | UIChatMessage[]> => {
+ if (!supportsRoundCursor(params)) return this.getMessages(params);
+
+ return this.getMessagesByRoundCursor(params, null);
+ };
+
+ /**
+ * Load one round-aligned page of history strictly OLDER than `cursor` (the
+ * start of the oldest loaded round). 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[]> => {
+ cursor: MessageRoundCursor,
+ ): Promise<MessageListPage> => {
// 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 [];
+ // round cursor: report the start as reached so the shared view keeps its
+ // current window instead of hitting the authed endpoint.
+ if (params.agentShareId) return { messages: [], olderCursor: null };
+
+ if (supportsRoundCursor(params)) return this.getMessagesByRoundCursor(params, cursor);
const data = await lambdaClient.message.getMessages.query({
...params,
- before,
+ before: { createdAt: new Date(cursor.createdAt), id: cursor.id },
includeFileWorks: true,
});
- return data as unknown as UIChatMessage[];
+ return { messages: data as unknown as UIChatMessage[] };
+ };
+
+ private getMessagesByRoundCursor = async (
+ params: MessageReadQueryContext,
+ cursor: MessageRoundCursor | null,
+ ): Promise<MessageListPage> => {
+ const page = await lambdaClient.message.getMessagesByCursor.query({
+ agentId: params.agentId,
+ countBudget: MESSAGE_PAGE_ROW_BUDGET,
+ cursor,
+ groupId: params.groupId,
+ includeFileWorks: true,
+ // The row budget is the real bound; ask for as many whole rounds as it holds.
+ roundLimit: MESSAGE_PAGE_ROW_BUDGET,
+ skipWorks: params.skipWorks,
+ topicId: params.topicId,
+ topicShareId: params.topicShareId,
+ });
+
+ return {
+ messages: page.messages as unknown as UIChatMessage[],
+ olderCursor: page.nextCursor,
+ };
};
diagnoseTopic = async (params: { agentId?: string | null; topicId: string }) => {
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index 4763207fc2a..951171fd63b 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -48,21 +48,26 @@ vi.stubGlobal(
);
// Mock service
-vi.mock('@/services/message', () => ({
- messageService: {
- getMessages: vi.fn(),
- updateMessageError: vi.fn(),
- removeMessage: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
- removeMessagesByAssistant: vi.fn(),
- removeMessages: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
- createMessage: vi.fn(() => Promise.resolve({ id: 'new-message-id', messages: [] })),
- updateMessage: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
- updateMessageMetadata: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
- updateMessagePlugin: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
- updateMessagePluginError: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
- updateMessageRAG: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
- },
-}));
+vi.mock('@/services/message', () => {
+ const getMessages = vi.fn();
+ return {
+ messageService: {
+ getMessages,
+ // The list cache reads pages; tests stub the plain list underneath.
+ getMessageListPage: vi.fn((params) => getMessages(params)),
+ updateMessageError: vi.fn(),
+ removeMessage: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
+ removeMessagesByAssistant: vi.fn(),
+ removeMessages: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
+ createMessage: vi.fn(() => Promise.resolve({ id: 'new-message-id', messages: [] })),
+ updateMessage: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
+ updateMessageMetadata: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
+ updateMessagePlugin: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
+ updateMessagePluginError: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
+ updateMessageRAG: vi.fn(() => Promise.resolve({ success: true, messages: [] })),
+ },
+ };
+});
vi.mock('@/services/topic', () => ({
topicService: {
createTopic: vi.fn(() => Promise.resolve()),
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index e35a2cc362e..e2bb26d6c0b 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -97,18 +97,20 @@ export class MessageQueryActionImpl {
prefetchingMessageKeys.add(messagesKey);
- const request = runMessageListQuery(context, messageService.getMessages).then((messages) => {
- // Re-check at DELIVERY time, not just at start: the user can open this
- // topic and submit a follow-up while the request is in flight. Applying
- // the pre-run snapshot then would drop the freshly created user/assistant
- // rows, and streaming updates targeting those now-missing ids are silent
- // no-ops until terminal reconciliation. Mirrors the defense-in-depth gate
- // in `useFetchMessages`' onData; the SWR cache seed below is unaffected.
- if (!operationSelectors.isAgentRuntimeRunningByContext(context)(this.#get())) {
- this.#get().replaceMessages(messages, { action: 'prefetchMessages', context });
- }
- return messages;
- });
+ const request = runMessageListQuery(context, messageService.getMessageListPage).then(
+ (messages) => {
+ // Re-check at DELIVERY time, not just at start: the user can open this
+ // topic and submit a follow-up while the request is in flight. Applying
+ // the pre-run snapshot then would drop the freshly created user/assistant
+ // rows, and streaming updates targeting those now-missing ids are silent
+ // no-ops until terminal reconciliation. Mirrors the defense-in-depth gate
+ // in `useFetchMessages`' onData; the SWR cache seed below is unaffected.
+ if (!operationSelectors.isAgentRuntimeRunningByContext(context)(this.#get())) {
+ this.#get().replaceMessages(messages, { action: 'prefetchMessages', context });
+ }
+ return messages;
+ },
+ );
try {
await mutate(messageListKey(context), request, { revalidate: false });
@@ -356,7 +358,7 @@ export class MessageQueryActionImpl {
return useClientDataSWRWithSync<UIChatMessage[]>(
shouldFetch ? messageListKey(context) : null,
- () => runMessageListQuery(context, messageService.getMessages),
+ () => runMessageListQuery(context, messageService.getMessageListPage),
{
...getMessageListFetchPolicy(context),
onData: (data) => {