Skip to content

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

fix(switchdash): make palette results behave like the sidebar (CHOO-1423)

Christian McDermottcb615bf72707
diff --git a/dash/apps/switchdash-desktop/src/main/core/search/search-service.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/search/search-service.db.test.ts
index 209ffdda5..1284c5413 100644
--- a/dash/apps/switchdash-desktop/src/main/core/search/search-service.db.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/search/search-service.db.test.ts
@@ -218,16 +218,23 @@ describe('searchService', () => {
expect(result.items.filter((i) => i.kind === 'session')).toHaveLength(0);
});
- it('finds sessions and locations alongside agents', () => {
+ it('finds sessions alongside agents', () => {
searchService.initialize();
expect(titles(searchService.search({ query: 'reviewer' }).items)).toEqual([
'Fix the reviewer crash',
'reviewer-bot',
]);
- expect(titles(searchService.search({ query: 'switchdash' }).items)).toContain(
- 'switchdash repo'
- );
+ });
+
+ // Locations are not a user-facing entity anywhere in switchdash — the
+ // sidebar lists agents flatly rather than by directory — so offering them
+ // as results pointed at a concept the product does not have.
+ it('does not index locations', () => {
+ searchService.initialize();
+
+ expect(searchService.search({ query: 'switchdash repo' }).items).toEqual([]);
+ expect(searchService.search({ query: 'other repo' }).items).toEqual([]);
});
});
});
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 ee1f9e641..871f8531d 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
@@ -1,10 +1,9 @@
import { eq } from 'drizzle-orm';
import { db, sqlite } from '@main/db/client';
-import { agents, locations, sessions } from '@main/db/schema';
+import { agents, 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,
@@ -13,7 +12,6 @@ import type {
} 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';
import { locationFileIndexService } from './location-file-index-service';
@@ -43,11 +41,6 @@ class SearchService {
// reconciler pruning a VM session) must also leave the index.
sessionHooks.on('session:deleted', (sessionId) => this.removeByType('session', sessionId));
- locationEvents.on('location:created', (location) => this.upsertLocation(location));
- locationEvents.on('location:deleted', (locationId) =>
- 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));
@@ -211,17 +204,6 @@ class SearchService {
}
}
- private upsertLocation(location: Location): void {
- try {
- this.replaceItem('location', location.id, null, location.name, location.dir);
- } catch (e) {
- log.warn('SearchService: upsertLocation failed', {
- locationId: location.id,
- error: String(e),
- });
- }
- }
-
private removeByType(itemType: string, itemId: string): void {
try {
sqlite
@@ -268,7 +250,6 @@ class SearchService {
.from(sessions)
.innerJoin(agents, eq(sessions.agentId, agents.id))
.all();
- const allLocations = db.select().from(locations).all();
const allAgents = db
.select({
id: agents.id,
@@ -289,9 +270,6 @@ class SearchService {
if (t.archivedAt) continue;
upsertStmt.run('session', t.id, t.locationId, null, t.title, '');
}
- 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);
}
@@ -299,7 +277,6 @@ class SearchService {
log.info('SearchService: backfilled search index', {
sessions: allSessions.filter((t) => !t.archivedAt).length,
- locations: allLocations.length,
agents: allAgents.length,
});
} catch (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 b9a500209..633b47cb0 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
@@ -3,35 +3,43 @@ import { Command } from 'cmdk';
import {
Activity,
Bot,
+ DoorOpen,
File,
- FolderOpen,
- GitBranch,
+ Globe,
+ HardDrive,
type LucideIcon,
- MessagesSquare,
+ MessageSquare,
+ Server,
} from 'lucide-react';
-import { useObserver } from 'mobx-react-lite';
+import { observer, useObserver } from 'mobx-react-lite';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { REMOTE_HOSTS_QUERY_KEY } from '@renderer/features/remote-hosts/query-keys';
import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
+import { agentExpandKey } from '@renderer/features/sidebar/agent-item';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { commandRegistry } from '@renderer/lib/commands/registry';
+import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { useDebounce } from '@renderer/lib/hooks/useDebounce';
import { getEffectiveHotkey } from '@renderer/lib/hooks/useKeyboardShortcuts';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
+import { scopeToLocationServer, scopeToRoomServer } from '@renderer/lib/layout/scope-to-server';
import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
-import { appState } from '@renderer/lib/stores/app-state';
+import { appState, sidebarStore } 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, 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, matchRooms } from './search-utils';
+import { applyContextAffinity, matchHosts, matchRooms, matchServers } from './search-utils';
interface CommandPaletteProps {
locationId?: string;
@@ -48,13 +56,52 @@ interface PaletteAction {
execute: () => void;
}
-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" />,
-};
+const MUTED_ICON = 'size-3.5 shrink-0 text-foreground/40';
+
+/**
+ * The icon a result carries in the left sidebar.
+ *
+ * Deliberately not a static kind→glyph map: the sidebar's icons are conditional
+ * — an agent shows its provider's mark, a room its bridge platform, a server its
+ * management kind — so a flat map can only ever approximate them. Resolving from
+ * the same stores the sidebar reads keeps the two in step instead of leaving a
+ * second set of lookalikes to drift.
+ */
+const PaletteKindIcon = observer(function PaletteKindIcon({ item }: { item: SearchItem }) {
+ switch (item.kind) {
+ case 'agent': {
+ const providerId = agentsStore.agentById(item.id)?.providerId;
+ return providerId ? (
+ <AgentIcon id={providerId} size={14} className="shrink-0" />
+ ) : (
+ <Bot className={MUTED_ICON} />
+ );
+ }
+ case 'room': {
+ const bridgeType = switchRoomsStore.roomBridgeTypeById(item.id);
+ return hasBridgeIcon(bridgeType) ? (
+ <BridgeIcon bridgeType={bridgeType} size={14} className="size-3.5 shrink-0" />
+ ) : (
+ <DoorOpen className={MUTED_ICON} />
+ );
+ }
+ case 'server': {
+ const server = switchServersStore.servers.find((s) => s.id === item.id);
+ if (server?.managementKind === 'remote') return <Server className={MUTED_ICON} />;
+ return server?.managed ? (
+ <HardDrive className={MUTED_ICON} />
+ ) : (
+ <Globe className={MUTED_ICON} />
+ );
+ }
+ case 'host':
+ return <Server className={MUTED_ICON} />;
+ case 'session':
+ return <MessageSquare className={MUTED_ICON} />;
+ default:
+ return null;
+ }
+});
/** Stable identity for the un-fetched state, so the default does not create a
* new object on every render and retrigger downstream memos. */
@@ -96,8 +143,8 @@ function PaletteItem({
const ActionIcon = action?.icon;
const iconNode = ActionIcon ? (
<ActionIcon size={14} className="shrink-0 text-foreground/40" />
- ) : (
- KIND_ICON[item.kind]
+ ) : action ? null : (
+ <PaletteKindIcon item={item as SearchItem} />
);
return (
<Command.Item value={value} onSelect={onSelect} className={cn(PALETTE_ITEM_CLASS, 'group')}>
@@ -137,6 +184,31 @@ function PaletteFileItem({
);
}
+/** One group of renderer-matched results, or nothing when the kind had no hits. */
+function PaletteResultGroup({
+ heading,
+ items,
+ onSelect,
+}: {
+ heading: string;
+ items: SearchItem[];
+ onSelect: (item: SearchItem) => void;
+}) {
+ if (items.length === 0) return null;
+ return (
+ <Command.Group heading={heading} className={GROUP_CLASS}>
+ {items.map((item) => (
+ <PaletteItem
+ key={`${item.kind}:${item.id}`}
+ value={`${item.kind}:${item.id}`}
+ item={item}
+ onSelect={() => onSelect(item)}
+ />
+ ))}
+ </Command.Group>
+ );
+}
+
export function CommandPaletteModal({
locationId,
sessionId,
@@ -237,13 +309,22 @@ export function CommandPaletteModal({
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.
+ // Rooms and servers come from MobX stores rather than the FTS index, read
+ // through useObserver so a background refresh reaches an open palette. Rooms
+ // span every server, not the active one: you search precisely because you do
+ // not know where a thing is.
const roomResults = useObserver(() =>
- matchRooms(switchRoomsStore.listedRoomsInActiveScope, debouncedQuery)
+ matchRooms(switchRoomsStore.listedRoomsOnAllServers, debouncedQuery)
);
+ const serverResults = useObserver(() => matchServers(switchServersStore.servers, debouncedQuery));
+
+ const { data: hosts = [] } = useQuery({
+ queryKey: REMOTE_HOSTS_QUERY_KEY,
+ queryFn: () => rpc.remoteHosts.listHosts(),
+ staleTime: 30_000,
+ });
+ const hostResults = matchHosts(hosts, debouncedQuery);
+ const rendererMatchCount = roomResults.length + serverResults.length + hostResults.length;
const q = debouncedQuery.toLowerCase();
const matchedResourceMonitor =
@@ -257,13 +338,11 @@ export function CommandPaletteModal({
const handleNavigateToSession = (item: SearchItem) => {
if (!item.locationId) return;
+ const locationId = item.locationId;
handleClose();
- navigate('session', { locationId: item.locationId, sessionId: item.id });
- };
-
- const handleNavigateToLocation = (item: SearchItem) => {
- handleClose();
- navigate('location', { locationId: item.id });
+ void scopeToLocationServer(locationId).then(() =>
+ navigate('session', { locationId, sessionId: item.id })
+ );
};
const handleOpenFile = (item: SearchItem) => {
@@ -272,25 +351,48 @@ 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.
+ /**
+ * Opens the agent, matching `sidebar/agent-item.tsx` exactly.
+ *
+ * `agentName` is what selects the agent — without it the location view falls
+ * back to its first agent, so the palette would open a different agent than
+ * the one that was picked. Expanding the group is the sidebar's other half:
+ * it is what makes the agent visible in the tree on arrival.
+ */
const handleNavigateToAgent = (item: SearchItem) => {
if (!item.locationId) return;
+ const locationId = item.locationId;
handleClose();
- navigate('location', { locationId: item.locationId });
+ void scopeToLocationServer(locationId).then(() => {
+ sidebarStore.ensureGroupExpanded(agentExpandKey(item.id));
+ navigate('location', { locationId, agentName: item.title });
+ });
};
const handleNavigateToRoom = (item: SearchItem) => {
handleClose();
- navigate('room', { roomId: item.id });
+ void scopeToRoomServer(item.id).then(() => navigate('room', { roomId: item.id }));
+ };
+
+ const handleNavigateToServer = (item: SearchItem) => {
+ handleClose();
+ void switchServersStore
+ .setActive(item.id)
+ .then(() => navigate('server', { serverId: item.id }));
+ };
+
+ const handleNavigateToHost = (item: SearchItem) => {
+ handleClose();
+ navigate('settings', { tab: 'remote-hosts', host: 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);
+ if (item.kind === 'server') return handleNavigateToServer(item);
+ if (item.kind === 'host') return handleNavigateToHost(item);
};
const handleResourceMonitorBack = useCallback(() => {
@@ -331,7 +433,7 @@ export function CommandPaletteModal({
<Command.Input
value={query}
onValueChange={setQuery}
- placeholder="Search sessions, locations, actions…"
+ placeholder="Search agents, sessions, rooms, servers, actions…"
className="w-full bg-transparent px-3 py-3 text-sm outline-none placeholder:text-foreground/40"
autoFocus
/>
@@ -339,7 +441,7 @@ export function CommandPaletteModal({
<Command.List className="h-96 overflow-y-auto p-1">
{query ? (
<>
- {searchResult.status === 'ok' && roomResults.length === 0 && (
+ {searchResult.status === 'ok' && rendererMatchCount === 0 && (
<Command.Empty className="py-8 text-center text-sm text-foreground/40">
No results for &ldquo;{query}&rdquo;
</Command.Empty>
@@ -352,22 +454,26 @@ export function CommandPaletteModal({
)}
{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.'}
+ Type at least 3 characters to search agents, sessions, files and commands.
+ {rendererMatchCount > 0 &&
+ ' Rooms, servers and hosts 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>
- )}
+ <PaletteResultGroup
+ heading="Rooms"
+ items={roomResults}
+ onSelect={handleNavigateToRoom}
+ />
+ <PaletteResultGroup
+ heading="Servers"
+ items={serverResults}
+ onSelect={handleNavigateToServer}
+ />
+ <PaletteResultGroup
+ heading="Remote hosts"
+ items={hostResults}
+ onSelect={handleNavigateToHost}
+ />
{matchedResourceMonitor && (
<PaletteItem
value={matchedResourceMonitor.id}
@@ -485,14 +591,6 @@ export function CommandPaletteModal({
})}
</Command.Group>
)}
- {!sessionId && (
- <PaletteLocationsGroup
- currentLocationId={locationId}
- limit={5}
- onClose={handleClose}
- navigate={navigate}
- />
- )}
</>
)}
</Command.List>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-locations-group.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-locations-group.tsx
deleted file mode 100644
index 44727f113..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-locations-group.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { Command } from 'cmdk';
-import { FolderOpen } from 'lucide-react';
-import { useObserver } from 'mobx-react-lite';
-import {
- asMounted,
- getLocationManagerStore,
-} from '@renderer/features/locations/stores/location-selectors';
-import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';
-import { cn } from '@renderer/utils/utils';
-import { PALETTE_ITEM_CLASS } from './palette-item-styles';
-
-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',
- '[&_[cmdk-group-heading]]:text-foreground/50'
-);
-
-interface PaletteLocationsGroupProps {
- /** When set, this location is excluded from the list (location scope). Undefined shows all (app scope). */
- currentLocationId: string | undefined;
- limit?: number;
- onClose: () => void;
- navigate: NavigateFnTyped;
-}
-
-export function PaletteLocationsGroup({
- currentLocationId,
- limit,
- onClose,
- navigate,
-}: PaletteLocationsGroupProps) {
- const locations = useObserver(() => {
- const result: Array<{ id: string; name: string }> = [];
- for (const store of getLocationManagerStore().locations.values()) {
- const mounted = asMounted(store);
- if (!mounted) continue;
- if (mounted.data.id === currentLocationId) continue;
- result.push({ id: mounted.data.id, name: store.name ?? mounted.data.id });
- }
- return result;
- });
-
- const visible = limit !== undefined ? locations.slice(0, limit) : locations;
-
- if (visible.length === 0) return null;
-
- return (
- <Command.Group heading="Locations" className={GROUP_CLASS}>
- {visible.map((p) => (
- <Command.Item
- key={p.id}
- value={`location:${p.id}`}
- onSelect={() => {
- navigate('location', { locationId: p.id });
- onClose();
- }}
- className={PALETTE_ITEM_CLASS}
- >
- <FolderOpen size={14} className="shrink-0 text-foreground/40" />
- <span className="flex-1 truncate">{p.name}</span>
- </Command.Item>
- ))}
- </Command.Group>
- );
-}
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 4fb560a0d..02d9ae82d 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,5 +1,5 @@
-import type { SearchItem } from '@shared/core/search';
-import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';
+import type { SearchItem, SearchItemKind } from '@shared/core/search';
+import type { RemoteRoomSummary, SwitchServer } from '@shared/core/switch-servers/switch-servers';
/**
* Re-ranks FTS5 results by boosting items belonging to the active location.
@@ -18,49 +18,96 @@ export function applyContextAffinity(
});
}
-/** 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;
+/** Per-kind cap for renderer-matched results. Enough to be useful, few enough
+ * that one kind cannot crowd out the rest of the palette. */
+const RENDERER_RESULT_LIMIT = 8;
/**
- * Matches Switch rooms for the palette.
+ * Rank one renderer-matched candidate, or null when the query does not match.
*
- * 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:
+ * `score` orders these against each other and nothing else. It is an ordinal,
+ * not a BM25 rank, so renderer-matched kinds render in their own groups rather
+ * than merged into the indexed results — the two number spaces are not
+ * comparable, and pretending otherwise would quietly corrupt the ordering of
+ * both.
*
- * - 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.
+ * Matching is a plain case-insensitive substring, so these kinds answer one- and
+ * two-character queries, below the trigram tokenizer's three-character floor
+ * that the indexed kinds are subject to.
+ */
+function rank(haystack: string, query: string): number | null {
+ const at = haystack.toLowerCase().indexOf(query);
+ if (at === -1) return null;
+ // 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.
+ return at === 0 ? -haystack.length : 1000 + at;
+}
+
+function finalise(items: SearchItem[]): SearchItem[] {
+ return items
+ .sort((a, b) => a.score - b.score || a.title.localeCompare(b.title))
+ .slice(0, RENDERER_RESULT_LIMIT);
+}
+
+function item(
+ kind: SearchItemKind,
+ id: string,
+ title: string,
+ subtitle: string,
+ score: number
+): SearchItem {
+ return { kind, id, locationId: null, sessionId: null, title, subtitle, score };
+}
+
+/**
+ * Matches Switch rooms, across every server rather than the active one — you
+ * search because you do not know where a thing is. Selecting one switches the
+ * active server so the sidebar follows.
*/
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,
- },
- ];
+ return finalise(
+ rooms.flatMap((room) => {
+ const score = rank(room.name, q);
+ return score === null ? [] : [item('room', room.id, room.name, room.description, score)];
})
- .sort((a, b) => a.score - b.score || a.title.localeCompare(b.title))
- .slice(0, ROOM_RESULT_LIMIT);
+ );
+}
+
+/** Matches Switch servers. Also matches on gateway URL, since a server is as
+ * often recognised by where it lives as by what it was named. */
+export function matchServers(servers: SwitchServer[], query: string): SearchItem[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return [];
+
+ return finalise(
+ servers.flatMap((server) => {
+ const score = rank(server.name, q) ?? rank(server.gatewayUrl, q);
+ return score === null
+ ? []
+ : [item('server', server.id, server.name, server.gatewayUrl, score)];
+ })
+ );
+}
+
+/**
+ * Matches onboarded remote hosts. The SSH alias is the host's identity (it is
+ * the primary key), so it is matched as well as the display name — the alias is
+ * usually what someone remembers.
+ */
+export function matchHosts(
+ hosts: { sshHost: string; name: string }[],
+ query: string
+): SearchItem[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return [];
+
+ return finalise(
+ hosts.flatMap((host) => {
+ const score = rank(host.name, q) ?? rank(host.sshHost, q);
+ return score === null ? [] : [item('host', host.sshHost, host.name, host.sshHost, score)];
+ })
+ );
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
index 7bb15e490..785c39181 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
@@ -134,6 +134,30 @@ export class SwitchRoomsStore {
return listed.sort((a, b) => a.name.localeCompare(b.name));
}
+ /**
+ * The same listed rooms as {@link listedRoomsInActiveScope}, but across every
+ * server rather than the active one.
+ *
+ * Search is deliberately not scoped to the active server: you search precisely
+ * because you do not know where a thing is, and a result set silently limited
+ * to the server you happen to be looking at cannot answer that. Navigating to
+ * one of these switches the active server (see `scopeToRoomServer`), so the
+ * sidebar follows you there rather than filtering the room back out.
+ */
+ get listedRoomsOnAllServers(): RemoteRoomSummary[] {
+ const serverIds = [
+ ...new Set([...this.allRoomsByServer.keys(), ...this.ownedRoomsByServer.keys()]),
+ ];
+ const listed = serverIds.flatMap((serverId) => {
+ const managed = switchServersStore.servers.find((s) => s.id === serverId)?.managed ?? false;
+ return (
+ (managed ? this.allRoomsByServer.get(serverId) : this.ownedRoomsByServer.get(serverId)) ??
+ []
+ );
+ });
+ return listed.sort((a, b) => a.name.localeCompare(b.name));
+ }
+
/**
* The messaging-app values worth offering as a room filter on the active
* server: the bridge types actually in use, plus the unbridged sentinel when
diff --git a/dash/apps/switchdash-desktop/src/renderer/tests/palette-search-utils.test.ts b/dash/apps/switchdash-desktop/src/renderer/tests/palette-search-utils.test.ts
index 047035c1a..62087f704 100644
--- a/dash/apps/switchdash-desktop/src/renderer/tests/palette-search-utils.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/tests/palette-search-utils.test.ts
@@ -1,7 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { applyContextAffinity, matchRooms } from '@renderer/features/command-palette/search-utils';
+import {
+ applyContextAffinity,
+ matchHosts,
+ matchRooms,
+ matchServers,
+} from '@renderer/features/command-palette/search-utils';
import type { SearchItem } from '@shared/core/search';
-import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';
+import type { RemoteRoomSummary, SwitchServer } from '@shared/core/switch-servers/switch-servers';
function room(over: Pick<RemoteRoomSummary, 'id' | 'name'>): RemoteRoomSummary {
return {
@@ -69,6 +74,78 @@ describe('matchRooms', () => {
});
});
+function server(over: Pick<SwitchServer, 'id' | 'name'> & Partial<SwitchServer>): SwitchServer {
+ return {
+ gatewayUrl: 'https://gateway.example',
+ apiUrl: 'https://api.example',
+ managed: false,
+ managementKind: null,
+ sshHost: null,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ ...over,
+ } as SwitchServer;
+}
+
+describe('matchServers', () => {
+ const SERVERS = [
+ server({ id: 's1', name: 'production' }),
+ server({ id: 's2', name: 'staging', gatewayUrl: 'https://switch.internal' }),
+ ];
+
+ it('matches on name', () => {
+ expect(matchServers(SERVERS, 'stag').map((s) => s.id)).toEqual(['s2']);
+ });
+
+ // A server is as often recognised by where it lives as by what it was called.
+ it('matches on gateway URL when the name does not match', () => {
+ expect(matchServers(SERVERS, 'internal').map((s) => s.id)).toEqual(['s2']);
+ });
+
+ it('returns nothing for an empty query', () => {
+ expect(matchServers(SERVERS, '')).toEqual([]);
+ });
+
+ it('emits palette items carrying the server id', () => {
+ expect(matchServers(SERVERS, 'production')[0]).toMatchObject({
+ kind: 'server',
+ id: 's1',
+ title: 'production',
+ });
+ });
+});
+
+describe('matchHosts', () => {
+ const HOSTS = [
+ { sshHost: 'gpu-box', name: 'GPU box' },
+ { sshHost: 'build-01', name: 'Build machine' },
+ ];
+
+ it('matches on the display name', () => {
+ expect(matchHosts(HOSTS, 'build').map((h) => h.id)).toEqual(['build-01']);
+ expect(matchHosts(HOSTS, 'build mach').map((h) => h.id)).toEqual(['build-01']);
+ expect(matchHosts(HOSTS, 'nonesuch')).toEqual([]);
+ });
+
+ // The SSH alias is the host's identity and usually what someone remembers.
+ it('matches on the SSH alias', () => {
+ expect(matchHosts(HOSTS, 'gpu-box').map((h) => h.id)).toEqual(['gpu-box']);
+ });
+
+ it('identifies the item by its SSH alias, which is the primary key', () => {
+ expect(matchHosts(HOSTS, 'gpu')[0]).toMatchObject({
+ kind: 'host',
+ id: 'gpu-box',
+ title: 'GPU box',
+ subtitle: 'gpu-box',
+ });
+ });
+
+ it('returns nothing for an empty query', () => {
+ expect(matchHosts(HOSTS, '')).toEqual([]);
+ });
+});
+
describe('applyContextAffinity', () => {
const item = (over: Partial<SearchItem> & Pick<SearchItem, 'id'>): SearchItem => ({
kind: 'session',
diff --git a/dash/apps/switchdash-desktop/src/shared/core/search.ts b/dash/apps/switchdash-desktop/src/shared/core/search.ts
index 4dc83f646..0ec6e93e2 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/search.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/search.ts
@@ -1,10 +1,17 @@
/**
- * `'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.
+ * Two populations, one item shape.
+ *
+ * `'session' | 'command' | 'file' | 'agent'` come from the SQLite FTS index —
+ * high-cardinality local content worth indexing.
+ *
+ * `'room' | 'server' | 'host'` are matched in the renderer against sets it has
+ * already loaded. Rooms are not mirrored into SQLite at all (the Switch server
+ * owns them); servers and hosts are local tables, but small ones with no
+ * lifecycle events, so indexing them would mean inventing change notifications
+ * whose only job is to stop the index going stale. Matching a handful of rows
+ * in the renderer is always fresh and has nothing to invalidate.
*/
-export type SearchItemKind = 'session' | 'location' | 'command' | 'file' | 'agent' | 'room';
+export type SearchItemKind = 'session' | 'command' | 'file' | 'agent' | 'room' | 'server' | 'host';
export interface SearchItem {
kind: SearchItemKind;