- {filteredRepos.length === 0 ? (
+ {rows.length === 0 ? (
{isLoading ? 'Loading projects...' : 'No projects found'}
) : (
- filteredRepos.map((repo, index) => {
- const isCursor = index === effectiveCursorIndex
+ rows.map((row, index) => {
+ const { repo } = row
+ const isCursor = index === cursorIndex
const isCurrent = repo.id === currentRepo?.id
const branch = getRepoBranchLabel(repo)
return (
setRowRef(repo.id, node)}
+ key={row.key}
+ ref={(node) => registerRef(row.key, node)}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') moveCursor(index)
diff --git a/frontend/src/components/session/SessionPickerDialog.test.tsx b/frontend/src/components/session/SessionPickerDialog.test.tsx
index 423c3d36..d6dbea48 100644
--- a/frontend/src/components/session/SessionPickerDialog.test.tsx
+++ b/frontend/src/components/session/SessionPickerDialog.test.tsx
@@ -91,8 +91,8 @@ vi.mock('@/hooks/useActiveWork', () => ({
mocks.activeWorkWindowMs = windowMs
return { groups: mocks.activeWorkGroups, isLoading: false, isError: false }
},
- useActivityWindowMs: () =>
- (mocks.preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES) * 60 * 1000,
+ useActivityWindowMinutes: () =>
+ mocks.preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES,
}))
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
@@ -619,6 +619,35 @@ describe('SessionPickerDialog', () => {
expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[0])
})
+ it('navigates the projects tab with wrapping arrows, PageUp/PageDown and Enter', async () => {
+ mocks.repos = Array.from({ length: 12 }, (_, index) =>
+ repo(index + 1, `repo-${index + 1}`, `/w/r${index + 1}`),
+ )
+ const { onSelectRepo } = renderPicker()
+
+ openProjectsTab()
+
+ expect(await screen.findByRole('option', { name: 'repo-1' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ )
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
+ expect(screen.getByRole('option', { name: 'repo-12' })).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
+ expect(screen.getByRole('option', { name: 'repo-1' })).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'PageDown' })
+ expect(screen.getByRole('option', { name: 'repo-11' })).toHaveAttribute('aria-selected', 'true')
+
+ fireEvent.keyDown(combobox(), { key: 'Enter' })
+ expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[10])
+
+ fireEvent.keyDown(combobox(), { key: 'PageUp' })
+ expect(screen.getByRole('option', { name: 'repo-1' })).toHaveAttribute('aria-selected', 'true')
+ })
+
it('opens a repo on click in the projects tab', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const { onSelectRepo } = renderPicker()
@@ -765,13 +794,25 @@ describe('SessionPickerDialog', () => {
openActiveTab()
expect(
- await screen.findByText('No active or recent sessions in the last 120 minutes'),
+ await screen.findByText('No active or recent sessions in the last 2 hours'),
).toBeInTheDocument()
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.queryByText('Running')).not.toBeInTheDocument()
expect(screen.queryByText('Recent')).not.toBeInTheDocument()
})
+ it('formats a full-day active work window as hours in the empty state', async () => {
+ mocks.preferences = { activityWindowMinutes: 1440 }
+
+ renderPicker()
+ openActiveTab()
+
+ expect(
+ await screen.findByText('No active or recent sessions in the last 24 hours'),
+ ).toBeInTheDocument()
+ expect(mocks.activeWorkWindowMs).toBe(1440 * 60 * 1000)
+ })
+
it('opens the cursor active row with Enter and selects its session and repo', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
diff --git a/frontend/src/components/session/SessionPickerDialog.tsx b/frontend/src/components/session/SessionPickerDialog.tsx
index 0834f6fb..54a4c5d7 100644
--- a/frontend/src/components/session/SessionPickerDialog.tsx
+++ b/frontend/src/components/session/SessionPickerDialog.tsx
@@ -1,10 +1,10 @@
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { format, startOfDay } from 'date-fns'
-import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
+import { MoreHorizontal, Pin, PinOff } from 'lucide-react'
import { getOpenCodeLocation } from '@/api/opencode'
import type { Repo, Session } from '@/api/types'
-import type { ActiveWorkItem } from '@/lib/activeWork'
+import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import {
@@ -13,15 +13,20 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
-import { Input } from '@/components/ui/input'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
import { ProjectPickerContent } from '@/components/session/ProjectPickerContent'
+import {
+ PickerSearchBar,
+ optionId,
+ usePickerCursor,
+ usePickerKeyNav,
+} from '@/components/session/usePickerKeyboardNav'
import { partitionSessions } from '@/components/session/session-partition'
import { buildRepoByDirectory } from '@/components/navigation/sidebar-session-tree'
import { useDeleteSession } from '@/hooks/useOpenCode'
-import { useActiveWork, useActivityWindowMs } from '@/hooks/useActiveWork'
+import { useActiveWork, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { useSessionSearch } from '@/hooks/useSessionSearch'
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
@@ -36,9 +41,7 @@ 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'
-const PAGE_STEP = 10
const NEAR_BOTTOM_PX = 240
-const MS_PER_MINUTE = 60_000
type SessionPickerTab = 'active' | 'sessions' | 'projects'
@@ -113,10 +116,6 @@ function buildSections(
return sections
}
-function optionId(baseId: string, index: number): string {
- return `${baseId}-option-${index}`
-}
-
function stripTrailingSlashes(value: string): string {
return value.replace(/\/+$/, '')
}
@@ -295,206 +294,126 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
)
})
-interface SessionPickerCursorState {
- rowIndexByKey: Map
- cursorIndex: number
- cursorRow: SessionPickerRow | undefined
- pendingDeleteKey: string | null
- setPendingDeleteKey: React.Dispatch>
- registerRef: (key: string, node: HTMLDivElement | null) => void
- moveCursor: (index: number) => void
- resetCursor: () => void
+interface SessionPickerRowActionsOptions {
+ directories: string[]
+ activeSessionID?: string
+ onSelectSession: (session: Session, repo: Repo) => void
+ onDeleteActiveSession: () => void
}
-function useSessionPickerCursor(
- rows: SessionPickerRow[],
- defaultCursorKey: string | null,
-): SessionPickerCursorState {
- const rowRefs = useRef(new Map())
- const [cursorKey, setCursorKey] = useState(null)
- const [pendingDeleteKey, setPendingDeleteKey] = useState(null)
-
- const rowIndexByKey = useMemo(
- () => new Map(rows.map((row, index) => [row.key, index])),
- [rows],
- )
-
- 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
-
- const registerRef = 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 resetCursor = useCallback(() => {
- setCursorKey(null)
- setPendingDeleteKey(null)
- }, [])
-
- return {
- rowIndexByKey,
- cursorIndex,
- cursorRow,
- pendingDeleteKey,
- setPendingDeleteKey,
- registerRef,
- moveCursor,
- resetCursor,
+interface SessionPickerRowActions {
+ pinnedKeys: ReadonlySet
+ pendingDeleteKey: string | null
+ clearPendingDelete: () => void
+ openRow: (row: SessionPickerRow | undefined) => void
+ deleteRow: (row: SessionPickerRow | undefined) => void
+ handleTogglePin: (row: SessionPickerRow) => void
+ handleRequestDelete: (session: Session) => void
+ deleteDialogProps: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onConfirm: () => void
+ onCancel: () => void
+ isDeleting: boolean
}
}
-interface SessionPickerKeyNavOptions {
- rows: SessionPickerRow[]
- cursorIndex: number
- cursorRow: SessionPickerRow | undefined
- moveCursor: (index: number) => void
- onOpenRow: (row: SessionPickerRow) => void
- onDeleteRow: (row: SessionPickerRow) => void
- onToggleAllProjects?: () => void
-}
+function useSessionPickerRowActions({
+ directories,
+ activeSessionID,
+ onSelectSession,
+ onDeleteActiveSession,
+}: SessionPickerRowActionsOptions): SessionPickerRowActions {
+ const { data: sessionPins } = useSessionPins()
+ const togglePin = useToggleSessionPin()
+ const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
+ const deleteSession = useDeleteSession(directories)
+ const [sessionToDelete, setSessionToDelete] = useState(null)
+ const [pendingDeleteKey, setPendingDeleteKey] = useState(null)
-function useSessionPickerKeyNav({
- rows,
- cursorIndex,
- cursorRow,
- moveCursor,
- onOpenRow,
- onDeleteRow,
- onToggleAllProjects,
-}: SessionPickerKeyNavOptions): (event: React.KeyboardEvent) => void {
- return useCallback(
- (event: React.KeyboardEvent) => {
- if (event.nativeEvent.isComposing) return
- if (event.metaKey || event.altKey) return
+ const clearPendingDelete = useCallback(() => {
+ setPendingDeleteKey(null)
+ }, [])
- 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()
- onOpenRow(cursorRow)
- return
- }
- if (onToggleAllProjects && event.ctrlKey && ctrlKey === 'a') {
- event.preventDefault()
- onToggleAllProjects()
- return
- }
- if (event.ctrlKey && ctrlKey === 'd') {
- if (!cursorRow) return
- event.preventDefault()
- onDeleteRow(cursorRow)
- }
+ const openRow = useCallback(
+ (row: SessionPickerRow | undefined) => {
+ if (!row) return
+ onSelectSession(row.session, row.repo)
},
- [rows, cursorIndex, cursorRow, moveCursor, onOpenRow, onDeleteRow, onToggleAllProjects],
+ [onSelectSession],
)
-}
-interface SessionPickerSearchBarProps {
- inputRef: React.RefObject
- listId: string
- open: boolean
- activeDescendantId: string | undefined
- value: string
- onChange: (value: string) => void
- onKeyDown: (event: React.KeyboardEvent) => void
- placeholder: string
- name: string
- trailing?: React.ReactNode
-}
-
-function SessionPickerSearchBar({
- inputRef,
- listId,
- open,
- activeDescendantId,
- value,
- onChange,
- onKeyDown,
- placeholder,
- name,
- trailing,
-}: SessionPickerSearchBarProps) {
- return (
-
-
-
- onChange(event.target.value)}
- onKeyDown={onKeyDown}
- placeholder={placeholder}
- className="h-9 pl-9"
- autoComplete="off"
- name={name}
- />
-
- {trailing}
-
+ const performDelete = useCallback(
+ (session: Session) => {
+ if (session.id === activeSessionID) onDeleteActiveSession()
+ return deleteSession
+ .mutateAsync({ id: session.id, directory: session.location.directory })
+ .catch(() => undefined)
+ },
+ [deleteSession, activeSessionID, onDeleteActiveSession],
)
+
+ const deleteRow = useCallback(
+ (row: SessionPickerRow | undefined) => {
+ if (!row) return
+ if (pendingDeleteKey !== row.key) {
+ setPendingDeleteKey(row.key)
+ return
+ }
+ void performDelete(row.session).finally(() => {
+ setPendingDeleteKey(null)
+ })
+ },
+ [pendingDeleteKey, performDelete],
+ )
+
+ const handleTogglePin = useCallback(
+ (row: SessionPickerRow) => {
+ togglePin.mutate({
+ sessionId: row.session.id,
+ directory: row.session.location.directory,
+ pinned: !pinnedKeys.has(row.key),
+ })
+ },
+ [togglePin, pinnedKeys],
+ )
+
+ const handleRequestDelete = useCallback((session: Session) => {
+ setSessionToDelete(session)
+ }, [])
+
+ const confirmDelete = useCallback(() => {
+ if (!sessionToDelete) return
+ void performDelete(sessionToDelete).finally(() => {
+ setSessionToDelete(null)
+ })
+ }, [sessionToDelete, performDelete])
+
+ const deleteDialogProps = useMemo(
+ () => ({
+ open: sessionToDelete !== null,
+ onOpenChange: (nextOpen: boolean) => {
+ if (!nextOpen) setSessionToDelete(null)
+ },
+ onConfirm: () => {
+ void confirmDelete()
+ },
+ onCancel: () => setSessionToDelete(null),
+ isDeleting: deleteSession.isPending,
+ }),
+ [sessionToDelete, confirmDelete, deleteSession.isPending],
+ )
+
+ return {
+ pinnedKeys,
+ pendingDeleteKey,
+ clearPendingDelete,
+ openRow,
+ deleteRow,
+ handleTogglePin,
+ handleRequestDelete,
+ deleteDialogProps,
+ }
}
interface SessionPickerListProps {
@@ -680,12 +599,21 @@ function SessionPickerContent({
[repoByDirectory, currentRepo],
)
- const { data: sessionPins } = useSessionPins()
- const togglePin = useToggleSessionPin()
- const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
- const deleteSession = useDeleteSession(directories)
-
- const [sessionToDelete, setSessionToDelete] = useState(null)
+ const {
+ pinnedKeys,
+ pendingDeleteKey,
+ clearPendingDelete,
+ openRow,
+ deleteRow,
+ handleTogglePin,
+ handleRequestDelete,
+ deleteDialogProps,
+ } = useSessionPickerRowActions({
+ directories,
+ activeSessionID,
+ onSelectSession,
+ onDeleteActiveSession,
+ })
const sections = useMemo(
() => buildSections(filteredSessions, pinnedKeys, getSessionKey, resolveRepo),
@@ -703,50 +631,25 @@ function SessionPickerContent({
rowIndexByKey,
cursorIndex,
cursorRow,
- pendingDeleteKey,
- setPendingDeleteKey,
registerRef,
- moveCursor,
+ moveCursor: moveCursorRaw,
resetCursor,
- } = useSessionPickerCursor(rows, defaultCursorKey)
+ } = usePickerCursor(rows, defaultCursorKey)
+
+ const moveCursor = useCallback(
+ (index: number) => {
+ clearPendingDelete()
+ moveCursorRaw(index)
+ },
+ [clearPendingDelete, moveCursorRaw],
+ )
useEffect(() => {
resetCursor()
- }, [trimmedQuery, allProjects, resetCursor])
+ clearPendingDelete()
+ }, [trimmedQuery, allProjects, resetCursor, clearPendingDelete])
- const openRow = useCallback(
- (row: SessionPickerRow | undefined) => {
- if (!row) return
- onSelectSession(row.session, row.repo)
- },
- [onSelectSession],
- )
-
- const performDelete = useCallback(
- (session: Session) => {
- if (session.id === activeSessionID) onDeleteActiveSession()
- return deleteSession
- .mutateAsync({ id: session.id, directory: session.location.directory })
- .catch(() => undefined)
- },
- [deleteSession, activeSessionID, onDeleteActiveSession],
- )
-
- const deleteRow = useCallback(
- (row: SessionPickerRow | undefined) => {
- if (!row) return
- if (pendingDeleteKey !== row.key) {
- setPendingDeleteKey(row.key)
- return
- }
- void performDelete(row.session).finally(() => {
- setPendingDeleteKey(null)
- })
- },
- [pendingDeleteKey, performDelete, setPendingDeleteKey],
- )
-
- const handleSearchKeyDown = useSessionPickerKeyNav({
+ const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
@@ -777,28 +680,6 @@ function SessionPickerContent({
}
}, [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 handleRequestDelete = useCallback((session: Session) => {
- setSessionToDelete(session)
- }, [])
-
- const confirmDelete = useCallback(() => {
- if (!sessionToDelete) return
- void performDelete(sessionToDelete).finally(() => {
- setSessionToDelete(null)
- })
- }, [sessionToDelete, performDelete])
-
const labelFor = useCallback(
(row: SessionPickerRow) =>
allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical),
@@ -808,7 +689,7 @@ function SessionPickerContent({
return (
<>
-
- {
- if (!nextOpen) setSessionToDelete(null)
- }}
- onConfirm={() => {
- void confirmDelete()
- }}
- onCancel={() => setSessionToDelete(null)}
- isDeleting={deleteSession.isPending}
- />
+
>
)
}
@@ -925,9 +796,8 @@ function ActivePickerContent({
switchHint,
searchInputRef,
}: ActivePickerContentProps) {
- const windowMs = useActivityWindowMs()
- const windowMinutes = Math.round(windowMs / MS_PER_MINUTE)
- const { groups, isLoading, isError } = useActiveWork(windowMs)
+ const windowMinutes = useActivityWindowMinutes()
+ const { groups, isLoading, isError } = useActiveWork(windowMinutes * MS_PER_MINUTE)
const listId = useId()
const optionBaseId = useId()
@@ -936,19 +806,14 @@ function ActivePickerContent({
const trimmedQuery = query.trim()
const sections = useMemo(() => {
- const definitions: Array<{ id: string; heading: string; items: ActiveWorkItem[] }> = [
- { id: 'needs-input', heading: 'Needs input', items: groups.needsInput },
- { id: 'running', heading: 'Running', items: groups.running },
- { id: 'recent', heading: 'Recent', items: groups.recent },
- ]
const needle = trimmedQuery.toLowerCase()
- return definitions.flatMap((definition) => {
+ return ACTIVE_WORK_GROUPS.flatMap((definition) => {
const rows: SessionPickerRow[] = []
- for (const item of definition.items) {
+ for (const item of groups[definition.key]) {
if (needle && !(item.session.title ?? '').toLowerCase().includes(needle)) continue
rows.push({ key: item.key, session: item.session, repo: item.repo })
}
- return rows.length > 0 ? [{ id: definition.id, heading: definition.heading, rows }] : []
+ return rows.length > 0 ? [{ id: definition.key, heading: definition.heading, rows }] : []
})
}, [groups, trimmedQuery])
@@ -963,62 +828,46 @@ function ActivePickerContent({
rowIndexByKey,
cursorIndex,
cursorRow,
- pendingDeleteKey,
- setPendingDeleteKey,
registerRef,
- moveCursor,
+ moveCursor: moveCursorRaw,
resetCursor,
- } = useSessionPickerCursor(rows, defaultCursorKey)
-
- useEffect(() => {
- resetCursor()
- }, [trimmedQuery, resetCursor])
-
- const { data: sessionPins } = useSessionPins()
- const togglePin = useToggleSessionPin()
- const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
+ } = usePickerCursor(rows, defaultCursorKey)
const directories = useMemo(
() => Array.from(new Set(rows.map((row) => row.session.location.directory))),
[rows],
)
- const deleteSession = useDeleteSession(directories)
- const [sessionToDelete, setSessionToDelete] = useState(null)
+ const {
+ pinnedKeys,
+ pendingDeleteKey,
+ clearPendingDelete,
+ openRow,
+ deleteRow,
+ handleTogglePin,
+ handleRequestDelete,
+ deleteDialogProps,
+ } = useSessionPickerRowActions({
+ directories,
+ activeSessionID,
+ onSelectSession,
+ onDeleteActiveSession,
+ })
- const openRow = useCallback(
- (row: SessionPickerRow | undefined) => {
- if (!row) return
- onSelectSession(row.session, row.repo)
+ const moveCursor = useCallback(
+ (index: number) => {
+ clearPendingDelete()
+ moveCursorRaw(index)
},
- [onSelectSession],
+ [clearPendingDelete, moveCursorRaw],
)
- const performDelete = useCallback(
- (session: Session) => {
- if (session.id === activeSessionID) onDeleteActiveSession()
- return deleteSession
- .mutateAsync({ id: session.id, directory: session.location.directory })
- .catch(() => undefined)
- },
- [deleteSession, activeSessionID, onDeleteActiveSession],
- )
+ useEffect(() => {
+ resetCursor()
+ clearPendingDelete()
+ }, [trimmedQuery, resetCursor, clearPendingDelete])
- const deleteRow = useCallback(
- (row: SessionPickerRow | undefined) => {
- if (!row) return
- if (pendingDeleteKey !== row.key) {
- setPendingDeleteKey(row.key)
- return
- }
- void performDelete(row.session).finally(() => {
- setPendingDeleteKey(null)
- })
- },
- [pendingDeleteKey, performDelete, setPendingDeleteKey],
- )
-
- const handleSearchKeyDown = useSessionPickerKeyNav({
+ const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
@@ -1027,40 +876,18 @@ function ActivePickerContent({
onDeleteRow: deleteRow,
})
- const handleTogglePin = useCallback(
- (row: SessionPickerRow) => {
- togglePin.mutate({
- sessionId: row.session.id,
- directory: row.session.location.directory,
- pinned: !pinnedKeys.has(row.key),
- })
- },
- [togglePin, pinnedKeys],
- )
-
- const handleRequestDelete = useCallback((session: Session) => {
- setSessionToDelete(session)
- }, [])
-
- const confirmDelete = useCallback(() => {
- if (!sessionToDelete) return
- void performDelete(sessionToDelete).finally(() => {
- setSessionToDelete(null)
- })
- }, [sessionToDelete, performDelete])
-
const emptyState = isLoading
? 'Loading sessions...'
: isError
? 'Failed to load active sessions'
: trimmedQuery
? 'No sessions found'
- : `No active or recent sessions in the last ${windowMinutes} minutes`
+ : formatActivityEmptyMessage(windowMinutes)
return (
<>
-
- {
- if (!nextOpen) setSessionToDelete(null)
- }}
- onConfirm={() => {
- void confirmDelete()
- }}
- onCancel={() => setSessionToDelete(null)}
- isDeleting={deleteSession.isPending}
- />
+
>
)
}
diff --git a/frontend/src/components/session/usePickerKeyboardNav.tsx b/frontend/src/components/session/usePickerKeyboardNav.tsx
new file mode 100644
index 00000000..7454cd34
--- /dev/null
+++ b/frontend/src/components/session/usePickerKeyboardNav.tsx
@@ -0,0 +1,209 @@
+/* eslint-disable react-refresh/only-export-components */
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { Search } from 'lucide-react'
+import { Input } from '@/components/ui/input'
+
+const PAGE_STEP = 10
+
+export interface PickerRow {
+ key: string
+}
+
+export function optionId(baseId: string, index: number): string {
+ return `${baseId}-option-${index}`
+}
+
+export interface PickerCursorState {
+ rowIndexByKey: Map
+ cursorIndex: number
+ cursorRow: Row | undefined
+ registerRef: (key: string, node: HTMLDivElement | null) => void
+ moveCursor: (index: number) => void
+ resetCursor: () => void
+}
+
+export function usePickerCursor(
+ rows: Row[],
+ defaultCursorKey: string | null,
+): PickerCursorState {
+ const rowRefs = useRef(new Map())
+ const [cursorKey, setCursorKey] = useState(null)
+
+ const rowIndexByKey = useMemo(
+ () => new Map(rows.map((row, index) => [row.key, index])),
+ [rows],
+ )
+
+ 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
+
+ const registerRef = 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)
+ },
+ [rows],
+ )
+
+ const resetCursor = useCallback(() => {
+ setCursorKey(null)
+ }, [])
+
+ return {
+ rowIndexByKey,
+ cursorIndex,
+ cursorRow,
+ registerRef,
+ moveCursor,
+ resetCursor,
+ }
+}
+
+export interface PickerKeyNavOptions {
+ rows: Row[]
+ cursorIndex: number
+ cursorRow: Row | undefined
+ moveCursor: (index: number) => void
+ onOpenRow: (row: Row) => void
+ onDeleteRow?: (row: Row) => void
+ onToggleAllProjects?: () => void
+}
+
+export function usePickerKeyNav({
+ rows,
+ cursorIndex,
+ cursorRow,
+ moveCursor,
+ onOpenRow,
+ onDeleteRow,
+ onToggleAllProjects,
+}: PickerKeyNavOptions): (event: React.KeyboardEvent) => void {
+ return useCallback(
+ (event: React.KeyboardEvent) => {
+ if (event.nativeEvent.isComposing) return
+ if (event.metaKey || event.altKey) return
+
+ const moveBy = (delta: number, wrap: boolean) => {
+ if (rows.length === 0) return
+ const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
+ const raw = base + delta
+ const next = wrap
+ ? ((raw % rows.length) + rows.length) % rows.length
+ : Math.max(0, Math.min(rows.length - 1, raw))
+ moveCursor(next)
+ }
+
+ const key = event.key
+ const ctrlKey = event.key.toLowerCase()
+
+ if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
+ event.preventDefault()
+ moveBy(1, true)
+ return
+ }
+ if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
+ event.preventDefault()
+ moveBy(-1, true)
+ return
+ }
+ if (key === 'PageDown') {
+ event.preventDefault()
+ moveBy(PAGE_STEP, false)
+ return
+ }
+ if (key === 'PageUp') {
+ event.preventDefault()
+ moveBy(-PAGE_STEP, false)
+ return
+ }
+ if (key === 'Enter') {
+ if (!cursorRow) return
+ event.preventDefault()
+ onOpenRow(cursorRow)
+ return
+ }
+ if (onToggleAllProjects && event.ctrlKey && ctrlKey === 'a') {
+ event.preventDefault()
+ onToggleAllProjects()
+ return
+ }
+ if (onDeleteRow && event.ctrlKey && ctrlKey === 'd') {
+ if (!cursorRow) return
+ event.preventDefault()
+ onDeleteRow(cursorRow)
+ }
+ },
+ [rows, cursorIndex, cursorRow, moveCursor, onOpenRow, onDeleteRow, onToggleAllProjects],
+ )
+}
+
+export interface PickerSearchBarProps {
+ inputRef: React.RefObject
+ listId: string
+ open: boolean
+ activeDescendantId: string | undefined
+ value: string
+ onChange: (value: string) => void
+ onKeyDown: (event: React.KeyboardEvent) => void
+ placeholder: string
+ name: string
+ trailing?: React.ReactNode
+}
+
+export function PickerSearchBar({
+ inputRef,
+ listId,
+ open,
+ activeDescendantId,
+ value,
+ onChange,
+ onKeyDown,
+ placeholder,
+ name,
+ trailing,
+}: PickerSearchBarProps) {
+ return (
+
+
+
+ onChange(event.target.value)}
+ onKeyDown={onKeyDown}
+ placeholder={placeholder}
+ className="h-9 pl-9"
+ autoComplete="off"
+ name={name}
+ />
+
+ {trailing}
+
+ )
+}
diff --git a/frontend/src/components/settings/ActivitySettings.test.tsx b/frontend/src/components/settings/ActivitySettings.test.tsx
index 8bc67cb5..8f461245 100644
--- a/frontend/src/components/settings/ActivitySettings.test.tsx
+++ b/frontend/src/components/settings/ActivitySettings.test.tsx
@@ -49,6 +49,13 @@ describe('ActivitySettings', () => {
expect(screen.getByRole('combobox', { name: 'Recent activity window' })).toHaveTextContent('2 hours')
})
+ it('shows a stored window that is not a preset option', () => {
+ mockUseSettings({ preferences: { ...basePreferences, activityWindowMinutes: 45 } })
+ render()
+
+ expect(screen.getByRole('combobox', { name: 'Recent activity window' })).toHaveTextContent('45 minutes')
+ })
+
it('saves the chosen window in minutes', async () => {
const user = userEvent.setup()
const updateSettings = vi.fn()
diff --git a/frontend/src/components/settings/ActivitySettings.tsx b/frontend/src/components/settings/ActivitySettings.tsx
index 82166205..8e1f1e09 100644
--- a/frontend/src/components/settings/ActivitySettings.tsx
+++ b/frontend/src/components/settings/ActivitySettings.tsx
@@ -1,3 +1,4 @@
+import { useMemo } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
@@ -8,6 +9,15 @@ export function ActivitySettings() {
const { preferences, updateSettings } = useSettings()
const activityWindowMinutes = preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
+ const windowOptions = useMemo(() => {
+ const options: number[] = [...ACTIVITY_WINDOW_MINUTE_OPTIONS]
+ if (!options.includes(activityWindowMinutes)) {
+ options.push(activityWindowMinutes)
+ options.sort((a, b) => a - b)
+ }
+ return options
+ }, [activityWindowMinutes])
+
return (
Activity
@@ -27,7 +37,7 @@ export function ActivitySettings() {
- {ACTIVITY_WINDOW_MINUTE_OPTIONS.map((minutes) => (
+ {windowOptions.map((minutes) => (
{formatActivityWindow(minutes)}
diff --git a/frontend/src/components/ui/activity-spinner.test.tsx b/frontend/src/components/ui/activity-spinner.test.tsx
index 69a9eaeb..9eac8fa4 100644
--- a/frontend/src/components/ui/activity-spinner.test.tsx
+++ b/frontend/src/components/ui/activity-spinner.test.tsx
@@ -1,14 +1,7 @@
-import { act, cleanup, render } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { stubMatchMedia } from '@/test/test-utils'
+import { cleanup, render } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { ActivitySpinner, SPINNER_FRAMES, brailleDots } from './activity-spinner'
-const advanceFrames = (count: number) => {
- act(() => {
- vi.advanceTimersByTime(80 * count)
- })
-}
-
const circles = (root: ParentNode) => Array.from(root.querySelectorAll('circle'))
const litIndexes = (root: ParentNode) =>
@@ -21,24 +14,17 @@ const litIndexesFor = (frame: string) =>
.map((lit, index) => (lit ? index : -1))
.filter((index) => index >= 0)
-const pattern = (root: ParentNode) => circles(root).map((circle) => circle.getAttribute('fill-opacity'))
-
describe('brailleDots', () => {
it('lights dots 1, 2 and 4 for the first frame', () => {
expect(brailleDots('⠋')).toEqual([true, true, false, true, false, false, false, false])
})
- it('lights dots 1 through 4 for the fourth frame', () => {
+ it('lights dots 1 through 4 for the last frame', () => {
expect(brailleDots('⠏')).toEqual([true, true, true, true, false, false, false, false])
})
})
describe('ActivitySpinner', () => {
- beforeEach(() => {
- vi.useFakeTimers()
- stubMatchMedia(false)
- })
-
afterEach(() => {
cleanup()
vi.useRealTimers()
@@ -52,67 +38,35 @@ describe('ActivitySpinner', () => {
expect(container.querySelector('svg')).toHaveAttribute('aria-hidden', 'true')
})
- it('advances one frame every 80ms and wraps after the last frame', () => {
+ it('steps every dot through all frames in order with a discrete, endless 80ms-per-frame animation', () => {
const { container } = render()
- expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[0]))
+ circles(container).forEach((circle, dotIndex) => {
+ const animate = circle.querySelector('animate')
+ expect(animate).toHaveAttribute('attributeName', 'fill-opacity')
+ expect(animate).toHaveAttribute('calcMode', 'discrete')
+ expect(animate).toHaveAttribute('repeatCount', 'indefinite')
+ expect(animate).toHaveAttribute('dur', `${80 * SPINNER_FRAMES.length}ms`)
- advanceFrames(1)
- expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[1]))
-
- advanceFrames(1)
- expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[2]))
-
- advanceFrames(SPINNER_FRAMES.length - 2)
- expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[0]))
+ const values = animate?.getAttribute('values')?.split(';')
+ expect(values).toEqual(SPINNER_FRAMES.map((frame) => (brailleDots(frame)[dotIndex] ? '1' : '0.25')))
+ })
})
- it('drives every mounted spinner from a single shared ticker', () => {
- const { container } = render(
+ it('schedules no JavaScript timers however many spinners are mounted', () => {
+ vi.useFakeTimers()
+
+ render(
<>
+
>,
)
- expect(vi.getTimerCount()).toBe(1)
-
- const [first, second] = Array.from(container.querySelectorAll('svg'))
- expect(pattern(first)).toEqual(pattern(second))
-
- advanceFrames(1)
-
- expect(litIndexes(first)).toEqual(litIndexesFor(SPINNER_FRAMES[1]))
- expect(pattern(first)).toEqual(pattern(second))
- })
-
- it('clears the shared ticker when the last spinner unmounts', () => {
- const { unmount } = render(
- <>
-
-
- >,
- )
-
- expect(vi.getTimerCount()).toBe(1)
-
- unmount()
-
expect(vi.getTimerCount()).toBe(0)
})
- it('keeps animating when the user prefers reduced motion', () => {
- stubMatchMedia(true)
-
- const { container } = render()
-
- expect(vi.getTimerCount()).toBe(1)
-
- advanceFrames(1)
-
- expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[1]))
- })
-
it('keeps every dot inside the cell and clear of its neighbours', () => {
const { container } = render()
diff --git a/frontend/src/components/ui/activity-spinner.tsx b/frontend/src/components/ui/activity-spinner.tsx
index 1ee8d71f..bd0ea4ad 100644
--- a/frontend/src/components/ui/activity-spinner.tsx
+++ b/frontend/src/components/ui/activity-spinner.tsx
@@ -1,9 +1,9 @@
-import { useSyncExternalStore } from 'react'
import { cn } from '@/lib/utils'
export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const
const FRAME_INTERVAL_MS = 80
+const CYCLE_DURATION = `${FRAME_INTERVAL_MS * SPINNER_FRAMES.length}ms`
const BRAILLE_BASE = 0x2800
const DOT_GRID: ReadonlyArray = [
@@ -19,41 +19,9 @@ const DOT_GRID: ReadonlyArray = [
const COLUMN_X = [2.25, 6.75] as const
const ROW_Y = [2.25, 6, 9.75, 13.5] as const
const DOT_RADIUS = 1.6
+const LIT_DOT_OPACITY = 1
const UNLIT_DOT_OPACITY = 0.25
-let frameIndex = 0
-const listeners = new Set<() => void>()
-let ticker: ReturnType | null = null
-
-function emit() {
- for (const listener of listeners) {
- listener()
- }
-}
-
-function subscribe(listener: () => void) {
- listeners.add(listener)
- if (ticker === null) {
- ticker = setInterval(() => {
- frameIndex = (frameIndex + 1) % SPINNER_FRAMES.length
- emit()
- }, FRAME_INTERVAL_MS)
- }
-
- return () => {
- listeners.delete(listener)
- if (listeners.size === 0 && ticker !== null) {
- clearInterval(ticker)
- ticker = null
- frameIndex = 0
- }
- }
-}
-
-function getSnapshot() {
- return frameIndex
-}
-
/**
* Decodes one braille frame into its eight dot positions, ordered by braille dot numbering:
* dot1, dot2 and dot3 are the left column top-to-bottom, dot4, dot5 and dot6 the right column
@@ -64,17 +32,21 @@ export function brailleDots(frame: string): boolean[] {
return DOT_GRID.map((_, index) => (bits & (1 << index)) !== 0)
}
+const FRAME_DOTS = SPINNER_FRAMES.map(brailleDots)
+
+const DOT_OPACITY_TIMELINES = DOT_GRID.map((_, index) =>
+ FRAME_DOTS.map((dots) => (dots[index] ? LIT_DOT_OPACITY : UNLIT_DOT_OPACITY)),
+)
+
/**
* Braille spinner mirroring the OpenCode TUI activity spinner as an inline SVG cell so the dots
- * stay visible at small text sizes. Every mounted instance shares one module-level 80 ms ticker,
- * which starts with the first subscriber and stops with the last. It animates regardless of
+ * stay visible at small text sizes. Each dot steps through its opacity for every frame with a
+ * declarative SVG `` derived from `SPINNER_FRAMES`, so frames advance in the browser
+ * with no JavaScript or React render per frame. It animates regardless of
* `prefers-reduced-motion`: a still frame is indistinguishable from a stalled spinner, and the
* motion is a small in-place status cue like the platform activity indicators.
*/
export function ActivitySpinner({ className }: { className?: string }) {
- const frame = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
- const dots = brailleDots(SPINNER_FRAMES[frame])
-
return (
+ fillOpacity={DOT_OPACITY_TIMELINES[index][0]}
+ >
+
+
))}
)
diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx
index c494864b..a83599c2 100644
--- a/frontend/src/contexts/EventContext.test.tsx
+++ b/frontend/src/contexts/EventContext.test.tsx
@@ -240,7 +240,7 @@ describe('EventProvider permissions and forms', () => {
mocks.replyForm.mockResolvedValue(undefined)
mocks.cancelForm.mockResolvedValue(undefined)
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
- useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), parents: new Map(), runningShells: new Map(), shellRevisions: new Map(), shellRevision: 0, revision: 0 })
+ useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), parents: new Map(), directories: new Map(), runningShells: new Map(), shellRevisions: new Map(), shellRevision: 0, revision: 0 })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories: vi.fn(),
@@ -275,6 +275,18 @@ describe('EventProvider permissions and forms', () => {
})
})
+ it('records the session directory for a pending permission loaded without an SSE status event', async () => {
+ mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
+ mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
+
+ render(, { wrapper: createWrapper() })
+
+ await waitFor(() => {
+ expect(useSessionStatus.getState().directories.get('session-1')).toBe('/repo')
+ })
+ expect(useSessionStatus.getState().statuses.has('session-1')).toBe(false)
+ })
+
it('clears stale pending permissions for a session', async () => {
mocks.listPendingPermissions
.mockResolvedValueOnce([pendingPermission])
diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx
index 02b3a48f..33dd5514 100644
--- a/frontend/src/contexts/EventContext.tsx
+++ b/frontend/src/contexts/EventContext.tsx
@@ -126,7 +126,7 @@ function reconcileBySessionForDirectory(
prev: Record,
directory: string,
items: T[],
- sessionDirectories: Map,
+ sessionDirectories: ReadonlyMap,
): Record {
const grouped = groupBySession(items)
const next = { ...prev }
@@ -273,7 +273,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const [formsBySession, setFormsBySession] = useState({})
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
- const sessionDirectoriesRef = useRef