Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
test(switchdash): cover the palette search service and room matching (CHOO-1423)
Christian McDermottef27bfdf3e25
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.tsnew file mode 100644index 000000000..209ffdda5--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/search/search-service.db.test.ts@@ -0,0 +1,233 @@+import { openFixture } from '@tooling/utils/db';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { agents, locations, sessions } from '@main/db/schema';+import type { Agent } from '@shared/core/agents/agents';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+ sqlite: undefined as unknown,+}));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+ get sqlite() {+ if (!mocks.sqlite) throw new Error('Test database not initialized');+ return mocks.sqlite;+ },+}));++// The file index is a separate FTS table with its own indexing lifecycle; these+// tests are about the item index, so it contributes nothing.+vi.mock('./location-file-index-service', () => ({+ locationFileIndexService: { search: () => [] },+}));++const { searchService } = await import('./search-service');+const { agentEvents } = await import('../agents/agent-events');++function agentRecord(over: Partial<Agent> & Pick<Agent, 'id' | 'name'>): Agent {+ return {+ locationId: 'loc-1',+ providerId: 'claude',+ switchAgentId: null,+ apiEndpoint: null,+ serverId: null,+ status: null,+ autoApprove: false,+ providerConfig: null,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ ...over,+ } as Agent;+}++/** Titles of the indexed items a query returns, for order-insensitive asserts. */+function titles(items: { title: string }[]): string[] {+ return items.map((i) => i.title).sort();+}++describe('searchService', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ mocks.sqlite = fixture.sqlite;++ await fixture.db+ .insert(locations)+ .values({ id: 'loc-1', name: 'switchdash repo', sshHost: '', dir: '/tmp/switchdash' });+ await fixture.db+ .insert(locations)+ .values({ id: 'loc-2', name: 'other repo', sshHost: '', dir: '/tmp/other' });+ await fixture.db+ .insert(agents)+ .values({ id: 'agent-1', locationId: 'loc-1', name: 'reviewer-bot', providerId: 'claude' });+ await fixture.db+ .insert(agents)+ .values({ id: 'agent-2', locationId: 'loc-2', name: 'migration-bot', providerId: 'codex' });+ await fixture.db+ .insert(sessions)+ .values({ id: 'session-1', agentId: 'agent-1', title: 'Fix the reviewer crash' });+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ mocks.sqlite = undefined;+ });++ describe('indexing agents', () => {+ it('backfills existing agents so they are findable by name', () => {+ searchService.initialize();++ const result = searchService.search({ query: 'reviewer-bot' });++ expect(result.status).toBe('ok');+ const agentHits = result.items.filter((i) => i.kind === 'agent');+ expect(agentHits).toHaveLength(1);+ expect(agentHits[0]).toMatchObject({ id: 'agent-1', title: 'reviewer-bot' });+ });++ it('finds an agent by its provider, which is indexed as a keyword', () => {+ searchService.initialize();++ const result = searchService.search({ query: 'codex' });++ expect(titles(result.items.filter((i) => i.kind === 'agent'))).toEqual(['migration-bot']);+ });++ it('indexes an agent created after startup', () => {+ searchService.initialize();+ expect(searchService.search({ query: 'newcomer' }).items).toHaveLength(0);++ agentEvents._emit(+ 'agent:created',+ agentRecord({ id: 'agent-3', name: 'newcomer-bot', locationId: 'loc-1' })+ );++ expect(titles(searchService.search({ query: 'newcomer' }).items)).toEqual(['newcomer-bot']);+ });++ // A rename that does not reach the index leaves the old name matching+ // forever and the new one matching nothing.+ it('replaces the old name when an agent is renamed', () => {+ searchService.initialize();++ agentEvents._emit(+ 'agent:updated',+ agentRecord({ id: 'agent-1', name: 'auditor-bot', locationId: 'loc-1' })+ );++ expect(searchService.search({ query: 'reviewer-bot' }).items).toHaveLength(0);+ expect(titles(searchService.search({ query: 'auditor-bot' }).items)).toEqual(['auditor-bot']);+ });++ // `INSERT OR REPLACE` cannot supersede a row here: an FTS5 table has no+ // unique constraint for the conflict clause to fire on, so repeated updates+ // used to append a duplicate every time and the palette listed the item once+ // per update it had ever received.+ it('keeps one row per agent however many updates arrive', () => {+ searchService.initialize();++ for (let i = 0; i < 3; i++) {+ agentEvents._emit(+ 'agent:updated',+ agentRecord({ id: 'agent-1', name: 'reviewer-bot', locationId: 'loc-1' })+ );+ }++ expect(searchService.search({ query: 'reviewer-bot' }).items).toHaveLength(1);+ });++ it('drops an agent from the index when it is deleted', () => {+ searchService.initialize();++ agentEvents._emit('agent:deleted', 'agent-1');++ expect(searchService.search({ query: 'reviewer-bot' }).items).toHaveLength(0);+ });++ it('carries the location so the palette can navigate to it', () => {+ searchService.initialize();++ const [hit] = searchService.search({ query: 'migration-bot' }).items;++ expect(hit).toMatchObject({ kind: 'agent', locationId: 'loc-2' });+ });+ });++ describe('reporting why the items are what they are', () => {+ it('reports an empty query as recents rather than as matches', () => {+ searchService.initialize();++ const result = searchService.search({ query: '' });++ expect(result.status).toBe('recents');+ expect(titles(result.items)).toEqual(['Fix the reviewer crash']);+ });++ // The trigram tokenizer cannot answer a query this short. Returning recents+ // is fine; returning them labelled 'ok' is what made them look like matches.+ it('reports a query with no usable term as query-too-short', () => {+ searchService.initialize();++ const result = searchService.search({ query: 'ab' });++ expect(result.status).toBe('query-too-short');+ expect(result.items.every((i) => i.kind === 'session')).toBe(true);+ });++ it('treats a multi-word query of short terms as too short, not as a match', () => {+ searchService.initialize();++ expect(searchService.search({ query: 'ab cd' }).status).toBe('query-too-short');+ });++ it('reports a usable query as ok', () => {+ searchService.initialize();++ expect(searchService.search({ query: 'reviewer' }).status).toBe('ok');+ });++ it('distinguishes a failed search from an empty one', () => {+ searchService.initialize();+ const broken = new Error('database disk image is malformed');+ vi.spyOn(fixture.sqlite, 'prepare').mockImplementationOnce(() => {+ throw broken;+ });++ const result = searchService.search({ query: 'reviewer' });++ expect(result.status).toBe('failed');+ expect(result.items).toEqual([]);+ });+ });++ describe('matching', () => {+ // item_type is stored UNINDEXED precisely so its own literal is not content.+ it('does not match every row of a kind by typing that kind name', () => {+ searchService.initialize();++ const result = searchService.search({ query: 'session' });++ expect(result.items.filter((i) => i.kind === 'session')).toHaveLength(0);+ });++ it('finds sessions and locations 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'+ );+ });+ });+});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.tsnew file mode 100644index 000000000..047035c1a--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/tests/palette-search-utils.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest';+import { applyContextAffinity, matchRooms } from '@renderer/features/command-palette/search-utils';+import type { SearchItem } from '@shared/core/search';+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';++function room(over: Pick<RemoteRoomSummary, 'id' | 'name'>): RemoteRoomSummary {+ return {+ description: '',+ channelType: null,+ agentCount: 0,+ bridgeDisplayName: null,+ bridgeType: null,+ externalChannelUrl: null,+ ownerId: null,+ archived: false,+ createdAt: '2026-01-01T00:00:00Z',+ ...over,+ } as RemoteRoomSummary;+}++const ROOMS = [+ room({ id: 'r1', name: 'switchdash search bar' }),+ room({ id: 'r2', name: 'Switch Workforce hub' }),+ room({ id: 'r3', name: 'release engineering' }),+];++describe('matchRooms', () => {+ it('returns nothing for an empty query rather than every room', () => {+ expect(matchRooms(ROOMS, '')).toEqual([]);+ expect(matchRooms(ROOMS, ' ')).toEqual([]);+ });++ it('matches case-insensitively on a substring', () => {+ expect(matchRooms(ROOMS, 'WORKFORCE').map((r) => r.id)).toEqual(['r2']);+ });++ // Rooms are matched in the renderer, so they are not subject to the trigram+ // tokenizer's three-character floor that the indexed kinds are.+ 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']);+ });++ it('ranks a name that starts with the query above one that merely contains it', () => {+ const hits = matchRooms(+ [+ room({ id: 'contains', name: 'the search bar' }),+ room({ id: 'starts', name: 'search bar' }),+ ],+ 'search'+ );+ expect(hits.map((h) => h.id)).toEqual(['starts', 'contains']);+ });++ it('emits palette items that navigate by room id', () => {+ const [hit] = matchRooms(ROOMS, 'workforce');+ expect(hit).toMatchObject({+ kind: 'room',+ id: 'r2',+ title: 'Switch Workforce hub',+ locationId: null,+ });+ });++ it('caps how much of the palette rooms can take', () => {+ const many = Array.from({ length: 30 }, (_, i) => room({ id: `r${i}`, name: `room ${i}` }));+ expect(matchRooms(many, 'room').length).toBeLessThanOrEqual(8);+ });+});++describe('applyContextAffinity', () => {+ const item = (over: Partial<SearchItem> & Pick<SearchItem, 'id'>): SearchItem => ({+ kind: 'session',+ locationId: null,+ sessionId: null,+ title: over.id,+ subtitle: '',+ score: 0,+ ...over,+ });++ it('puts items from the active location first', () => {+ const ranked = applyContextAffinity(+ [+ item({ id: 'elsewhere', locationId: 'loc-2', score: -5 }),+ item({ id: 'here', locationId: 'loc-1', score: -1 }),+ ],+ { locationId: 'loc-1' }+ );+ expect(ranked.map((r) => r.id)).toEqual(['here', 'elsewhere']);+ });++ it('falls back to BM25 order, where more negative is better', () => {+ const ranked = applyContextAffinity(+ [item({ id: 'weak', score: -1 }), item({ id: 'strong', score: -9 })],+ {}+ );+ expect(ranked.map((r) => r.id)).toEqual(['strong', 'weak']);+ });++ it('does not mutate the array it is given', () => {+ const items = [item({ id: 'b', score: -1 }), item({ id: 'a', score: -9 })];+ applyContextAffinity(items, {});+ expect(items.map((i) => i.id)).toEqual(['b', 'a']);+ });+});