diff --git a/app/renderer/sections/Overview.test.tsx b/app/renderer/sections/Overview.test.tsx index c777e15e..3f4b2222 100644 --- a/app/renderer/sections/Overview.test.tsx +++ b/app/renderer/sections/Overview.test.tsx @@ -4,8 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { Polled } from '../hooks/usePolled' import { setActiveCurrency } from '../lib/format' -import type { ActReportJson, MenubarPayload, YieldJsonReport } from '../lib/types' -import { Overview, OverviewContent, localDateKey } from './Overview' +import type { ActReportJson, DailyHistoryEntry, MenubarPayload, YieldJsonReport } from '../lib/types' +import { Overview, OverviewContent, deriveSignals, localDateKey } from './Overview' function polled(data: MenubarPayload): Polled { return { data, error: null, loading: false, lastSuccessAt: Date.now(), refresh: vi.fn() } @@ -147,6 +147,30 @@ function makePayload(now: Date): MenubarPayload { } } +function mkDay(date: string, cost: number): DailyHistoryEntry { + return { date, cost, savingsUSD: 0, calls: 10, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, topModels: [] } +} + +/** A payload with an explicit history + current overrides for deriveSignals tests. */ +function signalsPayload(now: Date, over: { + current?: Partial + daily?: DailyHistoryEntry[] + optimize?: MenubarPayload['optimize'] +}): MenubarPayload { + const base = makePayload(now) + return { + ...base, + current: { ...base.current, ...over.current }, + optimize: over.optimize ?? { findingCount: 0, savingsUSD: 0, topFindings: [] }, + history: { daily: over.daily ?? [] }, + } +} + +/** N consecutive days ending today; `cost(i)` sets each day's spend (i = oldest→0). */ +function consecutiveDays(now: Date, count: number, cost: (index: number) => number): DailyHistoryEntry[] { + return Array.from({ length: count }, (_, i) => mkDay(localDateKey(new Date(now.getFullYear(), now.getMonth(), now.getDate() - (count - 1 - i))), cost(i))) +} + describe('Overview', () => { beforeEach(() => { setActiveCurrency({ code: 'USD', symbol: '$', rate: 1 }) @@ -253,7 +277,7 @@ describe('Overview', () => { expect(screen.queryByText('Nearest limit')).not.toBeInTheDocument() }) - it('renders efficiency, cost-per-outcome, and real anomaly widgets', async () => { + it('renders efficiency, cost-per-outcome, and the weekday-spike risk signal', async () => { const now = new Date() const payload = makePayload(now) const today = payload.history.daily.at(-1) @@ -268,8 +292,10 @@ describe('Overview', () => { expect(outcome).not.toBeNull() expect(within(outcome as HTMLElement).getByText('$25.00')).toBeInTheDocument() expect(within(outcome as HTMLElement).getByText('$40.00')).toBeInTheDocument() - const anomalies = screen.getByLabelText('Spend anomalies') - expect(anomalies).toHaveTextContent(/Today's spend is 10× your typical/) + // The weekday-spike anomaly is absorbed into the Signals card as a risk. + const signals = screen.getByLabelText('Coaching signals') + const risks = within(signals).getByText('Risks').closest('.ov-signal-group') as HTMLElement + expect(within(risks).getByText(/Today's spend is 10× your typical/)).toBeInTheDocument() }) it('uses an honest empty state when no realized savings exist', async () => { @@ -437,14 +463,16 @@ describe('Overview', () => { expect(within(rows[1] as HTMLElement).getAllByText('—')).toHaveLength(2) }) - it('suppresses the week-over-week anomaly and MTD card for a custom range', async () => { + it('suppresses the week-over-week signal and MTD card for a custom range', async () => { const now = new Date() const overview = polled(makePayload(now)) const { rerender } = render() - // Baseline (no range): the MTD card and a week-over-week signal are present. + // Baseline (no range): the MTD card, the coach pacing line, and the + // week-over-week Signals entry are all present. expect(await screen.findByText('Month to date')).toBeInTheDocument() expect(screen.getAllByText(/than last week/).length).toBeGreaterThan(0) + expect(screen.getByText(/vs last 7 days/)).toBeInTheDocument() const from = localDateKey(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 2)) const to = localDateKey(now) @@ -453,6 +481,8 @@ describe('Overview', () => { expect(screen.queryByText('Month to date')).not.toBeInTheDocument() expect(screen.queryByText('Projected month')).not.toBeInTheDocument() expect(screen.queryByText(/than last week/)).toBeNull() + // The week-over-week Signals entry is suppressed under a custom range too. + expect(screen.queryByText(/vs last 7 days|vs prior 7 days/)).toBeNull() expect(screen.getByText(/is the biggest driver in this range/)).toBeInTheDocument() }) @@ -484,6 +514,156 @@ describe('Overview', () => { expect(await screen.findByRole('status')).toHaveTextContent('Refresh failed, showing last good data · codeburn exited 1') }) + it('groups current-driven signals into wins and improvements', () => { + const now = new Date() + const wins = deriveSignals(signalsPayload(now, { + current: { + cacheHitPercent: 85, + oneShotRate: 0.82, + localModelSavings: { totalUSD: 15, calls: 4, byModel: [], byProvider: [] }, + }, + optimize: { + findingCount: 2, + savingsUSD: 30, + topFindings: [ + { title: 'Trim CLAUDE.md preamble', impact: 'high', savingsUSD: 12 }, + { title: 'Route trivial edits to Haiku', impact: 'medium', savingsUSD: 8 }, + ], + }, + }), now, false) + expect(wins.wins.map(s => s.text)).toEqual([ + 'Cache hit at 85%, most prompts reuse cache', + '82% one-shot, edits land first try', + '$15.00 saved via local models', + ]) + expect(wins.improvements).toEqual([ + { text: 'Trim CLAUDE.md preamble', trailing: '$12.00' }, + { text: 'Route trivial edits to Haiku', trailing: '$8.00' }, + ]) + expect(wins.risks).toEqual([]) + }) + + it('flags low cache-hit, low one-shot, and heavy retry tax as improvements', () => { + const now = new Date() + const { improvements } = deriveSignals(signalsPayload(now, { + current: { + cacheHitPercent: 40, + oneShotRate: 0.4, + cost: 100, + retryTax: { totalUSD: 30, retries: 5, editTurns: 10, byModel: [] }, + }, + }), now, false) + expect(improvements.map(s => s.text)).toEqual([ + 'Cache hit only 40%, paying for cold prompts', + '40% one-shot, lots of iteration', + 'Retry tax is 30% of spend', + ]) + }) + + it('does not treat a zero cache-hit (no data) as a cold-prompt improvement', () => { + const now = new Date() + const { improvements } = deriveSignals(signalsPayload(now, { + current: { cacheHitPercent: 0, oneShotRate: 0.6 }, + }), now, false) + expect(improvements).toEqual([]) + }) + + it('derives streak and a week-over-week drop as wins from history', () => { + const now = new Date() + // 14 consecutive active days; prior 7 at $20, recent 7 at $5 → spend down 75%. + const daily = consecutiveDays(now, 14, i => (i < 7 ? 20 : 5)) + const { wins } = deriveSignals(signalsPayload(now, { + current: { cacheHitPercent: 60, oneShotRate: 0.6 }, + daily, + }), now, false) + expect(wins.map(s => s.text)).toEqual([ + 'Spend down 75% vs last 7 days', + '14-day usage streak', + ]) + }) + + it('reports weekday spike, week-over-week rise, and month overrun as risks', () => { + const now = new Date(2026, 6, 15) // Jul 15 2026 + // June total = $5 (prior-month baseline); July: prior 7 low, recent 7 high. + const daily = [mkDay('2026-06-11', 5), ...consecutiveDays(now, 14, i => (i < 7 ? 2 : 20))] + const { risks } = deriveSignals(signalsPayload(now, { + current: { cacheHitPercent: 60, oneShotRate: 0.6 }, + daily, + }), now, false) + expect(risks).toHaveLength(3) + expect(risks[0].text).toMatch(/Today's spend is 10× your typical/) + expect(risks[1].text).toBe('Spend up 900% vs prior 7 days') + expect(risks[2].text).toMatch(/^On pace for .* this month, \+\d+% vs last$/) + }) + + it('suppresses week-over-week and projection risks under a custom range, keeping the weekday spike', () => { + const now = new Date(2026, 6, 15) + const daily = [mkDay('2026-06-11', 5), ...consecutiveDays(now, 14, i => (i < 7 ? 2 : 20))] + const payload = signalsPayload(now, { current: { cacheHitPercent: 60, oneShotRate: 0.6 }, daily }) + const { risks } = deriveSignals(payload, now, true) + expect(risks).toHaveLength(1) + expect(risks[0].text).toMatch(/Today's spend is 10× your typical/) + }) + + it('caps each group at three signals', () => { + const now = new Date() + // Five wins would qualify (cache, one-shot, week-down, streak, local); cap keeps 3. + const daily = consecutiveDays(now, 14, i => (i < 7 ? 20 : 5)) + const { wins } = deriveSignals(signalsPayload(now, { + current: { + cacheHitPercent: 85, + oneShotRate: 0.82, + localModelSavings: { totalUSD: 15, calls: 4, byModel: [], byProvider: [] }, + }, + daily, + }), now, false) + expect(wins).toHaveLength(3) + expect(wins.map(s => s.text)).toEqual([ + 'Cache hit at 85%, most prompts reuse cache', + '82% one-shot, edits land first try', + 'Spend down 75% vs last 7 days', + ]) + }) + + it('renders the three-column Signals card with optimize findings under Improvements', async () => { + const now = new Date() + const payload = signalsPayload(now, { + current: { + cacheHitPercent: 85, + oneShotRate: 0.82, + localModelSavings: { totalUSD: 15, calls: 4, byModel: [], byProvider: [] }, + }, + optimize: { + findingCount: 1, + savingsUSD: 12, + topFindings: [{ title: 'Trim CLAUDE.md preamble', impact: 'high', savingsUSD: 12 }], + }, + }) + + render() + + const signals = await screen.findByLabelText('Coaching signals') + const wins = within(signals).getByText('Wins').closest('.ov-signal-group') as HTMLElement + expect(within(wins).getByText(/Cache hit at 85%/)).toBeInTheDocument() + const improvements = within(signals).getByText('Improvements').closest('.ov-signal-group') as HTMLElement + expect(within(improvements).getByText('Trim CLAUDE.md preamble')).toBeInTheDocument() + expect(within(improvements).getByText('$12.00')).toBeInTheDocument() + }) + + it('renders no Signals card when every group is empty', async () => { + const now = new Date() + const payload = signalsPayload(now, { + current: { cacheHitPercent: 60, oneShotRate: 0.6 }, + daily: [], + optimize: { findingCount: 0, savingsUSD: 0, topFindings: [] }, + }) + + render() + + expect(await screen.findByText('Daily spend')).toBeInTheDocument() + expect(screen.queryByLabelText('Coaching signals')).not.toBeInTheDocument() + }) + it('renders section costs in the active non-USD currency (rate applied once, symbol swapped)', async () => { setActiveCurrency({ code: 'EUR', symbol: '€', rate: 0.9 }) const now = new Date() diff --git a/app/renderer/sections/Overview.tsx b/app/renderer/sections/Overview.tsx index a5faffa8..38b47f9c 100644 --- a/app/renderer/sections/Overview.tsx +++ b/app/renderer/sections/Overview.tsx @@ -127,13 +127,47 @@ function CostPerOutcome({ outcome }: { outcome: Polled }) { ) } -type Anomaly = { lead: string; value: string; tail: string } +export type Signal = { text: string; trailing?: string } +export type SignalGroups = { wins: Signal[]; improvements: Signal[]; risks: Signal[] } -function deriveAnomalies(data: MenubarPayload, now: Date, includeWeekOverWeek = true): Anomaly[] { - const anomalies: Anomaly[] = [] +/** + * Client-side port of the menubar's FindingsSection rule set + * (mac/Sources/CodeBurnMenubar/Views/FindingsSection.swift:133-205). Thresholds + * mirror the Swift; the desktop-only weekday-spike anomaly is absorbed as a risk. + * Week-over-week and month-projection rules are suppressed for a custom range. + */ +export function deriveSignals(data: MenubarPayload, now: Date, rangeActive: boolean): SignalGroups { + const daily = data.history.daily + const current = data.current + const wins: Signal[] = [] + const improvements: Signal[] = [] + const risks: Signal[] = [] + + const streak = streakDays(daily, now) + + // Week-over-week: mean of the last 7 active entries vs the prior 7 (matches the + // coach's pacing line). Needs >= 14 entries for both windows to exist. + let weekDelta: number | null = null + if (daily.length >= 14) { + const recent14 = daily.slice(-14) + const weekNow = mean(recent14.slice(-7).map(day => day.cost)) + const weekPrior = mean(recent14.slice(0, 7).map(day => day.cost)) + if (weekPrior > 0) weekDelta = (weekNow - weekPrior) / weekPrior * 100 + } + + // Month projection vs previous calendar month's total. const todayKey = localDateKey(now) - const today = data.history.daily.find(day => day.date === todayKey) - const sameWeekdayCosts = data.history.daily + const monthPrefix = todayKey.slice(0, 7) + const mtd = daily.filter(day => day.date.startsWith(monthPrefix)).reduce((sum, day) => sum + day.cost, 0) + const medianDaily = median(daily.slice(-7).map(day => day.cost)) + const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate() + const projectedMonth = mtd + medianDaily * Math.max(0, daysInMonth - now.getDate()) + const prevPrefix = localDateKey(new Date(now.getFullYear(), now.getMonth() - 1, 1)).slice(0, 7) + const prevMonthTotal = daily.filter(day => day.date.startsWith(prevPrefix)).reduce((sum, day) => sum + day.cost, 0) + + // Weekday spike: today vs the mean of prior same-weekday entries. + const today = daily.find(day => day.date === todayKey) + const sameWeekdayCosts = daily .filter(day => { if (day.date === todayKey) return false const [year, month, date] = day.date.split('-').map(Number) @@ -141,38 +175,97 @@ function deriveAnomalies(data: MenubarPayload, now: Date, includeWeekOverWeek = }) .map(day => day.cost) const typicalWeekday = mean(sameWeekdayCosts) + + // ————— Wins ————— + if (current.cacheHitPercent >= 80) { + wins.push({ text: `Cache hit at ${Math.round(current.cacheHitPercent)}%, most prompts reuse cache` }) + } + if (current.oneShotRate !== null && current.oneShotRate >= 0.75) { + wins.push({ text: `${Math.round(current.oneShotRate * 100)}% one-shot, edits land first try` }) + } + if (!rangeActive && weekDelta !== null && weekDelta < -10) { + wins.push({ text: `Spend down ${Math.round(Math.abs(weekDelta))}% vs last 7 days` }) + } + if (streak >= 5) { + wins.push({ text: `${streak}-day usage streak` }) + } + if (current.localModelSavings.totalUSD > 0) { + wins.push({ text: `${formatUsd(current.localModelSavings.totalUSD)} saved via local models` }) + } + + // ————— Improvements ————— + for (const finding of data.optimize.topFindings.slice(0, 3)) { + improvements.push({ text: finding.title, trailing: formatUsd(finding.savingsUSD) }) + } + if (current.cacheHitPercent > 0 && current.cacheHitPercent < 50) { + improvements.push({ text: `Cache hit only ${Math.round(current.cacheHitPercent)}%, paying for cold prompts` }) + } + if (current.oneShotRate !== null && current.oneShotRate < 0.5) { + improvements.push({ text: `${Math.round(current.oneShotRate * 100)}% one-shot, lots of iteration` }) + } + // Retry-tax share is not a menubar rule; the threshold is the point where the + // efficiency scorecard's retry penalty saturates (retrySpendFraction * 4 == 1). + const retryShare = current.retryTax.totalUSD / Math.max(current.cost, 1e-9) + if (retryShare >= 0.25) { + improvements.push({ text: `Retry tax is ${Math.round(retryShare * 100)}% of spend` }) + } + + // ————— Risks ————— if (today && typicalWeekday > 0 && today.cost > typicalWeekday * 1.8) { const ratio = today.cost / typicalWeekday const weekday = now.toLocaleString('en-US', { weekday: 'long' }) - anomalies.push({ lead: "Today's spend is ", value: `${ratio.toFixed(1).replace(/\.0$/, '')}×`, tail: ` your typical ${weekday}.` }) + risks.push({ text: `Today's spend is ${ratio.toFixed(1).replace(/\.0$/, '')}× your typical ${weekday}` }) + } + if (!rangeActive && weekDelta !== null && weekDelta > 25) { + risks.push({ text: `Spend up ${Math.round(weekDelta)}% vs prior 7 days` }) + } + if (!rangeActive && prevMonthTotal > 0 && projectedMonth > prevMonthTotal * 1.3) { + const overPct = Math.round((projectedMonth - prevMonthTotal) / prevMonthTotal * 100) + risks.push({ text: `On pace for ${formatUsd(projectedMonth)} this month, +${overPct}% vs last` }) } - if (includeWeekOverWeek && data.history.daily.length >= 14) { - const recent14 = data.history.daily.slice(-14) - const currentWeek = mean(recent14.slice(-7).map(day => day.cost)) - const priorWeek = mean(recent14.slice(0, 7).map(day => day.cost)) - if (priorWeek > 0) { - const change = (currentWeek - priorWeek) / priorWeek * 100 - if (Math.abs(change) >= 25) { - anomalies.push({ lead: 'Spend is ', value: `${Math.round(Math.abs(change))}%`, tail: ` ${change >= 0 ? 'higher' : 'lower'} than last week.` }) - } - } - } - - if (data.current.cacheHitPercent < 50) { - anomalies.push({ lead: 'Cache hit is low (', value: `${Math.round(data.current.cacheHitPercent)}%`, tail: '). More of your context is uncached.' }) - } - return anomalies.slice(0, 3) + return { wins: wins.slice(0, 3), improvements: improvements.slice(0, 3), risks: risks.slice(0, 3) } } -function AnomalyCallouts({ anomalies }: { anomalies: Anomaly[] }) { - if (!anomalies.length) return null +const SIGNAL_GROUPS = [ + { + key: 'wins' as const, + label: 'Wins', + icon: <>, + }, + { + key: 'improvements' as const, + label: 'Improvements', + icon: <>, + }, + { + key: 'risks' as const, + label: 'Risks', + icon: <>, + }, +] + +function SignalsCard({ signals }: { signals: SignalGroups }) { + const groups = SIGNAL_GROUPS.filter(group => signals[group.key].length > 0) + if (!groups.length) return null return ( -
- Anomalies -
- {anomalies.map((anomaly, index) =>
{anomaly.lead}{anomaly.value}{anomaly.tail}
)} -
+
+ {groups.map(group => ( +
+
+ + {group.label} +
+
    + {signals[group.key].map((signal, index) => ( +
  • + {signal.text} + {signal.trailing && {signal.trailing}} +
  • + ))} +
+
+ ))}
) } @@ -504,7 +597,7 @@ export function OverviewContent({ const applied = saved > 0 ? (actReport.data?.totals.measuredActions ?? 0) : 0 const localSaved = data.current.localModelSavings.totalUSD // A custom range has no meaningful "vs last week" or month-to-date baseline. - const anomalies = deriveAnomalies(data, now, !rangeActive) + const signals = deriveSignals(data, now, rangeActive) return (
{error && } @@ -544,10 +637,10 @@ export function OverviewContent({
- - + +
diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css index e365672f..0325e89b 100644 --- a/app/renderer/styles/plain.css +++ b/app/renderer/styles/plain.css @@ -529,10 +529,19 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); } .ov-coach-tx { font-size: 12.5px; color: var(--mut); flex: 1; line-height: 1.45; } .ov-coach-tx .num { color: var(--ink); font-weight: 600; } .ov-coach-cta { white-space: nowrap; color: var(--accent-text); text-decoration: underline; text-decoration-color: color-mix(in srgb, var(--accent-text) 42%, transparent); text-underline-offset: 2px; font-size: var(--fs-meta); font-weight: var(--fw-medium); border: 0; background: none; cursor: pointer; } -.ov-anomalies { display: flex; align-items: flex-start; gap: 14px; padding: 9px 13px; } -.ov-anomaly-label { flex: 0 0 auto; color: var(--mut2); font-size: 10px; font-weight: 620; letter-spacing: .06em; line-height: 1.5; text-transform: uppercase; } -.ov-anomaly-list { display: flex; min-width: 0; flex: 1; flex-wrap: wrap; gap: 5px 20px; color: var(--mut); font-size: 11.5px; line-height: 1.35; } -.ov-anomaly-list strong { color: var(--ink); font-weight: 650; font-variant-numeric: tabular-nums; } +.ov-signals { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); overflow: hidden; align-items: stretch; } +.ov-signal-group { min-width: 0; padding: 12px 16px; } +.ov-signal-group + .ov-signal-group { border-left: 1px solid var(--line2); } +.ov-signal-head { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; } +.ov-signal-head svg { width: 13px; height: 13px; flex: 0 0 auto; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.ov-signal-head span { font-size: var(--fs-label); font-weight: var(--fw-strong); letter-spacing: .04em; text-transform: uppercase; } +.ov-signal-group.wins .ov-signal-head { color: var(--ok); } +.ov-signal-group.improvements .ov-signal-head { color: var(--accent-text); } +.ov-signal-group.risks .ov-signal-head { color: var(--warn); } +.ov-signal-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 5px; } +.ov-signal { display: flex; align-items: baseline; gap: 8px; font-size: var(--fs-meta); color: var(--mut); line-height: 1.35; } +.ov-signal > span:first-child { min-width: 0; flex: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.ov-signal-trailing { flex: 0 0 auto; color: var(--ink); font-family: var(--mono); font-variant-numeric: tabular-nums; } .ov-stats3 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); overflow: hidden; align-items: stretch; } .ov-stats3 > * { min-width: 0; padding: 14px 16px; } .ov-stats3 > * + * { border-left: 1px solid var(--line2); } @@ -652,13 +661,14 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); } .ov-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); } .ov-kpi:nth-child(3) { border-right: 0; } .ov-kpi:nth-child(-n+3) { border-bottom: 1px solid var(--line2); } - .ov-insight-band, .ov-analytics-row, .ov-body-grid, .ov-hero-split, .ov-stats3 { grid-template-columns: 1fr; } + .ov-insight-band, .ov-analytics-row, .ov-body-grid, .ov-hero-split, .ov-stats3, .ov-signals { grid-template-columns: 1fr; } .ov-main-column, .ov-side-column { display: contents; } .ov-models-widget { order: 1; } .ov-activities-widget { order: 2; } .ov-chart-widget { order: 3; } .ov-sessions-widget { order: 4; } .ov-hero-split > * + *, .ov-stats3 > * + * { border-top: 1px solid var(--line2); border-left: 0; } + .ov-signal-group + .ov-signal-group { border-top: 1px solid var(--line2); border-left: 0; } } @media (max-width: 600px) { .ov-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } @@ -666,7 +676,6 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); } .ov-kpi:nth-child(even) { border-right: 0; } .ov-kpi:nth-child(-n+4) { border-bottom: 1px solid var(--line2); } .ov-coach { align-items: flex-start; } - .ov-anomalies { flex-direction: column; gap: 5px; } } /* Sessions */