Merge pull request #436 from chriswritescode-dev/feat/activity-switcher

feat(activity): surface active work across the session picker, tool rail and mobile
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-16 12:48:52 -04:00
commit 33d9523666
60 files changed
+3992 -491

No files matched your search

+6
View File
@@ -11,6 +11,8 @@ import type {
import {
UserPreferencesSchema,
DEFAULT_USER_PREFERENCES,
DEFAULT_ACTIVITY_WINDOW_MINUTES,
isActivityWindowMinutes,
} from '../types/settings'
import { isColorThemeId, MANAGER_COLOR_THEME_ID } from '@opencode-manager/shared/themes'
@@ -69,6 +71,10 @@ export class SettingsService {
parsed.colorTheme = MANAGER_COLOR_THEME_ID
}
if (!isActivityWindowMinutes(parsed.activityWindowMinutes)) {
parsed.activityWindowMinutes = DEFAULT_ACTIVITY_WINDOW_MINUTES
}
const validated = UserPreferencesSchema.parse({
...DEFAULT_USER_PREFERENCES,
...parsed,
@@ -181,6 +181,39 @@ describe('internal/settings routes', () => {
expect(body.error).toBe('Invalid request body')
})
it('PATCH /api/internal/settings with { activityWindowMinutes: 45 } returns 400 (non-option reject)', async () => {
const res = await app.request('/api/internal/settings', {
method: 'PATCH',
body: JSON.stringify({ activityWindowMinutes: 45 }),
headers: {
'content-type': 'application/json',
authorization: `Bearer ${token}`,
},
})
expect(res.status).toBe(400)
const body = await res.json() as { error: string }
expect(body.error).toBe('Invalid request body')
})
it('PATCH /api/internal/settings with { activityWindowMinutes: 60 } persists an allowed option', async () => {
const patchRes = await app.request('/api/internal/settings', {
method: 'PATCH',
body: JSON.stringify({ activityWindowMinutes: 60 }),
headers: {
'content-type': 'application/json',
authorization: `Bearer ${token}`,
},
})
expect(patchRes.status).toBe(200)
const getRes = await app.request('/api/internal/settings', {
headers: { authorization: `Bearer ${token}` },
})
expect(getRes.status).toBe(200)
const body = await getRes.json() as { preferences: { activityWindowMinutes: number } }
expect(body.preferences.activityWindowMinutes).toBe(60)
})
it('PATCH /api/internal/settings with { tts: { voice: "x", speed: 1.5 } } merges and preserves apiKey/endpoint', async () => {
// Seed a full TTS config (including secrets) directly via settingsService
settingsService.updateSettings({
+35
View File
@@ -1519,6 +1519,41 @@ describe('Settings Routes - OpenCode Upgrade', () => {
})
})
describe('PATCH / - activity window validation', () => {
it.each([5, 45, 2000, 30.5])('rejects activityWindowMinutes %s with 400', async (minutes) => {
const res = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { activityWindowMinutes: minutes } }),
}))
const json = await res.json() as { error: string }
expect(res.status).toBe(400)
expect(json.error).toBe('Invalid settings data')
expect(mockUpdateSettings).not.toHaveBeenCalled()
})
it('accepts an allowed activityWindowMinutes value', async () => {
mockGetSettings.mockReturnValue({
preferences: { activityWindowMinutes: 30 },
updatedAt: 1,
})
mockUpdateSettings.mockReturnValue({
preferences: { activityWindowMinutes: 60 },
updatedAt: 2,
})
const res = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { activityWindowMinutes: 60 } }),
}))
expect(res.status).toBe(200)
expect(mockUpdateSettings).toHaveBeenCalledWith({ activityWindowMinutes: 60 }, 'default')
})
})
describe('PATCH / - sandbox enable guard', () => {
afterEach(() => {
forceProcessAttestation(null)
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@opencode-manager/shared/schemas'
import { SettingsService } from '../../src/services/settings'
import { allMigrations } from '../../src/db/migrations'
import { migrate } from '../../src/db/migration-runner'
describe('SettingsService', () => {
let db: Database
let settingsService: SettingsService
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
settingsService = new SettingsService(db)
})
it('recovers from a stored activityWindowMinutes outside the allowed options without losing other preferences', () => {
db.prepare(
`INSERT INTO user_preferences (user_id, preferences, updated_at)
VALUES (?, ?, ?)`
).run('default', JSON.stringify({ activityWindowMinutes: 5, autoScroll: false }), Date.now())
const settings = settingsService.getSettings()
expect(settings.preferences.activityWindowMinutes).toBe(DEFAULT_ACTIVITY_WINDOW_MINUTES)
expect(settings.preferences.autoScroll).toBe(false)
})
})
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import {
ACTIVITY_WINDOW_MINUTE_OPTIONS,
ActivityWindowMinutesSchema,
UserPreferencesSchema,
} from '@opencode-manager/shared/schemas'
describe('ActivityWindowMinutesSchema', () => {
it.each(ACTIVITY_WINDOW_MINUTE_OPTIONS)('accepts the configured option %s', (minutes) => {
expect(ActivityWindowMinutesSchema.safeParse(minutes).success).toBe(true)
})
it.each([5, 45, 2000, 30.5])('rejects %s', (minutes) => {
expect(ActivityWindowMinutesSchema.safeParse(minutes).success).toBe(false)
})
it('rejects a non-option value through UserPreferencesSchema', () => {
expect(UserPreferencesSchema.shape.activityWindowMinutes.safeParse(45).success).toBe(false)
expect(UserPreferencesSchema.shape.activityWindowMinutes.safeParse(60).success).toBe(true)
})
})
+13
View File
@@ -125,6 +125,19 @@ describe('OpenCode facade', () => {
expect(lastRequest().init.method).toBe('GET')
})
it('omits the parentID filter when including child sessions', async () => {
fetchMock.mockResolvedValue(
jsonResponse({ data: [sessionInfo('ses_child', '/repo')], cursor: {} }),
)
await listSessionPage({ directory: '/repo', limit: 25, order: 'desc', includeChildren: true })
expect(lastRequest().url).toBe(
'http://localhost/api/opencode/api/session?limit=25&order=desc&directory=%2Frepo',
)
expect(lastRequest().init.method).toBe('GET')
})
it('reads a single session from the V2 session route', async () => {
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_1', '/repo') }))
+2 -1
View File
@@ -48,6 +48,7 @@ export interface SessionPageInput {
order?: 'asc' | 'desc'
search?: string
cursor?: string
includeChildren?: boolean
}
export interface CreateSessionInput {
@@ -102,7 +103,7 @@ export async function listSessionPage(input: SessionPageInput): Promise<SessionP
...(input.directory === undefined ? {} : { directory: input.directory }),
...(input.project === undefined ? {} : { project: input.project }),
...(input.subpath === undefined ? {} : { subpath: input.subpath }),
parentID: 'null',
...(input.includeChildren ? {} : { parentID: 'null' }),
limit: input.limit,
order: input.order,
search: input.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,360 @@
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_MINUTES = 30
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}`,
updatedAt: overrides.session.time.updated,
...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'
minutes?: number
} = {},
) =>
render(
<MemoryRouter initialEntries={[path]}>
<ActivityList minutes={WINDOW_MINUTES} 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('renders the empty state with an hour-scale window', () => {
setGroups({})
renderList(vi.fn(), '/', { minutes: 1440 })
expect(screen.getByText('No active or recent sessions in the last 24 hours')).toBeInTheDocument()
})
it('calls onNavigate with the item when a row is clicked', () => {
const onNavigate = vi.fn()
const item = createItem({ state: 'recent', session: createSession('c1', 'Recent'), repo: createRepo(3, 'Gamma') })
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,222 @@
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 {
ACTIVE_WORK_GROUPS,
MS_PER_MINUTE,
formatActivityEmptyMessage,
type ActiveWorkItem,
} from '@/lib/activeWork'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
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 {
/** Activity window in minutes. */
minutes: number
/** Called when a row is chosen; the caller owns navigation so each surface can apply its own history and close rules. */
onNavigate: (item: ActiveWorkItem) => void
hideWhenEmpty?: boolean
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.updatedAt))}
</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.updatedAt))}
</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({
minutes,
onNavigate,
hideWhenEmpty = false,
title,
variant = 'full',
}: ActivityListProps) {
const location = useLocation()
const { groups, isLoading, isError } = useActiveWork(minutes * MS_PER_MINUTE)
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
return (
<p className="p-4 text-sm text-muted-foreground">{formatActivityEmptyMessage(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}
/>
))
) : (
<>
{ACTIVE_WORK_GROUPS.map((group) => (
<ActivityGroup
key={group.key}
heading={group.heading}
items={groups[group.key]}
currentSessionID={route.sessionId}
currentRepoId={route.repoId}
onSelect={onNavigate}
/>
))}
</>
)}
</section>
)
}
@@ -0,0 +1,20 @@
import { useActivityWindowMinutes } 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 minutes = useActivityWindowMinutes()
return (
<ActivityList
minutes={minutes}
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,62 @@ vi.mock('react-router-dom', async () => {
}
})
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
useActivityWindowMinutes: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
useRepoActivityState: () => null,
}))
function createActiveWorkItem(): ActiveWorkItem {
const now = Date.now()
return {
key: '1:s1',
state: 'recent',
updatedAt: now,
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 +156,8 @@ describe('MoreDrawer', () => {
cloneStatus: 'ready',
clonedAt: 0,
})
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
setActivityGroups({})
})
it('renders Settings and Logout menu items', () => {
@@ -264,4 +323,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(),
useActivityWindowMinutes: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
useRepoActivityState: () => null,
}))
vi.mock('@/api/repos')
vi.mock('@/contexts/EventContext', () => ({
@@ -92,6 +104,34 @@ function createRepo(id: number, name: string, fullPath: string) {
}
}
function createActiveWorkItem(): ActiveWorkItem {
const session = createSession('s1', Date.now(), '/path/to/repo1')
return {
key: '1:s1',
state: 'recent',
session,
repo: createRepo(1, 'repo1', '/path/to/repo1'),
updatedAt: session.time.updated,
path: '/repos/1/sessions/s1',
}
}
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 +170,8 @@ describe('RepoQuickSwitchSheet', () => {
sessionsData.splice(0, sessionsData.length)
sessionsHookCalls.splice(0, sessionsHookCalls.length)
permissionSessions.current.clear()
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
setActivityGroups({})
})
it('renders with loading state', async () => {
@@ -783,6 +825,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(),
useActivityWindowMinutes: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActiveWorkCounts: activityMocks.useActiveWorkCounts,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
}))
vi.mock('@/components/file-browser/FileBrowser', () => ({
FileBrowser: ({ initialSelectedFile }: { initialSelectedFile?: string }) => <div>files-tool {initialSelectedFile}</div>,
}))
@@ -76,6 +90,55 @@ function search(): URLSearchParams {
return new URLSearchParams(screen.getByTestId('search').textContent ?? '')
}
const WINDOW_MINUTES = 30
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',
updatedAt: session.time.updated,
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 (
@@ -86,6 +149,13 @@ function HomeHarness() {
)
}
beforeEach(() => {
vi.clearAllMocks()
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 0, running: 0 })
activityMocks.useActivityWindowMinutes.mockReturnValue(WINDOW_MINUTES)
setActivityGroups()
})
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
@@ -251,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'
@@ -22,10 +23,58 @@ 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, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { formatActivityWindow } from '@/lib/activeWork'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { restoreOverlayFocus } from '@/lib/overlayFocus'
import { cn } from '@/lib/utils'
const PANEL_WIDTH_CLASSES: Partial<Record<PanelTool, string>> = {
activity: 'w-80',
}
function ActivityWindowLabel() {
const minutes = useActivityWindowMinutes()
return (
<span className="shrink-0 text-xs text-muted-foreground">
Last {formatActivityWindow(minutes)}
</span>
)
}
function ActivityPanelBody() {
const navigate = useNavigate()
const minutes = useActivityWindowMinutes()
return (
<div className="min-h-0 flex-1 overflow-y-auto">
<ActivityList
minutes={minutes}
onNavigate={(item) => navigate({ pathname: item.path, search: '?panel=activity' })}
/>
</div>
)
}
function ActivityRailIndicator() {
const { needsInput, running } = useActiveWorkCounts()
const total = needsInput + running
const label = total > 0 ? `Activity, ${needsInput} needs input, ${running} running` : 'Activity'
return (
<>
<span className="sr-only">{label}</span>
<ActivityCountPill
needsInput={needsInput}
running={running}
className="absolute -right-0.5 -top-0.5"
/>
</>
)
}
interface ToolSidePanelProps {
panel: ToolPanelState
filesBasePath: string | undefined
@@ -47,9 +96,14 @@ interface RailButtonProps {
item: MoreDrawerItem
active: boolean
onClick: () => void
/**
* Rendered inside the button. When present, the indicator owns the button's accessible name,
* so the item label is not applied as an `aria-label`.
*/
indicator?: ReactNode
}
function RailButton({ item, active, onClick }: RailButtonProps) {
function RailButton({ item, active, onClick, indicator }: RailButtonProps) {
const Icon = item.icon
return (
<Tooltip delayDuration={0}>
@@ -57,10 +111,10 @@ function RailButton({ item, active, onClick }: RailButtonProps) {
<button
type="button"
onClick={onClick}
aria-label={item.label}
aria-label={indicator ? undefined : 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 +123,7 @@ function RailButton({ item, active, onClick }: RailButtonProps) {
)}
>
<Icon className="h-4 w-4" />
{indicator}
</button>
</TooltipTrigger>
<TooltipContent side="left" align="center">
@@ -140,6 +195,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':
@@ -170,10 +226,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 />
@@ -216,7 +278,13 @@ 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)}
indicator={tool === 'activity' ? <ActivityRailIndicator /> : 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. */
@@ -7,6 +7,23 @@ import { partitionSessions, selectRootSessions } from '@/components/session/sess
export const SIDEBAR_SESSIONS_PER_REPO = 10
/** Collects the loaded session from each query result, dropping unresolved queries. */
export const combineQuerySessions = (results: Array<{ data?: Session }>): Session[] =>
results.flatMap((result) => (result.data ? [result.data] : []))
/** Appends extra sessions after the base list, deduplicating by id within both lists. */
export function mergeExtraSessions(sessions: Session[], extraSessions: Session[]): Session[] {
if (extraSessions.length === 0) return sessions
const seen = new Set(sessions.map((session) => session.id))
const extras: Session[] = []
for (const session of extraSessions) {
if (seen.has(session.id)) continue
seen.add(session.id)
extras.push(session)
}
return extras.length === 0 ? sessions : [...sessions, ...extras]
}
export interface SidebarSessionItem {
key: string
session: Session
@@ -50,6 +67,22 @@ export function buildRepoByDirectory(repos: Repo[]): Map<string, Repo> {
return new Map(repos.map((repo) => [repo.fullPath, repo]))
}
export 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 && (
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { Search } from 'lucide-react'
import { useEffect, useId, useMemo, useState } from 'react'
import type { Repo } from '@/api/types'
import { Input } from '@/components/ui/input'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { cn, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
const PAGE_STEP = 10
import {
PickerSearchBar,
optionId,
usePickerCursor,
usePickerKeyNav,
} from '@/components/session/usePickerKeyboardNav'
interface ProjectPickerContentProps {
open: boolean
@@ -15,8 +17,9 @@ interface ProjectPickerContentProps {
searchInputRef: React.RefObject<HTMLInputElement | null>
}
function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
interface ProjectPickerRow {
key: string
repo: Repo
}
export function ProjectPickerContent({
@@ -27,12 +30,10 @@ export function ProjectPickerContent({
searchInputRef,
}: ProjectPickerContentProps) {
const { repos, isLoading } = useNavigableRepos()
const rowRefs = useRef(new Map<number, HTMLDivElement>())
const listId = useId()
const optionBaseId = useId()
const [query, setQuery] = useState('')
const [cursorIndex, setCursorIndex] = useState<number | null>(null)
const trimmedQuery = query.trim()
@@ -46,111 +47,49 @@ export function ProjectPickerContent({
})
}, [repos, trimmedQuery])
const defaultCursorIndex = useMemo(() => {
if (!trimmedQuery && currentRepo) {
const index = filteredRepos.findIndex((repo) => repo.id === currentRepo.id)
if (index >= 0) return index
}
return filteredRepos.length > 0 ? 0 : -1
}, [trimmedQuery, currentRepo, filteredRepos])
const effectiveCursorIndex = cursorIndex ?? defaultCursorIndex
const cursorRepo = effectiveCursorIndex >= 0 ? filteredRepos[effectiveCursorIndex] : undefined
useEffect(() => {
setCursorIndex(null)
}, [trimmedQuery])
const setRowRef = useCallback((key: number, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRepo) return
const node = rowRefs.current.get(cursorRepo.id)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRepo])
const moveCursor = useCallback(
(index: number) => {
if (!filteredRepos[index]) return
setCursorIndex(index)
},
const rows = useMemo<ProjectPickerRow[]>(
() => filteredRepos.map((repo) => ({ key: String(repo.id), repo })),
[filteredRepos],
)
const handleSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const defaultCursorKey = useMemo(() => {
if (!trimmedQuery && currentRepo) {
const current = rows.find((row) => row.repo.id === currentRepo.id)
if (current) return current.key
}
return rows[0]?.key ?? null
}, [trimmedQuery, currentRepo, rows])
const key = event.key
const ctrlKey = event.key.toLowerCase()
const moveBy = (delta: number, wrap: boolean) => {
if (filteredRepos.length === 0) return
const base = effectiveCursorIndex < 0 ? (delta > 0 ? -1 : 0) : effectiveCursorIndex
const raw = base + delta
const next = wrap
? ((raw % filteredRepos.length) + filteredRepos.length) % filteredRepos.length
: Math.max(0, Math.min(filteredRepos.length - 1, raw))
moveCursor(next)
}
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRepo) return
event.preventDefault()
onSelectRepo(cursorRepo)
}
},
[filteredRepos, effectiveCursorIndex, moveCursor, cursorRepo, onSelectRepo],
const { cursorIndex, cursorRow, registerRef, moveCursor, resetCursor } = usePickerCursor(
rows,
defaultCursorKey,
)
useEffect(() => {
resetCursor()
}, [trimmedQuery, resetCursor])
const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: (row) => onSelectRepo(row.repo),
})
return (
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
ref={searchInputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={effectiveCursorIndex >= 0 ? optionId(optionBaseId, effectiveCursorIndex) : undefined}
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search projects..."
className="h-9 pl-9"
autoComplete="off"
name="project-picker-search"
/>
</div>
</div>
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search projects..."
name="project-picker-search"
/>
<div
role="listbox"
@@ -158,19 +97,20 @@ export function ProjectPickerContent({
aria-label="Projects"
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{filteredRepos.length === 0 ? (
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">
{isLoading ? 'Loading projects...' : 'No projects found'}
</div>
) : (
filteredRepos.map((repo, index) => {
const isCursor = index === effectiveCursorIndex
rows.map((row, index) => {
const { repo } = row
const isCursor = index === cursorIndex
const isCurrent = repo.id === currentRepo?.id
const branch = getRepoBranchLabel(repo)
return (
<div
key={repo.id}
ref={(node) => setRowRef(repo.id, node)}
key={row.key}
ref={(node) => registerRef(row.key, node)}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') moveCursor(index)
@@ -217,7 +157,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 }
},
useActivityWindowMinutes: () =>
mocks.preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES,
}))
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
@@ -106,6 +124,24 @@ 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]
const itemSession = session(id, title, directory)
return {
key: `${directory}:${id}`,
session: itemSession,
repo: itemRepo,
state,
updatedAt: itemSession.time.updated,
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 +180,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 +199,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 +534,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...')
})
@@ -578,6 +621,35 @@ describe('SessionPickerDialog', () => {
expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[0])
})
it('navigates the projects tab with wrapping arrows, PageUp/PageDown and Enter', async () => {
mocks.repos = Array.from({ length: 12 }, (_, index) =>
repo(index + 1, `repo-${index + 1}`, `/w/r${index + 1}`),
)
const { onSelectRepo } = renderPicker()
openProjectsTab()
expect(await screen.findByRole('option', { name: 'repo-1' })).toHaveAttribute(
'aria-selected',
'true',
)
fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
expect(screen.getByRole('option', { name: 'repo-12' })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
expect(screen.getByRole('option', { name: 'repo-1' })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'PageDown' })
expect(screen.getByRole('option', { name: 'repo-11' })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'Enter' })
expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[10])
fireEvent.keyDown(combobox(), { key: 'PageUp' })
expect(screen.getByRole('option', { name: 'repo-1' })).toHaveAttribute('aria-selected', 'true')
})
it('opens a repo on click in the projects tab', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const { onSelectRepo } = renderPicker()
@@ -619,14 +691,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 +715,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 +768,113 @@ 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 2 hours'),
).toBeInTheDocument()
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.queryByText('Running')).not.toBeInTheDocument()
expect(screen.queryByText('Recent')).not.toBeInTheDocument()
})
it('formats a full-day active work window as hours in the empty state', async () => {
mocks.preferences = { activityWindowMinutes: 1440 }
renderPicker()
openActiveTab()
expect(
await screen.findByText('No active or recent sessions in the last 24 hours'),
).toBeInTheDocument()
expect(mocks.activeWorkWindowMs).toBe(1440 * 60 * 1000)
})
it('opens the cursor active row with Enter and selects its session and repo', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
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,
})
})
})
@@ -1,9 +1,10 @@
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { format, startOfDay } from 'date-fns'
import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
import { MoreHorizontal, Pin, PinOff } from 'lucide-react'
import { getOpenCodeLocation } from '@/api/opencode'
import type { Repo, Session } from '@/api/types'
import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import {
@@ -12,14 +13,20 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
import { ProjectPickerContent } from '@/components/session/ProjectPickerContent'
import {
PickerSearchBar,
optionId,
usePickerCursor,
usePickerKeyNav,
} from '@/components/session/usePickerKeyboardNav'
import { partitionSessions } from '@/components/session/session-partition'
import { buildRepoByDirectory } from '@/components/navigation/sidebar-session-tree'
import { useDeleteSession } from '@/hooks/useOpenCode'
import { useActiveWork, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { useSessionSearch } from '@/hooks/useSessionSearch'
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
@@ -34,10 +41,22 @@ import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
const PAGE_STEP = 10
const NEAR_BOTTOM_PX = 240
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
@@ -53,6 +72,7 @@ interface SessionPickerRow {
key: string
session: Session
repo: Repo
updatedAt?: number
}
interface SessionPickerSection {
@@ -97,10 +117,6 @@ function buildSections(
return sections
}
function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
}
function stripTrailingSlashes(value: string): string {
return value.replace(/\/+$/, '')
}
@@ -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) {
@@ -251,7 +263,7 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
>
{showRepo && <span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>}
{!showRepo && label && <span className="max-w-32 truncate">{label}</span>}
<span>{formatShortRelativeTime(new Date(row.session.time.updated))}</span>
<span>{formatShortRelativeTime(new Date(row.updatedAt ?? row.session.time.updated))}</span>
</span>
</div>
<div className="flex shrink-0 items-center pr-1">
@@ -283,6 +295,231 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
)
})
interface SessionPickerRowActionsOptions {
directories: string[]
activeSessionID?: string
onSelectSession: (session: Session, repo: Repo) => void
onDeleteActiveSession: () => void
}
interface SessionPickerRowActions {
pinnedKeys: ReadonlySet<string>
pendingDeleteKey: string | null
clearPendingDelete: () => void
openRow: (row: SessionPickerRow | undefined) => void
deleteRow: (row: SessionPickerRow | undefined) => void
handleTogglePin: (row: SessionPickerRow) => void
handleRequestDelete: (session: Session) => void
deleteDialogProps: {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
isDeleting: boolean
}
}
function useSessionPickerRowActions({
directories,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
}: SessionPickerRowActionsOptions): SessionPickerRowActions {
const { data: sessionPins } = useSessionPins()
const togglePin = useToggleSessionPin()
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
const deleteSession = useDeleteSession(directories)
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
const clearPendingDelete = useCallback(() => {
setPendingDeleteKey(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],
)
const handleTogglePin = useCallback(
(row: SessionPickerRow) => {
togglePin.mutate({
sessionId: row.session.id,
directory: row.session.location.directory,
pinned: !pinnedKeys.has(row.key),
})
},
[togglePin, pinnedKeys],
)
const handleRequestDelete = useCallback((session: Session) => {
setSessionToDelete(session)
}, [])
const confirmDelete = useCallback(() => {
if (!sessionToDelete) return
void performDelete(sessionToDelete).finally(() => {
setSessionToDelete(null)
})
}, [sessionToDelete, performDelete])
const deleteDialogProps = useMemo(
() => ({
open: sessionToDelete !== null,
onOpenChange: (nextOpen: boolean) => {
if (!nextOpen) setSessionToDelete(null)
},
onConfirm: () => {
void confirmDelete()
},
onCancel: () => setSessionToDelete(null),
isDeleting: deleteSession.isPending,
}),
[sessionToDelete, confirmDelete, deleteSession.isPending],
)
return {
pinnedKeys,
pendingDeleteKey,
clearPendingDelete,
openRow,
deleteRow,
handleTogglePin,
handleRequestDelete,
deleteDialogProps,
}
}
interface SessionPickerListProps {
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 +544,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()
@@ -364,154 +600,65 @@ function SessionPickerContent({
[repoByDirectory, currentRepo],
)
const { data: sessionPins } = useSessionPins()
const togglePin = useToggleSessionPin()
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
const deleteSession = useDeleteSession(directories)
const [cursorKey, setCursorKey] = useState<string | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
const {
pinnedKeys,
pendingDeleteKey,
clearPendingDelete,
openRow,
deleteRow,
handleTogglePin,
handleRequestDelete,
deleteDialogProps,
} = useSessionPickerRowActions({
directories,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
})
const sections = useMemo(
() => buildSections(filteredSessions, pinnedKeys, getSessionKey, resolveRepo),
[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
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 {
rowIndexByKey,
cursorIndex,
cursorRow,
registerRef,
moveCursor: moveCursorRaw,
resetCursor,
} = usePickerCursor(rows, defaultCursorKey)
const moveCursor = useCallback(
(index: number) => {
const row = rows[index]
if (!row) return
setCursorKey(row.key)
setPendingDeleteKey(null)
clearPendingDelete()
moveCursorRaw(index)
},
[rows],
[clearPendingDelete, moveCursorRaw],
)
const openRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
onSelectSession(row.session, row.repo)
},
[onSelectSession],
)
useEffect(() => {
resetCursor()
clearPendingDelete()
}, [trimmedQuery, allProjects, resetCursor, clearPendingDelete])
const performDelete = useCallback(
(session: Session) => {
if (session.id === activeSessionID) onDeleteActiveSession()
return deleteSession
.mutateAsync({ id: session.id, directory: session.location.directory })
.catch(() => undefined)
},
[deleteSession, activeSessionID, onDeleteActiveSession],
)
const deleteRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
if (pendingDeleteKey !== row.key) {
setPendingDeleteKey(row.key)
return
}
void performDelete(row.session).finally(() => {
setPendingDeleteKey(null)
})
},
[pendingDeleteKey, performDelete],
)
const 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 = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: openRow,
onDeleteRow: deleteRow,
onToggleAllProjects: toggleAllProjects,
})
const handleListScroll = useCallback(
(event: React.UIEvent<HTMLDivElement>) => {
@@ -534,144 +681,93 @@ function SessionPickerContent({
}
}, [open, isLoading, rows, canFetchNextPage, fetchNextPage])
const handleTogglePin = useCallback(
(row: SessionPickerRow) => {
togglePin.mutate({
sessionId: row.session.id,
directory: row.session.location.directory,
pinned: !pinnedKeys.has(row.key),
})
},
[togglePin, pinnedKeys],
const labelFor = useCallback(
(row: SessionPickerRow) =>
allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical),
[allProjects, location?.project.canonical],
)
const handleRequestDelete = useCallback((session: Session) => {
setSessionToDelete(session)
}, [])
const confirmDelete = useCallback(() => {
if (!sessionToDelete) return
void performDelete(sessionToDelete).finally(() => {
setSessionToDelete(null)
})
}, [sessionToDelete, performDelete])
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>
<PickerSearchBar
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'}
@@ -679,17 +775,158 @@ function SessionPickerContent({
</div>
</div>
<DeleteSessionDialog
open={sessionToDelete !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setSessionToDelete(null)
}}
onConfirm={() => {
void confirmDelete()
}}
onCancel={() => setSessionToDelete(null)}
isDeleting={deleteSession.isPending}
/>
<DeleteSessionDialog {...deleteDialogProps} />
</>
)
}
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 windowMinutes = useActivityWindowMinutes()
const { groups, isLoading, isError } = useActiveWork(windowMinutes * MS_PER_MINUTE)
const listId = useId()
const optionBaseId = useId()
const [query, setQuery] = useState('')
const trimmedQuery = query.trim()
const sections = useMemo(() => {
const needle = trimmedQuery.toLowerCase()
return ACTIVE_WORK_GROUPS.flatMap((definition) => {
const rows: SessionPickerRow[] = []
for (const item of groups[definition.key]) {
if (needle && !(item.session.title ?? '').toLowerCase().includes(needle)) continue
rows.push({ key: item.key, session: item.session, repo: item.repo, updatedAt: item.updatedAt })
}
return rows.length > 0 ? [{ id: definition.key, 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,
registerRef,
moveCursor: moveCursorRaw,
resetCursor,
} = usePickerCursor(rows, defaultCursorKey)
const directories = useMemo(
() => Array.from(new Set(rows.map((row) => row.session.location.directory))),
[rows],
)
const {
pinnedKeys,
pendingDeleteKey,
clearPendingDelete,
openRow,
deleteRow,
handleTogglePin,
handleRequestDelete,
deleteDialogProps,
} = useSessionPickerRowActions({
directories,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
})
const moveCursor = useCallback(
(index: number) => {
clearPendingDelete()
moveCursorRaw(index)
},
[clearPendingDelete, moveCursorRaw],
)
useEffect(() => {
resetCursor()
clearPendingDelete()
}, [trimmedQuery, resetCursor, clearPendingDelete])
const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: openRow,
onDeleteRow: deleteRow,
})
const emptyState = isLoading
? 'Loading sessions...'
: isError
? 'Failed to load active sessions'
: trimmedQuery
? 'No sessions found'
: formatActivityEmptyMessage(windowMinutes)
return (
<>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<PickerSearchBar
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 {...deleteDialogProps} />
</>
)
}
@@ -704,6 +941,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 +967,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 +981,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 +1008,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,209 @@
/* eslint-disable react-refresh/only-export-components */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Search } from 'lucide-react'
import { Input } from '@/components/ui/input'
const PAGE_STEP = 10
export interface PickerRow {
key: string
}
export function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
}
export interface PickerCursorState<Row extends PickerRow> {
rowIndexByKey: Map<string, number>
cursorIndex: number
cursorRow: Row | undefined
registerRef: (key: string, node: HTMLDivElement | null) => void
moveCursor: (index: number) => void
resetCursor: () => void
}
export function usePickerCursor<Row extends PickerRow>(
rows: Row[],
defaultCursorKey: string | null,
): PickerCursorState<Row> {
const rowRefs = useRef(new Map<string, HTMLDivElement>())
const [cursorKey, setCursorKey] = useState<string | null>(null)
const rowIndexByKey = useMemo(
() => new Map(rows.map((row, index) => [row.key, index])),
[rows],
)
const cursorIndex = useMemo(() => {
if (cursorKey) {
const index = rowIndexByKey.get(cursorKey)
if (index !== undefined) return index
}
return defaultCursorKey ? rowIndexByKey.get(defaultCursorKey) ?? -1 : -1
}, [cursorKey, rowIndexByKey, defaultCursorKey])
const cursorRow = cursorIndex >= 0 ? rows[cursorIndex] : undefined
const registerRef = useCallback((key: string, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRow) return
const node = rowRefs.current.get(cursorRow.key)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRow])
const moveCursor = useCallback(
(index: number) => {
const row = rows[index]
if (!row) return
setCursorKey(row.key)
},
[rows],
)
const resetCursor = useCallback(() => {
setCursorKey(null)
}, [])
return {
rowIndexByKey,
cursorIndex,
cursorRow,
registerRef,
moveCursor,
resetCursor,
}
}
export interface PickerKeyNavOptions<Row extends PickerRow> {
rows: Row[]
cursorIndex: number
cursorRow: Row | undefined
moveCursor: (index: number) => void
onOpenRow: (row: Row) => void
onDeleteRow?: (row: Row) => void
onToggleAllProjects?: () => void
}
export function usePickerKeyNav<Row extends PickerRow>({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow,
onDeleteRow,
onToggleAllProjects,
}: PickerKeyNavOptions<Row>): (event: React.KeyboardEvent<HTMLInputElement>) => void {
return useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const moveBy = (delta: number, wrap: boolean) => {
if (rows.length === 0) return
const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
const raw = base + delta
const next = wrap
? ((raw % rows.length) + rows.length) % rows.length
: Math.max(0, Math.min(rows.length - 1, raw))
moveCursor(next)
}
const key = event.key
const ctrlKey = event.key.toLowerCase()
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRow) return
event.preventDefault()
onOpenRow(cursorRow)
return
}
if (onToggleAllProjects && event.ctrlKey && ctrlKey === 'a') {
event.preventDefault()
onToggleAllProjects()
return
}
if (onDeleteRow && event.ctrlKey && ctrlKey === 'd') {
if (!cursorRow) return
event.preventDefault()
onDeleteRow(cursorRow)
}
},
[rows, cursorIndex, cursorRow, moveCursor, onOpenRow, onDeleteRow, onToggleAllProjects],
)
}
export interface PickerSearchBarProps {
inputRef: React.RefObject<HTMLInputElement | null>
listId: string
open: boolean
activeDescendantId: string | undefined
value: string
onChange: (value: string) => void
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void
placeholder: string
name: string
trailing?: React.ReactNode
}
export function PickerSearchBar({
inputRef,
listId,
open,
activeDescendantId,
value,
onChange,
onKeyDown,
placeholder,
name,
trailing,
}: PickerSearchBarProps) {
return (
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
ref={inputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeDescendantId}
value={value}
onChange={(event) => onChange(event.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className="h-9 pl-9"
autoComplete="off"
name={name}
/>
</div>
{trailing}
</div>
)
}
@@ -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,45 @@
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) => {
const minutes = ACTIVITY_WINDOW_MINUTE_OPTIONS.find((option) => String(option) === value)
if (minutes !== undefined) {
updateSettings({ activityWindowMinutes: minutes })
}
}}
>
<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,98 @@
import { cleanup, render } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ActivitySpinner, SPINNER_FRAMES, brailleDots } from './activity-spinner'
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)
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 last frame', () => {
expect(brailleDots('⠏')).toEqual([true, true, true, true, false, false, false, false])
})
})
describe('ActivitySpinner', () => {
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('steps every dot through all frames in order with a discrete, endless 80ms-per-frame animation', () => {
const { container } = render(<ActivitySpinner />)
circles(container).forEach((circle, dotIndex) => {
const animate = circle.querySelector('animate')
expect(animate).toHaveAttribute('attributeName', 'fill-opacity')
expect(animate).toHaveAttribute('calcMode', 'discrete')
expect(animate).toHaveAttribute('repeatCount', 'indefinite')
expect(animate).toHaveAttribute('dur', `${80 * SPINNER_FRAMES.length}ms`)
const values = animate?.getAttribute('values')?.split(';')
expect(values).toEqual(SPINNER_FRAMES.map((frame) => (brailleDots(frame)[dotIndex] ? '1' : '0.25')))
})
})
it('schedules no JavaScript timers however many spinners are mounted', () => {
vi.useFakeTimers()
render(
<>
<ActivitySpinner />
<ActivitySpinner />
<ActivitySpinner />
</>,
)
expect(vi.getTimerCount()).toBe(0)
})
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,76 @@
import { cn } from '@/lib/utils'
export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const
const FRAME_INTERVAL_MS = 80
const CYCLE_DURATION = `${FRAME_INTERVAL_MS * SPINNER_FRAMES.length}ms`
const BRAILLE_BASE = 0x2800
const DOT_GRID: ReadonlyArray<readonly [number, number]> = [
[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 LIT_DOT_OPACITY = 1
const UNLIT_DOT_OPACITY = 0.25
/**
* 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)
}
const FRAME_DOTS = SPINNER_FRAMES.map(brailleDots)
const DOT_OPACITY_TIMELINES = DOT_GRID.map((_, index) =>
FRAME_DOTS.map((dots) => (dots[index] ? LIT_DOT_OPACITY : UNLIT_DOT_OPACITY)),
)
/**
* Braille spinner mirroring the OpenCode TUI activity spinner as an inline SVG cell so the dots
* stay visible at small text sizes. Each dot steps through its opacity for every frame with a
* declarative SVG `<animate>` derived from `SPINNER_FRAMES`, so frames advance in the browser
* with no JavaScript or React render per frame. It animates regardless of
* `prefers-reduced-motion`: a still frame is indistinguishable from a stalled spinner, and the
* motion is a small in-place status cue like the platform activity indicators.
*/
export function ActivitySpinner({ className }: { className?: string }) {
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={DOT_OPACITY_TIMELINES[index][0]}
>
<animate
attributeName="fill-opacity"
values={DOT_OPACITY_TIMELINES[index].join(';')}
dur={CYCLE_DURATION}
calcMode="discrete"
repeatCount="indefinite"
/>
</circle>
))}
</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 (
+23 -11
View File
@@ -240,7 +240,7 @@ describe('EventProvider permissions and forms', () => {
mocks.replyForm.mockResolvedValue(undefined)
mocks.cancelForm.mockResolvedValue(undefined)
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), parents: new Map(), runningShells: new Map(), shellRevisions: new Map(), shellRevision: 0, revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), parents: new Map(), directories: new Map(), runningShells: new Map(), shellRevisions: new Map(), shellRevision: 0, revision: 0 })
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories: vi.fn(),
@@ -275,6 +275,18 @@ describe('EventProvider permissions and forms', () => {
})
})
it('records the session directory for a pending permission loaded without an SSE status event', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(useSessionStatus.getState().directories.get('session-1')).toBe('/repo')
})
expect(useSessionStatus.getState().statuses.has('session-1')).toBe(false)
})
it('clears stale pending permissions for a session', async () => {
mocks.listPendingPermissions
.mockResolvedValueOnce([pendingPermission])
@@ -1447,8 +1459,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 +1487,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 +2281,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 +2406,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 +2433,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 -19
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,
@@ -123,7 +126,7 @@ function reconcileBySessionForDirectory<T extends SessionScopedItem>(
prev: Record<string, T[]>,
directory: string,
items: T[],
sessionDirectories: Map<string, string>,
sessionDirectories: ReadonlyMap<string, string>,
): Record<string, T[]> {
const grouped = groupBySession(items)
const next = { ...prev }
@@ -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.
@@ -262,7 +273,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const [formsBySession, setFormsBySession] = useState<FormsBySession>({})
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
const prevPermissionCountRef = useRef(0)
const initialFetchDoneRef = useRef(false)
const statusSyncVersionRef = useRef(0)
@@ -279,6 +289,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],
@@ -290,7 +303,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const rememberSessionDirectory = useCallback((sessionID: string, directory?: string) => {
if (!directory) return
sessionDirectoriesRef.current.set(sessionID, directory)
useSessionStatus.getState().setSessionDirectory(sessionID, directory)
}, [])
const findCachedSessionDirectory = useCallback((sessionID: string): string | null => {
@@ -340,7 +353,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
}, [queryClient])
const findSessionDirectory = useCallback((sessionID: string): string | null => {
const remembered = sessionDirectoriesRef.current.get(sessionID)
const remembered = useSessionStatus.getState().directories.get(sessionID)
if (remembered) return remembered
return findCachedSessionDirectory(sessionID)
}, [findCachedSessionDirectory])
@@ -384,7 +397,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
})
setPermissionsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, permissions, sessionDirectoriesRef.current),
reconcileBySessionForDirectory(prev, directory, permissions, useSessionStatus.getState().directories),
)
}, [rememberSessionDirectory])
@@ -394,7 +407,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
})
setFormsBySession(prev =>
reconcileBySessionForDirectory(prev, directory, forms, sessionDirectoriesRef.current),
reconcileBySessionForDirectory(prev, directory, forms, useSessionStatus.getState().directories),
)
}, [rememberSessionDirectory])
@@ -506,7 +519,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
for (const repo of reposRef.current ?? []) {
if (repo.fullPath) directories.add(repo.fullPath)
}
for (const directory of sessionDirectoriesRef.current.values()) {
for (const directory of useSessionStatus.getState().directories.values()) {
if (directory) directories.add(directory)
}
return [...directories]
@@ -532,6 +545,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) {
@@ -672,6 +686,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 +697,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 +752,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 +878,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
permissions: {
current: currentPermission,
pendingCount: allPermissions.length,
pendingSessionIDs: pendingPermissionSessionIDs,
viewedSessionId,
currentDirectory: currentPermissionDirectory,
currentIsFromDifferentSession,
@@ -872,6 +894,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
forms: {
current: currentForm,
pendingCount: allForms.length,
pendingSessionIDs: pendingFormSessionIDs,
reply: replyToForm,
cancel: cancelPendingForm,
dismiss: removeForm,
@@ -887,6 +910,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
respondToSSHHostKey,
currentPermission,
allPermissions.length,
pendingPermissionSessionIDs,
viewedSessionId,
currentPermissionDirectory,
currentIsFromDifferentSession,
@@ -899,6 +923,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
syncPermissionsForSession,
currentForm,
allForms.length,
pendingFormSessionIDs,
replyToForm,
cancelPendingForm,
removeForm,
+200
View File
@@ -0,0 +1,200 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import type { Repo } from '@/api/types'
import { MS_PER_MINUTE } from '@/lib/activeWork'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useActiveWork } from './useActiveWork'
const REPO_PATH = '/repo'
const WINDOW_MS = 60 * MS_PER_MINUTE
const mocks = vi.hoisted(() => ({
listSessionPage: vi.fn(),
getSession: vi.fn(),
useNavigableRepos: vi.fn(),
pendingSessionIDs: [] as string[],
}))
vi.mock('@/api/opencode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/opencode')>()
return {
...actual,
listSessionPage: mocks.listSessionPage,
getSession: mocks.getSession,
}
})
vi.mock('@/hooks/useSidebarRepoGroups', () => ({
useNavigableRepos: mocks.useNavigableRepos,
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({ pendingSessionIDs: mocks.pendingSessionIDs }),
useForms: () => ({ pendingSessionIDs: mocks.pendingSessionIDs }),
}))
vi.mock('@/lib/toast', () => ({
showToast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warning: vi.fn(),
loading: vi.fn(),
promise: vi.fn(),
dismiss: vi.fn(),
},
}))
const session = (id: string, updated: number, parentID?: string | null): SessionInfo => ({
id,
projectID: 'proj_1',
title: `Session ${id}`,
time: { created: updated, updated },
location: { directory: REPO_PATH },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
...(parentID === undefined ? {} : { parentID }),
})
const repo: Repo = {
id: 1,
fullPath: REPO_PATH,
localPath: REPO_PATH,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
}
const createQueryClient = () =>
new QueryClient({ defaultOptions: { queries: { retry: false } } })
const createWrapper = (queryClient: QueryClient) =>
({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const recentIDs = (groups: { recent: Array<{ session: SessionInfo }> }): string[] =>
groups.recent.map((item) => item.session.id)
describe('useActiveWork', () => {
beforeEach(() => {
mocks.listSessionPage.mockReset()
mocks.getSession.mockReset()
mocks.useNavigableRepos.mockReset()
mocks.useNavigableRepos.mockReturnValue({ repos: [repo], isLoading: false, refetch: vi.fn() })
useSessionStatus.setState({
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
directories: new Map(),
runningShells: new Map(),
shellRevisions: new Map(),
shellRevision: 0,
revision: 0,
})
})
afterEach(() => {
vi.useRealTimers()
})
it('requests the next page while the oldest loaded session is inside the window', async () => {
const now = Date.now()
mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
if (cursor === 'page2') {
return { items: [session('root2', now - 1500)] }
}
return {
items: [session('a', now - 500), session('b', now - 1000)],
nextCursor: 'page2',
}
})
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
wrapper: createWrapper(createQueryClient()),
})
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('root2'))
expect(mocks.listSessionPage).toHaveBeenCalledWith({ cursor: 'page2', includeChildren: true })
})
it('does not request another page when the oldest loaded session is outside the window', async () => {
const now = Date.now()
mocks.listSessionPage.mockResolvedValue({
items: [session('recent', now - 500), session('old', now - 2 * WINDOW_MS)],
nextCursor: 'page2',
})
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
wrapper: createWrapper(createQueryClient()),
})
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('recent'))
await act(async () => {
await Promise.resolve()
})
expect(mocks.listSessionPage).toHaveBeenCalledTimes(1)
})
it('resolves an unlisted grandchild to its ancestor root', async () => {
const now = Date.now()
mocks.listSessionPage.mockResolvedValue({ items: [session('G', now - 500, 'C')] })
mocks.getSession.mockImplementation(async (id: string) => {
if (id === 'C') return session('C', now - 1000, 'R')
if (id === 'R') return session('R', now - 1500, null)
throw new Error(`unexpected session ${id}`)
})
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
wrapper: createWrapper(createQueryClient()),
})
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('R'))
expect(recentIDs(result.current.groups)).not.toContain('C')
})
it('keeps groups referentially stable across a rerender', async () => {
const now = Date.now()
mocks.listSessionPage.mockResolvedValue({ items: [session('root', now - 500)] })
const { result, rerender } = renderHook(() => useActiveWork(WINDOW_MS), {
wrapper: createWrapper(createQueryClient()),
})
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('root'))
const before = result.current.groups
rerender()
expect(result.current.groups).toBe(before)
})
it('drops a recent root once the clock advances past the window', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
const now = Date.now()
mocks.listSessionPage.mockResolvedValue({ items: [session('root', now - 1000)] })
const { result } = renderHook(() => useActiveWork(MS_PER_MINUTE), {
wrapper: createWrapper(createQueryClient()),
})
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('root'))
await act(async () => {
vi.setSystemTime(now + 5 * MS_PER_MINUTE)
vi.advanceTimersByTime(MS_PER_MINUTE)
})
expect(recentIDs(result.current.groups)).not.toContain('root')
})
})
+278
View File
@@ -0,0 +1,278 @@
import { useEffect, useMemo, useState } from 'react'
import { useQueries, useQueryClient, type QueryClient } from '@tanstack/react-query'
import type { SessionInfo } from '@opencode-manager/shared/opencode'
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 {
MS_PER_MINUTE,
buildActiveWork,
buildRepoActivityIndex,
collectActiveRoots,
repoActivityFromIndex,
rootSessionID,
type ActiveWorkGroups,
} from '@/lib/activeWork'
import {
combineQuerySessions,
mergeExtraSessions,
} from '@/components/navigation/sidebar-session-tree'
import type { Repo } from '@/api/types'
const ACTIVE_WORK_SESSION_LIMIT = 50
/**
* The active-work time window in minutes, derived from the user's configured
* `activityWindowMinutes` with the shared default as a fallback.
*/
export function useActivityWindowMinutes(): number {
const { preferences } = useSettings()
return preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
}
/** Pending permission and form session ids, merged once per snapshot into a referentially stable list. */
function usePendingInputSessionIDs(): string[] {
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
const pendingFormSessionIDs = useForms().pendingSessionIDs
return useMemo(
() => [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
[pendingPermissionSessionIDs, pendingFormSessionIDs],
)
}
/**
* Distinct active roots for a badge: needs-input roots and running roots that are not also
* 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 pendingInputSessionIDs = usePendingInputSessionIDs()
return useMemo(() => {
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, pendingInputSessionIDs])
}
/**
* 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 pendingInputSessionIDs = usePendingInputSessionIDs()
return useSessionStatus((state) =>
repoActivityFromIndex(
repo,
buildRepoActivityIndex({
statuses: state.statuses,
parents: state.parents,
runningShells: state.runningShells,
directories: state.directories,
pendingInputSessionIDs,
}),
),
)
}
/**
* Walks a session's ancestor chain through the shared session cache, returning each link as
* `[sessionID, parentID]` from the session down to its root. Stops at a root, a missing session,
* or a cycle. Reusing `sessionQueryOptions` keeps these reads on the shared session cache.
*/
async function fetchAncestorLinks(
queryClient: QueryClient,
sessionID: string,
directories: ReadonlyMap<string, string>,
): Promise<Array<[string, string | null]>> {
const links: Array<[string, string | null]> = []
const visited = new Set<string>()
let currentID: string | null | undefined = sessionID
while (currentID && !visited.has(currentID)) {
visited.add(currentID)
const session: SessionInfo = await queryClient.fetchQuery(
sessionQueryOptions(currentID, directories.get(currentID)),
)
const parentID: string | null = session.parentID ?? null
links.push([session.id, parentID])
currentID = parentID
}
return links
}
/** Flattens the resolved ancestor links from each query result, dropping unresolved queries. */
const combineAncestorLinks = (
results: Array<{ data?: Array<[string, string | null]> }>,
): Array<[string, string | null]> => results.flatMap((result) => result.data ?? [])
/**
* 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 queryClient = useQueryClient()
const [now, setNow] = useState(() => Date.now())
const { repos, isLoading: isReposLoading } = useNavigableRepos()
const repoDirectories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
const {
data: sessions,
isLoading: isSessionsLoading,
isError: isSessionsError,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isFetchNextPageError,
} = useSessionsAcrossDirectories(repoDirectories, {
allDirectories: true,
limit: ACTIVE_WORK_SESSION_LIMIT,
includeChildren: true,
})
useEffect(() => {
const interval = setInterval(() => setNow(Date.now()), MS_PER_MINUTE)
return () => clearInterval(interval)
}, [])
const oldestLoadedUpdatedAt = sessions.at(-1)?.time.updated
useEffect(() => {
if (!hasNextPage || isFetchingNextPage || isFetchNextPageError) return
if (oldestLoadedUpdatedAt === undefined || oldestLoadedUpdatedAt < now - windowMs) return
void fetchNextPage()
}, [
hasNextPage,
isFetchingNextPage,
isFetchNextPageError,
oldestLoadedUpdatedAt,
now,
windowMs,
fetchNextPage,
])
const statuses = useSessionStatus((state) => state.statuses)
const storeParents = useSessionStatus((state) => state.parents)
const runningShells = useSessionStatus((state) => state.runningShells)
const outcomes = useSessionStatus((state) => state.outcomes)
const sessionDirectories = useSessionStatus((state) => state.directories)
const pendingInputSessionIDs = usePendingInputSessionIDs()
const parents = useMemo(() => {
const merged = new Map<string, string | null>()
for (const session of sessions) {
merged.set(session.id, session.parentID ?? null)
}
for (const [sessionID, parentID] of storeParents) {
if (!merged.has(sessionID)) merged.set(sessionID, parentID)
}
return merged
}, [sessions, storeParents])
const roots = useMemo(
() => collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs }),
[statuses, parents, runningShells, pendingInputSessionIDs],
)
const listedSessionIDs = useMemo(
() => new Set(sessions.map((session) => session.id)),
[sessions],
)
const missingRootIDs = useMemo(() => {
const ids = new Set<string>()
const windowStart = now - windowMs
for (const session of sessions) {
if (session.time.updated < windowStart) continue
const rootID = rootSessionID(session.id, parents)
if (!listedSessionIDs.has(rootID)) ids.add(rootID)
}
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]
}, [sessions, parents, listedSessionIDs, roots, windowMs, now])
const ancestorLinks = useQueries({
queries: missingRootIDs.map((sessionID) => ({
queryKey: ['opencode', 'session-ancestry', sessionID] as const,
queryFn: () => fetchAncestorLinks(queryClient, sessionID, sessionDirectories),
staleTime: Infinity,
})),
combine: combineAncestorLinks,
})
const resolvedParents = useMemo(() => {
const merged = new Map(parents)
for (const [sessionID, parentID] of ancestorLinks) {
merged.set(sessionID, parentID)
}
return merged
}, [parents, ancestorLinks])
const resolvedRoots = useMemo(
() => collectActiveRoots({ statuses, parents: resolvedParents, runningShells, pendingInputSessionIDs }),
[statuses, resolvedParents, runningShells, pendingInputSessionIDs],
)
const backfillRootIDs = useMemo(() => {
const ids = new Set<string>()
for (const sessionID of missingRootIDs) {
const rootID = rootSessionID(sessionID, resolvedParents)
if (!listedSessionIDs.has(rootID)) ids.add(rootID)
}
return [...ids]
}, [missingRootIDs, resolvedParents, listedSessionIDs])
const fetchedSessions = useQueries({
queries: backfillRootIDs.map((sessionID) =>
sessionQueryOptions(sessionID, sessionDirectories.get(sessionID)),
),
combine: combineQuerySessions,
})
const mergedSessions = useMemo(
() => mergeExtraSessions(sessions, fetchedSessions),
[sessions, fetchedSessions],
)
const groups = useMemo(
() =>
buildActiveWork({
now,
windowMs,
repos,
sessions: mergedSessions,
parents: resolvedParents,
roots: resolvedRoots,
outcomes,
}),
[now, windowMs, repos, mergedSessions, resolvedParents, resolvedRoots, outcomes],
)
return {
groups,
isLoading: isReposLoading || isSessionsLoading,
isError: isSessionsError,
}
}
+55
View File
@@ -174,6 +174,61 @@ describe('useSessionsAcrossDirectories', () => {
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
})
it('requests child sessions and records includeChildren in the query key', async () => {
mocks.listSessionPage.mockResolvedValue({ items: [sessionInfo('ses_child', '/w/a')] })
const queryClient = createQueryClient()
const { result } = renderHook(
() => useSessionsAcrossDirectories(['/w/a'], { includeChildren: true }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
})
expect(mocks.listSessionPage).toHaveBeenCalledWith({
directory: '/w/a',
limit: 25,
order: 'desc',
search: undefined,
includeChildren: true,
})
expect(queryClient.getQueryCache().getAll()[0]?.queryKey).toEqual([
'opencode',
'sessions',
'/w/a',
{
search: undefined,
limit: 25,
allDirectories: false,
project: undefined,
subpath: undefined,
includeChildren: true,
},
])
})
it('keeps root-only and include-children lists in distinct cache entries', async () => {
mocks.listSessionPage.mockResolvedValue({ items: [] })
const queryClient = createQueryClient()
const wrapper = createWrapper(queryClient)
renderHook(() => useSessionsAcrossDirectories(['/w/a']), { wrapper })
renderHook(() => useSessionsAcrossDirectories(['/w/a'], { includeChildren: true }), { wrapper })
await waitFor(() => {
expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
})
const optionObjects = queryClient
.getQueryCache()
.getAll()
.map((query) => query.queryKey[3] as { includeChildren?: boolean })
expect(optionObjects.some((options) => options.includeChildren === true)).toBe(true)
expect(optionObjects.some((options) => options.includeChildren === false)).toBe(true)
})
it('pages a project scope through one cursor query with project and subpath', async () => {
mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
if (cursor === 'cursor_project') {
+10 -3
View File
@@ -44,6 +44,7 @@ interface UseSessionsAcrossDirectoriesOptions {
keepPreviousResults?: boolean
allDirectories?: boolean
project?: { id: string; subpath: string }
includeChildren?: boolean
}
type SessionDirectoryCursors = Record<string, string>
@@ -73,7 +74,9 @@ export const useSessionsAcrossDirectories = (
const projectSubpath = options?.project?.subpath;
const projectScoped = !allDirectories && projectId !== undefined;
const singleCursor = allDirectories || projectScoped;
const includeChildren = options?.includeChildren ?? false;
const directoryKey = uniqueDirectories.join('|');
const childSessionsParam = includeChildren ? { includeChildren: true } : {};
const query = useInfiniteQuery<
SessionListPage,
@@ -86,7 +89,7 @@ export const useSessionsAcrossDirectories = (
'opencode',
'sessions',
directoryKey,
{ search: normalizedSearch, limit, allDirectories, project: projectId, subpath: projectSubpath },
{ search: normalizedSearch, limit, allDirectories, project: projectId, subpath: projectSubpath, includeChildren },
],
queryFn: async ({ pageParam }) => {
if (singleCursor) {
@@ -98,8 +101,9 @@ export const useSessionsAcrossDirectories = (
order: 'desc',
search: normalizedSearch,
...(projectScoped ? { project: projectId, subpath: projectSubpath } : {}),
...childSessionsParam,
}
: { cursor },
: { cursor, ...childSessionsParam },
);
return {
items: page.items,
@@ -115,6 +119,7 @@ export const useSessionsAcrossDirectories = (
limit,
order: 'desc',
search: normalizedSearch,
...childSessionsParam,
}),
),
);
@@ -134,7 +139,9 @@ export const useSessionsAcrossDirectories = (
const entries = Object.entries(pageParam.cursors);
const pages = await Promise.all(
entries.map(([directory, cursor]) => listSessionPage({ directory, cursor })),
entries.map(([directory, cursor]) =>
listSessionPage({ directory, cursor, ...childSessionsParam }),
),
);
const cursors: SessionDirectoryCursors = {};
const items: SessionInfo[] = [];
+2 -2
View File
@@ -67,14 +67,14 @@ describe('useSSE', () => {
MockEventSource.instances = []
shellApi.listShells.mockResolvedValue([])
shellApi.removeShell.mockResolvedValue(undefined)
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), directories: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response))
})
afterEach(() => {
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), directories: new Map(), revision: 0 })
useSendErrorStore.setState({ errors: {} })
globalThis.EventSource = originalEventSource
globalThis.fetch = originalFetch
+5 -18
View File
@@ -4,29 +4,16 @@ import { listRepos } from '@/api/repos'
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useSessionPins } from '@/hooks/useSessionPins'
import { buildPinnedSessionKeys, buildSessionKey, getSessionKey } from '@/lib/sessionKey'
import type { Repo, Session } from '@/api/types'
import type { Repo } from '@/api/types'
import {
SIDEBAR_SESSIONS_PER_REPO,
buildSidebarRepoGroups,
combineQuerySessions,
mergeExtraSessions,
selectNavigableRepos,
type SidebarRepoGroup,
} from '@/components/navigation/sidebar-session-tree'
const combinePinnedSessions = (results: Array<{ data?: Session }>): Session[] =>
results.flatMap((result) => (result.data ? [result.data] : []))
const mergeSessions = (sessions: Session[], pinnedSessions: Session[]): Session[] => {
if (pinnedSessions.length === 0) return sessions
const seen = new Set(sessions.map((session) => session.id))
const extras: Session[] = []
for (const session of pinnedSessions) {
if (seen.has(session.id)) continue
seen.add(session.id)
extras.push(session)
}
return extras.length === 0 ? sessions : [...sessions, ...extras]
}
export function useSidebarRepoGroups(input: {
repos: Repo[]
search?: string
@@ -56,11 +43,11 @@ export function useSidebarRepoGroups(input: {
const pinnedSessions = useQueries({
queries: missingPins.map((pin) => sessionQueryOptions(pin.sessionId, pin.directory)),
combine: combinePinnedSessions,
combine: combineQuerySessions,
})
const mergedSessions = useMemo(
() => mergeSessions(sessions, pinnedSessions),
() => mergeExtraSessions(sessions, pinnedSessions),
[sessions, pinnedSessions],
)
+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)
+391
View File
@@ -0,0 +1,391 @@
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,
buildRepoActivityIndex,
collectActiveRoots,
formatActivityEmptyMessage,
formatActivityWindow,
repoActivityFromIndex,
rootSessionID,
} from './activeWork'
const NOW = 1_000_000_000_000
const WINDOW_MS = 60_000
function createSession(id: string, updated: number, directory: string, parentID?: 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 } },
...(parentID ? { parentID } : {}),
}
}
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('formatActivityEmptyMessage', () => {
it('names the window in the empty-state copy', () => {
expect(formatActivityEmptyMessage(30)).toBe('No active or recent sessions in the last 30 minutes')
expect(formatActivityEmptyMessage(1440)).toBe(
'No active or recent sessions in the last 24 hours',
)
})
})
describe('rootSessionID', () => {
it('climbs parents to the top-most root', () => {
const parents = new Map<string, string | null>([['child', 'parent'], ['parent', 'root'], ['root', null]])
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('buildRepoActivityIndex and repoActivityFromIndex', () => {
const noShells = new Map<string, { sessionID: string; directory: string }>()
const stateFor = (
repo: Repo,
input: Parameters<typeof buildRepoActivityIndex>[0],
): 'needs-input' | 'running' | null =>
repoActivityFromIndex(repo, buildRepoActivityIndex(input))
it('matches a busy session by its own directory', () => {
const state = stateFor(repoA, {
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 = stateFor(repoA, {
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 = stateFor(repoA, {
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 = stateFor(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 = stateFor(repoA, {
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 = stateFor(repoA, {
statuses: statuses({ session: { type: 'idle' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/a']]),
pendingInputSessionIDs: [],
})
expect(state).toBeNull()
})
it('returns null when the repo matches no indexed directory', () => {
const state = stateFor(repoA, {
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/other']]),
pendingInputSessionIDs: [],
})
expect(state).toBeNull()
})
it('reuses the index for the same snapshot references', () => {
const input: Parameters<typeof buildRepoActivityIndex>[0] = {
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/a']]),
pendingInputSessionIDs: [],
}
expect(buildRepoActivityIndex(input)).toBe(buildRepoActivityIndex(input))
})
})
describe('buildActiveWork', () => {
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, parents: new Map(), 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, parents: new Map(), 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, parents: new Map(), 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, parents: new Map(), 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, parents: new Map(), 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, parents: new Map(), 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, parents: new Map(), roots: emptyRoots, outcomes })
expect(groups.recent[0].outcome).toBe('failed')
})
it('rolls a child updated inside the window up to its root for the recent test and updatedAt', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const sessions = [
createSession('root', NOW - WINDOW_MS - 1, '/repos/a'),
createSession('child', NOW - 1000, '/repos/a', 'root'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['root'])
expect(groups.recent[0].updatedAt).toBe(NOW - 1000)
})
it('sorts by the rolled-up time and never emits children or grandchildren', () => {
const parents = new Map<string, string | null>([
['child-of-a', 'root-a'],
['grandchild-of-a', 'child-of-a'],
['root-a', null],
['root-b', null],
])
const sessions = [
createSession('root-a', NOW - 5000, '/repos/a'),
createSession('child-of-a', NOW - 4000, '/repos/a', 'root-a'),
createSession('grandchild-of-a', NOW - 1000, '/repos/a', 'child-of-a'),
createSession('root-b', NOW - 2000, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['root-a', 'root-b'])
expect(groups.recent[0].updatedAt).toBe(NOW - 1000)
})
it('does not emit a child whose root is absent from the input', () => {
const parents = new Map<string, string | null>([['child', 'root']])
const sessions = [createSession('child', NOW - 1000, '/repos/a', 'root')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toEqual([])
})
it('emits the root once it is supplied alongside its child', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const sessions = [
createSession('child', NOW - 1000, '/repos/a', 'root'),
createSession('root', NOW - WINDOW_MS - 1, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['root'])
})
})
+260
View File
@@ -0,0 +1,260 @@
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, normalizeDirectory } from '@/components/navigation/sidebar-session-tree'
export const MS_PER_MINUTE = 60_000
/**
* Human-readable label for an activity window in minutes: whole hours when the value divides
* evenly into hours, otherwise minutes.
*/
export function formatActivityWindow(minutes: number): string {
if (minutes % 60 === 0) {
const hours = minutes / 60
return `${hours} ${hours === 1 ? 'hour' : 'hours'}`
}
return `${minutes} minutes`
}
/** Empty-state copy for the activity list naming the window it searched. */
export function formatActivityEmptyMessage(minutes: number): string {
return `No active or recent sessions in the last ${formatActivityWindow(minutes)}`
}
export type ActiveWorkState = 'needs-input' | 'running' | 'recent'
export interface ActiveWorkItem {
key: string
session: Session
repo: Repo
state: ActiveWorkState
updatedAt: number
outcome?: ChildOutcome
path: string
}
export interface ActiveWorkGroups {
needsInput: ActiveWorkItem[]
running: ActiveWorkItem[]
recent: ActiveWorkItem[]
}
export const ACTIVE_WORK_GROUPS = [
{ key: 'needsInput', heading: 'Needs input' },
{ key: 'running', heading: 'Running' },
{ key: 'recent', heading: 'Recent' },
] as const satisfies ReadonlyArray<{ key: keyof ActiveWorkGroups; heading: string }>
export function rootSessionID(
sessionID: string,
parents: ReadonlyMap<string, string | null>,
): 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 }
}
interface RepoActivityIndexInput {
statuses: ReadonlyMap<string, SessionStatusType>
parents: ReadonlyMap<string, string | null>
runningShells: ReadonlyMap<string, { sessionID: string; directory: string }>
directories: ReadonlyMap<string, string>
pendingInputSessionIDs: Iterable<string>
}
let cachedRepoActivityIndex: (RepoActivityIndexInput & {
index: Map<string, 'needs-input' | 'running'>
}) | null = null
function computeRepoActivityIndex(input: RepoActivityIndexInput): Map<string, 'needs-input' | 'running'> {
const { statuses, parents, runningShells, directories, pendingInputSessionIDs } = input
const index = new Map<string, 'needs-input' | 'running'>()
const markNeedsInput = (directory?: string | null): void => {
const normalized = normalizeDirectory(directory)
if (normalized) index.set(normalized, 'needs-input')
}
const markRunning = (directory?: string | null): void => {
const normalized = normalizeDirectory(directory)
if (!normalized || index.get(normalized) === 'needs-input') return
index.set(normalized, 'running')
}
for (const sessionID of pendingInputSessionIDs) {
markNeedsInput(directories.get(sessionID))
markNeedsInput(directories.get(rootSessionID(sessionID, parents)))
}
for (const [sessionID, status] of statuses) {
if (status.type === 'idle') continue
markRunning(directories.get(sessionID))
markRunning(directories.get(rootSessionID(sessionID, parents)))
}
for (const shell of runningShells.values()) {
markRunning(shell.directory)
markRunning(directories.get(shell.sessionID))
markRunning(directories.get(rootSessionID(shell.sessionID, parents)))
}
return index
}
/**
* Indexes active sessions by normalized directory for repo badges. Pending input marks its own and
* its root's directory as needs-input; non-idle sessions and running shells mark running unless
* needs-input already claimed the directory. Shared across rows per store snapshot by reference.
*/
export function buildRepoActivityIndex(
input: RepoActivityIndexInput,
): Map<string, 'needs-input' | 'running'> {
if (
cachedRepoActivityIndex &&
cachedRepoActivityIndex.statuses === input.statuses &&
cachedRepoActivityIndex.parents === input.parents &&
cachedRepoActivityIndex.runningShells === input.runningShells &&
cachedRepoActivityIndex.directories === input.directories &&
cachedRepoActivityIndex.pendingInputSessionIDs === input.pendingInputSessionIDs
) {
return cachedRepoActivityIndex.index
}
const index = computeRepoActivityIndex(input)
cachedRepoActivityIndex = { ...input, index }
return index
}
/** The repo's activity from a prebuilt index, checking each of its paths. Needs-input outranks running. */
export function repoActivityFromIndex(
repo: Repo,
index: ReadonlyMap<string, 'needs-input' | 'running'>,
): 'needs-input' | 'running' | null {
let running = false
for (const path of [repo.fullPath, repo.localPath, repo.sourcePath]) {
const normalized = normalizeDirectory(path)
if (!normalized) continue
const state = index.get(normalized)
if (state === 'needs-input') return 'needs-input'
if (state === 'running') running = true
}
return running ? 'running' : null
}
/**
* 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.
* The input may mix roots and children; children never become items, but their latest update time
* rolls up into the root's `updatedAt` and decides the recent window and ordering.
*/
export function buildActiveWork(input: {
now: number
windowMs: number
repos: Repo[]
sessions: Session[]
parents: ReadonlyMap<string, string | null>
roots: { needsInput: Set<string>; running: Set<string> }
outcomes: ReadonlyMap<string, ChildOutcome>
}): ActiveWorkGroups {
const { now, windowMs, repos, sessions, parents, roots, outcomes } = input
const windowStart = now - windowMs
const activityByRoot = new Map<string, number>()
for (const session of sessions) {
if (session.time.archived) continue
const rootID = rootSessionID(session.id, parents)
const current = activityByRoot.get(rootID)
if (current === undefined || session.time.updated > current) {
activityByRoot.set(rootID, session.time.updated)
}
}
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
if (rootSessionID(session.id, parents) !== session.id) continue
const updatedAt = activityByRoot.get(session.id) ?? session.time.updated
const state: ActiveWorkState | null = roots.needsInput.has(session.id)
? 'needs-input'
: roots.running.has(session.id)
? 'running'
: updatedAt >= 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,
updatedAt,
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.updatedAt - a.updatedAt
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,
@@ -9,6 +9,7 @@ const resetStore = () => {
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
directories: new Map(),
runningShells: new Map(),
shellRevisions: new Map(),
shellRevision: 0,
+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
@@ -109,6 +109,7 @@ export const AssistantSettingsPatchSchema = UserPreferencesSchema.pick({
mode: true,
defaultModel: true,
walkthroughModel: true,
activityWindowMinutes: true,
defaultAgent: true,
autoScroll: true,
expandDiffs: true,
+14
View File
@@ -66,6 +66,18 @@ export type STTConfig = {
export const DEFAULT_LEADER_KEY = 'Ctrl+X';
export const ACTIVITY_WINDOW_MINUTE_OPTIONS = [15, 30, 60, 120, 240, 480, 1440] as const;
export const ActivityWindowMinutesSchema = z.literal(ACTIVITY_WINDOW_MINUTE_OPTIONS);
export type ActivityWindowMinutes = z.infer<typeof ActivityWindowMinutesSchema>;
export const DEFAULT_ACTIVITY_WINDOW_MINUTES: ActivityWindowMinutes = 30;
export function isActivityWindowMinutes(value: unknown): value is ActivityWindowMinutes {
return ActivityWindowMinutesSchema.safeParse(value).success;
}
export const DEFAULT_KEYBOARD_SHORTCUTS = {
submit: 'Cmd+Enter',
abort: 'Escape',
@@ -192,6 +204,7 @@ export const UserPreferencesSchema = z.object({
mode: z.enum(["plan", "build"]),
defaultModel: z.string().optional(),
walkthroughModel: z.string().optional(),
activityWindowMinutes: ActivityWindowMinutesSchema.optional(),
defaultAgent: z.string().optional(),
autoScroll: z.boolean(),
expandDiffs: z.boolean(),
@@ -249,6 +262,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,