diff --git a/frontend/src/components/session/SessionList.test.tsx b/frontend/src/components/session/SessionList.test.tsx index f2d20999..a2441237 100644 --- a/frontend/src/components/session/SessionList.test.tsx +++ b/frontend/src/components/session/SessionList.test.tsx @@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import type { ReactNode } from 'react' import { SessionList } from './SessionList' -const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({ +const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, isLoadingRef, isPlaceholderDataRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({ createSessionMock: vi.fn(), deleteSessionMock: vi.fn(), sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>, @@ -14,8 +14,10 @@ const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, hasNextPageRef: { current: false }, isFetchingNextPageRef: { current: false }, isFetchNextPageErrorRef: { current: false }, + isLoadingRef: { current: false }, + isPlaceholderDataRef: { current: false }, useRealSessionsHookRef: { current: false }, - lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number } } | undefined }, + lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean } } | undefined }, sessionPinsData: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>, togglePinMock: vi.fn(), })) @@ -24,15 +26,19 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => { const actual = await importOriginal() return { ...actual, - useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number }) => { + useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean }) => { if (useRealSessionsHookRef.current) { return actual.useSessionsAcrossDirectories(directories, options) } lastSessionsHookArgs.current = { directories, options } - const data = options?.search ? [] : sessionsData + const search = options?.search?.toLowerCase() ?? '' + const data = search + ? sessionsData.filter((session) => session.title.toLowerCase().includes(search)) + : sessionsData return { data, - isLoading: false, + isLoading: isLoadingRef.current, + isPlaceholderData: isPlaceholderDataRef.current, fetchNextPage: fetchNextPageMock, hasNextPage: hasNextPageRef.current, isFetchingNextPage: isFetchingNextPageRef.current, @@ -67,6 +73,8 @@ describe('SessionList', () => { hasNextPageRef.current = false isFetchingNextPageRef.current = false isFetchNextPageErrorRef.current = false + isLoadingRef.current = false + isPlaceholderDataRef.current = false useRealSessionsHookRef.current = false lastSessionsHookArgs.current = undefined sessionPinsData.splice(0, sessionPinsData.length) @@ -551,4 +559,257 @@ describe('SessionList', () => { vi.unstubAllGlobals() } }) + + it('filters rows by title immediately and keeps the search input focused', async () => { + const user = userEvent.setup() + 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 } }, + ) + + render( + , + ) + + const searchInput = screen.getByPlaceholderText('Search sessions...') + await user.click(searchInput) + await user.type(searchInput, 'alpha') + + expect(screen.getByText('alpha task')).toBeTruthy() + expect(screen.queryByText('beta task')).toBeNull() + 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 + + render( + , + ) + + expect(screen.getByPlaceholderText('Search sessions...')).toBeTruthy() + expect(screen.getByText('Loading sessions...')).toBeTruthy() + }) + + it('keeps previous rows and the search input mounted while a new search query is fetching', async () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + + const initialItems = [ + { id: 'ses_a', projectID: 'proj_1', title: 'alpha session', time: { created: 1, updated: 1 }, location: { directory: '/w/a' } }, + { id: 'ses_b', projectID: 'proj_1', title: 'beta session', time: { created: 2, updated: 2 }, location: { directory: '/w/a' } }, + ] + + let resolveSearch: ((response: Response) => void) | undefined + fetchMock.mockImplementation((input: RequestInfo | URL) => { + const url = String(input) + if (url.includes('search=beta')) { + return new Promise((resolve) => { + resolveSearch = resolve + }) + } + return Promise.resolve(new Response(JSON.stringify({ data: initialItems, cursor: {} }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + })) + }) + + useRealSessionsHookRef.current = true + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ) + + try { + render( + , + { wrapper }, + ) + + await waitFor(() => { + expect(screen.getByText('beta session')).toBeTruthy() + }) + + await userEvent.setup().type(screen.getByPlaceholderText('Search sessions...'), 'beta') + + await waitFor(() => { + expect(resolveSearch).toBeDefined() + }) + + expect(screen.getByText('beta session')).toBeTruthy() + expect(screen.getByPlaceholderText('Search sessions...')).toBeTruthy() + expect(screen.queryByText('Loading sessions...')).toBeNull() + + resolveSearch?.(new Response(JSON.stringify({ + data: [{ id: 'ses_b', projectID: 'proj_1', title: 'beta session', time: { created: 2, updated: 2 }, location: { directory: '/w/a' } }], + cursor: {}, + }), { status: 200, headers: { 'Content-Type': 'application/json' } })) + + await waitFor(() => { + expect(screen.queryByText('alpha session')).toBeNull() + }) + expect(screen.getByText('beta session')).toBeTruthy() + } finally { + queryClient.clear() + vi.unstubAllGlobals() + } + }) + + it('shows the searching state while a search is pending and the empty state once it settles', async () => { + const user = userEvent.setup() + sessionsData.splice(0, sessionsData.length, + { id: 'ses_a', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 1 } }, + ) + + render( + , + ) + + await user.type(screen.getByPlaceholderText('Search sessions...'), 'zzz') + + expect(screen.getByText('Searching sessions...')).toBeTruthy() + expect(screen.queryByText('No sessions found')).toBeNull() + + await waitFor(() => { + expect(screen.getByText('No sessions found')).toBeTruthy() + }) + expect(screen.queryByText('Searching sessions...')).toBeNull() + }) + + it('does not paginate while placeholder data is shown', async () => { + const user = userEvent.setup() + isPlaceholderDataRef.current = true + hasNextPageRef.current = true + sessionsData.splice(0, sessionsData.length, + { id: 'ses_a', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 1 } }, + ) + + render( + , + ) + + const scrollContainer = screen.getByRole('region', { name: 'Sessions' }) + Object.defineProperty(scrollContainer, 'scrollHeight', { value: 1000, configurable: true }) + Object.defineProperty(scrollContainer, 'clientHeight', { value: 500, configurable: true }) + Object.defineProperty(scrollContainer, 'scrollTop', { value: 300, configurable: true }) + + await user.type(screen.getByPlaceholderText('Search sessions...'), 'zzz') + fireEvent.scroll(scrollContainer) + + expect(screen.getByText('Searching sessions...')).toBeTruthy() + + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(fetchNextPageMock).not.toHaveBeenCalled() + }) }) diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx index a1bebb2d..601ca4cf 100644 --- a/frontend/src/components/session/SessionList.tsx +++ b/frontend/src/components/session/SessionList.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState, useMemo, useEffect, useRef, type ReactNode } from "react"; +import { useCallback, useState, useMemo, useEffect, useRef, useId, type ReactNode } from "react"; import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode"; import type { DeleteSessionTarget } from "@/hooks/useOpenCode"; import type { Session } from "@/api/types"; @@ -11,6 +11,7 @@ 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"; interface SessionListProps { directory?: string; @@ -50,7 +51,10 @@ export const SessionList = ({ buildSessionKey(session.location.directory, session.id), []); const [searchQuery, setSearchQuery] = useState(""); - const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(directoriesList, { search: searchQuery, limit: 25 }); + 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 deleteSession = useDeleteSession(directoriesList); const createSession = useCreateSession(sessionCreateDirectory, (newSession) => { onSelectSession(newSession.id); @@ -67,16 +71,52 @@ export const SessionList = ({ const [manageMode, setManageMode] = useState(false); const sessionListRef = useRef(null); - const filteredSessions = useMemo( + 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); @@ -89,10 +129,10 @@ export const SessionList = ({ const handleSessionsScroll = useCallback((event: React.UIEvent) => { const { scrollTop, scrollHeight, clientHeight } = event.currentTarget; - if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage && !isFetchNextPageError) { + if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData) { void fetchNextPage(); } - }, [hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]); + }, [hasNextPage, isFetchingNextPage, isFetchNextPageError, isPlaceholderData, fetchNextPage]); useEffect(() => { const sessionList = sessionListRef.current; @@ -101,6 +141,7 @@ export const SessionList = ({ : filteredSessions.length === 0; if ( !isLoading + && !isPlaceholderData && isNearBottom && hasNextPage && !isFetchingNextPage @@ -108,44 +149,72 @@ export const SessionList = ({ ) { void fetchNextPage(); } - }, [isLoading, filteredSessions, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]); + }, [isLoading, isPlaceholderData, filteredSessions, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]); - if (isLoading && !renderSessions) { - return
Loading sessions...
; - } + 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]); - if (!sessions || sessions.length === 0) { - if (isFetchNextPageError) { - return ( -
-

Failed to load sessions.

- -
- ); + 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; } - if ((hasNextPage || isFetchingNextPage) && !renderSessions) { - return
Loading sessions...
; + + 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; } - if (!searchQuery.trim() && !renderSessions) { - return ( -
- createSession.mutate({ agent: undefined })} - > -
-

No sessions yet

-

- Click here to start a new session -

-
-
-
- ); - } - } + }; const getDeleteTarget = (session: Session): DeleteSessionTarget => ({ id: session.id, @@ -211,7 +280,7 @@ export const SessionList = ({ const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => { const key = getSessionSelectionKey(session); - return ( + const card = ( 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)) { + if (isFetchNextPageError) { + return ( +
+

Failed to load sessions.

+ +
+ ); + } + if ((hasNextPage || isFetchingNextPage) && !renderSessions) { + return
Loading sessions...
; + } + if (!searchQuery.trim() && !renderSessions) { + return ( +
+ createSession.mutate({ agent: undefined })} + > +
+

No sessions yet

+

+ Click here to start a new session +

+
+
+
+ ); + } + } + return (
@@ -266,9 +383,14 @@ export const SessionList = ({ placeholder="Search sessions..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} + onKeyDown={handleSearchKeyDown} 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} />
)} - {isFetchingNextPage && ( + {isFetchingNextPage && (sessions?.length ?? 0) > 0 && (
Loading more sessions...
diff --git a/frontend/src/hooks/useOpenCode.test.tsx b/frontend/src/hooks/useOpenCode.test.tsx index e5019ca6..b07be369 100644 --- a/frontend/src/hooks/useOpenCode.test.tsx +++ b/frontend/src/hooks/useOpenCode.test.tsx @@ -154,6 +154,83 @@ describe('useSessionsAcrossDirectories', () => { expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true) }) }) + + it('does not keep previous results across a search change unless requested', async () => { + let resolveSearch: ((value: { items: SessionInfo[] }) => void) | undefined + mocks.listSessionPage.mockImplementation(({ search }: { search?: string }) => { + if (search === 'deploy') { + return new Promise<{ items: SessionInfo[] }>((resolve) => { resolveSearch = resolve }) + } + return Promise.resolve({ items: [sessionInfo('ses_a1', '/w/a')] }) + }) + + const queryClient = createQueryClient() + const { result, rerender } = renderHook( + (props: { search?: string }) => useSessionsAcrossDirectories(['/w/a'], { search: props.search }), + { wrapper: createWrapper(queryClient), initialProps: { search: undefined as string | undefined } }, + ) + + await waitFor(() => { + expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1']) + }) + + rerender({ search: 'deploy' }) + + await waitFor(() => expect(resolveSearch).toBeDefined()) + + expect(result.current.isPlaceholderData).toBe(false) + expect(result.current.isLoading).toBe(true) + expect(result.current.data).toHaveLength(0) + + await act(async () => { + resolveSearch?.({ items: [sessionInfo('ses_b1', '/w/a')] }) + }) + + await waitFor(() => { + expect(result.current.data.map((session) => session.id)).toEqual(['ses_b1']) + }) + }) + + it('keeps previous results across a search change when requested', async () => { + let resolveSearch: ((value: { items: SessionInfo[] }) => void) | undefined + mocks.listSessionPage.mockImplementation(({ search }: { search?: string }) => { + if (search === 'deploy') { + return new Promise<{ items: SessionInfo[] }>((resolve) => { resolveSearch = resolve }) + } + return Promise.resolve({ items: [sessionInfo('ses_a1', '/w/a')] }) + }) + + const queryClient = createQueryClient() + const { result, rerender } = renderHook( + (props: { search?: string; keepPreviousResults?: boolean }) => + useSessionsAcrossDirectories(['/w/a'], { + search: props.search, + keepPreviousResults: props.keepPreviousResults, + }), + { + wrapper: createWrapper(queryClient), + initialProps: { search: undefined as string | undefined, keepPreviousResults: true }, + }, + ) + + await waitFor(() => { + expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1']) + }) + + rerender({ search: 'deploy', keepPreviousResults: true }) + + await waitFor(() => expect(result.current.isPlaceholderData).toBe(true)) + expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1']) + + await act(async () => { + resolveSearch?.({ items: [sessionInfo('ses_b1', '/w/a')] }) + }) + + await waitFor(() => { + expect(result.current.data.map((session) => session.id)).toEqual(['ses_b1']) + }) + expect(result.current.isPlaceholderData).toBe(false) + }) }) describe('useSession', () => { diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 3b5ec6b9..611108a6 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -41,6 +41,7 @@ const EMPTY_SESSIONS: SessionInfo[] = [] interface UseSessionsAcrossDirectoriesOptions { search?: string limit?: number + keepPreviousResults?: boolean } type SessionPageParam = Record @@ -55,6 +56,7 @@ export const useSessionsAcrossDirectories = ( ); const normalizedSearch = options?.search?.trim() || undefined; const limit = options?.limit ?? SESSION_LIST_PAGE_SIZE; + const keepPreviousResults = options?.keepPreviousResults ?? false; const directoryKey = uniqueDirectories.join('|'); const query = useInfiniteQuery({ @@ -97,6 +99,10 @@ export const useSessionsAcrossDirectories = ( return { items, cursors }; }, initialPageParam: undefined as SessionPageParam | undefined, + placeholderData: keepPreviousResults + ? (previousData, previousQuery) => + previousQuery?.queryKey[2] === directoryKey ? previousData : undefined + : undefined, getNextPageParam: (lastPage) => { if (Object.keys(lastPage.cursors).length > 0) { return lastPage.cursors; @@ -117,6 +123,7 @@ export const useSessionsAcrossDirectories = ( return { data, isLoading: query.isLoading, + isPlaceholderData: query.isPlaceholderData, isError: query.isError, fetchNextPage: query.fetchNextPage, hasNextPage: query.hasNextPage, diff --git a/frontend/src/lib/overlayFocus.test.ts b/frontend/src/lib/overlayFocus.test.ts index 792f8897..91834d26 100644 --- a/frontend/src/lib/overlayFocus.test.ts +++ b/frontend/src/lib/overlayFocus.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, afterEach } from 'vitest' import { stubMatchMedia } from '@/test/test-utils' -import { getFocusedElement, hasOpenOverlay, restoreOverlayFocus } from './overlayFocus' +import { getFocusedElement, hasOpenOverlay, isFinePointer, restoreOverlayFocus } from './overlayFocus' import { PROMPT_INPUT_SELECTOR, isPromptInput, isTextEntryElement } from './domTargets' function createElement( @@ -26,6 +26,16 @@ describe('getFocusedElement', () => { }) }) +describe('isFinePointer', () => { + it('reflects the fine pointer media query', () => { + stubMatchMedia(true) + expect(isFinePointer()).toBe(true) + + stubMatchMedia(false) + expect(isFinePointer()).toBe(false) + }) +}) + describe('restoreOverlayFocus', () => { it('focuses the chat prompt on desktop when focus was on a button', () => { stubMatchMedia(true) diff --git a/frontend/src/lib/overlayFocus.ts b/frontend/src/lib/overlayFocus.ts index a41da3cf..fa8b08d2 100644 --- a/frontend/src/lib/overlayFocus.ts +++ b/frontend/src/lib/overlayFocus.ts @@ -12,7 +12,10 @@ export function getFocusedElement(): HTMLElement | null { : null } -function isFinePointer(): boolean { +/** + * Reports whether the current device uses a fine pointer, such as a mouse or trackpad. + */ +export function isFinePointer(): boolean { return ( typeof window !== 'undefined' && typeof window.matchMedia === 'function' && diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index a68024f5..c0d248cb 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -10,6 +10,7 @@ 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 { FetchError } from '@/api/fetchWrapper' import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; @@ -829,9 +830,17 @@ export function SessionDetail() { {/* Sessions Dialog */} - + { + if (!isFinePointer()) { + event.preventDefault(); + (event.currentTarget as HTMLElement).focus(); + } + }} + > Sessions -
+
{sessionDirectory && (