feat(app): send the CLI's telemetry snapshot and a few interaction events

The daily usage_snapshot event now carries the payload's
telemetrySnapshot verbatim, with the old renderer builder kept as the
fallback for an older CLI. Five name-only events join it: optimize_apply
with the fix kind, plan_set with the provider, export with the format,
compare_view with the two models, and settings_change with the setting
and its enum or boolean value.

The props sanitizer had allowed one level of arrays of flat objects and
would have stripped the snapshot's nested model and task rows; it walks
plain objects recursively now, five levels deep at most and a thousand
leaves per event, leaves still short strings, finite numbers and
booleans only. The README gains a Telemetry section listing every event
and field and how to turn it off.
This commit is contained in:
iamtoruk 2026-09-03 01:18:23 -07:00
parent e3dd333949
commit 2b06a3a5e4
14 changed files with 342 additions and 51 deletions

View file

@ -2,6 +2,9 @@
## Unreleased
### Added
- **The CLI now computes the anonymous usage aggregate the desktop app and the Windows tray send, so both report the identical shape.** `codeburn status --format menubar-json` gains a `telemetrySnapshot` block (schema 2) built by `src/telemetry-snapshot.ts` from the payload and its own turn-level reports. Its headline signal is the model x task cross: up to 8 models, each with a cost bucket, a turn bucket, a one-shot rate and up to 6 task categories with their share of that model's turns, alongside up to 12 task categories with their top models, providers, MCP servers, skills, tools, a session count and median-length bucket, and cache-hit and retry-tax shares. Every magnitude is a bucket label, never an exact dollar amount, count or duration, and every name is a model or configuration identifier: nothing in the block is derived from a working directory, project name, branch name, file path or message text. The desktop app sends the block verbatim as the once-daily `usage_snapshot` event when the CLI provides it and falls back to its own renderer-side builder for an older CLI, and it adds five name-only interaction events (`optimize_apply`, `plan_set`, `export`, `compare_view`, `settings_change`). Telemetry remains consent-gated behind the onboarding screen, off by default in the EU/EEA/UK/CH, and switchable at any time in Settings > Privacy & data; README documents exactly what each event carries. `STATUS_SNAPSHOT_VERSION` moves to 4 so persisted status snapshots re-derive with the new field.
## 0.9.23 - 2026-08-29
### Added

View file

