feat(sessions): TUI-style session picker with scope toggle and delete

This commit is contained in:
Chris Scott committed 2026-10-08 14:36:26 -04:00
1 parent f13463f82a
commit 85288d6393
13 files changed
+1189 -292

No files matched your search

@@ -583,102 +583,6 @@ describe('SessionList', () => {
expect(searchInput).toHaveFocus()
})
it('highlights the active session by default and the first match after typing', async () => {
const user = userEvent.setup()
sessionsData.splice(0, sessionsData.length,
{ id: 'ses_active', title: 'active task', location: { directory: '/w/a' }, time: { updated: 2 } },
{ id: 'ses_other', title: 'other task', location: { directory: '/w/a' }, time: { updated: 1 } },
)
render(
<SessionList
directories={['/w/a']}
activeSessionID="ses_active"
onSelectSession={vi.fn()}
/>,
)
expect(screen.getByRole('option', { selected: true }).textContent).toContain('active task')
await user.type(screen.getByPlaceholderText('Search sessions...'), 'other')
expect(screen.getByRole('option', { selected: true }).textContent).toContain('other task')
})
it('navigates with arrows and Ctrl+N/Ctrl+P, wrapping around, and selects with Enter', () => {
sessionsData.splice(0, sessionsData.length,
{ id: 'ses_1', title: 'one', location: { directory: '/w/a' }, time: { updated: 3 } },
{ id: 'ses_2', title: 'two', location: { directory: '/w/a' }, time: { updated: 2 } },
{ id: 'ses_3', title: 'three', location: { directory: '/w/a' }, time: { updated: 1 } },
)
const onSelectSession = vi.fn()
render(
<SessionList
directories={['/w/a']}
onSelectSession={onSelectSession}
/>,
)
const searchInput = screen.getByPlaceholderText('Search sessions...')
const highlightedTitle = () => screen.getByRole('option', { selected: true }).textContent ?? ''
expect(highlightedTitle()).toContain('one')
fireEvent.keyDown(searchInput, { key: 'ArrowDown' })
expect(highlightedTitle()).toContain('two')
fireEvent.keyDown(searchInput, { key: 'ArrowUp' })
expect(highlightedTitle()).toContain('one')
fireEvent.keyDown(searchInput, { key: 'ArrowUp' })
expect(highlightedTitle()).toContain('three')
fireEvent.keyDown(searchInput, { key: 'n', ctrlKey: true })
expect(highlightedTitle()).toContain('one')
fireEvent.keyDown(searchInput, { key: 'p', ctrlKey: true })
expect(highlightedTitle()).toContain('three')
fireEvent.keyDown(searchInput, { key: 'Enter' })
expect(onSelectSession).toHaveBeenCalledWith('ses_3')
})
it('clamps PageDown and PageUp navigation to the ends of the list', () => {
sessionsData.splice(0, sessionsData.length,
...Array.from({ length: 15 }, (_, index) => ({
id: `ses_${index}`,
title: `session ${index}`,
location: { directory: '/w/a' },
time: { updated: 15 - index },
})),
)
render(
<SessionList
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
const searchInput = screen.getByPlaceholderText('Search sessions...')
const highlightedTitle = () => screen.getByRole('option', { selected: true }).textContent ?? ''
expect(highlightedTitle()).toContain('session 0')
fireEvent.keyDown(searchInput, { key: 'PageDown' })
expect(highlightedTitle()).toContain('session 10')
fireEvent.keyDown(searchInput, { key: 'PageDown' })
expect(highlightedTitle()).toContain('session 14')
fireEvent.keyDown(searchInput, { key: 'PageUp' })
expect(highlightedTitle()).toContain('session 4')
fireEvent.keyDown(searchInput, { key: 'PageUp' })
expect(highlightedTitle()).toContain('session 0')
})
it('keeps the search input rendered while the first page is loading', () => {
isLoadingRef.current = true
+29 -157
View File
@@ -1,17 +1,17 @@
import { useCallback, useState, useMemo, useEffect, useRef, useId, type ReactNode } from "react";
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
import { useCallback, useState, useMemo, useEffect, useRef, type ReactNode } from "react";
import { useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
import type { Session } from "@/api/types";
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins';
import { buildSessionKey, buildPinnedSessionKeys } from '@/lib/sessionKey';
import { partitionSessions, selectRootSessions } from './session-partition';
import { partitionSessions } from './session-partition';
import { DeleteSessionDialog } from "./DeleteSessionDialog";
import { SessionCard } from "./SessionCard";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Search, Trash2, Pencil, X } from "lucide-react";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { useSessionSearch } from "@/hooks/useSessionSearch";
interface SessionListProps {
directory?: string;
@@ -44,17 +44,26 @@ export const SessionList = ({
const source = directories && directories.length > 0 ? directories : directory ? [directory] : [];
return Array.from(new Set(source.filter(Boolean)));
}, [directory, directories]);
const directorySet = useMemo(() => new Set(directoriesList), [directoriesList]);
const primaryDirectory = directoriesList[0];
const sessionCreateDirectory = createDirectory ?? primaryDirectory;
const getSessionSelectionKey = useCallback((session: Session) =>
buildSessionKey(session.location.directory, session.id),
[]);
const [searchQuery, setSearchQuery] = useState("");
const trimmedSearchQuery = searchQuery.trim();
const debouncedSearchQuery = useDebouncedValue(trimmedSearchQuery, 150);
const search = trimmedSearchQuery ? debouncedSearchQuery : '';
const { data: sessions, isLoading, isPlaceholderData, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(directoriesList, { search, limit: 25, keepPreviousResults: true });
const {
query,
setQuery,
trimmedQuery,
sessions,
filteredSessions,
isSearchPending,
isLoading,
isPlaceholderData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isFetchNextPageError,
canFetchNextPage,
} = useSessionSearch(directoriesList);
const deleteSession = useDeleteSession(directoriesList);
const createSession = useCreateSession(sessionCreateDirectory, (newSession) => {
onSelectSession(newSession.id);
@@ -71,52 +80,11 @@ export const SessionList = ({
const [manageMode, setManageMode] = useState(false);
const sessionListRef = useRef<HTMLDivElement>(null);
const rootSessions = useMemo(
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }),
[sessions, directorySet, getSessionSelectionKey],
);
const filteredSessions = useMemo(() => {
if (!trimmedSearchQuery) return rootSessions;
const needle = trimmedSearchQuery.toLowerCase();
return rootSessions.filter((session) => (session.title ?? '').toLowerCase().includes(needle));
}, [rootSessions, trimmedSearchQuery]);
const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo(
() => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey),
[filteredSessions, pinnedKeys, getSessionSelectionKey],
);
const navSessions = useMemo(
() => [...pinnedSessions, ...todaySessions, ...olderSessions],
[pinnedSessions, todaySessions, olderSessions],
);
const [highlightedKey, setHighlightedKey] = useState<string | null>(null);
useEffect(() => {
setHighlightedKey(null);
}, [trimmedSearchQuery]);
const highlightedSession = useMemo(() => {
if (navSessions.length === 0) return undefined;
if (highlightedKey) {
const stored = navSessions.find((session) => getSessionSelectionKey(session) === highlightedKey);
if (stored) return stored;
}
if (!trimmedSearchQuery && activeSessionID) {
const active = navSessions.find((session) => session.id === activeSessionID);
if (active) return active;
}
return navSessions[0];
}, [navSessions, highlightedKey, trimmedSearchQuery, activeSessionID, getSessionSelectionKey]);
const highlightedSessionKey = highlightedSession ? getSessionSelectionKey(highlightedSession) : null;
const highlightedIndex = highlightedSession ? navSessions.indexOf(highlightedSession) : -1;
const listboxId = useId();
const keyboardNavigationEnabled = !renderSessions && !manageMode;
const isSearchPending = trimmedSearchQuery !== search || isPlaceholderData;
const handleTogglePin = (session: Session) => {
const directory = session.location.directory;
const key = getSessionSelectionKey(session);
@@ -129,92 +97,20 @@ export const SessionList = ({
const handleSessionsScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData) {
if (scrollHeight - scrollTop - clientHeight <= 240 && canFetchNextPage) {
void fetchNextPage();
}
}, [hasNextPage, isFetchingNextPage, isFetchNextPageError, isPlaceholderData, fetchNextPage]);
}, [canFetchNextPage, fetchNextPage]);
useEffect(() => {
const sessionList = sessionListRef.current;
const isNearBottom = sessionList
? sessionList.scrollHeight - sessionList.scrollTop - sessionList.clientHeight <= 240
: filteredSessions.length === 0;
if (
!isLoading
&& !isPlaceholderData
&& isNearBottom
&& hasNextPage
&& !isFetchingNextPage
&& !isFetchNextPageError
) {
if (!isLoading && isNearBottom && canFetchNextPage) {
void fetchNextPage();
}
}, [isLoading, isPlaceholderData, filteredSessions, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
useEffect(() => {
if (!highlightedSessionKey) return;
const list = sessionListRef.current;
if (!list) return;
const highlighted = list.querySelector<HTMLElement>('[data-highlighted="true"]');
if (highlighted && typeof highlighted.scrollIntoView === 'function') {
highlighted.scrollIntoView({ block: 'nearest' });
}
}, [highlightedSessionKey]);
const handleSearchKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (!keyboardNavigationEnabled) return;
if (event.nativeEvent.isComposing) return;
if (event.altKey || event.metaKey) return;
const selectIndex = (index: number) => {
const session = navSessions[index];
if (!session) return false;
setHighlightedKey(getSessionSelectionKey(session));
return true;
};
const moveBy = (delta: number) => {
const count = navSessions.length;
if (count === 0) return false;
return selectIndex(((highlightedIndex + delta) % count + count) % count);
};
const moveClamped = (delta: number) => {
const count = navSessions.length;
if (count === 0) return false;
return selectIndex(Math.min(Math.max(highlightedIndex + delta, 0), count - 1));
};
if (event.ctrlKey) {
if (event.key.toLowerCase() === 'n') {
if (moveBy(1)) event.preventDefault();
} else if (event.key.toLowerCase() === 'p') {
if (moveBy(-1)) event.preventDefault();
}
return;
}
switch (event.key) {
case 'ArrowDown':
if (moveBy(1)) event.preventDefault();
break;
case 'ArrowUp':
if (moveBy(-1)) event.preventDefault();
break;
case 'PageDown':
if (moveClamped(10)) event.preventDefault();
break;
case 'PageUp':
if (moveClamped(-10)) event.preventDefault();
break;
case 'Enter':
if (highlightedSession) {
event.preventDefault();
onSelectSession(highlightedSession.id);
}
break;
default:
break;
}
};
}, [isLoading, filteredSessions, canFetchNextPage, fetchNextPage]);
const getDeleteTarget = (session: Session): DeleteSessionTarget => ({
id: session.id,
@@ -280,7 +176,7 @@ export const SessionList = ({
const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => {
const key = getSessionSelectionKey(session);
const card = (
return (
<SessionCard
key={key}
session={session}
@@ -294,21 +190,6 @@ export const SessionList = ({
onDelete={(e) => handleDelete(session, e)}
/>
);
if (!keyboardNavigationEnabled) return card;
const index = navSessions.indexOf(session);
const isHighlighted = highlightedSession === session;
return (
<div
key={key}
id={`${listboxId}-option-${index}`}
role="option"
aria-selected={isHighlighted}
data-highlighted={isHighlighted ? 'true' : undefined}
className={isHighlighted ? 'rounded-lg ring-2 ring-primary/60' : undefined}
>
{card}
</div>
);
};
if (!isLoading && !isPlaceholderData && (!sessions || sessions.length === 0)) {
@@ -325,7 +206,7 @@ export const SessionList = ({
if ((hasNextPage || isFetchingNextPage) && !renderSessions) {
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
}
if (!searchQuery.trim() && !renderSessions) {
if (!trimmedQuery && !renderSessions) {
return (
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<Card
@@ -381,16 +262,11 @@ export const SessionList = ({
<Input
type="text"
placeholder="Search sessions..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={handleSearchKeyDown}
value={query}
onChange={(e) => setQuery(e.target.value)}
className="pl-9 h-9"
autoComplete="off"
name="session-search"
role={keyboardNavigationEnabled ? 'combobox' : undefined}
aria-expanded={keyboardNavigationEnabled ? true : undefined}
aria-controls={keyboardNavigationEnabled ? listboxId : undefined}
aria-activedescendant={keyboardNavigationEnabled && highlightedIndex >= 0 ? `${listboxId}-option-${highlightedIndex}` : undefined}
/>
</div>
<Button
@@ -415,17 +291,13 @@ export const SessionList = ({
aria-label="Sessions"
onScroll={handleSessionsScroll}
>
<div
id={keyboardNavigationEnabled ? listboxId : undefined}
role={keyboardNavigationEnabled ? 'listbox' : undefined}
className="flex flex-col gap-4"
>
<div className="flex flex-col gap-4">
{isLoading && !renderSessions ? (
<div className="text-sm text-muted-foreground text-center py-4">Loading sessions...</div>
) : renderSessions ? (
renderSessions({
sessions: filteredSessions,
searchQuery,
searchQuery: query,
renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionSelectionKey(session))),
})
) : filteredSessions.length === 0 && !isFetchingNextPage ? (
@@ -0,0 +1,312 @@
import { 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 { SessionPickerDialog } from './SessionPickerDialog'
const mocks = vi.hoisted(() => ({
sessionsData: [] as Session[],
lastDirectories: [] as string[],
fetchNextPage: vi.fn(),
deleteSessionMock: vi.fn(),
togglePinMock: vi.fn(),
sessionPins: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
repos: [] as Repo[],
}))
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
return {
...actual,
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string }) => {
mocks.lastDirectories = directories
const search = options?.search?.toLowerCase() ?? ''
const data = search
? mocks.sessionsData.filter((session) => (session.title ?? '').toLowerCase().includes(search))
: mocks.sessionsData
return {
data,
isLoading: false,
isPlaceholderData: false,
fetchNextPage: mocks.fetchNextPage,
hasNextPage: false,
isFetchingNextPage: false,
isFetchNextPageError: false,
}
},
useDeleteSession: () => ({ mutateAsync: mocks.deleteSessionMock, isPending: false }),
}
})
vi.mock('@/hooks/useSessionPins', () => ({
useSessionPins: () => ({ data: mocks.sessionPins }),
useToggleSessionPin: () => ({ mutate: mocks.togglePinMock }),
}))
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' }) }
})
function session(id: string, title: string, directory: string, updated = Date.now()): Session {
return {
id,
projectID: 'proj',
title,
time: { created: updated, updated },
location: { directory },
cost: 0,
tokens: {},
} as unknown as Session
}
function repo(id: number, name: string, fullPath: string): Repo {
return {
id,
name,
localPath: fullPath,
fullPath,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
}
}
function renderPicker(overrides: Partial<React.ComponentProps<typeof SessionPickerDialog>> = {}) {
const onOpenChange = vi.fn()
const onSelectSession = vi.fn()
const onActiveSessionDeleted = vi.fn()
render(
<SessionPickerDialog
open
onOpenChange={onOpenChange}
currentRepo={mocks.repos[0]}
onSelectSession={onSelectSession}
onActiveSessionDeleted={onActiveSessionDeleted}
{...overrides}
/>,
)
return { onOpenChange, onSelectSession, onActiveSessionDeleted }
}
const combobox = () => screen.getByRole('combobox')
describe('SessionPickerDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
mocks.deleteSessionMock.mockResolvedValue(undefined)
mocks.sessionPins = []
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.sessionsData = []
})
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),
session('ses_other', 'Other session', '/w/a', 2000),
]
renderPicker({ activeSessionID: 'ses_active' })
const active = screen.getByRole('option', { name: /Active session/ })
const other = screen.getByRole('option', { name: /Other session/ })
expect(active).toHaveAttribute('aria-selected', 'true')
expect(active.textContent).toContain('●')
expect(other).toHaveAttribute('aria-selected', 'false')
})
it('filters rows immediately as the query is typed', () => {
mocks.sessionsData = [
session('ses_alpha', 'alpha task', '/w/a', 2000),
session('ses_beta', 'beta task', '/w/a', 1000),
]
renderPicker()
fireEvent.change(combobox(), { target: { value: 'beta' } })
expect(screen.queryByText('alpha task')).not.toBeInTheDocument()
expect(screen.getByText('beta task')).toBeInTheDocument()
})
it('moves the cursor with arrow keys and Ctrl+N/Ctrl+P, wrapping, and opens the row on Enter', () => {
mocks.sessionsData = [
session('ses_1', 'First', '/w/a', 3000),
session('ses_2', 'Second', '/w/a', 2000),
session('ses_3', 'Third', '/w/a', 1000),
]
const { onSelectSession } = renderPicker()
const first = screen.getByRole('option', { name: /First/ })
const second = screen.getByRole('option', { name: /Second/ })
const third = screen.getByRole('option', { name: /Third/ })
expect(first).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
expect(second).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
expect(first).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
expect(third).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'n', ctrlKey: true })
expect(first).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'p', ctrlKey: true })
expect(third).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'Enter' })
expect(onSelectSession).toHaveBeenCalledWith(
expect.objectContaining({ id: 'ses_3' }),
mocks.repos[0],
)
})
it('toggles scope with Ctrl+A, persists it, queries every repo directory and shows repo labels', () => {
mocks.sessionsData = [
session('ses_a', 'Alpha session', '/w/a', 2000),
session('ses_b', 'Beta session', '/w/b', 1000),
]
renderPicker()
expect(mocks.lastDirectories).toEqual(['/w/a'])
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(localStorage.getItem('oc:session-picker:all-projects')).toBe('true')
expect(screen.getByText('Beta session')).toBeInTheDocument()
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.getByText('beta')).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 'a', ctrlKey: true })
expect(mocks.lastDirectories).toEqual(['/w/a'])
expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('false')
})
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),
session('ses_2', 'Second', '/w/a', 2000),
]
renderPicker()
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument()
expect(mocks.deleteSessionMock).not.toHaveBeenCalled()
fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
expect(screen.queryByText('Press Ctrl+D again to confirm')).not.toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
expect(mocks.deleteSessionMock).toHaveBeenCalledWith({ id: 'ses_2', directory: '/w/a' })
await waitFor(() =>
expect(screen.queryByText('Press Ctrl+D again to confirm')).not.toBeInTheDocument(),
)
})
it('notifies when the active session is deleted', async () => {
mocks.sessionsData = [session('ses_active', 'Active', '/w/a', 3000)]
const { onActiveSessionDeleted } = renderPicker({ activeSessionID: 'ses_active' })
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
await waitFor(() => expect(onActiveSessionDeleted).toHaveBeenCalled())
})
it('moves the cursor when a mouse pointer moves over a row', () => {
mocks.sessionsData = [
session('ses_1', 'First', '/w/a', 3000),
session('ses_2', 'Second', '/w/a', 2000),
]
renderPicker()
const second = screen.getByRole('option', { name: /Second/ })
const pointerMove = new Event('pointermove', { bubbles: true })
Object.defineProperty(pointerMove, 'pointerType', { value: 'mouse' })
fireEvent(second, pointerMove)
expect(second).toHaveAttribute('aria-selected', 'true')
})
it('opens the delete confirmation from the row menu', async () => {
mocks.sessionsData = [session('ses_1', 'First', '/w/a', 3000)]
renderPicker()
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Session actions' }))
await user.click(await screen.findByText('Delete'))
expect(await screen.findByRole('dialog', { name: 'Delete Session' })).toBeInTheDocument()
})
it('groups older sessions under per-day headings', () => {
mocks.sessionsData = [
session('ses_jan2', 'Jan two', '/w/a', new Date(2020, 0, 2, 12).getTime()),
session('ses_jan1', 'Jan one', '/w/a', new Date(2020, 0, 1, 12).getTime()),
]
renderPicker()
expect(screen.getByText('Thu, Jan 2, 2020')).toBeInTheDocument()
expect(screen.getByText('Wed, Jan 1, 2020')).toBeInTheDocument()
})
it('resets the query and cursor on reopen', async () => {
mocks.sessionsData = [
session('ses_active', 'Active session', '/w/a', 3000),
session('ses_other', 'Other session', '/w/a', 2000),
]
function Host() {
const [open, setOpen] = useState(true)
return (
<>
<button type="button" onClick={() => setOpen(false)}>close-picker</button>
<button type="button" onClick={() => setOpen(true)}>open-picker</button>
<SessionPickerDialog
open={open}
onOpenChange={setOpen}
currentRepo={mocks.repos[0]}
activeSessionID="ses_active"
onSelectSession={vi.fn()}
onActiveSessionDeleted={vi.fn()}
/>
</>
)
}
render(<Host />)
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Other' } })
expect(screen.queryByText('Active session')).not.toBeInTheDocument()
fireEvent.click(screen.getByText('close-picker'))
fireEvent.click(screen.getByText('open-picker'))
await waitFor(() => expect(screen.getByRole('combobox')).toHaveValue(''))
expect(screen.getByRole('option', { name: /Active session/ })).toHaveAttribute('aria-selected', 'true')
})
})
@@ -0,0 +1,631 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { format, startOfDay } from 'date-fns'
import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
import type { Repo, Session } from '@/api/types'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
import { partitionSessions } from '@/components/session/session-partition'
import { useDeleteSession } from '@/hooks/useOpenCode'
import { useSessionSearch } from '@/hooks/useSessionSearch'
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
import { usePersistentBoolean } from '@/hooks/useSidebarCollapsed'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { buildPinnedSessionKeys, buildSessionKey } from '@/lib/sessionKey'
import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils'
import { isFinePointer } from '@/lib/overlayFocus'
const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
const PAGE_STEP = 10
const NEAR_BOTTOM_PX = 240
interface SessionPickerDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
currentRepo: Repo | undefined
activeSessionID?: string
onSelectSession: (session: Session, repo: Repo) => void
onActiveSessionDeleted: () => void
}
interface SessionPickerRow {
key: string
session: Session
repo: Repo
}
interface SessionPickerSection {
id: string
heading: string
rows: SessionPickerRow[]
}
function buildSections(
sessions: Session[],
pinnedKeys: ReadonlySet<string>,
keyFn: (session: Session) => string,
resolveRepo: (session: Session) => Repo | undefined,
): SessionPickerSection[] {
const { pinned, today, older } = partitionSessions(sessions, pinnedKeys, keyFn)
const toRows = (group: Session[]): SessionPickerRow[] =>
group.flatMap((session) => {
const repo = resolveRepo(session)
return repo ? [{ key: keyFn(session), session, repo }] : []
})
const sections: SessionPickerSection[] = []
const pinnedRows = toRows(pinned)
if (pinnedRows.length > 0) sections.push({ id: 'pinned', heading: 'Pinned', rows: pinnedRows })
const todayRows = toRows(today)
if (todayRows.length > 0) sections.push({ id: 'today', heading: 'Today', rows: todayRows })
const currentYear = new Date().getFullYear()
const byDay = new Map<number, SessionPickerRow[]>()
for (const row of toRows(older)) {
const day = startOfDay(new Date(row.session.time.updated)).getTime()
const existing = byDay.get(day)
if (existing) existing.push(row)
else byDay.set(day, [row])
}
for (const [day, rows] of byDay) {
const date = new Date(day)
const heading =
date.getFullYear() === currentYear ? format(date, 'EEE, MMM d') : format(date, 'EEE, MMM d, yyyy')
sections.push({ id: `day-${day}`, heading, rows })
}
return sections
}
function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
}
function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isActive: boolean }) {
const status = useSessionStatusForSession(sessionID)
if (status.type !== 'idle') {
return (
<SessionStatusIndicator
sessionID={sessionID}
size="sm"
className="[&>div]:gap-0 [&>div>div]:h-1.5 [&>div>div]:w-px"
/>
)
}
if (isActive) {
return <span aria-hidden="true">●</span>
}
return null
}
interface SessionPickerRowItemProps {
row: SessionPickerRow
optionId: string
isCursor: boolean
isActive: boolean
isPinned: boolean
isPendingDelete: boolean
showRepo: boolean
onOpen: () => void
onHover: () => void
onTogglePin: () => void
onRequestDelete: () => void
registerRef: (node: HTMLDivElement | null) => void
}
function SessionPickerRowItem({
row,
optionId,
isCursor,
isActive,
isPinned,
isPendingDelete,
showRepo,
onOpen,
onHover,
onTogglePin,
onRequestDelete,
registerRef,
}: SessionPickerRowItemProps) {
return (
<div
ref={registerRef}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') onHover()
}}
className={cn(
'group flex items-center rounded-md text-sm min-h-8 pointer-coarse:min-h-11',
isPendingDelete
? 'bg-destructive text-destructive-foreground'
: isCursor
? 'bg-primary text-primary-foreground'
: 'hover:bg-accent',
)}
>
<div
role="option"
id={optionId}
aria-selected={isCursor}
onClick={onOpen}
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">
<SessionPickerGutter sessionID={row.session.id} isActive={isActive} />
</span>
<span
className={cn(
'min-w-0 flex-1 truncate',
isPendingDelete
? 'text-destructive-foreground'
: isCursor
? 'text-primary-foreground'
: isActive
? 'text-primary'
: 'text-foreground',
)}
>
{isPendingDelete ? 'Press Ctrl+D again to confirm' : row.session.title || UNTITLED_SESSION_TITLE}
</span>
<span
className={cn(
'flex shrink-0 items-center gap-2 text-xs',
isPendingDelete
? 'text-destructive-foreground/80'
: isCursor
? 'text-primary-foreground/80'
: 'text-muted-foreground',
)}
>
{showRepo && <span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>}
<span>{formatShortRelativeTime(new Date(row.session.time.updated))}</span>
</span>
</div>
<div className="flex shrink-0 items-center pr-1">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
aria-label="Session actions"
onClick={(event) => event.stopPropagation()}
className={cn(
'h-7 w-7 p-0 shrink-0 pointer-coarse:h-11 pointer-coarse:w-11 pointer-coarse:opacity-100',
isCursor || isPendingDelete ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100',
)}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="z-[200]" onClick={(event) => event.stopPropagation()}>
<DropdownMenuItem onClick={onTogglePin}>
{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>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)
}
export function SessionPickerDialog({
open,
onOpenChange,
currentRepo,
activeSessionID,
onSelectSession,
onActiveSessionDeleted,
}: SessionPickerDialogProps) {
const [allProjects, toggleAllProjects] = usePersistentBoolean(ALL_PROJECTS_STORAGE_KEY, false)
const { repos } = useNavigableRepos(open)
const searchInputRef = useRef<HTMLInputElement>(null)
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)
if (currentRepo) map.set(currentRepo.fullPath, currentRepo)
return map
}, [repos, currentRepo])
const directories = useMemo(() => {
if (!allProjects) return currentRepo ? [currentRepo.fullPath] : []
const paths = repos.map((repo) => repo.fullPath)
if (currentRepo) paths.push(currentRepo.fullPath)
return Array.from(new Set(paths))
}, [allProjects, repos, currentRepo])
const {
query,
setQuery,
trimmedQuery,
filteredSessions,
isSearchPending,
isLoading,
fetchNextPage,
isFetchingNextPage,
isFetchNextPageError,
canFetchNextPage,
} = useSessionSearch(directories)
const keyFn = useCallback(
(session: Session) => buildSessionKey(session.location.directory, session.id),
[],
)
const resolveRepo = useCallback(
(session: Session) => repoByDirectory.get(session.location.directory) ?? currentRepo,
[repoByDirectory, currentRepo],
)
const { data: sessionPins } = useSessionPins()
const togglePin = useToggleSessionPin()
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
const deleteSession = useDeleteSession(directories)
const [cursorKey, setCursorKey] = useState<string | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
const sections = useMemo(
() => buildSections(filteredSessions, pinnedKeys, keyFn, resolveRepo),
[filteredSessions, pinnedKeys, keyFn, resolveRepo],
)
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
const rowIndexByKey = useMemo(
() => new Map(rows.map((row, index) => [row.key, index])),
[rows],
)
const activeRow = useMemo(
() => rows.find((row) => row.session.id === activeSessionID),
[rows, activeSessionID],
)
const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
const cursorIndex = useMemo(() => {
if (cursorKey) {
const index = rowIndexByKey.get(cursorKey)
if (index !== undefined) return index
}
return defaultCursorKey ? rowIndexByKey.get(defaultCursorKey) ?? -1 : -1
}, [cursorKey, rowIndexByKey, defaultCursorKey])
const cursorRow = cursorIndex >= 0 ? rows[cursorIndex] : undefined
useEffect(() => {
setCursorKey(null)
setPendingDeleteKey(null)
}, [trimmedQuery, allProjects])
useEffect(() => {
if (!open) return
setQuery('')
setCursorKey(null)
setPendingDeleteKey(null)
setSessionToDelete(null)
}, [open, setQuery])
const setRowRef = useCallback((key: string, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRow) return
const node = rowRefs.current.get(cursorRow.key)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRow])
const moveCursor = useCallback(
(index: number) => {
const row = rows[index]
if (!row) return
setCursorKey(row.key)
setPendingDeleteKey(null)
},
[rows],
)
const openRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
onSelectSession(row.session, row.repo)
},
[onSelectSession],
)
const deleteRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
if (pendingDeleteKey !== row.key) {
setPendingDeleteKey(row.key)
return
}
void deleteSession
.mutateAsync({ id: row.session.id, directory: row.session.location.directory })
.then(() => {
if (row.session.id === activeSessionID) onActiveSessionDeleted()
})
.catch(() => undefined)
.finally(() => {
setPendingDeleteKey(null)
})
},
[pendingDeleteKey, deleteSession, activeSessionID, onActiveSessionDeleted],
)
const handleSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const moveBy = (delta: number, wrap: boolean) => {
if (rows.length === 0) return
const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
const raw = base + delta
const next = wrap ? ((raw % rows.length) + rows.length) % rows.length : Math.max(0, Math.min(rows.length - 1, raw))
moveCursor(next)
}
const key = event.key
const ctrlKey = event.key.toLowerCase()
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRow) return
event.preventDefault()
openRow(cursorRow)
return
}
if (event.ctrlKey && ctrlKey === 'a') {
event.preventDefault()
toggleAllProjects()
return
}
if (event.ctrlKey && ctrlKey === 'd') {
if (!cursorRow) return
event.preventDefault()
deleteRow(cursorRow)
}
},
[cursorIndex, rows, moveCursor, cursorRow, openRow, toggleAllProjects, deleteRow],
)
const handleListScroll = useCallback(
(event: React.UIEvent<HTMLDivElement>) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget
if (scrollHeight - scrollTop - clientHeight <= NEAR_BOTTOM_PX && canFetchNextPage) {
void fetchNextPage()
}
},
[canFetchNextPage, fetchNextPage],
)
useEffect(() => {
if (!open) return
const node = listRef.current
const isNearBottom = node
? node.scrollHeight - node.scrollTop - node.clientHeight <= NEAR_BOTTOM_PX
: rows.length === 0
if (!isLoading && isNearBottom && canFetchNextPage) {
void fetchNextPage()
}
}, [open, isLoading, rows, canFetchNextPage, fetchNextPage])
const handleTogglePin = useCallback(
(row: SessionPickerRow) => {
togglePin.mutate({
sessionId: row.session.id,
directory: row.session.location.directory,
pinned: !pinnedKeys.has(row.key),
})
},
[togglePin, pinnedKeys],
)
const confirmDelete = useCallback(() => {
if (!sessionToDelete) return
void deleteSession
.mutateAsync({
id: sessionToDelete.id,
directory: sessionToDelete.location.directory,
})
.then(() => {
if (sessionToDelete.id === activeSessionID) onActiveSessionDeleted()
})
.catch(() => undefined)
.finally(() => {
setSessionToDelete(null)
})
}, [sessionToDelete, deleteSession, activeSessionID, onActiveSessionDeleted])
const renderRow = (row: SessionPickerRow) => {
const index = rowIndexByKey.get(row.key) ?? -1
return (
<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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
mobileFullscreen
className="flex min-h-0 w-full min-w-0 flex-col gap-0 p-0 sm:h-[70vh] sm:max-w-3xl sm:p-6"
onEscapeKeyDown={() => onOpenChange(false)}
onOpenAutoFocus={(event) => {
event.preventDefault()
if (isFinePointer()) {
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}
/>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,112 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import { useSessionSearch } from './useSessionSearch'
const { sessionsData, lastArgsRef, flagsRef } = vi.hoisted(() => ({
sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
lastArgsRef: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean } } | undefined },
flagsRef: { current: { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false } },
}))
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
return {
...actual,
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean }) => {
lastArgsRef.current = { directories, options }
const search = options?.search?.toLowerCase() ?? ''
const data = search
? sessionsData.filter((session) => session.title.toLowerCase().includes(search))
: sessionsData
return {
data,
isLoading: false,
isPlaceholderData: flagsRef.current.isPlaceholderData,
fetchNextPage: vi.fn(),
hasNextPage: flagsRef.current.hasNextPage,
isFetchingNextPage: flagsRef.current.isFetchingNextPage,
isFetchNextPageError: flagsRef.current.isFetchNextPageError,
}
},
}
})
describe('useSessionSearch', () => {
beforeEach(() => {
sessionsData.splice(0, sessionsData.length,
{ id: 'ses_alpha', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 2 } },
{ id: 'ses_beta', title: 'beta task', location: { directory: '/w/a' }, time: { updated: 1 } },
)
lastArgsRef.current = undefined
flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false }
})
afterEach(() => {
vi.useRealTimers()
})
it('filters sessions locally by title immediately', () => {
const { result } = renderHook(() => useSessionSearch(['/w/a']))
act(() => {
result.current.setQuery('alpha')
})
expect(result.current.filteredSessions.map((session) => session.title)).toEqual(['alpha task'])
expect(lastArgsRef.current?.options?.search).toBe('')
})
it('passes the debounced search to useSessionsAcrossDirectories with keepPreviousResults', () => {
vi.useFakeTimers()
const { result } = renderHook(() => useSessionSearch(['/w/a']))
act(() => {
result.current.setQuery('deploy')
})
act(() => {
vi.advanceTimersByTime(150)
})
expect(lastArgsRef.current?.options?.search).toBe('deploy')
expect(lastArgsRef.current?.options?.limit).toBe(25)
expect(lastArgsRef.current?.options?.keepPreviousResults).toBe(true)
})
it('reports a pending search before the debounce settles', () => {
vi.useFakeTimers()
const { result } = renderHook(() => useSessionSearch(['/w/a']))
act(() => {
result.current.setQuery('deploy')
})
expect(result.current.isSearchPending).toBe(true)
act(() => {
vi.advanceTimersByTime(150)
})
expect(result.current.isSearchPending).toBe(false)
})
it('exposes canFetchNextPage only when paging is safe', () => {
const { result, rerender } = renderHook(() => useSessionSearch(['/w/a']))
expect(result.current.canFetchNextPage).toBe(false)
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false }
rerender()
expect(result.current.canFetchNextPage).toBe(true)
flagsRef.current = { hasNextPage: true, isFetchingNextPage: true, isFetchNextPageError: false, isPlaceholderData: false }
rerender()
expect(result.current.canFetchNextPage).toBe(false)
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: true, isPlaceholderData: false }
rerender()
expect(result.current.canFetchNextPage).toBe(false)
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: true }
rerender()
expect(result.current.canFetchNextPage).toBe(false)
})
})
+71
View File
@@ -0,0 +1,71 @@
import { useCallback, useMemo, useState } from 'react'
import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
import { selectRootSessions } from '@/components/session/session-partition'
import { buildSessionKey } from '@/lib/sessionKey'
import type { Session } from '@/api/types'
const DEFAULT_LIMIT = 25
export interface UseSessionSearchOptions {
limit?: number
}
/**
* Owns the sessions-dialog search state: the raw query, its debounced server
* value, the root-session selection, and the immediate local title filter.
*/
export function useSessionSearch(directories: string[], options: UseSessionSearchOptions = {}) {
const limit = options.limit ?? DEFAULT_LIMIT
const [query, setQuery] = useState('')
const trimmedQuery = query.trim()
const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
const search = trimmedQuery ? debouncedQuery : ''
const {
data: sessions,
isLoading,
isPlaceholderData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isFetchNextPageError,
} = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true })
const directorySet = useMemo(() => new Set(directories), [directories])
const getSessionSelectionKey = useCallback(
(session: Session) => buildSessionKey(session.location.directory, session.id),
[],
)
const rootSessions = useMemo(
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }),
[sessions, directorySet, getSessionSelectionKey],
)
const filteredSessions = useMemo(() => {
if (!trimmedQuery) return rootSessions
const needle = trimmedQuery.toLowerCase()
return rootSessions.filter((session) => (session.title ?? '').toLowerCase().includes(needle))
}, [rootSessions, trimmedQuery])
const isSearchPending = trimmedQuery !== search || isPlaceholderData
const canFetchNextPage = Boolean(
hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData,
)
return {
query,
setQuery,
trimmedQuery,
sessions,
filteredSessions,
isSearchPending,
isLoading,
isPlaceholderData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isFetchNextPageError,
canFetchNextPage,
}
}
+5 -1
View File
@@ -31,7 +31,11 @@ function readStoredBoolean(key: string, fallback: boolean): boolean {
}
}
function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
/**
* Persists a boolean preference under `key` in localStorage and returns it with a toggler.
* Falls back to `fallback` when the stored value is missing or malformed.
*/
export function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
const toggle = useCallback(() => {
+21 -30
View File
@@ -8,13 +8,11 @@ import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
import { X, CornerUpLeft } from "lucide-react";
import { SquareFill } from "@/components/ui/square-fill";
import { Header } from "@/components/ui/header";
import { SessionList } from "@/components/session/SessionList";
import { getSessionListPath } from '@/lib/navigation'
import { isFinePointer } from '@/lib/overlayFocus'
import { SessionPickerDialog } from "@/components/session/SessionPickerDialog";
import { getSessionListPath, getSessionPath } from '@/lib/navigation'
import { FetchError } from '@/api/fetchWrapper'
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
import { useSession, useInterruptSession, useUpdateSession, useCreateSession } from "@/hooks/useOpenCode";
@@ -828,32 +826,25 @@ export function SessionDetail() {
)}
</div>
{/* Sessions Dialog */}
<Dialog open={sessionsDialogOpen} onOpenChange={setSessionsDialogOpen}>
<DialogContent
className="max-w-4xl max-h-[80vh]"
onOpenAutoFocus={(event) => {
if (!isFinePointer()) {
event.preventDefault();
(event.currentTarget as HTMLElement).focus();
}
}}
>
<DialogTitle>Sessions</DialogTitle>
<div className="mt-4 flex h-[60vh] min-h-0 flex-col">
{sessionDirectory && (
<SessionList
directory={repoDirectory}
activeSessionID={sessionId || undefined}
onSelectSession={(sessionID) => {
navigate(`/repos/${repoId}/sessions/${sessionID}${sessionRouteSuffix}`)
setSessionsDialogOpen(false)
}}
/>
)}
</div>
</DialogContent>
</Dialog>
{/* Sessions Picker */}
<SessionPickerDialog
open={sessionsDialogOpen}
onOpenChange={setSessionsDialogOpen}
currentRepo={repo}
activeSessionID={sessionId || undefined}
onSelectSession={(session, sessionRepo) => {
if (sessionRepo.id === repoId) {
navigate(`/repos/${repoId}/sessions/${session.id}${sessionRouteSuffix}`)
} else {
navigate(getSessionPath(sessionRepo.id, session.id))
}
setSessionsDialogOpen(false)
}}
onActiveSessionDeleted={() => {
setSessionsDialogOpen(false)
navigate(getSessionListPath(repoId, isAssistantSession))
}}
/>
{sideQuestion && sessionId && (
<SideQuestionDialog
@@ -131,8 +131,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
vi.mock('@/components/session/SessionPickerDialog', () => ({
SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/session/PermissionModeToggle', () => ({
@@ -207,7 +207,7 @@ vi.mock('@/components/navigation/ToolSidePanel', () => ({ ToolSidePanel: vi.fn((
vi.mock('@/hooks/useToolPanel', () => ({
useToolPanel: vi.fn(() => ({ activeTool: null, toggleTool: vi.fn(), closePanel: vi.fn() })),
}))
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
@@ -159,8 +159,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
vi.mock('@/components/session/SessionPickerDialog', () => ({
SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
@@ -137,7 +137,7 @@ vi.mock('@/hooks/useSessionGoals', () => ({
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) }))
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
@@ -154,8 +154,8 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
vi.mock('@/components/session/SessionPickerDialog', () => ({
SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({