From 2b06a3a5e4568c8eb979604d660a989d2fa23e17 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Thu, 3 Sep 2026 01:18:23 -0700 Subject: [PATCH] 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. --- CHANGELOG.md | 3 + README.md | 63 +++++++++++++++++- app/electron/telemetry.test.ts | 42 +++++++++++- app/electron/telemetry.ts | 88 ++++++++++++++++--------- app/renderer/App.test.tsx | 49 ++++++++++++++ app/renderer/App.tsx | 29 ++++---- app/renderer/lib/track.ts | 13 ++++ app/renderer/lib/types.ts | 6 ++ app/renderer/sections/Compare.test.tsx | 17 +++++ app/renderer/sections/Compare.tsx | 14 +++- app/renderer/sections/Optimize.test.tsx | 18 ++++- app/renderer/sections/Optimize.tsx | 5 ++ app/renderer/sections/Settings.test.tsx | 31 +++++++++ app/renderer/sections/Settings.tsx | 15 ++++- 14 files changed, 342 insertions(+), 51 deletions(-) create mode 100644 app/renderer/lib/track.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fe1b4045..43fc1896 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 2b367b8a..f0efbcd5 100644 --- a/README.md +++ b/README.md @@ -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).

Quick start · @@ -89,7 +89,8 @@ Everything runs locally. No wrapper, no proxy, no API keys, nothing leaves your Supported tools · Commands · Features · - How it reads data + How it reads data · + Telemetry

