import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { CliErrorPanel } from '../components/CliErrorPanel' import { Dropdown } from '../components/Dropdown' import { EmptyNote } from '../components/EmptyState' import { Panel } from '../components/Panel' import { SegTabs } from '../components/SegTabs' import { SectionSkeleton } from '../components/Skeleton' import { usePolled } from '../hooks/usePolled' import { applyVolumeBand, computeBandCohortStats, type VolumeBand, type VolumeMeasure, } from '../lib/cohortStats' import { formatCompact, formatCount, formatUsd, sessionCacheHitPercent, shortenProjectPath } from '../lib/format' import { Usd, tokensOf } from '../components/Usd' import { t } from '../i18n' import { codeburn } from '../lib/ipc' import { reportMemoKey } from '../lib/reportMemoKey' import { sessionFilters } from '../lib/investigation' import { trackEvent } from '../lib/track' import type { InvestigateRequest } from './Overview' import { sessionRowKey } from './Sessions' import type { CategoryComparison, CohortComparisonReport, CohortModelReport, CohortObservation, CompareJsonReport, ComparisonRow, DateRange, ModelStats, Period, WorkingStyleRow, } from '../lib/types' 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') } // The CLI `compare` command has no --from/--to, so a custom range falls back to // the selected period. Say so instead of silently ignoring the dates. function RangeNote() { return (

