The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): scope sidebar session search to the profile on screen
Teknium4a7962089820
diff --git a/apps/desktop/e2e/sidebar-search-profile-scope.spec.ts b/apps/desktop/e2e/sidebar-search-profile-scope.spec.tsnew file mode 100644index 00000000000..fd3d10b599d--- /dev/null+++ b/apps/desktop/e2e/sidebar-search-profile-scope.spec.ts@@ -0,0 +1,141 @@+/**+ * E2E: sidebar full-text search is keyed to the sidebar's profile.+ *+ * Two real profile homes on This device — `default` and `ssprobe-b` — each+ * hold one durable session. Both transcripts contain the shared word "zebra"+ * only in the assistant reply, so a loaded row never matches client-side and+ * every hit comes from the backend's `/api/sessions/search`. Each reply also+ * carries a profile-only marker. With the sidebar on a profile, searching the+ * shared word must surface that profile's marker and never the other one's,+ * across default → ssprobe-b → default.+ *+ * Prerequisite: `npm run build` (dist/) and the repo's `.venv`.+ */++import { spawnSync } from 'node:child_process'+import * as fs from 'node:fs'+import * as path from 'node:path'++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+import { startMockServer } from '../../../tests-js/scripts/mock-server'++import { buildAppEnv, createSandbox, launchDesktop, type MockBackendFixture, type Sandbox, waitForAppReady } from './fixtures'+import { type ElectronApplication, expect, type Page, test } from './test'++const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..', '..')+const PROFILE_B = 'ssprobe-b'+const MARKER = { default: 'alphaonlymarker', [PROFILE_B]: 'bravoonlymarker' } as const++/** Write one session into ``home``'s state.db through the real SessionDB. */+function seedSession(sandbox: Sandbox, home: string, sessionId: string, marker: string): void {+ const script = [+ 'import sys',+ 'from pathlib import Path',+ 'from hermes_state import SessionDB',+ 'home, sid, marker = sys.argv[1:4]',+ "db = SessionDB(db_path=Path(home) / 'state.db')",+ "db.create_session(sid, source='cli')",+ "db.append_message(sid, role='user', content=f'hello {marker}')",+ "db.append_message(sid, role='assistant', content=f'zebra {marker}')",+ 'db.close()'+ ].join('\n')++ const python = path.join(REPO_ROOT, '.venv', 'bin', 'python')++ const result = spawnSync(python, ['-c', script, home, sessionId, marker], {+ cwd: REPO_ROOT,+ encoding: 'utf8',+ env: { ...process.env, HERMES_HOME: sandbox.hermesHome, HOME: sandbox.root, PYTHONPATH: REPO_ROOT }+ })++ if (result.status !== 0) {+ throw new Error(`seeding ${home} failed:\n${result.stderr}`)+ }+}++const sidebar = (page: Page) => page.locator('[data-slot="sidebar"]').first()+const rail = (page: Page) => page.getByRole('group', { name: 'Profiles' })+const railButton = (page: Page, name: string) => rail(page).getByRole('button', { name, exact: true })++// The launch profile is the rail's home pill: "Switch to default" while another+// profile is selected, relabelled "Show all profiles" (pressed) once on default.+async function selectProfile(page: Page, name: string): Promise<void> {+ if (name === 'default') {+ const showAll = railButton(page, 'Show all profiles')++ if (!(await showAll.count()) || (await showAll.getAttribute('aria-pressed')) !== 'true') {+ await railButton(page, 'Switch to default').click()+ }++ await expect(showAll).toHaveAttribute('aria-pressed', 'true', { timeout: 60_000 })++ return+ }++ await railButton(page, name).click()+ await expect(railButton(page, name)).toHaveAttribute('aria-pressed', 'true', { timeout: 60_000 })+}++async function expectSearchScopedTo(page: Page, profile: keyof typeof MARKER): Promise<void> {+ const other = profile === 'default' ? PROFILE_B : 'default'+ const search = page.getByRole('textbox', { name: 'Search sessions' })++ await search.fill('')+ await search.fill('zebra')+ // Only the backend can match "zebra" here, so this waits for the server hits.+ await expect(sidebar(page).getByText(MARKER[profile])).toBeVisible({ timeout: 30_000 })+ await expect(sidebar(page).getByText(MARKER[other])).toHaveCount(0)+ await search.fill('')+}++test.describe('sidebar session search — profile scope', () => {+ test.describe.configure({ mode: 'serial' })++ let mock: Awaited<ReturnType<typeof startMockServer>>+ let sandbox: Sandbox+ let app: ElectronApplication+ let page: Page++ test.beforeAll(async () => {+ test.setTimeout(240_000)+ mock = await startMockServer()+ sandbox = createSandbox('search-scope')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)++ const homeB = path.join(sandbox.hermesHome, 'profiles', PROFILE_B)+ fs.mkdirSync(homeB, { recursive: true })+ writeMockProviderConfig(homeB, mock.url)+ writeEnvFile(homeB)+ seedSession(sandbox, sandbox.hermesHome, 'search-scope-default', MARKER.default)+ seedSession(sandbox, homeB, 'search-scope-b', MARKER[PROFILE_B])++ ;({ app, page } = await launchDesktop(buildAppEnv(sandbox)))+ await waitForAppReady({ app, page } as MockBackendFixture, 120_000)+ await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({+ timeout: 120_000+ })+ })++ test.afterAll(async () => {+ await app?.close().catch(() => undefined)+ await mock?.close()+ sandbox?.cleanup()+ })++ test('search returns only the selected profile across A → B → A', async () => {+ test.setTimeout(240_000)+ // Start on whichever profile the app booted into, then switch away and back.+ await expect(rail(page)).toBeVisible({ timeout: 60_000 })+ const bootedOnB = (await railButton(page, PROFILE_B).getAttribute('aria-pressed')) === 'true'+ const first: keyof typeof MARKER = bootedOnB ? PROFILE_B : 'default'+ const second: keyof typeof MARKER = first === 'default' ? PROFILE_B : 'default'++ await selectProfile(page, first)+ await expectSearchScopedTo(page, first)+ await selectProfile(page, second)+ await expectSearchScopedTo(page, second)+ await selectProfile(page, first)+ await expectSearchScopedTo(page, first)+ })+})diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.tsindex 085af6481f9..e151dc58da3 100644--- a/apps/desktop/src/api/sessions.test.ts+++ b/apps/desktop/src/api/sessions.test.ts@@ -22,6 +22,7 @@ const {getSession,getLatestSessionMessages,renameSession,+ searchSessions,setSessionArchived,setSessionPinnedRemote,setSessionUnreadRemote,@@ -321,3 +322,20 @@ describe('session reads pin the owner connection (#125372)', () => {})})})++describe('searchSessions profile scope', () => {+ it('searches the given profile instead of the primary backend', async () => {+ // Unscoped, the primary searched its launch profile while the sidebar showed another.+ hermesApi.mockResolvedValue({ results: [] } as never)+ vi.mocked(client.profileScoped).mockImplementation(profile =>+ profile ? { priority: 'foreground', profile } : {}+ )++ await searchSessions('zebra', 'research')++ expect(hermesApi.mock.calls[0][0]).toMatchObject({+ path: '/api/sessions/search?q=zebra&profile=research',+ profile: 'research'+ })+ })+})diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.tsindex d29f617e84d..4fd866c6d1a 100644--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@ -425,9 +425,17 @@ export function setSessionUnreadRemote(id: string, unread: boolean, profile?: st})}-export function searchSessions(query: string): Promise<SessionSearchResponse> {+// Full-text search over one profile's sessions. Pass the profile the caller is+// showing: an unscoped request lands on the primary backend, which searches+// its launch profile's state.db whatever profile the sidebar is on. `null`+// asks the primary on purpose; omitted follows the ambient request profile.+export function searchSessions(query: string, profile?: null | string): Promise<SessionSearchResponse> {+ const scope = profileScoped(profile)+ const suffix = scope.profile ? `&profile=${encodeURIComponent(scope.profile)}` : ''+return hermesApi<SessionSearchResponse>({- path: `/api/sessions/search?q=${encodeURIComponent(query)}`+ ...scope,+ path: `/api/sessions/search?q=${encodeURIComponent(query)}${suffix}`})}diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsxindex 47ea46cf814..d3dd287ba58 100644--- a/apps/desktop/src/app/chat/sidebar/index.tsx+++ b/apps/desktop/src/app/chat/sidebar/index.tsx@@ -23,7 +23,7 @@ import {} from '@/components/ui/sidebar'import { Tip, TipKeybindLabel } from '@/components/ui/tooltip'import { useContributions } from '@/contrib/react/use-contributions'-import { searchSessions, type SessionInfo, type SessionSearchResult } from '@/hermes'+import { type SessionInfo, type SessionSearchResult } from '@/hermes'import { useI18n } from '@/i18n'import { comboTokens } from '@/lib/keybinds/combo'import { sessionMatchesSearch } from '@/lib/session-search'@@ -191,6 +191,7 @@ import { buildSessionByAnyId, resolvePinnedSessions } from './session-index'import { SidebarSessionsSection, VIRTUALIZE_THRESHOLD } from './sessions-section'import { CONTEXT_SPLIT_KIT, SplitSubmenu } from './split-submenu'import { useEnteredProjectSessions } from './use-entered-project-sessions'+import { useServerSessionSearch } from './use-server-session-search'// Non-session groups (messaging platforms) stay compact: show a few rows up// front, reveal more in larger steps on demand. Keeps a busy platform from@@ -545,8 +546,6 @@ export function ChatSidebar({const newSessionCombo = useStore($bindings)['session.new']?.[0]const newSessionKbd = newSessionCombo ? comboTokens(newSessionCombo) : []const [searchQuery, setSearchQuery] = useState('')- const [serverMatches, setServerMatches] = useState<SessionSearchResult[]>([])- const [searchPending, setSearchPending] = useState(false)const [newSessionKbdFlash, setNewSessionKbdFlash] = useState(false)const [messagingLoadMorePending, setMessagingLoadMorePending] = useState<Record<string, boolean>>({})const [recentsLoadMorePending, setRecentsLoadMorePending] = useState(false)@@ -742,41 +741,7 @@ export function ChatSidebar({[isPinnedSession, filtersNarrow, sessionMatchesFilters])- // Full-text search across *all* sessions (not just the loaded page) so 699- // sessions stay findable. Debounced; loaded sessions are matched instantly- // client-side and merged ahead of the server hits.- useEffect(() => {- if (!trimmedQuery) {- setServerMatches([])- setSearchPending(false)-- return- }-- let cancelled = false-- setSearchPending(true)-- const id = window.setTimeout(() => {- void searchSessions(trimmedQuery)- .then(res => {- if (!cancelled) {- setServerMatches(res.results)- }- })- .catch(() => undefined)- .finally(() => {- if (!cancelled) {- setSearchPending(false)- }- })- }, 200)-- return () => {- cancelled = true- window.clearTimeout(id)- }- }, [trimmedQuery])+ const { searchPending, serverMatches } = useServerSessionSearch(trimmedQuery, profileScope)const searchResults = useMemo(() => mergeSearchResults(sortedSessions, trimmedQuery, serverMatches, sessionByAnyId, searchPending),diff --git a/apps/desktop/src/app/chat/sidebar/use-server-session-search.ts b/apps/desktop/src/app/chat/sidebar/use-server-session-search.tsnew file mode 100644index 00000000000..32fd677b19b--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/use-server-session-search.ts@@ -0,0 +1,58 @@+import { useEffect, useState } from 'react'++import { searchSessions, type SessionSearchResult } from '@/hermes'+import { ALL_PROFILES, normalizeProfileKey } from '@/store/profile'++const SEARCH_DEBOUNCE_MS = 200++export interface ServerSessionSearch {+ serverMatches: SessionSearchResult[]+ searchPending: boolean+}++/**+ * Debounced full-text search across *all* sessions (not just the loaded page)+ * so old sessions stay findable. Hits come from the profile the sidebar shows:+ * an unscoped request searches the primary backend's launch profile, whatever+ * profile is on screen. "All profiles" asks the primary as before.+ */+export function useServerSessionSearch(query: string, profileScope: string): ServerSessionSearch {+ const [serverMatches, setServerMatches] = useState<SessionSearchResult[]>([])+ const [searchPending, setSearchPending] = useState(false)+ const profile = profileScope === ALL_PROFILES ? null : normalizeProfileKey(profileScope)++ useEffect(() => {+ if (!query) {+ setServerMatches([])+ setSearchPending(false)++ return+ }++ let cancelled = false++ setSearchPending(true)++ const id = window.setTimeout(() => {+ void searchSessions(query, profile)+ .then(res => {+ if (!cancelled) {+ setServerMatches(res.results)+ }+ })+ .catch(() => undefined)+ .finally(() => {+ if (!cancelled) {+ setSearchPending(false)+ }+ })+ }, SEARCH_DEBOUNCE_MS)++ return () => {+ cancelled = true+ window.clearTimeout(id)+ }+ }, [query, profile])++ return { searchPending, serverMatches }+}