## Quick start @@ -778,6 +779,64 @@ CodeBurn deduplicates messages (by API message ID for Claude, by cumulative toke +## Telemetry + +
+What the desktop app sends, and how to turn it off + +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. + +
+ ## Environment Variables
diff --git a/app/electron/telemetry.test.ts b/app/electron/telemetry.test.ts index 4adbb701..305ac314 100644 --- a/app/electron/telemetry.test.ts +++ b/app/electron/telemetry.test.ts @@ -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 }> }).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 }> }).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 diff --git a/app/electron/telemetry.ts b/app/electron/telemetry.ts index a61592e2..fbf82022 100644 --- a/app/electron/telemetry.ts +++ b/app/electron/telemetry.ts @@ -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= 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, 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 { - if (!props || typeof props !== 'object' || Array.isArray(props)) return {} +function sanitizeObject(obj: Record, depth: number, budget: LeafBudget): Record { const out: Record = {} let keys = 0 - for (const [key, value] of Object.entries(props as Record)) { + 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[] = [] - for (const entry of value.slice(0, MAX_ARRAY)) { - if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue - const flat: Record = {} - let inner = 0 - for (const [ik, iv] of Object.entries(entry as Record)) { - 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 { + if (!props || typeof props !== 'object' || Array.isArray(props)) return {} + return sanitizeObject(props as Record, 1, { left: MAX_LEAVES }) +} + export class Telemetry { private readonly deps: Required> & Deps private state: PersistedState diff --git a/app/renderer/App.test.tsx b/app/renderer/App.test.tsx index 86fe0ce5..1a7cb07c 100644 --- a/app/renderer/App.test.tsx +++ b/app/renderer/App.test.tsx @@ -40,6 +40,7 @@ const mocks = vi.hoisted(() => ({ getAliases: vi.fn(), setCurrency: vi.fn(), resetCurrency: vi.fn(), + telemetryTrack: vi.fn<(name: string, props?: Record) => Promise>(), })) 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() + + 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() + + 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() + + // 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. diff --git a/app/renderer/App.tsx b/app/renderer/App.tsx index bbd7c7fb..6a77cdad 100644 --- a/app/renderer/App.tsx +++ b/app/renderer/App.tsx @@ -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 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): Record { 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) => { - 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(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 | 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) => { diff --git a/app/renderer/lib/track.ts b/app/renderer/lib/track.ts new file mode 100644 index 00000000..c7891983 --- /dev/null +++ b/app/renderer/lib/track.ts @@ -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): 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 */ } +} diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index 457973e3..0d5b2dc8 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -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 | null } // ————— src/types.ts + src/models-report.ts ————— diff --git a/app/renderer/sections/Compare.test.tsx b/app/renderer/sections/Compare.test.tsx index c68c84a5..a0269269 100644 --- a/app/renderer/sections/Compare.test.tsx +++ b/app/renderer/sections/Compare.test.tsx @@ -9,6 +9,7 @@ import { Compare } from './Compare' const mocks = vi.hoisted(() => ({ getCompareModels: vi.fn<(period: string, provider: string) => Promise>(), getCompare: vi.fn<(period: string, provider: string, modelA: string, modelB: string) => Promise>(), + telemetryTrack: vi.fn<(name: string, props?: Record) => Promise>(), })) vi.mock('../lib/ipc', async orig => { const actual = await orig() @@ -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() + + 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 () => { diff --git a/app/renderer/sections/Compare.tsx b/app/renderer/sections/Compare.tsx index 44bdd529..d3ee60d1 100644 --- a/app/renderer/sections/Compare.tsx +++ b/app/renderer/sections/Compare.tsx @@ -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(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) diff --git a/app/renderer/sections/Optimize.test.tsx b/app/renderer/sections/Optimize.test.tsx index e2283872..d37e51eb 100644 --- a/app/renderer/sections/Optimize.test.tsx +++ b/app/renderer/sections/Optimize.test.tsx @@ -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) => Promise>(), })) vi.mock('../lib/ipc', async orig => { const actual = await orig() - 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() + 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() diff --git a/app/renderer/sections/Optimize.tsx b/app/renderer/sections/Optimize.tsx index d00c0760..25f8d4a6 100644 --- a/app/renderer/sections/Optimize.tsx +++ b/app/renderer/sections/Optimize.tsx @@ -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) } diff --git a/app/renderer/sections/Settings.test.tsx b/app/renderer/sections/Settings.test.tsx index 11fb93e2..2793b7e5 100644 --- a/app/renderer/sections/Settings.test.tsx +++ b/app/renderer/sections/Settings.test.tsx @@ -32,6 +32,7 @@ const mocks = vi.hoisted(() => ({ setTrayAppPref: vi.fn(), setTrayDockPref: vi.fn(), setLaunchAtLogin: vi.fn(), + telemetryTrack: vi.fn<(name: string, props?: Record) => Promise>(), })) vi.mock('../lib/ipc', async orig => { const actual = await orig() @@ -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() + + 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() diff --git a/app/renderer/sections/Settings.tsx b/app/renderer/sections/Settings.tsx index 00b19242..6fd0519c 100644 --- a/app/renderer/sections/Settings.tsx +++ b/app/renderer/sections/Settings.tsx @@ -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,
Display
- {plans.data ? ({ value: code, label: code }))} onChange={value => void codeburn.setCurrency(value).then(finishCurrency)} width={92} /> : plans.error ? : Loading…} - + {plans.data ? ({ value: code, label: code }))} onChange={value => { trackEvent('settings_change', { setting: 'currency', value }); void codeburn.setCurrency(value).then(finishCurrency) }} width={92} /> : plans.error ? : Loading…} +
-
{ setDefaultPeriod(value); writeSetting('codeburn.defaultPeriod', value) }} width={92} />
+
{ setDefaultPeriod(value); writeSetting('codeburn.defaultPeriod', value); trackEvent('settings_change', { setting: 'defaultPeriod', value }) }} width={92} />
onScopeChange?.(value)} width={110} />
({ value: option.value, label: option.label }))} onChange={cadence.setValue} width={124} />
{ const kind = value as 'off' | 'usd' | 'tokens'; setBudgetKind(kind); persistBudget(kind, budgetInput) }} width={120} />{budgetKind !== 'off' && { setBudgetInput(event.target.value); persistBudget(budgetKind, event.target.value) }} style={{ width: 90 }} />}
@@ -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
Anonymous telemetry
Optional usage statistics: model mix, task success, performance and errors. Never prompts, code or anything identifying.