π€― 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
π fix(topic): scope per-agent topic search by agentId (#15798)
Arvin Xu3335072bdbf7
diff --git a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.tsindex af9e6ca69c3..93d666b234c 100644--- a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts@@ -6,7 +6,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { topicRouter } from '../../topic';-import { cleanupTestUser, createTestContext, createTestUser } from './setup';+import { cleanupTestUser, createTestAgent, createTestContext, createTestUser } from './setup';// We need to mock getServerDB to return our test database instancelet testDB: LobeChatDatabase;@@ -332,30 +332,78 @@ describe('Topic Router Integration Tests', () => {});});- // BM25 search requires pg_search extension (ParadeDB), not available in integration test DB+ // BM25 search requires pg_search extension (ParadeDB), not available in the+ // default integration test DB (PGlite). Run with TEST_SERVER_DB=1 ++ // DATABASE_TEST_URL pointing at a ParadeDB instance to exercise these.describe.skip('searchTopics', () => {it('should search topics using agentId', async () => {const caller = topicRouter.createCaller(createTestContext(userId));- // Create test topics- await caller.createTopic({- title: 'TypeScript Discussion',- sessionId: testSessionId,+ // Topics are agent-native: stored with agentId directly.+ await serverDB.insert(topics).values([+ { agentId: testAgentId, title: 'TypeScript Discussion', userId },+ { agentId: testAgentId, title: 'JavaScript Basics', userId },+ ]);++ const result = await caller.searchTopics({+ agentId: testAgentId,+ keywords: 'TypeScript',});- await caller.createTopic({- title: 'JavaScript Basics',- sessionId: testSessionId,+ expect(result.length).toBeGreaterThan(0);+ expect(result[0].title).toContain('TypeScript');+ });++ // Regression for the "No topics match these filters" bug: topics created by+ // the new agent system carry `agentId` directly with a NULL `sessionId`.+ // The old search resolved agentId -> sessionId and filtered by the+ // container only, so these rows were never matched even though the topics+ // list (which filters by agentId) showed them.+ it('should find agentId-scoped topics that have no sessionId', async () => {+ const caller = topicRouter.createCaller(createTestContext(userId));++ // Insert a topic the way the agent runtime does: agentId set, sessionId null.+ await serverDB.insert(topics).values({+ agentId: testAgentId,+ sessionId: null,+ title: '[email protected]',+ userId,});- // Search using agentIdconst result = await caller.searchTopics({- keywords: 'TypeScript',agentId: testAgentId,+ keywords: '[email protected]',});expect(result.length).toBeGreaterThan(0);- expect(result[0].title).toContain('TypeScript');+ expect(result[0].title).toBe('[email protected]');+ });++ // The agent scope mirrors the topics list exactly (agentId only). A row that+ // shares this agent's resolved session but is owned by a DIFFERENT agent+ // must not leak in β the bug the constrained-session-fallback review flagged.+ it('should not leak another agent topic that shares the session mapping', async () => {+ const caller = topicRouter.createCaller(createTestContext(userId));++ const otherAgentId = await createTestAgent(serverDB, userId);++ await serverDB.insert(topics).values([+ { agentId: testAgentId, title: 'mine [email protected]', userId },+ // Same session, different agent β used to leak via the session fallback.+ {+ agentId: otherAgentId,+ sessionId: testSessionId,+ title: 'theirs [email protected]',+ userId,+ },+ ]);++ const result = await caller.searchTopics({+ agentId: testAgentId,+ keywords: '[email protected]',+ });++ expect(result.map((t) => t.title)).toEqual(['mine [email protected]']);});});diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 1d27afa904f..a2b01c55c06 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -582,7 +582,17 @@ export const topicRouter = router({ctx.workspaceId ?? undefined,);- return ctx.topicModel.queryByKeyword(input.keywords, resolved.sessionId);+ // Scope the search exactly like the topics list (`query`): by agentId+ // directly (the new agent system stamps every topic with an agentId).+ // Passing only the resolved sessionId used to miss every agentId-scoped+ // topic β the cause of "no topics match" in the per-agent Topics search.+ // `containerId` is only the fallback for legacy callers that pass no+ // agentId/groupId.+ return ctx.topicModel.queryByKeyword(input.keywords, {+ agentId: input.agentId,+ containerId: resolved.sessionId,+ groupId: input.groupId,+ });}),/**diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.tsindex c8e82409d6a..38761b659a5 100644--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts@@ -1535,6 +1535,74 @@ describe('TopicModel - Query', () => {expect(result).toHaveLength(1);expect(result[0].id).toBe('title-match-topic');});++ it('should match topics by agentId when the scope provides one (no sessionId)', async () => {+ await serverDB.transaction(async (tx) => {+ await tx.insert(agents).values([{ id: 'search-agent', userId }]);+ await tx.insert(topics).values([+ // New agent system: topic carries agentId but no sessionId.+ { id: 'agent-topic', title: 'Hello world', agentId: 'search-agent', userId },+ { id: 'other-topic', title: 'Hello world', sessionId, userId },+ ]);+ });++ const result = await topicModel.queryByKeyword('hello', { agentId: 'search-agent' });++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('agent-topic');+ });++ it('should not fall back to the session when scoped by agentId (stays consistent with the list)', async () => {+ // The agent scope mirrors `query` exactly: it matches by agentId only,+ // with NO sessionId fallback. A legacy row that another agent owns but+ // shares the resolved session must not leak into this agent's search,+ // and un-backfilled rows the list hides must not appear here either.+ await serverDB.transaction(async (tx) => {+ await tx.insert(agents).values([+ { id: 'search-agent', userId },+ { id: 'other-agent', userId },+ ]);+ await tx.insert(topics).values([+ { id: 'agent-topic', title: 'Hello world', agentId: 'search-agent', userId },+ // Same session mapping, but already stamped for a DIFFERENT agent.+ {+ id: 'other-agent-topic',+ title: 'Hello world',+ agentId: 'other-agent',+ sessionId,+ userId,+ },+ // Legacy, un-backfilled (agentId null) β the list doesn't show it either.+ { id: 'legacy-topic', title: 'Hello legacy', sessionId, userId },+ ]);+ });++ const result = await topicModel.queryByKeyword('hello', {+ agentId: 'search-agent',+ containerId: sessionId,+ });++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('agent-topic');+ });++ it('should not leak other agents topics when scoped by agentId', async () => {+ await serverDB.transaction(async (tx) => {+ await tx.insert(agents).values([+ { id: 'search-agent', userId },+ { id: 'other-agent', userId },+ ]);+ await tx.insert(topics).values([+ { id: 'agent-topic', title: 'Hello world', agentId: 'search-agent', userId },+ { id: 'other-agent-topic', title: 'Hello world', agentId: 'other-agent', userId },+ ]);+ });++ const result = await topicModel.queryByKeyword('hello', { agentId: 'search-agent' });++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('agent-topic');+ });});describe('queryRecent', () => {diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex f71a0baf2d7..6cfcb39adb9 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -110,6 +110,22 @@ interface QueryTopicParams {export interface ModelTimingContext extends TimingSink {}+/**+ * Scope used to constrain a keyword search to a single conversation owner.+ * Mirrors the precedence of {@link TopicModel.query}: groupId > agentId >+ * containerId (legacy sessionId / groupId).+ */+export interface TopicKeywordScope {+ agentId?: string | null;+ /**+ * @deprecated Use agentId or groupId instead. Only consulted when neither+ * agentId nor groupId is provided (legacy / mobile string-arg callers).+ * Container ID (sessionId or groupId) to filter topics by.+ */+ containerId?: string | null;+ groupId?: string | null;+}+export interface ListTopicsForMemoryExtractorCursor {createdAt: Date;id: string;@@ -440,9 +456,18 @@ export class TopicModel {return this.db.select().from(topics).orderBy(topics.updatedAt).where(and(this.ownership()));};- queryByKeyword = async (keyword: string, containerId?: string | null): Promise<TopicItem[]> => {+ queryByKeyword = async (+ keyword: string,+ scope?: string | null | TopicKeywordScope,+ ): Promise<TopicItem[]> => {if (!keyword.trim()) return [];+ // Backward compatibility: a bare string / null second argument is treated+ // as the legacy `containerId` (sessionId or groupId).+ const scopeOptions: TopicKeywordScope =+ scope && typeof scope === 'object' ? scope : { containerId: scope ?? null };+ const scopeCondition = this.matchKeywordScope(scopeOptions);+const bm25Query = sanitizeBm25Query(keyword);// Run title and message content searches in parallel@@ -451,13 +476,7 @@ export class TopicModel {this.db.select().from(topics)- .where(- and(- this.ownership(),- this.matchContainer(containerId),- sql`${topics.title} @@@ ${bm25Query}`,- ),- )+ .where(and(this.ownership(), scopeCondition, sql`${topics.title} @@@ ${bm25Query}`)).orderBy(desc(topics.updatedAt)),// Query topic IDs matching by message content (BM25)this.db@@ -469,7 +488,7 @@ export class TopicModel {this.messageOwnership(),sql`${messages.content} @@@ ${bm25Query}`,this.ownership(),- this.matchContainer(containerId),+ scopeCondition,),).groupBy(messages.topicId),@@ -1034,6 +1053,31 @@ export class TopicModel {return and(isNull(topics.sessionId), isNull(topics.groupId));};+ /**+ * Build the WHERE condition that scopes a keyword search to a single+ * conversation owner. Mirrors {@link TopicModel.query}'s precedence and+ * conditions exactly (groupId > agentId > containerId), so search returns the+ * same set the topics list shows.+ *+ * The agent branch matches `topics.agentId` directly β the new agent system+ * stamps every topic with an agentId, and the old `matchContainer` path+ * (sessionId / groupId only) would miss those rows entirely. It deliberately+ * does NOT fall back to the resolved sessionId: the list has no such fallback+ * either, so adding one would (a) surface un-migrated rows the list hides and+ * (b) leak topics owned by another agent that shares the same session mapping.+ * Legacy rows are backfilled with an agentId by the migration the list query+ * triggers, after which the agentId match finds them.+ */+ private matchKeywordScope = ({+ agentId,+ containerId,+ groupId,+ }: TopicKeywordScope): SQL | undefined => {+ if (groupId) return eq(topics.groupId, groupId);+ if (agentId) return eq(topics.agentId, agentId);+ return this.matchContainer(containerId);+ };+listTopicsForMemoryExtractor = async (options: {cursor?: ListTopicsForMemoryExtractorCursor;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsxindex 6a85f599173..eb6c0172831 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx@@ -60,7 +60,6 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {}, [isSearching]);// Only search when there's a keyword (pass undefined to disable SWR)- // Note: searchTopics uses sessionId in the service, but agentId in the hookuseSearchTopics(isSearching ? trimmedKeyword : undefined, {agentId: activeAgentId,groupId: undefined,