feat(activity): surface active work across the session picker, tool rail and mobile

This commit is contained in:
Chris Scott committed 2026-10-16 00:54:06 -04:00
1 parent be874ee07c
commit d8f2fcf29c
46 files changed
+3120 -277

No files matched your search

+3 -1
View File
@@ -6,6 +6,8 @@ import {
DEFAULT_LEADER_KEY,
DEFAULT_DIRECT_SHORTCUTS,
BLOCKED_SERVER_ENV_KEYS,
DEFAULT_ACTIVITY_WINDOW_MINUTES,
ACTIVITY_WINDOW_MINUTE_OPTIONS,
selectPreferredOpenCodeConfigSourceName,
type TTSConfig,
type STTConfig,
@@ -29,7 +31,7 @@ import { saveFile } from '@/lib/download'
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, ModelConfig, ProviderConfig, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile, KeyboardShortcutAction } from '@opencode-manager/shared'
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, DEFAULT_DIRECT_SHORTCUTS, BLOCKED_SERVER_ENV_KEYS }
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, DEFAULT_DIRECT_SHORTCUTS, BLOCKED_SERVER_ENV_KEYS, DEFAULT_ACTIVITY_WINDOW_MINUTES, ACTIVITY_WINDOW_MINUTE_OPTIONS }
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'
export function getOpenCodeConfigSources(config: OpenCodeConfigFile): OpenCodeConfigSourceFile[] {
@@ -0,0 +1,25 @@
import { cn } from '@/lib/utils'
interface ActivityCountPillProps {
needsInput: number
running: number
className?: string
}
export function ActivityCountPill({ needsInput, running, className }: ActivityCountPillProps) {
const total = needsInput + running
if (total === 0) return null
return (
<span
aria-hidden="true"
className={cn(
'flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-semibold leading-none',
needsInput > 0 ? 'bg-warning text-warning-foreground' : 'bg-primary text-primary-foreground',
className,
)}
>
{total}
</span>
)
}
@@ -0,0 +1,346 @@
import { render, screen, fireEvent } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { MemoryRouter } from 'react-router-dom'
import type { Repo, Session } from '@/api/types'
import type { ActiveWorkItem } from '@/lib/activeWork'
import { formatShortRelativeTime } from '@/lib/utils'
import { ActivityList } from './ActivityList'
const mocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: mocks.useActiveWork,
}))
const WINDOW_MS = 30 * 60_000
const NOW = Date.now()
function createSession(id: string, title: string, updated = NOW - 60_000): Session {
return {
id,
projectID: 'proj-1',
title,
time: { created: updated - 10000, updated },
location: { directory: `/repos/${id}` },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(id: number, name: string): Repo {
return {
id,
name,
fullPath: `/repos/${id}`,
localPath: `/repos/${id}`,
defaultBranch: 'main',
currentBranch: 'feature/x',
cloneStatus: 'ready',
clonedAt: 0,
}
}
function createItem(
overrides: Partial<ActiveWorkItem> & Pick<ActiveWorkItem, 'state' | 'session' | 'repo'>,
): ActiveWorkItem {
return {
key: `${overrides.repo.id}:${overrides.session.id}`,
path: `/repos/${overrides.repo.id}/sessions/${overrides.session.id}`,
...overrides,
}
}
function setGroups(groups: {
needsInput?: ActiveWorkItem[]
running?: ActiveWorkItem[]
recent?: ActiveWorkItem[]
}) {
mocks.useActiveWork.mockReturnValue({
groups: {
needsInput: groups.needsInput ?? [],
running: groups.running ?? [],
recent: groups.recent ?? [],
},
isLoading: false,
isError: false,
})
}
const renderList = (
onNavigate = vi.fn(),
path = '/',
props: { hideWhenEmpty?: boolean; title?: string; variant?: 'full' | 'compact' } = {},
) =>
render(
<MemoryRouter initialEntries={[path]}>
<ActivityList windowMs={WINDOW_MS} onNavigate={onNavigate} {...props} />
</MemoryRouter>,
)
describe('ActivityList', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('renders non-empty groups in needs-input, running, recent order', () => {
setGroups({
needsInput: [createItem({ state: 'needs-input', session: createSession('n1', 'Needs'), repo: createRepo(1, 'Alpha') })],
running: [createItem({ state: 'running', session: createSession('r1', 'Running'), repo: createRepo(2, 'Beta') })],
recent: [createItem({ state: 'recent', session: createSession('c1', 'Recent'), repo: createRepo(3, 'Gamma') })],
})
renderList()
const headings = screen.getAllByRole('heading').map((node) => node.textContent)
expect(headings).toEqual(['Needs input', 'Running', 'Recent'])
})
it('hides empty groups', () => {
setGroups({
running: [createItem({ state: 'running', session: createSession('r1', 'Running'), repo: createRepo(2, 'Beta') })],
})
renderList()
const headings = screen.getAllByRole('heading').map((node) => node.textContent)
expect(headings).toEqual(['Running'])
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.queryByText('Recent')).not.toBeInTheDocument()
})
it('renders the empty state with the window minutes', () => {
setGroups({})
renderList()
expect(screen.getByText('No active or recent sessions in the last 30 minutes')).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') })
setGroups({ recent: [item] })
renderList(onNavigate)
fireEvent.click(screen.getByRole('button', { name: /Recent/ }))
expect(onNavigate).toHaveBeenCalledWith(item)
})
it('marks the currently open session with aria-current', () => {
setGroups({
recent: [
createItem({ state: 'recent', session: createSession('open', 'Open session'), repo: createRepo(7, 'Gamma') }),
createItem({ state: 'recent', session: createSession('other', 'Other session'), repo: createRepo(7, 'Gamma') }),
],
})
renderList(vi.fn(), '/repos/7/sessions/open')
expect(screen.getByRole('button', { name: /Open session/ })).toHaveAttribute('aria-current', 'true')
expect(screen.getByRole('button', { name: /Other session/ })).not.toHaveAttribute('aria-current')
})
it('shows a loading state', () => {
mocks.useActiveWork.mockReturnValue({
groups: { needsInput: [], running: [], recent: [] },
isLoading: true,
isError: false,
})
renderList()
expect(screen.getByText('Loading activity...')).toBeInTheDocument()
})
it('shows an error state', () => {
mocks.useActiveWork.mockReturnValue({
groups: { needsInput: [], running: [], recent: [] },
isLoading: false,
isError: true,
})
renderList()
expect(screen.getByText("Couldn't load activity.")).toBeInTheDocument()
})
it('renders nothing when hideWhenEmpty and there are no items', () => {
setGroups({})
const { container } = renderList(vi.fn(), '/', { hideWhenEmpty: true })
expect(container).toBeEmptyDOMElement()
})
it('renders nothing while loading when hideWhenEmpty', () => {
mocks.useActiveWork.mockReturnValue({
groups: { needsInput: [], running: [], recent: [] },
isLoading: true,
isError: false,
})
const { container } = renderList(vi.fn(), '/', { hideWhenEmpty: true })
expect(container).toBeEmptyDOMElement()
})
it('renders the title only when there are items', () => {
setGroups({
recent: [createItem({ state: 'recent', session: createSession('c1', 'Recent'), repo: createRepo(3, 'Gamma') })],
})
renderList(vi.fn(), '/', { title: 'Activity' })
expect(screen.getByRole('heading', { name: 'Activity' })).toBeInTheDocument()
})
it('does not render the title when there are no items', () => {
setGroups({})
renderList(vi.fn(), '/', { title: 'Activity' })
expect(screen.queryByRole('heading', { name: 'Activity' })).toBeNull()
})
})
describe('ActivityList compact variant', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('renders only the section title, without group headings', () => {
setGroups({
needsInput: [
createItem({ state: 'needs-input', session: createSession('n1', 'Needs work'), repo: createRepo(1, 'Alpha') }),
],
running: [
createItem({ state: 'running', session: createSession('r1', 'Running task'), repo: createRepo(2, 'Beta') }),
],
recent: [
createItem({ state: 'recent', session: createSession('c1', 'Recent task'), repo: createRepo(3, 'Gamma') }),
],
})
renderList(vi.fn(), '/', { variant: 'compact', title: 'Activity' })
expect(screen.getAllByRole('heading').map((node) => node.textContent)).toEqual(['Activity'])
expect(screen.queryByText('Needs input')).toBeNull()
expect(screen.queryByText('Running')).toBeNull()
expect(screen.queryByText('Recent')).toBeNull()
})
it('renders one single-line row per item in needs-input, running, recent order', () => {
const needs = createItem({
state: 'needs-input',
session: createSession('n1', 'Needs work'),
repo: createRepo(1, 'Alpha'),
})
const running = createItem({
state: 'running',
session: createSession('r1', 'Running task'),
repo: createRepo(2, 'Beta'),
})
const recent = createItem({
state: 'recent',
session: createSession('c1', 'Recent task'),
repo: createRepo(3, 'Gamma'),
})
setGroups({ needsInput: [needs], running: [running], recent: [recent] })
renderList(vi.fn(), '/', { variant: 'compact' })
const rows = screen.getAllByRole('button')
expect(rows).toHaveLength(3)
expect(rows[0]).toHaveTextContent('Needs work')
expect(rows[1]).toHaveTextContent('Running task')
expect(rows[2]).toHaveTextContent('Recent task')
expect(rows[0]).toHaveAccessibleName(/Needs work/)
expect(rows[0]).toHaveAccessibleName(/Alpha/)
expect(rows[0]).toHaveTextContent(formatShortRelativeTime(new Date(needs.session.time.updated)))
expect(rows[0]).not.toHaveTextContent('feature/x')
})
it('caps the compact list at five items, keeping needs-input and running over recent', () => {
setGroups({
needsInput: [1, 2].map((n): ActiveWorkItem =>
createItem({
state: 'needs-input',
session: createSession(`n${n}`, `Needs work ${n}`),
repo: createRepo(n, `Repo ${n}`),
}),
),
running: [1, 2, 3].map((n): ActiveWorkItem =>
createItem({
state: 'running',
session: createSession(`r${n}`, `Running task ${n}`),
repo: createRepo(10 + n, `Repo ${10 + n}`),
}),
),
recent: [1, 2, 3].map((n): ActiveWorkItem =>
createItem({
state: 'recent',
session: createSession(`c${n}`, `Recent task ${n}`),
repo: createRepo(20 + n, `Repo ${20 + n}`),
}),
),
})
renderList(vi.fn(), '/', { variant: 'compact' })
const rows = screen.getAllByRole('button')
expect(rows).toHaveLength(5)
expect(rows[0]).toHaveTextContent('Needs work 1')
expect(rows[4]).toHaveTextContent('Running task 3')
expect(screen.queryByText('Recent task 1')).toBeNull()
})
it('fills the remaining compact slots with recent items', () => {
setGroups({
running: [
createItem({ state: 'running', session: createSession('r1', 'Running task'), repo: createRepo(1, 'Alpha') }),
],
recent: [1, 2, 3, 4, 5].map((n): ActiveWorkItem =>
createItem({
state: 'recent',
session: createSession(`c${n}`, `Recent task ${n}`),
repo: createRepo(10 + n, `Repo ${10 + n}`),
}),
),
})
renderList(vi.fn(), '/', { variant: 'compact' })
const rows = screen.getAllByRole('button')
expect(rows).toHaveLength(5)
expect(rows[0]).toHaveTextContent('Running task')
expect(rows[4]).toHaveTextContent('Recent task 4')
expect(screen.queryByText('Recent task 5')).toBeNull()
})
it('marks the currently open session with aria-current', () => {
setGroups({
recent: [
createItem({ state: 'recent', session: createSession('open', 'Open session'), repo: createRepo(7, 'Gamma') }),
createItem({ state: 'recent', session: createSession('other', 'Other session'), repo: createRepo(7, 'Gamma') }),
],
})
renderList(vi.fn(), '/repos/7/sessions/open', { variant: 'compact' })
expect(screen.getByRole('button', { name: /Open session/ })).toHaveAttribute('aria-current', 'true')
expect(screen.getByRole('button', { name: /Other session/ })).not.toHaveAttribute('aria-current')
})
it('renders nothing when hideWhenEmpty and there are no items', () => {
setGroups({})
const { container } = renderList(vi.fn(), '/', { hideWhenEmpty: true, variant: 'compact' })
expect(container).toBeEmptyDOMElement()
})
})
@@ -0,0 +1,231 @@
import { useLocation } from 'react-router-dom'
import { CircleAlert, CircleCheck, CircleX } from 'lucide-react'
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'
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
/** 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
title?: string
/** `compact` renders one flat, single-line list capped at {@link COMPACT_MAX_ITEMS}; `full` renders grouped rows. */
variant?: 'full' | 'compact'
}
function isCurrentItem(item: ActiveWorkItem, sessionID: string | null, repoID: number | null) {
return item.repo.id === repoID && item.session.id === sessionID
}
function activityRowClass(isCurrent: boolean, compact: boolean) {
return cn(
'flex w-full items-center gap-2 rounded-md px-2 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
compact ? 'py-1' : 'py-1.5',
isCurrent && 'bg-accent',
)
}
function ActivityStateIcon({ item, iconClassName }: { item: ActiveWorkItem; iconClassName: string }) {
if (item.state === 'needs-input') {
return <CircleAlert className={cn(iconClassName, 'text-warning')} aria-hidden="true" />
}
if (item.state === 'running') {
return <SessionStatusIndicator sessionID={item.session.id} size="sm" />
}
if (item.outcome === 'failed') {
return <CircleX className={cn(iconClassName, 'text-destructive')} aria-hidden="true" />
}
if (item.outcome === 'succeeded') {
return <CircleCheck className={cn(iconClassName, 'text-success')} aria-hidden="true" />
}
return null
}
interface ActivityRowProps {
item: ActiveWorkItem
isCurrent: boolean
onSelect: (item: ActiveWorkItem) => void
}
function ActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
const branch = getRepoBranchLabel(item.repo)
const repoLine = branch
? `${getRepoDisplayName(item.repo)} · ${branch}`
: getRepoDisplayName(item.repo)
return (
<button
type="button"
onClick={() => onSelect(item)}
aria-current={isCurrent ? 'true' : undefined}
className={activityRowClass(isCurrent, false)}
>
<span className="flex w-5 shrink-0 items-center justify-center">
<ActivityStateIcon item={item} iconClassName={FULL_ICON_CLASS} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-foreground">
{item.session.title || UNTITLED_SESSION_TITLE}
</span>
<span className="block truncate text-xs text-muted-foreground">{repoLine}</span>
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{formatShortRelativeTime(new Date(item.session.time.updated))}
</span>
</button>
)
}
function CompactActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
return (
<button
type="button"
onClick={() => onSelect(item)}
aria-current={isCurrent ? 'true' : undefined}
className={activityRowClass(isCurrent, true)}
>
<span className="flex w-4 shrink-0 items-center justify-center">
<ActivityStateIcon item={item} iconClassName={COMPACT_ICON_CLASS} />
</span>
<span className="min-w-0 flex-1 truncate text-foreground">
{item.session.title || UNTITLED_SESSION_TITLE}
</span>
<span className="max-w-[35%] truncate text-xs text-muted-foreground">
{getRepoDisplayName(item.repo)}
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{formatShortRelativeTime(new Date(item.session.time.updated))}
</span>
</button>
)
}
interface ActivityGroupProps {
heading: string
items: ActiveWorkItem[]
currentSessionID: string | null
currentRepoId: number | null
onSelect: (item: ActiveWorkItem) => void
}
function ActivityGroup({ heading, items, currentSessionID, currentRepoId, onSelect }: ActivityGroupProps) {
if (items.length === 0) return null
return (
<div className="flex flex-col gap-0.5">
<h3 className="px-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground">{heading}</h3>
{items.map((item) => (
<ActivityRow
key={item.key}
item={item}
isCurrent={isCurrentItem(item, currentSessionID, currentRepoId)}
onSelect={onSelect}
/>
))}
</div>
)
}
export function ActivityList({
windowMs,
onNavigate,
hideWhenEmpty = false,
title,
variant = 'full',
}: ActivityListProps) {
const location = useLocation()
const { groups, isLoading, isError } = useActiveWork(windowMs)
const route = parseRepoRoute(location.pathname)
if (isLoading) {
if (hideWhenEmpty) return null
return <p className="p-4 text-sm text-muted-foreground">Loading activity...</p>
}
if (isError) {
if (hideWhenEmpty) return null
return <p className="p-4 text-sm text-destructive">Couldn&apos;t load activity.</p>
}
const isEmpty =
groups.needsInput.length === 0 && groups.running.length === 0 && groups.recent.length === 0
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>
)
}
const isCompact = variant === 'compact'
const compactItems = [...groups.needsInput, ...groups.running, ...groups.recent].slice(
0,
COMPACT_MAX_ITEMS,
)
return (
<section
aria-label={title}
className={cn('flex flex-col', isCompact ? 'pb-1' : 'pb-2', title && 'border-b border-border')}
>
{title && (
<h2
className={cn(
'px-4 text-xs font-medium uppercase tracking-wider text-muted-foreground',
isCompact ? 'pt-2 pb-0.5' : 'pt-3 pb-1',
)}
>
{title}
</h2>
)}
{isCompact ? (
compactItems.map((item) => (
<CompactActivityRow
key={item.key}
item={item}
isCurrent={isCurrentItem(item, route.sessionId, route.repoId)}
onSelect={onNavigate}
/>
))
) : (
<>
<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}
/>
</>
)}
</section>
)
}
@@ -0,0 +1,20 @@
import { useActivityWindowMs } from '@/hooks/useActiveWork'
import { ActivityList } from '@/components/activity/ActivityList'
/**
* A compact, self-titled Activity section that renders nothing when empty.
* Reads the network through `useActiveWork`, so it must only be mounted while visible.
*/
export function CompactActivityList({ onNavigate }: { onNavigate: (path: string) => void }) {
const windowMs = useActivityWindowMs()
return (
<ActivityList
windowMs={windowMs}
title="Activity"
hideWhenEmpty
variant="compact"
onNavigate={(item) => onNavigate(item.path)}
/>
)
}
@@ -0,0 +1,23 @@
import { ActivitySpinner } from '@/components/ui/activity-spinner'
import { useRepoActivityState } from '@/hooks/useActiveWork'
import { cn } from '@/lib/utils'
import type { Repo } from '@/api/types'
/**
* Renders nothing unless a session in the repo is active, then shows the braille spinner in the
* state colour (info while running, warning when a session needs input).
*/
export function RepoActivityIndicator({ repo, className }: { repo: Repo; className?: string }) {
const state = useRepoActivityState(repo)
if (state === null) return null
return (
<span
role="img"
aria-label={state === 'needs-input' ? 'Session needs input' : 'Sessions running'}
className={cn('inline-flex shrink-0 items-center', state === 'needs-input' ? 'text-warning' : 'text-info', className)}
>
<ActivitySpinner />
</span>
)
}
@@ -97,6 +97,10 @@ vi.mock('@/contexts/EventContext', () => ({
}),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useRepoActivityState: () => null,
}))
function createRepo(overrides: Partial<Repo> & { id: number; fullPath: string }): Repo {
return {
localPath: `repos/${overrides.id}`,
@@ -90,6 +90,7 @@ function SessionSearchResults({
{matchingGroups.map((group) => (
<RepoNavGroup
key={group.repo.id}
repo={group.repo}
name={group.label}
branch={group.branchLabel}
isWorktree={group.repo.isWorktree}
@@ -6,6 +6,7 @@ import { MoreDrawer } from './MoreDrawer'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { getRepo } from '@/api/repos'
import type { ActiveWorkItem } from '@/lib/activeWork'
vi.mock('@/hooks/useAuth')
vi.mock('@/hooks/useServerHealth')
@@ -20,6 +21,61 @@ vi.mock('react-router-dom', async () => {
}
})
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
useActivityWindowMs: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMs: activityMocks.useActivityWindowMs,
useRepoActivityState: () => null,
}))
function createActiveWorkItem(): ActiveWorkItem {
const now = Date.now()
return {
key: '1:s1',
state: 'recent',
path: '/repos/1/sessions/s1',
session: {
id: 's1',
projectID: 'proj-1',
title: 'Session s1',
time: { created: now - 10_000, updated: now },
location: { directory: '/path/to/repo1' },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
},
repo: {
id: 1,
name: 'repo1',
fullPath: '/path/to/repo1',
localPath: '/path/to/repo1',
defaultBranch: 'main',
currentBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
},
}
}
function setActivityGroups(groups: {
needsInput?: ActiveWorkItem[]
running?: ActiveWorkItem[]
recent?: ActiveWorkItem[]
}) {
activityMocks.useActiveWork.mockReturnValue({
groups: {
needsInput: groups.needsInput ?? [],
running: groups.running ?? [],
recent: groups.recent ?? [],
},
isLoading: false,
isError: false,
})
}
const mockAuth = (logout = vi.fn()) => {
vi.mocked(useAuth).mockReturnValue({
user: null,
@@ -99,6 +155,8 @@ describe('MoreDrawer', () => {
cloneStatus: 'ready',
clonedAt: 0,
})
activityMocks.useActivityWindowMs.mockReturnValue(30 * 60_000)
setActivityGroups({})
})
it('renders Settings and Logout menu items', () => {
@@ -264,4 +322,41 @@ describe('MoreDrawer', () => {
expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument()
})
it('shows the Activity section above the menu when there are items', () => {
mockAuth()
mockServerHealth()
setActivityGroups({ recent: [createActiveWorkItem()] })
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId' })
const heading = screen.getByRole('heading', { name: 'Activity' })
const firstMenuRow = screen.getByText('Files')
expect(screen.getByText('Session s1')).toBeInTheDocument()
expect(heading.compareDocumentPosition(firstMenuRow) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
})
it('hides the Activity section when there are no items', () => {
mockAuth()
mockServerHealth()
setActivityGroups({})
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId' })
expect(screen.queryByRole('heading', { name: 'Activity' })).not.toBeInTheDocument()
expect(screen.queryByText('Session s1')).not.toBeInTheDocument()
})
it('navigates to the activity item and closes the drawer when a row is clicked', () => {
const navigateMock = vi.fn()
vi.mocked(useNavigate).mockReturnValue(navigateMock)
mockAuth()
mockServerHealth()
setActivityGroups({ recent: [createActiveWorkItem()] })
const handleClose = vi.fn()
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId', onClose: handleClose })
fireEvent.click(screen.getByRole('button', { name: /Session s1/ }))
expect(navigateMock).toHaveBeenCalledWith('/repos/1/sessions/s1')
expect(handleClose).toHaveBeenCalled()
})
})
@@ -8,6 +8,7 @@ import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
import { CompactActivityList } from '@/components/activity/CompactActivityList'
import { buildMoreItems, buildNavModel, isSessionDetailPath, type MoreDrawerItem } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { cn, getRepoDisplayName } from '@/lib/utils'
@@ -183,6 +184,14 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
)}
</div>
<SideDrawerContent className="flex flex-col gap-4 pb-3">
{isOpen && (
<CompactActivityList
onNavigate={(path) => {
navigate(path)
onClose()
}}
/>
)}
<MenuSection>
{isSessionDetail && (
<MenuRow icon={FolderGit2} label="Repos" onClick={() => openMobileSheet('repos')} trailing />
@@ -6,6 +6,7 @@ import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
import { listRepos } from '@/api/repos'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import type { ActiveWorkItem } from '@/lib/activeWork'
type SessionFixture = {
id: string
@@ -32,6 +33,17 @@ const { sessionsData, sessionsHookCalls, permissionSessions, createSessionDirect
createSessionDirectories: [] as string[],
}))
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
useActivityWindowMs: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMs: activityMocks.useActivityWindowMs,
useRepoActivityState: () => null,
}))
vi.mock('@/api/repos')
vi.mock('@/contexts/EventContext', () => ({
@@ -92,6 +104,32 @@ function createRepo(id: number, name: string, fullPath: string) {
}
}
function createActiveWorkItem(): ActiveWorkItem {
return {
key: '1:s1',
state: 'recent',
path: '/repos/1/sessions/s1',
session: createSession('s1', Date.now(), '/path/to/repo1'),
repo: createRepo(1, 'repo1', '/path/to/repo1'),
}
}
function setActivityGroups(groups: {
needsInput?: ActiveWorkItem[]
running?: ActiveWorkItem[]
recent?: ActiveWorkItem[]
}) {
activityMocks.useActiveWork.mockReturnValue({
groups: {
needsInput: groups.needsInput ?? [],
running: groups.running ?? [],
recent: groups.recent ?? [],
},
isLoading: false,
isError: false,
})
}
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
@@ -130,6 +168,8 @@ describe('RepoQuickSwitchSheet', () => {
sessionsData.splice(0, sessionsData.length)
sessionsHookCalls.splice(0, sessionsHookCalls.length)
permissionSessions.current.clear()
activityMocks.useActivityWindowMs.mockReturnValue(30 * 60_000)
setActivityGroups({})
})
it('renders with loading state', async () => {
@@ -783,6 +823,79 @@ describe('RepoQuickSwitchSheet', () => {
expect(document.body.querySelector('[aria-hidden="true"].h-16')).not.toBeNull()
})
it('renders the Activity section above the repo list when there are items', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
setActivityGroups({ recent: [createActiveWorkItem()] })
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
})
const heading = screen.getByRole('heading', { name: 'Activity' })
const repo = screen.getByText('repo1')
expect(screen.getByText('Session s1')).toBeInTheDocument()
expect(heading.compareDocumentPosition(repo) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
})
it('hides the Activity section when there are no items', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
setActivityGroups({})
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
})
expect(screen.queryByRole('heading', { name: 'Activity' })).toBeNull()
expect(screen.queryByText('Session s1')).toBeNull()
})
it('hides the Activity section while a search query is entered', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
setActivityGroups({ recent: [createActiveWorkItem()] })
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
expect(await screen.findByRole('heading', { name: 'Activity' })).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Search projects...'), { target: { value: 'repo' } })
expect(screen.queryByRole('heading', { name: 'Activity' })).toBeNull()
expect(screen.queryByText('Session s1')).toBeNull()
})
it('navigates to the item path and closes the sheet when an activity row is clicked', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
setActivityGroups({ recent: [createActiveWorkItem()] })
const handleClose = vi.fn()
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1']}>
<Routes>
<Route
path="*"
element={
<>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
fireEvent.click(await screen.findByRole('button', { name: /Session s1/ }))
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/sessions/s1')
expect(handleClose).toHaveBeenCalled()
})
it('starts a new session in a repo, opens it and closes the sheet', async () => {
createSessionDirectories.splice(0, createSessionDirectories.length)
vi.mocked(listRepos).mockResolvedValue([
@@ -4,6 +4,7 @@ import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { Input } from '@/components/ui/input'
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
import { Button } from '@/components/ui/button'
import { CompactActivityList } from '@/components/activity/CompactActivityList'
import { getRepoDisplayName } from '@/lib/utils'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { FolderGit2, Plus } from 'lucide-react'
@@ -95,6 +96,9 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
</div>
</BottomSheetHeader>
<BottomSheetContent className="flex flex-col px-0 pt-0 gap-0">
{isOpen && !searchQuery.trim() && (
<CompactActivityList onNavigate={(path) => navigateAndClose(path)} />
)}
{isLoading ? (
<div className="flex flex-col gap-2 px-4 pt-3">
{Array.from({ length: 5 }).map((_, i) => (
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from
import { useLocation } from 'react-router-dom'
import { Bell, ChevronDown, ChevronRight, HelpCircle, Loader2, Pin, Plus, X } from 'lucide-react'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { RepoActivityIndicator } from '@/components/activity/RepoActivityIndicator'
import { useForms, usePermissions } from '@/contexts/EventContext'
import { useCreateSession } from '@/hooks/useOpenCode'
import { useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups'
@@ -23,6 +24,7 @@ function OpenRepoRail() {
}
interface RepoNavGroupProps {
repo: Repo
name: string
branch?: string | null
isWorktree?: boolean
@@ -35,6 +37,7 @@ interface RepoNavGroupProps {
}
export function RepoNavGroup({
repo,
name,
branch,
isWorktree,
@@ -76,8 +79,11 @@ export function RepoNavGroup({
onToggle ? 'pl-0' : 'pl-4',
)}
>
<span className="truncate text-[15px] font-bold tracking-tight text-highlight">
{name}
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate text-[15px] font-bold tracking-tight text-highlight">
{name}
</span>
<RepoActivityIndicator repo={repo} />
</span>
{branch && (
<span
@@ -237,6 +243,7 @@ export function RepoSessionNavList({
return (
<RepoNavGroup
key={repo.id}
repo={repo}
name={getRepoDisplayName(repo)}
branch={getRepoBranchLabel(repo)}
isWorktree={repo.isWorktree}
@@ -1,12 +1,26 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import type { Repo, Session } from '@/api/types'
import type { ActiveWorkItem } from '@/lib/activeWork'
import { stubMatchMedia } from '@/test/test-utils'
import { ToolSidePanel } from './ToolSidePanel'
import { useToolPanel } from '@/hooks/useToolPanel'
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
useActiveWorkCounts: vi.fn(),
useActivityWindowMs: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActiveWorkCounts: activityMocks.useActiveWorkCounts,
useActivityWindowMs: activityMocks.useActivityWindowMs,
}))
vi.mock('@/components/file-browser/FileBrowser', () => ({
FileBrowser: ({ initialSelectedFile }: { initialSelectedFile?: string }) => <div>files-tool {initialSelectedFile}</div>,
}))
@@ -77,6 +91,54 @@ function search(): URLSearchParams {
return new URLSearchParams(screen.getByTestId('search').textContent ?? '')
}
const WINDOW_MS = 30 * 60_000
const NOW = Date.now()
function createSession(id: string, title: string, updated = NOW - 60_000): Session {
return {
id,
projectID: 'proj-1',
title,
time: { created: updated - 10000, updated },
location: { directory: `/repos/${id}` },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(id: number, name: string): Repo {
return {
id,
name,
fullPath: `/repos/${id}`,
localPath: `/repos/${id}`,
defaultBranch: 'main',
currentBranch: 'feature/x',
cloneStatus: 'ready',
clonedAt: 0,
}
}
function createActivityItem(id: string, title: string, repoId: number, repoName: string): ActiveWorkItem {
const session = createSession(id, title)
const repo = createRepo(repoId, repoName)
return {
key: `${repoId}:${id}`,
session,
repo,
state: 'recent',
path: `/repos/${repoId}/sessions/${id}`,
}
}
function setActivityGroups(items: ActiveWorkItem[] = []) {
activityMocks.useActiveWork.mockReturnValue({
groups: { needsInput: [], running: [], recent: items },
isLoading: false,
isError: false,
})
}
function HomeHarness() {
const panel = useToolPanel(true)
return (
@@ -87,6 +149,13 @@ function HomeHarness() {
)
}
beforeEach(() => {
vi.clearAllMocks()
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 0, running: 0 })
activityMocks.useActivityWindowMs.mockReturnValue(WINDOW_MS)
setActivityGroups()
})
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
@@ -252,4 +321,46 @@ describe('ToolSidePanel', () => {
await waitFor(() => expect(search().has('panel')).toBe(false))
expect(screen.getByLabelText('prompt')).toHaveFocus()
})
it('lists the Activity tool first in the rail', () => {
renderAt('')
const rail = screen.getByRole('navigation', { name: 'Tools' })
const buttons = within(rail).getAllByRole('button')
expect(buttons[0]).toHaveAccessibleName('Activity')
})
it('opens the Activity panel with rows and the window label when clicked', async () => {
const user = userEvent.setup()
setActivityGroups([createActivityItem('other', 'Other Session', 2, 'Beta')])
renderAt('')
await user.click(screen.getByRole('button', { name: 'Activity' }))
expect(await screen.findByText('Other Session')).toBeInTheDocument()
expect(search().get('panel')).toBe('activity')
expect(screen.getByRole('complementary', { name: 'Activity' })).toHaveClass('w-80')
expect(screen.getByText('Last 30 minutes')).toBeInTheDocument()
})
it('keeps the Activity panel open when a row navigates to a session', async () => {
const user = userEvent.setup()
setActivityGroups([createActivityItem('other', 'Other Session', 2, 'Beta')])
renderAt('')
await user.click(screen.getByRole('button', { name: 'Activity' }))
await user.click(await screen.findByRole('button', { name: /Other Session/ }))
await waitFor(() => expect(screen.getByTestId('pathname').textContent).toBe('/repos/2/sessions/other'))
expect(search().get('panel')).toBe('activity')
})
it('shows an Activity count pill and extends the accessible name', () => {
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 1, running: 2 })
renderAt('')
const button = screen.getByRole('button', { name: 'Activity, 1 needs input, 2 running' })
const pill = within(button).getByText('3')
expect(pill.className).toContain('bg-warning')
})
})
@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react'
import type { ReactNode } from 'react'
import { X } from 'lucide-react'
import { useLocation } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'
import { FileBrowser } from '@/components/file-browser/FileBrowser'
import { SourceControlContent } from '@/components/source-control'
import { TerminalWorkspace } from '@/components/terminal/TerminalPanel'
@@ -23,10 +24,43 @@ import type { ModelRef } from '@opencode-manager/shared/opencode'
import { buildToolItems, toolKeyOf, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToolPanel'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { ActivityList } from '@/components/activity/ActivityList'
import { ActivityCountPill } from '@/components/activity/ActivityCountPill'
import { useActiveWorkCounts, useActivityWindowMs } 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()
return (
<span className="shrink-0 text-xs text-muted-foreground">
Last {formatActivityWindow(Math.round(windowMs / MS_PER_MINUTE))}
</span>
)
}
function ActivityPanelBody() {
const navigate = useNavigate()
const windowMs = useActivityWindowMs()
return (
<div className="min-h-0 flex-1 overflow-y-auto">
<ActivityList
windowMs={windowMs}
onNavigate={(item) => navigate({ pathname: item.path, search: '?panel=activity' })}
/>
</div>
)
}
interface ToolSidePanelProps {
panel: ToolPanelState
filesBasePath: string | undefined
@@ -47,9 +81,11 @@ interface RailButtonProps {
item: MoreDrawerItem
active: boolean
onClick: () => void
ariaLabel?: string
indicator?: ReactNode
}
function RailButton({ item, active, onClick }: RailButtonProps) {
function RailButton({ item, active, onClick, ariaLabel, indicator }: RailButtonProps) {
const Icon = item.icon
return (
<Tooltip delayDuration={0}>
@@ -57,10 +93,10 @@ function RailButton({ item, active, onClick }: RailButtonProps) {
<button
type="button"
onClick={onClick}
aria-label={item.label}
aria-label={ariaLabel ?? item.label}
aria-pressed={active}
className={cn(
'rounded-md p-2 transition-colors',
'relative rounded-md p-2 transition-colors',
active
? 'bg-accent text-foreground'
: item.danger
@@ -69,6 +105,7 @@ function RailButton({ item, active, onClick }: RailButtonProps) {
)}
>
<Icon className="h-4 w-4" />
{indicator}
</button>
</TooltipTrigger>
<TooltipContent side="left" align="center">
@@ -100,6 +137,7 @@ 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)
@@ -122,6 +160,18 @@ 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) => {
@@ -139,6 +189,7 @@ export function ToolSidePanel({
if (tool === 'preview') return <PreviewWorkspace isOpen directory={directory} compact />
if (tool === 'mcp') return repoDirectory ? <RepoMcpContent open directory={repoDirectory} /> : null
if (tool === 'walkthrough') return sessionId ? <ChangesWalkthroughView /> : null
if (tool === 'activity') return <ActivityPanelBody />
if (repoId === undefined) return null
switch (tool) {
case 'sourceControl':
@@ -169,10 +220,16 @@ export function ToolSidePanel({
activeTool && activeLabel ? (
<aside
aria-label={activeLabel}
className="flex w-[min(600px,45vw)] shrink-0 flex-col border-l border-border bg-background"
className={cn(
'flex shrink-0 flex-col border-l border-border bg-background',
PANEL_WIDTH_CLASSES[activeTool] ?? 'w-[min(600px,45vw)]',
)}
>
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
<h2 className="min-w-0 flex-1 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
<div className="flex min-w-0 flex-1 items-baseline gap-2">
<h2 className="min-w-0 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
{activeTool === 'activity' ? <ActivityWindowLabel /> : null}
</div>
{activeTool === 'walkthrough' ? (
<>
<ChangesWalkthroughSourcePicker />
@@ -215,7 +272,14 @@ export function ToolSidePanel({
<TooltipProvider>
<nav ref={railRef} aria-label="Tools" className="flex w-11 shrink-0 flex-col items-center gap-1 overflow-y-auto border-l border-border bg-background py-2">
{panelTools.map(({ item, tool }) => (
<RailButton key={item.key} item={item} active={tool === activeTool} onClick={() => toggleTool(tool)} />
<RailButton
key={item.key}
item={item}
active={tool === activeTool}
onClick={() => toggleTool(tool)}
ariaLabel={tool === 'activity' ? activityAriaLabel : undefined}
indicator={tool === 'activity' ? activityIndicator : undefined}
/>
))}
{actionItems.length > 0 ? <div className="my-1 h-px w-6 shrink-0 bg-border" role="separator" /> : null}
{actionItems.map((item) => (
@@ -139,8 +139,18 @@ describe('buildMoreItems', () => {
})
describe('buildToolItems', () => {
it('leads every route with the Activity tool', () => {
for (const path of ['/', '/repos/42', '/repos/42/sessions/abc', '/assistant', '/schedules']) {
const [first] = buildToolItems(path)
expect(first.key).toBe('activity')
expect(first.label).toBe('Activity')
expect(first.panelTool).toBe('activity')
}
})
it('returns the session route items without home and account entries', () => {
expect(buildToolItems('/repos/42/sessions/abc').map((item) => item.key)).toEqual([
'activity',
'files',
'mcp',
'skills',
@@ -155,15 +165,15 @@ describe('buildToolItems', () => {
})
it('returns the home route tools', () => {
expect(buildToolItems('/').map((item) => item.key)).toEqual(['all-schedules', 'files'])
expect(buildToolItems('/').map((item) => item.key)).toEqual(['activity', 'all-schedules', 'files'])
})
it.each(['/repos/42', '/assistant'])('opens schedules in the panel on %s', (path) => {
expect(buildToolItems(path).find((item) => item.key === 'schedules')?.panelTool).toBe('schedules')
})
it.each(['/schedules', '/repos/42/schedules'])('returns nothing on %s', (path) => {
expect(buildToolItems(path)).toEqual([])
it.each(['/schedules', '/repos/42/schedules'])('returns only the Activity tool on %s', (path) => {
expect(buildToolItems(path).map((item) => item.key)).toEqual(['activity'])
})
})
@@ -1,5 +1,5 @@
import type { LucideIcon } from 'lucide-react'
import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
import { Activity, BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
@@ -57,7 +57,8 @@ const NON_TOOL_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
/** Route-scoped tool items, shown in the desktop tool rail instead of the sidebar. */
export function buildToolItems(pathname: string): MoreDrawerItem[] {
return buildNavModel(pathname).items.filter((item) => !NON_TOOL_ITEM_KEYS.has(item.key))
const routeItems = buildNavModel(pathname).items.filter((item) => !NON_TOOL_ITEM_KEYS.has(item.key))
return [{ key: 'activity', label: 'Activity', icon: Activity, panelTool: 'activity' }, ...routeItems]
}
/** The `?panel=`/`?dialog=` tool identifier an item targets, preferring its panel tool. */
@@ -50,6 +50,22 @@ export function buildRepoByDirectory(repos: Repo[]): Map<string, Repo> {
return new Map(repos.map((repo) => [repo.fullPath, repo]))
}
function normalizeDirectory(directory?: string | null): string | null {
return directory?.replace(/\/+$/, '') ?? null
}
export function repoMatchesDirectory(repo: Repo, directory?: string | null): boolean {
const normalizedDirectory = normalizeDirectory(directory)
if (!normalizedDirectory) return false
return [repo.fullPath, repo.localPath, repo.sourcePath]
.some((path) => normalizeDirectory(path) === normalizedDirectory)
}
export function findRepoForDirectory(repos: Repo[], directory?: string | null): Repo | undefined {
return repos.find((repo) => repoMatchesDirectory(repo, directory))
}
export function buildSidebarRepoGroups(input: {
repos: Repo[]
sessions: Session[]
@@ -13,12 +13,22 @@ vi.mock('react-router-dom', async () => {
}
})
const activityMocks = vi.hoisted(() => ({
useRepoActivityState: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useRepoActivityState: activityMocks.useRepoActivityState,
}))
const defaultProps = {
repo: {
id: 1,
repoUrl: 'https://github.com/test/test-repo',
localPath: 'repos/test-repo',
fullPath: '/Users/test/repos/test-repo',
defaultBranch: 'main',
clonedAt: 0,
branch: 'main',
currentBranch: 'main',
cloneStatus: 'ready' as const,
@@ -45,6 +55,7 @@ const renderWithRouter = (ui: React.ReactElement) => {
describe('RepoCard', () => {
beforeEach(() => {
vi.clearAllMocks()
activityMocks.useRepoActivityState.mockReturnValue(null)
})
it('should not navigate when cloneStatus is not ready', () => {
@@ -156,4 +167,29 @@ describe('RepoCard', () => {
expect(screen.getByText('Cloning...')).toBeInTheDocument()
})
it('should show the running indicator when a session in the repo is running', () => {
activityMocks.useRepoActivityState.mockReturnValue('running')
renderWithRouter(<RepoCard {...defaultProps} />)
expect(screen.getByLabelText('Sessions running')).toBeInTheDocument()
})
it('should show the needs-input indicator when a session in the repo needs input', () => {
activityMocks.useRepoActivityState.mockReturnValue('needs-input')
renderWithRouter(<RepoCard {...defaultProps} />)
expect(screen.getByLabelText('Session needs input')).toBeInTheDocument()
})
it('should not show an activity indicator when the repo is idle', () => {
activityMocks.useRepoActivityState.mockReturnValue(null)
renderWithRouter(<RepoCard {...defaultProps} />)
expect(screen.queryByLabelText('Sessions running')).not.toBeInTheDocument()
expect(screen.queryByLabelText('Session needs input')).not.toBeInTheDocument()
})
})
+4 -14
View File
@@ -2,24 +2,13 @@ import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Loader2, GitBranch, FolderOpen, AlertCircle } from "lucide-react";
import { getRepoDisplayName } from "@/lib/utils";
import type { Repo } from "@/api/types";
import type { GitStatusResponse } from "@/types/git"
import { RepoActivityIndicator } from "@/components/activity/RepoActivityIndicator"
import { RepoRowActions } from "./RepoRowActions"
interface RepoCardProps {
repo: {
id: number;
name?: string | null;
repoUrl?: string | null;
localPath?: string;
sourcePath?: string;
branch?: string;
currentBranch?: string;
cloneStatus: string;
isWorktree?: boolean;
isLocal?: boolean;
fullPath?: string;
lastAccessedAt?: number;
};
repo: Repo;
onDelete: (id: number) => void;
isDeleting: boolean;
isSelected?: boolean;
@@ -90,6 +79,7 @@ export function RepoCard({
{isReady && (
<div className={`w-2 h-2 rounded-full shrink-0 ${isDirty ? 'bg-highlight' : 'bg-success'}`} />
)}
<RepoActivityIndicator repo={repo} />
</div>
{!manageMode && !isSelected && !hasSelectedRepos && (
@@ -217,7 +217,7 @@ export function ProjectPickerContent({
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open
{switchHint ? ` · ${switchHint} sessions` : ''}
{switchHint ? ` · ${switchHint} active` : ''}
</div>
</div>
)
@@ -4,7 +4,9 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Repo, Session } from '@/api/types'
import type { ActiveWorkGroups, ActiveWorkItem, ActiveWorkState } from '@/lib/activeWork'
import { stubMatchMedia } from '@/test/test-utils'
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
import { SessionPickerDialog } from './SessionPickerDialog'
@@ -23,8 +25,15 @@ const mocks = vi.hoisted(() => ({
getOpenCodeLocation: vi.fn(),
sessionPins: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
repos: [] as Repo[],
activeWorkGroups: { needsInput: [], running: [], recent: [] } as ActiveWorkGroups,
activeWorkWindowMs: 0,
preferences: undefined as
| { leaderKey?: string; keyboardShortcuts?: Record<string, string>; directShortcuts?: string[] }
| {
leaderKey?: string
keyboardShortcuts?: Record<string, string>
directShortcuts?: string[]
activityWindowMinutes?: number
}
| undefined,
}))
@@ -77,6 +86,15 @@ vi.mock('@/hooks/useSidebarRepoGroups', () => ({
useNavigableRepos: () => ({ repos: mocks.repos, isLoading: false, refetch: vi.fn() }),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: (windowMs: number) => {
mocks.activeWorkWindowMs = windowMs
return { groups: mocks.activeWorkGroups, isLoading: false, isError: false }
},
useActivityWindowMs: () =>
(mocks.preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES) * 60 * 1000,
}))
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
@@ -106,6 +124,22 @@ function repo(id: number, name: string, fullPath: string): Repo {
}
}
function activeWorkItem(
id: string,
title: string,
directory: string,
state: ActiveWorkState = 'recent',
): ActiveWorkItem {
const itemRepo = mocks.repos.find((candidate) => candidate.fullPath === directory) ?? mocks.repos[0]
return {
key: `${directory}:${id}`,
session: session(id, title, directory),
repo: itemRepo,
state,
path: `/repos/${itemRepo.id}/sessions/${id}`,
}
}
function renderWithClient(ui: React.ReactElement) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const directory = mocks.repos[0]?.fullPath
@@ -144,6 +178,10 @@ const openProjectsTab = () => {
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Projects' }))
}
const openActiveTab = () => {
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Active' }))
}
describe('SessionPickerDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -159,6 +197,8 @@ describe('SessionPickerDialog', () => {
mocks.sessionPins = []
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.sessionsData = []
mocks.activeWorkGroups = { needsInput: [], running: [], recent: [] }
mocks.activeWorkWindowMs = 0
mocks.preferences = undefined
})
@@ -492,10 +532,11 @@ describe('SessionPickerDialog', () => {
expect(screen.getByRole('option', { name: /Active session/ })).toHaveAttribute('aria-selected', 'true')
})
it('renders a Sessions/Projects tab switcher and defaults to the sessions tab', () => {
it('renders an Active/Sessions/Projects tab switcher and defaults to the sessions tab', () => {
renderPicker()
expect(screen.getByRole('tab', { name: 'Sessions' })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByRole('tab', { name: 'Active' })).toHaveAttribute('aria-selected', 'false')
expect(screen.getByRole('tab', { name: 'Projects' })).toHaveAttribute('aria-selected', 'false')
expect(combobox()).toHaveAttribute('placeholder', 'Search sessions...')
})
@@ -619,14 +660,19 @@ describe('SessionPickerDialog', () => {
expect(screen.getByText('No projects found')).toBeInTheDocument()
})
it('toggles between tabs with the default Ctrl+S binding in either search input', async () => {
it('cycles Active, Sessions and Projects with the default Ctrl+S binding', async () => {
renderPicker()
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
expect(await screen.findByRole('tab', { name: 'Active', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
})
it('honors a configured switch binding and shows it in the footer', async () => {
@@ -638,7 +684,7 @@ describe('SessionPickerDialog', () => {
fireEvent.keyDown(combobox(), { key: 'g', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
expect(screen.getByText(/Ctrl\+G sessions/)).toBeInTheDocument()
expect(screen.getByText(/Ctrl\+G active/)).toBeInTheDocument()
})
it('shows the normalized leader, arrow and key in the footer for a leader switch binding', () => {
@@ -691,4 +737,101 @@ describe('SessionPickerDialog', () => {
expect(screen.getByRole('tab', { name: 'Sessions' })).toHaveAttribute('aria-selected', 'true'),
)
})
it('groups active work into needs input, running and recent sections with repo labels', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
needsInput: [activeWorkItem('ses_ni', 'Needs input task', '/w/a', 'needs-input')],
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
recent: [activeWorkItem('ses_recent', 'Recent task', '/w/a', 'recent')],
}
renderPicker()
openActiveTab()
expect(await screen.findByText('Needs input')).toBeInTheDocument()
expect(screen.getByText('Running')).toBeInTheDocument()
expect(screen.getByText('Recent')).toBeInTheDocument()
expect(screen.getByRole('option', { name: /Needs input task/ }).textContent).toContain('alpha')
expect(screen.getByRole('option', { name: /Running task/ }).textContent).toContain('beta')
expect(screen.getByRole('option', { name: /Recent task/ }).textContent).toContain('alpha')
expect(mocks.activeWorkWindowMs).toBe(30 * 60 * 1000)
})
it('skips empty active work sections and shows the empty state for the configured window', async () => {
mocks.preferences = { activityWindowMinutes: 120 }
renderPicker()
openActiveTab()
expect(
await screen.findByText('No active or recent sessions in the last 120 minutes'),
).toBeInTheDocument()
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.queryByText('Running')).not.toBeInTheDocument()
expect(screen.queryByText('Recent')).not.toBeInTheDocument()
})
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 = {
needsInput: [],
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
recent: [activeWorkItem('ses_recent', 'Recent task', '/w/a', 'recent')],
}
const { onSelectSession } = renderPicker()
openActiveTab()
const running = await screen.findByRole('option', { name: /Running task/ })
expect(running).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
expect(screen.getByRole('option', { name: /Recent task/ })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'Enter' })
expect(onSelectSession).toHaveBeenCalledWith(expect.objectContaining({ id: 'ses_recent' }), mocks.repos[0])
})
it('filters active work rows by title and drops sections left empty', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
needsInput: [activeWorkItem('ses_ni', 'Needs input task', '/w/a', 'needs-input')],
running: [],
recent: [activeWorkItem('ses_recent', 'Recent task', '/w/b', 'recent')],
}
renderPicker()
openActiveTab()
await screen.findByRole('option', { name: /Needs input task/ })
fireEvent.change(combobox(), { target: { value: 'recent' } })
expect(screen.queryByRole('option', { name: /Needs input task/ })).not.toBeInTheDocument()
expect(screen.getByRole('option', { name: /Recent task/ })).toBeInTheDocument()
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.getByText('Recent')).toBeInTheDocument()
})
it('pins an active work row from the shared row menu', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
needsInput: [],
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
recent: [],
}
renderPicker()
const user = userEvent.setup()
openActiveTab()
await screen.findByRole('option', { name: /Running task/ })
await user.click(screen.getByRole('button', { name: 'Session actions' }))
await user.click(await screen.findByText('Pin'))
expect(mocks.togglePinMock).toHaveBeenCalledWith({
sessionId: 'ses_run',
directory: '/w/b',
pinned: true,
})
})
})
@@ -4,6 +4,7 @@ import { format, startOfDay } from 'date-fns'
import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
import { getOpenCodeLocation } from '@/api/opencode'
import type { Repo, Session } from '@/api/types'
import type { ActiveWorkItem } from '@/lib/activeWork'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import {
@@ -20,6 +21,7 @@ import { ProjectPickerContent } from '@/components/session/ProjectPickerContent'
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 { useSessionSearch } from '@/hooks/useSessionSearch'
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
@@ -36,8 +38,22 @@ 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 = 'sessions' | 'projects'
type SessionPickerTab = 'active' | 'sessions' | 'projects'
const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects']
const SESSION_PICKER_TAB_LABELS: Record<SessionPickerTab, string> = {
active: 'Active',
sessions: 'Sessions',
projects: 'Projects',
}
function nextSessionPickerTab(tab: SessionPickerTab): SessionPickerTab {
const index = SESSION_PICKER_TABS.indexOf(tab)
return SESSION_PICKER_TABS[(index + 1) % SESSION_PICKER_TABS.length]
}
interface SessionPickerDialogProps {
open: boolean
@@ -153,11 +169,7 @@ function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isAct
const status = useSessionStatusForSession(sessionID)
if (status.type !== 'idle') {
return (
<SessionStatusIndicator
sessionID={sessionID}
size="sm"
className="[&>div]:gap-0 [&>div>div]:h-1.5 [&>div>div]:w-px"
/>
<SessionStatusIndicator sessionID={sessionID} size="sm" />
)
}
if (isActive) {
@@ -283,6 +295,311 @@ 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
}
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 SessionPickerKeyNavOptions {
rows: SessionPickerRow[]
cursorIndex: number
cursorRow: SessionPickerRow | undefined
moveCursor: (index: number) => void
onOpenRow: (row: SessionPickerRow) => void
onDeleteRow: (row: SessionPickerRow) => void
onToggleAllProjects?: () => void
}
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 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)
}
},
[rows, cursorIndex, cursorRow, moveCursor, onOpenRow, onDeleteRow, onToggleAllProjects],
)
}
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>
)
}
interface SessionPickerListProps {
listId: string
optionBaseId: string
ariaLabel: string
sections: SessionPickerSection[]
rows: SessionPickerRow[]
rowIndexByKey: ReadonlyMap<string, number>
cursorIndex: number
activeSessionID?: string
pinnedKeys: ReadonlySet<string>
pendingDeleteKey: string | null
showRepo: boolean
labelFor?: (row: SessionPickerRow) => string | undefined
emptyState: React.ReactNode
onOpenRow: (row: SessionPickerRow) => void
onHoverRow: (index: number) => void
onTogglePin: (row: SessionPickerRow) => void
onRequestDelete: (session: Session) => void
registerRef: (key: string, node: HTMLDivElement | null) => void
listRef?: React.RefObject<HTMLDivElement | null>
onScroll?: (event: React.UIEvent<HTMLDivElement>) => void
children?: React.ReactNode
}
function SessionPickerList({
listId,
optionBaseId,
ariaLabel,
sections,
rows,
rowIndexByKey,
cursorIndex,
activeSessionID,
pinnedKeys,
pendingDeleteKey,
showRepo,
labelFor,
emptyState,
onOpenRow,
onHoverRow,
onTogglePin,
onRequestDelete,
registerRef,
listRef,
onScroll,
children,
}: SessionPickerListProps) {
return (
<div
ref={listRef}
role="listbox"
id={listId}
aria-label={ariaLabel}
onScroll={onScroll}
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">{emptyState}</div>
) : (
<>
{sections.map((section) => (
<div
key={section.id}
role="group"
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
>
<div
id={`${optionBaseId}-heading-${section.id}`}
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
>
{section.heading}
</div>
{section.rows.map((row) => {
const index = rowIndexByKey.get(row.key) ?? -1
return (
<SessionPickerRowItem
key={row.key}
row={row}
index={index}
optionId={optionId(optionBaseId, index)}
isCursor={index === cursorIndex}
isActive={row.session.id === activeSessionID}
isPinned={pinnedKeys.has(row.key)}
isPendingDelete={pendingDeleteKey === row.key}
showRepo={showRepo}
label={labelFor?.(row)}
onOpen={onOpenRow}
onHover={onHoverRow}
onTogglePin={onTogglePin}
onRequestDelete={onRequestDelete}
registerRef={registerRef}
/>
)
})}
</div>
))}
{children}
</>
)}
</div>
)
}
interface SessionPickerContentProps {
open: boolean
currentRepo: Repo | undefined
@@ -307,7 +624,6 @@ function SessionPickerContent({
const [allProjects, toggleAllProjects] = usePersistentBoolean(ALL_PROJECTS_STORAGE_KEY, false)
const { repos } = useNavigableRepos()
const listRef = useRef<HTMLDivElement>(null)
const rowRefs = useRef(new Map<string, HTMLDivElement>())
const listId = useId()
const optionBaseId = useId()
@@ -369,8 +685,6 @@ function SessionPickerContent({
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
const deleteSession = useDeleteSession(directories)
const [cursorKey, setCursorKey] = useState<string | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
const sections = useMemo(
@@ -378,52 +692,27 @@ function SessionPickerContent({
[filteredSessions, pinnedKeys, resolveRepo],
)
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
const rowIndexByKey = useMemo(
() => new Map(rows.map((row, index) => [row.key, index])),
[rows],
)
const activeRow = useMemo(
() => rows.find((row) => row.session.id === activeSessionID),
[rows, activeSessionID],
)
const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
const cursorIndex = useMemo(() => {
if (cursorKey) {
const index = rowIndexByKey.get(cursorKey)
if (index !== undefined) return index
}
return defaultCursorKey ? rowIndexByKey.get(defaultCursorKey) ?? -1 : -1
}, [cursorKey, rowIndexByKey, defaultCursorKey])
const cursorRow = cursorIndex >= 0 ? rows[cursorIndex] : undefined
const {
rowIndexByKey,
cursorIndex,
cursorRow,
pendingDeleteKey,
setPendingDeleteKey,
registerRef,
moveCursor,
resetCursor,
} = useSessionPickerCursor(rows, defaultCursorKey)
useEffect(() => {
setCursorKey(null)
setPendingDeleteKey(null)
}, [trimmedQuery, allProjects])
const setRowRef = useCallback((key: string, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRow) return
const node = rowRefs.current.get(cursorRow.key)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRow])
const moveCursor = useCallback(
(index: number) => {
const row = rows[index]
if (!row) return
setCursorKey(row.key)
setPendingDeleteKey(null)
},
[rows],
)
resetCursor()
}, [trimmedQuery, allProjects, resetCursor])
const openRow = useCallback(
(row: SessionPickerRow | undefined) => {
@@ -454,64 +743,18 @@ function SessionPickerContent({
setPendingDeleteKey(null)
})
},
[pendingDeleteKey, performDelete],
[pendingDeleteKey, performDelete, setPendingDeleteKey],
)
const handleSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const moveBy = (delta: number, wrap: boolean) => {
if (rows.length === 0) return
const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
const raw = base + delta
const next = wrap ? ((raw % rows.length) + rows.length) % rows.length : Math.max(0, Math.min(rows.length - 1, raw))
moveCursor(next)
}
const key = event.key
const ctrlKey = event.key.toLowerCase()
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRow) return
event.preventDefault()
openRow(cursorRow)
return
}
if (event.ctrlKey && ctrlKey === 'a') {
event.preventDefault()
toggleAllProjects()
return
}
if (event.ctrlKey && ctrlKey === 'd') {
if (!cursorRow) return
event.preventDefault()
deleteRow(cursorRow)
}
},
[cursorIndex, rows, moveCursor, cursorRow, openRow, toggleAllProjects, deleteRow],
)
const handleSearchKeyDown = useSessionPickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: openRow,
onDeleteRow: deleteRow,
onToggleAllProjects: toggleAllProjects,
})
const handleListScroll = useCallback(
(event: React.UIEvent<HTMLDivElement>) => {
@@ -556,122 +799,93 @@ function SessionPickerContent({
})
}, [sessionToDelete, performDelete])
const labelFor = useCallback(
(row: SessionPickerRow) =>
allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical),
[allProjects, location?.project.canonical],
)
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={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search sessions..."
className="h-9 pl-9"
autoComplete="off"
name="session-picker-search"
/>
</div>
<Button
type="button"
variant="outline"
size="sm"
aria-pressed={allProjects}
onClick={toggleAllProjects}
className="h-9 shrink-0"
>
{allProjects ? 'All projects' : 'This project'}
{hasFinePointer && (
<kbd className="ml-1 rounded border border-border bg-muted px-1 text-[10px] text-muted-foreground">
Ctrl+A
</kbd>
)}
</Button>
</div>
<SessionPickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search sessions..."
name="session-picker-search"
trailing={
<Button
type="button"
variant="outline"
size="sm"
aria-pressed={allProjects}
onClick={toggleAllProjects}
className="h-9 shrink-0"
>
{allProjects ? 'All projects' : 'This project'}
{hasFinePointer && (
<kbd className="ml-1 rounded border border-border bg-muted px-1 text-[10px] text-muted-foreground">
Ctrl+A
</kbd>
)}
</Button>
}
/>
<div
ref={listRef}
role="listbox"
id={listId}
aria-label="Sessions"
<SessionPickerList
listRef={listRef}
listId={listId}
optionBaseId={optionBaseId}
ariaLabel="Sessions"
sections={sections}
rows={rows}
rowIndexByKey={rowIndexByKey}
cursorIndex={cursorIndex}
activeSessionID={activeSessionID}
pinnedKeys={pinnedKeys}
pendingDeleteKey={pendingDeleteKey}
showRepo={allProjects}
labelFor={labelFor}
emptyState={
isPickerLoading
? 'Loading sessions...'
: isSearchPending
? 'Searching sessions...'
: trimmedQuery
? 'No sessions found'
: 'No sessions yet'
}
onOpenRow={openRow}
onHoverRow={moveCursor}
onTogglePin={handleTogglePin}
onRequestDelete={handleRequestDelete}
registerRef={registerRef}
onScroll={handleListScroll}
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">
{isPickerLoading
? 'Loading sessions...'
: isSearchPending
? 'Searching sessions...'
: trimmedQuery
? 'No sessions found'
: 'No sessions yet'}
{isFetchNextPageError && (
<div className="flex flex-col items-center gap-2 py-4">
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
<Button
variant="outline"
size="sm"
onClick={() => {
void fetchNextPage()
}}
disabled={isFetchingNextPage}
>
Retry
</Button>
</div>
) : (
<>
{sections.map((section) => (
<div
key={section.id}
role="group"
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
>
<div
id={`${optionBaseId}-heading-${section.id}`}
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
>
{section.heading}
</div>
{section.rows.map((row) => {
const index = rowIndexByKey.get(row.key) ?? -1
return (
<SessionPickerRowItem
key={row.key}
row={row}
index={index}
optionId={optionId(optionBaseId, index)}
isCursor={index === cursorIndex}
isActive={row.session.id === activeSessionID}
isPinned={pinnedKeys.has(row.key)}
isPendingDelete={pendingDeleteKey === row.key}
showRepo={allProjects}
label={allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical)}
onOpen={openRow}
onHover={moveCursor}
onTogglePin={handleTogglePin}
onRequestDelete={handleRequestDelete}
registerRef={setRowRef}
/>
)
})}
</div>
))}
{isFetchNextPageError && (
<div className="flex flex-col items-center gap-2 py-4">
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
<Button
variant="outline"
size="sm"
onClick={() => {
void fetchNextPage()
}}
disabled={isFetchingNextPage}
>
Retry
</Button>
</div>
)}
{isFetchingNextPage && rows.length > 0 && (
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
)}
</>
)}
</div>
{isFetchingNextPage && rows.length > 0 && (
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
)}
</SessionPickerList>
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
@@ -694,6 +908,211 @@ function SessionPickerContent({
)
}
interface ActivePickerContentProps {
open: boolean
activeSessionID?: string
onSelectSession: (session: Session, repo: Repo) => void
onDeleteActiveSession: () => void
switchHint: string
searchInputRef: React.RefObject<HTMLInputElement | null>
}
function ActivePickerContent({
open,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
switchHint,
searchInputRef,
}: ActivePickerContentProps) {
const windowMs = useActivityWindowMs()
const windowMinutes = Math.round(windowMs / MS_PER_MINUTE)
const { groups, isLoading, isError } = useActiveWork(windowMs)
const listId = useId()
const optionBaseId = useId()
const [query, setQuery] = useState('')
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) => {
const rows: SessionPickerRow[] = []
for (const item of definition.items) {
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 }] : []
})
}, [groups, trimmedQuery])
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
const activeRow = useMemo(
() => rows.find((row) => row.session.id === activeSessionID),
[rows, activeSessionID],
)
const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
const {
rowIndexByKey,
cursorIndex,
cursorRow,
pendingDeleteKey,
setPendingDeleteKey,
registerRef,
moveCursor,
resetCursor,
} = useSessionPickerCursor(rows, defaultCursorKey)
useEffect(() => {
resetCursor()
}, [trimmedQuery, resetCursor])
const { data: sessionPins } = useSessionPins()
const togglePin = useToggleSessionPin()
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
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 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({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: openRow,
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`
return (
<>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<SessionPickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search sessions..."
name="active-picker-search"
/>
<SessionPickerList
listId={listId}
optionBaseId={optionBaseId}
ariaLabel="Active sessions"
sections={sections}
rows={rows}
rowIndexByKey={rowIndexByKey}
cursorIndex={cursorIndex}
activeSessionID={activeSessionID}
pinnedKeys={pinnedKeys}
pendingDeleteKey={pendingDeleteKey}
showRepo
emptyState={emptyState}
onOpenRow={openRow}
onHoverRow={moveCursor}
onTogglePin={handleTogglePin}
onRequestDelete={handleRequestDelete}
registerRef={registerRef}
/>
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open · Ctrl+D delete
{switchHint ? ` · ${switchHint} sessions` : ''}
</div>
</div>
<DeleteSessionDialog
open={sessionToDelete !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setSessionToDelete(null)
}}
onConfirm={() => {
void confirmDelete()
}}
onCancel={() => setSessionToDelete(null)}
isDeleting={deleteSession.isPending}
/>
</>
)
}
export function SessionPickerDialog({
open,
onOpenChange,
@@ -704,6 +1123,7 @@ export function SessionPickerDialog({
onSelectRepo,
}: SessionPickerDialogProps) {
const searchInputRef = useRef<HTMLInputElement>(null)
const activeSearchInputRef = useRef<HTMLInputElement>(null)
const projectSearchInputRef = useRef<HTMLInputElement>(null)
const focusSearchAfterSwitchRef = useRef(false)
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
@@ -729,7 +1149,7 @@ export function SessionPickerDialog({
const toggleTab = useCallback(() => {
focusSearchAfterSwitchRef.current = true
setTab((current) => (current === 'sessions' ? 'projects' : 'sessions'))
setTab((current) => nextSessionPickerTab(current))
}, [])
useShortcutActions({ switchPickerTab: open ? toggleTab : undefined })
@@ -743,6 +1163,7 @@ export function SessionPickerDialog({
const frame = requestAnimationFrame(() => {
focusSearchAfterSwitchRef.current = false
if (tab === 'projects') projectSearchInputRef.current?.focus()
else if (tab === 'active') activeSearchInputRef.current?.focus()
else searchInputRef.current?.focus()
})
return () => cancelAnimationFrame(frame)
@@ -769,12 +1190,26 @@ export function SessionPickerDialog({
className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0"
>
<div className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
<DialogTitle className="sr-only">{tab === 'sessions' ? 'Sessions' : 'Projects'}</DialogTitle>
<DialogTitle className="sr-only">{SESSION_PICKER_TAB_LABELS[tab]}</DialogTitle>
<TabsList>
<TabsTrigger value="active">Active</TabsTrigger>
<TabsTrigger value="sessions">Sessions</TabsTrigger>
<TabsTrigger value="projects">Projects</TabsTrigger>
</TabsList>
</div>
<TabsContent
value="active"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
>
<ActivePickerContent
open={open}
activeSessionID={activeSessionID}
onSelectSession={onSelectSession}
onDeleteActiveSession={onDeleteActiveSession}
switchHint={switchHint}
searchInputRef={activeSearchInputRef}
/>
</TabsContent>
<TabsContent
value="sessions"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
@@ -0,0 +1,64 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ActivitySettings } from './ActivitySettings'
import { useSettings } from '@/hooks/useSettings'
import type { UserPreferences } from '@/api/types/settings'
import { createUseSettingsMock } from '@/test/test-utils'
vi.mock('@/hooks/useSettings')
const basePreferences: UserPreferences = {
theme: 'dark',
mode: 'build',
autoScroll: true,
expandDiffs: true,
expandToolCalls: false,
showReasoning: false,
simpleChatMode: false,
keyboardShortcuts: {},
customCommands: [],
}
function mockUseSettings(overrides: Partial<ReturnType<typeof useSettings>> = {}) {
vi.mocked(useSettings).mockReturnValue(createUseSettingsMock({ preferences: basePreferences, ...overrides }))
}
describe('ActivitySettings', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('shows the default window when the preference is unset', () => {
mockUseSettings()
render(<ActivitySettings />)
expect(screen.getByRole('combobox', { name: 'Recent activity window' })).toHaveTextContent('30 minutes')
})
it('shows the stored window', () => {
mockUseSettings({ preferences: { ...basePreferences, activityWindowMinutes: 120 } })
render(<ActivitySettings />)
expect(screen.getByRole('combobox', { name: 'Recent activity window' })).toHaveTextContent('2 hours')
})
it('saves the chosen window in minutes', async () => {
const user = userEvent.setup()
const updateSettings = vi.fn()
mockUseSettings({ updateSettings })
render(<ActivitySettings />)
await user.click(screen.getByRole('combobox', { name: 'Recent activity window' }))
await user.click(screen.getByRole('option', { name: '4 hours' }))
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({ activityWindowMinutes: 240 })
})
})
@@ -0,0 +1,40 @@
import { useSettings } from '@/hooks/useSettings'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { ACTIVITY_WINDOW_MINUTE_OPTIONS, DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
import { formatActivityWindow } from '@/lib/activeWork'
export function ActivitySettings() {
const { preferences, updateSettings } = useSettings()
const activityWindowMinutes = preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
return (
<div className="space-y-6">
<h2 className="text-lg font-semibold text-foreground">Activity</h2>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="activityWindowMinutes">Recent activity window</Label>
<p className="text-sm text-muted-foreground">
How far back the Activity panel lists recently active sessions.
</p>
</div>
<Select
value={String(activityWindowMinutes)}
onValueChange={(value) => updateSettings({ activityWindowMinutes: Number(value) })}
>
<SelectTrigger id="activityWindowMinutes" className="w-full shrink-0 sm:w-40">
<SelectValue placeholder="Select a window" />
</SelectTrigger>
<SelectContent>
{ACTIVITY_WINDOW_MINUTE_OPTIONS.map((minutes) => (
<SelectItem key={minutes} value={String(minutes)}>
{formatActivityWindow(minutes)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
)
}
@@ -7,6 +7,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { Switch } from '@/components/ui/switch'
import { SessionAutomationSettings } from './SessionAutomationSettings'
import { WalkthroughSettings } from './WalkthroughSettings'
import { ActivitySettings } from './ActivitySettings'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
@@ -199,6 +200,8 @@ export function GeneralSettings() {
<SessionAutomationSettings />
<WalkthroughSettings />
<ActivitySettings />
</div>
)
}
@@ -0,0 +1,144 @@
import { act, cleanup, render } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
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) =>
circles(root)
.map((circle, index) => (circle.getAttribute('fill-opacity') === '1' ? index : -1))
.filter((index) => index >= 0)
const litIndexesFor = (frame: string) =>
brailleDots(frame)
.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', () => {
expect(brailleDots('⠏')).toEqual([true, true, true, true, false, false, false, false])
})
})
describe('ActivitySpinner', () => {
beforeEach(() => {
vi.useFakeTimers()
stubMatchMedia(false)
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
it('renders eight dots with the first frame lit and hidden from assistive technology', () => {
const { container } = render(<ActivitySpinner />)
expect(circles(container)).toHaveLength(8)
expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[0]))
expect(container.querySelector('svg')).toHaveAttribute('aria-hidden', 'true')
})
it('advances one frame every 80ms and wraps after the last frame', () => {
const { container } = render(<ActivitySpinner />)
expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[0]))
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]))
})
it('drives every mounted spinner from a single shared ticker', () => {
const { container } = render(
<>
<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 />)
const svg = container.querySelector('svg')
expect(svg).toHaveAttribute('viewBox', '0 0 9 16')
const dots = circles(container).map((circle) => ({
cx: Number(circle.getAttribute('cx')),
cy: Number(circle.getAttribute('cy')),
r: Number(circle.getAttribute('r')),
}))
expect(dots).toHaveLength(8)
for (const dot of dots) {
expect(dot.cx - dot.r).toBeGreaterThan(0)
expect(dot.cx + dot.r).toBeLessThan(9)
expect(dot.cy - dot.r).toBeGreaterThan(0)
expect(dot.cy + dot.r).toBeLessThan(16)
}
for (let i = 0; i < dots.length; i += 1) {
for (let j = i + 1; j < dots.length; j += 1) {
const distance = Math.hypot(dots[i].cx - dots[j].cx, dots[i].cy - dots[j].cy)
expect(distance).toBeGreaterThanOrEqual(dots[i].r + dots[j].r)
}
}
})
})
@@ -0,0 +1,96 @@
import { useSyncExternalStore } from 'react'
import { cn } from '@/lib/utils'
export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const
const FRAME_INTERVAL_MS = 80
const BRAILLE_BASE = 0x2800
const DOT_GRID: ReadonlyArray<readonly [number, number]> = [
[0, 0],
[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[0, 3],
[1, 3],
]
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 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
* top-to-bottom, and dot7 and dot8 the bottom-left and bottom-right cells.
*/
export function brailleDots(frame: string): boolean[] {
const bits = (frame.codePointAt(0) ?? BRAILLE_BASE) - BRAILLE_BASE
return DOT_GRID.map((_, index) => (bits & (1 << index)) !== 0)
}
/**
* 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
* `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"
viewBox="0 0 9 16"
className={cn('inline-block h-4 w-[9px] shrink-0', className)}
>
{DOT_GRID.map(([column, row], index) => (
<circle
key={index}
cx={COLUMN_X[column]}
cy={ROW_Y[row]}
r={DOT_RADIUS}
fill="currentColor"
fillOpacity={dots[index] ? 1 : UNLIT_DOT_OPACITY}
/>
))}
</svg>
)
}
@@ -1,6 +1,7 @@
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it } from 'vitest'
import { SessionStatusIndicator } from './session-status-indicator'
import { SPINNER_FRAMES, brailleDots } from './activity-spinner'
import { useSessionStatus } from '@/stores/sessionStatusStore'
const resetStore = () => {
@@ -11,6 +12,7 @@ const resetStore = () => {
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
directories: new Map(),
runningShells: new Map(),
revision: 0,
})
@@ -34,4 +36,14 @@ describe('SessionStatusIndicator background activity', () => {
expect(container).toBeEmptyDOMElement()
})
it('renders the braille spinner with a running label for a busy session', () => {
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
const { container } = render(<SessionStatusIndicator sessionID="session-a" size="sm" />)
expect(screen.getByLabelText('Running')).toBeInTheDocument()
const litDots = container.querySelectorAll('svg[aria-hidden="true"] circle[fill-opacity="1"]')
expect(litDots).toHaveLength(brailleDots(SPINNER_FRAMES[0]).filter(Boolean).length)
})
})
@@ -1,4 +1,5 @@
import { memo, useEffect, useState } from 'react'
import { ActivitySpinner } from '@/components/ui/activity-spinner'
import { useHasBackgroundActivity, useSessionStatusForSession, type SessionStatusType } from '@/stores/sessionStatusStore'
interface SessionStatusIndicatorProps {
@@ -11,6 +12,10 @@ interface SessionStatusIndicatorProps {
const SCANNER_WIDTH = 6
const SCANNER_SEGMENTS = 12
/**
* Shows a session's activity. `sm` renders the braille spinner sized for list rows;
* `md` renders the animated scanner used by the session composer.
*/
export const SessionStatusIndicator = memo(function SessionStatusIndicator({
sessionID,
className = '',
@@ -25,6 +30,9 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
const backgroundOnly = status.type === 'idle' && hasBackground
useEffect(() => {
if (size !== 'md') {
return
}
if (status.type === 'idle' && !hasBackground) {
return
}
@@ -45,7 +53,7 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
}, 60)
return () => clearInterval(interval)
}, [status.type, hasBackground, direction])
}, [size, status.type, hasBackground, direction])
useEffect(() => {
if (!showLabel || status.type !== 'retry') {
@@ -68,6 +76,34 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
return null
}
if (size === 'sm') {
const colorClass = backgroundOnly
? 'text-muted-foreground'
: status.type === 'retry'
? 'text-warning'
: status.type === 'compact'
? 'text-primary'
: 'text-info'
const label = backgroundOnly
? 'Background tasks running'
: status.type === 'retry'
? 'Retrying'
: status.type === 'compact'
? 'Compacting'
: 'Running'
return (
<span
role="img"
aria-label={label}
title={backgroundOnly ? label : undefined}
className={`inline-flex items-center ${colorClass} ${className}`}
>
<ActivitySpinner />
</span>
)
}
const getSegmentColor = (index: number, statusType: SessionStatusType['type'], background: boolean) => {
const distance = Math.abs(index - (position + SCANNER_WIDTH / 2))
const maxDistance = SCANNER_WIDTH / 2
@@ -105,7 +141,7 @@ export const SessionStatusIndicator = memo(function SessionStatusIndicator({
return 'bg-info/20'
}
const segmentClass = size === 'sm' ? 'w-0.5 h-2' : 'w-1 h-4'
const segmentClass = 'w-1 h-4'
const containerGap = showLabel ? 'gap-2' : ''
return (
+10 -10
View File
@@ -1447,8 +1447,8 @@ describe('EventProvider permissions and forms', () => {
it('resolves ancestry when a permission arrives for an unknown session', async () => {
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1', location: { directory: '/repo' } })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1', location: { directory: '/repo' } })
return Promise.reject(new Error('Session not found'))
})
@@ -1475,8 +1475,8 @@ describe('EventProvider permissions and forms', () => {
it('resolves ancestry when a form arrives for an unknown session', async () => {
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1', location: { directory: '/repo' } })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1', location: { directory: '/repo' } })
return Promise.reject(new Error('Session not found'))
})
@@ -2269,8 +2269,8 @@ describe('EventProvider permissions and forms', () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({ 'child-1': { type: 'running' } })
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1', location: { directory: '/repo' } })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1', location: { directory: '/repo' } })
return Promise.reject(new Error('Session not found'))
})
@@ -2394,8 +2394,8 @@ describe('EventProvider permissions and forms', () => {
{ id: 'shell-1', status: 'running', metadata: { sessionID: 'child-1' } },
])
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1' })
if (sessionID === 'child-1') return Promise.resolve({ id: 'child-1', parentID: 'parent-1', location: { directory: '/repo' } })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1', location: { directory: '/repo' } })
return Promise.reject(new Error('Session not found'))
})
@@ -2421,8 +2421,8 @@ describe('EventProvider permissions and forms', () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listActiveSessions.mockResolvedValue({ 'child-1': { type: 'running' } })
mocks.getSession.mockImplementation((sessionID: string) => {
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1', parentID: 'grandparent-1' })
if (sessionID === 'grandparent-1') return Promise.resolve({ id: 'grandparent-1' })
if (sessionID === 'parent-1') return Promise.resolve({ id: 'parent-1', parentID: 'grandparent-1', location: { directory: '/repo' } })
if (sessionID === 'grandparent-1') return Promise.resolve({ id: 'grandparent-1', location: { directory: '/repo' } })
return Promise.reject(new Error('Session not found'))
})
+44 -12
View File
@@ -20,6 +20,7 @@ import { showToast } from '@/lib/toast'
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
import { getSessionPath, parseRepoRoute } from '@/lib/navigation'
import { repoMatchesDirectory } from '@/components/navigation/sidebar-session-tree'
import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough'
import { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
import {
@@ -46,6 +47,20 @@ type StreamEvent = (V2Event & { directory?: string }) | { type: 'ssh.host-key-re
type SessionScopedItem = { id: string; sessionID: string }
const EMPTY_SESSION_IDS: string[] = []
/**
* Session ids whose queued item list is non-empty. The array reference is stable across renders
* while the set of ids is unchanged, even when the backing record is replaced.
*/
function usePendingSessionIDs(bySession: Record<string, unknown[]>): string[] {
const idsKey = useMemo(
() => Object.keys(bySession).filter((sessionID) => (bySession[sessionID]?.length ?? 0) > 0).join('\u0000'),
[bySession],
)
return useMemo(() => (idsKey ? idsKey.split('\u0000') : EMPTY_SESSION_IDS), [idsKey])
}
function groupBySession<T extends SessionScopedItem>(items: T[]): Record<string, T[]> {
return items.reduce<Record<string, T[]>>((grouped, item) => {
const existing = grouped[item.sessionID] ?? []
@@ -60,18 +75,6 @@ function sortById<T extends SessionScopedItem>(items: T[]): T[] {
return [...items].sort((a, b) => a.id.localeCompare(b.id))
}
function normalizeDirectory(directory?: string | null) {
return directory?.replace(/\/+$/, '') ?? null
}
function repoMatchesDirectory(repo: Repo, directory?: string | null) {
const normalizedDirectory = normalizeDirectory(directory)
if (!normalizedDirectory) return false
return [repo.fullPath, repo.localPath, repo.sourcePath]
.some((path) => normalizeDirectory(path) === normalizedDirectory)
}
function isSessionWithinView(
sessionID: string,
viewedSessionID: string,
@@ -152,6 +155,10 @@ interface EventContextValue {
permissions: {
current: PermissionRequest | null
pendingCount: number
/**
* Ids of sessions with at least one pending permission request, stable while the queue is unchanged.
*/
pendingSessionIDs: string[]
/**
* Session currently being viewed from the route, or null when no session route is active.
*/
@@ -187,6 +194,10 @@ interface EventContextValue {
forms: {
current: FormInfo | null
pendingCount: number
/**
* Ids of sessions with at least one pending form, stable while the queue is unchanged.
*/
pendingSessionIDs: string[]
/**
* Answers a form and removes it from the queue. Resolves, after showing an "expired" toast,
* when the server no longer knows the form (`FormNotFoundError`); rejects on any other failure.
@@ -279,6 +290,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const allPermissions = useMemo(() => Object.values(permissionsBySession).flat(), [permissionsBySession])
const allForms = useMemo(() => Object.values(formsBySession).flat(), [formsBySession])
const pendingPermissionSessionIDs = usePendingSessionIDs(permissionsBySession)
const pendingFormSessionIDs = usePendingSessionIDs(formsBySession)
const viewedSessionId = useMemo(
() => parseRepoRoute(location.pathname).sessionId,
[location.pathname],
@@ -532,6 +546,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
try {
const session = await getSession(lookupID)
useSessionStatus.getState().setSessionParent(lookupID, session.parentID ?? null)
useSessionStatus.getState().setSessionDirectory(lookupID, session.location.directory)
currentID = session.parentID ?? null
} catch (error) {
if (import.meta.env.DEV) {
@@ -644,6 +659,9 @@ 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])
@@ -658,6 +676,9 @@ 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])
@@ -672,6 +693,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}
case 'session.status': {
const { sessionID, status } = event.data
if (event.directory) {
useSessionStatus.getState().setSessionDirectory(sessionID, event.directory)
}
useSessionStatus.getState().setStatus(sessionID, status)
break
}
@@ -680,6 +704,9 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
break
}
case 'session.execution.started': {
if (event.directory) {
useSessionStatus.getState().setSessionDirectory(event.data.sessionID, event.directory)
}
useSessionStatus.getState().clearOutcome(event.data.sessionID)
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'busy' })
break
@@ -732,6 +759,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
) {
const sessionID = info.metadata.sessionID
useSessionStatus.getState().setShellRunning(info.id, sessionID, event.directory)
useSessionStatus.getState().setSessionDirectory(sessionID, event.directory)
if (!useSessionStatus.getState().parents.has(sessionID)) {
void resolveSessionAncestry([sessionID])
}
@@ -857,6 +885,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
permissions: {
current: currentPermission,
pendingCount: allPermissions.length,
pendingSessionIDs: pendingPermissionSessionIDs,
viewedSessionId,
currentDirectory: currentPermissionDirectory,
currentIsFromDifferentSession,
@@ -872,6 +901,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
forms: {
current: currentForm,
pendingCount: allForms.length,
pendingSessionIDs: pendingFormSessionIDs,
reply: replyToForm,
cancel: cancelPendingForm,
dismiss: removeForm,
@@ -887,6 +917,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
respondToSSHHostKey,
currentPermission,
allPermissions.length,
pendingPermissionSessionIDs,
viewedSessionId,
currentPermissionDirectory,
currentIsFromDifferentSession,
@@ -899,6 +930,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
syncPermissionsForSession,
currentForm,
allForms.length,
pendingFormSessionIDs,
replyToForm,
cancelPendingForm,
removeForm,
+164
View File
@@ -0,0 +1,164 @@
import { useMemo } from 'react'
import { useQueries } from '@tanstack/react-query'
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
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'
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
* `activityWindowMinutes` with the shared default as a fallback.
*/
export function useActivityWindowMs(): number {
const { preferences } = useSettings()
const minutes = preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
return minutes * MS_PER_MINUTE
}
const combineSessions = (results: Array<{ data?: Session }>): Session[] =>
results.flatMap((result) => (result.data ? [result.data] : []))
/**
* Distinct active roots for a badge: needs-input roots and running roots that are not also
* pending input. Reads only the session-status store and the pending queues, with no network.
*/
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
return useMemo(() => {
const pendingInputSessionIDs = new Set([
...pendingPermissionSessionIDs,
...pendingFormSessionIDs,
])
const roots = collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs })
let running = 0
for (const rootID of roots.running) {
if (!roots.needsInput.has(rootID)) running += 1
}
return { needsInput: roots.needsInput.size, running }
}, [statuses, parents, runningShells, pendingPermissionSessionIDs, pendingFormSessionIDs])
}
/**
* Whether a repo has any active session, returned as a primitive so rows only re-render when it
* 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],
)
return useSessionStatus((state) =>
activeRepoState({
repo,
statuses: state.statuses,
parents: state.parents,
runningShells: state.runningShells,
directories: state.directories,
pendingInputSessionIDs,
}),
)
}
/**
* The full active-work list. Performs network reads, so it must only be used by components that
* are mounted while visible (the session picker fetches only while open).
*/
export function useActiveWork(windowMs: number): {
groups: ActiveWorkGroups
isLoading: boolean
isError: boolean
} {
const { repos, isLoading: isReposLoading } = useNavigableRepos()
const directories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
const {
data: sessions,
isLoading: isSessionsLoading,
isError: isSessionsError,
} = useSessionsAcrossDirectories(directories, {
allDirectories: true,
limit: ACTIVE_WORK_SESSION_LIMIT,
})
const statuses = useSessionStatus((state) => state.statuses)
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 roots = useMemo(
() =>
collectActiveRoots({
statuses,
parents,
runningShells,
pendingInputSessionIDs: [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
}),
[statuses, parents, runningShells, pendingPermissionSessionIDs, pendingFormSessionIDs],
)
const listedSessionIDs = useMemo(
() => new Set(sessions.map((session) => session.id)),
[sessions],
)
const missingRootIDs = useMemo(() => {
const ids = new Set<string>()
for (const sessionID of roots.needsInput) {
if (!listedSessionIDs.has(sessionID)) ids.add(sessionID)
}
for (const sessionID of roots.running) {
if (!listedSessionIDs.has(sessionID)) ids.add(sessionID)
}
return [...ids]
}, [roots, listedSessionIDs])
const fetchedSessions = useQueries({
queries: missingRootIDs.map((sessionID) => sessionQueryOptions(sessionID)),
combine: combineSessions,
})
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 groups = useMemo(
() =>
buildActiveWork({
now: Date.now(),
windowMs,
repos,
sessions: mergedSessions,
roots,
outcomes,
}),
[windowMs, repos, mergedSessions, roots, outcomes],
)
return {
groups,
isLoading: isReposLoading || isSessionsLoading,
isError: isSessionsError,
}
}
+29 -1
View File
@@ -1,5 +1,33 @@
import { describe, expect, it } from 'vitest'
import { toggleToolDialogParams, toggleToolPanelParams } from './useToolPanel'
import { createElement } from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { isPanelTool, toggleToolDialogParams, toggleToolPanelParams, useToolPanel } from './useToolPanel'
describe('activity tool', () => {
it('is a panel tool', () => {
expect(isPanelTool('activity')).toBe(true)
})
it('clears without opening a dialog when the panel is not docked', async () => {
function Probe() {
useToolPanel(false)
const location = useLocation()
return createElement('div', { 'data-testid': 'search' }, location.search)
}
render(
createElement(
MemoryRouter,
{ initialEntries: ['/repos/1/sessions/abc?panel=activity'] },
createElement(Probe),
),
)
await waitFor(() => expect(screen.getByTestId('search').textContent).not.toContain('panel=activity'))
expect(screen.getByTestId('search').textContent).not.toContain('dialog=activity')
})
})
describe('toggleToolPanelParams', () => {
it('opens a tool, clears other tools owned params, and preserves unrelated params', () => {
+2 -2
View File
@@ -4,7 +4,7 @@ import { useUrlParams } from './useUrlParams'
const PANEL_PARAM = 'panel'
const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules'] as const
const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules', 'activity'] as const
export type PanelTool = (typeof PANEL_TOOLS)[number]
@@ -14,7 +14,7 @@ const TOOL_OWNED_PARAMS: Partial<Record<PanelTool, readonly string[]>> = {
schedules: ['scheduleTab', 'scheduleDialog', 'jobId', 'runId'],
}
const PANEL_ONLY_TOOLS: ReadonlySet<PanelTool> = new Set(['schedules'])
const PANEL_ONLY_TOOLS: ReadonlySet<PanelTool> = new Set(['schedules', 'activity'])
export function isPanelTool(value: string | null): value is PanelTool {
return value !== null && (PANEL_TOOLS as readonly string[]).includes(value)
+296
View File
@@ -0,0 +1,296 @@
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'
const NOW = 1_000_000_000_000
const WINDOW_MS = 60_000
function createSession(id: string, updated: number, directory: string): Session {
return {
id,
projectID: 'proj-1',
title: `Session ${id}`,
time: { created: updated - 10000, updated },
location: { directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(overrides: Partial<Repo> & { id: number; fullPath: string }): Repo {
return {
localPath: `repos/${overrides.id}`,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
...overrides,
}
}
function statuses(entries: Record<string, SessionStatusType>): Map<string, SessionStatusType> {
return new Map(Object.entries(entries))
}
const repoA = createRepo({ id: 1, fullPath: '/repos/a' })
const emptyRoots = { needsInput: new Set<string>(), running: new Set<string>() }
describe('formatActivityWindow', () => {
it('labels the known minute options', () => {
expect(formatActivityWindow(15)).toBe('15 minutes')
expect(formatActivityWindow(30)).toBe('30 minutes')
expect(formatActivityWindow(60)).toBe('1 hour')
expect(formatActivityWindow(120)).toBe('2 hours')
expect(formatActivityWindow(240)).toBe('4 hours')
expect(formatActivityWindow(480)).toBe('8 hours')
expect(formatActivityWindow(1440)).toBe('24 hours')
})
it('falls back to minutes for unknown values', () => {
expect(formatActivityWindow(45)).toBe('45 minutes')
expect(formatActivityWindow(90)).toBe('90 minutes')
})
it('falls back to hours for unknown values divisible by sixty', () => {
expect(formatActivityWindow(180)).toBe('3 hours')
})
})
describe('rootSessionID', () => {
it('climbs parents to the top-most root', () => {
const parents = new Map<string, string | null>([['child', 'parent'], ['parent', 'root'], ['root', null]])
expect(rootSessionID('child', parents)).toBe('root')
expect(rootSessionID('parent', parents)).toBe('root')
expect(rootSessionID('root', parents)).toBe('root')
})
it('terminates on a parent cycle', () => {
const parents = new Map<string, string | null>([['a', 'b'], ['b', 'a']])
expect(typeof rootSessionID('a', parents)).toBe('string')
})
})
describe('collectActiveRoots', () => {
it('rolls a busy child up to its root as running', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const roots = collectActiveRoots({
statuses: statuses({ child: { type: 'busy' } }),
parents,
runningShells: new Map(),
pendingInputSessionIDs: [],
})
expect(roots.running.has('root')).toBe(true)
expect(roots.running.has('child')).toBe(false)
expect(roots.needsInput.size).toBe(0)
})
it('rolls a running shell under a child up to the root', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const roots = collectActiveRoots({
statuses: statuses({}),
parents,
runningShells: new Map([['shell-1', { sessionID: 'child' }]]),
pendingInputSessionIDs: [],
})
expect(roots.running.has('root')).toBe(true)
})
it('rolls a pending permission up to the root as needs-input', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const roots = collectActiveRoots({
statuses: statuses({}),
parents,
runningShells: new Map(),
pendingInputSessionIDs: ['child'],
})
expect(roots.needsInput.has('root')).toBe(true)
})
it('terminates on a parent cycle', () => {
const parents = new Map<string, string | null>([['a', 'b'], ['b', 'a']])
const roots = collectActiveRoots({
statuses: statuses({ a: { type: 'busy' } }),
parents,
runningShells: new Map(),
pendingInputSessionIDs: [],
})
expect(roots.running.size).toBe(1)
})
})
describe('activeRepoState', () => {
const repo = repoA
const noShells = new Map<string, { sessionID: string; directory: string }>()
it('matches a busy session by its own directory', () => {
const state = activeRepoState({
repo,
statuses: statuses({ child: { type: 'busy' } }),
parents: new Map([['child', 'root'], ['root', null]]),
runningShells: noShells,
directories: new Map([['child', '/repos/a']]),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
it('matches a busy session by its root directory', () => {
const state = activeRepoState({
repo,
statuses: statuses({ child: { type: 'busy' } }),
parents: new Map([['child', 'root'], ['root', null]]),
runningShells: noShells,
directories: new Map([['root', '/repos/a']]),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
it('matches a running shell by its own directory', () => {
const state = activeRepoState({
repo,
statuses: statuses({}),
parents: new Map(),
runningShells: new Map([['shell-1', { sessionID: 'orphan', directory: '/repos/a' }]]),
directories: new Map(),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
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,
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/local/path']]),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
it('prefers needs-input over running', () => {
const state = activeRepoState({
repo,
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/a']]),
pendingInputSessionIDs: ['session'],
})
expect(state).toBe('needs-input')
})
it('returns null when every matching session is idle', () => {
const state = activeRepoState({
repo,
statuses: statuses({ session: { type: 'idle' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/a']]),
pendingInputSessionIDs: [],
})
expect(state).toBeNull()
})
})
describe('buildActiveWork', () => {
it('puts a root with both a pending permission and a busy status in needs-input only, once', () => {
const parents = new Map<string, string | null>()
const roots = collectActiveRoots({
statuses: statuses({ root: { type: 'busy' } }),
parents,
runningShells: new Map(),
pendingInputSessionIDs: ['root'],
})
const sessions = [createSession('root', NOW - 1000, '/repos/a')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots, outcomes: new Map() })
expect(groups.needsInput.map((item) => item.session.id)).toEqual(['root'])
expect(groups.running).toEqual([])
const all = [...groups.needsInput, ...groups.running, ...groups.recent]
expect(all.filter((item) => item.session.id === 'root')).toHaveLength(1)
})
it('includes a session updated exactly at the window boundary and excludes the one before it', () => {
const sessions = [
createSession('inside', NOW - WINDOW_MS, '/repos/a'),
createSession('outside', NOW - WINDOW_MS - 1, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['inside'])
})
it('excludes archived sessions', () => {
const archived = createSession('archived', NOW - 1000, '/repos/a')
archived.time.archived = NOW - 500
const sessions = [createSession('active', NOW - 1000, '/repos/a'), archived]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['active'])
})
it('excludes sessions whose directory matches no repo', () => {
const sessions = [createSession('orphan', NOW - 1000, '/repos/other')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toEqual([])
})
it('resolves a repo by local path and trims trailing slashes', () => {
const repo = createRepo({ id: 5, fullPath: '/repos/full', localPath: '/local/path' })
const sessions = [createSession('local', NOW - 1000, '/local/path/')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repo], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toHaveLength(1)
expect(groups.recent[0].repo.id).toBe(5)
expect(groups.recent[0].key).toBe('/local/path/:local')
expect(groups.recent[0].path).toBe('/repos/5/sessions/local')
})
it('sorts each group by updated descending', () => {
const sessions = [
createSession('oldest', NOW - 3000, '/repos/a'),
createSession('newest', NOW - 1000, '/repos/a'),
createSession('middle', NOW - 2000, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['newest', 'middle', 'oldest'])
})
it('carries the child outcome onto the item', () => {
const sessions = [createSession('root', NOW - 1000, '/repos/a')]
const outcomes = new Map<string, ChildOutcome>([['root', 'failed']])
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes })
expect(groups.recent[0].outcome).toBe('failed')
})
})
+191
View File
@@ -0,0 +1,191 @@
import type { Repo, Session } from '@/api/types'
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'
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',
}
/**
* 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.
*/
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'}`
}
return `${minutes} minutes`
}
export type ActiveWorkState = 'needs-input' | 'running' | 'recent'
export interface ActiveWorkItem {
key: string
session: Session
repo: Repo
state: ActiveWorkState
outcome?: ChildOutcome
path: string
}
export interface ActiveWorkGroups {
needsInput: ActiveWorkItem[]
running: ActiveWorkItem[]
recent: ActiveWorkItem[]
}
export function rootSessionID(
sessionID: string,
parents: ReadonlyMap<string, string | null>,
): string {
const visited = new Set<string>()
let currentID = sessionID
while (!visited.has(currentID)) {
visited.add(currentID)
const parentID = parents.get(currentID)
if (parentID === undefined || parentID === null) break
currentID = parentID
}
return currentID
}
/**
* Rolls every active or pending session id up to its root. `needsInput` and `running` may both
* contain a root; callers apply the needs-input over running priority when grouping.
*/
export function collectActiveRoots(input: {
statuses: ReadonlyMap<string, SessionStatusType>
parents: ReadonlyMap<string, string | null>
runningShells: ReadonlyMap<string, { sessionID: string }>
pendingInputSessionIDs: Iterable<string>
}): { needsInput: Set<string>; running: Set<string> } {
const { statuses, parents, runningShells, pendingInputSessionIDs } = input
const needsInput = new Set<string>()
for (const sessionID of pendingInputSessionIDs) {
needsInput.add(rootSessionID(sessionID, parents))
}
const running = new Set<string>()
for (const [sessionID, status] of statuses) {
if (status.type === 'idle') continue
running.add(rootSessionID(sessionID, parents))
}
for (const shell of runningShells.values()) {
running.add(rootSessionID(shell.sessionID, parents))
}
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
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))
}
for (const sessionID of pendingInputSessionIDs) {
if (sessionMatches(sessionID)) return 'needs-input'
}
for (const [sessionID, status] of statuses) {
if (status.type === 'idle') continue
if (sessionMatches(sessionID)) return 'running'
}
for (const shell of runningShells.values()) {
if (repoMatchesDirectory(repo, shell.directory) || sessionMatches(shell.sessionID)) return 'running'
}
return null
}
/**
* Groups the given sessions into needs-input, running, and recent roots. A session appears in
* exactly one group (needs-input over running over recent) and only when it resolves to a repo.
*/
export function buildActiveWork(input: {
now: number
windowMs: number
repos: Repo[]
sessions: Session[]
roots: { needsInput: Set<string>; running: Set<string> }
outcomes: ReadonlyMap<string, ChildOutcome>
}): ActiveWorkGroups {
const { now, windowMs, repos, sessions, roots, outcomes } = input
const windowStart = now - windowMs
const needsInput: ActiveWorkItem[] = []
const running: ActiveWorkItem[] = []
const recent: ActiveWorkItem[] = []
const seen = new Set<string>()
for (const session of sessions) {
if (seen.has(session.id)) continue
if (session.time.archived) continue
const state: ActiveWorkState | null = roots.needsInput.has(session.id)
? 'needs-input'
: roots.running.has(session.id)
? 'running'
: session.time.updated >= windowStart
? 'recent'
: null
if (!state) continue
const repo = findRepoForDirectory(repos, session.location.directory)
if (!repo) continue
seen.add(session.id)
const item: ActiveWorkItem = {
key: getSessionKey(session),
session,
repo,
state,
outcome: outcomes.get(session.id),
path: getSessionPath(repo.id, session.id),
}
if (state === 'needs-input') needsInput.push(item)
else if (state === 'running') running.push(item)
else recent.push(item)
}
const byUpdatedDesc = (a: ActiveWorkItem, b: ActiveWorkItem) =>
b.session.time.updated - a.session.time.updated
needsInput.sort(byUpdatedDesc)
running.sort(byUpdatedDesc)
recent.sort(byUpdatedDesc)
return { needsInput, running, recent }
}
@@ -39,6 +39,11 @@ vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDia
vi.mock('@/components/source-control', () => ({ SourceControlPanel: () => null }))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWorkCounts: () => ({ needsInput: 0, running: 0 }),
useRepoActivityState: () => null,
}))
vi.mock('@/components/terminal/TerminalView', async () => {
const React = await import('react')
return {
@@ -58,6 +58,10 @@ vi.mock('@/hooks/useRepoSiblings', () => ({
}))
vi.mock('@/hooks/useRepoActivity', () => ({ useRepoActivity: mocks.useRepoActivity }))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWorkCounts: () => ({ needsInput: 0, running: 0 }),
useRepoActivityState: () => null,
}))
vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE }))
vi.mock('@/hooks/useOpenCode', () => ({ useCreateSession: mocks.useCreateSession }))
vi.mock('@/hooks/useMultiRuns', () => ({
@@ -42,6 +42,10 @@ vi.mock('@/hooks/useRepoSiblings', () => ({
}))
vi.mock('@/hooks/useRepoActivity', () => ({ useRepoActivity: mocks.useRepoActivity }))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWorkCounts: () => ({ needsInput: 0, running: 0 }),
useRepoActivityState: () => null,
}))
vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE }))
vi.mock('@/hooks/useOpenCode', () => ({ useCreateSession: mocks.useCreateSession }))
@@ -108,6 +108,11 @@ vi.mock('@/contexts/EventContext', async (importOriginal) => {
}
})
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWorkCounts: () => ({ needsInput: 0, running: 0 }),
useRepoActivityState: () => null,
}))
vi.mock('@/api/repos', () => ({
getRepo: vi.fn((repoId: number) => Promise.resolve(repoId === 0 ? {
id: 0,
@@ -135,6 +135,11 @@ vi.mock('@/contexts/EventContext', async (importOriginal) => {
}
})
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWorkCounts: () => ({ needsInput: 0, running: 0 }),
useRepoActivityState: () => null,
}))
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve({
id: 1,
@@ -130,6 +130,11 @@ vi.mock('@/contexts/EventContext', async (importOriginal) => {
}
})
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWorkCounts: () => ({ needsInput: 0, running: 0 }),
useRepoActivityState: () => null,
}))
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve({
id: 1,
+16
View File
@@ -30,6 +30,7 @@ interface SessionStatusStore {
knownSessions: Set<string>
outcomes: Map<string, ChildOutcome>
parents: Map<string, string | null>
directories: Map<string, string>
runningShells: Map<string, RunningShell>
shellRevisions: Map<string, number>
shellRevision: number
@@ -45,6 +46,7 @@ interface SessionStatusStore {
getStatus: (sessionID: string) => SessionStatusType
clearStatus: (sessionID: string) => void
setSessionParent: (sessionID: string, parentID: string | null) => void
setSessionDirectory: (sessionID: string, directory: string) => void
setShellRunning: (shellID: string, sessionID: string, directory: string) => void
clearShell: (shellID: string) => void
replaceRunningShells: (directory: string, shells: Array<{ id: string; sessionID: string }>, token: ShellSnapshotToken) => void
@@ -245,6 +247,7 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
directories: new Map(),
runningShells: new Map(),
shellRevisions: new Map(),
shellRevision: 0,
@@ -448,6 +451,15 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
})
},
setSessionDirectory: (sessionID: string, directory: string) => {
if (get().directories.get(sessionID) === directory) return
set((state) => {
const directories = new Map(state.directories)
directories.set(sessionID, directory)
return { directories }
})
},
setShellRunning: (shellID: string, sessionID: string, directory: string) => {
const current = get().runningShells.get(shellID)
if (current && current.sessionID === sessionID && current.directory === directory) {
@@ -533,6 +545,7 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
current.knownSessions.has(sessionID) ||
current.outcomes.has(sessionID) ||
current.parents.has(sessionID) ||
current.directories.has(sessionID) ||
ownsShell
if (!hasSession && inFlightSnapshots.size === 0) return
@@ -542,12 +555,14 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
const knownSessions = new Set(state.knownSessions)
const outcomes = new Map(state.outcomes)
const parents = new Map(state.parents)
const directories = new Map(state.directories)
const runningShells = new Map(state.runningShells)
statuses.delete(sessionID)
statusCache.delete(sessionID)
knownSessions.delete(sessionID)
outcomes.delete(sessionID)
parents.delete(sessionID)
directories.delete(sessionID)
const removedShellIDs: string[] = []
for (const [shellID, shell] of runningShells.entries()) {
if (shell.sessionID !== sessionID) continue
@@ -560,6 +575,7 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
knownSessions,
outcomes,
parents,
directories,
runningShells,
...(shellTouchPatch(state, removedShellIDs) ?? {}),
...(recordRevisionPatch(state, sessionID) ?? {}),
+1
View File
@@ -91,6 +91,7 @@ export const AssistantSettingsPatchSchema = UserPreferencesSchema.pick({
mode: true,
defaultModel: true,
walkthroughModel: true,
activityWindowMinutes: true,
defaultAgent: true,
autoScroll: true,
expandDiffs: true,
+6
View File
@@ -66,6 +66,10 @@ export type STTConfig = {
export const DEFAULT_LEADER_KEY = 'Ctrl+X';
export const DEFAULT_ACTIVITY_WINDOW_MINUTES = 30;
export const ACTIVITY_WINDOW_MINUTE_OPTIONS = [15, 30, 60, 120, 240, 480, 1440] as const;
export const DEFAULT_KEYBOARD_SHORTCUTS = {
submit: 'Cmd+Enter',
abort: 'Escape',
@@ -192,6 +196,7 @@ export const UserPreferencesSchema = z.object({
mode: z.enum(["plan", "build"]),
defaultModel: z.string().optional(),
walkthroughModel: z.string().optional(),
activityWindowMinutes: z.number().int().min(5).max(1440).optional(),
defaultAgent: z.string().optional(),
autoScroll: z.boolean(),
expandDiffs: z.boolean(),
@@ -249,6 +254,7 @@ export const DEFAULT_USER_PREFERENCES = {
theme: "dark" as const,
colorTheme: MANAGER_COLOR_THEME_ID,
mode: "build" as const,
activityWindowMinutes: DEFAULT_ACTIVITY_WINDOW_MINUTES,
autoScroll: true,
expandDiffs: true,
expandToolCalls: false,