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): stop the palette matching mid-word (CHOO-1423)

Christian McDermott422022198baf
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 1284c5413..f18ee9a47 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,6 +218,39 @@ describe('searchService', () => {
expect(result.items.filter((i) => i.kind === 'session')).toHaveLength(0);
});
+ // The trigram index matches any 3-char substring anywhere, so it happily
+ // returns "Manage storage quotas" for "age" and "migration-bot" for "rat".
+ // Those are hits the index likes and a person does not.
+ it('does not match mid-word, however happy the index is to', () => {
+ searchService.initialize();
+
+ expect(titles(searchService.search({ query: 'rat' }).items)).toEqual([]);
+ expect(titles(searchService.search({ query: 'iewer' }).items)).toEqual([]);
+ expect(titles(searchService.search({ query: 'ion' }).items)).toEqual([]);
+ });
+
+ it('matches a word after a separator, so a suffixed name is still findable', () => {
+ searchService.initialize();
+
+ expect(titles(searchService.search({ query: 'bot' }).items)).toEqual([
+ 'migration-bot',
+ 'reviewer-bot',
+ ]);
+ });
+
+ it('ranks a title match above one found only in keywords', () => {
+ searchService.initialize();
+ agentEvents._emit(
+ 'agent:created',
+ agentRecord({ id: 'agent-4', name: 'codex-runner', locationId: 'loc-1' })
+ );
+
+ // 'codex' is agent-2's provider (a keyword) and agent-4's name.
+ const items = searchService.search({ query: 'codex' }).items;
+
+ expect(items.map((i) => i.title)).toEqual(['codex-runner', 'migration-bot']);
+ });
+
it('finds sessions alongside agents', () => {
searchService.initialize();
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 871f8531d..c6f528fc4 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
@@ -4,11 +4,12 @@ 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 {
- CommandPaletteQuery,
- SearchItem,
- SearchItemKind,
- SearchResult,
+import {
+ type CommandPaletteQuery,
+ matchQuality,
+ type SearchItem,
+ type SearchItemKind,
+ type SearchResult,
} from '@shared/core/search';
import type { Session } from '@shared/core/sessions/sessions';
import { agentEvents } from '../agents/agent-events';
@@ -22,9 +23,55 @@ type FtsRow = {
location_id: string | null;
session_id: string | null;
title: string;
+ keywords: string;
rank: number;
};
+/**
+ * Rows pulled from the index before the word-boundary filter, and rows returned
+ * after it. The index over-matches (see `matchQuality`), so the filter discards
+ * a share of what it returns — asking for more candidates than the caller wants
+ * keeps a precise query from coming back thin just because a lot of mid-word
+ * noise sorted above the real hits.
+ */
+const FTS_CANDIDATE_LIMIT = 120;
+const RESULT_LIMIT = 30;
+
+/** Ranking tiers, best first: the title starts with the term, a word in the
+ * title does, or only a keyword does. */
+const TIER_TITLE_PREFIX = 0;
+const TIER_TITLE_WORD = 1;
+const TIER_KEYWORD = 2;
+/** Wider than any BM25 magnitude, so the tier decides before the score does. */
+const TIER_STRIDE = 1_000_000;
+
+/**
+ * The worst tier across all terms, or null when any term fails to begin a word
+ * in either the title or the keywords.
+ *
+ * Judged on the worst term so that a query only ranks as a title match when
+ * *every* word of it is one — "reviewer bot" matching an item whose title holds
+ * one word and whose description holds the other is a keyword-grade hit, not a
+ * name hit.
+ */
+function matchTier(row: FtsRow, terms: string[]): number | null {
+ let worst = TIER_TITLE_PREFIX;
+ for (const term of terms) {
+ const inTitle = matchQuality(row.title, term);
+ const tier =
+ inTitle === 'prefix'
+ ? TIER_TITLE_PREFIX
+ : inTitle === 'word'
+ ? TIER_TITLE_WORD
+ : matchQuality(row.keywords, term)
+ ? TIER_KEYWORD
+ : null;
+ if (tier === null) return null;
+ worst = Math.max(worst, tier);
+ }
+ return worst;
+}
+
type RecentSessionRow = {
id: string;
title: string;
@@ -71,27 +118,41 @@ class SearchService {
try {
rows = sqlite
.prepare(
- `SELECT item_type, item_id, location_id, session_id, title, bm25(search_index) AS rank
+ `SELECT item_type, item_id, location_id, session_id, title, keywords,
+ bm25(search_index) AS rank
FROM search_index
WHERE search_index MATCH ?
ORDER BY rank
- LIMIT 30`
+ LIMIT ?`
)
- .all(ftsQuery) as FtsRow[];
+ .all(ftsQuery, FTS_CANDIDATE_LIMIT) as FtsRow[];
} catch (e) {
log.error('SearchService: FTS query failed', { query, error: String(e) });
return { items: [], status: 'failed' };
}
- const results: SearchItem[] = rows.map((r) => ({
- kind: r.item_type as SearchItemKind,
- id: r.item_id,
- locationId: r.location_id,
- sessionId: r.session_id,
- title: r.title,
- subtitle: '',
- score: r.rank,
- }));
+ const results: SearchItem[] = rows
+ .flatMap((r) => {
+ const tier = matchTier(r, terms);
+ return tier === null
+ ? []
+ : [
+ {
+ kind: r.item_type as SearchItemKind,
+ id: r.item_id,
+ locationId: r.location_id,
+ sessionId: r.session_id,
+ title: r.title,
+ subtitle: '',
+ // Tier dominates BM25 so a name match always outranks a hit
+ // buried in a command's description, whatever the text lengths
+ // do to the relevance score.
+ score: tier * TIER_STRIDE + r.rank,
+ },
+ ];
+ })
+ .sort((a, b) => a.score - b.score)
+ .slice(0, RESULT_LIMIT);
// 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
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 633b47cb0..878a00fcf 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
@@ -14,7 +14,7 @@ import {
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 { REMOTE_HOSTS_QUERY_KEY } from '@renderer/features/remote-hosts/views/remote-hosts-view';
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';
@@ -383,7 +383,7 @@ export function CommandPaletteModal({
const handleNavigateToHost = (item: SearchItem) => {
handleClose();
- navigate('settings', { tab: 'remote-hosts', host: item.id });
+ navigate('remoteHost', { sshHost: item.id });
};
const handleSelect = (item: SearchItem) => {
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-session-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-session-item.tsx
index 680d08724..200614582 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-session-item.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-session-item.tsx
@@ -1,5 +1,5 @@
import { Command } from 'cmdk';
-import { GitBranch } from 'lucide-react';
+import { MessageSquare } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { AgentStatusIndicator } from '@renderer/features/sessions/components/agent-status-indicator';
import { sessionAgentStatus } from '@renderer/features/sessions/stores/session-selectors';
@@ -19,7 +19,8 @@ export const PaletteSessionItem = observer(function PaletteSessionItem({
return (
<Command.Item value={value} onSelect={onSelect} className={PALETTE_ITEM_CLASS}>
- <GitBranch size={14} className="shrink-0 text-foreground/40" />
+ {/* Matches the sidebar's session row (`sidebar/session-item.tsx`). */}
+ <MessageSquare size={14} className="shrink-0 text-foreground/40" />
<span className="flex-1 truncate">{sessionStore.data.title}</span>
<AgentStatusIndicator status={status} disableTooltip />
</Command.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 02d9ae82d..0e6f554b4 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,4 @@
-import type { SearchItem, SearchItemKind } from '@shared/core/search';
+import { matchQuality, type SearchItem, type SearchItemKind } from '@shared/core/search';
import type { RemoteRoomSummary, SwitchServer } from '@shared/core/switch-servers/switch-servers';
/**
@@ -25,22 +25,30 @@ const RENDERER_RESULT_LIMIT = 8;
/**
* Rank one renderer-matched candidate, or null when the query does not match.
*
+ * Held to the same word-boundary rule as the indexed kinds (see `matchQuality`),
+ * so the two populations agree on what counts as a match — a palette where
+ * rooms match mid-word and agents do not would be incoherent to use, whichever
+ * rule is the better one.
+ *
* `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 these kinds answer one- and
- * two-character queries, below the trigram tokenizer's three-character floor
- * that the indexed kinds are subject to.
+ * Unlike the indexed kinds these have no three-character floor, since nothing
+ * here goes through the trigram tokenizer.
*/
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;
+ switch (matchQuality(haystack, query)) {
+ // Ties break on the shorter name, which is the more exact match.
+ case 'prefix':
+ return -haystack.length;
+ case 'word':
+ return 1000 + haystack.length;
+ default:
+ return null;
+ }
}
function finalise(items: SearchItem[]): SearchItem[] {
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 62087f704..a44011dde 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
@@ -41,10 +41,23 @@ describe('matchRooms', () => {
// Rooms are matched in the renderer, so they are not subject to the trigram
// tokenizer's three-character floor that the indexed kinds are.
+ // No trigram tokenizer here, so there is no three-character floor.
it('answers a one- and two-character query', () => {
- // 'se' matches "relea(se)" and "(se)arch"; the earlier position wins.
- expect(matchRooms(ROOMS, 'se').map((r) => r.id)).toEqual(['r3', 'r1']);
- expect(matchRooms(ROOMS, 'w').map((r) => r.id)).toEqual(['r2', 'r1']);
+ expect(matchRooms(ROOMS, 'se').map((r) => r.id)).toEqual(['r1']);
+ // 'Workforce', not 's(w)itchdash'.
+ expect(matchRooms(ROOMS, 'w').map((r) => r.id)).toEqual(['r2']);
+ });
+
+ // "relea(se)" is a substring match a person did not ask for. Matching only at
+ // word starts is what keeps the result set honest.
+ it('does not match mid-word', () => {
+ expect(matchRooms(ROOMS, 'lease')).toEqual([]);
+ expect(matchRooms(ROOMS, 'ork')).toEqual([]);
+ });
+
+ it('still matches a word after a separator', () => {
+ expect(matchRooms(ROOMS, 'bar').map((r) => r.id)).toEqual(['r1']);
+ expect(matchRooms(ROOMS, 'hub').map((r) => r.id)).toEqual(['r2']);
});
it('ranks a name that starts with the query above one that merely contains it', () => {
diff --git a/dash/apps/switchdash-desktop/src/shared/core/search.ts b/dash/apps/switchdash-desktop/src/shared/core/search.ts
index 0ec6e93e2..81bfe9028 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/search.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/search.ts
@@ -45,6 +45,39 @@ export interface SearchResult {
status: SearchStatus;
}
+/**
+ * Where a term matched, best first. `null` means "not usefully matched".
+ *
+ * The FTS index is trigram-tokenised, which matches any substring of three or
+ * more characters anywhere in a column. That is far broader than anyone means
+ * when they type: "age" matches *Man*age* and *stor*age*, "ion" matches
+ * migrat*ion*-bot and Sess*ion*, "rat" matches mig*rat*ion. Every one of those
+ * is a hit the index is happy with and a person is not.
+ *
+ * So the index is treated as a candidate generator and the results are held to
+ * a stricter rule: a term must begin a word. That keeps "bot" finding
+ * `reviewer-bot` and "ses" finding `New Session`, and drops the mid-word noise.
+ *
+ * The cost is deliberate and worth stating: a term that starts mid-word no
+ * longer matches, so "dash" no longer finds `switchdash`. Precision is bought
+ * with recall — there is no setting of this dial that gives both.
+ */
+export type MatchQuality = 'prefix' | 'word' | null;
+
+/** Characters that separate words for matching. Covers the shapes names take
+ * here: `reviewer-bot`, `gpu_box`, `switch.local`, `host:port`, paths, URLs. */
+const WORD_SEPARATORS = /[\s\-_./:@\\]+/;
+
+/** How well `term` matches `text`: at its start, at the start of a word inside
+ * it, or not well enough to offer. */
+export function matchQuality(text: string, term: string): MatchQuality {
+ const haystack = text.toLowerCase();
+ const needle = term.toLowerCase();
+ if (!needle) return null;
+ if (haystack.startsWith(needle)) return 'prefix';
+ return haystack.split(WORD_SEPARATORS).some((word) => word.startsWith(needle)) ? 'word' : null;
+}
+
export interface CommandPaletteQuery {
query: string;
context?: {