🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(search): find files by their parsed text in Command K (#23779)
Innei3659778080b2
diff --git a/apps/server/src/services/ftsSearch/index.test.ts b/apps/server/src/services/ftsSearch/index.test.tsindex ad395218081..cb812be7921 100644--- a/apps/server/src/services/ftsSearch/index.test.ts+++ b/apps/server/src/services/ftsSearch/index.test.ts@@ -157,7 +157,7 @@ describe('full-text search provider selection', () => {);await expect(repo.search({ query: 'candidate' })).resolves.toEqual([]);- expect(elasticsearchSearch).toHaveBeenCalledTimes(9);+ expect(elasticsearchSearch).toHaveBeenCalledTimes(10);expect(createPgSearchBackend).not.toHaveBeenCalled();expect(pgSearch).not.toHaveBeenCalled();});diff --git a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.fileContent.test.ts b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.fileContent.test.tsnew file mode 100644index 00000000000..64ced820516--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.fileContent.test.ts@@ -0,0 +1,166 @@+// @vitest-environment node+import { FileSource } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { DOCUMENT_FOLDER_TYPE, documents, files, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ElasticsearchFtsSearchBackend, type ElasticsearchFtsSearchClient } from '../elasticsearch';+import type { FtsSearchBackendRequest, FtsSearchFileResult, FtsSearchPageResult } from '../types';++const db: LobeChatDatabase = await getTestDB();++const userId = 'es-file-content-user';+const filler = 'Unrelated planning paragraph. '.repeat(15);++const createClient = (ids: string[]): ElasticsearchFtsSearchClient => ({+ search: vi.fn().mockResolvedValue({+ hits: { hits: ids.map((id, index) => ({ _id: id, _score: 10 - index })) },+ }),+});++const documentRequest = (+ documentKind: 'fileContent' | 'page',+ mode?: FtsSearchBackendRequest['mode'],+ excludeFileDerived?: boolean,+): FtsSearchBackendRequest => ({+ entity: 'documents',+ filters: { documentKind, excludeFileDerived },+ mode,+ pagination: { limit: 5 },+ query: { text: 'kestrel' },+ scope: { userId },+});++const insertParsedFile = async (id: string, content: string, source?: FileSource) => {+ await db.insert(files).values({+ fileType: 'application/pdf',+ id,+ name: `${id}.pdf`,+ size: 10,+ source,+ url: `s3://bucket/${id}.pdf`,+ userId,+ });+ await db.insert(documents).values({+ content,+ fileId: id,+ fileType: 'custom/document',+ filename: `${id}.pdf`,+ id: `doc-${id}`,+ source: `s3://bucket/${id}.pdf`,+ sourceType: 'file',+ totalCharCount: content.length,+ totalLineCount: 1,+ userId,+ });+};++beforeEach(async () => {+ await db.delete(users);+ await db.insert(users).values({ id: userId });+});++describe('ElasticsearchFtsSearchBackend file content', () => {+ it('queries parsed file documents by content only', async () => {+ const client = createClient([]);+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace: 'test' });++ await backend.search(documentRequest('fileContent', 'candidates'));++ const { body } = vi.mocked(client.search).mock.calls[0][0];+ expect(body.query.bool.filter).toEqual(+ expect.arrayContaining([{ exists: { field: 'file_id' } }, { term: { source_type: 'file' } }]),+ );+ expect(body.query.bool.must_not).toContainEqual({+ term: { file_type: DOCUMENT_FOLDER_TYPE },+ });+ expect(body.query.bool.must[0].multi_match.fields).toEqual(['content']);+ });++ it('hydrates document hits into their files with a snippet around the match', async () => {+ await insertParsedFile('es-fc-contract', `${filler}The kestrel clause covers renewals.`);+ const backend = new ElasticsearchFtsSearchBackend(db, {+ client: createClient(['doc-es-fc-contract']),+ indexNamespace: 'test',+ });++ const response = await backend.search(documentRequest('fileContent'));+ const items = response.items as FtsSearchFileResult[];++ expect(items.map(({ id, type }) => ({ id, type }))).toEqual([+ { id: 'es-fc-contract', type: 'file' },+ ]);+ expect(items[0].description).toContain('kestrel clause');+ });++ it('drops document hits whose file is hidden from the library', async () => {+ await insertParsedFile('es-fc-hidden', 'kestrel secret', FileSource.ToolResult);+ const backend = new ElasticsearchFtsSearchBackend(db, {+ client: createClient(['doc-es-fc-hidden']),+ indexNamespace: 'test',+ });++ const response = await backend.search(documentRequest('fileContent'));++ expect(response.items).toEqual([]);+ });++ it('keeps parsed uploads out of page candidates', async () => {+ const client = createClient([]);+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace: 'test' });++ await backend.search(documentRequest('page', 'candidates', true));++ const { body } = vi.mocked(client.search).mock.calls[0][0];+ expect(body.query.bool.must_not).toContainEqual({+ bool: { filter: [{ term: { source_type: 'file' } }, { exists: { field: 'file_id' } }] },+ });+ });++ it('drops a parsed upload from page hydration', async () => {+ await insertParsedFile('es-fc-as-page', 'kestrel handbook');+ const backend = new ElasticsearchFtsSearchBackend(db, {+ client: createClient(['doc-es-fc-as-page']),+ indexNamespace: 'test',+ });++ const response = await backend.search(documentRequest('page', undefined, true));++ expect(response.items).toEqual([]);+ });++ it('keeps parsed uploads in page-only searches', async () => {+ await insertParsedFile('es-fc-recall', 'kestrel handbook');+ const client = createClient(['doc-es-fc-recall']);+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace: 'test' });++ const response = await backend.search(documentRequest('page'));++ expect(response.items).toEqual([expect.objectContaining({ id: 'doc-es-fc-recall' })]);+ });++ it('shows where a page matched', async () => {+ await db.insert(documents).values({+ content: `${filler}The kestrel section explains the rollout.`,+ fileType: 'custom/document',+ filename: 'roadmap.md',+ id: 'es-fc-page',+ source: 'internal://es-fc-page',+ sourceType: 'api',+ title: 'Roadmap',+ totalCharCount: 100,+ totalLineCount: 1,+ userId,+ });+ const backend = new ElasticsearchFtsSearchBackend(db, {+ client: createClient(['es-fc-page']),+ indexNamespace: 'test',+ });++ const response = await backend.search(documentRequest('page'));+ const items = response.items as FtsSearchPageResult[];++ expect(items[0].description).toContain('kestrel section');+ });+});diff --git a/packages/database/src/repositories/ftsSearch/__tests__/fileContentBehavior.ts b/packages/database/src/repositories/ftsSearch/__tests__/fileContentBehavior.tsnew file mode 100644index 00000000000..da5130bf899--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/__tests__/fileContentBehavior.ts@@ -0,0 +1,251 @@+import { FileSource } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import { documents, files, knowledgeBaseFiles, knowledgeBases, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import type { FtsSearchRepo } from '../index';+import type { FtsSearchFileResult, FtsSearchPageResult } from '../types';++const userId = 'file-content-search-user';+const otherUserId = 'file-content-search-other-user';++export interface FtsSearchFileContentBehaviorOptions {+ createRepo: (db: LobeChatDatabase, userId: string) => FtsSearchRepo;+ db: LobeChatDatabase;+}++const filler = 'Quarterly planning notes and unrelated paragraphs. '.repeat(12);++/**+ * Provider-neutral behaviour for searching the parsed text of uploaded files+ * and showing where a page or file matched.+ */+export const describeFtsSearchFileContentBehavior = ({+ createRepo,+ db,+}: FtsSearchFileContentBehaviorOptions) => {+ describe('search - file content', () => {+ let repo: FtsSearchRepo;++ const insertFile = async (+ id: string,+ name: string,+ content: string | null,+ options: { ownerId?: string; source?: FileSource } = {},+ ) => {+ const ownerId = options.ownerId ?? userId;+ await db.insert(files).values({+ fileType: 'application/pdf',+ id,+ name,+ size: 1024,+ source: options.source,+ url: `s3://bucket/${id}.pdf`,+ userId: ownerId,+ });+ if (content === null) return;+ await db.insert(documents).values({+ content,+ fileId: id,+ fileType: 'custom/document',+ filename: name,+ id: `doc-${id}`,+ source: `s3://bucket/${id}.pdf`,+ sourceType: 'file',+ title: name,+ totalCharCount: content.length,+ totalLineCount: 1,+ userId: ownerId,+ });+ };++ const searchFiles = async (query: string, limitPerType?: number) =>+ (await repo.search({ limitPerType, query, type: 'file' })) as FtsSearchFileResult[];++ beforeEach(async () => {+ await db.delete(users);+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+ repo = createRepo(db, userId);+ });++ it('finds a file whose parsed text matches when its name does not', async () => {+ await insertFile(+ 'fc-contract',+ 'contract-2026.pdf',+ `${filler}The kestrel clause covers renewals.`,+ );+ await insertFile('fc-other', 'budget.pdf', filler);++ const results = await searchFiles('kestrel');++ expect(results.map(({ id }) => id)).toEqual(['fc-contract']);+ expect(results[0]).toMatchObject({ name: 'contract-2026.pdf', type: 'file' });+ expect(results[0].description).toContain('kestrel clause');+ });++ it('also returns content matches in an untyped search', async () => {+ await insertFile('fc-untyped', 'scan-001.pdf', 'Notes about the kestrel launch');++ const results = await repo.search({ query: 'kestrel' });++ expect(results.filter(({ type }) => type === 'file').map(({ id }) => id)).toEqual([+ 'fc-untyped',+ ]);+ });++ it('lists name matches before content-only matches', async () => {+ await insertFile('fc-by-content', 'notes.pdf', 'kestrel kestrel kestrel kestrel');+ await insertFile('fc-by-name', 'kestrel-brief.pdf', filler);++ const results = await searchFiles('kestrel');++ expect(results.map(({ id }) => id)).toEqual(['fc-by-name', 'fc-by-content']);+ });++ it('returns a file once when both its name and its text match', async () => {+ await insertFile('fc-both', 'kestrel-report.pdf', `${filler}Kestrel figures for the quarter`);++ const results = await searchFiles('kestrel');++ expect(results.map(({ id }) => id)).toEqual(['fc-both']);+ expect(results[0].description).toContain('Kestrel figures');+ });++ it('respects the per-type limit across name and content matches', async () => {+ await insertFile('fc-limit-name', 'kestrel-a.pdf', filler);+ await insertFile('fc-limit-content-1', 'a.pdf', 'kestrel one');+ await insertFile('fc-limit-content-2', 'b.pdf', 'kestrel two');++ const results = await searchFiles('kestrel', 2);++ expect(results).toHaveLength(2);+ expect(results[0].id).toBe('fc-limit-name');+ });++ it('does not reveal content matches from files hidden from the library', async () => {+ await insertFile('fc-hidden', 'tool-output.pdf', 'kestrel secret', {+ source: FileSource.ToolResult,+ });++ expect(await searchFiles('kestrel')).toEqual([]);+ });++ it('does not reveal content matches from another user', async () => {+ await insertFile('fc-foreign', 'theirs.pdf', 'kestrel secret', { ownerId: otherUserId });++ expect(await searchFiles('kestrel')).toEqual([]);+ });++ it('does not reveal content matches from restricted knowledge bases', async () => {+ await insertFile('fc-restricted', 'restricted.pdf', 'kestrel secret');+ await insertFile('fc-open', 'open.pdf', 'kestrel public');+ await db+ .insert(knowledgeBases)+ .values({ id: 'fc-kb-restricted', name: 'Restricted', userId });+ await db+ .insert(knowledgeBaseFiles)+ .values({ fileId: 'fc-restricted', knowledgeBaseId: 'fc-kb-restricted', userId });++ const results = await repo.search({+ excludeKnowledgeBaseIds: ['fc-kb-restricted'],+ query: 'kestrel',+ type: 'file',+ });++ expect(results.map(({ id }) => id)).toEqual(['fc-open']);+ });++ it('lists a parsed upload as its file, not as a page', async () => {+ await insertFile('fc-parsed', 'handbook.pdf', 'The kestrel policy applies to every team.');++ const results = await repo.search({ query: 'kestrel' });++ expect(results.map(({ id, type }) => ({ id, type }))).toEqual([+ { id: 'fc-parsed', type: 'file' },+ ]);+ });++ it('keeps parsed uploads in page-only searches such as recall', async () => {+ await insertFile('fc-recall', 'handbook.pdf', 'The kestrel policy applies to every team.');++ const results = await repo.search({ query: 'kestrel', type: 'page' });++ expect(results.map(({ id, type }) => ({ id, type }))).toEqual([+ { id: 'doc-fc-recall', type: 'page' },+ ]);+ });++ it('still finds legacy parsed rows stored with the upload mime type', async () => {+ await insertFile('fc-legacy', 'legacy.pdf', null);+ await db.insert(documents).values({+ content: 'Legacy kestrel notes',+ fileId: 'fc-legacy',+ fileType: 'application/pdf',+ filename: 'legacy.pdf',+ id: 'doc-fc-legacy',+ source: 's3://bucket/fc-legacy.pdf',+ sourceType: 'file',+ totalCharCount: 20,+ totalLineCount: 1,+ userId,+ });++ expect((await searchFiles('kestrel')).map(({ id }) => id)).toEqual(['fc-legacy']);+ });++ it('keeps a knowledge base page with its mirror file a page', async () => {+ await db.insert(knowledgeBases).values({ id: 'fc-kb-pages', name: 'Pages', userId });+ await db.insert(files).values({+ fileType: 'custom/document',+ id: 'fc-mirror',+ name: 'Rollout notes',+ size: 10,+ url: 'internal://document/placeholder',+ userId,+ });+ await db.insert(documents).values({+ content: 'Rollout notes about kestrel',+ fileId: 'fc-mirror',+ fileType: 'custom/document',+ filename: 'Rollout notes',+ id: 'fc-kb-page',+ knowledgeBaseId: 'fc-kb-pages',+ source: 'internal://document/placeholder',+ sourceType: 'api',+ title: 'Rollout notes',+ totalCharCount: 27,+ totalLineCount: 1,+ userId,+ });++ const results = await repo.search({ query: 'kestrel' });++ expect(results.map(({ id, type }) => ({ id, type }))).toEqual([+ { id: 'fc-kb-page', type: 'page' },+ ]);+ });++ it('shows where a page matched', async () => {+ await db.insert(documents).values({+ content: `${filler}The kestrel section explains the rollout.`,+ fileType: 'custom/document',+ filename: 'roadmap.md',+ id: 'fc-page',+ source: 'internal://fc-page',+ sourceType: 'api',+ title: 'Roadmap',+ totalCharCount: 100,+ totalLineCount: 1,+ userId,+ });++ const results = (await repo.search({+ query: 'kestrel',+ type: 'page',+ })) as FtsSearchPageResult[];++ expect(results.map(({ id }) => id)).toEqual(['fc-page']);+ expect(results[0].description).toContain('kestrel section');+ });+ });+};diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch.ts b/packages/database/src/repositories/ftsSearch/elasticsearch.tsindex 42bfa16138e..3a608f7408c 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch.ts@@ -3,6 +3,7 @@ import { searchElasticsearchCandidates } from './elasticsearch/candidates';import {hydrateAgents,hydrateChatGroups,+ hydrateFileContents,hydrateFiles,hydrateFolders,hydrateKnowledgeBaseDocuments,@@ -239,6 +240,23 @@ export class ElasticsearchFtsSearchBackend implements FtsSearchBackend {hits,request.scope,limit,+ query,+ request.filters.excludeKnowledgeBaseIds,+ request.filters.excludeFileDerived,+ ),+ ),+ };+ }+ if (target.documentKind === 'fileContent') {+ return {+ candidates,+ items: await this.observe(entity, 'pg_hydration', () =>+ hydrateFileContents(+ this.db,+ hits,+ request.scope,+ limit,+ query,request.filters.excludeKnowledgeBaseIds,),),diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.tsindex 0b3e30710a4..dc911843e27 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts@@ -309,6 +309,14 @@ export const searchElasticsearchCandidates = async (filter.push({ term: { file_type: DOCUMENT_FOLDER_TYPE } });} else if (documentKind === 'page') {filter.push({ term: { file_type: 'custom/document' } });+ if (request.filters.excludeFileDerived) {+ mustNot.push({+ bool: { filter: [{ term: { source_type: 'file' } }, { exists: { field: 'file_id' } }] },+ });+ }+ } else if (documentKind === 'fileContent') {+ filter.push({ exists: { field: 'file_id' } }, { term: { source_type: 'file' } });+ mustNot.push({ term: { file_type: DOCUMENT_FOLDER_TYPE } });} else if (documentKind === 'knowledgeBaseDocument') {filter.push({ terms: { knowledge_base_ids: request.filters.knowledgeBaseIds ?? [] } });mustNot.push({ term: { file_type: DOCUMENT_FOLDER_TYPE } });diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.tsindex c28123bbe2e..b28a10d1fd7 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts@@ -37,6 +37,7 @@ import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shaimport { notTrashed } from '../../../utils/softDelete';import { notChannelTopic, notChannelTopicRef } from '../../../utils/topicVisibility';import { buildWorkspaceWhere } from '../../../utils/workspace';+import { loadDocumentSnippets } from '../snippet';import type {FtsSearchAgentResult,FtsSearchBackendScope,@@ -601,7 +602,9 @@ export const hydratePages = async (hits: FtsSearchCandidateHit[],scope: FtsSearchBackendScope,limit: number,+ query: string,excludeKnowledgeBaseIds: string[] = [],+ excludeFileDerived = false,): Promise<FtsSearchPageResult[]> => {if (hits.length === 0) return [];@@ -624,6 +627,9 @@ export const hydratePages = async (),buildWorkspaceWhere(scope, documents),eq(documents.fileType, 'custom/document'),+ excludeFileDerived+ ? or(ne(documents.sourceType, 'file'), isNull(documents.fileId))+ : undefined,notAgentShareDocument(documents.metadata),notAgentShareFileReference(db, documents.fileId),),@@ -641,17 +647,71 @@ export const hydratePages = async (return knowledgeBaseIds.every((knowledgeBaseId) => !excluded.has(knowledgeBaseId));});- return attachScores(authorizedRows, hits)- .slice(0, limit)- .map((row) => ({- createdAt: row.createdAt,- description: null,- id: row.id,- relevance: row.relevance,- title: row.title || row.filename || 'Untitled',- type: 'page' as const,- updatedAt: row.updatedAt,- }));+ const selectedRows = attachScores(authorizedRows, hits).slice(0, limit);+ const snippets = await loadDocumentSnippets(+ db,+ selectedRows.map(({ id }) => id),+ query,+ );++ return selectedRows.map((row) => ({+ createdAt: row.createdAt,+ description: snippets.get(row.id) ?? null,+ id: row.id,+ relevance: row.relevance,+ title: row.title || row.filename || 'Untitled',+ type: 'page' as const,+ updatedAt: row.updatedAt,+ }));+};++export const hydrateFileContents = async (+ db: LobeChatDatabase,+ hits: FtsSearchCandidateHit[],+ scope: FtsSearchBackendScope,+ limit: number,+ query: string,+ excludeKnowledgeBaseIds: string[] = [],+): Promise<FtsSearchFileResult[]> => {+ if (hits.length === 0) return [];++ const documentRows = await db+ .select({ fileId: documents.fileId, id: documents.id })+ .from(documents)+ .where(+ and(+ inArray(+ documents.id,+ hits.map(({ id }) => id),+ ),+ buildWorkspaceWhere(scope, documents),+ isNotNull(documents.fileId),+ eq(documents.sourceType, 'file'),+ ne(documents.fileType, DOCUMENT_FOLDER_TYPE),+ notAgentShareDocument(documents.metadata),+ ),+ );+ const fileIdByDocument = new Map(documentRows.map(({ fileId, id }) => [id, fileId!]));+ const documentIdByFile = new Map<string, string>();+ const fileHits: FtsSearchCandidateHit[] = [];+ for (const hit of hits) {+ const fileId = fileIdByDocument.get(hit.id);+ if (!fileId || documentIdByFile.has(fileId)) continue;+ documentIdByFile.set(fileId, hit.id);+ fileHits.push({ ...hit, id: fileId });+ }++ const items = await hydrateFiles(db, fileHits, scope, limit, excludeKnowledgeBaseIds);+ const snippets = await loadDocumentSnippets(+ db,+ items.map(({ id }) => documentIdByFile.get(id)!),+ query,+ );++ return items.map((item) => ({+ ...item,+ description: snippets.get(documentIdByFile.get(item.id)!) ?? null,+ }));};export const hydrateKnowledgeBaseDocuments = async (diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.tsindex 641067d0a31..35db8bdb08a 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.ts@@ -22,6 +22,7 @@ export const ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS = {} as const;export const ELASTICSEARCH_FTS_SEARCH_DOCUMENT_QUERY_FIELDS = {+ fileContent: ['content'],folder: ['title^4', 'slug^3', 'description^2'],knowledgeBaseDocument: ['title^4', 'slug^3', 'content'],page: ['title^4', 'slug^3', 'content'],diff --git a/packages/database/src/repositories/ftsSearch/index.test.ts b/packages/database/src/repositories/ftsSearch/index.test.tsindex daca15d9a06..d4b9ba5ab32 100644--- a/packages/database/src/repositories/ftsSearch/index.test.ts+++ b/packages/database/src/repositories/ftsSearch/index.test.ts@@ -32,7 +32,6 @@ let ftsSearchRepo: FtsSearchRepo;const serverDB: LobeChatDatabase = await getTestDB();beforeEach(async () => {- // Clean upawait serverDB.delete(users);// Create test users@@ -132,6 +131,7 @@ const REWRITTEN_RESULT_TYPES = [const SCAN_ALIASES = ['agent_hits','chat_group_hits',+ 'file_content_hits','file_hits','folder_hits','knowledge_base_hits',diff --git a/packages/database/src/repositories/ftsSearch/index.ts b/packages/database/src/repositories/ftsSearch/index.tsindex f0a69fc70e3..1ad27912b89 100644--- a/packages/database/src/repositories/ftsSearch/index.ts+++ b/packages/database/src/repositories/ftsSearch/index.ts@@ -9,6 +9,7 @@ import type {FtsSearchCandidateRequest,FtsSearchCandidateResult,FtsSearchDatabaseResult,+ FtsSearchFileResult,FtsSearchKnowledgeBaseDocumentHit,FtsSearchOptions,FtsSearchRepoOptions,@@ -171,11 +172,7 @@ export class FtsSearchRepo {);}if ((!type || type === 'file') && limits.file > 0) {- searches.push(- this.execute(- this.createRequest('files', trimmedQuery, limits.file, { excludeKnowledgeBaseIds }),- ),- );+ searches.push(this.searchFiles(trimmedQuery, limits.file, excludeKnowledgeBaseIds));}if ((!type || type === 'folder') && limits.folder > 0) {searches.push(@@ -192,6 +189,7 @@ export class FtsSearchRepo {this.execute(this.createRequest('documents', trimmedQuery, limits.page, {documentKind: 'page',+ excludeFileDerived: !type,excludeKnowledgeBaseIds,timeRange,}),@@ -217,6 +215,34 @@ export class FtsSearchRepo {return responses.flatMap((response) => response.items as FtsSearchDatabaseResult[]);}+ private async searchFiles(+ query: string,+ limit: number,+ excludeKnowledgeBaseIds: string[],+ ): Promise<FtsSearchBackendResponse> {+ const [byName, byContent] = await Promise.all([+ this.execute(this.createRequest('files', query, limit, { excludeKnowledgeBaseIds })),+ this.execute(+ this.createRequest('documents', query, limit, {+ documentKind: 'fileContent',+ excludeKnowledgeBaseIds,+ }),+ ),+ ]);+ const contentItems = byContent.items as FtsSearchFileResult[];+ const contentById = new Map(contentItems.map((item) => [item.id, item]));+ const nameItems = (byName.items as FtsSearchFileResult[]).map((item) => {+ const description = contentById.get(item.id)?.description;+ return description ? { ...item, description } : item;+ });+ const nameIds = new Set(nameItems.map(({ id }) => id));++ return {+ candidates: [...byName.candidates, ...byContent.candidates],+ items: [...nameItems, ...contentItems.filter(({ id }) => !nameIds.has(id))].slice(0, limit),+ };+ }+/** Candidate-only retrieval for legacy and hybrid paths that own their PostgreSQL hydration. */async ftsSearchCandidates(request: FtsSearchCandidateRequest): Promise<FtsSearchCandidateResult> {if (!this.ftsSearchCandidateEnabled) {diff --git a/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts b/packages/database/src/repositories/ftsSearch/pgLike/index.test.tsindex 49687f6867f..3114418c26b 100644--- a/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts+++ b/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts@@ -16,6 +16,7 @@ import {} from '../../../schemas/userMemories';import { workspaces } from '../../../schemas/workspace';import type { LobeChatDatabase } from '../../../type';+import { describeFtsSearchFileContentBehavior } from '../__tests__/fileContentBehavior';import {describeFtsSearchProductBehavior,otherUserId,@@ -49,6 +50,7 @@ const createRepo = (describe('FtsSearchRepo (pg_like)', () => {describeFtsSearchProductBehavior({ createRepo, db: serverDB });describeFtsSearchTimeRangeBehavior({ createRepo, db: serverDB, supportsCandidates: true });+ describeFtsSearchFileContentBehavior({ createRepo, db: serverDB });describe('LIKE wildcard escaping', () => {beforeEach(async () => {diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/fileContent.test.ts b/packages/database/src/repositories/ftsSearch/pgSearch/fileContent.test.tsnew file mode 100644index 00000000000..c7f72a82482--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgSearch/fileContent.test.ts@@ -0,0 +1,24 @@+// @vitest-environment node+import { describe } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import type { LobeChatDatabase } from '../../../type';+import { describeFtsSearchFileContentBehavior } from '../__tests__/fileContentBehavior';+import { FtsSearchRepo } from '../index';+import { PgSearchFtsSearchBackend } from './index';++const serverDB: LobeChatDatabase = await getTestDB();++// BM25 retrieval requires the pg_search extension (ParadeDB), not available in PGlite.+describe.skipIf(process.env.TEST_SERVER_DB !== '1')(+ 'FtsSearchRepo file content (pg_search)',+ () => {+ describeFtsSearchFileContentBehavior({+ createRepo: (db, userId) =>+ new FtsSearchRepo(db, userId, undefined, undefined, {+ backend: new PgSearchFtsSearchBackend(db, { userId }),+ }),+ db: serverDB,+ });+ },+);diff --git a/packages/database/src/repositories/ftsSearch/postgres/backend.ts b/packages/database/src/repositories/ftsSearch/postgres/backend.tsindex f697d2c79df..fea550b8e99 100644--- a/packages/database/src/repositories/ftsSearch/postgres/backend.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/backend.ts@@ -17,6 +17,7 @@ import type { PostgresFtsSearchContext } from './context';import { createPostgresFtsSearchContext } from './context';import type { PostgresFtsSearchDialect } from './dialect';import { searchFolders, searchKnowledgeBaseDocuments, searchPages } from './documents';+import { searchFileContents } from './fileContents';import { searchMemories } from './memories';/**@@ -71,8 +72,12 @@ export abstract class PostgresFtsSearchBackend implements FtsSearchBackend {limit,filters.excludeKnowledgeBaseIds,filters.timeRange,+ filters.excludeFileDerived,);}+ if (filters.documentKind === 'fileContent') {+ return searchFileContents(this.context, query, limit, filters.excludeKnowledgeBaseIds);+ }if (filters.documentKind === 'knowledgeBaseDocument') {return searchKnowledgeBaseDocuments(this.context,diff --git a/packages/database/src/repositories/ftsSearch/postgres/documents.ts b/packages/database/src/repositories/ftsSearch/postgres/documents.tsindex 3ca09545dcf..644f6bde06e 100644--- a/packages/database/src/repositories/ftsSearch/postgres/documents.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/documents.ts@@ -1,10 +1,12 @@import type { SQLWrapper } from 'drizzle-orm';import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';+import type { AnyPgColumn } from 'drizzle-orm/pg-core';import { DOCUMENT_FOLDER_TYPE, documents, knowledgeBaseFiles } from '../../../schemas';import { notAgentShareDocument } from '../../../utils/documentVisibility';import { notAgentShareFileReference } from '../../../utils/fileVisibility';import { buildWorkspaceWhere } from '../../../utils/workspace';+import { loadDocumentSnippets } from '../snippet';import type {FtsSearchBackendResponse,FtsSearchFolderResult,@@ -31,6 +33,10 @@ const PAGE_FIELDS: PostgresFtsSearchField[] = [const KNOWLEDGE_BASE_DOCUMENT_FIELDS = PAGE_FIELDS;+// The library lists a parsed upload as its file; searches that also return files do the same.+const notFileDerived = (sourceType: AnyPgColumn, fileId: AnyPgColumn) =>+ or(ne(sourceType, 'file'), isNull(fileId));+/** Search folders (documents with `file_type=DOCUMENT_FOLDER_TYPE`). */export async function searchFolders(context: PostgresFtsSearchContext,@@ -119,6 +125,7 @@ export async function searchPages(limit: number,excludeKbIds?: string[],timeRange?: FtsSearchTimeRange,+ excludeFileDerived?: boolean,): Promise<FtsSearchBackendResponse<FtsSearchPageResult>> {const { db, dialect } = context;const preparedQuery = dialect.prepare(query);@@ -151,6 +158,7 @@ export async function searchPages(knowledgeBaseId: documents.knowledgeBaseId,metadata: documents.metadata,score: score.as('score'),+ sourceType: documents.sourceType,title: documents.title,updatedAt: documents.updatedAt,workspaceId: documents.workspaceId,@@ -162,7 +170,12 @@ export async function searchPages(eq(documents.fileType, 'custom/document'),context.liftsExclusionFilter? undefined- : excludeKb(documents.knowledgeBaseId, documents.fileId),+ : and(+ excludeKb(documents.knowledgeBaseId, documents.fileId),+ excludeFileDerived+ ? notFileDerived(documents.sourceType, documents.fileId)+ : undefined,+ ),timeRangeWhere(documents, timeRange),dialect.match(PAGE_FIELDS, preparedQuery),),@@ -186,17 +199,27 @@ export async function searchPages(context.liftedScopeWhere(hits.workspaceId),notAgentShareDocument(hits.metadata),notAgentShareFileReference(db, hits.fileId),- context.liftsExclusionFilter ? excludeKb(hits.knowledgeBaseId, hits.fileId) : undefined,+ context.liftsExclusionFilter+ ? and(+ excludeKb(hits.knowledgeBaseId, hits.fileId),+ excludeFileDerived ? notFileDerived(hits.sourceType, hits.fileId) : undefined,+ )+ : undefined,),).orderBy(desc(hits.score)).limit(limit);+ const snippets = await loadDocumentSnippets(+ db,+ rows.map(({ id }) => id),+ query,+ );return buildResponse(rows, (row) => {const title = row.title || row.filename || 'Untitled';return {createdAt: row.createdAt,- description: null,+ description: snippets.get(row.id) ?? null,id: row.id,relevance: row.relevance,title,diff --git a/packages/database/src/repositories/ftsSearch/postgres/fileContents.ts b/packages/database/src/repositories/ftsSearch/postgres/fileContents.tsnew file mode 100644index 00000000000..661d3a5f823--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/postgres/fileContents.ts@@ -0,0 +1,143 @@+import type { SQLWrapper } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, ne, notInArray, sql } from 'drizzle-orm';++import { DOCUMENT_FOLDER_TYPE, documents, files, knowledgeBaseFiles } from '../../../schemas';+import { notAgentShareDocument } from '../../../utils/documentVisibility';+import {+ libraryVisibleFileSource,+ notAgentShareFileReference,+} from '../../../utils/fileVisibility';+import { buildWorkspaceWhere } from '../../../utils/workspace';+import { loadDocumentSnippets } from '../snippet';+import type { FtsSearchBackendResponse, FtsSearchFileResult } from '../types';+import type { PostgresFtsSearchContext } from './context';+import type { PostgresFtsSearchField } from './dialect';+import { buildResponse } from './results';++const FILE_CONTENT_FIELDS: PostgresFtsSearchField[] = [{ column: documents.content }];++// Inline documents without a file and re-parsed duplicates of one file share the+// scored pool, so it is drawn deeper than the number of files returned.+const FILE_CONTENT_CANDIDATE_MULTIPLIER = 4;++export async function searchFileContents(+ context: PostgresFtsSearchContext,+ query: string,+ limit: number,+ excludeKbIds?: string[],+): Promise<FtsSearchBackendResponse<FtsSearchFileResult>> {+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(documents.id, FILE_CONTENT_FIELDS, preparedQuery);+ const candidateLimit = limit * FILE_CONTENT_CANDIDATE_MULTIPLIER;+ const excludeKb = (fileId: SQLWrapper) =>+ excludeKbIds && excludeKbIds.length > 0+ ? notInArray(+ fileId,+ db+ .select({ fileId: knowledgeBaseFiles.fileId })+ .from(knowledgeBaseFiles)+ .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),+ )+ : undefined;++ const hits = db+ .select({+ fileId: documents.fileId,+ id: documents.id,+ metadata: documents.metadata,+ score: score.as('score'),+ workspaceId: documents.workspaceId,+ })+ .from(documents)+ .where(+ and(+ context.scanScopeWhere(documents),+ eq(documents.sourceType, 'file'),+ ne(documents.fileType, DOCUMENT_FOLDER_TYPE),+ // file_id is not a BM25 field, so ParadeDB keeps it out of its TopN scan.+ context.liftsExclusionFilter+ ? undefined+ : and(isNotNull(documents.fileId), excludeKb(documents.fileId)),+ dialect.match(FILE_CONTENT_FIELDS, preparedQuery),+ ),+ )+ .orderBy(sql`${score} DESC`)+ .limit(context.scanCandidateLimit(candidateLimit))+ .as('file_content_hits');++ const rows = await db+ .select({+ createdAt: files.createdAt,+ documentId: hits.id,+ fileType: files.fileType,+ id: files.id,+ name: files.name,+ score: hits.score,+ size: files.size,+ updatedAt: files.updatedAt,+ url: files.url,+ })+ .from(hits)+ .innerJoin(files, eq(files.id, hits.fileId))+ .where(+ and(+ context.liftedScopeWhere(hits.workspaceId),+ buildWorkspaceWhere(context.scope, files),+ ne(files.fileType, 'custom/document'),+ libraryVisibleFileSource(files.source),+ notAgentShareDocument(hits.metadata),+ notAgentShareFileReference(db, files.id),+ context.liftsExclusionFilter ? excludeKb(files.id) : undefined,+ ),+ )+ .orderBy(desc(hits.score), files.id)+ .limit(candidateLimit);++ const seenFileIds = new Set<string>();+ const fileRows = rows+ .filter(({ id }) => {+ if (seenFileIds.has(id)) return false;+ seenFileIds.add(id);+ return true;+ })+ .slice(0, limit);++ const fileIds = fileRows.map(({ id }) => id);+ const [snippets, knowledgeBaseRows] = await Promise.all([+ loadDocumentSnippets(+ db,+ fileRows.map(({ documentId }) => documentId),+ query,+ ),+ fileIds.length === 0+ ? []+ : db+ .select({+ fileId: knowledgeBaseFiles.fileId,+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,+ })+ .from(knowledgeBaseFiles)+ .where(inArray(knowledgeBaseFiles.fileId, fileIds))+ .orderBy(knowledgeBaseFiles.knowledgeBaseId),+ ]);+ const knowledgeBaseIdByFile = new Map<string, string>();+ for (const { fileId, knowledgeBaseId } of knowledgeBaseRows) {+ if (!knowledgeBaseIdByFile.has(fileId)) knowledgeBaseIdByFile.set(fileId, knowledgeBaseId);+ }++ return buildResponse(fileRows, (row) => ({+ createdAt: row.createdAt,+ description: snippets.get(row.documentId) ?? null,+ fileType: row.fileType,+ id: row.id,+ knowledgeBaseId: knowledgeBaseIdByFile.get(row.id) ?? null,+ name: row.name,+ relevance: row.relevance,+ size: row.size,+ title: row.name,+ type: 'file' as const,+ updatedAt: row.updatedAt,+ url: row.url,+ }));+}diff --git a/packages/database/src/repositories/ftsSearch/snippet.test.ts b/packages/database/src/repositories/ftsSearch/snippet.test.tsnew file mode 100644index 00000000000..8ee9e14bded--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/snippet.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { buildMatchSnippet } from './snippet';++describe('buildMatchSnippet', () => {+ it('returns null without content', () => {+ expect(buildMatchSnippet(null, 'kestrel')).toBeNull();+ expect(buildMatchSnippet(' ', 'kestrel')).toBeNull();+ });++ it('keeps the opening text when the match is near the start', () => {+ expect(buildMatchSnippet('Kestrel rollout notes', 'kestrel')).toBe('Kestrel rollout notes');+ });++ it('centres a late match and marks both cut edges', () => {+ const content = `${'filler words '.repeat(40)}the kestrel rollout starts ${'tail words '.repeat(40)}`;++ const snippet = buildMatchSnippet(content, 'kestrel', 80)!;++ expect(snippet.startsWith('...')).toBe(true);+ expect(snippet.endsWith('...')).toBe(true);+ expect(snippet).toContain('the kestrel rollout');+ expect(snippet.length).toBeLessThanOrEqual(86);+ });++ it('does not cut the first word in half', () => {+ const content = `${'alpha beta gamma delta '.repeat(10)}kestrel`;++ const snippet = buildMatchSnippet(content, 'kestrel', 60)!;++ expect(snippet.replace(/^\.\.\./, '').split(' ')[0]).toMatch(/^(alpha|beta|gamma|delta)$/);+ });++ it('matches case-insensitively and picks the earliest of several terms', () => {+ const content = `${'x '.repeat(100)}Falcon appears first, then KESTREL`;++ expect(buildMatchSnippet(content, 'kestrel falcon', 40)).toContain('Falcon appears');+ });++ it('collapses whitespace from parsed documents but keeps line breaks for markdown', () => {+ expect(buildMatchSnippet('Line one \n\n\t## kestrel here', 'kestrel')).toBe(+ 'Line one\n## kestrel here',+ );+ });++ it('matches CJK queries without word boundaries', () => {+ const content = `${'æ— å…³å†…å®¹'.repeat(30)}这里讲机器å¦ä¹ 的基础${'结尾'.repeat(30)}`;++ expect(buildMatchSnippet(content, '机器å¦ä¹ ', 40)).toContain('机器å¦ä¹ ');+ });++ it('falls back to the opening text when no term appears literally', () => {+ const content = `Running notes ${'more '.repeat(60)}`;++ expect(buildMatchSnippet(content, 'runs', 20)).toBe('Running notes more m...');+ });+});diff --git a/packages/database/src/repositories/ftsSearch/snippet.ts b/packages/database/src/repositories/ftsSearch/snippet.tsnew file mode 100644index 00000000000..fd3a334a76d--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/snippet.ts@@ -0,0 +1,79 @@+import { inArray, sql } from 'drizzle-orm';++import { documents } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++const SNIPPET_MAX_LEAD_CHARS = 40;+const SNIPPET_MAX_TERMS = 16;++// Matches beyond this prefix fall back to the opening text instead of loading the whole document.+export const FTS_SEARCH_SNIPPET_SCAN_CHARS = 200_000;++const splitTerms = (query: string) => [+ ...new Set(+ query+ .toLowerCase()+ .replaceAll('-', ' ')+ .split(/\s+/)+ .filter(Boolean)+ .slice(0, SNIPPET_MAX_TERMS),+ ),+];++const withEllipsis = (text: string, start: number, maxLength: number) => {+ const end = start + maxLength;+ return `${start > 0 ? '...' : ''}${text.slice(start, end)}${end < text.length ? '...' : ''}`;+};++export const buildMatchSnippet = (+ content: string | null | undefined,+ query: string,+ maxLength: number = 160,+): string | null => {+ if (!content) return null;++ const text = content+ .replaceAll(/\s*\n\s*/g, '\n')+ .replaceAll(/[^\S\n]+/g, ' ')+ .trim();+ if (!text) return null;++ const lowerText = text.toLowerCase();+ let matchAt = -1;+ for (const term of splitTerms(query)) {+ const index = lowerText.indexOf(term);+ if (index !== -1 && (matchAt === -1 || index < matchAt)) matchAt = index;+ }++ const lead = Math.min(SNIPPET_MAX_LEAD_CHARS, Math.floor(maxLength / 4));+ if (matchAt <= lead) return withEllipsis(text, 0, maxLength);++ let start = matchAt - lead;+ const wordBreak = text.slice(start, matchAt).search(/\s/);+ if (wordBreak !== -1) start += wordBreak + 1;++ return withEllipsis(text, start, maxLength);+};++export const loadDocumentSnippets = async (+ db: LobeChatDatabase,+ documentIds: string[],+ query: string,+): Promise<Map<string, string>> => {+ if (documentIds.length === 0) return new Map();++ const rows = await db+ .select({+ content: sql<string | null>`left(${documents.content}, ${FTS_SEARCH_SNIPPET_SCAN_CHARS})`,+ id: documents.id,+ })+ .from(documents)+ .where(inArray(documents.id, documentIds));++ const snippets = new Map<string, string>();+ for (const row of rows) {+ const snippet = buildMatchSnippet(row.content, query);+ if (snippet) snippets.set(row.id, snippet);+ }+ return snippets;+};diff --git a/packages/database/src/repositories/ftsSearch/types.ts b/packages/database/src/repositories/ftsSearch/types.tsindex 21dfbd46708..13ef5440aec 100644--- a/packages/database/src/repositories/ftsSearch/types.ts+++ b/packages/database/src/repositories/ftsSearch/types.ts@@ -231,7 +231,8 @@ export interface FtsSearchTimeRange {export interface FtsSearchBackendFilters {agentId?: string;- documentKind?: 'folder' | 'knowledgeBaseDocument' | 'page';+ documentKind?: 'fileContent' | 'folder' | 'knowledgeBaseDocument' | 'page';+ excludeFileDerived?: boolean;excludeKnowledgeBaseIds?: string[];excludeVirtual?: boolean;knowledgeBaseIds?: string[];diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsxindex d9b801b6a64..a966d8b79dc 100644--- a/src/features/CommandMenu/SearchResults.tsx+++ b/src/features/CommandMenu/SearchResults.tsx@@ -37,7 +37,7 @@ import { generationTopicSelectors as videoGenerationTopicSelectors } from '@/stoimport { markdownToTxt } from '@/utils/markdownToTxt';import type { CommandMenuResultClick } from './analytics';-import { CommandItem } from './components';+import { CommandItem, HighlightedText } from './components';import { styles } from './styles';import { goalResultStatusKey } from './utils/goalResults';import { shouldShowMarketplaceFallback } from './utils/marketplaceFallback';@@ -293,8 +293,8 @@ const SearchResults = memo<SearchResultsProps>(const getDescription = (result: FtsSearchResult) => {if (!result.description) return null;- // Sanitize markdown content for message search results- if (result.type === 'message') {+ // Message, page and file snippets carry raw markdown+ if (result.type === 'message' || result.type === 'page' || result.type === 'file') {return markdownToTxt(result.description);}return result.description;@@ -361,6 +361,10 @@ const SearchResults = memo<SearchResultsProps>(return formattedDate;}+ if (description && (result.type === 'page' || result.type === 'file')) {+ return <HighlightedText query={searchQuery} text={description} />;+ }+return description;};diff --git a/src/features/CommandMenu/components/HighlightedText.tsx b/src/features/CommandMenu/components/HighlightedText.tsxnew file mode 100644index 00000000000..29b2768da4a--- /dev/null+++ b/src/features/CommandMenu/components/HighlightedText.tsx@@ -0,0 +1,36 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import { splitQueryHighlightSegments } from '../utils/highlightSegments';++const styles = stylex.create({+ mark: {+ backgroundColor: cssVar.colorWarningBgHover,+ borderRadius: 2,+ color: cssVar.colorText,+ },+});++interface HighlightedTextProps {+ query: string;+ text: string;+}++const HighlightedText = memo<HighlightedTextProps>(({ query, text }) => (+ <>+ {splitQueryHighlightSegments(text, query).map((segment, index) =>+ segment.match ? (+ <mark key={index} {...stylex.props(styles.mark)}>+ {segment.text}+ </mark>+ ) : (+ segment.text+ ),+ )}+ </>+));++HighlightedText.displayName = 'CommandMenuHighlightedText';++export default HighlightedText;diff --git a/src/features/CommandMenu/components/index.ts b/src/features/CommandMenu/components/index.tsindex 7078b2fc932..182565c009e 100644--- a/src/features/CommandMenu/components/index.ts+++ b/src/features/CommandMenu/components/index.ts@@ -1,3 +1,4 @@export { default as CommandFooter } from './CommandFooter';export { default as CommandInput } from './CommandInput';export { default as CommandItem } from './CommandItem';+export { default as HighlightedText } from './HighlightedText';diff --git a/src/features/CommandMenu/utils/highlightSegments.test.ts b/src/features/CommandMenu/utils/highlightSegments.test.tsnew file mode 100644index 00000000000..a9d9e41326b--- /dev/null+++ b/src/features/CommandMenu/utils/highlightSegments.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { splitQueryHighlightSegments } from './highlightSegments';++describe('splitQueryHighlightSegments', () => {+ it('returns the whole text unmarked for an empty query', () => {+ expect(splitQueryHighlightSegments('Kestrel notes', ' ')).toEqual([+ { match: false, text: 'Kestrel notes' },+ ]);+ });++ it('marks every case-insensitive occurrence of each term', () => {+ expect(+ splitQueryHighlightSegments('Kestrel and falcon, then kestrel', 'kestrel Falcon'),+ ).toEqual([+ { match: true, text: 'Kestrel' },+ { match: false, text: ' and ' },+ { match: true, text: 'falcon' },+ { match: false, text: ', then ' },+ { match: true, text: 'kestrel' },+ ]);+ });++ it('prefers the longer term where terms overlap', () => {+ expect(splitQueryHighlightSegments('kestrels', 'kestrel kestrels')).toEqual([+ { match: true, text: 'kestrels' },+ ]);+ });++ it('treats regular expression characters literally', () => {+ expect(splitQueryHighlightSegments('cost (usd) a.b', '(usd) a.b')).toEqual([+ { match: false, text: 'cost ' },+ { match: true, text: '(usd)' },+ { match: false, text: ' ' },+ { match: true, text: 'a.b' },+ ]);+ });++ it('matches CJK text', () => {+ expect(splitQueryHighlightSegments('这里讲机器å¦ä¹ 的基础', '机器å¦ä¹ ')).toEqual([+ { match: false, text: '这里讲' },+ { match: true, text: '机器å¦ä¹ ' },+ { match: false, text: '的基础' },+ ]);+ });+});diff --git a/src/features/CommandMenu/utils/highlightSegments.ts b/src/features/CommandMenu/utils/highlightSegments.tsnew file mode 100644index 00000000000..ffff06fef00--- /dev/null+++ b/src/features/CommandMenu/utils/highlightSegments.ts@@ -0,0 +1,45 @@+import { findFoldedMatches } from '@/utils/findInDom';++export interface HighlightSegment {+ match: boolean;+ text: string;+}++const MAX_HIGHLIGHT_TERMS = 16;++const splitTerms = (query: string) =>+ [+ ...new Set(+ query+ .toLowerCase()+ .replaceAll('-', ' ')+ .split(/\s+/)+ .filter(Boolean)+ .slice(0, MAX_HIGHLIGHT_TERMS),+ ),+ ].sort((left, right) => right.length - left.length);++export const splitQueryHighlightSegments = (text: string, query: string): HighlightSegment[] => {+ const ranges: [number, number][] = [];+ for (const term of splitTerms(query)) {+ for (const [start, end] of findFoldedMatches(text, term)) {+ const overlaps = ranges.some(+ ([takenStart, takenEnd]) => start < takenEnd && end > takenStart,+ );+ if (!overlaps) ranges.push([start, end]);+ }+ }+ if (ranges.length === 0) return [{ match: false, text }];++ ranges.sort(([left], [right]) => left - right);+ const segments: HighlightSegment[] = [];+ let cursor = 0;+ for (const [start, end] of ranges) {+ if (start > cursor) segments.push({ match: false, text: text.slice(cursor, start) });+ segments.push({ match: true, text: text.slice(start, end) });+ cursor = end;+ }+ if (cursor < text.length) segments.push({ match: false, text: text.slice(cursor) });++ return segments;+};