feat(app): Sessions and Compare screens

Sessions: provider-grouped list of every session in range (project,
models, turns, cost, tokens) with a lightweight real detail — no
fabricated titles, no unbacked context-window widget.

Compare: two-model picker (defaults to top two by cost) across
Performance, Efficiency, Category head-to-head, Working style, and a
derived Context panel, all mapped straight from `compare --format json`.

Nav reordered to match the design: Overview, Sessions, Spend, Optimize,
Models, Compare, Plans, Settings (⌘1-7).
This commit is contained in:
iamtoruk 2026-07-11 12:37:04 -07:00
parent 6023067bdc
commit e331c7da63
10 changed files with 722 additions and 24 deletions

View file

@ -9,6 +9,9 @@ const mocks = vi.hoisted(() => ({
getOverview: vi.fn<(period: string, provider: string, range?: DateRange) => Promise<MenubarPayload>>(),
getSpendFlow: vi.fn<(period: string, provider: string, range?: DateRange) => Promise<SpendFlow>>(),
getModels: vi.fn(),
getSessions: vi.fn(),
getCompareModels: vi.fn(),
getCompare: vi.fn(),
getPlans: vi.fn(),
getActReport: vi.fn(),
getYield: vi.fn(),
@ -82,6 +85,8 @@ describe('App shortcuts', () => {
mocks.getOverview.mockResolvedValue(overviewPayload())
mocks.getSpendFlow.mockResolvedValue({ period: { label: 'Last 30 days', start: '', end: '' }, models: [], projects: [], links: [] })
mocks.getModels.mockResolvedValue([])
mocks.getSessions.mockResolvedValue([])
mocks.getCompareModels.mockResolvedValue([])
mocks.getPlans.mockResolvedValue({})
mocks.getActReport.mockResolvedValue({ totals: { realizedCostUSD: 0, measuredActions: 0 } })
mocks.getYield.mockResolvedValue({
@ -120,30 +125,35 @@ describe('App shortcuts', () => {
expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument()
fireEvent.keyDown(document, { key: '2', metaKey: true })
expect(await screen.findByText('Cost flow · model → project')).toBeInTheDocument()
expect(await screen.findByText('No sessions in this range yet.')).toBeInTheDocument()
})
it('keeps command navigation, settings, and refresh shortcuts active without stale hints', async () => {
render(<App />)
expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument()
expect(screen.getByText('⌘1-5')).toBeInTheDocument()
expect(screen.getByText('⌘1-7')).toBeInTheDocument()
expect(screen.getAllByText('⌘,').length).toBeGreaterThan(0)
expect(screen.getByText('⌘R')).toBeInTheDocument()
expect(screen.queryByText('Command')).not.toBeInTheDocument()
expect(screen.queryByText('Export view')).not.toBeInTheDocument()
fireEvent.keyDown(document, { key: '2', metaKey: true })
expect(await screen.findByText('Cost flow · model → project')).toBeInTheDocument()
expect(await screen.findByText('No sessions in this range yet.')).toBeInTheDocument()
fireEvent.keyDown(document, { key: '3', metaKey: true })
expect(await screen.findByText('No waste findings in this range yet.')).toBeInTheDocument()
expect(await screen.findByText('Cost flow · model → project')).toBeInTheDocument()
fireEvent.keyDown(document, { key: '4', metaKey: true })
expect(await screen.findByText('No model usage in this range yet.')).toBeInTheDocument()
expect(await screen.findByText('No waste findings in this range yet.')).toBeInTheDocument()
fireEvent.keyDown(document, { key: '5', metaKey: true })
expect(await screen.findByText('No model usage in this range yet.')).toBeInTheDocument()
fireEvent.keyDown(document, { key: '6', metaKey: true })
expect(await screen.findByText('Need at least two models with usage in this range to compare.')).toBeInTheDocument()
fireEvent.keyDown(document, { key: '7', metaKey: true })
expect(await screen.findByText('No plans configured')).toBeInTheDocument()
fireEvent.keyDown(document, { key: ',', metaKey: true })
@ -158,7 +168,7 @@ describe('App shortcuts', () => {
it('re-polls visible section data when period or provider changes', async () => {
render(<App />)
fireEvent.keyDown(document, { key: '2', metaKey: true })
fireEvent.keyDown(document, { key: '3', metaKey: true })
expect(await screen.findByText('Cost flow · model → project')).toBeInTheDocument()
fireEvent.click(screen.getByText('Today'))
@ -180,7 +190,7 @@ describe('App shortcuts', () => {
it('applies a calendar range to overview and visible section polls', async () => {
render(<App />)
fireEvent.keyDown(document, { key: '2', metaKey: true })
fireEvent.keyDown(document, { key: '3', metaKey: true })
expect(await screen.findByText('Cost flow · model → project')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Choose date range' }))

View file

@ -11,6 +11,8 @@ import { codeburn } from './lib/ipc'
import { OverviewContent } from './sections/Overview'
import { OptimizeContent } from './sections/Optimize'
import { Models } from './sections/Models'
import { Sessions } from './sections/Sessions'
import { Compare } from './sections/Compare'
import { Plans } from './sections/Plans'
import { Settings } from './sections/Settings'
import { SpendContent } from './sections/Spend'
@ -18,9 +20,11 @@ import type { DateRange, MenubarPayload, Period } from './lib/types'
const SECTION_TITLES: Record<Section, string> = {
overview: 'Overview',
sessions: 'Sessions',
spend: 'Spend',
optimize: 'Optimize',
models: 'Models',
compare: 'Compare',
plans: 'Plans',
settings: 'Settings',
}
@ -100,10 +104,12 @@ export function App() {
if (!event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) return
const key = event.key.toLowerCase()
if (key === '1') setSection('overview')
else if (key === '2') setSection('spend')
else if (key === '3') setSection('optimize')
else if (key === '4') setSection('models')
else if (key === '5') setSection('plans')
else if (key === '2') setSection('sessions')
else if (key === '3') setSection('spend')
else if (key === '4') setSection('optimize')
else if (key === '5') setSection('models')
else if (key === '6') setSection('compare')
else if (key === '7') setSection('plans')
else if (key === ',') setSection('settings')
else if (key === 'r') refreshVisible()
else return
@ -153,12 +159,16 @@ export function App() {
<div className="body">
{section === 'overview' ? (
<OverviewContent period={period} overview={overview} onNavigate={setSection} />
) : section === 'sessions' ? (
<Sessions period={period} provider={provider} range={customRange} refreshToken={refreshToken} />
) : section === 'spend' ? (
<SpendContent period={period} provider={provider} range={customRange} overview={overview} refreshToken={refreshToken} />
) : section === 'optimize' ? (
<OptimizeContent period={period} range={customRange} overview={overview} refreshToken={refreshToken} />
) : section === 'models' ? (
<Models period={period} provider={provider} range={customRange} refreshToken={refreshToken} />
) : section === 'compare' ? (
<Compare period={period} provider={provider} refreshToken={refreshToken} />
) : (
<SectionPlaceholder title={SECTION_TITLES[section]} />
)}
@ -168,7 +178,7 @@ export function App() {
{section !== 'settings' && (
<Hint
items={[
{ k: '⌘1-5', label: 'Navigate' },
{ k: '⌘1-7', label: 'Navigate' },
{ k: '⌘,', label: 'Settings' },
{ k: '⌘R', label: 'Refresh' },
]}

View file

@ -5,12 +5,13 @@ import { render, screen, fireEvent } from '@testing-library/react'
import { Sidebar } from './Sidebar'
describe('Sidebar', () => {
it('renders all six nav items', () => {
it('renders all eight nav items in the desktop order', () => {
render(<Sidebar active="overview" onNavigate={() => {}} />)
expect(screen.getAllByRole('button')).toHaveLength(6)
for (const label of ['Overview', 'Spend', 'Optimize', 'Models', 'Plans', 'Settings']) {
expect(screen.getByRole('button', { name: new RegExp(label) })).toBeInTheDocument()
}
const labels = screen.getAllByRole('button').map(item => item.textContent?.replace(/⌘[\d,]/, ''))
expect(labels).toEqual(['Overview', 'Sessions', 'Spend', 'Optimize', 'Models', 'Compare', 'Plans', 'Settings'])
expect(screen.getByRole('button', { name: /Sessions.*⌘2/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Compare.*⌘6/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Plans.*⌘7/ })).toBeInTheDocument()
})
it('calls onNavigate with the section id when a nav item is clicked', () => {

View file

@ -2,22 +2,28 @@ import type { ReactNode } from 'react'
import flameLogo from '../assets/flame.png'
export type Section = 'overview' | 'spend' | 'optimize' | 'models' | 'plans' | 'settings'
export type Section = 'overview' | 'sessions' | 'spend' | 'optimize' | 'models' | 'compare' | 'plans' | 'settings'
export const NAV_ITEMS: Array<{ id: Section; label: string; key: string; icon: ReactNode }> = [
{ id: 'overview', label: 'Overview', key: '⌘1', icon: (
<svg viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="9" rx="1" /><rect x="14" y="3" width="7" height="5" rx="1" /><rect x="14" y="12" width="7" height="9" rx="1" /><rect x="3" y="16" width="7" height="5" rx="1" /></svg>
) },
{ id: 'spend', label: 'Spend', key: '⌘2', icon: (
{ id: 'sessions', label: 'Sessions', key: '⌘2', icon: (
<svg viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="4" rx="1"/><rect x="4" y="10" width="16" height="4" rx="1"/><rect x="4" y="16" width="16" height="4" rx="1"/></svg>
) },
{ id: 'spend', label: 'Spend', key: '⌘3', icon: (
<svg viewBox="0 0 24 24"><line x1="6" y1="20" x2="6" y2="13" /><line x1="12" y1="20" x2="12" y2="4" /><line x1="18" y1="20" x2="18" y2="9" /></svg>
) },
{ id: 'optimize', label: 'Optimize', key: '⌘3', icon: (
{ id: 'optimize', label: 'Optimize', key: '⌘4', icon: (
<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>
) },
{ id: 'models', label: 'Models', key: '⌘4', icon: (
{ id: 'models', label: 'Models', key: '⌘5', icon: (
<svg viewBox="0 0 24 24"><path d="M21 16V8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /><path d="M3.3 7 12 12l8.7-5M12 22V12" /></svg>
) },
{ id: 'plans', label: 'Plans', key: '⌘5', icon: (
{ id: 'compare', label: 'Compare', key: '⌘6', icon: (
<svg viewBox="0 0 24 24"><path d="M8 3 4 7l4 4"/><path d="M4 7h16"/><path d="M16 21l4-4-4-4"/><path d="M20 17H4"/></svg>
) },
{ id: 'plans', label: 'Plans', key: '⌘7', icon: (
<svg viewBox="0 0 24 24"><rect x="2" y="5" width="20" height="14" rx="2" /><line x1="2" y1="10" x2="22" y2="10" /></svg>
) },
{ id: 'settings', label: 'Settings', key: '⌘,', icon: (

View file

@ -0,0 +1,85 @@
// @vitest-environment jsdom
import { render, screen, waitFor, within } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { CompareJsonReport, ModelStats } from '../lib/types'
import { Compare } from './Compare'
const mocks = vi.hoisted(() => ({
getCompareModels: vi.fn<(period: string, provider: string) => Promise<ModelStats[]>>(),
getCompare: vi.fn<(period: string, provider: string, modelA: string, modelB: string) => Promise<CompareJsonReport>>(),
}))
vi.mock('../lib/ipc', async orig => {
const actual = await orig<typeof import('../lib/ipc')>()
return { ...actual, codeburn: mocks }
})
const modelA: ModelStats = {
model: 'Opus 4.8', calls: 4812, cost: 331.2, outputTokens: 9_640_000, inputTokens: 152_600_000,
cacheReadTokens: 119_400_000, cacheWriteTokens: 16_000_000, totalTurns: 1000, editTurns: 786,
oneShotTurns: 558, retries: 267, selfCorrections: 33, editCost: 0.42,
firstSeen: '2026-06-12T00:00:00.000Z', lastSeen: '2026-07-11T00:00:00.000Z',
}
const modelB: ModelStats = {
model: 'Sonnet 5', calls: 3318, cost: 108.63, outputTokens: 6_080_000, inputTokens: 77_700_000,
cacheReadTokens: 63_300_000, cacheWriteTokens: 7_000_000, totalTurns: 850, editTurns: 641,
oneShotTurns: 404, retries: 300, selfCorrections: 40, editCost: 0.19,
firstSeen: '2026-06-14T00:00:00.000Z', lastSeen: '2026-07-11T00:00:00.000Z',
}
const report: CompareJsonReport = {
period: { label: 'Last 30 days', provider: 'all' },
modelA,
modelB,
metrics: [
{ section: 'Performance', label: 'One-shot rate', valueA: 71, valueB: 63, formatFn: 'percent', winner: 'a' },
{ section: 'Efficiency', label: 'Cost / call', valueA: 0.069, valueB: 0.033, formatFn: 'cost', winner: 'b' },
],
categories: [
{ category: 'Coding', turnsA: 400, editTurnsA: 312, oneShotRateA: 74, turnsB: 350, editTurnsB: 280, oneShotRateB: 66, winner: 'a' },
],
workingStyle: [
{ label: 'Planning rate', valueA: 22, valueB: 9, formatFn: 'percent' },
],
}
describe('Compare', () => {
beforeEach(() => {
mocks.getCompareModels.mockReset()
mocks.getCompare.mockReset()
})
it('defaults to the top two and renders formatted report panels and winners', async () => {
mocks.getCompareModels.mockResolvedValue([modelA, modelB])
mocks.getCompare.mockResolvedValue(report)
render(<Compare period="30days" provider="all" />)
const first = await screen.findByLabelText('First model')
const second = screen.getByLabelText('Second model')
await waitFor(() => {
expect(first).toHaveValue('Opus 4.8')
expect(second).toHaveValue('Sonnet 5')
})
expect(await screen.findByText('Performance')).toBeInTheDocument()
expect(mocks.getCompare).toHaveBeenCalledWith('30days', 'all', 'Opus 4.8', 'Sonnet 5')
expect(screen.getByText('Efficiency')).toBeInTheDocument()
expect(screen.getByText('Context')).toBeInTheDocument()
expect(screen.getByText('71%')).toHaveClass('cmp-best')
expect(screen.getByText('$0.03')).toHaveClass('cmp-best')
expect(screen.getByText('$331.20')).toBeInTheDocument()
expect(screen.getByText('152.6M')).toBeInTheDocument()
expect(screen.getByText('9.64M')).toBeInTheDocument()
const context = screen.getByText('Context').closest<HTMLElement>('.cmp-card')!
expect(within(context).getByText('Cache hit rate')).toBeInTheDocument()
expect(within(context).getByText('Days of data')).toBeInTheDocument()
})
it('renders the need-two-models note without requesting a report', async () => {
mocks.getCompareModels.mockResolvedValue([modelA])
render(<Compare period="week" provider="all" />)
expect(await screen.findByText('Need at least two models with usage in this range to compare.')).toBeInTheDocument()
expect(mocks.getCompare).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,277 @@
import { useCallback, useEffect, useState } from 'react'
import { CliErrorPanel } from '../components/CliErrorPanel'
import { Panel } from '../components/Panel'
import { usePolled } from '../hooks/usePolled'
import { formatUsd } from '../lib/format'
import { codeburn } from '../lib/ipc'
import type { CompareJsonReport, ComparisonRow, ModelStats, Period, WorkingStyleRow } from '../lib/types'
function fmtCompact(n: number): string {
if (n === 0) return '0'
if (n < 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
return new Intl.NumberFormat('en-US', {
notation: 'compact',
maximumFractionDigits: n >= 10_000_000 ? 1 : 2,
}).format(n)
}
function fmtMetric(v: number | null, fn: 'cost' | 'number' | 'percent' | 'decimal'): string {
if (v === null) return '—'
if (fn === 'cost') return formatUsd(v)
if (fn === 'percent') return `${v.toFixed(0)}%`
if (fn === 'decimal') return v.toFixed(2)
return Math.round(v).toLocaleString('en-US')
}
function EmptyNote({ children }: { children: React.ReactNode }) {
return <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>{children}</p>
}
export function Compare({
period,
provider,
refreshToken = 0,
}: {
period: Period
provider: string
refreshToken?: number
}) {
const models = usePolled<ModelStats[]>(
() => codeburn.getCompareModels(period, provider),
[period, provider, refreshToken],
)
const [modelA, setModelA] = useState<string | null>(null)
const [modelB, setModelB] = useState<string | null>(null)
useEffect(() => {
if (!models.data) return
const available = new Set(models.data.map(model => model.model))
setModelA(current => current && available.has(current) ? current : models.data?.[0]?.model ?? null)
setModelB(current => current && available.has(current) ? current : models.data?.[1]?.model ?? null)
}, [models.data])
const resetToDefaults = useCallback(() => {
if (!models.data) return
setModelA(models.data[0]?.model ?? null)
setModelB(models.data[1]?.model ?? null)
}, [models.data])
if (!models.data) {
if (models.error) return <CliErrorPanel error={models.error} subject="model comparisons" />
return (
<Panel title="Compare">
<EmptyNote>Scanning model usage…</EmptyNote>
</Panel>
)
}
if (models.data.length < 2) {
return (
<Panel title="Compare">
<EmptyNote>Need at least two models with usage in this range to compare.</EmptyNote>
</Panel>
)
}
const modelRows = models.data
const nudgeDistinct = (chosen: string) => modelRows.find(model => model.model !== chosen)?.model ?? null
return (
<>
<div className="cmp-picker" aria-label="Models being compared">
<select
className="cmp-select"
aria-label="First model"
value={modelA ?? ''}
onChange={event => {
const next = event.target.value
setModelA(next)
if (next === modelB) setModelB(nudgeDistinct(next))
}}
>
{modelRows.map(model => <option key={model.model} value={model.model}>{model.model} — {model.calls.toLocaleString()} calls</option>)}
</select>
<span className="cmp-vs">vs</span>
<select
className="cmp-select"
aria-label="Second model"
value={modelB ?? ''}
onChange={event => {
const next = event.target.value
setModelB(next)
if (next === modelA) setModelA(nudgeDistinct(next))
}}
>
{modelRows.map(model => <option key={model.model} value={model.model}>{model.model} — {model.calls.toLocaleString()} calls</option>)}
</select>
</div>
{modelA && modelB && modelA !== modelB && (
<CompareReport
period={period}
provider={provider}
modelA={modelA}
modelB={modelB}
refreshToken={refreshToken}
onError={resetToDefaults}
/>
)}
</>
)
}
function CompareReport({
period,
provider,
modelA,
modelB,
refreshToken,
onError,
}: {
period: Period
provider: string
modelA: string
modelB: string
refreshToken: number
onError: () => void
}) {
const report = usePolled<CompareJsonReport>(
() => codeburn.getCompare(period, provider, modelA, modelB),
[period, provider, modelA, modelB, refreshToken],
)
useEffect(() => {
if (report.error) onError()
}, [report.error, onError])
if (!report.data) {
if (report.error) return <CliErrorPanel error={report.error} subject="model comparisons" />
return (
<Panel title="Compare">
<EmptyNote>Comparing models…</EmptyNote>
</Panel>
)
}
const performance = report.data.metrics.filter(metric => metric.section === 'Performance')
const efficiency = report.data.metrics.filter(metric => metric.section === 'Efficiency')
return (
<div className="cmp-body">
<div className="cmp-pair">
<MetricCard title="Performance" rows={performance} modelA={report.data.modelA.model} modelB={report.data.modelB.model} showWinners />
<MetricCard title="Efficiency" rows={efficiency} modelA={report.data.modelA.model} modelB={report.data.modelB.model} showWinners />
</div>
<CategoryCard report={report.data} />
<div className="cmp-pair">
<MetricCard title="Working style" rows={report.data.workingStyle} modelA={report.data.modelA.model} modelB={report.data.modelB.model} />
<ContextCard modelA={report.data.modelA} modelB={report.data.modelB} />
</div>
</div>
)
}
function MetricCard({
title,
rows,
modelA,
modelB,
showWinners = false,
}: {
title: string
rows: Array<ComparisonRow | WorkingStyleRow>
modelA: string
modelB: string
showWinners?: boolean
}) {
return (
<div className="panel cmp-card">
<div className="cmp-head"><h3>{title}</h3></div>
<div className="cmp-metrics">
<MetricHeader modelA={modelA} modelB={modelB} />
{rows.map(row => {
const winner = 'winner' in row ? row.winner : 'none'
return (
<div className="cmp-metric" key={row.label}>
<span className="cmp-label">{row.label}</span>
<span className={`cmp-value${showWinners && winner === 'a' ? ' cmp-best' : ''}`}>{fmtMetric(row.valueA, row.formatFn)}</span>
<span className={`cmp-value${showWinners && winner === 'b' ? ' cmp-best' : ''}`}>{fmtMetric(row.valueB, row.formatFn)}</span>
</div>
)
})}
</div>
{showWinners && <div className="cmp-foot">Green = better on that metric.</div>}
</div>
)
}
function MetricHeader({ modelA, modelB }: { modelA: string; modelB: string }) {
return <div className="cmp-metric-head"><span>Metric</span><span>{modelA}</span><span>{modelB}</span></div>
}
function CategoryCard({ report }: { report: CompareJsonReport }) {
return (
<div className="panel cmp-card">
<div className="cmp-head"><h3>Category head-to-head</h3><span className="cmp-head-note">One-shot rate · edit turns</span></div>
<div className="cmp-category-body">
<div className="cmp-legend">
<span className="cmp-legend-item"><span className="cmp-key" />{report.modelA.model}</span>
<span className="cmp-legend-item"><span className="cmp-key cmp-key-b" />{report.modelB.model}</span>
</div>
<div className="cmp-categories">
{report.categories.map(category => (
<div className="cmp-category" key={category.category}>
<span className="cmp-category-name">{category.category}</span>
<div className="cmp-bars">
<div className="cmp-bar-row">
<span className="cmp-track"><span className="cmp-bar" style={{ width: `${category.oneShotRateA ?? 0}%` }} /></span>
<span className={`cmp-bar-value${category.winner === 'a' ? ' cmp-best' : ''}`}>{fmtMetric(category.oneShotRateA, 'percent')} <span className="cmp-turns">({category.editTurnsA})</span></span>
</div>
<div className="cmp-bar-row">
<span className="cmp-track"><span className="cmp-bar cmp-bar-b" style={{ width: `${category.oneShotRateB ?? 0}%` }} /></span>
<span className={`cmp-bar-value${category.winner === 'b' ? ' cmp-best' : ''}`}>{fmtMetric(category.oneShotRateB, 'percent')} <span className="cmp-turns">({category.editTurnsB})</span></span>
</div>
</div>
</div>
))}
</div>
</div>
</div>
)
}
function cacheHitRate(model: ModelStats): string {
const total = model.inputTokens + model.cacheReadTokens + model.cacheWriteTokens
return total > 0 ? `${Math.round(model.cacheReadTokens / total * 100)}%` : '—'
}
function daysOfData(model: ModelStats): string {
if (!model.firstSeen || !model.lastSeen) return '—'
return String(Math.max(1, Math.round((new Date(model.lastSeen).getTime() - new Date(model.firstSeen).getTime()) / 86_400_000) + 1))
}
function ContextCard({ modelA, modelB }: { modelA: ModelStats; modelB: ModelStats }) {
const rows = [
['Calls', modelA.calls.toLocaleString(), modelB.calls.toLocaleString()],
['Total cost', formatUsd(modelA.cost), formatUsd(modelB.cost)],
['Input tokens', fmtCompact(modelA.inputTokens), fmtCompact(modelB.inputTokens)],
['Output tokens', fmtCompact(modelA.outputTokens), fmtCompact(modelB.outputTokens)],
['Edit turns', modelA.editTurns.toLocaleString(), modelB.editTurns.toLocaleString()],
['Self-corrections', modelA.selfCorrections.toLocaleString(), modelB.selfCorrections.toLocaleString()],
['Cache hit rate', cacheHitRate(modelA), cacheHitRate(modelB)],
['Days of data', daysOfData(modelA), daysOfData(modelB)],
]
return (
<div className="panel cmp-card">
<div className="cmp-head"><h3>Context</h3></div>
<div className="cmp-metrics">
<MetricHeader modelA={modelA.model} modelB={modelB.model} />
{rows.map(([label, valueA, valueB]) => (
<div className="cmp-metric" key={label}>
<span className="cmp-label">{label}</span><span className="cmp-value">{valueA}</span><span className="cmp-value">{valueB}</span>
</div>
))}
</div>
</div>
)
}

View file

@ -0,0 +1,85 @@
// @vitest-environment jsdom
import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { SessionRow } from '../lib/types'
import { Sessions } from './Sessions'
const { getSessions } = vi.hoisted(() => ({
getSessions: vi.fn<(period: string, provider: string) => Promise<SessionRow[]>>(),
}))
vi.mock('../lib/ipc', async orig => {
const actual = await orig<typeof import('../lib/ipc')>()
return { ...actual, codeburn: { getSessions } }
})
const rows: SessionRow[] = [
{
sessionId: 'claude-session-123456789',
project: 'codeburn',
provider: 'claude',
models: ['Opus 4.8'],
cost: 8.41,
savingsUSD: 1.25,
calls: 44,
turns: 41,
inputTokens: 1_420_000,
outputTokens: 64_000,
cacheReadTokens: 1_130_000,
cacheWriteTokens: 12_000,
startedAt: '2026-07-11T10:00:00.000Z',
endedAt: '2026-07-11T11:35:00.000Z',
durationMs: 5_700_000,
},
{
sessionId: 'codex-session-987654321',
project: 'client-api',
provider: 'codex',
models: ['GPT-5.5 Codex'],
cost: 3.92,
savingsUSD: 0,
calls: 25,
turns: 22,
inputTokens: 120_000,
outputTokens: 16_000,
cacheReadTokens: 40_000,
cacheWriteTokens: 4_000,
startedAt: '2026-07-10T10:00:00.000Z',
endedAt: '2026-07-10T10:30:00.000Z',
durationMs: 1_800_000,
},
]
describe('Sessions', () => {
beforeEach(() => getSessions.mockReset())
it('groups real rows by provider and opens the four-stat detail', async () => {
getSessions.mockResolvedValue(rows)
const { container } = render(<Sessions period="30days" provider="all" />)
expect(await screen.findByText('Claude · 1 session · $8.41')).toBeInTheDocument()
expect(screen.getByText('Codex · 1 session · $3.92')).toBeInTheDocument()
expect(screen.getByText('codeburn')).toBeInTheDocument()
expect(screen.getByText('client-api')).toBeInTheDocument()
expect(screen.getByText('$8.41')).toBeInTheDocument()
expect(screen.getByText('$3.92')).toBeInTheDocument()
expect(screen.getByText('claude-session-123')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /codeburn/ }))
expect(await screen.findByRole('button', { name: '← Back to sessions' })).toBeInTheDocument()
expect(container.querySelectorAll('.stat')).toHaveLength(4)
for (const label of ['Cost', 'Input', 'Output', 'Cache read']) {
expect(screen.getByText(label)).toBeInTheDocument()
}
expect(screen.getByText('Saved $1.25 vs baseline')).toBeInTheDocument()
expect(screen.getByText('Duration 1h 35m')).toBeInTheDocument()
expect(screen.queryByText('Context window')).not.toBeInTheDocument()
})
it('renders the honest empty state', async () => {
getSessions.mockResolvedValue([])
render(<Sessions period="week" provider="all" />)
expect(await screen.findByText('No sessions in this range yet.')).toBeInTheDocument()
})
})

View file

@ -0,0 +1,145 @@
import { useState } from 'react'
import { CliErrorPanel } from '../components/CliErrorPanel'
import { Panel } from '../components/Panel'
import { Stat } from '../components/Stat'
import { usePolled } from '../hooks/usePolled'
import { formatUsd } from '../lib/format'
import { codeburn } from '../lib/ipc'
import type { DateRange, Period, SessionRow } from '../lib/types'
function fmtCompact(n: number): string {
if (n === 0) return '0'
if (n < 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
return new Intl.NumberFormat('en-US', {
notation: 'compact',
maximumFractionDigits: n >= 10_000_000 ? 1 : 2,
}).format(n)
}
function providerName(provider: string): string {
return provider
.split(/[-\s]+/)
.filter(Boolean)
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ')
}
function durationLabel(durationMs: number): string {
const minutes = Math.round(durationMs / 60_000)
if (minutes < 60) return `${minutes}m`
const hours = Math.floor(minutes / 60)
return `${hours}h ${minutes % 60}m`
}
function EmptyNote({ children }: { children: React.ReactNode }) {
return <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>{children}</p>
}
export function Sessions({
period,
provider,
range = null,
refreshToken = 0,
}: {
period: Period
provider: string
range?: DateRange | null
refreshToken?: number
}) {
const [selected, setSelected] = useState<SessionRow | null>(null)
const report = usePolled<SessionRow[]>(
() => range ? codeburn.getSessions(period, provider, range) : codeburn.getSessions(period, provider),
[period, provider, range?.from, range?.to, refreshToken],
)
if (!report.data) {
if (report.error) return <CliErrorPanel error={report.error} subject="sessions" />
return (
<Panel title="Sessions">
<EmptyNote>Scanning sessions…</EmptyNote>
</Panel>
)
}
if (selected) return <SessionDetail session={selected} onBack={() => setSelected(null)} />
if (!report.data.length) {
return (
<Panel title="Sessions">
<EmptyNote>No sessions in this range yet.</EmptyNote>
</Panel>
)
}
const grouped = report.data.reduce((map, row) => {
const rows = map.get(row.provider) ?? []
rows.push(row)
map.set(row.provider, rows)
return map
}, new Map<string, SessionRow[]>())
const groups = [...grouped.entries()]
.map(([name, rows]) => ({
name,
rows: [...rows].sort((a, b) => b.cost - a.cost),
cost: rows.reduce((sum, row) => sum + row.cost, 0),
}))
.sort((a, b) => b.cost - a.cost)
return (
<div className="sessions-list-view">
<div className="session-list">
{groups.map(group => (
<div className="session-provider" key={group.name}>
<div className="provider-h">
{providerName(group.name)} · {group.rows.length.toLocaleString('en-US')} {group.rows.length === 1 ? 'session' : 'sessions'} · {formatUsd(group.cost)}
</div>
{group.rows.map(row => (
<button className="session-row" key={row.sessionId} type="button" onClick={() => setSelected(row)}>
<span className="session-primary">
<span className="session-title">{row.project}</span>
<span className="session-project">{String(row.sessionId).slice(0, 18)}</span>
</span>
<span className="session-meta">
<span>{row.models.join(', ')}</span>
<span>{row.turns} turns</span>
<span>{formatUsd(row.cost)}</span>
<span>{fmtCompact(row.inputTokens + row.outputTokens)} tok</span>
</span>
</button>
))}
</div>
))}
</div>
</div>
)
}
function SessionDetail({ session, onBack }: { session: SessionRow; onBack: () => void }) {
const cacheTotal = session.inputTokens + session.cacheReadTokens
const cacheHit = cacheTotal > 0 ? `${Math.round(session.cacheReadTokens / cacheTotal * 100)}% hit` : '—'
return (
<div className="session-detail">
<button className="back-link" type="button" onClick={onBack}>← Back to sessions</button>
<div className="panel detail-head">
<h3 className="detail-title">{session.project}</h3>
<div className="detail-line">
{session.provider} · {session.models.join(', ')} · {new Date(session.startedAt).toLocaleDateString()} · {formatUsd(session.cost)} · {session.turns} turns
</div>
</div>
<div className="stats">
<Stat label="Cost" value={formatUsd(session.cost)} delta="this session" />
<Stat label="Input" value={fmtCompact(session.inputTokens)} delta="tokens sent" />
<Stat label="Output" value={fmtCompact(session.outputTokens)} delta="tokens generated" />
<Stat label="Cache read" value={fmtCompact(session.cacheReadTokens)} delta={cacheHit} />
</div>
{(session.savingsUSD > 0 || session.durationMs > 0) && (
<div className="session-detail-notes">
{session.savingsUSD > 0 && <span>Saved {formatUsd(session.savingsUSD)} vs baseline</span>}
{session.durationMs > 0 && <span>Duration {durationLabel(session.durationMs)}</span>}
</div>
)}
</div>
)
}

View file

@ -48,7 +48,7 @@ export function Settings({ period, refreshToken = 0 }: { period: Period; refresh
</div>
<Hint
items={[
{ k: '⌘1-5', label: 'Navigate' },
{ k: '⌘1-7', label: 'Navigate' },
{ k: '⌘R', label: 'Refresh' },
]}
right="pairing uses mutual TLS · approve-style, no PIN"

View file

@ -381,3 +381,82 @@ body { overflow: hidden; background: var(--bg); color: var(--ink); }
.ov-coach { align-items: flex-start; }
.ov-anomalies { flex-direction: column; gap: 5px; }
}
/* Sessions */
.sessions-list-view { width: 100%; }
.session-list { max-height: 460px; overflow-y: auto; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); }
.session-provider { display: contents; }
.provider-h { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 8px; padding: 11px 14px 6px; background: var(--panel); color: var(--mut2); font-size: 10.5px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; }
.session-row { display: flex; width: 100%; align-items: center; gap: 18px; padding: 11px 14px; border: 0; border-top: 1px solid var(--line2); background: transparent; color: var(--ink); font: inherit; text-align: left; cursor: pointer; }
.session-row:hover, .session-row:focus-visible { background: var(--hover); outline: none; }
.session-primary { min-width: 0; flex: 1; }
.session-title { display: block; overflow: hidden; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
.session-project { display: block; overflow: hidden; margin-top: 2px; color: var(--mut2); font-family: var(--mono); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
.session-meta { display: grid; grid-template-columns: minmax(110px, 1fr) 58px 70px 76px; align-items: center; gap: 10px; color: var(--mut); font-size: 11.5px; font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
.session-meta span:first-child { overflow: hidden; text-align: left; text-overflow: ellipsis; }
.session-detail { display: flex; width: 100%; flex-direction: column; gap: 16px; }
.back-link { align-self: flex-start; padding: 0; border: 0; background: transparent; color: var(--accent); font: inherit; font-weight: 520; cursor: pointer; }
.back-link:hover { text-decoration: underline; }
.detail-head { padding: 14px 15px; }
.detail-head h3 { margin: 0 0 6px; font-size: 15px; font-weight: 620; }
.detail-line { color: var(--mut); font-size: 12px; font-variant-numeric: tabular-nums; }
.stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
.stat .v { font-size: 24px; font-weight: 640; font-variant-numeric: tabular-nums; letter-spacing: -.03em; line-height: 1.1; }
.stat .d { margin-top: 4px; color: var(--mut2); font-size: 10.5px; font-variant-numeric: tabular-nums; }
.session-detail-notes { display: flex; flex-wrap: wrap; gap: 8px 24px; color: var(--mut); font-size: 11.5px; font-variant-numeric: tabular-nums; }
/* Compare */
.cmp-picker { display: flex; width: auto; align-items: center; align-self: flex-start; gap: 8px; }
select.cmp-select { min-width: 210px; padding: 6px 30px 6px 10px; border: 1px solid var(--line); border-radius: 7px; background-color: var(--panel); color: var(--ink); font: inherit; font-size: 11.5px; cursor: pointer; }
select.cmp-select:focus-visible { border-color: var(--accent); outline: 1px solid var(--accent); outline-offset: 1px; }
.cmp-vs { color: var(--mut2); font-size: 10.5px; font-weight: 600; text-transform: uppercase; }
.cmp-body { display: flex; width: 100%; flex-direction: column; gap: 14px; }
.cmp-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; }
.cmp-card { min-width: 0; overflow: hidden; border-radius: 8px; }
.cmp-head { display: flex; min-height: 42px; align-items: center; padding: 0 14px; border-bottom: 1px solid var(--line2); background: var(--phead); }
.cmp-head h3 { margin: 0; font-size: 12.5px; font-weight: 620; letter-spacing: -.005em; }
.cmp-head-note { margin-left: auto; color: var(--mut2); font-size: 10px; }
.cmp-metrics { padding: 4px 14px 7px; }
.cmp-metric-head, .cmp-metric { display: grid; grid-template-columns: minmax(120px, 1fr) minmax(74px, .56fr) minmax(74px, .56fr); align-items: center; column-gap: 12px; }
.cmp-metric-head { min-height: 31px; border-bottom: 1px solid var(--line2); color: var(--mut2); font-size: 9.5px; font-weight: 600; }
.cmp-metric-head span:not(:first-child) { overflow: hidden; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
.cmp-metric { min-height: 37px; border-bottom: 1px solid var(--line2); }
.cmp-metric:last-child { border-bottom: 0; }
.cmp-label { color: var(--mut); font-size: 11.5px; }
.cmp-value { color: var(--mut); font-family: var(--mono); font-size: 11.5px; font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
.cmp-best { color: var(--ok); font-weight: 600; }
.cmp-foot { padding: 8px 14px 10px; border-top: 1px solid var(--line2); color: var(--mut2); font-size: 10px; }
.cmp-category-body { padding: 12px 14px 14px; }
.cmp-legend { display: flex; justify-content: flex-end; gap: 16px; margin-bottom: 10px; color: var(--mut); font-size: 10px; }
.cmp-legend-item { display: inline-flex; align-items: center; gap: 6px; }
.cmp-key { width: 14px; height: 4px; border-radius: 2px; background: var(--accent); }
.cmp-key.cmp-key-b { background: var(--bar-hi); }
.cmp-categories { display: flex; flex-direction: column; gap: 11px; }
.cmp-category { display: grid; grid-template-columns: 86px minmax(0, 1fr); align-items: start; gap: 12px; }
.cmp-category-name { padding-top: 8px; color: var(--ink); font-size: 11.5px; font-weight: 560; }
.cmp-bars { display: grid; gap: 5px; }
.cmp-bar-row { display: grid; min-width: 0; grid-template-columns: minmax(0, 1fr) 82px; align-items: center; gap: 10px; }
.cmp-track { height: 6px; overflow: hidden; border-radius: 3px; background: var(--fill); }
.cmp-bar { display: block; height: 100%; border-radius: 3px; background: var(--accent); }
.cmp-bar.cmp-bar-b { background: var(--bar-hi); }
.cmp-bar-value { color: var(--mut); font-family: var(--mono); font-size: 10.5px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.cmp-turns { color: var(--mut2); }
@media (max-width: 860px) {
.session-meta { grid-template-columns: 90px 52px 62px; }
.session-meta span:last-child { display: none; }
select.cmp-select { min-width: 180px; }
.cmp-pair { grid-template-columns: 1fr; }
.cmp-metric-head, .cmp-metric { grid-template-columns: minmax(110px, 1fr) 76px 76px; }
}
@media (max-width: 620px) {
.cmp-picker { gap: 5px; }
select.cmp-select { min-width: 0; max-width: 42vw; }
.cmp-category { grid-template-columns: 70px minmax(0, 1fr); }
.cmp-bar-row { grid-template-columns: minmax(0, 1fr) 76px; }
}
@media (max-width: 720px) {
.stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}