mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(sessions): address PR #403 review findings
- fetch picker sessions only while the dialog is open - list all-projects sessions with one request per page - block infinite-scroll paging while a search is pending - memoize picker rows with stable callbacks - remove deleted sessions from list caches instead of refetching - keep the repo tab when the open session is deleted - reuse useSessionSearch in the sidebar session tree - drop dead activeSessionID/isActive and share delete, session-key and repo-map helpers - move usePersistentBoolean to its own hook
This commit is contained in:
1 parent
85288d6393
commit
2d14972fad
24 files changed
+814
-412
No files matched your search
@@ -34,6 +34,7 @@ const {
|
||||
getSessionMock,
|
||||
sessionPinsData,
|
||||
sessionsHasNextPage,
|
||||
searchError,
|
||||
} = vi.hoisted(() => ({
|
||||
listReposMock: vi.fn(),
|
||||
sessionsData: [] as SessionFixture[],
|
||||
@@ -45,6 +46,7 @@ const {
|
||||
getSessionMock: vi.fn(),
|
||||
sessionPinsData: { current: [] as SessionPinFixture[] },
|
||||
sessionsHasNextPage: { current: false },
|
||||
searchError: { current: false },
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', async (importOriginal) => {
|
||||
@@ -62,12 +64,17 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number }) => {
|
||||
sessionsHookCalls.push({ directories, options })
|
||||
if (directories.length > 0) sessionsHookCalls.push({ directories, options })
|
||||
const data =
|
||||
options?.search && emptyOnSearch.current
|
||||
? []
|
||||
: sessionsData.filter((session) => directories.includes(session.location.directory))
|
||||
return { data, isLoading: false, isError: false, hasNextPage: sessionsHasNextPage.current }
|
||||
return {
|
||||
data,
|
||||
isLoading: false,
|
||||
isError: Boolean(options?.search) && searchError.current,
|
||||
hasNextPage: sessionsHasNextPage.current,
|
||||
}
|
||||
},
|
||||
useCreateSession: (directory?: string) => ({
|
||||
mutate: (vars?: unknown) => {
|
||||
@@ -161,6 +168,7 @@ describe('DesktopSessionTree', () => {
|
||||
getSessionMock.mockResolvedValue(undefined)
|
||||
sessionPinsData.current = []
|
||||
sessionsHasNextPage.current = false
|
||||
searchError.current = false
|
||||
})
|
||||
|
||||
it('lists every repo by last access, even inside a repo, with no Recent section', async () => {
|
||||
@@ -302,6 +310,9 @@ describe('DesktopSessionTree', () => {
|
||||
await user.type(input, 'Session')
|
||||
|
||||
expect(await screen.findByRole('button', { name: /^Session a1/ })).toBeTruthy()
|
||||
await waitFor(() =>
|
||||
expect(sessionsHookCalls.some((call) => call.options?.search === 'Session')).toBe(true),
|
||||
)
|
||||
const searchCall = sessionsHookCalls.find((call) => call.options?.search === 'Session')
|
||||
expect(searchCall?.directories).toEqual(['/repos/a', '/repos/b'])
|
||||
expect(sessionsHookCalls.some((call) => call.options?.search === 'Sess')).toBe(false)
|
||||
@@ -315,6 +326,19 @@ describe('DesktopSessionTree', () => {
|
||||
expect(toggleFor('Alpha')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('filters loaded sessions by title immediately', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
|
||||
|
||||
const input = await screen.findByLabelText('Search sessions')
|
||||
await screen.findByText('Alpha')
|
||||
await user.type(input, 'a1')
|
||||
|
||||
expect(await screen.findByRole('button', { name: /^Session a1/ })).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: /^Session b1/ })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: /^Session c1/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('clears an active search with the clear button', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
|
||||
@@ -340,6 +364,7 @@ describe('DesktopSessionTree', () => {
|
||||
|
||||
expect(await screen.findByRole('button', { name: /^Session b1/ })).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: /^Session a1/ })).toBeNull()
|
||||
await waitFor(() => expect(sessionsHookCalls.some((call) => call.options?.search === 'bet')).toBe(true))
|
||||
const searchCall = sessionsHookCalls.find((call) => call.options?.search === 'bet')
|
||||
expect(searchCall?.directories).toEqual(['/repos/c', '/repos/a'])
|
||||
})
|
||||
@@ -369,6 +394,17 @@ describe('DesktopSessionTree', () => {
|
||||
expect(await screen.findByText('No sessions found')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows the error state when the session search fails', async () => {
|
||||
const user = userEvent.setup()
|
||||
searchError.current = true
|
||||
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
|
||||
|
||||
const input = await screen.findByLabelText('Search sessions')
|
||||
await user.type(input, 'Session')
|
||||
|
||||
expect(await screen.findByText('Failed to load sessions')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('creates a session in the repo full path', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { Search } from 'lucide-react'
|
||||
import type { Repo } from '@/api/types'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useNavigableRepos, useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups'
|
||||
import { useSessionSearch } from '@/hooks/useSessionSearch'
|
||||
import { useSessionPins } from '@/hooks/useSessionPins'
|
||||
import {
|
||||
NewSessionButton,
|
||||
RepoNavGroup,
|
||||
@@ -12,12 +14,16 @@ import {
|
||||
SessionNavRow,
|
||||
SessionNavStatus,
|
||||
} from '@/components/navigation/RepoSessionNav'
|
||||
import { getActiveRepoId, isCurrentSessionItem, isRepoReady } from '@/components/navigation/sidebar-session-tree'
|
||||
import {
|
||||
SIDEBAR_SESSIONS_PER_REPO,
|
||||
buildSidebarRepoGroups,
|
||||
getActiveRepoId,
|
||||
isCurrentSessionItem,
|
||||
isRepoReady,
|
||||
} from '@/components/navigation/sidebar-session-tree'
|
||||
import { getRepoPath } from '@/lib/navigation'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
|
||||
|
||||
const SESSION_SEARCH_DEBOUNCE_MS = 300
|
||||
import { buildPinnedSessionKeys } from '@/lib/sessionKey'
|
||||
|
||||
function SessionSearchInput({ value, onChange }: { value: string; onChange: (value: string) => void }) {
|
||||
const clear = () => onChange('')
|
||||
@@ -46,29 +52,37 @@ function SessionSearchInput({ value, onChange }: { value: string; onChange: (val
|
||||
)
|
||||
}
|
||||
|
||||
function SessionSearchResults({ repos, search }: { repos: Repo[]; search: string }) {
|
||||
interface SessionSearchResultsProps {
|
||||
nameMatchedRepos: Repo[]
|
||||
otherRepos: Repo[]
|
||||
sessions: Session[]
|
||||
isSearchLoading: boolean
|
||||
isSearchError: boolean
|
||||
}
|
||||
|
||||
function SessionSearchResults({
|
||||
nameMatchedRepos,
|
||||
otherRepos,
|
||||
sessions,
|
||||
isSearchLoading,
|
||||
isSearchError,
|
||||
}: SessionSearchResultsProps) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { nameMatchedRepos, otherRepos } = useMemo(() => {
|
||||
const query = search.toLowerCase()
|
||||
const readyRepos = repos.filter(isRepoReady)
|
||||
const isNameMatch = (repo: Repo) => getRepoDisplayName(repo).toLowerCase().includes(query)
|
||||
return {
|
||||
nameMatchedRepos: readyRepos.filter(isNameMatch),
|
||||
otherRepos: readyRepos.filter((repo) => !isNameMatch(repo)),
|
||||
}
|
||||
}, [repos, search])
|
||||
const nameMatches = useSidebarRepoGroups({ repos: nameMatchedRepos })
|
||||
const sessionMatches = useSidebarRepoGroups({ repos: otherRepos, search })
|
||||
const isLoading = nameMatches.isLoading || sessionMatches.isLoading
|
||||
const isError = nameMatches.isError || sessionMatches.isError
|
||||
const { data: sessionPins } = useSessionPins()
|
||||
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
|
||||
const sessionGroups = useMemo(
|
||||
() => buildSidebarRepoGroups({ repos: otherRepos, sessions, pinnedKeys, now: Date.now() }),
|
||||
[otherRepos, sessions, pinnedKeys],
|
||||
)
|
||||
const matchingGroups = [
|
||||
...nameMatches.groups,
|
||||
...sessionMatches.groups.filter((group) => group.items.length > 0),
|
||||
...sessionGroups.filter((group) => group.items.length > 0),
|
||||
]
|
||||
|
||||
if (isLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
|
||||
if (isError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
|
||||
if (nameMatches.isLoading || isSearchLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
|
||||
if (nameMatches.isError || isSearchError) return <SessionNavStatus>Failed to load sessions</SessionNavStatus>
|
||||
if (matchingGroups.length === 0) return <SessionNavStatus>No sessions found</SessionNavStatus>
|
||||
|
||||
return (
|
||||
@@ -101,23 +115,53 @@ function SessionSearchResults({ repos, search }: { repos: Repo[]; search: string
|
||||
export function DesktopSessionTree() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { repos, isLoading } = useNavigableRepos()
|
||||
const readyRepos = useMemo(() => repos.filter(isRepoReady), [repos])
|
||||
|
||||
const [draft, setDraft] = useState('')
|
||||
const trimmedDraft = draft.trim()
|
||||
const debouncedSearch = useDebouncedValue(trimmedDraft, SESSION_SEARCH_DEBOUNCE_MS)
|
||||
const search = trimmedDraft ? debouncedSearch : ''
|
||||
const { repos, isLoading } = useNavigableRepos()
|
||||
|
||||
const { nameMatchedRepos, otherRepos } = useMemo(() => {
|
||||
const query = trimmedDraft.toLowerCase()
|
||||
const isNameMatch = (repo: Repo) => getRepoDisplayName(repo).toLowerCase().includes(query)
|
||||
return {
|
||||
nameMatchedRepos: readyRepos.filter(isNameMatch),
|
||||
otherRepos: readyRepos.filter((repo) => !isNameMatch(repo)),
|
||||
}
|
||||
}, [readyRepos, trimmedDraft])
|
||||
|
||||
const otherDirectories = useMemo(() => otherRepos.map((repo) => repo.fullPath), [otherRepos])
|
||||
const searchDirectories = useMemo(
|
||||
() => (trimmedDraft ? otherDirectories : []),
|
||||
[trimmedDraft, otherDirectories],
|
||||
)
|
||||
const { setQuery, filteredSessions, isLoading: isSearchLoading, isError: isSearchError } = useSessionSearch(
|
||||
searchDirectories,
|
||||
{ limit: SIDEBAR_SESSIONS_PER_REPO },
|
||||
)
|
||||
|
||||
const handleSearchChange = (value: string) => {
|
||||
setDraft(value)
|
||||
setQuery(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="px-2 pb-2">
|
||||
<SessionSearchInput value={draft} onChange={setDraft} />
|
||||
<SessionSearchInput value={draft} onChange={handleSearchChange} />
|
||||
</div>
|
||||
|
||||
<div role="region" aria-label="Session navigator" className="min-h-0 flex-1 overflow-y-auto pb-2">
|
||||
{isLoading ? (
|
||||
<SessionNavStatus>Loading repos...</SessionNavStatus>
|
||||
) : search ? (
|
||||
<SessionSearchResults repos={repos} search={search} />
|
||||
) : trimmedDraft ? (
|
||||
<SessionSearchResults
|
||||
nameMatchedRepos={nameMatchedRepos}
|
||||
otherRepos={otherRepos}
|
||||
sessions={filteredSessions}
|
||||
isSearchLoading={isSearchLoading}
|
||||
isSearchError={isSearchError}
|
||||
/>
|
||||
) : (
|
||||
<RepoSessionNavList
|
||||
repos={repos}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import {
|
||||
buildRepoByDirectory,
|
||||
buildSidebarRepoGroups,
|
||||
getActiveRepoId,
|
||||
isCurrentSessionItem,
|
||||
@@ -112,6 +113,19 @@ describe('selectNavigableRepos', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRepoByDirectory', () => {
|
||||
it('indexes each repo by full path', () => {
|
||||
const repoA = createRepo({ id: 1, fullPath: '/repos/a' })
|
||||
const repoB = createRepo({ id: 2, fullPath: '/repos/b' })
|
||||
|
||||
const byDirectory = buildRepoByDirectory([repoA, repoB])
|
||||
|
||||
expect(byDirectory.get('/repos/a')).toBe(repoA)
|
||||
expect(byDirectory.get('/repos/b')).toBe(repoB)
|
||||
expect(byDirectory.size).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildSidebarRepoGroups', () => {
|
||||
const repoA = createRepo({ id: 1, fullPath: '/repos/a', name: 'Alpha' })
|
||||
const repoB = createRepo({ id: 2, fullPath: '/repos/b', name: 'Beta' })
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
|
||||
import { buildSessionKey } from '@/lib/sessionKey'
|
||||
import { getSessionKey } from '@/lib/sessionKey'
|
||||
import { getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
|
||||
import { partitionSessions, selectRootSessions } from '@/components/session/session-partition'
|
||||
|
||||
@@ -46,6 +46,10 @@ export function selectNavigableRepos(repos: Repo[]): Repo[] {
|
||||
)
|
||||
}
|
||||
|
||||
export function buildRepoByDirectory(repos: Repo[]): Map<string, Repo> {
|
||||
return new Map(repos.map((repo) => [repo.fullPath, repo]))
|
||||
}
|
||||
|
||||
export function buildSidebarRepoGroups(input: {
|
||||
repos: Repo[]
|
||||
sessions: Session[]
|
||||
@@ -53,8 +57,8 @@ export function buildSidebarRepoGroups(input: {
|
||||
now: number
|
||||
}): SidebarRepoGroup[] {
|
||||
const { repos, sessions, pinnedKeys, now } = input
|
||||
const keyFn = (session: Session) => buildSessionKey(session.location.directory, session.id)
|
||||
const repoByDirectory = new Map(repos.map((repo) => [repo.fullPath, repo]))
|
||||
const keyFn = getSessionKey
|
||||
const repoByDirectory = buildRepoByDirectory(repos)
|
||||
|
||||
const roots = selectRootSessions(sessions, {
|
||||
directories: new Set(repos.map((repo) => repo.fullPath)),
|
||||
|
||||
@@ -12,7 +12,6 @@ import { Button } from "@/components/ui/button";
|
||||
interface SessionCardProps {
|
||||
session: Session;
|
||||
isSelected: boolean;
|
||||
isActive: boolean;
|
||||
manageMode: boolean;
|
||||
isPinned?: boolean;
|
||||
onTogglePin?: () => void;
|
||||
@@ -24,7 +23,6 @@ interface SessionCardProps {
|
||||
export const SessionCard = ({
|
||||
session,
|
||||
isSelected,
|
||||
isActive,
|
||||
manageMode,
|
||||
isPinned,
|
||||
onTogglePin,
|
||||
@@ -71,9 +69,7 @@ export const SessionCard = ({
|
||||
} ${
|
||||
isSelected
|
||||
? "border-primary shadow-lg shadow-primary/30 bg-accent"
|
||||
: isActive
|
||||
? "bg-accent border-border"
|
||||
: "bg-card border-border hover:bg-accent hover:border-border"
|
||||
: "bg-card border-border hover:bg-accent hover:border-border"
|
||||
} hover:shadow-lg`}
|
||||
onClick={() => {
|
||||
if (!isOpen) {
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 { getSessionKey, buildPinnedSessionKeys } from '@/lib/sessionKey';
|
||||
import { partitionSessions } from './session-partition';
|
||||
import { DeleteSessionDialog } from "./DeleteSessionDialog";
|
||||
import { SessionCard } from "./SessionCard";
|
||||
@@ -17,7 +17,6 @@ interface SessionListProps {
|
||||
directory?: string;
|
||||
directories?: string[];
|
||||
createDirectory?: string;
|
||||
activeSessionID?: string;
|
||||
onSelectSession: (sessionID: string) => void;
|
||||
renderSessions?: (args: SessionListRenderArgs) => ReactNode;
|
||||
}
|
||||
@@ -36,7 +35,6 @@ export const SessionList = ({
|
||||
directory,
|
||||
directories,
|
||||
createDirectory,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
renderSessions,
|
||||
}: SessionListProps) => {
|
||||
@@ -46,9 +44,6 @@ export const SessionList = ({
|
||||
}, [directory, directories]);
|
||||
const primaryDirectory = directoriesList[0];
|
||||
const sessionCreateDirectory = createDirectory ?? primaryDirectory;
|
||||
const getSessionSelectionKey = useCallback((session: Session) =>
|
||||
buildSessionKey(session.location.directory, session.id),
|
||||
[]);
|
||||
const {
|
||||
query,
|
||||
setQuery,
|
||||
@@ -81,13 +76,13 @@ export const SessionList = ({
|
||||
const sessionListRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo(
|
||||
() => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey),
|
||||
[filteredSessions, pinnedKeys, getSessionSelectionKey],
|
||||
() => partitionSessions(filteredSessions, pinnedKeys, getSessionKey),
|
||||
[filteredSessions, pinnedKeys],
|
||||
);
|
||||
|
||||
const handleTogglePin = (session: Session) => {
|
||||
const directory = session.location.directory;
|
||||
const key = getSessionSelectionKey(session);
|
||||
const key = getSessionKey(session);
|
||||
togglePin.mutate({ sessionId: session.id, directory, pinned: !pinnedKeys.has(key) });
|
||||
};
|
||||
|
||||
@@ -141,7 +136,7 @@ export const SessionList = ({
|
||||
};
|
||||
|
||||
const toggleSessionSelection = (session: Session, selected: boolean) => {
|
||||
const selectionKey = getSessionSelectionKey(session);
|
||||
const selectionKey = getSessionKey(session);
|
||||
const newSelected = new Set(selectedSessions);
|
||||
if (selected) {
|
||||
newSelected.add(selectionKey);
|
||||
@@ -153,20 +148,20 @@ export const SessionList = ({
|
||||
|
||||
const allVisibleSelected =
|
||||
filteredSessions.length > 0 &&
|
||||
filteredSessions.every((session) => selectedSessions.has(getSessionSelectionKey(session)));
|
||||
filteredSessions.every((session) => selectedSessions.has(getSessionKey(session)));
|
||||
|
||||
const toggleSelectAll = () => {
|
||||
if (allVisibleSelected) {
|
||||
setSelectedSessions(new Set());
|
||||
} else {
|
||||
setSelectedSessions(new Set(filteredSessions.map(getSessionSelectionKey)));
|
||||
setSelectedSessions(new Set(filteredSessions.map(getSessionKey)));
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkDelete = () => {
|
||||
if (selectedSessions.size > 0) {
|
||||
const selectedTargets = filteredSessions
|
||||
.filter((session) => selectedSessions.has(getSessionSelectionKey(session)))
|
||||
.filter((session) => selectedSessions.has(getSessionKey(session)))
|
||||
.map(getDeleteTarget);
|
||||
if (selectedTargets.length === 0) return;
|
||||
setSessionToDelete(selectedTargets);
|
||||
@@ -175,13 +170,12 @@ export const SessionList = ({
|
||||
};
|
||||
|
||||
const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => {
|
||||
const key = getSessionSelectionKey(session);
|
||||
const key = getSessionKey(session);
|
||||
return (
|
||||
<SessionCard
|
||||
key={key}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(key)}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
isPinned={isPinned}
|
||||
onSelect={onSelectSession}
|
||||
@@ -298,7 +292,7 @@ export const SessionList = ({
|
||||
renderSessions({
|
||||
sessions: filteredSessions,
|
||||
searchQuery: query,
|
||||
renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionSelectionKey(session))),
|
||||
renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionKey(session))),
|
||||
})
|
||||
) : filteredSessions.length === 0 && !isFetchingNextPage ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useState } from 'react'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { SessionPickerDialog } from './SessionPickerDialog'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
sessionsData: [] as Session[],
|
||||
lastDirectories: [] as string[],
|
||||
lastAllDirectories: false,
|
||||
sessionsHook: vi.fn(),
|
||||
fetchNextPage: vi.fn(),
|
||||
deleteSessionMock: vi.fn(),
|
||||
togglePinMock: vi.fn(),
|
||||
@@ -19,8 +22,13 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string }) => {
|
||||
useSessionsAcrossDirectories: (
|
||||
directories: string[],
|
||||
options?: { search?: string; allDirectories?: boolean },
|
||||
) => {
|
||||
mocks.sessionsHook()
|
||||
mocks.lastDirectories = directories
|
||||
mocks.lastAllDirectories = options?.allDirectories ?? false
|
||||
const search = options?.search?.toLowerCase() ?? ''
|
||||
const data = search
|
||||
? mocks.sessionsData.filter((session) => (session.title ?? '').toLowerCase().includes(search))
|
||||
@@ -48,11 +56,6 @@ vi.mock('@/hooks/useSidebarRepoGroups', () => ({
|
||||
useNavigableRepos: () => ({ repos: mocks.repos, isLoading: false, refetch: vi.fn() }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/overlayFocus', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/overlayFocus')>()
|
||||
return { ...actual, isFinePointer: () => true }
|
||||
})
|
||||
|
||||
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
|
||||
return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
|
||||
@@ -104,6 +107,7 @@ const combobox = () => screen.getByRole('combobox')
|
||||
describe('SessionPickerDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
stubMatchMedia(true)
|
||||
localStorage.clear()
|
||||
mocks.deleteSessionMock.mockResolvedValue(undefined)
|
||||
mocks.sessionPins = []
|
||||
@@ -111,6 +115,10 @@ describe('SessionPickerDialog', () => {
|
||||
mocks.sessionsData = []
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
|
||||
it('opens with the active session as the cursor and marks it with a dot', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_active', 'Active session', '/w/a', 3000),
|
||||
@@ -185,12 +193,14 @@ describe('SessionPickerDialog', () => {
|
||||
renderPicker()
|
||||
|
||||
expect(mocks.lastDirectories).toEqual(['/w/a'])
|
||||
expect(mocks.lastAllDirectories).toBe(false)
|
||||
expect(screen.getByText('Alpha session')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Beta session')).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(combobox(), { key: 'a', ctrlKey: true })
|
||||
|
||||
expect(mocks.lastDirectories).toEqual(['/w/a', '/w/b'])
|
||||
expect(mocks.lastAllDirectories).toBe(true)
|
||||
expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('true')
|
||||
expect(screen.getByText('Beta session')).toBeInTheDocument()
|
||||
expect(screen.getByText('alpha')).toBeInTheDocument()
|
||||
@@ -198,9 +208,38 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
fireEvent.keyDown(combobox(), { key: 'a', ctrlKey: true })
|
||||
expect(mocks.lastDirectories).toEqual(['/w/a'])
|
||||
expect(mocks.lastAllDirectories).toBe(false)
|
||||
expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('false')
|
||||
})
|
||||
|
||||
it('does not query sessions while closed and queries after opening', async () => {
|
||||
mocks.sessionsData = [session('ses_1', 'First', '/w/a', 3000)]
|
||||
|
||||
function Host() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open-picker</button>
|
||||
<SessionPickerDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
currentRepo={mocks.repos[0]}
|
||||
onSelectSession={vi.fn()}
|
||||
onActiveSessionDeleted={vi.fn()}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(<Host />)
|
||||
|
||||
expect(mocks.sessionsHook).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByText('open-picker'))
|
||||
|
||||
await waitFor(() => expect(mocks.sessionsHook).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('deletes on a second Ctrl+D and clears the pending state on a move', async () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_1', 'First', '/w/a', 3000),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { memo, 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'
|
||||
@@ -14,15 +14,16 @@ 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 { buildRepoByDirectory } from '@/components/navigation/sidebar-session-tree'
|
||||
import { useDeleteSession } from '@/hooks/useOpenCode'
|
||||
import { useSessionSearch } from '@/hooks/useSessionSearch'
|
||||
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
|
||||
import { usePersistentBoolean } from '@/hooks/useSidebarCollapsed'
|
||||
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
|
||||
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
import { buildPinnedSessionKeys, buildSessionKey } from '@/lib/sessionKey'
|
||||
import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey'
|
||||
import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils'
|
||||
import { isFinePointer } from '@/lib/overlayFocus'
|
||||
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'
|
||||
@@ -109,21 +110,23 @@ function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isAct
|
||||
|
||||
interface SessionPickerRowItemProps {
|
||||
row: SessionPickerRow
|
||||
index: number
|
||||
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
|
||||
onOpen: (row: SessionPickerRow) => void
|
||||
onHover: (index: number) => void
|
||||
onTogglePin: (row: SessionPickerRow) => void
|
||||
onRequestDelete: (session: Session) => void
|
||||
registerRef: (key: string, node: HTMLDivElement | null) => void
|
||||
}
|
||||
|
||||
function SessionPickerRowItem({
|
||||
const SessionPickerRowItem = memo(function SessionPickerRowItem({
|
||||
row,
|
||||
index,
|
||||
optionId,
|
||||
isCursor,
|
||||
isActive,
|
||||
@@ -138,10 +141,10 @@ function SessionPickerRowItem({
|
||||
}: SessionPickerRowItemProps) {
|
||||
return (
|
||||
<div
|
||||
ref={registerRef}
|
||||
ref={(node) => registerRef(row.key, node)}
|
||||
role="presentation"
|
||||
onPointerMove={(event) => {
|
||||
if (event.pointerType === 'mouse') onHover()
|
||||
if (event.pointerType === 'mouse') onHover(index)
|
||||
}}
|
||||
className={cn(
|
||||
'group flex items-center rounded-md text-sm min-h-8 pointer-coarse:min-h-11',
|
||||
@@ -156,7 +159,7 @@ function SessionPickerRowItem({
|
||||
role="option"
|
||||
id={optionId}
|
||||
aria-selected={isCursor}
|
||||
onClick={onOpen}
|
||||
onClick={() => onOpen(row)}
|
||||
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2"
|
||||
>
|
||||
<span className="flex w-4 shrink-0 items-center justify-center">
|
||||
@@ -207,37 +210,46 @@ function SessionPickerRowItem({
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="z-[200]" onClick={(event) => event.stopPropagation()}>
|
||||
<DropdownMenuItem onClick={onTogglePin}>
|
||||
<DropdownMenuItem onClick={() => onTogglePin(row)}>
|
||||
{isPinned ? <PinOff className="h-4 w-4 mr-2" /> : <Pin className="h-4 w-4 mr-2" />}
|
||||
{isPinned ? 'Unpin' : 'Pin'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={onRequestDelete}>Delete</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => onRequestDelete(row.session)}>Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
interface SessionPickerContentProps {
|
||||
open: boolean
|
||||
currentRepo: Repo | undefined
|
||||
activeSessionID?: string
|
||||
onSelectSession: (session: Session, repo: Repo) => void
|
||||
onActiveSessionDeleted: () => void
|
||||
searchInputRef: React.RefObject<HTMLInputElement | null>
|
||||
hasFinePointer: boolean
|
||||
}
|
||||
|
||||
export function SessionPickerDialog({
|
||||
function SessionPickerContent({
|
||||
open,
|
||||
onOpenChange,
|
||||
currentRepo,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onActiveSessionDeleted,
|
||||
}: SessionPickerDialogProps) {
|
||||
searchInputRef,
|
||||
hasFinePointer,
|
||||
}: SessionPickerContentProps) {
|
||||
const [allProjects, toggleAllProjects] = usePersistentBoolean(ALL_PROJECTS_STORAGE_KEY, false)
|
||||
const { repos } = useNavigableRepos(open)
|
||||
const searchInputRef = useRef<HTMLInputElement>(null)
|
||||
const { repos } = useNavigableRepos()
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const rowRefs = useRef(new Map<string, HTMLDivElement>())
|
||||
const listId = useId()
|
||||
const optionBaseId = useId()
|
||||
|
||||
const repoByDirectory = useMemo(() => {
|
||||
const map = new Map<string, Repo>()
|
||||
for (const repo of repos) map.set(repo.fullPath, repo)
|
||||
const map = buildRepoByDirectory(repos)
|
||||
if (currentRepo) map.set(currentRepo.fullPath, currentRepo)
|
||||
return map
|
||||
}, [repos, currentRepo])
|
||||
@@ -260,12 +272,8 @@ export function SessionPickerDialog({
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
canFetchNextPage,
|
||||
} = useSessionSearch(directories)
|
||||
} = useSessionSearch(directories, { allDirectories: allProjects })
|
||||
|
||||
const keyFn = useCallback(
|
||||
(session: Session) => buildSessionKey(session.location.directory, session.id),
|
||||
[],
|
||||
)
|
||||
const resolveRepo = useCallback(
|
||||
(session: Session) => repoByDirectory.get(session.location.directory) ?? currentRepo,
|
||||
[repoByDirectory, currentRepo],
|
||||
@@ -281,8 +289,8 @@ export function SessionPickerDialog({
|
||||
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
|
||||
|
||||
const sections = useMemo(
|
||||
() => buildSections(filteredSessions, pinnedKeys, keyFn, resolveRepo),
|
||||
[filteredSessions, pinnedKeys, keyFn, resolveRepo],
|
||||
() => buildSections(filteredSessions, pinnedKeys, getSessionKey, resolveRepo),
|
||||
[filteredSessions, pinnedKeys, resolveRepo],
|
||||
)
|
||||
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
|
||||
const rowIndexByKey = useMemo(
|
||||
@@ -309,14 +317,6 @@ export function SessionPickerDialog({
|
||||
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)
|
||||
@@ -348,6 +348,17 @@ export function SessionPickerDialog({
|
||||
[onSelectSession],
|
||||
)
|
||||
|
||||
const performDelete = useCallback(
|
||||
(session: Session) =>
|
||||
deleteSession
|
||||
.mutateAsync({ id: session.id, directory: session.location.directory })
|
||||
.then(() => {
|
||||
if (session.id === activeSessionID) onActiveSessionDeleted()
|
||||
})
|
||||
.catch(() => undefined),
|
||||
[deleteSession, activeSessionID, onActiveSessionDeleted],
|
||||
)
|
||||
|
||||
const deleteRow = useCallback(
|
||||
(row: SessionPickerRow | undefined) => {
|
||||
if (!row) return
|
||||
@@ -355,17 +366,11 @@ export function SessionPickerDialog({
|
||||
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)
|
||||
})
|
||||
void performDelete(row.session).finally(() => {
|
||||
setPendingDeleteKey(null)
|
||||
})
|
||||
},
|
||||
[pendingDeleteKey, deleteSession, activeSessionID, onActiveSessionDeleted],
|
||||
[pendingDeleteKey, performDelete],
|
||||
)
|
||||
|
||||
const handleSearchKeyDown = useCallback(
|
||||
@@ -456,42 +461,170 @@ export function SessionPickerDialog({
|
||||
[togglePin, pinnedKeys],
|
||||
)
|
||||
|
||||
const handleRequestDelete = useCallback((session: Session) => {
|
||||
setSessionToDelete(session)
|
||||
}, [])
|
||||
|
||||
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])
|
||||
void performDelete(sessionToDelete).finally(() => {
|
||||
setSessionToDelete(null)
|
||||
})
|
||||
}, [sessionToDelete, performDelete])
|
||||
|
||||
const renderRow = (row: SessionPickerRow) => {
|
||||
const index = rowIndexByKey.get(row.key) ?? -1
|
||||
return (
|
||||
<SessionPickerRowItem
|
||||
key={row.key}
|
||||
row={row}
|
||||
optionId={optionId(optionBaseId, index)}
|
||||
isCursor={index === cursorIndex}
|
||||
isActive={row.session.id === activeSessionID}
|
||||
isPinned={pinnedKeys.has(row.key)}
|
||||
isPendingDelete={pendingDeleteKey === row.key}
|
||||
showRepo={allProjects}
|
||||
onOpen={() => openRow(row)}
|
||||
onHover={() => moveCursor(index)}
|
||||
onTogglePin={() => handleTogglePin(row)}
|
||||
onRequestDelete={() => setSessionToDelete(row.session)}
|
||||
registerRef={(node) => setRowRef(row.key, node)}
|
||||
return (
|
||||
<>
|
||||
<DialogTitle className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
|
||||
Sessions
|
||||
{!allProjects && currentRepo && (
|
||||
<span className="font-normal text-muted-foreground"> for {getRepoDisplayName(currentRepo)}</span>
|
||||
)}
|
||||
</DialogTitle>
|
||||
|
||||
<div className="mt-4 flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
ref={searchInputRef}
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-controls={listId}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={cursorIndex >= 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"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-pressed={allProjects}
|
||||
onClick={toggleAllProjects}
|
||||
className="h-9 shrink-0"
|
||||
>
|
||||
{allProjects ? 'All projects' : 'This project'}
|
||||
{hasFinePointer && (
|
||||
<kbd className="ml-1 rounded border border-border bg-muted px-1 text-[10px] text-muted-foreground">
|
||||
Ctrl+A
|
||||
</kbd>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={listRef}
|
||||
role="listbox"
|
||||
id={listId}
|
||||
aria-label="Sessions"
|
||||
onScroll={handleListScroll}
|
||||
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">
|
||||
{isLoading
|
||||
? 'Loading sessions...'
|
||||
: isSearchPending
|
||||
? 'Searching sessions...'
|
||||
: trimmedQuery
|
||||
? 'No sessions found'
|
||||
: 'No sessions yet'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{sections.map((section) => (
|
||||
<div
|
||||
key={section.id}
|
||||
role="group"
|
||||
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
|
||||
>
|
||||
<div
|
||||
id={`${optionBaseId}-heading-${section.id}`}
|
||||
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
|
||||
>
|
||||
{section.heading}
|
||||
</div>
|
||||
{section.rows.map((row) => {
|
||||
const index = rowIndexByKey.get(row.key) ?? -1
|
||||
return (
|
||||
<SessionPickerRowItem
|
||||
key={row.key}
|
||||
row={row}
|
||||
index={index}
|
||||
optionId={optionId(optionBaseId, index)}
|
||||
isCursor={index === cursorIndex}
|
||||
isActive={row.session.id === activeSessionID}
|
||||
isPinned={pinnedKeys.has(row.key)}
|
||||
isPendingDelete={pendingDeleteKey === row.key}
|
||||
showRepo={allProjects}
|
||||
onOpen={openRow}
|
||||
onHover={moveCursor}
|
||||
onTogglePin={handleTogglePin}
|
||||
onRequestDelete={handleRequestDelete}
|
||||
registerRef={setRowRef}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
{isFetchNextPageError && (
|
||||
<div className="flex flex-col items-center gap-2 py-4">
|
||||
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void fetchNextPage()
|
||||
}}
|
||||
disabled={isFetchingNextPage}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isFetchingNextPage && rows.length > 0 && (
|
||||
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
|
||||
↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteSessionDialog
|
||||
open={sessionToDelete !== null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setSessionToDelete(null)
|
||||
}}
|
||||
onConfirm={() => {
|
||||
void confirmDelete()
|
||||
}}
|
||||
onCancel={() => setSessionToDelete(null)}
|
||||
isDeleting={deleteSession.isPending}
|
||||
/>
|
||||
)
|
||||
}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function SessionPickerDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
currentRepo,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onActiveSessionDeleted,
|
||||
}: SessionPickerDialogProps) {
|
||||
const searchInputRef = useRef<HTMLInputElement>(null)
|
||||
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -501,129 +634,21 @@ export function SessionPickerDialog({
|
||||
onEscapeKeyDown={() => onOpenChange(false)}
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
if (isFinePointer()) {
|
||||
if (hasFinePointer) {
|
||||
searchInputRef.current?.focus()
|
||||
} else {
|
||||
;(event.currentTarget as HTMLElement).focus()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogTitle className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
|
||||
Sessions
|
||||
{!allProjects && currentRepo && (
|
||||
<span className="font-normal text-muted-foreground"> for {getRepoDisplayName(currentRepo)}</span>
|
||||
)}
|
||||
</DialogTitle>
|
||||
|
||||
<div className="mt-4 flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
ref={searchInputRef}
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-controls={listId}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={cursorIndex >= 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"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-pressed={allProjects}
|
||||
onClick={toggleAllProjects}
|
||||
className="h-9 shrink-0"
|
||||
>
|
||||
{allProjects ? 'All projects' : 'This project'}
|
||||
{isFinePointer() && (
|
||||
<kbd className="ml-1 rounded border border-border bg-muted px-1 text-[10px] text-muted-foreground">
|
||||
Ctrl+A
|
||||
</kbd>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={listRef}
|
||||
role="listbox"
|
||||
id={listId}
|
||||
aria-label="Sessions"
|
||||
onScroll={handleListScroll}
|
||||
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">
|
||||
{isLoading
|
||||
? 'Loading sessions...'
|
||||
: isSearchPending
|
||||
? 'Searching sessions...'
|
||||
: trimmedQuery
|
||||
? 'No sessions found'
|
||||
: 'No sessions yet'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{sections.map((section) => (
|
||||
<div
|
||||
key={section.id}
|
||||
role="group"
|
||||
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
|
||||
>
|
||||
<div
|
||||
id={`${optionBaseId}-heading-${section.id}`}
|
||||
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
|
||||
>
|
||||
{section.heading}
|
||||
</div>
|
||||
{section.rows.map(renderRow)}
|
||||
</div>
|
||||
))}
|
||||
{isFetchNextPageError && (
|
||||
<div className="flex flex-col items-center gap-2 py-4">
|
||||
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void fetchNextPage()
|
||||
}}
|
||||
disabled={isFetchingNextPage}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isFetchingNextPage && rows.length > 0 && (
|
||||
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
|
||||
↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteSessionDialog
|
||||
open={sessionToDelete !== null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setSessionToDelete(null)
|
||||
}}
|
||||
onConfirm={() => {
|
||||
void confirmDelete()
|
||||
}}
|
||||
onCancel={() => setSessionToDelete(null)}
|
||||
isDeleting={deleteSession.isPending}
|
||||
<SessionPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
activeSessionID={activeSessionID}
|
||||
onSelectSession={onSelectSession}
|
||||
onActiveSessionDeleted={onActiveSessionDeleted}
|
||||
searchInputRef={searchInputRef}
|
||||
hasFinePointer={hasFinePointer}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
Reference in new issue
Block a user