import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react' import { useQuery } from '@tanstack/react-query' import { format, startOfDay } from 'date-fns' import { MoreHorizontal, Pin, PinOff } from 'lucide-react' import { getOpenCodeLocation } from '@/api/opencode' import type { Repo, Session } from '@/api/types' import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork' 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 { SessionStatusIndicator } from '@/components/ui/session-status-indicator' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog' import { ProjectPickerContent } from '@/components/session/ProjectPickerContent' import { PickerSearchBar, optionId, usePickerCursor, usePickerKeyNav, } from '@/components/session/usePickerKeyboardNav' import { partitionSessions } from '@/components/session/session-partition' import { buildRepoByDirectory } from '@/components/navigation/sidebar-session-tree' import { useDeleteSession } from '@/hooks/useOpenCode' import { useActiveWork, useActivityWindowMinutes } from '@/hooks/useActiveWork' import { useSessionSearch } from '@/hooks/useSessionSearch' import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins' import { usePersistentBoolean } from '@/hooks/usePersistentBoolean' import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups' import { useSessionStatusForSession } from '@/stores/sessionStatusStore' import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext' import { useSettings } from '@/hooks/useSettings' import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey' import { formatShortcutLabel, resolveShortcutBindings } from '@/lib/keyboardShortcuts' import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils' import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery' const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects' const UNTITLED_SESSION_TITLE = 'Untitled Session' const NEAR_BOTTOM_PX = 240 type SessionPickerTab = 'active' | 'sessions' | 'projects' const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects'] const SESSION_PICKER_TAB_LABELS: Record = { active: 'Active', sessions: 'Sessions', projects: 'Projects', } function nextSessionPickerTab(tab: SessionPickerTab): SessionPickerTab { const index = SESSION_PICKER_TABS.indexOf(tab) return SESSION_PICKER_TABS[(index + 1) % SESSION_PICKER_TABS.length] } interface SessionPickerDialogProps { open: boolean onOpenChange: (open: boolean) => void currentRepo: Repo | undefined activeSessionID?: string onSelectSession: (session: Session, repo: Repo) => void onDeleteActiveSession: () => void onSelectRepo: (repo: Repo) => void } interface SessionPickerRow { key: string session: Session repo: Repo updatedAt?: number } 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 stripTrailingSlashes(value: string): string { return value.replace(/\/+$/, '') } function relativeSubpath(base: string, target: string): string { const baseSegments = stripTrailingSlashes(base).split('/').filter(Boolean) const targetSegments = stripTrailingSlashes(target).split('/').filter(Boolean) let common = 0 while ( common < baseSegments.length && common < targetSegments.length && baseSegments[common] === targetSegments[common] ) { common += 1 } const upward = baseSegments.length - common const downward = targetSegments.slice(common) return [...Array.from({ length: upward }, () => '..'), ...downward].join('/') } function sessionRootDirectory(session: Session): string { const directory = stripTrailingSlashes(session.location.directory) const subpath = session.subpath if (!subpath) return directory const depth = subpath.split('/').filter(Boolean).length let root = directory for (let index = 0; index < depth; index += 1) { const separator = root.lastIndexOf('/') if (separator <= 0) break root = root.slice(0, separator) } return root } function isPathInside(base: string, target: string): boolean { const normalizedBase = stripTrailingSlashes(base) if (target === normalizedBase) return true return target.startsWith(`${normalizedBase}/`) } function sessionWorktreeLabel(session: Session, canonical: string | undefined): string | undefined { if (!canonical) return undefined const root = sessionRootDirectory(session) if (isPathInside(canonical, root)) return undefined const segments = root.split('/').filter(Boolean) return segments[segments.length - 1] } 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 index: number optionId: string isCursor: boolean isActive: boolean isPinned: boolean isPendingDelete: boolean showRepo: boolean label?: string onOpen: (row: SessionPickerRow) => void onHover: (index: number) => void onTogglePin: (row: SessionPickerRow) => void onRequestDelete: (session: Session) => void registerRef: (key: string, node: HTMLDivElement | null) => void } const SessionPickerRowItem = memo(function SessionPickerRowItem({ row, index, optionId, isCursor, isActive, isPinned, isPendingDelete, showRepo, label, onOpen, onHover, onTogglePin, onRequestDelete, registerRef, }: SessionPickerRowItemProps) { return (
registerRef(row.key, node)} role="presentation" onPointerMove={(event) => { if (event.pointerType === 'mouse') onHover(index) }} 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', )} >
onOpen(row)} className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2" > {isPendingDelete ? 'Press Ctrl+D again to confirm' : row.session.title || UNTITLED_SESSION_TITLE} {showRepo && {getRepoDisplayName(row.repo)}} {!showRepo && label && {label}} {formatShortRelativeTime(new Date(row.updatedAt ?? row.session.time.updated))}
event.stopPropagation()}> onTogglePin(row)}> {isPinned ? : } {isPinned ? 'Unpin' : 'Pin'} onRequestDelete(row.session)}>Delete
) }) interface SessionPickerRowActionsOptions { directories: string[] activeSessionID?: string onSelectSession: (session: Session, repo: Repo) => void onDeleteActiveSession: () => void } interface SessionPickerRowActions { pinnedKeys: ReadonlySet pendingDeleteKey: string | null clearPendingDelete: () => void openRow: (row: SessionPickerRow | undefined) => void deleteRow: (row: SessionPickerRow | undefined) => void handleTogglePin: (row: SessionPickerRow) => void handleRequestDelete: (session: Session) => void deleteDialogProps: { open: boolean onOpenChange: (open: boolean) => void onConfirm: () => void onCancel: () => void isDeleting: boolean } } function useSessionPickerRowActions({ directories, activeSessionID, onSelectSession, onDeleteActiveSession, }: SessionPickerRowActionsOptions): SessionPickerRowActions { const { data: sessionPins } = useSessionPins() const togglePin = useToggleSessionPin() const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins]) const deleteSession = useDeleteSession(directories) const [sessionToDelete, setSessionToDelete] = useState(null) const [pendingDeleteKey, setPendingDeleteKey] = useState(null) const clearPendingDelete = useCallback(() => { setPendingDeleteKey(null) }, []) const openRow = useCallback( (row: SessionPickerRow | undefined) => { if (!row) return onSelectSession(row.session, row.repo) }, [onSelectSession], ) const performDelete = useCallback( (session: Session) => { if (session.id === activeSessionID) onDeleteActiveSession() return deleteSession .mutateAsync({ id: session.id, directory: session.location.directory }) .catch(() => undefined) }, [deleteSession, activeSessionID, onDeleteActiveSession], ) const deleteRow = useCallback( (row: SessionPickerRow | undefined) => { if (!row) return if (pendingDeleteKey !== row.key) { setPendingDeleteKey(row.key) return } void performDelete(row.session).finally(() => { setPendingDeleteKey(null) }) }, [pendingDeleteKey, performDelete], ) const handleTogglePin = useCallback( (row: SessionPickerRow) => { togglePin.mutate({ sessionId: row.session.id, directory: row.session.location.directory, pinned: !pinnedKeys.has(row.key), }) }, [togglePin, pinnedKeys], ) const handleRequestDelete = useCallback((session: Session) => { setSessionToDelete(session) }, []) const confirmDelete = useCallback(() => { if (!sessionToDelete) return void performDelete(sessionToDelete).finally(() => { setSessionToDelete(null) }) }, [sessionToDelete, performDelete]) const deleteDialogProps = useMemo( () => ({ open: sessionToDelete !== null, onOpenChange: (nextOpen: boolean) => { if (!nextOpen) setSessionToDelete(null) }, onConfirm: () => { void confirmDelete() }, onCancel: () => setSessionToDelete(null), isDeleting: deleteSession.isPending, }), [sessionToDelete, confirmDelete, deleteSession.isPending], ) return { pinnedKeys, pendingDeleteKey, clearPendingDelete, openRow, deleteRow, handleTogglePin, handleRequestDelete, deleteDialogProps, } } interface SessionPickerListProps { listId: string optionBaseId: string ariaLabel: string sections: SessionPickerSection[] rows: SessionPickerRow[] rowIndexByKey: ReadonlyMap cursorIndex: number activeSessionID?: string pinnedKeys: ReadonlySet pendingDeleteKey: string | null showRepo: boolean labelFor?: (row: SessionPickerRow) => string | undefined emptyState: React.ReactNode onOpenRow: (row: SessionPickerRow) => void onHoverRow: (index: number) => void onTogglePin: (row: SessionPickerRow) => void onRequestDelete: (session: Session) => void registerRef: (key: string, node: HTMLDivElement | null) => void listRef?: React.RefObject onScroll?: (event: React.UIEvent) => void children?: React.ReactNode } function SessionPickerList({ listId, optionBaseId, ariaLabel, sections, rows, rowIndexByKey, cursorIndex, activeSessionID, pinnedKeys, pendingDeleteKey, showRepo, labelFor, emptyState, onOpenRow, onHoverRow, onTogglePin, onRequestDelete, registerRef, listRef, onScroll, children, }: SessionPickerListProps) { return (
{rows.length === 0 ? (
{emptyState}
) : ( <> {sections.map((section) => (
{section.heading}
{section.rows.map((row) => { const index = rowIndexByKey.get(row.key) ?? -1 return ( ) })}
))} {children} )}
) } interface SessionPickerContentProps { open: boolean currentRepo: Repo | undefined activeSessionID?: string onSelectSession: (session: Session, repo: Repo) => void onDeleteActiveSession: () => void switchHint: string searchInputRef: React.RefObject hasFinePointer: boolean } function SessionPickerContent({ open, currentRepo, activeSessionID, onSelectSession, onDeleteActiveSession, switchHint, searchInputRef, hasFinePointer, }: SessionPickerContentProps) { const [allProjects, toggleAllProjects] = usePersistentBoolean(ALL_PROJECTS_STORAGE_KEY, false) const { repos } = useNavigableRepos() const listRef = useRef(null) const listId = useId() const optionBaseId = useId() const repoByDirectory = useMemo(() => { const map = buildRepoByDirectory(repos) if (currentRepo) map.set(currentRepo.fullPath, currentRepo) return map }, [repos, currentRepo]) const locationQuery = useQuery({ queryKey: ['opencode', 'location', currentRepo?.fullPath], queryFn: () => getOpenCodeLocation(currentRepo!.fullPath), enabled: !allProjects && Boolean(currentRepo?.fullPath), staleTime: 5 * 60 * 1000, }) const location = locationQuery.data const locationPending = !allProjects && Boolean(currentRepo?.fullPath) && locationQuery.isPending const projectOption = useMemo(() => { if (allProjects || !location || location.project.id === 'global') return undefined return { id: location.project.id, subpath: relativeSubpath(location.project.directory, location.directory), } }, [allProjects, location]) const directories = useMemo(() => { if (allProjects) { const paths = repos.map((repo) => repo.fullPath) if (currentRepo) paths.push(currentRepo.fullPath) return Array.from(new Set(paths)) } if (locationPending) return [] return currentRepo ? [currentRepo.fullPath] : [] }, [allProjects, repos, currentRepo, locationPending]) const { query, setQuery, trimmedQuery, filteredSessions, isSearchPending, isLoading, fetchNextPage, isFetchingNextPage, isFetchNextPageError, canFetchNextPage, } = useSessionSearch(directories, { allDirectories: allProjects, project: projectOption }) const isPickerLoading = isLoading || locationPending const resolveRepo = useCallback( (session: Session) => repoByDirectory.get(session.location.directory) ?? currentRepo, [repoByDirectory, currentRepo], ) const { pinnedKeys, pendingDeleteKey, clearPendingDelete, openRow, deleteRow, handleTogglePin, handleRequestDelete, deleteDialogProps, } = useSessionPickerRowActions({ directories, activeSessionID, onSelectSession, onDeleteActiveSession, }) const sections = useMemo( () => buildSections(filteredSessions, pinnedKeys, getSessionKey, resolveRepo), [filteredSessions, pinnedKeys, resolveRepo], ) const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections]) const activeRow = useMemo( () => rows.find((row) => row.session.id === activeSessionID), [rows, activeSessionID], ) const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null const { rowIndexByKey, cursorIndex, cursorRow, registerRef, moveCursor: moveCursorRaw, resetCursor, } = usePickerCursor(rows, defaultCursorKey) const moveCursor = useCallback( (index: number) => { clearPendingDelete() moveCursorRaw(index) }, [clearPendingDelete, moveCursorRaw], ) useEffect(() => { resetCursor() clearPendingDelete() }, [trimmedQuery, allProjects, resetCursor, clearPendingDelete]) const handleSearchKeyDown = usePickerKeyNav({ rows, cursorIndex, cursorRow, moveCursor, onOpenRow: openRow, onDeleteRow: deleteRow, onToggleAllProjects: toggleAllProjects, }) 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 labelFor = useCallback( (row: SessionPickerRow) => allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical), [allProjects, location?.project.canonical], ) return ( <>
= 0 ? optionId(optionBaseId, cursorIndex) : undefined} value={query} onChange={setQuery} onKeyDown={handleSearchKeyDown} placeholder="Search sessions..." name="session-picker-search" trailing={ } /> {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'} {switchHint ? ` · ${switchHint} projects` : ''}
) } interface ActivePickerContentProps { open: boolean activeSessionID?: string onSelectSession: (session: Session, repo: Repo) => void onDeleteActiveSession: () => void switchHint: string searchInputRef: React.RefObject } function ActivePickerContent({ open, activeSessionID, onSelectSession, onDeleteActiveSession, switchHint, searchInputRef, }: ActivePickerContentProps) { const windowMinutes = useActivityWindowMinutes() const { groups, isLoading, isError } = useActiveWork(windowMinutes * MS_PER_MINUTE) const listId = useId() const optionBaseId = useId() const [query, setQuery] = useState('') const trimmedQuery = query.trim() const sections = useMemo(() => { const needle = trimmedQuery.toLowerCase() return ACTIVE_WORK_GROUPS.flatMap((definition) => { const rows: SessionPickerRow[] = [] for (const item of groups[definition.key]) { if (needle && !(item.session.title ?? '').toLowerCase().includes(needle)) continue rows.push({ key: item.key, session: item.session, repo: item.repo, updatedAt: item.updatedAt }) } return rows.length > 0 ? [{ id: definition.key, heading: definition.heading, rows }] : [] }) }, [groups, trimmedQuery]) const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections]) const activeRow = useMemo( () => rows.find((row) => row.session.id === activeSessionID), [rows, activeSessionID], ) const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null const { rowIndexByKey, cursorIndex, cursorRow, registerRef, moveCursor: moveCursorRaw, resetCursor, } = usePickerCursor(rows, defaultCursorKey) const directories = useMemo( () => Array.from(new Set(rows.map((row) => row.session.location.directory))), [rows], ) const { pinnedKeys, pendingDeleteKey, clearPendingDelete, openRow, deleteRow, handleTogglePin, handleRequestDelete, deleteDialogProps, } = useSessionPickerRowActions({ directories, activeSessionID, onSelectSession, onDeleteActiveSession, }) const moveCursor = useCallback( (index: number) => { clearPendingDelete() moveCursorRaw(index) }, [clearPendingDelete, moveCursorRaw], ) useEffect(() => { resetCursor() clearPendingDelete() }, [trimmedQuery, resetCursor, clearPendingDelete]) const handleSearchKeyDown = usePickerKeyNav({ rows, cursorIndex, cursorRow, moveCursor, onOpenRow: openRow, onDeleteRow: deleteRow, }) const emptyState = isLoading ? 'Loading sessions...' : isError ? 'Failed to load active sessions' : trimmedQuery ? 'No sessions found' : formatActivityEmptyMessage(windowMinutes) return ( <>
= 0 ? optionId(optionBaseId, cursorIndex) : undefined} value={query} onChange={setQuery} onKeyDown={handleSearchKeyDown} placeholder="Search sessions..." name="active-picker-search" />
↑↓ move · Enter open · Ctrl+D delete {switchHint ? ` · ${switchHint} sessions` : ''}
) } export function SessionPickerDialog({ open, onOpenChange, currentRepo, activeSessionID, onSelectSession, onDeleteActiveSession, onSelectRepo, }: SessionPickerDialogProps) { const searchInputRef = useRef(null) const activeSearchInputRef = useRef(null) const projectSearchInputRef = useRef(null) const focusSearchAfterSwitchRef = useRef(false) const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY) const { preferences } = useSettings() const switchHint = useMemo( () => { const bindings = resolveShortcutBindings(preferences) return formatShortcutLabel( bindings.shortcuts.switchPickerTab, bindings.directShortcuts.includes('switchPickerTab'), bindings.leaderKey, ) }, [preferences], ) const [tab, setTab] = useState('sessions') const [prevOpen, setPrevOpen] = useState(open) if (prevOpen !== open) { setPrevOpen(open) if (open) setTab('sessions') } const toggleTab = useCallback(() => { focusSearchAfterSwitchRef.current = true setTab((current) => nextSessionPickerTab(current)) }, []) useShortcutActions({ switchPickerTab: open ? toggleTab : undefined }) useEffect(() => { if (!open) { focusSearchAfterSwitchRef.current = false return } if (!hasFinePointer && !focusSearchAfterSwitchRef.current) return const frame = requestAnimationFrame(() => { focusSearchAfterSwitchRef.current = false if (tab === 'projects') projectSearchInputRef.current?.focus() else if (tab === 'active') activeSearchInputRef.current?.focus() else searchInputRef.current?.focus() }) return () => cancelAnimationFrame(frame) }, [open, tab, hasFinePointer]) return ( onOpenChange(false)} onOpenAutoFocus={(event) => { event.preventDefault() if (hasFinePointer) { searchInputRef.current?.focus() } else { ;(event.currentTarget as HTMLElement).focus() } }} > setTab(value as SessionPickerTab)} className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0" >
{SESSION_PICKER_TAB_LABELS[tab]} Active Sessions Projects
) }