Skip to content

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

✨ feat(cmdk): show agent identity on topic search results (#14204)

Arvin Xu91db61b74f01
diff --git a/packages/database/src/repositories/search/index.test.ts b/packages/database/src/repositories/search/index.test.ts
index 75b7d541a5b..de35015f793 100644
--- a/packages/database/src/repositories/search/index.test.ts
+++ b/packages/database/src/repositories/search/index.test.ts
@@ -567,6 +567,84 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
expect(agentIds.has(otherAgentId)).toBe(true);
});
+ it('should populate agent metadata on topic results', async () => {
+ // Add avatar/background to an existing agent so we can assert join output
+ const [decoratedAgent] = await serverDB
+ .insert(agents)
+ .values({
+ avatar: '🤖',
+ backgroundColor: '#123456',
+ slug: 'decorated-agent',
+ title: 'Decorated Agent',
+ userId,
+ })
+ .returning();
+
+ await serverDB.insert(topics).values({
+ agentId: decoratedAgent.id,
+ title: 'Testing Decorated Agent',
+ userId,
+ });
+
+ const results = await searchRepo.search({ query: 'decorated' });
+ const topicResults = results.filter((r) => r.type === 'topic');
+ const decoratedTopic = topicResults.find(
+ (t) => t.type === 'topic' && t.agentId === decoratedAgent.id,
+ );
+
+ expect(decoratedTopic).toBeDefined();
+ if (decoratedTopic && decoratedTopic.type === 'topic') {
+ expect(decoratedTopic.agent).toEqual({
+ avatar: '🤖',
+ backgroundColor: '#123456',
+ title: 'Decorated Agent',
+ });
+ }
+
+ // Topic without an agent should have a null agent field
+ const orphanTopic = topicResults.find((t) => t.type === 'topic' && t.agentId === null);
+ if (orphanTopic && orphanTopic.type === 'topic') {
+ expect(orphanTopic.agent).toBeNull();
+ }
+ });
+
+ it('should not leak agent metadata when topic.agentId points to another user', async () => {
+ // Foreign agent owned by a different user
+ const [foreignAgent] = await serverDB
+ .insert(agents)
+ .values({
+ avatar: '🕵️',
+ backgroundColor: '#abcdef',
+ slug: 'foreign-agent',
+ title: 'Foreign Agent',
+ userId: otherUserId,
+ })
+ .returning();
+
+ // Topic owned by the current user but carrying the foreign agent id —
+ // simulates state reachable via crafted/migrated rows (e.g. topic
+ // creation persists input.agentId even when resolveContext fails).
+ await serverDB.insert(topics).values({
+ agentId: foreignAgent.id,
+ title: 'Cross-tenant probe',
+ userId,
+ });
+
+ const results = await searchRepo.search({ query: 'cross-tenant' });
+ const topicResults = results.filter((r) => r.type === 'topic');
+ const probeTopic = topicResults.find(
+ (t) => t.type === 'topic' && t.title === 'Cross-tenant probe',
+ );
+
+ expect(probeTopic).toBeDefined();
+ if (probeTopic && probeTopic.type === 'topic') {
+ // The raw agentId is preserved (used for navigation), but no
+ // foreign agent metadata is surfaced to the renderer.
+ expect(probeTopic.agentId).toBe(foreignAgent.id);
+ expect(probeTopic.agent).toBeNull();
+ }
+ });
+
it('should return 6 topics in agent context', async () => {
// Create additional topics to test limit
await serverDB.insert(topics).values(
diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.ts
index 4f93e97e7a1..bbc2becd8f1 100644
--- a/packages/database/src/repositories/search/index.ts
+++ b/packages/database/src/repositories/search/index.ts
@@ -66,6 +66,11 @@ export interface ChatGroupSearchResult extends BaseSearchResult {
}
export interface TopicSearchResult extends BaseSearchResult {
+ agent: {
+ avatar: string | null;
+ backgroundColor: string | null;
+ title: string | null;
+ } | null;
agentId: string | null;
favorite: boolean | null;
sessionId: string | null;
@@ -405,7 +410,16 @@ export class SearchRepo {
const rows = await this.db
.select({
+ // agents.id is selected as a sentinel: non-null only when the JOIN
+ // matched an agent owned by this user. Topics carrying an agentId
+ // that points to another user's agent (possible via migrated/crafted
+ // data) yield null here, so the renderer falls back to the
+ // agent-less subtitle and never surfaces foreign metadata.
+ agentAvatar: agents.avatar,
+ agentBackgroundColor: agents.backgroundColor,
agentId: topics.agentId,
+ agentMatchedId: agents.id,
+ agentTitle: agents.title,
content: topics.content,
createdAt: topics.createdAt,
favorite: topics.favorite,
@@ -416,6 +430,7 @@ export class SearchRepo {
updatedAt: topics.updatedAt,
})
.from(topics)
+ .leftJoin(agents, and(eq(topics.agentId, agents.id), eq(agents.userId, this.userId)))
.where(
and(
eq(topics.userId, this.userId),
@@ -427,6 +442,13 @@ export class SearchRepo {
.limit(limit);
return this.mapScoresToRelevance(rows).map((row) => ({
+ agent: row.agentMatchedId
+ ? {
+ avatar: row.agentAvatar,
+ backgroundColor: row.agentBackgroundColor,
+ title: row.agentTitle,
+ }
+ : null,
agentId: row.agentId,
createdAt: row.createdAt,
description: this.truncate(row.content),
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index 9ef37ac3d72..1e317192be5 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -1,3 +1,5 @@
+import { DEFAULT_AVATAR } from '@lobechat/const';
+import { Avatar, Flexbox } from '@lobehub/ui';
import { Command } from 'cmdk';
import dayjs from 'dayjs';
import {
@@ -14,7 +16,7 @@ import {
Sparkles,
Users,
} from 'lucide-react';
-import { memo } from 'react';
+import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -243,11 +245,40 @@ const SearchResults = memo<SearchResultsProps>(
return result.description;
};
- const getSubtitle = (result: SearchResult) => {
+ const getSubtitle = (result: SearchResult): ReactNode => {
const description = getDescription(result);
- // For topic and message results, append creation date
- if (result.type === 'topic' || result.type === 'message') {
+ // Topic results: prefix with agent identity (avatar + title) so users can
+ // distinguish topics with the same name (e.g. customer email) across agents.
+ if (result.type === 'topic') {
+ const formattedDate = dayjs(result.createdAt).format('MMM D, YYYY');
+ if (!result.agent) {
+ return description ? `${description} · ${formattedDate}` : formattedDate;
+ }
+ return (
+ <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0 }}>
+ <Avatar
+ avatar={result.agent.avatar || DEFAULT_AVATAR}
+ background={result.agent.backgroundColor || undefined}
+ size={14}
+ />
+ <span style={{ flex: 'none' }}>{result.agent.title || t('defaultAgent')}</span>
+ <span style={{ flex: 'none' }}>·</span>
+ <span style={{ flex: 'none' }}>{formattedDate}</span>
+ {description && (
+ <>
+ <span style={{ flex: 'none' }}>·</span>
+ <span style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {description}
+ </span>
+ </>
+ )}
+ </Flexbox>
+ );
+ }
+
+ // For message results, append creation date
+ if (result.type === 'message') {
const formattedDate = dayjs(result.createdAt).format('MMM D, YYYY');
if (description) {
return `${description} · ${formattedDate}`;