Global Usage dashboard dialog (?usage=open) with sidebar

This commit is contained in:
Chris Scott authored and Forge Sandbox committed 2026-11-30 05:49:19 +00:00
1 parent 4d5a2c745e
commit 987339e3b8
29 files changed
+2343 -33

No files matched your search

+2
View File
@@ -17,6 +17,7 @@ import { Register } from './pages/Register'
import { Setup } from './pages/Setup'
import { AssistantRedirect } from './pages/AssistantRedirect'
import { SettingsDialog } from './components/settings/SettingsDialog'
import { UsageDialog } from '@/components/usage/UsageDialog'
import { VersionNotifier } from './components/VersionNotifier'
import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt'
import { MobileTabBar } from '@/components/navigation/MobileTabBar'
@@ -242,6 +243,7 @@ export function AppShell() {
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<UsageDialog />
<HealthMonitor />
<VersionNotifier />
</KeyboardShortcutsProvider>
@@ -93,7 +93,7 @@ describe('DesktopSidebar', () => {
async (path) => {
renderSidebar({ route: path })
for (const label of ['Home', 'Settings', 'Logout']) {
for (const label of ['Home', 'Usage', 'Settings', 'Logout']) {
expect(await screen.findByText(label)).toBeInTheDocument()
}
for (const label of [
@@ -143,6 +143,17 @@ describe('DesktopSidebar', () => {
expect(searchParams(capturedSearch).get('settingsTab')).toBe('account')
})
it('opens usage by updating usage query params', async () => {
const { capturedPathname, capturedSearch } = renderSidebar({ route: '/?dialog=files&mobileTab=more' })
fireEvent.click(await screen.findByText('Usage'))
await waitFor(() => expect(searchParams(capturedSearch).get('usage')).toBe('open'))
expect(capturedPathname.current).toBe('/')
expect(searchParams(capturedSearch).get('dialog')).toBe('files')
expect(searchParams(capturedSearch).get('mobileTab')).toBeNull()
})
it('renders the session tree with home and account items in the footer', async () => {
renderSidebar({ route: '/repos/5' })
@@ -150,6 +161,7 @@ describe('DesktopSidebar', () => {
expect(within(region).getByLabelText('Search sessions')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Sessions' })).toBeNull()
expect(screen.getByText('Home')).toBeInTheDocument()
expect(screen.getByText('Usage')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
})
@@ -167,6 +179,7 @@ describe('DesktopSidebar', () => {
expect(await screen.findByText('Sessions')).toBeInTheDocument()
expect(screen.queryByLabelText('Search sessions')).toBeNull()
expect(screen.getByText('Home')).toBeInTheDocument()
expect(screen.getByText('Usage')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.queryByText('Files')).toBeNull()
})
@@ -9,6 +9,7 @@ import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { useSessionPickerRouteScope } from '@/hooks/useSessionPickerRouteScope'
import { useSessionPickerNavigation } from '@/hooks/useSessionPickerNavigation'
import { useToolPanelToggle } from '@/hooks/useToolPanel'
import { useUsageDialog } from '@/hooks/useUsageDialog'
import { useUIState } from '@/stores/uiStateStore'
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
import { SessionPickerDialog } from '@/components/session/SessionPickerDialog'
@@ -21,7 +22,7 @@ import {
} from '@/components/ui/sidebar'
import { List } from 'lucide-react'
const FOOTER_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
const FOOTER_ITEM_KEYS = new Set(['home', 'usage', 'settings', 'logout'])
function DesktopSessionsPicker({ onDismiss }: { onDismiss: () => void }) {
const { currentRepo, activeSessionID, remote } = useSessionPickerRouteScope(true)
@@ -52,6 +53,7 @@ export function DesktopSidebar() {
const { isAuthenticated, isLoading, logout } = useAuth()
const isToolRailMounted = useUIState((state) => state.isToolRailMounted)
const togglePanelTool = useToolPanelToggle()
const { open: openUsageDialog } = useUsageDialog()
const isDesktop = useDesktop()
@@ -67,7 +69,9 @@ export function DesktopSidebar() {
const handleItemClick = (item: MoreDrawerItem) => {
if (openNavItem(item)) return
if (item.key === 'logout') {
if (item.key === 'usage') {
openUsageDialog()
} else if (item.key === 'logout') {
logout()
} else if (item.key === 'settings') {
updateParams((p) => {
@@ -75,6 +75,18 @@ describe('MoreDrawer', () => {
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
expect(screen.getAllByText('Usage')).toHaveLength(1)
expect(screen.getByText('Home').closest('section')).toContainElement(screen.getByText('Usage'))
})
it('opens the usage dialog from the drawer without navigating', async () => {
const { capturedPathname, capturedSearch } = renderMoreDrawer('/?mobileTab=more')
fireEvent.click(screen.getByText('Usage'))
await waitFor(() => expect(capturedSearch.current).toContain('usage=open'))
expect(new URLSearchParams(capturedSearch.current).get('mobileTab')).toBeNull()
expect(capturedPathname.current).toBe('/')
})
it('does not render theme controls', () => {
@@ -12,6 +12,7 @@ import { ScheduleReportsList } from '@/components/notifications/ScheduleReportsB
import { useMarkAllScheduleRunsViewed, useUnreadScheduleRuns } from '@/hooks/useSchedules'
import { buildMoreItems, buildNavModel, isManagerOnlyNavItem, isSessionDetailPath, type MoreDrawerItem } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { useUsageDialog } from '@/hooks/useUsageDialog'
import { cn, getRepoDisplayName } from '@/lib/utils'
import { getPathWithReturnTo, isAssistantPath, parseServerSessionRoute } from '@/lib/navigation'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
@@ -81,6 +82,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const isAssistantSession = isSessionDetail && searchParams.get('assistant') === '1'
const isRemoteRoute = !isLocalOpenCodeServer(useRouteOpenCodeServerId())
const { open: openMobileSheet } = useMobileTabBar()
const { open: openUsageDialog } = useUsageDialog()
const { data: unreadReports } = useUnreadScheduleRuns()
const markAllReportsViewed = useMarkAllScheduleRunsViewed()
const total = unreadReports?.total ?? 0
@@ -122,6 +124,10 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
}
const handleItemClick = (item: MoreDrawerItem) => {
if (item.key === 'usage') {
openUsageDialog('replace')
return
}
if (item.key === 'settings') {
handleSettingsClick()
return
@@ -2,19 +2,20 @@ import { describe, it, expect } from 'vitest'
import { buildMoreItems, buildNavModel, buildToolItems } from './moreDrawerItems'
describe('buildMoreItems', () => {
it('returns Home + All Schedules + Files + Settings + Logout for root path', () => {
it('returns Home + All Schedules + Files + Usage + Settings + Logout for root path', () => {
const items = buildMoreItems('/')
expect(items).toHaveLength(5)
expect(items).toHaveLength(6)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('all-schedules')
expect(items[2].key).toBe('files')
expect(items[3].key).toBe('settings')
expect(items[4].key).toBe('logout')
expect(items[3].key).toBe('usage')
expect(items[4].key).toBe('settings')
expect(items[5].key).toBe('logout')
})
it('returns repo-specific items for /repos/:id', () => {
const items = buildMoreItems('/repos/42')
expect(items).toHaveLength(13)
expect(items).toHaveLength(14)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[1].dialog).toBe('files')
@@ -37,13 +38,14 @@ describe('buildMoreItems', () => {
expect(items[9].dialog).toBe('actions')
expect(items[10].key).toBe('preview')
expect(items[10].dialog).toBe('preview')
expect(items[11].key).toBe('settings')
expect(items[12].key).toBe('logout')
expect(items[11].key).toBe('usage')
expect(items[12].key).toBe('settings')
expect(items[13].key).toBe('logout')
})
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
const items = buildMoreItems('/repos/42/sessions/abc')
expect(items).toHaveLength(13)
expect(items).toHaveLength(14)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[2].key).toBe('mcp')
@@ -60,8 +62,9 @@ describe('buildMoreItems', () => {
expect(items[9].dialog).toBe('actions')
expect(items[10].key).toBe('preview')
expect(items[10].dialog).toBe('preview')
expect(items[11].key).toBe('settings')
expect(items[12].key).toBe('logout')
expect(items[11].key).toBe('usage')
expect(items[12].key).toBe('settings')
expect(items[13].key).toBe('logout')
})
it('returns only the server tools a linked server can serve for /servers/:id/sessions/:sid', () => {
@@ -72,6 +75,7 @@ describe('buildMoreItems', () => {
'skills',
'source-control',
'terminal',
'usage',
'settings',
'logout',
])
@@ -85,6 +89,7 @@ describe('buildMoreItems', () => {
'skills',
'source-control',
'terminal',
'usage',
'settings',
'logout',
])
@@ -93,19 +98,20 @@ describe('buildMoreItems', () => {
it('omits the Actions item for an Assistant session', () => {
const items = buildMoreItems('/repos/0/sessions/abc')
expect(items).toHaveLength(12)
expect(items).toHaveLength(13)
expect(items.map((item) => item.key)).not.toContain('actions')
expect(items[7].key).toBe('terminal')
expect(items[8].key).toBe('walkthrough')
expect(items[9].key).toBe('preview')
expect(items[9].dialog).toBe('preview')
expect(items[10].key).toBe('settings')
expect(items[11].key).toBe('logout')
expect(items[10].key).toBe('usage')
expect(items[11].key).toBe('settings')
expect(items[12].key).toBe('logout')
})
it('returns assistant workspace items for /repos/:id/assistant', () => {
const items = buildMoreItems('/repos/42/assistant')
expect(items).toHaveLength(11)
expect(items).toHaveLength(12)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[1].dialog).toBe('files')
@@ -118,32 +124,36 @@ describe('buildMoreItems', () => {
expect(items[7].dialog).toBe('terminal')
expect(items[8].key).toBe('preview')
expect(items[8].dialog).toBe('preview')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
expect(items[9].key).toBe('usage')
expect(items[10].key).toBe('settings')
expect(items[11].key).toBe('logout')
})
it('returns only Home + Settings + Logout for /schedules', () => {
it('returns only Home + Usage + Settings + Logout for /schedules', () => {
const items = buildMoreItems('/schedules')
expect(items).toHaveLength(3)
expect(items).toHaveLength(4)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('settings')
expect(items[2].key).toBe('logout')
expect(items[1].key).toBe('usage')
expect(items[2].key).toBe('settings')
expect(items[3].key).toBe('logout')
})
it('returns only Home + Settings + Logout for /repos/:id/schedules', () => {
it('returns only Home + Usage + Settings + Logout for /repos/:id/schedules', () => {
const items = buildMoreItems('/repos/42/schedules')
expect(items).toHaveLength(3)
expect(items).toHaveLength(4)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('settings')
expect(items[2].key).toBe('logout')
expect(items[1].key).toBe('usage')
expect(items[2].key).toBe('settings')
expect(items[3].key).toBe('logout')
})
it('returns only Home + Settings + Logout for unknown paths', () => {
it('returns only Home + Usage + Settings + Logout for unknown paths', () => {
const items = buildMoreItems('/unknown/path')
expect(items).toHaveLength(3)
expect(items).toHaveLength(4)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('settings')
expect(items[2].key).toBe('logout')
expect(items[1].key).toBe('usage')
expect(items[2].key).toBe('settings')
expect(items[3].key).toBe('logout')
})
it('leads every route with a Home item routed to /', () => {
@@ -227,6 +237,10 @@ describe('buildToolItems', () => {
expect(secrets?.panelTool).toBeUndefined()
})
it('keeps the Usage entry out of the tool rail', () => {
expect(buildToolItems('/repos/42/sessions/abc').map((item) => item.key)).not.toContain('usage')
})
it.each(['/schedules', '/repos/42/schedules'])('returns only the Sessions tool on %s', (path) => {
expect(buildToolItems(path).map((item) => item.key)).toEqual(['sessions'])
})
@@ -1,5 +1,5 @@
import type { LucideIcon } from 'lucide-react'
import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, List, Play, Globe, KeyRound } from 'lucide-react'
import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, List, Play, Globe, KeyRound, BarChart3 } from 'lucide-react'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
@@ -42,6 +42,7 @@ function getHomeItem(): MoreDrawerItem {
function getBaseItems(): MoreDrawerItem[] {
return [
{ key: 'usage', label: 'Usage', icon: BarChart3 },
{ key: 'settings', label: 'Settings', icon: Settings },
{ key: 'logout', label: 'Logout', icon: LogOut },
]
@@ -55,7 +56,7 @@ export function isSessionDetailPath(pathname: string): boolean {
return SESSION_DETAIL_PATH.test(pathname)
}
const NON_TOOL_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
const NON_TOOL_ITEM_KEYS = new Set(['home', 'usage', 'settings', 'logout'])
const MANAGER_ONLY_ITEM_KEYS: ReadonlySet<string> = new Set([
'files',
@@ -0,0 +1,67 @@
import { describe, it, expect } from 'vitest'
import { screen } from '@testing-library/react'
import { renderWithProviders } from '@/test/render'
import { UsageActivityChart } from './UsageActivityChart'
const providerOptions = { auth: false, theme: false, tts: false } as const
function barHeight(label: string): string {
const bar = screen.getByRole('img', { name: label })
return bar.style.height
}
describe('UsageActivityChart', () => {
it('renders one accessible bar per day', () => {
renderWithProviders(
<UsageActivityChart
activity={[
{ date: '2026-01-01', steps: 3 },
{ date: '2026-01-02', steps: 1 },
]}
/>,
providerOptions,
)
expect(screen.getByText('Activity')).toBeInTheDocument()
expect(screen.getByRole('img', { name: '2026-01-01: 3 steps' })).toBeInTheDocument()
expect(screen.getByRole('img', { name: '2026-01-02: 1 steps' })).toBeInTheDocument()
expect(screen.getAllByRole('img')).toHaveLength(2)
})
it('scales bar heights against the busiest day', () => {
renderWithProviders(
<UsageActivityChart
activity={[
{ date: '2026-01-01', steps: 10 },
{ date: '2026-01-02', steps: 5 },
]}
/>,
providerOptions,
)
expect(barHeight('2026-01-01: 10 steps')).toBe('100%')
expect(barHeight('2026-01-02: 5 steps')).toBe('50%')
})
it('renders nothing when there is no activity', () => {
renderWithProviders(<UsageActivityChart activity={[]} />, providerOptions)
expect(screen.queryByText('Activity')).not.toBeInTheDocument()
expect(screen.queryAllByRole('img')).toHaveLength(0)
})
it('keeps all-zero activity visible without throwing', () => {
renderWithProviders(
<UsageActivityChart
activity={[
{ date: '2026-01-01', steps: 0 },
{ date: '2026-01-02', steps: 0 },
]}
/>,
providerOptions,
)
expect(screen.getAllByRole('img')).toHaveLength(2)
expect(barHeight('2026-01-01: 0 steps')).toBe('0%')
})
})
@@ -0,0 +1,33 @@
import type { SessionStatsActivity } from '@opencode-manager/shared/opencode'
interface UsageActivityChartProps {
activity: SessionStatsActivity[]
}
export function UsageActivityChart({ activity }: UsageActivityChartProps) {
if (activity.length === 0) return null
const maxSteps = Math.max(...activity.map((day) => day.steps))
return (
<div className="space-y-2">
<h2 className="text-sm font-medium">Activity</h2>
<div className="flex h-32 items-end gap-1">
{activity.map((day) => {
const height = maxSteps === 0 ? 0 : Math.max(2, Math.round((day.steps / maxSteps) * 100))
const label = `${day.date}: ${day.steps} steps`
return (
<div
key={day.date}
role="img"
aria-label={label}
title={label}
className="flex-1 rounded-sm bg-primary"
style={{ height: `${height}%` }}
/>
)
})}
</div>
</div>
)
}
@@ -0,0 +1,385 @@
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { SessionStatsInfo } from '@opencode-manager/shared/opencode'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { renderWithProviders } from '@/test/render'
import { installPointerCapture } from '@/test/browserFakes'
import type { FetchRoute } from '@/test/fetchFake'
import { makeRepo, makeSession } from '@/test/fixtures/api'
import { UsageDashboard } from './UsageDashboard'
const providerOptions = { auth: false, theme: false, tts: false } as const
const statsPath = '/api/opencode/api/experimental/session/stats'
const statsFixture: SessionStatsInfo = {
range: {
from: new Date('2026-01-01T00:00:00').getTime(),
to: new Date('2026-01-01T04:00:00').getTime(),
},
sessions: 3,
subagents: 0,
prompts: 9,
steps: 12,
tokens: { input: 1500, output: 500, reasoning: 0, cache: { read: 200, write: 0 } },
cost: 1,
tools: {
mode: 'detail',
totals: { calls: 2, succeeded: 1, failed: 1, unfinished: 0 },
usage: [
{ name: 'bash', calls: 2, succeeded: 1, failed: 1, unfinished: 0, durationP50: 120 },
],
},
activeDays: 2,
streak: 1,
activity: [{ date: '2026-01-01', steps: 12 }],
models: [
{
model: { providerID: 'anthropic', id: 'claude' },
steps: 10,
tokens: { input: 1000, output: 400, reasoning: 0, cache: { read: 200, write: 0 } },
cost: 0.75,
},
{
model: { providerID: 'openai', id: 'gpt-4o' },
steps: 2,
tokens: { input: 500, output: 100, reasoning: 0, cache: { read: 0, write: 0 } },
cost: 0.25,
},
],
}
const hiddenSectionsNote =
'Prompts, streak, activity, tool reliability and sessions cannot be split per model, so they are hidden while a model filter is active.'
function statsRoute(path: string = statsPath): FetchRoute {
return { method: 'GET', path, respond: () => ({ json: { data: statsFixture } }) }
}
function localSessionsRoute(): FetchRoute {
return {
method: 'GET',
path: '/api/opencode/api/session',
respond: () => ({
json: {
data: [
makeSession({
id: 'ses_1',
title: 'Fix tests',
location: { directory: '/workspace/demo' },
cost: 0.4,
tokens: {
input: 100,
output: 50,
reasoning: 0,
cache: { read: 0, write: 0 },
},
time: { created: 1, updated: 2 },
}),
],
cursor: {},
},
}),
}
}
function remoteSessionsRoute(serverId: string): FetchRoute {
return {
method: 'GET',
path: `/api/opencode/servers/${serverId}/api/session`,
respond: () => ({
json: {
data: [
makeSession({
id: 'ses_remote',
title: 'Remote session',
cost: 1,
time: { created: 1, updated: 2 },
}),
],
cursor: {},
},
}),
}
}
function reposRoute(): FetchRoute {
return {
method: 'GET',
path: '/api/repos',
respond: () => ({ json: [makeRepo({ id: 1, fullPath: '/workspace/demo' })] }),
}
}
function sessionMessageFallback() {
return { json: { data: [], cursor: {} } }
}
function statText(label: string): string {
const grid = screen.getByText('Spend').parentElement?.parentElement
if (!grid) throw new Error('Summary grid not found')
const labelNode = within(grid).getByText(label)
return labelNode.parentElement?.textContent ?? ''
}
function freezeNow(): void {
vi.spyOn(Date, 'now').mockReturnValue(2_000)
}
async function openModelMenu(user: ReturnType<typeof userEvent.setup>): Promise<void> {
await user.click(screen.getByRole('button', { name: 'Filter by model' }))
}
afterEach(() => {
vi.restoreAllMocks()
})
beforeAll(() => {
installPointerCapture()
})
describe('UsageDashboard', () => {
it('renders the default 4h summary, composition, models, tools, sessions, and range without a chart', async () => {
freezeNow()
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
expect(screen.getByRole('combobox', { name: 'Range' })).toHaveTextContent('Last 4 hours')
await screen.findByText('Fix tests')
expect(
screen.getByText('Jan 1, 2026 00:00 – Jan 1, 2026 04:00'),
).toBeInTheDocument()
expect(statText('Spend')).toContain('$1.00')
expect(statText('Tokens')).toContain('2k')
expect(statText('Steps')).toContain('12')
expect(statText('Prompts')).toContain('9')
expect(statText('Active days')).toContain('2')
expect(statText('Streak')).toContain('1')
expect(screen.getByRole('heading', { name: 'Token composition' })).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Models' })).toBeInTheDocument()
expect(screen.getByText('anthropic/claude')).toBeInTheDocument()
expect(screen.getByText('openai/gpt-4o')).toBeInTheDocument()
expect(screen.getByText('75.0%')).toBeInTheDocument()
expect(screen.getByText('25.0%')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Tools' })).toBeInTheDocument()
expect(screen.getByText('bash')).toBeInTheDocument()
expect(screen.getByText('Total')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Sessions by spend' })).toBeInTheDocument()
expect(screen.getByText('Fix tests')).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'Activity' })).not.toBeInTheDocument()
})
it('shows the activity chart for a whole-day range', async () => {
window.localStorage.setItem('oc:usage:range', JSON.stringify({ preset: '7d' }))
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
expect(screen.getByRole('combobox', { name: 'Range' })).toHaveTextContent('Last 7 days')
expect(
await screen.findByRole('img', { name: '2026-01-01: 12 steps' }),
).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Activity' })).toBeInTheDocument()
})
it('persists a changed range and restores it on the next open', async () => {
const user = userEvent.setup()
const first = renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
await screen.findByRole('heading', { name: 'Sessions by spend' })
await user.click(screen.getByRole('combobox', { name: 'Range' }))
await user.click(screen.getByRole('option', { name: 'Last 7 days' }))
expect(JSON.parse(window.localStorage.getItem('oc:usage:range') ?? 'null')).toEqual({
preset: '7d',
})
first.unmount()
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
expect(screen.getByRole('combobox', { name: 'Range' })).toHaveTextContent('Last 7 days')
})
it('filters summaries and models to a single selected model and hides unsplittable sections', async () => {
const user = userEvent.setup()
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
await screen.findByRole('heading', { name: 'Sessions by spend' })
await openModelMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: 'anthropic/claude' }))
expect(statText('Spend')).toContain('$0.7500')
expect(statText('Tokens')).toContain('2k')
expect(statText('Steps')).toContain('10')
expect(screen.getByText(hiddenSectionsNote)).toBeInTheDocument()
expect(screen.queryByText('Prompts')).not.toBeInTheDocument()
expect(screen.queryByText('Active days')).not.toBeInTheDocument()
expect(screen.queryByText('Streak')).not.toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'Activity' })).not.toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'Tools' })).not.toBeInTheDocument()
expect(screen.queryByText('Sessions by spend')).not.toBeInTheDocument()
expect(screen.queryByText('openai/gpt-4o')).not.toBeInTheDocument()
expect(screen.getAllByText('anthropic/claude').length).toBeGreaterThan(0)
})
it('shows the remaining count when two models are selected', async () => {
const user = userEvent.setup()
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
await screen.findByRole('heading', { name: 'Sessions by spend' })
await openModelMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: 'anthropic/claude' }))
await openModelMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: 'openai/gpt-4o' }))
expect(screen.getByRole('button', { name: 'Filter by model' })).toHaveTextContent('+1 more')
})
it('resets filters back to all models and the default range', async () => {
const user = userEvent.setup()
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
await screen.findByRole('heading', { name: 'Sessions by spend' })
await openModelMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: 'anthropic/claude' }))
await openModelMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: 'openai/gpt-4o' }))
await user.click(screen.getByRole('button', { name: 'Reset filters' }))
expect(screen.getByRole('button', { name: 'Filter by model' })).toHaveTextContent('All models')
expect(screen.getByRole('combobox', { name: 'Range' })).toHaveTextContent('Last 4 hours')
expect(statText('Prompts')).toContain('9')
expect(screen.getByText('openai/gpt-4o')).toBeInTheDocument()
expect(screen.queryByText(hiddenSectionsNote)).not.toBeInTheDocument()
expect(window.localStorage.getItem('oc:usage:models')).toBe('[]')
})
it('prunes stored models that are missing from the loaded stats', async () => {
window.localStorage.setItem(
'oc:usage:models',
JSON.stringify(['anthropic/claude', 'ghost/model']),
)
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
await waitFor(() =>
expect(JSON.parse(window.localStorage.getItem('oc:usage:models') ?? '[]')).toEqual([
'anthropic/claude',
]),
)
})
it('renders an error banner when the stats request fails', async () => {
renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [
{
method: 'GET',
path: statsPath,
respond: () => ({ status: 500, json: { error: 'boom' } }),
},
],
fetchFallback: sessionMessageFallback,
})
expect(await screen.findByText('Usage unavailable')).toBeInTheDocument()
expect(
screen.getByText('This OpenCode server could not return usage statistics.'),
).toBeInTheDocument()
expect(screen.getByRole('combobox', { name: 'Range' })).toHaveTextContent('Last 4 hours')
})
it('loads a linked server and links its sessions to the server route', async () => {
freezeNow()
const serverId = 'srv_kitchen'
const remoteStatsPath = `/api/opencode/servers/${serverId}/api/experimental/session/stats`
const result = renderWithProviders(<UsageDashboard serverId={serverId} />, {
...providerOptions,
fetchRoutes: [
statsRoute(remoteStatsPath),
remoteSessionsRoute(serverId),
],
fetchFallback: sessionMessageFallback,
})
const link = await screen.findByRole('link', { name: 'Remote session' })
expect(link).toHaveAttribute('href', '/servers/srv_kitchen/sessions/ses_remote')
expect(result.fetchFake.findRequests('GET', remoteStatsPath)).toHaveLength(1)
expect(screen.getAllByText('Spend').length).toBeGreaterThan(0)
expect(screen.getAllByText('Tokens').length).toBeGreaterThan(0)
expect(result.fetchFake.findRequests('GET', '/api/repos')).toHaveLength(0)
})
it('asks for a custom range instead of loading stats when the range is incomplete', async () => {
window.localStorage.setItem(
'oc:usage:range',
JSON.stringify({ preset: 'custom', from: null, to: null }),
)
const result = renderWithProviders(<UsageDashboard serverId={LOCAL_OPENCODE_SERVER_ID} />, {
...providerOptions,
fetchRoutes: [statsRoute(), localSessionsRoute(), reposRoute()],
fetchFallback: sessionMessageFallback,
})
expect(
screen.getByText('Choose a start and end time to see usage for a custom range.'),
).toBeInTheDocument()
expect(screen.queryByText('Loading usage…')).not.toBeInTheDocument()
expect(result.fetchFake.findRequests('GET', statsPath)).toHaveLength(0)
})
})
@@ -0,0 +1,163 @@
import { useEffect } from 'react'
import { format } from 'date-fns'
import type { SessionStatsInfo } from '@opencode-manager/shared/opencode'
import { ActivitySpinner } from '@/components/ui/activity-spinner'
import { Button } from '@/components/ui/button'
import { ErrorBanner } from '@/components/ui/error-banner'
import { useUsageStats } from '@/hooks/useUsage'
import {
USAGE_RANGE_STORAGE_KEY,
useUsageModelsPreference,
useUsageRangePreference,
} from '@/hooks/useUsagePreferences'
import {
DEFAULT_GLOBAL_USAGE_RANGE,
rangeHasDailyActivity,
resolveUsageRange,
type ResolvedUsageRange,
type UsageRangeSelection,
} from '@/lib/usageRange'
import { filterModelUsage, modelUsageKey } from '@/lib/usageStats'
import { UsageActivityChart } from './UsageActivityChart'
import { UsageModelFilter } from './UsageModelFilter'
import { UsageModelsTable } from './UsageModelsTable'
import { UsageRangePicker } from './UsageRangePicker'
import { UsageSessionsTable } from './UsageSessionsTable'
import { UsageSummaryCards } from './UsageSummaryCards'
import { UsageTokenComposition } from './UsageTokenComposition'
import { UsageToolsTable } from './UsageToolsTable'
interface UsageDashboardProps {
serverId: string
}
const RANGE_DISPLAY_FORMAT = 'MMM d, yyyy HH:mm'
function isDefaultUsageRange(selection: UsageRangeSelection): boolean {
if (selection.preset !== DEFAULT_GLOBAL_USAGE_RANGE.preset) return false
if (selection.preset !== 'custom') return true
const fallback = DEFAULT_GLOBAL_USAGE_RANGE
return (
fallback.preset === 'custom' &&
selection.from === fallback.from &&
selection.to === fallback.to
)
}
export function UsageDashboard({ serverId }: UsageDashboardProps) {
const [range, setSelection] = useUsageRangePreference(
USAGE_RANGE_STORAGE_KEY,
DEFAULT_GLOBAL_USAGE_RANGE,
)
const [models, setModels] = useUsageModelsPreference()
const resolvedRange = resolveUsageRange(range, Date.now())
const stats = useUsageStats(range, serverId)
const data = stats.data
useEffect(() => {
if (!data) return
const available = new Set(data.models.map((entry) => modelUsageKey(entry.model)))
const pruned = models.filter((key) => available.has(key))
if (pruned.length !== models.length) setModels(pruned)
}, [data, models, setModels])
const isFiltered = models.length > 0
const showReset = isFiltered || !isDefaultUsageRange(range)
function renderStats(statsData: SessionStatsInfo, activeRange: ResolvedUsageRange) {
const totals = filterModelUsage(statsData.models, models)
return (
<div className="space-y-6">
<p className="text-xs text-muted-foreground">
{`${format(statsData.range.from, RANGE_DISPLAY_FORMAT)} – ${format(statsData.range.to, RANGE_DISPLAY_FORMAT)}`}
</p>
{isFiltered ? (
<>
<UsageSummaryCards cost={totals.cost} tokens={totals.tokens} steps={totals.steps} />
<UsageTokenComposition tokens={totals.tokens} />
<UsageModelsTable
models={statsData.models.filter((entry) =>
models.includes(modelUsageKey(entry.model)),
)}
/>
<p className="text-xs text-muted-foreground">
Prompts, streak, activity, tool reliability and sessions cannot be split per model,
so they are hidden while a model filter is active.
</p>
</>
) : (
<>
<UsageSummaryCards
cost={totals.cost}
tokens={totals.tokens}
steps={totals.steps}
prompts={statsData.prompts}
activeDays={statsData.activeDays}
streak={statsData.streak}
/>
<UsageTokenComposition tokens={totals.tokens} />
{rangeHasDailyActivity(range, Date.now()) && (
<UsageActivityChart activity={statsData.activity} />
)}
<UsageModelsTable models={statsData.models} />
{statsData.tools.mode === 'detail' && (
<UsageToolsTable totals={statsData.tools.totals} usage={statsData.tools.usage} />
)}
<UsageSessionsTable serverId={serverId} range={activeRange} />
</>
)}
</div>
)
}
function renderContent() {
if (resolvedRange === null) {
return <p>Choose a start and end time to see usage for a custom range.</p>
}
if (stats.isPending) {
return (
<div className="flex items-center gap-2">
<ActivitySpinner />
<span>Loading usage…</span>
</div>
)
}
if (stats.isError) {
return (
<ErrorBanner
title="Usage unavailable"
summary="This OpenCode server could not return usage statistics."
detail={stats.error instanceof Error ? stats.error.message : undefined}
/>
)
}
if (!stats.data) return null
return renderStats(stats.data, resolvedRange)
}
return (
<div className="space-y-6">
<div className="flex flex-wrap items-end gap-2">
<UsageRangePicker value={range} onChange={setSelection} />
<UsageModelFilter
models={data?.models.map((entry) => modelUsageKey(entry.model)) ?? []}
selected={models}
onChange={setModels}
/>
{showReset && (
<Button
variant="outline"
size="sm"
onClick={() => {
setModels([])
setSelection(DEFAULT_GLOBAL_USAGE_RANGE)
}}
>
Reset filters
</Button>
)}
</div>
{renderContent()}
</div>
)
}
@@ -0,0 +1,187 @@
import { describe, expect, it } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useNavigate } from 'react-router-dom'
import type { SessionStatsInfo } from '@opencode-manager/shared/opencode'
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
import { useUsageDialog } from '@/hooks/useUsageDialog'
import { renderWithProviders } from '@/test/render'
import { LocationCatcher } from '@/test/test-components'
import type { FetchRoute } from '@/test/fetchFake'
import { UsageDialog } from './UsageDialog'
const STATS_PATH = '/api/opencode/api/experimental/session/stats'
const statsFixture: SessionStatsInfo = {
range: { from: 0, to: 1000 },
sessions: 0,
subagents: 0,
prompts: 0,
steps: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
cost: 0,
tools: { mode: 'none' },
activeDays: 0,
streak: 0,
activity: [],
models: [],
}
function dialogFetchRoutes(): FetchRoute[] {
return [
{ method: 'GET', path: '/api/opencode-servers', respond: () => ({ json: { servers: [] } }) },
{ method: 'GET', path: '/api/opencode-servers/status', respond: () => ({ json: { statuses: [] } }) },
{ method: 'GET', path: '/api/repos', respond: () => ({ json: [] }) },
{ method: 'GET', path: '/api/opencode/api/session', respond: () => ({ json: { data: [], cursor: {} } }) },
{ method: 'GET', path: STATS_PATH, respond: () => ({ json: { data: statsFixture } }) },
]
}
const providerOptions = { auth: false, theme: false, tts: false } as const
const fetchFallback = () => ({ json: { data: [], cursor: {} } })
function UsageHarness() {
const { open, close } = useUsageDialog()
const navigate = useNavigate()
return (
<div>
<button onClick={() => open()}>Open usage</button>
<button onClick={close}>Close usage</button>
<button onClick={() => navigate(-1)}>Go back</button>
<UsageDialog />
</div>
)
}
describe('UsageDialog', () => {
it('stays closed and requests no stats by default', () => {
const result = renderWithProviders(<UsageDialog />, {
...providerOptions,
initialEntries: ['/'],
fetchRoutes: dialogFetchRoutes(),
fetchFallback,
})
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(result.fetchFake.findRequests('GET', STATS_PATH)).toHaveLength(0)
})
it('renders the dashboard for the open URL param', async () => {
const result = renderWithProviders(<UsageDialog />, {
...providerOptions,
initialEntries: ['/?usage=open'],
fetchRoutes: dialogFetchRoutes(),
fetchFallback,
})
expect(await screen.findByRole('heading', { name: 'Usage' })).toBeInTheDocument()
expect(screen.getByRole('combobox', { name: 'Range' })).toBeInTheDocument()
await waitFor(() => expect(result.fetchFake.findRequests('GET', STATS_PATH)).toHaveLength(1))
})
it('closes through the close button and drops the usage param', async () => {
const user = userEvent.setup()
const capturedSearch = { current: '' }
renderWithProviders(
<>
<LocationCatcher capturedSearch={capturedSearch} />
<UsageDialog />
</>,
{
...providerOptions,
initialEntries: ['/?usage=open'],
fetchRoutes: dialogFetchRoutes(),
fetchFallback,
},
)
expect(await screen.findByRole('heading', { name: 'Usage' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Close' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await waitFor(() => expect(capturedSearch.current).not.toContain('usage'))
})
it('opens and closes through the hook while restoring the previous search', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 })
const capturedSearch = { current: '' }
const capturedPathname = { current: '' }
renderWithProviders(
<>
<LocationCatcher capturedSearch={capturedSearch} capturedPathname={capturedPathname} />
<UsageHarness />
</>,
{
...providerOptions,
initialEntries: ['/?keep=1'],
fetchRoutes: dialogFetchRoutes(),
fetchFallback,
},
)
await user.click(screen.getByRole('button', { name: 'Open usage' }))
expect(await screen.findByRole('heading', { name: 'Usage' })).toBeInTheDocument()
await waitFor(() => expect(capturedSearch.current).toContain('usage=open'))
await user.click(screen.getByRole('button', { name: 'Close usage', hidden: true }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await waitFor(() => expect(capturedSearch.current).toBe('?keep=1'))
expect(capturedPathname.current).toBe('/')
})
it('closes when the browser goes back after opening', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 })
const capturedSearch = { current: '' }
renderWithProviders(
<>
<LocationCatcher capturedSearch={capturedSearch} />
<UsageHarness />
</>,
{
...providerOptions,
initialEntries: ['/?keep=1'],
fetchRoutes: dialogFetchRoutes(),
fetchFallback,
},
)
await user.click(screen.getByRole('button', { name: 'Open usage' }))
expect(await screen.findByRole('heading', { name: 'Usage' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Go back', hidden: true }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await waitFor(() => expect(capturedSearch.current).toBe('?keep=1'))
})
it('requests stats from the selected linked server only', async () => {
const serverId = 'srv_kitchen'
const linkedStatsPath = `/api/opencode/servers/${serverId}/api/experimental/session/stats`
const linkedSessionsPath = `/api/opencode/servers/${serverId}/api/session`
useSidebarServerStore.getState().selectServer(serverId)
const result = renderWithProviders(<UsageDialog />, {
...providerOptions,
initialEntries: ['/?usage=open'],
fetchRoutes: [
...dialogFetchRoutes(),
{ method: 'GET', path: linkedStatsPath, respond: () => ({ json: { data: statsFixture } }) },
{ method: 'GET', path: linkedSessionsPath, respond: () => ({ json: { data: [], cursor: {} } }) },
],
fetchFallback,
})
expect(await screen.findByRole('heading', { name: 'Usage' })).toBeInTheDocument()
await waitFor(() => expect(result.fetchFake.findRequests('GET', linkedStatsPath)).toHaveLength(1))
expect(result.fetchFake.findRequests('GET', STATS_PATH)).toHaveLength(0)
})
})
@@ -0,0 +1,38 @@
import { X } from 'lucide-react'
import { LinkedServersNav } from '@/components/navigation/LinkedServersNav'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection'
import { useUsageDialog } from '@/hooks/useUsageDialog'
import { UsageDashboard } from './UsageDashboard'
export function UsageDialog() {
const { isOpen, close } = useUsageDialog()
const [serverId] = useSidebarServerSelection()
return (
<Dialog
open={isOpen}
onOpenChange={(open) => {
if (!open) close()
}}
>
<DialogContent fullscreen>
<div className="flex h-full min-h-0 flex-col">
<header className="flex items-center justify-between gap-3 border-b border-border px-4 py-3">
<DialogTitle className="text-base font-semibold">Usage</DialogTitle>
<div className="flex items-center gap-2">
<LinkedServersNav variant="header" />
<Button variant="ghost" size="icon" aria-label="Close" onClick={close}>
<X className="h-4 w-4" />
</Button>
</div>
</header>
<div className="min-h-0 flex-1 overflow-y-auto p-3 sm:p-4">
{isOpen && <UsageDashboard serverId={serverId} />}
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,92 @@
import { describe, expect, it, vi } from 'vitest'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithProviders } from '@/test/render'
import { UsageModelFilter } from './UsageModelFilter'
const models = ['anthropic/claude', 'openai/gpt', 'google/gemini']
function renderFilter(selected: string[] = [], onChange = vi.fn()) {
const user = userEvent.setup()
renderWithProviders(<UsageModelFilter models={models} selected={selected} onChange={onChange} />, {
auth: false,
theme: false,
tts: false,
})
return { user, onChange }
}
async function openMenu(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('button', { name: 'Filter by model' }))
}
describe('UsageModelFilter', () => {
it('shows All models and no overflow badge when nothing is selected', () => {
renderFilter()
const trigger = screen.getByRole('button', { name: 'Filter by model' })
expect(trigger).toHaveTextContent('All models')
expect(screen.queryByText(/\+\d+ more/)).not.toBeInTheDocument()
})
it('shows the first selected model and the remaining count', () => {
renderFilter(['anthropic/claude', 'openai/gpt', 'google/gemini'])
const trigger = screen.getByRole('button', { name: 'Filter by model' })
expect(trigger).toHaveTextContent('anthropic/claude')
expect(trigger).toHaveTextContent('+2 more')
})
it('lists All models and every model key in the menu', async () => {
const { user } = renderFilter()
await openMenu(user)
expect(await screen.findByRole('menuitemcheckbox', { name: /All models/ })).toBeInTheDocument()
expect(await screen.findByRole('menuitemcheckbox', { name: 'anthropic/claude' })).toBeInTheDocument()
expect(screen.getByRole('menuitemcheckbox', { name: 'openai/gpt' })).toBeInTheDocument()
expect(screen.getByRole('menuitemcheckbox', { name: 'google/gemini' })).toBeInTheDocument()
})
it('adds an unselected model to the selection', async () => {
const { user, onChange } = renderFilter(['anthropic/claude'])
await openMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: 'openai/gpt' }))
expect(onChange).toHaveBeenCalledWith(['anthropic/claude', 'openai/gpt'])
})
it('removes an already-selected model from the selection', async () => {
const { user, onChange } = renderFilter(['anthropic/claude', 'openai/gpt'])
await openMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: /openai\/gpt/ }))
expect(onChange).toHaveBeenCalledWith(['anthropic/claude'])
})
it('clears the selection when All models is clicked', async () => {
const { user, onChange } = renderFilter(['anthropic/claude', 'openai/gpt'])
await openMenu(user)
await user.click(await screen.findByRole('menuitemcheckbox', { name: /All models/ }))
expect(onChange).toHaveBeenCalledWith([])
})
it('marks All models checked when the selection is empty', async () => {
const { user } = renderFilter()
await openMenu(user)
expect(await screen.findByRole('menuitemcheckbox', { name: /All models/ })).toHaveAttribute('aria-checked', 'true')
})
it('marks All models unchecked when models are selected', async () => {
const { user } = renderFilter(['anthropic/claude'])
await openMenu(user)
expect(await screen.findByRole('menuitemcheckbox', { name: /All models/ })).toHaveAttribute('aria-checked', 'false')
})
})
@@ -0,0 +1,55 @@
import { ChevronDown } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
interface UsageModelFilterProps {
models: string[]
selected: string[]
onChange: (selected: string[]) => void
}
export function UsageModelFilter({ models, selected, onChange }: UsageModelFilterProps) {
const firstSelected = selected[0]
function toggleModel(model: string) {
const next = selected.includes(model)
? selected.filter((key) => key !== model)
: [...selected, model]
onChange(next)
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label="Filter by model"
className="flex items-center gap-2 rounded-md border border-border bg-background px-3 py-1.5 text-sm transition-colors hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span className="max-w-[12rem] truncate">{firstSelected ?? 'All models'}</span>
{selected.length > 1 && <Badge variant="secondary">+{selected.length - 1} more</Badge>}
<ChevronDown className="h-4 w-4 text-muted-foreground" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuCheckboxItem checked={selected.length === 0} onCheckedChange={() => onChange([])}>
All models
</DropdownMenuCheckboxItem>
{models.map((model) => (
<DropdownMenuCheckboxItem
key={model}
checked={selected.includes(model)}
onCheckedChange={() => toggleModel(model)}
>
{model}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,92 @@
import { describe, expect, it } from 'vitest'
import { screen } from '@testing-library/react'
import type { SessionStatsModelUsage } from '@opencode-manager/shared/opencode'
import { renderWithProviders } from '@/test/render'
import { UsageModelsTable } from './UsageModelsTable'
const providerOptions = { auth: false, theme: false, tts: false } as const
interface ModelUsageOptions {
id: string
cost: number
steps?: number
inputTokens?: number
}
function modelUsage({ id, cost, steps = 1, inputTokens = 0 }: ModelUsageOptions): SessionStatsModelUsage {
return {
model: { id, providerID: 'anthropic' },
steps,
tokens: {
input: inputTokens,
output: 0,
reasoning: 0,
cache: { read: 0, write: 0 },
},
cost,
}
}
describe('UsageModelsTable', () => {
it('renders the model key, steps, tokens, cost and share', () => {
const { unmount } = renderWithProviders(
<UsageModelsTable
models={[modelUsage({ id: 'claude-sonnet-4', cost: 0.25, steps: 3, inputTokens: 1500 })]}
/>,
providerOptions,
)
expect(screen.getByRole('heading', { name: 'Models' })).toBeInTheDocument()
expect(screen.getByText('anthropic/claude-sonnet-4')).toBeInTheDocument()
expect(screen.getByText('3')).toBeInTheDocument()
expect(screen.getByText('2k')).toBeInTheDocument()
expect(screen.getByText('$0.2500')).toBeInTheDocument()
expect(screen.getByText('100.0%')).toBeInTheDocument()
unmount()
renderWithProviders(
<UsageModelsTable
models={[modelUsage({ id: 'costly', cost: 3 }), modelUsage({ id: 'cheap', cost: 1 })]}
/>,
providerOptions,
)
expect(screen.getByText('25.0%')).toBeInTheDocument()
expect(screen.getByText('75.0%')).toBeInTheDocument()
})
it('preserves the input order of rows', () => {
renderWithProviders(
<UsageModelsTable
models={[modelUsage({ id: 'zeta', cost: 2 }), modelUsage({ id: 'alpha', cost: 1 })]}
/>,
providerOptions,
)
const rows = screen.getAllByRole('row').slice(1)
expect(rows).toHaveLength(2)
expect(rows[0]).toHaveTextContent('anthropic/zeta')
expect(rows[1]).toHaveTextContent('anthropic/alpha')
})
it('shows a dash for share when every cost is zero', () => {
renderWithProviders(
<UsageModelsTable
models={[modelUsage({ id: 'alpha', cost: 0 }), modelUsage({ id: 'beta', cost: 0 })]}
/>,
providerOptions,
)
expect(screen.getAllByText('—')).toHaveLength(2)
})
it('shows the empty message and no table when there are no models', () => {
renderWithProviders(<UsageModelsTable models={[]} />, providerOptions)
expect(screen.getByRole('heading', { name: 'Models' })).toBeInTheDocument()
expect(screen.getByText('No model usage in this range.')).toBeInTheDocument()
expect(screen.queryByRole('table')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,46 @@
import type { SessionStatsModelUsage } from '@opencode-manager/shared/opencode'
import { formatCompactTokens } from '@/lib/contextUsage'
import { formatUsd, modelUsageKey, sumModelUsage, totalTokens } from '@/lib/usageStats'
interface UsageModelsTableProps {
models: SessionStatsModelUsage[]
}
export function UsageModelsTable({ models }: UsageModelsTableProps) {
const totalCost = sumModelUsage(models).cost
return (
<div className="space-y-3">
<h2 className="text-sm font-medium">Models</h2>
{models.length === 0 ? (
<p className="text-sm text-muted-foreground">No model usage in this range.</p>
) : (
<table className="w-full text-sm">
<thead className="border-b border-border/60 text-xs uppercase text-muted-foreground">
<tr>
<th scope="col" className="px-3 py-2.5 text-left font-medium">Model</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Steps</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Tokens</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Cost</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Share</th>
</tr>
</thead>
<tbody className="divide-y divide-border/60">
{models.map((model) => {
const share = totalCost === 0 ? '—' : `${((model.cost / totalCost) * 100).toFixed(1)}%`
return (
<tr key={modelUsageKey(model.model)}>
<td className="px-3 py-2.5">{modelUsageKey(model.model)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{String(model.steps)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{formatCompactTokens(totalTokens(model.tokens))}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{formatUsd(model.cost)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{share}</td>
</tr>
)
})}
</tbody>
</table>
)}
</div>
)
}
@@ -0,0 +1,92 @@
import { beforeAll, describe, expect, it, vi } from 'vitest'
import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { UsageRangePicker } from './UsageRangePicker'
import { installPointerCapture } from '@/test/browserFakes'
import { renderWithProviders } from '@/test/render'
import type { UsageRangeSelection } from '@/lib/usageRange'
const CUSTOM_FROM = new Date('2026-01-02T03:04').getTime()
const CUSTOM_TO = new Date('2026-01-03T04:05').getTime()
function renderPicker(value: UsageRangeSelection, onChange: (selection: UsageRangeSelection) => void) {
return {
...renderWithProviders(<UsageRangePicker value={value} onChange={onChange} />, {
auth: false,
theme: false,
tts: false,
}),
onChange,
}
}
describe('UsageRangePicker', () => {
beforeAll(() => {
installPointerCapture()
})
it('renders the label for the current preset', () => {
renderPicker({ preset: '4h' }, vi.fn())
expect(screen.getByRole('combobox', { name: 'Range' })).toHaveTextContent('Last 4 hours')
})
it('calls onChange with only the preset when another preset is selected', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
renderPicker({ preset: '4h' }, onChange)
await user.click(screen.getByRole('combobox', { name: 'Range' }))
await user.click(screen.getByRole('option', { name: 'Last 7 days' }))
expect(onChange).toHaveBeenCalledTimes(1)
expect(onChange).toHaveBeenCalledWith({ preset: '7d' })
})
it('renders the From and To inputs for a custom selection', () => {
renderPicker({ preset: 'custom', from: null, to: null }, vi.fn())
expect(screen.getByText('From')).toBeInTheDocument()
expect(screen.getByText('To')).toBeInTheDocument()
expect(screen.getByLabelText('From')).toHaveAttribute('type', 'datetime-local')
expect(screen.getByLabelText('To')).toHaveAttribute('type', 'datetime-local')
})
it('parses a changed From value into epoch milliseconds and preserves To', () => {
const onChange = vi.fn()
renderPicker({ preset: 'custom', from: null, to: CUSTOM_TO }, onChange)
fireEvent.change(screen.getByLabelText('From'), { target: { value: '2026-01-02T03:04' } })
expect(onChange).toHaveBeenCalledWith({
preset: 'custom',
from: new Date('2026-01-02T03:04').getTime(),
to: CUSTOM_TO,
})
})
it('calls onChange with a null To when the To input is cleared', () => {
const onChange = vi.fn()
renderPicker({ preset: 'custom', from: CUSTOM_FROM, to: CUSTOM_TO }, onChange)
fireEvent.change(screen.getByLabelText('To'), { target: { value: '' } })
expect(onChange).toHaveBeenCalledWith({ preset: 'custom', from: CUSTOM_FROM, to: null })
})
it('renders existing custom values as local datetime input values', () => {
renderPicker({ preset: 'custom', from: CUSTOM_FROM, to: CUSTOM_TO }, vi.fn())
expect(screen.getByLabelText('From')).toHaveValue('2026-01-02T03:04')
expect(screen.getByLabelText('To')).toHaveValue('2026-01-03T04:05')
})
it('does not call onChange when a custom selection re-renders', () => {
const onChange = vi.fn()
const { rerender } = renderPicker({ preset: 'custom', from: CUSTOM_FROM, to: CUSTOM_TO }, onChange)
rerender(<UsageRangePicker value={{ preset: 'custom', from: CUSTOM_FROM, to: CUSTOM_TO }} onChange={onChange} />)
expect(onChange).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,88 @@
import { useId } from 'react'
import { format } from 'date-fns'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { USAGE_RANGE_LABELS, USAGE_RANGE_PRESETS } from '@/lib/usageRange'
import type { UsageRangePreset, UsageRangeSelection } from '@/lib/usageRange'
const LOCAL_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm"
interface UsageRangePickerProps {
value: UsageRangeSelection
onChange: (selection: UsageRangeSelection) => void
}
function formatLocalDateTime(timestamp: number | null): string {
return timestamp === null ? '' : format(timestamp, LOCAL_DATE_TIME_FORMAT)
}
function parseLocalDateTime(text: string): number | null {
if (text === '') return null
const timestamp = new Date(text).getTime()
return Number.isNaN(timestamp) ? null : timestamp
}
function isBoundedPreset(value: string): value is Exclude<UsageRangePreset, 'custom'> {
return USAGE_RANGE_PRESETS.some((preset) => preset !== 'custom' && preset === value)
}
export function UsageRangePicker({ value, onChange }: UsageRangePickerProps) {
const fromId = useId()
const toId = useId()
const from = value.preset === 'custom' ? value.from : null
const to = value.preset === 'custom' ? value.to : null
const handlePresetChange = (next: string) => {
if (next === 'custom') {
if (value.preset !== 'custom') onChange({ preset: 'custom', from: null, to: null })
return
}
if (isBoundedPreset(next)) onChange({ preset: next })
}
return (
<div className="flex flex-wrap items-end gap-2">
<Select value={value.preset} onValueChange={handlePresetChange}>
<SelectTrigger className="w-[180px]" aria-label="Range">
<SelectValue>{USAGE_RANGE_LABELS[value.preset]}</SelectValue>
</SelectTrigger>
<SelectContent>
{USAGE_RANGE_PRESETS.map((preset) => (
<SelectItem key={preset} value={preset}>
{USAGE_RANGE_LABELS[preset]}
</SelectItem>
))}
</SelectContent>
</Select>
{value.preset === 'custom' && (
<>
<div className="flex flex-col gap-1">
<Label htmlFor={fromId}>From</Label>
<Input
id={fromId}
type="datetime-local"
aria-label="From"
value={formatLocalDateTime(from)}
onChange={(event) =>
onChange({ preset: 'custom', from: parseLocalDateTime(event.target.value), to })
}
/>
</div>
<div className="flex flex-col gap-1">
<Label htmlFor={toId}>To</Label>
<Input
id={toId}
type="datetime-local"
aria-label="To"
value={formatLocalDateTime(to)}
onChange={(event) =>
onChange({ preset: 'custom', from, to: parseLocalDateTime(event.target.value) })
}
/>
</div>
</>
)}
</div>
)
}
@@ -0,0 +1,276 @@
import { describe, expect, it } from 'vitest'
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { renderWithProviders, type TestProviderOptions } from '@/test/render'
import type { FetchRoute } from '@/test/fetchFake'
import { makeRepo, makeSession } from '@/test/fixtures/api'
import { UsageSessionsTable } from './UsageSessionsTable'
const localOptions = {
auth: false,
theme: false,
tts: false,
initialEntries: ['/?usage=open'],
} satisfies Omit<TestProviderOptions, 'fetchRoutes'>
const zeroTokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
const spentTokens = { input: 1000, output: 500, reasoning: 0, cache: { read: 0, write: 0 } }
function assistantStep(id: string) {
return {
id,
type: 'assistant' as const,
agent: 'build',
model: { providerID: 'anthropic', id: 'claude' },
time: { created: 1000, streamed: 2000 },
content: [],
cost: 0.1,
tokens: { input: 100, output: 50, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function reposRoute(): FetchRoute {
return {
method: 'GET',
path: '/api/repos',
respond: () => ({ json: [makeRepo({ id: 1, fullPath: '/workspace/demo' })] }),
}
}
function sessionsRoute(sessions: SessionInfo[], serverId = LOCAL_OPENCODE_SERVER_ID): FetchRoute {
const path =
serverId === LOCAL_OPENCODE_SERVER_ID
? '/api/opencode/api/session'
: `/api/opencode/servers/${serverId}/api/session`
return {
method: 'GET',
path,
respond: () => ({ json: { data: sessions, cursor: {} } }),
}
}
function messagesRoute(serverId = LOCAL_OPENCODE_SERVER_ID): FetchRoute {
const path =
serverId === LOCAL_OPENCODE_SERVER_ID
? '/api/opencode/api/session/:sessionID/message'
: `/api/opencode/servers/${serverId}/api/session/:sessionID/message`
return {
method: 'GET',
path,
respond: (_request, params) => ({
json: { data: [assistantStep(`msg_${params.sessionID}`)], cursor: {} },
}),
}
}
function rowTitles(): string[] {
return screen
.getAllByRole('row')
.slice(1)
.map((row) => within(row).getAllByRole('cell')[0]?.textContent ?? '')
}
function cellsFor(title: string): HTMLElement[] {
const row = screen.getByText(title).closest('tr')
if (!row) throw new Error(`No row for ${title}`)
return within(row).getAllByRole('cell')
}
describe('UsageSessionsTable', () => {
it('renders only sessions with spend or tokens, sorted by cost descending', async () => {
const sessions = [
makeSession({
id: 'ses_low',
title: 'Low spend',
cost: 0.1,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
}),
makeSession({
id: 'ses_high',
title: 'High spend',
cost: 0.9,
tokens: spentTokens,
time: { created: 1000, updated: 3000 },
}),
makeSession({
id: 'ses_mid',
title: 'Mid spend',
cost: 0.5,
tokens: zeroTokens,
time: { created: 1000, updated: 4000 },
}),
makeSession({
id: 'ses_free',
title: 'Free session',
cost: 0,
tokens: zeroTokens,
time: { created: 1000, updated: 5000 },
}),
]
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
})
await screen.findByText('High spend')
expect(rowTitles()).toEqual(['High spend', 'Mid spend', 'Low spend'])
expect(screen.queryByText('Free session')).not.toBeInTheDocument()
})
it('renders step counts and average token throughput per session', async () => {
const sessions = [
makeSession({
id: 'ses_demo',
title: 'Demo session',
cost: 0.4,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
}),
]
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
})
await screen.findByText('Demo session')
await waitFor(() => expect(cellsFor('Demo session')[1]).toHaveTextContent('1'))
expect(cellsFor('Demo session')[5]).toHaveTextContent('50.0 tok/s')
})
it('links local sessions to a matching repo and leaves unmatched directories as plain text', async () => {
const sessions = [
makeSession({
id: 'ses_demo',
title: 'Demo session',
cost: 0.4,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
location: { directory: '/workspace/demo' },
}),
makeSession({
id: 'ses_orphan',
title: 'Orphan session',
cost: 0.2,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
location: { directory: '/workspace/elsewhere' },
}),
]
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
})
const link = await screen.findByRole('link', { name: 'Demo session' })
expect(link).toHaveAttribute('href', '/repos/1/sessions/ses_demo')
expect(link.getAttribute('href')).not.toContain('usage')
expect(screen.getByText('Orphan session').closest('a')).toBeNull()
})
it('links sessions on a remote server without requesting repos', async () => {
const serverId = 'srv_kitchen'
const sessions = [
makeSession({
id: 'ses_remote',
title: 'Remote session',
cost: 0.4,
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
}),
]
const result = renderWithProviders(
<UsageSessionsTable serverId={serverId} range={{ from: 0 }} />,
{
...localOptions,
fetchRoutes: [sessionsRoute(sessions, serverId), messagesRoute(serverId)],
},
)
const link = await screen.findByRole('link', { name: 'Remote session' })
expect(link).toHaveAttribute('href', '/servers/srv_kitchen/sessions/ses_remote')
expect(result.fetchFake.findRequests('GET', '/api/repos')).toHaveLength(0)
})
it('shows ten rows initially and reveals the eleventh with Show more', async () => {
const sessions = Array.from({ length: 11 }, (_, index) =>
makeSession({
id: `ses_${index + 1}`,
title: `Session ${index + 1}`,
cost: Number(((11 - index) * 0.01).toFixed(2)),
tokens: spentTokens,
time: { created: 1000, updated: 2000 },
}),
)
const user = userEvent.setup()
renderWithProviders(<UsageSessionsTable serverId={LOCAL_OPENCODE_SERVER_ID} range={{ from: 0 }} />, {
...localOptions,
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
})
await screen.findByText('Session 1')
expect(screen.getAllByRole('row')).toHaveLength(11)
expect(screen.queryByText('Session 11')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Show more' }))
await waitFor(() => expect(screen.getAllByRole('row')).toHaveLength(12))
expect(screen.getByText('Session 11')).toBeInTheDocument()
})
it('excludes sessions outside the range and sessions without spend or tokens', async () => {
const sessions = [
makeSession({
id: 'ses_valid',
title: 'Valid session',
cost: 0.2,
tokens: spentTokens,
time: { created: 1000, updated: 5000 },
}),
makeSession({
id: 'ses_old',
title: 'Out of range',
cost: 0.8,
tokens: spentTokens,
time: { created: 100, updated: 100 },
}),
makeSession({
id: 'ses_empty',
title: 'Empty session',
cost: 0,
tokens: zeroTokens,
time: { created: 1000, updated: 5000 },
}),
]
renderWithProviders(
<UsageSessionsTable
serverId={LOCAL_OPENCODE_SERVER_ID}
range={{ from: 1000, to: 6000 }}
/>,
{
...localOptions,
fetchRoutes: [reposRoute(), sessionsRoute(sessions), messagesRoute()],
},
)
await screen.findByText('Valid session')
expect(rowTitles()).toEqual(['Valid session'])
expect(screen.queryByText('Out of range')).not.toBeInTheDocument()
expect(screen.queryByText('Empty session')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,187 @@
import { useMemo, useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import type { UseQueryResult } from '@tanstack/react-query'
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import type { SessionUsageMessages } from '@/api/usage'
import { findRepoForDirectory } from '@/components/navigation/sidebar-session-tree'
import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useSessionUsageQueries } from '@/hooks/useUsage'
import { formatCompactTokens } from '@/lib/contextUsage'
import { getServerSessionPath, getSessionPath } from '@/lib/navigation'
import { isWithinUsageRange, type ResolvedUsageRange } from '@/lib/usageRange'
import {
formatTokensPerSecond,
formatUsd,
summarizeSessionSteps,
totalTokens,
} from '@/lib/usageStats'
interface UsageSessionsTableProps {
serverId: string
range: ResolvedUsageRange
}
interface SessionMetrics {
steps: string
throughput: string
}
const INITIAL_ROWS = 10
const ROW_INCREMENT = 10
function hasSpendOrTokens(session: SessionInfo): boolean {
return session.cost > 0 || totalTokens(session.tokens) > 0
}
function sessionMetrics(
query: UseQueryResult<SessionUsageMessages> | undefined,
): SessionMetrics {
if (!query || query.isPending) return { steps: '…', throughput: '…' }
if (!query.data) return { steps: '—', throughput: '—' }
const summary = summarizeSessionSteps(query.data.steps, { range: {}, models: [] })
return {
steps: String(summary.steps),
throughput: formatTokensPerSecond(summary.averageTokensPerSecond),
}
}
export function UsageSessionsTable({ serverId, range }: UsageSessionsTableProps) {
const { data: sessions, isLoading } = useSessionsAcrossDirectories([], {
allDirectories: true,
limit: 100,
serverId,
})
const isLocal = serverId === LOCAL_OPENCODE_SERVER_ID
const { repos } = useNavigableRepos(isLocal)
const location = useLocation()
const [showCount, setShowCount] = useState(INITIAL_ROWS)
const search = useMemo(() => {
const params = new URLSearchParams(location.search)
params.delete('usage')
const remaining = params.toString()
return remaining ? `?${remaining}` : ''
}, [location.search])
const sortedSessions = useMemo(
() =>
sessions
.filter(
(session) =>
isWithinUsageRange(session.time.updated, range) && hasSpendOrTokens(session),
)
.sort((a, b) => b.cost - a.cost || totalTokens(b.tokens) - totalTokens(a.tokens)),
[sessions, range],
)
const visibleSessions = sortedSessions.slice(0, showCount)
const usageQueries = useSessionUsageQueries(
visibleSessions.map((session) => session.id),
serverId,
)
function renderTitle(session: SessionInfo) {
const title = session.title ?? session.id
if (isLocal) {
const repo = findRepoForDirectory(repos, session.location.directory)
if (repo) {
return (
<Link
to={{ pathname: getSessionPath(repo.id, session.id), search }}
className="transition-colors hover:text-primary"
>
{title}
</Link>
)
}
return <span>{title}</span>
}
return (
<Link
to={{ pathname: getServerSessionPath(serverId, session.id), search }}
className="transition-colors hover:text-primary"
>
{title}
</Link>
)
}
return (
<div className="space-y-3">
<h2 className="text-sm font-medium">Sessions by spend</h2>
<p className="text-xs text-muted-foreground">
Lifetime totals of sessions active in this range.
</p>
{isLoading && sortedSessions.length === 0 ? (
<p className="text-sm text-muted-foreground">Loading sessions…</p>
) : sortedSessions.length === 0 ? (
<p className="text-sm text-muted-foreground">No sessions in this range.</p>
) : (
<>
<table className="w-full text-sm">
<thead className="border-b border-border/60 text-xs uppercase text-muted-foreground">
<tr>
<th scope="col" className="px-3 py-2.5 text-left font-medium">
Session
</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">
Steps
</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">
Input
</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">
Output
</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">
Cache read
</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">
Avg tokens/s
</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">
Cost
</th>
</tr>
</thead>
<tbody className="divide-y divide-border/60">
{visibleSessions.map((session, index) => {
const metrics = sessionMetrics(usageQueries[index])
return (
<tr key={session.id}>
<td className="px-3 py-2.5">{renderTitle(session)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{metrics.steps}</td>
<td className="px-3 py-2.5 text-right tabular-nums">
{formatCompactTokens(session.tokens.input)}
</td>
<td className="px-3 py-2.5 text-right tabular-nums">
{formatCompactTokens(session.tokens.output)}
</td>
<td className="px-3 py-2.5 text-right tabular-nums">
{formatCompactTokens(session.tokens.cache.read)}
</td>
<td className="px-3 py-2.5 text-right tabular-nums">{metrics.throughput}</td>
<td className="px-3 py-2.5 text-right tabular-nums">
{formatUsd(session.cost)}
</td>
</tr>
)
})}
</tbody>
</table>
{sortedSessions.length > showCount && (
<button
type="button"
onClick={() => setShowCount((count) => count + ROW_INCREMENT)}
className="text-xs font-medium text-primary hover:underline"
>
Show more
</button>
)}
</>
)}
</div>
)
}
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest'
import { screen } from '@testing-library/react'
import { renderWithProviders } from '@/test/render'
import { UsageSummaryCards } from './UsageSummaryCards'
const tokens = {
input: 1500,
output: 0,
reasoning: 0,
cache: { read: 0, write: 0 },
}
const providerOptions = { auth: false, theme: false, tts: false } as const
describe('UsageSummaryCards', () => {
it('renders spend, tokens and steps with formatted values', () => {
renderWithProviders(
<UsageSummaryCards cost={1.5} tokens={tokens} steps={7} />,
providerOptions,
)
expect(screen.getByText('Spend')).toBeInTheDocument()
expect(screen.getByText('$1.50')).toBeInTheDocument()
expect(screen.getByText('Tokens')).toBeInTheDocument()
expect(screen.getByText('2k')).toBeInTheDocument()
expect(screen.getByText('Steps')).toBeInTheDocument()
expect(screen.getByText('7')).toBeInTheDocument()
})
it('renders prompts, active days and streak when provided', () => {
renderWithProviders(
<UsageSummaryCards
cost={0.25}
tokens={tokens}
steps={7}
prompts={4}
activeDays={3}
streak={2}
/>,
providerOptions,
)
expect(screen.getByText('Prompts')).toBeInTheDocument()
expect(screen.getByText('4')).toBeInTheDocument()
expect(screen.getByText('Active days')).toBeInTheDocument()
expect(screen.getByText('3')).toBeInTheDocument()
expect(screen.getByText('Streak')).toBeInTheDocument()
expect(screen.getByText('2')).toBeInTheDocument()
})
it('omits prompts, active days and streak when undefined', () => {
renderWithProviders(
<UsageSummaryCards cost={1.5} tokens={tokens} steps={7} />,
providerOptions,
)
expect(screen.queryByText('Prompts')).not.toBeInTheDocument()
expect(screen.queryByText('Active days')).not.toBeInTheDocument()
expect(screen.queryByText('Streak')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,52 @@
import type { TokenUsageInfo } from '@opencode-manager/shared/opencode'
import { Card, CardContent } from '@/components/ui/card'
import { formatCompactTokens } from '@/lib/contextUsage'
import { formatUsd, totalTokens } from '@/lib/usageStats'
interface UsageSummaryCardsProps {
cost: number
tokens: TokenUsageInfo
steps: number
prompts?: number
activeDays?: number
streak?: number
}
interface UsageStat {
label: string
value: string
}
export function UsageSummaryCards({
cost,
tokens,
steps,
prompts,
activeDays,
streak,
}: UsageSummaryCardsProps) {
const stats: UsageStat[] = [
{ label: 'Spend', value: formatUsd(cost) },
{ label: 'Tokens', value: formatCompactTokens(totalTokens(tokens)) },
{ label: 'Steps', value: String(steps) },
]
if (prompts !== undefined) stats.push({ label: 'Prompts', value: String(prompts) })
if (activeDays !== undefined) stats.push({ label: 'Active days', value: String(activeDays) })
if (streak !== undefined) stats.push({ label: 'Streak', value: String(streak) })
return (
<Card>
<CardContent className="p-4">
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
{stats.map((stat) => (
<div key={stat.label}>
<p className="text-xs uppercase tracking-wider text-muted-foreground">{stat.label}</p>
<p className="mt-1 text-lg font-semibold">{stat.value}</p>
</div>
))}
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,38 @@
import { describe, it, expect } from 'vitest'
import { screen } from '@testing-library/react'
import { renderWithProviders } from '@/test/render'
import { UsageTokenComposition } from './UsageTokenComposition'
const providerOptions = { auth: false, theme: false, tts: false } as const
describe('UsageTokenComposition', () => {
it('renders every label and formatted value, including zeros', () => {
renderWithProviders(
<UsageTokenComposition
tokens={{
input: 1500,
output: 3400,
reasoning: 0,
cache: { read: 2400000, write: 0 },
}}
/>,
providerOptions,
)
expect(screen.getByText('Token composition')).toBeInTheDocument()
const rows: Array<[string, string]> = [
['Input', '2k'],
['Output', '3k'],
['Reasoning', '0'],
['Cache read', '2.4M'],
['Cache write', '0'],
]
for (const [label, value] of rows) {
const term = screen.getByText(label)
expect(term.nextElementSibling).toHaveTextContent(value)
expect(term.nextElementSibling?.tagName).toBe('DD')
}
})
})
@@ -0,0 +1,33 @@
import type { TokenUsageInfo } from '@opencode-manager/shared/opencode'
import { Card, CardContent } from '@/components/ui/card'
import { formatCompactTokens } from '@/lib/contextUsage'
interface UsageTokenCompositionProps {
tokens: TokenUsageInfo
}
export function UsageTokenComposition({ tokens }: UsageTokenCompositionProps) {
const rows = [
{ label: 'Input', value: tokens.input },
{ label: 'Output', value: tokens.output },
{ label: 'Reasoning', value: tokens.reasoning },
{ label: 'Cache read', value: tokens.cache.read },
{ label: 'Cache write', value: tokens.cache.write },
]
return (
<Card>
<CardContent className="space-y-3 p-4">
<h2 className="text-sm font-medium">Token composition</h2>
<dl className="space-y-1 text-sm">
{rows.map((row) => (
<div key={row.label} className="flex items-center justify-between gap-2">
<dt className="text-muted-foreground">{row.label}</dt>
<dd className="font-medium">{formatCompactTokens(row.value)}</dd>
</div>
))}
</dl>
</CardContent>
</Card>
)
}
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'
import { screen, within } from '@testing-library/react'
import { renderWithProviders } from '@/test/render'
import { UsageToolsTable } from './UsageToolsTable'
const providerOptions = { auth: false, theme: false, tts: false } as const
const totals = {
calls: 4,
succeeded: 3,
failed: 1,
unfinished: 0,
}
function cellTexts(row: HTMLElement): Array<string | null> {
return within(row).getAllByRole('cell').map((cell) => cell.textContent)
}
describe('UsageToolsTable', () => {
it('renders a tool row with counts and P50 duration', () => {
renderWithProviders(
<UsageToolsTable
totals={totals}
usage={[{ name: 'bash', calls: 3, succeeded: 2, failed: 1, unfinished: 0, durationP50: 120 }]}
/>,
providerOptions,
)
const rows = screen.getAllByRole('row')
expect(screen.getByRole('heading', { name: 'Tools' })).toBeInTheDocument()
expect(cellTexts(rows[1])).toEqual(['bash', '3', '2', '1', '0', '120 ms'])
})
it('shows a dash for a missing P50 duration', () => {
renderWithProviders(
<UsageToolsTable
totals={totals}
usage={[{ name: 'read', calls: 1, succeeded: 1, failed: 0, unfinished: 0 }]}
/>,
providerOptions,
)
const rows = screen.getAllByRole('row')
expect(cellTexts(rows[1])).toEqual(['read', '1', '1', '0', '0', '—'])
})
it('renders the total footer from totals', () => {
renderWithProviders(
<UsageToolsTable
totals={totals}
usage={[{ name: 'bash', calls: 4, succeeded: 3, failed: 1, unfinished: 0 }]}
/>,
providerOptions,
)
const rows = screen.getAllByRole('row')
const footer = rows[rows.length - 1]
expect(footer.parentElement?.tagName).toBe('TFOOT')
expect(cellTexts(footer)).toEqual(['Total', '4', '3', '1', '0', '—'])
})
it('shows the empty message and no table when there is no usage', () => {
renderWithProviders(<UsageToolsTable totals={totals} usage={[]} />, providerOptions)
expect(screen.getByRole('heading', { name: 'Tools' })).toBeInTheDocument()
expect(screen.getByText('No tool calls in this range.')).toBeInTheDocument()
expect(screen.queryByRole('table')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,56 @@
import type { SessionStatsTools, SessionStatsToolUsage } from '@opencode-manager/shared/opencode'
type ToolTotals = Extract<SessionStatsTools, { mode: 'detail' }>['totals']
interface UsageToolsTableProps {
totals: ToolTotals
usage: SessionStatsToolUsage[]
}
export function UsageToolsTable({ totals, usage }: UsageToolsTableProps) {
return (
<div className="space-y-3">
<h2 className="text-sm font-medium">Tools</h2>
{usage.length === 0 ? (
<p className="text-sm text-muted-foreground">No tool calls in this range.</p>
) : (
<table className="w-full text-sm">
<thead className="border-b border-border/60 text-xs uppercase text-muted-foreground">
<tr>
<th scope="col" className="px-3 py-2.5 text-left font-medium">Tool</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Calls</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Succeeded</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Failed</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">Unfinished</th>
<th scope="col" className="px-3 py-2.5 text-right font-medium">P50</th>
</tr>
</thead>
<tbody className="divide-y divide-border/60">
{usage.map((entry) => (
<tr key={entry.name}>
<td className="px-3 py-2.5">{entry.name}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{String(entry.calls)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{String(entry.succeeded)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{String(entry.failed)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">{String(entry.unfinished)}</td>
<td className="px-3 py-2.5 text-right tabular-nums">
{entry.durationP50 !== undefined ? `${Math.round(entry.durationP50)} ms` : '—'}
</td>
</tr>
))}
</tbody>
<tfoot className="border-t border-border/60">
<tr>
<td className="px-3 py-2.5 font-medium">Total</td>
<td className="px-3 py-2.5 text-right font-medium tabular-nums">{String(totals.calls)}</td>
<td className="px-3 py-2.5 text-right font-medium tabular-nums">{String(totals.succeeded)}</td>
<td className="px-3 py-2.5 text-right font-medium tabular-nums">{String(totals.failed)}</td>
<td className="px-3 py-2.5 text-right font-medium tabular-nums">{String(totals.unfinished)}</td>
<td className="px-3 py-2.5 text-right font-medium tabular-nums">—</td>
</tr>
</tfoot>
</table>
)}
</div>
)
}
+118
View File
@@ -0,0 +1,118 @@
import { act, render, screen } from '@testing-library/react'
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
import { describe, it, expect } from 'vitest'
import { useUsageDialog } from './useUsageDialog'
import { renderHookWithRouter, renderHookWithRouterAndLocation } from '@/test/test-utils'
describe('useUsageDialog', () => {
it('is closed when no params are present', () => {
const { result } = renderHookWithRouter(() => useUsageDialog())
expect(result.current.isOpen).toBe(false)
})
it('is open when the URL has usage=open', () => {
const { result } = renderHookWithRouter(() => useUsageDialog(), ['/?usage=open'])
expect(result.current.isOpen).toBe(true)
})
it('open sets usage=open and drops mobileTab while keeping other params', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(
() => useUsageDialog(),
['/?mobileTab=more&keep=1'],
)
expect(result.current.isOpen).toBe(false)
act(() => { result.current.open() })
const params = new URLSearchParams(capturedSearch.current)
expect(params.get('usage')).toBe('open')
expect(params.has('mobileTab')).toBe(false)
expect(params.get('keep')).toBe('1')
expect(result.current.isOpen).toBe(true)
})
it('open with replace history also sets usage=open and drops mobileTab', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(
() => useUsageDialog(),
['/?mobileTab=more&keep=1'],
)
act(() => { result.current.open('replace') })
const params = new URLSearchParams(capturedSearch.current)
expect(params.get('usage')).toBe('open')
expect(params.has('mobileTab')).toBe(false)
expect(params.get('keep')).toBe('1')
expect(result.current.isOpen).toBe(true)
})
it('close removes usage and keeps other params for a direct entry', () => {
const { result, capturedSearch } = renderHookWithRouterAndLocation(
() => useUsageDialog(),
['/?usage=open&keep=1'],
)
expect(result.current.isOpen).toBe(true)
act(() => { result.current.close() })
const params = new URLSearchParams(capturedSearch.current)
expect(params.has('usage')).toBe(false)
expect(params.get('keep')).toBe('1')
expect(result.current.isOpen).toBe(false)
})
it('open then close returns to the original search', () => {
const { result, capturedSearch, rerender } = renderHookWithRouterAndLocation(
() => useUsageDialog(),
['/?keep=1'],
)
expect(result.current.isOpen).toBe(false)
act(() => { result.current.open() })
rerender()
expect(result.current.isOpen).toBe(true)
act(() => { result.current.close() })
rerender()
expect(result.current.isOpen).toBe(false)
expect(new URLSearchParams(capturedSearch.current).toString()).toBe('keep=1')
})
describe('history entries', () => {
function UsageHarness() {
const { isOpen, open } = useUsageDialog()
const location = useLocation()
const navigate = useNavigate()
return (
<div>
<span data-testid="dialog-state">{isOpen ? 'open' : 'closed'}</span>
<span data-testid="pathname">{location.pathname}</span>
<span data-testid="search">{location.search}</span>
<button onClick={() => { open() }}>open</button>
<button onClick={() => navigate(-1)}>back</button>
</div>
)
}
it('browser back after open closes the dialog and restores the URL', () => {
render(
<MemoryRouter initialEntries={['/?keep=1']}>
<UsageHarness />
</MemoryRouter>,
)
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
act(() => { screen.getByText('open').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('open')
expect(new URLSearchParams(screen.getByTestId('search').textContent ?? '').get('usage')).toBe('open')
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
expect(screen.getByTestId('pathname').textContent).toBe('/')
expect(screen.getByTestId('search').textContent).toBe('?keep=1')
})
})
})
+27
View File
@@ -0,0 +1,27 @@
import { useCallback } from 'react'
import { useUrlParams } from './useUrlParams'
interface UseUsageDialogReturn {
isOpen: boolean
open: (history?: 'push' | 'replace') => void
close: () => void
}
export function useUsageDialog(): UseUsageDialogReturn {
const { searchParams, updateParams, closePushedParams } = useUrlParams()
const isOpen = searchParams.get('usage') === 'open'
const open = useCallback((history: 'push' | 'replace' = 'push') => {
updateParams((p) => {
p.set('usage', 'open')
p.delete('mobileTab')
}, history)
}, [updateParams])
const close = useCallback(() => {
closePushedParams((p) => p.delete('usage'))
}, [closePushedParams])
return { isOpen, open, close }
}