Skip to content

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

✨ feat(chat): prefetch a topic's first page and final-answer previews on hover (#21724)

Inneieda6bdfdc196
diff --git a/apps/server/src/routers/lambda/__tests__/integration/message.topicPreviews.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/message.topicPreviews.integration.test.ts
new file mode 100644
index 00000000000..f555375b68b
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/message.topicPreviews.integration.test.ts
@@ -0,0 +1,302 @@
+// @vitest-environment node
+import { deriveOperationEditedFiles } from '@lobechat/builtin-tools/operationArtifacts';
+import { resolveConversationTail } from '@lobechat/conversation-flow';
+import { type LobeChatDatabase } from '@lobechat/database';
+import { chatGroups, messagePlugins, messages, topics } 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;
+ }),
+}));
+
+const featureFlags = vi.hoisted(() => ({ enableTopicPreview: true }));
+vi.mock('@/server/featureFlags', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(async () => featureFlags),
+}));
+
+const at = (seconds: number) => new Date(Date.UTC(2024, 0, 1, 0, 0, seconds));
+
+describe('message.getTopicPreviews', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+
+ const createTopic = async (values: Partial<typeof topics.$inferInsert> = {}) => {
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ userId, ...values })
+ .returning();
+ return topic;
+ };
+
+ const seedSingleReply = async (topicId: string) => {
+ await serverDB.insert(messages).values([
+ { content: 'older', createdAt: at(0), id: `${topicId}-u0`, role: 'user', topicId, userId },
+ {
+ content: 'older answer',
+ createdAt: at(1),
+ id: `${topicId}-a0`,
+ parentId: `${topicId}-u0`,
+ role: 'assistant',
+ topicId,
+ userId,
+ },
+ {
+ content: 'question',
+ createdAt: at(2),
+ id: `${topicId}-u1`,
+ parentId: `${topicId}-a0`,
+ role: 'user',
+ topicId,
+ userId,
+ },
+ {
+ content: 'final answer',
+ createdAt: at(3),
+ id: `${topicId}-a1`,
+ parentId: `${topicId}-u1`,
+ role: 'assistant',
+ topicId,
+ userId,
+ },
+ ]);
+ };
+
+ const seedToolRound = async (
+ topicId: string,
+ { finished, writesFile = false }: { finished: boolean; writesFile?: boolean },
+ ) => {
+ const tool = writesFile
+ ? {
+ apiName: 'writeFile',
+ arguments: '{"path":"/workspace/a.ts","content":"x"}',
+ identifier: 'lobe-cloud-sandbox',
+ state: { path: '/workspace/a.ts', success: true },
+ }
+ : { apiName: 'search', arguments: '{"query":"x"}', identifier: 'lobe-web-browsing' };
+ await serverDB.insert(messages).values([
+ { content: 'question', createdAt: at(0), id: `${topicId}-u1`, role: 'user', topicId, userId },
+ {
+ content: '',
+ createdAt: at(1),
+ id: `${topicId}-a1`,
+ parentId: `${topicId}-u1`,
+ role: 'assistant',
+ tools: [
+ {
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ id: `${topicId}-call`,
+ identifier: tool.identifier,
+ type: 'builtin',
+ },
+ ],
+ topicId,
+ userId,
+ },
+ {
+ content: 'search result',
+ createdAt: at(2),
+ id: `${topicId}-t1`,
+ parentId: `${topicId}-a1`,
+ role: 'tool',
+ topicId,
+ userId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ ...tool,
+ id: `${topicId}-t1`,
+ toolCallId: `${topicId}-call`,
+ userId,
+ });
+ if (finished) {
+ await serverDB.insert(messages).values({
+ content: 'final answer',
+ createdAt: at(3),
+ id: `${topicId}-a2`,
+ parentId: `${topicId}-t1`,
+ role: 'assistant',
+ topicId,
+ userId,
+ });
+ }
+ };
+
+ const readHeadPage = async (topicId: string) => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+ return caller.getMessagesByCursor({
+ countBudget: 50,
+ includeFileWorks: true,
+ projectToolPayloads: true,
+ roundLimit: 1000,
+ topicId,
+ });
+ };
+
+ const headPageTail = async (topicId: string) => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+ const page = await caller.getMessagesByCursor({
+ countBudget: 50,
+ includeFileWorks: true,
+ projectToolPayloads: true,
+ roundLimit: 1000,
+ topicId,
+ });
+ return page.messages.at(-1);
+ };
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ featureFlags.enableTopicPreview = true;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ it('returns the head page final answer for a plain reply', async () => {
+ const topic = await createTopic();
+ await seedSingleReply(topic.id);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ expect(item).toMatchObject({ kind: 'single', status: 'ok', topicId: topic.id });
+ if (item.status !== 'ok') throw new Error('expected a preview');
+ expect(item.message).toEqual(await headPageTail(topic.id));
+ expect(item.topicUpdatedAt).toBe(topic.updatedAt.toISOString());
+ });
+
+ it('returns a group tail for a round that called tools', async () => {
+ const topic = await createTopic();
+ await seedToolRound(topic.id, { finished: true });
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ expect(item).toMatchObject({ kind: 'group', status: 'ok' });
+ if (item.status !== 'ok') throw new Error('expected a preview');
+ expect(item.message.id).toBe(`${topic.id}-a2`);
+ expect(item.message).toEqual(await headPageTail(topic.id));
+ expect(item).toMatchObject({
+ editedFiles: [],
+ goals: [],
+ workRootOperationId: null,
+ works: [],
+ });
+ });
+
+ it('carries the question and step timeline when the round is the whole topic', async () => {
+ const topic = await createTopic();
+ await seedToolRound(topic.id, { finished: true });
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ if (item.status !== 'ok') throw new Error('expected a preview');
+ const page = await readHeadPage(topic.id);
+ const rendered = resolveConversationTail(page.messages);
+ expect(item.leading).toEqual([page.messages[0]]);
+ expect(item.blocks).toEqual(rendered?.message.children);
+ expect(item.timeline.map((row) => row.id)).toEqual(page.messages.map((row) => row.id));
+ });
+
+ it('leaves out the question when earlier rounds exist', async () => {
+ const topic = await createTopic();
+ await seedSingleReply(topic.id);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ if (item.status !== 'ok') throw new Error('expected a preview');
+ expect(item.leading).toBeNull();
+ expect(item.blocks).toEqual([]);
+ });
+
+ it('derives edited files the same way the renderer does over the head page', async () => {
+ const topic = await createTopic();
+ await seedToolRound(topic.id, { finished: true, writesFile: true });
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ if (item.status !== 'ok') throw new Error('expected a preview');
+ const rendered = resolveConversationTail((await readHeadPage(topic.id)).messages);
+ expect(item.editedFiles).toHaveLength(1);
+ expect(item.editedFiles).toEqual(deriveOperationEditedFiles(rendered?.message.children));
+ expect(item.kind).toBe(rendered?.kind);
+ });
+
+ it('skips a running topic', async () => {
+ const topic = await createTopic({ status: 'running' });
+ await seedSingleReply(topic.id);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ expect(item).toEqual({ reason: 'running', status: 'skipped', topicId: topic.id });
+ });
+
+ it('skips a topic that ends on a tool result', async () => {
+ const topic = await createTopic();
+ await seedToolRound(topic.id, { finished: false });
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ expect(item).toEqual({ reason: 'notFinalAnswer', status: 'skipped', topicId: topic.id });
+ });
+
+ it('skips group chat topics', async () => {
+ const [group] = await serverDB.insert(chatGroups).values({ userId }).returning();
+ const topic = await createTopic({ groupId: group.id });
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const [item] = await caller.getTopicPreviews({ groupId: group.id, topicIds: [topic.id] });
+
+ expect(item).toEqual({ reason: 'unsupported', status: 'skipped', topicId: topic.id });
+ });
+
+ it("reports a topic it cannot read as not found, keeping the other topics' previews", async () => {
+ const topic = await createTopic();
+ await seedSingleReply(topic.id);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const items = await caller.getTopicPreviews({ topicIds: ['tpc_missing', topic.id] });
+
+ expect(items[0]).toEqual({ reason: 'notFound', status: 'skipped', topicId: 'tpc_missing' });
+ expect(items[1]).toMatchObject({ status: 'ok', topicId: topic.id });
+ });
+
+ it('answers disabled for every topic when the flag is off', async () => {
+ featureFlags.enableTopicPreview = false;
+ const topic = await createTopic();
+ await seedSingleReply(topic.id);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const items = await caller.getTopicPreviews({ topicIds: [topic.id] });
+
+ expect(items).toEqual([{ reason: 'disabled', status: 'skipped', topicId: topic.id }]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/topicPreviews.test.ts b/apps/server/src/routers/lambda/_helpers/topicPreviews.test.ts
new file mode 100644
index 00000000000..0333cd60111
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/topicPreviews.test.ts
@@ -0,0 +1,41 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { readMessagesByCursor } from './messagesByCursor';
+import { readTopicPreviews } from './topicPreviews';
+
+vi.mock('@/server/featureFlags', () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(async () => ({ enableTopicPreview: true })),
+}));
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return {
+ findByIds: vi.fn(async (ids: string[]) =>
+ ids.map((id) => ({ id, status: 'active', updatedAt: new Date(0) })),
+ ),
+ };
+ }),
+}));
+vi.mock('./messagesByCursor', () => ({ readMessagesByCursor: vi.fn() }));
+
+describe('readTopicPreviews', () => {
+ it('reads one topic at a time', async () => {
+ let inFlight = 0;
+ let maxInFlight = 0;
+ vi.mocked(readMessagesByCursor).mockImplementation(async () => {
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ inFlight -= 1;
+ return { messages: [] } as any;
+ });
+
+ const items = await readTopicPreviews(
+ { serverDB: {} as any, userId: 'user_1' },
+ { agentId: 'agt_1', topicIds: ['tpc_a', 'tpc_b', 'tpc_c', 'tpc_d'] },
+ );
+
+ expect(items).toHaveLength(4);
+ expect(maxInFlight).toBe(1);
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/topicPreviews.ts b/apps/server/src/routers/lambda/_helpers/topicPreviews.ts
new file mode 100644
index 00000000000..adef508e5e9
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/topicPreviews.ts
@@ -0,0 +1,179 @@
+import {
+ deriveOperationEditedFiles,
+ deriveOperationGoals,
+ type OperationEditedFile,
+ type OperationGoal,
+} from '@lobechat/builtin-tools/operationArtifacts';
+import { LOADING_FLAT } from '@lobechat/const';
+import {
+ type ConversationTailKind,
+ findLatestWorkRootOperationId,
+ getOperationFinalRootId,
+ parse,
+ resolveConversationTail,
+} from '@lobechat/conversation-flow';
+import type { AssistantContentBlock, UIChatMessage, WorkSummaryItem } from '@lobechat/types';
+import { z } from 'zod';
+
+import { TopicModel } from '@/database/models/topic';
+import type { LobeChatDatabase } from '@/database/type';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
+import { readMessagesByCursor } from './messagesByCursor';
+
+// The chat head page's budget; the preview reads the same page so its message
+// matches the row the real list renders.
+const HEAD_PAGE_ROW_BUDGET = 50;
+
+export const topicPreviewsInputSchema = z.object({
+ agentId: z.string().nullish(),
+ groupId: z.string().nullish(),
+ topicIds: z.array(z.string().min(1)).min(1).max(5),
+});
+
+export interface TopicPreviewTimelineRow {
+ createdAt: Date | number | string;
+ finishType?: string;
+ id: string;
+ updatedAt: Date | number | string;
+}
+
+export type TopicPreviewSkipReason =
+ 'disabled' | 'notFinalAnswer' | 'notFound' | 'running' | 'unsupported' | 'waitingForHuman';
+
+export type TopicPreviewItem =
+ | {
+ blocks: AssistantContentBlock[];
+ editedFiles: OperationEditedFile[];
+ goals: OperationGoal[];
+ kind: ConversationTailKind;
+ // The rows above the answer, sent only when this round is the whole topic:
+ // the list then top-aligns them instead of filling the screen with history.
+ leading: UIChatMessage[] | null;
+ message: UIChatMessage;
+ status: 'ok';
+ timeline: TopicPreviewTimelineRow[];
+ topicId: string;
+ topicUpdatedAt: string;
+ workRootOperationId: string | null;
+ works: WorkSummaryItem[];
+ }
+ | { reason: TopicPreviewSkipReason; status: 'skipped'; topicId: string };
+
+interface TopicPreviewsContext {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+const skipped = (topicId: string, reason: TopicPreviewSkipReason): TopicPreviewItem => ({
+ reason,
+ status: 'skipped',
+ topicId,
+});
+
+const isFinalAnswer = (message: UIChatMessage | undefined) =>
+ message?.role === 'assistant' &&
+ !message.tools?.length &&
+ !message.error &&
+ !!message.content &&
+ message.content !== LOADING_FLAT;
+
+const findWorks = (messages: UIChatMessage[], rootOperationId: string | undefined) => {
+ if (!rootOperationId) return [];
+ const anchor = messages.find(
+ (message) =>
+ !!message.works?.length &&
+ (getOperationFinalRootId(message.metadata) ?? message.works[0].event.rootOperationId) ===
+ rootOperationId,
+ );
+ return anchor?.works ?? [];
+};
+
+const readTopicPreview = async (
+ ctx: TopicPreviewsContext,
+ agentId: string | null | undefined,
+ topic: { id: string; updatedAt: Date },
+): Promise<TopicPreviewItem> => {
+ const page = await readMessagesByCursor(ctx, {
+ agentId,
+ countBudget: HEAD_PAGE_ROW_BUDGET,
+ includeFileWorks: true,
+ projectToolPayloads: true,
+ roundLimit: 1,
+ topicId: topic.id,
+ });
+ const tail = resolveConversationTail(page.messages);
+ if (!tail) return skipped(topic.id, 'notFound');
+
+ // A steered round renders as one chain across several groups, so its cards
+ // aggregate blocks this single-group derivation would miss.
+ if (page.messages.some((message) => message.role === 'user' && message.metadata?.steer)) {
+ return skipped(topic.id, 'unsupported');
+ }
+
+ const children = (tail.kind === 'group' ? tail.message.children : undefined) ?? [];
+ const leading = page.nextCursor ? null : parse(page.messages).flatList.slice(0, -1);
+ const finalId = tail.kind === 'group' ? children.at(-1)?.id : tail.message.id;
+ const message = page.messages.find((item) => item.id === finalId);
+ if (!isFinalAnswer(message) || !message) return skipped(topic.id, 'notFinalAnswer');
+
+ const taskCompletions = tail.message.taskCompletions as AssistantContentBlock[] | undefined;
+ const workRootOperationId = findLatestWorkRootOperationId(
+ tail.message.metadata,
+ children,
+ taskCompletions,
+ );
+
+ return {
+ blocks: children,
+ editedFiles: deriveOperationEditedFiles(children, !!workRootOperationId),
+ goals: deriveOperationGoals(children),
+ kind: tail.kind,
+ leading: leading as UIChatMessage[] | null,
+ message,
+ status: 'ok',
+ timeline: page.messages.map(({ createdAt, id, metadata, updatedAt }) => ({
+ createdAt,
+ finishType: typeof metadata?.finishType === 'string' ? metadata.finishType : undefined,
+ id,
+ updatedAt,
+ })),
+ topicId: topic.id,
+ topicUpdatedAt: topic.updatedAt.toISOString(),
+ workRootOperationId: workRootOperationId ?? null,
+ works: findWorks(page.messages, workRootOperationId),
+ };
+};
+
+// First version: reads each topic's head page through the chat read pipeline,
+// so `message` matches the real list by construction. The backend replaces the
+// internals with a final-answer-only read before `topic_preview` is turned on.
+export const readTopicPreviews = async (
+ ctx: TopicPreviewsContext,
+ { agentId, groupId, topicIds }: z.infer<typeof topicPreviewsInputSchema>,
+): Promise<TopicPreviewItem[]> => {
+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(ctx.userId);
+ if (!featureFlags.enableTopicPreview) return topicIds.map((id) => skipped(id, 'disabled'));
+ if (groupId) return topicIds.map((id) => skipped(id, 'unsupported'));
+
+ const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ const rows = await topicModel.findByIds(topicIds);
+ const topicsById = new Map(rows.map((row) => [row.id, row]));
+
+ // One head read at a time: a batch must not multiply the per-request DB load.
+ const items: TopicPreviewItem[] = [];
+ for (const topicId of topicIds) {
+ const topic = topicsById.get(topicId);
+ if (!topic || (agentId && topic.agentId && topic.agentId !== agentId)) {
+ items.push(skipped(topicId, 'notFound'));
+ } else if (topic.groupId) {
+ items.push(skipped(topicId, 'unsupported'));
+ } else if (topic.status === 'running' || topic.status === 'waitingForHuman') {
+ items.push(skipped(topicId, topic.status));
+ } else {
+ items.push(await readTopicPreview(ctx, agentId, topic));
+ }
+ }
+ return items;
+};
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 9aa2b283b41..133e99d43d7 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -41,6 +41,7 @@ import {
assertCreatorMessageTargets,
assertCreatorTopicTargets,
} from './_helpers/shareVisitorTargetGuard';
+import { readTopicPreviews, topicPreviewsInputSchema } from './_helpers/topicPreviews';
import { basicContextSchema } from './_schema/context';
const { logTiming, runTimedStage } = createTimingHelpers('lobe-server:chat:lobehub:timing');
@@ -564,6 +565,10 @@ export const messageRouter = router({
.input(messagesByCursorInputSchema)
.query(({ ctx, input }) => readMessagesByCursor(ctx, input)),
+ getTopicPreviews: messageProcedure
+ .input(topicPreviewsInputSchema)
+ .query(({ ctx, input }) => readTopicPreviews(ctx, input)),
+
rankModels: messageProcedure.query(async ({ ctx }) => {
return ctx.messageModel.rankModels();
}),
diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.ts
index 4beb8a5aa8f..4c751e2e1ae 100644
--- a/packages/app-config/src/featureFlags/schema.test.ts
+++ b/packages/app-config/src/featureFlags/schema.test.ts
@@ -193,6 +193,18 @@ describe('mapFeatureFlagsEnvToState', () => {
expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);
});
+ it('should keep topic previews off by default and enable them for listed users', () => {
+ expect(DEFAULT_FEATURE_FLAGS.topic_preview).toBe(false);
+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableTopicPreview).toBe(
+ false,
+ );
+
+ const config = { topic_preview: ['user-123'] };
+
+ expect(mapFeatureFlagsEnvToState(config, 'user-123').enableTopicPreview).toBe(true);
+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableTopicPreview).toBe(false);
+ });
+
it('should gate the mobile gateway mux independently from the Web flag', () => {
expect(DEFAULT_FEATURE_FLAGS.agent_gateway_mux_mobile).toBe(false);
expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableGatewayMuxMobile).toBe(
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index 2789d6c36af..a80fe439041 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -91,6 +91,8 @@ export const FeatureFlagsSchema = z.object({
*/
channel: FeatureFlagValue.optional(),
+ topic_preview: FeatureFlagValue.optional(),
+
// internal flag
agent_onboarding: FeatureFlagValue.optional(),
dev_dock: FeatureFlagValue.optional(),
@@ -170,6 +172,9 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
// Off until an admin publishes a user allowlist or flips it to true.
channel: false,
+ // Off until the backend replaces the preview read; allowlist first.
+ topic_preview: false,
+
agent_onboarding: isDev,
dev_dock: isDev,
auth_captcha: true,
@@ -207,6 +212,7 @@ export const mapFeatureFlagsEnvToState = (
enableLlmRelay: evaluateFeatureFlag(config.agent_llm_relay, userId),
enableDashboard: evaluateFeatureFlag(config.dashboard, userId),
enableChannels: evaluateFeatureFlag(config.channel, userId),
+ enableTopicPreview: evaluateFeatureFlag(config.topic_preview, userId),
showProvider: evaluateFeatureFlag(config.provider_settings, userId),
showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 42ca900c2b9..edb175d9ae1 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -17,7 +17,8 @@
"./dynamicInterventionAudits": "./src/dynamicInterventionAudits.ts",
"./featureGates": "./src/featureGates.ts",
"./workRegistration": "./src/workRegistration.ts",
- "./fileEditScan": "./src/fileEditScan/index.ts"
+ "./fileEditScan": "./src/fileEditScan/index.ts",
+ "./operationArtifacts": "./src/operationArtifacts/index.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tools/src/operationArtifacts/editedFiles.test.ts b/packages/builtin-tools/src/operationArtifacts/editedFiles.test.ts
new file mode 100644
index 00000000000..0d854caefce
--- /dev/null
+++ b/packages/builtin-tools/src/operationArtifacts/editedFiles.test.ts
@@ -0,0 +1,256 @@
+import type { AssistantContentBlock, ChatToolPayloadWithResult } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { collectFileEditToolCallRecords, deriveOperationEditedFiles } from './editedFiles';
+
+/** Build a display tool payload with a resolved plugin state (result.state). */
+const tool = (
+ partial: Partial<ChatToolPayloadWithResult> & { apiName: string; id: string },
+): ChatToolPayloadWithResult => ({
+ arguments: '{}',
+ identifier: 'lobe-cloud-sandbox',
+ type: 'builtin',
+ ...partial,
+});
+
+const block = (tools: ChatToolPayloadWithResult[]): AssistantContentBlock => ({
+ content: '',
+ id: `block-${Math.random()}`,
+ tools,
+});
+
+const sandboxWrite = (id: string, path: string) =>
+ tool({
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path }),
+ id,
+ result: { content: '', id: `${id}-r`, state: { path, success: true } },
+ });
+
+const sandboxEdit = (
+ id: string,
+ path: string,
+ deltas: { diffText?: string; linesAdded?: number; linesDeleted?: number } = {},
+) =>
+ tool({
+ apiName: 'editFile',
+ arguments: JSON.stringify({ path }),
+ id,
+ result: { content: '', id: `${id}-r`, state: { path, ...deltas } },
+ });
+
+describe('collectFileEditToolCallRecords', () => {
+ it('flattens block tools into scanner records, surfacing result.state', () => {
+ const records = collectFileEditToolCallRecords([
+ block([sandboxWrite('t1', '/work/a.ts')]),
+ block([sandboxEdit('t2', '/work/a.ts', { linesAdded: 2 })]),
+ ]);
+
+ expect(records).toEqual([
+ {
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path: '/work/a.ts' }),
+ identifier: 'lobe-cloud-sandbox',
+ state: { path: '/work/a.ts', success: true },
+ toolCallId: 't1',
+ },
+ {
+ apiName: 'editFile',
+ arguments: JSON.stringify({ path: '/work/a.ts' }),
+ identifier: 'lobe-cloud-sandbox',
+ state: { linesAdded: 2, path: '/work/a.ts' },
+ toolCallId: 't2',
+ },
+ ]);
+ });
+
+ it('tolerates empty blocks / tool lists', () => {
+ expect(collectFileEditToolCallRecords([])).toEqual([]);
+ expect(collectFileEditToolCallRecords([block([])])).toEqual([]);
+ });
+
+ // Regression: a tool call with no merged result never executed (pending
+ // human approval, or the run was interrupted first). Forwarding it would let
+ // the scanner fall back to `arguments.path` and show a file as edited that
+ // was never actually written.
+ it('drops tool calls that have no result yet', () => {
+ const records = collectFileEditToolCallRecords([
+ block([
+ tool({ apiName: 'writeFile', arguments: JSON.stringify({ path: '/work/a.ts' }), id: 't1' }),
+ sandboxWrite('t2', '/work/b.ts'),
+ ]),
+ ]);
+
+ expect(records.map((record) => record.toolCallId)).toEqual(['t2']);
+ });
+});
+
+describe('deriveOperationEditedFiles', () => {
+ it('aggregates multi-file edits across blocks', () => {
+ const entries = deriveOperationEditedFiles([
+ block([sandboxWrite('t1', '/work/a.ts')]),
+ block([
+ sandboxEdit('t2', '/work/a.ts', { diffText: '@@ a', linesAdded: 3, linesDeleted: 1 }),
+ sandboxWrite('t3', '/work/b.ts'),
+ ]),
+ ]);
+
+ expect(entries.map((e) => [e.path, e.kind])).toEqual([
+ ['/work/a.ts', 'added'],
+ ['/work/b.ts', 'added'],
+ ]);
+ // Deltas fold onto the write→edit chain for a.ts.
+ expect(entries[0]).toMatchObject({ diffTexts: ['@@ a'], linesAdded: 3, linesDeleted: 1 });
+ });
+
+ it('drops entity-format files (they surface as file Works) but keeps html + other', () => {
+ const entries = deriveOperationEditedFiles(
+ [
+ block([
+ sandboxWrite('t1', '/work/deck.pptx'),
+ sandboxWrite('t2', '/work/data.xlsx'),
+ sandboxWrite('t3', '/work/report.pdf'),
+ sandboxWrite('t4', '/work/index.html'),
+ sandboxWrite('t5', '/work/notes.md'),
+ ]),
+ ],
+ true,
+ );
+
+ expect(entries.map((e) => e.path)).toEqual(['/work/index.html', '/work/notes.md']);
+ });
+
+ it('keeps sandbox entity files when the round has no work surface (legacy client runtime)', () => {
+ // Without a work anchor no file Work registers, so dropping the entry
+ // would make the file invisible on both surfaces β€” the card keeps it.
+ const entries = deriveOperationEditedFiles([
+ block([sandboxWrite('t1', '/work/deck.pptx'), sandboxWrite('t2', '/work/notes.md')]),
+ ]);
+
+ expect(entries.map((e) => e.path)).toEqual(['/work/deck.pptx', '/work/notes.md']);
+ });
+
+ it('keeps a hetero-edited entity file in the card (no file Work covers it)', () => {
+ // Registration only exports from the cloud sandbox, so a codex-edited
+ // entity file registers no Work β€” the card is the only place it can show.
+ const codexCsv = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 2, linesDeleted: 1, path: '/repo/data.csv' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles(
+ [block([sandboxWrite('t1', '/work/deck.pptx'), codexCsv])],
+ true,
+ );
+
+ expect(entries.map((e) => e.path)).toEqual(['/repo/data.csv']);
+ });
+
+ it('keeps a deleted entity file in the card even when the round has a work surface', () => {
+ // The file Work registrar skips `kind === 'deleted'` entries (nothing left
+ // to export), so the card is the only surface where the deletion shows.
+ const codexDelete = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'delete', linesAdded: 0, linesDeleted: 12, path: '/repo/report.pdf' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles([block([codexDelete])], true);
+
+ expect(entries.map((e) => [e.path, e.kind])).toEqual([['/repo/report.pdf', 'deleted']]);
+ });
+
+ it('drops an entity file only when its LAST edit is sandbox-backed', () => {
+ // Sandbox writes it, codex re-edits it β†’ the Work provenance rule keys off
+ // the last edit, so no Work registers and the card must keep the file.
+ const codexReEdit = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 1, linesDeleted: 0, path: '/work/deck.pptx' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles(
+ [block([sandboxWrite('t1', '/work/deck.pptx'), codexReEdit])],
+ true,
+ );
+
+ expect(entries.map((e) => e.path)).toEqual(['/work/deck.pptx']);
+ });
+
+ it('annotates entries with sandboxBacked from the LAST edit provenance', () => {
+ // The card routes clicks by origin: sandbox-backed files live-read via the
+ // sandbox tool, everything else goes through the local/device filesystem.
+ const codexCsv = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 2, linesDeleted: 1, path: '/repo/data.csv' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles([
+ block([sandboxWrite('t1', '/work/notes.md'), codexCsv]),
+ ]);
+
+ expect(entries.map((e) => [e.path, e.sandboxBacked])).toEqual([
+ ['/work/notes.md', true],
+ ['/repo/data.csv', false],
+ ]);
+ });
+
+ it('drops a tool call whose result carries an error', () => {
+ const entries = deriveOperationEditedFiles([
+ block([
+ tool({
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ path: '/work/a.ts' }),
+ id: 't1',
+ result: { content: '', error: 'boom', id: 't1-r', state: { path: '/work/a.ts' } },
+ }),
+ ]),
+ ]);
+ expect(entries).toEqual([]);
+ });
+
+ it('returns an empty list when the operation touched no files', () => {
+ expect(deriveOperationEditedFiles([])).toEqual([]);
+ expect(
+ deriveOperationEditedFiles([
+ block([
+ tool({
+ apiName: 'runCommand',
+ id: 't1',
+ result: { content: '', id: 'r', state: { success: true } },
+ }),
+ ]),
+ ]),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/builtin-tools/src/operationArtifacts/editedFiles.ts b/packages/builtin-tools/src/operationArtifacts/editedFiles.ts
new file mode 100644
index 00000000000..132eb85da11
--- /dev/null
+++ b/packages/builtin-tools/src/operationArtifacts/editedFiles.ts
@@ -0,0 +1,109 @@
+import type { AssistantContentBlock } from '@lobechat/types';
+
+import {
+ classifyEditedFile,
+ CLOUD_SANDBOX_IDENTIFIER,
+ scanOperationFileEdits,
+} from '../fileEditScan';
+import type { EditedFileEntry, FileEditToolCallRecord } from '../fileEditScan/types';
+
+/**
+ * Map the display-layer tool payloads of one assistant round into the shared
+ * scanner's record shape. Each `block.tools` entry is a
+ * `ChatToolPayloadWithResult`, so its persisted `pluginState` is surfaced at
+ * `tool.result.state` (see `FlatListBuilder.createAssistantGroupMessage`) β€” the
+ * exact `state` the scanner reads for sandbox / codex / claude-code edits.
+ */
+export const collectFileEditToolCallRecords = (
+ blocks: AssistantContentBlock[] = [],
+): FileEditToolCallRecord[] =>
+ blocks.flatMap((block) =>
+ (block.tools ?? [])
+ // A tool call with NO merged result never executed (still pending human
+ // approval, or the run was interrupted first) β€” FlatListBuilder only
+ // attaches `result` once a tool message exists. Without this guard the
+ // scanner would fall back to `arguments.path` for sandbox write/edit
+ // calls and show a file as edited that was never actually written.
+ .filter((tool) => tool.result != null)
+ .map((tool) => ({
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ // A failed tool call surfaces its error on the merged result, mirroring
+ // the server's `message_plugins.error`; the scanner skips such records.
+ error: tool.result?.error,
+ identifier: tool.identifier,
+ state: tool.result?.state,
+ toolCallId: tool.id,
+ })),
+ );
+
+/**
+ * Derive the aggregated edited-file entries for one operation's "edited N files"
+ * card. Scans every tool call in the assistant group's blocks, then drops
+ * entity-format files (pptx / xlsx / docx / pdf / …) whose last edit is
+ * sandbox-backed β€” those surface through the `file` Work system (WorksSection /
+ * WorkGallery) instead. An entity file last edited by a hetero source (codex /
+ * claude-code / lobe-local-system / device-routed lobe-skills commands, including
+ * entities detected from shell command text) registers NO file Work (registration
+ * only exports from the cloud sandbox, see server `fileWorkRegistration`), so it
+ * stays in the card β€” the only place it remains visible. HTML (artifact hosting) and every other file stay in the card
+ * too.
+ *
+ * The sandbox-entity drop only applies when `hasWorkSurface` is true β€” i.e. the
+ * round carries a work anchor (server-runtime operation), so a `file` Work can
+ * actually exist. Legacy client-runtime rounds have no work registration; for
+ * them the drop would make the file invisible on BOTH surfaces, so entries are
+ * kept in the card instead.
+ *
+ * Purely derived from the message payload already in the store β€” nothing is
+ * persisted. Callers must memoize on the blocks reference (see
+ * the client's `useOperationEditedFiles`) so the scan runs once per snapshot.
+ */
+/**
+ * An edited-file entry annotated with its content origin, so the card can route
+ * a click to the right preview transport (sandbox live-read vs local/device
+ * filesystem).
+ */
+export interface OperationEditedFile extends EditedFileEntry {
+ /**
+ * Whether the file's LAST edit came from the cloud sandbox β€” mirroring the
+ * server's provenance rule, the terminal edit owns the file's content.
+ */
+ sandboxBacked: boolean;
+}
+
+export const deriveOperationEditedFiles = (
+ blocks: AssistantContentBlock[] = [],
+ hasWorkSurface = false,
+): OperationEditedFile[] => {
+ const records = collectFileEditToolCallRecords(blocks);
+ if (records.length === 0) return [];
+
+ const sandboxToolCallIds = new Set(
+ records
+ .filter((record) => record.identifier === CLOUD_SANDBOX_IDENTIFIER)
+ .map((record) => record.toolCallId),
+ );
+
+ const entries = scanOperationFileEdits(records).map((entry): OperationEditedFile => {
+ const lastSourceToolCallId = entry.sourceToolCallIds.at(-1);
+ return {
+ ...entry,
+ sandboxBacked: !!lastSourceToolCallId && sandboxToolCallIds.has(lastSourceToolCallId),
+ };
+ });
+ if (!hasWorkSurface) return entries;
+
+ // Drop sandbox-backed entity files: their `file` Work card covers them.
+ // Deleted entries stay β€” the file Work registrar skips `kind === 'deleted'`
+ // (there is nothing left in the sandbox to export), so the card is the only
+ // surface where a deleted entity file remains visible.
+ return entries.filter(
+ (entry) =>
+ !(
+ entry.kind !== 'deleted' &&
+ classifyEditedFile(entry.path).category === 'entity' &&
+ entry.sandboxBacked
+ ),
+ );
+};
diff --git a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.test.ts b/packages/builtin-tools/src/operationArtifacts/goals.test.ts
similarity index 99%
rename from src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.test.ts
rename to packages/builtin-tools/src/operationArtifacts/goals.test.ts
index 122674ddaa3..87cc9707e78 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.test.ts
+++ b/packages/builtin-tools/src/operationArtifacts/goals.test.ts
@@ -1,7 +1,7 @@
import type { AssistantContentBlock } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { deriveOperationGoals } from './deriveOperationGoals';
+import { deriveOperationGoals } from './goals';
const block = (tools: AssistantContentBlock['tools']): AssistantContentBlock => ({
content: '',
diff --git a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts b/packages/builtin-tools/src/operationArtifacts/goals.ts
similarity index 96%
rename from src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts
rename to packages/builtin-tools/src/operationArtifacts/goals.ts
index 91f6ed675b1..75cf03b7480 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals.ts
+++ b/packages/builtin-tools/src/operationArtifacts/goals.ts
@@ -1,6 +1,5 @@
import { isGoalIdentifier } from '@lobechat/builtin-tool-goal';
import type { AssistantContentBlock, ChatToolPayloadWithResult } from '@lobechat/types';
-import { safeParseJSON } from '@lobechat/utils';
export interface OperationGoal {
criteriaCount: number;
@@ -15,6 +14,15 @@ export interface OperationGoal {
source: 'command' | 'tool';
}
+const safeParseJSON = (text?: string): unknown => {
+ if (typeof text !== 'string') return undefined;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+};
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null;
diff --git a/packages/builtin-tools/src/operationArtifacts/index.ts b/packages/builtin-tools/src/operationArtifacts/index.ts
new file mode 100644
index 00000000000..3d508a2fc01
--- /dev/null
+++ b/packages/builtin-tools/src/operationArtifacts/index.ts
@@ -0,0 +1,4 @@
+export type { OperationEditedFile } from './editedFiles';
+export { collectFileEditToolCallRecords, deriveOperationEditedFiles } from './editedFiles';
+export type { OperationGoal } from './goals';
+export { deriveOperationGoals } from './goals';
diff --git a/packages/conversation-flow/src/index.ts b/packages/conversation-flow/src/index.ts
index e2948d25176..14db69fa98f 100644
--- a/packages/conversation-flow/src/index.ts
+++ b/packages/conversation-flow/src/index.ts
@@ -37,6 +37,12 @@ export type {
export type { FlatMessage, FlatMessageExtra, FlatMessageRole } from './types';
// Shared Types
+export type { ConversationTail, ConversationTailKind } from './tail';
+export {
+ findLatestWorkRootOperationId,
+ getOperationFinalRootId,
+ resolveConversationTail,
+} from './tail';
export type {
HelperMaps,
IdNode,
diff --git a/packages/conversation-flow/src/tail/index.test.ts b/packages/conversation-flow/src/tail/index.test.ts
new file mode 100644
index 00000000000..b0915a86c42
--- /dev/null
+++ b/packages/conversation-flow/src/tail/index.test.ts
@@ -0,0 +1,80 @@
+import type { AssistantContentBlock } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { Message } from '../types';
+import { findLatestWorkRootOperationId, getOperationFinalRootId, resolveConversationTail } from '.';
+
+const at = (seconds: number) => 1_700_000_000_000 + seconds * 1000;
+
+const message = (partial: Partial<Message> & Pick<Message, 'id' | 'role'>): Message =>
+ ({
+ content: '',
+ createdAt: at(0),
+ meta: {},
+ updatedAt: at(0),
+ ...partial,
+ }) as Message;
+
+describe('resolveConversationTail', () => {
+ it('is single for a plain assistant reply', () => {
+ const tail = resolveConversationTail([
+ message({ content: 'hi', id: 'u1', role: 'user' }),
+ message({ content: 'hello', createdAt: at(1), id: 'a1', parentId: 'u1', role: 'assistant' }),
+ ]);
+
+ expect(tail?.kind).toBe('single');
+ expect(tail?.message.id).toBe('a1');
+ });
+
+ it('is group for an assistant turn that called tools', () => {
+ const tail = resolveConversationTail([
+ message({ content: 'hi', id: 'u1', role: 'user' }),
+ message({
+ createdAt: at(1),
+ id: 'a1',
+ parentId: 'u1',
+ role: 'assistant',
+ tools: [
+ { apiName: 'search', arguments: '{}', id: 'call_1', identifier: 'web', type: 'builtin' },
+ ],
+ }),
+ message({
+ content: 'result',
+ createdAt: at(2),
+ id: 't1',
+ parentId: 'a1',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ }),
+ message({ content: 'done', createdAt: at(3), id: 'a2', parentId: 't1', role: 'assistant' }),
+ ]);
+
+ expect(tail?.kind).toBe('group');
+ expect(tail?.message.children?.map((block) => block.id)).toEqual(['a1', 'a2']);
+ });
+
+ it('is undefined for an empty page', () => {
+ expect(resolveConversationTail([])).toBeUndefined();
+ });
+});
+
+describe('work root', () => {
+ it('reads the stamped root operation id', () => {
+ expect(getOperationFinalRootId({ work: { rootOperationId: 'op_1' } })).toBe('op_1');
+ expect(getOperationFinalRootId({ work: { rootOperationId: 1 } })).toBeUndefined();
+ });
+
+ it('prefers the latest block stamp over the group metadata', () => {
+ const blocks = [
+ { content: '', id: 'b1', metadata: { work: { rootOperationId: 'op_old' } } },
+ { content: '', id: 'b2', metadata: { work: { rootOperationId: 'op_new' } } },
+ ] as AssistantContentBlock[];
+
+ expect(findLatestWorkRootOperationId({ work: { rootOperationId: 'op_group' } }, blocks)).toBe(
+ 'op_new',
+ );
+ expect(findLatestWorkRootOperationId({ work: { rootOperationId: 'op_group' } }, [])).toBe(
+ 'op_group',
+ );
+ });
+});
diff --git a/packages/conversation-flow/src/tail/index.ts b/packages/conversation-flow/src/tail/index.ts
new file mode 100644
index 00000000000..61ac3f08a05
--- /dev/null
+++ b/packages/conversation-flow/src/tail/index.ts
@@ -0,0 +1,38 @@
+import type { AssistantContentBlock } from '@lobechat/types';
+
+import { parse } from '../parse';
+import type { FlatMessage, Message } from '../types';
+
+export type ConversationTailKind = 'group' | 'single';
+
+export interface ConversationTail {
+ kind: ConversationTailKind;
+ message: FlatMessage;
+}
+
+export const resolveConversationTail = (messages: Message[]): ConversationTail | undefined => {
+ const message = parse(messages).flatList.at(-1);
+ if (!message) return undefined;
+
+ return { kind: message.role === 'assistantGroup' ? 'group' : 'single', message };
+};
+
+export const getOperationFinalRootId = (
+ metadata?: { work?: { rootOperationId?: unknown } } | null,
+) =>
+ typeof metadata?.work?.rootOperationId === 'string' ? metadata.work.rootOperationId : undefined;
+
+export const findLatestWorkRootOperationId = (
+ metadata?: { work?: { rootOperationId?: unknown } } | null,
+ children?: AssistantContentBlock[],
+ taskCompletions?: AssistantContentBlock[],
+) => {
+ const blocks = [...(children ?? []), ...(taskCompletions ?? [])];
+
+ for (let index = blocks.length - 1; index >= 0; index -= 1) {
+ const rootOperationId = getOperationFinalRootId(blocks[index]?.metadata);
+ if (rootOperationId) return rootOperationId;
+ }
+
+ return getOperationFinalRootId(metadata);
+};
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 33df011b475..ac8946aefaa 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
@@ -113,6 +113,51 @@ describe('MessageModel.queryTopicMessagesByCursor', () => {
expect(page.hasMore).toBe(true);
});
+ it('returns the newest round whole when it alone exceeds countBudget', async () => {
+ const topicId = 't-cursor-oversized-only';
+ const { ids } = await seedRounds(topicId, 1, 8);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ topicId,
+ roundLimit: 1000,
+ countBudget: 3,
+ });
+
+ expect(page.messages.map((m) => m.id)).toEqual(ids);
+ expect(page.hasMore).toBe(false);
+ expect(page.nextCursor).toBeNull();
+ });
+
+ it('pages older history after an oversized newest round', async () => {
+ const topicId = 't-cursor-oversized-older';
+ await seedRounds(topicId, 2, 8);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ topicId,
+ roundLimit: 1000,
+ countBudget: 3,
+ });
+
+ expect(page.messages).toHaveLength(9);
+ expect(page.messages[0].id).toBe(`${topicId}-u2`);
+ expect(page.hasMore).toBe(true);
+ expect(page.nextCursor).toEqual({ createdAt: expect.any(String), id: `${topicId}-u2` });
+ });
+
+ it('does not start a round at a steer user message', async () => {
+ const topicId = 't-cursor-steer';
+ await seedRounds(topicId, 2, 2);
+ await serverDB
+ .update(messages)
+ .set({ metadata: { steer: true }, role: 'user' })
+ .where(eq(messages.id, `${topicId}-a2-1`));
+
+ const page = await messageModel.queryTopicMessagesByCursor({ topicId, roundLimit: 1 });
+
+ expect(page.messages[0].id).toBe(`${topicId}-u2`);
+ expect(page.messages).toHaveLength(3);
+ });
+
it('returns an empty page with no cursor for an empty topic', async () => {
const topicId = 't-cursor-empty';
await serverDB.insert(topics).values([{ id: topicId, userId }]);
diff --git a/packages/database/src/models/message/cursorWindow.ts b/packages/database/src/models/message/cursorWindow.ts
index 3a2386182b5..8470eb44940 100644
--- a/packages/database/src/models/message/cursorWindow.ts
+++ b/packages/database/src/models/message/cursorWindow.ts
@@ -14,6 +14,7 @@ interface WindowRow {
createdAtIso: string;
id: string;
role: string;
+ steer: boolean;
}
/**
@@ -25,6 +26,11 @@ interface WindowRow {
*/
const createdAtIso = sql<string>`to_char(${messages.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+// A steered user message continues the running turn instead of opening a new one.
+const isSteer = sql<boolean>`coalesce((${messages.metadata}->>'steer')::boolean, false)`;
+
+const isRoundStart = (row: WindowRow) => row.role === 'user' && !row.steer;
+
/**
* `(createdAt, id)` strictly before the cursor β€” the "older than" half-open
* bound. Compares against the cursor's lossless microsecond string cast to
@@ -74,7 +80,7 @@ const resolveBackwardRoundWindow = async (
const olderThanCursor = cursor ? messageStrictlyBefore(cursor) : undefined;
const rows = (await db
- .select({ createdAtIso, id: messages.id, role: messages.role })
+ .select({ createdAtIso, id: messages.id, role: messages.role, steer: isSteer })
.from(messages)
.where(and(where, isNull(messages.messageGroupId), olderThanCursor))
.orderBy(desc(messages.createdAt), desc(messages.id))
@@ -85,7 +91,7 @@ const resolveBackwardRoundWindow = async (
let rounds = 0;
let boundaryIndex = -1;
for (let i = 0; i < rows.length; i += 1) {
- if (rows[i].role === 'user') {
+ if (isRoundStart(rows[i])) {
rounds += 1;
boundaryIndex = i;
if (rounds >= roundLimit) break;
@@ -95,10 +101,39 @@ const resolveBackwardRoundWindow = async (
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).
+ // The newest round is larger than the budget: extend the window to its start
+ // so the page never begins mid-round (the renderer would root the cut-off
+ // steps as orphan chains).
+ if (boundaryIndex === -1 && rows.length > countBudget) {
+ const [roundStart] = (await db
+ .select({ createdAtIso, id: messages.id, role: messages.role, steer: isSteer })
+ .from(messages)
+ .where(
+ and(
+ where,
+ isNull(messages.messageGroupId),
+ olderThanCursor,
+ sql`${messages.role} = 'user'`,
+ sql`not ${isSteer}`,
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(1)) as WindowRow[];
+
+ if (roundStart) {
+ const lowerBound = { createdAt: roundStart.createdAtIso, id: roundStart.id };
+ const [older] = await db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(and(where, isNull(messages.messageGroupId), messageStrictlyBefore(lowerBound)))
+ .limit(1);
+
+ return { hasMore: !!older, lowerBound };
+ }
+ }
+
+ // No round start anywhere older than the cursor: fall back to the oldest
+ // fetched row.
if (boundaryIndex === -1) boundaryIndex = rows.length - 1;
const boundaryRow = rows[boundaryIndex];
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index d943bf38322..e8cb895b22f 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -65,6 +65,8 @@ export type IFeatureFlagsState = {
enableRAGEval: boolean | undefined;
enableSTT: boolean | undefined;
enableStorageOverage: boolean | undefined;
+ /** Hover previews of a topic's final answer (`topic_preview`). */
+ enableTopicPreview: boolean | undefined;
enableVoiceDictation: boolean | undefined;
enableWorkspace: boolean | undefined;
hideDocs: boolean | undefined;
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index f19f9fa2864..6b4b8b96816 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -50,6 +50,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { useTopicHoverPrefetch } from '../../hooks/topicHoverPrefetch/useTopicHoverPrefetch';
import { markSidebarTopicActivation } from '../../hooks/useScrollActiveTopicIntoView';
import { useTopicNavigation } from '../../hooks/useTopicNavigation';
import ThreadList from '../../TopicListContent/ThreadList';
@@ -400,6 +401,11 @@ const TopicItemRow = memo<TopicItemRowProps>(
// `status` is the row's own copy: a project list keeps its topics outside
// the chat store, so `isUnreadCompleted` never sees them there.
const hasUnread = id && (isUnreadCompleted || status === 'unread' || isRunningTailUnread);
+ const hoverPrefetchHandlers = useTopicHoverPrefetch({
+ agentId: activeAgentId,
+ status,
+ topicId: id,
+ });
useEffect(() => {
if (!activeAgentId || !id || !isUnreadCompleted || hasLocalRunningRuntime) return;
@@ -658,7 +664,12 @@ const TopicItemRow = memo<TopicItemRowProps>(
);
return (
- <Flexbox data-testid="topic-item" data-topic-id={id} style={{ position: 'relative' }}>
+ <Flexbox
+ data-testid="topic-item"
+ data-topic-id={id}
+ style={{ position: 'relative' }}
+ {...hoverPrefetchHandlers}
+ >
{metaCard ? (
<Popover
arrow={false}
diff --git a/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/filters.test.ts b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/filters.test.ts
new file mode 100644
index 00000000000..b2d47cb063a
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/filters.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import { canPrefetchTopicFirstPage, canPreviewTopic, type TopicHoverEnv } from './filters';
+
+const env = (overrides: Partial<TopicHoverEnv> = {}): TopicHoverEnv => ({
+ activeTopicId: 'tpc_open',
+ creatingTopicIds: [],
+ enabled: true,
+ hasLocalMessages: () => false,
+ hasPreview: () => false,
+ hasReadingPosition: () => false,
+ isProjectedRead: () => true,
+ isRunning: () => false,
+ ...overrides,
+});
+
+const row = { agentId: 'agt_1', topicId: 'tpc_a' };
+
+describe('canPreviewTopic', () => {
+ it('accepts a finished, unopened topic of a gateway agent', () => {
+ expect(canPreviewTopic(row, env())).toBe(true);
+ });
+
+ it.each<
+ [string, Partial<TopicHoverEnv>, Partial<typeof row & { groupId: string; status: string }>]
+ >([
+ ['the flag is off', { enabled: false }, {}],
+ ['the agent runs in the browser', { isProjectedRead: () => false }, {}],
+ ['the topic is open', { activeTopicId: 'tpc_a' }, {}],
+ ['the topic is still being created', { creatingTopicIds: ['tpc_a'] }, {}],
+ ['messages are already loaded', { hasLocalMessages: () => true }, {}],
+ ['a valid preview is cached', { hasPreview: () => true }, {}],
+ ['the reader left a reading position', { hasReadingPosition: () => true }, {}],
+ ['a local run is going', { isRunning: () => true }, {}],
+ ['the topic reports running', {}, { status: 'running' }],
+ ['the topic waits for a human', {}, { status: 'waitingForHuman' }],
+ ['the topic is a group chat', {}, { groupId: 'grp_1' }],
+ ])('rejects when %s', (_, envOverrides, rowOverrides) => {
+ expect(canPreviewTopic({ ...row, ...rowOverrides }, env(envOverrides))).toBe(false);
+ });
+});
+
+describe('canPrefetchTopicFirstPage', () => {
+ it('accepts an unopened topic of a gateway agent', () => {
+ expect(canPrefetchTopicFirstPage(row, env())).toBe(true);
+ });
+
+ it('leaves loaded, open, browser-run and flag-off topics alone', () => {
+ expect(canPrefetchTopicFirstPage(row, env({ hasLocalMessages: () => true }))).toBe(false);
+ expect(canPrefetchTopicFirstPage(row, env({ activeTopicId: 'tpc_a' }))).toBe(false);
+ expect(canPrefetchTopicFirstPage(row, env({ isProjectedRead: () => false }))).toBe(false);
+ expect(canPrefetchTopicFirstPage(row, env({ enabled: false }))).toBe(false);
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/filters.ts b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/filters.ts
new file mode 100644
index 00000000000..29bd07a153e
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/filters.ts
@@ -0,0 +1,37 @@
+export interface TopicHoverRow {
+ agentId: string;
+ groupId?: string | null;
+ status?: string | null;
+ topicId: string;
+}
+
+export interface TopicHoverEnv {
+ activeTopicId?: string | null;
+ creatingTopicIds: string[];
+ enabled: boolean;
+ hasLocalMessages: (row: TopicHoverRow) => boolean;
+ hasPreview: (topicId: string) => boolean;
+ hasReadingPosition: (row: TopicHoverRow) => boolean;
+ // Browser-run agents read whole 1000-row pages, which a hover must not trigger.
+ isProjectedRead: (agentId: string) => boolean;
+ isRunning: (row: TopicHoverRow) => boolean;
+}
+
+const isUnopenedServerTopic = (row: TopicHoverRow, env: TopicHoverEnv) =>
+ env.enabled &&
+ env.isProjectedRead(row.agentId) &&
+ row.topicId !== env.activeTopicId &&
+ !env.creatingTopicIds.includes(row.topicId) &&
+ !env.hasLocalMessages(row);
+
+export const canPrefetchTopicFirstPage = (row: TopicHoverRow, env: TopicHoverEnv) =>
+ isUnopenedServerTopic(row, env);
+
+export const canPreviewTopic = (row: TopicHoverRow, env: TopicHoverEnv) =>
+ isUnopenedServerTopic(row, env) &&
+ !row.groupId &&
+ row.status !== 'running' &&
+ row.status !== 'waitingForHuman' &&
+ !env.isRunning(row) &&
+ !env.hasPreview(row.topicId) &&
+ !env.hasReadingPosition(row);
diff --git a/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/scheduler.test.ts b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/scheduler.test.ts
new file mode 100644
index 00000000000..876859bec93
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/scheduler.test.ts
@@ -0,0 +1,189 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createTopicHoverScheduler,
+ HOVER_DWELL_MS,
+ NEIGHBOR_FLUSH_MS,
+ SCROLL_QUIET_MS,
+} from './scheduler';
+
+const ROWS = ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9'];
+
+const neighborsOf = (topicId: string) => {
+ const index = ROWS.indexOf(topicId);
+ return ROWS.slice(Math.max(0, index - 2), index + 3).filter((id) => id !== topicId);
+};
+
+const deferred = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => (resolve = r));
+ return { promise, resolve };
+};
+
+const setup = () => {
+ const prefetchFirstPage = vi.fn((_topicId: string) => Promise.resolve());
+ const fetchPreviews = vi.fn((_topicIds: string[]) => Promise.resolve());
+ const scheduler = createTopicHoverScheduler({
+ canPrefetch: () => true,
+ canPreview: () => true,
+ fetchPreviews,
+ getNeighbors: neighborsOf,
+ prefetchFirstPage,
+ });
+ return { fetchPreviews, prefetchFirstPage, scheduler };
+};
+
+describe('createTopicHoverScheduler', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('does nothing when the pointer leaves before the dwell time', () => {
+ const { fetchPreviews, prefetchFirstPage, scheduler } = setup();
+
+ scheduler.pointerMove('t4');
+ vi.advanceTimersByTime(HOVER_DWELL_MS - 20);
+ scheduler.pointerLeave('t4');
+ vi.advanceTimersByTime(NEIGHBOR_FLUSH_MS * 2);
+
+ expect(prefetchFirstPage).not.toHaveBeenCalled();
+ expect(fetchPreviews).not.toHaveBeenCalled();
+ });
+
+ it('prefetches the hovered row at once and its neighbors in one batch after the window', async () => {
+ const { fetchPreviews, prefetchFirstPage, scheduler } = setup();
+
+ scheduler.pointerMove('t4');
+ vi.advanceTimersByTime(HOVER_DWELL_MS);
+
+ expect(prefetchFirstPage).toHaveBeenCalledWith('t4');
+ expect(fetchPreviews).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(NEIGHBOR_FLUSH_MS);
+
+ expect(fetchPreviews).toHaveBeenCalledTimes(1);
+ expect(fetchPreviews).toHaveBeenCalledWith(['t2', 't3', 't5', 't6']);
+ });
+
+ it('ignores hover intent right after the sidebar scrolls', () => {
+ const { fetchPreviews, prefetchFirstPage, scheduler } = setup();
+
+ scheduler.scroll();
+ vi.advanceTimersByTime(SCROLL_QUIET_MS - 50);
+ scheduler.pointerMove('t4');
+ vi.advanceTimersByTime(HOVER_DWELL_MS + NEIGHBOR_FLUSH_MS);
+
+ expect(prefetchFirstPage).not.toHaveBeenCalled();
+ expect(fetchPreviews).not.toHaveBeenCalled();
+ });
+
+ it('cancels a dwell that a scroll interrupts', () => {
+ const { prefetchFirstPage, scheduler } = setup();
+
+ scheduler.pointerMove('t4');
+ vi.advanceTimersByTime(HOVER_DWELL_MS / 2);
+ scheduler.scroll();
+ vi.advanceTimersByTime(HOVER_DWELL_MS);
+
+ expect(prefetchFirstPage).not.toHaveBeenCalled();
+ });
+
+ it('keeps one first page in flight and only queues the latest hovered row', async () => {
+ const { prefetchFirstPage, scheduler } = setup();
+ const first = deferred();
+ prefetchFirstPage.mockImplementationOnce(() => first.promise);
+
+ scheduler.focus('t1');
+ scheduler.focus('t4');
+ scheduler.focus('t8');
+
+ expect(prefetchFirstPage.mock.calls).toEqual([['t1']]);
+
+ first.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(prefetchFirstPage.mock.calls).toEqual([['t1'], ['t8']]);
+ });
+
+ it("caps a batch at four, keeping the latest hovered row's neighbors", async () => {
+ const { fetchPreviews, scheduler } = setup();
+
+ scheduler.focus('t1');
+ scheduler.focus('t7');
+ await vi.advanceTimersByTimeAsync(NEIGHBOR_FLUSH_MS);
+
+ expect(fetchPreviews).toHaveBeenCalledTimes(1);
+ expect(fetchPreviews.mock.calls[0][0]).toEqual(['t5', 't6', 't8', 't9']);
+ });
+
+ it('never previews a row whose first page is being prefetched', async () => {
+ const { fetchPreviews, scheduler } = setup();
+
+ scheduler.focus('t4');
+ scheduler.focus('t5');
+ await vi.advanceTimersByTimeAsync(NEIGHBOR_FLUSH_MS);
+
+ const previewed = fetchPreviews.mock.calls.flatMap(([ids]) => ids);
+ expect(previewed).not.toContain('t4');
+ expect(previewed).not.toContain('t5');
+ });
+
+ it('holds the next batch until the preview request in flight returns', async () => {
+ const { fetchPreviews, scheduler } = setup();
+ const first = deferred();
+ fetchPreviews.mockImplementationOnce(() => first.promise);
+
+ scheduler.focus('t2');
+ await vi.advanceTimersByTimeAsync(NEIGHBOR_FLUSH_MS);
+ scheduler.focus('t8');
+ await vi.advanceTimersByTimeAsync(NEIGHBOR_FLUSH_MS * 2);
+
+ expect(fetchPreviews).toHaveBeenCalledTimes(1);
+
+ first.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(fetchPreviews).toHaveBeenCalledTimes(2);
+ expect(fetchPreviews.mock.calls[1][0]).toEqual(['t6', 't7', 't9']);
+ });
+
+ it('skips rows the filters reject', async () => {
+ const prefetchFirstPage = vi.fn(() => Promise.resolve());
+ const fetchPreviews = vi.fn((_topicIds: string[]) => Promise.resolve());
+ const scheduler = createTopicHoverScheduler({
+ canPrefetch: (id) => id !== 't4',
+ canPreview: (id) => id !== 't3',
+ fetchPreviews,
+ getNeighbors: neighborsOf,
+ prefetchFirstPage,
+ });
+
+ scheduler.focus('t4');
+ await vi.advanceTimersByTimeAsync(NEIGHBOR_FLUSH_MS);
+
+ expect(prefetchFirstPage).not.toHaveBeenCalled();
+ expect(fetchPreviews).toHaveBeenCalledWith(['t2', 't5', 't6']);
+ });
+
+ it('fires one intent per pointer entry however long the pointer keeps moving', async () => {
+ const { fetchPreviews, prefetchFirstPage, scheduler } = setup();
+
+ for (let elapsed = 0; elapsed < 5000; elapsed += 16) {
+ scheduler.pointerMove('t4');
+ await vi.advanceTimersByTimeAsync(16);
+ }
+
+ expect(prefetchFirstPage).toHaveBeenCalledTimes(1);
+ expect(fetchPreviews).toHaveBeenCalledTimes(1);
+
+ scheduler.pointerLeave('t4');
+ scheduler.pointerMove('t4');
+ await vi.advanceTimersByTimeAsync(HOVER_DWELL_MS);
+
+ expect(prefetchFirstPage).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/scheduler.ts b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/scheduler.ts
new file mode 100644
index 00000000000..9f7dab99328
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/scheduler.ts
@@ -0,0 +1,124 @@
+export const HOVER_DWELL_MS = 120;
+// Content scrolling under a still pointer fires hover events the user never made.
+export const SCROLL_QUIET_MS = 200;
+export const NEIGHBOR_FLUSH_MS = 500;
+export const MAX_PREVIEW_BATCH = 4;
+
+interface TopicHoverSchedulerOptions {
+ canPrefetch: (topicId: string) => boolean;
+ canPreview: (topicId: string) => boolean;
+ fetchPreviews: (topicIds: string[]) => Promise<void>;
+ getNeighbors: (topicId: string) => string[];
+ prefetchFirstPage: (topicId: string) => Promise<void>;
+}
+
+export const createTopicHoverScheduler = ({
+ canPrefetch,
+ canPreview,
+ fetchPreviews,
+ getNeighbors,
+ prefetchFirstPage,
+}: TopicHoverSchedulerOptions) => {
+ let lastScrollAt = Number.NEGATIVE_INFINITY;
+ let dwell: { timer: ReturnType<typeof setTimeout>; topicId: string } | undefined;
+ // One intent per pointer entry: moving inside the same row must not repeat it.
+ let intentFiredFor: string | undefined;
+
+ let firstPageInFlight: string | undefined;
+ let firstPageQueued: string | undefined;
+
+ const collected = new Set<string>();
+ let latestNeighbors: string[] = [];
+ let flushTimer: ReturnType<typeof setTimeout> | undefined;
+ let previewInFlight = false;
+
+ const isFirstPageTarget = (topicId: string) =>
+ topicId === firstPageInFlight || topicId === firstPageQueued;
+
+ const runFirstPage = (topicId: string) => {
+ firstPageInFlight = topicId;
+ void prefetchFirstPage(topicId)
+ .catch(() => undefined)
+ .finally(() => {
+ firstPageInFlight = undefined;
+ const next = firstPageQueued;
+ firstPageQueued = undefined;
+ if (next && canPrefetch(next)) runFirstPage(next);
+ });
+ };
+
+ const requestFirstPage = (topicId: string) => {
+ if (isFirstPageTarget(topicId) || !canPrefetch(topicId)) return;
+ if (firstPageInFlight) firstPageQueued = topicId;
+ else runFirstPage(topicId);
+ };
+
+ const flush = () => {
+ flushTimer = undefined;
+ if (previewInFlight) return;
+
+ const candidates = [...collected].filter((id) => !isFirstPageTarget(id) && canPreview(id));
+ collected.clear();
+ const batch =
+ candidates.length > MAX_PREVIEW_BATCH
+ ? latestNeighbors.filter((id) => candidates.includes(id)).slice(0, MAX_PREVIEW_BATCH)
+ : candidates;
+ if (batch.length === 0) return;
+
+ previewInFlight = true;
+ void fetchPreviews(batch)
+ .catch(() => undefined)
+ .finally(() => {
+ previewInFlight = false;
+ if (collected.size > 0 && !flushTimer) flush();
+ });
+ };
+
+ const collectNeighbors = (topicId: string) => {
+ collected.delete(topicId);
+ const neighbors = getNeighbors(topicId).filter(
+ (id) => id !== topicId && !isFirstPageTarget(id) && canPreview(id),
+ );
+ latestNeighbors = neighbors;
+ for (const id of neighbors) collected.add(id);
+ if (collected.size > 0 && !flushTimer) flushTimer = setTimeout(flush, NEIGHBOR_FLUSH_MS);
+ };
+
+ const intent = (topicId: string) => {
+ requestFirstPage(topicId);
+ collectNeighbors(topicId);
+ };
+
+ const cancelDwell = () => {
+ if (!dwell) return;
+ clearTimeout(dwell.timer);
+ dwell = undefined;
+ };
+
+ return {
+ focus: intent,
+ pointerLeave: (topicId: string) => {
+ if (dwell?.topicId === topicId) cancelDwell();
+ if (intentFiredFor === topicId) intentFiredFor = undefined;
+ },
+ pointerMove: (topicId: string) => {
+ if (Date.now() - lastScrollAt < SCROLL_QUIET_MS) return;
+ if (dwell?.topicId === topicId || intentFiredFor === topicId) return;
+ cancelDwell();
+ dwell = {
+ timer: setTimeout(() => {
+ dwell = undefined;
+ intentFiredFor = topicId;
+ intent(topicId);
+ }, HOVER_DWELL_MS),
+ topicId,
+ };
+ },
+ scroll: () => {
+ lastScrollAt = Date.now();
+ cancelDwell();
+ },
+ };
+};
+
+export type TopicHoverScheduler = ReturnType<typeof createTopicHoverScheduler>;
diff --git a/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/useTopicHoverPrefetch.ts b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/useTopicHoverPrefetch.ts
new file mode 100644
index 00000000000..6e145ae0abf
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/topicHoverPrefetch/useTopicHoverPrefetch.ts
@@ -0,0 +1,143 @@
+import type { FocusEvent, PointerEvent } from 'react';
+import { useEffect, useMemo } from 'react';
+
+import { hasReadingPositionSnapshot } from '@/features/Conversation/ChatList/utils/scrollSnapshotStore';
+import { isProjectedConversationRead } from '@/helpers/conversationMessageRead';
+import { fetchTopicPreviews, hasRecentTopicPreviewAttempt } from '@/services/message/topicPreview';
+import { useChatStore } from '@/store/chat';
+import { operationSelectors } from '@/store/chat/selectors';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { getServerConfigStoreState } from '@/store/serverConfig';
+import { serverConfigSelectors } from '@/store/serverConfig/selectors';
+
+import {
+ canPrefetchTopicFirstPage,
+ canPreviewTopic,
+ type TopicHoverEnv,
+ type TopicHoverRow,
+} from './filters';
+import { createTopicHoverScheduler, type TopicHoverScheduler } from './scheduler';
+
+const NEIGHBOR_RADIUS = 2;
+const ROW_SELECTOR = '[data-testid="topic-item"][data-topic-id]';
+
+const rows = new Map<string, TopicHoverRow>();
+const rowElements = new Map<string, HTMLElement>();
+
+const rowKey = (row: TopicHoverRow) =>
+ messageMapKey({ agentId: row.agentId, topicId: row.topicId });
+
+const readEnv = (): TopicHoverEnv => {
+ const chat = useChatStore.getState();
+ const serverConfig = getServerConfigStoreState();
+ return {
+ activeTopicId: chat.activeTopicId,
+ creatingTopicIds: chat.creatingTopicIds,
+ enabled: !!serverConfig && serverConfigSelectors.enableTopicPreview(serverConfig),
+ hasLocalMessages: (row) => !!chat.dbMessagesMap[rowKey(row)],
+ hasPreview: hasRecentTopicPreviewAttempt,
+ hasReadingPosition: (row) => hasReadingPositionSnapshot(rowKey(row)),
+ isProjectedRead: isProjectedConversationRead,
+ isRunning: (row) =>
+ operationSelectors.isAgentRuntimeRunningByContext({
+ agentId: row.agentId,
+ topicId: row.topicId,
+ })(chat),
+ };
+};
+
+// Sidebar order is whatever the current grouping rendered, so read it from the DOM.
+const getNeighbors = (topicId: string) => {
+ const element = rowElements.get(topicId);
+ if (!element?.isConnected) return [];
+ const ordered = [...element.ownerDocument.querySelectorAll<HTMLElement>(ROW_SELECTOR)];
+ const index = ordered.indexOf(element);
+ if (index < 0) return [];
+ const agentId = rows.get(topicId)?.agentId;
+ return ordered
+ .slice(Math.max(0, index - NEIGHBOR_RADIUS), index + NEIGHBOR_RADIUS + 1)
+ .map((row) => row.dataset.topicId!)
+ .filter((id) => id !== topicId && rows.get(id)?.agentId === agentId);
+};
+
+const fetchPreviewBatch = async (topicIds: string[]) => {
+ const byAgent = new Map<string, string[]>();
+ for (const topicId of topicIds) {
+ const agentId = rows.get(topicId)?.agentId;
+ if (!agentId) continue;
+ byAgent.set(agentId, [...(byAgent.get(agentId) ?? []), topicId]);
+ }
+ for (const [agentId, ids] of byAgent) {
+ await fetchTopicPreviews({ agentId, topicIds: ids });
+ }
+};
+
+let scheduler: TopicHoverScheduler | undefined;
+
+const getScheduler = () => {
+ if (scheduler) return scheduler;
+ const created = createTopicHoverScheduler({
+ canPrefetch: (topicId) => {
+ const row = rows.get(topicId);
+ return !!row && canPrefetchTopicFirstPage(row, readEnv());
+ },
+ canPreview: (topicId) => {
+ const row = rows.get(topicId);
+ return !!row && canPreviewTopic(row, readEnv());
+ },
+ fetchPreviews: fetchPreviewBatch,
+ getNeighbors,
+ prefetchFirstPage: async (topicId) => {
+ const row = rows.get(topicId);
+ if (!row) return;
+ await useChatStore
+ .getState()
+ .prefetchMessages({ agentId: row.agentId, scope: 'main', topicId });
+ },
+ });
+ document.addEventListener(
+ 'scroll',
+ (event) => {
+ if (event.target instanceof Element && event.target.querySelector(ROW_SELECTOR)) {
+ created.scroll();
+ }
+ },
+ { capture: true, passive: true },
+ );
+ scheduler = created;
+ return created;
+};
+
+export const useTopicHoverPrefetch = (row: Partial<TopicHoverRow>) => {
+ const { agentId, groupId, status, topicId } = row;
+
+ useEffect(() => {
+ if (!agentId || !topicId) return;
+ const entry = { agentId, groupId, status, topicId };
+ rows.set(topicId, entry);
+ return () => {
+ if (rows.get(topicId) !== entry) return;
+ rows.delete(topicId);
+ rowElements.delete(topicId);
+ };
+ }, [agentId, groupId, status, topicId]);
+
+ return useMemo(() => {
+ if (!agentId || !topicId) return undefined;
+ const track = (element: HTMLElement) => rowElements.set(topicId, element);
+ return {
+ onFocus: (event: FocusEvent<HTMLElement>) => {
+ if (!(event.target instanceof HTMLElement) || !event.target.matches(':focus-visible'))
+ return;
+ track(event.currentTarget);
+ getScheduler().focus(topicId);
+ },
+ onPointerLeave: () => getScheduler().pointerLeave(topicId),
+ onPointerMove: (event: PointerEvent<HTMLElement>) => {
+ if (event.pointerType !== 'mouse') return;
+ track(event.currentTarget);
+ getScheduler().pointerMove(topicId);
+ },
+ };
+ }, [agentId, topicId]);
+};
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
index 37f91d6c469..af3588c8487 100644
--- a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
@@ -1,10 +1,9 @@
import { isGoalPrompt } from '@lobechat/builtin-tool-goal';
+import { deriveOperationGoals } from '@lobechat/builtin-tools/operationArtifacts';
import type { UIChatMessage } from '@lobechat/types';
import type { GoalListItem } from '@/services/goal';
-import { deriveOperationGoals } from '../../Messages/GoalTaskCard/deriveOperationGoals';
-
/** The tray is a pointer, not a list β€” past this the goal page's list is the right surface. */
export const MAX_LINKED_GOALS = 3;
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/PreviewQuestion.tsx b/src/features/Conversation/ChatList/components/PreviewTail/PreviewQuestion.tsx
new file mode 100644
index 00000000000..25ab3a1a5e1
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/PreviewQuestion.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import type { UIChatMessage } from '@lobechat/types';
+import { memo } from 'react';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useUserAvatar } from '@/hooks/useUserAvatar';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { ChatItem } from '../../../ChatItem';
+import UserMessageContent from '../../../Messages/User/components/MessageContent';
+
+const PreviewQuestion = memo<{ message: UIChatMessage }>(({ message }) => {
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const avatar = useUserAvatar();
+ const title = useUserStore(userProfileSelectors.displayUserName);
+ const showSender = Boolean(activeWorkspaceId);
+
+ return (
+ <ChatItem
+ actions={<div style={{ height: '28px' }} />}
+ avatar={{ avatar, title }}
+ message={message.content}
+ placement={'right'}
+ showAvatar={showSender}
+ showTitle={showSender}
+ time={message.createdAt}
+ >
+ <UserMessageContent {...message} />
+ </ChatItem>
+ );
+});
+
+PreviewQuestion.displayName = 'PreviewQuestion';
+
+export default PreviewQuestion;
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/index.tsx b/src/features/Conversation/ChatList/components/PreviewTail/index.tsx
new file mode 100644
index 00000000000..201fe77403b
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/index.tsx
@@ -0,0 +1,153 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import type { ReactNode } from 'react';
+import { memo, useLayoutEffect, useRef } from 'react';
+
+import { delayed } from '@/components/Skeleton/Delayed';
+import type { TopicPreview } from '@/services/message/topicPreview';
+
+import WideScreenContainer from '../../../../WideScreenContainer';
+import { ChatItem } from '../../../ChatItem';
+import SkeletonList from '../../../components/SkeletonList';
+import { useAgentMeta } from '../../../hooks';
+import MessageContent from '../../../Messages/Assistant/components/MessageContent';
+import { AssistantMessageExtra } from '../../../Messages/Assistant/Extra';
+import ContentBlock from '../../../Messages/AssistantGroup/components/ContentBlock';
+import ProcessFold from '../../../Messages/AssistantGroup/components/ProcessFold';
+import { formatReasoningDuration } from '../../../Messages/AssistantGroup/toolDisplayNames';
+import EditedFilesCard from '../../../Messages/EditedFilesCard';
+import GoalTaskCard from '../../../Messages/GoalTaskCard';
+import { MessageWorkList } from '../../../Messages/MessageWorks';
+import {
+ groupAnswerProps,
+ resolvePreviewLayout,
+ resolvePreviewProcess,
+ resolveWholeTopicLeading,
+} from './layout';
+import PreviewQuestion from './PreviewQuestion';
+
+interface PreviewTailProps {
+ headerSlot?: ReactNode;
+ overlayHeight: number;
+ preview: TopicPreview;
+}
+
+const PreviewAnswer = memo<{ preview: TopicPreview }>(({ preview }) => {
+ const { message } = preview;
+ const avatar = useAgentMeta(message.agentId);
+ const { cardsBelow, showModelLine, worksAfterActions } = resolvePreviewLayout(preview);
+ const process = resolvePreviewProcess(preview);
+
+ return (
+ <ChatItem
+ showTitle
+ actions={<div style={{ height: '28px' }} />}
+ afterActions={worksAfterActions && <MessageWorkList items={worksAfterActions} />}
+ avatar={avatar}
+ placement={'left'}
+ time={message.createdAt}
+ belowMessage={
+ cardsBelow && (
+ <Flexbox gap={8}>
+ {cardsBelow.editedFiles.length > 0 && (
+ <EditedFilesCard entries={cardsBelow.editedFiles} />
+ )}
+ {cardsBelow.goals.length > 0 && <GoalTaskCard goals={cardsBelow.goals} />}
+ {cardsBelow.works.length > 0 && <MessageWorkList items={cardsBelow.works} />}
+ </Flexbox>
+ )
+ }
+ messageExtra={
+ showModelLine ? (
+ <AssistantMessageExtra
+ content={message.content}
+ extra={message.extra}
+ id={message.id}
+ model={message.model ?? undefined}
+ performance={(message.performance || message.metadata) ?? undefined}
+ provider={message.provider ?? undefined}
+ tools={message.tools}
+ usage={(message.usage || message.metadata) ?? undefined}
+ />
+ ) : undefined
+ }
+ >
+ {preview.kind === 'group' ? (
+ <Flexbox gap={4}>
+ {process && (
+ <ProcessFold
+ stepCount={process.stepCount}
+ durationText={
+ process.durationMs >= 1000 ? formatReasoningDuration(process.durationMs) : undefined
+ }
+ >
+ {null}
+ </ProcessFold>
+ )}
+ <ContentBlock {...groupAnswerProps(message)} />
+ </Flexbox>
+ ) : (
+ <MessageContent {...message} />
+ )}
+ </ChatItem>
+ );
+});
+
+PreviewAnswer.displayName = 'PreviewAnswer';
+
+// Paints the final answer where the real list will put it, so the swap only adds rows above.
+const PreviewTail = memo<PreviewTailProps>(({ headerSlot, overlayHeight, preview }) => {
+ const paddingBottom = Math.max(24, overlayHeight + 12);
+ const leading = resolveWholeTopicLeading(preview);
+ const viewportRef = useRef<HTMLDivElement>(null);
+
+ // A whole topic flows from the top like the list; once it overflows, the list
+ // opens on its bottom, so the preview pins there too.
+ useLayoutEffect(() => {
+ const viewport = viewportRef.current;
+ if (!leading || !viewport) return;
+ const pin = () => {
+ viewport.scrollTop = viewport.scrollHeight;
+ };
+ pin();
+ const observer = new ResizeObserver(pin);
+ for (const child of viewport.children) observer.observe(child);
+ return () => observer.disconnect();
+ }, [leading]);
+
+ if (leading) {
+ return (
+ <div ref={viewportRef} style={{ height: '100%', minHeight: 0, overflow: 'hidden' }}>
+ {headerSlot && <WideScreenContainer>{headerSlot}</WideScreenContainer>}
+ {leading.map((message) => (
+ <WideScreenContainer key={message.id} style={{ position: 'relative' }}>
+ <PreviewQuestion message={message} />
+ </WideScreenContainer>
+ ))}
+ <WideScreenContainer style={{ position: 'relative' }}>
+ <PreviewAnswer preview={preview} />
+ </WideScreenContainer>
+ <div style={{ height: paddingBottom }} />
+ </div>
+ );
+ }
+
+ return (
+ <Flexbox
+ height={'100%'}
+ justify={'flex-end'}
+ style={{ minHeight: 0, overflow: 'hidden', paddingBottom }}
+ >
+ {headerSlot && <WideScreenContainer>{headerSlot}</WideScreenContainer>}
+ <Flexbox flex={'none'}>{delayed(<SkeletonList />)}</Flexbox>
+ <WideScreenContainer style={{ position: 'relative' }}>
+ <PreviewAnswer preview={preview} />
+ </WideScreenContainer>
+ </Flexbox>
+ );
+});
+
+PreviewTail.displayName = 'PreviewTail';
+
+export default PreviewTail;
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/layout.test.ts b/src/features/Conversation/ChatList/components/PreviewTail/layout.test.ts
new file mode 100644
index 00000000000..b557e2b89f0
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/layout.test.ts
@@ -0,0 +1,166 @@
+import { describe, expect, it } from 'vitest';
+
+import type { TopicPreview } from '@/services/message/topicPreview';
+
+import {
+ groupAnswerProps,
+ resolvePreviewLayout,
+ resolvePreviewProcess,
+ resolveWholeTopicLeading,
+} from './layout';
+
+const preview = (overrides: Partial<TopicPreview> = {}): TopicPreview =>
+ ({
+ editedFiles: [],
+ goals: [],
+ kind: 'group',
+ message: { content: 'the final answer', id: 'msg_final', role: 'assistant' },
+ status: 'ok',
+ topicId: 'tpc_a',
+ topicUpdatedAt: '2026-10-27T00:00:00.000Z',
+ workRootOperationId: null,
+ works: [],
+ blocks: [],
+ leading: null,
+ timeline: [],
+ ...overrides,
+ }) as TopicPreview;
+
+describe('groupAnswerProps', () => {
+ it('hands the answer text to the group block, which otherwise reads an empty store', () => {
+ const props = groupAnswerProps(preview().message);
+
+ expect(props.contentOverride).toBe('the final answer');
+ expect(props.hasToolsOverride).toBe(false);
+ expect(props.domId).toBe('msg_final__answer');
+ });
+});
+
+describe('resolvePreviewLayout', () => {
+ it('leaves the model line to the action row for a group answer', () => {
+ expect(resolvePreviewLayout(preview()).showModelLine).toBe(false);
+ });
+
+ it('shows the model line under a single reply', () => {
+ expect(resolvePreviewLayout(preview({ kind: 'single' })).showModelLine).toBe(true);
+ });
+
+ it("reserves the round's cards below a group answer", () => {
+ const layout = resolvePreviewLayout(
+ preview({
+ editedFiles: [{ path: '/a.ts' }] as TopicPreview['editedFiles'],
+ goals: [{ goalId: 'goal_1' }] as TopicPreview['goals'],
+ workRootOperationId: 'op_1',
+ works: [{ id: 'work_1' }] as TopicPreview['works'],
+ }),
+ );
+
+ expect(layout.cardsBelow).toEqual({
+ editedFiles: [{ path: '/a.ts' }],
+ goals: [{ goalId: 'goal_1' }],
+ works: [{ id: 'work_1' }],
+ });
+ expect(layout.worksAfterActions).toBeUndefined();
+ });
+
+ it('keeps works off a group answer whose round has no work root', () => {
+ const layout = resolvePreviewLayout(
+ preview({ works: [{ id: 'work_1' }] as TopicPreview['works'] }),
+ );
+
+ expect(layout.cardsBelow).toBeUndefined();
+ });
+
+ it('puts a single reply works after the action row', () => {
+ const layout = resolvePreviewLayout(
+ preview({
+ kind: 'single',
+ message: {
+ content: 'answer',
+ id: 'msg_final',
+ metadata: { work: { rootOperationId: 'op_1' } },
+ role: 'assistant',
+ } as TopicPreview['message'],
+ works: [{ id: 'work_1' }] as TopicPreview['works'],
+ }),
+ );
+
+ expect(layout.worksAfterActions).toEqual([{ id: 'work_1' }]);
+ expect(layout.cardsBelow).toBeUndefined();
+ });
+});
+
+describe('resolvePreviewProcess', () => {
+ const toolBlock = {
+ content: '',
+ id: 'msg_call',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'lobe-web-browsing',
+ result_msg_id: 'msg_result',
+ type: 'builtin',
+ },
+ ],
+ };
+ const answerBlock = { content: 'the final answer', id: 'msg_final' };
+ const timeline = [
+ {
+ createdAt: '2026-10-27T00:00:00.000Z',
+ id: 'msg_call',
+ updatedAt: '2026-10-27T00:00:00.000Z',
+ },
+ {
+ createdAt: '2026-10-27T00:00:01.000Z',
+ id: 'msg_result',
+ updatedAt: '2026-10-27T00:00:04.000Z',
+ },
+ {
+ createdAt: '2026-10-27T00:00:12.000Z',
+ id: 'msg_final',
+ updatedAt: '2026-10-27T00:00:12.000Z',
+ },
+ ];
+
+ it('folds a finished tool round the way the list header does', () => {
+ const process = resolvePreviewProcess(
+ preview({ blocks: [toolBlock, answerBlock] as TopicPreview['blocks'], timeline }),
+ );
+
+ expect(process).toEqual({ durationMs: 12_000, stepCount: 2 });
+ });
+
+ it('has no process header for a plain reply', () => {
+ expect(resolvePreviewProcess(preview({ kind: 'single' }))).toBeUndefined();
+ });
+
+ it('has no process header when the round made no tool calls', () => {
+ expect(
+ resolvePreviewProcess(preview({ blocks: [answerBlock] as TopicPreview['blocks'], timeline })),
+ ).toBeUndefined();
+ });
+});
+
+describe('resolveWholeTopicLeading', () => {
+ const question = { content: 'question', id: 'msg_q', role: 'user' };
+
+ it('draws the question when the round is the whole topic', () => {
+ const leading = [question] as TopicPreview['leading'];
+
+ expect(resolveWholeTopicLeading(preview({ leading }))).toBe(leading);
+ });
+
+ it('keeps the history skeleton when earlier rounds exist', () => {
+ expect(resolveWholeTopicLeading(preview({ leading: null }))).toBeUndefined();
+ });
+
+ it('keeps the history skeleton for a row it cannot draw like the list', () => {
+ const fromBot = { ...question, metadata: { botSender: { name: 'Bot' } } };
+
+ expect(
+ resolveWholeTopicLeading(preview({ leading: [fromBot] as TopicPreview['leading'] })),
+ ).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/layout.ts b/src/features/Conversation/ChatList/components/PreviewTail/layout.ts
new file mode 100644
index 00000000000..df42567d5c2
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/layout.ts
@@ -0,0 +1,103 @@
+import { splitAssistantGroupFinalAnswer } from '@lobechat/conversation-flow';
+
+import type { TopicPreview } from '@/services/message/topicPreview';
+
+import { getScmEventSource } from '../../../Markdown/plugins/ScmEvent/parseScmEvent';
+import {
+ buildChainView,
+ getChainDurationsMs,
+} from '../../../Messages/AssistantGroup/components/groupChain';
+import {
+ countAssistantLlmCalls,
+ hasRenderableFinalAnswer,
+ shouldFoldProcess,
+} from '../../../Messages/AssistantGroup/components/segments';
+import { getAgentSender, getBotSender } from '../../../Messages/User/resolveSenderIdentity';
+
+type PreviewMessage = TopicPreview['message'];
+
+// The group block reads its text from the conversation store unless overridden,
+// and the store holds no messages while the preview shows.
+export const groupAnswerProps = (message: PreviewMessage) => ({
+ assistantId: message.id,
+ content: message.content,
+ contentOverride: message.content,
+ disableEditing: true,
+ domId: `${message.id}__answer`,
+ error: message.error ?? undefined,
+ hasToolsOverride: false,
+ id: message.id,
+ imageList: message.imageList,
+ metadata: message.metadata ?? undefined,
+ reasoning: message.reasoning ?? undefined,
+ tools: message.tools,
+});
+
+export const resolvePreviewLayout = ({
+ editedFiles,
+ goals,
+ kind,
+ message,
+ workRootOperationId,
+ works,
+}: TopicPreview) => {
+ const roundWorks = workRootOperationId ? works : [];
+ const hasCards = editedFiles.length > 0 || goals.length > 0 || roundWorks.length > 0;
+
+ return {
+ cardsBelow:
+ kind === 'group' && hasCards ? { editedFiles, goals, works: roundWorks } : undefined,
+ showModelLine: kind === 'single',
+ worksAfterActions:
+ kind === 'single' && message.metadata?.work?.rootOperationId && works.length > 0
+ ? works
+ : undefined,
+ };
+};
+
+// Mirrors the group's own fold decision, so the header the list draws above the
+// answer is already there and the swap does not push the avatar row.
+export const resolvePreviewProcess = ({ blocks, kind, message, timeline }: TopicPreview) => {
+ if (kind !== 'group' || blocks.length === 0) return undefined;
+
+ const finishTypes = new Map(
+ timeline.flatMap((row) => (row.finishType ? [[row.id, row.finishType] as const] : [])),
+ );
+ const chain = {
+ blocks: blocks.map((block) => {
+ const finishType = finishTypes.get(block.id);
+ if (block.metadata?.finishType != null || !finishType) return block;
+ return { ...block, metadata: { ...block.metadata, finishType } };
+ }),
+ id: message.id,
+ };
+ const view = buildChainView(chain, { hasActiveOperation: false, isGenerating: false });
+ const { finalSegments, processSegments } = splitAssistantGroupFinalAnswer(view.segments);
+ const folds = shouldFoldProcess({
+ enabled: true,
+ hasFinalAnswer: hasRenderableFinalAnswer(finalSegments),
+ isGenerating: false,
+ isLatestItem: true,
+ operationEnded: true,
+ processSegments,
+ });
+ if (!folds) return undefined;
+
+ return {
+ durationMs: getChainDurationsMs(timeline, [chain])[0] ?? 0,
+ stepCount: countAssistantLlmCalls(view.segments),
+ };
+};
+
+// PreviewQuestion draws the viewer's own plain question; any other sender keeps
+// the bottom-anchored preview, where the skeleton covers the rows above.
+const isPlainQuestion = (message: PreviewMessage) =>
+ message.role === 'user' &&
+ !getBotSender(message) &&
+ !getAgentSender(message) &&
+ !message.metadata?.subAgentCallback &&
+ !message.metadata?.steer &&
+ !getScmEventSource(message.content);
+
+export const resolveWholeTopicLeading = ({ leading }: TopicPreview) =>
+ leading && leading.every(isPlainQuestion) ? leading : undefined;
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/resolveTopicPreview.test.ts b/src/features/Conversation/ChatList/components/PreviewTail/resolveTopicPreview.test.ts
new file mode 100644
index 00000000000..d4ddb3ae2fd
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/resolveTopicPreview.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getValidTopicPreview } from '@/services/message/topicPreview';
+
+import { hasReadingPositionSnapshot } from '../../utils/scrollSnapshotStore';
+import { resolveTopicPreview } from './resolveTopicPreview';
+
+vi.mock('@/services/message/topicPreview', () => ({ getValidTopicPreview: vi.fn() }));
+vi.mock('../../utils/scrollSnapshotStore', () => ({ hasReadingPositionSnapshot: vi.fn() }));
+
+const cached = { message: { id: 'msg_final' } };
+
+describe('resolveTopicPreview', () => {
+ it('returns the cached preview for an unchanged, idle topic', () => {
+ vi.mocked(getValidTopicPreview).mockReturnValueOnce(cached as any);
+ vi.mocked(hasReadingPositionSnapshot).mockReturnValueOnce(false);
+
+ expect(
+ resolveTopicPreview({
+ contextKey: 'main_agt_1_tpc_a',
+ running: false,
+ topicId: 'tpc_a',
+ topicUpdatedAt: '2026-10-27T00:00:00.000Z',
+ }),
+ ).toBe(cached);
+ expect(getValidTopicPreview).toHaveBeenCalledWith('tpc_a', {
+ running: false,
+ topicUpdatedAt: '2026-10-27T00:00:00.000Z',
+ });
+ });
+
+ it('opens without a preview when the reader left a reading position', () => {
+ vi.mocked(getValidTopicPreview).mockReturnValueOnce(cached as any);
+ vi.mocked(hasReadingPositionSnapshot).mockReturnValueOnce(true);
+
+ expect(
+ resolveTopicPreview({ contextKey: 'k', running: false, topicId: 'tpc_a', topicUpdatedAt: 1 }),
+ ).toBeUndefined();
+ });
+
+ it('has no preview for a new conversation', () => {
+ expect(resolveTopicPreview({ contextKey: 'k', running: false, topicId: null })).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/resolveTopicPreview.ts b/src/features/Conversation/ChatList/components/PreviewTail/resolveTopicPreview.ts
new file mode 100644
index 00000000000..37ffdab6c9d
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/resolveTopicPreview.ts
@@ -0,0 +1,21 @@
+import { getValidTopicPreview, type TopicPreview } from '@/services/message/topicPreview';
+
+import { hasReadingPositionSnapshot } from '../../utils/scrollSnapshotStore';
+
+export const resolveTopicPreview = ({
+ contextKey,
+ running,
+ topicId,
+ topicUpdatedAt,
+}: {
+ contextKey: string;
+ running: boolean;
+ topicId?: string | null;
+ topicUpdatedAt?: Date | string | number | null;
+}): TopicPreview | undefined => {
+ if (!topicId) return undefined;
+ const preview = getValidTopicPreview(topicId, { running, topicUpdatedAt });
+ // The preview only paints the bottom of the list; a saved reading position opens elsewhere.
+ if (!preview || hasReadingPositionSnapshot(contextKey)) return undefined;
+ return preview;
+};
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/usePreviewHandoff.test.ts b/src/features/Conversation/ChatList/components/PreviewTail/usePreviewHandoff.test.ts
new file mode 100644
index 00000000000..373118208ef
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/usePreviewHandoff.test.ts
@@ -0,0 +1,62 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { TopicPreview } from '@/services/message/topicPreview';
+
+import { usePreviewHandoff } from './usePreviewHandoff';
+import { waitForAnswerInView } from './waitForAnswerInView';
+
+vi.mock('./waitForAnswerInView', () => ({ waitForAnswerInView: vi.fn(() => vi.fn()) }));
+
+const wait = vi.mocked(waitForAnswerInView);
+
+const preview = { message: { id: 'msg_final' }, topicId: 'tpc_a' } as TopicPreview;
+
+interface Props {
+ contextKey: string;
+ listMounted: boolean;
+ preview?: TopicPreview;
+}
+
+const setup = (initial: Props) => {
+ const listRef = { current: document.createElement('div') };
+ return renderHook((props: Props) => usePreviewHandoff({ ...props, listRef }), {
+ initialProps: initial,
+ });
+};
+
+describe('usePreviewHandoff', () => {
+ beforeEach(() => {
+ wait.mockClear();
+ });
+
+ it('keeps the preview over the list until the list shows the final answer', () => {
+ const { rerender, result } = setup({ contextKey: 'a', listMounted: false, preview });
+ rerender({ contextKey: 'a', listMounted: true, preview: undefined });
+
+ expect(result.current).toBe(preview);
+ expect(wait).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'msg_final' }));
+
+ act(() => wait.mock.calls[0][0].onReady());
+
+ expect(result.current).toBeUndefined();
+ });
+
+ it('does not cover a list the preview was never shown for', () => {
+ const { result } = setup({ contextKey: 'a', listMounted: true, preview: undefined });
+
+ expect(result.current).toBeUndefined();
+ expect(wait).not.toHaveBeenCalled();
+ });
+
+ it('drops a held preview once the user moves to another topic', () => {
+ const { rerender, result } = setup({ contextKey: 'a', listMounted: false, preview });
+ rerender({ contextKey: 'b', listMounted: true, preview: undefined });
+
+ expect(result.current).toBeUndefined();
+
+ rerender({ contextKey: 'a', listMounted: true, preview: undefined });
+
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/usePreviewHandoff.ts b/src/features/Conversation/ChatList/components/PreviewTail/usePreviewHandoff.ts
new file mode 100644
index 00000000000..cb1ef60a7e0
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/usePreviewHandoff.ts
@@ -0,0 +1,40 @@
+import type { RefObject } from 'react';
+import { useEffect, useState } from 'react';
+
+import type { TopicPreview } from '@/services/message/topicPreview';
+
+import { waitForAnswerInView } from './waitForAnswerInView';
+
+interface UsePreviewHandoffOptions {
+ contextKey: string;
+ listMounted: boolean;
+ listRef: RefObject<HTMLElement | null>;
+ preview?: TopicPreview;
+}
+
+// The list mounts at the top and lands on its bottom a few frames later, so the
+// preview stays over it until the real final answer is where the preview drew it.
+export const usePreviewHandoff = ({
+ contextKey,
+ listMounted,
+ listRef,
+ preview,
+}: UsePreviewHandoffOptions) => {
+ const [held, setHeld] = useState<{ contextKey: string; preview: TopicPreview }>();
+ if (preview && (held?.preview !== preview || held.contextKey !== contextKey)) {
+ setHeld({ contextKey, preview });
+ } else if (!preview && held && held.contextKey !== contextKey) {
+ setHeld(undefined);
+ }
+
+ const active = listMounted && held?.contextKey === contextKey ? held.preview : undefined;
+ const messageId = active?.message.id;
+
+ useEffect(() => {
+ const container = listRef.current;
+ if (!messageId || !container) return;
+ return waitForAnswerInView({ container, messageId, onReady: () => setHeld(undefined) });
+ }, [listRef, messageId]);
+
+ return active;
+};
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/waitForAnswerInView.test.ts b/src/features/Conversation/ChatList/components/PreviewTail/waitForAnswerInView.test.ts
new file mode 100644
index 00000000000..ceab1b1afc4
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/waitForAnswerInView.test.ts
@@ -0,0 +1,124 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { HANDOFF_MAX_MS, waitForAnswerInView } from './waitForAnswerInView';
+
+const FRAME_MS = 16;
+
+const rect = (top: number, bottom: number) => ({ bottom, top }) as DOMRect;
+
+const setup = () => {
+ const container = document.createElement('div');
+ document.body.append(container);
+ container.getBoundingClientRect = () => rect(0, 600);
+ const renderAnswer = (bottom: number, id = 'msg_final__answer') => {
+ const answer = document.createElement('div');
+ answer.id = id;
+ let current = bottom;
+ answer.getBoundingClientRect = () => rect(current - 80, current);
+ container.append(answer);
+ return { moveTo: (next: number) => (current = next) };
+ };
+ return { container, renderAnswer };
+};
+
+describe('waitForAnswerInView', () => {
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'requestAnimationFrame', 'cancelAnimationFrame'],
+ });
+ document.body.innerHTML = '';
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('waits while the list has not rendered the final answer yet', () => {
+ const { container } = setup();
+ const onReady = vi.fn();
+
+ waitForAnswerInView({ container, messageId: 'msg_final', onReady });
+ vi.advanceTimersByTime(FRAME_MS * 10);
+
+ expect(onReady).not.toHaveBeenCalled();
+ });
+
+ it('waits while the final answer sits below the visible part of the list', () => {
+ const { container, renderAnswer } = setup();
+ renderAnswer(1400);
+ const onReady = vi.fn();
+
+ waitForAnswerInView({ container, messageId: 'msg_final', onReady });
+ vi.advanceTimersByTime(FRAME_MS * 10);
+
+ expect(onReady).not.toHaveBeenCalled();
+ });
+
+ it('hands off once the final answer is in view and holds still', () => {
+ const { container, renderAnswer } = setup();
+ const answer = renderAnswer(1400);
+ const onReady = vi.fn();
+
+ waitForAnswerInView({ container, messageId: 'msg_final', onReady });
+ vi.advanceTimersByTime(FRAME_MS * 3);
+ answer.moveTo(520);
+ vi.advanceTimersByTime(FRAME_MS);
+ answer.moveTo(560);
+ vi.advanceTimersByTime(FRAME_MS);
+
+ expect(onReady).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(FRAME_MS * 3);
+
+ expect(onReady).toHaveBeenCalledTimes(1);
+ });
+
+ it('finds a single message rendered under its own id', () => {
+ const { container, renderAnswer } = setup();
+ renderAnswer(560, 'msg_final');
+ const onReady = vi.fn();
+
+ waitForAnswerInView({ container, messageId: 'msg_final', onReady });
+ vi.advanceTimersByTime(FRAME_MS * 4);
+
+ expect(onReady).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores a copy of the answer outside the list', () => {
+ const { container } = setup();
+ const outside = document.createElement('div');
+ outside.id = 'msg_final__answer';
+ outside.getBoundingClientRect = () => rect(480, 560);
+ document.body.prepend(outside);
+ const onReady = vi.fn();
+
+ waitForAnswerInView({ container, messageId: 'msg_final', onReady });
+ vi.advanceTimersByTime(FRAME_MS * 10);
+
+ expect(onReady).not.toHaveBeenCalled();
+ });
+
+ it('hands off after the time cap even if the answer never shows', () => {
+ const { container } = setup();
+ const onReady = vi.fn();
+
+ waitForAnswerInView({ container, messageId: 'msg_final', onReady });
+ vi.advanceTimersByTime(HANDOFF_MAX_MS);
+
+ expect(onReady).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(HANDOFF_MAX_MS);
+ expect(onReady).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops waiting once cancelled', () => {
+ const { container, renderAnswer } = setup();
+ renderAnswer(560);
+ const onReady = vi.fn();
+
+ const cancel = waitForAnswerInView({ container, messageId: 'msg_final', onReady });
+ cancel();
+ vi.advanceTimersByTime(HANDOFF_MAX_MS * 2);
+
+ expect(onReady).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/ChatList/components/PreviewTail/waitForAnswerInView.ts b/src/features/Conversation/ChatList/components/PreviewTail/waitForAnswerInView.ts
new file mode 100644
index 00000000000..2be676461f6
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/PreviewTail/waitForAnswerInView.ts
@@ -0,0 +1,54 @@
+export const HANDOFF_MAX_MS = 1000;
+const STEADY_FRAMES = 2;
+
+interface WaitForAnswerInViewOptions {
+ container: HTMLElement;
+ maxMs?: number;
+ messageId: string;
+ onReady: () => void;
+}
+
+const findAnswer = (container: HTMLElement, messageId: string) =>
+ container.querySelector<HTMLElement>(`[id="${messageId}__answer"]`) ??
+ container.querySelector<HTMLElement>(`[id="${messageId}"]`);
+
+export const waitForAnswerInView = ({
+ container,
+ maxMs = HANDOFF_MAX_MS,
+ messageId,
+ onReady,
+}: WaitForAnswerInViewOptions) => {
+ let frame = 0;
+ let lastBottom: number | undefined;
+ let steady = 0;
+ let done = false;
+
+ const finish = () => {
+ if (done) return;
+ done = true;
+ cancelAnimationFrame(frame);
+ clearTimeout(timer);
+ onReady();
+ };
+ const timer = setTimeout(finish, maxMs);
+
+ const check = () => {
+ const answer = findAnswer(container, messageId);
+ const view = container.getBoundingClientRect();
+ const bottom = answer?.getBoundingClientRect().bottom;
+ const inView = bottom !== undefined && bottom > view.top && bottom <= view.bottom + 1;
+
+ steady =
+ inView && lastBottom !== undefined && Math.abs(bottom - lastBottom) < 1 ? steady + 1 : 0;
+ lastBottom = inView ? bottom : undefined;
+ if (steady >= STEADY_FRAMES) return finish();
+ frame = requestAnimationFrame(check);
+ };
+ frame = requestAnimationFrame(check);
+
+ return () => {
+ done = true;
+ cancelAnimationFrame(frame);
+ clearTimeout(timer);
+ };
+};
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index b2ef309c2bf..eff91f110fb 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -117,7 +117,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
const { recordScroll } = useTopicScrollPersist({
contextKey,
containerRef,
- dataSourceLength: dataSource.length,
+ dataSource,
getScroller,
headerOffset: LEADING_ROWS,
initialPosition: isForward ? 'top' : initialScrollPosition,
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
index 8dfbc7788ac..4d178616114 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
@@ -225,7 +225,7 @@ describe('useConversationScroll β€” pin behavior', () => {
it('scrolls to the user message when a user+assistant pair is appended', () => {
const { rerender } = renderScrollHook({
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
isSecondLastMessageFromUser: false,
});
@@ -240,7 +240,7 @@ describe('useConversationScroll β€” pin behavior', () => {
it('translates the pin target by headerOffset when a header slot row is present', () => {
const { rerender } = renderScrollHook({
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
headerOffset: 1,
isSecondLastMessageFromUser: false,
});
@@ -257,7 +257,7 @@ describe('useConversationScroll β€” pin behavior', () => {
it('does not scroll when a forward read appends its next page as a user+assistant pair', () => {
const { rerender } = renderScrollHook({
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
fixture: { hasLaterMessages: true },
isSecondLastMessageFromUser: false,
});
@@ -272,6 +272,20 @@ describe('useConversationScroll β€” pin behavior', () => {
expect(scrollToIndex).not.toHaveBeenCalled();
});
+ it('does not scroll when an older round is prepended in front of the loaded rows', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: [userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+
+ rerender({
+ dataSource: ['older-user', 'older-assistant', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
it('does not scroll when only the assistant message is appended', () => {
const { rerender } = renderScrollHook({
dataSource: [userId, assistantId],
@@ -320,7 +334,7 @@ describe('useConversationScroll β€” pin behavior', () => {
it('does not treat a topic switch as a send even when the length delta is +2', () => {
const { rerender } = renderScrollHook({
contextKey: 'main_agt_1_tpc_a',
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
isSecondLastMessageFromUser: false,
});
@@ -336,7 +350,7 @@ describe('useConversationScroll β€” pin behavior', () => {
it('deactivates a live spacer when the context switches', async () => {
const { result, rerender } = renderScrollHook({
contextKey: 'main_agt_1_tpc_a',
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
isSecondLastMessageFromUser: false,
fixture: {
virtuaScrollMethods: {
@@ -389,7 +403,7 @@ describe('useConversationScroll β€” pin behavior', () => {
it('stops pinning once the user scrolls up', () => {
const { result, rerender } = renderScrollHook({
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
isSecondLastMessageFromUser: false,
});
@@ -425,7 +439,7 @@ describe('useConversationScroll β€” pin behavior', () => {
// An instant re-pin there aborts the animation (the "no slide" bug).
it('keeps settle re-pins smooth right after send', () => {
const { result, rerender } = renderScrollHook({
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
isSecondLastMessageFromUser: false,
});
@@ -450,7 +464,7 @@ describe('useConversationScroll β€” pin behavior', () => {
// itself a visible slide, so late re-pins must land instantly.
it('re-pins without smooth scrolling once the send animation window has passed', () => {
const { result, rerender } = renderScrollHook({
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
isSecondLastMessageFromUser: false,
});
@@ -530,7 +544,7 @@ describe('useConversationScroll β€” pin behavior', () => {
try {
const { rerender } = renderScrollHook({
- dataSource: [assistantId, 'prev'],
+ dataSource: ['m0', 'm1'],
isSecondLastMessageFromUser: false,
});
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
index d5d5e79cc18..d057573b7da 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
@@ -484,7 +484,9 @@ export const useConversationScroll = ({
// render rather than waiting for an unrelated dep to change.
const [userMessageIndex, setUserMessageIndex] = useState<number | null>(null);
const [assistantMessageIndex, setAssistantMessageIndex] = useState<number | null>(null);
+ const lastId = dataSource.at(-1);
const prevLengthRef = useRef(dataSource.length);
+ const prevLastIdRef = useRef<string | undefined>(lastId);
// Whether later rounds were still unread as of the previous dataSource. A
// send can only append at the end of the conversation, so a pair appended
// while later rounds were unread is a forward read's next page.
@@ -541,6 +543,7 @@ export const useConversationScroll = ({
prevContextKeyRef.current = contextKey;
prevLengthRef.current = dataSource.length;
+ prevLastIdRef.current = dataSource.at(-1);
hadLaterMessagesRef.current = hasLaterMessages;
clearPin('context switch');
setUserMessageIndex(null);
@@ -554,10 +557,20 @@ export const useConversationScroll = ({
useEffect(() => {
const newMessageCount = dataSource.length - prevLengthRef.current;
prevLengthRef.current = dataSource.length;
+ // An older page that happens to be one round long also grows the list by
+ // two; only a pair placed after the previous last row is a send.
+ const appendedAtEnd = dataSource.at(-3) === prevLastIdRef.current;
+ prevLastIdRef.current = dataSource.at(-1);
const appendedLaterPage = hadLaterMessagesRef.current;
hadLaterMessagesRef.current = hasLaterMessages;
- if (newMessageCount !== 2 || !isSecondLastMessageFromUser || appendedLaterPage) return;
+ if (
+ newMessageCount !== 2 ||
+ !appendedAtEnd ||
+ !isSecondLastMessageFromUser ||
+ appendedLaterPage
+ )
+ return;
const userMessage = displayMessages.at(-2);
const assistantMessage = displayMessages.at(-1);
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.initialPosition.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.initialPosition.test.ts
index b8b3f3a40df..965b74393e7 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.initialPosition.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.initialPosition.test.ts
@@ -20,6 +20,8 @@ const createHandle = (scrollSize: number) => {
},
} as unknown as HTMLElement;
const handle = {
+ findItemIndex: (offset: number) => Math.floor(offset / 200),
+ getItemOffset: (index: number) => index * 200,
scrollOffset: 0,
scrollSize,
scrollTo: vi.fn(),
@@ -54,7 +56,7 @@ describe('useTopicScrollPersist initialPosition', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_share',
- dataSourceLength: 50,
+ dataSource: Array.from({ length: 50 }, (_, index) => `m${index}`),
getScroller: () => scroller,
initialPosition: 'top',
virtuaRef: ref,
@@ -77,7 +79,7 @@ describe('useTopicScrollPersist initialPosition', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_share',
- dataSourceLength: 50,
+ dataSource: Array.from({ length: 50 }, (_, index) => `m${index}`),
getScroller: () => scroller,
initialPosition: 'top',
virtuaRef: ref,
@@ -94,7 +96,7 @@ describe('useTopicScrollPersist initialPosition', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_share',
- dataSourceLength: 50,
+ dataSource: Array.from({ length: 50 }, (_, index) => `m${index}`),
getScroller: () => scroller,
initialPosition: 'top',
messageDeepLink: {
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
index 0af75526c11..cc2d807476e 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
@@ -9,6 +9,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { loadScrollSnapshot, saveScrollSnapshot } from '../utils/scrollSnapshotStore';
import { useTopicScrollPersist } from './useTopicScrollPersist';
+const ROW_HEIGHT = 200;
+const rowsOf = (length: number) => Array.from({ length }, (_, index) => `m${index}`);
+const ROWS = rowsOf(50);
+
+const anchoredAt = (offset: number) => {
+ const index = Math.min(ROWS.length - 1, Math.floor(offset / ROW_HEIGHT));
+ return { anchorId: ROWS[index], anchorOffset: offset - index * ROW_HEIGHT };
+};
+
interface FakeScroller extends HTMLElement {
/** Fires the listeners the hook registered for `type` */
emit: (type: string) => void;
@@ -17,6 +26,8 @@ interface FakeScroller extends HTMLElement {
}
interface FakeVList {
+ findItemIndex: (offset: number) => number;
+ getItemOffset: (index: number) => number;
scroller: FakeScroller;
scrollOffset: number;
scrollSize: number;
@@ -55,6 +66,8 @@ const createFakeScroller = (handle: FakeVList): FakeScroller => {
const createFakeVList = (overrides: Partial<Omit<FakeVList, 'scroller'>> = {}): FakeVList => {
const handle = {
+ findItemIndex: (offset: number) => Math.max(0, Math.floor(offset / ROW_HEIGHT)),
+ getItemOffset: (index: number) => index * ROW_HEIGHT,
scrollOffset: 0,
scrollSize: 0,
scrollTo: vi.fn(),
@@ -92,6 +105,7 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 6000 });
@@ -100,7 +114,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
headerOffset: 1,
messageDeepLink: {
@@ -137,7 +151,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
containerRef: { current: container },
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: 'assistant-group',
@@ -175,7 +189,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
containerRef: { current: container },
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: 'assistant-group',
@@ -217,7 +231,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
containerRef: { current: container },
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: 'assistant-group',
@@ -245,6 +259,7 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
@@ -252,7 +267,7 @@ describe('useTopicScrollPersist', () => {
({ navigationKey }: { navigationKey?: string }) =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
messageDeepLink: navigationKey
? {
@@ -283,7 +298,7 @@ describe('useTopicScrollPersist', () => {
({ index, navigationKey }: { index: number; navigationKey: string }) =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: `message-${index}`,
@@ -312,7 +327,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -330,7 +345,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -355,7 +370,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -376,7 +391,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -399,7 +414,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -423,7 +438,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -439,13 +454,14 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -461,13 +477,14 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -491,29 +508,30 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 999_999,
+ ...anchoredAt(999_999),
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
- // 30-frame cap + a few extra for the release rAFs.
- await advanceFrames(40);
+ // 30-frame cap + a few extra for the release rAFs, then the anchor row reveal.
+ await advanceFrames(80);
- expect(handle.scroller.setScrollTop).toHaveBeenCalledTimes(1);
- expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(999_999);
+ expect(handle.scroller.setScrollTop).toHaveBeenLastCalledWith(999_999);
});
it('converges the snapshot to the actual landing position after capping out', async () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 999_999,
+ ...anchoredAt(999_999),
savedAt: Date.now() - 60_000,
});
const handle = createFakeVList({ scrollSize: 1500, viewportSize: 800 });
@@ -525,7 +543,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -545,6 +563,7 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: originalSavedAt,
});
const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
@@ -555,7 +574,7 @@ describe('useTopicScrollPersist', () => {
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -569,10 +588,11 @@ describe('useTopicScrollPersist', () => {
expect(persisted?.savedAt).toBe(originalSavedAt);
});
- it('skips the entire restore until dataSourceLength becomes non-zero', async () => {
+ it('skips the entire restore until the data source has rows', async () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 6000 });
@@ -580,7 +600,7 @@ describe('useTopicScrollPersist', () => {
({ length }: { length: number }) =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: length,
+ dataSource: rowsOf(length),
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -600,14 +620,19 @@ describe('useTopicScrollPersist', () => {
describe('recordScroll suppression during restore', () => {
it('drops recordScroll calls fired before the restore lands', async () => {
- const startingSnapshot = { atBottom: false, offset: 5000, savedAt: Date.now() };
+ const startingSnapshot = {
+ atBottom: false,
+ offset: 5000,
+ ...anchoredAt(5000),
+ savedAt: Date.now(),
+ };
saveScrollSnapshot('main_agt_1_tpc_a', startingSnapshot);
const handle = createFakeVList({ scrollSize: 6000 });
const { result } = renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -631,6 +656,7 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: Date.now(),
});
const handle = createFakeVList({ scrollSize: 6000 });
@@ -638,7 +664,7 @@ describe('useTopicScrollPersist', () => {
const { result } = renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -663,6 +689,7 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_b', {
atBottom: false,
offset: 3000,
+ ...anchoredAt(3000),
savedAt: fixedNow,
});
const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
@@ -674,7 +701,7 @@ describe('useTopicScrollPersist', () => {
({ contextKey, length }: { contextKey: string; length: number }) =>
useTopicScrollPersist({
contextKey,
- dataSourceLength: length,
+ dataSource: rowsOf(length),
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -705,7 +732,7 @@ describe('useTopicScrollPersist', () => {
({ contextKey, length }: { contextKey: string; length: number }) =>
useTopicScrollPersist({
contextKey,
- dataSourceLength: length,
+ dataSource: rowsOf(length),
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -732,7 +759,7 @@ describe('useTopicScrollPersist', () => {
const { result, unmount } = renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -765,6 +792,7 @@ describe('useTopicScrollPersist', () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
+ ...anchoredAt(5000),
savedAt: fixedNow,
});
const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
@@ -775,7 +803,7 @@ describe('useTopicScrollPersist', () => {
const { unmount } = renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -800,7 +828,7 @@ describe('useTopicScrollPersist', () => {
const { unmount } = renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_empty',
- dataSourceLength: 50,
+ dataSource: ROWS,
getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
@@ -814,4 +842,241 @@ describe('useTopicScrollPersist', () => {
expect(persisted?.atBottom ?? true).toBe(true);
});
});
+
+ describe('message anchor', () => {
+ it('restores to the anchor row plus its offset', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ anchorId: 'm30',
+ anchorOffset: 40,
+ atBottom: false,
+ offset: 100,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 10_000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(30 * ROW_HEIGHT + 40);
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalledWith(100);
+ });
+
+ it('renders a tall anchor row before aiming deep inside it', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ anchorId: 'm30',
+ anchorOffset: 1500,
+ atBottom: false,
+ offset: 7500,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 20_000 });
+ handle.scroller.getBoundingClientRect = () => ({ top: 0 }) as DOMRect;
+ // Virtua under-estimates the unmeasured rows above; the rendered row sits 900px lower.
+ const renderedRow = {
+ getBoundingClientRect: () => ({ top: 30 * ROW_HEIGHT + 900 - handle.scrollOffset }),
+ };
+ let anchorRendered = false;
+ const container = {
+ querySelector: (selector: string) =>
+ anchorRendered && selector === '[data-index="30"]' ? renderedRow : null,
+ } as unknown as HTMLDivElement;
+ renderHook(() =>
+ useTopicScrollPersist({
+ containerRef: { current: container },
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(30 * ROW_HEIGHT);
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalledWith(30 * ROW_HEIGHT + 1500);
+
+ anchorRendered = true;
+ await advanceFrames(4);
+ expect(handle.scroller.setScrollTop).toHaveBeenLastCalledWith(30 * ROW_HEIGHT + 900 + 1500);
+ });
+
+ it('still reaches a tall anchor when its row never shows up', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ anchorId: 'm30',
+ anchorOffset: 1500,
+ atBottom: false,
+ offset: 7500,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 20_000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(40);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenLastCalledWith(30 * ROW_HEIGHT + 1500);
+ });
+
+ it('re-aims at the anchor while rows above it are measured', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ anchorId: 'm30',
+ anchorOffset: 40,
+ atBottom: false,
+ offset: 100,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 20_000 });
+ let measuredRows = 0;
+ handle.getItemOffset = (index: number) => index * ROW_HEIGHT + Math.min(measuredRows, 3) * 50;
+ handle.scroller.setScrollTop.mockImplementation(() => {
+ measuredRows += 1;
+ });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(30);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenLastCalledWith(30 * ROW_HEIGHT + 150 + 40);
+ });
+
+ it('stops re-aiming once the user scrolls', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ anchorId: 'm30',
+ anchorOffset: 40,
+ atBottom: false,
+ offset: 100,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 20_000 });
+ let shift = 0;
+ handle.getItemOffset = (index: number) => index * ROW_HEIGHT + shift;
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(2);
+ handle.scroller.emit('wheel');
+ const writes = handle.scroller.setScrollTop.mock.calls.length;
+ shift = 500;
+ await advanceFrames(10);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledTimes(writes);
+ });
+
+ it('counts header rows when locating the anchor', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ anchorId: 'm30',
+ anchorOffset: 40,
+ atBottom: false,
+ offset: 100,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 10_000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ headerOffset: 1,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(31 * ROW_HEIGHT + 40);
+ });
+
+ it('opens at the bottom when the anchor row is not loaded', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ anchorId: 'msg_trimmed',
+ anchorOffset: 40,
+ atBottom: false,
+ offset: 2000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 6000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(6000);
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalledWith(2000);
+ });
+
+ it('opens at the bottom for a snapshot saved without an anchor', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 2000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 6000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(6000);
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalledWith(2000);
+ });
+
+ it('records the message at the top of the viewport as the anchor', async () => {
+ const handle = createFakeVList({ scrollSize: 6000 });
+ const { result } = renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSource: ROWS,
+ getScroller: () => handle.scroller,
+ headerOffset: 1,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(10);
+ act(() => {
+ result.current.recordScroll(21 * ROW_HEIGHT + 50, false);
+ });
+ await vi.advanceTimersByTimeAsync(300);
+
+ const persisted = loadScrollSnapshot('main_agt_1_tpc_a');
+ expect(persisted?.anchorId).toBe('m20');
+ expect(persisted?.anchorOffset).toBe(50);
+ });
+ });
});
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
index 810c62d8143..5439d250c35 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
@@ -11,6 +11,7 @@ import {
pruneScrollSnapshots,
saveScrollSnapshot,
} from '../utils/scrollSnapshotStore';
+import { settleScrollTarget } from '../utils/settleScrollTarget';
const FLUSH_THROTTLE_MS = 200;
const DEEP_LINK_MAX_ATTEMPTS = 30;
@@ -26,18 +27,24 @@ const BOTTOM_SETTLE_QUIET_MS = 150;
const BOTTOM_SETTLE_MAX_MS = 1000;
const USER_SCROLL_INPUT_EVENTS = ['keydown', 'pointerdown', 'touchstart', 'wheel'] as const;
-interface PendingWrite {
+interface ScrollPosition {
+ anchorId?: string;
+ anchorOffset?: number;
atBottom: boolean;
- key: string;
offset: number;
}
+interface PendingWrite extends ScrollPosition {
+ key: string;
+}
+
export type InitialScrollPosition = 'bottom' | 'top';
interface UseTopicScrollPersistOptions {
containerRef?: RefObject<HTMLDivElement | null>;
contextKey: string;
- dataSourceLength: number;
+ /** Message row ids, in message-index space. */
+ dataSource: string[];
/**
* Returns the VList scroll element. Snapshot and bottom restores write its
* `scrollTop` directly: virtua's `scrollTo` / `scrollToIndex` keep
@@ -112,7 +119,7 @@ const findDeepLinkElement = (
export const useTopicScrollPersist = ({
containerRef,
contextKey,
- dataSourceLength,
+ dataSource,
getScroller,
headerOffset = 0,
initialPosition = 'bottom',
@@ -126,12 +133,13 @@ export const useTopicScrollPersist = ({
// (cleared after each throttled flush), this survives idle reading so a
// leave-time re-stamp can refresh `savedAt` even when the user hasn't
// scrolled β€” see `persistFresh`.
- const lastKnownRef = useRef<{ atBottom: boolean; offset: number } | null>(null);
+ const lastKnownRef = useRef<ScrollPosition | null>(null);
// Initial mount counts as a "key change" so the first restore attempt fires.
const needsRestoreRef = useRef(true);
const prevContextKeyRef = useRef(contextKey);
- const dataSourceLengthRef = useRef(dataSourceLength);
- dataSourceLengthRef.current = dataSourceLength;
+ const dataSourceLength = dataSource.length;
+ const dataSourceRef = useRef(dataSource);
+ dataSourceRef.current = dataSource;
// Mirror the active key so unmount / beforeunload handlers (bound once) can
// re-stamp the topic the user is actually leaving.
const contextKeyRef = useRef(contextKey);
@@ -144,6 +152,26 @@ export const useTopicScrollPersist = ({
const handledDeepLinkRef = useRef<string | undefined>(undefined);
const restoreSequenceRef = useRef(0);
+ const resolvePosition = useCallback(
+ (offset: number, atBottom: boolean): ScrollPosition => {
+ const ref = virtuaRef.current;
+ const messages = dataSourceRef.current;
+ if (!ref || messages.length === 0) return { atBottom, offset };
+
+ const messageIndex = Math.min(
+ Math.max(ref.findItemIndex(offset) - headerOffset, 0),
+ messages.length - 1,
+ );
+ return {
+ anchorId: messages[messageIndex],
+ anchorOffset: offset - ref.getItemOffset(headerOffset + messageIndex),
+ atBottom,
+ offset,
+ };
+ },
+ [headerOffset, virtuaRef],
+ );
+
const flushNow = useCallback(() => {
if (flushTimerRef.current) {
clearTimeout(flushTimerRef.current);
@@ -151,26 +179,24 @@ export const useTopicScrollPersist = ({
}
const pending = pendingWriteRef.current;
if (!pending) return;
- saveScrollSnapshot(pending.key, {
- atBottom: pending.atBottom,
- offset: pending.offset,
- savedAt: Date.now(),
- });
+ const { key, ...position } = pending;
+ saveScrollSnapshot(key, { ...position, savedAt: Date.now() });
pendingWriteRef.current = null;
}, []);
const recordScroll = useCallback(
(offset: number, atBottom: boolean) => {
if (restoringRef.current) return;
- lastKnownRef.current = { atBottom, offset };
- pendingWriteRef.current = { atBottom, key: contextKey, offset };
+ const position = resolvePosition(offset, atBottom);
+ lastKnownRef.current = position;
+ pendingWriteRef.current = { ...position, key: contextKey };
if (flushTimerRef.current) return;
flushTimerRef.current = setTimeout(() => {
flushTimerRef.current = null;
flushNow();
}, FLUSH_THROTTLE_MS);
},
- [contextKey, flushNow],
+ [contextKey, flushNow, resolvePosition],
);
// Re-stamp the last known position for `key` with a fresh `savedAt`. Called
@@ -187,7 +213,7 @@ export const useTopicScrollPersist = ({
pendingWriteRef.current = null;
const last = lastKnownRef.current;
if (!last) return;
- saveScrollSnapshot(key, { atBottom: last.atBottom, offset: last.offset, savedAt: Date.now() });
+ saveScrollSnapshot(key, { ...last, savedAt: Date.now() });
}, []);
// On contextKey change: re-stamp the previous key with the latest position,
@@ -210,7 +236,7 @@ export const useTopicScrollPersist = ({
migrateScrollSnapshot(prevKey, contextKey);
// If data hasn't rendered yet, leave the default first-mount restore
// (scroll-to-bottom) in place β€” there's nothing to preserve.
- if (dataSourceLengthRef.current > 0) {
+ if (dataSourceRef.current.length > 0) {
needsRestoreRef.current = false;
}
return;
@@ -248,16 +274,13 @@ export const useTopicScrollPersist = ({
// Seed the last-known position from where the restore actually
// landed so a later leave-time re-stamp (persistFresh) has a
// position to refresh even if the user reads without scrolling.
- lastKnownRef.current = { atBottom: isAtBottom, offset: ref.scrollOffset };
+ const landed = resolvePosition(ref.scrollOffset, isAtBottom);
+ lastKnownRef.current = landed;
if (convergeSnapshot) {
// Target was unreachable β€” persist the actual landing position so
// the snapshot self-heals and future revisits don't burn the
// polling budget.
- pendingWriteRef.current = {
- atBottom: isAtBottom,
- key: contextKey,
- offset: ref.scrollOffset,
- };
+ pendingWriteRef.current = { ...landed, key: contextKey };
flushNow();
}
}
@@ -332,9 +355,12 @@ export const useTopicScrollPersist = ({
}
const snapshot = loadScrollSnapshot(contextKey);
- const targetOffset = snapshot && !snapshot.atBottom ? snapshot.offset : null;
+ const anchorIndex =
+ snapshot && !snapshot.atBottom && snapshot.anchorId
+ ? dataSourceRef.current.indexOf(snapshot.anchorId)
+ : -1;
- if (targetOffset === null) {
+ if (!snapshot || anchorIndex < 0) {
const scroller = getScroller();
if (!scroller) {
restoringRef.current = false;
@@ -397,6 +423,24 @@ export const useTopicScrollPersist = ({
// freshly-mounted VList. A single rAF isn't enough β€” only the viewport-
// visible items have laid out by then, and ResizeObserver hasn't reported
// below-the-fold heights yet.
+ const anchorOffset = snapshot.anchorOffset ?? 0;
+ const estimatedTarget = (ref: VListHandle) =>
+ ref.getItemOffset(headerOffset + anchorIndex) + anchorOffset;
+ const findAnchorRow = () =>
+ containerRef?.current?.querySelector<HTMLElement>(`[data-index="${anchorIndex}"]`) ?? null;
+ // Once the anchor row is on screen its laid-out position is the truth;
+ // virtua's offsets still count the unmeasured rows above at their estimate.
+ const anchorTarget = (ref: VListHandle) => {
+ const row = findAnchorRow();
+ const scroller = getScroller();
+ if (!row || !scroller) return estimatedTarget(ref);
+ return (
+ scroller.scrollTop +
+ row.getBoundingClientRect().top -
+ scroller.getBoundingClientRect().top +
+ anchorOffset
+ );
+ };
let attempts = 0;
const tryScroll = () => {
if (restoreSequenceRef.current !== restoreSequence) return;
@@ -406,12 +450,53 @@ export const useTopicScrollPersist = ({
restoringRef.current = false;
return;
}
+ const targetOffset = estimatedTarget(ref);
const required = targetOffset + ref.viewportSize;
const cappedOut = attempts >= RESTORE_MAX_FRAMES;
if (ref.scrollSize >= required || cappedOut) {
const scroller = getScroller();
- if (scroller) scroller.scrollTop = targetOffset;
- finalize(cappedOut);
+ if (!scroller) return finalize(cappedOut);
+ const aimAt = (target: number) => {
+ scroller.scrollTop = target;
+ lastKnownRef.current = resolvePosition(target, false);
+ };
+ const settleOnAnchor = () => {
+ const ref = virtuaRef.current;
+ if (!ref || restoreSequenceRef.current !== restoreSequence) return;
+ const target = anchorTarget(ref);
+ aimAt(target);
+ // Rows above the anchor start at virtua's estimated size; as they are
+ // measured the anchor moves, so keep re-aiming until it holds still.
+ settleScrollTarget({
+ aimAt,
+ initialTarget: target,
+ isStale: () => restoreSequenceRef.current !== restoreSequence,
+ maxMs: BOTTOM_SETTLE_MAX_MS,
+ onDone: () => finalize(cappedOut),
+ quietMs: BOTTOM_SETTLE_QUIET_MS,
+ readTarget: () => (virtuaRef.current ? anchorTarget(virtuaRef.current) : undefined),
+ scroller,
+ stopEvents: USER_SCROLL_INPUT_EVENTS,
+ });
+ };
+
+ // Aiming more than a viewport into the anchor leaves the anchor row
+ // itself outside virtua's render window, so the aim rests on estimated
+ // heights and a tall reply lands a round late. Chase the row's start
+ // until it renders, then aim from where it actually is.
+ if (anchorOffset <= ref.viewportSize) return settleOnAnchor();
+ let anchorFrames = 0;
+ const revealAnchorRow = () => {
+ if (restoreSequenceRef.current !== restoreSequence) return;
+ const current = virtuaRef.current;
+ if (findAnchorRow() || !current || ++anchorFrames >= RESTORE_MAX_FRAMES) {
+ settleOnAnchor();
+ return;
+ }
+ aimAt(current.getItemOffset(headerOffset + anchorIndex));
+ requestAnimationFrame(revealAnchorRow);
+ };
+ revealAnchorRow();
return;
}
attempts += 1;
@@ -427,6 +512,7 @@ export const useTopicScrollPersist = ({
headerOffset,
initialPosition,
messageDeepLink,
+ resolvePosition,
virtuaRef,
]);
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 75f58c53130..38b23efe938 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -3,7 +3,7 @@
import type { UIChatMessage } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import type { ReactNode } from 'react';
-import { memo, useCallback, useEffect, useMemo } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import AsyncError from '@/components/AsyncError';
import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';
@@ -11,11 +11,12 @@ import { useFetchNotebookDocuments } from '@/hooks/useFetchNotebookDocuments';
import { getMessageListCacheIdentity, isMessageListServerVerified } from '@/services/message/cache';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
-import { operationSelectors } from '@/store/chat/selectors';
+import { operationSelectors, topicSelectors } from '@/store/chat/selectors';
import {
hasPendingInterventions,
INTERVENTION_REFRESH_INTERVAL,
} from '@/store/chat/utils/interventionSync';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useUserStore } from '@/store/user';
import { authSelectors, labPreferSelectors, settingsSelectors } from '@/store/user/selectors';
@@ -32,6 +33,9 @@ import {
useConversationStoreApi,
} from '../store';
import AgentSignalReceiptList from './components/AgentSignalReceiptList';
+import PreviewTail from './components/PreviewTail';
+import { resolveTopicPreview } from './components/PreviewTail/resolveTopicPreview';
+import { usePreviewHandoff } from './components/PreviewTail/usePreviewHandoff';
import { RefreshError } from './components/RefreshError';
import VirtualizedList from './components/VirtualizedList';
import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';
@@ -332,6 +336,32 @@ const ChatList = memo<ChatListProps>(
messagesInit,
});
+ const activeTopic = useChatStore((s) =>
+ context.topicId ? topicSelectors.getTopicById(context.topicId)(s) : undefined,
+ );
+ const topicPreview = useMemo(
+ () =>
+ feedback.showSkeleton
+ ? resolveTopicPreview({
+ contextKey: messageMapKey(context),
+ running:
+ isStreaming ||
+ activeTopic?.status === 'running' ||
+ activeTopic?.status === 'waitingForHuman',
+ topicId: context.topicId,
+ topicUpdatedAt: activeTopic?.updatedAt,
+ })
+ : undefined,
+ [activeTopic, context, feedback.showSkeleton, isStreaming],
+ );
+ const listRef = useRef<HTMLDivElement>(null);
+ const handoffPreview = usePreviewHandoff({
+ contextKey: messageMapKey(context),
+ listMounted: !topicPreview && !feedback.showSkeleton && !feedback.showFirstLoadError,
+ listRef,
+ preview: topicPreview,
+ });
+
// The hint renders inside the latest assistant row, which subscribes to the
// store itself (virtua would not repaint a cached row from a prop change).
// Resolved against the rows actually rendered: folded steer chains in the
@@ -360,6 +390,12 @@ const ChatList = memo<ChatListProps>(
);
}
+ if (topicPreview) {
+ return (
+ <PreviewTail headerSlot={headerSlot} overlayHeight={overlayHeight} preview={topicPreview} />
+ );
+ }
+
if (feedback.showSkeleton) {
// The header is chrome, not async content: dropping it here blanks a
// server-rendered title the moment the list mounts to fetch.
@@ -405,7 +441,7 @@ const ChatList = memo<ChatListProps>(
);
return (
- <Flexbox style={{ height: '100%', minHeight: 0 }}>
+ <Flexbox style={{ height: '100%', minHeight: 0, position: 'relative' }}>
{messageAuthorAgentIds.map((agentId) => (
<MessageAuthorConfigLoader
agentId={agentId}
@@ -413,9 +449,22 @@ const ChatList = memo<ChatListProps>(
key={agentId}
/>
))}
- <Flexbox flex={1} style={{ minHeight: 0 }}>
+ <Flexbox
+ flex={1}
+ ref={listRef}
+ style={{ minHeight: 0, visibility: handoffPreview ? 'hidden' : undefined }}
+ >
{content}
</Flexbox>
+ {handoffPreview && (
+ <div style={{ inset: 0, position: 'absolute' }}>
+ <PreviewTail
+ headerSlot={headerSlot}
+ overlayHeight={overlayHeight}
+ preview={handoffPreview}
+ />
+ </div>
+ )}
{feedback.showBackgroundError && (
<RefreshError
error={refreshError.error}
diff --git a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.test.ts b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.test.ts
index 8444f60ebcf..8ea94439caa 100644
--- a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.test.ts
+++ b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.test.ts
@@ -4,6 +4,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ hasReadingPositionSnapshot,
isDraftPromotionKey,
loadScrollSnapshot,
migrateScrollSnapshot,
@@ -249,4 +250,45 @@ describe('scrollSnapshotStore', () => {
expect(loadScrollSnapshot('next')?.offset).toBe(9);
});
});
+
+ describe('hasReadingPositionSnapshot', () => {
+ it('is true for an anchored snapshot away from the bottom', () => {
+ saveScrollSnapshot('k', {
+ anchorId: 'msg_1',
+ anchorOffset: 12,
+ atBottom: false,
+ offset: 300,
+ savedAt: Date.now(),
+ });
+ expect(hasReadingPositionSnapshot('k')).toBe(true);
+ });
+
+ it('is false at the bottom', () => {
+ saveScrollSnapshot('k', {
+ anchorId: 'msg_1',
+ anchorOffset: 12,
+ atBottom: true,
+ offset: 300,
+ savedAt: Date.now(),
+ });
+ expect(hasReadingPositionSnapshot('k')).toBe(false);
+ });
+
+ it('is false for a snapshot without an anchor, which restores to the bottom', () => {
+ saveScrollSnapshot('k', { atBottom: false, offset: 300, savedAt: Date.now() });
+ expect(hasReadingPositionSnapshot('k')).toBe(false);
+ });
+
+ it('is false with no snapshot', () => {
+ expect(hasReadingPositionSnapshot('k')).toBe(false);
+ });
+ });
+
+ it('drops a snapshot whose anchor id is not a string', () => {
+ localStorage.setItem(
+ `${SCROLL_SNAPSHOT_KEY_PREFIX}:k`,
+ JSON.stringify({ anchorId: 7, atBottom: false, offset: 1, savedAt: Date.now() }),
+ );
+ expect(loadScrollSnapshot('k')).toBeNull();
+ });
});
diff --git a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts
index b65f99717ff..7191d384c32 100644
--- a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts
+++ b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts
@@ -8,7 +8,11 @@ export const SCROLL_SNAPSHOT_MAX_ENTRIES = 500;
// the short TTL also keeps the localStorage key count tiny.
export const SCROLL_SNAPSHOT_MAX_AGE_MS = 5 * 60 * 1000;
+// A paged topic reopens with only its newest rows, so a pixel offset from the
+// top points at different content on the next visit; the anchor row does not.
export interface ScrollSnapshot {
+ anchorId?: string;
+ anchorOffset?: number;
atBottom: boolean;
offset: number;
savedAt: number;
@@ -33,7 +37,10 @@ const isValidSnapshot = (value: unknown): value is ScrollSnapshot => {
Number.isFinite(v.offset) &&
typeof v.atBottom === 'boolean' &&
typeof v.savedAt === 'number' &&
- Number.isFinite(v.savedAt)
+ Number.isFinite(v.savedAt) &&
+ (v.anchorId === undefined || (typeof v.anchorId === 'string' && v.anchorId.length > 0)) &&
+ (v.anchorOffset === undefined ||
+ (typeof v.anchorOffset === 'number' && Number.isFinite(v.anchorOffset)))
);
};
@@ -130,6 +137,11 @@ export const loadScrollSnapshot = (contextKey: string): ScrollSnapshot | null =>
}
};
+export const hasReadingPositionSnapshot = (contextKey: string): boolean => {
+ const snapshot = loadScrollSnapshot(contextKey);
+ return !!snapshot && !snapshot.atBottom && !!snapshot.anchorId;
+};
+
export const saveScrollSnapshot = (contextKey: string, snapshot: ScrollSnapshot): void => {
const storage = getStorage();
if (!storage) return;
diff --git a/src/features/Conversation/ChatList/utils/settleScrollTarget.test.ts b/src/features/Conversation/ChatList/utils/settleScrollTarget.test.ts
new file mode 100644
index 00000000000..cf7c25418b0
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/settleScrollTarget.test.ts
@@ -0,0 +1,76 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { settleScrollTarget } from './settleScrollTarget';
+
+const createScroller = () => {
+ const scroller = { scrollTop: 0 } as HTMLElement & { scrollTop: number };
+ scroller.addEventListener = vi.fn();
+ scroller.removeEventListener = vi.fn();
+ return scroller;
+};
+
+describe('settleScrollTarget', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('re-aims when the scroller drifts off a target that holds still', async () => {
+ const scroller = createScroller();
+ const aimAt = vi.fn((target: number) => {
+ scroller.scrollTop = target;
+ });
+ const onDone = vi.fn();
+ scroller.scrollTop = 1000;
+
+ settleScrollTarget({
+ aimAt,
+ initialTarget: 1000,
+ isStale: () => false,
+ maxMs: 1000,
+ onDone,
+ quietMs: 150,
+ readTarget: () => 1000,
+ scroller,
+ stopEvents: [],
+ });
+
+ await vi.advanceTimersByTimeAsync(32);
+ scroller.scrollTop = 2800;
+ await vi.advanceTimersByTimeAsync(400);
+
+ expect(aimAt).toHaveBeenLastCalledWith(1000);
+ expect(scroller.scrollTop).toBe(1000);
+ expect(onDone).toHaveBeenCalled();
+ });
+
+ it('settles once the target holds still where the scroller already is', async () => {
+ const scroller = createScroller();
+ const aimAt = vi.fn();
+ const onDone = vi.fn();
+ scroller.scrollTop = 1000;
+
+ settleScrollTarget({
+ aimAt,
+ initialTarget: 1000,
+ isStale: () => false,
+ maxMs: 1000,
+ onDone,
+ quietMs: 150,
+ readTarget: () => 1000,
+ scroller,
+ stopEvents: [],
+ });
+
+ await vi.advanceTimersByTimeAsync(400);
+
+ expect(aimAt).not.toHaveBeenCalled();
+ expect(onDone).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/Conversation/ChatList/utils/settleScrollTarget.ts b/src/features/Conversation/ChatList/utils/settleScrollTarget.ts
new file mode 100644
index 00000000000..d9a98dbf918
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/settleScrollTarget.ts
@@ -0,0 +1,66 @@
+interface SettleScrollTargetOptions {
+ aimAt: (target: number) => void;
+ initialTarget: number;
+ isStale: () => boolean;
+ maxMs: number;
+ onDone: () => void;
+ quietMs: number;
+ readTarget: () => number | undefined;
+ scroller: HTMLElement;
+ stopEvents: readonly string[];
+}
+
+export const settleScrollTarget = ({
+ aimAt,
+ initialTarget,
+ isStale,
+ maxMs,
+ onDone,
+ quietMs,
+ readTarget,
+ scroller,
+ stopEvents,
+}: SettleScrollTargetOptions) => {
+ let interrupted = false;
+ const interrupt = () => {
+ interrupted = true;
+ };
+ for (const type of stopEvents) scroller.addEventListener(type, interrupt, { passive: true });
+ const stopListening = () => {
+ for (const type of stopEvents) scroller.removeEventListener(type, interrupt);
+ };
+
+ const startedAt = Date.now();
+ let lastChangeAt = startedAt;
+ let lastTarget = initialTarget;
+ let landedAt = scroller.scrollTop;
+ const step = () => {
+ if (isStale()) {
+ stopListening();
+ return;
+ }
+ const target = interrupted ? undefined : readTarget();
+ if (target === undefined) {
+ stopListening();
+ onDone();
+ return;
+ }
+ const now = Date.now();
+ // Virtua shifts scrollTop on its own as rows above get measured, so a
+ // target that holds still can still be missed. Drift is measured from where
+ // the last aim landed, since a clamped target is never reached.
+ if (target !== lastTarget || Math.abs(scroller.scrollTop - landedAt) > 1) {
+ aimAt(target);
+ landedAt = scroller.scrollTop;
+ lastTarget = target;
+ lastChangeAt = now;
+ }
+ if (now - lastChangeAt >= quietMs || now - startedAt >= maxMs) {
+ stopListening();
+ onDone();
+ return;
+ }
+ requestAnimationFrame(step);
+ };
+ requestAnimationFrame(step);
+};
diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsx
index 18725094c49..7cd141e8350 100644
--- a/src/features/Conversation/ConversationProvider.test.tsx
+++ b/src/features/Conversation/ConversationProvider.test.tsx
@@ -120,6 +120,7 @@ vi.mock('@/store/chat/selectors', () => ({
operationSelectors: {
isAgentRuntimeRunningByContext: () => () => chatListMocks.isStreaming,
},
+ topicSelectors: { getTopicById: () => () => undefined },
}));
vi.mock('@/store/serverConfig', () => ({
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index 8e17a596422..69c500e54f8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import { findLatestWorkRootOperationId } from '@lobechat/conversation-flow';
import type { AssistantContentBlock, EmojiReaction, UISignalCallbacksBlock } from '@lobechat/types';
import { Flexbox, Tag } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
@@ -31,7 +32,6 @@ import {
useConversationStore,
} from '../../store';
import type { SteerContinuation } from '../../store/slices/data/steerChains';
-import { getOperationFinalRootId } from '../../store/slices/data/workSummaries';
import InterruptedHint from '../Assistant/components/InterruptedHint';
import Usage from '../components/Extras/Usage';
import MessageBranch from '../components/MessageBranch';
@@ -65,21 +65,6 @@ const actionBarHolder = (
/>
);
-const findLatestWorkRootOperationId = (
- metadata?: { work?: { rootOperationId?: unknown } } | null,
- children?: AssistantContentBlock[],
- taskCompletions?: AssistantContentBlock[],
-) => {
- const blocks = [...(children ?? []), ...(taskCompletions ?? [])];
-
- for (let index = blocks.length - 1; index >= 0; index -= 1) {
- const rootOperationId = getOperationFinalRootId(blocks[index]?.metadata);
- if (rootOperationId) return rootOperationId;
- }
-
- return getOperationFinalRootId(metadata);
-};
-
interface GroupMessageProps {
/** Later turns steered onto this one, rendered as one continuous chain. */
continuations?: SteerContinuation[];
diff --git a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
index 3f28e03a615..dbcde9dc12c 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
@@ -1,11 +1,8 @@
+import { deriveOperationEditedFiles } from '@lobechat/builtin-tools/operationArtifacts';
import type { AssistantContentBlock, ChatToolPayloadWithResult } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import {
- collectFileEditToolCallRecords,
- deriveOperationEditedFiles,
- summarizeEditedFilesTotals,
-} from './deriveEditedFiles';
+import { summarizeEditedFilesTotals } from './deriveEditedFiles';
/** Build a display tool payload with a resolved plugin state (result.state). */
const tool = (
@@ -23,14 +20,6 @@ const block = (tools: ChatToolPayloadWithResult[]): AssistantContentBlock => ({
tools,
});
-const sandboxWrite = (id: string, path: string) =>
- tool({
- apiName: 'writeFile',
- arguments: JSON.stringify({ path }),
- id,
- result: { content: '', id: `${id}-r`, state: { path, success: true } },
- });
-
const sandboxEdit = (
id: string,
path: string,
@@ -43,222 +32,6 @@ const sandboxEdit = (
result: { content: '', id: `${id}-r`, state: { path, ...deltas } },
});
-describe('collectFileEditToolCallRecords', () => {
- it('flattens block tools into scanner records, surfacing result.state', () => {
- const records = collectFileEditToolCallRecords([
- block([sandboxWrite('t1', '/work/a.ts')]),
- block([sandboxEdit('t2', '/work/a.ts', { linesAdded: 2 })]),
- ]);
-
- expect(records).toEqual([
- {
- apiName: 'writeFile',
- arguments: JSON.stringify({ path: '/work/a.ts' }),
- identifier: 'lobe-cloud-sandbox',
- state: { path: '/work/a.ts', success: true },
- toolCallId: 't1',
- },
- {
- apiName: 'editFile',
- arguments: JSON.stringify({ path: '/work/a.ts' }),
- identifier: 'lobe-cloud-sandbox',
- state: { linesAdded: 2, path: '/work/a.ts' },
- toolCallId: 't2',
- },
- ]);
- });
-
- it('tolerates empty blocks / tool lists', () => {
- expect(collectFileEditToolCallRecords([])).toEqual([]);
- expect(collectFileEditToolCallRecords([block([])])).toEqual([]);
- });
-
- // Regression: a tool call with no merged result never executed (pending
- // human approval, or the run was interrupted first). Forwarding it would let
- // the scanner fall back to `arguments.path` and show a file as edited that
- // was never actually written.
- it('drops tool calls that have no result yet', () => {
- const records = collectFileEditToolCallRecords([
- block([
- tool({ apiName: 'writeFile', arguments: JSON.stringify({ path: '/work/a.ts' }), id: 't1' }),
- sandboxWrite('t2', '/work/b.ts'),
- ]),
- ]);
-
- expect(records.map((record) => record.toolCallId)).toEqual(['t2']);
- });
-});
-
-describe('deriveOperationEditedFiles', () => {
- it('aggregates multi-file edits across blocks', () => {
- const entries = deriveOperationEditedFiles([
- block([sandboxWrite('t1', '/work/a.ts')]),
- block([
- sandboxEdit('t2', '/work/a.ts', { diffText: '@@ a', linesAdded: 3, linesDeleted: 1 }),
- sandboxWrite('t3', '/work/b.ts'),
- ]),
- ]);
-
- expect(entries.map((e) => [e.path, e.kind])).toEqual([
- ['/work/a.ts', 'added'],
- ['/work/b.ts', 'added'],
- ]);
- // Deltas fold onto the write→edit chain for a.ts.
- expect(entries[0]).toMatchObject({ diffTexts: ['@@ a'], linesAdded: 3, linesDeleted: 1 });
- });
-
- it('drops entity-format files (they surface as file Works) but keeps html + other', () => {
- const entries = deriveOperationEditedFiles(
- [
- block([
- sandboxWrite('t1', '/work/deck.pptx'),
- sandboxWrite('t2', '/work/data.xlsx'),
- sandboxWrite('t3', '/work/report.pdf'),
- sandboxWrite('t4', '/work/index.html'),
- sandboxWrite('t5', '/work/notes.md'),
- ]),
- ],
- true,
- );
-
- expect(entries.map((e) => e.path)).toEqual(['/work/index.html', '/work/notes.md']);
- });
-
- it('keeps sandbox entity files when the round has no work surface (legacy client runtime)', () => {
- // Without a work anchor no file Work registers, so dropping the entry
- // would make the file invisible on both surfaces β€” the card keeps it.
- const entries = deriveOperationEditedFiles([
- block([sandboxWrite('t1', '/work/deck.pptx'), sandboxWrite('t2', '/work/notes.md')]),
- ]);
-
- expect(entries.map((e) => e.path)).toEqual(['/work/deck.pptx', '/work/notes.md']);
- });
-
- it('keeps a hetero-edited entity file in the card (no file Work covers it)', () => {
- // Registration only exports from the cloud sandbox, so a codex-edited
- // entity file registers no Work β€” the card is the only place it can show.
- const codexCsv = tool({
- apiName: 'file_change',
- id: 't2',
- identifier: 'codex',
- result: {
- content: '',
- id: 't2-r',
- state: {
- changes: [{ kind: 'update', linesAdded: 2, linesDeleted: 1, path: '/repo/data.csv' }],
- },
- },
- });
-
- const entries = deriveOperationEditedFiles(
- [block([sandboxWrite('t1', '/work/deck.pptx'), codexCsv])],
- true,
- );
-
- expect(entries.map((e) => e.path)).toEqual(['/repo/data.csv']);
- });
-
- it('keeps a deleted entity file in the card even when the round has a work surface', () => {
- // The file Work registrar skips `kind === 'deleted'` entries (nothing left
- // to export), so the card is the only surface where the deletion shows.
- const codexDelete = tool({
- apiName: 'file_change',
- id: 't2',
- identifier: 'codex',
- result: {
- content: '',
- id: 't2-r',
- state: {
- changes: [{ kind: 'delete', linesAdded: 0, linesDeleted: 12, path: '/repo/report.pdf' }],
- },
- },
- });
-
- const entries = deriveOperationEditedFiles([block([codexDelete])], true);
-
- expect(entries.map((e) => [e.path, e.kind])).toEqual([['/repo/report.pdf', 'deleted']]);
- });
-
- it('drops an entity file only when its LAST edit is sandbox-backed', () => {
- // Sandbox writes it, codex re-edits it β†’ the Work provenance rule keys off
- // the last edit, so no Work registers and the card must keep the file.
- const codexReEdit = tool({
- apiName: 'file_change',
- id: 't2',
- identifier: 'codex',
- result: {
- content: '',
- id: 't2-r',
- state: {
- changes: [{ kind: 'update', linesAdded: 1, linesDeleted: 0, path: '/work/deck.pptx' }],
- },
- },
- });
-
- const entries = deriveOperationEditedFiles(
- [block([sandboxWrite('t1', '/work/deck.pptx'), codexReEdit])],
- true,
- );
-
- expect(entries.map((e) => e.path)).toEqual(['/work/deck.pptx']);
- });
-
- it('annotates entries with sandboxBacked from the LAST edit provenance', () => {
- // The card routes clicks by origin: sandbox-backed files live-read via the
- // sandbox tool, everything else goes through the local/device filesystem.
- const codexCsv = tool({
- apiName: 'file_change',
- id: 't2',
- identifier: 'codex',
- result: {
- content: '',
- id: 't2-r',
- state: {
- changes: [{ kind: 'update', linesAdded: 2, linesDeleted: 1, path: '/repo/data.csv' }],
- },
- },
- });
-
- const entries = deriveOperationEditedFiles([
- block([sandboxWrite('t1', '/work/notes.md'), codexCsv]),
- ]);
-
- expect(entries.map((e) => [e.path, e.sandboxBacked])).toEqual([
- ['/work/notes.md', true],
- ['/repo/data.csv', false],
- ]);
- });
-
- it('drops a tool call whose result carries an error', () => {
- const entries = deriveOperationEditedFiles([
- block([
- tool({
- apiName: 'writeFile',
- arguments: JSON.stringify({ path: '/work/a.ts' }),
- id: 't1',
- result: { content: '', error: 'boom', id: 't1-r', state: { path: '/work/a.ts' } },
- }),
- ]),
- ]);
- expect(entries).toEqual([]);
- });
-
- it('returns an empty list when the operation touched no files', () => {
- expect(deriveOperationEditedFiles([])).toEqual([]);
- expect(
- deriveOperationEditedFiles([
- block([
- tool({
- apiName: 'runCommand',
- id: 't1',
- result: { content: '', id: 'r', state: { success: true } },
- }),
- ]),
- ]),
- ).toEqual([]);
- });
-});
-
describe('summarizeEditedFilesTotals', () => {
it('sums per-file line deltas', () => {
const entries = deriveOperationEditedFiles([
diff --git a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
index f4d93cb5518..936d9feb3ac 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
@@ -1,112 +1,4 @@
-import {
- classifyEditedFile,
- CLOUD_SANDBOX_IDENTIFIER,
- type EditedFileEntry,
- type FileEditToolCallRecord,
- scanOperationFileEdits,
-} from '@lobechat/builtin-tools/fileEditScan';
-import type { AssistantContentBlock } from '@lobechat/types';
-
-/**
- * Map the display-layer tool payloads of one assistant round into the shared
- * scanner's record shape. Each `block.tools` entry is a
- * `ChatToolPayloadWithResult`, so its persisted `pluginState` is surfaced at
- * `tool.result.state` (see `FlatListBuilder.createAssistantGroupMessage`) β€” the
- * exact `state` the scanner reads for sandbox / codex / claude-code edits.
- */
-export const collectFileEditToolCallRecords = (
- blocks: AssistantContentBlock[] = [],
-): FileEditToolCallRecord[] =>
- blocks.flatMap((block) =>
- (block.tools ?? [])
- // A tool call with NO merged result never executed (still pending human
- // approval, or the run was interrupted first) β€” FlatListBuilder only
- // attaches `result` once a tool message exists. Without this guard the
- // scanner would fall back to `arguments.path` for sandbox write/edit
- // calls and show a file as edited that was never actually written.
- .filter((tool) => tool.result != null)
- .map((tool) => ({
- apiName: tool.apiName,
- arguments: tool.arguments,
- // A failed tool call surfaces its error on the merged result, mirroring
- // the server's `message_plugins.error`; the scanner skips such records.
- error: tool.result?.error,
- identifier: tool.identifier,
- state: tool.result?.state,
- toolCallId: tool.id,
- })),
- );
-
-/**
- * Derive the aggregated edited-file entries for one operation's "edited N files"
- * card. Scans every tool call in the assistant group's blocks, then drops
- * entity-format files (pptx / xlsx / docx / pdf / …) whose last edit is
- * sandbox-backed β€” those surface through the `file` Work system (WorksSection /
- * WorkGallery) instead. An entity file last edited by a hetero source (codex /
- * claude-code / lobe-local-system / device-routed lobe-skills commands, including
- * entities detected from shell command text) registers NO file Work (registration
- * only exports from the cloud sandbox, see server `fileWorkRegistration`), so it
- * stays in the card β€” the only place it remains visible. HTML (artifact hosting) and every other file stay in the card
- * too.
- *
- * The sandbox-entity drop only applies when `hasWorkSurface` is true β€” i.e. the
- * round carries a work anchor (server-runtime operation), so a `file` Work can
- * actually exist. Legacy client-runtime rounds have no work registration; for
- * them the drop would make the file invisible on BOTH surfaces, so entries are
- * kept in the card instead.
- *
- * Purely derived from the message payload already in the store β€” nothing is
- * persisted. Callers must memoize on the blocks reference (see
- * {@link useOperationEditedFiles}) so the scan runs once per snapshot.
- */
-/**
- * An edited-file entry annotated with its content origin, so the card can route
- * a click to the right preview transport (sandbox live-read vs local/device
- * filesystem).
- */
-export interface OperationEditedFile extends EditedFileEntry {
- /**
- * Whether the file's LAST edit came from the cloud sandbox β€” mirroring the
- * server's provenance rule, the terminal edit owns the file's content.
- */
- sandboxBacked: boolean;
-}
-
-export const deriveOperationEditedFiles = (
- blocks: AssistantContentBlock[] = [],
- hasWorkSurface = false,
-): OperationEditedFile[] => {
- const records = collectFileEditToolCallRecords(blocks);
- if (records.length === 0) return [];
-
- const sandboxToolCallIds = new Set(
- records
- .filter((record) => record.identifier === CLOUD_SANDBOX_IDENTIFIER)
- .map((record) => record.toolCallId),
- );
-
- const entries = scanOperationFileEdits(records).map((entry): OperationEditedFile => {
- const lastSourceToolCallId = entry.sourceToolCallIds.at(-1);
- return {
- ...entry,
- sandboxBacked: !!lastSourceToolCallId && sandboxToolCallIds.has(lastSourceToolCallId),
- };
- });
- if (!hasWorkSurface) return entries;
-
- // Drop sandbox-backed entity files: their `file` Work card covers them.
- // Deleted entries stay β€” the file Work registrar skips `kind === 'deleted'`
- // (there is nothing left in the sandbox to export), so the card is the only
- // surface where a deleted entity file remains visible.
- return entries.filter(
- (entry) =>
- !(
- entry.kind !== 'deleted' &&
- classifyEditedFile(entry.path).category === 'entity' &&
- entry.sandboxBacked
- ),
- );
-};
+import type { EditedFileEntry } from '@lobechat/builtin-tools/fileEditScan';
export interface EditedFilesTotals {
linesAdded: number;
diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.tsx b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
index e1ce09c8142..4ceb8965bd0 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/index.tsx
+++ b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
@@ -1,6 +1,7 @@
'use client';
import type { EditedFileEntry } from '@lobechat/builtin-tools/fileEditScan';
+import type { OperationEditedFile } from '@lobechat/builtin-tools/operationArtifacts';
import {
FilePathDisplay,
getFileLanguage,
@@ -22,7 +23,7 @@ import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
-import { type OperationEditedFile, summarizeEditedFilesTotals } from './deriveEditedFiles';
+import { summarizeEditedFilesTotals } from './deriveEditedFiles';
import { useOpenEditedFile } from './useOpenEditedFile';
export const SINGLE_EDITED_FILE_ICON_SIZE = 40;
diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
index a1bbd4fad09..ef2c66091fe 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
@@ -1,3 +1,4 @@
+import type { OperationEditedFile } from '@lobechat/builtin-tools/operationArtifacts';
import { useCallback } from 'react';
import { isDesktop } from '@/const/version';
@@ -10,7 +11,6 @@ import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { useConversationStore } from '../../store';
-import type { OperationEditedFile } from './deriveEditedFiles';
// Home-relative paths are already anchored: the file tools expand exactly `~`,
// `~/…`, and `~\…` at write time (see local-file-shell's `expandTilde`). A
diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts b/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
index a690dafb9e9..65968a01c63 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
@@ -1,8 +1,10 @@
+import {
+ deriveOperationEditedFiles,
+ type OperationEditedFile,
+} from '@lobechat/builtin-tools/operationArtifacts';
import type { AssistantContentBlock } from '@lobechat/types';
import { useMemo } from 'react';
-import { deriveOperationEditedFiles, type OperationEditedFile } from './deriveEditedFiles';
-
/**
* Derived, non-persisted list of files edited across one assistant round.
*
diff --git a/src/features/Conversation/Messages/GoalTaskCard/index.tsx b/src/features/Conversation/Messages/GoalTaskCard/index.tsx
index b3ae30fd00e..cf5bdc6599d 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/index.tsx
+++ b/src/features/Conversation/Messages/GoalTaskCard/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { OperationGoal } from '@lobechat/builtin-tools/operationArtifacts';
import { createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
import { ChevronRightIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
@@ -10,7 +11,6 @@ import GoalStatusGlyph from '@/features/AgentGoals/GoalStatusGlyph';
import RunningGlyph from '@/features/Home/components/RunningGlyph';
import { useChatStore } from '@/store/chat';
-import type { OperationGoal } from './deriveOperationGoals';
import { buildGoalCardModel } from './goalCardModel';
import GoalElapsedTime from './GoalElapsedTime';
import type { GoalTaskPhase } from './goalTaskProgress';
diff --git a/src/features/Conversation/Messages/GoalTaskCard/useOperationGoals.ts b/src/features/Conversation/Messages/GoalTaskCard/useOperationGoals.ts
index 13b6e8a6479..b4c2759f13a 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/useOperationGoals.ts
+++ b/src/features/Conversation/Messages/GoalTaskCard/useOperationGoals.ts
@@ -1,8 +1,10 @@
+import {
+ deriveOperationGoals,
+ type OperationGoal,
+} from '@lobechat/builtin-tools/operationArtifacts';
import type { AssistantContentBlock } from '@lobechat/types';
import { useMemo } from 'react';
-import { deriveOperationGoals, type OperationGoal } from './deriveOperationGoals';
-
/**
* Display-only Goal artifacts derived from one settled assistant group.
*
diff --git a/src/features/Conversation/Messages/MessageWorks/index.tsx b/src/features/Conversation/Messages/MessageWorks/index.tsx
index 03c423081b4..dca308ba8b2 100644
--- a/src/features/Conversation/Messages/MessageWorks/index.tsx
+++ b/src/features/Conversation/Messages/MessageWorks/index.tsx
@@ -3,6 +3,7 @@
import type { WorkSummaryItem } from '@lobechat/types';
import { createStaticStyles, Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
+import type { ComponentProps } from 'react';
import { memo } from 'react';
import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
@@ -16,6 +17,25 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
+interface MessageWorkListProps {
+ items: WorkSummaryItem[];
+ onOpen?: ComponentProps<typeof WorkSummaryCard>['onOpen'];
+}
+
+export const MessageWorkList = memo<MessageWorkListProps>(({ items, onOpen }) => {
+ if (items.length === 0) return null;
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {items.map((item) => (
+ <WorkSummaryCard item={item} key={item.id} onOpen={onOpen} />
+ ))}
+ </Flexbox>
+ );
+});
+
+MessageWorkList.displayName = 'MessageWorkList';
+
interface MessageWorksProps {
rootOperationId?: string | null;
}
@@ -33,19 +53,7 @@ const MessageWorks = memo<MessageWorksProps>(({ rootOperationId }) => {
const agentShareId = useConversationStore((s) => s.context.agentShareId);
const handleVisitorOpen = useVisitorWorkOpen();
- if (data.length === 0) return null;
-
- return (
- <Flexbox className={styles.container} gap={8}>
- {data.map((item) => (
- <WorkSummaryCard
- item={item}
- key={item.id}
- onOpen={agentShareId ? handleVisitorOpen : undefined}
- />
- ))}
- </Flexbox>
- );
+ return <MessageWorkList items={data} onOpen={agentShareId ? handleVisitorOpen : undefined} />;
}, isEqual);
MessageWorks.displayName = 'MessageWorks';
diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts
index 81b5dae2d8e..2ade0ea2bb2 100644
--- a/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts
+++ b/src/features/Conversation/WorkingSidebar/GoalSection/goalWorkflowView.ts
@@ -1,7 +1,6 @@
+import type { OperationGoal } from '@lobechat/builtin-tools/operationArtifacts';
import type { GoalNodeStatus } from '@lobechat/types';
-import type { OperationGoal } from '@/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals';
-
export type GoalWorkflowRowState = 'done' | 'running' | 'waiting' | 'pending';
export interface GoalWorkflowRow {
diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts
index 5fa096a65a8..f329be93fbd 100644
--- a/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts
+++ b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts
@@ -1,9 +1,9 @@
-import { useMemo } from 'react';
-
import {
deriveOperationGoals,
type OperationGoal,
-} from '@/features/Conversation/Messages/GoalTaskCard/deriveOperationGoals';
+} from '@lobechat/builtin-tools/operationArtifacts';
+import { useMemo } from 'react';
+
import {
getGoalTaskProgress,
type GoalTaskPhase,
diff --git a/src/features/Conversation/store/slices/data/workSummaries.ts b/src/features/Conversation/store/slices/data/workSummaries.ts
index 86b4f3af086..2d3f2888dcb 100644
--- a/src/features/Conversation/store/slices/data/workSummaries.ts
+++ b/src/features/Conversation/store/slices/data/workSummaries.ts
@@ -1,16 +1,6 @@
+import { getOperationFinalRootId } from '@lobechat/conversation-flow';
import type { UIChatMessage, WorkSummaryItem } from '@lobechat/types';
-/**
- * Reads the operation-final work root id stamped on message/block metadata by
- * the server work registry (`metadata.work.rootOperationId`). Consumed by the
- * in-message Works chip resolution (`AssistantGroup`) and the work-summary index
- * below.
- */
-export const getOperationFinalRootId = (
- metadata?: { work?: { rootOperationId?: unknown } } | null,
-) =>
- typeof metadata?.work?.rootOperationId === 'string' ? metadata.work.rootOperationId : undefined;
-
const toTime = (value: unknown): number => {
if (!value) return 0;
const time = value instanceof Date ? value.getTime() : new Date(value as string).getTime();
diff --git a/src/features/Conversation/store/slices/generation/action.partialHead.test.ts b/src/features/Conversation/store/slices/generation/action.partialHead.test.ts
new file mode 100644
index 00000000000..045ba34d2b0
--- /dev/null
+++ b/src/features/Conversation/store/slices/generation/action.partialHead.test.ts
@@ -0,0 +1,94 @@
+import { act } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { type ConversationContext } from '../../../types';
+import { createStore } from '../../index';
+
+vi.mock('@/services/topic', () => ({
+ topicService: { branchTopicAtMessage: vi.fn(), cancelRateLimitContinuation: vi.fn() },
+}));
+vi.mock('@/services/message/roundCursorPage', () => ({ isPartialHeadWindow: () => true }));
+
+const context: ConversationContext = { agentId: 'session-1', threadId: null, topicId: 'topic-1' };
+const key = messageMapKey(context);
+
+const olderRound = [
+ { content: 'older question', id: 'msg-0', role: 'user' },
+ { content: 'older answer', id: 'msg-0a', parentId: 'msg-0', role: 'assistant' },
+];
+const headRound = [
+ { content: 'Hello', id: 'msg-1', parentId: 'msg-0a', role: 'user' },
+ {
+ children: [{ content: 'Hi there', id: 'child-1' }],
+ content: '',
+ id: 'group-1',
+ parentId: 'msg-1',
+ role: 'assistantGroup',
+ },
+];
+
+const chatState: Record<string, any> = {};
+const executeClientAgent = vi.fn();
+const refreshMessages = vi.fn(async () => {
+ chatState.messagesMap = { [key]: [...olderRound, ...headRound] };
+});
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: vi.fn(() => chatState), setState: vi.fn() },
+}));
+
+describe('client-mode runs on a partial head page', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ Object.assign(chatState, {
+ associateMessageWithOperation: vi.fn(),
+ completeOperation: vi.fn(),
+ dbMessagesMap: {},
+ executeClientAgent,
+ failOperation: vi.fn(),
+ isGatewayModeEnabled: () => false,
+ messagesMap: { [key]: headRound },
+ operations: {},
+ operationsByMessage: {},
+ refreshMessages,
+ startOperation: vi.fn(() => ({ operationId: 'op-1' })),
+ switchMessageBranch: vi.fn(),
+ topicDataMap: {},
+ });
+ });
+
+ it('regenerates with the full history', async () => {
+ const store = createStore({ context });
+ act(() => store.setState({ displayMessages: headRound } as any));
+
+ await act(async () => {
+ await store.getState().regenerateUserMessage('msg-1');
+ });
+
+ expect(refreshMessages).toHaveBeenCalledWith(context);
+ expect(executeClientAgent.mock.calls[0][0].messages.map((m: { id: string }) => m.id)).toEqual([
+ 'msg-0',
+ 'msg-0a',
+ 'msg-1',
+ ]);
+ });
+
+ it('continues with the full history', async () => {
+ const store = createStore({ context });
+ act(() => store.setState({ displayMessages: headRound } as any));
+
+ await act(async () => {
+ await store.getState().continueGeneration('group-1');
+ });
+
+ expect(refreshMessages).toHaveBeenCalledWith(context);
+ expect(executeClientAgent.mock.calls[0][0].messages.map((m: { id: string }) => m.id)).toEqual([
+ 'msg-0',
+ 'msg-0a',
+ 'msg-1',
+ 'group-1',
+ ]);
+ });
+});
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index df08a89a107..9953600c4b6 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -20,6 +20,7 @@ import {
parseSelectedSkillsFromEditorData,
parseSelectedToolsFromEditorData,
} from '@/store/chat/slices/agentRun/actions/entries/commandBus';
+import { ensureFullHistoryForClientRun } from '@/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
import {
@@ -265,10 +266,15 @@ const regenerateUserMessageFromSource = async (
}
// ── Client mode: run agent locally ──
+ const reloaded = await ensureFullHistoryForClientRun(context, chatStore.refreshMessages);
+ const fullMessages = reloaded
+ ? useChatStore.getState().messagesMap[messageMapKey(context)]
+ : undefined;
+ const fullIndex = fullMessages?.findIndex((m) => m.id === messageId) ?? -1;
await chatStore.executeClientAgent({
context,
initialContext,
- messages: contextMessages,
+ messages: fullIndex >= 0 ? fullMessages!.slice(0, fullIndex + 1) : contextMessages,
parentMessageId: messageId,
parentMessageType: 'user',
parentOperationId: operationId,
@@ -747,9 +753,12 @@ export const generationSlice: StateCreator<
}
// ── Client mode: run agent locally ──
+ const reloaded = await ensureFullHistoryForClientRun(context, chatStore.refreshMessages);
await chatStore.executeClientAgent({
context,
- messages: displayMessages,
+ messages:
+ (reloaded && useChatStore.getState().messagesMap[messageMapKey(context)]) ||
+ displayMessages,
parentMessageId: dbMessageId,
parentMessageType: message.role as 'assistant' | 'tool' | 'user',
parentOperationId: operationId,
diff --git a/src/helpers/conversationMessageRead.test.ts b/src/helpers/conversationMessageRead.test.ts
index 8f06f4470b9..531fb0b93e9 100644
--- a/src/helpers/conversationMessageRead.test.ts
+++ b/src/helpers/conversationMessageRead.test.ts
@@ -8,6 +8,7 @@ import { useUserStore } from '@/store/user';
import {
readConversationMessageListPage,
readConversationMessages,
+ readEarlierConversationMessages,
} from './conversationMessageRead';
const mockGatewayMode = ({
@@ -86,3 +87,20 @@ describe('readConversationMessageListPage', () => {
});
});
});
+
+describe('readEarlierConversationMessages', () => {
+ it('pages older history with the same projection gate as the head page', async () => {
+ mockGatewayMode({ gatewayMode: true });
+ const getEarlierMessages = vi
+ .spyOn(messageService, 'getEarlierMessages')
+ .mockResolvedValue({ messages: [], olderCursor: null });
+ const cursor = { createdAt: '2026-10-27T00:00:00.000Z', id: 'msg_1' };
+
+ await readEarlierConversationMessages({ agentId: 'agent-1', topicId: 'topic-1' }, cursor);
+
+ expect(getEarlierMessages).toHaveBeenCalledWith(
+ { agentId: 'agent-1', projectToolPayloads: true, topicId: 'topic-1' },
+ cursor,
+ );
+ });
+});
diff --git a/src/helpers/conversationMessageRead.ts b/src/helpers/conversationMessageRead.ts
index 375e1814f19..04b4ef11135 100644
--- a/src/helpers/conversationMessageRead.ts
+++ b/src/helpers/conversationMessageRead.ts
@@ -24,13 +24,15 @@ import { canUseGatewayProtocolV2 } from './gatewayProtocol';
* since switched to the browser, which is why `ClientMessageTransport` refills
* omitted payloads before building a context rather than trusting this gate.
*/
+export const isProjectedConversationRead = (agentId?: string | null): boolean =>
+ canUseGatewayProtocolV2() &&
+ resolveGatewayModeEnabled(getAgentStoreState(), agentId ?? undefined);
+
const withConversationReadOptions = (
context: MessageReadQueryContext,
): MessageReadQueryContext => ({
...context,
- projectToolPayloads:
- canUseGatewayProtocolV2() &&
- resolveGatewayModeEnabled(getAgentStoreState(), context.agentId ?? undefined),
+ projectToolPayloads: isProjectedConversationRead(context.agentId),
});
export const readConversationMessages = (
@@ -47,3 +49,9 @@ export const readConversationMessageListPage = (
context: MessageReadQueryContext,
): ReturnType<typeof messageService.getMessageListPage> =>
messageService.getMessageListPage(withConversationReadOptions(context));
+
+export const readEarlierConversationMessages = (
+ context: MessageReadQueryContext,
+ cursor: Parameters<typeof messageService.getEarlierMessages>[1],
+): ReturnType<typeof messageService.getEarlierMessages> =>
+ messageService.getEarlierMessages(withConversationReadOptions(context), cursor);
diff --git a/src/services/message/roundCursorPage.test.ts b/src/services/message/roundCursorPage.test.ts
index 670cdf2afab..0bac1ac60d8 100644
--- a/src/services/message/roundCursorPage.test.ts
+++ b/src/services/message/roundCursorPage.test.ts
@@ -5,9 +5,12 @@ import { lambdaClient } from '@/libs/trpc/client';
import { MessageService } from './index';
import {
ForwardPagingUnsupportedError,
+ isPartialHeadWindow,
primeMessageListPage,
+ readMessagesByRoundCursor,
readMessagesForward,
SHARED_TOPIC_FIRST_PAGE,
+ toRoundCursorQueryInput,
} from './roundCursorPage';
vi.mock('@/libs/trpc/client', () => ({
@@ -28,6 +31,56 @@ 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('toRoundCursorQueryInput', () => {
+ it('reads a gateway display page with the 50-row budget', () => {
+ const input = toRoundCursorQueryInput(
+ { agentId: 'a', projectToolPayloads: true, topicId: 't' },
+ null,
+ );
+
+ expect(input).toMatchObject({ countBudget: 50, roundLimit: 1000 });
+ });
+
+ it('keeps the full window for client-mode reads', () => {
+ const input = toRoundCursorQueryInput({ agentId: 'a', topicId: 't' }, null);
+
+ expect(input).toMatchObject({ countBudget: 1000, roundLimit: 1000 });
+ });
+});
+
+describe('partial head window', () => {
+ const older = { createdAt: '2026-01-01T00:00:00.000000Z', id: 'u1' };
+
+ it('marks a gateway head page that has older history', async () => {
+ const context = nextContext();
+ query.mockResolvedValueOnce({ ...page('m'), hasMore: true, nextCursor: older });
+
+ await readMessagesByRoundCursor({ ...context, projectToolPayloads: true }, null);
+
+ expect(isPartialHeadWindow(context)).toBe(true);
+ });
+
+ it('clears the mark once a full-budget head page lands', async () => {
+ const context = nextContext();
+ query.mockResolvedValueOnce({ ...page('m'), hasMore: true, nextCursor: older });
+ await readMessagesByRoundCursor({ ...context, projectToolPayloads: true }, null);
+ query.mockResolvedValueOnce({ ...page('m'), hasMore: true, nextCursor: older });
+
+ await readMessagesByRoundCursor(context, null);
+
+ expect(isPartialHeadWindow(context)).toBe(false);
+ });
+
+ it('does not mark a gateway head page that holds the whole topic', async () => {
+ const context = nextContext();
+ query.mockResolvedValueOnce(page('m'));
+
+ await readMessagesByRoundCursor({ ...context, projectToolPayloads: true }, null);
+
+ expect(isPartialHeadWindow(context)).toBe(false);
+ });
+});
+
describe('primeMessageListPage', () => {
const service = new MessageService();
diff --git a/src/services/message/roundCursorPage.ts b/src/services/message/roundCursorPage.ts
index 4738ca9885d..5d06e8a9d54 100644
--- a/src/services/message/roundCursorPage.ts
+++ b/src/services/message/roundCursorPage.ts
@@ -11,6 +11,9 @@ import type { MessageListPage, MessageRoundCursor } from './cache';
*/
export const MESSAGE_PAGE_ROW_BUDGET = 1000;
+// Client-mode reads keep the full budget: the client runtime replays the loaded rows as model history.
+export const GATEWAY_PAGE_ROW_BUDGET = 50;
+
/** Page sizes for reading a topic forward from its first round. */
export interface ForwardPageSize {
countBudget: number;
@@ -34,7 +37,7 @@ export const toRoundCursorQueryInput = (
cursor: MessageRoundCursor | null,
) => ({
agentId: params.agentId,
- countBudget: MESSAGE_PAGE_ROW_BUDGET,
+ countBudget: params.projectToolPayloads ? GATEWAY_PAGE_ROW_BUDGET : MESSAGE_PAGE_ROW_BUDGET,
cursor,
groupId: params.groupId,
includeFileWorks: true,
@@ -59,10 +62,25 @@ export const toMessageListPage = (page: RoundCursorQueryResult): MessageListPage
export const readMessagesByRoundCursor = async (
params: RoundCursorReadParams,
cursor: MessageRoundCursor | null,
-): Promise<MessageListPage> =>
- toMessageListPage(
- await lambdaClient.message.getMessagesByCursor.query(toRoundCursorQueryInput(params, cursor)),
- );
+): Promise<MessageListPage> => {
+ const input = toRoundCursorQueryInput(params, cursor);
+ const page = toMessageListPage(await lambdaClient.message.getMessagesByCursor.query(input));
+
+ if (cursor === null) {
+ const key = primeKey(params);
+ if (input.countBudget < MESSAGE_PAGE_ROW_BUDGET && page.olderCursor)
+ partialHeadWindows.add(key);
+ else partialHeadWindows.delete(key);
+ }
+
+ return page;
+};
+
+const partialHeadWindows = new Set<string>();
+
+// A head page smaller than the client runtime's history window: a client-side run must reload it first.
+export const isPartialHeadWindow = (context: MessageListQueryContext): boolean =>
+ partialHeadWindows.has(primeKey(context));
/** The `getMessagesByCursor` input for one forward page, starting after `cursor`. */
export const toForwardRoundCursorQueryInput = (
diff --git a/src/services/message/topicPreview.test.ts b/src/services/message/topicPreview.test.ts
new file mode 100644
index 00000000000..41b8d6c5693
--- /dev/null
+++ b/src/services/message/topicPreview.test.ts
@@ -0,0 +1,177 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+import {
+ fetchTopicPreviews,
+ getValidTopicPreview,
+ hasRecentTopicPreviewAttempt,
+ hasTopicPreview,
+ invalidateTopicPreview,
+ resetTopicPreviews,
+ TOPIC_PREVIEW_MAX_ENTRIES,
+ TOPIC_PREVIEW_TTL_MS,
+} from './topicPreview';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { message: { getTopicPreviews: { query: vi.fn() } } },
+}));
+
+const query = vi.mocked(lambdaClient.message.getTopicPreviews.query);
+
+const UPDATED_AT = '2026-10-27T00:00:00.000Z';
+
+const okItem = (topicId: string, topicUpdatedAt = UPDATED_AT) => ({
+ editedFiles: [],
+ goals: [],
+ kind: 'single' as const,
+ message: { content: `answer of ${topicId}`, id: `msg_${topicId}`, role: 'assistant' },
+ status: 'ok' as const,
+ topicId,
+ topicUpdatedAt,
+ workRootOperationId: null,
+ works: [],
+});
+
+const answerWith = (topicIds: string[]) =>
+ query.mockResolvedValueOnce(topicIds.map((id) => okItem(id)) as any);
+
+describe('topicPreview cache', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ resetTopicPreviews();
+ query.mockReset();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('serves a fetched preview while the topic is unchanged', async () => {
+ answerWith(['tpc_a']);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ expect(query).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ groupId: undefined,
+ topicIds: ['tpc_a'],
+ });
+ expect(getValidTopicPreview('tpc_a', { topicUpdatedAt: UPDATED_AT })?.message.id).toBe(
+ 'msg_tpc_a',
+ );
+ expect(hasTopicPreview('tpc_a')).toBe(true);
+ });
+
+ it('keeps skipped items out of the cache', async () => {
+ query.mockResolvedValueOnce([{ reason: 'running', status: 'skipped', topicId: 'tpc_a' }]);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ expect(hasTopicPreview('tpc_a')).toBe(false);
+ });
+
+ it('expires a preview after its time to live', async () => {
+ answerWith(['tpc_a']);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ vi.advanceTimersByTime(TOPIC_PREVIEW_TTL_MS + 1);
+
+ expect(getValidTopicPreview('tpc_a', { topicUpdatedAt: UPDATED_AT })).toBeUndefined();
+ expect(hasTopicPreview('tpc_a')).toBe(false);
+ });
+
+ it('drops a preview whose topic has been updated since', async () => {
+ answerWith(['tpc_a']);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ expect(
+ getValidTopicPreview('tpc_a', { topicUpdatedAt: '2026-10-27T00:05:00.000Z' }),
+ ).toBeUndefined();
+ expect(hasTopicPreview('tpc_a')).toBe(false);
+ });
+
+ it('drops a preview once the topic is running', async () => {
+ answerWith(['tpc_a']);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ expect(getValidTopicPreview('tpc_a', { running: true, topicUpdatedAt: UPDATED_AT })).toBe(
+ undefined,
+ );
+ expect(hasTopicPreview('tpc_a')).toBe(false);
+ });
+
+ it('accepts a topic list timestamp given as a Date', async () => {
+ answerWith(['tpc_a']);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ expect(getValidTopicPreview('tpc_a', { topicUpdatedAt: new Date(UPDATED_AT) })).toBeDefined();
+ });
+
+ it('evicts the oldest preview past the size cap', async () => {
+ const ids = Array.from({ length: TOPIC_PREVIEW_MAX_ENTRIES + 1 }, (_, i) => `tpc_${i}`);
+ for (const id of ids) {
+ answerWith([id]);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: [id] });
+ }
+
+ expect(hasTopicPreview('tpc_0')).toBe(false);
+ expect(hasTopicPreview('tpc_1')).toBe(true);
+ expect(hasTopicPreview(ids.at(-1)!)).toBe(true);
+ });
+
+ it('removes an invalidated preview', async () => {
+ answerWith(['tpc_a']);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ invalidateTopicPreview('tpc_a');
+
+ expect(hasTopicPreview('tpc_a')).toBe(false);
+ });
+
+ it('does not cache a preview fetched before a local change to its topic', async () => {
+ let resolve!: (value: unknown) => void;
+ query.mockReturnValueOnce(new Promise((r) => (resolve = r)) as any);
+ const pending = fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ invalidateTopicPreview('tpc_a');
+ resolve([okItem('tpc_a')]);
+ await pending;
+
+ expect(hasTopicPreview('tpc_a')).toBe(false);
+ });
+
+ it('swallows a failed request', async () => {
+ query.mockRejectedValueOnce(new Error('network'));
+
+ await expect(fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] })).resolves.toEqual(
+ [],
+ );
+ });
+
+ it('remembers a skipped topic for the time to live so hovering does not ask again', async () => {
+ query.mockResolvedValueOnce([
+ { reason: 'notFinalAnswer', status: 'skipped', topicId: 'tpc_a' },
+ ] as any);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ expect(hasRecentTopicPreviewAttempt('tpc_a')).toBe(true);
+ vi.advanceTimersByTime(TOPIC_PREVIEW_TTL_MS + 1);
+ expect(hasRecentTopicPreviewAttempt('tpc_a')).toBe(false);
+ });
+
+ it('remembers the topics of a failed request', async () => {
+ query.mockRejectedValueOnce(new Error('network'));
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a', 'tpc_b'] });
+
+ expect(hasRecentTopicPreviewAttempt('tpc_a')).toBe(true);
+ expect(hasRecentTopicPreviewAttempt('tpc_b')).toBe(true);
+ });
+
+ it('counts a cached preview as an attempt and forgets both on invalidation', async () => {
+ answerWith(['tpc_a']);
+ await fetchTopicPreviews({ agentId: 'agt_1', topicIds: ['tpc_a'] });
+
+ expect(hasRecentTopicPreviewAttempt('tpc_a')).toBe(true);
+ invalidateTopicPreview('tpc_a');
+ expect(hasRecentTopicPreviewAttempt('tpc_a')).toBe(false);
+ });
+});
diff --git a/src/services/message/topicPreview.ts b/src/services/message/topicPreview.ts
new file mode 100644
index 00000000000..3bb5c78c613
--- /dev/null
+++ b/src/services/message/topicPreview.ts
@@ -0,0 +1,123 @@
+import debug from 'debug';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+const log = debug('lobe-client:topic-preview');
+
+export const TOPIC_PREVIEW_TTL_MS = 60_000;
+export const TOPIC_PREVIEW_MAX_ENTRIES = 50;
+
+type TopicPreviewItem = Awaited<
+ ReturnType<typeof lambdaClient.message.getTopicPreviews.query>
+>[number];
+
+export type TopicPreview = Extract<TopicPreviewItem, { status: 'ok' }>;
+
+interface CacheEntry {
+ fetchedAt: number;
+ preview: TopicPreview;
+}
+
+const previews = new Map<string, CacheEntry>();
+// Skipped and failed answers are not cached as previews, but asking again within
+// the TTL would only repeat the same server read.
+const attempts = new Map<string, number>();
+let generation = 0;
+const invalidatedAt = new Map<string, number>();
+
+const isFresh = (entry: CacheEntry) => Date.now() - entry.fetchedAt <= TOPIC_PREVIEW_TTL_MS;
+
+const recordAttempt = (topicId: string) => {
+ attempts.delete(topicId);
+ attempts.set(topicId, Date.now());
+ while (attempts.size > TOPIC_PREVIEW_MAX_ENTRIES) {
+ const oldest = attempts.keys().next().value;
+ if (oldest === undefined) break;
+ attempts.delete(oldest);
+ }
+};
+
+const store = (preview: TopicPreview) => {
+ previews.delete(preview.topicId);
+ previews.set(preview.topicId, { fetchedAt: Date.now(), preview });
+ while (previews.size > TOPIC_PREVIEW_MAX_ENTRIES) {
+ const oldest = previews.keys().next().value;
+ if (oldest === undefined) break;
+ previews.delete(oldest);
+ }
+};
+
+export const fetchTopicPreviews = async (params: {
+ agentId?: string | null;
+ groupId?: string | null;
+ topicIds: string[];
+}): Promise<TopicPreviewItem[]> => {
+ const requestedAt = ++generation;
+ try {
+ const items = await lambdaClient.message.getTopicPreviews.query({
+ agentId: params.agentId,
+ groupId: params.groupId,
+ topicIds: params.topicIds,
+ });
+ for (const item of items) {
+ recordAttempt(item.topicId);
+ if (item.status !== 'ok') continue;
+ // A local change landed while the request was out: the answer may predate it.
+ if ((invalidatedAt.get(item.topicId) ?? 0) > requestedAt) continue;
+ store(item);
+ }
+ return items;
+ } catch (error) {
+ log('Failed to fetch topic previews: %O', error);
+ for (const topicId of params.topicIds) recordAttempt(topicId);
+ return [];
+ }
+};
+
+export const hasTopicPreview = (topicId: string): boolean => {
+ const entry = previews.get(topicId);
+ if (!entry) return false;
+ if (isFresh(entry)) return true;
+ previews.delete(topicId);
+ return false;
+};
+
+export const hasRecentTopicPreviewAttempt = (topicId: string): boolean => {
+ const attemptedAt = attempts.get(topicId);
+ if (attemptedAt === undefined) return false;
+ if (Date.now() - attemptedAt <= TOPIC_PREVIEW_TTL_MS) return true;
+ attempts.delete(topicId);
+ return false;
+};
+
+const toTime = (value: Date | string | number) => new Date(value).getTime();
+
+export const getValidTopicPreview = (
+ topicId: string,
+ topic: { running?: boolean; topicUpdatedAt?: Date | string | number | null },
+): TopicPreview | undefined => {
+ const entry = previews.get(topicId);
+ if (!entry) return undefined;
+
+ const valid =
+ isFresh(entry) &&
+ !topic.running &&
+ topic.topicUpdatedAt != null &&
+ toTime(topic.topicUpdatedAt) === toTime(entry.preview.topicUpdatedAt);
+ if (valid) return entry.preview;
+
+ previews.delete(topicId);
+ return undefined;
+};
+
+export const invalidateTopicPreview = (topicId: string): void => {
+ invalidatedAt.set(topicId, ++generation);
+ previews.delete(topicId);
+ attempts.delete(topicId);
+};
+
+export const resetTopicPreviews = (): void => {
+ previews.clear();
+ attempts.clear();
+ invalidatedAt.clear();
+};
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.gatewayOptimistic.test.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.gatewayOptimistic.test.ts
index 64bc9c2ea9e..566f36c79e8 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.gatewayOptimistic.test.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.gatewayOptimistic.test.ts
@@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { lambdaClient } from '@/libs/trpc/client';
+import * as roundCursorPage from '@/services/message/roundCursorPage';
import { useChatStore } from '../../../../store';
import { messageMapKey } from '../../../../utils/messageMapKey';
@@ -404,6 +405,34 @@ describe('Client runtime approval cards', () => {
expect(result.current.executeClientAgent).not.toHaveBeenCalled();
});
+ it('reloads a partial head window before resuming the client runtime', async () => {
+ seedPendingTools(['tool-1']);
+ const { result } = renderHook(() => useChatStore());
+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(false);
+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined as any);
+ const order: string[] = [];
+ vi.spyOn(result.current, 'refreshMessages').mockImplementation(async () => {
+ order.push('refresh');
+ });
+ vi.spyOn(result.current, 'executeClientAgent').mockImplementation(async () => {
+ order.push('run');
+ return undefined as any;
+ });
+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({
+ context: {},
+ state: {},
+ } as any);
+ vi.spyOn(roundCursorPage, 'isPartialHeadWindow').mockImplementation(
+ (context) => context.topicId === topicId,
+ );
+
+ await act(async () => {
+ await result.current.approveToolCalling('tool-1', '');
+ });
+
+ expect(order).toEqual(['refresh', 'run']);
+ });
+
it('restores the pending card when persisting the rejection fails', async () => {
seedPendingTools(['tool-1']);
const { result } = setupClient();
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 11f2be5a49e..dd52575fe5a 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -30,7 +30,7 @@ import {
import { shareChatService } from '@/services/shareChat';
import { getAgentStoreState } from '@/store/agent';
import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
-import { displayMessageSelectors, topicSelectors } from '@/store/chat/selectors';
+import { topicSelectors } from '@/store/chat/selectors';
import {
type AgentRuntimeType,
selectRuntimeType,
@@ -49,6 +49,7 @@ import { userProfileSelectors } from '@/store/user/selectors';
import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';
import { type RunScope } from '../lifecycle/types';
+import { readClientRunMessages } from './ensureFullHistoryForClientRun';
import { createInterventionProjection } from './interventionProjection';
/**
@@ -917,7 +918,7 @@ export class ConversationControlActionImpl {
// 3. Get current messages for state construction using context
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
- const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
+ const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
const currentRequestMetadata = this.#getRequestMetadataFromMessageChain(
toolMessageId,
currentMessages,
@@ -1325,7 +1326,7 @@ export class ConversationControlActionImpl {
// the agent marketplace picker forks agents directly) β€” the LLM should see the
// tool result, not a fake user turn.
if (!shouldCreateUserMessage) {
- const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
+ const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
const requestMetadata = this.#getRequestMetadataFromMessageChain(
toolMessageId,
currentMessages,
@@ -1407,11 +1408,10 @@ export class ConversationControlActionImpl {
// optimisticCreateMessage above is another await round-trip after the earlier
// guard, and executeClientAgent would otherwise start a fresh child run that
// wasn't present when the cancellation propagated.
+ const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
if (this.#wasInterimOpStopped(operationId)) return;
// 3. Resume agent from user message (not tool re-execution)
- const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
-
const { state, context: initialContext } = this.#get().internal_createAgentState({
messages: currentMessages,
parentMessageId: userMsg.id,
@@ -1609,11 +1609,10 @@ export class ConversationControlActionImpl {
// optimisticCreateMessage above is another await round-trip after the guard
// before it, and executeClientAgent would otherwise start a fresh child run
// that wasn't present when the cancellation propagated.
+ const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
if (this.#wasInterimOpStopped(operationId)) return;
// 3. Resume agent from user message
- const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
-
const { state, context: initialContext } = this.#get().internal_createAgentState({
messages: currentMessages,
parentMessageId: userMsg.id,
@@ -2345,7 +2344,7 @@ export class ConversationControlActionImpl {
// Get current messages for state construction using context
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
- const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
+ const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
const requestMetadata = this.#getRequestMetadataFromMessageChain(messageId, currentMessages);
// Create agent state and context to continue from rejected tool message
diff --git a/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.test.ts b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.test.ts
new file mode 100644
index 00000000000..e59e3a94bcd
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.test.ts
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { isPartialHeadWindow } from '@/services/message/roundCursorPage';
+import { displayMessageSelectors } from '@/store/chat/selectors';
+import type { ChatStore } from '@/store/chat/store';
+
+import { readClientRunMessages } from './ensureFullHistoryForClientRun';
+
+vi.mock('@/services/message/roundCursorPage', () => ({ isPartialHeadWindow: vi.fn() }));
+vi.mock('@/store/chat/selectors', () => ({
+ displayMessageSelectors: { getDisplayMessagesByKey: vi.fn() },
+}));
+
+const context = { agentId: 'agt_1', scope: 'main', topicId: 'tpc_1' } as const;
+
+const setup = () => {
+ let messages = [{ id: 'msg_newest' }];
+ const store = {
+ refreshMessages: vi.fn(async () => {
+ messages = [{ id: 'msg_oldest' }, { id: 'msg_newest' }];
+ }),
+ } as unknown as ChatStore;
+ vi.mocked(displayMessageSelectors.getDisplayMessagesByKey).mockImplementation(
+ () => () => messages as any,
+ );
+ return { get: () => store, store };
+};
+
+describe('readClientRunMessages', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('reads the whole history once a partial head window has been re-read', async () => {
+ vi.mocked(isPartialHeadWindow).mockReturnValue(true);
+ const { get, store } = setup();
+
+ const messages = await readClientRunMessages(get, context, 'main_agt_1_tpc_1');
+
+ expect(store.refreshMessages).toHaveBeenCalledWith(context);
+ expect(messages.map((message) => message.id)).toEqual(['msg_oldest', 'msg_newest']);
+ expect(displayMessageSelectors.getDisplayMessagesByKey).toHaveBeenCalledWith(
+ 'main_agt_1_tpc_1',
+ );
+ });
+
+ it('reads the loaded messages as they are when the window is already complete', async () => {
+ vi.mocked(isPartialHeadWindow).mockReturnValue(false);
+ const { get, store } = setup();
+
+ const messages = await readClientRunMessages(get, context, 'main_agt_1_tpc_1');
+
+ expect(store.refreshMessages).not.toHaveBeenCalled();
+ expect(messages.map((message) => message.id)).toEqual(['msg_newest']);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.ts b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.ts
new file mode 100644
index 00000000000..ed593ae2983
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.ts
@@ -0,0 +1,29 @@
+import type { ConversationContext } from '@lobechat/types';
+
+import { isPartialHeadWindow } from '@/services/message/roundCursorPage';
+import { displayMessageSelectors } from '@/store/chat/selectors';
+import type { ChatStore } from '@/store/chat/store';
+
+// Returns whether the history was re-read, so callers re-select their message list.
+export const ensureFullHistoryForClientRun = async (
+ context: ConversationContext,
+ refreshMessages: (context: ConversationContext) => Promise<void>,
+): Promise<boolean> => {
+ if (!isPartialHeadWindow(context)) return false;
+
+ try {
+ await refreshMessages(context);
+ } catch (error) {
+ console.warn('[ensureFullHistoryForClientRun] Failed to reload a partial head window:', error);
+ }
+ return true;
+};
+
+export const readClientRunMessages = async (
+ get: () => ChatStore,
+ context: ConversationContext,
+ chatKey: string,
+) => {
+ await ensureFullHistoryForClientRun(context, get().refreshMessages);
+ return displayMessageSelectors.getDisplayMessagesByKey(chatKey)(get());
+};
diff --git a/src/store/chat/slices/message/actions/internals.topicPreview.test.ts b/src/store/chat/slices/message/actions/internals.topicPreview.test.ts
new file mode 100644
index 00000000000..73fd1dec951
--- /dev/null
+++ b/src/store/chat/slices/message/actions/internals.topicPreview.test.ts
@@ -0,0 +1,24 @@
+import { act } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { invalidateTopicPreview } from '@/services/message/topicPreview';
+import { useChatStore } from '@/store/chat';
+
+vi.mock('@/services/message/topicPreview', () => ({ invalidateTopicPreview: vi.fn() }));
+
+describe('internal_dispatchMessage', () => {
+ it("drops the topic's preview on a local message change", () => {
+ act(() => {
+ useChatStore.getState().internal_dispatchMessage(
+ {
+ id: 'msg_local',
+ type: 'createMessage',
+ value: { content: 'hi', role: 'user' },
+ },
+ { context: { agentId: 'agt_1', threadId: null, topicId: 'tpc_a' } },
+ );
+ });
+
+ expect(invalidateTopicPreview).toHaveBeenCalledWith('tpc_a');
+ });
+});
diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.ts
index d8a5129d10e..1a3551bea42 100644
--- a/src/store/chat/slices/message/actions/internals.ts
+++ b/src/store/chat/slices/message/actions/internals.ts
@@ -2,6 +2,7 @@ import { type ConversationContext, type TraceEventPayloads } from '@lobechat/typ
import debug from 'debug';
import isEqual from 'fast-deep-equal';
+import { invalidateTopicPreview } from '@/services/message/topicPreview';
import { traceService } from '@/services/trace';
import { type ChatStore } from '@/store/chat/store';
import { type StoreSetter } from '@/store/types';
@@ -62,6 +63,7 @@ export class MessageInternalsActionImpl {
);
const messagesKey = messageMapKey(ctx);
+ if (ctx.topicId) invalidateTopicPreview(ctx.topicId);
// Get raw messages from dbMessagesMap and apply reducer
const rawMessages = this.#get().dbMessagesMap[messagesKey] || [];
diff --git a/src/store/chat/slices/message/transcript/index.ts b/src/store/chat/slices/message/transcript/index.ts
index 74243fdbe65..452ad226453 100644
--- a/src/store/chat/slices/message/transcript/index.ts
+++ b/src/store/chat/slices/message/transcript/index.ts
@@ -1,10 +1,12 @@
import { type ChatTopic, type ConversationContext, type UIChatMessage } from '@lobechat/types';
import debug from 'debug';
-import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';
+import {
+ readConversationMessageListPage,
+ readEarlierConversationMessages,
+} from '@/helpers/conversationMessageRead';
import { createReplicaSlice, readReplicaStoredKeys } from '@/libs/replica';
import { lambdaClient } from '@/libs/trpc/client';
-import { messageService } from '@/services/message';
import {
getMessageListCacheIdentity,
getMessageListWindowOlderCursor,
@@ -339,7 +341,7 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
context: ConversationMessageParams,
cursor: NonNullable<ConversationMessagePage['nextCursor']>,
): Promise<ConversationMessageFetch> => {
- const page = await messageService.getEarlierMessages(
+ const page = await readEarlierConversationMessages(
{
agentId: context.agentId,
agentShareId: context.agentShareId,
diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.ts
index 2a73d698395..9de3cc4f6fd 100644
--- a/src/store/serverConfig/selectors.ts
+++ b/src/store/serverConfig/selectors.ts
@@ -12,6 +12,7 @@ export const serverConfigSelectors = {
enableChannels: (s: ServerConfigStore) => s.featureFlags.enableChannels === true,
enableDashboard: (s: ServerConfigStore) => s.featureFlags.enableDashboard === true,
enableGatewayMode: (s: ServerConfigStore) => s.serverConfig.enableGatewayMode || false,
+ enableTopicPreview: (s: ServerConfigStore) => s.featureFlags.enableTopicPreview === true,
enableLobehubSkill: (s: ServerConfigStore) => s.serverConfig.enableLobehubSkill || false,
enableMagicLink: (s: ServerConfigStore) => s.serverConfig.enableMagicLink || false,
enableMarketTrustedClient: (s: ServerConfigStore) =>