Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(share): overlap first-paint code and data on shared topics (#21082)

Innei6956923360e0
diff --git a/apps/server/src/routers/lambda/__tests__/integration/message.cursorForward.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/message.cursorForward.integration.test.ts
new file mode 100644
index 00000000000..3738c1ecbea
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/message.cursorForward.integration.test.ts
@@ -0,0 +1,115 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { chatGroups, messages, topics, topicShares } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { messageRouter } from '../../message';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ deleteFile: vi.fn().mockResolvedValue(undefined),
+ deleteFiles: vi.fn().mockResolvedValue(undefined),
+ getFileAccessUrl: vi.fn().mockResolvedValue('mock-url'),
+ getFullFileUrl: vi.fn().mockResolvedValue('mock-url'),
+ };
+ }),
+}));
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+describe('message.getMessagesByCursor direction', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+
+ const seedTwoRounds = async (topicId: string, groupId?: string) => {
+ await serverDB.insert(messages).values(
+ [
+ ['fwd-u1', 'user', '2024-01-01T00:00:00.000Z'],
+ ['fwd-a1', 'assistant', '2024-01-01T00:00:01.000Z'],
+ ['fwd-u2', 'user', '2024-01-01T00:00:02.000Z'],
+ ['fwd-a2', 'assistant', '2024-01-01T00:00:03.000Z'],
+ ].map(([id, role, at]) => ({
+ content: id,
+ createdAt: new Date(at),
+ groupId,
+ id,
+ role,
+ topicId,
+ userId,
+ })),
+ );
+ };
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ it('pages forward from the first round and echoes the direction', async () => {
+ const [topic] = await serverDB.insert(topics).values({ userId }).returning();
+ await seedTwoRounds(topic.id);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const first = await caller.getMessagesByCursor({
+ direction: 'forward',
+ roundLimit: 1,
+ topicId: topic.id,
+ });
+ const second = await caller.getMessagesByCursor({
+ cursor: first.nextCursor,
+ direction: 'forward',
+ roundLimit: 1,
+ topicId: topic.id,
+ });
+
+ expect(first.direction).toBe('forward');
+ expect(first.messages.map((m) => m.id)).toEqual(['fwd-u1', 'fwd-a1']);
+ expect(second.messages.map((m) => m.id)).toEqual(['fwd-u2', 'fwd-a2']);
+ expect(second.nextCursor).toBeNull();
+ });
+
+ it('keeps backward as the default and says so', async () => {
+ const [topic] = await serverDB.insert(topics).values({ userId }).returning();
+ await seedTwoRounds(topic.id);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const page = await caller.getMessagesByCursor({ roundLimit: 1, topicId: topic.id });
+
+ expect(page.direction).toBe('backward');
+ expect(page.messages.map((m) => m.id)).toEqual(['fwd-u2', 'fwd-a2']);
+ });
+
+ it("reads a group share from its share id alone, using the topic's own group", async () => {
+ const [group] = await serverDB.insert(chatGroups).values({ userId }).returning();
+ const [topic] = await serverDB.insert(topics).values({ groupId: group.id, userId }).returning();
+ await seedTwoRounds(topic.id, group.id);
+ 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({
+ direction: 'forward',
+ topicShareId: share.id,
+ });
+
+ expect(page.messages.map((m) => m.id)).toEqual(['fwd-u1', 'fwd-a1', 'fwd-u2', 'fwd-a2']);
+
+ await cleanupTestUser(serverDB, visitorId);
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts b/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts
new file mode 100644
index 00000000000..48e9afaf68d
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts
@@ -0,0 +1,136 @@
+import { projectToolViewModels } from '@lobechat/tool-view-model';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { MessageModel } from '@/database/models/message';
+import { TopicShareModel } from '@/database/models/topicShare';
+import type { LobeChatDatabase } from '@/database/type';
+import { FileService } from '@/server/services/file';
+
+import { assertCanUseTopicTargets } from './conversationResourceGuard';
+import { projectSharedTopicMessages } from './projectSharedTopicMessages';
+
+/**
+ * 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;
+
+export const messagesByCursorInputSchema = 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(),
+ direction: z.enum(['backward', 'forward']).optional(),
+ 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(),
+ /** Same opt-in as `getMessages`: render-facing tool view models. */
+ projectToolPayloads: 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(),
+});
+
+interface MessagesByCursorContext {
+ serverDB: LobeChatDatabase;
+ userId?: string | null;
+ workspaceId?: string | null;
+}
+
+/**
+ * One cursor page of a topic's mainline. The response echoes the direction it
+ * was read in: a server that predates `direction` strips the input and answers
+ * with the newest page, and a forward reader must be able to tell.
+ */
+export const readMessagesByCursor = async (
+ ctx: MessagesByCursorContext,
+ input: z.infer<typeof messagesByCursorInputSchema>,
+) => {
+ const {
+ direction = 'backward',
+ projectToolPayloads,
+ 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(
+ {
+ ...queryParams,
+ direction,
+ // The share record already names the topic's group, so a share link
+ // reads with only its id.
+ groupId: queryParams.groupId === undefined ? share.groupId : queryParams.groupId,
+ // Force skipWorks: Work summaries join LIVE task/version state, so serving
+ // them here would leak post-share mutations to anonymous visitors.
+ skipWorks: true,
+ topicId: share.topicId,
+ },
+ {
+ postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
+ },
+ );
+
+ return { ...page, direction, 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(
+ { db: 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, direction, topicId },
+ {
+ postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),
+ },
+ );
+
+ // Same rule as `getMessages`: only the caller knows whether this page is
+ // rendered or fed to a model, so projection is opt-in per read.
+ return projectToolPayloads
+ ? { ...page, direction, messages: projectToolViewModels(page.messages) }
+ : { ...page, direction };
+};
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index bdf001f4fe6..830d364c222 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -32,6 +32,7 @@ import {
assertCanUseTopicTargets,
assertCanViewMessageTargets,
} from './_helpers/conversationResourceGuard';
+import { messagesByCursorInputSchema, readMessagesByCursor } from './_helpers/messagesByCursor';
import { projectSharedTopicMessages } from './_helpers/projectSharedTopicMessages';
import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';
import {
@@ -42,15 +43,6 @@ 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'];
@@ -561,99 +553,14 @@ export const messageRouter = router({
* 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.
+ * Omit `cursor` for the first page; pass a prior `nextCursor` to continue.
+ * `direction: 'forward'` pages from the first round (shared transcripts).
*/
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(),
- /** Same opt-in as `getMessages`: render-facing tool view models. */
- projectToolPayloads: 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 { projectToolPayloads, 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 }),
- },
- );
-
- // Same rule as `getMessages`: only the caller knows whether this page is
- // rendered or fed to a model, so projection is opt-in per read.
- return projectToolPayloads
- ? { ...page, messages: projectToolViewModels(page.messages) }
- : page;
- }),
+ .input(messagesByCursorInputSchema)
+ .query(({ ctx, input }) => readMessagesByCursor(ctx, input)),
rankModels: messageProcedure.query(async ({ ctx }) => {
return ctx.messageModel.rankModels();
diff --git a/apps/share/app/routes/shareTopic.tsx b/apps/share/app/routes/shareTopic.tsx
index 0d906c487af..8c234b2fe15 100644
--- a/apps/share/app/routes/shareTopic.tsx
+++ b/apps/share/app/routes/shareTopic.tsx
@@ -1,12 +1,16 @@
import { BRANDING_NAME } from '@lobechat/business-const';
-import type { LoaderFunctionArgs, MetaFunction } from 'react-router';
+import type { ClientLoaderFunctionArgs, LoaderFunctionArgs, MetaFunction } from 'react-router';
import { useLoaderData } from 'react-router';
import { SWRConfig, unstable_serialize } from 'swr';
import { shareKeys } from '@/libs/swr/keys';
import { resolveRequestLocale } from '@/locales/requestLocale';
-import SharedTopicView from '../../src/features/topic/SharedTopicView';
+import {
+ readSharedTopicFirstPage,
+ sharedTopicMessagesScript,
+} from '../../src/features/topic/sharedConversation';
+import SharedTopicView, { preloadSharedTopic } from '../../src/features/topic/SharedTopicView';
import { buildTopicByline } from '../../src/features/topic/topicByline';
import { loadShareResources } from '../../src/shell/createShareI18n';
import { cloudflareContext } from '../lib/cloudflareContext';
@@ -20,13 +24,19 @@ export const loader = async ({ context, params, request }: LoaderFunctionArgs) =
const client = createServerLambdaClient(request, apiBase);
// SSR data is best-effort: on any backend failure fall back to CSR, where SWR
- // refetches and surfaces the error state exactly as before.
- const topic = await client.share.getSharedTopic.query({ shareId }).catch((error) => {
- console.error('[share] shared topic SSR fetch failed:', error);
- return null;
- });
+ // refetches and surfaces the error state exactly as before. The first rounds
+ // are read with the share id alone, so both reads run side by side.
+ const [topic, { firstPage, messageReadMode }] = await Promise.all([
+ client.share.getSharedTopic.query({ shareId }).catch((error) => {
+ console.error('[share] shared topic SSR fetch failed:', error);
+ return null;
+ }),
+ readSharedTopicFirstPage(client, shareId),
+ ]);
return {
+ firstPage,
+ messageReadMode,
byline: topic ? buildTopicByline(topic) : undefined,
description: shareMetaDescription(await loadShareResources(locale), 'topicDescription'),
locale,
@@ -35,6 +45,19 @@ export const loader = async ({ context, params, request }: LoaderFunctionArgs) =
};
};
+// Runs as the hydrated router initializes. On that first call `serverLoader()`
+// hands back the data already in the document, so this costs no request; it
+// hands the conversation the messages the document carries.
+export const clientLoader = async ({ serverLoader }: ClientLoaderFunctionArgs) => {
+ const data = await serverLoader<typeof loader>();
+ if (data.topic) preloadSharedTopic(data.topic, data);
+
+ return data;
+};
+
+// No `HydrateFallback`: the route keeps hydrating with its server data.
+clientLoader.hydrate = true as const;
+
export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {
const title = loaderData?.topic?.title;
@@ -49,7 +72,11 @@ export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {
};
export default function ShareTopicRoute() {
- const { shareId, topic } = useLoaderData<typeof loader>();
+ const { messageReadMode, shareId, topic } = useLoaderData<typeof loader>();
+ // The document starts the newest-first read only when the server cannot page
+ // forward; reading forward, the first rounds are already in the loader data.
+ const messagesScript =
+ topic && messageReadMode === 'backward' ? sharedTopicMessagesScript(topic) : '';
return (
<SWRConfig
@@ -57,7 +84,8 @@ export default function ShareTopicRoute() {
fallback: topic ? { [unstable_serialize(shareKeys.topic(shareId))]: topic } : {},
}}
>
- <SharedTopicView />
+ {messagesScript && <script dangerouslySetInnerHTML={{ __html: messagesScript }} />}
+ <SharedTopicView messageReadMode={messageReadMode} />
</SWRConfig>
);
}
diff --git a/apps/share/src/features/topic/SharePortal.tsx b/apps/share/src/features/topic/SharePortal.tsx
index e9a43066093..66a0fc8dd27 100644
--- a/apps/share/src/features/topic/SharePortal.tsx
+++ b/apps/share/src/features/topic/SharePortal.tsx
@@ -1,14 +1,14 @@
'use client';
-import { DraggablePanel } from '@lobehub/ui';
-import { createStaticStyles } from '@lobehub/ui';
-import { memo } from 'react';
+import { createStaticStyles, DraggablePanel } from '@lobehub/ui';
+import { lazy, memo, Suspense, useState } from 'react';
import { CHAT_PORTAL_TOOL_UI_WIDTH } from '@/const/layoutTokens';
-import { PortalContent } from '@/features/Portal/router';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import ShareLoading from '../../shell/ShareLoading';
+
const styles = createStaticStyles(({ cssVar, css }) => ({
body: css`
overflow: hidden;
@@ -39,8 +39,19 @@ const styles = createStaticStyles(({ cssVar, css }) => ({
`,
}));
+// Every portal view (artifacts, documents, tasks, goals…) ships with the router,
+// about 1MB gzipped, for a panel that starts collapsed. Loading it on first open
+// keeps it off the download the transcript waits for.
+const PortalContent = lazy(() =>
+ import('@/features/Portal/router').then((module) => ({ default: module.PortalContent })),
+);
+
const SharePortal = memo(() => {
const showPortal = useChatStore(chatPortalSelectors.showPortal);
+ // Latched: once opened the content stays mounted, as it always has, so
+ // closing the panel animates out with its view instead of an empty body.
+ const [opened, setOpened] = useState(showPortal);
+ if (showPortal && !opened) setOpened(true);
return (
<DraggablePanel
@@ -55,7 +66,11 @@ const SharePortal = memo(() => {
showHandleWideArea={false}
size={{ height: '100%', width: CHAT_PORTAL_TOOL_UI_WIDTH }}
>
- <PortalContent renderBody={(body) => <div className={styles.body}>{body}</div>} />
+ {opened && (
+ <Suspense fallback={<ShareLoading />}>
+ <PortalContent renderBody={(body) => <div className={styles.body}>{body}</div>} />
+ </Suspense>
+ )}
</DraggablePanel>
);
});
diff --git a/apps/share/src/features/topic/SharedMessageList.tsx b/apps/share/src/features/topic/SharedMessageList.tsx
index 7aa66d7a2b7..14b3bbc7f4c 100644
--- a/apps/share/src/features/topic/SharedMessageList.tsx
+++ b/apps/share/src/features/topic/SharedMessageList.tsx
@@ -2,31 +2,32 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { Flexbox, Text } from '@lobehub/ui';
-import { memo, type ReactNode, useCallback, useMemo } from 'react';
+import { memo, type ReactNode, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChatList, ConversationProvider, MessageItem } from '@/features/Conversation';
+import { type SharedTopicReadMode, toSharedConversationContext } from './sharedConversation';
+
interface SharedMessageListProps {
agentId: string | null;
groupId: string | null;
headerSlot?: ReactNode;
+ messageReadMode: SharedTopicReadMode;
shareId: string;
topicId: string;
}
const SharedMessageList = memo<SharedMessageListProps>((props) => {
- const { agentId, groupId, headerSlot, shareId, topicId } = props;
+ const { agentId, groupId, headerSlot, messageReadMode, shareId, topicId } = props;
const { t } = useTranslation('chat');
+ const [newestFirstShareId, setNewestFirstShareId] = useState<string>();
+ const readMode = newestFirstShareId === shareId ? 'backward' : messageReadMode;
const context = useMemo(
- () => ({
- agentId: agentId ?? '',
- groupId: groupId ?? undefined,
- topicId,
- topicShareId: shareId,
- }),
- [agentId, groupId, shareId, topicId],
+ () => toSharedConversationContext({ agentId, groupId, shareId, topicId }, readMode),
+ [agentId, groupId, readMode, shareId, topicId],
);
+ const readNewestFirst = useCallback(() => setNewestFirstShareId(shareId), [shareId]);
const itemContent = useCallback(
(index: number, id: string) => <MessageItem disableEditing id={id} index={index} key={id} />,
@@ -38,6 +39,7 @@ const SharedMessageList = memo<SharedMessageListProps>((props) => {
<ChatList
disableActionsBar
headerSlot={headerSlot}
+ initialScrollPosition={'top'}
itemContent={itemContent}
footerSlot={
<Flexbox align={'center'} paddingBlock={24} paddingInline={24}>
@@ -46,6 +48,7 @@ const SharedMessageList = memo<SharedMessageListProps>((props) => {
</Text>
</Flexbox>
}
+ onForwardPagingUnsupported={readNewestFirst}
/>
</ConversationProvider>
);
diff --git a/apps/share/src/features/topic/SharedTopicBody.client.tsx b/apps/share/src/features/topic/SharedTopicBody.client.tsx
index df51680524c..976d619fad1 100644
--- a/apps/share/src/features/topic/SharedTopicBody.client.tsx
+++ b/apps/share/src/features/topic/SharedTopicBody.client.tsx
@@ -7,16 +7,18 @@ import { ShareHero } from '@/business/client/features/ShareShell';
import { shareKeys } from '@/libs/swr/keys';
import { lambdaClient } from '@/libs/trpc/client';
+import { type SharedTopicReadMode } from './sharedConversation';
import SharedMessageList from './SharedMessageList';
import TopicAvatar from './TopicAvatar';
import { buildTopicByline } from './topicByline';
import { useSyncSharedTopicMeta } from './useSyncSharedTopicMeta';
interface SharedTopicBodyProps {
+ messageReadMode: SharedTopicReadMode;
shareId: string;
}
-const SharedTopicBody = memo<SharedTopicBodyProps>(({ shareId }) => {
+const SharedTopicBody = memo<SharedTopicBodyProps>(({ messageReadMode, shareId }) => {
const { data } = useSWR(
shareKeys.topic(shareId),
() => lambdaClient.share.getSharedTopic.query({ shareId }),
@@ -31,6 +33,7 @@ const SharedTopicBody = memo<SharedTopicBodyProps>(({ shareId }) => {
<SharedMessageList
agentId={data.agentId}
groupId={data.groupId}
+ messageReadMode={messageReadMode}
shareId={data.shareId}
topicId={data.topicId}
headerSlot={
diff --git a/apps/share/src/features/topic/SharedTopicView.tsx b/apps/share/src/features/topic/SharedTopicView.tsx
index 8bf89c2953b..591c52a7a60 100644
--- a/apps/share/src/features/topic/SharedTopicView.tsx
+++ b/apps/share/src/features/topic/SharedTopicView.tsx
@@ -12,10 +12,16 @@ import { lambdaClient } from '@/libs/trpc/client';
import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { type SharedTopicData } from '@/types/topic';
import { clientOnly } from '../../shell/clientOnly';
import ShareLayout from '../../shell/ShareLayout';
import ExplainTopic from './ExplainTopic';
+import {
+ primeSharedTopicMessages,
+ type SharedTopicFirstPage,
+ type SharedTopicReadMode,
+} from './sharedConversation';
import TopicAvatar from './TopicAvatar';
import { buildTopicByline } from './topicByline';
@@ -24,7 +30,21 @@ const SharedTopicBody = clientOnly(() =>
);
const SharedTopicAside = clientOnly(() => import('./SharedTopicAside.client'));
-const SharedTopicView = memo(() => {
+/**
+ * Everything the conversation needs before it can paint: its chunk and the
+ * messages the document carries. The route calls this as the hydrated router
+ * initializes, ahead of the body's own mount.
+ */
+export const preloadSharedTopic = (topic: SharedTopicData, firstPage: SharedTopicFirstPage) => {
+ SharedTopicBody.preload();
+ primeSharedTopicMessages(topic, firstPage);
+};
+
+interface SharedTopicViewProps {
+ messageReadMode: SharedTopicReadMode;
+}
+
+const SharedTopicView = memo<SharedTopicViewProps>(({ messageReadMode }) => {
const wideScreen = useGlobalStore(systemStatusSelectors.wideScreen);
const { id } = useParams<{ id: string }>();
@@ -63,7 +83,9 @@ const SharedTopicView = memo(() => {
loading={isLoading && !data}
title={data?.title}
>
- {id && data ? <SharedTopicBody fallback={hero} shareId={id} /> : null}
+ {id && data ? (
+ <SharedTopicBody fallback={hero} messageReadMode={messageReadMode} shareId={id} />
+ ) : null}
</ShareLayout>
);
});
diff --git a/apps/share/src/features/topic/sharedConversation.test.ts b/apps/share/src/features/topic/sharedConversation.test.ts
new file mode 100644
index 00000000000..990832577b2
--- /dev/null
+++ b/apps/share/src/features/topic/sharedConversation.test.ts
@@ -0,0 +1,235 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import superjson from 'superjson';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { MessageService } from '@/services/message';
+import {
+ SHARED_TOPIC_FIRST_PAGE,
+ takePrimedForwardMessagePage,
+ toRoundCursorQueryInput,
+} from '@/services/message/roundCursorPage';
+
+import {
+ primeSharedTopicMessages,
+ readSharedTopicFirstPage,
+ SHARED_TOPIC_FIRST_PAGE_MAX_CHARS,
+ sharedTopicMessagesScript,
+ sharedTopicMessagesUrl,
+ toSharedConversationContext,
+} from './sharedConversation';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ message: {
+ getMessages: { query: vi.fn() },
+ getMessagesByCursor: { query: vi.fn() },
+ },
+ },
+}));
+
+const query = vi.mocked(lambdaClient.message.getMessagesByCursor.query);
+const fetchMock = vi.fn();
+
+let seq = 0;
+const topic = (overrides: Record<string, unknown> = {}) =>
+ ({
+ agentId: 'agent-1',
+ groupId: null,
+ shareId: `share-${++seq}`,
+ topicId: 'topic-1',
+ ...overrides,
+ }) as any;
+
+const BACKWARD = { firstPage: null, messageReadMode: 'backward' } as const;
+
+const trpcBody = (data: unknown) => ({ result: { data: superjson.serialize(data) } });
+
+const runDocumentScript = (shared: ReturnType<typeof topic>) =>
+ new Function(sharedTopicMessagesScript(shared))();
+
+describe('sharedTopicMessagesScript', () => {
+ beforeEach(() => {
+ vi.stubGlobal('fetch', fetchMock);
+ fetchMock.mockReset();
+ query.mockReset();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ delete window.__LOBE_SHARED_TOPIC_MESSAGES__;
+ });
+
+ // The document reads for the list; any other input is a page the list would
+ // not have asked for.
+ it('requests the read the mounted list makes', () => {
+ fetchMock.mockResolvedValue(new Response('{}'));
+ const shared = topic({ groupId: 'group-1' });
+
+ runDocumentScript(shared);
+
+ const [url, init] = fetchMock.mock.calls[0];
+ const input = new URL(url, 'http://share.test').searchParams.get('input')!;
+ expect(superjson.deserialize(JSON.parse(input))).toEqual(
+ toRoundCursorQueryInput(toSharedConversationContext(shared), null),
+ );
+ expect(init).toMatchObject({ credentials: 'include' });
+ expect(window.__LOBE_SHARED_TOPIC_MESSAGES__?.shareId).toBe(shared.shareId);
+ });
+
+ it('cannot be closed by a share id from the URL', () => {
+ const script = sharedTopicMessagesScript(topic({ shareId: '</script><script>alert(1)//' }));
+
+ expect(script).not.toContain('</script');
+ });
+
+ it('skips a share the list would not read', () => {
+ expect(sharedTopicMessagesScript(topic({ agentId: null }))).toBe('');
+ });
+
+ it('hands the document read to the list without a second request', async () => {
+ const shared = topic();
+ fetchMock.mockResolvedValue(
+ new Response(JSON.stringify(trpcBody({ messages: [{ id: 'm1' }], nextCursor: null }))),
+ );
+
+ runDocumentScript(shared);
+ primeSharedTopicMessages(shared, BACKWARD);
+ const page = await new MessageService().getMessageListPage(toSharedConversationContext(shared));
+
+ expect(page).toEqual({ messages: [{ id: 'm1' }], olderCursor: null });
+ expect(query).not.toHaveBeenCalled();
+ expect(window.__LOBE_SHARED_TOPIC_MESSAGES__).toBeUndefined();
+ });
+
+ it('lets the list read for itself when the document read failed', async () => {
+ const shared = topic();
+ fetchMock.mockResolvedValue(new Response('{}', { status: 500 }));
+ query.mockResolvedValue({
+ hasMore: false,
+ messages: [{ id: 'retry' }],
+ nextCursor: null,
+ } as any);
+
+ runDocumentScript(shared);
+ primeSharedTopicMessages(shared, BACKWARD);
+ const page = await new MessageService().getMessageListPage(toSharedConversationContext(shared));
+
+ expect(page).toEqual({ messages: [{ id: 'retry' }], olderCursor: null });
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it('is not handed to another share', async () => {
+ const shared = topic();
+ fetchMock.mockResolvedValue(new Response('{}'));
+ query.mockResolvedValue({ hasMore: false, messages: [], nextCursor: null } as any);
+
+ runDocumentScript(shared);
+ const other = topic();
+ primeSharedTopicMessages(other, BACKWARD);
+ await new MessageService().getMessageListPage(toSharedConversationContext(other));
+
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(sharedTopicMessagesUrl(other)).not.toBe(sharedTopicMessagesUrl(shared));
+ });
+});
+
+describe('readSharedTopicFirstPage', () => {
+ const serverClient = (impl: () => Promise<unknown>) => {
+ const serverQuery = vi.fn(impl);
+ return {
+ client: { message: { getMessagesByCursor: { query: serverQuery } } } as any,
+ serverQuery,
+ };
+ };
+
+ it('leaves a first page too large to embed to the client, still forward', async () => {
+ const heavy = 'x'.repeat(SHARED_TOPIC_FIRST_PAGE_MAX_CHARS);
+ const { client } = serverClient(async () => ({
+ direction: 'forward',
+ hasMore: true,
+ messages: [{ content: heavy, id: 'u1' }],
+ nextCursor: null,
+ }));
+
+ await expect(readSharedTopicFirstPage(client, 'share-heavy')).resolves.toEqual({
+ firstPage: null,
+ messageReadMode: 'forward',
+ });
+ });
+
+ it('reads the first rounds forward from the share id alone', async () => {
+ const page = {
+ direction: 'forward',
+ hasMore: true,
+ messages: [{ id: 'u1' }],
+ nextCursor: null,
+ };
+ const { client, serverQuery } = serverClient(async () => page);
+
+ const result = await readSharedTopicFirstPage(client, 'share-x');
+
+ expect(result).toEqual({
+ firstPage: { messages: [{ id: 'u1' }], newerCursor: null },
+ messageReadMode: 'forward',
+ });
+ expect(serverQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ countBudget: SHARED_TOPIC_FIRST_PAGE.countBudget,
+ direction: 'forward',
+ roundLimit: SHARED_TOPIC_FIRST_PAGE.roundLimit,
+ topicShareId: 'share-x',
+ }),
+ );
+ });
+
+ it('falls back to the newest-first page when the server cannot page forward', async () => {
+ const { client } = serverClient(async () => ({
+ hasMore: false,
+ messages: [],
+ nextCursor: null,
+ }));
+
+ expect(await readSharedTopicFirstPage(client, 'share-x')).toEqual({
+ firstPage: null,
+ messageReadMode: 'backward',
+ });
+ });
+
+ it('leaves a failed read to the client while still paging forward', async () => {
+ const { client } = serverClient(async () => {
+ throw new Error('upstream 502');
+ });
+
+ expect(await readSharedTopicFirstPage(client, 'share-x')).toEqual({
+ firstPage: null,
+ messageReadMode: 'forward',
+ });
+ });
+});
+
+describe('primeSharedTopicMessages forward', () => {
+ afterEach(() => {
+ delete window.__LOBE_SHARED_TOPIC_MESSAGES__;
+ });
+
+ it('hands the embedded first page to the forward list', async () => {
+ const shared = topic();
+ const firstPage = { messages: [{ id: 'u1' }] as any, newerCursor: null };
+
+ primeSharedTopicMessages(shared, { firstPage, messageReadMode: 'forward' });
+
+ await expect(
+ takePrimedForwardMessagePage(toSharedConversationContext(shared, 'forward')),
+ ).resolves.toEqual(firstPage);
+ });
+
+ it('marks the forward context so it reads apart from the newest-first list', () => {
+ expect(toSharedConversationContext(topic(), 'forward')).toMatchObject({
+ messageReadMode: 'forward',
+ });
+ expect(toSharedConversationContext(topic(), 'backward')).not.toHaveProperty('messageReadMode');
+ });
+});
diff --git a/apps/share/src/features/topic/sharedConversation.ts b/apps/share/src/features/topic/sharedConversation.ts
new file mode 100644
index 00000000000..61b3815de5f
--- /dev/null
+++ b/apps/share/src/features/topic/sharedConversation.ts
@@ -0,0 +1,164 @@
+import { CLIENT_VERSION_HEADER, CURRENT_VERSION } from '@lobechat/const';
+import { type ConversationContext } from '@lobechat/types';
+import superjson, { type SuperJSONResult } from 'superjson';
+
+import {
+ type ForwardMessagePage,
+ ForwardPagingUnsupportedError,
+ primeForwardMessagePage,
+ primeMessageListPage,
+ readMessagesForward,
+ type RoundCursorQueryResult,
+ SHARED_TOPIC_FIRST_PAGE,
+ toMessageListPage,
+ toRoundCursorQueryInput,
+} from '@/services/message/roundCursorPage';
+import { type SharedTopicData } from '@/types/topic';
+
+type SharedTopicTarget = Pick<SharedTopicData, 'agentId' | 'groupId' | 'shareId' | 'topicId'>;
+
+interface DocumentSharedTopicMessages {
+ response: Promise<unknown>;
+ shareId: string;
+}
+
+declare global {
+ interface Window {
+ __LOBE_SHARED_TOPIC_MESSAGES__?: DocumentSharedTopicMessages;
+ }
+}
+
+/**
+ * The conversation a share link shows. The rendered list and the primed read
+ * must build it identically, or the list misses the primed page and asks again.
+ */
+export const toSharedConversationContext = (
+ topic: SharedTopicTarget,
+ readMode: SharedTopicReadMode = 'backward',
+): ConversationContext => ({
+ agentId: topic.agentId ?? '',
+ groupId: topic.groupId ?? undefined,
+ ...(readMode === 'forward' && { messageReadMode: 'forward' as const }),
+ topicId: topic.topicId,
+ topicShareId: topic.shareId,
+});
+
+export type SharedTopicReadMode = 'backward' | 'forward';
+
+/** How the share document reads its transcript, decided once by the loader. */
+export interface SharedTopicFirstPage {
+ /** The first rounds, embedded in the document; null when the client reads them. */
+ firstPage: ForwardMessagePage | null;
+ messageReadMode: SharedTopicReadMode;
+}
+
+type ForwardReadClient = Parameters<typeof readMessagesForward>[0];
+
+/**
+ * Serialized size above which the first page stays out of the document. The
+ * worker buffers the whole HTML before sending it, so one heavy first round
+ * (a long agent run with tool payloads) would hold back the first paint; the
+ * client reads such a page itself, in parallel with the code.
+ */
+export const SHARED_TOPIC_FIRST_PAGE_MAX_CHARS = 256 * 1024;
+
+/**
+ * Read a share's first rounds forward for the document. A server that cannot
+ * page forward keeps the page on the newest-first read; any other failure
+ * leaves the first page to the client, still forward.
+ */
+export const readSharedTopicFirstPage = async (
+ client: ForwardReadClient,
+ shareId: string,
+): Promise<SharedTopicFirstPage> => {
+ try {
+ const firstPage = await readMessagesForward(
+ client,
+ { topicShareId: shareId },
+ null,
+ SHARED_TOPIC_FIRST_PAGE,
+ );
+ if (JSON.stringify(firstPage.messages).length > SHARED_TOPIC_FIRST_PAGE_MAX_CHARS)
+ return { firstPage: null, messageReadMode: 'forward' };
+ return { firstPage, messageReadMode: 'forward' };
+ } catch (error) {
+ if (error instanceof ForwardPagingUnsupportedError) {
+ return { firstPage: null, messageReadMode: 'backward' };
+ }
+ console.error('[share] shared topic first page SSR fetch failed:', error);
+ return { firstPage: null, messageReadMode: 'forward' };
+ }
+};
+
+/** The list's first read of the share, as the unbatched tRPC GET the lambda route serves. */
+export const sharedTopicMessagesUrl = (topic: SharedTopicTarget) => {
+ const input = superjson.serialize(
+ toRoundCursorQueryInput(toSharedConversationContext(topic), null),
+ );
+
+ return `/trpc/lambda/message.getMessagesByCursor?input=${encodeURIComponent(JSON.stringify(input))}`;
+};
+
+// `shareId` comes from the URL: escape everything that could end the script.
+const toScriptLiteral = (value: string) =>
+ JSON.stringify(value)
+ .replaceAll('<', String.raw`\u003c`)
+ .replaceAll('\u2028', String.raw`\u2028`)
+ .replaceAll('\u2029', String.raw`\u2029`);
+
+/**
+ * An inline script that requests the share's newest messages while the document
+ * parses, alongside the module downloads instead of after them. Empty for a
+ * share the list would not read: it only reads a conversation it can attribute
+ * to an agent (`useFetchMessages`).
+ */
+export const sharedTopicMessagesScript = (topic: SharedTopicTarget) => {
+ if (!topic.agentId) return '';
+
+ const url = toScriptLiteral(sharedTopicMessagesUrl(topic));
+ const headers = `{${toScriptLiteral(CLIENT_VERSION_HEADER)}:${toScriptLiteral(CURRENT_VERSION)}}`;
+
+ return [
+ `var r=fetch(${url},{credentials:'include',headers:${headers}})`,
+ `.then(function(res){if(!res.ok)throw new Error(res.status);return res.json()});`,
+ `r.catch(function(){});`,
+ `window.__LOBE_SHARED_TOPIC_MESSAGES__={response:r,shareId:${toScriptLiteral(topic.shareId)}};`,
+ ].join('');
+};
+
+const takeDocumentSharedTopicMessages = (shareId: string) => {
+ const started = window.__LOBE_SHARED_TOPIC_MESSAGES__;
+ if (started?.shareId !== shareId) return;
+
+ delete window.__LOBE_SHARED_TOPIC_MESSAGES__;
+
+ return started.response.then((body) =>
+ toMessageListPage(
+ superjson.deserialize<RoundCursorQueryResult>(
+ (body as { result: { data: SuperJSONResult } }).result.data,
+ ),
+ ),
+ );
+};
+
+/**
+ * Hand the messages the document carries to the list, so it paints without
+ * waiting for its own read: the embedded first rounds when reading forward,
+ * else the newest page the document's script started. Taken once: a later
+ * navigation's list reads for itself.
+ */
+export const primeSharedTopicMessages = (
+ topic: SharedTopicTarget,
+ { firstPage, messageReadMode }: SharedTopicFirstPage,
+) => {
+ if (messageReadMode === 'forward') {
+ if (firstPage)
+ primeForwardMessagePage(toSharedConversationContext(topic, 'forward'), firstPage);
+ return;
+ }
+
+ const page = takeDocumentSharedTopicMessages(topic.shareId);
+ if (!page) return;
+
+ primeMessageListPage(toSharedConversationContext(topic), page);
+};
diff --git a/apps/share/src/shell/clientOnly.test.ts b/apps/share/src/shell/clientOnly.test.ts
new file mode 100644
index 00000000000..e9da320c029
--- /dev/null
+++ b/apps/share/src/shell/clientOnly.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { clientOnly } from './clientOnly';
+
+const Loaded = () => null;
+
+describe('clientOnly preload', () => {
+ it('requests the chunk once however often it is preloaded', () => {
+ const importFn = vi.fn(async () => ({ default: Loaded }));
+ const View = clientOnly(importFn);
+
+ View.preload();
+ View.preload();
+
+ expect(importFn).toHaveBeenCalledTimes(1);
+ });
+
+ it('asks again after a failed download', async () => {
+ const importFn = vi
+ .fn<() => Promise<{ default: typeof Loaded }>>()
+ .mockRejectedValueOnce(new Error('chunk'))
+ .mockResolvedValueOnce({ default: Loaded });
+ const View = clientOnly(importFn);
+
+ View.preload();
+ await vi.waitFor(() => expect(importFn).toHaveBeenCalledTimes(1));
+ // Let the rejection clear the cached request before asking again.
+ await new Promise((resolve) => setTimeout(resolve));
+ View.preload();
+
+ expect(importFn).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/share/src/shell/clientOnly.tsx b/apps/share/src/shell/clientOnly.tsx
index c818fd95284..31aa113027f 100644
--- a/apps/share/src/shell/clientOnly.tsx
+++ b/apps/share/src/shell/clientOnly.tsx
@@ -18,13 +18,24 @@ const useHydrated = () =>
*
* `fallback` is what the document ships and what hydration matches; pass the
* static half of the view there so the client takeover is not a visible swap.
+ *
+ * `preload()` starts the download ahead of the post-hydration render that would
+ * otherwise request it; the render then joins that same request.
*/
export const clientOnly = <P extends object>(
importFn: () => Promise<{ default: ComponentType<P> }>,
) => {
- const Component = lazy(importFn);
+ let loading: Promise<{ default: ComponentType<P> }> | undefined;
+ const load = () =>
+ (loading ??= importFn().catch((error) => {
+ // Clear a failed download so a later `preload()` asks again.
+ loading = undefined;
+ throw error;
+ }));
+
+ const Component = lazy(load);
- return function ClientOnly({ fallback, ...props }: P & { fallback?: ReactNode }) {
+ const ClientOnly = ({ fallback, ...props }: P & { fallback?: ReactNode }) => {
const hydrated = useHydrated();
if (!hydrated) return fallback ?? null;
@@ -35,4 +46,11 @@ export const clientOnly = <P extends object>(
</Suspense>
);
};
+
+ return Object.assign(ClientOnly, {
+ preload: () => {
+ // The render reports a failure through its boundary; a warm-up has no one to tell.
+ load().catch(() => {});
+ },
+ });
};
diff --git a/eslint.bundleBoundaries.mjs b/eslint.bundleBoundaries.mjs
new file mode 100644
index 00000000000..cd026009356
--- /dev/null
+++ b/eslint.bundleBoundaries.mjs
@@ -0,0 +1,69 @@
+// Bundle-size import boundaries for src/**, shared by eslint.config.mjs. These
+// keep real import() seams in place instead of relying on component-level
+// conditional rendering.
+
+// Shared by every src/** no-restricted-imports block: flat config replaces a
+// rule per file instead of merging it, so a scoped override would otherwise
+// drop these.
+export const performanceRestrictedImportPaths = [
+ {
+ allowTypeImports: true,
+ importNames: ['ModelIcon', 'ModelTag', 'ProviderCombine', 'ProviderIcon'],
+ message:
+ 'These features statically import every brand icon (~3 MB). Import them from "@/components/LobeIcons", which mounts them through lazy().',
+ name: '@lobehub/icons',
+ },
+ {
+ allowTypeImports: true,
+ message:
+ 'Import ProviderIcon / ProviderCombine from "@/components/LobeIcons", which mounts them through lazy().',
+ name: '@/libs/providerIcon',
+ },
+ {
+ allowTypeImports: true,
+ importNames: ['EmojiPicker'],
+ message:
+ 'EmojiPicker carries the emoji-mart dataset. Use "@/components/EmojiPicker", which mounts it through lazy().',
+ name: '@lobehub/ui',
+ },
+ {
+ message:
+ 'Import the imperative facade from "@/features/ShareModal" so the modal implementation stays outside initial chunks.',
+ name: '@/features/ShareModal/Modal',
+ },
+ {
+ allowTypeImports: true,
+ importNames: ['motion', 'm'],
+ message:
+ 'The app runs under <LazyMotion features={domMax}>; `motion` bundles every feature again and `m` from the barrel drags it along. Use `import * as m from "motion/react-m"`.',
+ name: 'motion/react',
+ },
+ {
+ allowTypeImports: true,
+ message:
+ 'Do not import the model-bank root barrel; it re-exports the full aiModels catalog (1.4 MB raw). Use a subpath such as "model-bank/aiModel", "model-bank/modelProvider", "model-bank/standardParameters" or "model-bank/utils".',
+ name: 'model-bank',
+ },
+];
+
+// Relative imports inside a feature never match a `paths` name, so the modal
+// seams that features reach through relative paths are guarded by pattern.
+export const performanceRestrictedImportPatterns = [
+ {
+ message:
+ 'Import the facade from "ShareMessageModal" (openShareMessageModal), which loads the modal with its screenshot and PDF libraries on click.',
+ regex: String.raw`(^|/)ShareMessageModal/Content$`,
+ },
+];
+
+// Bundle boundary for browser code: these entries work there but drag a large
+// graph into every chunk that reaches them. Server-side trees opt out with
+// `serverSide: true`, where the full runtime is the point.
+export const browserBundleRestrictedImportPaths = [
+ {
+ allowTypeImports: true,
+ message:
+ 'The @lobechat/model-runtime root re-exports every provider with its SDK (~420 KB gzipped on the share page). Import a subpath such as "@lobechat/model-runtime/errors", and enums like AgentRuntimeErrorType from "@lobechat/types".',
+ name: '@lobechat/model-runtime',
+ },
+];
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 1b026eb5c66..fe4458f0228 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -5,54 +5,16 @@ import { eslint } from '@lobehub/lint';
import { restrictedImports } from '@lobehub/ui/eslint';
import { flat as mdxFlat } from 'eslint-plugin-mdx';
+import {
+ browserBundleRestrictedImportPaths,
+ performanceRestrictedImportPaths,
+ performanceRestrictedImportPatterns,
+} from './eslint.bundleBoundaries.mjs';
+
const tsconfigRootDir = fileURLToPath(new URL('.', import.meta.url));
const baseRestrictedImportOptions = restrictedImports.rules['no-restricted-imports'][1];
-// Shared by every src/** no-restricted-imports block: flat config replaces a
-// rule per file instead of merging it, so a scoped override would otherwise
-// drop these.
-const performanceRestrictedImportPaths = [
- {
- allowTypeImports: true,
- importNames: ['ModelIcon', 'ModelTag', 'ProviderCombine', 'ProviderIcon'],
- message:
- 'These features statically import every brand icon (~3 MB). Import them from "@/components/LobeIcons", which mounts them through lazy().',
- name: '@lobehub/icons',
- },
- {
- allowTypeImports: true,
- message:
- 'Import ProviderIcon / ProviderCombine from "@/components/LobeIcons", which mounts them through lazy().',
- name: '@/libs/providerIcon',
- },
- {
- allowTypeImports: true,
- importNames: ['EmojiPicker'],
- message:
- 'EmojiPicker carries the emoji-mart dataset. Use "@/components/EmojiPicker", which mounts it through lazy().',
- name: '@lobehub/ui',
- },
- {
- message:
- 'Import the imperative facade from "@/features/ShareModal" so the modal implementation stays outside initial chunks.',
- name: '@/features/ShareModal/Modal',
- },
- {
- allowTypeImports: true,
- importNames: ['motion', 'm'],
- message:
- 'The app runs under <LazyMotion features={domMax}>; `motion` bundles every feature again and `m` from the barrel drags it along. Use `import * as m from "motion/react-m"`.',
- name: 'motion/react',
- },
- {
- allowTypeImports: true,
- message:
- 'Do not import the model-bank root barrel; it re-exports the full aiModels catalog (1.4 MB raw). Use a subpath such as "model-bank/aiModel", "model-bank/modelProvider", "model-bank/standardParameters" or "model-bank/utils".',
- name: 'model-bank',
- },
-];
-
// On desktop the shell — every NavPanelPortal sidebar, the titlebar, the command
// menu — renders as a sibling of TabHost, so React context binds these hooks to
// the frozen root router while page content lives in per-tab memory routers.
@@ -256,11 +218,13 @@ const createRestrictedImportRule = ({ paths = [], patterns, serverSide = false }
...(baseRestrictedImportOptions.paths ?? []),
...performanceRestrictedImportPaths,
...(serverSide ? [] : browserRuntimeRestrictedImportPaths),
+ ...(serverSide ? [] : browserBundleRestrictedImportPaths),
...paths,
],
patterns: [
...(baseRestrictedImportOptions.patterns ?? []),
...runtimeRestrictedImportPatterns,
+ ...performanceRestrictedImportPatterns,
...(serverSide ? [] : browserRuntimeRestrictedImportPatterns),
...(patterns ?? []),
],
@@ -375,7 +339,7 @@ export default eslint(
// Performance import boundaries. These restrictions preserve real import()
// seams instead of relying on component-level conditional rendering.
{
- files: ['src/**/*.{ts,tsx}'],
+ files: ['src/**/*.{ts,tsx}', 'apps/share/src/**/*.{ts,tsx}'],
rules: {
'no-restricted-imports': createRestrictedImportRule(),
},
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index c54a0250afc..6365a94cd82 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -106,6 +106,7 @@
"builtinCopilot": "Built-in Copilot",
"chatList.earlierHistoryError": "Couldn't load earlier messages",
"chatList.expandMessage": "Expand Message",
+ "chatList.laterHistoryError": "Couldn't load later messages",
"chatList.longMessageDetail": "View Details",
"chatList.refreshError": "Couldn't refresh messages",
"chatList.refreshing": "Fetching latest messages…",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 184bb743b87..c73f38a4ff1 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -106,6 +106,7 @@
"builtinCopilot": "内置 Copilot",
"chatList.earlierHistoryError": "未能加载更早的消息",
"chatList.expandMessage": "展开消息",
+ "chatList.laterHistoryError": "未能加载后续消息",
"chatList.longMessageDetail": "查看详情",
"chatList.refreshError": "未能刷新消息",
"chatList.refreshing": "正在拉取最新消息…",
diff --git a/packages/database/src/models/__tests__/messages/cursorQueryTestUtils.ts b/packages/database/src/models/__tests__/messages/cursorQueryTestUtils.ts
new file mode 100644
index 00000000000..f0a58c85912
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/cursorQueryTestUtils.ts
@@ -0,0 +1,55 @@
+import { messages, topics } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+
+/**
+ * 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.
+ */
+export const seedCursorRounds = async (
+ serverDB: LobeChatDatabase,
+ userId: string,
+ 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 };
+};
diff --git a/packages/database/src/models/__tests__/messages/message.cursor-query.forward.test.ts b/packages/database/src/models/__tests__/messages/message.cursor-query.forward.test.ts
new file mode 100644
index 00000000000..84a80fe66f5
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.cursor-query.forward.test.ts
@@ -0,0 +1,216 @@
+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 { chatGroups, messageGroups, messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+import { seedCursorRounds } from './cursorQueryTestUtils';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'cursor-forward-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));
+});
+
+const walkForward = async (
+ params: { countBudget?: number; groupId?: string; roundLimit: number; topicId: string },
+ maxPages = 20,
+) => {
+ const pages: string[][] = [];
+ let cursor: any = null;
+ for (let i = 0; i < maxPages; i += 1) {
+ const page = await messageModel.queryTopicMessagesByCursor({
+ ...params,
+ cursor,
+ direction: 'forward',
+ });
+ pages.push(page.messages.map((m) => m.id));
+ if (!page.hasMore) {
+ expect(page.nextCursor).toBeNull();
+ break;
+ }
+ cursor = page.nextCursor;
+ }
+ return pages;
+};
+
+describe('MessageModel.queryTopicMessagesByCursor forward', () => {
+ it('starts at the first round and ends before the next round start', async () => {
+ const topicId = 't-fwd-first';
+ const { ids } = await seedCursorRounds(serverDB, userId, topicId, 5, 2);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ direction: 'forward',
+ roundLimit: 2,
+ topicId,
+ });
+
+ expect(page.messages.map((m) => m.id)).toEqual(ids.slice(0, 6));
+ expect(page.hasMore).toBe(true);
+ expect(page.nextCursor).toEqual({ createdAt: expect.any(String), id: `${topicId}-a2-2` });
+ });
+
+ it('walks every round once, in order, with no gaps', async () => {
+ const topicId = 't-fwd-walk';
+ const { ids } = await seedCursorRounds(serverDB, userId, topicId, 5, 2);
+
+ const pages = await walkForward({ roundLimit: 2, topicId });
+
+ expect(pages).toHaveLength(3);
+ expect(pages.flat()).toEqual(ids);
+ for (const page of pages) expect(page[0]).toMatch(/-u\d+$/);
+ });
+
+ it('ends at the last round boundary once the row budget is walked', async () => {
+ const topicId = 't-fwd-budget';
+ const { ids } = await seedCursorRounds(serverDB, userId, topicId, 4, 2);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ countBudget: 5,
+ direction: 'forward',
+ roundLimit: 10,
+ topicId,
+ });
+
+ expect(page.messages.map((m) => m.id)).toEqual(ids.slice(0, 3));
+ expect(page.hasMore).toBe(true);
+ });
+
+ it('splits a first round larger than the budget and continues it on the next page', async () => {
+ const topicId = 't-fwd-oversized';
+ const { ids } = await seedCursorRounds(serverDB, userId, topicId, 2, 9);
+
+ const pages = await walkForward({ countBudget: 4, roundLimit: 1, topicId });
+
+ expect(pages[0]).toEqual(ids.slice(0, 4));
+ expect(pages.flat()).toEqual(ids);
+ });
+
+ it('returns an empty page with no cursor for an empty topic', async () => {
+ const topicId = 't-fwd-empty';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ direction: 'forward',
+ topicId,
+ });
+
+ expect(page).toEqual({ hasMore: false, messages: [], nextCursor: null });
+ });
+
+ it('keeps microsecond boundaries exact across forward pages', async () => {
+ const topicId = 't-fwd-micros';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+ const roles = ['user', 'assistant', 'user', 'assistant', 'user', 'assistant'];
+ const ids: string[] = [];
+ let prev: string | null = null;
+ for (let i = 0; i < 6; i += 1) {
+ const id = `${topicId}-m${i + 1}`;
+ await serverDB.insert(messages).values({
+ content: `c${i + 1}`,
+ createdAt: sql`${`2023-01-01T00:00:00.${String(i + 1).padStart(6, '0')}Z`}::timestamptz`,
+ id,
+ parentId: prev,
+ role: roles[i] as any,
+ topicId,
+ userId,
+ });
+ ids.push(id);
+ prev = id;
+ }
+
+ const pages = await walkForward({ roundLimit: 1, topicId });
+
+ expect(pages).toHaveLength(3);
+ expect(pages.flat()).toEqual(ids);
+ });
+
+ it('emits every compression group exactly once over a full forward walk', async () => {
+ const topicId = 't-fwd-groups';
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+ const row = (id: string, role: string, at: string, parentId?: string) => ({
+ content: id,
+ createdAt: new Date(at),
+ id: `${topicId}-${id}`,
+ parentId: parentId ? `${topicId}-${parentId}` : undefined,
+ role: role as any,
+ topicId,
+ userId,
+ });
+ await serverDB
+ .insert(messages)
+ .values([
+ row('u1', 'user', '2024-01-01T10:00:00Z'),
+ row('a1', 'assistant', '2024-01-01T10:00:01Z', 'u1'),
+ row('mid1', 'user', '2024-01-01T10:02:00Z', 'a1'),
+ row('mid2', 'assistant', '2024-01-01T10:02:01Z', 'mid1'),
+ row('u2', 'user', '2024-01-01T10:05:00Z', 'mid2'),
+ row('a2', 'assistant', '2024-01-01T10:05:01Z', 'u2'),
+ row('u3', 'user', '2024-01-01T10:06:00Z', 'a2'),
+ row('a3', 'assistant', '2024-01-01T10:06:01Z', 'u3'),
+ ]);
+ await serverDB.insert(messageGroups).values({
+ content: 'summary between round 1 and round 2',
+ createdAt: new Date('2024-01-01T10:03:00Z'),
+ id: `${topicId}-cg`,
+ topicId,
+ type: MessageGroupType.Compression,
+ userId,
+ });
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: `${topicId}-cg` })
+ .where(inArray(messages.id, [`${topicId}-mid1`, `${topicId}-mid2`]));
+
+ const pages = await walkForward({ roundLimit: 1, topicId });
+
+ const groupHits = pages.flat().filter((id) => id === `${topicId}-cg`);
+ expect(groupHits).toHaveLength(1);
+ expect(pages.flat().filter((id) => id !== `${topicId}-cg`)).toEqual(
+ ['u1', 'a1', 'u2', 'a2', 'u3', 'a3'].map((id) => `${topicId}-${id}`),
+ );
+ });
+
+ it('reads a group chat topic through its group id', async () => {
+ const topicId = 't-fwd-group-chat';
+ await serverDB.insert(chatGroups).values([{ id: 'cg-fwd', userId }]);
+ await serverDB.insert(topics).values([{ groupId: 'cg-fwd', id: topicId, userId }]);
+ await serverDB.insert(messages).values([
+ {
+ content: 'q1',
+ createdAt: new Date(2023, 0, 1, 0, 0),
+ groupId: 'cg-fwd',
+ id: `${topicId}-u1`,
+ role: 'user',
+ topicId,
+ userId,
+ },
+ {
+ content: 'a1',
+ createdAt: new Date(2023, 0, 1, 0, 1),
+ groupId: 'cg-fwd',
+ id: `${topicId}-a1`,
+ parentId: `${topicId}-u1`,
+ role: 'assistant',
+ topicId,
+ userId,
+ },
+ ]);
+
+ const pages = await walkForward({ groupId: 'cg-fwd', roundLimit: 1, topicId });
+
+ expect(pages).toEqual([[`${topicId}-u1`, `${topicId}-a1`]]);
+ });
+});
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
index b219494d5e6..33df011b475 100644
--- a/packages/database/src/models/__tests__/messages/message.cursor-query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.cursor-query.test.ts
@@ -8,6 +8,7 @@ import { getTestDB } from '../../../core/getTestDB';
import { agents, chatGroups, messageGroups, messages, topics, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
+import { seedCursorRounds } from './cursorQueryTestUtils';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -25,52 +26,8 @@ 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 };
-};
+const seedRounds = (topicId: string, rounds: number, stepsPerRound: number) =>
+ seedCursorRounds(serverDB, userId, topicId, rounds, stepsPerRound);
describe('MessageModel.queryTopicMessagesByCursor', () => {
it('initial load returns the newest N rounds, round-aligned, with the final answer', async () => {
diff --git a/packages/database/src/models/message/cursorWindow.ts b/packages/database/src/models/message/cursorWindow.ts
new file mode 100644
index 00000000000..3a2386182b5
--- /dev/null
+++ b/packages/database/src/models/message/cursorWindow.ts
@@ -0,0 +1,275 @@
+import type { SQL } from 'drizzle-orm';
+import { and, asc, desc, gt, gte, isNull, lt, or, sql } from 'drizzle-orm';
+
+import { messages } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type { MessageGroupNodeWindow, MessageRoundCursor } from './types';
+
+export interface RowBound {
+ createdAt: string;
+ id: string;
+}
+
+interface WindowRow {
+ createdAtIso: string;
+ id: string;
+ role: string;
+}
+
+/**
+ * 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.
+ */
+const createdAtIso = sql<string>`to_char(${messages.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+
+/**
+ * `(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.
+ */
+export const messageStrictlyBefore = (cursor: MessageRoundCursor) =>
+ or(
+ sql`${messages.createdAt} < ${cursor.createdAt}::timestamptz`,
+ and(sql`${messages.createdAt} = ${cursor.createdAt}::timestamptz`, lt(messages.id, cursor.id)),
+ );
+
+/** `(createdAt, id)` strictly after the cursor — the "newer than" half-open bound. */
+export const messageStrictlyAfter = (cursor: MessageRoundCursor) =>
+ or(
+ sql`${messages.createdAt} > ${cursor.createdAt}::timestamptz`,
+ and(sql`${messages.createdAt} = ${cursor.createdAt}::timestamptz`, gt(messages.id, cursor.id)),
+ );
+
+/** `(createdAt, id)` at or after the lower bound — the inclusive window start. */
+export const messageAtOrAfter = (bound: RowBound) =>
+ or(
+ sql`${messages.createdAt} > ${bound.createdAt}::timestamptz`,
+ and(sql`${messages.createdAt} = ${bound.createdAt}::timestamptz`, gte(messages.id, bound.id)),
+ );
+
+/**
+ * Resolve the round window for a backward 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. Rows
+ * folded into a message group never count toward the window.
+ */
+const resolveBackwardRoundWindow = async (
+ db: LobeChatDatabase,
+ {
+ countBudget,
+ cursor,
+ roundLimit,
+ where,
+ }: {
+ countBudget: number;
+ cursor?: MessageRoundCursor | null;
+ roundLimit: number;
+ where: SQL | undefined;
+ },
+): Promise<{ hasMore: boolean; lowerBound: RowBound | null }> => {
+ const olderThanCursor = cursor ? messageStrictlyBefore(cursor) : undefined;
+
+ const rows = (await db
+ .select({ createdAtIso, id: messages.id, role: messages.role })
+ .from(messages)
+ .where(and(where, isNull(messages.messageGroupId), olderThanCursor))
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(countBudget + 1)) as WindowRow[];
+
+ 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 } };
+};
+
+/**
+ * Resolve the round window for a forward cursor page: walk mainline rows
+ * oldest-first after the cursor and end just before the `(roundLimit + 1)`-th
+ * round start. A page that starts mid-round (the previous page split it) counts
+ * that continuation as its first round. Once `countBudget` rows are walked the
+ * page ends at the last round boundary it holds; when the first round alone is
+ * larger, the page ends at the cap and the next page continues the round.
+ * Returns the first row past the page (the exclusive upper bound) and the last
+ * row in it (the next cursor).
+ */
+const resolveForwardRoundWindow = async (
+ db: LobeChatDatabase,
+ {
+ countBudget,
+ cursor,
+ roundLimit,
+ where,
+ }: {
+ countBudget: number;
+ cursor?: MessageRoundCursor | null;
+ roundLimit: number;
+ where: SQL | undefined;
+ },
+): Promise<{ first: RowBound | null; last: RowBound | null; upperBound: RowBound | null }> => {
+ const newerThanCursor = cursor ? messageStrictlyAfter(cursor) : undefined;
+
+ const rows = (await db
+ .select({ createdAtIso, id: messages.id, role: messages.role })
+ .from(messages)
+ .where(and(where, isNull(messages.messageGroupId), newerThanCursor))
+ .orderBy(asc(messages.createdAt), asc(messages.id))
+ .limit(countBudget + 1)) as WindowRow[];
+
+ if (rows.length === 0) return { first: null, last: null, upperBound: null };
+
+ let rounds = 0;
+ let lastBoundary = -1;
+ let end = rows.length;
+ for (let i = 0; i < rows.length; i += 1) {
+ if (i === 0 || rows[i].role === 'user') {
+ rounds += 1;
+ if (rounds > roundLimit) {
+ end = i;
+ break;
+ }
+ if (i > 0) lastBoundary = i;
+ }
+ if (i + 1 >= countBudget) {
+ end = lastBoundary > 0 ? lastBoundary : i + 1;
+ break;
+ }
+ }
+
+ const toBound = (row: WindowRow): RowBound => ({ createdAt: row.createdAtIso, id: row.id });
+
+ return {
+ first: toBound(rows[0]),
+ last: toBound(rows[end - 1]),
+ upperBound: end < rows.length ? toBound(rows[end]) : null,
+ };
+};
+
+export interface CursorPageWindow {
+ /** MessageGroup nodes assembled with this page; see `MessageGroupNodeWindow`. */
+ groupNodeWindow: MessageGroupNodeWindow;
+ hasMore: boolean;
+ /** Cursor for the next page in the same direction, or null at the end. */
+ nextCursor: MessageRoundCursor | null;
+ /** The page's mainline rows, or `false` for a group-only page. */
+ where: SQL | undefined;
+}
+
+/**
+ * The rows and group nodes of one cursor page. `mainlineWhere` selects the
+ * topic's mainline; `scopeWhere` adds the caller's ownership scope for the
+ * window walk.
+ */
+export const resolveCursorPageWindow = async (
+ db: LobeChatDatabase,
+ {
+ countBudget,
+ cursor,
+ direction,
+ mainlineWhere,
+ roundLimit,
+ scopeWhere,
+ }: {
+ countBudget: number;
+ cursor?: MessageRoundCursor | null;
+ direction: 'backward' | 'forward';
+ mainlineWhere: SQL | undefined;
+ roundLimit: number;
+ scopeWhere: SQL | undefined;
+ },
+): Promise<CursorPageWindow> => {
+ const windowWhere = and(scopeWhere, mainlineWhere);
+
+ if (direction === 'forward') {
+ const { first, last, upperBound } = await resolveForwardRoundWindow(db, {
+ countBudget,
+ cursor,
+ roundLimit,
+ where: windowWhere,
+ });
+ const hasMore = !!upperBound;
+
+ return {
+ // Adjacent pages share a boundary: this page's `before` is the next page's
+ // own first row, which that page uses as `from`, so a group dated between
+ // two pages lands on exactly one of them. The first page leaves the lower
+ // side open and the last page the upper side.
+ groupNodeWindow: {
+ before: upperBound?.createdAt ?? null,
+ from: cursor && first ? first.createdAt : null,
+ },
+ hasMore,
+ nextCursor: hasMore ? last : null,
+ where: first
+ ? and(
+ mainlineWhere,
+ cursor ? messageStrictlyAfter(cursor) : undefined,
+ upperBound ? messageStrictlyBefore(upperBound) : undefined,
+ )
+ : sql`false`,
+ };
+ }
+
+ const { lowerBound, hasMore } = await resolveBackwardRoundWindow(db, {
+ countBudget,
+ cursor,
+ roundLimit,
+ where: windowWhere,
+ });
+
+ return {
+ // 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.
+ groupNodeWindow: {
+ before: cursor?.createdAt ?? null,
+ from: hasMore && lowerBound ? lowerBound.createdAt : null,
+ },
+ hasMore,
+ // `lowerBound.createdAt` is already the lossless microsecond cursor string.
+ nextCursor: hasMore && lowerBound ? lowerBound : 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.
+ where: lowerBound
+ ? and(
+ mainlineWhere,
+ messageAtOrAfter(lowerBound),
+ cursor ? messageStrictlyBefore(cursor) : undefined,
+ )
+ : sql`false`,
+ };
+};
diff --git a/packages/database/src/models/message/query.ts b/packages/database/src/models/message/query.ts
index 12565ae323a..e6fcc7e1f27 100644
--- a/packages/database/src/models/message/query.ts
+++ b/packages/database/src/models/message/query.ts
@@ -12,31 +12,16 @@ import {
runTimedSinkStage as runTimedStage,
} from '@lobechat/utils';
import type { SQL } from 'drizzle-orm';
-import {
- and,
- asc,
- count,
- desc,
- eq,
- gte,
- inArray,
- isNotNull,
- isNull,
- lt,
- ne,
- or,
- sql,
-} from 'drizzle-orm';
+import { and, asc, count, desc, eq, inArray, isNotNull, ne } from 'drizzle-orm';
import { messagePlugins, messages } from '../../schemas';
import { notShareVisitorMessage } from '../../utils/shareVisitor';
+import { resolveCursorPageWindow } from './cursorWindow';
import type { MessageLookupQueries } from './lookup';
import type { MessagePageQueries } from './queryWithWhere';
import type { MessageScopeArgs } from './scope';
import { MessageScope } from './scope';
import type {
- MessageGroupNodeWindow,
- MessageRoundCursor,
ModelTimingContext,
QueryTopicByCursorParams,
TopicMessagesByCursorResult,
@@ -468,6 +453,7 @@ export class MessageConversationQueries extends MessageScope {
{
countBudget = DEFAULT_ROUND_COUNT_BUDGET,
cursor,
+ direction = 'backward',
groupId,
includeFileWorks,
roundLimit = DEFAULT_ROUND_LIMIT,
@@ -498,41 +484,15 @@ export class MessageConversationQueries extends MessageScope {
this.matchThread(undefined),
);
- const { lowerBound, hasMore } = await this.resolveRoundWindow({
+ const { groupNodeWindow, hasMore, nextCursor, where } = await resolveCursorPageWindow(this.db, {
countBudget,
cursor,
+ direction,
mainlineWhere,
roundLimit,
+ scopeWhere: this.ownership(),
});
- // 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.page.queryWithWhere({
allowShareVisitor: true,
current: 0,
@@ -548,90 +508,6 @@ export class MessageConversationQueries extends MessageScope {
groupNodeWindow,
});
- // `lowerBound.createdAt` is already the lossless microsecond cursor string.
- return { hasMore, messages, nextCursor: hasMore && lowerBound ? lowerBound : null };
+ return { hasMore, messages, nextCursor };
};
-
- /**
- * 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)),
- );
}
diff --git a/packages/database/src/models/message/types.ts b/packages/database/src/models/message/types.ts
index edcc147100d..866501efd4e 100644
--- a/packages/database/src/models/message/types.ts
+++ b/packages/database/src/models/message/types.ts
@@ -119,9 +119,10 @@ export interface TopicTranscriptResult {
}
/**
- * Round-boundary cursor for {@link MessageModel.queryTopicMessagesByCursor}. Points
- * at a mainline `user` message (a round start); paging older fetches the rounds
- * strictly before it.
+ * Cursor for {@link MessageModel.queryTopicMessagesByCursor}. Backward, it points
+ * at a mainline `user` message (a round start) and the next page holds the rounds
+ * strictly before it; forward, it points at the last row already loaded (any
+ * role, when a page split a round) and the next page starts strictly after it.
*/
export interface MessageRoundCursor {
createdAt: string;
@@ -137,8 +138,13 @@ export interface QueryTopicByCursorParams {
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. */
+ /**
+ * Omit for the first page (the newest when backward, the oldest when forward);
+ * pass a prior `nextCursor` to continue in the same direction.
+ */
cursor?: MessageRoundCursor | null;
+ /** `backward` (default) pages newest-first toward older rounds; `forward` from the first round. */
+ direction?: 'backward' | 'forward';
/** Group chat topic: rows carry the group id, same filter as `query`. */
groupId?: string | null;
/** See {@link QueryMessageParams.includeFileWorks}. */
@@ -154,7 +160,7 @@ export interface QueryTopicByCursorParams {
export interface TopicMessagesByCursorResult {
hasMore: boolean;
messages: UIChatMessage[];
- /** Cursor to load the previous (older) page, or null when at the topic start. */
+ /** Cursor for the next page in the same direction, or null at the topic's start/end. */
nextCursor: MessageRoundCursor | null;
}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index abda1a353ed..4c6da53314a 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -312,6 +312,7 @@ export default {
'builtinCopilot': 'Built-in Copilot',
'chatList.earlierHistoryError': "Couldn't load earlier messages",
'chatList.expandMessage': 'Expand Message',
+ 'chatList.laterHistoryError': "Couldn't load later messages",
'chatList.longMessageDetail': 'View Details',
'chatList.refreshError': "Couldn't refresh messages",
'chatList.refreshing': 'Fetching latest messages…',
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
index 50d8df83a05..98f46477c88 100644
--- a/packages/replica/src/core/engine.ts
+++ b/packages/replica/src/core/engine.ts
@@ -8,7 +8,9 @@ import {
getNextPageCursor,
hasPagedItem,
insertHeadItems,
+ joinPages,
mapPagedItem,
+ pagingFor,
type ReplicaPagedData,
type ReplicaPageResult,
type ReplicaPagingContext,
@@ -144,6 +146,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
) => {
const { port } = options;
const paging = resource.paging;
+ const at = (key: string) => pagingFor(paging!, key);
const pagingCtx: ReplicaPagingContext<any> = { isClientOnly: options.isClientOnly };
const prefix = options.actionPrefix ?? resource.name;
const writeQueue = resource.storage ? new ReplicaWriteQueue<TData>(resource.storage) : undefined;
@@ -693,7 +696,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
* same-pool query change (a re-sort, a view-mode switch) never drops them.
* A cross-pool navigate is not "client-only" for the new params and is dropped.
*/
- const keepClientOnlyRows = (incoming: TData, current: TData | undefined): TData => {
+ const keepClientOnlyRows = (incoming: TData, current: TData | undefined, key: string): TData => {
if (!paging || !options.isClientOnly || !current) return incoming;
const page = incoming as unknown as ReplicaPagedData<unknown, unknown>;
const currentItems = (current as unknown as ReplicaPagedData<unknown, unknown>).items ?? [];
@@ -702,10 +705,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
(item) => options.isClientOnly!(item) && !incomingIds.has(paging.getId(item)),
);
if (survivors.length === 0) return incoming;
- const items =
- paging.direction === 'forward'
- ? [...survivors, ...page.items]
- : [...page.items, ...survivors];
+ const items = joinPages(survivors, page.items, at(key).direction);
return { ...(incoming as object), items } as TData;
};
@@ -764,7 +764,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
// Entities deleted while the read was in flight may still be in the row.
const stored = withoutRemovedEntities(scope, cached.data);
if (stored === undefined) return false;
- const data = overwrite ? keepClientOnlyRows(stored, port.read(key)) : stored;
+ const data = overwrite ? keepClientOnlyRows(stored, port.read(key), key) : stored;
const applied = dispatch({
data,
key,
@@ -803,7 +803,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const page = incoming as unknown as ReplicaPageResult<unknown, unknown>;
const pageSize = (params as { pageSize?: number }).pageSize ?? page.items.length;
const merged = {
- ...applyHeadPage(confirmed as any, page, { pageSize, reset }, paging!, pagingCtx),
+ ...applyHeadPage(confirmed as any, page, { pageSize, reset }, at(key), pagingCtx),
...options.viewFields?.(params),
isLoadingMore: loadingMore.has(key),
};
@@ -1109,7 +1109,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
if (paging.mode === 'cursor' && entry?.source === 'storage') return;
const params = (entry?.params ?? fallbackParams) as TParams | undefined;
if (params === undefined) return;
- const cursor = getNextPageCursor(current, paging);
+ const cursor = getNextPageCursor(current, at(key));
if (cursor === null || cursor === undefined) return;
const query = entry?.query;
@@ -1136,7 +1136,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
if (!isCurrent()) return void setLoading({ isLoadingMore: false });
update(
key,
- (data) => data && (applyNextPage(data as any, page, paging, pagingCtx) as TData),
+ (data) => data && (applyNextPage(data as any, page, at(key), pagingCtx) as TData),
{ persist: (paging.persist?.pages ?? 1) > 1 },
);
} catch (error) {
@@ -1149,7 +1149,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
/** Insert rows at the head (new / streamed items). */
const insertHead = <TItem>(key: string, items: TItem[], { persist = false } = {}) =>
paging
- ? update(key, (data) => data && (insertHeadItems(data as any, items, paging) as TData), {
+ ? update(key, (data) => data && (insertHeadItems(data as any, items, at(key)) as TData), {
persist,
})
: false;
@@ -1157,7 +1157,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
/** Drop loaded pages, keeping the head (e.g. after an edit inside older pages). */
const collapse = (key: string) =>
paging
- ? update(key, (data) => data && (collapseToHead(data as any, paging) as TData), {
+ ? update(key, (data) => data && (collapseToHead(data as any, at(key)) as TData), {
persist: false,
})
: false;
diff --git a/packages/replica/src/core/paging.ts b/packages/replica/src/core/paging.ts
index ec3176e4a5e..2741b247f84 100644
--- a/packages/replica/src/core/paging.ts
+++ b/packages/replica/src/core/paging.ts
@@ -27,6 +27,12 @@ export interface ReplicaPagingConfig<TItem, TCursor = any> {
*/
deriveCursor?: (item: TItem) => TCursor;
direction: ReplicaPagingDirection;
+ /**
+ * Per-entry direction, for a resource whose entries read differently (a
+ * transcript read from its first round). Defaults to `direction`. Persisting
+ * an entry always uses `direction`, so keep such entries in memory.
+ */
+ directionOf?: (key: string) => ReplicaPagingDirection;
getId: (item: TItem) => string;
/**
* Rows that may anchor a join or derive a cursor. Synthetic rows the query
@@ -129,8 +135,17 @@ const ordered = <TItem>(items: TItem[], config: ReplicaPagingConfig<TItem>) =>
config.sort ? [...items].sort(config.sort) : items;
/** Concatenate in view order: forward = head first, backward = head last. */
-const join = <TItem>(head: TItem[], rest: TItem[], direction: ReplicaPagingDirection) =>
- direction === 'forward' ? [...head, ...rest] : [...rest, ...head];
+export const joinPages = <TItem>(
+ head: TItem[],
+ rest: TItem[],
+ direction: ReplicaPagingDirection,
+) => (direction === 'forward' ? [...head, ...rest] : [...rest, ...head]);
+
+/** The paging config one entry reads with: `directionOf` resolved for `key`. */
+export const pagingFor = <TItem, TCursor>(
+ config: ReplicaPagingConfig<TItem, TCursor>,
+ key: string,
+) => (config.directionOf ? { ...config, direction: config.directionOf(key) } : config);
const deriveHasMore = <TItem, TCursor>(
data: Pick<ReplicaPagedData<TItem, TCursor>, 'items' | 'nextCursor' | 'total'>,
@@ -306,7 +321,7 @@ export const applyHeadPage = <TItem, TCursor>(
anchorId: anchorId ?? current.anchorId,
currentPage: current.currentPage,
headSyntheticIds: syntheticIds(fresh, config),
- items: ordered(join(headItems, rest, direction), config),
+ items: ordered(joinPages(headItems, rest, direction), config),
nextCursor: current.nextCursor,
pageSize: options.pageSize,
pages,
@@ -386,7 +401,7 @@ export const insertHeadItems = <TItem, TCursor>(
const pages = current.pages?.length ? current.pages : [{ count: current.items.length }];
return {
...current,
- items: ordered(join(added, current.items, config.direction), config),
+ items: ordered(joinPages(added, current.items, config.direction), config),
pages: [{ ...pages[0], count: pages[0].count + added.length }, ...pages.slice(1)],
total: current.total === undefined ? undefined : current.total + added.length,
};
diff --git a/packages/replica/src/zustand/pagedSlice.direction.test.ts b/packages/replica/src/zustand/pagedSlice.direction.test.ts
new file mode 100644
index 00000000000..545e46d14ed
--- /dev/null
+++ b/packages/replica/src/zustand/pagedSlice.direction.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createStore } from 'zustand/vanilla';
+
+import { testDriver as driver } from '../../tests/testDriver';
+import { definePagedReplica } from '../core/defineReplica';
+import type { ReplicaPagedData, ReplicaPageResult } from '../core/paging';
+import { createReplicaState } from '../core/reducer';
+import type { ReplicaScope, ReplicaState } from '../core/types';
+import { createReplicaSlice, recordLens } from './createReplicaSlice';
+
+interface Row {
+ id: string;
+}
+interface Params {
+ forward: boolean;
+ topic: string;
+}
+type Paged = ReplicaPagedData<Row, string>;
+interface TestState {
+ rows: Record<string, Paged>;
+ rowsReplica: ReplicaState<Paged>;
+}
+
+const scope: ReplicaScope = { canPersist: () => false, get: () => 'user-1', use: () => 'user-1' };
+
+const page = (items: string[], nextCursor: string | null): ReplicaPageResult<Row, string> => ({
+ items: items.map((id) => ({ id })),
+ nextCursor,
+});
+
+const setup = () => {
+ const fetchPage = vi.fn(async ({ forward }: Params, cursor?: string) =>
+ forward
+ ? cursor === 'after-b'
+ ? page(['c', 'd'], null)
+ : page(['a', 'b'], 'after-b')
+ : cursor === 'before-c'
+ ? page(['a', 'b'], null)
+ : page(['c', 'd'], 'before-c'),
+ );
+ const resource = definePagedReplica<Params, Row, string>({
+ fetchPage,
+ key: ({ forward, topic }) => `${forward ? 'f' : 'b'}:${topic}`,
+ name: 'directionTest',
+ paging: {
+ direction: 'backward',
+ directionOf: (key) => (key.startsWith('f:') ? 'forward' : 'backward'),
+ getId: (item) => item.id,
+ mode: 'cursor',
+ },
+ scope,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({ rows: {}, rowsReplica: createReplicaState() }));
+ const slice = createReplicaSlice(resource, {
+ driver,
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'rowsReplica',
+ view: recordLens<TestState, Paged>('rows'),
+ });
+ return { slice, store };
+};
+
+const ids = (data?: Paged) => data?.items.map((item) => item.id);
+
+describe('paged replica direction per key', () => {
+ it('appends the next page after the head for a forward key', async () => {
+ const { slice, store } = setup();
+ const params = { forward: true, topic: 't1' };
+
+ slice.replace(params, page(['a', 'b'], 'after-b'));
+ await slice.loadMore('f:t1', params);
+
+ expect(ids(store.getState().rows['f:t1'])).toEqual(['a', 'b', 'c', 'd']);
+ expect(store.getState().rows['f:t1']).toMatchObject({ hasMore: false });
+ });
+
+ it('keeps prepending older pages for a key the resolver leaves backward', async () => {
+ const { slice, store } = setup();
+ const params = { forward: false, topic: 't1' };
+
+ slice.replace(params, page(['c', 'd'], 'before-c'));
+ await slice.loadMore('b:t1', params);
+
+ expect(ids(store.getState().rows['b:t1'])).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('keeps appended pages when a forward head is refreshed', async () => {
+ const { slice, store } = setup();
+ const params = { forward: true, topic: 't1' };
+
+ slice.replace(params, page(['a', 'b'], 'after-b'));
+ await slice.loadMore('f:t1', params);
+ slice.replace(params, page(['a', 'b'], 'after-b'));
+
+ expect(ids(store.getState().rows['f:t1'])).toEqual(['a', 'b', 'c', 'd']);
+ });
+});
diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.ts
index 5a20abb9dde..3e4324e89c2 100644
--- a/packages/types/src/conversation.ts
+++ b/packages/types/src/conversation.ts
@@ -187,6 +187,12 @@ export interface ConversationContext {
* - context-engine will restore role back to 'assistant' for model
*/
isSupervisor?: boolean;
+ /**
+ * `forward` reads the transcript from its first round and appends later
+ * rounds (shared topics read from the start). Omitted means the default
+ * newest-first window with older history paged in above.
+ */
+ messageReadMode?: 'forward';
/**
* Orchestration role of the current agent within a group conversation.
* Canonical replacement for {@link isSupervisor} — stamped onto the assistant
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx
index d63d33a5644..2c9a2571df2 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx
@@ -1,6 +1,6 @@
'use client';
-import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import { AgentRuntimeErrorType } from '@lobechat/types';
import { Block, createStaticStyles, cssVar, Flexbox, Icon } from '@lobehub/ui';
import {
ActionIcon,
diff --git a/src/features/Conversation/ChatList/components/EarlierHistoryError.tsx b/src/features/Conversation/ChatList/components/EarlierHistoryError.tsx
deleted file mode 100644
index e11901b5fc9..00000000000
--- a/src/features/Conversation/ChatList/components/EarlierHistoryError.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { memo, useCallback } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import AsyncError from '@/components/AsyncError';
-
-import { useConversationStore } from '../../store';
-
-/**
- * Inline failure row shown above the messages when a page of pre-window
- * history failed to load. Scroll gestures stop re-firing the request while it
- * stands, so Retry is the explicit way back. A retry clears the error as it
- * starts, handing the row over to the skeleton.
- *
- * Like `EarlierHistorySkeleton`, it subscribes to the store itself: virtua
- * caches the leading row's element, so a prop passed from the list would never
- * repaint it.
- */
-const EarlierHistoryError = memo(() => {
- const { t } = useTranslation('chat');
- const error = useConversationStore((s) => s.earlierMessagesError);
- const loadEarlierMessages = useConversationStore((s) => s.loadEarlierMessages);
-
- const handleRetry = useCallback(() => {
- void loadEarlierMessages({ retry: true });
- }, [loadEarlierMessages]);
-
- if (error === undefined) return null;
-
- return (
- <Flexbox horizontal align={'center'} aria-live={'polite'} justify={'center'} role={'status'}>
- <AsyncError
- error={error}
- title={t('chatList.earlierHistoryError')}
- variant={'inline'}
- onRetry={handleRetry}
- />
- </Flexbox>
- );
-});
-
-EarlierHistoryError.displayName = 'EarlierHistoryError';
-
-export default EarlierHistoryError;
diff --git a/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx b/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx
deleted file mode 100644
index 096edff2795..00000000000
--- a/src/features/Conversation/ChatList/components/EarlierHistorySkeleton.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-'use client';
-
-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. 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
- * row would never repaint on a flag change passed down from the list.
- */
-const EarlierHistorySkeleton = memo(() => {
- const isLoading = useConversationStore((s) => s.isLoadingEarlierMessages);
-
- return isLoading ? delayed(<SkeletonList />) : null;
-});
-
-EarlierHistorySkeleton.displayName = 'EarlierHistorySkeleton';
-
-export default EarlierHistorySkeleton;
diff --git a/src/features/Conversation/ChatList/components/HistoryPageError.tsx b/src/features/Conversation/ChatList/components/HistoryPageError.tsx
new file mode 100644
index 00000000000..ac516d22584
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/HistoryPageError.tsx
@@ -0,0 +1,53 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+
+import { useConversationStore } from '../../store';
+import { type HistoryPageSide } from './HistoryPageSkeleton';
+
+/**
+ * Inline failure row shown where a page of history failed to load: above the
+ * messages for earlier history, below them for later rounds. Scroll gestures
+ * stop re-firing the request while it stands, so Retry is the explicit way
+ * back. A retry clears the error as it starts, handing the row over to the
+ * skeleton.
+ *
+ * Like `HistoryPageSkeleton`, it subscribes to the store itself: virtua caches
+ * the slot row's element, so a prop passed from the list would never repaint it.
+ */
+const HistoryPageError = memo<{ side: HistoryPageSide }>(({ side }) => {
+ const { t } = useTranslation('chat');
+ const error = useConversationStore((s) =>
+ side === 'earlier' ? s.earlierMessagesError : s.laterMessagesError,
+ );
+ const loadPage = useConversationStore((s) =>
+ side === 'earlier' ? s.loadEarlierMessages : s.loadLaterMessages,
+ );
+
+ const handleRetry = useCallback(() => {
+ void loadPage({ retry: true });
+ }, [loadPage]);
+
+ if (error === undefined) return null;
+
+ return (
+ <Flexbox horizontal align={'center'} aria-live={'polite'} justify={'center'} role={'status'}>
+ <AsyncError
+ error={error}
+ variant={'inline'}
+ title={t(
+ side === 'earlier' ? 'chatList.earlierHistoryError' : 'chatList.laterHistoryError',
+ )}
+ onRetry={handleRetry}
+ />
+ </Flexbox>
+ );
+});
+
+HistoryPageError.displayName = 'HistoryPageError';
+
+export default HistoryPageError;
diff --git a/src/features/Conversation/ChatList/components/HistoryPageSkeleton.tsx b/src/features/Conversation/ChatList/components/HistoryPageSkeleton.tsx
new file mode 100644
index 00000000000..b5efce6e45b
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/HistoryPageSkeleton.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { memo } from 'react';
+
+import { delayed } from '@/components/Skeleton/Delayed';
+
+import SkeletonList from '../../components/SkeletonList';
+import { useConversationStore } from '../../store';
+
+export type HistoryPageSide = 'earlier' | 'later';
+
+/**
+ * The conversation skeleton shown beside the messages while a page of history
+ * is in flight: above them for earlier history, below them for the later
+ * rounds of a forward transcript. 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 slot row
+ * would never repaint on a flag change passed down from the list.
+ */
+const HistoryPageSkeleton = memo<{ side: HistoryPageSide }>(({ side }) => {
+ const isLoading = useConversationStore((s) =>
+ side === 'earlier' ? s.isLoadingEarlierMessages : s.isLoadingLaterMessages,
+ );
+
+ return isLoading ? delayed(<SkeletonList />) : null;
+});
+
+HistoryPageSkeleton.displayName = 'HistoryPageSkeleton';
+
+export default HistoryPageSkeleton;
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 590bb001b7f..f423391d396 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -32,16 +32,17 @@ import {
useConversationScroll,
} from '../hooks/useConversationScroll';
import { useEarlierHistoryTrigger } from '../hooks/useEarlierHistoryTrigger';
+import { useLaterHistoryTrigger } from '../hooks/useLaterHistoryTrigger';
import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';
-import { useTopicScrollPersist } from '../hooks/useTopicScrollPersist';
+import { type InitialScrollPosition, useTopicScrollPersist } from '../hooks/useTopicScrollPersist';
import { resolveAutoScrollDetached } from '../utils/autoScrollFollow';
import type { ResolvedMessageDeepLink } from '../utils/messageDeepLink';
import AutoScroll from './AutoScroll';
import { AT_BOTTOM_THRESHOLD } from './AutoScroll/const';
import { useAutoScrollEnabled } from './AutoScroll/useAutoScrollEnabled';
import BackBottom from './BackBottom';
-import EarlierHistoryError from './EarlierHistoryError';
-import EarlierHistorySkeleton from './EarlierHistorySkeleton';
+import HistoryPageError from './HistoryPageError';
+import HistoryPageSkeleton from './HistoryPageSkeleton';
const DebugInspector = lazy(() => import('./AutoScroll/DebugInspector'));
@@ -64,8 +65,10 @@ interface VirtualizedListProps {
dataSource: string[];
footerSlot?: ReactNode;
headerSlot?: ReactNode;
+ initialScrollPosition?: InitialScrollPosition;
itemContent: (index: number, data: string) => ReactNode;
messageDeepLink?: ResolvedMessageDeepLink;
+ paging?: 'backward' | 'forward';
}
/**
@@ -74,7 +77,16 @@ interface VirtualizedListProps {
* Based on ConversationStore data flow, no dependency on global ChatStore.
*/
const VirtualizedList = memo<VirtualizedListProps>(
- ({ dataSource, footerSlot, headerSlot, itemContent, messageDeepLink }) => {
+ ({
+ dataSource,
+ footerSlot,
+ headerSlot,
+ initialScrollPosition,
+ itemContent,
+ messageDeepLink,
+ paging,
+ }) => {
+ const isForward = paging === 'forward';
const virtuaRef = useRef<VListHandle>(null);
const containerRef = useRef<HTMLDivElement>(null);
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -100,6 +112,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
dataSourceLength: dataSource.length,
getScroller,
headerOffset: LEADING_ROWS,
+ initialPosition: isForward ? 'top' : initialScrollPosition,
messageDeepLink,
virtuaRef,
});
@@ -136,6 +149,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
// Store actions
const storeApi = useConversationStoreApi();
const loadEarlierMessages = useConversationStore((s) => s.loadEarlierMessages);
+ const loadLaterMessages = useConversationStore((s) => s.loadLaterMessages);
const registerVirtuaScrollMethods = useConversationStore((s) => s.registerVirtuaScrollMethods);
const setScrollState = useConversationStore((s) => s.setScrollState);
const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
@@ -144,6 +158,12 @@ const VirtualizedList = memo<VirtualizedListProps>(
const activeIndex = useConversationStore(virtuaListSelectors.activeIndex);
const earlierHistory = useEarlierHistoryTrigger({ loadEarlierMessages, virtuaRef });
+ const laterHistory = useLaterHistoryTrigger({
+ enabled: isForward,
+ loadLaterMessages,
+ virtuaRef,
+ });
+ const historyTrigger = isForward ? laterHistory : earlierHistory;
const markUserScrollIntent = useCallback(() => {
lastUserScrollIntentAtRef.current = Date.now();
@@ -199,25 +219,25 @@ const VirtualizedList = memo<VirtualizedListProps>(
if (SCROLL_KEYS.has(event.key)) {
markActiveScrollInput();
}
- earlierHistory.onKeyDown(event);
+ historyTrigger.onKeyDown(event);
},
- [earlierHistory, markActiveScrollInput],
+ [historyTrigger, markActiveScrollInput],
);
const handleWheel = useCallback(
(event: WheelEvent<HTMLDivElement>) => {
markActiveScrollInput();
- earlierHistory.onWheel(event);
+ historyTrigger.onWheel(event);
},
- [earlierHistory, markActiveScrollInput],
+ [historyTrigger, markActiveScrollInput],
);
const handleTouchMove = useCallback(
(event: TouchEvent<HTMLDivElement>) => {
markActiveScrollInput();
- earlierHistory.onTouchMove(event);
+ historyTrigger.onTouchMove(event);
},
- [earlierHistory, markActiveScrollInput],
+ [historyTrigger, markActiveScrollInput],
);
const getDistanceToBottom = useCallback(() => {
@@ -256,7 +276,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
onScrollOffset(ref.scrollOffset, hasUserScrollIntent);
// Programmatic mount/restore scrolls carry no intent and never fetch.
- if (hasUserScrollIntent) earlierHistory.onUserScroll();
+ if (hasUserScrollIntent) historyTrigger.onUserScroll();
const autoScrollDetached = resolveAutoScrollDetached({
detached: storeApi.getState().autoScrollDetached,
@@ -277,8 +297,8 @@ const VirtualizedList = memo<VirtualizedListProps>(
}
}, [
activeIndex,
- earlierHistory,
getDistanceToBottom,
+ historyTrigger,
markUserScrolling,
onScrollOffset,
recordScroll,
@@ -392,6 +412,9 @@ const VirtualizedList = memo<VirtualizedListProps>(
}, [dataSource, streamingIndices, selectionMessageIds]);
const atBottom = useConversationStore(virtuaListSelectors.atBottom);
+ // The bottom of a forward transcript with rounds still to load is not the
+ // conversation's end.
+ const hasLaterMessages = useConversationStore(dataSelectors.hasLaterMessages);
// The ChatInput's floating overlay (TodoProgress + QueueTray) covers the
// bottom of this scroll viewport like a layer. Extend VList's internal
@@ -402,9 +425,16 @@ const VirtualizedList = memo<VirtualizedListProps>(
const overlayHeight = useConversationStore(inputSelectors.chatInputOverlayHeight);
const paddingBottom = Math.max(24, overlayHeight + 12);
+ // A forward list always ends in the footer row: it hosts the later-page
+ // skeleton and retry row, kept before the footer slot.
+ const hasFooterRow = !!footerSlot || isForward;
const dataWithSlots = useMemo(
- () => [CONVERSATION_HEADER_ID, ...listData, ...(footerSlot ? [CONVERSATION_FOOTER_ID] : [])],
- [footerSlot, listData],
+ () => [
+ CONVERSATION_HEADER_ID,
+ ...listData,
+ ...(hasFooterRow ? [CONVERSATION_FOOTER_ID] : []),
+ ],
+ [hasFooterRow, listData],
);
// Prepend detection for virtua: when pre-window history loads, the former
@@ -427,8 +457,12 @@ const VirtualizedList = memo<VirtualizedListProps>(
// excludes a zero-height row at the top from its render range, so it
// would never mount to show the skeleton it hosts.
const keepMountedIndicesWithSlots = useMemo(
- () => [0, ...keepMountedIndices.map((index) => index + LEADING_ROWS)],
- [keepMountedIndices],
+ () => [
+ 0,
+ ...keepMountedIndices.map((index) => index + LEADING_ROWS),
+ ...(isForward ? [dataWithSlots.length - 1] : []),
+ ],
+ [dataWithSlots.length, isForward, keepMountedIndices],
);
// Mirror the latest data length into a ref so the scroll-methods registered
@@ -447,7 +481,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
onPointerDownCapture={handlePointerDown}
onPointerMoveCapture={handlePointerMove}
onTouchMoveCapture={handleTouchMove}
- onTouchStartCapture={earlierHistory.onTouchStart}
+ onTouchStartCapture={historyTrigger.onTouchStart}
onWheelCapture={handleWheel}
>
{/* Pinned to the list viewport top; only renders while multi-selecting */}
@@ -474,14 +508,16 @@ const VirtualizedList = memo<VirtualizedListProps>(
return (
<WideScreenContainer key={messageId} style={{ position: 'relative' }}>
{headerSlot}
- <EarlierHistorySkeleton />
- <EarlierHistoryError />
+ <HistoryPageSkeleton side={'earlier'} />
+ <HistoryPageError side={'earlier'} />
</WideScreenContainer>
);
}
if (messageId === CONVERSATION_FOOTER_ID) {
return (
<WideScreenContainer key={messageId} style={{ position: 'relative' }}>
+ {isForward && <HistoryPageSkeleton side={'later'} />}
+ {isForward && <HistoryPageError side={'later'} />}
{footerSlot}
</WideScreenContainer>
);
@@ -544,7 +580,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
<BackBottom
atBottom={atBottom}
bottomOffset={overlayHeight}
- visible={!atBottom}
+ visible={!atBottom && !hasLaterMessages}
onScrollToBottom={handleBackBottom}
/>
</WideScreenContainer>
diff --git a/src/features/Conversation/ChatList/hooks/useForwardPagingFallback.test.ts b/src/features/Conversation/ChatList/hooks/useForwardPagingFallback.test.ts
new file mode 100644
index 00000000000..cf33bd1b5c2
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useForwardPagingFallback.test.ts
@@ -0,0 +1,60 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { ForwardPagingUnsupportedError } from '@/services/message/roundCursorPage';
+
+import { useForwardPagingFallback } from './useForwardPagingFallback';
+
+describe('useForwardPagingFallback', () => {
+ it('hands a forward list back to newest-first when the server cannot page forward', () => {
+ const onUnsupported = vi.fn();
+
+ const { result } = renderHook(() =>
+ useForwardPagingFallback({
+ errors: [new ForwardPagingUnsupportedError()],
+ onUnsupported,
+ paging: 'forward',
+ }),
+ );
+
+ expect(result.current).toBe(true);
+ expect(onUnsupported).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves other failures and newest-first lists to the usual error rows', () => {
+ const onUnsupported = vi.fn();
+
+ const network = renderHook(() =>
+ useForwardPagingFallback({
+ errors: [new Error('network down'), undefined],
+ onUnsupported,
+ paging: 'forward',
+ }),
+ );
+ const backward = renderHook(() =>
+ useForwardPagingFallback({
+ errors: [new ForwardPagingUnsupportedError()],
+ onUnsupported,
+ paging: 'backward',
+ }),
+ );
+
+ expect(network.result.current).toBe(false);
+ expect(backward.result.current).toBe(false);
+ expect(onUnsupported).not.toHaveBeenCalled();
+ });
+
+ it('does not hide the failure when nothing can switch the list', () => {
+ const { result } = renderHook(() =>
+ useForwardPagingFallback({
+ errors: [new ForwardPagingUnsupportedError()],
+ paging: 'forward',
+ }),
+ );
+
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useForwardPagingFallback.ts b/src/features/Conversation/ChatList/hooks/useForwardPagingFallback.ts
new file mode 100644
index 00000000000..97a13072d06
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useForwardPagingFallback.ts
@@ -0,0 +1,32 @@
+import { useEffect } from 'react';
+
+import { ForwardPagingUnsupportedError } from '@/services/message/roundCursorPage';
+
+interface UseForwardPagingFallbackOptions {
+ errors: unknown[];
+ onUnsupported?: () => void;
+ paging: 'backward' | 'forward';
+}
+
+/**
+ * A forward list whose server answers without paging forward (rolled back
+ * after the page was rendered) cannot continue: hand it back to its owner,
+ * which re-reads it newest-first. Returns whether that hand-over is under way,
+ * so the failure is not shown meanwhile.
+ */
+export const useForwardPagingFallback = ({
+ errors,
+ onUnsupported,
+ paging,
+}: UseForwardPagingFallbackOptions) => {
+ const fallingBack =
+ paging === 'forward' &&
+ !!onUnsupported &&
+ errors.some((error) => error instanceof ForwardPagingUnsupportedError);
+
+ useEffect(() => {
+ if (fallingBack) onUnsupported?.();
+ }, [fallingBack, onUnsupported]);
+
+ return fallingBack;
+};
diff --git a/src/features/Conversation/ChatList/hooks/useLaterHistoryTrigger.test.ts b/src/features/Conversation/ChatList/hooks/useLaterHistoryTrigger.test.ts
new file mode 100644
index 00000000000..b42c3e94ffc
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useLaterHistoryTrigger.test.ts
@@ -0,0 +1,98 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import type { KeyboardEvent, RefObject, TouchEvent, WheelEvent } from 'react';
+import type { VListHandle } from 'virtua';
+import { describe, expect, it, vi } from 'vitest';
+
+import { LATER_HISTORY_TRIGGER_PX, useLaterHistoryTrigger } from './useLaterHistoryTrigger';
+
+const VIEWPORT = 600;
+
+const refAt = (distanceToEnd: number, scrollSize = 4000): RefObject<VListHandle | null> => ({
+ current: {
+ scrollOffset: Math.max(0, scrollSize - VIEWPORT - distanceToEnd),
+ scrollSize,
+ viewportSize: VIEWPORT,
+ } as unknown as VListHandle,
+});
+
+const wheel = (deltaY: number) => ({ deltaY }) as WheelEvent<HTMLElement>;
+const key = (value: string) => ({ key: value }) as KeyboardEvent<HTMLElement>;
+const touchAt = (clientY: number) =>
+ ({ touches: [{ clientY }] }) as unknown as TouchEvent<HTMLElement>;
+
+const setup = (virtuaRef: RefObject<VListHandle | null>, enabled = true) => {
+ const loadLaterMessages = vi.fn().mockResolvedValue(undefined);
+ const { result } = renderHook(() =>
+ useLaterHistoryTrigger({ enabled, loadLaterMessages, virtuaRef }),
+ );
+ return { loadLaterMessages, trigger: result.current };
+};
+
+describe('useLaterHistoryTrigger', () => {
+ it('loads on a wheel-down over a first page too short to scroll', () => {
+ const { loadLaterMessages, trigger } = setup(refAt(0, 300));
+
+ trigger.onWheel(wheel(120));
+
+ expect(loadLaterMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores a wheel-up and any gesture away from the end', () => {
+ const atEnd = setup(refAt(0));
+ atEnd.trigger.onWheel(wheel(-120));
+ expect(atEnd.loadLaterMessages).not.toHaveBeenCalled();
+
+ const farUp = setup(refAt(LATER_HISTORY_TRIGGER_PX));
+ farUp.trigger.onWheel(wheel(120));
+ farUp.trigger.onUserScroll();
+ farUp.trigger.onKeyDown(key('PageDown'));
+ expect(farUp.loadLaterMessages).not.toHaveBeenCalled();
+ });
+
+ it('loads on a user scroll that reaches the end region', () => {
+ const { loadLaterMessages, trigger } = setup(refAt(LATER_HISTORY_TRIGGER_PX - 1));
+
+ trigger.onUserScroll();
+
+ expect(loadLaterMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it('loads on downward navigation keys only', () => {
+ const { loadLaterMessages, trigger } = setup(refAt(0));
+
+ trigger.onKeyDown(key('ArrowUp'));
+ trigger.onKeyDown(key('Home'));
+ expect(loadLaterMessages).not.toHaveBeenCalled();
+
+ trigger.onKeyDown(key('ArrowDown'));
+ trigger.onKeyDown(key('PageDown'));
+ trigger.onKeyDown(key('End'));
+ expect(loadLaterMessages).toHaveBeenCalledTimes(3);
+ });
+
+ it('loads when a touch drags upward (content scrolls down), not downward', () => {
+ const { loadLaterMessages, trigger } = setup(refAt(0));
+
+ trigger.onTouchStart(touchAt(300));
+ trigger.onTouchMove(touchAt(360));
+ expect(loadLaterMessages).not.toHaveBeenCalled();
+
+ trigger.onTouchMove(touchAt(250));
+ expect(loadLaterMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it('never loads on a newest-first list', () => {
+ const { loadLaterMessages, trigger } = setup(refAt(0, 300), false);
+
+ trigger.onWheel(wheel(120));
+ trigger.onUserScroll();
+ trigger.onKeyDown(key('End'));
+ trigger.onTouchStart(touchAt(300));
+ trigger.onTouchMove(touchAt(250));
+
+ expect(loadLaterMessages).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useLaterHistoryTrigger.ts b/src/features/Conversation/ChatList/hooks/useLaterHistoryTrigger.ts
new file mode 100644
index 00000000000..3fabe10b685
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useLaterHistoryTrigger.ts
@@ -0,0 +1,74 @@
+import type { KeyboardEvent, RefObject, TouchEvent, WheelEvent } from 'react';
+import { useCallback, useMemo, useRef } from 'react';
+import type { VListHandle } from 'virtua';
+
+/**
+ * Distance from the end of the loaded rows (px) under which a downward gesture
+ * appends the next rounds of a forward transcript. `loadLaterMessages`
+ * self-guards against duplicate and exhausted loads, so firing it per gesture
+ * is safe.
+ */
+export const LATER_HISTORY_TRIGGER_PX = 200;
+
+const DOWNWARD_KEYS = new Set(['ArrowDown', 'End', 'PageDown']);
+
+interface UseLaterHistoryTriggerOptions {
+ enabled: boolean;
+ loadLaterMessages: () => Promise<void>;
+ virtuaRef: RefObject<VListHandle | null>;
+}
+
+/**
+ * The forward counterpart of `useEarlierHistoryTrigger`: a downward gesture
+ * near the end appends the next page. Gestures fire whether or not the list can
+ * scroll, so a first page shorter than the viewport still continues on the
+ * reader's first wheel or swipe; nothing loads without one.
+ */
+export const useLaterHistoryTrigger = ({
+ enabled,
+ loadLaterMessages,
+ virtuaRef,
+}: UseLaterHistoryTriggerOptions) => {
+ const touchStartYRef = useRef<number | null>(null);
+
+ const requestIfNearEnd = useCallback(() => {
+ const ref = virtuaRef.current;
+ if (!enabled || !ref) return;
+ if (ref.scrollSize - ref.scrollOffset - ref.viewportSize >= LATER_HISTORY_TRIGGER_PX) return;
+ void loadLaterMessages();
+ }, [enabled, loadLaterMessages, virtuaRef]);
+
+ const onUserScroll = requestIfNearEnd;
+
+ const onWheel = useCallback(
+ (event: WheelEvent<HTMLElement>) => {
+ if (event.deltaY > 0) requestIfNearEnd();
+ },
+ [requestIfNearEnd],
+ );
+
+ const onKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLElement>) => {
+ if (DOWNWARD_KEYS.has(event.key)) requestIfNearEnd();
+ },
+ [requestIfNearEnd],
+ );
+
+ const onTouchStart = useCallback((event: TouchEvent<HTMLElement>) => {
+ touchStartYRef.current = event.touches[0]?.clientY ?? null;
+ }, []);
+
+ const onTouchMove = useCallback(
+ (event: TouchEvent<HTMLElement>) => {
+ const startY = touchStartYRef.current;
+ const currentY = event.touches[0]?.clientY;
+ if (startY !== null && currentY !== undefined && currentY < startY) requestIfNearEnd();
+ },
+ [requestIfNearEnd],
+ );
+
+ return useMemo(
+ () => ({ onKeyDown, onTouchMove, onTouchStart, onUserScroll, onWheel }),
+ [onKeyDown, onTouchMove, onTouchStart, onUserScroll, onWheel],
+ );
+};
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.initialPosition.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.initialPosition.test.ts
new file mode 100644
index 00000000000..b8b3f3a40df
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.initialPosition.test.ts
@@ -0,0 +1,113 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { type RefObject } from 'react';
+import { type VListHandle } from 'virtua';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { saveScrollSnapshot } from '../utils/scrollSnapshotStore';
+import { useTopicScrollPersist } from './useTopicScrollPersist';
+
+const createHandle = (scrollSize: number) => {
+ const setScrollTop = vi.fn<(value: number) => void>();
+ const scroller = {
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ scrollHeight: scrollSize,
+ set scrollTop(value: number) {
+ setScrollTop(value);
+ },
+ } as unknown as HTMLElement;
+ const handle = {
+ scrollOffset: 0,
+ scrollSize,
+ scrollTo: vi.fn(),
+ scrollToIndex: vi.fn(),
+ viewportSize: 800,
+ };
+ return {
+ handle,
+ ref: { current: handle as unknown as VListHandle } as RefObject<VListHandle | null>,
+ scroller,
+ setScrollTop,
+ };
+};
+
+const advanceFrames = async (frames: number) => {
+ await vi.advanceTimersByTimeAsync(frames * 32);
+};
+
+describe('useTopicScrollPersist initialPosition', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('opens at the first message instead of jumping to the end', async () => {
+ const { ref, scroller, setScrollTop } = createHandle(5000);
+
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_share',
+ dataSourceLength: 50,
+ getScroller: () => scroller,
+ initialPosition: 'top',
+ virtuaRef: ref,
+ }),
+ );
+ await advanceFrames(10);
+
+ expect(setScrollTop).toHaveBeenCalledWith(0);
+ expect(setScrollTop).not.toHaveBeenCalledWith(5000);
+ });
+
+ it('ignores a saved reading position', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_share', {
+ atBottom: false,
+ offset: 1200,
+ savedAt: Date.now(),
+ });
+ const { ref, scroller, setScrollTop } = createHandle(5000);
+
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_share',
+ dataSourceLength: 50,
+ getScroller: () => scroller,
+ initialPosition: 'top',
+ virtuaRef: ref,
+ }),
+ );
+ await advanceFrames(10);
+
+ expect(setScrollTop).not.toHaveBeenCalledWith(1200);
+ });
+
+ it('still lets a message deep link choose the position', async () => {
+ const { handle, ref, scroller } = createHandle(5000);
+
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_share',
+ dataSourceLength: 50,
+ getScroller: () => scroller,
+ initialPosition: 'top',
+ messageDeepLink: {
+ displayMessageId: 'msg-20',
+ index: 20,
+ messageId: 'msg-20',
+ navigationKey: 'nav-1',
+ } as any,
+ virtuaRef: ref,
+ }),
+ );
+ await advanceFrames(1);
+
+ expect(handle.scrollToIndex).toHaveBeenCalledWith(20, { align: 'center' });
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
index 5d087fc57d7..810c62d8143 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
@@ -32,6 +32,8 @@ interface PendingWrite {
offset: number;
}
+export type InitialScrollPosition = 'bottom' | 'top';
+
interface UseTopicScrollPersistOptions {
containerRef?: RefObject<HTMLDivElement | null>;
contextKey: string;
@@ -50,6 +52,11 @@ interface UseTopicScrollPersistOptions {
* so scrollToIndex lands on the right virtua row.
*/
headerOffset?: number;
+ /**
+ * Where a topic opens when there is no deep link. `bottom` restores the saved
+ * position, or the end of the conversation; `top` always opens at the start.
+ */
+ initialPosition?: InitialScrollPosition;
messageDeepLink?: ResolvedMessageDeepLink;
virtuaRef: RefObject<VListHandle | null>;
}
@@ -108,6 +115,7 @@ export const useTopicScrollPersist = ({
dataSourceLength,
getScroller,
headerOffset = 0,
+ initialPosition = 'bottom',
messageDeepLink,
virtuaRef,
}: UseTopicScrollPersistOptions) => {
@@ -316,6 +324,13 @@ export const useTopicScrollPersist = ({
return;
}
+ if (initialPosition === 'top') {
+ const scroller = getScroller();
+ if (scroller) scroller.scrollTop = 0;
+ finalize(false);
+ return;
+ }
+
const snapshot = loadScrollSnapshot(contextKey);
const targetOffset = snapshot && !snapshot.atBottom ? snapshot.offset : null;
@@ -410,6 +425,7 @@ export const useTopicScrollPersist = ({
flushNow,
getScroller,
headerOffset,
+ initialPosition,
messageDeepLink,
virtuaRef,
]);
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index fe3045cdf36..646832b6c8e 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -35,8 +35,10 @@ import AgentSignalReceiptList from './components/AgentSignalReceiptList';
import { RefreshError } from './components/RefreshError';
import VirtualizedList from './components/VirtualizedList';
import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';
+import { useForwardPagingFallback } from './hooks/useForwardPagingFallback';
import { useInitialRevalidation } from './hooks/useInitialRevalidation';
import { useMessageRefreshError } from './hooks/useMessageRefreshError';
+import { type InitialScrollPosition } from './hooks/useTopicScrollPersist';
import { resolveMessageListFeedback } from './resolveMessageListFeedback';
import { buildChatRows } from './utils/chatRows';
import { hoistCompressedGroups } from './utils/compressedGroupOrder';
@@ -93,12 +95,23 @@ export interface ChatListProps {
* show the plain dot loader instead (e.g. on external visitor surfaces).
*/
hideBackgroundRunHint?: boolean;
+ /**
+ * Where the conversation opens: the saved position or the end (`bottom`,
+ * default), or always the first message (`top`, e.g. in share page).
+ */
+ initialScrollPosition?: InitialScrollPosition;
/**
* Custom item renderer. If not provided, uses default ChatItem.
*/
itemContent?: (index: number, id: string) => ReactNode;
/** Message hash target to locate after the virtual list has rendered. */
messageDeepLink?: MessageDeepLink;
+ /**
+ * The conversation reads forward (`messageReadMode: 'forward'`) but the
+ * server cannot page forward. The owner of the context should switch it back
+ * to the newest-first read.
+ */
+ onForwardPagingUnsupported?: () => void;
/**
* Force showing welcome component even when messages exist
*/
@@ -121,13 +134,16 @@ const ChatList = memo<ChatListProps>(
footerSlot,
headerSlot,
hideBackgroundRunHint,
+ initialScrollPosition,
welcome,
itemContent,
messageDeepLink,
+ onForwardPagingUnsupported,
showWelcome,
}) => {
// The chat store owns the transcript; this view keeps its sync mounted.
const context = useConversationStore((s) => s.context);
+ const paging = context.messageReadMode === 'forward' ? 'forward' : 'backward';
const enableUserMemories = useUserStore(settingsSelectors.memoryEnabled);
const skipFetch = useConversationStore(dataSelectors.skipFetch);
const useFetchMessages = useChatStore((s) => s.useFetchMessages);
@@ -151,9 +167,15 @@ const ChatList = memo<ChatListProps>(
skipFetch: skipFetch || isCreatingTopic,
syncInterventions: true,
});
+ const laterMessagesError = useConversationStore((s) => s.laterMessagesError);
+ const isFallingBack = useForwardPagingFallback({
+ errors: [messagesSWR.error, laterMessagesError],
+ onUnsupported: onForwardPagingUnsupported,
+ paging,
+ });
const messageListIdentity = getMessageListCacheIdentity(context);
const refreshError = useMessageRefreshError({
- error: messagesSWR.error,
+ error: isFallingBack ? undefined : messagesSWR.error,
identity: messageListIdentity,
isValidating: messagesSWR.isValidating,
mutate: messagesSWR.mutate,
@@ -339,8 +361,10 @@ const ChatList = memo<ChatListProps>(
dataSource={rowIds}
footerSlot={footerSlot}
headerSlot={headerSlot}
+ initialScrollPosition={initialScrollPosition}
itemContent={itemContent ?? defaultItemContent}
messageDeepLink={resolvedMessageDeepLink}
+ paging={paging}
/>
</BackgroundRunHintContext>
</MessageActionProvider>
diff --git a/src/features/Conversation/Error/dedicatedErrorCards.ts b/src/features/Conversation/Error/dedicatedErrorCards.ts
index e694a4c9070..7ad26854d29 100644
--- a/src/features/Conversation/Error/dedicatedErrorCards.ts
+++ b/src/features/Conversation/Error/dedicatedErrorCards.ts
@@ -1,5 +1,4 @@
-import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
-import { ChatErrorType } from '@lobechat/types';
+import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';
/**
* Error types that `ErrorMessageExtra` renders with a dedicated card instead of the
diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsx
index b4560b9d36b..8b501988eff 100644
--- a/src/features/Conversation/Error/index.test.tsx
+++ b/src/features/Conversation/Error/index.test.tsx
@@ -1,9 +1,7 @@
import type * as lobechatConstModule from '@lobechat/const';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
-import type * as modelRuntimeModule from '@lobechat/model-runtime';
-import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
import type * as lobechatTypesModule from '@lobechat/types';
-import { ChatErrorType } from '@lobechat/types';
+import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -50,18 +48,6 @@ vi.mock('@lobechat/const', async (importOriginal) => {
return { ...actual, isDesktop: true };
});
-vi.mock('@lobechat/model-runtime', async (importOriginal) => {
- const actual = (await importOriginal()) as typeof modelRuntimeModule;
-
- return {
- ...actual,
- AgentRuntimeErrorType: {
- ...actual.AgentRuntimeErrorType,
- AgentRuntimeError: 'AgentRuntimeError',
- },
- };
-});
-
vi.mock('@lobechat/types', async (importOriginal) => {
const actual = (await importOriginal()) as typeof lobechatTypesModule;
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index 1304eaf7ebe..af461315466 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -1,10 +1,15 @@
import { isDesktop } from '@lobechat/const';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';
-import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';
-import { AgentRuntimeErrorType, getErrorCodeSpec } from '@lobechat/model-runtime';
-import { type ChatMessageError, type ErrorType, type IToolErrorType } from '@lobechat/types';
-import { ChatErrorType } from '@lobechat/types';
+import { getErrorCodeSpec } from '@lobechat/model-runtime/errors';
+import {
+ AgentRuntimeErrorType,
+ ChatErrorType,
+ type ChatMessageError,
+ type ErrorType,
+ type ILobeAgentRuntimeErrorType,
+ type IToolErrorType,
+} from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import { type AlertProps, Block, Highlighter, Skeleton, toast } from '@lobehub/ui';
import { memo, useCallback, useMemo } from 'react';
diff --git a/src/features/Conversation/components/ShareMessageModal/Content.tsx b/src/features/Conversation/components/ShareMessageModal/Content.tsx
new file mode 100644
index 00000000000..d298b7ad6dd
--- /dev/null
+++ b/src/features/Conversation/components/ShareMessageModal/Content.tsx
@@ -0,0 +1,87 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { Flexbox, Tabs } from '@lobehub/ui';
+import { memo, useId, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ShareDataProvider from '@/features/ShareModal/ShareDataProvider';
+import SharePdf from '@/features/ShareModal/SharePdf';
+import { useIsMobile } from '@/hooks/useIsMobile';
+
+import type { createStore } from '../../store';
+import { Provider, useConversationStore } from '../../store';
+import ShareImage from './ShareImage';
+import ShareText from './ShareText';
+
+enum Tab {
+ PDF = 'pdf',
+ Screenshot = 'screenshot',
+ Text = 'text',
+}
+
+interface ShareMessageModalContentProps {
+ message: UIChatMessage;
+}
+
+const ShareMessageModalContent = memo<ShareMessageModalContentProps>(({ message }) => {
+ const [tab, setTab] = useState<Tab>(Tab.Screenshot);
+ const { t } = useTranslation('chat');
+ const uniqueId = useId();
+ const isMobile = useIsMobile();
+ const context = useConversationStore((s) => s.context);
+
+ const tabItems = useMemo(() => {
+ const items = [
+ {
+ children: <ShareImage message={message} mobile={isMobile} uniqueId={uniqueId} />,
+ key: Tab.Screenshot,
+ label: t('shareModal.screenshot'),
+ },
+ {
+ children: <ShareText item={message} />,
+ key: Tab.Text,
+ label: t('shareModal.text'),
+ },
+ {
+ children: (
+ <ShareDataProvider context={context}>
+ <Flexbox style={{ height: 'min(70vh, 720px)' }}>
+ <SharePdf message={message} />
+ </Flexbox>
+ </ShareDataProvider>
+ ),
+ key: Tab.PDF,
+ label: t('shareModal.pdf'),
+ },
+ ];
+
+ return items;
+ }, [context, isMobile, message, uniqueId, t]);
+
+ return (
+ <Flexbox gap={isMobile ? 8 : 24}>
+ <Tabs
+ activeKey={tab}
+ items={tabItems}
+ styles={{
+ list: { display: 'flex', width: '100%' },
+ tab: { flex: 1 },
+ }}
+ onChange={(key) => setTab(key as Tab)}
+ />
+ </Flexbox>
+ );
+});
+
+ShareMessageModalContent.displayName = 'ShareMessageModalContent';
+
+interface ShareMessageModalProps extends ShareMessageModalContentProps {
+ createConversationStore: () => ReturnType<typeof createStore>;
+}
+
+const ShareMessageModal = ({ createConversationStore, message }: ShareMessageModalProps) => (
+ <Provider createStore={createConversationStore}>
+ <ShareMessageModalContent message={message} />
+ </Provider>
+);
+
+export default ShareMessageModal;
diff --git a/src/features/Conversation/components/ShareMessageModal/index.test.ts b/src/features/Conversation/components/ShareMessageModal/index.test.ts
new file mode 100644
index 00000000000..0483964f864
--- /dev/null
+++ b/src/features/Conversation/components/ShareMessageModal/index.test.ts
@@ -0,0 +1,68 @@
+import type { ReactElement } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { openShareMessageModal } from './index';
+
+const createModal = vi.hoisted(() => vi.fn((_props: { content: ReactElement<any> }) => ({})));
+const notifyChunkError = vi.hoisted(() => vi.fn());
+// Detection belongs to `@/utils/chunkError` (and its own tests).
+const isChunkLoadError = vi.hoisted(() => vi.fn(() => false));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ createModal,
+}));
+vi.mock('@/utils/chunkError', () => ({ isChunkLoadError, notifyChunkError }));
+
+const modalContent = (call: number) => createModal.mock.calls[call][0].content;
+// SafeBoundary > Suspense > the lazily loaded modal body.
+const modalBody = (call: number) => modalContent(call).props.children.props.children;
+
+describe('openShareMessageModal', () => {
+ beforeEach(() => {
+ createModal.mockClear();
+ notifyChunkError.mockClear();
+ isChunkLoadError.mockReset().mockReturnValue(false);
+ });
+
+ it('puts the modal up on click, before its content has loaded', () => {
+ openShareMessageModal({ id: 'msg-1' } as any, vi.fn());
+
+ expect(createModal).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows each clicked message in its own modal', () => {
+ const storeA = vi.fn();
+ const storeB = vi.fn();
+
+ openShareMessageModal({ id: 'msg-a' } as any, storeA);
+ openShareMessageModal({ id: 'msg-b' } as any, storeB);
+
+ expect(modalBody(0).props).toMatchObject({
+ createConversationStore: storeA,
+ message: { id: 'msg-a' },
+ });
+ expect(modalBody(1).props).toMatchObject({
+ createConversationStore: storeB,
+ message: { id: 'msg-b' },
+ });
+ });
+
+ it('hands content that failed to load to the chunk recovery', () => {
+ isChunkLoadError.mockReturnValue(true);
+ openShareMessageModal({ id: 'msg-1' } as any, vi.fn());
+ const error = new TypeError('Failed to fetch dynamically imported module: /assets/Content.js');
+
+ modalContent(0).props.onError(error);
+
+ expect(notifyChunkError).toHaveBeenCalledWith(error);
+ });
+
+ it('leaves other render errors to the boundary', () => {
+ openShareMessageModal({ id: 'msg-1' } as any, vi.fn());
+
+ modalContent(0).props.onError(new Error('modal bug'));
+
+ expect(notifyChunkError).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/components/ShareMessageModal/index.tsx b/src/features/Conversation/components/ShareMessageModal/index.tsx
index 840040da5c3..aa66449f29f 100644
--- a/src/features/Conversation/components/ShareMessageModal/index.tsx
+++ b/src/features/Conversation/components/ShareMessageModal/index.tsx
@@ -1,79 +1,23 @@
import { type UIChatMessage } from '@lobechat/types';
-import { createModal, Flexbox, Tabs } from '@lobehub/ui';
+import { createModal } from '@lobehub/ui';
import { t } from 'i18next';
-import { memo, useId, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
+import { lazy, Suspense } from 'react';
-import ShareDataProvider from '@/features/ShareModal/ShareDataProvider';
-import SharePdf from '@/features/ShareModal/SharePdf';
-import { useIsMobile } from '@/hooks/useIsMobile';
+import SafeBoundary from '@/components/ErrorBoundary';
+import ContentLoading from '@/components/Loading/ContentLoading';
+import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';
import type { createStore } from '../../store';
-import { Provider, useConversationStore } from '../../store';
-import ShareImage from './ShareImage';
-import ShareText from './ShareText';
-enum Tab {
- PDF = 'pdf',
- Screenshot = 'screenshot',
- Text = 'text',
-}
+// The modal renders a message as an image, text and PDF, so the screenshot
+// library and pdf.js come with it. Every surface that lists messages reaches
+// this entry through its action bar; the modal opens on click and its content
+// loads inside it.
+const ShareMessageModal = lazy(() => import('./Content'));
-interface ShareMessageModalContentProps {
- message: UIChatMessage;
-}
-
-const ShareMessageModalContent = memo<ShareMessageModalContentProps>(({ message }) => {
- const [tab, setTab] = useState<Tab>(Tab.Screenshot);
- const { t } = useTranslation('chat');
- const uniqueId = useId();
- const isMobile = useIsMobile();
- const context = useConversationStore((s) => s.context);
-
- const tabItems = useMemo(() => {
- const items = [
- {
- children: <ShareImage message={message} mobile={isMobile} uniqueId={uniqueId} />,
- key: Tab.Screenshot,
- label: t('shareModal.screenshot'),
- },
- {
- children: <ShareText item={message} />,
- key: Tab.Text,
- label: t('shareModal.text'),
- },
- {
- children: (
- <ShareDataProvider context={context}>
- <Flexbox style={{ height: 'min(70vh, 720px)' }}>
- <SharePdf message={message} />
- </Flexbox>
- </ShareDataProvider>
- ),
- key: Tab.PDF,
- label: t('shareModal.pdf'),
- },
- ];
-
- return items;
- }, [context, isMobile, message, uniqueId, t]);
-
- return (
- <Flexbox gap={isMobile ? 8 : 24}>
- <Tabs
- activeKey={tab}
- items={tabItems}
- styles={{
- list: { display: 'flex', width: '100%' },
- tab: { flex: 1 },
- }}
- onChange={(key) => setTab(key as Tab)}
- />
- </Flexbox>
- );
-});
-
-ShareMessageModalContent.displayName = 'ShareMessageModalContent';
+const handleContentError = (error: unknown) => {
+ if (isChunkLoadError(error)) notifyChunkError(error);
+};
export const openShareMessageModal = (
message: UIChatMessage,
@@ -81,9 +25,11 @@ export const openShareMessageModal = (
) =>
createModal({
content: (
- <Provider createStore={createConversationStore}>
- <ShareMessageModalContent message={message} />
- </Provider>
+ <SafeBoundary variant="alert" onError={handleContentError}>
+ <Suspense fallback={<ContentLoading />}>
+ <ShareMessageModal createConversationStore={createConversationStore} message={message} />
+ </Suspense>
+ </SafeBoundary>
),
footer: null,
maskClosable: true,
diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.ts
index 8307f3878b3..f8f9a626283 100644
--- a/src/features/Conversation/store/initialState.ts
+++ b/src/features/Conversation/store/initialState.ts
@@ -76,6 +76,8 @@ export const createEphemeralResetState = (): Partial<State> => ({
heteroOverloadWaitOpIds: {},
inputMessage: '',
isLoadingEarlierMessages: false,
+ isLoadingLaterMessages: false,
+ laterMessagesError: undefined,
refreshingRowId: undefined,
isScrolling: false,
messageEditingIds: [],
diff --git a/src/features/Conversation/store/slices/data/action.laterMessages.test.ts b/src/features/Conversation/store/slices/data/action.laterMessages.test.ts
new file mode 100644
index 00000000000..f9dc2e0eb7e
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/action.laterMessages.test.ts
@@ -0,0 +1,115 @@
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { conversationMessagesKey } from '@/services/message/replica';
+import { useChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { createStore } from '../../index';
+import { createEphemeralResetState } from '../../initialState';
+import { dataSelectors } from './selectors';
+
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => ({
+ flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt),
+ messageMap: Object.fromEntries(messages.map((m) => [m.id, m])),
+ }),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { message: { getMessagesByCursor: { query: vi.fn() } } },
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => undefined,
+ useActiveWorkspaceId: () => undefined,
+}));
+
+const query = vi.mocked(lambdaClient.message.getMessagesByCursor.query);
+
+const row = (id: string, createdAt: number) =>
+ ({ content: id, createdAt, id, role: 'user' }) as UIChatMessage;
+
+const cursor = { createdAt: '2024-01-01T00:00:01.000Z', id: 'a1' };
+
+const forward = (shareId: string): ConversationContext => ({
+ agentId: 'share-agent',
+ messageReadMode: 'forward',
+ topicId: `topic-${shareId}`,
+ topicShareId: shareId,
+});
+
+const seedFirstPage = (context: ConversationContext) =>
+ useChatStore.setState((state) => ({
+ dbMessagesMap: {
+ ...state.dbMessagesMap,
+ [messageMapKey(context)]: [row('u1', 0), row('a1', 1)],
+ },
+ messagePagingMap: {
+ ...state.messagePagingMap,
+ [conversationMessagesKey(context)]: {
+ currentPage: 0,
+ hasMore: true,
+ nextCursor: cursor,
+ pageSize: 2,
+ },
+ },
+ }));
+
+const laterPage = {
+ direction: 'forward' as const,
+ hasMore: false,
+ messages: [row('u2', 2), row('a2', 3)],
+ nextCursor: null,
+};
+
+describe('loadLaterMessages', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useChatStore.setState({ dbMessagesMap: {}, messagePagingMap: {}, messagesMap: {} });
+ });
+
+ it('appends the next rounds below the loaded ones', async () => {
+ const context = forward('later-append');
+ seedFirstPage(context);
+ const store = createStore({ context });
+ query.mockResolvedValueOnce(laterPage);
+ expect(dataSelectors.hasLaterMessages(store.getState())).toBe(true);
+
+ await store.getState().loadLaterMessages();
+
+ expect(query).toHaveBeenCalledWith(expect.objectContaining({ cursor, direction: 'forward' }));
+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u1', 'a1', 'u2', 'a2']);
+ expect(store.getState().isLoadingLaterMessages).toBe(false);
+ expect(store.getState().laterMessagesError).toBeUndefined();
+ expect(dataSelectors.hasLaterMessages(store.getState())).toBe(false);
+ });
+
+ it('keeps a failed page as state and only retries on explicit request', async () => {
+ const context = forward('later-fail');
+ seedFirstPage(context);
+ const store = createStore({ context });
+ const failure = new Error('network down');
+ query.mockRejectedValueOnce(failure).mockResolvedValueOnce(laterPage);
+
+ await expect(store.getState().loadLaterMessages()).resolves.toBeUndefined();
+ expect(store.getState().isLoadingLaterMessages).toBe(false);
+ expect(store.getState().laterMessagesError).toBe(failure);
+
+ await store.getState().loadLaterMessages();
+ expect(query).toHaveBeenCalledTimes(1);
+
+ await store.getState().loadLaterMessages({ retry: true });
+ expect(query).toHaveBeenCalledTimes(2);
+ expect(store.getState().laterMessagesError).toBeUndefined();
+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u1', 'a1', 'u2', 'a2']);
+ });
+
+ it('clears the loading state and the failure on conversation switch', () => {
+ expect(createEphemeralResetState()).toMatchObject({
+ isLoadingLaterMessages: false,
+ laterMessagesError: undefined,
+ });
+ });
+});
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index 43630c62403..af7067d897a 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -4,6 +4,8 @@ import debug from 'debug';
import { type StateCreator } from 'zustand/vanilla';
import { useChatStore } from '@/store/chat';
+import { messageStateSelectors } from '@/store/chat/slices/message/selectors/messageState';
+import { type ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { type Store as ConversationStore } from '../../action';
@@ -16,6 +18,28 @@ import { stabilizeReferences } from './stabilizeReferences';
const log = debug('lobe-render:features:Conversation');
+type PageSide = 'earlier' | 'later';
+
+const PAGE_SIDES = {
+ earlier: {
+ error: 'earlierMessagesError',
+ load: (...args) => useChatStore.getState().loadEarlierMessages(...args),
+ loading: 'isLoadingEarlierMessages',
+ },
+ later: {
+ error: 'laterMessagesError',
+ load: (...args) => useChatStore.getState().loadLaterMessages(...args),
+ loading: 'isLoadingLaterMessages',
+ },
+} satisfies Record<
+ PageSide,
+ {
+ error: keyof State;
+ load: ChatStore['loadEarlierMessages'];
+ loading: keyof State;
+ }
+>;
+
/**
* The conversation's rows as the chat store holds them: `dbMessages` is the
* bucket itself, `displayMessages` its parsed list pinned to the previous
@@ -25,7 +49,7 @@ export const chatTranscriptState = (
context: ConversationContext,
skipFetch: boolean | undefined,
previousDisplayMessages: UIChatMessage[],
-): Pick<State, 'dbMessages' | 'displayMessages' | 'messagesInit'> => {
+): Pick<State, 'dbMessages' | 'displayMessages' | 'hasLaterMessages' | 'messagesInit'> => {
const chat = useChatStore.getState();
const bucket = messageMapKey(context);
const rows = chat.dbMessagesMap[bucket];
@@ -36,6 +60,7 @@ export const chatTranscriptState = (
return {
dbMessages: rows ?? [],
displayMessages: stabilizeReferences(previousDisplayMessages, parsed ?? []),
+ hasLaterMessages: messageStateSelectors.hasLaterMessages(context)(chat),
// An absent bucket is "not loaded yet"; `[]` is a loaded, empty transcript.
// A conversation that never syncs has nothing to wait for.
messagesInit: !!rows || !!skipFetch,
@@ -74,6 +99,13 @@ export interface DataAction {
*/
loadEarlierMessages: (options?: { retry?: boolean }) => Promise<void>;
+ /**
+ * Load the rounds after a forward transcript's loaded pages and append them.
+ * Same contract as `loadEarlierMessages`, with its failure kept in
+ * `laterMessagesError`.
+ */
+ loadLaterMessages: (options?: { retry?: boolean }) => Promise<void>;
+
/**
* Replace all messages with new data
* Used for syncing after database operations (optimistic update pattern)
@@ -117,6 +149,26 @@ export const dataSlice: StateCreator<
action,
);
+ const loadPage = async (side: PageSide, options?: { retry?: boolean }) => {
+ const { context, transcriptSource } = get();
+ if (transcriptSource !== 'chat') return;
+ const { error: errorKey, load, loading } = PAGE_SIDES[side];
+ if (get()[errorKey] !== undefined && !options?.retry) return;
+
+ const { error, started } = await load(context, {
+ onStart: () =>
+ set({ [errorKey]: undefined, [loading]: true }, false, `${side}Messages/start`),
+ });
+ if (!started) return;
+ get().internal_syncChatTranscript();
+
+ // The flag is conversation-wide state: after a context switch it belongs
+ // to the new conversation (reset by createEphemeralResetState), so a
+ // late settle from the previous one must not clear it.
+ if (!isSameConversationContext(context, get().context)) return;
+ set({ [errorKey]: error ?? undefined, [loading]: false }, false, `${side}Messages/end`);
+ };
+
return {
internal_dispatchMessage: (payload) => {
const { context, transcriptSource } = get();
@@ -169,38 +221,16 @@ export const dataSlice: StateCreator<
if (
next.dbMessages === state.dbMessages &&
next.displayMessages === state.displayMessages &&
+ next.hasLaterMessages === state.hasLaterMessages &&
next.messagesInit === state.messagesInit
)
return;
set(next, false, 'syncChatTranscript');
},
- loadEarlierMessages: async (options) => {
- const { context, transcriptSource } = get();
- if (transcriptSource !== 'chat') return;
- if (get().earlierMessagesError !== undefined && !options?.retry) return;
-
- const { error, started } = await useChatStore.getState().loadEarlierMessages(context, {
- onStart: () =>
- set(
- { earlierMessagesError: undefined, isLoadingEarlierMessages: true },
- false,
- 'loadEarlierMessages/start',
- ),
- });
- if (!started) return;
- get().internal_syncChatTranscript();
-
- // The flag is conversation-wide state: after a context switch it belongs
- // to the new conversation (reset by createEphemeralResetState), so a
- // late settle from the previous one must not clear it.
- if (!isSameConversationContext(context, get().context)) return;
- set(
- { earlierMessagesError: error ?? undefined, isLoadingEarlierMessages: false },
- false,
- 'loadEarlierMessages/end',
- );
- },
+ loadEarlierMessages: (options) => loadPage('earlier', options),
+
+ loadLaterMessages: (options) => loadPage('later', options),
replaceMessages: (messages, options) => {
const { context, transcriptSource } = get();
diff --git a/src/features/Conversation/store/slices/data/initialState.ts b/src/features/Conversation/store/slices/data/initialState.ts
index c60a75cb101..ec614e13fff 100644
--- a/src/features/Conversation/store/slices/data/initialState.ts
+++ b/src/features/Conversation/store/slices/data/initialState.ts
@@ -20,12 +20,28 @@ export interface DataState {
*/
earlierMessagesError?: unknown;
+ /**
+ * A forward transcript has rounds after its loaded pages, mirrored from the
+ * chat store's paging with the rows.
+ */
+ hasLaterMessages: boolean;
+
/**
* A round-cursor fetch for history older than the server's newest-first
* window is in flight. Drives the top-of-list loading hint.
*/
isLoadingEarlierMessages: boolean;
+ /** A forward transcript's next page is in flight. Drives the end-of-list loading row. */
+ isLoadingLaterMessages: boolean;
+
+ /**
+ * The last forward page fetch failed. Drives the inline error row with Retry
+ * after the last message; cleared when a retry starts and on conversation
+ * switch.
+ */
+ laterMessagesError?: unknown;
+
/**
* Whether messages have been initialized
*/
@@ -54,7 +70,9 @@ export interface DataState {
export const dataInitialState: DataState = {
dbMessages: [],
displayMessages: [],
+ hasLaterMessages: false,
isLoadingEarlierMessages: false,
+ isLoadingLaterMessages: false,
messagesInit: false,
transcriptSource: 'chat',
};
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
index d1429fce33d..adec0d9d6cb 100644
--- a/src/features/Conversation/store/slices/data/selectors.ts
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -17,6 +17,7 @@ const displayMessageIds = (s: State) => s.displayMessages.map((m) => m.id);
const dbMessages = (s: State) => s.dbMessages;
const messagesInit = (s: State) => s.messagesInit;
const skipFetch = (s: State) => s.skipFetch;
+const hasLaterMessages = (s: State) => s.hasLaterMessages;
const getDisplayMessageById = (id: string) => (s: State) => {
// First, try to find in top-level displayMessages
@@ -343,6 +344,7 @@ const getVerifyOrdinal = (id: string) => (s: State) => {
};
export const dataSelectors = {
+ hasLaterMessages,
isRefreshingAt,
currentTopicSummary,
dbMessages,
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 521415f2d0b..9f7af0b1d95 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -23,6 +23,7 @@ import { lambdaClient } from '@/libs/trpc/client';
import { abortableRequest } from '../utils/abortableRequest';
import type { MessageListPage, MessageRoundCursor } from './cache';
import { supportsRoundCursor } from './cache';
+import { readMessagesByRoundCursor, takePrimedMessageListPage } from './roundCursorPage';
/**
* Query context for message operations
@@ -58,12 +59,6 @@ export 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;
@@ -242,7 +237,12 @@ export class MessageService {
): Promise<MessageListPage | UIChatMessage[]> => {
if (!supportsRoundCursor(params)) return this.getMessages(params);
- return this.getMessagesByRoundCursor(params, null);
+ // A page primed for this conversation (see `primeMessageListPage`) answers
+ // its first read; if that request failed, read again rather than fail.
+ const primed = takePrimedMessageListPage(params);
+ if (primed) return primed.catch(() => readMessagesByRoundCursor(params, null));
+
+ return readMessagesByRoundCursor(params, null);
};
/**
@@ -260,7 +260,7 @@ export class MessageService {
// current window instead of hitting the authed endpoint.
if (params.agentShareId) return { messages: [], olderCursor: null };
- if (supportsRoundCursor(params)) return this.getMessagesByRoundCursor(params, cursor);
+ if (supportsRoundCursor(params)) return readMessagesByRoundCursor(params, cursor);
const data = await lambdaClient.message.getMessages.query({
...params,
@@ -271,30 +271,6 @@ export class MessageService {
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,
- projectToolPayloads: params.projectToolPayloads,
- // 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 }) => {
return lambdaClient.message.diagnoseTopic.query(params);
};
diff --git a/src/services/message/replica.ts b/src/services/message/replica.ts
index b93caaa591d..49dc187741f 100644
--- a/src/services/message/replica.ts
+++ b/src/services/message/replica.ts
@@ -55,6 +55,7 @@ const isSyntheticGroupNode = (message: UIChatMessage) =>
const isPersistableContext = (context: ConversationContext) => {
if (!context.agentId || !context.topicId) return false;
if (context.agentShareId || context.topicShareId) return false;
+ if (context.messageReadMode === 'forward') return false;
return messageMapKey(context) === canonicalBucketOf(context);
};
@@ -76,12 +77,17 @@ const canonicalBucketOf = (context: {
* Entry identity of a conversation. Persistable conversations key by the
* canonical read context (`p:`), so the route loader and every surface showing
* the same conversation address one row; the rest key by their bucket (`m:`)
- * and stay in memory.
+ * and stay in memory. A forward transcript is its own entry: its pages run the
+ * other way, so it never shares paging with the newest-first one.
*/
export const conversationMessagesKey = (context: ConversationContext) =>
isPersistableContext(context)
? `p:${JSON.stringify(normalizeMessageListQueryContext(context))}`
- : `m:${JSON.stringify({ bucket: messageMapKey(context), threadId: context.threadId ?? null })}`;
+ : `m:${JSON.stringify({
+ bucket: messageMapKey(context),
+ threadId: context.threadId ?? null,
+ ...(context.messageReadMode === 'forward' && { paging: 'forward' }),
+ })}`;
/**
* The canonical read context a persisted (`p:`) entry key was built from;
@@ -98,9 +104,12 @@ export const persistedContextOf = (key: string): CanonicalMessageListContext | u
export const transcriptBucketOf = (key: string): { bucket: string; threadId: string | null } => {
const value = JSON.parse(key.slice(2));
if (key.startsWith('p:')) return { bucket: canonicalBucketOf(value), threadId: value.threadId };
- return value;
+ return { bucket: value.bucket, threadId: value.threadId };
};
+const isForwardTranscriptKey = (key: string) =>
+ key.startsWith('m:') && JSON.parse(key.slice(2)).paging === 'forward';
+
const transcriptPaging: ReplicaPagingConfig<UIChatMessage, MessageRoundCursor> = {
// Only reached for read paths without round cursors (threads, shared
// views): main topics always report the window's lossless cursor.
@@ -109,6 +118,7 @@ const transcriptPaging: ReplicaPagingConfig<UIChatMessage, MessageRoundCursor> =
id: message.id,
}),
direction: 'backward',
+ directionOf: (key) => (isForwardTranscriptKey(key) ? 'forward' : 'backward'),
getId: (message) => message.id,
isCursorable: (message) => !isSyntheticGroupNode(message) && !isLocalOnlyMessage(message),
mode: 'cursor',
diff --git a/src/services/message/roundCursorPage.test.ts b/src/services/message/roundCursorPage.test.ts
new file mode 100644
index 00000000000..670cdf2afab
--- /dev/null
+++ b/src/services/message/roundCursorPage.test.ts
@@ -0,0 +1,160 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+import { MessageService } from './index';
+import {
+ ForwardPagingUnsupportedError,
+ primeMessageListPage,
+ readMessagesForward,
+ SHARED_TOPIC_FIRST_PAGE,
+} from './roundCursorPage';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ message: {
+ getMessages: { query: vi.fn() },
+ getMessagesByCursor: { query: vi.fn() },
+ },
+ },
+}));
+
+const query = vi.mocked(lambdaClient.message.getMessagesByCursor.query);
+
+const page = (id: string) => ({ hasMore: false, messages: [{ id }], nextCursor: null }) as any;
+const listPage = (id: string) => Promise.resolve({ messages: [{ id }], olderCursor: null } as any);
+
+let seq = 0;
+// The primed map is module state: give every test its own conversation.
+const nextContext = () => ({ agentId: 'agent-1', topicId: 'topic-1', topicShareId: `s${++seq}` });
+
+describe('primeMessageListPage', () => {
+ const service = new MessageService();
+
+ beforeEach(() => {
+ query.mockReset();
+ });
+
+ it('answers the first list read without a request', async () => {
+ const context = nextContext();
+
+ primeMessageListPage(context, listPage('primed'));
+
+ // The list asks with its own read options; projection is not part of the identity.
+ const result = await service.getMessageListPage({ ...context, projectToolPayloads: true });
+
+ expect(query).not.toHaveBeenCalled();
+ expect(result).toEqual({ messages: [{ id: 'primed' }], olderCursor: null });
+ });
+
+ it('is taken once: later reads go to the server', async () => {
+ query.mockResolvedValueOnce(page('fresh'));
+ const context = nextContext();
+
+ primeMessageListPage(context, listPage('primed'));
+ await service.getMessageListPage(context);
+ const second = await service.getMessageListPage(context);
+
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(query).toHaveBeenCalledWith(
+ expect.objectContaining({ cursor: null, topicShareId: context.topicShareId }),
+ );
+ expect(second).toEqual({ messages: [{ id: 'fresh' }], olderCursor: null });
+ });
+
+ it('keeps the first page primed for a conversation', async () => {
+ const context = nextContext();
+
+ primeMessageListPage(context, listPage('first'));
+ primeMessageListPage({ ...context }, listPage('second'));
+
+ expect(await service.getMessageListPage(context)).toEqual({
+ messages: [{ id: 'first' }],
+ olderCursor: null,
+ });
+ });
+
+ it('is not handed to a different conversation', async () => {
+ query.mockResolvedValueOnce(page('group'));
+ const context = nextContext();
+
+ primeMessageListPage(context, listPage('primed'));
+ const result = await service.getMessageListPage({ ...context, groupId: 'group-1' });
+
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ messages: [{ id: 'group' }], olderCursor: null });
+ });
+
+ it('falls back to a fresh read when the primed request failed', async () => {
+ query.mockResolvedValueOnce(page('retry'));
+ const context = nextContext();
+
+ primeMessageListPage(context, Promise.reject(new Error('network')));
+ const result = await service.getMessageListPage(context);
+
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ messages: [{ id: 'retry' }], olderCursor: null });
+ });
+});
+
+describe('readMessagesForward', () => {
+ const forwardClient = (response: unknown) => {
+ const forwardQuery = vi.fn().mockResolvedValue(response);
+ return {
+ client: { message: { getMessagesByCursor: { query: forwardQuery } } } as any,
+ forwardQuery,
+ };
+ };
+ const context = { agentId: 'agent-1', topicId: 'topic-1', topicShareId: 'share-1' };
+
+ it('asks for a forward page of the given size', async () => {
+ const { client, forwardQuery } = forwardClient({
+ direction: 'forward',
+ hasMore: false,
+ messages: [],
+ nextCursor: null,
+ });
+
+ await readMessagesForward(client, context, null, SHARED_TOPIC_FIRST_PAGE);
+
+ expect(forwardQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ countBudget: SHARED_TOPIC_FIRST_PAGE.countBudget,
+ cursor: null,
+ direction: 'forward',
+ roundLimit: SHARED_TOPIC_FIRST_PAGE.roundLimit,
+ topicShareId: 'share-1',
+ }),
+ );
+ });
+
+ it('returns the page with the cursor for the rounds after it', async () => {
+ const cursor = { createdAt: '2024-01-01T00:00:01.000000Z', id: 'a1' };
+ const { client } = forwardClient({
+ direction: 'forward',
+ hasMore: true,
+ messages: [{ id: 'u1' }, { id: 'a1' }],
+ nextCursor: cursor,
+ });
+
+ const page = await readMessagesForward(client, context, null);
+
+ expect(page).toEqual({ messages: [{ id: 'u1' }, { id: 'a1' }], newerCursor: cursor });
+ });
+
+ it.each([undefined, 'backward'])(
+ 'refuses a page the server did not read forward (echo: %s)',
+ async (direction) => {
+ const { client } = forwardClient({
+ direction,
+ hasMore: false,
+ messages: [{ id: 'newest' }],
+ nextCursor: null,
+ });
+
+ await expect(readMessagesForward(client, context, null)).rejects.toBeInstanceOf(
+ ForwardPagingUnsupportedError,
+ );
+ },
+ );
+});
diff --git a/src/services/message/roundCursorPage.ts b/src/services/message/roundCursorPage.ts
new file mode 100644
index 00000000000..4738ca9885d
--- /dev/null
+++ b/src/services/message/roundCursorPage.ts
@@ -0,0 +1,189 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+import { type MessageListQueryContext, normalizeMessageListQueryContext } from '@/libs/swr/keys';
+import { lambdaClient } from '@/libs/trpc/client';
+
+import type { MessageListPage, MessageRoundCursor } from './cache';
+
+/**
+ * Rows walked per round-cursor page: whole rounds up to this many mainline rows,
+ * matching the newest-first window `getMessages` serves.
+ */
+export const MESSAGE_PAGE_ROW_BUDGET = 1000;
+
+/** Page sizes for reading a topic forward from its first round. */
+export interface ForwardPageSize {
+ countBudget: number;
+ roundLimit: number;
+}
+
+/** The first page of a shared topic, embedded in the share document. */
+export const SHARED_TOPIC_FIRST_PAGE: ForwardPageSize = { countBudget: 200, roundLimit: 3 };
+
+/** Each page a reader appends while scrolling a shared topic. */
+export const FORWARD_PAGE: ForwardPageSize = { countBudget: 1000, roundLimit: 5 };
+
+export interface RoundCursorReadParams extends MessageListQueryContext {
+ projectToolPayloads?: boolean;
+ skipWorks?: boolean;
+}
+
+/** The `getMessagesByCursor` input for one round-aligned page of a topic's mainline. */
+export const toRoundCursorQueryInput = (
+ params: RoundCursorReadParams,
+ cursor: MessageRoundCursor | null,
+) => ({
+ agentId: params.agentId,
+ countBudget: MESSAGE_PAGE_ROW_BUDGET,
+ cursor,
+ groupId: params.groupId,
+ includeFileWorks: true,
+ projectToolPayloads: params.projectToolPayloads,
+ // 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,
+});
+
+export type RoundCursorQueryResult = Awaited<
+ ReturnType<typeof lambdaClient.message.getMessagesByCursor.query>
+>;
+
+export const toMessageListPage = (page: RoundCursorQueryResult): MessageListPage => ({
+ messages: page.messages as unknown as UIChatMessage[],
+ olderCursor: page.nextCursor,
+});
+
+/** One round-aligned page of a topic's mainline: the newest with a `null` cursor, else older. */
+export const readMessagesByRoundCursor = async (
+ params: RoundCursorReadParams,
+ cursor: MessageRoundCursor | null,
+): Promise<MessageListPage> =>
+ toMessageListPage(
+ await lambdaClient.message.getMessagesByCursor.query(toRoundCursorQueryInput(params, cursor)),
+ );
+
+/** The `getMessagesByCursor` input for one forward page, starting after `cursor`. */
+export const toForwardRoundCursorQueryInput = (
+ params: MessageListQueryContext,
+ cursor: MessageRoundCursor | null,
+ size: ForwardPageSize = FORWARD_PAGE,
+) => ({
+ agentId: params.agentId,
+ countBudget: size.countBudget,
+ cursor,
+ direction: 'forward' as const,
+ groupId: params.groupId,
+ includeFileWorks: true,
+ roundLimit: size.roundLimit,
+ topicId: params.topicId,
+ topicShareId: params.topicShareId,
+});
+
+/** The server answered with a page it did not read forward. */
+export class ForwardPagingUnsupportedError extends Error {
+ constructor() {
+ super('getMessagesByCursor did not page forward');
+ this.name = 'ForwardPagingUnsupportedError';
+ }
+}
+
+export interface ForwardMessagePage {
+ messages: UIChatMessage[];
+ /** Cursor for the rounds after this page, or null at the topic's end. */
+ newerCursor: MessageRoundCursor | null;
+}
+
+interface ForwardCursorClient {
+ message: {
+ getMessagesByCursor: {
+ query: (input: ReturnType<typeof toForwardRoundCursorQueryInput>) => Promise<{
+ direction?: 'backward' | 'forward';
+ messages: unknown[];
+ nextCursor: MessageRoundCursor | null;
+ }>;
+ };
+ };
+}
+
+/**
+ * One forward page through `client`: the browser's lambda client, or the share
+ * worker's server client. A server that predates `direction` strips it and
+ * answers with the newest page, so anything not echoed as forward is refused.
+ */
+export const readMessagesForward = async (
+ client: ForwardCursorClient,
+ params: MessageListQueryContext,
+ cursor: MessageRoundCursor | null,
+ size: ForwardPageSize = FORWARD_PAGE,
+): Promise<ForwardMessagePage> => {
+ const page = await client.message.getMessagesByCursor.query(
+ toForwardRoundCursorQueryInput(params, cursor, size),
+ );
+ if (page.direction !== 'forward') throw new ForwardPagingUnsupportedError();
+
+ return { messages: page.messages as UIChatMessage[], newerCursor: page.nextCursor };
+};
+
+/**
+ * Newest pages requested before the code that renders them has loaded, by
+ * conversation. The share page starts its read from the document, while the
+ * conversation stack is still downloading, and hands it over here. This module
+ * stays dependency-light because the share route imports it ahead of the
+ * message service and the chat store.
+ */
+const primedPages = new Map<string, Promise<MessageListPage>>();
+
+const primeKey = (context: MessageListQueryContext) =>
+ JSON.stringify(normalizeMessageListQueryContext(context));
+
+/**
+ * Hand over a conversation's newest page already in flight; its first head read
+ * takes it instead of asking again. The page must be read without tool-payload
+ * projection: whole payloads are the answer that cannot lose data for any reader.
+ */
+export const primeMessageListPage = (
+ context: MessageListQueryContext,
+ page: Promise<MessageListPage>,
+): void => {
+ const key = primeKey(context);
+ if (primedPages.has(key)) return;
+
+ // The taker owns failure (it falls back to its own read); an unclaimed page
+ // must not surface as an unhandled rejection.
+ page.catch(() => {});
+ primedPages.set(key, page);
+};
+
+/** Hand over a primed page once: every later read of the conversation goes to the server. */
+export const takePrimedMessageListPage = (
+ context: MessageListQueryContext,
+): Promise<MessageListPage> | undefined => {
+ const key = primeKey(context);
+ const page = primedPages.get(key);
+ if (page) primedPages.delete(key);
+
+ return page;
+};
+
+/** First forward pages handed over by the document, by conversation. */
+const primedForwardPages = new Map<string, Promise<ForwardMessagePage>>();
+
+/** Hand over a conversation's first forward page; its forward head read takes it once. */
+export const primeForwardMessagePage = (
+ context: MessageListQueryContext,
+ page: ForwardMessagePage,
+): void => {
+ primedForwardPages.set(primeKey(context), Promise.resolve(page));
+};
+
+export const takePrimedForwardMessagePage = (
+ context: MessageListQueryContext,
+): Promise<ForwardMessagePage> | undefined => {
+ const key = primeKey(context);
+ const page = primedForwardPages.get(key);
+ if (page) primedForwardPages.delete(key);
+
+ return page;
+};
diff --git a/src/store/chat/slices/message/actions/transcript.forward.test.ts b/src/store/chat/slices/message/actions/transcript.forward.test.ts
new file mode 100644
index 00000000000..da7c64d068c
--- /dev/null
+++ b/src/store/chat/slices/message/actions/transcript.forward.test.ts
@@ -0,0 +1,187 @@
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+import { waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { messageService } from '@/services/message';
+import { clearMessageListClientCacheState } from '@/services/message/cache';
+import { conversationMessagesKey } from '@/services/message/replica';
+import { primeForwardMessagePage } from '@/services/message/roundCursorPage';
+import { useChatStore } from '@/store/chat';
+import { messageStateSelectors } from '@/store/chat/selectors';
+
+import { resetTranscripts, rowsOf, syncMessages } from './testUtils';
+
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => ({
+ flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt),
+ messageMap: Object.fromEntries(messages.map((m) => [m.id, m])),
+ }),
+}));
+
+vi.mock('@/services/message', () => {
+ const getMessages = vi.fn();
+ return {
+ messageService: {
+ getEarlierMessages: vi.fn(),
+ getMessageListPage: vi.fn((params) => getMessages(params)),
+ getMessages,
+ },
+ };
+});
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { message: { getMessagesByCursor: { query: vi.fn() } } },
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => undefined,
+ useActiveWorkspaceId: () => undefined,
+}));
+
+const fired = vi.hoisted(() => new Set<string>());
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn((key, fetcher, options) => {
+ const id = JSON.stringify(key);
+ if (key && !fired.has(id)) {
+ fired.add(id);
+ fetcher?.().then((data: unknown) => options?.onSuccess?.(data));
+ }
+ return { data: undefined, isValidating: true, mutate: vi.fn() };
+ }),
+}));
+
+const query = vi.mocked(lambdaClient.message.getMessagesByCursor.query);
+
+const row = (id: string, createdAt: number) =>
+ ({ content: id, createdAt, id, role: 'user' }) as UIChatMessage;
+
+const cursorAt = (id: string) => ({ createdAt: '2024-01-01T00:00:00.000Z', id });
+
+const forward = (shareId: string): ConversationContext => ({
+ agentId: 'share-agent',
+ messageReadMode: 'forward',
+ topicId: `topic-${shareId}`,
+ topicShareId: shareId,
+});
+
+const forwardPage = (ids: string[], next: string | null) => ({
+ direction: 'forward' as const,
+ hasMore: next !== null,
+ messages: ids.map((id, i) => row(id, i)),
+ nextCursor: next ? cursorAt(next) : null,
+});
+
+describe('message transcript in forward read mode', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ fired.clear();
+ clearMessageListClientCacheState();
+ resetTranscripts();
+ });
+
+ it('reads the head forward from the first round with the shared first-page size', async () => {
+ const context = forward('share-head');
+ query.mockResolvedValueOnce(forwardPage(['u1', 'a1'], 'a1'));
+
+ syncMessages(context);
+
+ await waitFor(() => expect(rowsOf(context)?.map((m) => m.id)).toEqual(['u1', 'a1']));
+ expect(query).toHaveBeenCalledWith(
+ expect.objectContaining({
+ countBudget: 200,
+ cursor: null,
+ direction: 'forward',
+ roundLimit: 3,
+ topicShareId: 'share-head',
+ }),
+ );
+ expect(messageService.getMessageListPage).not.toHaveBeenCalled();
+ expect(messageStateSelectors.hasLaterMessages(context)(useChatStore.getState())).toBe(true);
+ });
+
+ it('takes the first page the document embedded instead of asking again', async () => {
+ const context = forward('share-primed');
+ primeForwardMessagePage(context, {
+ messages: [row('u1', 0), row('a1', 1)],
+ newerCursor: cursorAt('a1'),
+ });
+
+ syncMessages(context);
+
+ await waitFor(() => expect(rowsOf(context)?.map((m) => m.id)).toEqual(['u1', 'a1']));
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('appends the next rounds after the loaded ones until the topic ends', async () => {
+ const context = forward('share-later');
+ query.mockResolvedValueOnce(forwardPage(['u1', 'a1'], 'a1'));
+ syncMessages(context);
+ await waitFor(() => expect(rowsOf(context)).toHaveLength(2));
+ query.mockResolvedValueOnce({
+ ...forwardPage([], null),
+ messages: [row('u2', 2), row('a2', 3)],
+ });
+
+ const result = await useChatStore.getState().loadLaterMessages(context);
+
+ expect(result).toEqual({ error: undefined, started: true });
+ expect(query).toHaveBeenLastCalledWith(
+ expect.objectContaining({ cursor: cursorAt('a1'), direction: 'forward' }),
+ );
+ expect(rowsOf(context)?.map((m) => m.id)).toEqual(['u1', 'a1', 'u2', 'a2']);
+ expect(messageStateSelectors.hasLaterMessages(context)(useChatStore.getState())).toBe(false);
+ await expect(useChatStore.getState().loadLaterMessages(context)).resolves.toEqual({
+ started: false,
+ });
+ });
+
+ it('resolves a failed later page with its error and keeps the loaded rows', async () => {
+ const context = forward('share-fail');
+ query.mockResolvedValueOnce(forwardPage(['u1', 'a1'], 'a1'));
+ syncMessages(context);
+ await waitFor(() => expect(rowsOf(context)).toHaveLength(2));
+ const failure = new Error('network down');
+ query.mockRejectedValueOnce(failure);
+
+ const result = await useChatStore.getState().loadLaterMessages(context);
+
+ expect(result).toEqual({ error: failure, started: true });
+ expect(rowsOf(context)?.map((m) => m.id)).toEqual(['u1', 'a1']);
+ });
+
+ it('never pages earlier history of a forward transcript', async () => {
+ const context = forward('share-no-earlier');
+ query.mockResolvedValueOnce(forwardPage(['u1', 'a1'], 'a1'));
+ syncMessages(context);
+ await waitFor(() => expect(rowsOf(context)).toHaveLength(2));
+
+ const result = await useChatStore.getState().loadEarlierMessages(context);
+
+ expect(result).toEqual({ started: false });
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(messageService.getEarlierMessages).not.toHaveBeenCalled();
+ });
+
+ it('keeps a forward transcript in memory, apart from the newest-first one', () => {
+ const owned = { agentId: 'a', topicId: 't' };
+ const ownedForward = { ...owned, messageReadMode: 'forward' as const };
+
+ expect(conversationMessagesKey(owned)).toMatch(/^p:/);
+ expect(conversationMessagesKey(ownedForward)).toMatch(/^m:/);
+ expect(conversationMessagesKey(forward('s'))).not.toBe(
+ conversationMessagesKey({ ...forward('s'), messageReadMode: undefined }),
+ );
+ });
+
+ it('does not page later rounds of a newest-first transcript', async () => {
+ const context = { agentId: 'owned-agent', topicId: 'owned-topic' };
+
+ await expect(useChatStore.getState().loadLaterMessages(context)).resolves.toEqual({
+ started: false,
+ });
+ expect(messageStateSelectors.hasLaterMessages(context)(useChatStore.getState())).toBe(false);
+ });
+});
diff --git a/src/store/chat/slices/message/actions/transcript.ts b/src/store/chat/slices/message/actions/transcript.ts
index 16edaec071e..5a9fa8dea55 100644
--- a/src/store/chat/slices/message/actions/transcript.ts
+++ b/src/store/chat/slices/message/actions/transcript.ts
@@ -90,6 +90,7 @@ export class MessageTranscriptActionImpl {
): Promise<{ error?: unknown; started: boolean }> => {
const skipped = { started: false };
if (!context.agentId || !context.topicId) return skipped;
+ if (context.messageReadMode === 'forward') return skipped;
const { slice } = this.#transcript;
const key = this.#transcript.keyOf(context);
@@ -123,6 +124,29 @@ export class MessageTranscriptActionImpl {
return { error: error ?? undefined, started: true };
};
+ /**
+ * Load the rounds after a forward transcript's loaded pages and append them.
+ * No-ops for a newest-first transcript, while a page is in flight, and once
+ * the topic's end is reached. Never rejects: resolves the failure instead.
+ */
+ loadLaterMessages = async (
+ context: ConversationContext,
+ options?: { onStart?: () => void },
+ ): Promise<{ error?: unknown; started: boolean }> => {
+ const skipped = { started: false };
+ if (context.messageReadMode !== 'forward') return skipped;
+
+ const key = this.#transcript.keyOf(context);
+ const view = this.#transcript.read(key);
+ if (!view?.hasMore || view.isLoadingMore) return skipped;
+
+ options?.onStart?.();
+ await this.#transcript.slice.loadMore(key, context);
+ const error = this.#transcript.read(key)?.loadMoreError;
+ if (error) log('[loadLaterMessages] failed | key=%s | %O', messageMapKey(context), error);
+ return { error: error ?? undefined, started: true };
+ };
+
/**
* Seed a conversation's persisted transcript before its route commits, so a
* topic opened before paints from local data instead of a skeleton. Rows
diff --git a/src/store/chat/slices/message/selectors/messageState.ts b/src/store/chat/slices/message/selectors/messageState.ts
index dcc262c4ae3..4439c3bccd0 100644
--- a/src/store/chat/slices/message/selectors/messageState.ts
+++ b/src/store/chat/slices/message/selectors/messageState.ts
@@ -1,3 +1,7 @@
+import { type ConversationContext } from '@lobechat/types';
+
+import { conversationMessagesKey } from '@/services/message/replica';
+
import { type ChatStoreState } from '../../../initialState';
import { operationSelectors } from '../../operation/selectors';
import { getDbMessageByToolCallId } from './dbMessage';
@@ -62,7 +66,13 @@ const isToolApiNameShining =
const isCreatingMessage = (s: ChatStoreState) => s.isCreatingMessage;
+/** A forward transcript has rounds after its loaded pages. */
+const hasLaterMessages = (context: ConversationContext) => (s: ChatStoreState) =>
+ context.messageReadMode === 'forward' &&
+ !!s.messagePagingMap[conversationMessagesKey(context)]?.hasMore;
+
export const messageStateSelectors = {
+ hasLaterMessages,
isCreatingMessage,
isInToolsCalling,
isMessageCollapsed,
diff --git a/src/store/chat/slices/message/transcript/index.ts b/src/store/chat/slices/message/transcript/index.ts
index 855593bb23a..b4e3b06db13 100644
--- a/src/store/chat/slices/message/transcript/index.ts
+++ b/src/store/chat/slices/message/transcript/index.ts
@@ -3,6 +3,7 @@ import debug from 'debug';
import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';
import { createReplicaSlice, readReplicaStoredKeys } from '@/libs/replica';
+import { lambdaClient } from '@/libs/trpc/client';
import { messageService } from '@/services/message';
import {
getMessageListCacheIdentity,
@@ -19,6 +20,11 @@ import {
toPersistedTranscript,
transcriptOf,
} from '@/services/message/replica';
+import {
+ readMessagesForward,
+ SHARED_TOPIC_FIRST_PAGE,
+ takePrimedForwardMessagePage,
+} from '@/services/message/roundCursorPage';
import { topicService } from '@/services/topic';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { topicSelectors } from '@/store/chat/slices/topic/selectors';
@@ -84,6 +90,17 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
const bucketRows = (key: string) => get().dbMessagesMap[bucketOfKey(key).bucket];
// ---- reads ---------------------------------------------------------------
+ const fetchForward = async (
+ context: ConversationMessageParams,
+ cursor: ConversationMessagePage['nextCursor'] = null,
+ ): Promise<ConversationMessageFetch> => {
+ const page = cursor
+ ? await readMessagesForward(lambdaClient, context, cursor)
+ : await (takePrimedForwardMessagePage(context) ??
+ readMessagesForward(lambdaClient, context, null, SHARED_TOPIC_FIRST_PAGE));
+ return { items: page.messages, nextCursor: page.newerCursor };
+ };
+
const fetchHead = async (context: ConversationMessageParams): Promise<UIChatMessage[]> => {
const syncKey = getMessageListCacheIdentity(context);
const dbMessages = bucketRows(conversationMessagesKey(context)) ?? [];
@@ -195,7 +212,12 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
const slice = createReplicaSlice(conversationMessagesResource, {
actionPrefix: 'messageTranscript',
- fetcher: (context, cursor) => (cursor ? fetchOlder(context, cursor) : fetchHead(context)),
+ fetcher: (context, cursor) =>
+ context.messageReadMode === 'forward'
+ ? fetchForward(context, cursor)
+ : cursor
+ ? fetchOlder(context, cursor)
+ : fetchHead(context),
get,
prepareHead,
set,
diff --git a/src/utils/locale/runtimeErrorMessage.ts b/src/utils/locale/runtimeErrorMessage.ts
index 69b3047b4dd..112ce11e178 100644
--- a/src/utils/locale/runtimeErrorMessage.ts
+++ b/src/utils/locale/runtimeErrorMessage.ts
@@ -1,4 +1,4 @@
-import { getRuntimeErrorI18nKey } from '@lobechat/model-runtime';
+import { getRuntimeErrorI18nKey } from '@lobechat/model-runtime/errors';
/**
* Loose `t` shape that accepts any key / vars — the type-safe key inference in
diff --git a/src/utils/server/parseModels.ts b/src/utils/server/parseModels.ts
index 9d2ffd9f926..9fda926f7f5 100644
--- a/src/utils/server/parseModels.ts
+++ b/src/utils/server/parseModels.ts
@@ -1,4 +1,4 @@
-import { getModelPropertyWithFallback } from '@lobechat/model-runtime';
+import { getModelPropertyWithFallback } from '@lobechat/model-runtime/getModelPropertyWithFallback';
import { merge } from '@lobechat/utils';
import { produce } from 'immer';
import {
diff --git a/vitest.config.mts b/vitest.config.mts
index 30b8463fb30..a21975a692f 100644
--- a/vitest.config.mts
+++ b/vitest.config.mts
@@ -77,7 +77,7 @@ export default defineConfig({
exclude: ['crypto', 'util', 'tty'],
},
plugins: [
- tsconfigPaths({ projects: ['.', './apps/workbench'] }),
+ tsconfigPaths({ projects: ['.', './apps/share', './apps/workbench'] }),
// Let `.md` imports resolve to their raw text content so Rollup/Vitest
// doesn't try to parse Markdown as JavaScript.
{