{t('compare.classic.rangeNote')}

) } type CompareMode = 'classic' | 'cohorts' export function Compare({ period, provider, range = null, refreshToken = 0, ready = true, onInvestigate, }: { period: Period provider: string range?: DateRange | null refreshToken?: number ready?: boolean onInvestigate?: (request: InvestigateRequest) => void }) { const [mode, setMode] = useState('classic') if (mode === 'cohorts') { return (
setMode(next as CompareMode)} />
) } return (
setMode(next as CompareMode)} />
) } function ClassicCompare({ period, provider, range, refreshToken, ready, }: { period: Period provider: string range: DateRange | null refreshToken: number ready: boolean }) { const models = usePolled( () => codeburn.getCompareModels(period, provider), [period, provider, refreshToken], { enabled: ready, memoKey: reportMemoKey('comparemodels', period, provider) }, ) const [modelA, setModelA] = useState(null) const [modelB, setModelB] = useState(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]) // One event per distinct pair actually put on screen, not per keystroke in // the pickers. Model names only. const comparedPair = useRef(null) useEffect(() => { if (!modelA || !modelB || modelA === modelB) return const pair = `${modelA} ${modelB}` if (comparedPair.current === pair) return comparedPair.current = pair trackEvent('compare_view', { modelA, modelB }) }, [modelA, modelB]) 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 return } if (models.data.length < 2) { return ( {t('compare.classic.needTwoModels')} ) } const modelRows = models.data const nudgeDistinct = (chosen: string) => modelRows.find(model => model.model !== chosen)?.model ?? null return ( <> {range && }
({ value: model.model, label: `${model.model} · ${formatCount(model.calls, 'call')}` }))} onChange={next => { setModelA(next) if (next === modelB) setModelB(nudgeDistinct(next)) }} /> {t('compare.vs')} ({ value: model.model, label: `${model.model} · ${formatCount(model.calls, 'call')}` }))} onChange={next => { setModelB(next) if (next === modelA) setModelA(nudgeDistinct(next)) }} />
{modelA && modelB && modelA !== modelB && modelRows.some(row => row.model === modelA) && modelRows.some(row => row.model === modelB) && ( )} ) } function CompareReport({ period, provider, modelA, modelB, refreshToken, onError, }: { period: Period provider: string modelA: string modelB: string refreshToken: number onError: () => void }) { const report = usePolled( () => codeburn.getCompare(period, provider, modelA, modelB), [period, provider, modelA, modelB, refreshToken], { memoKey: reportMemoKey('compare', period, provider, null, `${modelA}|${modelB}`) }, ) useEffect(() => { if (report.error) onError() }, [report.error, onError]) if (!report.data) { if (report.error) return return } const performance = report.data.metrics.filter(metric => metric.section === 'Performance') const efficiency = report.data.metrics.filter(metric => metric.section === 'Efficiency') return (
) } function MetricCard({ title, rows, modelA, modelB, showWinners = false, }: { title: string rows: Array modelA: string modelB: string showWinners?: boolean }) { return (

{title}

{rows.map(row => { const winner = 'winner' in row ? row.winner : 'none' return (
{row.label} {fmtMetric(row.valueA, row.formatFn)} {fmtMetric(row.valueB, row.formatFn)}
) })}
{showWinners &&
{t('compare.classic.greenBetter')}
}
) } function MetricHeader({ modelA, modelB }: { modelA: string; modelB: string }) { return
{t('compare.classic.metricHeader')}{modelA}{modelB}
} /** A category is a head-to-head only when both models worked in it and both * produced a rate. Anything less draws a bar against an empty track under a * legend — a chart that shows no comparison. */ function isComparable(category: CategoryComparison): boolean { return category.turnsA > 0 && category.turnsB > 0 && category.oneShotRateA !== null && category.oneShotRateB !== null } function CategoryCard({ report }: { report: CompareJsonReport }) { const comparable = report.categories.some(isComparable) return (

{t('compare.classic.categoryHeadToHead')}

{t('compare.classic.oneShotRateEditTurns')}
{!comparable ? {t('compare.classic.noCategoriesToCompare')} : <>
{report.modelA.model} {report.modelB.model}
{report.categories.map(category => (
{category.category}
{fmtMetric(category.oneShotRateA, 'percent')} ({category.editTurnsA})
{fmtMetric(category.oneShotRateB, 'percent')} ({category.editTurnsB})
))}
}
) } function cacheHitRate(model: ModelStats): string { const percent = sessionCacheHitPercent(model.inputTokens, model.cacheReadTokens, model.cacheWriteTokens) return percent === null ? '—' : `${Math.round(percent)}%` } 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: Array<[string, ReactNode, ReactNode]> = [ [t('compare.classic.context.calls'), modelA.calls.toLocaleString(), modelB.calls.toLocaleString()], [t('compare.classic.context.totalCost'), , ], [t('compare.classic.context.inputTokens'), formatCompact(modelA.inputTokens), formatCompact(modelB.inputTokens)], [t('compare.classic.context.outputTokens'), formatCompact(modelA.outputTokens), formatCompact(modelB.outputTokens)], [t('compare.classic.context.editTurns'), modelA.editTurns.toLocaleString(), modelB.editTurns.toLocaleString()], [t('compare.classic.context.selfCorrections'), modelA.selfCorrections.toLocaleString(), modelB.selfCorrections.toLocaleString()], [t('compare.classic.context.cacheHitRate'), cacheHitRate(modelA), cacheHitRate(modelB)], [t('compare.classic.context.daysOfData'), daysOfData(modelA), daysOfData(modelB)], ] return (

{t('compare.classic.context')}

{rows.map(([label, valueA, valueB]) => (
{label}{valueA}{valueB}
))}
) } // ————— Cohorts mode: model comparison over an explicit, inspectable population ————— const SAMPLES_INITIAL_COUNT = 20 type BandMeasureLabel = { value: VolumeMeasure; labelKey: string } // Translated at render time (VolumeBandFilter), never at module scope, so a // language switch picks it up like everything else. const BAND_MEASURES: BandMeasureLabel[] = [ { value: 'output', labelKey: 'compare.cohort.band.outputTokens' }, { value: 'input', labelKey: 'compare.cohort.band.inputTokens' }, { value: 'contextProxy', labelKey: 'compare.cohort.band.contextProxy' }, ] function CohortCompare({ period, provider, range, refreshToken, ready, onInvestigate, }: { period: Period provider: string range: DateRange | null refreshToken: number ready: boolean onInvestigate?: (request: InvestigateRequest) => void }) { const facets = usePolled( () => codeburn.getCompareCohortModels(period, provider, range ?? undefined), [period, provider, range?.from, range?.to, refreshToken], { enabled: ready, memoKey: reportMemoKey('cohortmodels-v2', period, provider, range) }, ) const [modelA, setModelA] = useState(null) const [modelB, setModelB] = useState(null) const [project, setProject] = useState('') const [category, setCategory] = useState('') useEffect(() => { if (!facets.data) return const available = new Set(facets.data.models.map(model => model.model)) setModelA(current => current && available.has(current) ? current : facets.data?.models[0]?.model ?? null) setModelB(current => current && available.has(current) ? current : facets.data?.models[1]?.model ?? null) // A project/category that vanished from the population must not keep // filtering silently: fall back to "all". setProject(current => { if (!current) return '' return facets.data?.projects.some(p => p.id === current) ? current : '' }) }, [facets.data]) // facets.data is masked to the current period/provider, so this keeps the // previous selection from being requested before the effect above resets it // (the CLI exits 1 on a model it cannot find). const listed = (model: string | null) => !!model && !!facets.data?.models.some(row => row.model === model) const report = usePolled( () => codeburn.getCompareCohort(period, provider, modelA ?? '', modelB ?? '', range ?? undefined, project ? [project] : undefined, category || undefined), [period, provider, modelA, modelB, range?.from, range?.to, project, category, refreshToken], { enabled: ready && listed(modelA) && listed(modelB) && modelA !== modelB, memoKey: reportMemoKey('cohort-v2', period, provider, range, JSON.stringify([modelA, modelB, project, category])), }, ) if (!facets.data) { if (facets.error) return return } if (facets.data.models.length < 2) { return ( {t('compare.classic.needTwoModels')} ) } const modelRows = facets.data.models const nudgeDistinct = (chosen: string) => modelRows.find(model => model.model !== chosen)?.model ?? null const intervalLabel = range ? `${range.from} → ${range.to}` : (report.data?.period.label ?? period) return ( <>
({ value: model.model, label: `${model.model} · ${formatCount(model.calls, 'call')}` }))} onChange={next => { setModelA(next) if (next === modelB) setModelB(nudgeDistinct(next)) }} /> {t('compare.vs')} ({ value: model.model, label: `${model.model} · ${formatCount(model.calls, 'call')}` }))} onChange={next => { setModelB(next) if (next === modelA) setModelA(nudgeDistinct(next)) }} /> ({ value: p.id, label: shortenProjectPath(p.id) }))]} onChange={setProject} /> ({ value: c.id, label: c.label }))]} onChange={setCategory} />

