diff --git a/app/renderer/components/Sankey.tsx b/app/renderer/components/Sankey.tsx index 5da6a878..16bd8c32 100644 --- a/app/renderer/components/Sankey.tsx +++ b/app/renderer/components/Sankey.tsx @@ -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 }) { ( - + ))} {projects.map(node => ( - + ))} {models.map(node => ( - - {node.label} · {fmtUsd(node.cost)} + + {node.displayLabel} · {fmtUsd(node.cost)} ))} {projects.map(node => ( - - {node.label} · {fmtUsd(node.cost)} + + {node.displayLabel} · {fmtUsd(node.cost)} ))} @@ -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 +} diff --git a/app/renderer/components/StackedBars.tsx b/app/renderer/components/StackedBars.tsx index 607b1a3a..fc3f16c3 100644 --- a/app/renderer/components/StackedBars.tsx +++ b/app/renderer/components/StackedBars.tsx @@ -10,6 +10,14 @@ export const SERIES_HEX = { export type SeriesKey = keyof typeof SERIES_HEX +const SERIES_LABELS: Record = { + 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() 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[] }) { ))}
- - - Opus 4.8 - - - - Sonnet 5 - - - - Haiku 4.5 - - - - GPT-5.5 Codex - + {legendSeries.map(series => ( + + + {SERIES_LABELS[series]} + + ))}
) diff --git a/app/renderer/lib/period.test.ts b/app/renderer/lib/period.test.ts new file mode 100644 index 00000000..a5e70e89 --- /dev/null +++ b/app/renderer/lib/period.test.ts @@ -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) + }) +}) diff --git a/app/renderer/lib/period.ts b/app/renderer/lib/period.ts index 96d50b6a..37ccb4e1 100644 --- a/app/renderer/lib/period.ts +++ b/app/renderer/lib/period.ts @@ -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) - } - } -} diff --git a/app/renderer/sections/Spend.test.tsx b/app/renderer/sections/Spend.test.tsx index 732df234..bdd764ab 100644 --- a/app/renderer/sections/Spend.test.tsx +++ b/app/renderer/sections/Spend.test.tsx @@ -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() + 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() + 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() + + 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() + + 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() + + 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() + 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() + + 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') + }) }) diff --git a/app/renderer/sections/Spend.tsx b/app/renderer/sections/Spend.tsx index 97361e73..6fb16f8b 100644 --- a/app/renderer/sections/Spend.tsx +++ b/app/renderer/sections/Spend.tsx @@ -93,7 +93,7 @@ function ProjectsLens({ {daily.length ? : No model spend in this range yet.} - + {projects.length ? ( projects.map((project, i) => (