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(conversation): find in topic with Mod+F in the working sidebar (#21530)

LiJianbf0d41288c9a
diff --git a/apps/server/src/routers/lambda/__tests__/integration/message.searchInTopic.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/message.searchInTopic.integration.test.ts
new file mode 100644
index 00000000000..24189f20538
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/message.searchInTopic.integration.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { 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 { getFileAccessUrl: vi.fn().mockResolvedValue('mock-url') };
+ }),
+}));
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+describe('message.searchInTopic', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let otherUserId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ otherUserId = await createTestUser(serverDB);
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ await cleanupTestUser(serverDB, otherUserId);
+ });
+
+ it('returns the matches of a topic the caller can read', async () => {
+ const [topic] = await serverDB.insert(topics).values({ userId }).returning();
+ await serverDB.insert(messages).values([
+ { content: 'first question', id: 'find-u1', role: 'user', topicId: topic.id, userId },
+ { content: 'an answer', id: 'find-a1', role: 'assistant', topicId: topic.id, userId },
+ ]);
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const result = await caller.searchInTopic({ keyword: 'QUESTION', topicId: topic.id });
+
+ expect(result.map((match) => match.id)).toEqual(['find-u1']);
+ });
+
+ it('finds nothing in a topic that belongs to someone else', async () => {
+ const [topic] = await serverDB.insert(topics).values({ userId: otherUserId }).returning();
+ await serverDB.insert(messages).values({
+ content: 'private question',
+ role: 'user',
+ topicId: topic.id,
+ userId: otherUserId,
+ });
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ expect(await caller.searchInTopic({ keyword: 'question', topicId: topic.id })).toEqual([]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index a38e55312d3..fc8ef1e7be7 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -31,6 +31,7 @@ import {
assertCanUseMessageTargets,
assertCanUseTopicTargets,
assertCanViewMessageTargets,
+ assertCanViewTopicTargets,
} from './_helpers/conversationResourceGuard';
import { getMessagesPageSizeSchema } from './_helpers/getMessagesPageSize';
import { messagesByCursorInputSchema, readMessagesByCursor } from './_helpers/messagesByCursor';
@@ -679,6 +680,15 @@ export const messageRouter = router({
return ctx.messageModel.deleteMessagesBySession(null, input.topicId, input.groupId);
}),
+ /** Find-in-topic: literal keyword matches across a topic's whole history. */
+ searchInTopic: messageProcedure
+ .input(z.object({ keyword: z.string().max(200), topicId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ await assertCanViewTopicTargets(guardCtx(ctx), [input.topicId]);
+
+ return ctx.messageModel.searchInTopic(input);
+ }),
+
searchMessages: messageSearchProcedure
.input(z.object({ keywords: z.string() }))
.query(async ({ input, ctx }) => {
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index da773db1611..d5015f8270b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3527,6 +3527,19 @@
"workingPanel.review.viewMode.unified": "Switch to unified view",
"workingPanel.review.wordWrap.disable": "Disable word wrap",
"workingPanel.review.wordWrap.enable": "Enable word wrap",
+ "workingPanel.search.empty": "No messages contain \"{{keyword}}\"",
+ "workingPanel.search.error": "Search failed. Try again.",
+ "workingPanel.search.hint": "Searches every message in this topic, including earlier history that is not loaded yet.",
+ "workingPanel.search.limitReached": "Showing the first {{count}} messages. Use a more specific keyword to narrow it down.",
+ "workingPanel.search.next": "Next match",
+ "workingPanel.search.placeholder": "Find in this topic",
+ "workingPanel.search.prev": "Previous match",
+ "workingPanel.search.resultCount_one": "{{count}} message",
+ "workingPanel.search.resultCount_other": "{{count}} messages",
+ "workingPanel.search.retry": "Retry",
+ "workingPanel.search.role.assistant": "Assistant",
+ "workingPanel.search.role.user": "You",
+ "workingPanel.search.title": "Search",
"workingPanel.skills.actions.comingSoon": "Coming soon",
"workingPanel.skills.actions.delete": "Delete",
"workingPanel.skills.actions.rename": "Rename",
diff --git a/locales/en-US/hotkey.json b/locales/en-US/hotkey.json
index b8a7ac0f173..baebdaf4838 100644
--- a/locales/en-US/hotkey.json
+++ b/locales/en-US/hotkey.json
@@ -17,6 +17,8 @@
"desktop.showApp.title": "Show/Hide Main Window",
"editMessage.desc": "Enter edit mode by holding Alt and double-clicking the message",
"editMessage.title": "Edit Message",
+ "findInTopic.desc": "Search every message of the current topic in the right panel",
+ "findInTopic.title": "Find in Topic",
"navigateToChat.desc": "Switch to the Chat tab and enter Lobe AI",
"navigateToChat.title": "Switch to Default Chat",
"nextTab.desc": "Cycle to the next browser-style tab in the Desktop app; wraps around to the first tab at the end",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 1f9369c69b6..3a681d822bc 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3527,6 +3527,19 @@
"workingPanel.review.viewMode.unified": "切换到合并视图",
"workingPanel.review.wordWrap.disable": "关闭自动换行",
"workingPanel.review.wordWrap.enable": "启用自动换行",
+ "workingPanel.search.empty": "没有消息包含「{{keyword}}」",
+ "workingPanel.search.error": "搜索失败,请重试",
+ "workingPanel.search.hint": "搜索当前话题的全部消息,包括还没加载出来的历史记录。",
+ "workingPanel.search.limitReached": "只显示前 {{count}} 条消息,换个更具体的关键词可以缩小范围。",
+ "workingPanel.search.next": "下一个",
+ "workingPanel.search.placeholder": "在当前话题中查找",
+ "workingPanel.search.prev": "上一个",
+ "workingPanel.search.resultCount_one": "{{count}} 条消息",
+ "workingPanel.search.resultCount_other": "{{count}} 条消息",
+ "workingPanel.search.retry": "重试",
+ "workingPanel.search.role.assistant": "助理",
+ "workingPanel.search.role.user": "你",
+ "workingPanel.search.title": "搜索",
"workingPanel.skills.actions.comingSoon": "即将支持",
"workingPanel.skills.actions.delete": "删除",
"workingPanel.skills.actions.rename": "重命名",
diff --git a/locales/zh-CN/hotkey.json b/locales/zh-CN/hotkey.json
index 003e2d9b268..ac8035cc0f0 100644
--- a/locales/zh-CN/hotkey.json
+++ b/locales/zh-CN/hotkey.json
@@ -17,6 +17,8 @@
"desktop.showApp.title": "显示/隐藏主窗口",
"editMessage.desc": "通过按住 Alt 并双击消息进入编辑模式",
"editMessage.title": "编辑消息",
+ "findInTopic.desc": "在右侧面板中搜索当前话题的所有消息",
+ "findInTopic.title": "在话题中查找",
"navigateToChat.desc": "切换至会话标签并进入Lobe AI",
"navigateToChat.title": "切换至默认会话",
"nextTab.desc": "在桌面端标签页之间循环切换,到达末尾后跳回第一个标签页",
diff --git a/packages/const/src/hotkeys.ts b/packages/const/src/hotkeys.ts
index 84326d58523..882836d0ff2 100644
--- a/packages/const/src/hotkeys.ts
+++ b/packages/const/src/hotkeys.ts
@@ -45,6 +45,7 @@ export const HotkeyEnum = {
DeleteAndRegenerateMessage: 'deleteAndRegenerateMessage',
DeleteLastMessage: 'deleteLastMessage',
EditMessage: 'editMessage',
+ FindInTopic: 'findInTopic',
NavigateToChat: 'navigateToChat',
NextTab: 'nextTab',
OpenChatSettings: 'openChatSettings',
@@ -142,6 +143,12 @@ export const HOTKEYS_REGISTRATION: HotkeyRegistration = [
scopes: [HotkeyScopeEnum.Global],
},
// Chat
+ {
+ group: HotkeyGroupEnum.Conversation,
+ id: HotkeyEnum.FindInTopic,
+ keys: combineKeys([KeyEnum.Mod, 'f']),
+ scopes: [HotkeyScopeEnum.Chat],
+ },
{
group: HotkeyGroupEnum.Conversation,
id: HotkeyEnum.ToggleTerminalPanel,
diff --git a/packages/const/src/message.ts b/packages/const/src/message.ts
index 1c195c3ab5e..8b89c209f2d 100644
--- a/packages/const/src/message.ts
+++ b/packages/const/src/message.ts
@@ -9,3 +9,6 @@ export const MESSAGE_WELCOME_GUIDE_ID = 'welcome';
export const THREAD_DRAFT_ID = '__THREAD_DRAFT_ID__';
export const MESSAGE_FLAGGED_THINKING = 'FLAGGED_THINKING';
+
+/** Upper bound of one find-in-topic read; the result list says when it is reached. */
+export const TOPIC_MESSAGE_SEARCH_LIMIT = 200;
diff --git a/packages/database/src/models/__tests__/messages/message.searchInTopic.test.ts b/packages/database/src/models/__tests__/messages/message.searchInTopic.test.ts
new file mode 100644
index 00000000000..b65179daeed
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.searchInTopic.test.ts
@@ -0,0 +1,139 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messages, threads, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'message-search-in-topic-test';
+const otherUserId = 'message-search-in-topic-test-other';
+const messageModel = new MessageModel(serverDB, userId);
+
+const at = (minute: number) => new Date(Date.UTC(2026, 0, 1, 0, minute));
+
+beforeEach(async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.delete(users).where(eq(users.id, userId));
+ await trx.delete(users).where(eq(users.id, otherUserId));
+ await trx.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await trx.insert(topics).values([
+ { id: 'topic-a', userId },
+ { id: 'topic-b', userId },
+ { id: 'topic-other', userId: otherUserId },
+ ]);
+ await trx.insert(threads).values({
+ id: 'thread-a',
+ topicId: 'topic-a',
+ type: 'standalone',
+ userId,
+ });
+ await trx.insert(messages).values([
+ {
+ content: 'How do I deploy?',
+ createdAt: at(1),
+ id: 'm1',
+ role: 'user',
+ topicId: 'topic-a',
+ userId,
+ },
+ {
+ content: 'Run `bun deploy`, then DEPLOY again.',
+ createdAt: at(2),
+ id: 'm2',
+ role: 'assistant',
+ topicId: 'topic-a',
+ userId,
+ },
+ {
+ content: 'deploy tool output',
+ createdAt: at(3),
+ id: 'm3',
+ role: 'tool',
+ topicId: 'topic-a',
+ userId,
+ },
+ {
+ content: 'deploy inside a thread',
+ createdAt: at(4),
+ id: 'm4',
+ role: 'user',
+ threadId: 'thread-a',
+ topicId: 'topic-a',
+ userId,
+ },
+ {
+ content: 'deploy elsewhere',
+ createdAt: at(5),
+ id: 'm5',
+ role: 'user',
+ topicId: 'topic-b',
+ userId,
+ },
+ {
+ content: '100% done_now',
+ createdAt: at(6),
+ id: 'm6',
+ role: 'user',
+ topicId: 'topic-a',
+ userId,
+ },
+ {
+ content: '100x doneXnow',
+ createdAt: at(7),
+ id: 'm7',
+ role: 'user',
+ topicId: 'topic-a',
+ userId,
+ },
+ {
+ content: 'deploy by someone else',
+ createdAt: at(8),
+ id: 'm8',
+ role: 'user',
+ topicId: 'topic-other',
+ userId: otherUserId,
+ },
+ ]);
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('MessageModel.searchInTopic', () => {
+ it('finds case-insensitive mainline matches of one topic, oldest first', async () => {
+ const result = await messageModel.searchInTopic({ keyword: 'Deploy', topicId: 'topic-a' });
+
+ expect(result.map(({ id, matchCount, role }) => ({ id, matchCount, role }))).toEqual([
+ { id: 'm1', matchCount: 1, role: 'user' },
+ { id: 'm2', matchCount: 2, role: 'assistant' },
+ ]);
+ expect(result[1].snippet).toBe('Run `bun deploy`, then DEPLOY again.');
+ });
+
+ it('matches LIKE metacharacters literally', async () => {
+ expect(
+ (await messageModel.searchInTopic({ keyword: '0% done_', topicId: 'topic-a' })).map(
+ (match) => match.id,
+ ),
+ ).toEqual(['m6']);
+ });
+
+ it('never reads another user topic', async () => {
+ expect(await messageModel.searchInTopic({ keyword: 'deploy', topicId: 'topic-other' })).toEqual(
+ [],
+ );
+ });
+
+ it('returns nothing for a blank keyword and honors the limit', async () => {
+ expect(await messageModel.searchInTopic({ keyword: ' ', topicId: 'topic-a' })).toEqual([]);
+ expect(
+ await messageModel.searchInTopic({ keyword: 'deploy', limit: 1, topicId: 'topic-a' }),
+ ).toHaveLength(1);
+ });
+});
diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.ts
index 633dd02e095..81debe12000 100644
--- a/packages/database/src/models/message/index.ts
+++ b/packages/database/src/models/message/index.ts
@@ -39,6 +39,7 @@ export class MessageModel {
findMessageQueriesById: MessageLookupQueries['findMessageQueriesById'];
queryBySessionId: MessageLookupQueries['queryBySessionId'];
queryByKeyword: MessageLookupQueries['queryByKeyword'];
+ searchInTopic: MessageLookupQueries['searchInTopic'];
queryByIds: MessageByIdsQueries['queryByIds'];
@@ -150,6 +151,7 @@ export class MessageModel {
this.findMessageQueriesById = lookups.findMessageQueriesById;
this.queryBySessionId = lookups.queryBySessionId;
this.queryByKeyword = lookups.queryByKeyword;
+ this.searchInTopic = lookups.searchInTopic;
this.queryByIds = byIds.queryByIds;
this.queryWithWhere = page.queryWithWhere;
this.queryLastUserMessageByTopics = conversation.queryLastUserMessageByTopics;
diff --git a/packages/database/src/models/message/lookup.ts b/packages/database/src/models/message/lookup.ts
index 5d362353ce3..bda2655064d 100644
--- a/packages/database/src/models/message/lookup.ts
+++ b/packages/database/src/models/message/lookup.ts
@@ -1,7 +1,8 @@
-import type { DBMessageItem, IThreadType } from '@lobechat/types';
+import { TOPIC_MESSAGE_SEARCH_LIMIT } from '@lobechat/const';
+import type { DBMessageItem, IThreadType, TopicMessageSearchMatch } from '@lobechat/types';
import { ThreadType } from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
-import { and, asc, desc, eq, inArray, isNull, lte, not, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, inArray, isNull, lte, ne, not, or, sql } from 'drizzle-orm';
import {
agentsToSessions,
@@ -13,10 +14,12 @@ import {
} from '../../schemas';
import { sanitizeBm25Query } from '../../utils/bm25';
import { inJsonStringArray } from '../../utils/inJsonStringArray';
+import { ilikeContains } from '../../utils/like';
import { searchableMessage } from '../../utils/searchableMessage';
import { notShareVisitorMessage } from '../../utils/shareVisitor';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { MessageScope } from './scope';
+import { buildMessageSearchSnippet } from './searchSnippet';
export class MessageLookupQueries extends MessageScope {
/**
@@ -293,6 +296,49 @@ export class MessageLookupQueries extends MessageScope {
return result as DBMessageItem[];
};
+ /**
+ * Literal, case-insensitive find over one topic's mainline (thread rows are
+ * left out), oldest first: the order the conversation reads in. Tool results
+ * are skipped because the conversation renders them as tool cards, not text.
+ */
+ searchInTopic = async ({
+ keyword,
+ limit = TOPIC_MESSAGE_SEARCH_LIMIT,
+ topicId,
+ }: {
+ keyword: string;
+ limit?: number;
+ topicId: string;
+ }): Promise<TopicMessageSearchMatch[]> => {
+ const needle = keyword.trim();
+ if (!needle) return [];
+
+ const rows = await this.db
+ .select({
+ content: messages.content,
+ createdAt: messages.createdAt,
+ id: messages.id,
+ role: messages.role,
+ })
+ .from(messages)
+ .where(
+ and(
+ this.ownership(),
+ eq(messages.topicId, topicId),
+ isNull(messages.threadId),
+ ne(messages.role, 'tool'),
+ ilikeContains(messages.content, needle),
+ ),
+ )
+ .orderBy(asc(messages.createdAt), asc(messages.id))
+ .limit(limit);
+
+ return rows.map(({ content, ...row }) => ({
+ ...row,
+ ...buildMessageSearchSnippet(content ?? '', needle),
+ }));
+ };
+
queryByKeyword = async (keyword: string) => {
if (!keyword.trim()) return [];
diff --git a/packages/database/src/models/message/searchSnippet.test.ts b/packages/database/src/models/message/searchSnippet.test.ts
new file mode 100644
index 00000000000..9ebd9c08dc4
--- /dev/null
+++ b/packages/database/src/models/message/searchSnippet.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildMessageSearchSnippet } from './searchSnippet';
+
+describe('buildMessageSearchSnippet', () => {
+ it('centers the excerpt on the first case-insensitive match and counts every match', () => {
+ const content = `${'a'.repeat(100)} Deploy the build, then deploy again ${'b'.repeat(100)}`;
+
+ const result = buildMessageSearchSnippet(content, 'deploy', 10);
+
+ expect(result.matchCount).toBe(2);
+ expect(result.snippet).toBe('…aaaaaaaaa Deploy the build…');
+ });
+
+ it('collapses whitespace so a multi-line message reads as one line', () => {
+ expect(buildMessageSearchSnippet('line one\n\n line two', 'two').snippet).toBe(
+ 'line one line two',
+ );
+ });
+
+ it('matches a keyword that spans collapsed whitespace', () => {
+ expect(buildMessageSearchSnippet('hello\n world', 'hello world').matchCount).toBe(1);
+ });
+
+ it('falls back to the head of the text when JavaScript cannot find the match', () => {
+ const result = buildMessageSearchSnippet('x'.repeat(300), 'missing', 10);
+
+ expect(result.matchCount).toBe(0);
+ expect(result.snippet).toBe(`${'x'.repeat(20)}…`);
+ });
+});
diff --git a/packages/database/src/models/message/searchSnippet.ts b/packages/database/src/models/message/searchSnippet.ts
new file mode 100644
index 00000000000..b01ed318b57
--- /dev/null
+++ b/packages/database/src/models/message/searchSnippet.ts
@@ -0,0 +1,42 @@
+const ELLIPSIS = '…';
+
+export interface MessageSearchSnippet {
+ matchCount: number;
+ snippet: string;
+}
+
+/**
+ * Excerpt of `content` around the first case-insensitive occurrence of
+ * `keyword`, with whitespace collapsed so a multi-line message reads as one
+ * line in a result list. Falls back to the head of the text when the database
+ * matched a case fold JavaScript does not reproduce.
+ */
+export const buildMessageSearchSnippet = (
+ content: string,
+ keyword: string,
+ radius = 60,
+): MessageSearchSnippet => {
+ const text = content.replaceAll(/\s+/g, ' ').trim();
+ const needle = keyword.replaceAll(/\s+/g, ' ').trim().toLowerCase();
+ const haystack = text.toLowerCase();
+
+ let matchCount = 0;
+ if (needle) {
+ for (let index = haystack.indexOf(needle); index !== -1;) {
+ matchCount += 1;
+ index = haystack.indexOf(needle, index + needle.length);
+ }
+ }
+
+ const firstMatch = needle ? haystack.indexOf(needle) : -1;
+ const start = Math.max(0, (firstMatch === -1 ? 0 : firstMatch) - radius);
+ const end = Math.min(
+ text.length,
+ (firstMatch === -1 ? 0 : firstMatch + needle.length) + radius * (firstMatch === -1 ? 2 : 1),
+ );
+
+ return {
+ matchCount,
+ snippet: `${start > 0 ? ELLIPSIS : ''}${text.slice(start, end)}${end < text.length ? ELLIPSIS : ''}`,
+ };
+};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 9b2e3faf5d0..4295551d954 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3813,6 +3813,21 @@ export default {
'workingPanel.files.showInReview': 'Show in Review',
'workingPanel.files.showInSystem': 'Reveal in Folder',
'workingPanel.files.title': 'Files',
+ 'workingPanel.search.empty': 'No messages contain "{{keyword}}"',
+ 'workingPanel.search.error': 'Search failed. Try again.',
+ 'workingPanel.search.hint':
+ 'Searches every message in this topic, including earlier history that is not loaded yet.',
+ 'workingPanel.search.limitReached':
+ 'Showing the first {{count}} messages. Use a more specific keyword to narrow it down.',
+ 'workingPanel.search.next': 'Next match',
+ 'workingPanel.search.placeholder': 'Find in this topic',
+ 'workingPanel.search.prev': 'Previous match',
+ 'workingPanel.search.resultCount_one': '{{count}} message',
+ 'workingPanel.search.resultCount_other': '{{count}} messages',
+ 'workingPanel.search.retry': 'Retry',
+ 'workingPanel.search.role.assistant': 'Assistant',
+ 'workingPanel.search.role.user': 'You',
+ 'workingPanel.search.title': 'Search',
'workingPanel.files.truncatedNotice':
'Some expanded folders are too large to list fully — only the first entries are shown',
'workingPanel.files.views.changes': 'Git Changes',
diff --git a/packages/locales/src/default/hotkey.ts b/packages/locales/src/default/hotkey.ts
index 28c15821b30..9a336ce3f27 100644
--- a/packages/locales/src/default/hotkey.ts
+++ b/packages/locales/src/default/hotkey.ts
@@ -17,6 +17,8 @@ export default {
'desktop.showApp.title': 'Show/Hide Main Window',
'editMessage.desc': 'Enter edit mode by holding Alt and double-clicking the message',
'editMessage.title': 'Edit Message',
+ 'findInTopic.desc': 'Search every message of the current topic in the right panel',
+ 'findInTopic.title': 'Find in Topic',
'navigateToChat.desc': 'Switch to the Chat tab and enter Lobe AI',
'navigateToChat.title': 'Switch to Default Chat',
'nextTab.desc':
diff --git a/packages/types/src/hotkey.ts b/packages/types/src/hotkey.ts
index 0031b09295e..2c9262c55a3 100644
--- a/packages/types/src/hotkey.ts
+++ b/packages/types/src/hotkey.ts
@@ -4,6 +4,7 @@ export type HotkeyId =
| 'deleteAndRegenerateMessage'
| 'deleteLastMessage'
| 'editMessage'
+ | 'findInTopic'
| 'navigateToChat'
| 'nextTab'
| 'openChatSettings'
diff --git a/packages/types/src/message/common/index.ts b/packages/types/src/message/common/index.ts
index e4bed9949c4..67dd7f42b48 100644
--- a/packages/types/src/message/common/index.ts
+++ b/packages/types/src/message/common/index.ts
@@ -6,4 +6,5 @@ export * from './messageGroup';
export * from './metadata';
export * from './pageSelection';
export * from './tools';
+export * from './topicSearch';
export * from './translate';
diff --git a/packages/types/src/message/common/topicSearch.ts b/packages/types/src/message/common/topicSearch.ts
new file mode 100644
index 00000000000..e86ea48ab14
--- /dev/null
+++ b/packages/types/src/message/common/topicSearch.ts
@@ -0,0 +1,10 @@
+/** One message of a topic whose text contains the searched keyword. */
+export interface TopicMessageSearchMatch {
+ createdAt: Date;
+ id: string;
+ /** Occurrences of the keyword in the message content. */
+ matchCount: number;
+ role: string;
+ /** Whitespace-collapsed excerpt around the first occurrence. */
+ snippet: string;
+}
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index f423391d396..30f7f81552c 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -27,6 +27,7 @@ import {
useConversationStoreApi,
virtuaListSelectors,
} from '../../store';
+import { VLIST_CLASS_NAME } from '../constants';
import {
CONVERSATION_SPACER_TRANSITION_MS,
useConversationScroll,
@@ -57,7 +58,6 @@ const CONVERSATION_HEADER_ID = '__conversation_header__';
// that talk to virtua directly) work in MESSAGE index space; this offset
// translates at the virtua boundary.
const LEADING_ROWS = 1;
-const VLIST_CLASS_NAME = 'conversation-vlist';
const USER_SCROLL_INTENT_TTL_MS = 500;
const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']);
diff --git a/src/features/Conversation/ChatList/constants.ts b/src/features/Conversation/ChatList/constants.ts
new file mode 100644
index 00000000000..f3531752dea
--- /dev/null
+++ b/src/features/Conversation/ChatList/constants.ts
@@ -0,0 +1,2 @@
+/** Class of the virtual list that renders a conversation's rows. */
+export const VLIST_CLASS_NAME = 'conversation-vlist';
diff --git a/src/features/Conversation/ChatList/hooks/useDeepLinkBranchActivation.test.ts b/src/features/Conversation/ChatList/hooks/useDeepLinkBranchActivation.test.ts
new file mode 100644
index 00000000000..3e000c7c94c
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useDeepLinkBranchActivation.test.ts
@@ -0,0 +1,48 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useDeepLinkBranchActivation } from './useDeepLinkBranchActivation';
+
+const messages = [
+ { id: 'u1', metadata: { activeBranchIndex: 1 }, role: 'user' },
+ { id: 'a1', parentId: 'u1', role: 'assistant' },
+ { id: 'a2', parentId: 'u1', role: 'assistant' },
+] as UIChatMessage[];
+
+const setup = (props: { navigationKey?: string; resolved?: boolean; targetId?: string }) => {
+ const switchMessageBranch = vi.fn().mockResolvedValue(undefined);
+ const initialProps = {
+ deepLink: props.targetId
+ ? { id: props.targetId, navigationKey: props.navigationKey ?? 'k1' }
+ : undefined,
+ messages,
+ resolved: props.resolved ?? false,
+ switchMessageBranch,
+ };
+ const hook = renderHook((current) => useDeepLinkBranchActivation(current), { initialProps });
+ return { ...hook, initialProps, switchMessageBranch };
+};
+
+describe('useDeepLinkBranchActivation', () => {
+ it('switches to the inactive branch holding a loaded target, once per navigation', async () => {
+ const { initialProps, rerender, result, switchMessageBranch } = setup({ targetId: 'a1' });
+
+ expect(result.current).toBe(true);
+ await waitFor(() => expect(switchMessageBranch).toHaveBeenCalledWith('a1', 0));
+
+ rerender({ ...initialProps, messages: [...messages] });
+ expect(switchMessageBranch).toHaveBeenCalledTimes(1);
+
+ rerender({ ...initialProps, deepLink: { id: 'a1', navigationKey: 'k2' } });
+ await waitFor(() => expect(switchMessageBranch).toHaveBeenCalledTimes(2));
+ });
+
+ it('leaves branches alone when the target already renders or is not loaded', () => {
+ expect(setup({ resolved: true, targetId: 'a1' }).switchMessageBranch).not.toHaveBeenCalled();
+
+ const unloaded = setup({ targetId: 'older' });
+ expect(unloaded.result.current).toBe(false);
+ expect(unloaded.switchMessageBranch).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useDeepLinkBranchActivation.ts b/src/features/Conversation/ChatList/hooks/useDeepLinkBranchActivation.ts
new file mode 100644
index 00000000000..a7a088ecd69
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useDeepLinkBranchActivation.ts
@@ -0,0 +1,44 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { useEffect, useRef } from 'react';
+
+import { findBranchSwitchesToMessage } from '../utils/deepLinkBranch';
+import type { MessageDeepLink } from '../utils/messageDeepLink';
+
+interface UseDeepLinkBranchActivationOptions {
+ deepLink?: MessageDeepLink;
+ /** The conversation's loaded rows, every branch included. */
+ messages: UIChatMessage[];
+ /** The target already renders on the displayed path. */
+ resolved: boolean;
+ switchMessageBranch: (messageId: string, branchIndex: number) => Promise<void>;
+}
+
+/**
+ * When a deep-linked message is loaded but sits on a branch the user moved
+ * away from, switch each fork on its path once per navigation so the
+ * conversation renders it and the deep link can scroll there. Returns whether
+ * the target row is loaded, which also tells history backfill to stop.
+ */
+export const useDeepLinkBranchActivation = ({
+ deepLink,
+ messages,
+ resolved,
+ switchMessageBranch,
+}: UseDeepLinkBranchActivationOptions) => {
+ const handledKeyRef = useRef<string | undefined>(undefined);
+ const targetLoaded = !!deepLink && messages.some((message) => message.id === deepLink.id);
+
+ useEffect(() => {
+ if (!deepLink || resolved || !targetLoaded) return;
+ if (handledKeyRef.current === deepLink.navigationKey) return;
+ handledKeyRef.current = deepLink.navigationKey;
+
+ const switches = findBranchSwitchesToMessage(messages, deepLink.id);
+ void (async () => {
+ for (const { branchIndex, messageId } of switches)
+ await switchMessageBranch(messageId, branchIndex);
+ })();
+ }, [deepLink, messages, resolved, switchMessageBranch, targetLoaded]);
+
+ return targetLoaded;
+};
diff --git a/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.test.ts b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.test.ts
new file mode 100644
index 00000000000..31e45bb3751
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.test.ts
@@ -0,0 +1,61 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ MAX_DEEP_LINK_BACKFILL_PAGES,
+ useDeepLinkHistoryBackfill,
+} from './useDeepLinkHistoryBackfill';
+
+const setup = (initial: {
+ deepLinkKey?: string;
+ loadedCount?: number;
+ ready?: boolean;
+ resolved?: boolean;
+}) => {
+ const loadEarlierMessages = vi.fn().mockResolvedValue(undefined);
+ const props = { loadedCount: 10, ready: true, resolved: false, ...initial };
+ const hook = renderHook(
+ (current: typeof props) => useDeepLinkHistoryBackfill({ ...current, loadEarlierMessages }),
+ { initialProps: props },
+ );
+
+ return { ...hook, loadEarlierMessages, props };
+};
+
+describe('useDeepLinkHistoryBackfill', () => {
+ it('loads one older page per settled page until the target is loaded', () => {
+ const { loadEarlierMessages, props, rerender } = setup({ deepLinkKey: 'k1' });
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(1);
+
+ rerender({ ...props, loadedCount: 20 });
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(2);
+
+ rerender({ ...props, loadedCount: 30, resolved: true });
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops once a page adds no rows', () => {
+ const { loadEarlierMessages, props, rerender } = setup({ deepLinkKey: 'k1' });
+
+ rerender({ ...props, ready: false });
+ rerender({ ...props });
+
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it('does nothing without a pending deep link or before the first page settles', () => {
+ expect(setup({}).loadEarlierMessages).not.toHaveBeenCalled();
+ expect(setup({ deepLinkKey: 'k1', ready: false }).loadEarlierMessages).not.toHaveBeenCalled();
+ expect(setup({ deepLinkKey: 'k1', resolved: true }).loadEarlierMessages).not.toHaveBeenCalled();
+ });
+
+ it('starts over for a new navigation and caps the pages per deep link', () => {
+ const { loadEarlierMessages, props, rerender } = setup({ deepLinkKey: 'k1' });
+ for (let page = 1; page <= MAX_DEEP_LINK_BACKFILL_PAGES + 5; page += 1)
+ rerender({ ...props, loadedCount: 10 + page });
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(MAX_DEEP_LINK_BACKFILL_PAGES);
+
+ rerender({ ...props, deepLinkKey: 'k2', loadedCount: 999 });
+ expect(loadEarlierMessages).toHaveBeenCalledTimes(MAX_DEEP_LINK_BACKFILL_PAGES + 1);
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.ts b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.ts
new file mode 100644
index 00000000000..e1c0fd924ef
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.ts
@@ -0,0 +1,45 @@
+import { useEffect, useRef } from 'react';
+
+/** Upper bound of older pages one deep link may pull in before giving up. */
+export const MAX_DEEP_LINK_BACKFILL_PAGES = 50;
+
+interface UseDeepLinkHistoryBackfillOptions {
+ /** Changes with every navigation to a deep link, even to the same message. */
+ deepLinkKey?: string;
+ loadEarlierMessages: () => Promise<void>;
+ /** Rows loaded so far; a page that adds none means the topic start was reached. */
+ loadedCount: number;
+ /** The first page has settled and the list pages backward. */
+ ready: boolean;
+ /** The target is among the loaded rows. */
+ resolved: boolean;
+}
+
+/**
+ * A deep link (a search hit, a `#<messageId>` URL) can point at a message older
+ * than the loaded window. Page older history in, one page per settled load,
+ * until the target is loaded, a page adds nothing, or the page budget is spent.
+ */
+export const useDeepLinkHistoryBackfill = ({
+ deepLinkKey,
+ loadedCount,
+ loadEarlierMessages,
+ ready,
+ resolved,
+}: UseDeepLinkHistoryBackfillOptions) => {
+ const progressRef = useRef({ key: undefined as string | undefined, lastCount: -1, pages: 0 });
+
+ useEffect(() => {
+ if (!deepLinkKey || resolved || !ready) return;
+
+ if (progressRef.current.key !== deepLinkKey)
+ progressRef.current = { key: deepLinkKey, lastCount: -1, pages: 0 };
+ const progress = progressRef.current;
+ if (progress.lastCount === loadedCount || progress.pages >= MAX_DEEP_LINK_BACKFILL_PAGES)
+ return;
+
+ progress.lastCount = loadedCount;
+ progress.pages += 1;
+ void loadEarlierMessages();
+ }, [deepLinkKey, loadedCount, loadEarlierMessages, ready, resolved]);
+};
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 646832b6c8e..5c6926cff39 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -35,6 +35,8 @@ import AgentSignalReceiptList from './components/AgentSignalReceiptList';
import { RefreshError } from './components/RefreshError';
import VirtualizedList from './components/VirtualizedList';
import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';
+import { useDeepLinkBranchActivation } from './hooks/useDeepLinkBranchActivation';
+import { useDeepLinkHistoryBackfill } from './hooks/useDeepLinkHistoryBackfill';
import { useForwardPagingFallback } from './hooks/useForwardPagingFallback';
import { useInitialRevalidation } from './hooks/useInitialRevalidation';
import { useMessageRefreshError } from './hooks/useMessageRefreshError';
@@ -288,6 +290,22 @@ const ChatList = memo<ChatListProps>(
[rowIds.length, rowById, defaultWorkflowExpandLevel, receiptsByAnchor],
);
const messagesInit = useConversationStore(dataSelectors.messagesInit);
+ const dbMessages = useConversationStore(dataSelectors.dbMessages);
+ const loadEarlierMessages = useConversationStore((s) => s.loadEarlierMessages);
+ const switchMessageBranch = useConversationStore((s) => s.switchMessageBranch);
+ const deepLinkTargetLoaded = useDeepLinkBranchActivation({
+ deepLink: messageDeepLink,
+ messages: dbMessages,
+ resolved: !!resolvedMessageDeepLink,
+ switchMessageBranch,
+ });
+ useDeepLinkHistoryBackfill({
+ deepLinkKey: messageDeepLink?.navigationKey,
+ loadedCount: dbMessages.length,
+ loadEarlierMessages,
+ ready: messagesInit && paging === 'backward',
+ resolved: !!resolvedMessageDeepLink || deepLinkTargetLoaded,
+ });
// When topicId is null (new conversation), show welcome directly without waiting for fetch
// because there's no server data to fetch - only local optimistic updates exist
diff --git a/src/features/Conversation/ChatList/utils/deepLinkBranch.test.ts b/src/features/Conversation/ChatList/utils/deepLinkBranch.test.ts
new file mode 100644
index 00000000000..37aff18a440
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/deepLinkBranch.test.ts
@@ -0,0 +1,71 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { findBranchSwitchesToMessage } from './deepLinkBranch';
+
+const msg = (
+ id: string,
+ parentId: string | null,
+ role: UIChatMessage['role'] = 'assistant',
+ activeBranchIndex?: number,
+) =>
+ ({
+ content: id,
+ id,
+ metadata: activeBranchIndex === undefined ? undefined : { activeBranchIndex },
+ parentId: parentId ?? undefined,
+ role,
+ }) as UIChatMessage;
+
+describe('findBranchSwitchesToMessage', () => {
+ it('activates the regenerated reply the target lives on', () => {
+ // u1 -> a1 (first answer) | a2 (regenerated, active) ; a1 -> u2 -> target
+ const messages = [
+ msg('u1', null, 'user', 1),
+ msg('a1', 'u1'),
+ msg('a2', 'u1'),
+ msg('u2', 'a1', 'user'),
+ msg('a3', 'u2'),
+ ];
+
+ expect(findBranchSwitchesToMessage(messages, 'a3')).toEqual([
+ { branchIndex: 0, messageId: 'a1' },
+ ]);
+ });
+
+ it('switches every inactive fork on the path, outermost first, and skips active ones', () => {
+ const messages = [
+ msg('u1', null, 'user', 1),
+ msg('a1', 'u1'),
+ msg('a2', 'u1'),
+ msg('u2', 'a1', 'user', 0),
+ msg('a3', 'u2'),
+ msg('a4', 'u2'),
+ msg('u3', 'a4', 'user'),
+ ];
+
+ expect(findBranchSwitchesToMessage(messages, 'u3')).toEqual([
+ { branchIndex: 0, messageId: 'a1' },
+ { branchIndex: 1, messageId: 'a4' },
+ ]);
+ });
+
+ it('does not count tool results as branches', () => {
+ const messages = [
+ msg('u1', null, 'user'),
+ msg('a1', 'u1', 'assistant', 0),
+ msg('t1', 'a1', 'tool'),
+ msg('a2', 'a1'),
+ ];
+
+ expect(findBranchSwitchesToMessage(messages, 'a2')).toEqual([]);
+ expect(findBranchSwitchesToMessage(messages, 't1')).toEqual([]);
+ });
+
+ it('returns nothing for a linear path or an unknown target', () => {
+ const messages = [msg('u1', null, 'user'), msg('a1', 'u1')];
+
+ expect(findBranchSwitchesToMessage(messages, 'a1')).toEqual([]);
+ expect(findBranchSwitchesToMessage(messages, 'missing')).toEqual([]);
+ });
+});
diff --git a/src/features/Conversation/ChatList/utils/deepLinkBranch.ts b/src/features/Conversation/ChatList/utils/deepLinkBranch.ts
new file mode 100644
index 00000000000..cc2e2bc39b0
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/deepLinkBranch.ts
@@ -0,0 +1,49 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+export interface BranchSwitch {
+ branchIndex: number;
+ /** The branch child to activate; `switchMessageBranch` stores the index on its parent. */
+ messageId: string;
+}
+
+/**
+ * The branch switches that put `targetId` on the displayed path, outermost
+ * fork first. A deep link can point at a regenerated reply the user moved away
+ * from: the row is loaded, but the conversation only renders each fork's
+ * active branch. Siblings are counted the way `conversation-flow` counts
+ * persisted branch indexes: non-tool children of the parent, in loaded order.
+ */
+export const findBranchSwitchesToMessage = (
+ messages: UIChatMessage[],
+ targetId: string,
+): BranchSwitch[] => {
+ const byId = new Map(messages.map((message) => [message.id, message]));
+ const branchIdsByParent = new Map<string, string[]>();
+ for (const message of messages) {
+ if (!message.parentId || message.role === 'tool') continue;
+ const siblings = branchIdsByParent.get(message.parentId);
+ if (siblings) siblings.push(message.id);
+ else branchIdsByParent.set(message.parentId, [message.id]);
+ }
+
+ const switches: BranchSwitch[] = [];
+ const visited = new Set<string>();
+ for (let child = byId.get(targetId); child?.parentId && !visited.has(child.id);) {
+ visited.add(child.id);
+ const parent = byId.get(child.parentId);
+ if (!parent) break;
+
+ const branchIds = branchIdsByParent.get(parent.id) ?? [];
+ const branchIndex = branchIds.indexOf(child.id);
+ if (
+ branchIds.length > 1 &&
+ branchIndex !== -1 &&
+ parent.metadata?.activeBranchIndex !== branchIndex
+ )
+ switches.unshift({ branchIndex, messageId: child.id });
+
+ child = parent;
+ }
+
+ return switches;
+};
diff --git a/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.test.ts b/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.test.ts
new file mode 100644
index 00000000000..fa4f8494c83
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { findKeywordRanges } from './conversationHighlights';
+
+const render = (html: string) => {
+ const root = document.createElement('div');
+ root.innerHTML = html;
+ document.body.append(root);
+ return root;
+};
+
+describe('findKeywordRanges', () => {
+ it('finds every case-insensitive occurrence across text nodes', () => {
+ const root = render('<p>Deploy now</p><p>then <b>deploy</b> again</p>');
+
+ expect(findKeywordRanges(root, 'deploy').map((range) => range.toString())).toEqual([
+ 'Deploy',
+ 'deploy',
+ ]);
+ });
+
+ it('skips editable and form text', () => {
+ const root = render(
+ '<textarea>deploy</textarea><div contenteditable="true">deploy</div><span>deploy</span>',
+ );
+
+ expect(findKeywordRanges(root, 'deploy')).toHaveLength(1);
+ });
+
+ it('finds nothing for a blank keyword', () => {
+ expect(findKeywordRanges(render('<p>deploy</p>'), ' ')).toEqual([]);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.ts b/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.ts
new file mode 100644
index 00000000000..b03c35a1c56
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/conversationHighlights.ts
@@ -0,0 +1,70 @@
+/**
+ * Topic search paints its matches into the conversation through the CSS Custom
+ * Highlight API: the message list is virtualized and re-renders while it
+ * streams, so wrapping matches in mark nodes would mean owning that DOM. A
+ * highlight range owns no DOM and is simply rebuilt from the rendered rows.
+ */
+export const TOPIC_SEARCH_HIGHLIGHT = {
+ active: 'lobe-topic-search-active',
+ all: 'lobe-topic-search',
+} as const;
+
+const SKIPPED_TAGS = new Set(['INPUT', 'NOSCRIPT', 'SCRIPT', 'STYLE', 'TEXTAREA']);
+
+export const supportsHighlightApi = () =>
+ typeof CSS !== 'undefined' && 'highlights' in CSS && typeof Highlight !== 'undefined';
+
+/** Ranges of every case-insensitive `keyword` occurrence in the text under `root`. */
+export const findKeywordRanges = (root: Node, keyword: string): Range[] => {
+ const needle = keyword.trim().toLowerCase();
+ const document = root.ownerDocument;
+ if (!needle || !document) return [];
+
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
+ acceptNode: (node) => {
+ const parent = node.parentElement;
+ return !parent || SKIPPED_TAGS.has(parent.tagName) || parent.isContentEditable
+ ? NodeFilter.FILTER_REJECT
+ : NodeFilter.FILTER_ACCEPT;
+ },
+ });
+
+ const ranges: Range[] = [];
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const value = node.nodeValue ?? '';
+ const text = value.toLowerCase();
+ // A case fold that changes the length would shift every offset below.
+ if (text.length !== value.length) continue;
+
+ for (let index = text.indexOf(needle); index !== -1;) {
+ const range = document.createRange();
+ range.setStart(node, index);
+ range.setEnd(node, index + needle.length);
+ ranges.push(range);
+ index = text.indexOf(needle, index + needle.length);
+ }
+ }
+
+ return ranges;
+};
+
+const setRegistry = (name: string, ranges: Range[], priority: number) => {
+ if (ranges.length === 0) {
+ CSS.highlights.delete(name);
+ return;
+ }
+ const highlight = new Highlight(...ranges);
+ highlight.priority = priority;
+ CSS.highlights.set(name, highlight);
+};
+
+export const paintTopicSearchHighlights = (all: Range[], active: Range[]) => {
+ if (!supportsHighlightApi()) return;
+ setRegistry(TOPIC_SEARCH_HIGHLIGHT.all, all, 1);
+ setRegistry(TOPIC_SEARCH_HIGHLIGHT.active, active, 2);
+};
+
+export const clearTopicSearchHighlights = () => {
+ if (!supportsHighlightApi()) return;
+ for (const name of Object.values(TOPIC_SEARCH_HIGHLIGHT)) CSS.highlights.delete(name);
+};
diff --git a/src/features/Conversation/WorkingSidebar/Search/highlightSegments.test.ts b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.test.ts
new file mode 100644
index 00000000000..0230d959eb8
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { splitHighlightSegments } from './highlightSegments';
+
+describe('splitHighlightSegments', () => {
+ it('marks every case-insensitive occurrence and keeps the original casing', () => {
+ expect(splitHighlightSegments('Deploy, then deploy', 'DEPLOY')).toEqual([
+ { match: true, text: 'Deploy' },
+ { match: false, text: ', then ' },
+ { match: true, text: 'deploy' },
+ ]);
+ });
+
+ it('returns the text untouched for a blank keyword or no match', () => {
+ expect(splitHighlightSegments('hello', ' ')).toEqual([{ match: false, text: 'hello' }]);
+ expect(splitHighlightSegments('hello', 'bye')).toEqual([{ match: false, text: 'hello' }]);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Search/highlightSegments.ts b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.ts
new file mode 100644
index 00000000000..f4220f8afb9
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/highlightSegments.ts
@@ -0,0 +1,24 @@
+export interface HighlightSegment {
+ match: boolean;
+ text: string;
+}
+
+/** Splits `text` into plain and matching runs of a case-insensitive `keyword`. */
+export const splitHighlightSegments = (text: string, keyword: string): HighlightSegment[] => {
+ const needle = keyword.trim().toLowerCase();
+ const haystack = text.toLowerCase();
+ // A case fold that changes the length would shift every offset below.
+ if (!needle || haystack.length !== text.length) return [{ match: false, text }];
+
+ const segments: HighlightSegment[] = [];
+ let cursor = 0;
+ for (let index = haystack.indexOf(needle); index !== -1;) {
+ if (index > cursor) segments.push({ match: false, text: text.slice(cursor, index) });
+ segments.push({ match: true, text: text.slice(index, index + needle.length) });
+ cursor = index + needle.length;
+ index = haystack.indexOf(needle, cursor);
+ }
+ if (cursor < text.length) segments.push({ match: false, text: text.slice(cursor) });
+
+ return segments;
+};
diff --git a/src/features/Conversation/WorkingSidebar/Search/index.tsx b/src/features/Conversation/WorkingSidebar/Search/index.tsx
new file mode 100644
index 00000000000..1f129ec491e
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/index.tsx
@@ -0,0 +1,281 @@
+'use client';
+
+import { TOPIC_MESSAGE_SEARCH_LIMIT } from '@lobechat/const';
+import type { TopicMessageSearchMatch } from '@lobechat/types';
+import {
+ ActionIcon,
+ cssVar as lobeCssVar,
+ Flexbox,
+ Icon,
+ Input,
+ Skeleton,
+ Text,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useDebounce } from 'ahooks';
+import dayjs from 'dayjs';
+import { ChevronDownIcon, ChevronUpIcon, SearchIcon } from 'lucide-react';
+import type { KeyboardEvent } from 'react';
+import { memo, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+
+import { TOPIC_SEARCH_HIGHLIGHT } from './conversationHighlights';
+import { splitHighlightSegments } from './highlightSegments';
+import { useConversationHighlight } from './useConversationHighlight';
+import { useMatchNavigation } from './useMatchNavigation';
+import { useTopicSearch } from './useTopicSearch';
+
+const SEARCH_DEBOUNCE_MS = 250;
+
+// `::highlight()` is a document-level pseudo-element, so it cannot be a scoped
+// StyleX rule. React hoists and dedupes this sheet by its `href`.
+const HIGHLIGHT_SHEET = `
+::highlight(${TOPIC_SEARCH_HIGHLIGHT.all}) { background-color: ${lobeCssVar.colorWarningBgHover}; }
+::highlight(${TOPIC_SEARCH_HIGHLIGHT.active}) { background-color: ${lobeCssVar.colorWarningBorder}; }
+`;
+
+const styles = stylex.create({
+ header: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ paddingBlock: 8,
+ paddingInline: 12,
+ },
+ item: {
+ borderRadius: 6,
+ cursor: 'pointer',
+ paddingBlock: 6,
+ paddingInline: 8,
+ backgroundColor: {
+ ':hover': cssVar.colorFillTertiary,
+ 'default': 'transparent',
+ },
+ },
+ itemActive: {
+ backgroundColor: {
+ ':hover': cssVar.colorFillSecondary,
+ 'default': cssVar.colorFillSecondary,
+ },
+ },
+ list: {
+ flex: '1',
+ minHeight: 0,
+ overflowY: 'auto',
+ paddingBlock: 6,
+ paddingInline: 6,
+ },
+ mark: {
+ backgroundColor: cssVar.colorWarningBgHover,
+ borderRadius: 2,
+ color: 'inherit',
+ },
+ meta: {
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ },
+ position: {
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ fontVariantNumeric: 'tabular-nums',
+ whiteSpace: 'nowrap',
+ },
+ snippet: {
+ color: cssVar.colorText,
+ fontSize: 13,
+ lineHeight: 1.5,
+ overflowWrap: 'anywhere',
+ },
+});
+
+interface MatchItemProps {
+ active: boolean;
+ keyword: string;
+ label: string;
+ match: TopicMessageSearchMatch;
+ onSelect: (id: string) => void;
+}
+
+const MatchItem = memo<MatchItemProps>(({ active, keyword, label, match, onSelect }) => {
+ const ref = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (active) ref.current?.scrollIntoView({ block: 'nearest' });
+ }, [active]);
+
+ return (
+ <div
+ aria-selected={active}
+ ref={ref}
+ role={'option'}
+ {...stylex.props(styles.item, active && styles.itemActive)}
+ onClick={() => onSelect(match.id)}
+ >
+ <Flexbox horizontal gap={8} justify={'space-between'} {...stylex.props(styles.meta)}>
+ <span>{label}</span>
+ <span>{dayjs(match.createdAt).format('MM-DD HH:mm')}</span>
+ </Flexbox>
+ <div {...stylex.props(styles.snippet)}>
+ {splitHighlightSegments(match.snippet, keyword).map((segment, index) =>
+ segment.match ? (
+ <mark key={index} {...stylex.props(styles.mark)}>
+ {segment.text}
+ </mark>
+ ) : (
+ segment.text
+ ),
+ )}
+ </div>
+ </div>
+ );
+});
+
+MatchItem.displayName = 'TopicSearchMatchItem';
+
+interface TopicSearchPaneProps {
+ /** The pane is on screen: focus the input and paint matches into the conversation. */
+ active: boolean;
+ topicId: string;
+}
+
+/** Find-in-topic: searches the topic's whole history and jumps to a match in the conversation. */
+export const TopicSearchPane = memo<TopicSearchPaneProps>(({ active, topicId }) => {
+ const { t } = useTranslation('chat');
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [value, setValue] = useState('');
+ const keyword = useDebounce(value, { wait: SEARCH_DEBOUNCE_MS }).trim();
+ const { failed, isSearching, matches, retry } = useTopicSearch(topicId, keyword);
+ const matchIds = useMemo(() => matches.map((match) => match.id), [matches]);
+ const { activeId, activeIndex, select, step } = useMatchNavigation(matchIds);
+ const agentName = useAgentStore(agentSelectors.currentAgentDisplayName);
+ const focusRequest = useGlobalStore((s) =>
+ s.status.workingSidebarTabRequest?.tab === 'search'
+ ? s.status.workingSidebarTabRequest.nonce
+ : undefined,
+ );
+
+ useConversationHighlight({ activeMessageId: activeId, enabled: active, keyword });
+
+ // Mod+F lands here: focus and select, so typing replaces the last keyword.
+ useEffect(() => {
+ if (!active) return;
+ const timer = setTimeout(() => {
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ });
+ return () => clearTimeout(timer);
+ }, [active, focusRequest]);
+
+ const roleLabel = (role: string) =>
+ role === 'user'
+ ? t('workingPanel.search.role.user')
+ : agentName || t('workingPanel.search.role.assistant');
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') step(event.shiftKey ? -1 : 1);
+ else if (event.key === 'ArrowDown') step(1);
+ else if (event.key === 'ArrowUp') step(-1);
+ else if (event.key === 'Escape' && value) setValue('');
+ else return;
+
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ const renderBody = () => {
+ if (!keyword)
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('workingPanel.search.hint')}
+ </Text>
+ );
+ if (failed)
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('workingPanel.search.error')} <a onClick={retry}>{t('workingPanel.search.retry')}</a>
+ </Text>
+ );
+ if (isSearching && matches.length === 0) return <Skeleton.Text rows={4} />;
+ if (matches.length === 0)
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('workingPanel.search.empty', { keyword })}
+ </Text>
+ );
+
+ return (
+ <Flexbox gap={2} role={'listbox'}>
+ {matches.map((match) => (
+ <MatchItem
+ active={match.id === activeId}
+ key={match.id}
+ keyword={keyword}
+ label={roleLabel(match.role)}
+ match={match}
+ onSelect={select}
+ />
+ ))}
+ {matches.length >= TOPIC_MESSAGE_SEARCH_LIMIT && (
+ <Text fontSize={12} style={{ padding: 8 }} type={'secondary'}>
+ {t('workingPanel.search.limitReached', { count: TOPIC_MESSAGE_SEARCH_LIMIT })}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ };
+
+ return (
+ <Flexbox flex={1} style={{ minHeight: 0 }}>
+ <style href={'lobe-topic-search-highlight'} precedence={'default'}>
+ {HIGHLIGHT_SHEET}
+ </style>
+ <Flexbox gap={6} {...stylex.props(styles.header)}>
+ <Input
+ placeholder={t('workingPanel.search.placeholder')}
+ prefix={<Icon icon={SearchIcon} size={13} />}
+ ref={inputRef}
+ size={'small'}
+ value={value}
+ suffix={
+ <Flexbox horizontal align={'center'} gap={2}>
+ {matches.length > 0 && (
+ <span {...stylex.props(styles.position)}>
+ {activeIndex + 1}/{matches.length}
+ </span>
+ )}
+ <ActionIcon
+ disabled={matches.length === 0}
+ icon={ChevronUpIcon}
+ size={'small'}
+ title={t('workingPanel.search.prev')}
+ onClick={() => step(-1)}
+ />
+ <ActionIcon
+ disabled={matches.length === 0}
+ icon={ChevronDownIcon}
+ size={'small'}
+ title={t('workingPanel.search.next')}
+ onClick={() => step(1)}
+ />
+ </Flexbox>
+ }
+ onChange={(event) => setValue(event.target.value)}
+ onKeyDown={handleKeyDown}
+ />
+ {matches.length > 0 && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('workingPanel.search.resultCount', { count: matches.length })}
+ </Text>
+ )}
+ </Flexbox>
+ <div {...stylex.props(styles.list)}>{renderBody()}</div>
+ </Flexbox>
+ );
+});
+
+TopicSearchPane.displayName = 'TopicSearchPane';
diff --git a/src/features/Conversation/WorkingSidebar/Search/useConversationHighlight.ts b/src/features/Conversation/WorkingSidebar/Search/useConversationHighlight.ts
new file mode 100644
index 00000000000..648e705eb88
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/useConversationHighlight.ts
@@ -0,0 +1,59 @@
+import { useEffect } from 'react';
+
+import { VLIST_CLASS_NAME } from '../../ChatList/constants';
+import {
+ clearTopicSearchHighlights,
+ findKeywordRanges,
+ paintTopicSearchHighlights,
+ supportsHighlightApi,
+} from './conversationHighlights';
+
+const findMessageElement = (messageId: string) =>
+ document.getElementById(messageId) ??
+ document.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(messageId)}"]`);
+
+/**
+ * Marks the keyword in the rendered conversation rows while the search pane is
+ * visible, and repaints whenever rows mount, stream, or unmount.
+ */
+export const useConversationHighlight = ({
+ activeMessageId,
+ enabled,
+ keyword,
+}: {
+ activeMessageId?: string;
+ enabled: boolean;
+ keyword: string;
+}) => {
+ useEffect(() => {
+ if (!enabled || !keyword.trim() || !supportsHighlightApi()) return;
+
+ let frame: number | undefined;
+ const paint = () => {
+ frame = undefined;
+ const activeElement = activeMessageId ? findMessageElement(activeMessageId) : null;
+ const all: Range[] = [];
+ const active: Range[] = [];
+ for (const root of document.querySelectorAll(`.${VLIST_CLASS_NAME}`)) {
+ for (const range of findKeywordRanges(root, keyword)) {
+ all.push(range);
+ if (activeElement?.contains(range.startContainer)) active.push(range);
+ }
+ }
+ paintTopicSearchHighlights(all, active);
+ };
+ const schedule = () => {
+ frame ??= requestAnimationFrame(paint);
+ };
+
+ paint();
+ const observer = new MutationObserver(schedule);
+ observer.observe(document.body, { characterData: true, childList: true, subtree: true });
+
+ return () => {
+ observer.disconnect();
+ if (frame !== undefined) cancelAnimationFrame(frame);
+ clearTopicSearchHighlights();
+ };
+ }, [activeMessageId, enabled, keyword]);
+};
diff --git a/src/features/Conversation/WorkingSidebar/Search/useMatchNavigation.test.ts b/src/features/Conversation/WorkingSidebar/Search/useMatchNavigation.test.ts
new file mode 100644
index 00000000000..ee5d333f212
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/useMatchNavigation.test.ts
@@ -0,0 +1,52 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useMatchNavigation } from './useMatchNavigation';
+
+const navigate = vi.fn();
+
+vi.mock('react-router', () => ({
+ useLocation: () => ({ pathname: '/agent/a1/tpc_1', search: '?x=1' }),
+ useNavigate: () => navigate,
+}));
+
+describe('useMatchNavigation', () => {
+ beforeEach(() => {
+ navigate.mockReset();
+ });
+
+ it('starts at the first match going forward and at the last going back', () => {
+ const forward = renderHook(() => useMatchNavigation(['m1', 'm2', 'm3']));
+ act(() => forward.result.current.step(1));
+ expect(forward.result.current.activeId).toBe('m1');
+
+ const backward = renderHook(() => useMatchNavigation(['m1', 'm2', 'm3']));
+ act(() => backward.result.current.step(-1));
+ expect(backward.result.current.activeId).toBe('m3');
+ });
+
+ it('wraps around and jumps through the message deep link without a history entry', () => {
+ const { result } = renderHook(() => useMatchNavigation(['m1', 'm2']));
+
+ act(() => result.current.select('m2'));
+ act(() => result.current.step(1));
+
+ expect(result.current.activeIndex).toBe(0);
+ expect(navigate).toHaveBeenLastCalledWith(
+ { hash: 'm1', pathname: '/agent/a1/tpc_1', search: '?x=1' },
+ { replace: true },
+ );
+ });
+
+ it('forgets a match that is no longer in the results', () => {
+ const { rerender, result } = renderHook(({ ids }) => useMatchNavigation(ids), {
+ initialProps: { ids: ['m1', 'm2'] },
+ });
+
+ act(() => result.current.select('m2'));
+ rerender({ ids: ['m1'] });
+
+ expect(result.current.activeId).toBeUndefined();
+ expect(result.current.activeIndex).toBe(-1);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Search/useMatchNavigation.ts b/src/features/Conversation/WorkingSidebar/Search/useMatchNavigation.ts
new file mode 100644
index 00000000000..60a2406a64d
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/useMatchNavigation.ts
@@ -0,0 +1,34 @@
+import { useCallback, useState } from 'react';
+import { useLocation, useNavigate } from 'react-router';
+
+/**
+ * The match the user is on, and moving between matches. Jumping reuses the
+ * conversation's message deep link (`#<messageId>`), which also pages in
+ * history that is not loaded yet; `replace` keeps stepping through matches out
+ * of the back stack.
+ */
+export const useMatchNavigation = (matchIds: string[]) => {
+ const navigate = useNavigate();
+ const { pathname, search } = useLocation();
+ const [activeId, setActiveId] = useState<string>();
+ const activeIndex = activeId ? matchIds.indexOf(activeId) : -1;
+
+ const select = useCallback(
+ (id: string) => {
+ setActiveId(id);
+ navigate({ hash: encodeURIComponent(id), pathname, search }, { replace: true });
+ },
+ [navigate, pathname, search],
+ );
+
+ const step = useCallback(
+ (delta: 1 | -1) => {
+ if (matchIds.length === 0) return;
+ const from = activeIndex === -1 ? (delta === 1 ? -1 : 0) : activeIndex;
+ select(matchIds[(from + delta + matchIds.length) % matchIds.length]);
+ },
+ [activeIndex, matchIds, select],
+ );
+
+ return { activeId: activeIndex === -1 ? undefined : activeId, activeIndex, select, step };
+};
diff --git a/src/features/Conversation/WorkingSidebar/Search/useTopicSearch.test.ts b/src/features/Conversation/WorkingSidebar/Search/useTopicSearch.test.ts
new file mode 100644
index 00000000000..e6f300828c1
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/useTopicSearch.test.ts
@@ -0,0 +1,45 @@
+import type { TopicMessageSearchMatch } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { selectTopicSearchView } from './useTopicSearch';
+
+const match = (id: string) => ({ id }) as TopicMessageSearchMatch;
+const deploy = { keyword: 'deploy', matches: [match('m1'), match('m2')] };
+
+describe('selectTopicSearchView', () => {
+ it('lists the matches that answer the current keyword', () => {
+ expect(selectTopicSearchView({ data: deploy, query: 'deploy' })).toEqual({
+ failed: false,
+ isSearching: false,
+ matches: deploy.matches,
+ });
+ });
+
+ it('keeps the previous matches only while the new keyword is loading', () => {
+ expect(selectTopicSearchView({ data: deploy, query: 'release' })).toEqual({
+ failed: false,
+ isSearching: true,
+ matches: deploy.matches,
+ });
+ });
+
+ it('drops the previous matches and reports the failure when the new keyword errors', () => {
+ expect(
+ selectTopicSearchView({ data: deploy, error: new Error('offline'), query: 'release' }),
+ ).toEqual({ failed: true, isSearching: false, matches: [] });
+ });
+
+ it('keeps a successful result when only its revalidation failed', () => {
+ expect(
+ selectTopicSearchView({ data: deploy, error: new Error('offline'), query: 'deploy' }).matches,
+ ).toEqual(deploy.matches);
+ });
+
+ it('shows nothing without a keyword', () => {
+ expect(selectTopicSearchView({ data: deploy, query: '' })).toEqual({
+ failed: false,
+ isSearching: false,
+ matches: [],
+ });
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Search/useTopicSearch.ts b/src/features/Conversation/WorkingSidebar/Search/useTopicSearch.ts
new file mode 100644
index 00000000000..6ef3bba52da
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Search/useTopicSearch.ts
@@ -0,0 +1,59 @@
+import type { TopicMessageSearchMatch } from '@lobechat/types';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { messageService } from '@/services/message';
+
+const NO_MATCHES: TopicMessageSearchMatch[] = [];
+
+interface TopicSearchResult {
+ /** The keyword these matches answer; SWR may hand back an older keyword's result. */
+ keyword: string;
+ matches: TopicMessageSearchMatch[];
+}
+
+export interface TopicSearchView {
+ /** The search for the current keyword failed and no result answers it. */
+ failed: boolean;
+ /** A request for the current keyword is in flight. */
+ isSearching: boolean;
+ /** Matches to list: the current keyword's, or the previous ones while a new search loads. */
+ matches: TopicMessageSearchMatch[];
+}
+
+/**
+ * What the pane shows for `query`. A result kept from an earlier keyword only
+ * bridges the wait for the new one: once the new search fails it is dropped,
+ * so old matches never pose as answers to the keyword that errored.
+ */
+export const selectTopicSearchView = ({
+ data,
+ error,
+ query,
+}: {
+ data?: TopicSearchResult;
+ error?: unknown;
+ query: string;
+}): TopicSearchView => {
+ if (!query) return { failed: false, isSearching: false, matches: NO_MATCHES };
+
+ const current = data?.keyword === query ? data.matches : undefined;
+ if (current) return { failed: false, isSearching: false, matches: current };
+ if (error) return { failed: true, isSearching: false, matches: NO_MATCHES };
+
+ return { failed: false, isSearching: true, matches: data?.matches ?? NO_MATCHES };
+};
+
+/** Every message of `topicId` containing `keyword`, read from the server's full history. */
+export const useTopicSearch = (topicId: string | undefined, keyword: string) => {
+ const query = keyword.trim();
+ const { data, error, mutate } = useClientDataSWR<TopicSearchResult>(
+ topicId && query ? ['topicMessageSearch', topicId, query] : null,
+ async ([, id, text]: [string, string, string]) => ({
+ keyword: text,
+ matches: await messageService.searchInTopic({ keyword: text, topicId: id }),
+ }),
+ { keepPreviousData: true, revalidateOnFocus: false },
+ );
+
+ return { ...selectTopicSearchView({ data, error, query }), retry: () => mutate() };
+};
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
index 5167765b5fc..8d2b5cc9440 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
@@ -206,6 +206,12 @@ vi.mock('../ParamsSection', () => ({
},
}));
vi.mock('../WorksSection', () => ({ default: () => <div /> }));
+vi.mock('../Search', () => ({
+ TopicSearchPane: ({ topicId }: { topicId: string }) => (
+ <div data-testid="topic-search">{topicId}</div>
+ ),
+}));
+vi.mock('@/hooks/useHotkeys', () => ({ useFindInTopicHotkey: () => undefined }));
vi.mock('../Browser', () => ({
default: (props: (typeof browserPanes.current)[number]) => {
browserPanes.current.push(props);
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index cb557c85d6f..6d5cd5cfc78 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -1,4 +1,3 @@
-import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { getWorkingDirEffectivePath } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { ActionIcon, type DropdownItem, DropdownMenu, Flexbox, Icon, Skeleton } from '@lobehub/ui';
@@ -15,12 +14,10 @@ import {
MessageCircleIcon,
PanelRightCloseIcon,
PanelsTopLeftIcon,
- PinIcon,
- PinOffIcon,
PlusIcon,
+ SearchIcon,
Settings2Icon,
SquareTerminalIcon,
- XIcon,
} from 'lucide-react';
import { AnimatePresence } from 'motion/react';
import * as m from 'motion/react-m';
@@ -56,8 +53,8 @@ import { getWorkingDirectoryPathString } from '@/helpers/workingDirectoryPath';
import { useDeferredMount } from '@/hooks/useDeferredMount';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
+import { useFindInTopicHotkey } from '@/hooks/useHotkeys';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
-import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -92,7 +89,9 @@ import PullRequest from './PullRequest';
import { useLinkedPullRequest } from './PullRequest/useLinkedPullRequest';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
+import { TopicSearchPane } from './Search';
import { useSandboxFilesDirectory } from './useSandboxFilesDirectory';
+import { useTabContextMenuItems } from './useTabContextMenuItems';
import WorkspaceTab from './WorkspaceTab';
import WorksSection from './WorksSection';
@@ -425,6 +424,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
? currentPortalView.topicId
: undefined;
const isCurrentTopicComments = currentCommentTopicId === topicId;
+ const searchAvailable = !!topicId;
+ useFindInTopicHotkey(searchAvailable);
const tabDescriptors = useMemo<SidebarTabDescriptor[]>(
() => [
{ icon: SkillsIcon, key: 'skills', label: t('workingPanel.resources.filter.skills') },
@@ -441,6 +442,9 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
{ icon: GlobeIcon, key: 'web', label: t('workingPanel.resources.filter.web') },
]),
{ icon: BoxesIcon, key: 'works', label: t('workingPanel.works.title') },
+ ...(searchAvailable
+ ? [{ icon: SearchIcon, key: 'search', label: t('workingPanel.search.title') }]
+ : []),
...(commentsAvailable
? [{ icon: MessageCircleIcon, key: 'comments', label: t('topicComment.title') }]
: []),
@@ -486,6 +490,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
paramsAvailable,
pullRequest,
reviewAvailable,
+ searchAvailable,
t,
],
);
@@ -717,57 +722,14 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
) ?? availableTabs.get(tab),
)
.filter((tab): tab is SidebarTabDescriptor => Boolean(tab));
- const createTabContextMenuItems = useCallback(
- (tab: string, index: number): NativeContextMenuItem[] => {
- const pinned = pinnedTabsSet.has(tab);
- const leftTabs = openedTabs.slice(0, index);
- const rightTabs = openedTabs.slice(index + 1);
- const otherTabs = openedTabs.filter((item) => item !== tab);
- const hasClosable = (tabs: string[]) => tabs.some((item) => !pinnedTabsSet.has(item));
-
- return [
- ...(!isDynamicTab(tab)
- ? [
- {
- icon: pinned ? PinOffIcon : PinIcon,
- key: pinned ? 'unpin' : 'pin',
- label: t(pinned ? 'workingPanel.tabs.unpin' : 'workingPanel.tabs.pin'),
- onClick: () => (pinned ? unpinTab(tab) : pinTab(tab)),
- sfSymbol: (pinned ? 'pin.slash' : 'pin') satisfies SFSymbol,
- } as NativeContextMenuItem,
- { type: 'divider' as const },
- ]
- : []),
- {
- disabled: pinned,
- icon: XIcon,
- key: 'close',
- label: t('workingPanel.tabs.close'),
- onClick: () => closeTab(tab),
- },
- {
- disabled: !hasClosable(otherTabs),
- key: 'closeOthers',
- label: t('workingPanel.tabs.closeOthers'),
- onClick: () => closeTabs(otherTabs, tab),
- },
- { type: 'divider' },
- {
- disabled: !hasClosable(leftTabs),
- key: 'closeLeft',
- label: t('workingPanel.tabs.closeLeft'),
- onClick: () => closeTabs(leftTabs, tab),
- },
- {
- disabled: !hasClosable(rightTabs),
- key: 'closeRight',
- label: t('workingPanel.tabs.closeRight'),
- onClick: () => closeTabs(rightTabs, tab),
- },
- ];
- },
- [closeTab, closeTabs, openedTabs, pinTab, pinnedTabsSet, t, unpinTab],
- );
+ const createTabContextMenuItems = useTabContextMenuItems({
+ closeTab,
+ closeTabs,
+ openedTabs,
+ pinTab,
+ pinnedTabsSet,
+ unpinTab,
+ });
const tabsRef = useRef<HTMLDivElement>(null);
const pendingTabFocusRef = useRef<string | undefined>(undefined);
const pendingTabFocusTimeoutRef = useRef<number | undefined>(undefined);
@@ -909,6 +871,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
};
const workspaceGroup = group('workspace', t('workingPanel.openMenu.workspace'), [
+ 'search',
'review',
'pr',
'files',
@@ -1097,6 +1060,17 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
<TopicCommentsSidebar />
</Flexbox>
)}
+ {!!topicId && (
+ <Activity mode={showRightPanel && activeTab === 'search' ? 'visible' : 'hidden'}>
+ <Flexbox className={styles.pane} style={{ overflow: 'hidden' }}>
+ <TopicSearchPane
+ active={!!showRightPanel && activeTab === 'search'}
+ key={topicId}
+ topicId={topicId}
+ />
+ </Flexbox>
+ </Activity>
+ )}
{paramsAvailable && activeTab === 'params' && (
<Flexbox className={styles.pane}>
<Suspense
diff --git a/src/features/Conversation/WorkingSidebar/useTabContextMenuItems.ts b/src/features/Conversation/WorkingSidebar/useTabContextMenuItems.ts
new file mode 100644
index 00000000000..4706e1d1573
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/useTabContextMenuItems.ts
@@ -0,0 +1,81 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
+import { PinIcon, PinOffIcon, XIcon } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
+
+import { isDynamicTab } from './dynamicTabs';
+
+interface UseTabContextMenuItemsOptions {
+ closeTab: (tab: string) => void;
+ closeTabs: (tabs: string[], fallbackTab?: string) => void;
+ openedTabs: string[];
+ pinnedTabsSet: Set<string>;
+ pinTab: (tab: string) => void;
+ unpinTab: (tab: string) => void;
+}
+
+/** Builds the right-click menu (pin / close variants) of one working-sidebar tab. */
+export const useTabContextMenuItems = ({
+ closeTab,
+ closeTabs,
+ openedTabs,
+ pinTab,
+ pinnedTabsSet,
+ unpinTab,
+}: UseTabContextMenuItemsOptions) => {
+ const { t } = useTranslation('chat');
+
+ return useCallback(
+ (tab: string, index: number): NativeContextMenuItem[] => {
+ const pinned = pinnedTabsSet.has(tab);
+ const leftTabs = openedTabs.slice(0, index);
+ const rightTabs = openedTabs.slice(index + 1);
+ const otherTabs = openedTabs.filter((item) => item !== tab);
+ const hasClosable = (tabs: string[]) => tabs.some((item) => !pinnedTabsSet.has(item));
+
+ return [
+ ...(!isDynamicTab(tab)
+ ? [
+ {
+ icon: pinned ? PinOffIcon : PinIcon,
+ key: pinned ? 'unpin' : 'pin',
+ label: t(pinned ? 'workingPanel.tabs.unpin' : 'workingPanel.tabs.pin'),
+ onClick: () => (pinned ? unpinTab(tab) : pinTab(tab)),
+ sfSymbol: (pinned ? 'pin.slash' : 'pin') satisfies SFSymbol,
+ } as NativeContextMenuItem,
+ { type: 'divider' as const },
+ ]
+ : []),
+ {
+ disabled: pinned,
+ icon: XIcon,
+ key: 'close',
+ label: t('workingPanel.tabs.close'),
+ onClick: () => closeTab(tab),
+ },
+ {
+ disabled: !hasClosable(otherTabs),
+ key: 'closeOthers',
+ label: t('workingPanel.tabs.closeOthers'),
+ onClick: () => closeTabs(otherTabs, tab),
+ },
+ { type: 'divider' },
+ {
+ disabled: !hasClosable(leftTabs),
+ key: 'closeLeft',
+ label: t('workingPanel.tabs.closeLeft'),
+ onClick: () => closeTabs(leftTabs, tab),
+ },
+ {
+ disabled: !hasClosable(rightTabs),
+ key: 'closeRight',
+ label: t('workingPanel.tabs.closeRight'),
+ onClick: () => closeTabs(rightTabs, tab),
+ },
+ ];
+ },
+ [closeTab, closeTabs, openedTabs, pinTab, pinnedTabsSet, t, unpinTab],
+ );
+};
diff --git a/src/hooks/useHotkeys/chatScope.test.ts b/src/hooks/useHotkeys/chatScope.test.ts
index d60a225966d..4d0ac5f3574 100644
--- a/src/hooks/useHotkeys/chatScope.test.ts
+++ b/src/hooks/useHotkeys/chatScope.test.ts
@@ -5,10 +5,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { HOTKEYS_REGISTRATION } from '@/const/hotkeys';
-import { useToggleTerminalPanelHotkey } from './chatScope';
+import { useFindInTopicHotkey, useToggleTerminalPanelHotkey } from './chatScope';
const mocks = vi.hoisted(() => ({
hotkeyCallback: undefined as (() => void) | undefined,
+ openWorkingSidebar: vi.fn(),
toggleTerminalPanel: vi.fn(),
useHotkeyById: vi.fn(),
}));
@@ -19,8 +20,16 @@ vi.mock('@lobechat/const', async (importOriginal) => ({
}));
vi.mock('@/store/global', () => ({
- useGlobalStore: (selector: (state: { toggleTerminalPanel: () => void }) => unknown) =>
- selector({ toggleTerminalPanel: mocks.toggleTerminalPanel }),
+ useGlobalStore: (
+ selector: (state: {
+ openWorkingSidebar: (tab?: string) => void;
+ toggleTerminalPanel: () => void;
+ }) => unknown,
+ ) =>
+ selector({
+ openWorkingSidebar: mocks.openWorkingSidebar,
+ toggleTerminalPanel: mocks.toggleTerminalPanel,
+ }),
}));
vi.mock('./useHotkeyById', () => ({
@@ -78,3 +87,34 @@ describe('useToggleTerminalPanelHotkey', () => {
);
});
});
+
+describe('useFindInTopicHotkey', () => {
+ beforeEach(() => {
+ mocks.hotkeyCallback = undefined;
+ mocks.openWorkingSidebar.mockReset();
+ mocks.useHotkeyById.mockReset();
+ });
+
+ it('opens the search tab of the working sidebar', () => {
+ renderHook(() => useFindInTopicHotkey(true));
+
+ act(() => {
+ mocks.hotkeyCallback?.();
+ });
+
+ expect(mocks.useHotkeyById).toHaveBeenCalledWith(HotkeyEnum.FindInTopic, expect.any(Function), {
+ enableOnContentEditable: true,
+ enabled: true,
+ });
+ expect(mocks.openWorkingSidebar).toHaveBeenCalledWith('search');
+ });
+
+ it('takes over Mod+F in the chat scope', () => {
+ expect(HOTKEYS_REGISTRATION).toContainEqual({
+ group: HotkeyGroupEnum.Conversation,
+ id: HotkeyEnum.FindInTopic,
+ keys: 'mod+f',
+ scopes: [HotkeyScopeEnum.Chat],
+ });
+ });
+});
diff --git a/src/hooks/useHotkeys/chatScope.ts b/src/hooks/useHotkeys/chatScope.ts
index 96f9db75314..681e561e05d 100644
--- a/src/hooks/useHotkeys/chatScope.ts
+++ b/src/hooks/useHotkeys/chatScope.ts
@@ -36,6 +36,20 @@ export const useToggleTerminalPanelHotkey = (enabled: boolean = isDesktop) => {
});
};
+/**
+ * Replaces the browser's find, which cannot see the virtualized message list:
+ * the topic search in the working sidebar reads the whole history instead.
+ * Callers turn it on only once a topic exists to search.
+ */
+export const useFindInTopicHotkey = (enabled: boolean) => {
+ const openWorkingSidebar = useGlobalStore((s) => s.openWorkingSidebar);
+
+ return useHotkeyById(HotkeyEnum.FindInTopic, () => openWorkingSidebar('search'), {
+ enableOnContentEditable: true,
+ enabled,
+ });
+};
+
// Note: useRegenerateMessageHotkey has been moved to ConversationStore
// Note: useDeleteAndRegenerateMessageHotkey has been moved to ConversationStore
// Note: useDeleteLastMessageHotkey has been moved to ConversationStore
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 9f7af0b1d95..83380157cfb 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -10,6 +10,7 @@ import {
type MessageMetadata,
type MessagePluginItem,
type ModelRankItem,
+ type TopicMessageSearchMatch,
type UIChatMessage,
type UpdateMessageParams,
type UpdateMessageRAGParams,
@@ -271,6 +272,13 @@ export class MessageService {
return { messages: data as unknown as UIChatMessage[] };
};
+ searchInTopic = async (params: {
+ keyword: string;
+ topicId: string;
+ }): Promise<TopicMessageSearchMatch[]> => {
+ return lambdaClient.message.searchInTopic.query(params);
+ };
+
diagnoseTopic = async (params: { agentId?: string | null; topicId: string }) => {
return lambdaClient.message.diagnoseTopic.query(params);
};
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index a023438d4d5..41d80e5dcad 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -45,6 +45,7 @@ export type WorkingSidebarTab =
| 'overview'
| 'params'
| 'review'
+ | 'search'
| 'skills'
| 'web'
| (string & {});