@ -76,7 +76,7 @@ You pay for Claude, Codex, Cursor, and a stack of other AI tools. The bill tells
CodeBurn does. It reads the session files your tools already write to disk and breaks down every token and dollar by **task, model, tool, and project**, across **41 AI tools**.
Everything runs locally. No wrapper, no proxy, no API keys, nothing leaves your machine. Pricing comes from [LiteLLM](https://github.com/BerriAI/litellm), refreshed daily.
Everything runs locally. No wrapper, no proxy, no API keys, nothing leaves your machine. Pricing comes from [LiteLLM](https://github.com/BerriAI/litellm), refreshed daily. The optional desktop app can send an anonymous, bucketed usage report if you say yes to it; see [Telemetry](#telemetry).
<p align="center">
<a href="#quick-start">Quick start</a> ·
@ -89,7 +89,8 @@ Everything runs locally. No wrapper, no proxy, no API keys, nothing leaves your
<a href="#supported-tools">Supported tools</a> ·
<a href="#commands">Commands</a> ·
<a href="#features">Features</a> ·
<a href="#how-it-reads-your-data">How it reads data</a>
<a href="#how-it-reads-your-data">How it reads data</a> ·
<a href="#telemetry">Telemetry</a>
</p>
## Quick start
@ -778,6 +779,64 @@ CodeBurn deduplicates messages (by API message ID for Claude, by cumulative toke
</details>
## Telemetry
<details>
<summary><strong>What the desktop app sends, and how to turn it off</strong></summary>
The **CLI sends nothing.** No wrapper, no proxy, no phoning home.
The **desktop app and the Windows tray** can send an anonymous usage report, and only after you
decide on the first-launch consent screen. The toggle defaults to **off** in the EU, EEA, UK and
Switzerland, and anywhere the region is unknown; **on** elsewhere. Either way it is your call, and
you can change it any time in **Settings > Privacy & data > Anonymous telemetry**. Turning it off
stops all sending, clears anything queued, and mints a fresh install id so past and future reports
cannot be linked.
The only identifier is a random id generated on your machine. Events carry the calendar day, never
a clock time. Alongside each batch go the app version, platform, architecture and country.
**`usage_snapshot`** goes out at most once per calendar day. It is computed by the CLI so the app
and the tray report the identical shape, and every magnitude in it is a bucket, never an exact
figure:
| Field | What it carries |
|-------|-----------------|
| `schema`, `period` | Snapshot version, and the period label you were looking at (for example `30 Days`) |
| `providerCount`, `costBucket` | How many providers had usage, and total spend as a range: `<1`, `1-10`, `10-50`, `50-200`, `200-1k`, `1k+` USD |
| `models` | Up to 8 model names, each with its cost bucket, turn-count bucket, one-shot rate, and up to 6 task categories with a turn bucket and share of that model's turns |
| `categories` | Up to 12 task category names (Coding, Debugging, Planning, …) with a turn bucket, one-shot rate, and up to 3 model names |
| `providers` | Up to 8 provider names with a cost bucket each |
| `mcpServers`, `skills`, `tools` | Up to 12 names each with a call-count bucket: `1-10`, `10-100`, `100-1k`, `1k+` |
| `sessions` | Session count bucket, and median session length as a bucket: `<5`, `5-15`, `15-60`, `60-240`, `240+` minutes |
| `efficiency` | Cache hit rate and retry tax as shares of the total, to two decimals |
The other events are name-only:
| Event | Fields |
|-------|--------|
| `app_open`, `app_close` | Session length in whole minutes |
| `section_view` | Which section you opened (`overview`, `spend`, …) |
| `cold_start` | Milliseconds to the first painted overview, and whether it timed out |
| `cli_error` | Error kind and the command name, capped at 20 per kind per day |
| `optimize_apply` | The finding id you took a fix for (`unused-mcp`, `claude-md-too-long`, …) and the fix type |
| `plan_set` | Provider and plan preset id |
| `export` | Format (`csv` or `json`) and provider |
| `compare_view` | The two model names being compared |
| `settings_change` | Setting name and its new boolean or enum value |
**Never collected:** prompts, code, file contents, file or folder names, project names, branch names,
working directories, session titles, PR links, API keys, exact dollar amounts, exact counts, clock
times, IP-based location beyond the country, or anything that could identify you or your employer.
The snapshot is built from bucket labels and configuration identifiers only, and a whitelist
sanitizer drops anything that is not a short string, a finite number or a boolean before it leaves
the machine.
**To turn it off:** decline on the consent screen, or open **Settings > Privacy & data** and switch
**Anonymous telemetry** off.
</details>
## Environment Variables
<details>

View file

@ -110,7 +110,7 @@ describe('events', () => {
telemetry.track('totally_made_up', { a: 1 })
telemetry.track('section_view', {
section: 'x'.repeat(500),
junk: { nested: 'object' },
junk: new Date(),
fn: () => {},
nan: NaN,
ok: 42,
@ -128,6 +128,46 @@ describe('events', () => {
expect(body.events[0]!.day).toMatch(/^\d{4}-\d{2}-\d{2}$/)
})
it('keeps the daily snapshot shape but drops anything deeper or bigger', async () => {
const { telemetry, posts } = make()
telemetry.completeOnboarding(true)
telemetry.track('usage_snapshot', {
schema: 2,
models: [{ name: 'Sonnet 4.5', tasks: [{ name: 'Coding', share: 0.75 }] }],
categories: [{ name: 'Coding', topModels: ['Sonnet 4.5', 'Opus 4.6'] }],
sessions: { countBucket: '100-1k' },
// One container deeper than the snapshot's own deepest shape.
tooDeep: [{ a: [{ b: [{ c: 1 }] }] }],
wide: Array.from({ length: 40 }, (_, i) => ({ name: `n${i}` })),
})
await telemetry.flush()
const props = (posts[0]!.body as { events: Array<{ name: string; props: Record<string, unknown> }> }).events[1]!.props
expect(props.models).toEqual([{ name: 'Sonnet 4.5', tasks: [{ name: 'Coding', share: 0.75 }] }])
expect(props.categories).toEqual([{ name: 'Coding', topModels: ['Sonnet 4.5', 'Opus 4.6'] }])
expect(props.sessions).toEqual({ countBucket: '100-1k' })
expect(props.tooDeep).toBeUndefined()
expect(props.wide).toHaveLength(12)
})
it('accepts the name-only interaction events', async () => {
const { telemetry, posts } = make()
telemetry.completeOnboarding(true)
telemetry.track('optimize_apply', { kind: 'claude-md-too-long', fixType: 'file-content' })
telemetry.track('plan_set', { provider: 'cursor', plan: 'cursor-pro' })
telemetry.track('export', { format: 'json', provider: 'all' })
telemetry.track('compare_view', { modelA: 'Sonnet 4.5', modelB: 'Opus 4.6' })
telemetry.track('settings_change', { setting: 'theme', value: 'dark' })
await telemetry.flush()
const events = (posts[0]!.body as { events: Array<{ name: string; props: Record<string, unknown> }> }).events
expect(events.map(event => event.name)).toEqual([
'app_open', 'optimize_apply', 'plan_set', 'export', 'compare_view', 'settings_change',
])
expect(events[1]!.props).toEqual({ kind: 'claude-md-too-long', fixType: 'file-content' })
expect(events[5]!.props).toEqual({ setting: 'theme', value: 'dark' })
})
it('stamps events with the LOCAL calendar day, not the UTC day', async () => {
const savedTZ = process.env.TZ
process.env.TZ = 'America/Los_Angeles' // UTC-07/08

View file

@ -14,7 +14,12 @@ import { dirname, join } from 'node:path'
// Either way the user decides on the consent screen.
// - The only identifier is a random UUID minted locally. No fingerprinting.
// - Events carry day-granularity timestamps only, and props pass a whitelist
// sanitizer (short strings / finite numbers / booleans, capped arrays).
// sanitizer: every leaf is a short string, a finite number or a boolean, and
// the nesting, key count and array length are all capped. Anything else
// (functions, dates, deep trees) is dropped rather than encoded.
// - The richest event is `usage_snapshot`, the CLI-computed daily aggregate in
// `payload.telemetrySnapshot`. It is bucketed and name-only by construction:
// see src/telemetry-snapshot.ts for the contract it holds.
// - Dev / unpackaged builds never send (CODEBURN_TELEMETRY_DEV=1 overrides
// for end-to-end testing).
@ -40,6 +45,13 @@ export const EVENT_NAMES = new Set([
'cold_start',
'usage_snapshot',
'cli_error',
// Name-only interaction events. Props carry a fix id, a provider, a format,
// a model name or a setting name and its boolean/enum value, never free text.
'optimize_apply',
'plan_set',
'export',
'compare_view',
'settings_change',
])
const MAX_QUEUE = 200
@ -47,6 +59,13 @@ const MAX_CLI_ERRORS_PER_KIND_PER_DAY = 20
const MAX_STRING = 64
const MAX_ARRAY = 12
const MAX_KEYS = 16
// Containers may nest this deep below the props object. The daily usage
// snapshot is the deepest shape we send: props -> models[] -> model -> tasks[]
// -> task. Anything deeper is dropped whole.
const MAX_DEPTH = 5
// Belt and braces on top of the per-level caps: one event can never encode more
// than this many leaf values, whatever shape it arrives in.
const MAX_LEAVES = 1000
export type TelemetryStatus = {
installId: string
@ -99,47 +118,54 @@ function loadCliErrorBudget(day: unknown, counts: unknown): Pick<PersistedState,
return { cliErrorDay: day, cliErrorCounts: cleanCounts }
}
function sanitizeValue(value: unknown): unknown | undefined {
if (typeof value === 'string') return value.slice(0, MAX_STRING)
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
if (typeof value === 'boolean') return value
return undefined
type LeafBudget = { left: number }
function sanitizeValue(value: unknown, depth: number, budget: LeafBudget): unknown | undefined {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
if (budget.left <= 0) return undefined
if (typeof value === 'number' && !Number.isFinite(value)) return undefined
budget.left--
return typeof value === 'string' ? value.slice(0, MAX_STRING) : value
}
if (depth >= MAX_DEPTH) return undefined
if (Array.isArray(value)) {
const items: unknown[] = []
for (const entry of value.slice(0, MAX_ARRAY)) {
const sv = sanitizeValue(entry, depth + 1, budget)
if (sv !== undefined) items.push(sv)
}
return items.length > 0 ? items : undefined
}
// Plain objects only. A Date, Map, function or class instance carries state
// we have no whitelist for, so it is dropped rather than walked.
if (value === null || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype) return undefined
const flat = sanitizeObject(value as Record<string, unknown>, depth + 1, budget)
return Object.keys(flat).length > 0 ? flat : undefined
}
/** Whitelist sanitizer: primitives, plus one level of arrays-of-flat-objects. */
export function sanitizeProps(props: unknown): Record<string, unknown> {
if (!props || typeof props !== 'object' || Array.isArray(props)) return {}
function sanitizeObject(obj: Record<string, unknown>, depth: number, budget: LeafBudget): Record<string, unknown> {
const out: Record<string, unknown> = {}
let keys = 0
for (const [key, value] of Object.entries(props as Record<string, unknown>)) {
for (const [key, value] of Object.entries(obj)) {
if (keys >= MAX_KEYS) break
const k = key.slice(0, MAX_STRING)
if (Array.isArray(value)) {
const items: Record<string, unknown>[] = []
for (const entry of value.slice(0, MAX_ARRAY)) {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
const flat: Record<string, unknown> = {}
let inner = 0
for (const [ik, iv] of Object.entries(entry as Record<string, unknown>)) {
if (inner >= MAX_KEYS) break
const sv = sanitizeValue(iv)
if (sv === undefined) continue
flat[ik.slice(0, MAX_STRING)] = sv
inner++
}
if (Object.keys(flat).length > 0) items.push(flat)
}
if (items.length > 0) { out[k] = items; keys++ }
continue
}
const sv = sanitizeValue(value)
const sv = sanitizeValue(value, depth, budget)
if (sv === undefined) continue
out[k] = sv
out[key.slice(0, MAX_STRING)] = sv
keys++
}
return out
}
/** Whitelist sanitizer. Keeps short strings, finite numbers and booleans, plus
* plain objects and arrays of them nested up to MAX_DEPTH, each level capped by
* MAX_KEYS / MAX_ARRAY and the whole event by MAX_LEAVES. Everything else is
* dropped. Deep enough for the daily usage snapshot's model x task cross and
* nothing more. */
export function sanitizeProps(props: unknown): Record<string, unknown> {
if (!props || typeof props !== 'object' || Array.isArray(props)) return {}
return sanitizeObject(props as Record<string, unknown>, 1, { left: MAX_LEAVES })
}
export class Telemetry {
private readonly deps: Required<Pick<Deps, 'stateDir' | 'country' | 'isPackaged' | 'appVersion'>> & Deps
private state: PersistedState

View file

@ -40,6 +40,7 @@ const mocks = vi.hoisted(() => ({
getAliases: vi.fn(),
setCurrency: vi.fn(),
resetCurrency: vi.fn(),
telemetryTrack: vi.fn<(name: string, props?: Record<string, unknown>) => Promise<boolean>>(),
}))
vi.mock('./lib/ipc', async orig => {
@ -191,6 +192,7 @@ function installDefaultMocks() {
mocks.getAliases.mockResolvedValue([])
mocks.setCurrency.mockResolvedValue({ ok: true, stdout: '', stderr: '' })
mocks.resetCurrency.mockResolvedValue({ ok: true, stdout: '', stderr: '' })
mocks.telemetryTrack.mockResolvedValue(true)
}
describe('App shortcuts', () => {
@ -1077,6 +1079,53 @@ describe('currency correctness', () => {
})
})
describe('usage_snapshot dispatch', () => {
beforeEach(() => {
installDefaultMocks()
localStorage.clear()
localStorage.setItem('codeburn.defaultPeriod', '30days')
})
it('forwards the CLI-computed snapshot verbatim, with no by-model join', async () => {
const payload = overviewPayload()
// Opaque to the renderer: whatever the CLI put here is what goes out.
payload.telemetrySnapshot = { schema: 2, period: 'Last 30 days', costBucket: '10-50', models: [] }
mocks.getOverview.mockResolvedValue(payload)
render(<App />)
await waitFor(() => expect(mocks.telemetryTrack).toHaveBeenCalledWith('usage_snapshot', payload.telemetrySnapshot))
expect(mocks.getModels).not.toHaveBeenCalled()
})
it('falls back to the renderer builder when an older CLI omits the field', async () => {
const payload = overviewPayload()
payload.current.topModels = [{ name: 'claude-opus-4-8', cost: 30, savingsUSD: 0, savingsBaselineModel: '', calls: 400 }]
mocks.getOverview.mockResolvedValue(payload)
mocks.getModels.mockResolvedValue([])
render(<App />)
await waitFor(() => expect(mocks.telemetryTrack).toHaveBeenCalledWith('usage_snapshot', expect.objectContaining({
period: 'Last 30 days',
costBucket: '10-50',
})))
expect(mocks.getModels).toHaveBeenCalled()
})
it('sends nothing when the snapshot field is explicitly null and the payload is empty', async () => {
const payload = overviewPayload()
payload.telemetrySnapshot = null
mocks.getOverview.mockResolvedValue(payload)
mocks.getModels.mockResolvedValue([])
render(<App />)
// A null snapshot is an older/failed CLI, not a reason to skip the event.
await waitFor(() => expect(mocks.telemetryTrack).toHaveBeenCalledWith('usage_snapshot', expect.objectContaining({ period: 'Last 30 days' })))
})
})
describe('usage_snapshot telemetry props', () => {
// The renderer builds these props; the main-process sanitizer (sanitizeProps)
// is the last gate before the wire. Test the composition, which is what ships.

View file

@ -19,6 +19,7 @@ import { formatCompact, formatUsd, setActiveCurrency } from './lib/format'
import { motionClass } from './lib/motion'
import { clearOverviewHeadlines, readOverviewHeadline, writeOverviewHeadline } from './lib/overviewSnapshot'
import { codeburn } from './lib/ipc'
import { trackEvent } from './lib/track'
import { isModifierChord, shortcutLabel } from './lib/platform'
import { localDateKey, PERIOD_LABELS } from './lib/period'
import { readDisabledProviders } from './lib/providers'
@ -71,7 +72,11 @@ export function topCategoryByModel(rows: ModelReportRow[]): Map<string, string>
return map
}
/** The once-per-day anonymous aggregate (main process dedups by calendar day). */
/** The once-per-day anonymous aggregate, built in the renderer.
* Fallback only: current CLIs compute the richer `payload.telemetrySnapshot`
* (src/telemetry-snapshot.ts) so the desktop app and the Windows tray send the
* identical shape. This builder covers a CLI that predates that field.
* The main process dedups the event by calendar day either way. */
export function usageSnapshotProps(payload: MenubarPayload, modelCategories?: Map<string, string>): Record<string, unknown> {
return {
period: payload.current.label,
@ -354,16 +359,13 @@ function AppMain() {
if (typeof codeburn.completeOnboarding === 'function') void codeburn.completeOnboarding(enabled).catch(() => {})
}, [])
const trackEvent = useCallback((name: string, props?: Record<string, unknown>) => {
if (typeof codeburn.telemetryTrack === 'function') void codeburn.telemetryTrack(name, props).catch(() => {})
}, [])
// Once-per-day anonymous usage aggregate, only from the canonical view
// (all providers, standard period, no config scope) so buckets are stable.
// Gated to the first qualifying render per calendar day so the extra by-model
// report fetch runs at most once/day, not on every poll (main also dedups the
// event). The fetch enriches each model with its dominant task category; if it
// fails we still emit the snapshot, just without the model x category cross.
// Gated to the first qualifying render per calendar day (main also dedups the
// event). Current CLIs hand us the finished, already-bucketed snapshot and we
// forward it verbatim; only an older CLI falls back to the renderer builder,
// which needs an extra by-model report fetch to get the model x category cross
// and still emits without it if that fetch fails.
const snapshotDayRef = useRef<string | null>(null)
useEffect(() => {
if (!overview.data || provider !== 'all' || customRange || claudeConfigSource || scope !== 'local') return
@ -371,6 +373,11 @@ function AppMain() {
if (snapshotDayRef.current === today) return
snapshotDayRef.current = today
const payload = overview.data
const fromCli = payload.telemetrySnapshot
if (fromCli && typeof fromCli === 'object') {
trackEvent('usage_snapshot', fromCli)
return
}
void (async () => {
let modelCategories: Map<string, string> | undefined
try {
@ -378,7 +385,7 @@ function AppMain() {
} catch { /* degrade: emit the snapshot without per-model topCategory */ }
trackEvent('usage_snapshot', usageSnapshotProps(payload, modelCategories))
})()
}, [overview.data, provider, customRange, claudeConfigSource, scope, period, trackEvent])
}, [overview.data, provider, customRange, claudeConfigSource, scope, period])
useEffect(() => {
let saved: string | null = null
@ -589,7 +596,7 @@ function AppMain() {
setSettingsPane(pane)
setSection(next)
trackEvent('section_view', { section: next })
}, [trackEvent])
}, [])
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {

13
app/renderer/lib/track.ts Normal file
View file

@ -0,0 +1,13 @@
import { codeburn } from './ipc'
/** Fire-and-forget consent-gated telemetry. The main process decides whether
* anything is sent (see app/electron/telemetry.ts); the renderer only names the
* event. Nothing about it is load-bearing, so a preload that predates the
* bridge method, returns nothing, or throws must degrade to "no tracking"
* rather than take a click handler down with it. */
export function trackEvent(name: string, props?: Record<string, unknown>): void {
if (typeof codeburn.telemetryTrack !== 'function') return
try {
void Promise.resolve(codeburn.telemetryTrack(name, props)).catch(() => {})
} catch { /* a bridge that throws synchronously is still just no tracking */ }
}

View file

@ -299,6 +299,12 @@ export type MenubarPayload = {
currency?: { code: string; symbol: string; rate: number }
combined?: CombinedUsage
claudeConfigs?: ClaudeConfigSelector
// The CLI's anonymised, fully bucketed daily aggregate (src/telemetry-snapshot.ts).
// Sent verbatim as the `usage_snapshot` telemetry event, so the desktop app and
// the Windows tray report identical shapes. Opaque here: the renderer never reads
// inside it. Absent on CLIs that predate the field, which is when the renderer's
// own fallback builder takes over.
telemetrySnapshot?: Record<string, unknown> | null
}
// ————— src/types.ts + src/models-report.ts —————

View file

@ -9,6 +9,7 @@ import { Compare } from './Compare'
const mocks = vi.hoisted(() => ({
getCompareModels: vi.fn<(period: string, provider: string) => Promise<ModelStats[]>>(),
getCompare: vi.fn<(period: string, provider: string, modelA: string, modelB: string) => Promise<CompareJsonReport>>(),
telemetryTrack: vi.fn<(name: string, props?: Record<string, unknown>) => Promise<boolean>>(),
}))
vi.mock('../lib/ipc', async orig => {
const actual = await orig<typeof import('../lib/ipc')>()
@ -47,6 +48,22 @@ describe('Compare', () => {
beforeEach(() => {
mocks.getCompareModels.mockReset()
mocks.getCompare.mockReset()
mocks.telemetryTrack.mockReset().mockResolvedValue(true)
})
it('reports each distinct pair put on screen as a name-only compare_view', async () => {
const user = userEvent.setup()
mocks.getCompareModels.mockResolvedValue([modelA, modelB])
mocks.getCompare.mockResolvedValue(report)
render(<Compare period="30days" provider="all" />)
await waitFor(() => expect(mocks.telemetryTrack).toHaveBeenCalledWith('compare_view', { modelA: 'Opus 4.8', modelB: 'Sonnet 5' }))
expect(mocks.telemetryTrack).toHaveBeenCalledTimes(1)
// Re-rendering the same pair does not fire again.
await user.click(await screen.findByLabelText('First model'))
await user.click(screen.getByRole('option', { name: 'Opus 4.8 · 4,812 calls' }))
expect(mocks.telemetryTrack).toHaveBeenCalledTimes(1)
})
it('defaults to the top two and renders formatted report panels and winners', async () => {

View file

@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { CliErrorPanel } from '../components/CliErrorPanel'
import { Dropdown } from '../components/Dropdown'
@ -10,6 +10,7 @@ import { usePolled } from '../hooks/usePolled'
import { formatCompact, formatUsd } from '../lib/format'
import { codeburn } from '../lib/ipc'
import { reportMemoKey } from '../lib/reportMemoKey'
import { trackEvent } from '../lib/track'
import type { CompareJsonReport, ComparisonRow, DateRange, ModelStats, Period, WorkingStyleRow } from '../lib/types'
function fmtMetric(v: number | null, fn: 'cost' | 'number' | 'percent' | 'decimal'): string {
@ -58,6 +59,17 @@ export function Compare({
setModelB(current => current && available.has(current) ? current : models.data?.[1]?.model ?? null)
}, [models.data])
// One event per distinct pair actually put on screen, not per keystroke in
// the pickers. Model names only.
const comparedPair = useRef<string | null>(null)
useEffect(() => {
if (!modelA || !modelB || modelA === modelB) return
const pair = `${modelA} ${modelB}`
if (comparedPair.current === pair) return
comparedPair.current = pair
trackEvent('compare_view', { modelA, modelB })
}, [modelA, modelB])
const resetToDefaults = useCallback(() => {
if (!models.data) return
setModelA(models.data[0]?.model ?? null)

View file

@ -5,14 +5,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { MenubarPayload, OptimizeJsonReport, YieldJsonReport } from '../lib/types'
import { Optimize, OptimizeContent } from './Optimize'
const { getOverview, getOptimizeReport, getYield } = vi.hoisted(() => ({
const { getOverview, getOptimizeReport, getYield, telemetryTrack } = vi.hoisted(() => ({
getOverview: vi.fn(),
getOptimizeReport: vi.fn(),
getYield: vi.fn(),
telemetryTrack: vi.fn<(name: string, props?: Record<string, unknown>) => Promise<boolean>>(),
}))
vi.mock('../lib/ipc', async orig => {
const actual = await orig<typeof import('../lib/ipc')>()
return { ...actual, codeburn: { getOverview, getOptimizeReport, getYield } }
return { ...actual, codeburn: { getOverview, getOptimizeReport, getYield, telemetryTrack } }
})
function makePayload(): MenubarPayload {
@ -126,6 +127,7 @@ describe('Optimize', () => {
getOptimizeReport.mockReset().mockResolvedValue(makeOptimizeReport())
getYield.mockReset().mockResolvedValue(makeYield())
writeText.mockReset().mockResolvedValue(undefined)
telemetryTrack.mockReset().mockResolvedValue(true)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
})
@ -169,6 +171,18 @@ describe('Optimize', () => {
])
})
it('reports taking a fix as a name-only optimize_apply event', async () => {
render(<Optimize period="30days" provider="all" />)
fireEvent.click(await screen.findByRole('button', { name: /Opus is doing your small talk/ }))
fireEvent.click(screen.getByRole('button', { name: 'Copy' }))
await waitFor(() => expect(telemetryTrack).toHaveBeenCalledWith('optimize_apply', { kind: 'unused-mcp', fixType: 'paste' }))
// The finding's own text never travels with it.
const props = JSON.stringify(telemetryTrack.mock.calls[0]![1])
expect(props).not.toContain('Use Sonnet')
expect(props).not.toContain('small talk')
})
it('renders tabs and actionable Waste findings with impact, savings, explanation, and copy-paste fix', async () => {
render(<Optimize period="30days" provider="all" />)

View file

@ -11,6 +11,7 @@ import { type Polled, usePolled } from '../hooks/usePolled'
import { formatCompact, formatUsd } from '../lib/format'
import { codeburn } from '../lib/ipc'
import { reportMemoKey } from '../lib/reportMemoKey'
import { trackEvent } from '../lib/track'
import type { DateRange, FindingClass, MenubarPayload, OptimizeJsonReport, Period, SessionYieldJson, WasteAction, YieldJsonReport } from '../lib/types'
type OptimizeTab = 'waste' | 'reverts' | 'abandoned' | 'fixes'
@ -179,6 +180,10 @@ function ActionableFindingRows({ findings, byClass }: { findings: OptimizeFindin
const copyFix = async (finding: OptimizeFinding) => {
await navigator.clipboard.writeText(actionText(finding.fix))
// Taking a fix is the closest thing the app has to applying one. The id is a
// fixed detector name (`claude-md-too-long`, `unused-mcp`, ...), never text
// from the finding.
trackEvent('optimize_apply', { kind: finding.id, fixType: finding.fix.type })
setCopiedId(finding.id)
window.setTimeout(() => setCopiedId(current => current === finding.id ? null : current), 1_500)
}

View file

@ -32,6 +32,7 @@ const mocks = vi.hoisted(() => ({
setTrayAppPref: vi.fn(),
setTrayDockPref: vi.fn(),
setLaunchAtLogin: vi.fn(),
telemetryTrack: vi.fn<(name: string, props?: Record<string, unknown>) => Promise<boolean>>(),
}))
vi.mock('../lib/ipc', async orig => {
const actual = await orig<typeof import('../lib/ipc')>()
@ -91,6 +92,7 @@ describe('Settings', () => {
mocks.resetPlan.mockResolvedValue(actionOk)
mocks.chooseDirectory.mockResolvedValue('/Users/toruk/Exports')
mocks.exportData.mockResolvedValue(actionOk)
mocks.telemetryTrack.mockResolvedValue(true)
// No bundled tray app unless a test says otherwise, which is every platform but Windows.
mocks.companionStatus.mockResolvedValue({ supported: false, menuBar: false, sidebar: false, store: false })
mocks.trayPrefs.mockResolvedValue(trayPrefs)
@ -119,6 +121,35 @@ describe('Settings', () => {
expect(await screen.findByText('Updated')).toBeInTheDocument()
})
it('reports settings, plan and export interactions as name-only events', async () => {
const user = userEvent.setup()
render(<Settings period="month" />)
await user.click(screen.getByRole('button', { name: 'Dark' }))
expect(mocks.telemetryTrack).toHaveBeenCalledWith('settings_change', { setting: 'theme', value: 'dark' })
await user.click(await screen.findByLabelText('Currency'))
await user.click(screen.getByRole('option', { name: 'CNY' }))
expect(mocks.telemetryTrack).toHaveBeenCalledWith('settings_change', { setting: 'currency', value: 'CNY' })
await user.click(screen.getByRole('button', { name: 'Plans' }))
await user.click(await screen.findByLabelText('Add a plan'))
await user.click(screen.getByRole('option', { name: 'Cursor Pro' }))
await user.click(screen.getByRole('button', { name: 'Add' }))
expect(mocks.telemetryTrack).toHaveBeenCalledWith('plan_set', { provider: 'cursor', plan: 'cursor-pro' })
await user.click(screen.getAllByRole('button', { name: 'Export' }).at(-1)!)
await user.click(screen.getByRole('button', { name: 'Choose folder…' }))
await screen.findByText('/Users/toruk/Exports')
await user.click(screen.getByRole('button', { name: 'JSON' }))
await user.click(screen.getAllByRole('button', { name: 'Export' }).at(-1)!)
expect(mocks.telemetryTrack).toHaveBeenCalledWith('export', { format: 'json', provider: 'all' })
// The chosen folder is a real path on this machine and never travels.
const sent = JSON.stringify(mocks.telemetryTrack.mock.calls)
expect(sent).not.toContain('/Users/toruk')
})
it('persists theme choices and applies forced themes to the root', async () => {
const user = userEvent.setup()
render(<Settings period="month" />)

View file

@ -20,6 +20,7 @@ import { PROVIDER_NAMES, QUOTA_PROVIDERS, readDisabledProviders, writeDisabledPr
import { REFRESH_OPTIONS, useRefreshCadence } from '../lib/refreshCadence'
import { reportMemoKey } from '../lib/reportMemoKey'
import { showToast } from '../lib/toast'
import { trackEvent } from '../lib/track'
import { ToastHost } from '../components/ToastHost'
import { rateLimitedNote } from './Plans'
import { SharingPane } from './SettingsSharing'
@ -214,6 +215,7 @@ function GeneralPane({ period, refreshToken, claudeConfigs, claudeConfigSource,
const chooseTheme = (next: Theme) => {
setTheme(next)
writeSetting('codeburn.theme', next)
trackEvent('settings_change', { setting: 'theme', value: next })
}
const finishCurrency = (result: ActionResult) => {
showToast(result.ok ? 'Updated' : result.stderr || 'Unable to update currency', result.ok ? 'ok' : 'error')
@ -245,10 +247,10 @@ function GeneralPane({ period, refreshToken, claudeConfigs, claudeConfigSource,
<div className="about-sec">
<div className="about-sec-h">Display</div>
<div className="about-row"><label className="tx" htmlFor="settings-currency">Currency</label><span className="r">
{plans.data ? <Dropdown id="settings-currency" ariaLabel="Currency" value={plans.data.currency} options={currencies.map(code => ({ value: code, label: code }))} onChange={value => void codeburn.setCurrency(value).then(finishCurrency)} width={92} /> : plans.error ? <SettingsErrorText error={plans.error} /> : <span className="set-cap">Loading…</span>}
<button className="set-text-button" onClick={() => void codeburn.resetCurrency().then(finishCurrency)}>Reset to USD</button>
{plans.data ? <Dropdown id="settings-currency" ariaLabel="Currency" value={plans.data.currency} options={currencies.map(code => ({ value: code, label: code }))} onChange={value => { trackEvent('settings_change', { setting: 'currency', value }); void codeburn.setCurrency(value).then(finishCurrency) }} width={92} /> : plans.error ? <SettingsErrorText error={plans.error} /> : <span className="set-cap">Loading…</span>}
<button className="set-text-button" onClick={() => { trackEvent('settings_change', { setting: 'currency', value: 'USD' }); void codeburn.resetCurrency().then(finishCurrency) }}>Reset to USD</button>
</span></div>
<div className="about-row"><label className="tx" htmlFor="settings-period">Default period<small>Applied on next launch.</small></label><span className="r"><Dropdown id="settings-period" ariaLabel="Default period" value={defaultPeriod} options={[{ value: 'today', label: 'Today' }, { value: 'week', label: '7d' }, { value: '30days', label: '30d' }, { value: 'month', label: 'Month' }, { value: 'all', label: 'All' }]} onChange={value => { setDefaultPeriod(value); writeSetting('codeburn.defaultPeriod', value) }} width={92} /></span></div>
<div className="about-row"><label className="tx" htmlFor="settings-period">Default period<small>Applied on next launch.</small></label><span className="r"><Dropdown id="settings-period" ariaLabel="Default period" value={defaultPeriod} options={[{ value: 'today', label: 'Today' }, { value: 'week', label: '7d' }, { value: '30days', label: '30d' }, { value: 'month', label: 'Month' }, { value: 'all', label: 'All' }]} onChange={value => { setDefaultPeriod(value); writeSetting('codeburn.defaultPeriod', value); trackEvent('settings_change', { setting: 'defaultPeriod', value }) }} width={92} /></span></div>
<div className="about-row"><label className="tx" htmlFor="settings-scope">Scope<small>Combined aggregates usage across every paired device, like the menubar. Local shows this device only.</small></label><span className="r"><Dropdown id="settings-scope" ariaLabel="Scope" value={scope} options={[{ value: 'local', label: 'Local' }, { value: 'combined', label: 'Combined' }]} onChange={value => onScopeChange?.(value)} width={110} /></span></div>
<div className="about-row"><label className="tx" htmlFor="settings-refresh">Refresh every<small>Runs automatically at this interval. Press {shortcutLabel('R')} to refresh sooner.</small></label><span className="r"><Dropdown id="settings-refresh" ariaLabel="Refresh every" value={cadence.value} options={REFRESH_OPTIONS.map(option => ({ value: option.value, label: option.label }))} onChange={cadence.setValue} width={124} /></span></div>
<div className="about-row"><label className="tx" htmlFor="settings-budget">Daily budget<small>Warns at 80%, alerts at 100%.</small></label><span className="r"><Dropdown id="settings-budget" ariaLabel="Daily budget" value={budgetKind} options={[{ value: 'off', label: 'Off' }, { value: 'usd', label: 'USD amount' }, { value: 'tokens', label: 'Tokens' }]} onChange={value => { const kind = value as 'off' | 'usd' | 'tokens'; setBudgetKind(kind); persistBudget(kind, budgetInput) }} width={120} />{budgetKind !== 'off' && <input className="set-input" type="text" inputMode="decimal" aria-label="Daily budget amount" placeholder={budgetKind === 'usd' ? 'USD' : 'tokens'} value={budgetInput} onChange={event => { setBudgetInput(event.target.value); persistBudget(budgetKind, event.target.value) }} style={{ width: 90 }} />}</span></div>
@ -429,6 +431,7 @@ function PlansPane({ period, refreshToken, onNavigate, onConfigMutated }: { peri
}
const add = () => {
const preset = MANUAL_PLAN_PRESETS.find(item => item.id === presetId)!
trackEvent('plan_set', { provider: preset.provider, plan: preset.id })
void codeburn.setPlan(preset.id, preset.provider).then(finish)
}
@ -479,6 +482,9 @@ function ExportPane({ period, refreshToken }: { period: Period; refreshToken: nu
if (!destination) return
setExporting(true)
try {
// Format and provider only. The destination is a real path on this
// machine and never leaves it.
trackEvent('export', { format, provider })
const result = await codeburn.exportData(format, provider, destination)
showToast(result.ok ? `Exported to ${destination}` : (result.stderr || 'Export failed'), result.ok ? 'ok' : 'error')
} finally {
@ -534,6 +540,9 @@ function TelemetryClaim() {
if (!status) return null
const toggle = () => {
if (typeof codeburn.setTelemetryEnabled !== 'function') return
// Only the opt-IN is reportable: turning telemetry off mints a fresh install
// id and drops the queue, so an opt-out event would never be sent anyway.
if (!status.enabled) trackEvent('settings_change', { setting: 'telemetry', value: true })
codeburn.setTelemetryEnabled(!status.enabled).then(value => setStatus(value)).catch(() => {})
}
return <div className="set-claim"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 19v-5M9 19V9M14 19v-8M19 19V5" /></svg><div style={{ flex: 1 }}><div className="set-claim-t">Anonymous telemetry</div><div className="set-claim-d">Optional usage statistics: model mix, task success, performance and errors. Never prompts, code or anything identifying.</div></div>