{isLoading && !renderSessions ? (
Loading sessions...
) : renderSessions ? (
renderSessions({
sessions: filteredSessions,
- searchQuery,
+ searchQuery: query,
renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionSelectionKey(session))),
})
) : filteredSessions.length === 0 && !isFetchingNextPage ? (
diff --git a/frontend/src/components/session/SessionPickerDialog.test.tsx b/frontend/src/components/session/SessionPickerDialog.test.tsx
new file mode 100644
index 00000000..8b62962d
--- /dev/null
+++ b/frontend/src/components/session/SessionPickerDialog.test.tsx
@@ -0,0 +1,312 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { useState } from 'react'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import type { Repo, Session } from '@/api/types'
+import { SessionPickerDialog } from './SessionPickerDialog'
+
+const mocks = vi.hoisted(() => ({
+ sessionsData: [] as Session[],
+ lastDirectories: [] as string[],
+ fetchNextPage: vi.fn(),
+ deleteSessionMock: vi.fn(),
+ togglePinMock: vi.fn(),
+ sessionPins: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
+ repos: [] as Repo[],
+}))
+
+vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
+ const actual = await importOriginal
()
+ return {
+ ...actual,
+ useSessionsAcrossDirectories: (directories: string[], options?: { search?: string }) => {
+ mocks.lastDirectories = directories
+ const search = options?.search?.toLowerCase() ?? ''
+ const data = search
+ ? mocks.sessionsData.filter((session) => (session.title ?? '').toLowerCase().includes(search))
+ : mocks.sessionsData
+ return {
+ data,
+ isLoading: false,
+ isPlaceholderData: false,
+ fetchNextPage: mocks.fetchNextPage,
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ isFetchNextPageError: false,
+ }
+ },
+ useDeleteSession: () => ({ mutateAsync: mocks.deleteSessionMock, isPending: false }),
+ }
+})
+
+vi.mock('@/hooks/useSessionPins', () => ({
+ useSessionPins: () => ({ data: mocks.sessionPins }),
+ useToggleSessionPin: () => ({ mutate: mocks.togglePinMock }),
+}))
+
+vi.mock('@/hooks/useSidebarRepoGroups', () => ({
+ useNavigableRepos: () => ({ repos: mocks.repos, isLoading: false, refetch: vi.fn() }),
+}))
+
+vi.mock('@/lib/overlayFocus', async (importOriginal) => {
+ const actual = await importOriginal()
+ return { ...actual, isFinePointer: () => true }
+})
+
+vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
+ const actual = await importOriginal()
+ return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
+})
+
+function session(id: string, title: string, directory: string, updated = Date.now()): Session {
+ return {
+ id,
+ projectID: 'proj',
+ title,
+ time: { created: updated, updated },
+ location: { directory },
+ cost: 0,
+ tokens: {},
+ } as unknown as Session
+}
+
+function repo(id: number, name: string, fullPath: string): Repo {
+ return {
+ id,
+ name,
+ localPath: fullPath,
+ fullPath,
+ defaultBranch: 'main',
+ cloneStatus: 'ready',
+ clonedAt: 0,
+ }
+}
+
+function renderPicker(overrides: Partial> = {}) {
+ const onOpenChange = vi.fn()
+ const onSelectSession = vi.fn()
+ const onActiveSessionDeleted = vi.fn()
+ render(
+ ,
+ )
+ return { onOpenChange, onSelectSession, onActiveSessionDeleted }
+}
+
+const combobox = () => screen.getByRole('combobox')
+
+describe('SessionPickerDialog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ mocks.deleteSessionMock.mockResolvedValue(undefined)
+ mocks.sessionPins = []
+ mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
+ mocks.sessionsData = []
+ })
+
+ it('opens with the active session as the cursor and marks it with a dot', () => {
+ mocks.sessionsData = [
+ session('ses_active', 'Active session', '/w/a', 3000),
+ session('ses_other', 'Other session', '/w/a', 2000),
+ ]
+
+ renderPicker({ activeSessionID: 'ses_active' })
+
+ const active = screen.getByRole('option', { name: /Active session/ })
+ const other = screen.getByRole('option', { name: /Other session/ })
+ expect(active).toHaveAttribute('aria-selected', 'true')
+ expect(active.textContent).toContain('●')
+ expect(other).toHaveAttribute('aria-selected', 'false')
+ })
+
+ it('filters rows immediately as the query is typed', () => {
+ mocks.sessionsData = [
+ session('ses_alpha', 'alpha task', '/w/a', 2000),
+ session('ses_beta', 'beta task', '/w/a', 1000),
+ ]
+
+ renderPicker()
+
+ fireEvent.change(combobox(), { target: { value: 'beta' } })
+
+ expect(screen.queryByText('alpha task')).not.toBeInTheDocument()
+ expect(screen.getByText('beta task')).toBeInTheDocument()
+ })
+
+ it('moves the cursor with arrow keys and Ctrl+N/Ctrl+P, wrapping, and opens the row on Enter', () => {
+ mocks.sessionsData = [
+ session('ses_1', 'First', '/w/a', 3000),
+ session('ses_2', 'Second', '/w/a', 2000),
+ session('ses_3', 'Third', '/w/a', 1000),
+ ]
+ const { onSelectSession } = renderPicker()
+
+ const first = screen.getByRole('option', { name: /First/ })
+ const second = screen.getByRole('option', { name: /Second/ })
+ const third = screen.getByRole('option', { name: /Third/ })
+
+ expect(first).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
+ expect(second).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
+ expect(first).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
+ expect(third).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'n', ctrlKey: true })
+ expect(first).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'p', ctrlKey: true })
+ expect(third).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'Enter' })
+ expect(onSelectSession).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'ses_3' }),
+ mocks.repos[0],
+ )
+ })
+
+ it('toggles scope with Ctrl+A, persists it, queries every repo directory and shows repo labels', () => {
+ mocks.sessionsData = [
+ session('ses_a', 'Alpha session', '/w/a', 2000),
+ session('ses_b', 'Beta session', '/w/b', 1000),
+ ]
+
+ renderPicker()
+
+ expect(mocks.lastDirectories).toEqual(['/w/a'])
+ expect(screen.getByText('Alpha session')).toBeInTheDocument()
+ expect(screen.queryByText('Beta session')).not.toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'a', ctrlKey: true })
+
+ expect(mocks.lastDirectories).toEqual(['/w/a', '/w/b'])
+ expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('true')
+ expect(screen.getByText('Beta session')).toBeInTheDocument()
+ expect(screen.getByText('alpha')).toBeInTheDocument()
+ expect(screen.getByText('beta')).toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'a', ctrlKey: true })
+ expect(mocks.lastDirectories).toEqual(['/w/a'])
+ expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('false')
+ })
+
+ it('deletes on a second Ctrl+D and clears the pending state on a move', async () => {
+ mocks.sessionsData = [
+ session('ses_1', 'First', '/w/a', 3000),
+ session('ses_2', 'Second', '/w/a', 2000),
+ ]
+ renderPicker()
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument()
+ expect(mocks.deleteSessionMock).not.toHaveBeenCalled()
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
+ expect(screen.queryByText('Press Ctrl+D again to confirm')).not.toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument()
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ expect(mocks.deleteSessionMock).toHaveBeenCalledWith({ id: 'ses_2', directory: '/w/a' })
+
+ await waitFor(() =>
+ expect(screen.queryByText('Press Ctrl+D again to confirm')).not.toBeInTheDocument(),
+ )
+ })
+
+ it('notifies when the active session is deleted', async () => {
+ mocks.sessionsData = [session('ses_active', 'Active', '/w/a', 3000)]
+ const { onActiveSessionDeleted } = renderPicker({ activeSessionID: 'ses_active' })
+
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+ fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
+
+ await waitFor(() => expect(onActiveSessionDeleted).toHaveBeenCalled())
+ })
+
+ it('moves the cursor when a mouse pointer moves over a row', () => {
+ mocks.sessionsData = [
+ session('ses_1', 'First', '/w/a', 3000),
+ session('ses_2', 'Second', '/w/a', 2000),
+ ]
+ renderPicker()
+
+ const second = screen.getByRole('option', { name: /Second/ })
+ const pointerMove = new Event('pointermove', { bubbles: true })
+ Object.defineProperty(pointerMove, 'pointerType', { value: 'mouse' })
+ fireEvent(second, pointerMove)
+
+ expect(second).toHaveAttribute('aria-selected', 'true')
+ })
+
+ it('opens the delete confirmation from the row menu', async () => {
+ mocks.sessionsData = [session('ses_1', 'First', '/w/a', 3000)]
+ renderPicker()
+ const user = userEvent.setup()
+
+ await user.click(screen.getByRole('button', { name: 'Session actions' }))
+ await user.click(await screen.findByText('Delete'))
+
+ expect(await screen.findByRole('dialog', { name: 'Delete Session' })).toBeInTheDocument()
+ })
+
+ it('groups older sessions under per-day headings', () => {
+ mocks.sessionsData = [
+ session('ses_jan2', 'Jan two', '/w/a', new Date(2020, 0, 2, 12).getTime()),
+ session('ses_jan1', 'Jan one', '/w/a', new Date(2020, 0, 1, 12).getTime()),
+ ]
+
+ renderPicker()
+
+ expect(screen.getByText('Thu, Jan 2, 2020')).toBeInTheDocument()
+ expect(screen.getByText('Wed, Jan 1, 2020')).toBeInTheDocument()
+ })
+
+ it('resets the query and cursor on reopen', async () => {
+ mocks.sessionsData = [
+ session('ses_active', 'Active session', '/w/a', 3000),
+ session('ses_other', 'Other session', '/w/a', 2000),
+ ]
+
+ function Host() {
+ const [open, setOpen] = useState(true)
+ return (
+ <>
+
+
+
+ >
+ )
+ }
+
+ render()
+
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Other' } })
+ expect(screen.queryByText('Active session')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('close-picker'))
+ fireEvent.click(screen.getByText('open-picker'))
+
+ await waitFor(() => expect(screen.getByRole('combobox')).toHaveValue(''))
+ expect(screen.getByRole('option', { name: /Active session/ })).toHaveAttribute('aria-selected', 'true')
+ })
+})
diff --git a/frontend/src/components/session/SessionPickerDialog.tsx b/frontend/src/components/session/SessionPickerDialog.tsx
new file mode 100644
index 00000000..d8e63ecf
--- /dev/null
+++ b/frontend/src/components/session/SessionPickerDialog.tsx
@@ -0,0 +1,631 @@
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
+import { format, startOfDay } from 'date-fns'
+import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
+import type { Repo, Session } from '@/api/types'
+import { Button } from '@/components/ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { Input } from '@/components/ui/input'
+import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
+import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
+import { partitionSessions } from '@/components/session/session-partition'
+import { useDeleteSession } from '@/hooks/useOpenCode'
+import { useSessionSearch } from '@/hooks/useSessionSearch'
+import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
+import { usePersistentBoolean } from '@/hooks/useSidebarCollapsed'
+import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
+import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
+import { buildPinnedSessionKeys, buildSessionKey } from '@/lib/sessionKey'
+import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils'
+import { isFinePointer } from '@/lib/overlayFocus'
+
+const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects'
+const UNTITLED_SESSION_TITLE = 'Untitled Session'
+const PAGE_STEP = 10
+const NEAR_BOTTOM_PX = 240
+
+interface SessionPickerDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ currentRepo: Repo | undefined
+ activeSessionID?: string
+ onSelectSession: (session: Session, repo: Repo) => void
+ onActiveSessionDeleted: () => void
+}
+
+interface SessionPickerRow {
+ key: string
+ session: Session
+ repo: Repo
+}
+
+interface SessionPickerSection {
+ id: string
+ heading: string
+ rows: SessionPickerRow[]
+}
+
+function buildSections(
+ sessions: Session[],
+ pinnedKeys: ReadonlySet,
+ keyFn: (session: Session) => string,
+ resolveRepo: (session: Session) => Repo | undefined,
+): SessionPickerSection[] {
+ const { pinned, today, older } = partitionSessions(sessions, pinnedKeys, keyFn)
+ const toRows = (group: Session[]): SessionPickerRow[] =>
+ group.flatMap((session) => {
+ const repo = resolveRepo(session)
+ return repo ? [{ key: keyFn(session), session, repo }] : []
+ })
+
+ const sections: SessionPickerSection[] = []
+ const pinnedRows = toRows(pinned)
+ if (pinnedRows.length > 0) sections.push({ id: 'pinned', heading: 'Pinned', rows: pinnedRows })
+ const todayRows = toRows(today)
+ if (todayRows.length > 0) sections.push({ id: 'today', heading: 'Today', rows: todayRows })
+
+ const currentYear = new Date().getFullYear()
+ const byDay = new Map()
+ for (const row of toRows(older)) {
+ const day = startOfDay(new Date(row.session.time.updated)).getTime()
+ const existing = byDay.get(day)
+ if (existing) existing.push(row)
+ else byDay.set(day, [row])
+ }
+ for (const [day, rows] of byDay) {
+ const date = new Date(day)
+ const heading =
+ date.getFullYear() === currentYear ? format(date, 'EEE, MMM d') : format(date, 'EEE, MMM d, yyyy')
+ sections.push({ id: `day-${day}`, heading, rows })
+ }
+ return sections
+}
+
+function optionId(baseId: string, index: number): string {
+ return `${baseId}-option-${index}`
+}
+
+function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isActive: boolean }) {
+ const status = useSessionStatusForSession(sessionID)
+ if (status.type !== 'idle') {
+ return (
+
+ )
+ }
+ if (isActive) {
+ return ●
+ }
+ return null
+}
+
+interface SessionPickerRowItemProps {
+ row: SessionPickerRow
+ optionId: string
+ isCursor: boolean
+ isActive: boolean
+ isPinned: boolean
+ isPendingDelete: boolean
+ showRepo: boolean
+ onOpen: () => void
+ onHover: () => void
+ onTogglePin: () => void
+ onRequestDelete: () => void
+ registerRef: (node: HTMLDivElement | null) => void
+}
+
+function SessionPickerRowItem({
+ row,
+ optionId,
+ isCursor,
+ isActive,
+ isPinned,
+ isPendingDelete,
+ showRepo,
+ onOpen,
+ onHover,
+ onTogglePin,
+ onRequestDelete,
+ registerRef,
+}: SessionPickerRowItemProps) {
+ return (
+ {
+ if (event.pointerType === 'mouse') onHover()
+ }}
+ className={cn(
+ 'group flex items-center rounded-md text-sm min-h-8 pointer-coarse:min-h-11',
+ isPendingDelete
+ ? 'bg-destructive text-destructive-foreground'
+ : isCursor
+ ? 'bg-primary text-primary-foreground'
+ : 'hover:bg-accent',
+ )}
+ >
+
+
+
+
+
+ {isPendingDelete ? 'Press Ctrl+D again to confirm' : row.session.title || UNTITLED_SESSION_TITLE}
+
+
+ {showRepo && {getRepoDisplayName(row.repo)}}
+ {formatShortRelativeTime(new Date(row.session.time.updated))}
+
+
+
+
+
+
+
+ event.stopPropagation()}>
+
+ {isPinned ? : }
+ {isPinned ? 'Unpin' : 'Pin'}
+
+ Delete
+
+
+
+
+ )
+}
+
+export function SessionPickerDialog({
+ open,
+ onOpenChange,
+ currentRepo,
+ activeSessionID,
+ onSelectSession,
+ onActiveSessionDeleted,
+}: SessionPickerDialogProps) {
+ const [allProjects, toggleAllProjects] = usePersistentBoolean(ALL_PROJECTS_STORAGE_KEY, false)
+ const { repos } = useNavigableRepos(open)
+ const searchInputRef = useRef(null)
+ const listRef = useRef(null)
+ const rowRefs = useRef(new Map())
+ const listId = useId()
+ const optionBaseId = useId()
+
+ const repoByDirectory = useMemo(() => {
+ const map = new Map()
+ for (const repo of repos) map.set(repo.fullPath, repo)
+ if (currentRepo) map.set(currentRepo.fullPath, currentRepo)
+ return map
+ }, [repos, currentRepo])
+
+ const directories = useMemo(() => {
+ if (!allProjects) return currentRepo ? [currentRepo.fullPath] : []
+ const paths = repos.map((repo) => repo.fullPath)
+ if (currentRepo) paths.push(currentRepo.fullPath)
+ return Array.from(new Set(paths))
+ }, [allProjects, repos, currentRepo])
+
+ const {
+ query,
+ setQuery,
+ trimmedQuery,
+ filteredSessions,
+ isSearchPending,
+ isLoading,
+ fetchNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ canFetchNextPage,
+ } = useSessionSearch(directories)
+
+ const keyFn = useCallback(
+ (session: Session) => buildSessionKey(session.location.directory, session.id),
+ [],
+ )
+ const resolveRepo = useCallback(
+ (session: Session) => repoByDirectory.get(session.location.directory) ?? currentRepo,
+ [repoByDirectory, currentRepo],
+ )
+
+ const { data: sessionPins } = useSessionPins()
+ const togglePin = useToggleSessionPin()
+ const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
+ const deleteSession = useDeleteSession(directories)
+
+ const [cursorKey, setCursorKey] = useState(null)
+ const [pendingDeleteKey, setPendingDeleteKey] = useState(null)
+ const [sessionToDelete, setSessionToDelete] = useState(null)
+
+ const sections = useMemo(
+ () => buildSections(filteredSessions, pinnedKeys, keyFn, resolveRepo),
+ [filteredSessions, pinnedKeys, keyFn, resolveRepo],
+ )
+ const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
+ const rowIndexByKey = useMemo(
+ () => new Map(rows.map((row, index) => [row.key, index])),
+ [rows],
+ )
+
+ const activeRow = useMemo(
+ () => rows.find((row) => row.session.id === activeSessionID),
+ [rows, activeSessionID],
+ )
+ const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
+ const cursorIndex = useMemo(() => {
+ if (cursorKey) {
+ const index = rowIndexByKey.get(cursorKey)
+ if (index !== undefined) return index
+ }
+ return defaultCursorKey ? rowIndexByKey.get(defaultCursorKey) ?? -1 : -1
+ }, [cursorKey, rowIndexByKey, defaultCursorKey])
+ const cursorRow = cursorIndex >= 0 ? rows[cursorIndex] : undefined
+
+ useEffect(() => {
+ setCursorKey(null)
+ setPendingDeleteKey(null)
+ }, [trimmedQuery, allProjects])
+
+ useEffect(() => {
+ if (!open) return
+ setQuery('')
+ setCursorKey(null)
+ setPendingDeleteKey(null)
+ setSessionToDelete(null)
+ }, [open, setQuery])
+
+ const setRowRef = useCallback((key: string, node: HTMLDivElement | null) => {
+ if (node) rowRefs.current.set(key, node)
+ else rowRefs.current.delete(key)
+ }, [])
+
+ useEffect(() => {
+ if (!cursorRow) return
+ const node = rowRefs.current.get(cursorRow.key)
+ if (node && typeof node.scrollIntoView === 'function') {
+ node.scrollIntoView({ block: 'nearest' })
+ }
+ }, [cursorRow])
+
+ const moveCursor = useCallback(
+ (index: number) => {
+ const row = rows[index]
+ if (!row) return
+ setCursorKey(row.key)
+ setPendingDeleteKey(null)
+ },
+ [rows],
+ )
+
+ const openRow = useCallback(
+ (row: SessionPickerRow | undefined) => {
+ if (!row) return
+ onSelectSession(row.session, row.repo)
+ },
+ [onSelectSession],
+ )
+
+ const deleteRow = useCallback(
+ (row: SessionPickerRow | undefined) => {
+ if (!row) return
+ if (pendingDeleteKey !== row.key) {
+ setPendingDeleteKey(row.key)
+ return
+ }
+ void deleteSession
+ .mutateAsync({ id: row.session.id, directory: row.session.location.directory })
+ .then(() => {
+ if (row.session.id === activeSessionID) onActiveSessionDeleted()
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ setPendingDeleteKey(null)
+ })
+ },
+ [pendingDeleteKey, deleteSession, activeSessionID, onActiveSessionDeleted],
+ )
+
+ const handleSearchKeyDown = useCallback(
+ (event: React.KeyboardEvent) => {
+ if (event.nativeEvent.isComposing) return
+ if (event.metaKey || event.altKey) return
+
+ const moveBy = (delta: number, wrap: boolean) => {
+ if (rows.length === 0) return
+ const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
+ const raw = base + delta
+ const next = wrap ? ((raw % rows.length) + rows.length) % rows.length : Math.max(0, Math.min(rows.length - 1, raw))
+ moveCursor(next)
+ }
+
+ const key = event.key
+ const ctrlKey = event.key.toLowerCase()
+
+ if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
+ event.preventDefault()
+ moveBy(1, true)
+ return
+ }
+ if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
+ event.preventDefault()
+ moveBy(-1, true)
+ return
+ }
+ if (key === 'PageDown') {
+ event.preventDefault()
+ moveBy(PAGE_STEP, false)
+ return
+ }
+ if (key === 'PageUp') {
+ event.preventDefault()
+ moveBy(-PAGE_STEP, false)
+ return
+ }
+ if (key === 'Enter') {
+ if (!cursorRow) return
+ event.preventDefault()
+ openRow(cursorRow)
+ return
+ }
+ if (event.ctrlKey && ctrlKey === 'a') {
+ event.preventDefault()
+ toggleAllProjects()
+ return
+ }
+ if (event.ctrlKey && ctrlKey === 'd') {
+ if (!cursorRow) return
+ event.preventDefault()
+ deleteRow(cursorRow)
+ }
+ },
+ [cursorIndex, rows, moveCursor, cursorRow, openRow, toggleAllProjects, deleteRow],
+ )
+
+ const handleListScroll = useCallback(
+ (event: React.UIEvent) => {
+ const { scrollTop, scrollHeight, clientHeight } = event.currentTarget
+ if (scrollHeight - scrollTop - clientHeight <= NEAR_BOTTOM_PX && canFetchNextPage) {
+ void fetchNextPage()
+ }
+ },
+ [canFetchNextPage, fetchNextPage],
+ )
+
+ useEffect(() => {
+ if (!open) return
+ const node = listRef.current
+ const isNearBottom = node
+ ? node.scrollHeight - node.scrollTop - node.clientHeight <= NEAR_BOTTOM_PX
+ : rows.length === 0
+ if (!isLoading && isNearBottom && canFetchNextPage) {
+ void fetchNextPage()
+ }
+ }, [open, isLoading, rows, canFetchNextPage, fetchNextPage])
+
+ const handleTogglePin = useCallback(
+ (row: SessionPickerRow) => {
+ togglePin.mutate({
+ sessionId: row.session.id,
+ directory: row.session.location.directory,
+ pinned: !pinnedKeys.has(row.key),
+ })
+ },
+ [togglePin, pinnedKeys],
+ )
+
+ const confirmDelete = useCallback(() => {
+ if (!sessionToDelete) return
+ void deleteSession
+ .mutateAsync({
+ id: sessionToDelete.id,
+ directory: sessionToDelete.location.directory,
+ })
+ .then(() => {
+ if (sessionToDelete.id === activeSessionID) onActiveSessionDeleted()
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ setSessionToDelete(null)
+ })
+ }, [sessionToDelete, deleteSession, activeSessionID, onActiveSessionDeleted])
+
+ const renderRow = (row: SessionPickerRow) => {
+ const index = rowIndexByKey.get(row.key) ?? -1
+ return (
+ openRow(row)}
+ onHover={() => moveCursor(index)}
+ onTogglePin={() => handleTogglePin(row)}
+ onRequestDelete={() => setSessionToDelete(row.session)}
+ registerRef={(node) => setRowRef(row.key, node)}
+ />
+ )
+ }
+
+ return (
+
+ )
+}
diff --git a/frontend/src/hooks/useSessionSearch.test.tsx b/frontend/src/hooks/useSessionSearch.test.tsx
new file mode 100644
index 00000000..d8a4b51d
--- /dev/null
+++ b/frontend/src/hooks/useSessionSearch.test.tsx
@@ -0,0 +1,112 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import { useSessionSearch } from './useSessionSearch'
+
+const { sessionsData, lastArgsRef, flagsRef } = vi.hoisted(() => ({
+ sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
+ lastArgsRef: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean } } | undefined },
+ flagsRef: { current: { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false } },
+}))
+
+vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean }) => {
+ lastArgsRef.current = { directories, options }
+ const search = options?.search?.toLowerCase() ?? ''
+ const data = search
+ ? sessionsData.filter((session) => session.title.toLowerCase().includes(search))
+ : sessionsData
+ return {
+ data,
+ isLoading: false,
+ isPlaceholderData: flagsRef.current.isPlaceholderData,
+ fetchNextPage: vi.fn(),
+ hasNextPage: flagsRef.current.hasNextPage,
+ isFetchingNextPage: flagsRef.current.isFetchingNextPage,
+ isFetchNextPageError: flagsRef.current.isFetchNextPageError,
+ }
+ },
+ }
+})
+
+describe('useSessionSearch', () => {
+ beforeEach(() => {
+ sessionsData.splice(0, sessionsData.length,
+ { id: 'ses_alpha', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 2 } },
+ { id: 'ses_beta', title: 'beta task', location: { directory: '/w/a' }, time: { updated: 1 } },
+ )
+ lastArgsRef.current = undefined
+ flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false }
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('filters sessions locally by title immediately', () => {
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ act(() => {
+ result.current.setQuery('alpha')
+ })
+
+ expect(result.current.filteredSessions.map((session) => session.title)).toEqual(['alpha task'])
+ expect(lastArgsRef.current?.options?.search).toBe('')
+ })
+
+ it('passes the debounced search to useSessionsAcrossDirectories with keepPreviousResults', () => {
+ vi.useFakeTimers()
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ act(() => {
+ result.current.setQuery('deploy')
+ })
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(lastArgsRef.current?.options?.search).toBe('deploy')
+ expect(lastArgsRef.current?.options?.limit).toBe(25)
+ expect(lastArgsRef.current?.options?.keepPreviousResults).toBe(true)
+ })
+
+ it('reports a pending search before the debounce settles', () => {
+ vi.useFakeTimers()
+ const { result } = renderHook(() => useSessionSearch(['/w/a']))
+
+ act(() => {
+ result.current.setQuery('deploy')
+ })
+
+ expect(result.current.isSearchPending).toBe(true)
+
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(result.current.isSearchPending).toBe(false)
+ })
+
+ it('exposes canFetchNextPage only when paging is safe', () => {
+ const { result, rerender } = renderHook(() => useSessionSearch(['/w/a']))
+ expect(result.current.canFetchNextPage).toBe(false)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(true)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: true, isFetchNextPageError: false, isPlaceholderData: false }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(false)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: true, isPlaceholderData: false }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(false)
+
+ flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: true }
+ rerender()
+ expect(result.current.canFetchNextPage).toBe(false)
+ })
+})
diff --git a/frontend/src/hooks/useSessionSearch.ts b/frontend/src/hooks/useSessionSearch.ts
new file mode 100644
index 00000000..955d699c
--- /dev/null
+++ b/frontend/src/hooks/useSessionSearch.ts
@@ -0,0 +1,71 @@
+import { useCallback, useMemo, useState } from 'react'
+import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
+import { useDebouncedValue } from '@/hooks/useDebouncedValue'
+import { selectRootSessions } from '@/components/session/session-partition'
+import { buildSessionKey } from '@/lib/sessionKey'
+import type { Session } from '@/api/types'
+
+const DEFAULT_LIMIT = 25
+
+export interface UseSessionSearchOptions {
+ limit?: number
+}
+
+/**
+ * Owns the sessions-dialog search state: the raw query, its debounced server
+ * value, the root-session selection, and the immediate local title filter.
+ */
+export function useSessionSearch(directories: string[], options: UseSessionSearchOptions = {}) {
+ const limit = options.limit ?? DEFAULT_LIMIT
+ const [query, setQuery] = useState('')
+ const trimmedQuery = query.trim()
+ const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
+ const search = trimmedQuery ? debouncedQuery : ''
+ const {
+ data: sessions,
+ isLoading,
+ isPlaceholderData,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ } = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true })
+
+ const directorySet = useMemo(() => new Set(directories), [directories])
+ const getSessionSelectionKey = useCallback(
+ (session: Session) => buildSessionKey(session.location.directory, session.id),
+ [],
+ )
+
+ const rootSessions = useMemo(
+ () => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }),
+ [sessions, directorySet, getSessionSelectionKey],
+ )
+
+ const filteredSessions = useMemo(() => {
+ if (!trimmedQuery) return rootSessions
+ const needle = trimmedQuery.toLowerCase()
+ return rootSessions.filter((session) => (session.title ?? '').toLowerCase().includes(needle))
+ }, [rootSessions, trimmedQuery])
+
+ const isSearchPending = trimmedQuery !== search || isPlaceholderData
+ const canFetchNextPage = Boolean(
+ hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData,
+ )
+
+ return {
+ query,
+ setQuery,
+ trimmedQuery,
+ sessions,
+ filteredSessions,
+ isSearchPending,
+ isLoading,
+ isPlaceholderData,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ canFetchNextPage,
+ }
+}
diff --git a/frontend/src/hooks/useSidebarCollapsed.ts b/frontend/src/hooks/useSidebarCollapsed.ts
index 3ae6662a..148868bb 100644
--- a/frontend/src/hooks/useSidebarCollapsed.ts
+++ b/frontend/src/hooks/useSidebarCollapsed.ts
@@ -31,7 +31,11 @@ function readStoredBoolean(key: string, fallback: boolean): boolean {
}
}
-function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
+/**
+ * Persists a boolean preference under `key` in localStorage and returns it with a toggler.
+ * Falls back to `fallback` when the stored value is missing or malformed.
+ */
+export function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
const toggle = useCallback(() => {
diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx
index c0d248cb..20529d97 100644
--- a/frontend/src/pages/SessionDetail.tsx
+++ b/frontend/src/pages/SessionDetail.tsx
@@ -8,13 +8,11 @@ import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
import { X, CornerUpLeft } from "lucide-react";
import { SquareFill } from "@/components/ui/square-fill";
import { Header } from "@/components/ui/header";
-import { SessionList } from "@/components/session/SessionList";
-import { getSessionListPath } from '@/lib/navigation'
-import { isFinePointer } from '@/lib/overlayFocus'
+import { SessionPickerDialog } from "@/components/session/SessionPickerDialog";
+import { getSessionListPath, getSessionPath } from '@/lib/navigation'
import { FetchError } from '@/api/fetchWrapper'
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
-import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
import { useSession, useInterruptSession, useUpdateSession, useCreateSession } from "@/hooks/useOpenCode";
@@ -828,32 +826,25 @@ export function SessionDetail() {
)}