diff --git a/windows/src/App.tsx b/windows/src/App.tsx index 7a472a72..80da43dd 100644 --- a/windows/src/App.tsx +++ b/windows/src/App.tsx @@ -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' && } + {activeInsight === 'calendar' && } {activeInsight === 'pulse' && payload && } {activeInsight === 'stats' && payload && } + {activeInsight === 'optimize' && payload && } {payload?.current && ( <> diff --git a/windows/src/components/CalendarInsight.tsx b/windows/src/components/CalendarInsight.tsx new file mode 100644 index 00000000..ef14d76c --- /dev/null +++ b/windows/src/components/CalendarInsight.tsx @@ -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((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(null) + const [weekCount, setWeekCount] = useState(26) + const [hovered, setHovered] = useState(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 ( +
+
+
+
Daily activity
+
{formatCurrency(stats.total, currency)}
+
+
{stats.activeDays} active days
+
+ +
+
+ {WEEKDAY_LABELS.map((label, i) => {label})} +
+
setHovered(null)}> + {weeks.map(week => ( +
+ {week.days.map(day => ( + setHovered(day.date)} + /> + ))} +
+ ))} +
+
+ +
+
+
{hoveredDay ? prettyDate(hoveredDay.date) : 'Daily detail'}
+
{detailValue(hoveredDay, currency)}
+
+
+
Calls
+
{hoveredDay && !hoveredDay.isFuture ? hoveredDay.calls : '-'}
+
+
+
Tokens
+
+ {hoveredDay && !hoveredDay.isFuture ? formatTokens(hoveredDay.tokens) : '-'} +
+
+
+ +
+
+
Peak day
+
+ {stats.peak ? `${formatCompactCurrency(stats.peak.cost, currency)} on ${monthDay(stats.peak.date)}` : '-'} +
+
+
+
Avg active
+
{formatCompactCurrency(stats.avgActive, currency)}
+
+
+
Streak
+
{stats.streak}d
+
+
+
+ ) +} + +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` +} diff --git a/windows/src/components/Icons.tsx b/windows/src/components/Icons.tsx index 13d9f81c..a60ad120 100644 --- a/windows/src/components/Icons.tsx +++ b/windows/src/components/Icons.tsx @@ -34,6 +34,24 @@ export function ChevronRight(p: IconProps) { return } +export function RetryIcon(p: IconProps) { + return ( + + + + + ) +} + +export function RouteIcon(p: IconProps) { + return ( + + + + + ) +} + export function LeafIcon(p: IconProps) { return ( diff --git a/windows/src/components/InsightPills.tsx b/windows/src/components/InsightPills.tsx index abd71a5d..90efdec9 100644 --- a/windows/src/components/InsightPills.tsx +++ b/windows/src/components/InsightPills.tsx @@ -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 = { 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 diff --git a/windows/src/components/OptimizeInsight.tsx b/windows/src/components/OptimizeInsight.tsx new file mode 100644 index 00000000..96ca19b1 --- /dev/null +++ b/windows/src/components/OptimizeInsight.tsx @@ -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 ( +
+ Nothing to optimize in this period. No retries and no calls that a cheaper model + would have handled. +
+ ) + } + + return ( +
+ {cost > 0 && ( +
+
+
Potential savings
+
{formatCompactCurrency(totalWaste, currency)}
+
+
+
{Math.round((totalWaste / cost) * 100)}% of spend
+
could be optimized
+
+
+ )} + + +
+ ) +} + +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 ( +
+ +
+ {plural(retryTax.retries, 'retry', 'retries')} across {plural(retryTax.editTurns, 'edit')} +
+ {expanded && ( +
+ {retryTax.byModel.map(model => ( +
+ {model.name} + + {model.retriesPerEdit != null && ( + {model.retriesPerEdit.toFixed(1)} ret/edit + )} + {formatCompactCurrency(model.taxUSD, currency)} +
+ ))} +
+ )} +
+ ) +} + +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 ( +
+ + {routingWaste.baselineModel !== '' && ( +
+ vs {routingWaste.baselineModel} @ {formatCompactCurrency(routingWaste.baselineCostPerEdit, currency)}/edit +
+ )} + {expanded && ( +
+ {routingWaste.byModel.map(model => ( +
+ {model.name} + + {formatCompactCurrency(model.costPerEdit, currency)}/edit + {formatCompactCurrency(model.savingsUSD, currency)} +
+ ))} +
+ )} +
+ ) +} diff --git a/windows/src/lib/payload.ts b/windows/src/lib/payload.ts index 0c3c8514..7fcaaead 100644 --- a/windows/src/lib/payload.ts +++ b/windows/src/lib/payload.ts @@ -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 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 diff --git a/windows/src/styles.css b/windows/src/styles.css index 8a9dcdb8..683b7321 100644 --- a/windows/src/styles.css +++ b/windows/src/styles.css @@ -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); }