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.

πŸ› fix(command-menu): order topic/message search results by recency (#15094)

Arvin Xu063c0b7a21c6
diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.ts
index b61bbc63b10..a758b8ab571 100644
--- a/packages/database/src/repositories/search/index.ts
+++ b/packages/database/src/repositories/search/index.ts
@@ -180,6 +180,14 @@ export interface SearchOptions {
type?: SearchResultType;
}
+/**
+ * Topics and messages are ordered by recency rather than BM25 score, so we fetch
+ * a larger candidate pool first (most relevant matches), then keep the most recent
+ * ones. This prevents newly created/updated items from being buried under older
+ * high-scoring matches that would otherwise fill the small per-type limit.
+ */
+const RECENCY_CANDIDATE_MULTIPLIER = 4;
+
/**
* Search Repository - provides unified search across Agents, Topics, and Files
*/
@@ -239,10 +247,11 @@ export class SearchRepo {
const results = await Promise.all(searchPromises);
- // Flatten and sort by relevance ASC, then by updatedAt DESC
- return results
- .flat()
- .sort((a, b) => a.relevance - b.relevance || b.updatedAt.getTime() - a.updatedAt.getTime());
+ // Each search method already returns its results in the intended display order
+ // (topics/messages by recency, other types by BM25 score). The command palette
+ // groups results by type, so we only need to preserve each type's internal order
+ // here rather than re-sorting the merged list by relevance.
+ return results.flat();
}
/**
@@ -453,27 +462,30 @@ export class SearchRepo {
),
)
.orderBy(sql`paradedb.score(${topics.id}) DESC`)
- .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),
- favorite: row.favorite,
- id: row.id,
- relevance: row.relevance,
- sessionId: row.sessionId,
- title: row.title || '',
- type: 'topic' as const,
- updatedAt: row.updatedAt,
- }));
+ .limit(limit * RECENCY_CANDIDATE_MULTIPLIER);
+
+ 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),
+ favorite: row.favorite,
+ id: row.id,
+ relevance: row.relevance,
+ sessionId: row.sessionId,
+ title: row.title || '',
+ type: 'topic' as const,
+ updatedAt: row.updatedAt,
+ }))
+ .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())
+ .slice(0, limit);
}
/**
@@ -510,22 +522,25 @@ export class SearchRepo {
),
)
.orderBy(sql`paradedb.score(${messages.id}) DESC`)
- .limit(limit);
+ .limit(limit * RECENCY_CANDIDATE_MULTIPLIER);
- return this.mapScoresToRelevance(rows).map((row) => ({
- agentId: row.agentId,
- content: row.content || '',
- createdAt: row.createdAt,
- description: row.agentTitle || 'General Chat',
- id: row.id,
- model: row.model,
- relevance: row.relevance,
- role: row.role,
- title: this.truncate(row.content) || '',
- topicId: row.topicId,
- type: 'message' as const,
- updatedAt: row.updatedAt,
- }));
+ return this.mapScoresToRelevance(rows)
+ .map((row) => ({
+ agentId: row.agentId,
+ content: row.content || '',
+ createdAt: row.createdAt,
+ description: row.agentTitle || 'General Chat',
+ id: row.id,
+ model: row.model,
+ relevance: row.relevance,
+ role: row.role,
+ title: this.truncate(row.content) || '',
+ topicId: row.topicId,
+ type: 'message' as const,
+ updatedAt: row.updatedAt,
+ }))
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
+ .slice(0, limit);
}
/**
diff --git a/src/features/CommandMenu/index.tsx b/src/features/CommandMenu/index.tsx
index 8be61fcee22..94ee704de69 100644
--- a/src/features/CommandMenu/index.tsx
+++ b/src/features/CommandMenu/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Avatar, stopPropagation } from '@lobehub/ui';
-import { Command } from 'cmdk';
+import { Command, defaultFilter } from 'cmdk';
import { CornerDownLeft } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
@@ -66,12 +66,29 @@ const CommandMenuContent = memo<CommandMenuContentProps>(({ isClosing, onClose }
}
}, [page, setSearch]);
+ // Search result items (value prefixed with "search-result ") are already ranked
+ // and ordered server-side β€” topics/messages by recency. cmdk would otherwise
+ // re-rank them by fuzzy match against the query; returning a constant keeps their
+ // server order (cmdk's sort is stable). They are force-mounted, so visibility is
+ // unaffected. The constant is below a strong command match (1 = exact, ~0.9 =
+ // prefix) so a well-matching built-in command still ranks above search results,
+ // but above incidental fuzzy matches β€” preserving the prior "rank after built-in
+ // commands" intent while fixing the within-group ordering.
+ const commandFilter = useCallback(
+ (itemValue: string, searchValue: string, keywords?: string[]) => {
+ if (itemValue.startsWith('search-result ')) return 0.5;
+ return defaultFilter?.(itemValue, searchValue, keywords) ?? 0;
+ },
+ [],
+ );
+
return (
<div className={styles.overlay} data-closing={isClosing} onClick={onClose}>
<div onClick={stopPropagation}>
<Command
className={styles.commandRoot}
data-closing={isClosing}
+ filter={commandFilter}
shouldFilter={page !== 'ask-ai' && !selectedAgent && !search.trimStart().startsWith('@')}
value={value}
onValueChange={setValue}
diff --git a/src/server/routers/lambda/search.ts b/src/server/routers/lambda/search.ts
index ebf1bda5ac5..ac11d995cfe 100644
--- a/src/server/routers/lambda/search.ts
+++ b/src/server/routers/lambda/search.ts
@@ -193,12 +193,11 @@ export const searchRouter = router({
// Execute searches in parallel and merge results
const results = await Promise.all(searchPromises);
- const mergedResults = results.flat();
- // Sort by relevance and limit total results
- return mergedResults.sort((a, b) => {
- if (a.relevance !== b.relevance) return a.relevance - b.relevance;
- return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
- });
+ // Results arrive pre-ordered per type (DB types from SearchRepo with
+ // topics/messages by recency, marketplace types from the discover service).
+ // The command palette groups results by type, so we keep each source's order
+ // instead of re-sorting the merged list by relevance.
+ return results.flat();
}),
});