Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(commands): add thread search groups to command palette

Steven Enamakelafaa0e7659ed
diff --git a/app/src/components/commands/CommandPalette.tsx b/app/src/components/commands/CommandPalette.tsx
index 4847925e98..99edba5821 100644
--- a/app/src/components/commands/CommandPalette.tsx
+++ b/app/src/components/commands/CommandPalette.tsx
@@ -1,19 +1,27 @@
import { Command } from 'cmdk';
import { Dialog } from 'radix-ui';
-import { useMemo, useSyncExternalStore } from 'react';
+import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { GROUP_LABEL_KEYS } from '../../lib/commands/globalActions';
import { hotkeyManager } from '../../lib/commands/hotkeyManager';
import { registry } from '../../lib/commands/registry';
import type { RegisteredAction } from '../../lib/commands/types';
import { useT } from '../../lib/i18n/I18nContext';
+import type { Thread } from '../../types/thread';
import Kbd from './Kbd';
+import ThreadSearchGroups from './ThreadSearchGroups';
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
+ /** Conversations searchable by title; their messages are searched in the core. */
+ threads?: Thread[];
+ /** Open a conversation picked from the search. Thread search is off without it. */
+ onOpenThread?: (threadId: string) => void;
}
+const NO_THREADS: Thread[] = [];
+
function subscribe(listener: () => void): () => void {
const u1 = registry.subscribe(listener);
const u2 = hotkeyManager.subscribe(listener);
@@ -27,9 +35,20 @@ function getSnapshot(): RegisteredAction[] {
return registry.getActiveActions(hotkeyManager.getStackSymbols());
}
-export default function CommandPalette({ open, onOpenChange }: Props) {
+export default function CommandPalette({
+ open,
+ onOpenChange,
+ threads = NO_THREADS,
+ onOpenThread,
+}: Props) {
const { t } = useT();
const actions = useSyncExternalStore(subscribe, getSnapshot);
+ const [search, setSearch] = useState('');
+
+ // Every opening starts from an empty query.
+ useEffect(() => {
+ if (!open) setSearch('');
+ }, [open]);
const groups = useMemo(() => {
const byGroup = new Map<string, RegisteredAction[]>();
@@ -57,6 +76,11 @@ export default function CommandPalette({ open, onOpenChange }: Props) {
});
}
+ function openThread(threadId: string): void {
+ onOpenChange(false);
+ onOpenThread?.(threadId);
+ }
+
return (
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Portal>
@@ -71,6 +95,8 @@ export default function CommandPalette({ open, onOpenChange }: Props) {
<Command label={t('commandPalette.label')} shouldFilter={true}>
<Command.Input
autoFocus
+ value={search}
+ onValueChange={setSearch}
placeholder={t('commandPalette.placeholder')}
className="w-full px-4 py-3 bg-transparent outline-hidden border-b border-cmd-border text-cmd-foreground placeholder:text-cmd-foreground-muted"
aria-label={t('commandPalette.searchAria')}
@@ -110,6 +136,9 @@ export default function CommandPalette({ open, onOpenChange }: Props) {
})}
</Command.Group>
))}
+ {onOpenThread && (
+ <ThreadSearchGroups query={search} threads={threads} onOpenThread={openThread} />
+ )}
</Command.List>
<div className="flex items-center gap-1.5 px-4 py-2 border-t border-cmd-border text-xs text-cmd-foreground-muted">
{/* Advertise ⌘/ (allowed while this search box is focused) rather
diff --git a/app/src/components/commands/CommandProvider.tsx b/app/src/components/commands/CommandProvider.tsx
index cc7eec2296..77a6e76fa4 100644
--- a/app/src/components/commands/CommandProvider.tsx
+++ b/app/src/components/commands/CommandProvider.tsx
@@ -5,8 +5,9 @@ import { type GlobalActionHandlers, registerGlobalActions } from '../../lib/comm
import { hotkeyManager } from '../../lib/commands/hotkeyManager';
import { registry } from '../../lib/commands/registry';
import { ScopeContext } from '../../lib/commands/ScopeContext';
-import { useAppDispatch } from '../../store/hooks';
+import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { toggleSidebar } from '../../store/layoutSlice';
+import { chatThreadPath } from '../../utils/chatRoutes';
import { APP_SHELL_LAYOUT_ID } from '../layout/shell/RootShellLayout';
import { useNewChat } from '../layout/shell/useNewChat';
import KeyboardShortcutsModal from '../shortcuts/KeyboardShortcutsModal';
@@ -22,6 +23,7 @@ export default function CommandProvider({ children }: Props) {
const navigate = useNavigate();
const dispatch = useAppDispatch();
const newChat = useNewChat();
+ const threads = useAppSelector(state => state.thread.threads);
const [paletteOpen, setPaletteOpen] = useState(false);
const [shortcutsOpen, setShortcutsOpen] = useState(false);
const [globalFrame, setGlobalFrame] = useState<symbol | null>(null);
@@ -90,7 +92,12 @@ export default function CommandProvider({ children }: Props) {
return (
<ScopeContext.Provider value={value}>
{children}
- <CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} />
+ <CommandPalette
+ open={paletteOpen}
+ onOpenChange={setPaletteOpen}
+ threads={threads}
+ onOpenThread={threadId => navigate(chatThreadPath(threadId))}
+ />
<KeyboardShortcutsModal open={shortcutsOpen} onOpenChange={setShortcutsOpen} />
</ScopeContext.Provider>
);
diff --git a/app/src/components/commands/ThreadSearchGroups.tsx b/app/src/components/commands/ThreadSearchGroups.tsx
new file mode 100644
index 0000000000..fca0bad1ca
--- /dev/null
+++ b/app/src/components/commands/ThreadSearchGroups.tsx
@@ -0,0 +1,139 @@
+import { Command } from 'cmdk';
+import debug from 'debug';
+import { MessageSquare, MessagesSquare } from 'lucide-react';
+import { useEffect, useMemo, useState } from 'react';
+
+import { threadMatchesQuery } from '../../features/conversations/threadList/groupThreads';
+import { useT } from '../../lib/i18n/I18nContext';
+import { threadApi } from '../../services/api/threadApi';
+import type { Thread, ThreadSearchHit } from '../../types/thread';
+
+const log = debug('openhuman:commands:thread-search');
+
+/** Conversations matched by title, most recent first. */
+const MAX_TITLE_MATCHES = 8;
+/** Message hits asked of the core per query. */
+const MESSAGE_LIMIT = 20;
+/** Shortest query sent to the message index (its trigrams need three). */
+const MIN_MESSAGE_QUERY = 2;
+/** Typing pause before the message index is queried. */
+const DEBOUNCE_MS = 200;
+
+const GROUP_CLASS =
+ '**:[[cmdk-group-heading]]:px-4 **:[[cmdk-group-heading]]:py-1 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:uppercase **:[[cmdk-group-heading]]:text-cmd-foreground-muted';
+const ITEM_CLASS =
+ 'flex items-center gap-3 px-4 py-2 cursor-pointer aria-selected:bg-cmd-surface-elevated';
+
+interface Props {
+ /** The palette's current input. */
+ query: string;
+ threads: Thread[];
+ onOpenThread: (threadId: string) => void;
+}
+
+/**
+ * The palette's conversation search: threads whose title matches, then
+ * messages anywhere in any thread (`openhuman.threads_search`). Each item lists
+ * the query among its keywords so cmdk's own filter keeps what the core found
+ * by trigram rather than by exact substring.
+ */
+export default function ThreadSearchGroups({ query, threads, onOpenThread }: Props) {
+ const { t } = useT();
+ const needle = query.trim();
+ const [hits, setHits] = useState<ThreadSearchHit[]>([]);
+ const [searching, setSearching] = useState(false);
+
+ useEffect(() => {
+ if (needle.length < MIN_MESSAGE_QUERY) {
+ setHits([]);
+ setSearching(false);
+ return;
+ }
+ let cancelled = false;
+ setSearching(true);
+ const timer = window.setTimeout(() => {
+ threadApi
+ .searchMessages(needle, MESSAGE_LIMIT)
+ .then(found => {
+ if (cancelled) return;
+ log('query_chars=%d hits=%d', needle.length, found.length);
+ setHits(found);
+ })
+ .catch(error => {
+ if (cancelled) return;
+ log('search failed: %o', error);
+ setHits([]);
+ })
+ .finally(() => {
+ if (!cancelled) setSearching(false);
+ });
+ }, DEBOUNCE_MS);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ };
+ }, [needle]);
+
+ const titleMatches = useMemo(() => {
+ if (!needle) return [];
+ return threads
+ .filter(thread => threadMatchesQuery(thread.title ?? '', needle))
+ .sort((a, b) => new Date(b.lastMessageAt).getTime() - new Date(a.lastMessageAt).getTime())
+ .slice(0, MAX_TITLE_MATCHES);
+ }, [threads, needle]);
+
+ const titleOf = useMemo(() => {
+ const byId = new Map(threads.map(thread => [thread.id, thread.title]));
+ return (threadId: string) =>
+ byId.get(threadId)?.trim() || t('commandPalette.untitledConversation');
+ }, [threads, t]);
+
+ if (!needle) return null;
+
+ return (
+ <>
+ {titleMatches.length > 0 && (
+ <Command.Group heading={t('commandPalette.group.conversations')} className={GROUP_CLASS}>
+ {titleMatches.map(thread => (
+ <Command.Item
+ key={thread.id}
+ value={`thread:${thread.id}`}
+ keywords={[needle, thread.title ?? '']}
+ onSelect={() => onOpenThread(thread.id)}
+ data-testid={`palette-thread-${thread.id}`}
+ className={ITEM_CLASS}>
+ <MessagesSquare className="w-4 h-4 text-cmd-foreground-muted" />
+ <span className="flex-1 truncate">{titleOf(thread.id)}</span>
+ </Command.Item>
+ ))}
+ </Command.Group>
+ )}
+ {hits.length > 0 && (
+ <Command.Group heading={t('commandPalette.group.messages')} className={GROUP_CLASS}>
+ {hits.map(hit => (
+ <Command.Item
+ key={`${hit.threadId}:${hit.messageId}`}
+ value={`message:${hit.threadId}:${hit.messageId}`}
+ keywords={[needle, hit.snippet]}
+ onSelect={() => onOpenThread(hit.threadId)}
+ data-testid={`palette-message-${hit.messageId}`}
+ className={ITEM_CLASS}>
+ <MessageSquare className="w-4 h-4 shrink-0 text-cmd-foreground-muted" />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate">{titleOf(hit.threadId)}</span>
+ <span className="truncate text-xs text-cmd-foreground-muted">{hit.snippet}</span>
+ </span>
+ </Command.Item>
+ ))}
+ </Command.Group>
+ )}
+ {searching && hits.length === 0 && (
+ <Command.Loading>
+ <div className="px-4 py-2 text-xs text-cmd-foreground-muted">
+ {t('commandPalette.searchingMessages')}
+ </div>
+ </Command.Loading>
+ )}
+ </>
+ );
+}