Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(switchdash): find agents and rooms in the palette, and say what results are (CHOO-1423)

Christian McDermott67ca3b40c728
diff --git a/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts b/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts
index c1eeb6da6..ee1f9e641 100644
--- a/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts
@@ -3,9 +3,16 @@ import { db, sqlite } from '@main/db/client';
import { agents, locations, sessions } from '@main/db/schema';
import { log } from '@main/lib/logger';
import { ALL_COMMAND_DEFS } from '@shared/commands';
+import type { Agent } from '@shared/core/agents/agents';
import type { Location } from '@shared/core/locations/locations';
-import type { CommandPaletteQuery, SearchItem, SearchItemKind } from '@shared/core/search';
+import type {
+ CommandPaletteQuery,
+ SearchItem,
+ SearchItemKind,
+ SearchResult,
+} from '@shared/core/search';
import type { Session } from '@shared/core/sessions/sessions';
+import { agentEvents } from '../agents/agent-events';
import { locationEvents } from '../locations/location-events';
import { sessionHooks } from '../sessions/session-hooks';
import { sessionService } from '../sessions/session-service';
@@ -41,22 +48,29 @@ class SearchService {
this.removeByType('location', locationId)
);
+ agentEvents.on('agent:created', (agent) => this.upsertAgent(agent));
+ agentEvents.on('agent:updated', (agent) => this.upsertAgent(agent));
+ agentEvents.on('agent:deleted', (agentId) => this.removeByType('agent', agentId));
+
this.backfill();
this.seedCommands();
}
- search({ query, context }: CommandPaletteQuery): SearchItem[] {
- if (!query.trim()) return this.recents(context);
+ search({ query, context }: CommandPaletteQuery): SearchResult {
+ if (!query.trim()) return { items: this.recents(context), status: 'recents' };
- // Trigram tokenizer requires each term to be at least 3 characters.
- // Terms shorter than 3 chars are dropped; if nothing survives, fall back
- // to recents rather than sending an invalid query to SQLite.
+ // Trigram tokenizer requires each term to be at least 3 characters, so
+ // shorter terms are dropped. When nothing survives there is no query to
+ // run: recents are returned, but reported as recents so the palette can
+ // say so rather than presenting them as matches.
const terms = query
.trim()
.split(/[\s\-_]+/)
.filter((t) => t.length >= 3);
- if (terms.length === 0) return this.recents(context);
+ if (terms.length === 0) {
+ return { items: this.recents(context), status: 'query-too-short' };
+ }
const ftsQuery = terms.map((t) => `"${t}"`).join(' AND ');
@@ -72,8 +86,8 @@ class SearchService {
)
.all(ftsQuery) as FtsRow[];
} catch (e) {
- log.warn('SearchService: FTS query failed', { query, error: String(e) });
- return [];
+ log.error('SearchService: FTS query failed', { query, error: String(e) });
+ return { items: [], status: 'failed' };
}
const results: SearchItem[] = rows.map((r) => ({
@@ -86,14 +100,17 @@ class SearchService {
score: r.rank,
}));
- if (context?.locationId) {
+ // Only offered when a session is in context: opening a file navigates to a
+ // session, so without one there is nothing to open and the hit would render
+ // as a row that silently does nothing when clicked.
+ if (context?.locationId && context.sessionId) {
const fileHits = locationFileIndexService.search(context.locationId, query);
for (const h of fileHits) {
results.push({
kind: 'file',
id: h.path,
- locationId: context.locationId ?? null,
- sessionId: context.sessionId ?? null,
+ locationId: context.locationId,
+ sessionId: context.sessionId,
title: h.filename,
subtitle: h.path,
score: 0,
@@ -101,7 +118,7 @@ class SearchService {
}
}
- return results;
+ return { items: results, status: 'ok' };
}
private recents(context?: CommandPaletteQuery['context']): SearchItem[] {
@@ -144,6 +161,34 @@ class SearchService {
}));
}
+ /**
+ * Replace one item's row.
+ *
+ * Delete-then-insert rather than `INSERT OR REPLACE`: an FTS5 virtual table
+ * has no unique constraint for the conflict clause to fire on, so `OR REPLACE`
+ * degrades to a plain insert and every update appends a duplicate row instead
+ * of superseding the old one.
+ */
+ private replaceItem(
+ itemType: SearchItemKind,
+ itemId: string,
+ locationId: string | null,
+ title: string,
+ keywords: string
+ ): void {
+ sqlite.transaction(() => {
+ sqlite
+ .prepare(`DELETE FROM search_index WHERE item_id = ? AND item_type = ?`)
+ .run(itemId, itemType);
+ sqlite
+ .prepare(
+ `INSERT INTO search_index(item_type, item_id, location_id, session_id, title, keywords)
+ VALUES (?, ?, ?, NULL, ?, ?)`
+ )
+ .run(itemType, itemId, locationId, title, keywords);
+ })();
+ }
+
private upsertSession(session: Session): void {
try {
const [agent] = db
@@ -152,25 +197,23 @@ class SearchService {
.where(eq(agents.id, session.agentId))
.all();
if (!agent) return;
- sqlite
- .prepare(
- `INSERT OR REPLACE INTO search_index(item_type, item_id, location_id, session_id, title, keywords)
- VALUES ('session', ?, ?, NULL, ?, '')`
- )
- .run(session.id, agent.locationId, session.title);
+ this.replaceItem('session', session.id, agent.locationId, session.title, '');
} catch (e) {
log.warn('SearchService: upsertSession failed', { sessionId: session.id, error: String(e) });
}
}
+ private upsertAgent(agent: Agent): void {
+ try {
+ this.replaceItem('agent', agent.id, agent.locationId, agent.name, agent.providerId);
+ } catch (e) {
+ log.warn('SearchService: upsertAgent failed', { agentId: agent.id, error: String(e) });
+ }
+ }
+
private upsertLocation(location: Location): void {
try {
- sqlite
- .prepare(
- `INSERT OR REPLACE INTO search_index(item_type, item_id, location_id, session_id, title, keywords)
- VALUES ('location', ?, NULL, NULL, ?, ?)`
- )
- .run(location.id, location.name, location.dir);
+ this.replaceItem('location', location.id, null, location.name, location.dir);
} catch (e) {
log.warn('SearchService: upsertLocation failed', {
locationId: location.id,
@@ -226,6 +269,15 @@ class SearchService {
.innerJoin(agents, eq(sessions.agentId, agents.id))
.all();
const allLocations = db.select().from(locations).all();
+ const allAgents = db
+ .select({
+ id: agents.id,
+ locationId: agents.locationId,
+ name: agents.name,
+ providerId: agents.providerId,
+ })
+ .from(agents)
+ .all();
const upsertStmt = sqlite.prepare(
`INSERT OR REPLACE INTO search_index(item_type, item_id, location_id, session_id, title, keywords)
@@ -240,11 +292,15 @@ class SearchService {
for (const l of allLocations) {
upsertStmt.run('location', l.id, null, null, l.name, l.dir);
}
+ for (const a of allAgents) {
+ upsertStmt.run('agent', a.id, a.locationId, null, a.name, a.providerId);
+ }
})();
log.info('SearchService: backfilled search index', {
sessions: allSessions.filter((t) => !t.archivedAt).length,
locations: allLocations.length,
+ agents: allAgents.length,
});
} catch (e) {
log.warn('SearchService: backfill failed', { error: String(e) });
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
index 5ce790c81..b9a500209 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
@@ -1,10 +1,19 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Command } from 'cmdk';
-import { Activity, File, FolderOpen, GitBranch, type LucideIcon } from 'lucide-react';
+import {
+ Activity,
+ Bot,
+ File,
+ FolderOpen,
+ GitBranch,
+ type LucideIcon,
+ MessagesSquare,
+} from 'lucide-react';
import { useObserver } from 'mobx-react-lite';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { commandRegistry } from '@renderer/lib/commands/registry';
import { useDebounce } from '@renderer/lib/hooks/useDebounce';
import { getEffectiveHotkey } from '@renderer/lib/hooks/useKeyboardShortcuts';
@@ -15,14 +24,14 @@ import { appState } from '@renderer/lib/stores/app-state';
import { Shortcut } from '@renderer/lib/ui/shortcut';
import { cn } from '@renderer/utils/utils';
import { ALL_COMMAND_DEFS, type CommandDef } from '@shared/commands';
-import type { SearchItem } from '@shared/core/search';
+import type { SearchItem, SearchResult } from '@shared/core/search';
import { getCommandIcon } from './command-icons';
import { PALETTE_ITEM_CLASS } from './palette-item-styles';
import { PaletteLocationsGroup } from './palette-locations-group';
import { PaletteNotificationsGroup } from './palette-notifications-group';
import { PaletteSessionItem } from './palette-session-item';
import { ResourceMonitorView } from './resource-monitor-view';
-import { applyContextAffinity } from './search-utils';
+import { applyContextAffinity, matchRooms } from './search-utils';
interface CommandPaletteProps {
locationId?: string;
@@ -43,8 +52,14 @@ const KIND_ICON: Record<string, React.ReactNode> = {
action: null,
session: <GitBranch size={14} className="shrink-0 text-foreground/40" />,
location: <FolderOpen size={14} className="shrink-0 text-foreground/40" />,
+ agent: <Bot size={14} className="shrink-0 text-foreground/40" />,
+ room: <MessagesSquare size={14} className="shrink-0 text-foreground/40" />,
};
+/** Stable identity for the un-fetched state, so the default does not create a
+ * new object on every render and retrigger downstream memos. */
+const EMPTY_RESULT: SearchResult = { items: [], status: 'recents' };
+
const GROUP_CLASS = cn(
'[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5',
'[&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium',
@@ -153,7 +168,7 @@ export function CommandPaletteModal({
// oxlint-disable-next-line react/exhaustive-deps
}, []);
- const { data: dbResults = [] } = useQuery({
+ const { data: searchResult = EMPTY_RESULT } = useQuery({
queryKey: ['cmdk-search', debouncedQuery, locationId, sessionId],
queryFn: () =>
rpc.search.commandPalette({
@@ -164,8 +179,6 @@ export function CommandPaletteModal({
// returns cached data instantly rather than waiting for a round-trip.
staleTime: 5_000,
placeholderData: (prev) => prev,
- // Skip FTS queries that the trigram tokenizer would reject (< 3 chars).
- enabled: debouncedQuery.length === 0 || debouncedQuery.length >= 3,
});
const registryActions = useObserver((): PaletteAction[] =>
@@ -221,9 +234,17 @@ export function CommandPaletteModal({
.slice(0, 7);
}, [registryActions, resourceMonitorAction, locationId, sessionId]);
- const rankedDb = applyContextAffinity(dbResults, { locationId });
+ const rankedDb = applyContextAffinity(searchResult.items, { locationId });
const actionResults = actions;
+ // Rooms come from the gateway-backed store rather than the FTS index, and are
+ // read through useObserver so a background refresh reaches the open palette.
+ // Substring-matched, so they answer one- and two-character queries that the
+ // trigram-indexed kinds cannot.
+ const roomResults = useObserver(() =>
+ matchRooms(switchRoomsStore.listedRoomsInActiveScope, debouncedQuery)
+ );
+
const q = debouncedQuery.toLowerCase();
const matchedResourceMonitor =
resourceMonitorAction &&
@@ -251,10 +272,25 @@ export function CommandPaletteModal({
navigate('session', { locationId: item.locationId, sessionId: item.sessionId });
};
+ // There is no per-agent view — the location view is the agents-at-a-location
+ // view — so an agent opens the location it belongs to.
+ const handleNavigateToAgent = (item: SearchItem) => {
+ if (!item.locationId) return;
+ handleClose();
+ navigate('location', { locationId: item.locationId });
+ };
+
+ const handleNavigateToRoom = (item: SearchItem) => {
+ handleClose();
+ navigate('room', { roomId: item.id });
+ };
+
const handleSelect = (item: SearchItem) => {
if (item.kind === 'session') return handleNavigateToSession(item);
if (item.kind === 'location') return handleNavigateToLocation(item);
if (item.kind === 'file') return handleOpenFile(item);
+ if (item.kind === 'agent') return handleNavigateToAgent(item);
+ if (item.kind === 'room') return handleNavigateToRoom(item);
};
const handleResourceMonitorBack = useCallback(() => {
@@ -303,9 +339,35 @@ export function CommandPaletteModal({
<Command.List className="h-96 overflow-y-auto p-1">
{query ? (
<>
- <Command.Empty className="py-8 text-center text-sm text-foreground/40">
- No results for &ldquo;{query}&rdquo;
- </Command.Empty>
+ {searchResult.status === 'ok' && roomResults.length === 0 && (
+ <Command.Empty className="py-8 text-center text-sm text-foreground/40">
+ No results for &ldquo;{query}&rdquo;
+ </Command.Empty>
+ )}
+ {searchResult.status === 'failed' && (
+ <div className="text-destructive px-3 py-6 text-center text-sm">
+ Search failed for &ldquo;{query}&rdquo;. This is an error, not an empty result — see
+ the log for details.
+ </div>
+ )}
+ {searchResult.status === 'query-too-short' && (
+ <div className="px-3 py-6 text-center text-sm text-foreground/40">
+ Type at least 3 characters to search sessions, agents, locations and commands.
+ {roomResults.length > 0 && ' Rooms are matched from the first character.'}
+ </div>
+ )}
+ {roomResults.length > 0 && (
+ <Command.Group heading="Rooms" className={GROUP_CLASS}>
+ {roomResults.map((item) => (
+ <PaletteItem
+ key={`room:${item.id}`}
+ value={`room:${item.id}`}
+ item={item}
+ onSelect={() => handleNavigateToRoom(item)}
+ />
+ ))}
+ </Command.Group>
+ )}
{matchedResourceMonitor && (
<PaletteItem
value={matchedResourceMonitor.id}
@@ -313,72 +375,76 @@ export function CommandPaletteModal({
onSelect={matchedResourceMonitor.execute}
/>
)}
- {rankedDb.map((item) => {
- if (item.kind === 'command') {
- const live = commandRegistry.findById(item.id);
- if (!live || live.enabled === false || live.hideFromPalette) return null;
- const def = ALL_COMMAND_DEFS.find((d) => d.id === item.id) as
- | CommandDef
- | undefined;
- const shortcut = def?.shortcutKey
- ? getEffectiveHotkey(def.shortcutKey, keyboard)
- : null;
- const displayItem: PaletteAction = {
- kind: 'action',
- id: item.id,
- title: live.label,
- subtitle: live.description,
- shortcut,
- icon: getCommandIcon(def?.iconKey),
- execute: () => {
- handleClose();
- live.execute();
- },
- };
- return (
- <PaletteItem
- key={item.id}
- value={item.id}
- item={displayItem}
- onSelect={() => {
+ {/* Only when the items actually answer the query. Under any other
+ status they are recents or nothing, and rendering them here is
+ what made a too-short query look like a result set. */}
+ {searchResult.status === 'ok' &&
+ rankedDb.map((item) => {
+ if (item.kind === 'command') {
+ const live = commandRegistry.findById(item.id);
+ if (!live || live.enabled === false || live.hideFromPalette) return null;
+ const def = ALL_COMMAND_DEFS.find((d) => d.id === item.id) as
+ | CommandDef
+ | undefined;
+ const shortcut = def?.shortcutKey
+ ? getEffectiveHotkey(def.shortcutKey, keyboard)
+ : null;
+ const displayItem: PaletteAction = {
+ kind: 'action',
+ id: item.id,
+ title: live.label,
+ subtitle: live.description,
+ shortcut,
+ icon: getCommandIcon(def?.iconKey),
+ execute: () => {
handleClose();
live.execute();
- }}
- />
- );
- }
- if (item.kind === 'session' && item.locationId) {
- const store = getSessionStore(item.locationId, item.id);
- if (store) {
+ },
+ };
return (
- <PaletteSessionItem
- key={`session:${item.id}`}
- sessionStore={store}
- value={`session:${item.id}`}
- onSelect={() => handleNavigateToSession(item)}
+ <PaletteItem
+ key={item.id}
+ value={item.id}
+ item={displayItem}
+ onSelect={() => {
+ handleClose();
+ live.execute();
+ }}
+ />
+ );
+ }
+ if (item.kind === 'session' && item.locationId) {
+ const store = getSessionStore(item.locationId, item.id);
+ if (store) {
+ return (
+ <PaletteSessionItem
+ key={`session:${item.id}`}
+ sessionStore={store}
+ value={`session:${item.id}`}
+ onSelect={() => handleNavigateToSession(item)}
+ />
+ );
+ }
+ }
+ if (item.kind === 'file') {
+ return (
+ <PaletteFileItem
+ key={`file:${item.id}`}
+ value={`file:${item.id}`}
+ item={item}
+ onSelect={() => handleOpenFile(item)}
/>
);
}
- }
- if (item.kind === 'file') {
return (
- <PaletteFileItem
- key={`file:${item.id}`}
- value={`file:${item.id}`}
+ <PaletteItem
+ key={`${item.kind}:${item.id}`}
+ value={`${item.kind}:${item.id}`}
item={item}
- onSelect={() => handleOpenFile(item)}
+ onSelect={() => handleSelect(item)}
/>
);
- }
- return (
- <PaletteItem
- key={`${item.kind}:${item.id}`}
- value={`${item.kind}:${item.id}`}
- item={item}
- onSelect={() => handleSelect(item)}
- />
- );
- })}
+ })}
</>
) : (
<>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.ts b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.ts
index 48e11fc6b..4fb560a0d 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/search-utils.ts
@@ -1,4 +1,5 @@
import type { SearchItem } from '@shared/core/search';
+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';
/**
* Re-ranks FTS5 results by boosting items belonging to the active location.
@@ -16,3 +17,50 @@ export function applyContextAffinity(
return diff !== 0 ? diff : a.score - b.score;
});
}
+
+/** Rooms shown for one query. Enough to be useful, few enough that they cannot
+ * crowd out the rest of the palette. */
+const ROOM_RESULT_LIMIT = 8;
+
+/**
+ * Matches Switch rooms for the palette.
+ *
+ * Rooms are not in the FTS index — the Switch server owns them and switchdash
+ * deliberately does not mirror them into SQLite — so they are matched here
+ * against the rooms already loaded in `switchRoomsStore`. Two consequences worth
+ * knowing:
+ *
+ * - Matching is a plain case-insensitive substring, so rooms are findable at one
+ * or two characters, below the trigram tokenizer's three-character floor that
+ * the indexed kinds are subject to.
+ * - `score` orders rooms against each other and nothing else. It is an ordinal,
+ * not a BM25 rank, so these items are rendered in their own group rather than
+ * merged into the ranked list — the two number spaces are not comparable and
+ * pretending otherwise would quietly corrupt the ordering of both.
+ */
+export function matchRooms(rooms: RemoteRoomSummary[], query: string): SearchItem[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return [];
+
+ return rooms
+ .flatMap((room) => {
+ const name = room.name.toLowerCase();
+ const at = name.indexOf(q);
+ if (at === -1) return [];
+ return [
+ {
+ kind: 'room' as const,
+ id: room.id,
+ locationId: null,
+ sessionId: null,
+ title: room.name,
+ subtitle: room.description,
+ // A name that starts with the query beats one that merely contains it;
+ // ties break on the shorter name, which is the more exact match.
+ score: at === 0 ? -room.name.length : 1000 + at,
+ },
+ ];
+ })
+ .sort((a, b) => a.score - b.score || a.title.localeCompare(b.title))
+ .slice(0, ROOM_RESULT_LIMIT);
+}
diff --git a/dash/apps/switchdash-desktop/src/shared/core/search.ts b/dash/apps/switchdash-desktop/src/shared/core/search.ts
index 70e5ff12e..4dc83f646 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/search.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/search.ts
@@ -1,4 +1,10 @@
-export type SearchItemKind = 'session' | 'location' | 'command' | 'file';
+/**
+ * `'room'` is produced by the renderer, not the search service: rooms are not
+ * mirrored into SQLite (the Switch server is their source of truth), so they are
+ * matched against the already-loaded `switchRoomsStore` and rendered through the
+ * same item shape as everything else.
+ */
+export type SearchItemKind = 'session' | 'location' | 'command' | 'file' | 'agent' | 'room';
export interface SearchItem {
kind: SearchItemKind;
@@ -10,6 +16,28 @@ export interface SearchItem {
score: number;
}
+/**
+ * Why the accompanying items are what they are. Without this the palette cannot
+ * tell a result set from a consolation prize: an empty query, a query too short
+ * for the trigram tokenizer, and a query whose search failed outright all used
+ * to arrive as a bare array and render identically.
+ */
+export type SearchStatus =
+ /** `items` are matches for the query. */
+ | 'ok'
+ /** No query was entered; `items` are recents, not matches. */
+ | 'recents'
+ /** A query was entered but no term survived the tokenizer's 3-char minimum;
+ * `items` are recents and must be labelled as such. */
+ | 'query-too-short'
+ /** The search itself failed; `items` is empty and that is not "no matches". */
+ | 'failed';
+
+export interface SearchResult {
+ items: SearchItem[];
+ status: SearchStatus;
+}
+
export interface CommandPaletteQuery {
query: string;
context?: {