codeburn/src/format.ts
Resham Joshi b2be8eba56
feat: mark estimated dollars the same way in every view (#1657)
* Mark estimated costs with the same ~ in every view

The ~ marker and legend that report already used now appear wherever a
dollar figure is mostly a guess: the models and sessions CLI output, the
desktop Models, Overview, Sessions and Settings provider rows, the macOS
menu bar model rows and provider tabs, and the Windows tray.

One rule decides the marker everywhere: the estimated portion is at least
1% of the figure. report, overview and the MCP tables switch to it from
"any estimated cent", so a metered Codex row holding a few text-estimated
turns stays unmarked.

JSON is additive: estimatedCostUSD and isEstimated on models rows,
estimatedCost and isEstimated on sessions rows, estimatedCostUSD on
menubar providerDetails rows. Totals are unchanged.

* Skip the ~ marker on figures that print as zero

A sub-cent row that is fully estimated printed as "~$0.00": nothing visible
to qualify. The shared helper now also requires the amount, as the surface
prints it in the active currency, to show a non-zero digit. CLI, desktop,
macOS and Windows helpers all apply it.
2026-10-06 22:27:13 +02:00

124 lines
6.3 KiB
TypeScript

import chalk from 'chalk'
import type { ProjectSummary } from './types.js'
import { behavioralCallCount } from './behavioral-weight.js'
// Re-exported from currency.ts so existing imports from './format.js' keep working.
// The currency-aware version applies exchange rate and symbol automatically.
// Imported locally too since renderStatusBar below uses it directly.
import { formatCost } from './currency.js'
export { formatCost }
/// Prefix a formatted cost with the estimated marker (`~`) when the figure is
/// priced from estimated tokens rather than metered. Keeps the marker identical
/// across the report, overview, and MCP surfaces so a legend line can explain it
/// once. `isEstimated` is typically `isEstimatedCost(entry.cost, entry.estimatedCostUSD)`.
export function markEstimated(costStr: string, isEstimated: boolean): string {
return isEstimated ? `~${costStr}` : costStr
}
export const ESTIMATED_COST_LEGEND = '~ estimated cost (priced from estimated tokens)'
/// A row carries the estimated marker once its estimated portion is at least 1%
/// of its cost: a handful of unmetered calls inside a metered row (a Codex turn
/// with no token record) must not mark the whole row as a guess. `shown` is the
/// amount as the surface prints it; a figure that reads as zero ("$0.00") gets
/// no marker, since there is nothing visible to qualify.
export function isEstimatedCost(costUSD: number, estimatedCostUSD: number | undefined, shown: string = formatCost(costUSD)): boolean {
const estimated = estimatedCostUSD ?? 0
return estimated > 0 && estimated >= costUSD * 0.01 && /[1-9]/.test(shown)
}
/// Shared wording for the durable-cache carry-forward footnote: some of a
/// period's total came from days whose session logs have since expired, but
/// the figure is real (preserved in the durable daily cache). overview.ts and
/// dashboard.tsx both show this so a headline that includes carried days
/// doesn't read as inconsistent with detail views that can only see
/// surviving session files.
export function carriedCostNote(carriedCostUSD: number): string | null {
return carriedCostUSD > 0 ? `includes ${formatCost(carriedCostUSD)} preserved from expired session logs` : null
}
/// Shared wording for the gateway-exclusion footnote. A Vercel AI Gateway row
/// is a daily aggregate the local tools routed through the gateway already
/// report, so it is shown but never added to a total. overview.ts and
/// dashboard.tsx both print this so a headline that is short of the provider
/// list explains itself.
export function excludedGatewayNote(excludedGatewayCostUSD: number): string | null {
return excludedGatewayCostUSD > 0
? `excludes ${formatCost(excludedGatewayCostUSD)} of Vercel AI Gateway daily totals (your local tools may already count it) — include with: codeburn gateway-totals include`
: null
}
export function formatTokens(n: number): string {
// Guard against Infinity / NaN / negatives that would otherwise leak into
// the UI as "Infinity" or "NaN" strings when an upstream calculation glitches.
if (!Number.isFinite(n)) return '?'
if (n < 0) return '0'
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(1)}B`
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
return Math.round(n).toString()
}
/// Returns YYYY-MM-DD for the given date in the process-local timezone. Cheaper than shelling
/// out to Intl.DateTimeFormat for every turn in a loop and avoids the UTC drift that bites
/// `Date.toISOString().slice(0,10)` whenever the user runs this between local midnight and
/// UTC midnight.
function localDateString(d: Date): string {
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${day}`
}
/// Precomputed today/month totals from the durable daily cache. When supplied,
/// the status bar renders these instead of bucketing the live parse, so the
/// figures match the menubar exactly (carried, expired-source days included).
export type StatusBarTotals = {
today: { cost: number; calls: number }
month: { cost: number; calls: number }
}
export function renderStatusBar(projects: ProjectSummary[], totals?: StatusBarTotals): string {
const now = new Date()
const today = localDateString(now)
const monthStart = `${today.slice(0, 7)}-01`
let todayCost = 0, todayCalls = 0, monthCost = 0, monthCalls = 0
if (totals) {
todayCost = totals.today.cost; todayCalls = totals.today.calls
monthCost = totals.month.cost; monthCalls = totals.month.calls
const lines: string[] = ['']
lines.push(` ${chalk.bold('Today')} ${chalk.yellowBright(formatCost(todayCost))} ${chalk.dim(`${todayCalls} calls`)} ${chalk.bold('Month')} ${chalk.yellowBright(formatCost(monthCost))} ${chalk.dim(`${monthCalls} calls`)}`)
lines.push('')
return lines.join('\n')
}
for (const project of projects) {
for (const session of project.sessions) {
for (const turn of session.turns) {
if (turn.assistantCalls.length === 0) continue
// Bucket by the first assistant call's local date -- the moment the cost was
// incurred. Bucketing by `turn.timestamp` (the user message time) drops turns
// that straddle midnight (user asked at 23:58, response arrived at 00:30) and
// disagrees with parseAllSessions' dateRange filter which is also on assistant
// time.
const bucketTs = turn.assistantCalls[0]!.timestamp
if (!bucketTs) continue
const day = localDateString(new Date(bucketTs))
const turnCost = turn.assistantCalls.reduce((s, c) => s + c.costUSD, 0)
// Cost keeps every call; the calls figure counts only behavioral ones,
// so a supplementary-only turn still spends but adds no requests.
const turnCalls = behavioralCallCount(turn.assistantCalls)
if (day === today) { todayCost += turnCost; todayCalls += turnCalls }
if (day >= monthStart) { monthCost += turnCost; monthCalls += turnCalls }
}
}
}
const lines: string[] = ['']
lines.push(` ${chalk.bold('Today')} ${chalk.yellowBright(formatCost(todayCost))} ${chalk.dim(`${todayCalls} calls`)} ${chalk.bold('Month')} ${chalk.yellowBright(formatCost(monthCost))} ${chalk.dim(`${monthCalls} calls`)}`)
lines.push('')
return lines.join('\n')
}