{t('compare.cohort.intervalNote', { interval: intervalLabel })}

{modelA && modelB && modelA !== modelB && ( )} ) } function CohortReport({ report, onInvestigate }: { report: ReturnType> onInvestigate?: (request: InvestigateRequest) => void }) { const [band, setBand] = useState(null) if (!report.data) { if (report.error) return return } const data = report.data // Volume bands recompute from the report's own declared population — instant, // deterministic, and reproducible from the sample lists. const sideA = cohortSide(data.modelA, band) const sideB = cohortSide(data.modelB, band) return (
) } function cohortSide(model: CohortModelReport, band: VolumeBand | null) { const filtered = applyVolumeBand(model.observations, band) const stats = band ? computeBandCohortStats(model.model, filtered.kept) : model.stats return { model, band, kept: filtered.kept, excludedOutsideBand: filtered.outsideBand, excludedMissingMeasure: filtered.missingMeasure, stats, } } type CohortSide = ReturnType function PopulationCard({ data, sideA, sideB, band, onBandChange }: { data: CohortComparisonReport sideA: CohortSide sideB: CohortSide band: VolumeBand | null onBandChange: (band: VolumeBand | null) => void }) { const bandExcludedTotal = sideA.excludedOutsideBand + sideB.excludedOutsideBand const missingMeasureTotal = sideA.excludedMissingMeasure + sideB.excludedMissingMeasure return (

{t('compare.cohort.population.title')}

{t('compare.cohort.population.subtitle')}
{t('compare.cohort.population.selectionHeader')}{data.modelA.label}{data.modelB.label}
{t('compare.cohort.population.observations')} {sideA.stats.observationCount.toLocaleString()} {sideB.stats.observationCount.toLocaleString()}
{t('compare.cohort.population.distinctSessions')} {sideA.stats.distinctSessionCount.toLocaleString()} {sideB.stats.distinctSessionCount.toLocaleString()}
{t('compare.cohort.population.excludedMixedLabel')} {data.modelA.exclusions.multiModelTurnCount.toLocaleString()} ({formatUsd(data.modelA.exclusions.combinedMultiModelCostUSD)}) {data.modelB.exclusions.multiModelTurnCount.toLocaleString()} ({formatUsd(data.modelB.exclusions.combinedMultiModelCostUSD)})
{t('compare.cohort.population.excludedNoModelLabel')} {data.modelA.exclusions.noBehavioralModelTurns.toLocaleString()} {data.modelB.exclusions.noBehavioralModelTurns.toLocaleString()}
{t('compare.cohort.population.unknownCostLabel')} {sideA.stats.unknownCostCount.toLocaleString()} {sideB.stats.unknownCostCount.toLocaleString()}
{t('compare.cohort.population.projectsCategoryLabel')} {describeSelection(data)}
{(bandExcludedTotal > 0 || missingMeasureTotal > 0) && (
{t('compare.cohort.population.bandExcluded', { count: bandExcludedTotal.toLocaleString() })} {missingMeasureTotal > 0 ? t('compare.cohort.population.bandExcludedMissing', { count: missingMeasureTotal.toLocaleString() }) : ''}. {' '}{t('compare.cohort.population.ratesNote')}
)}
{t('compare.cohort.population.conventionNote')}
) } function describeSelection(data: CohortComparisonReport): string { const projects = data.selection.projects const projectLabel = projects.length === 0 ? t('compare.cohort.selection.all') : projects.length <= 2 ? projects.join(', ') : t('compare.cohort.selection.projectsCount', { count: projects.length }) const category = data.selection.category ?? t('compare.cohort.selection.allCategories') const interval = data.selection.from && data.selection.to ? `${data.selection.from} → ${data.selection.to}` : data.period.label return `${projectLabel} · ${category} · ${interval}` } function VolumeBandFilter({ band, onChange }: { band: VolumeBand | null; onChange: (band: VolumeBand | null) => void }) { const measure = band?.measure ?? 'output' const min = band?.min?.toString() ?? '' const max = band?.max?.toString() ?? '' const push = (next: { measure?: VolumeMeasure; min?: string; max?: string }) => { const nextMeasure = next.measure ?? measure const minRaw = next.min ?? min const maxRaw = next.max ?? max const minNum = minRaw.trim() === '' ? null : Number(minRaw) const maxNum = maxRaw.trim() === '' ? null : Number(maxRaw) const validMin = minNum != null && Number.isFinite(minNum) ? minNum : null const validMax = maxNum != null && Number.isFinite(maxNum) ? maxNum : null if (validMin == null && validMax == null) { onChange(null) return } onChange({ measure: nextMeasure, min: validMin, max: validMax }) } return (
{t('compare.cohort.band.label')} ({ value: m.value, label: t(m.labelKey) }))} onChange={next => push({ measure: next as VolumeMeasure })} /> push({ min: event.target.value })} /> – push({ max: event.target.value })} /> {band && ( )}
) } function CohortModelCard({ side }: { side: CohortSide }) { const stats = side.stats const histogram = stats.costHistogram const maxCount = Math.max(1, ...histogram.counts) return (

{t('compare.cohort.model.costPerEditTurn')}

{side.model.label}
{t('compare.cohort.model.medianCost')}{fmtCost(stats.costMedian)}
{t('compare.cohort.model.p90Cost')}{fmtCost(stats.costP90)}
{t('compare.cohort.model.meanCost')}{fmtCost(stats.costMean)}
{t('compare.cohort.model.oneShotRateLabel')}{fmtMetric(stats.oneShotRate, 'percent')} ({stats.oneShotCount}/{stats.observationCount})
{t('compare.cohort.model.retryRateLabel')}{fmtMetric(stats.retryRate, 'decimal')} ({stats.retryCount})
{t('compare.cohort.model.costKnownFor')}{t('compare.cohort.model.observationsOf', { known: stats.costKnownCount, total: stats.observationCount })}
{histogram.edges.length === 0 && histogram.counts.length === 1 ? (
{t('compare.cohort.model.allFreeCosts')}
) : ( histogram.counts.map((count, index) => (
{bucketLabel(histogram.edges, index)} {count.toLocaleString()}
)) )}
) } function fmtCost(value: number | null): string { return value === null ? '—' : formatUsd(value) } function bucketLabel(edges: number[], index: number): string { if (edges.length === 0) return '$0' if (index === 0) return `< ${formatUsd(edges[0] as number)}` if (index === edges.length) return `≥ ${formatUsd(edges[edges.length - 1] as number)}` return `${formatUsd(edges[index - 1] as number)}–${formatUsd(edges[index] as number)}` } function VolumeCard({ title, side }: { title: string; side: CohortSide }) { const volume = side.stats.volume // id drives the tooltip lookup so it survives translation; the row's own // English label can no longer be pattern-matched once it's localized. const rows: Array<{ id: 'output' | 'input' | 'context'; labelKey: string; median: string; p90: string }> = [ { id: 'output', labelKey: 'compare.cohort.volume.outputTokensRow', median: fmtVolume(volume.outputMedian), p90: fmtVolume(volume.outputP90) }, { id: 'input', labelKey: 'compare.cohort.volume.inputTokensRow', median: fmtVolume(volume.inputMedian), p90: fmtVolume(volume.inputP90) }, { id: 'context', labelKey: 'compare.cohort.volume.contextProxyRow', median: fmtVolume(volume.contextProxyMedian), p90: fmtVolume(volume.contextProxyP90) }, ] return (

{title}

{side.model.label}
{t('compare.cohort.volume.columnHeader')}{t('compare.cohort.volume.medianHeader')}{t('compare.cohort.volume.p90Header')}
{rows.map(row => (
{t(row.labelKey)} {row.median} {row.p90}
))}
{t('compare.cohort.volume.missingMeasureLabel')} {volume.missingMeasureCount.toLocaleString()}
) } function fmtVolume(value: number | null): string { return value === null ? '—' : formatCompact(value) } /** Inspect samples: the declared population, inspectable row by row. Activating * a row drills through to the owning session with the shared investigation * navigation, keyed by the same provider/project/session triple Sessions uses. */ function SampleInspector({ side, onInvestigate }: { side: CohortSide onInvestigate?: (request: InvestigateRequest) => void }) { const [showAll, setShowAll] = useState(false) const observations = useMemo( () => [...side.kept].sort((a, b) => b.costUSD - a.costUSD || a.timestamp.localeCompare(b.timestamp)), [side.kept], ) const visible = showAll ? observations : observations.slice(0, SAMPLES_INITIAL_COUNT) return (

{t('compare.cohort.samples.title')}

{side.model.label} · {t('compare.cohort.samples.ofInSelection', { count: side.stats.observationCount.toLocaleString(), total: side.model.stats.observationCount.toLocaleString() })}
{observations.length === 0 ? (
{t('compare.cohort.samples.noObservations')}{side.band ? t('compare.cohort.samples.andVolumeBand') : ''}{t('compare.cohort.samples.nothingCompared')}
) : (
{visible.map((observation, index) => ( ))} {observations.length > SAMPLES_INITIAL_COUNT && ( )}
)}
) } function SampleRow({ observation, onInvestigate }: { observation: CohortObservation onInvestigate?: (request: InvestigateRequest) => void }) { const activate = () => { onInvestigate?.({ filters: sessionFilters({ provider: observation.provider, sessionId: observation.sessionId }), sessionId: sessionRowKey(observation), }) } return ( ) }