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.

⚑️ perf(search): lift agent filter above BM25 scans to restore TopN and real scores (#17755)

Rdmclin2cf8d3505e8a8
diff --git a/apps/server/src/routers/lambda/__tests__/search.test.ts b/apps/server/src/routers/lambda/__tests__/search.test.ts
index 5ed84333ea3..1b0b5debac7 100644
--- a/apps/server/src/routers/lambda/__tests__/search.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/search.test.ts
@@ -95,7 +95,21 @@ describe('searchRouter', () => {
expect(getUserSettings).not.toHaveBeenCalled();
});
- it('preserves global search results when the community agent search rejects', async () => {
+ it('keeps untyped searches including the marketplace by default', async () => {
+ const localResult = { id: 'local-agent', title: 'Local Agent', type: 'agent' };
+ search.mockResolvedValue([localResult]);
+ getAssistantList.mockResolvedValue({ items: [] });
+ const caller = searchRouter.createCaller({ userId: 'test-user' } as any);
+
+ const result = await caller.query({ query: 'assistant' });
+
+ expect(result).toEqual([localResult]);
+ expect(getAssistantList).toHaveBeenCalled();
+ expect(getMcpList).toHaveBeenCalled();
+ expect(getPluginList).toHaveBeenCalled();
+ });
+
+ it('preserves untyped search results when the community agent search rejects', async () => {
const localResult = { id: 'local-agent', title: 'Local Agent', type: 'agent' };
search.mockResolvedValue([localResult]);
getAssistantList.mockRejectedValue(new Error('Market unavailable'));
@@ -115,6 +129,21 @@ describe('searchRouter', () => {
);
});
+ it('keeps the opted-out aggregate search DB-only: no marketplace calls, no market identity', async () => {
+ const localResult = { id: 'local-agent', title: 'Local Agent', type: 'agent' };
+ search.mockResolvedValue([localResult]);
+ const caller = searchRouter.createCaller({ userId: 'test-user' } as any);
+
+ const result = await caller.query({ includeMarketplace: false, query: 'assistant' });
+
+ expect(result).toEqual([localResult]);
+ expect(getAssistantList).not.toHaveBeenCalled();
+ expect(getMcpList).not.toHaveBeenCalled();
+ expect(getPluginList).not.toHaveBeenCalled();
+ expect(UserModel.findById).not.toHaveBeenCalled();
+ expect(getUserSettings).not.toHaveBeenCalled();
+ });
+
it('returns a typed error when the community agent market search fails', async () => {
const marketError = new Error('Market unavailable');
getAssistantList.mockRejectedValue(marketError);
diff --git a/apps/server/src/routers/lambda/search.ts b/apps/server/src/routers/lambda/search.ts
index 0b8f63e9ef0..053c2bdaaf4 100644
--- a/apps/server/src/routers/lambda/search.ts
+++ b/apps/server/src/routers/lambda/search.ts
@@ -23,15 +23,28 @@ function calculateMarketplaceRelevance(query: string, title: string): number {
return 4;
}
+/**
+ * Whether a query input reaches the marketplace at all. Untyped searches
+ * include the marketplace by default (CLI and other callers rely on it);
+ * latency-sensitive callers such as the command menu opt out with
+ * `includeMarketplace: false` to keep the aggregate response DB-only.
+ */
+const wantsMarketplace = (input?: { includeMarketplace?: unknown; type?: unknown }) => {
+ const type = typeof input?.type === 'string' ? input.type : undefined;
+ if (type) return MARKETPLACE_SEARCH_TYPES.has(type);
+ return input?.includeMarketplace !== false;
+};
+
const searchProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
- const rawInput = (await opts.getRawInput()) as { type?: unknown } | undefined;
- const type = typeof rawInput?.type === 'string' ? rawInput.type : undefined;
+ const rawInput = (await opts.getRawInput()) as
+ { includeMarketplace?: unknown; type?: unknown } | undefined;
const wsId = ctx.workspaceId ?? undefined;
- const marketContext =
- !type || MARKETPLACE_SEARCH_TYPES.has(type)
- ? await resolveMarketUserContext(ctx)
- : { marketAccessToken: undefined, marketUserInfo: undefined };
+ // Marketplace identity is only needed when the marketplace will be queried;
+ // DB-only searches skip the extra auth round-trip.
+ const marketContext = wantsMarketplace(rawInput)
+ ? await resolveMarketUserContext(ctx)
+ : { marketAccessToken: undefined, marketUserInfo: undefined };
return opts.next({
ctx: {
@@ -54,6 +67,14 @@ export const searchRouter = router({
.input(
z.object({
agentId: z.string().optional(),
+ /**
+ * Whether an untyped search also queries the marketplace (default
+ * true). The command menu passes false: its aggregate response used to
+ * gate on the slowest of three remote marketplace round-trips on every
+ * keystroke. Ignored when `type` is set β€” an explicit marketplace type
+ * always queries the marketplace, other types never do.
+ */
+ includeMarketplace: z.boolean().optional(),
limitPerType: z.number().optional(),
locale: z.string().optional(),
offset: z.number().optional(),
@@ -103,8 +124,11 @@ export const searchRouter = router({
searchPromises.push(ctx.searchRepo.search(input));
}
- // Marketplace searches (mcp, plugin)
- if (!type || type === 'mcp') {
+ // Marketplace searches: see `includeMarketplace` on the input schema β€”
+ // untyped searches include them by default, the command menu opts out.
+ const marketplaceEnabled = wantsMarketplace(input);
+
+ if (marketplaceEnabled && (!type || type === 'mcp')) {
searchPromises.push(
ctx.discoverService
.getMcpList({
@@ -140,7 +164,7 @@ export const searchRouter = router({
);
}
- if (!type || type === 'plugin') {
+ if (marketplaceEnabled && (!type || type === 'plugin')) {
searchPromises.push(
ctx.discoverService
.getPluginList({
@@ -172,7 +196,7 @@ export const searchRouter = router({
);
}
- if (!type || type === 'communityAgent') {
+ if (marketplaceEnabled && (!type || type === 'communityAgent')) {
searchPromises.push(
ctx.discoverService
.getAssistantList(
diff --git a/packages/database/src/repositories/search/index.test.ts b/packages/database/src/repositories/search/index.test.ts
index f45c06fc85d..9d94b2616d7 100644
--- a/packages/database/src/repositories/search/index.test.ts
+++ b/packages/database/src/repositories/search/index.test.ts
@@ -1489,6 +1489,19 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
expectEveryHitScopedTo(results, 'workspace');
});
+ it('keeps agent-scoped search exact in workspace mode', async () => {
+ const results = await new SearchRepo(serverDB, userId, workspaceId).search({
+ agentId: workspaceAgentId,
+ query: 'Kubernetes',
+ });
+
+ const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');
+ expect(scoped.length).toBeGreaterThan(0);
+ for (const r of scoped) {
+ if (r.type === 'topic' || r.type === 'message') expect(r.agentId).toBe(workspaceAgentId);
+ }
+ });
+
it('should keep joined agent metadata on topics and messages after the scan split', async () => {
const results = await new SearchRepo(serverDB, userId).search({ query: 'Kubernetes' });
@@ -1532,6 +1545,88 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
if (hit?.type === 'file') expect(hit.knowledgeBaseId).toBe(base.id);
});
});
+ // Regression guard for LOBE-12575: the agent filter on topics/messages moved
+ // from inside the BM25 scan to above it (over-fetching through a deep
+ // candidate pool). These tests pin the result semantics that move could
+ // break: rows leaking across agents, and the filter being lost entirely.
+ describe('search - agent scoping', () => {
+ let agentAId: string;
+ let agentBId: string;
+
+ beforeEach(async () => {
+ const insertedAgents = await serverDB
+ .insert(agents)
+ .values([
+ { title: 'Terraform Agent A', userId },
+ { title: 'Terraform Agent B', userId },
+ ])
+ .returning({ id: agents.id, title: agents.title });
+
+ agentAId = insertedAgents.find((a) => a.title === 'Terraform Agent A')!.id;
+ agentBId = insertedAgents.find((a) => a.title === 'Terraform Agent B')!.id;
+
+ await serverDB.insert(topics).values([
+ { agentId: agentAId, title: 'Terraform topic from agent A', userId },
+ { agentId: agentBId, title: 'Terraform topic from agent B', userId },
+ { title: 'Terraform topic without agent', userId },
+ ]);
+
+ await serverDB.insert(messages).values([
+ { agentId: agentAId, content: 'Terraform message from agent A', role: 'user', userId },
+ { agentId: agentBId, content: 'Terraform message from agent B', role: 'user', userId },
+ { content: 'Terraform message without agent', role: 'user', userId },
+ ]);
+ });
+
+ it('should only surface the requested agent rows in topics and messages', async () => {
+ const results = await searchRepo.search({ agentId: agentAId, query: 'Terraform' });
+
+ const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');
+ expect(scoped.length).toBeGreaterThan(0);
+
+ const foreign = scoped.filter(
+ (r) => (r.type === 'topic' || r.type === 'message') && r.agentId !== agentAId,
+ );
+ expect(foreign.map((r) => `${r.type}: ${r.title}`)).toEqual([]);
+ });
+
+ it('should not leak rows between two agent-scoped searches', async () => {
+ const [forA, forB] = await Promise.all([
+ searchRepo.search({ agentId: agentAId, query: 'Terraform' }),
+ searchRepo.search({ agentId: agentBId, query: 'Terraform' }),
+ ]);
+
+ const idsOf = (results: SearchResult[]) =>
+ results.filter((r) => r.type === 'topic' || r.type === 'message').map((r) => r.id);
+
+ expect(idsOf(forA)).toHaveLength(2);
+ expect(idsOf(forB)).toHaveLength(2);
+ expect(idsOf(forA).filter((id) => idsOf(forB).includes(id))).toEqual([]);
+ });
+
+ it('should keep agent-less rows reachable without an agent filter', async () => {
+ const results = await searchRepo.search({ query: 'Terraform' });
+
+ const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');
+ const agentIds = new Set(
+ scoped.map((r) => (r.type === 'topic' || r.type === 'message' ? r.agentId : null)),
+ );
+ expect(agentIds).toEqual(new Set([agentAId, agentBId, null]));
+ });
+
+ it('should keep joined agent metadata after the agent filter moved above the scan', async () => {
+ const results = await searchRepo.search({ agentId: agentAId, query: 'Terraform' });
+
+ const topic = results.find((r) => r.type === 'topic');
+ expect(topic).toBeDefined();
+ if (topic?.type === 'topic') expect(topic.agent?.title).toBe('Terraform Agent A');
+
+ const message = results.find((r) => r.type === 'message');
+ expect(message).toBeDefined();
+ if (message?.type === 'message') expect(message.description).toBe('Terraform Agent A');
+ });
+ });
+
// The workspace-scoping tests above pin *results*, and this change is
// deliberately result-neutral β€” they pass against the pre-fix implementation
// too. What actually fixes LOBE-12379 is the *shape* of the emitted SQL, so
@@ -1550,20 +1645,31 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
await loggingPool?.end();
});
+ interface CapturedStatement {
+ params: unknown[];
+ sql: string;
+ }
+
/** Runs a search against the test DB and returns every BM25 statement it emitted. */
- const captureScanSql = async (workspaceId?: string): Promise<string[]> => {
- const captured: string[] = [];
+ const captureScanSql = async (options?: {
+ agentId?: string;
+ workspaceId?: string;
+ }): Promise<CapturedStatement[]> => {
+ const captured: CapturedStatement[] = [];
loggingPool ??= new NodePool({ connectionString: process.env.DATABASE_TEST_URL });
const db = nodeDrizzle(loggingPool, {
- logger: { logQuery: (query: string) => captured.push(query) },
+ logger: {
+ logQuery: (query: string, params: unknown[]) => captured.push({ params, sql: query }),
+ },
schema,
});
- await new SearchRepo(db as unknown as LobeChatDatabase, userId, workspaceId).search({
+ await new SearchRepo(db as unknown as LobeChatDatabase, userId, options?.workspaceId).search({
+ agentId: options?.agentId,
query: 'kubernetes',
});
- return captured.filter((query) => query.includes('@@@'));
+ return captured.filter(({ sql }) => sql.includes('@@@'));
};
/** Body of the first parenthesised subquery, i.e. the isolated BM25 scan. */
@@ -1581,11 +1687,11 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
};
/** Locates one method's statement and returns its isolated scan, failing loudly if absent. */
- const scanOf = (statements: string[], alias: string): string => {
- const statement = statements.find((query) => query.includes(`"${alias}"`));
+ const scanOf = (statements: CapturedStatement[], alias: string): string => {
+ const statement = statements.find(({ sql }) => sql.includes(`"${alias}"`));
expect(statement, `no statement produced the ${alias} subquery`).toBeDefined();
- const scan = innerScanOf(statement!);
+ const scan = innerScanOf(statement!.sql);
expect(scan, `${alias}: BM25 scan is not isolated in a subquery`).toBeDefined();
return scan!;
@@ -1628,13 +1734,16 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
expect(where).toContain('user_id');
// the filter must survive somewhere, or scoping would silently break
- const statement = statements.find((query) => query.includes(`"${alias}"`))!;
- expect(statement).toContain(`"${alias}"."workspace_id" is null`);
+ const statement = statements.find(({ sql }) => sql.includes(`"${alias}"`))!;
+ expect(statement.sql).toContain(`"${alias}"."workspace_id" is null`);
}
});
it('keeps the ownership predicate exact and inline in workspace mode', async () => {
- const statements = await captureScanSql('search-test-workspace');
+ const statements = await captureScanSql({
+ agentId: 'agent-under-test',
+ workspaceId: 'search-test-workspace',
+ });
for (const alias of SCAN_ALIASES) {
const where = whereClauseOf(scanOf(statements, alias));
@@ -1646,6 +1755,40 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
'workspace_id',
);
}
+
+ // With the workspace qual inline, paradedb.score() is NULL for the whole
+ // statement (pg_search 0.15.26), so a score-ordered pool cut would be an
+ // arbitrary slice. The agent filter must therefore stay inline too β€”
+ // exact, on the already-degraded plan.
+ for (const alias of ['message_hits', 'topic_hits']) {
+ const where = whereClauseOf(scanOf(statements, alias));
+ expect(where, `${alias}: workspace mode must keep the agent filter inline`).toContain(
+ 'agent_id',
+ );
+ }
+ });
+
+ // Guard for LOBE-12575: `agent_id` is not a BM25 field either β€” inside the
+ // scan it costs TopN and, on production pg_search 0.15.26, NULLs out every
+ // score (arbitrary order, flat relevance 3). The agent filter must sit
+ // above the scan, backed by a deepened candidate pool.
+ it('keeps the non-indexed agent filter above the scan in agent context', async () => {
+ const statements = await captureScanSql({ agentId: 'agent-under-test' });
+
+ for (const alias of ['message_hits', 'topic_hits']) {
+ const where = whereClauseOf(scanOf(statements, alias));
+ expect(where, `${alias}: agent qual moved back into the BM25 scan`).not.toContain(
+ 'agent_id',
+ );
+
+ const statement = statements.find(({ sql }) => sql.includes(`"${alias}"`))!;
+
+ // the filter must survive above the scan, or agent scoping would break
+ expect(statement.sql).toContain(`"${alias}"."agent_id" = `);
+
+ // and the pool deepens so small agents survive the lifted filter
+ expect(statement.params, `${alias}: agent-scoped scan pool`).toContain(20_000);
+ }
});
});
});
diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.ts
index 351862a06d3..60170098ec5 100644
--- a/packages/database/src/repositories/search/index.ts
+++ b/packages/database/src/repositories/search/index.ts
@@ -216,18 +216,43 @@ const RECENCY_CANDIDATE_MULTIPLIER = 4;
* So joins always live outside the scan, and the ownership predicate is split by
* `liftsWorkspaceFilter` below.
*
- * Known remaining gap: `agent_id` is not a BM25 field either, so the
- * agent-scoped variants of `searchMessages` / `searchTopics` (the command menu
- * passes the active agent) keep a non-indexed qual inside the scan and do not
- * reach TopN. It is kept inline on purpose β€” `agent_id` is far more selective
- * than the ownership predicate, so lifting it above the scan would drop most of
- * the requested rows rather than merely risk a short result set. The fix is to
- * index the column; tracked with the other missing fast fields in LOBE-12381.
+ * On top of the plan degradation, production pg_search (0.15.26) has a scoring
+ * defect that makes any non-indexed qual inside the scan strictly worse than
+ * slow: `paradedb.score()` returns NULL for *every* row of the statement
+ * (fixed in v0.17.0, see neondatabase/neon#12853). `ORDER BY score DESC` over
+ * an all-NULL column is an arbitrary order, and `mapScoresToRelevance` maps it
+ * to a flat relevance of 3. So a non-indexed qual inside the scan does not
+ * merely cost TopN β€” it silently breaks ranking. That is why no such qual is
+ * ever allowed back inside, and why falling back to the inline-exact query is
+ * not an option: the "exact" query is the broken one.
+ *
+ * `agent_id` is not a BM25 field either, so the agent-scoped variants of
+ * `searchMessages` / `searchTopics` (the command menu passes the active agent)
+ * lift it above the scan the same way, over-fetching through a dedicated
+ * candidate pool (`AGENT_SCOPE_CANDIDATE_POOL`) β€” but only while the scan's
+ * score ordering is real (see `liftsAgentFilter`): trading the exact inline
+ * predicate for a score-ordered pool is unsound when the scores backing that
+ * order are NULL. Indexing the column instead is tracked with the other
+ * missing fast fields in LOBE-12381.
*
* @see https://linear.app/lobehub/issue/LOBE-12379
+ * @see https://linear.app/lobehub/issue/LOBE-12575
*/
const WORKSPACE_FILTER_CANDIDATE_MULTIPLIER = 5;
+/**
+ * Candidate pool for the inner scan when the agent filter is lifted above it.
+ *
+ * `agent_id` is far more selective than the ownership predicate β€” a single
+ * agent can hold well under 1% of an account's matches β€” so the pool has to be
+ * much deeper than the workspace one for small agents to survive the cut. The
+ * agent-scoped caller needs β‰₯ 24 rows to fill its per-type limit (limit 6 Γ—
+ * `RECENCY_CANDIDATE_MULTIPLIER`); measured on a 60k-match account, a pool of
+ * 20k keeps ~50 rows for an agent holding 0.32% of matches, while the TopN
+ * scan's cost stays nearly flat as the pool grows (6ms at 500 β†’ 11ms at 20k).
+ */
+const AGENT_SCOPE_CANDIDATE_POOL = 20_000;
+
/**
* Floor for the personal-mode candidate pool. Rows dropped by the lifted
* `workspace_id IS NULL` check eat into the per-type limit, so an account with
@@ -292,6 +317,23 @@ export class SearchRepo {
return !WORKSPACE_ID_IN_BM25_INDEX && !this.workspaceId;
}
+ /**
+ * Whether the agent filter can be lifted above the BM25 scan.
+ *
+ * Lifting swaps the exact inline predicate for a score-ordered candidate
+ * pool, which is only sound while the scan's `ORDER BY paradedb.score()` is
+ * real. Personal mode qualifies: its scan keeps only pushdown-able quals, so
+ * scores are valid and the pool is genuinely the top-N matches. Workspace
+ * mode does not (until LOBE-12381 makes `workspace_id` a fast field): its
+ * inline `workspace_id` qual NULLs the whole score column on pg_search
+ * 0.15.26, so a pool cut on that ordering would be an arbitrary slice that
+ * silently drops agent rows. It keeps `agent_id` inline next to
+ * `workspace_id` instead β€” exact, on the already-degraded plan.
+ */
+ private get liftsAgentFilter() {
+ return WORKSPACE_ID_IN_BM25_INDEX || !this.workspaceId;
+ }
+
/** Ownership predicate that is safe to keep inside the BM25 scan. */
private scanScopeWhere(cols: WorkspaceScopedColumns): SQL {
if (!this.liftsWorkspaceFilter) return buildWorkspaceWhere(this.scope, cols);
@@ -594,14 +636,19 @@ export class SearchRepo {
.where(
and(
this.scanScopeWhere(topics),
- // Not a BM25 field β€” costs TopN on the agent-scoped path. See the
- // note on the scan-shape invariant above.
- agentId ? eq(topics.agentId, agentId) : undefined,
+ agentId && !this.liftsAgentFilter ? eq(topics.agentId, agentId) : undefined,
sql`(${topics.title} @@@ ${bm25Query} OR ${topics.content} @@@ ${bm25Query} OR ${topics.description} @@@ ${bm25Query})`,
),
)
.orderBy(sql`paradedb.score(${topics.id}) DESC`)
- .limit(this.scanCandidateLimit(candidateLimit))
+ // `agent_id` is not a BM25 field, so where the scan's score order is real
+ // its filter lives above the scan and the pool deepens to compensate. See
+ // the scan-shape invariant and `liftsAgentFilter` above.
+ .limit(
+ agentId && this.liftsAgentFilter
+ ? AGENT_SCOPE_CANDIDATE_POOL
+ : this.scanCandidateLimit(candidateLimit),
+ )
.as('topic_hits');
const rows = await this.db
@@ -629,7 +676,12 @@ export class SearchRepo {
})
.from(hits)
.leftJoin(agents, and(eq(hits.agentId, agents.id), buildWorkspaceWhere(this.scope, agents)))
- .where(this.liftedScopeWhere(hits.workspaceId))
+ .where(
+ and(
+ this.liftedScopeWhere(hits.workspaceId),
+ agentId ? eq(hits.agentId, agentId) : undefined,
+ ),
+ )
.orderBy(desc(hits.score))
.limit(candidateLimit);
@@ -694,14 +746,19 @@ export class SearchRepo {
and(
this.scanScopeWhere(messages),
ne(messages.role, 'tool'),
- // Not a BM25 field β€” costs TopN on the agent-scoped path. See the
- // note on the scan-shape invariant above.
- agentId ? eq(messages.agentId, agentId) : undefined,
+ agentId && !this.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,
sql`${messages.content} @@@ ${bm25Query}`,
),
)
.orderBy(sql`paradedb.score(${messages.id}) DESC`)
- .limit(this.scanCandidateLimit(candidateLimit))
+ // `agent_id` is not a BM25 field, so where the scan's score order is real
+ // its filter lives above the scan and the pool deepens to compensate. See
+ // the scan-shape invariant and `liftsAgentFilter` above.
+ .limit(
+ agentId && this.liftsAgentFilter
+ ? AGENT_SCOPE_CANDIDATE_POOL
+ : this.scanCandidateLimit(candidateLimit),
+ )
.as('message_hits');
const rows = await this.db
@@ -721,7 +778,12 @@ export class SearchRepo {
})
.from(hits)
.leftJoin(agents, eq(hits.agentId, agents.id))
- .where(this.liftedScopeWhere(hits.workspaceId))
+ .where(
+ and(
+ this.liftedScopeWhere(hits.workspaceId),
+ agentId ? eq(hits.agentId, agentId) : undefined,
+ ),
+ )
.orderBy(desc(hits.score))
.limit(candidateLimit);
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index 30d6785b33e..8f6f28f3bc0 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -361,8 +361,11 @@ const SearchResults = memo<SearchResultsProps>(
const knowledgeBaseResults = results.filter((r) => r.type === 'knowledgeBase');
const assistantResults = results.filter((r) => r.type === 'communityAgent');
- // Don't render anything if no results and not loading
- if (!hasResults && !hasLocalTopicResults && !isLoading) {
+ // Don't render anything if no results and not loading β€” except in the
+ // unfiltered view, which always carries the permanent marketplace entries
+ // below (the aggregate response is DB-only, so a query whose matches live
+ // only in the marketplace would otherwise dead-end with no visible route).
+ if (!hasResults && !hasLocalTopicResults && !isLoading && typeFilter) {
return null;
}
@@ -407,13 +410,18 @@ const SearchResults = memo<SearchResultsProps>(
);
};
+ // Marketplace types are absent from the aggregate response (it is DB-only),
+ // so their "Search More" entries must not depend on a non-zero result count.
+ const MARKETPLACE_TYPES: ValidSearchType[] = ['mcp', 'plugin', 'communityAgent'];
+
// Helper to render "Search More" button
const renderSearchMore = (type: ValidSearchType, count: number) => {
// Don't show if already filtering by this type
if (typeFilter) return null;
- // Show if there are results (might have more)
- if (count === 0) return null;
+ // Show if there are results (might have more); marketplace entries always
+ // show β€” they are the only visible route into the explicit marketplace search
+ if (count === 0 && !MARKETPLACE_TYPES.includes(type)) return null;
const typeLabel = getTypeLabel(type);
const titleText = `${t('cmdk.search.searchMore', { type: typeLabel })} with "${searchQuery}"`;
@@ -597,6 +605,17 @@ const SearchResults = memo<SearchResultsProps>(
</Command.Group>
)}
+ {/* The aggregate search is DB-only, so marketplace hits never appear
+ above; keep permanent typed-search entries as the visible route into
+ marketplace discovery. */}
+ {!typeFilter && (
+ <Command.Group forceMount>
+ {renderSearchMore('mcp', mcpResults.length)}
+ {renderSearchMore('plugin', pluginResults.length)}
+ {renderSearchMore('communityAgent', assistantResults.length)}
+ </Command.Group>
+ )}
+
{/* Show loading skeleton below existing results */}
{isLoading && (
<Command.Group forceMount>
diff --git a/src/features/CommandMenu/index.tsx b/src/features/CommandMenu/index.tsx
index d6188c9d40b..4f5ee42266f 100644
--- a/src/features/CommandMenu/index.tsx
+++ b/src/features/CommandMenu/index.tsx
@@ -132,10 +132,15 @@ const CommandMenuContent = memo<CommandMenuContentProps>(({ isClosing, onClose }
<Command.List ref={listRef}>
{/* Hide cmdk's Empty when we have search results or are loading them,
- since force-mounted items aren't counted by cmdk's internal filter */}
- {!(hasSearch && (searchResults.length > 0 || isSearching)) && (
- <Command.Empty>{t('cmdk.noResults')}</Command.Empty>
- )}
+ since force-mounted items aren't counted by cmdk's internal filter.
+ The unfiltered search view also always renders the permanent
+ marketplace entries, so it is never truly empty. */}
+ {!(
+ hasSearch &&
+ (searchResults.length > 0 ||
+ isSearching ||
+ (!page && !selectedAgent && !typeFilter && !search.trimStart().startsWith('@')))
+ ) && <Command.Empty>{t('cmdk.noResults')}</Command.Empty>}
{/* Show send command when agent is selected */}
{selectedAgent && (
diff --git a/src/features/CommandMenu/useCommandMenu.ts b/src/features/CommandMenu/useCommandMenu.ts
index f815639606d..5cf1ca34c5d 100644
--- a/src/features/CommandMenu/useCommandMenu.ts
+++ b/src/features/CommandMenu/useCommandMenu.ts
@@ -67,6 +67,10 @@ export const useCommandMenu = () => {
const locale = globalHelpers.getCurrentLanguage();
return lambdaClient.search.query.query({
agentId,
+ // Keep the aggregate response DB-only: marketplace results are reached
+ // through the permanent typed-search entries instead of gating every
+ // keystroke on three remote marketplace round-trips.
+ includeMarketplace: false,
limitPerType: typeFilter ? 50 : 5, // Show more results when filtering by type
locale,
query: searchQuery,