test(app): Spend coverage (lenses, states, colors, Sankey, period windows) + proportional/labeled Sankey

Addresses T3 review: full test coverage for all lenses + empty/error states, segment
color mapping, Sankey ribbon properties, and lib/period.ts across all windows; Sankey
ribbon widths now truly proportional (removed the 28px cap) and labels are pretty/basename
+ truncated so real ids don't clip; legend reflects present models; honest "top N" project count.

Implemented by Codex gpt-5.5 (high); committed by Fable (git blocked in Codex sandbox).
This commit is contained in:
iamtoruk 2026-07-10 18:30:17 -07:00
parent d7f3ccd1f0
commit 5cd5c783a2
6 changed files with 276 additions and 59 deletions

View file

@ -6,16 +6,18 @@ type LayoutNode = SpendFlowNode & {
y: number
h: number
fill: string
displayLabel: string
}
const VIEW_W = 640
const VIEW_W = 760
const VIEW_H = 190
const TOP = 14
const BOTTOM = 18
const LEFT_X = 72
const RIGHT_X = 562
const LEFT_X = 126
const RIGHT_X = 520
const NODE_W = 5
const GAP = 8
const MIN_RIBBON_W = 2
export function Sankey({ flow }: { flow: SpendFlow }) {
const models = layoutNodes(flow.models, LEFT_X, true)
@ -32,7 +34,7 @@ export function Sankey({ flow }: { flow: SpendFlow }) {
const sourceSegment = segmentSize(source, link.cost)
const targetSegment = segmentSize(target, link.cost)
const width = Math.max(2, Math.min(28, (sourceSegment + targetSegment) / 2))
const width = Math.max(MIN_RIBBON_W, (sourceSegment + targetSegment) / 2)
const sy = source.y + (sourceOffset.get(source.id) ?? 0) + sourceSegment / 2
const ty = target.y + (targetOffset.get(target.id) ?? 0) + targetSegment / 2
sourceOffset.set(source.id, (sourceOffset.get(source.id) ?? 0) + sourceSegment)
@ -43,6 +45,8 @@ export function Sankey({ flow }: { flow: SpendFlow }) {
<path
key={`${link.model}-${link.project}-${i}`}
data-testid="sankey-ribbon"
data-model={source.id}
data-project={target.id}
d={`M ${LEFT_X + NODE_W + 1} ${round(sy)} C 300 ${round(sy)} 380 ${round(ty)} ${RIGHT_X - 1} ${round(ty)}`}
stroke={`url(#${gradId})`}
strokeWidth={round(width)}
@ -66,20 +70,40 @@ export function Sankey({ flow }: { flow: SpendFlow }) {
{ribbons}
{models.map(node => (
<rect key={node.id} x={node.x} y={round(node.y)} width={NODE_W} height={round(node.h)} rx="2.5" fill={node.fill} />
<rect
key={node.id}
data-testid="sankey-node"
data-node-id={node.id}
x={node.x}
y={round(node.y)}
width={NODE_W}
height={round(node.h)}
rx="2.5"
fill={node.fill}
/>
))}
{projects.map(node => (
<rect key={node.id} x={node.x} y={round(node.y)} width={NODE_W} height={round(node.h)} rx="2.5" fill={node.fill} />
<rect
key={node.id}
data-testid="sankey-node"
data-node-id={node.id}
x={node.x}
y={round(node.y)}
width={NODE_W}
height={round(node.h)}
rx="2.5"
fill={node.fill}
/>
))}
{models.map(node => (
<text key={node.id} x="64" y={round(node.y + node.h / 2 + 3)} textAnchor="end" fontSize="10" fill="#9BA3B7">
{node.label} · {fmtUsd(node.cost)}
<text key={node.id} x="118" y={round(node.y + node.h / 2 + 3)} textAnchor="end" fontSize="10" fill="#9BA3B7">
{node.displayLabel} · {fmtUsd(node.cost)}
</text>
))}
{projects.map(node => (
<text key={node.id} x="575" y={round(node.y + node.h / 2 + 3)} fontSize="10" fill="#9BA3B7">
{node.label} · {fmtUsd(node.cost)}
<text key={node.id} x="534" y={round(node.y + node.h / 2 + 3)} fontSize="10" fill="#9BA3B7">
{node.displayLabel} · {fmtUsd(node.cost)}
</text>
))}
</svg>
@ -100,14 +124,15 @@ function layoutNodes(nodes: SpendFlowNode[], x: number, modelSide: boolean): Lay
const h = Math.max(2, inflated[i] * scale)
const neutral = isOtherNode(node.id) || isOtherNode(node.label)
const fill = modelSide && !neutral ? seriesHexForModel(node.label || node.id) : neutral ? '#5F6780' : '#3A4258'
const laidOut = { ...node, x, y, h, fill }
const displayLabel = modelSide ? modelDisplayLabel(node.label || node.id) : projectDisplayLabel(node.label || node.id)
const laidOut = { ...node, x, y, h, fill, displayLabel }
y += h + GAP
return laidOut
})
}
function segmentSize(node: LayoutNode, cost: number): number {
return node.cost > 0 ? Math.max(1, (Math.max(0, cost) / node.cost) * node.h) : 1
return node.cost > 0 ? (Math.max(0, cost) / node.cost) * node.h : 0
}
function gradientId(id: string): string {
@ -121,3 +146,28 @@ function round(n: number): number {
function fmtUsd(n: number): string {
return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}
function modelDisplayLabel(raw: string): string {
const value = raw.trim()
const lower = value.toLowerCase()
if (lower.includes('opus')) return 'Opus 4.8'
if (lower.includes('sonnet')) return 'Sonnet 5'
if (lower.includes('haiku')) return 'Haiku 4.5'
if (lower.includes('gpt') || lower.includes('codex')) return 'GPT-5.5 Codex'
return ellipsize(shortenId(value), 18)
}
function projectDisplayLabel(raw: string): string {
const value = raw.trim()
if (isOtherNode(value)) return 'Other'
const parts = value.split(/[\\/]+/).filter(Boolean)
return ellipsize(parts.at(-1) ?? value, 24)
}
function shortenId(value: string): string {
return value.replace(/^claude[-_]/i, '').replace(/^openai[-_]/i, '')
}
function ellipsize(value: string, max: number): string {
return value.length > max ? `${value.slice(0, max - 3)}...` : value
}

View file

@ -10,6 +10,14 @@ export const SERIES_HEX = {
export type SeriesKey = keyof typeof SERIES_HEX
const SERIES_LABELS: Record<SeriesKey, string> = {
opus: 'Opus 4.8',
sonnet: 'Sonnet 5',
haiku: 'Haiku 4.5',
gpt: 'GPT-5.5 Codex',
other: 'Other',
}
export function seriesKeyForModel(model?: string): SeriesKey {
const m = (model ?? '').toLowerCase()
if (m.includes('opus')) return 'opus'
@ -44,10 +52,17 @@ export function isOtherNode(idOrLabel?: string): boolean {
}
export function StackedBars({ daily }: { daily: DailyHistoryEntry[] }) {
const presentSeries = new Set<SeriesKey>()
const maxTotal = Math.max(
1,
...daily.map(day => day.topModels.reduce((sum, model) => sum + Math.max(0, model.cost), 0)),
)
for (const day of daily) {
for (const model of day.topModels) {
if (model.cost > 0) presentSeries.add(seriesKeyForModel(model.name))
}
}
const legendSeries = (['opus', 'sonnet', 'haiku', 'gpt', 'other'] as const).filter(series => presentSeries.has(series))
return (
<>
@ -69,22 +84,12 @@ export function StackedBars({ daily }: { daily: DailyHistoryEntry[] }) {
))}
</div>
<div className="legend">
<span>
<i style={{ background: 'var(--blue)' }} />
Opus 4.8
</span>
<span>
<i style={{ background: 'var(--purple)' }} />
Sonnet 5
</span>
<span>
<i style={{ background: 'var(--lav)' }} />
Haiku 4.5
</span>
<span>
<i style={{ background: 'var(--cyan)' }} />
GPT-5.5 Codex
</span>
{legendSeries.map(series => (
<span key={series}>
<i style={{ background: SERIES_HEX[series] }} />
{SERIES_LABELS[series]}
</span>
))}
</div>
</>
)

View file

@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest'
import type { DailyHistoryEntry, Period } from './types'
import { sliceDailyToPeriod } from './period'
function entry(date: string): DailyHistoryEntry {
return {
date,
cost: 1,
savingsUSD: 0,
calls: 1,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
topModels: [],
}
}
const NOW = new Date(2026, 6, 10, 12, 0, 0)
const DAILY = [
entry('2026-05-31'),
entry('2026-06-01'),
entry('2026-06-10'),
entry('2026-06-11'),
entry('2026-07-01'),
entry('2026-07-03'),
entry('2026-07-04'),
entry('2026-07-09'),
entry('2026-07-10'),
entry('2026-07-11'),
]
describe('sliceDailyToPeriod', () => {
it.each<[Period, string[]]>([
['today', ['2026-07-10']],
['week', ['2026-07-04', '2026-07-09', '2026-07-10']],
['30days', ['2026-06-11', '2026-07-01', '2026-07-03', '2026-07-04', '2026-07-09', '2026-07-10']],
['month', ['2026-07-01', '2026-07-03', '2026-07-04', '2026-07-09', '2026-07-10']],
[
'all',
[
'2026-05-31',
'2026-06-01',
'2026-06-10',
'2026-06-11',
'2026-07-01',
'2026-07-03',
'2026-07-04',
'2026-07-09',
'2026-07-10',
],
],
])('returns only in-window entries for %s', (period, expectedDates) => {
expect(sliceDailyToPeriod(DAILY, period, NOW).map(day => day.date)).toEqual(expectedDates)
})
})

View file

@ -30,25 +30,3 @@ export function sliceDailyToPeriod(daily: DailyHistoryEntry[], period: Period, n
const todayKey = localDateKey(now)
return daily.filter(d => (start === null || d.date >= start) && d.date <= todayKey)
}
/** Length of the selected period in days; `all` spans available history when provided. */
export function periodLengthDays(period: Period, daily: DailyHistoryEntry[] = [], now = new Date()): number {
switch (period) {
case 'today':
return 1
case 'week':
return 7
case '30days':
return 30
case 'month':
return now.getDate()
case 'all': {
if (daily.length === 0) return 1
const earliest = daily.reduce((min, d) => (d.date < min ? d.date : min), daily[0].date)
const [y, m, d] = earliest.split('-').map(Number)
const start = new Date(y, m - 1, d)
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
return Math.max(1, Math.round((today.getTime() - start.getTime()) / 86_400_000) + 1)
}
}
}

View file

@ -1,5 +1,5 @@
// @vitest-environment jsdom
import { render, screen } from '@testing-library/react'
import { fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { MenubarPayload, SpendFlow } from '../lib/types'
@ -98,22 +98,31 @@ function makeFlow(): SpendFlow {
return {
period: { label: 'Last 7 days', start: '2026-07-04', end: '2026-07-10' },
models: [
{ id: 'claude-opus-4', label: 'Opus 4.8', cost: 22 },
{ id: 'gpt-5.5-codex', label: 'GPT-5.5 Codex', cost: 18 },
{ id: 'claude-opus-4-20260701', label: 'claude-opus-4-20260701', cost: 22 },
{ id: 'gpt-5.5-codex', label: 'gpt-5.5-codex', cost: 18 },
],
projects: [
{ id: 'codeburn', label: 'codeburn', cost: 30 },
{ id: '__other__', label: 'Other', cost: 10 },
{ id: '/Users/me/src/mobile-app', label: '/Users/me/src/mobile-app', cost: 30 },
{ id: '__other__', label: '__other__', cost: 10 },
],
links: [
{ model: 'claude-opus-4', project: 'codeburn', cost: 18 },
{ model: 'claude-opus-4', project: '__other__', cost: 4 },
{ model: 'gpt-5.5-codex', project: 'codeburn', cost: 12 },
{ model: 'claude-opus-4-20260701', project: '/Users/me/src/mobile-app', cost: 18 },
{ model: 'claude-opus-4-20260701', project: '__other__', cost: 4 },
{ model: 'gpt-5.5-codex', project: '/Users/me/src/mobile-app', cost: 12 },
{ model: 'gpt-5.5-codex', project: '__other__', cost: 6 },
],
}
}
function emptyFlow(): SpendFlow {
return {
period: { label: 'Last 7 days', start: '2026-07-04', end: '2026-07-10' },
models: [],
projects: [],
links: [],
}
}
describe('Spend', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] })
@ -135,6 +144,7 @@ describe('Spend', () => {
expect(await screen.findByText('codeburn')).toBeInTheDocument()
expect(screen.getByText('$246.10')).toBeInTheDocument()
expect(screen.getByText('agentseal-dash')).toBeInTheDocument()
expect(screen.getByText('top 2')).toBeInTheDocument()
const barColumns = container.querySelectorAll('.sbars .c')
expect(barColumns).toHaveLength(3)
@ -146,4 +156,121 @@ describe('Spend', () => {
expect(container.querySelectorAll('[data-testid="sankey-ribbon"]')).toHaveLength(makeFlow().links.length)
})
it.each([
['Activity', ['coding', '$42.00', 'imagegen', '$1.25']],
['Tools', ['Read', '30 calls']],
['MCP', ['filesystem', '9 calls']],
['Subagents', ['reviewer', '$2.50']],
])('renders %s lens data', async (tab, expectedTexts) => {
getOverview.mockResolvedValue(makePayload(new Date()))
getSpendFlow.mockResolvedValue(makeFlow())
render(<Spend period="week" provider="all" />)
expect(await screen.findByText('codeburn')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: tab }))
for (const text of expectedTexts) {
expect(screen.getByText(text)).toBeInTheDocument()
}
})
it.each([
['Activity', 'No activity or skill spend in this range yet.'],
['Tools', 'No tool calls in this range yet.'],
['MCP', 'No MCP server calls in this range yet.'],
['Subagents', 'No subagent spend in this range yet.'],
])('renders the honest empty state for %s', async (tab, emptyText) => {
const payload = makePayload(new Date())
payload.current.topActivities = []
payload.current.skills = []
payload.current.tools = []
payload.current.mcpServers = []
payload.current.subagents = []
getOverview.mockResolvedValue(payload)
getSpendFlow.mockResolvedValue(makeFlow())
render(<Spend period="week" provider="all" />)
expect(await screen.findByText('codeburn')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: tab }))
expect(screen.getByText(emptyText)).toBeInTheDocument()
})
it('renders empty stacked chart and empty flow states', async () => {
const payload = makePayload(new Date())
payload.history.daily = []
getOverview.mockResolvedValue(payload)
getSpendFlow.mockResolvedValue(emptyFlow())
render(<Spend period="week" provider="all" />)
expect(await screen.findByText('No model spend in this range yet.')).toBeInTheDocument()
expect(await screen.findByText('No model-project flow in this range yet.')).toBeInTheDocument()
})
it('renders the flow error path without hiding the rest of spend', async () => {
getOverview.mockResolvedValue(makePayload(new Date()))
getSpendFlow.mockRejectedValue({ kind: 'nonzero', message: 'flow command failed' })
render(<Spend period="week" provider="all" />)
expect(await screen.findByText('codeburn')).toBeInTheDocument()
expect(await screen.findByText('flow command failed')).toBeInTheDocument()
})
it('renders the not-found panel when codeburn is not on PATH', async () => {
getOverview.mockRejectedValue({ kind: 'not-found', message: 'codeburn not found' })
getSpendFlow.mockResolvedValue(emptyFlow())
render(<Spend period="week" provider="all" />)
expect(await screen.findByText('Locate the codeburn CLI')).toBeInTheDocument()
expect(screen.getByText(/isn't on your PATH yet/)).toBeInTheDocument()
})
it('maps stacked segments to the expected model series classes', async () => {
const payload = makePayload(new Date())
payload.history.daily = [
daily('2026-07-10', 25, [
{ name: 'claude-opus-4', cost: 5 },
{ name: 'claude-sonnet-5', cost: 5 },
{ name: 'claude-haiku-4', cost: 5 },
{ name: 'gpt-5.5-codex', cost: 5 },
{ name: 'mystery-model', cost: 5 },
]),
]
getOverview.mockResolvedValue(payload)
getSpendFlow.mockResolvedValue(makeFlow())
const { container } = render(<Spend period="week" provider="all" />)
expect(await screen.findByLabelText('Daily spend by model')).toBeInTheDocument()
expect(container.querySelector('.sbars .s-opus')).toBeInTheDocument()
expect(container.querySelector('.sbars .s-son')).toBeInTheDocument()
expect(container.querySelector('.sbars .s-hai')).toBeInTheDocument()
expect(container.querySelector('.sbars .s-gpt')).toBeInTheDocument()
expect(container.querySelector('.sbars .s-other')).toBeInTheDocument()
expect(screen.getByText('Other')).toBeInTheDocument()
})
it('renders Sankey ribbons with model gradients, neutral other nodes, and shortened labels', async () => {
getOverview.mockResolvedValue(makePayload(new Date()))
getSpendFlow.mockResolvedValue(makeFlow())
const { container } = render(<Spend period="week" provider="all" />)
expect(await screen.findAllByText(/Opus 4.8/)).toHaveLength(2)
expect(screen.getByText(/mobile-app/)).toBeInTheDocument()
expect(screen.queryByText(/Users\/me\/src\/mobile-app/)).not.toBeInTheDocument()
const opusRibbon = container.querySelector('[data-testid="sankey-ribbon"][data-model="claude-opus-4-20260701"]')
expect(opusRibbon?.getAttribute('stroke')).toBe('url(#sankey-claude-opus-4-20260701)')
const opusStop = container.querySelector('linearGradient[id="sankey-claude-opus-4-20260701"] stop')
expect(opusStop?.getAttribute('stop-color')).toBe('#5B8CFF')
const otherNode = container.querySelector('[data-testid="sankey-node"][data-node-id="__other__"]')
expect(otherNode?.getAttribute('fill')).toBe('#5F6780')
})
})

View file

@ -93,7 +93,7 @@ function ProjectsLens({
<Panel title="Daily spend by model">
{daily.length ? <StackedBars daily={daily} /> : <EmptyNote>No model spend in this range yet.</EmptyNote>}
</Panel>
<Panel title="By project" right={`${projects.length} ${projects.length === 1 ? 'project' : 'projects'}`}>
<Panel title="By project" right={projects.length ? `top ${projects.length}` : undefined}>
{projects.length ? (
projects.map((project, i) => (
<ListRow