fix(activity): animate the braille spinner in SVG and tighten the activity lists

- Draw the TUI braille spinner as a 2x4 SVG dot cell stepped by declarative
  <animate> timelines derived from SPINNER_FRAMES: no JavaScript timer or React
  render per frame, and it keeps animating under prefers-reduced-motion so an
  active session never looks stalled
- Enlarge the spinner cell and dots so it stays legible next to 14px text
- Add a compact ActivityList variant for the mobile More drawer and Repos sheet:
  one flat list capped at five rows, single-line rows, no group subheadings
- Let ActivityList callers own navigation so a row tap navigates once instead of
  pushing a duplicate history entry
- Share the picker keyboard navigation between the session and project tabs and
  reuse the shared session merge helpers in the sidebar repo groups
This commit is contained in:
Chris Scott committed 2026-10-16 11:42:03 -04:00
1 parent d8f2fcf29c
commit 8b6251d83b
24 files changed
+858 -787

No files matched your search

@@ -14,7 +14,7 @@ vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: mocks.useActiveWork,
}))
const WINDOW_MS = 30 * 60_000
const WINDOW_MINUTES = 30
const NOW = Date.now()
function createSession(id: string, title: string, updated = NOW - 60_000): Session {
@@ -71,11 +71,16 @@ function setGroups(groups: {
const renderList = (
onNavigate = vi.fn(),
path = '/',
props: { hideWhenEmpty?: boolean; title?: string; variant?: 'full' | 'compact' } = {},
props: {
hideWhenEmpty?: boolean
title?: string
variant?: 'full' | 'compact'
minutes?: number
} = {},
) =>
render(
<MemoryRouter initialEntries={[path]}>
<ActivityList windowMs={WINDOW_MS} onNavigate={onNavigate} {...props} />
<ActivityList minutes={WINDOW_MINUTES} onNavigate={onNavigate} {...props} />
</MemoryRouter>,
)
@@ -118,6 +123,14 @@ describe('ActivityList', () => {
expect(screen.getByText('No active or recent sessions in the last 30 minutes')).toBeInTheDocument()
})
it('renders the empty state with an hour-scale window', () => {
setGroups({})
renderList(vi.fn(), '/', { minutes: 1440 })
expect(screen.getByText('No active or recent sessions in the last 24 hours')).toBeInTheDocument()
})
it('calls onNavigate with the item when a row is clicked', () => {
const onNavigate = vi.fn()
const item = createItem({ state: 'recent', session: createSession('c1', 'Recent'), repo: createRepo(3, 'Gamma') })
@@ -4,17 +4,22 @@ import { useActiveWork } from '@/hooks/useActiveWork'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { parseRepoRoute } from '@/lib/navigation'
import { cn, formatShortRelativeTime, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
import type { ActiveWorkItem } from '@/lib/activeWork'
import {
ACTIVE_WORK_GROUPS,
MS_PER_MINUTE,
formatActivityEmptyMessage,
type ActiveWorkItem,
} from '@/lib/activeWork'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
const MS_PER_MINUTE = 60_000
const COMPACT_MAX_ITEMS = 5
const FULL_ICON_CLASS = 'h-4 w-4'
const COMPACT_ICON_CLASS = 'h-3.5 w-3.5'
interface ActivityListProps {
windowMs: number
/** Activity window in minutes. */
minutes: number
/** Called when a row is chosen; the caller owns navigation so each surface can apply its own history and close rules. */
onNavigate: (item: ActiveWorkItem) => void
hideWhenEmpty?: boolean
@@ -137,14 +142,14 @@ function ActivityGroup({ heading, items, currentSessionID, currentRepoId, onSele
}
export function ActivityList({
windowMs,
minutes,
onNavigate,
hideWhenEmpty = false,
title,
variant = 'full',
}: ActivityListProps) {
const location = useLocation()
const { groups, isLoading, isError } = useActiveWork(windowMs)
const { groups, isLoading, isError } = useActiveWork(minutes * MS_PER_MINUTE)
const route = parseRepoRoute(location.pathname)
@@ -163,11 +168,8 @@ export function ActivityList({
if (isEmpty) {
if (hideWhenEmpty) return null
const minutes = Math.round(windowMs / MS_PER_MINUTE)
return (
<p className="p-4 text-sm text-muted-foreground">
No active or recent sessions in the last {minutes} minutes
</p>
<p className="p-4 text-sm text-muted-foreground">{formatActivityEmptyMessage(minutes)}</p>
)
}
@@ -203,27 +205,16 @@ export function ActivityList({
))
) : (
<>
<ActivityGroup
heading="Needs input"
items={groups.needsInput}
currentSessionID={route.sessionId}
currentRepoId={route.repoId}
onSelect={onNavigate}
/>
<ActivityGroup
heading="Running"
items={groups.running}
currentSessionID={route.sessionId}
currentRepoId={route.repoId}
onSelect={onNavigate}
/>
<ActivityGroup
heading="Recent"
items={groups.recent}
currentSessionID={route.sessionId}
currentRepoId={route.repoId}
onSelect={onNavigate}
/>
{ACTIVE_WORK_GROUPS.map((group) => (
<ActivityGroup
key={group.key}
heading={group.heading}
items={groups[group.key]}
currentSessionID={route.sessionId}
currentRepoId={route.repoId}
onSelect={onNavigate}
/>
))}
</>
)}
</section>
@@ -1,4 +1,4 @@
import { useActivityWindowMs } from '@/hooks/useActiveWork'
import { useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { ActivityList } from '@/components/activity/ActivityList'
/**
@@ -6,11 +6,11 @@ import { ActivityList } from '@/components/activity/ActivityList'
* Reads the network through `useActiveWork`, so it must only be mounted while visible.
*/
export function CompactActivityList({ onNavigate }: { onNavigate: (path: string) => void }) {
const windowMs = useActivityWindowMs()
const minutes = useActivityWindowMinutes()
return (
<ActivityList
windowMs={windowMs}
minutes={minutes}
title="Activity"
hideWhenEmpty
variant="compact"
@@ -23,12 +23,12 @@ vi.mock('react-router-dom', async () => {
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
useActivityWindowMs: vi.fn(),
useActivityWindowMinutes: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMs: activityMocks.useActivityWindowMs,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
useRepoActivityState: () => null,
}))
@@ -155,7 +155,7 @@ describe('MoreDrawer', () => {
cloneStatus: 'ready',
clonedAt: 0,
})
activityMocks.useActivityWindowMs.mockReturnValue(30 * 60_000)
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
setActivityGroups({})
})
@@ -35,12 +35,12 @@ const { sessionsData, sessionsHookCalls, permissionSessions, createSessionDirect
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
useActivityWindowMs: vi.fn(),
useActivityWindowMinutes: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMs: activityMocks.useActivityWindowMs,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
useRepoActivityState: () => null,
}))
@@ -168,7 +168,7 @@ describe('RepoQuickSwitchSheet', () => {
sessionsData.splice(0, sessionsData.length)
sessionsHookCalls.splice(0, sessionsHookCalls.length)
permissionSessions.current.clear()
activityMocks.useActivityWindowMs.mockReturnValue(30 * 60_000)
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
setActivityGroups({})
})
@@ -12,13 +12,13 @@ import { useToolPanel } from '@/hooks/useToolPanel'
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
useActiveWorkCounts: vi.fn(),
useActivityWindowMs: vi.fn(),
useActivityWindowMinutes: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActiveWorkCounts: activityMocks.useActiveWorkCounts,
useActivityWindowMs: activityMocks.useActivityWindowMs,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
}))
vi.mock('@/components/file-browser/FileBrowser', () => ({
@@ -91,7 +91,7 @@ function search(): URLSearchParams {
return new URLSearchParams(screen.getByTestId('search').textContent ?? '')
}
const WINDOW_MS = 30 * 60_000
const WINDOW_MINUTES = 30
const NOW = Date.now()
function createSession(id: string, title: string, updated = NOW - 60_000): Session {
@@ -152,7 +152,7 @@ function HomeHarness() {
beforeEach(() => {
vi.clearAllMocks()
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 0, running: 0 })
activityMocks.useActivityWindowMs.mockReturnValue(WINDOW_MS)
activityMocks.useActivityWindowMinutes.mockReturnValue(WINDOW_MINUTES)
setActivityGroups()
})
@@ -26,41 +26,56 @@ import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToo
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { ActivityList } from '@/components/activity/ActivityList'
import { ActivityCountPill } from '@/components/activity/ActivityCountPill'
import { useActiveWorkCounts, useActivityWindowMs } from '@/hooks/useActiveWork'
import { useActiveWorkCounts, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { formatActivityWindow } from '@/lib/activeWork'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { restoreOverlayFocus } from '@/lib/overlayFocus'
import { cn } from '@/lib/utils'
const MS_PER_MINUTE = 60_000
const PANEL_WIDTH_CLASSES: Partial<Record<PanelTool, string>> = {
activity: 'w-80',
}
function ActivityWindowLabel() {
const windowMs = useActivityWindowMs()
const minutes = useActivityWindowMinutes()
return (
<span className="shrink-0 text-xs text-muted-foreground">
Last {formatActivityWindow(Math.round(windowMs / MS_PER_MINUTE))}
Last {formatActivityWindow(minutes)}
</span>
)
}
function ActivityPanelBody() {
const navigate = useNavigate()
const windowMs = useActivityWindowMs()
const minutes = useActivityWindowMinutes()
return (
<div className="min-h-0 flex-1 overflow-y-auto">
<ActivityList
windowMs={windowMs}
minutes={minutes}
onNavigate={(item) => navigate({ pathname: item.path, search: '?panel=activity' })}
/>
</div>
)
}
function ActivityRailIndicator() {
const { needsInput, running } = useActiveWorkCounts()
const total = needsInput + running
const label = total > 0 ? `Activity, ${needsInput} needs input, ${running} running` : 'Activity'
return (
<>
<span className="sr-only">{label}</span>
<ActivityCountPill
needsInput={needsInput}
running={running}
className="absolute -right-0.5 -top-0.5"
/>
</>
)
}
interface ToolSidePanelProps {
panel: ToolPanelState
filesBasePath: string | undefined
@@ -81,11 +96,14 @@ interface RailButtonProps {
item: MoreDrawerItem
active: boolean
onClick: () => void
ariaLabel?: string
/**
* Rendered inside the button. When present, the indicator owns the button's accessible name,
* so the item label is not applied as an `aria-label`.
*/
indicator?: ReactNode
}
function RailButton({ item, active, onClick, ariaLabel, indicator }: RailButtonProps) {
function RailButton({ item, active, onClick, indicator }: RailButtonProps) {
const Icon = item.icon
return (
<Tooltip delayDuration={0}>
@@ -93,7 +111,7 @@ function RailButton({ item, active, onClick, ariaLabel, indicator }: RailButtonP
<button
type="button"
onClick={onClick}
aria-label={ariaLabel ?? item.label}
aria-label={indicator ? undefined : item.label}
aria-pressed={active}
className={cn(
'relative rounded-md p-2 transition-colors',
@@ -137,7 +155,6 @@ export function ToolSidePanel({
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
const openNavItem = useOpenNavItem()
const { needsInput, running } = useActiveWorkCounts()
const railRef = useRef<HTMLElement>(null)
const previousActiveToolRef = useRef(activeTool)
@@ -160,18 +177,6 @@ export function ToolSidePanel({
}
const activeLabel = panelTools.find(({ tool }) => tool === activeTool)?.item.label
const activityTotal = needsInput + running
const activityAriaLabel =
activityTotal > 0 ? `Activity, ${needsInput} needs input, ${running} running` : undefined
const activityIndicator =
activityTotal > 0 ? (
<ActivityCountPill
needsInput={needsInput}
running={running}
className="absolute -right-0.5 -top-0.5"
/>
) : undefined
if (panelTools.length === 0 && actionItems.length === 0) return null
const renderTool = (tool: PanelTool) => {
@@ -277,8 +282,7 @@ export function ToolSidePanel({
item={item}
active={tool === activeTool}
onClick={() => toggleTool(tool)}
ariaLabel={tool === 'activity' ? activityAriaLabel : undefined}
indicator={tool === 'activity' ? activityIndicator : undefined}
indicator={tool === 'activity' ? <ActivityRailIndicator /> : undefined}
/>
))}
{actionItems.length > 0 ? <div className="my-1 h-px w-6 shrink-0 bg-border" role="separator" /> : null}
@@ -7,6 +7,23 @@ import { partitionSessions, selectRootSessions } from '@/components/session/sess
export const SIDEBAR_SESSIONS_PER_REPO = 10
/** Collects the loaded session from each query result, dropping unresolved queries. */
export const combineQuerySessions = (results: Array<{ data?: Session }>): Session[] =>
results.flatMap((result) => (result.data ? [result.data] : []))
/** Appends extra sessions after the base list, deduplicating by id within both lists. */
export function mergeExtraSessions(sessions: Session[], extraSessions: Session[]): Session[] {
if (extraSessions.length === 0) return sessions
const seen = new Set(sessions.map((session) => session.id))
const extras: Session[] = []
for (const session of extraSessions) {
if (seen.has(session.id)) continue
seen.add(session.id)
extras.push(session)
}
return extras.length === 0 ? sessions : [...sessions, ...extras]
}
export interface SidebarSessionItem {
key: string
session: Session
@@ -50,7 +67,7 @@ export function buildRepoByDirectory(repos: Repo[]): Map<string, Repo> {
return new Map(repos.map((repo) => [repo.fullPath, repo]))
}
function normalizeDirectory(directory?: string | null): string | null {
export function normalizeDirectory(directory?: string | null): string | null {
return directory?.replace(/\/+$/, '') ?? null
}
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { Search } from 'lucide-react'
import { useEffect, useId, useMemo, useState } from 'react'
import type { Repo } from '@/api/types'
import { Input } from '@/components/ui/input'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { cn, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
const PAGE_STEP = 10
import {
PickerSearchBar,
optionId,
usePickerCursor,
usePickerKeyNav,
} from '@/components/session/usePickerKeyboardNav'
interface ProjectPickerContentProps {
open: boolean
@@ -15,8 +17,9 @@ interface ProjectPickerContentProps {
searchInputRef: React.RefObject<HTMLInputElement | null>
}
function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
interface ProjectPickerRow {
key: string
repo: Repo
}
export function ProjectPickerContent({
@@ -27,12 +30,10 @@ export function ProjectPickerContent({
searchInputRef,
}: ProjectPickerContentProps) {
const { repos, isLoading } = useNavigableRepos()
const rowRefs = useRef(new Map<number, HTMLDivElement>())
const listId = useId()
const optionBaseId = useId()
const [query, setQuery] = useState('')
const [cursorIndex, setCursorIndex] = useState<number | null>(null)
const trimmedQuery = query.trim()
@@ -46,111 +47,49 @@ export function ProjectPickerContent({
})
}, [repos, trimmedQuery])
const defaultCursorIndex = useMemo(() => {
if (!trimmedQuery && currentRepo) {
const index = filteredRepos.findIndex((repo) => repo.id === currentRepo.id)
if (index >= 0) return index
}
return filteredRepos.length > 0 ? 0 : -1
}, [trimmedQuery, currentRepo, filteredRepos])
const effectiveCursorIndex = cursorIndex ?? defaultCursorIndex
const cursorRepo = effectiveCursorIndex >= 0 ? filteredRepos[effectiveCursorIndex] : undefined
useEffect(() => {
setCursorIndex(null)
}, [trimmedQuery])
const setRowRef = useCallback((key: number, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRepo) return
const node = rowRefs.current.get(cursorRepo.id)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRepo])
const moveCursor = useCallback(
(index: number) => {
if (!filteredRepos[index]) return
setCursorIndex(index)
},
const rows = useMemo<ProjectPickerRow[]>(
() => filteredRepos.map((repo) => ({ key: String(repo.id), repo })),
[filteredRepos],
)
const handleSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const defaultCursorKey = useMemo(() => {
if (!trimmedQuery && currentRepo) {
const current = rows.find((row) => row.repo.id === currentRepo.id)
if (current) return current.key
}
return rows[0]?.key ?? null
}, [trimmedQuery, currentRepo, rows])
const key = event.key
const ctrlKey = event.key.toLowerCase()
const moveBy = (delta: number, wrap: boolean) => {
if (filteredRepos.length === 0) return
const base = effectiveCursorIndex < 0 ? (delta > 0 ? -1 : 0) : effectiveCursorIndex
const raw = base + delta
const next = wrap
? ((raw % filteredRepos.length) + filteredRepos.length) % filteredRepos.length
: Math.max(0, Math.min(filteredRepos.length - 1, raw))
moveCursor(next)
}
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 (!cursorRepo) return
event.preventDefault()
onSelectRepo(cursorRepo)
}
},
[filteredRepos, effectiveCursorIndex, moveCursor, cursorRepo, onSelectRepo],
const { cursorIndex, cursorRow, registerRef, moveCursor, resetCursor } = usePickerCursor(
rows,
defaultCursorKey,
)
useEffect(() => {
resetCursor()
}, [trimmedQuery, resetCursor])
const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: (row) => onSelectRepo(row.repo),
})
return (
<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={effectiveCursorIndex >= 0 ? optionId(optionBaseId, effectiveCursorIndex) : undefined}
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search projects..."
className="h-9 pl-9"
autoComplete="off"
name="project-picker-search"
/>
</div>
</div>
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search projects..."
name="project-picker-search"
/>
<div
role="listbox"
@@ -158,19 +97,20 @@ export function ProjectPickerContent({
aria-label="Projects"
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{filteredRepos.length === 0 ? (
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">
{isLoading ? 'Loading projects...' : 'No projects found'}
</div>
) : (
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 (
<div
key={repo.id}
ref={(node) => setRowRef(repo.id, node)}
key={row.key}
ref={(node) => registerRef(row.key, node)}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') moveCursor(index)
@@ -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 = {
@@ -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<string, number>
cursorIndex: number
cursorRow: SessionPickerRow | undefined
pendingDeleteKey: string | null
setPendingDeleteKey: React.Dispatch<React.SetStateAction<string | null>>
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<string, HTMLDivElement>())
const [cursorKey, setCursorKey] = useState<string | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(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<string>
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<Session | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
function useSessionPickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow,
onDeleteRow,
onToggleAllProjects,
}: SessionPickerKeyNavOptions): (event: React.KeyboardEvent<HTMLInputElement>) => void {
return useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
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<HTMLInputElement | null>
listId: string
open: boolean
activeDescendantId: string | undefined
value: string
onChange: (value: string) => void
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void
placeholder: string
name: string
trailing?: React.ReactNode
}
function SessionPickerSearchBar({
inputRef,
listId,
open,
activeDescendantId,
value,
onChange,
onKeyDown,
placeholder,
name,
trailing,
}: SessionPickerSearchBarProps) {
return (
<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={inputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeDescendantId}
value={value}
onChange={(event) => onChange(event.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className="h-9 pl-9"
autoComplete="off"
name={name}
/>
</div>
{trailing}
</div>
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<Session | null>(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 (
<>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<SessionPickerSearchBar
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
@@ -893,17 +774,7 @@ function SessionPickerContent({
</div>
</div>
<DeleteSessionDialog
open={sessionToDelete !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setSessionToDelete(null)
}}
onConfirm={() => {
void confirmDelete()
}}
onCancel={() => setSessionToDelete(null)}
isDeleting={deleteSession.isPending}
/>
<DeleteSessionDialog {...deleteDialogProps} />
</>
)
}
@@ -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<Session | null>(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 (
<>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<SessionPickerSearchBar
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
@@ -1098,17 +925,7 @@ function ActivePickerContent({
</div>
</div>
<DeleteSessionDialog
open={sessionToDelete !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setSessionToDelete(null)
}}
onConfirm={() => {
void confirmDelete()
}}
onCancel={() => setSessionToDelete(null)}
isDeleting={deleteSession.isPending}
/>
<DeleteSessionDialog {...deleteDialogProps} />
</>
)
}
@@ -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<Row extends PickerRow> {
rowIndexByKey: Map<string, number>
cursorIndex: number
cursorRow: Row | undefined
registerRef: (key: string, node: HTMLDivElement | null) => void
moveCursor: (index: number) => void
resetCursor: () => void
}
export function usePickerCursor<Row extends PickerRow>(
rows: Row[],
defaultCursorKey: string | null,
): PickerCursorState<Row> {
const rowRefs = useRef(new Map<string, HTMLDivElement>())
const [cursorKey, setCursorKey] = useState<string | null>(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<Row extends PickerRow> {
rows: Row[]
cursorIndex: number
cursorRow: Row | undefined
moveCursor: (index: number) => void
onOpenRow: (row: Row) => void
onDeleteRow?: (row: Row) => void
onToggleAllProjects?: () => void
}
export function usePickerKeyNav<Row extends PickerRow>({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow,
onDeleteRow,
onToggleAllProjects,
}: PickerKeyNavOptions<Row>): (event: React.KeyboardEvent<HTMLInputElement>) => void {
return 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()
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<HTMLInputElement | null>
listId: string
open: boolean
activeDescendantId: string | undefined
value: string
onChange: (value: string) => void
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void
placeholder: string
name: string
trailing?: React.ReactNode
}
export function PickerSearchBar({
inputRef,
listId,
open,
activeDescendantId,
value,
onChange,
onKeyDown,
placeholder,
name,
trailing,
}: PickerSearchBarProps) {
return (
<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={inputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeDescendantId}
value={value}
onChange={(event) => onChange(event.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className="h-9 pl-9"
autoComplete="off"
name={name}
/>
</div>
{trailing}
</div>
)
}
@@ -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(<ActivitySettings />)
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()
@@ -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 (
<div className="space-y-6">
<h2 className="text-lg font-semibold text-foreground">Activity</h2>
@@ -27,7 +37,7 @@ export function ActivitySettings() {
<SelectValue placeholder="Select a window" />
</SelectTrigger>
<SelectContent>
{ACTIVITY_WINDOW_MINUTE_OPTIONS.map((minutes) => (
{windowOptions.map((minutes) => (
<SelectItem key={minutes} value={String(minutes)}>
{formatActivityWindow(minutes)}
</SelectItem>
@@ -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(<ActivitySpinner />)
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(
<>
<ActivitySpinner />
<ActivitySpinner />
<ActivitySpinner />
</>,
)
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(
<>
<ActivitySpinner />
<ActivitySpinner />
</>,
)
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(<ActivitySpinner />)
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(<ActivitySpinner />)
+21 -41
View File
@@ -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<readonly [number, number]> = [
@@ -19,41 +19,9 @@ const DOT_GRID: ReadonlyArray<readonly [number, number]> = [
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<typeof setInterval> | 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 `<animate>` 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 (
<svg
aria-hidden="true"
@@ -88,8 +60,16 @@ export function ActivitySpinner({ className }: { className?: string }) {
cy={ROW_Y[row]}
r={DOT_RADIUS}
fill="currentColor"
fillOpacity={dots[index] ? 1 : UNLIT_DOT_OPACITY}
/>
fillOpacity={DOT_OPACITY_TIMELINES[index][0]}
>
<animate
attributeName="fill-opacity"
values={DOT_OPACITY_TIMELINES[index].join(';')}
dur={CYCLE_DURATION}
calcMode="discrete"
repeatCount="indefinite"
/>
</circle>
))}
</svg>
)
+13 -1
View File
@@ -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(<Harness />, { 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])
+6 -13
View File
@@ -126,7 +126,7 @@ function reconcileBySessionForDirectory<T extends SessionScopedItem>(
prev: Record<string, T[]>,
directory: string,
items: T[],
sessionDirectories: Map<string, string>,
sessionDirectories: ReadonlyMap<string, string>,
): Record<string, T[]> {
const grouped = groupBySession(items)
const next = { ...prev }
@@ -273,7 +273,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const [formsBySession, setFormsBySession] = useState<FormsBySession>({})
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
const prevPermissionCountRef = useRef(0)
const initialFetchDoneRef = useRef(false)
const statusSyncVersionRef = useRef(0)
@@ -304,7 +303,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const rememberSessionDirectory = useCallback((sessionID: string, directory?: string) => {
if (!directory) return
sessionDirectoriesRef.current.set(sessionID, directory)
useSessionStatus.getState().setSessionDirectory(sessionID, directory)
}, [])
const findCachedSessionDirectory = useCallback((sessionID: string): string | null => {
@@ -354,7 +353,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [queryClient])
const findSessionDirectory = useCallback((sessionID: string): string | null => {
const remembered = sessionDirectoriesRef.current.get(sessionID)
const remembered = useSessionStatus.getState().directories.get(sessionID)
if (remembered) return remembered
return findCachedSessionDirectory(sessionID)
}, [findCachedSessionDirectory])
@@ -398,7 +397,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
})
setPermissionsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, permissions, sessionDirectoriesRef.current),
reconcileBySessionForDirectory(prev, directory, permissions, useSessionStatus.getState().directories),
)
}, [rememberSessionDirectory])
@@ -408,7 +407,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
})
setFormsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, forms, sessionDirectoriesRef.current),
reconcileBySessionForDirectory(prev, directory, forms, useSessionStatus.getState().directories),
)
}, [rememberSessionDirectory])
@@ -520,7 +519,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
for (const repo of reposRef.current ?? []) {
if (repo.fullPath) directories.add(repo.fullPath)
}
for (const directory of sessionDirectoriesRef.current.values()) {
for (const directory of useSessionStatus.getState().directories.values()) {
if (directory) directories.add(directory)
}
return [...directories]
@@ -659,9 +658,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
case 'permission.asked': {
const request = event.data
rememberSessionDirectory(request.sessionID, event.directory)
if (event.directory) {
useSessionStatus.getState().setSessionDirectory(request.sessionID, event.directory)
}
addPermission(request)
if (!useSessionStatus.getState().parents.has(request.sessionID)) {
void resolveSessionAncestry([request.sessionID])
@@ -676,9 +672,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
case 'form.created': {
const form = event.data.form
rememberSessionDirectory(form.sessionID, event.directory)
if (event.directory) {
useSessionStatus.getState().setSessionDirectory(form.sessionID, event.directory)
}
addForm(form)
if (!useSessionStatus.getState().parents.has(form.sessionID)) {
void resolveSessionAncestry([form.sessionID])
+51 -49
View File
@@ -6,24 +6,40 @@ import { useForms, usePermissions } from '@/contexts/EventContext'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useSettings } from '@/hooks/useSettings'
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
import { buildActiveWork, collectActiveRoots, activeRepoState, type ActiveWorkGroups } from '@/lib/activeWork'
import type { Repo, Session } from '@/api/types'
import {
buildActiveWork,
buildRepoActivityIndex,
collectActiveRoots,
repoActivityFromIndex,
type ActiveWorkGroups,
} from '@/lib/activeWork'
import {
combineQuerySessions,
mergeExtraSessions,
} from '@/components/navigation/sidebar-session-tree'
import type { Repo } from '@/api/types'
const ACTIVE_WORK_SESSION_LIMIT = 50
const MS_PER_MINUTE = 60_000
/**
* The active-work time window in milliseconds, derived from the user's configured
* The active-work time window in minutes, derived from the user's configured
* `activityWindowMinutes` with the shared default as a fallback.
*/
export function useActivityWindowMs(): number {
export function useActivityWindowMinutes(): number {
const { preferences } = useSettings()
const minutes = preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
return minutes * MS_PER_MINUTE
return preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
}
const combineSessions = (results: Array<{ data?: Session }>): Session[] =>
results.flatMap((result) => (result.data ? [result.data] : []))
/** Pending permission and form session ids, merged once per snapshot into a referentially stable list. */
function usePendingInputSessionIDs(): string[] {
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
const pendingFormSessionIDs = useForms().pendingSessionIDs
return useMemo(
() => [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
[pendingPermissionSessionIDs, pendingFormSessionIDs],
)
}
/**
* Distinct active roots for a badge: needs-input roots and running roots that are not also
@@ -33,14 +49,9 @@ export function useActiveWorkCounts(): { needsInput: number; running: number } {
const statuses = useSessionStatus((state) => state.statuses)
const parents = useSessionStatus((state) => state.parents)
const runningShells = useSessionStatus((state) => state.runningShells)
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
const pendingFormSessionIDs = useForms().pendingSessionIDs
const pendingInputSessionIDs = usePendingInputSessionIDs()
return useMemo(() => {
const pendingInputSessionIDs = new Set([
...pendingPermissionSessionIDs,
...pendingFormSessionIDs,
])
const roots = collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs })
let running = 0
@@ -49,7 +60,7 @@ export function useActiveWorkCounts(): { needsInput: number; running: number } {
}
return { needsInput: roots.needsInput.size, running }
}, [statuses, parents, runningShells, pendingPermissionSessionIDs, pendingFormSessionIDs])
}, [statuses, parents, runningShells, pendingInputSessionIDs])
}
/**
@@ -57,22 +68,19 @@ export function useActiveWorkCounts(): { needsInput: number; running: number } {
* changes. Reads only the session-status store and the pending queues, with no network.
*/
export function useRepoActivityState(repo: Repo): 'needs-input' | 'running' | null {
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
const pendingFormSessionIDs = useForms().pendingSessionIDs
const pendingInputSessionIDs = useMemo(
() => [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
[pendingPermissionSessionIDs, pendingFormSessionIDs],
)
const pendingInputSessionIDs = usePendingInputSessionIDs()
return useSessionStatus((state) =>
activeRepoState({
repoActivityFromIndex(
repo,
statuses: state.statuses,
parents: state.parents,
runningShells: state.runningShells,
directories: state.directories,
pendingInputSessionIDs,
}),
buildRepoActivityIndex({
statuses: state.statuses,
parents: state.parents,
runningShells: state.runningShells,
directories: state.directories,
pendingInputSessionIDs,
}),
),
)
}
@@ -86,13 +94,13 @@ export function useActiveWork(windowMs: number): {
isError: boolean
} {
const { repos, isLoading: isReposLoading } = useNavigableRepos()
const directories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
const repoDirectories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
const {
data: sessions,
isLoading: isSessionsLoading,
isError: isSessionsError,
} = useSessionsAcrossDirectories(directories, {
} = useSessionsAcrossDirectories(repoDirectories, {
allDirectories: true,
limit: ACTIVE_WORK_SESSION_LIMIT,
})
@@ -101,18 +109,12 @@ export function useActiveWork(windowMs: number): {
const parents = useSessionStatus((state) => state.parents)
const runningShells = useSessionStatus((state) => state.runningShells)
const outcomes = useSessionStatus((state) => state.outcomes)
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
const pendingFormSessionIDs = useForms().pendingSessionIDs
const sessionDirectories = useSessionStatus((state) => state.directories)
const pendingInputSessionIDs = usePendingInputSessionIDs()
const roots = useMemo(
() =>
collectActiveRoots({
statuses,
parents,
runningShells,
pendingInputSessionIDs: [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
}),
[statuses, parents, runningShells, pendingPermissionSessionIDs, pendingFormSessionIDs],
() => collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs }),
[statuses, parents, runningShells, pendingInputSessionIDs],
)
const listedSessionIDs = useMemo(
@@ -132,16 +134,16 @@ export function useActiveWork(windowMs: number): {
}, [roots, listedSessionIDs])
const fetchedSessions = useQueries({
queries: missingRootIDs.map((sessionID) => sessionQueryOptions(sessionID)),
combine: combineSessions,
queries: missingRootIDs.map((sessionID) =>
sessionQueryOptions(sessionID, sessionDirectories.get(sessionID)),
),
combine: combineQuerySessions,
})
const mergedSessions = useMemo(() => {
if (fetchedSessions.length === 0) return sessions
const seen = new Set(sessions.map((session) => session.id))
const extras = fetchedSessions.filter((session) => !seen.has(session.id))
return extras.length === 0 ? sessions : [...sessions, ...extras]
}, [sessions, fetchedSessions])
const mergedSessions = useMemo(
() => mergeExtraSessions(sessions, fetchedSessions),
[sessions, fetchedSessions],
)
const groups = useMemo(
() =>
+2 -2
View File
@@ -67,14 +67,14 @@ describe('useSSE', () => {
MockEventSource.instances = []
shellApi.listShells.mockResolvedValue([])
shellApi.removeShell.mockResolvedValue(undefined)
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), directories: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response))
})
afterEach(() => {
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), directories: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = originalEventSource
globalThis.fetch = originalFetch
+5 -18
View File
@@ -4,29 +4,16 @@ import { listRepos } from '@/api/repos'
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useSessionPins } from '@/hooks/useSessionPins'
import { buildPinnedSessionKeys, buildSessionKey, getSessionKey } from '@/lib/sessionKey'
import type { Repo, Session } from '@/api/types'
import type { Repo } from '@/api/types'
import {
SIDEBAR_SESSIONS_PER_REPO,
buildSidebarRepoGroups,
combineQuerySessions,
mergeExtraSessions,
selectNavigableRepos,
type SidebarRepoGroup,
} from '@/components/navigation/sidebar-session-tree'
const combinePinnedSessions = (results: Array<{ data?: Session }>): Session[] =>
results.flatMap((result) => (result.data ? [result.data] : []))
const mergeSessions = (sessions: Session[], pinnedSessions: Session[]): Session[] => {
if (pinnedSessions.length === 0) return sessions
const seen = new Set(sessions.map((session) => session.id))
const extras: Session[] = []
for (const session of pinnedSessions) {
if (seen.has(session.id)) continue
seen.add(session.id)
extras.push(session)
}
return extras.length === 0 ? sessions : [...sessions, ...extras]
}
export function useSidebarRepoGroups(input: {
repos: Repo[]
search?: string
@@ -56,11 +43,11 @@ export function useSidebarRepoGroups(input: {
const pinnedSessions = useQueries({
queries: missingPins.map((pin) => sessionQueryOptions(pin.sessionId, pin.directory)),
combine: combinePinnedSessions,
combine: combineQuerySessions,
})
const mergedSessions = useMemo(
() => mergeSessions(sessions, pinnedSessions),
() => mergeExtraSessions(sessions, pinnedSessions),
[sessions, pinnedSessions],
)
+55 -15
View File
@@ -2,7 +2,15 @@ import { describe, it, expect } from 'vitest'
import type { Repo, Session } from '@/api/types'
import type { ChildOutcome } from '@/lib/backgroundWork'
import type { SessionStatusType } from '@/stores/sessionStatusStore'
import { buildActiveWork, collectActiveRoots, activeRepoState, rootSessionID, formatActivityWindow } from './activeWork'
import {
buildActiveWork,
buildRepoActivityIndex,
collectActiveRoots,
formatActivityEmptyMessage,
formatActivityWindow,
repoActivityFromIndex,
rootSessionID,
} from './activeWork'
const NOW = 1_000_000_000_000
const WINDOW_MS = 60_000
@@ -57,6 +65,15 @@ describe('formatActivityWindow', () => {
})
})
describe('formatActivityEmptyMessage', () => {
it('names the window in the empty-state copy', () => {
expect(formatActivityEmptyMessage(30)).toBe('No active or recent sessions in the last 30 minutes')
expect(formatActivityEmptyMessage(1440)).toBe(
'No active or recent sessions in the last 24 hours',
)
})
})
describe('rootSessionID', () => {
it('climbs parents to the top-most root', () => {
const parents = new Map<string, string | null>([['child', 'parent'], ['parent', 'root'], ['root', null]])
@@ -129,13 +146,17 @@ describe('collectActiveRoots', () => {
})
})
describe('activeRepoState', () => {
const repo = repoA
describe('buildRepoActivityIndex and repoActivityFromIndex', () => {
const noShells = new Map<string, { sessionID: string; directory: string }>()
const stateFor = (
repo: Repo,
input: Parameters<typeof buildRepoActivityIndex>[0],
): 'needs-input' | 'running' | null =>
repoActivityFromIndex(repo, buildRepoActivityIndex(input))
it('matches a busy session by its own directory', () => {
const state = activeRepoState({
repo,
const state = stateFor(repoA, {
statuses: statuses({ child: { type: 'busy' } }),
parents: new Map([['child', 'root'], ['root', null]]),
runningShells: noShells,
@@ -147,8 +168,7 @@ describe('activeRepoState', () => {
})
it('matches a busy session by its root directory', () => {
const state = activeRepoState({
repo,
const state = stateFor(repoA, {
statuses: statuses({ child: { type: 'busy' } }),
parents: new Map([['child', 'root'], ['root', null]]),
runningShells: noShells,
@@ -160,8 +180,7 @@ describe('activeRepoState', () => {
})
it('matches a running shell by its own directory', () => {
const state = activeRepoState({
repo,
const state = stateFor(repoA, {
statuses: statuses({}),
parents: new Map(),
runningShells: new Map([['shell-1', { sessionID: 'orphan', directory: '/repos/a' }]]),
@@ -174,8 +193,7 @@ describe('activeRepoState', () => {
it('matches a session directory against the repo local path', () => {
const localRepo = createRepo({ id: 7, fullPath: '/repos/full', localPath: '/local/path' })
const state = activeRepoState({
repo: localRepo,
const state = stateFor(localRepo, {
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
@@ -187,8 +205,7 @@ describe('activeRepoState', () => {
})
it('prefers needs-input over running', () => {
const state = activeRepoState({
repo,
const state = stateFor(repoA, {
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
@@ -200,8 +217,7 @@ describe('activeRepoState', () => {
})
it('returns null when every matching session is idle', () => {
const state = activeRepoState({
repo,
const state = stateFor(repoA, {
statuses: statuses({ session: { type: 'idle' } }),
parents: new Map(),
runningShells: noShells,
@@ -211,6 +227,30 @@ describe('activeRepoState', () => {
expect(state).toBeNull()
})
it('returns null when the repo matches no indexed directory', () => {
const state = stateFor(repoA, {
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/other']]),
pendingInputSessionIDs: [],
})
expect(state).toBeNull()
})
it('reuses the index for the same snapshot references', () => {
const input: Parameters<typeof buildRepoActivityIndex>[0] = {
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/a']]),
pendingInputSessionIDs: [],
}
expect(buildRepoActivityIndex(input)).toBe(buildRepoActivityIndex(input))
})
})
describe('buildActiveWork', () => {
+84 -31
View File
@@ -3,26 +3,15 @@ import type { ChildOutcome } from '@/lib/backgroundWork'
import type { SessionStatusType } from '@/stores/sessionStatusStore'
import { getSessionKey } from '@/lib/sessionKey'
import { getSessionPath } from '@/lib/navigation'
import { findRepoForDirectory, repoMatchesDirectory } from '@/components/navigation/sidebar-session-tree'
import { findRepoForDirectory, normalizeDirectory } from '@/components/navigation/sidebar-session-tree'
const ACTIVITY_WINDOW_LABELS: Record<number, string> = {
15: '15 minutes',
30: '30 minutes',
60: '1 hour',
120: '2 hours',
240: '4 hours',
480: '8 hours',
1440: '24 hours',
}
export const MS_PER_MINUTE = 60_000
/**
* Human-readable label for an activity window in minutes. Known options map to their labels;
* other values fall back to minutes, or to hours when the value divides evenly into hours.
* Human-readable label for an activity window in minutes: whole hours when the value divides
* evenly into hours, otherwise minutes.
*/
export function formatActivityWindow(minutes: number): string {
const known = ACTIVITY_WINDOW_LABELS[minutes]
if (known) return known
if (minutes % 60 === 0) {
const hours = minutes / 60
return `${hours} ${hours === 1 ? 'hour' : 'hours'}`
@@ -31,6 +20,11 @@ export function formatActivityWindow(minutes: number): string {
return `${minutes} minutes`
}
/** Empty-state copy for the activity list naming the window it searched. */
export function formatActivityEmptyMessage(minutes: number): string {
return `No active or recent sessions in the last ${formatActivityWindow(minutes)}`
}
export type ActiveWorkState = 'needs-input' | 'running' | 'recent'
export interface ActiveWorkItem {
@@ -48,6 +42,12 @@ export interface ActiveWorkGroups {
recent: ActiveWorkItem[]
}
export const ACTIVE_WORK_GROUPS = [
{ key: 'needsInput', heading: 'Needs input' },
{ key: 'running', heading: 'Running' },
{ key: 'recent', heading: 'Recent' },
] as const satisfies ReadonlyArray<{ key: keyof ActiveWorkGroups; heading: string }>
export function rootSessionID(
sessionID: string,
parents: ReadonlyMap<string, string | null>,
@@ -94,40 +94,93 @@ export function collectActiveRoots(input: {
return { needsInput, running }
}
/**
* Whether a repo has any active session. A session counts when its own directory or its root's
* directory matches the repo; running shells carry their own directory. Needs-input outranks running.
*/
export function activeRepoState(input: {
repo: Repo
interface RepoActivityIndexInput {
statuses: ReadonlyMap<string, SessionStatusType>
parents: ReadonlyMap<string, string | null>
runningShells: ReadonlyMap<string, { sessionID: string; directory: string }>
directories: ReadonlyMap<string, string>
pendingInputSessionIDs: Iterable<string>
}): 'needs-input' | 'running' | null {
const { repo, statuses, parents, runningShells, directories, pendingInputSessionIDs } = input
}
const sessionMatches = (sessionID: string): boolean => {
if (repoMatchesDirectory(repo, directories.get(sessionID))) return true
const rootID = rootSessionID(sessionID, parents)
return rootID !== sessionID && repoMatchesDirectory(repo, directories.get(rootID))
let cachedRepoActivityIndex: (RepoActivityIndexInput & {
index: Map<string, 'needs-input' | 'running'>
}) | null = null
function computeRepoActivityIndex(input: RepoActivityIndexInput): Map<string, 'needs-input' | 'running'> {
const { statuses, parents, runningShells, directories, pendingInputSessionIDs } = input
const index = new Map<string, 'needs-input' | 'running'>()
const markNeedsInput = (directory?: string | null): void => {
const normalized = normalizeDirectory(directory)
if (normalized) index.set(normalized, 'needs-input')
}
const markRunning = (directory?: string | null): void => {
const normalized = normalizeDirectory(directory)
if (!normalized || index.get(normalized) === 'needs-input') return
index.set(normalized, 'running')
}
for (const sessionID of pendingInputSessionIDs) {
if (sessionMatches(sessionID)) return 'needs-input'
markNeedsInput(directories.get(sessionID))
markNeedsInput(directories.get(rootSessionID(sessionID, parents)))
}
for (const [sessionID, status] of statuses) {
if (status.type === 'idle') continue
if (sessionMatches(sessionID)) return 'running'
markRunning(directories.get(sessionID))
markRunning(directories.get(rootSessionID(sessionID, parents)))
}
for (const shell of runningShells.values()) {
if (repoMatchesDirectory(repo, shell.directory) || sessionMatches(shell.sessionID)) return 'running'
markRunning(shell.directory)
markRunning(directories.get(shell.sessionID))
markRunning(directories.get(rootSessionID(shell.sessionID, parents)))
}
return null
return index
}
/**
* Indexes active sessions by normalized directory for repo badges. Pending input marks its own and
* its root's directory as needs-input; non-idle sessions and running shells mark running unless
* needs-input already claimed the directory. Shared across rows per store snapshot by reference.
*/
export function buildRepoActivityIndex(
input: RepoActivityIndexInput,
): Map<string, 'needs-input' | 'running'> {
if (
cachedRepoActivityIndex &&
cachedRepoActivityIndex.statuses === input.statuses &&
cachedRepoActivityIndex.parents === input.parents &&
cachedRepoActivityIndex.runningShells === input.runningShells &&
cachedRepoActivityIndex.directories === input.directories &&
cachedRepoActivityIndex.pendingInputSessionIDs === input.pendingInputSessionIDs
) {
return cachedRepoActivityIndex.index
}
const index = computeRepoActivityIndex(input)
cachedRepoActivityIndex = { ...input, index }
return index
}
/** The repo's activity from a prebuilt index, checking each of its paths. Needs-input outranks running. */
export function repoActivityFromIndex(
repo: Repo,
index: ReadonlyMap<string, 'needs-input' | 'running'>,
): 'needs-input' | 'running' | null {
let running = false
for (const path of [repo.fullPath, repo.localPath, repo.sourcePath]) {
const normalized = normalizeDirectory(path)
if (!normalized) continue
const state = index.get(normalized)
if (state === 'needs-input') return 'needs-input'
if (state === 'running') running = true
}
return running ? 'running' : null
}
/**
@@ -9,6 +9,7 @@ const resetStore = () => {
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
directories: new Map(),
runningShells: new Map(),
shellRevisions: new Map(),
shellRevision: 0,