mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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
@@ -98,6 +98,32 @@ describe('OpenCode facade', () => {
|
||||
expect(page.nextCursor).toBeUndefined()
|
||||
})
|
||||
|
||||
it('omits the directory when listing sessions across all directories', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({ data: [sessionInfo('ses_1', '/repo')], cursor: { next: 'cursor_next' } }),
|
||||
)
|
||||
|
||||
const page = await listSessionPage({ limit: 25, order: 'desc' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?limit=25&order=desc&parentID=null',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
expect(page.items).toEqual([sessionInfo('ses_1', '/repo')])
|
||||
expect(page.nextCursor).toBe('cursor_next')
|
||||
})
|
||||
|
||||
it('omits the directory on an all-directories continuation page', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: [], cursor: {} }))
|
||||
|
||||
await listSessionPage({ cursor: 'cursor_1' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?parentID=null&cursor=cursor_1',
|
||||
)
|
||||
expect(lastRequest().init.method).toBe('GET')
|
||||
})
|
||||
|
||||
it('reads a single session from the V2 session route', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_1', '/repo') }))
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ export interface SessionPage {
|
||||
}
|
||||
|
||||
export interface SessionPageInput {
|
||||
directory: string
|
||||
directory?: string
|
||||
limit?: number
|
||||
order?: 'asc' | 'desc'
|
||||
search?: string
|
||||
@@ -93,7 +93,7 @@ function buildPromptFields(input: PromptFields) {
|
||||
export async function listSessionPage(input: SessionPageInput): Promise<SessionPage> {
|
||||
const { data, cursor } = await callOpenCode((api) =>
|
||||
api.session.list({
|
||||
directory: input.directory,
|
||||
...(input.directory === undefined ? {} : { directory: input.directory }),
|
||||
parentID: 'null',
|
||||
limit: input.limit,
|
||||
order: input.order,
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -134,12 +134,58 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('deletes each session through the facade and invalidates the session list cache', async () => {
|
||||
it('issues one call per page across all directories and paginates by cursor', async () => {
|
||||
mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
|
||||
if (cursor === 'cursor_all') {
|
||||
return { items: [sessionInfo('ses_all2', '/w/b', 2000)] }
|
||||
}
|
||||
return { items: [sessionInfo('ses_all1', '/w/a')], nextCursor: 'cursor_all' }
|
||||
})
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(
|
||||
() => useSessionsAcrossDirectories(['/w/a', '/w/b'], { allDirectories: true }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
})
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1'])
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.fetchNextPage()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data).toHaveLength(2)
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
|
||||
expect(mocks.listSessionPage).toHaveBeenLastCalledWith({ cursor: 'cursor_all' })
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
|
||||
})
|
||||
|
||||
it('deletes each session through the facade and removes it from cached lists without invalidating', async () => {
|
||||
mocks.deleteSession.mockResolvedValue(undefined)
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25 }]
|
||||
queryClient.setQueryData(listKey, { pages: [{ items: [], cursors: {} }], pageParams: [undefined] })
|
||||
const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25, allDirectories: false }]
|
||||
queryClient.setQueryData(listKey, {
|
||||
pages: [{
|
||||
items: [sessionInfo('ses_a1', '/w/a'), sessionInfo('ses_a2', '/w/a')],
|
||||
nextParam: undefined,
|
||||
}],
|
||||
pageParams: [undefined],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useDeleteSession(['/w/a']), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
@@ -150,6 +196,31 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
})
|
||||
|
||||
expect(mocks.deleteSession).toHaveBeenCalledWith('ses_a1')
|
||||
const cached = queryClient.getQueryData<{ pages: Array<{ items: SessionInfo[] }> }>(listKey)
|
||||
expect(cached?.pages[0].items.map((session) => session.id)).toEqual(['ses_a2'])
|
||||
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(false)
|
||||
})
|
||||
|
||||
it('invalidates the session list cache when a delete fails', async () => {
|
||||
mocks.deleteSession.mockRejectedValue(new Error('nope'))
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25, allDirectories: false }]
|
||||
queryClient.setQueryData(listKey, {
|
||||
pages: [{ items: [sessionInfo('ses_a1', '/w/a')], nextParam: undefined }],
|
||||
pageParams: [undefined],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useDeleteSession(['/w/a']), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.mutateAsync({ id: 'ses_a1', directory: '/w/a' }),
|
||||
).rejects.toThrow('Failed to delete 1 session(s)')
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true)
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery, type InfiniteData } from "@tanstack/react-query";
|
||||
import { useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import {
|
||||
createSession,
|
||||
@@ -42,9 +42,19 @@ interface UseSessionsAcrossDirectoriesOptions {
|
||||
search?: string
|
||||
limit?: number
|
||||
keepPreviousResults?: boolean
|
||||
allDirectories?: boolean
|
||||
}
|
||||
|
||||
type SessionPageParam = Record<string, string>
|
||||
type SessionDirectoryCursors = Record<string, string>
|
||||
|
||||
type SessionListPageParam =
|
||||
| { mode: 'directories'; cursors: SessionDirectoryCursors }
|
||||
| { mode: 'all'; cursor: string }
|
||||
|
||||
interface SessionListPage {
|
||||
items: SessionInfo[]
|
||||
nextParam?: SessionListPageParam
|
||||
}
|
||||
|
||||
export const useSessionsAcrossDirectories = (
|
||||
directories: string[],
|
||||
@@ -57,12 +67,32 @@ export const useSessionsAcrossDirectories = (
|
||||
const normalizedSearch = options?.search?.trim() || undefined;
|
||||
const limit = options?.limit ?? SESSION_LIST_PAGE_SIZE;
|
||||
const keepPreviousResults = options?.keepPreviousResults ?? false;
|
||||
const allDirectories = options?.allDirectories ?? false;
|
||||
const directoryKey = uniqueDirectories.join('|');
|
||||
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit }],
|
||||
const query = useInfiniteQuery<
|
||||
SessionListPage,
|
||||
Error,
|
||||
InfiniteData<SessionListPage, SessionListPageParam | undefined>,
|
||||
readonly unknown[],
|
||||
SessionListPageParam | undefined
|
||||
>({
|
||||
queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit, allDirectories }],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (!pageParam) {
|
||||
if (allDirectories) {
|
||||
const cursor = pageParam?.mode === 'all' ? pageParam.cursor : undefined;
|
||||
const page = await listSessionPage(
|
||||
cursor === undefined
|
||||
? { limit, order: 'desc', search: normalizedSearch }
|
||||
: { cursor },
|
||||
);
|
||||
return {
|
||||
items: page.items,
|
||||
nextParam: page.nextCursor ? { mode: 'all', cursor: page.nextCursor } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (!pageParam || pageParam.mode !== 'directories') {
|
||||
const pages = await Promise.all(
|
||||
uniqueDirectories.map((directory) =>
|
||||
listSessionPage({
|
||||
@@ -73,7 +103,7 @@ export const useSessionsAcrossDirectories = (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const cursors: SessionPageParam = {};
|
||||
const cursors: SessionDirectoryCursors = {};
|
||||
const items: SessionInfo[] = [];
|
||||
for (let i = 0; i < pages.length; i++) {
|
||||
items.push(...pages[i].items);
|
||||
@@ -81,14 +111,17 @@ export const useSessionsAcrossDirectories = (
|
||||
cursors[uniqueDirectories[i]] = pages[i].nextCursor!;
|
||||
}
|
||||
}
|
||||
return { items, cursors };
|
||||
return {
|
||||
items,
|
||||
nextParam: Object.keys(cursors).length > 0 ? { mode: 'directories', cursors } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const entries = Object.entries(pageParam);
|
||||
const entries = Object.entries(pageParam.cursors);
|
||||
const pages = await Promise.all(
|
||||
entries.map(([directory, cursor]) => listSessionPage({ directory, cursor })),
|
||||
);
|
||||
const cursors: SessionPageParam = {};
|
||||
const cursors: SessionDirectoryCursors = {};
|
||||
const items: SessionInfo[] = [];
|
||||
for (let i = 0; i < pages.length; i++) {
|
||||
items.push(...pages[i].items);
|
||||
@@ -96,19 +129,17 @@ export const useSessionsAcrossDirectories = (
|
||||
cursors[entries[i][0]] = pages[i].nextCursor!;
|
||||
}
|
||||
}
|
||||
return { items, cursors };
|
||||
return {
|
||||
items,
|
||||
nextParam: Object.keys(cursors).length > 0 ? { mode: 'directories', cursors } : undefined,
|
||||
};
|
||||
},
|
||||
initialPageParam: undefined as SessionPageParam | undefined,
|
||||
initialPageParam: undefined as SessionListPageParam | undefined,
|
||||
placeholderData: keepPreviousResults
|
||||
? (previousData, previousQuery) =>
|
||||
previousQuery?.queryKey[2] === directoryKey ? previousData : undefined
|
||||
: undefined,
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (Object.keys(lastPage.cursors).length > 0) {
|
||||
return lastPage.cursors;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
getNextPageParam: (lastPage) => lastPage.nextParam,
|
||||
enabled: uniqueDirectories.length > 0,
|
||||
staleTime: 10000,
|
||||
refetchOnWindowFocus: true,
|
||||
@@ -252,19 +283,43 @@ export const useDeleteSession = (directory?: string | string[]) => {
|
||||
|
||||
return { deleted: targets.length, results }
|
||||
},
|
||||
onSuccess: ({ deleted }) => {
|
||||
onSuccess: ({ deleted }, variables) => {
|
||||
removeDeletedSessionsFromListCaches(queryClient, variables);
|
||||
cleanupSessionPins(queryClient, variables, primaryDirectory);
|
||||
showToast.success(deleted === 1 ? 'Session deleted' : `${deleted} sessions deleted`);
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to delete sessions');
|
||||
},
|
||||
onSettled: (_data, _error, variables) => {
|
||||
onError: (_error, variables) => {
|
||||
invalidateSessionListCaches(queryClient);
|
||||
cleanupSessionPins(queryClient, variables, primaryDirectory);
|
||||
showToast.error('Failed to delete sessions');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const removeDeletedSessionsFromListCaches = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
) => {
|
||||
const deletedIDs = new Set(
|
||||
(Array.isArray(variables) ? variables : [variables]).map(getDeleteSessionTargetId),
|
||||
);
|
||||
if (deletedIDs.size === 0) return;
|
||||
queryClient.setQueriesData<InfiniteData<SessionListPage, SessionListPageParam | undefined>>(
|
||||
{ queryKey: ['opencode', 'sessions'] },
|
||||
(current) => {
|
||||
if (!current) return current;
|
||||
let changed = false;
|
||||
const pages = current.pages.map((page) => {
|
||||
const items = page.items.filter((item) => !deletedIDs.has(item.id));
|
||||
if (items.length === page.items.length) return page;
|
||||
changed = true;
|
||||
return { ...page, items };
|
||||
});
|
||||
return changed ? { ...current, pages } : current;
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const cleanupSessionPins = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { usePersistentBoolean } from './usePersistentBoolean'
|
||||
|
||||
const STORAGE_KEY = 'oc:test:flag'
|
||||
|
||||
const localStorageMock = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
}
|
||||
|
||||
describe('usePersistentBoolean', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
writable: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: window.localStorage,
|
||||
writable: true,
|
||||
})
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('returns the fallback when no stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(localStorageMock.getItem).toHaveBeenCalledWith(STORAGE_KEY)
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns a stored true value', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('toggles the value and persists it to localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1]()
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith(STORAGE_KEY, 'true')
|
||||
})
|
||||
|
||||
it('returns the fallback when the stored value is malformed JSON', () => {
|
||||
localStorageMock.getItem.mockReturnValue('not-json{{')
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns the fallback when the stored value is JSON but not a boolean', () => {
|
||||
localStorageMock.getItem.mockReturnValue('"some string"')
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('honours a true fallback when no value is stored', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, true))
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
function readStorage(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStorage(key: string, value: unknown): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function readStoredBoolean(key: string, fallback: boolean): boolean {
|
||||
const stored = readStorage(key)
|
||||
if (stored === null) {
|
||||
return fallback
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(stored)
|
||||
return typeof parsed === 'boolean' ? parsed : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(() => {
|
||||
setValue((prev: boolean) => {
|
||||
const newValue = !prev
|
||||
writeStorage(key, newValue)
|
||||
return newValue
|
||||
})
|
||||
}, [key])
|
||||
|
||||
return [value, toggle]
|
||||
}
|
||||
@@ -4,15 +4,15 @@ 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 } },
|
||||
lastArgsRef: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean } } | undefined },
|
||||
flagsRef: { current: { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false } },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean }) => {
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean }) => {
|
||||
lastArgsRef.current = { directories, options }
|
||||
const search = options?.search?.toLowerCase() ?? ''
|
||||
const data = search
|
||||
@@ -21,6 +21,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
return {
|
||||
data,
|
||||
isLoading: false,
|
||||
isError: flagsRef.current.isError,
|
||||
isPlaceholderData: flagsRef.current.isPlaceholderData,
|
||||
fetchNextPage: vi.fn(),
|
||||
hasNextPage: flagsRef.current.hasNextPage,
|
||||
@@ -38,7 +39,7 @@ describe('useSessionSearch', () => {
|
||||
{ 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 }
|
||||
flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -89,23 +90,59 @@ describe('useSessionSearch', () => {
|
||||
expect(result.current.isSearchPending).toBe(false)
|
||||
})
|
||||
|
||||
it('passes allDirectories through to useSessionsAcrossDirectories', () => {
|
||||
renderHook(() => useSessionSearch(['/w/a'], { allDirectories: true }))
|
||||
|
||||
expect(lastArgsRef.current?.options?.allDirectories).toBe(true)
|
||||
})
|
||||
|
||||
it('passes isError through from useSessionsAcrossDirectories', () => {
|
||||
flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: true }
|
||||
|
||||
const { result } = renderHook(() => useSessionSearch(['/w/a']))
|
||||
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks pagination while a search is pending', () => {
|
||||
vi.useFakeTimers()
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
const { result } = renderHook(() => useSessionSearch(['/w/a']))
|
||||
|
||||
expect(result.current.canFetchNextPage).toBe(true)
|
||||
|
||||
act(() => {
|
||||
result.current.setQuery('deploy')
|
||||
})
|
||||
|
||||
expect(result.current.isSearchPending).toBe(true)
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(150)
|
||||
})
|
||||
|
||||
expect(result.current.isSearchPending).toBe(false)
|
||||
expect(result.current.canFetchNextPage).toBe(true)
|
||||
})
|
||||
|
||||
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 }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(true)
|
||||
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: true, isFetchNextPageError: false, isPlaceholderData: false }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: true, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: true, isPlaceholderData: false }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: true, isPlaceholderData: false, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: true }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: true, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
})
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { 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'
|
||||
import { getSessionKey } from '@/lib/sessionKey'
|
||||
|
||||
const DEFAULT_LIMIT = 25
|
||||
|
||||
export interface UseSessionSearchOptions {
|
||||
limit?: number
|
||||
allDirectories?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -17,6 +17,7 @@ export interface UseSessionSearchOptions {
|
||||
*/
|
||||
export function useSessionSearch(directories: string[], options: UseSessionSearchOptions = {}) {
|
||||
const limit = options.limit ?? DEFAULT_LIMIT
|
||||
const allDirectories = options.allDirectories ?? false
|
||||
const [query, setQuery] = useState('')
|
||||
const trimmedQuery = query.trim()
|
||||
const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
|
||||
@@ -24,22 +25,19 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
|
||||
const {
|
||||
data: sessions,
|
||||
isLoading,
|
||||
isError,
|
||||
isPlaceholderData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
} = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true })
|
||||
} = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true, allDirectories })
|
||||
|
||||
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],
|
||||
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionKey }),
|
||||
[sessions, directorySet],
|
||||
)
|
||||
|
||||
const filteredSessions = useMemo(() => {
|
||||
@@ -50,7 +48,7 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
|
||||
|
||||
const isSearchPending = trimmedQuery !== search || isPlaceholderData
|
||||
const canFetchNextPage = Boolean(
|
||||
hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData,
|
||||
hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isSearchPending,
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -61,6 +59,7 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
|
||||
filteredSessions,
|
||||
isSearchPending,
|
||||
isLoading,
|
||||
isError,
|
||||
isPlaceholderData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
|
||||
@@ -9,7 +9,7 @@ const localStorageMock = {
|
||||
clear: vi.fn(),
|
||||
}
|
||||
|
||||
describe('sidebar collapse hooks', () => {
|
||||
describe('useSidebarCollapsed', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
@@ -26,52 +26,27 @@ describe('sidebar collapse hooks', () => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('useSidebarCollapsed', () => {
|
||||
it('returns false by default when no stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
it('reads and persists under the sidebar storage key with a false default', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
expect(localStorageMock.getItem).toHaveBeenCalledWith('oc:sidebar:collapsed')
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1]()
|
||||
})
|
||||
|
||||
it('returns stored value from localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
it('returns the stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
it('toggles collapsed state and persists to localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1]()
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
|
||||
})
|
||||
|
||||
it('returns false when stored value is malformed JSON', () => {
|
||||
localStorageMock.getItem.mockReturnValue('not-json{{')
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when stored value is JSON but not a boolean', () => {
|
||||
localStorageMock.getItem.mockReturnValue('"some string"')
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,54 +1,7 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
import { usePersistentBoolean } from './usePersistentBoolean'
|
||||
|
||||
const STORAGE_KEY = 'oc:sidebar:collapsed'
|
||||
|
||||
function readStorage(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStorage(key: string, value: unknown): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function readStoredBoolean(key: string, fallback: boolean): boolean {
|
||||
const stored = readStorage(key)
|
||||
if (stored === null) {
|
||||
return fallback
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(stored)
|
||||
return typeof parsed === 'boolean' ? parsed : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(() => {
|
||||
setValue((prev: boolean) => {
|
||||
const newValue = !prev
|
||||
writeStorage(key, newValue)
|
||||
return newValue
|
||||
})
|
||||
}, [key])
|
||||
|
||||
return [value, toggle]
|
||||
}
|
||||
|
||||
export function useSidebarCollapsed(): [boolean, () => void] {
|
||||
return usePersistentBoolean(STORAGE_KEY, false)
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useQueries, useQuery } from '@tanstack/react-query'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
||||
import { useSessionPins } from '@/hooks/useSessionPins'
|
||||
import { buildPinnedSessionKeys, buildSessionKey } from '@/lib/sessionKey'
|
||||
import { buildPinnedSessionKeys, buildSessionKey, getSessionKey } from '@/lib/sessionKey'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import {
|
||||
SIDEBAR_SESSIONS_PER_REPO,
|
||||
@@ -46,9 +46,7 @@ export function useSidebarRepoGroups(input: {
|
||||
const missingPins = useMemo(() => {
|
||||
if (search) return []
|
||||
const repoDirectories = new Set(directories)
|
||||
const fetchedKeys = new Set(
|
||||
sessions.map((session) => buildSessionKey(session.location.directory, session.id)),
|
||||
)
|
||||
const fetchedKeys = new Set(sessions.map(getSessionKey))
|
||||
return (sessionPins ?? []).filter(
|
||||
(pin) =>
|
||||
repoDirectories.has(pin.directory) &&
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { getFocusedElement, hasOpenOverlay, isFinePointer, restoreOverlayFocus } from './overlayFocus'
|
||||
import { getFocusedElement, hasOpenOverlay, restoreOverlayFocus } from './overlayFocus'
|
||||
import { PROMPT_INPUT_SELECTOR, isPromptInput, isTextEntryElement } from './domTargets'
|
||||
|
||||
function createElement<K extends keyof HTMLElementTagNameMap>(
|
||||
@@ -26,16 +26,6 @@ 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)
|
||||
|
||||
@@ -12,10 +12,7 @@ export function getFocusedElement(): HTMLElement | null {
|
||||
: null
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the current device uses a fine pointer, such as a mouse or trackpad.
|
||||
*/
|
||||
export function isFinePointer(): boolean {
|
||||
function isFinePointer(): boolean {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.matchMedia === 'function' &&
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildPinnedSessionKeys } from './sessionKey'
|
||||
import { buildPinnedSessionKeys, getSessionKey } from './sessionKey'
|
||||
import type { Session } from '@/api/types'
|
||||
|
||||
describe('getSessionKey', () => {
|
||||
it('combines the session directory and id', () => {
|
||||
const session = { id: 'ses_1', location: { directory: '/w/a' } } as Session
|
||||
|
||||
expect(getSessionKey(session)).toBe('/w/a:ses_1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildPinnedSessionKeys', () => {
|
||||
it('builds a session key for each pin', () => {
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { Session } from '@/api/types'
|
||||
|
||||
export function buildSessionKey(directory: string | undefined, id: string): string {
|
||||
return `${directory ?? ''}:${id}`
|
||||
}
|
||||
|
||||
export function getSessionKey(session: Pick<Session, 'id' | 'location'>): string {
|
||||
return buildSessionKey(session.location.directory, session.id)
|
||||
}
|
||||
|
||||
export function buildPinnedSessionKeys(
|
||||
pins: ReadonlyArray<{ directory: string; sessionId: string }>,
|
||||
): Set<string> {
|
||||
|
||||
@@ -842,7 +842,7 @@ export function SessionDetail() {
|
||||
}}
|
||||
onActiveSessionDeleted={() => {
|
||||
setSessionsDialogOpen(false)
|
||||
navigate(getSessionListPath(repoId, isAssistantSession))
|
||||
handleCloseSession()
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
Reference in new issue
Block a user