feat(windows): the Calendar and Optimize insights

The two insight pills the popover never had.

Calendar is the contribution grid: one column per week, Monday at the top,
shaded against the busiest visible day so it answers "compared with my own
worst day" rather than against some absolute figure. The week count is
measured from the container rather than fixed, so the grid always ends
flush with the right edge whatever the popover is asked to be. Hovering a
day fills the detail strip underneath with its cost, calls and tokens.

Optimize names the spend the CLI can call avoidable. Retry tax is what
re-asking cost; routing waste is what the same edits would have cost on a
cheaper model. They keep separate hues and separate rows because they are
separate decisions, and only the headline adds them up. Each expands to a
per-model breakdown. With nothing to optimize the pill says so rather
than showing two empty sections.

Both read fields `codeburn status` has been emitting all along and the
payload type simply ignored.
This commit is contained in:
iamtoruk 2026-09-01 18:41:10 -07:00
parent 1dd1298c57
commit 2c1599f3ce
7 changed files with 555 additions and 2 deletions

View file

@ -15,6 +15,8 @@ import type { Provider } from './components/AgentTabStrip'
import { ModelsSection } from './components/ModelsSection'
import { InsightPills, INSIGHT_ORDER, isInsightMode, type InsightMode } from './components/InsightPills'
import { TrendInsight, trendDayCount } from './components/TrendInsight'
import { CalendarInsight } from './components/CalendarInsight'
import { OptimizeInsight } from './components/OptimizeInsight'
import { ForecastInsight } from './components/ForecastInsight'
import { PulseInsight } from './components/PulseInsight'
import { StatsInsight } from './components/StatsInsight'
@ -419,8 +421,10 @@ export function App() {
/>
)}
{activeInsight === 'forecast' && <ForecastInsight days={payload?.history?.daily ?? []} currency={currency} />}
{activeInsight === 'calendar' && <CalendarInsight days={payload?.history?.daily ?? []} currency={currency} />}
{activeInsight === 'pulse' && payload && <PulseInsight payload={payload} currency={currency} />}
{activeInsight === 'stats' && payload && <StatsInsight payload={payload} currency={currency} period={period} />}
{activeInsight === 'optimize' && payload && <OptimizeInsight payload={payload} currency={currency} />}
</div>
{payload?.current && (
<>

View file

@ -0,0 +1,225 @@
import { useLayoutEffect, useRef, useState } from 'react'
import type { DailyEntry } from '../lib/payload'
import type { CurrencyState } from '../lib/currency'
import { formatCompactCurrency, formatCurrency, formatTokens } from '../lib/currency'
import { addDays, formatDateKey, monthDay, prettyDate, startOfDay } from '../lib/dates'
/// Port of ContributionHeatmapInsight in mac/.../Views/HeatmapSection.swift: a GitHub-style
/// grid of the last N weeks, one column per week, Monday at the top. The week count is
/// measured rather than fixed so the grid always ends flush with the right edge.
const CELL = 8
const GAP = 3
const LABEL_WIDTH = 26
/// The gap between the weekday labels and the grid, from the mac HStack spacing.
const LABEL_GAP = 6
const MAX_WEEKS = 52
type Day = {
date: string
cost: number
calls: number
tokens: number
level: number
isToday: boolean
isFuture: boolean
}
type Week = { start: string; days: Day[] }
export function contributionLevel(value: number, maxValue: number): number {
if (value <= 0 || maxValue <= 0) return 0
const ratio = Math.min(Math.max(value / maxValue, 0), 1)
if (ratio < 0.25) return 1
if (ratio < 0.5) return 2
if (ratio < 0.75) return 3
return 4
}
/// Monday of the week containing `date`.
function startOfWeek(date: Date): Date {
return addDays(date, -((date.getDay() + 6) % 7))
}
export function buildWeeks(entries: DailyEntry[], weekCount: number, now = new Date()): Week[] {
const today = startOfDay(now)
const tk = formatDateKey(today)
const visible = Math.min(Math.max(weekCount, 1), MAX_WEEKS)
const byDate = new Map(entries.map(e => [e.date, e]))
const first = addDays(startOfWeek(today), -(visible - 1) * 7)
// The scale is set by the busiest visible day, so the shading answers "compared with my
// own busiest day", not with some absolute figure.
let maxCost = 0
for (let i = 0; i < visible * 7; i++) {
const d = addDays(first, i)
if (d > today) break
maxCost = Math.max(maxCost, byDate.get(formatDateKey(d))?.cost ?? 0)
}
const weeks: Week[] = []
for (let w = 0; w < visible; w++) {
const weekStart = addDays(first, w * 7)
const days: Day[] = []
for (let i = 0; i < 7; i++) {
const d = addDays(weekStart, i)
const key = formatDateKey(d)
const entry = byDate.get(key)
const isFuture = d > today
const cost = isFuture ? 0 : entry?.cost ?? 0
days.push({
date: key,
cost,
calls: isFuture ? 0 : entry?.calls ?? 0,
tokens: isFuture ? 0 : (entry?.inputTokens ?? 0) + (entry?.outputTokens ?? 0),
level: isFuture ? 0 : contributionLevel(cost, maxCost),
isToday: key === tk,
isFuture,
})
}
weeks.push({ start: formatDateKey(weekStart), days })
}
return weeks
}
type Stats = {
total: number
activeDays: number
avgActive: number
peak: Day | null
streak: number
}
export function computeStats(weeks: Week[]): Stats {
const days = weeks.flatMap(w => w.days).filter(d => !d.isFuture)
const active = days.filter(d => d.cost > 0)
const total = active.reduce((s, d) => s + d.cost, 0)
const peak = active.reduce<Day | null>((best, d) => (best && best.cost >= d.cost ? best : d), null)
let streak = 0
for (let i = days.length - 1; i >= 0; i--) {
if (days[i].cost <= 0) break
streak++
}
return {
total,
activeDays: active.length,
avgActive: active.length === 0 ? 0 : total / active.length,
peak,
streak,
}
}
const WEEKDAY_LABELS = ['Mon', '', 'Wed', '', 'Fri', '', 'Sun']
export function CalendarInsight({ days, currency }: { days: DailyEntry[]; currency: CurrencyState }) {
const grid = useRef<HTMLDivElement>(null)
const [weekCount, setWeekCount] = useState(26)
const [hovered, setHovered] = useState<string | null>(null)
useLayoutEffect(() => {
const el = grid.current
if (!el) return
const measure = () => {
const available = Math.max(0, el.clientWidth - LABEL_WIDTH - LABEL_GAP - 4)
const raw = Math.floor((available + GAP) / (CELL + GAP))
setWeekCount(Math.min(Math.max(raw, 1), MAX_WEEKS))
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
return () => observer.disconnect()
}, [])
const weeks = buildWeeks(days, weekCount)
const stats = computeStats(weeks)
const hoveredDay = hovered === null ? null : weeks.flatMap(w => w.days).find(d => d.date === hovered) ?? null
return (
<div className="calendar-insight" ref={grid}>
<div className="insight-header">
<div>
<div className="insight-sublabel">Daily activity</div>
<div className="insight-hero">{formatCurrency(stats.total, currency)}</div>
</div>
<div className="heat-active">{stats.activeDays} active days</div>
</div>
<div className="heat-body">
<div className="heat-weekdays">
{WEEKDAY_LABELS.map((label, i) => <span key={i}>{label}</span>)}
</div>
<div className="heat-weeks" onMouseLeave={() => setHovered(null)}>
{weeks.map(week => (
<div key={week.start} className="heat-week">
{week.days.map(day => (
<span
key={day.date}
className={cellClass(day, hovered === day.date)}
title={helpText(day, currency)}
aria-label={helpText(day, currency)}
onMouseEnter={() => setHovered(day.date)}
/>
))}
</div>
))}
</div>
</div>
<div className="heat-detail">
<div className="heat-detail-main">
<div className="heat-detail-label">{hoveredDay ? prettyDate(hoveredDay.date) : 'Daily detail'}</div>
<div className="heat-detail-value">{detailValue(hoveredDay, currency)}</div>
</div>
<div className="heat-detail-metric">
<div className="heat-detail-label">Calls</div>
<div className="heat-detail-num">{hoveredDay && !hoveredDay.isFuture ? hoveredDay.calls : '-'}</div>
</div>
<div className="heat-detail-metric">
<div className="heat-detail-label">Tokens</div>
<div className="heat-detail-num">
{hoveredDay && !hoveredDay.isFuture ? formatTokens(hoveredDay.tokens) : '-'}
</div>
</div>
</div>
<div className="mini-stats">
<div className="mini-stat">
<div className="mini-stat-label">Peak day</div>
<div className="mini-stat-value">
{stats.peak ? `${formatCompactCurrency(stats.peak.cost, currency)} on ${monthDay(stats.peak.date)}` : '-'}
</div>
</div>
<div className="mini-stat">
<div className="mini-stat-label">Avg active</div>
<div className="mini-stat-value">{formatCompactCurrency(stats.avgActive, currency)}</div>
</div>
<div className="mini-stat">
<div className="mini-stat-label">Streak</div>
<div className="mini-stat-value">{stats.streak}d</div>
</div>
</div>
</div>
)
}
function cellClass(day: Day, isHovered: boolean): string {
return [
'heat-cell',
`heat-l${day.level}`,
day.isFuture ? 'is-future' : '',
day.isToday ? 'is-today' : '',
isHovered ? 'is-hovered' : '',
].filter(Boolean).join(' ')
}
function detailValue(day: Day | null, currency: CurrencyState): string {
if (!day) return 'Hover a day'
if (day.isFuture) return 'Future day'
if (day.cost <= 0 && day.calls === 0) return 'No tracked usage'
return formatCompactCurrency(day.cost, currency)
}
function helpText(day: Day, currency: CurrencyState): string {
if (day.isFuture) return `${prettyDate(day.date)}: future day`
if (day.cost <= 0 && day.calls === 0) return `${prettyDate(day.date)}: no tracked usage`
return `${prettyDate(day.date)}: ${formatCompactCurrency(day.cost, currency)}, ${day.calls} calls, ${formatTokens(day.tokens)} tokens`
}

View file

@ -34,6 +34,24 @@ export function ChevronRight(p: IconProps) {
return <Svg {...p}><path d="M6 3.5 10.5 8 6 12.5" /></Svg>
}
export function RetryIcon(p: IconProps) {
return (
<Svg {...p}>
<path d="M2.5 6.5A5 5 0 0 1 12 5.4M13.5 9.5A5 5 0 0 1 4 10.6" />
<path d="M12.5 2.5v3h-3M3.5 13.5v-3h3" />
</Svg>
)
}
export function RouteIcon(p: IconProps) {
return (
<Svg {...p}>
<path d="M2.5 5h8.5M2.5 11h8.5" />
<path d="M9 2.5 11.5 5 9 7.5M5 8.5 2.5 11 5 13.5" />
</Svg>
)
}
export function LeafIcon(p: IconProps) {
return (
<Svg {...p}>

View file

@ -1,15 +1,19 @@
export type InsightMode = 'plan' | 'trend' | 'forecast' | 'pulse' | 'stats'
export type InsightMode = 'plan' | 'trend' | 'forecast' | 'calendar' | 'pulse' | 'stats' | 'optimize'
export const INSIGHT_LABELS: Record<InsightMode, string> = {
plan: 'Plan',
trend: 'Trend',
forecast: 'Forecast',
calendar: 'Calendar',
pulse: 'Pulse',
stats: 'Stats',
optimize: 'Optimize',
}
/// Same order as the macOS InsightMode enum: Plan first when it is visible.
export const INSIGHT_ORDER: InsightMode[] = ['plan', 'trend', 'forecast', 'pulse', 'stats']
export const INSIGHT_ORDER: InsightMode[] = [
'plan', 'trend', 'forecast', 'calendar', 'pulse', 'stats', 'optimize',
]
export function isInsightMode(value: string | null): value is InsightMode {
return value !== null && value in INSIGHT_LABELS

View file

@ -0,0 +1,127 @@
import { useState } from 'react'
import type { MenubarPayload, RetryTax, RoutingWaste } from '../lib/payload'
import type { CurrencyState } from '../lib/currency'
import { formatCompactCurrency, plural } from '../lib/currency'
import { ChevronRight, RetryIcon, RouteIcon } from './Icons'
/// Port of OptimizeInsight in mac/.../Views/HeatmapSection.swift: the two kinds of spend the
/// CLI can name as avoidable. Retry tax is what re-asking cost; routing waste is what the
/// same edits would have cost on a cheaper model. They are shown apart because they are
/// different decisions, and their sum is only a headline.
export function OptimizeInsight({ payload, currency }: { payload: MenubarPayload; currency: CurrencyState }) {
const retryTax = payload.current.retryTax
const routingWaste = payload.current.routingWaste
const cost = payload.current.cost
const totalWaste = (retryTax?.totalUSD ?? 0) + (routingWaste?.totalSavingsUSD ?? 0)
if (totalWaste <= 0) {
return (
<div className="optimize-empty">
Nothing to optimize in this period. No retries and no calls that a cheaper model
would have handled.
</div>
)
}
return (
<div className="optimize-insight">
{cost > 0 && (
<div className="insight-header optimize-headline">
<div>
<div className="insight-sublabel">Potential savings</div>
<div className="optimize-total">{formatCompactCurrency(totalWaste, currency)}</div>
</div>
<div className="optimize-share">
<div className="optimize-share-pct">{Math.round((totalWaste / cost) * 100)}% of spend</div>
<div className="optimize-share-note">could be optimized</div>
</div>
</div>
)}
<RetryTaxRow retryTax={retryTax} totalCost={cost} currency={currency} />
<RoutingWasteRow routingWaste={routingWaste} totalCost={cost} currency={currency} />
</div>
)
}
function RetryTaxRow({ retryTax, totalCost, currency }: {
retryTax: RetryTax | undefined
totalCost: number
currency: CurrencyState
}) {
const [expanded, setExpanded] = useState(false)
if (!retryTax || retryTax.totalUSD <= 0) return null
return (
<div className="waste-block is-retry">
<button type="button" className="waste-head" aria-expanded={expanded} onClick={() => setExpanded(e => !e)}>
<RetryIcon size={9} className="waste-icon" />
<span className="waste-title">Retry tax</span>
<span className="waste-spacer" />
<span className="waste-total">{formatCompactCurrency(retryTax.totalUSD, currency)}</span>
{totalCost > 0 && (
<span className="waste-share">({Math.round((retryTax.totalUSD / totalCost) * 100)}%)</span>
)}
<ChevronRight size={7} className={`chevron ${expanded ? 'chevron-open' : ''}`} />
</button>
<div className="waste-note">
{plural(retryTax.retries, 'retry', 'retries')} across {plural(retryTax.editTurns, 'edit')}
</div>
{expanded && (
<div className="waste-rows">
{retryTax.byModel.map(model => (
<div key={model.name} className="waste-row">
<span className="waste-row-name">{model.name}</span>
<span className="waste-spacer" />
{model.retriesPerEdit != null && (
<span className="waste-row-note">{model.retriesPerEdit.toFixed(1)} ret/edit</span>
)}
<span className="waste-row-value">{formatCompactCurrency(model.taxUSD, currency)}</span>
</div>
))}
</div>
)}
</div>
)
}
function RoutingWasteRow({ routingWaste, totalCost, currency }: {
routingWaste: RoutingWaste | undefined
totalCost: number
currency: CurrencyState
}) {
const [expanded, setExpanded] = useState(false)
if (!routingWaste || routingWaste.totalSavingsUSD <= 0) return null
return (
<div className="waste-block is-routing">
<button type="button" className="waste-head" aria-expanded={expanded} onClick={() => setExpanded(e => !e)}>
<RouteIcon size={9} className="waste-icon" />
<span className="waste-title">Routing waste</span>
<span className="waste-spacer" />
<span className="waste-total">{formatCompactCurrency(routingWaste.totalSavingsUSD, currency)}</span>
{totalCost > 0 && (
<span className="waste-share">({Math.round((routingWaste.totalSavingsUSD / totalCost) * 100)}%)</span>
)}
<ChevronRight size={7} className={`chevron ${expanded ? 'chevron-open' : ''}`} />
</button>
{routingWaste.baselineModel !== '' && (
<div className="waste-note">
vs {routingWaste.baselineModel} @ {formatCompactCurrency(routingWaste.baselineCostPerEdit, currency)}/edit
</div>
)}
{expanded && (
<div className="waste-rows">
{routingWaste.byModel.map(model => (
<div key={model.name} className="waste-row">
<span className="waste-row-name">{model.name}</span>
<span className="waste-spacer" />
<span className="waste-row-note">{formatCompactCurrency(model.costPerEdit, currency)}/edit</span>
<span className="waste-row-value">{formatCompactCurrency(model.savingsUSD, currency)}</span>
</div>
))}
</div>
)}
</div>
)
}

View file

@ -17,6 +17,10 @@ export type MenubarPayload = {
/// Counterfactual spend avoided by routing calls to a local model, from the
/// mappings `codeburn model-savings` keeps. Absent on older CLI payloads.
localModelSavings?: LocalModelSavings
/// What re-asking cost, and what the same edits would have cost on a cheaper model.
/// Both absent on older CLI payloads.
retryTax?: RetryTax
routingWaste?: RoutingWaste
providers: Record<string, number>
providerDetails?: Array<{
id: string
@ -54,6 +58,27 @@ export type LocalModelSavings = {
calls: number
}
export type RetryTax = {
totalUSD: number
retries: number
editTurns: number
byModel: Array<{ name: string; taxUSD: number; retries: number; retriesPerEdit?: number | null }>
}
export type RoutingWaste = {
totalSavingsUSD: number
baselineModel: string
baselineCostPerEdit: number
byModel: Array<{
name: string
costPerEdit: number
editTurns: number
actualUSD: number
counterfactualUSD: number
savingsUSD: number
}>
}
export type DailyModel = {
name: string
cost: number

View file

@ -38,6 +38,8 @@
--menu-shadow: 0 8px 28px rgba(0, 0, 0, 0.18), 0 1px 3px rgba(0, 0, 0, 0.10);
--icon-contrast: #FFFFFF;
--danger: #C83F2C;
/* Routing waste, from the mac OptimizeInsight purple. */
--routing-ink: #8944AB;
/* Quota severity, from QuotaSummary.Severity: under 50 green, then yellow, orange, red.
Three sets, because one colour cannot do three jobs here. The bare token is the bar
@ -113,6 +115,7 @@
--sev-danger-ink: #FF453A;
--sev-critical-tip: #C2610A;
--sev-danger-tip: #C83F2C;
--routing-ink: #BF5AF2;
--icon-contrast: #1C1816;
color-scheme: dark;
}
@ -154,6 +157,7 @@
--sev-danger-ink: #FF453A;
--sev-critical-tip: #C2610A;
--sev-danger-tip: #C83F2C;
--routing-ink: #BF5AF2;
--icon-contrast: #1C1816;
color-scheme: dark;
}
@ -869,6 +873,152 @@ code { font-family: var(--font-mono); }
.bar-tooltip-tokens { font-family: var(--font-mono); font-size: 9.5px; color: var(--tooltip-fg-2); }
.bar-tooltip-split { font-family: var(--font-mono); font-size: 9px; color: var(--tooltip-fg-3); }
/* Calendar heatmap. Cell 8, gap 3, weekday gutter 26, from ContributionHeatmapInsight. */
.calendar-insight { display: flex; flex-direction: column; gap: 10px; }
.heat-active { font-size: 10.5px; font-weight: 500; color: var(--brand-accent); font-variant-numeric: tabular-nums; }
.heat-body { display: flex; align-items: flex-start; gap: 6px; }
.heat-weekdays {
display: flex;
flex-direction: column;
gap: 3px;
width: 26px;
flex: 0 0 26px;
}
.heat-weekdays span {
height: 8px;
line-height: 8px;
text-align: right;
font-size: 8.5px;
font-weight: 500;
color: var(--label-3);
}
.heat-weeks { display: flex; gap: 3px; flex: 1; justify-content: flex-end; }
.heat-week { display: flex; flex-direction: column; gap: 3px; }
.heat-cell {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--fill-15);
box-shadow: inset 0 0 0 0 transparent;
transition: transform 100ms ease-out;
}
.heat-l1 { background: color-mix(in srgb, var(--brand-accent) 30%, transparent); }
.heat-l2 { background: color-mix(in srgb, var(--brand-accent) 48%, transparent); }
.heat-l3 { background: color-mix(in srgb, var(--brand-accent) 66%, transparent); }
.heat-l4 { background: color-mix(in srgb, var(--brand-accent) 88%, transparent); }
.heat-cell.is-future { background: var(--fill-06); }
.heat-cell.is-today { box-shadow: inset 0 0 0 1px var(--brand-accent); }
.heat-cell.is-hovered {
background: var(--brand-accent);
box-shadow: inset 0 0 0 1px var(--brand-accent);
transform: scale(1.35);
}
.heat-detail {
display: flex;
align-items: center;
gap: 12px;
min-height: 42px;
padding: 7px 9px;
border-radius: var(--radius-pill);
background: var(--fill-06);
}
.heat-detail-main { flex: 1; min-width: 0; }
.heat-detail-metric { min-width: 42px; text-align: right; }
.heat-detail-label { font-size: 9px; font-weight: 500; color: var(--label-3); }
.heat-detail-main .heat-detail-label { font-size: 10px; }
.heat-detail-value {
font-size: 13px;
font-weight: 600;
color: var(--label);
font-variant-numeric: tabular-nums;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.heat-detail-num {
font-family: var(--font-mono);
font-size: 11px;
font-weight: 600;
color: var(--label);
}
/* Optimize. Retry tax and routing waste keep their own hues, as on the mac, so the two
kinds of avoidable spend never read as one pot. */
.optimize-insight { display: flex; flex-direction: column; gap: 12px; }
.optimize-empty { font-size: 11px; line-height: 1.45; color: var(--label-2); }
.optimize-headline { padding-bottom: 2px; }
.optimize-total {
font-family: var(--font-display);
font-size: 24px;
font-weight: 700;
letter-spacing: -0.5px;
font-variant-numeric: tabular-nums;
color: var(--sev-critical-ink);
}
.optimize-share { text-align: right; }
.optimize-share-pct { font-size: 11px; font-weight: 600; color: var(--sev-critical-ink); }
.optimize-share-note { font-size: 9.5px; color: var(--label-3); }
.waste-block {
display: flex;
flex-direction: column;
gap: 4px;
padding-top: 10px;
border-top: 1px solid var(--separator-soft);
}
.waste-head {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
padding: 0;
border: 0;
background: transparent;
color: inherit;
cursor: pointer;
text-align: left;
}
.waste-spacer { flex: 1; }
.waste-title { font-size: 10px; font-weight: 500; color: var(--label-3); }
.waste-total {
font-family: var(--font-mono);
font-size: 11px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.waste-share { font-size: 9.5px; color: var(--label-3); }
.waste-note { font-size: 9.5px; color: var(--label-3); }
.is-retry .waste-icon, .is-retry .waste-total { color: var(--sev-critical-ink); }
.is-routing .waste-icon, .is-routing .waste-total { color: var(--routing-ink); }
.waste-rows { display: flex; flex-direction: column; gap: 3px; }
.waste-row {
display: flex;
align-items: center;
gap: 8px;
padding: 2px 6px;
border-radius: var(--radius-util);
}
.is-retry .waste-row { background: rgba(255, 149, 0, 0.07); }
.is-routing .waste-row { background: rgba(175, 82, 222, 0.07); }
.waste-row-name {
font-size: 9.5px;
font-weight: 500;
color: var(--label-2);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.waste-row-note { font-size: 9px; color: var(--label-3); }
.waste-row-value {
font-family: var(--font-mono);
font-size: 10px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.is-retry .waste-row-value { color: var(--sev-critical-ink); }
.is-routing .waste-row-value { color: var(--routing-ink); }
.mini-stats { display: flex; gap: 14px; }
.mini-stat { flex: 1; min-width: 0; }
.mini-stat-label { font-size: 9.5px; font-weight: 500; color: var(--label-3); }