diff --git a/frontend/src/components/session/SessionList.test.tsx b/frontend/src/components/session/SessionList.test.tsx index a2441237..e445c323 100644 --- a/frontend/src/components/session/SessionList.test.tsx +++ b/frontend/src/components/session/SessionList.test.tsx @@ -583,102 +583,6 @@ describe('SessionList', () => { expect(searchInput).toHaveFocus() }) - it('highlights the active session by default and the first match after typing', async () => { - const user = userEvent.setup() - sessionsData.splice(0, sessionsData.length, - { id: 'ses_active', title: 'active task', location: { directory: '/w/a' }, time: { updated: 2 } }, - { id: 'ses_other', title: 'other task', location: { directory: '/w/a' }, time: { updated: 1 } }, - ) - - render( - , - ) - - expect(screen.getByRole('option', { selected: true }).textContent).toContain('active task') - - await user.type(screen.getByPlaceholderText('Search sessions...'), 'other') - - expect(screen.getByRole('option', { selected: true }).textContent).toContain('other task') - }) - - it('navigates with arrows and Ctrl+N/Ctrl+P, wrapping around, and selects with Enter', () => { - sessionsData.splice(0, sessionsData.length, - { id: 'ses_1', title: 'one', location: { directory: '/w/a' }, time: { updated: 3 } }, - { id: 'ses_2', title: 'two', location: { directory: '/w/a' }, time: { updated: 2 } }, - { id: 'ses_3', title: 'three', location: { directory: '/w/a' }, time: { updated: 1 } }, - ) - const onSelectSession = vi.fn() - - render( - , - ) - - const searchInput = screen.getByPlaceholderText('Search sessions...') - const highlightedTitle = () => screen.getByRole('option', { selected: true }).textContent ?? '' - - expect(highlightedTitle()).toContain('one') - - fireEvent.keyDown(searchInput, { key: 'ArrowDown' }) - expect(highlightedTitle()).toContain('two') - - fireEvent.keyDown(searchInput, { key: 'ArrowUp' }) - expect(highlightedTitle()).toContain('one') - - fireEvent.keyDown(searchInput, { key: 'ArrowUp' }) - expect(highlightedTitle()).toContain('three') - - fireEvent.keyDown(searchInput, { key: 'n', ctrlKey: true }) - expect(highlightedTitle()).toContain('one') - - fireEvent.keyDown(searchInput, { key: 'p', ctrlKey: true }) - expect(highlightedTitle()).toContain('three') - - fireEvent.keyDown(searchInput, { key: 'Enter' }) - expect(onSelectSession).toHaveBeenCalledWith('ses_3') - }) - - it('clamps PageDown and PageUp navigation to the ends of the list', () => { - sessionsData.splice(0, sessionsData.length, - ...Array.from({ length: 15 }, (_, index) => ({ - id: `ses_${index}`, - title: `session ${index}`, - location: { directory: '/w/a' }, - time: { updated: 15 - index }, - })), - ) - - render( - , - ) - - const searchInput = screen.getByPlaceholderText('Search sessions...') - const highlightedTitle = () => screen.getByRole('option', { selected: true }).textContent ?? '' - - expect(highlightedTitle()).toContain('session 0') - - fireEvent.keyDown(searchInput, { key: 'PageDown' }) - expect(highlightedTitle()).toContain('session 10') - - fireEvent.keyDown(searchInput, { key: 'PageDown' }) - expect(highlightedTitle()).toContain('session 14') - - fireEvent.keyDown(searchInput, { key: 'PageUp' }) - expect(highlightedTitle()).toContain('session 4') - - fireEvent.keyDown(searchInput, { key: 'PageUp' }) - expect(highlightedTitle()).toContain('session 0') - }) - it('keeps the search input rendered while the first page is loading', () => { isLoadingRef.current = true diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx index 601ca4cf..7f3d4fb0 100644 --- a/frontend/src/components/session/SessionList.tsx +++ b/frontend/src/components/session/SessionList.tsx @@ -1,17 +1,17 @@ -import { useCallback, useState, useMemo, useEffect, useRef, useId, type ReactNode } from "react"; -import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode"; +import { useCallback, useState, useMemo, useEffect, useRef, type ReactNode } from "react"; +import { useDeleteSession, useCreateSession } from "@/hooks/useOpenCode"; import type { DeleteSessionTarget } from "@/hooks/useOpenCode"; import type { Session } from "@/api/types"; import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'; import { buildSessionKey, buildPinnedSessionKeys } from '@/lib/sessionKey'; -import { partitionSessions, selectRootSessions } from './session-partition'; +import { partitionSessions } from './session-partition'; import { DeleteSessionDialog } from "./DeleteSessionDialog"; import { SessionCard } from "./SessionCard"; import { Card } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Search, Trash2, Pencil, X } from "lucide-react"; -import { useDebouncedValue } from "@/hooks/useDebouncedValue"; +import { useSessionSearch } from "@/hooks/useSessionSearch"; interface SessionListProps { directory?: string; @@ -44,17 +44,26 @@ export const SessionList = ({ const source = directories && directories.length > 0 ? directories : directory ? [directory] : []; return Array.from(new Set(source.filter(Boolean))); }, [directory, directories]); - const directorySet = useMemo(() => new Set(directoriesList), [directoriesList]); const primaryDirectory = directoriesList[0]; const sessionCreateDirectory = createDirectory ?? primaryDirectory; const getSessionSelectionKey = useCallback((session: Session) => buildSessionKey(session.location.directory, session.id), []); - const [searchQuery, setSearchQuery] = useState(""); - const trimmedSearchQuery = searchQuery.trim(); - const debouncedSearchQuery = useDebouncedValue(trimmedSearchQuery, 150); - const search = trimmedSearchQuery ? debouncedSearchQuery : ''; - const { data: sessions, isLoading, isPlaceholderData, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(directoriesList, { search, limit: 25, keepPreviousResults: true }); + const { + query, + setQuery, + trimmedQuery, + sessions, + filteredSessions, + isSearchPending, + isLoading, + isPlaceholderData, + fetchNextPage, + hasNextPage, + isFetchingNextPage, + isFetchNextPageError, + canFetchNextPage, + } = useSessionSearch(directoriesList); const deleteSession = useDeleteSession(directoriesList); const createSession = useCreateSession(sessionCreateDirectory, (newSession) => { onSelectSession(newSession.id); @@ -71,52 +80,11 @@ export const SessionList = ({ const [manageMode, setManageMode] = useState(false); const sessionListRef = useRef(null); - const rootSessions = useMemo( - () => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }), - [sessions, directorySet, getSessionSelectionKey], - ); - - const filteredSessions = useMemo(() => { - if (!trimmedSearchQuery) return rootSessions; - const needle = trimmedSearchQuery.toLowerCase(); - return rootSessions.filter((session) => (session.title ?? '').toLowerCase().includes(needle)); - }, [rootSessions, trimmedSearchQuery]); - const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo( () => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey), [filteredSessions, pinnedKeys, getSessionSelectionKey], ); - const navSessions = useMemo( - () => [...pinnedSessions, ...todaySessions, ...olderSessions], - [pinnedSessions, todaySessions, olderSessions], - ); - - const [highlightedKey, setHighlightedKey] = useState(null); - - useEffect(() => { - setHighlightedKey(null); - }, [trimmedSearchQuery]); - - const highlightedSession = useMemo(() => { - if (navSessions.length === 0) return undefined; - if (highlightedKey) { - const stored = navSessions.find((session) => getSessionSelectionKey(session) === highlightedKey); - if (stored) return stored; - } - if (!trimmedSearchQuery && activeSessionID) { - const active = navSessions.find((session) => session.id === activeSessionID); - if (active) return active; - } - return navSessions[0]; - }, [navSessions, highlightedKey, trimmedSearchQuery, activeSessionID, getSessionSelectionKey]); - - const highlightedSessionKey = highlightedSession ? getSessionSelectionKey(highlightedSession) : null; - const highlightedIndex = highlightedSession ? navSessions.indexOf(highlightedSession) : -1; - const listboxId = useId(); - const keyboardNavigationEnabled = !renderSessions && !manageMode; - const isSearchPending = trimmedSearchQuery !== search || isPlaceholderData; - const handleTogglePin = (session: Session) => { const directory = session.location.directory; const key = getSessionSelectionKey(session); @@ -129,92 +97,20 @@ export const SessionList = ({ const handleSessionsScroll = useCallback((event: React.UIEvent) => { const { scrollTop, scrollHeight, clientHeight } = event.currentTarget; - if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData) { + if (scrollHeight - scrollTop - clientHeight <= 240 && canFetchNextPage) { void fetchNextPage(); } - }, [hasNextPage, isFetchingNextPage, isFetchNextPageError, isPlaceholderData, fetchNextPage]); + }, [canFetchNextPage, fetchNextPage]); useEffect(() => { const sessionList = sessionListRef.current; const isNearBottom = sessionList ? sessionList.scrollHeight - sessionList.scrollTop - sessionList.clientHeight <= 240 : filteredSessions.length === 0; - if ( - !isLoading - && !isPlaceholderData - && isNearBottom - && hasNextPage - && !isFetchingNextPage - && !isFetchNextPageError - ) { + if (!isLoading && isNearBottom && canFetchNextPage) { void fetchNextPage(); } - }, [isLoading, isPlaceholderData, filteredSessions, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]); - - useEffect(() => { - if (!highlightedSessionKey) return; - const list = sessionListRef.current; - if (!list) return; - const highlighted = list.querySelector('[data-highlighted="true"]'); - if (highlighted && typeof highlighted.scrollIntoView === 'function') { - highlighted.scrollIntoView({ block: 'nearest' }); - } - }, [highlightedSessionKey]); - - const handleSearchKeyDown = (event: React.KeyboardEvent) => { - if (!keyboardNavigationEnabled) return; - if (event.nativeEvent.isComposing) return; - if (event.altKey || event.metaKey) return; - - const selectIndex = (index: number) => { - const session = navSessions[index]; - if (!session) return false; - setHighlightedKey(getSessionSelectionKey(session)); - return true; - }; - const moveBy = (delta: number) => { - const count = navSessions.length; - if (count === 0) return false; - return selectIndex(((highlightedIndex + delta) % count + count) % count); - }; - const moveClamped = (delta: number) => { - const count = navSessions.length; - if (count === 0) return false; - return selectIndex(Math.min(Math.max(highlightedIndex + delta, 0), count - 1)); - }; - - if (event.ctrlKey) { - if (event.key.toLowerCase() === 'n') { - if (moveBy(1)) event.preventDefault(); - } else if (event.key.toLowerCase() === 'p') { - if (moveBy(-1)) event.preventDefault(); - } - return; - } - - switch (event.key) { - case 'ArrowDown': - if (moveBy(1)) event.preventDefault(); - break; - case 'ArrowUp': - if (moveBy(-1)) event.preventDefault(); - break; - case 'PageDown': - if (moveClamped(10)) event.preventDefault(); - break; - case 'PageUp': - if (moveClamped(-10)) event.preventDefault(); - break; - case 'Enter': - if (highlightedSession) { - event.preventDefault(); - onSelectSession(highlightedSession.id); - } - break; - default: - break; - } - }; + }, [isLoading, filteredSessions, canFetchNextPage, fetchNextPage]); const getDeleteTarget = (session: Session): DeleteSessionTarget => ({ id: session.id, @@ -280,7 +176,7 @@ export const SessionList = ({ const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => { const key = getSessionSelectionKey(session); - const card = ( + return ( handleDelete(session, e)} /> ); - if (!keyboardNavigationEnabled) return card; - const index = navSessions.indexOf(session); - const isHighlighted = highlightedSession === session; - return ( -
- {card} -
- ); }; if (!isLoading && !isPlaceholderData && (!sessions || sessions.length === 0)) { @@ -325,7 +206,7 @@ export const SessionList = ({ if ((hasNextPage || isFetchingNextPage) && !renderSessions) { return
Loading sessions...
; } - if (!searchQuery.trim() && !renderSessions) { + if (!trimmedQuery && !renderSessions) { return (
setSearchQuery(e.target.value)} - onKeyDown={handleSearchKeyDown} + value={query} + onChange={(e) => setQuery(e.target.value)} className="pl-9 h-9" autoComplete="off" name="session-search" - role={keyboardNavigationEnabled ? 'combobox' : undefined} - aria-expanded={keyboardNavigationEnabled ? true : undefined} - aria-controls={keyboardNavigationEnabled ? listboxId : undefined} - aria-activedescendant={keyboardNavigationEnabled && highlightedIndex >= 0 ? `${listboxId}-option-${highlightedIndex}` : undefined} />
+ + + + ) + } + + 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 ( + + 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} + /> +
+
+ ) +} 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() { )} - {/* Sessions Dialog */} - - { - if (!isFinePointer()) { - event.preventDefault(); - (event.currentTarget as HTMLElement).focus(); - } - }} - > - Sessions -
- {sessionDirectory && ( - { - navigate(`/repos/${repoId}/sessions/${sessionID}${sessionRouteSuffix}`) - setSessionsDialogOpen(false) - }} - /> - )} -
-
-
+ {/* Sessions Picker */} + { + if (sessionRepo.id === repoId) { + navigate(`/repos/${repoId}/sessions/${session.id}${sessionRouteSuffix}`) + } else { + navigate(getSessionPath(sessionRepo.id, session.id)) + } + setSessionsDialogOpen(false) + }} + onActiveSessionDeleted={() => { + setSessionsDialogOpen(false) + navigate(getSessionListPath(repoId, isAssistantSession)) + }} + /> {sideQuestion && sessionId && ( ({ vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: vi.fn(() => ({ data: undefined })), })) -vi.mock('@/components/session/SessionList', () => ({ - SessionList: vi.fn(() => null), +vi.mock('@/components/session/SessionPickerDialog', () => ({ + SessionPickerDialog: vi.fn(() => null), })) vi.mock('@/components/session/PermissionModeToggle', () => ({ diff --git a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx index 85d20b26..9088fdd9 100644 --- a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx @@ -207,7 +207,7 @@ vi.mock('@/components/navigation/ToolSidePanel', () => ({ ToolSidePanel: vi.fn(( vi.mock('@/hooks/useToolPanel', () => ({ useToolPanel: vi.fn(() => ({ activeTool: null, toggleTool: vi.fn(), closePanel: vi.fn() })), })) -vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) })) +vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) })) vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) })) vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) })) vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx index 287ecce2..c0ade130 100644 --- a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx @@ -159,8 +159,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({ useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })), useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })), })) -vi.mock('@/components/session/SessionList', () => ({ - SessionList: vi.fn(() => null), +vi.mock('@/components/session/SessionPickerDialog', () => ({ + SessionPickerDialog: vi.fn(() => null), })) vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ diff --git a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx index e055c3c7..9ed44a8c 100644 --- a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx @@ -137,7 +137,7 @@ vi.mock('@/hooks/useSessionGoals', () => ({ vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: vi.fn(() => ({ data: undefined })), })) -vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) })) +vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) })) vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: vi.fn(() => null) })) vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) })) vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx index 9a00bc0d..7362bed9 100644 --- a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx @@ -154,8 +154,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({ useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })), useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })), })) -vi.mock('@/components/session/SessionList', () => ({ - SessionList: vi.fn(() => null), +vi.mock('@/components/session/SessionPickerDialog', () => ({ + SessionPickerDialog: vi.fn(() => null), })) vi.mock('@/components/file-browser/FileBrowserSheet', () => ({