🤯 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
⚡️ perf: optimize search with BM25 indexes and ICU tokenizer (#12914)
YuTengjingfc5b462892e1
diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex d3e4f76465c..e53319fb338 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -162,6 +162,8 @@"cmdk.search.agents": "Agents","cmdk.search.assistant": "Agent","cmdk.search.assistants": "Agents",+ "cmdk.search.chatGroup": "Agent Team",+ "cmdk.search.chatGroups": "Agent Teams","cmdk.search.communityAgent": "Community Agent","cmdk.search.file": "File","cmdk.search.files": "Files",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 0ae052ec903..938966d4a31 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -162,6 +162,8 @@"cmdk.search.agents": "助理","cmdk.search.assistant": "助理","cmdk.search.assistants": "助理",+ "cmdk.search.chatGroup": "团队",+ "cmdk.search.chatGroups": "团队","cmdk.search.communityAgent": "社区助理","cmdk.search.file": "文件","cmdk.search.files": "文件",diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex afc2324585b..da311dd948f 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1403,7 +1403,9 @@ describe('MessageModel Query Tests', () => {});});- describe('queryByKeyWord', () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in PGlite+ const isServerDB = process.env.TEST_SERVER_DB === '1';+ describe.skipIf(!isServerDB)('queryByKeyWord', () => {it('should query messages by keyword', async () => {// Create test dataawait serverDB.insert(messages).values([diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.tsindex 04c2626fcdd..06161ec115c 100644--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts@@ -895,7 +895,9 @@ describe('TopicModel - Query', () => {});});- describe('queryByKeyword', () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in PGlite+ const isServerDB = process.env.TEST_SERVER_DB === '1';+ describe.skipIf(!isServerDB)('queryByKeyword', () => {it('should return topics matching topic title keyword', async () => {await serverDB.transaction(async (tx) => {await tx.insert(topics).values([diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex e1c11a9fa0e..5b69278905d 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -35,7 +35,6 @@ import {inArray,isNotNull,isNull,- like,lte,not,or,@@ -65,6 +64,7 @@ import {topics,} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';+import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';@@ -1082,11 +1082,14 @@ export class MessageModel {};queryByKeyword = async (keyword: string) => {- if (!keyword) return [];- const result = await this.db.query.messages.findMany({- orderBy: [desc(messages.createdAt)],- where: and(eq(messages.userId, this.userId), like(messages.content, `%${keyword}%`)),- });+ if (!keyword.trim()) return [];++ const bm25Query = sanitizeBm25Query(keyword);+ const result = await this.db+ .select()+ .from(messages)+ .where(and(eq(messages.userId, this.userId), sql`${messages.content} @@@ ${bm25Query}`))+ .orderBy(desc(messages.createdAt));return result as DBMessageItem[];};diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.tsindex 7bf17e0a981..259b001af20 100644--- a/packages/database/src/models/session.ts+++ b/packages/database/src/models/session.ts@@ -6,8 +6,7 @@ import type {LobeGroupSession,SessionRankItem,} from '@lobechat/types';-import type { Column } from 'drizzle-orm';-import { and, asc, count, desc, eq, gt, inArray, isNull, like, not, or, sql } from 'drizzle-orm';+import { and, asc, count, desc, eq, gt, inArray, isNull, not, or, sql } from 'drizzle-orm';import type { PartialDeep } from 'type-fest';import { merge } from '@/utils/merge';@@ -15,6 +14,7 @@ import { merge } from '@/utils/merge';import type { AgentItem, NewAgent, NewSession, SessionItem } from '../schemas';import { agents, agentsToSessions, sessionGroups, sessions, topics } from '../schemas';import type { LobeChatDatabase } from '../type';+import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';@@ -634,6 +634,8 @@ export class SessionModel {const offset = current * pageSize;try {+ const bm25Query = sanitizeBm25Query(keyword);+const results = await this.db.query.agents.findMany({limit: pageSize,offset,@@ -641,13 +643,7 @@ export class SessionModel {orderBy: [asc(agents.id)],where: and(eq(agents.userId, this.userId),- or(- like(sql`lower(${agents.title})` as unknown as Column, `%${keyword.toLowerCase()}%`),- like(- sql`lower(${agents.description})` as unknown as Column,- `%${keyword.toLowerCase()}%`,- ),- ),+ sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query})`,),with: { agentsToSessions: { columns: {}, with: { session: true } } },});diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 181e18c2ee5..349799242fe 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1,25 +1,11 @@import type { ChatTopicMetadata, DBMessageItem, TopicRankItem } from '@lobechat/types';import type { SQL } from 'drizzle-orm';-import {- and,- count,- desc,- eq,- gt,- gte,- ilike,- inArray,- isNull,- lte,- ne,- not,- or,- sql,-} from 'drizzle-orm';+import { and, count, desc, eq, gt, gte, inArray, isNull, lte, ne, not, or, sql } from 'drizzle-orm';import type { TopicItem } from '../schemas';import { agents, agentsToSessions, messagePlugins, messages, topics } from '../schemas';import type { LobeChatDatabase } from '../type';+import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';@@ -239,34 +225,39 @@ export class TopicModel {};queryByKeyword = async (keyword: string, containerId?: string | null): Promise<TopicItem[]> => {- if (!keyword) return [];+ if (!keyword.trim()) return [];- const keywordLowerCase = keyword.toLowerCase();+ const bm25Query = sanitizeBm25Query(keyword);- // Query topics matching by title- const topicsByTitle = await this.db.query.topics.findMany({- orderBy: [desc(topics.updatedAt)],- where: and(- eq(topics.userId, this.userId),- this.matchContainer(containerId),- ilike(topics.title, `%${keywordLowerCase}%`),- ),- });-- // Query topic IDs matching by message content- const topicIdsByMessages = await this.db- .select({ topicId: messages.topicId })- .from(messages)- .innerJoin(topics, eq(messages.topicId, topics.id))- .where(- and(- eq(messages.userId, this.userId),- ilike(messages.content, `%${keywordLowerCase}%`),- eq(topics.userId, this.userId),- this.matchContainer(containerId),- ),- )- .groupBy(messages.topicId);+ // Run title and message content searches in parallel+ const [topicsByTitle, topicIdsByMessages] = await Promise.all([+ // Query topics matching by title (BM25)+ this.db+ .select()+ .from(topics)+ .where(+ and(+ eq(topics.userId, this.userId),+ this.matchContainer(containerId),+ sql`${topics.title} @@@ ${bm25Query}`,+ ),+ )+ .orderBy(desc(topics.updatedAt)),+ // Query topic IDs matching by message content (BM25)+ this.db+ .select({ topicId: messages.topicId })+ .from(messages)+ .innerJoin(topics, eq(messages.topicId, topics.id))+ .where(+ and(+ eq(messages.userId, this.userId),+ sql`${messages.content} @@@ ${bm25Query}`,+ eq(topics.userId, this.userId),+ this.matchContainer(containerId),+ ),+ )+ .groupBy(messages.topicId),+ ]);// If no topics found by message content, return topics matching by titleif (topicIdsByMessages.length === 0) {return topicsByTitle;diff --git a/packages/database/src/models/userMemory/__tests__/activity.test.ts b/packages/database/src/models/userMemory/__tests__/activity.test.tsindex 50e5340f0ac..a0bb8fd9cd2 100644--- a/packages/database/src/models/userMemory/__tests__/activity.test.ts+++ b/packages/database/src/models/userMemory/__tests__/activity.test.ts@@ -236,28 +236,30 @@ describe('UserMemoryActivityModel', () => {expect(result.pageSize).toBe(100);});- it('should search by query in title', async () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in PGlite+ const isServerDB = process.env.TEST_SERVER_DB === '1';+ it.skipIf(!isServerDB)('should search by query in title', async () => {const result = await activityModel.queryList({ q: 'Search Test' });expect(result.items).toHaveLength(1);expect(result.items[0].id).toBe('list-activity-3');});- it('should search by query in narrative', async () => {+ it.skipIf(!isServerDB)('should search by query in narrative', async () => {const result = await activityModel.queryList({ q: 'Searchable narrative' });expect(result.items).toHaveLength(1);expect(result.items[0].id).toBe('list-activity-3');});- it('should search by query in notes', async () => {+ it.skipIf(!isServerDB)('should search by query in notes', async () => {const result = await activityModel.queryList({ q: 'Some notes' });expect(result.items).toHaveLength(1);expect(result.items[0].id).toBe('list-activity-1');});- it('should search by query in feedback', async () => {+ it.skipIf(!isServerDB)('should search by query in feedback', async () => {const result = await activityModel.queryList({ q: 'Some feedback' });expect(result.items).toHaveLength(1);diff --git a/packages/database/src/models/userMemory/__tests__/experience.test.ts b/packages/database/src/models/userMemory/__tests__/experience.test.tsindex 8d68f12db19..94647913bde 100644--- a/packages/database/src/models/userMemory/__tests__/experience.test.ts+++ b/packages/database/src/models/userMemory/__tests__/experience.test.ts@@ -433,28 +433,30 @@ describe('UserMemoryExperienceModel', () => {expect(result.pageSize).toBe(100);});- it('should search by query in title', async () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in PGlite+ const isServerDB = process.env.TEST_SERVER_DB === '1';+ it.skipIf(!isServerDB)('should search by query in title', async () => {const result = await experienceModel.queryList({ q: 'Searchable Title' });expect(result.items).toHaveLength(1);expect(result.items[0].id).toBe('list-exp-3');});- it('should search by query in situation', async () => {+ it.skipIf(!isServerDB)('should search by query in situation', async () => {const result = await experienceModel.queryList({ q: 'Searchable situation' });expect(result.items).toHaveLength(1);expect(result.items[0].id).toBe('list-exp-3');});- it('should search by query in keyLearning', async () => {+ it.skipIf(!isServerDB)('should search by query in keyLearning', async () => {const result = await experienceModel.queryList({ q: 'Searchable learning' });expect(result.items).toHaveLength(1);expect(result.items[0].id).toBe('list-exp-3');});- it('should search by query in action', async () => {+ it.skipIf(!isServerDB)('should search by query in action', async () => {const result = await experienceModel.queryList({ q: 'Searchable action' });expect(result.items).toHaveLength(1);diff --git a/packages/database/src/models/userMemory/__tests__/identity.test.ts b/packages/database/src/models/userMemory/__tests__/identity.test.tsindex fece6881ab4..0e5febdaf29 100644--- a/packages/database/src/models/userMemory/__tests__/identity.test.ts+++ b/packages/database/src/models/userMemory/__tests__/identity.test.ts@@ -451,7 +451,9 @@ describe('UserMemoryIdentityModel', () => {expect(result.pageSize).toBe(100);});- it('should search by query in title', async () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in PGlite+ const isServerDB = process.env.TEST_SERVER_DB === '1';+ it.skipIf(!isServerDB)('should search by query in title', async () => {const result = await identityModel.queryList({q: 'Searchable Title',relationships: [RelationshipEnum.Self, RelationshipEnum.Friend],@@ -461,14 +463,14 @@ describe('UserMemoryIdentityModel', () => {expect(result.items[0].id).toBe('list-id-3');});- it('should search by query in description', async () => {+ it.skipIf(!isServerDB)('should search by query in description', async () => {const result = await identityModel.queryList({ q: 'Searchable description' });expect(result.items).toHaveLength(1);expect(result.items[0].id).toBe('list-id-2');});- it('should search by query in role', async () => {+ it.skipIf(!isServerDB)('should search by query in role', async () => {const result = await identityModel.queryList({ q: 'Searchable role' });expect(result.items).toHaveLength(1);diff --git a/packages/database/src/models/userMemory/__tests__/model.test.ts b/packages/database/src/models/userMemory/__tests__/model.test.tsindex 095f0ccbc3c..7cf3280b6e7 100644--- a/packages/database/src/models/userMemory/__tests__/model.test.ts+++ b/packages/database/src/models/userMemory/__tests__/model.test.ts@@ -488,7 +488,9 @@ describe('UserMemoryModel', () => {expect(result.total).toBe(2);});- it('should filter by text query', async () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in PGlite+ const isServerDB = process.env.TEST_SERVER_DB === '1';+ it.skipIf(!isServerDB)('should filter by text query', async () => {await createContextPair({ title: 'Apple project' });await createContextPair({ title: 'Banana project' });diff --git a/packages/database/src/models/userMemory/activity.ts b/packages/database/src/models/userMemory/activity.tsindex f084621b2d3..9d56dad34ad 100644--- a/packages/database/src/models/userMemory/activity.ts+++ b/packages/database/src/models/userMemory/activity.ts@@ -1,10 +1,11 @@import type { ActivityListParams, ActivityListResult } from '@lobechat/types';import type { SQL } from 'drizzle-orm';-import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, or, sql } from 'drizzle-orm';import type { NewUserMemoryActivity, UserMemoryActivity } from '../../schemas';import { userMemories, userMemoriesActivities } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { sanitizeBm25Query } from '../../utils/bm25';export class UserMemoryActivityModel {private userId: string;@@ -68,16 +69,12 @@ export class UserMemoryActivityModel {const normalizedPageSize = Math.min(Math.max(pageSize, 1), 100);const offset = (normalizedPage - 1) * normalizedPageSize;const normalizedQuery = typeof q === 'string' ? q.trim() : '';+ const bm25Query = normalizedQuery ? sanitizeBm25Query(normalizedQuery) : '';const conditions: Array<SQL | undefined> = [eq(userMemoriesActivities.userId, this.userId),normalizedQuery- ? or(- ilike(userMemories.title, `%${normalizedQuery}%`),- ilike(userMemoriesActivities.narrative, `%${normalizedQuery}%`),- ilike(userMemoriesActivities.notes, `%${normalizedQuery}%`),- ilike(userMemoriesActivities.feedback, `%${normalizedQuery}%`),- )+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemoriesActivities.narrative} @@@ ${bm25Query} OR ${userMemoriesActivities.notes} @@@ ${bm25Query} OR ${userMemoriesActivities.feedback} @@@ ${bm25Query})`: undefined,types && types.length > 0 ? inArray(userMemoriesActivities.type, types) : undefined,status && status.length > 0 ? inArray(userMemoriesActivities.status, status) : undefined,diff --git a/packages/database/src/models/userMemory/experience.ts b/packages/database/src/models/userMemory/experience.tsindex e2da2a0ceda..55a4ca989f0 100644--- a/packages/database/src/models/userMemory/experience.ts+++ b/packages/database/src/models/userMemory/experience.ts@@ -1,10 +1,11 @@import type { ExperienceListParams, ExperienceListResult } from '@lobechat/types';import type { SQL } from 'drizzle-orm';-import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, or, sql } from 'drizzle-orm';import type { NewUserMemoryExperience, UserMemoryExperience } from '../../schemas';import { userMemories, userMemoriesExperiences } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { sanitizeBm25Query } from '../../utils/bm25';export class UserMemoryExperienceModel {private userId: string;@@ -73,18 +74,14 @@ export class UserMemoryExperienceModel {const normalizedPageSize = Math.min(Math.max(pageSize, 1), 100);const offset = (normalizedPage - 1) * normalizedPageSize;const normalizedQuery = typeof q === 'string' ? q.trim() : '';+ const bm25Query = normalizedQuery ? sanitizeBm25Query(normalizedQuery) : '';// Build WHERE conditionsconst conditions: Array<SQL | undefined> = [eq(userMemoriesExperiences.userId, this.userId),// Full-text search across title, situation, keyLearning, actionnormalizedQuery- ? or(- ilike(userMemories.title, `%${normalizedQuery}%`),- ilike(userMemoriesExperiences.situation, `%${normalizedQuery}%`),- ilike(userMemoriesExperiences.keyLearning, `%${normalizedQuery}%`),- ilike(userMemoriesExperiences.action, `%${normalizedQuery}%`),- )+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemoriesExperiences.situation} @@@ ${bm25Query} OR ${userMemoriesExperiences.keyLearning} @@@ ${bm25Query} OR ${userMemoriesExperiences.action} @@@ ${bm25Query})`: undefined,types && types.length > 0 ? inArray(userMemoriesExperiences.type, types) : undefined,tags && tags.length > 0diff --git a/packages/database/src/models/userMemory/identity.ts b/packages/database/src/models/userMemory/identity.tsindex 675b9f11009..0e4d2d42cdc 100644--- a/packages/database/src/models/userMemory/identity.ts+++ b/packages/database/src/models/userMemory/identity.ts@@ -1,11 +1,12 @@import type { IdentityListParams, IdentityListResult } from '@lobechat/types';import { RelationshipEnum } from '@lobechat/types';import type { SQL } from 'drizzle-orm';-import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';import type { NewUserMemoryIdentity, UserMemoryIdentity } from '../../schemas';import { userMemories, userMemoriesIdentities } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { sanitizeBm25Query } from '../../utils/bm25';export class UserMemoryIdentityModel {private userId: string;@@ -74,17 +75,14 @@ export class UserMemoryIdentityModel {const normalizedPageSize = Math.min(Math.max(pageSize, 1), 100);const offset = (normalizedPage - 1) * normalizedPageSize;const normalizedQuery = typeof q === 'string' ? q.trim() : '';+ const bm25Query = normalizedQuery ? sanitizeBm25Query(normalizedQuery) : '';// Build WHERE conditionsconst conditions: Array<SQL | undefined> = [eq(userMemoriesIdentities.userId, this.userId),// Full-text search across title, description, rolenormalizedQuery- ? or(- ilike(userMemories.title, `%${normalizedQuery}%`),- ilike(userMemoriesIdentities.description, `%${normalizedQuery}%`),- ilike(userMemoriesIdentities.role, `%${normalizedQuery}%`),- )+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemoriesIdentities.description} @@@ ${bm25Query} OR ${userMemoriesIdentities.role} @@@ ${bm25Query})`: undefined,types && types.length > 0 ? inArray(userMemoriesIdentities.type, types) : undefined,// Default to 'self' relationship if not specifieddiff --git a/packages/database/src/models/userMemory/model.ts b/packages/database/src/models/userMemory/model.tsindex c508ba78c30..4ccde510768 100644--- a/packages/database/src/models/userMemory/model.ts+++ b/packages/database/src/models/userMemory/model.ts@@ -21,19 +21,7 @@ import {RelationshipEnum,} from '@lobechat/types';import type { AnyColumn, SQL } from 'drizzle-orm';-import {- and,- asc,- cosineDistance,- desc,- eq,- ilike,- inArray,- isNotNull,- ne,- or,- sql,-} from 'drizzle-orm';+import { and, asc, cosineDistance, desc, eq, inArray, isNotNull, ne, or, sql } from 'drizzle-orm';import { merge } from '@/utils/merge';@@ -55,6 +43,7 @@ import {userMemoriesPreferences,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { sanitizeBm25Query } from '../../utils/bm25';import { selectNonVectorColumns } from '../../utils/columns';import { TopicModel } from '../topic';@@ -890,6 +879,7 @@ export class UserMemoryModel {const normalizedQuery = typeof q === 'string' ? q.trim() : '';const resolvedLayer = layer ?? LayersEnum.Context;+ const bm25Query = normalizedQuery ? sanitizeBm25Query(normalizedQuery) : '';const conditions: Array<SQL | undefined> = [eq(userMemories.userId, this.userId),@@ -897,13 +887,6 @@ export class UserMemoryModel {? inArray(userMemories.memoryCategory, categories): undefined,eq(userMemories.memoryLayer, resolvedLayer),- normalizedQuery- ? or(- ilike(userMemories.title, `%${normalizedQuery}%`),- ilike(userMemories.summary, `%${normalizedQuery}%`),- ilike(userMemories.details, `%${normalizedQuery}%`),- )- : undefined,];const filters = conditions.filter((condition): condition is SQL => condition !== undefined);@@ -963,6 +946,9 @@ export class UserMemoryModel {const contextFilters: Array<SQL | undefined> = [whereClause,+ normalizedQuery+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesContexts.title} @@@ ${bm25Query} OR ${userMemoriesContexts.description} @@@ ${bm25Query} OR ${userMemoriesContexts.currentStatus} @@@ ${bm25Query})`+ : undefined,types && types.length > 0 ? inArray(userMemoriesContexts.type, types) : undefined,tags && tags.length > 0? or(@@ -1049,6 +1035,9 @@ export class UserMemoryModel {const activityFilters: Array<SQL | undefined> = [whereClause,+ normalizedQuery+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesActivities.narrative} @@@ ${bm25Query} OR ${userMemoriesActivities.notes} @@@ ${bm25Query} OR ${userMemoriesActivities.feedback} @@@ ${bm25Query})`+ : undefined,types && types.length > 0 ? inArray(userMemoriesActivities.type, types) : undefined,status && status.length > 0 ? inArray(userMemoriesActivities.status, status) : undefined,tags && tags.length > 0@@ -1143,6 +1132,9 @@ export class UserMemoryModel {const experienceFilters: Array<SQL | undefined> = [whereClause,+ normalizedQuery+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesExperiences.situation} @@@ ${bm25Query} OR ${userMemoriesExperiences.keyLearning} @@@ ${bm25Query} OR ${userMemoriesExperiences.action} @@@ ${bm25Query})`+ : undefined,types && types.length > 0 ? inArray(userMemoriesExperiences.type, types) : undefined,tags && tags.length > 0? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesExperiences.tags})`))@@ -1217,6 +1209,9 @@ export class UserMemoryModel {const identityFilters: Array<SQL | undefined> = [whereClause,+ normalizedQuery+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesIdentities.description} @@@ ${bm25Query} OR ${userMemoriesIdentities.role} @@@ ${bm25Query})`+ : undefined,types && types.length > 0 ? inArray(userMemoriesIdentities.type, types) : undefined,tags && tags.length > 0? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesIdentities.tags})`))@@ -1298,6 +1293,9 @@ export class UserMemoryModel {const preferenceFilters: Array<SQL | undefined> = [whereClause,+ normalizedQuery+ ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesPreferences.conclusionDirectives} @@@ ${bm25Query} OR ${userMemoriesPreferences.suggestions} @@@ ${bm25Query})`+ : undefined,types && types.length > 0 ? inArray(userMemoriesPreferences.type, types) : undefined,tags && tags.length > 0? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesPreferences.tags})`))diff --git a/packages/database/src/repositories/home/__tests__/index.test.ts b/packages/database/src/repositories/home/__tests__/index.test.tsindex 9f51f77b744..6d434ec9ce7 100644--- a/packages/database/src/repositories/home/__tests__/index.test.ts+++ b/packages/database/src/repositories/home/__tests__/index.test.ts@@ -416,7 +416,9 @@ describe('HomeRepository', () => {});});- describe('searchAgents', () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in PGlite+ const isServerDB = process.env.TEST_SERVER_DB === '1';+ describe.skipIf(!isServerDB)('searchAgents', () => {beforeEach(async () => {// Create test agents for searchawait clientDB.transaction(async (tx) => {diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex 997e5f46542..2436ed7d4d7 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -4,7 +4,7 @@ import {type SidebarGroup,} from '@lobechat/types';import { cleanObject } from '@lobechat/utils';-import { and, desc, eq, ilike, inArray, not, or } from 'drizzle-orm';+import { and, desc, eq, inArray, not, sql } from 'drizzle-orm';import {agents,@@ -15,6 +15,7 @@ import {sessions,} from '../../schemas';import { type LobeChatDatabase } from '../../type';+import { sanitizeBm25Query } from '../../utils/bm25';// Re-export types for backward compatibilityexport type {@@ -199,52 +200,54 @@ export class HomeRepository {async searchAgents(keyword: string): Promise<SidebarAgentItem[]> {if (!keyword.trim()) return [];- const searchPattern = `%${keyword.toLowerCase()}%`;+ const bm25Query = sanitizeBm25Query(keyword);- // 1. Search agents by title or description- const agentResults = await this.db- .select({- avatar: agents.avatar,- backgroundColor: agents.backgroundColor,- description: agents.description,- id: agents.id,- pinned: agents.pinned,- sessionId: sessions.id,- sessionPinned: sessions.pinned,- title: agents.title,- updatedAt: agents.updatedAt,- })- .from(agents)- .leftJoin(agentsToSessions, eq(agents.id, agentsToSessions.agentId))- .leftJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))- .where(- and(- eq(agents.userId, this.userId),- not(eq(agents.virtual, true)),- or(ilike(agents.title, searchPattern), ilike(agents.description, searchPattern)),- ),- )- .orderBy(desc(agents.updatedAt));-- // 2. Search chat groups by title or description- const chatGroupResults = await this.db- .select({- avatar: chatGroups.avatar,- backgroundColor: chatGroups.backgroundColor,- description: chatGroups.description,- id: chatGroups.id,- pinned: chatGroups.pinned,- title: chatGroups.title,- updatedAt: chatGroups.updatedAt,- })- .from(chatGroups)- .where(- and(- eq(chatGroups.userId, this.userId),- or(ilike(chatGroups.title, searchPattern), ilike(chatGroups.description, searchPattern)),- ),- )- .orderBy(desc(chatGroups.updatedAt));+ // Run agent and chat group searches in parallel+ const [agentResults, chatGroupResults] = await Promise.all([+ // 1. Search agents by title or description (BM25)+ this.db+ .select({+ avatar: agents.avatar,+ backgroundColor: agents.backgroundColor,+ description: agents.description,+ id: agents.id,+ pinned: agents.pinned,+ sessionId: sessions.id,+ sessionPinned: sessions.pinned,+ title: agents.title,+ updatedAt: agents.updatedAt,+ })+ .from(agents)+ .leftJoin(agentsToSessions, eq(agents.id, agentsToSessions.agentId))+ .leftJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))+ .where(+ and(+ eq(agents.userId, this.userId),+ not(eq(agents.virtual, true)),+ sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query})`,+ ),+ )+ .orderBy(desc(agents.updatedAt)),+ // 2. Search chat groups by title or description (BM25)+ this.db+ .select({+ avatar: chatGroups.avatar,+ backgroundColor: chatGroups.backgroundColor,+ description: chatGroups.description,+ id: chatGroups.id,+ pinned: chatGroups.pinned,+ title: chatGroups.title,+ updatedAt: chatGroups.updatedAt,+ })+ .from(chatGroups)+ .where(+ and(+ eq(chatGroups.userId, this.userId),+ sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,+ ),+ )+ .orderBy(desc(chatGroups.updatedAt)),+ ]);// 2.1 Query member avatars for matching chat groupsconst memberAvatarsMap = await this.getChatGroupMemberAvatars(diff --git a/packages/database/src/repositories/search/index.test.ts b/packages/database/src/repositories/search/index.test.tsindex 74db4e2baeb..f79dd50beca 100644--- a/packages/database/src/repositories/search/index.test.ts+++ b/packages/database/src/repositories/search/index.test.ts@@ -32,7 +32,10 @@ beforeEach(async () => {searchRepo = new SearchRepo(serverDB, userId);});-describe('SearchRepo', () => {+// BM25 search requires pg_search extension (ParadeDB), not available in PGlite+const isServerDB = process.env.TEST_SERVER_DB === '1';++describe.skipIf(!isServerDB)('SearchRepo', () => {describe('search - empty query', () => {it('should return empty array for empty query', async () => {const results = await searchRepo.search({ query: '' });@@ -117,8 +120,10 @@ describe('SearchRepo', () => {expect(topicResults[0].title).toBe('React Hooks Guide');});+ // Note: ICU tokenizer treats "react-component.jsx" as a single token,+ // so we search by prefix "react" which matches via BM25it('should find files by name', async () => {- const results = await searchRepo.search({ query: 'react-component' });+ const results = await searchRepo.search({ query: 'react' });const fileResults = results.filter((r) => r.type === 'file');expect(fileResults).toHaveLength(1);@@ -184,46 +189,28 @@ describe('SearchRepo', () => {await serverDB.insert(agents).values(testAgents);});- it('should prioritize exact match (relevance=1)', async () => {+ it('should assign relevance values in valid range', async () => {const results = await searchRepo.search({ query: 'test' });- const exactMatch = results.find((r) => r.type === 'agent' && r.slug === 'exact');- expect(exactMatch).toBeDefined();- expect(exactMatch?.relevance).toBe(1);- });-- it('should rank prefix match second (relevance=2)', async () => {- const results = await searchRepo.search({ query: 'test' });-- const prefixMatch = results.find((r) => r.type === 'agent' && r.slug === 'prefix');- expect(prefixMatch).toBeDefined();- expect(prefixMatch?.relevance).toBe(2);- });-- it('should rank contains match third (relevance=3)', async () => {- const results = await searchRepo.search({ query: 'test' });+ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBe(3);- const containsMatch = results.find((r) => r.type === 'agent' && r.slug === 'contains');- expect(containsMatch).toBeDefined();- expect(containsMatch?.relevance).toBe(3);+ // All relevance values should be in [1, 3] range+ for (const result of agentResults) {+ expect(result.relevance).toBeGreaterThanOrEqual(1);+ expect(result.relevance).toBeLessThanOrEqual(3);+ }});- it('should order results by relevance', async () => {+ it('should rank results by BM25 relevance (lower = better)', async () => {const results = await searchRepo.search({ query: 'test' });const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBe(3);- // Exact match should come first- expect(agentResults[0].slug).toBe('exact');- expect(agentResults[0].relevance).toBe(1);-- // Prefix match should come second- expect(agentResults[1].slug).toBe('prefix');- expect(agentResults[1].relevance).toBe(2);-- // Contains match should come third- expect(agentResults[2].slug).toBe('contains');- expect(agentResults[2].relevance).toBe(3);+ // Best match should have lowest relevance value+ expect(agentResults[0].relevance).toBeLessThanOrEqual(agentResults[1].relevance);+ expect(agentResults[1].relevance).toBeLessThanOrEqual(agentResults[2].relevance);});});@@ -429,9 +416,9 @@ describe('SearchRepo', () => {await serverDB.insert(files).values({fileType: 'text/plain',- name: 'test.txt',+ name: 'test report',size: 100,- url: 'file://test.txt',+ url: 'file://test-report',userId,});});diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.tsindex d0277801e35..cd538ab94c5 100644--- a/packages/database/src/repositories/search/index.ts+++ b/packages/database/src/repositories/search/index.ts@@ -1,7 +1,8 @@-import { and, desc, eq, ilike, ne, or, sql } from 'drizzle-orm';+import { and, eq, ne, sql } from 'drizzle-orm';import {agents,+ chatGroups,documents,files,knowledgeBaseFiles,@@ -11,12 +12,14 @@ import {userMemories,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { sanitizeBm25Query } from '../../utils/bm25';export type SearchResultType =| 'page'| 'pageContent'| 'agent'| 'topic'+ | 'chatGroup'| 'file'| 'folder'| 'memory'@@ -55,6 +58,12 @@ export interface AgentSearchResult extends BaseSearchResult {type: 'agent';}+export interface ChatGroupSearchResult extends BaseSearchResult {+ avatar: string | null;+ backgroundColor: string | null;+ type: 'chatGroup';+}+export interface TopicSearchResult extends BaseSearchResult {agentId: string | null;favorite: boolean | null;@@ -131,6 +140,7 @@ export type SearchResult =| PageSearchResult| PageContentSearchResult| AgentSearchResult+ | ChatGroupSearchResult| TopicSearchResult| FileSearchResult| FolderSearchResult@@ -182,6 +192,9 @@ export class SearchRepo {if ((!type || type === 'agent') && limits.agent > 0) {searchPromises.push(this.searchAgents(trimmedQuery, limits.agent));}+ if ((!type || type === 'chatGroup') && limits.chatGroup > 0) {+ searchPromises.push(this.searchChatGroups(trimmedQuery, limits.chatGroup));+ }if ((!type || type === 'topic') && limits.topic > 0) {searchPromises.push(this.searchTopics(trimmedQuery, limits.topic, agentId));}@@ -222,6 +235,7 @@ export class SearchRepo {contextType?: 'agent' | 'resource' | 'page',): {agent: number;+ chatGroup: number;file: number;folder: number;knowledgeBase: number;@@ -235,6 +249,7 @@ export class SearchRepo {if (type) {return {agent: type === 'agent' ? baseLimit : 0,+ chatGroup: type === 'chatGroup' ? baseLimit : 0,file: type === 'file' ? baseLimit : 0,folder: type === 'folder' ? baseLimit : 0,knowledgeBase: type === 'knowledgeBase' ? baseLimit : 0,@@ -250,6 +265,7 @@ export class SearchRepo {if (contextType === 'page') {return {agent: 3,+ chatGroup: 3,file: 3,folder: 3,knowledgeBase: 3,@@ -265,6 +281,7 @@ export class SearchRepo {if (contextType === 'resource') {return {agent: 3,+ chatGroup: 3,file: 6,folder: 6,knowledgeBase: 6,@@ -280,6 +297,7 @@ export class SearchRepo {if (agentId || contextType === 'agent') {return {agent: 3,+ chatGroup: 3,file: 3,folder: 3,knowledgeBase: 3,@@ -294,6 +312,7 @@ export class SearchRepo {// General context: limit all types to 3return {agent: 3,+ chatGroup: 3,file: 3,folder: 3,knowledgeBase: 3,@@ -306,15 +325,18 @@ export class SearchRepo {}/**- * Calculate relevance score: 1=exact, 2=prefix, 3=contains+ * Map BM25 scores to relevance values compatible with the existing sort system.+ * BM25 score (higher=better) → relevance (1-3, lower=better)*/- private calculateRelevance(value: string | null | undefined, query: string): number {- if (!value) return 3;- const lower = value.toLowerCase();- const queryLower = query.toLowerCase();- if (lower === queryLower) return 1;- if (lower.startsWith(queryLower)) return 2;- return 3;+ private mapScoresToRelevance<T extends { score: number }>(+ rows: T[],+ ): (Omit<T, 'score'> & { relevance: number })[] {+ if (rows.length === 0) return [];+ const maxScore = Math.max(...rows.map((r) => r.score));+ return rows.map(({ score, ...rest }) => ({+ ...rest,+ relevance: maxScore > 0 ? 1 + 2 * (1 - score / maxScore) : 3,+ }));}/**@@ -327,38 +349,41 @@ export class SearchRepo {}/**- * Search agents by title, description, slug, tags+ * Search agents by title, description, slug, tags (BM25)*/private async searchAgents(query: string, limit: number): Promise<AgentSearchResult[]> {- const searchTerm = `%${query}%`;+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db- .select()+ .select({+ avatar: agents.avatar,+ backgroundColor: agents.backgroundColor,+ createdAt: agents.createdAt,+ description: agents.description,+ id: agents.id,+ score: sql<number>`paradedb.score(${agents.id})`,+ slug: agents.slug,+ tags: agents.tags,+ title: agents.title,+ updatedAt: agents.updatedAt,+ }).from(agents).where(and(eq(agents.userId, this.userId),- or(- ilike(agents.title, searchTerm),- ilike(sql`COALESCE(${agents.description}, '')`, searchTerm),- ilike(sql`COALESCE(${agents.slug}, '')`, searchTerm),- sql`${agents.tags} IS NOT NULL AND EXISTS (- SELECT 1 FROM jsonb_array_elements_text(${agents.tags}) AS tag- WHERE tag ILIKE ${searchTerm}- )`,- ),+ sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query} OR ${agents.slug} @@@ ${bm25Query} OR ${agents.tags} @@@ ${bm25Query} OR ${agents.systemRole} @@@ ${bm25Query})`,),)- .orderBy(desc(agents.updatedAt))+ .orderBy(sql`paradedb.score(${agents.id}) DESC`).limit(limit);- return rows.map((row) => ({+ return this.mapScoresToRelevance(rows).map((row) => ({avatar: row.avatar,backgroundColor: row.backgroundColor,createdAt: row.createdAt,description: row.description,id: row.id,- relevance: this.calculateRelevance(row.title, query),+ relevance: row.relevance,slug: row.slug,tags: (row.tags as string[]) || [],title: row.title || '',@@ -368,37 +393,41 @@ export class SearchRepo {}/**- * Search topics by title, content, historySummary+ * Search topics by title, content, description (BM25)*/private async searchTopics(query: string,limit: number,agentId?: string,): Promise<TopicSearchResult[]> {- const searchTerm = `%${query}%`;+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db- .select()+ .select({+ agentId: topics.agentId,+ content: topics.content,+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ id: topics.id,+ score: sql<number>`paradedb.score(${topics.id})`,+ sessionId: topics.sessionId,+ title: topics.title,+ updatedAt: topics.updatedAt,+ }).from(topics).where(and(eq(topics.userId, this.userId),- or(- ilike(sql`COALESCE(${topics.title}, '')`, searchTerm),- ilike(sql`COALESCE(${topics.content}, '')`, searchTerm),- ilike(sql`COALESCE(${topics.historySummary}, '')`, searchTerm),- ),+ sql`(${topics.title} @@@ ${bm25Query} OR ${topics.content} @@@ ${bm25Query} OR ${topics.description} @@@ ${bm25Query})`,),)- .orderBy(desc(topics.updatedAt))+ .orderBy(sql`paradedb.score(${topics.id}) DESC`).limit(limit);- return rows.map((row) => {- // Agent context boosting: current agent's topics get higher priority- let relevance = this.calculateRelevance(row.title, query);+ return this.mapScoresToRelevance(rows).map((row) => {+ let { relevance } = row;if (agentId && row.agentId === agentId) {- // Boost current agent's topics (0.5-0.7 range)- relevance = relevance === 1 ? 0.5 : relevance === 2 ? 0.6 : 0.7;+ relevance = relevance * 0.5;}return {@@ -417,22 +446,14 @@ export class SearchRepo {}/**- * Search messages by content+ * Search messages by content (BM25)*/private async searchMessages(query: string,limit: number,agentId?: string,): Promise<MessageSearchResult[]> {- const searchTerm = `%${query}%`;-- // Split query into words for multi-word search- const words = query.split(/\s+/).filter((w) => w.length > 0);-- const wordConditions =- words.length > 1- ? or(...words.map((word) => ilike(sql`COALESCE(${messages.content}, '')`, `%${word}%`)))- : ilike(sql`COALESCE(${messages.content}, '')`, searchTerm);+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db.select({@@ -443,20 +464,26 @@ export class SearchRepo {id: messages.id,model: messages.model,role: messages.role,+ score: sql<number>`paradedb.score(${messages.id})`,topicId: messages.topicId,updatedAt: messages.updatedAt,}).from(messages).leftJoin(agents, eq(messages.agentId, agents.id))- .where(and(eq(messages.userId, this.userId), ne(messages.role, 'tool'), wordConditions))- .orderBy(desc(messages.createdAt))+ .where(+ and(+ eq(messages.userId, this.userId),+ ne(messages.role, 'tool'),+ sql`${messages.content} @@@ ${bm25Query}`,+ ),+ )+ .orderBy(sql`paradedb.score(${messages.id}) DESC`).limit(limit);- return rows.map((row) => {- // Agent context boosting- let relevance = this.calculateRelevance(row.content, query);+ return this.mapScoresToRelevance(rows).map((row) => {+ let { relevance } = row;if (agentId && row.agentId === agentId) {- relevance = relevance === 1 ? 0.5 : relevance === 2 ? 0.6 : 0.7;+ relevance = relevance * 0.5;}return {@@ -477,10 +504,12 @@ export class SearchRepo {}/**- * Search files by name+ * Search files by name (BM25)+ * Note: ICU tokenizer treats hyphenated/dotted names (e.g. "react-component.jsx") as single tokens,+ * so partial searches like "component" won't match. Full words or prefixes work fine.*/private async searchFiles(query: string, limit: number): Promise<FileSearchResult[]> {- const searchTerm = `%${query}%`;+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db.select({@@ -490,6 +519,7 @@ export class SearchRepo {id: files.id,knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,name: files.name,+ score: sql<number>`paradedb.score(${files.id})`,size: files.size,updatedAt: files.updatedAt,url: files.url,@@ -501,20 +531,20 @@ export class SearchRepo {and(eq(files.userId, this.userId),ne(files.fileType, 'custom/document'),- ilike(files.name, searchTerm),+ sql`${files.name} @@@ ${bm25Query}`,),)- .orderBy(desc(files.updatedAt))+ .orderBy(sql`paradedb.score(${files.id}) DESC`).limit(limit);- return rows.map((row) => ({+ return this.mapScoresToRelevance(rows).map((row) => ({createdAt: row.createdAt,description: this.truncate(row.content),fileType: row.fileType,id: row.id,knowledgeBaseId: row.knowledgeBaseId,name: row.name,- relevance: this.calculateRelevance(row.name, query),+ relevance: row.relevance,size: row.size,title: row.name,type: 'file' as const,@@ -524,36 +554,42 @@ export class SearchRepo {}/**- * Search folders (documents with file_type='custom/folder')+ * Search folders (documents with file_type='custom/folder') (BM25)*/private async searchFolders(query: string, limit: number): Promise<FolderSearchResult[]> {- const searchTerm = `%${query}%`;+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db- .select()+ .select({+ createdAt: documents.createdAt,+ description: documents.description,+ filename: documents.filename,+ id: documents.id,+ knowledgeBaseId: documents.knowledgeBaseId,+ score: sql<number>`paradedb.score(${documents.id})`,+ slug: documents.slug,+ title: documents.title,+ updatedAt: documents.updatedAt,+ }).from(documents).where(and(eq(documents.userId, this.userId),eq(documents.fileType, 'custom/folder'),- or(- ilike(sql`COALESCE(${documents.title}, '')`, searchTerm),- ilike(sql`COALESCE(${documents.filename}, '')`, searchTerm),- ilike(sql`COALESCE(${documents.description}, '')`, searchTerm),- ),+ sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.description} @@@ ${bm25Query})`,),)- .orderBy(desc(documents.updatedAt))+ .orderBy(sql`paradedb.score(${documents.id}) DESC`).limit(limit);- return rows.map((row) => {+ return this.mapScoresToRelevance(rows).map((row) => {const title = row.title || row.filename || 'Untitled';return {createdAt: row.createdAt,description: row.description,id: row.id,knowledgeBaseId: row.knowledgeBaseId,- relevance: this.calculateRelevance(title, query),+ relevance: row.relevance,slug: row.slug,title,type: 'folder' as const,@@ -563,34 +599,38 @@ export class SearchRepo {}/**- * Search pages (documents with file_type='custom/document')+ * Search pages (documents with file_type='custom/document') (BM25)*/private async searchPages(query: string, limit: number): Promise<PageSearchResult[]> {- const searchTerm = `%${query}%`;+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db- .select()+ .select({+ createdAt: documents.createdAt,+ filename: documents.filename,+ id: documents.id,+ score: sql<number>`paradedb.score(${documents.id})`,+ title: documents.title,+ updatedAt: documents.updatedAt,+ }).from(documents).where(and(eq(documents.userId, this.userId),eq(documents.fileType, 'custom/document'),- or(- ilike(sql`COALESCE(${documents.title}, '')`, searchTerm),- ilike(sql`COALESCE(${documents.filename}, '')`, searchTerm),- ),+ sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`,),)- .orderBy(desc(documents.updatedAt))+ .orderBy(sql`paradedb.score(${documents.id}) DESC`).limit(limit);- return rows.map((row) => {+ return this.mapScoresToRelevance(rows).map((row) => {const title = row.title || row.filename || 'Untitled';return {createdAt: row.createdAt,description: null,id: row.id,- relevance: this.calculateRelevance(title, query),+ relevance: row.relevance,title,type: 'page' as const,updatedAt: row.updatedAt,@@ -599,33 +639,37 @@ export class SearchRepo {}/**- * Search memories by title, summary, details+ * Search memories by title, summary, details (BM25)*/private async searchMemories(query: string, limit: number): Promise<MemorySearchResult[]> {- const searchTerm = `%${query}%`;+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db- .select()+ .select({+ createdAt: userMemories.createdAt,+ id: userMemories.id,+ memoryLayer: userMemories.memoryLayer,+ score: sql<number>`paradedb.score(${userMemories.id})`,+ summary: userMemories.summary,+ title: userMemories.title,+ updatedAt: userMemories.updatedAt,+ }).from(userMemories).where(and(eq(userMemories.userId, this.userId),- or(- ilike(sql`COALESCE(${userMemories.title}, '')`, searchTerm),- ilike(sql`COALESCE(${userMemories.summary}, '')`, searchTerm),- ilike(sql`COALESCE(${userMemories.details}, '')`, searchTerm),- ),+ sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query})`,),)- .orderBy(desc(userMemories.updatedAt))+ .orderBy(sql`paradedb.score(${userMemories.id}) DESC`).limit(limit);- return rows.map((row) => ({+ return this.mapScoresToRelevance(rows).map((row) => ({createdAt: row.createdAt,description: this.truncate(row.summary),id: row.id,memoryLayer: row.memoryLayer,- relevance: this.calculateRelevance(row.title, query),+ relevance: row.relevance,title: row.title || 'Untitled Memory',type: 'memory' as const,updatedAt: row.updatedAt,@@ -633,35 +677,80 @@ export class SearchRepo {}/**- * Search knowledge bases by name and description+ * Search chat groups by title and description (BM25)+ */+ private async searchChatGroups(query: string, limit: number): Promise<ChatGroupSearchResult[]> {+ const bm25Query = sanitizeBm25Query(query);++ const rows = await this.db+ .select({+ avatar: chatGroups.avatar,+ backgroundColor: chatGroups.backgroundColor,+ createdAt: chatGroups.createdAt,+ description: chatGroups.description,+ id: chatGroups.id,+ score: sql<number>`paradedb.score(${chatGroups.id})`,+ title: chatGroups.title,+ updatedAt: chatGroups.updatedAt,+ })+ .from(chatGroups)+ .where(+ and(+ eq(chatGroups.userId, this.userId),+ sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,+ ),+ )+ .orderBy(sql`paradedb.score(${chatGroups.id}) DESC`)+ .limit(limit);++ return this.mapScoresToRelevance(rows).map((row) => ({+ avatar: row.avatar,+ backgroundColor: row.backgroundColor,+ createdAt: row.createdAt,+ description: row.description,+ id: row.id,+ relevance: row.relevance,+ title: row.title || '',+ type: 'chatGroup' as const,+ updatedAt: row.updatedAt,+ }));+ }++ /**+ * Search knowledge bases by name and description (BM25)*/private async searchKnowledgeBases(query: string,limit: number,): Promise<KnowledgeBaseSearchResult[]> {- const searchTerm = `%${query}%`;+ const bm25Query = sanitizeBm25Query(query);const rows = await this.db- .select()+ .select({+ avatar: knowledgeBases.avatar,+ createdAt: knowledgeBases.createdAt,+ description: knowledgeBases.description,+ id: knowledgeBases.id,+ name: knowledgeBases.name,+ score: sql<number>`paradedb.score(${knowledgeBases.id})`,+ updatedAt: knowledgeBases.updatedAt,+ }).from(knowledgeBases).where(and(eq(knowledgeBases.userId, this.userId),- or(- ilike(knowledgeBases.name, searchTerm),- ilike(sql`COALESCE(${knowledgeBases.description}, '')`, searchTerm),- ),+ sql`(${knowledgeBases.name} @@@ ${bm25Query} OR ${knowledgeBases.description} @@@ ${bm25Query})`,),)- .orderBy(desc(knowledgeBases.updatedAt))+ .orderBy(sql`paradedb.score(${knowledgeBases.id}) DESC`).limit(limit);- return rows.map((row) => ({+ return this.mapScoresToRelevance(rows).map((row) => ({avatar: row.avatar,createdAt: row.createdAt,description: row.description,id: row.id,- relevance: this.calculateRelevance(row.name, query),+ relevance: row.relevance,title: row.name,type: 'knowledgeBase' as const,updatedAt: row.updatedAt,diff --git a/packages/database/src/utils/bm25.test.ts b/packages/database/src/utils/bm25.test.tsnew file mode 100644index 00000000000..c120b3cbad1--- /dev/null+++ b/packages/database/src/utils/bm25.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import { sanitizeBm25Query } from './bm25';++describe('sanitizeBm25Query', () => {+ it('should join multiple words with AND', () => {+ expect(sanitizeBm25Query('hello world')).toBe('hello AND world');+ });++ it('should return single word as-is', () => {+ expect(sanitizeBm25Query('hello')).toBe('hello');+ });++ it('should escape tantivy special characters', () => {+ expect(sanitizeBm25Query('hello+world')).toBe('hello\\+world');+ expect(sanitizeBm25Query('a-b')).toBe('a AND b');+ expect(sanitizeBm25Query('a&b|c')).toBe('a\\&b\\|c');+ expect(sanitizeBm25Query('a &b| c')).toBe('a AND \\&b\\| AND c');+ expect(sanitizeBm25Query('test!')).toBe('test\\!');+ expect(sanitizeBm25Query('(group)')).toBe('\\(group\\)');+ expect(sanitizeBm25Query('{curly}')).toBe('\\{curly\\}');+ expect(sanitizeBm25Query('[bracket]')).toBe('\\[bracket\\]');+ expect(sanitizeBm25Query('a^b')).toBe('a\\^b');+ expect(sanitizeBm25Query('"quoted"')).toBe('\\"quoted\\"');+ expect(sanitizeBm25Query('~fuzzy')).toBe('\\~fuzzy');+ expect(sanitizeBm25Query('wild*card')).toBe('wild\\*card');+ expect(sanitizeBm25Query('single?char')).toBe('single\\?char');+ expect(sanitizeBm25Query('field:value')).toBe('field\\:value');+ expect(sanitizeBm25Query('back\\slash')).toBe('back\\\\slash');+ expect(sanitizeBm25Query('a/b')).toBe('a\\/b');+ });++ it('should escape multiple special characters and join with AND', () => {+ expect(sanitizeBm25Query('(a+b) & c!')).toBe('\\(a\\+b\\) AND \\& AND c\\!');+ expect(sanitizeBm25Query('react-component')).toBe('react AND component');+ });++ it('should trim whitespace', () => {+ expect(sanitizeBm25Query(' hello ')).toBe('hello');+ expect(sanitizeBm25Query(' hello world ')).toBe('hello AND world');+ });++ it('should throw on empty string', () => {+ expect(() => sanitizeBm25Query('')).toThrow('Query is empty after sanitization');+ });++ it('should throw on whitespace-only string', () => {+ expect(() => sanitizeBm25Query(' ')).toThrow('Query is empty after sanitization');+ });++ it('should handle CJK characters', () => {+ expect(sanitizeBm25Query('你好世界')).toBe('你好世界');+ expect(sanitizeBm25Query('こんにちは')).toBe('こんにちは');+ });+});diff --git a/packages/database/src/utils/bm25.ts b/packages/database/src/utils/bm25.tsnew file mode 100644index 00000000000..d0243c07bda--- /dev/null+++ b/packages/database/src/utils/bm25.ts@@ -0,0 +1,16 @@+/**+ * Escape special tantivy query syntax characters and join terms with AND+ * so all words must match (instead of Tantivy's default OR behavior).+ */+export function sanitizeBm25Query(query: string): string {+ const terms = query+ .trim()+ .replaceAll('-', ' ') // treat hyphens as word separators (ICU tokenizer does the same)+ .split(/\s+/)+ .map((word) => word.replaceAll(/[+&|!(){}[\]^"~*?:\\/]/g, '\\$&'))+ .filter(Boolean);++ if (terms.length === 0) throw new Error('Query is empty after sanitization');++ return terms.join(' AND ');+}diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsxindex db9aa45f53e..b968fbfad15 100644--- a/src/features/CommandMenu/SearchResults.tsx+++ b/src/features/CommandMenu/SearchResults.tsx@@ -12,6 +12,7 @@ import {Plug,Puzzle,Sparkles,+ Users,} from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -47,6 +48,10 @@ const SearchResults = memo<SearchResultsProps>(navigate(`/agent/${result.id}?agent=${result.id}`);break;}+ case 'chatGroup': {+ navigate(`/group/${result.id}`);+ break;+ }case 'topic': {if (result.agentId) {navigate(`/agent/${result.agentId}?topic=${result.id}`);@@ -125,6 +130,9 @@ const SearchResults = memo<SearchResultsProps>(case 'agent': {return <Sparkles size={16} />;}+ case 'chatGroup': {+ return <Users size={16} />;+ }case 'topic': {return <MessageSquare size={16} />;}@@ -163,6 +171,9 @@ const SearchResults = memo<SearchResultsProps>(case 'agent': {return t('cmdk.search.agent');}+ case 'chatGroup': {+ return t('cmdk.search.chatGroup');+ }case 'topic': {return t('cmdk.search.topic');}@@ -235,6 +246,7 @@ const SearchResults = memo<SearchResultsProps>(// Group results by typeconst messageResults = results.filter((r) => r.type === 'message');+ const chatGroupResults = results.filter((r) => r.type === 'chatGroup');const agentResults = results.filter((r) => r.type === 'agent');const topicResults = results.filter((r) => r.type === 'topic');const fileResults = results.filter((r) => r.type === 'file');@@ -338,6 +350,13 @@ const SearchResults = memo<SearchResultsProps>(</Command.Group>)}+ {chatGroupResults.length > 0 && (+ <Command.Group forceMount>+ {chatGroupResults.map((result) => renderResultItem(result))}+ {renderSearchMore('chatGroup', chatGroupResults.length)}+ </Command.Group>+ )}+{topicResults.length > 0 && (<Command.Group forceMount>{topicResults.map((result) => renderResultItem(result))}diff --git a/src/features/CommandMenu/utils/queryParser.test.ts b/src/features/CommandMenu/utils/queryParser.test.tsindex c59de3f95df..6d9bbaab2c2 100644--- a/src/features/CommandMenu/utils/queryParser.test.ts+++ b/src/features/CommandMenu/utils/queryParser.test.ts@@ -51,6 +51,21 @@ describe('parseSearchQuery', () => {});});+ it('should handle case-insensitive matching for camelCase types', () => {+ expect(parseSearchQuery('type:chatgroup search')).toEqual({+ cleanQuery: 'search',+ typeFilter: 'chatGroup',+ });+ expect(parseSearchQuery('type:KNOWLEDGEBASE search')).toEqual({+ cleanQuery: 'search',+ typeFilter: 'knowledgeBase',+ });+ expect(parseSearchQuery('is:communityagent search')).toEqual({+ cleanQuery: 'search',+ typeFilter: 'communityAgent',+ });+ });+it('should ignore invalid type values', () => {const result = parseSearchQuery('type:invalid search');expect(result).toEqual({@@ -76,9 +91,20 @@ describe('parseSearchQuery', () => {});it('should handle all valid types', () => {- // Note: Only lowercase types work because the parser normalizes to lowercase- // and VALID_TYPES comparison is case-sensitive- const types = ['agent', 'topic', 'message', 'file', 'page', 'mcp', 'plugin'];+ const types = [+ 'agent',+ 'chatGroup',+ 'topic',+ 'message',+ 'file',+ 'folder',+ 'page',+ 'memory',+ 'mcp',+ 'plugin',+ 'communityAgent',+ 'knowledgeBase',+ ];for (const type of types) {const result = parseSearchQuery(`type:${type} search`);diff --git a/src/features/CommandMenu/utils/queryParser.ts b/src/features/CommandMenu/utils/queryParser.tsindex 3107a5bee1e..180b43f6e23 100644--- a/src/features/CommandMenu/utils/queryParser.ts+++ b/src/features/CommandMenu/utils/queryParser.ts@@ -13,6 +13,7 @@ export interface ParsedQuery {// Note: 'pageContent' is excluded as it's not yet integrated in the backendconst VALID_TYPES = ['agent',+ 'chatGroup','topic','message','file',@@ -65,9 +66,10 @@ export function parseSearchQuery(query: string): ParsedQuery {const [fullMatch, , typeValue] = match;const normalizedType = typeValue.toLowerCase();- // Validate type- if (VALID_TYPES.includes(normalizedType as ValidSearchType)) {- typeFilter = normalizedType as ValidSearchType;+ // Validate type (case-insensitive match for camelCase types like chatGroup, knowledgeBase)+ const matchedType = VALID_TYPES.find((t) => t.toLowerCase() === normalizedType);+ if (matchedType) {+ typeFilter = matchedType;// Remove the type filter from the querycleanQuery = cleanQuery.replace(fullMatch, ' ').trim();}diff --git a/src/locales/default/common.ts b/src/locales/default/common.tsindex 42b3c535bec..f648938a759 100644--- a/src/locales/default/common.ts+++ b/src/locales/default/common.ts@@ -222,6 +222,10 @@ export default {'cmdk.search.assistants': 'Agents',+ 'cmdk.search.chatGroup': 'Agent Team',++ 'cmdk.search.chatGroups': 'Agent Teams',+'cmdk.search.communityAgent': 'Community Agent','cmdk.search.file': 'File',diff --git a/src/routes/(main)/memory/contexts/index.tsx b/src/routes/(main)/memory/contexts/index.tsxindex e7abc12f002..d21872a0922 100644--- a/src/routes/(main)/memory/contexts/index.tsx+++ b/src/routes/(main)/memory/contexts/index.tsx@@ -49,7 +49,6 @@ const ContextsArea = memo(() => {// Reset list when search or sort changesuseEffect(() => {- if (!apiSort) return;const sort = viewMode === 'grid' ? apiSort : undefined;resetContextsList({ q: searchValue || undefined, sort });}, [searchValue, apiSort, viewMode]);diff --git a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts b/src/server/routers/lambda/__tests__/integration/message.integration.test.tsindex c1c5ddb3f86..f6e93b7e985 100644--- a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/message.integration.test.ts@@ -1015,7 +1015,8 @@ describe('Message Router Integration Tests', () => {});});- describe('searchMessages', () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in integration test DB+ describe.skip('searchMessages', () => {it('should search messages by keyword', async () => {const caller = messageRouter.createCaller(createTestContext(userId));diff --git a/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts b/src/server/routers/lambda/__tests__/integration/topic.integration.test.tsindex e799ce7ca09..e537eca17bf 100644--- a/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts@@ -359,7 +359,8 @@ describe('Topic Router Integration Tests', () => {});});- describe('searchTopics', () => {+ // BM25 search requires pg_search extension (ParadeDB), not available in integration test DB+ describe.skip('searchTopics', () => {it('should search topics using agentId', async () => {const caller = topicRouter.createCaller(createTestContext(userId));diff --git a/src/server/routers/lambda/search.ts b/src/server/routers/lambda/search.tsindex 9342af81c45..ebf1bda5ac5 100644--- a/src/server/routers/lambda/search.ts+++ b/src/server/routers/lambda/search.ts@@ -47,6 +47,7 @@ export const searchRouter = router({type: z.enum(['agent',+ 'chatGroup','topic','file','folder',@@ -71,7 +72,20 @@ export const searchRouter = router({const searchPromises: Promise<any>[] = [];// Database searches (agent, topic, file, folder, message, page, memory)- if (!type || ['agent', 'topic', 'file', 'folder', 'message', 'page', 'memory', 'knowledgeBase'].includes(type)) {+ if (+ !type ||+ [+ 'agent',+ 'chatGroup',+ 'topic',+ 'file',+ 'folder',+ 'message',+ 'page',+ 'memory',+ 'knowledgeBase',+ ].includes(type)+ ) {searchPromises.push(ctx.searchRepo.search(input));}@@ -169,7 +183,7 @@ export const searchRouter = router({),tags: item.tags || null,title: (item.title || item.identifier) as string,- type: 'assistant' as const,+ type: 'communityAgent' as const,updatedAt: new Date(item.updatedAt || Date.now()),})),)diff --git a/src/store/userMemory/slices/context/action.ts b/src/store/userMemory/slices/context/action.tsindex a46b866d0d2..ab3d383d183 100644--- a/src/store/userMemory/slices/context/action.ts+++ b/src/store/userMemory/slices/context/action.ts@@ -92,12 +92,8 @@ export class ContextActionImpl {this.#set(produce((draft) => {draft.contextsSearchLoading = false;-- // Set basic information- if (!draft.contextsInit) {- draft.contextsInit = true;- draft.contextsTotal = data.total;- }+ draft.contextsInit = true;+ draft.contextsTotal = data.total;// Transform data structureconst transformedItems: DisplayContextMemory[] = data.items.map((item: any) => ({