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 ( onOpenChange(false)} onOpenAutoFocus={(event) => { event.preventDefault() if (isFinePointer()) { searchInputRef.current?.focus() } else { ;(event.currentTarget as HTMLElement).focus() } }} > Sessions {!allProjects && currentRepo && ( for {getRepoDisplayName(currentRepo)} )}
= 0 ? optionId(optionBaseId, cursorIndex) : undefined} value={query} onChange={(event) => setQuery(event.target.value)} onKeyDown={handleSearchKeyDown} placeholder="Search sessions..." className="h-9 pl-9" autoComplete="off" name="session-picker-search" />
{rows.length === 0 ? (
{isLoading ? 'Loading sessions...' : isSearchPending ? 'Searching sessions...' : trimmedQuery ? 'No sessions found' : 'No sessions yet'}
) : ( <> {sections.map((section) => (
{section.heading}
{section.rows.map(renderRow)}
))} {isFetchNextPageError && (

Failed to load more sessions

)} {isFetchingNextPage && rows.length > 0 && (
Loading more sessions...
)} )}
↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
{ if (!nextOpen) setSessionToDelete(null) }} onConfirm={() => { void confirmDelete() }} onCancel={() => setSessionToDelete(null)} isDeleting={deleteSession.isPending} />
) }