diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f91d77c..03a484be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ - **The resident `codeburn serve` child.** The first real panel request is also the cache warm-up, so startup never runs an artificial warm-up query beside a duplicate one-shot child; each served command carries its own read-only option allowlist, and anything outside it falls back to a normal spawn; the child exits when its stdin closes, so it can never outlive the app. Requests whose response exceeds the 16 MiB frame limit still replace the child, but that deliberate kill no longer spends the resident's unexpected-death budget. (#972) ### Fixed +- **The unpriced-models warning in the dashboard is now readable at every terminal width.** It lived in a fixed-width panel with an inline model list and a fix command, so it clipped mid-name at 80 columns and clipped *earlier* at 200, where the three-column layout narrows each panel - neither the affected models nor a runnable command survived. The panel line is now a pointer, `! N unpriced: codeburn models --unpriced` (shortened to `! N: codeburn models --unpriced` below 45 columns of panel), and the model list moves to that command's plain output, which is full width, copyable, and lists every model rather than the first two. The command's hint no longer reads as an unconditional instruction to alias: a subscription or flat-rate model is correctly $0, and mapping it onto another model's per-token rate would invent spend that was never billed. Provider-supplied model IDs are now stripped of terminal control characters in every human-readable report rather than only on the unpriced path, and `--unpriced` shows raw IDs instead of friendly names because `model-alias` keys on the raw ID. (#969) - **`codeburn models --unpriced --top N` returned nothing for a `--top N` smaller than the number of priced models.** `--top` is applied inside `aggregateModels`, before the unpriced filter, on rows sorted cost-first — and unpriced rows are $0 on both, so they sorted last and the slice removed exactly the rows the flag exists to show. A user with unpriced models was told they had none. The slice now runs after the filter — and after ranking, because unpriced rows tie at $0 on both keys, so slicing them in aggregate order kept whichever models happened to appear earliest in the transcript rather than the largest. The order now matches the one the unpriced-models warning shows. (#969) - **Old durable sources remain visible while they still exist.** The 90-day session-cache age-out now applies only after a durable source disappears from discovery, so an unchanged older Copilot source keeps reporting usage and reuses its persisted fingerprint instead of being reparsed and immediately discarded. (#987) On long-lived machines this makes previously dropped history reappear, so lifetime totals can jump once after upgrading. - **`optimize` no longer treats subagent transcripts as your sessions.** Claude Code writes each subagent's transcript to its own `subagents/agent-*.jsonl` file with `isSidechain: true` on every entry, and optimize counted each one as a user-started session. That inflated the session count in the header and fed the session-level detectors a population that fails their tests by construction: a sidechain is handed a large context and returns a short answer (context-heavy), and it never commits or opens a PR because its parent does (low-worth). Excluded from sidechains now: the header session count, the `low-worth-sessions`, `context-bloat`, `cost-outliers` and `capability-reliability` detectors, the coaching notes, the file-churn table, the median time-to-first-edit, the worst one-shot category, and the model-default recommendation - plus `duplicate-reads`, because a subagent starts on a fresh context and re-reading what its parent read is a necessary read, not a repeat. Everything else keeps the full population: `build-folder-reads` and `read-edit-ratio` still count calls made inside a sidechain, since reading `node_modules` or editing without reading is the same waste whoever does it and the `CLAUDE.md` rule they suggest binds subagents too, and so do the MCP, cache-bloat, ghost-command and configuration-overhead findings. Classification is sticky across the whole file, so calls that appear before the first marked entry are reclassified too, and `isSidechain` now survives the compact parser's 32 KB large-line path and warm-cache range rebuilds. Nothing is deleted from spend: sidechain tokens, calls and cost stay in every total and in `status`, and the optimize result cache keys on sidechain identity so a run cannot be served a pre-fix result. Absent markers still read as user-started, so no cache re-parse is needed. (#974) diff --git a/README.md b/README.md index bdd2192b..b04e01db 100644 --- a/README.md +++ b/README.md @@ -516,7 +516,7 @@ Sync sends token counts, costs, models, and projects, never prompts or code. Thi | `codeburn models --by-task` | Break each model into per-task-type rows | | `codeburn models --by-agent` | Break each model into per-agent rows: which agent drove which model's spend (`(main)` covers non-agent sessions; `--min-cost 0` shows sub-cent agents) | | `codeburn models --top 10` | Only the 10 most expensive models | -| `codeburn models --unpriced` | Only models with usage that currently price at $0 — the copyable form of the unpriced-models warning | +| `codeburn models --unpriced` | Only models with usage that currently price at $0 — the copyable form of the unpriced-models warning. Shows raw model IDs (not friendly names) so they can be pasted into `model-alias`; JSON keeps them exact | | `codeburn models --format markdown` | Emit a paste-friendly markdown table | | `codeburn models --task feature` | Filter to feature-development work | | `codeburn models --provider claude` | Filter to a single provider | diff --git a/src/audit-report.ts b/src/audit-report.ts index a133dcf4..7a40c5c7 100644 --- a/src/audit-report.ts +++ b/src/audit-report.ts @@ -1,4 +1,4 @@ -import { getModelCosts, type ModelCosts } from './models.js' +import { getModelCosts, sanitizeModelForDisplay, type ModelCosts } from './models.js' import { getProvider } from './providers/index.js' import { formatCost, formatTokens } from './format.js' import { renderTable, type TableColumn } from './text-table.js' @@ -111,7 +111,9 @@ export async function aggregateAudit(projects: ProjectSummary[]): Promise p.modelDisplayName(m) : (m: string) => m, + formatModel: p + ? (m: string) => sanitizeModelForDisplay(p.modelDisplayName(m)) + : sanitizeModelForDisplay, } providerCache.set(name, entry) return entry diff --git a/src/dashboard.tsx b/src/dashboard.tsx index 90a21988..7eeeaf35 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -653,8 +653,10 @@ function ModelBreakdown({ projects, pw, bw }: { projects: ProjectSummary[]; pw: ) })} {unpriced.length > 0 && ( - - {`! ${unpriced.length} model${unpriced.length === 1 ? '' : 's'} unpriced at $0, fix: codeburn model-alias (${unpriced.slice(0, 2).map(u => u.model).join(', ')}${unpriced.length > 2 ? ', ...' : ''})`} + + {pw <= 44 + ? `! ${unpriced.length}: codeburn models --unpriced` + : `! ${unpriced.length} unpriced: codeburn models --unpriced`} )} {anyEstimated && ( diff --git a/src/main.ts b/src/main.ts index d3a67849..fdaea87d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,7 +2,7 @@ import { isAbsolute } from 'path' import { Command, Option } from 'commander' import { installMenubarApp } from './menubar-installer.js' import { exportCsv, exportJson, type PeriodExport } from './export.js' -import { findUnpricedModels, loadPricing, setModelAliases, setPriceOverrides, setLocalModelSavings, setProxyPaths, normalizeProxyPath } from './models.js' +import { findUnpricedModels, loadPricing, sanitizeModelForDisplay, setModelAliases, setPriceOverrides, setLocalModelSavings, setProxyPaths, normalizeProxyPath } from './models.js' import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI } from './parser.js' import { allProviderNames, getAllProviders } from './providers/index.js' import { getProvider } from './providers/index.js' @@ -2143,17 +2143,27 @@ program const fmt = (opts.format ?? 'table').toLowerCase() if (rows.length === 0 && (fmt === 'table' || fmt === 'markdown')) { - process.stdout.write('No model usage found for the selected period.\n') + process.stdout.write(opts.unpriced + ? 'No unpriced models found for the selected period.\n' + : 'No model usage found for the selected period.\n') return } + // The friendly name is useless for `model-alias`, which keys on the raw ID. + // Sanitized because this bypasses the shared display path in models-report. + const renderRows = opts.unpriced && fmt !== 'json' + ? rows.map(row => ({ ...row, modelDisplayName: sanitizeModelForDisplay(row.model) })) + : rows if (fmt === 'json') { process.stdout.write(renderJson(rows) + '\n') } else if (fmt === 'csv') { - process.stdout.write(renderCsv(rows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent }) + '\n') + process.stdout.write(renderCsv(renderRows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent }) + '\n') } else if (fmt === 'markdown' || fmt === 'md') { - process.stdout.write(renderMarkdown(rows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') + process.stdout.write(renderMarkdown(renderRows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') } else if (fmt === 'table') { - process.stdout.write(renderTable(rows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') + process.stdout.write(renderTable(renderRows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') + // Never advise aliasing unconditionally: a subscription or flat-rate model + // is correctly $0, and mapping it onto another model's rate invents spend. + if (opts.unpriced) process.stdout.write('If a model is billed per token, map it with: codeburn model-alias "" . Subscription or flat-rate models are correctly $0.\n') } else { process.stderr.write(`codeburn: unknown --format "${opts.format}". Choose table, markdown, json, or csv.\n`) process.exit(1) diff --git a/src/models-report.ts b/src/models-report.ts index aaeb2235..66938b6f 100644 --- a/src/models-report.ts +++ b/src/models-report.ts @@ -3,6 +3,7 @@ import stripAnsi from 'strip-ansi' import { codexCredits } from './codex-credits.js' import { formatCost, formatTokens } from './format.js' +import { sanitizeModelForDisplay } from './models.js' import { getProvider } from './providers/index.js' import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types.js' @@ -153,7 +154,9 @@ export async function aggregateModels(projects: ProjectSummary[], opts: Aggregat const p = await getProvider(name) const entry = { displayName: p?.displayName ?? name, - formatModel: p ? (m: string) => p.modelDisplayName(m) : (m: string) => m, + formatModel: p + ? (m: string) => sanitizeModelForDisplay(p.modelDisplayName(m)) + : sanitizeModelForDisplay, } providerCache.set(name, entry) return entry diff --git a/src/models.ts b/src/models.ts index 0ad8fccc..dbe1c49d 100644 --- a/src/models.ts +++ b/src/models.ts @@ -791,6 +791,11 @@ function shouldWarnAboutUnknownModel(name: string): boolean { return true } +/** Render provider-supplied model IDs without terminal control characters. */ +export function sanitizeModelForDisplay(model: string): string { + return model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200) +} + export function calculateCost( model: string, inputTokens: number, @@ -808,7 +813,7 @@ export function calculateCost( // Strip control characters and cap length: model names come from JSONL // payloads written by external tools, so a hostile or corrupt file // could embed terminal escape sequences here. - const safeName = model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200) + const safeName = sanitizeModelForDisplay(model) const aliasHint = `Map it with: codeburn model-alias "${safeName}" , or track local-model savings with: codeburn model-savings "${safeName}" ` process.stderr.write( `codeburn: no pricing data for model "${safeName}" — costs for this model will show $0. ` + diff --git a/tests/cli-models-unpriced.test.ts b/tests/cli-models-unpriced.test.ts new file mode 100644 index 00000000..eb93fe90 --- /dev/null +++ b/tests/cli-models-unpriced.test.ts @@ -0,0 +1,153 @@ +import { spawnSync } from 'node:child_process' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { describe, expect, it } from 'vitest' + +function runCli(args: string[], home: string, locale?: string) { + return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { + cwd: process.cwd(), + env: { + ...process.env, + HOME: home, + USERPROFILE: home, + CLAUDE_CONFIG_DIR: join(home, '.claude'), + CODEBURN_CACHE_DIR: join(home, '.cache', 'codeburn'), + TZ: 'UTC', + ...(locale ? { LANG: locale, LC_ALL: locale } : {}), + }, + encoding: 'utf-8', + timeout: 30_000, + }) +} + +function userLine(timestamp: string): string { + return JSON.stringify({ + type: 'user', sessionId: 'unpriced-969', timestamp, cwd: '/tmp/unpriced-969', + message: { role: 'user', content: 'inspect pricing coverage' }, + }) +} + +function assistantLine(model: string, timestamp: string, messageId: string, input: number): string { + return JSON.stringify({ + type: 'assistant', sessionId: 'unpriced-969', timestamp, cwd: '/tmp/unpriced-969', + message: { + id: messageId, type: 'message', role: 'assistant', model, + content: [{ type: 'text', text: 'done' }], + usage: { + input_tokens: input, output_tokens: 100, + cache_read_input_tokens: 0, cache_creation_input_tokens: 0, + }, + }, + }) +} + +async function withFixture(lines: string[], run: (home: string) => void): Promise { + const home = await mkdtemp(join(tmpdir(), 'codeburn-models-unpriced-')) + try { + const projectDir = join(home, '.claude', 'projects', 'unpriced-969') + await mkdir(projectDir, { recursive: true }) + await writeFile(join(projectDir, 'session.jsonl'), `${lines.join('\n')}\n`) + run(home) + } finally { + await rm(home, { recursive: true, force: true }) + } +} + +const range = ['--from', '2026-05-20', '--to', '2026-05-20', '--provider', 'claude'] + +describe('codeburn models --unpriced public CLI', () => { + it('filters before --top and returns the largest unpriced raw ID deterministically', async () => { + await withFixture([ + userLine('2026-05-20T10:00:00.000Z'), + assistantLine('acme/unknown-small-969', '2026-05-20T10:01:00.000Z', 'small', 1_000), + assistantLine('claude-opus-4-6', '2026-05-20T10:02:00.000Z', 'priced', 20_000), + assistantLine('acme/unknown-large-969', '2026-05-20T10:03:00.000Z', 'large', 9_000), + ], home => { + const result = runCli(['models', '--unpriced', '--top', '1', '--format', 'json', ...range], home) + expect(result.status, result.stderr).toBe(0) + expect(JSON.parse(result.stdout)).toEqual([ + expect.objectContaining({ model: 'acme/unknown-large-969', totalTokens: 9_100 }), + ]) + }) + }) + + it('orders tied unpriced rows identically across host locales', async () => { + await withFixture([ + userLine('2026-05-20T10:00:00.000Z'), + assistantLine('acme/z-unknown-969', '2026-05-20T10:01:00.000Z', 'z-model', 1_000), + assistantLine('acme/ä-unknown-969', '2026-05-20T10:02:00.000Z', 'a-umlaut-model', 1_000), + ], home => { + const args = ['models', '--unpriced', '--format', 'json', ...range] + const english = runCli(args, home, 'en_US.UTF-8') + const swedish = runCli(args, home, 'sv_SE.UTF-8') + expect(english.status, english.stderr).toBe(0) + expect(swedish.status, swedish.stderr).toBe(0) + const models = (stdout: string) => (JSON.parse(stdout) as Array<{ model: string }>).map(row => row.model) + expect(models(english.stdout)).toEqual(['acme/z-unknown-969', 'acme/ä-unknown-969']) + expect(models(swedish.stdout)).toEqual(models(english.stdout)) + }) + }) + + it('honors an explicitly supplied finite --min-cost threshold', async () => { + await withFixture([ + userLine('2026-05-20T10:00:00.000Z'), + assistantLine('acme/unknown-zero-969', '2026-05-20T10:01:00.000Z', 'zero', 1_000), + ], home => { + const result = runCli(['models', '--unpriced', '--min-cost', '0.01', '--format', 'json', ...range], home) + expect(result.status, result.stderr).toBe(0) + expect(JSON.parse(result.stdout)).toEqual([]) + }) + }) + + it('lists every unpriced model in table output with an actionable hint', async () => { + await withFixture([ + userLine('2026-05-20T10:00:00.000Z'), + assistantLine('acme/unknown-alpha-969', '2026-05-20T10:01:00.000Z', 'alpha', 1_000), + assistantLine('acme/unknown-beta-969', '2026-05-20T10:02:00.000Z', 'beta', 2_000), + assistantLine('claude-opus-4-6', '2026-05-20T10:03:00.000Z', 'priced', 3_000), + ], home => { + const result = runCli(['models', '--unpriced', ...range], home) + expect(result.status, result.stderr).toBe(0) + expect(result.stdout).toContain('acme/unknown-alpha-969') + expect(result.stdout).toContain('acme/unknown-beta-969') + expect(result.stdout).not.toContain('claude-opus-4-6') + expect(result.stdout).toContain('If a model is billed per token, map it with: codeburn model-alias "" ') + // #968: aliasing a subscription-billed model fabricates spend, so the + // hint must never read as an unconditional instruction. + expect(result.stdout).toContain('Subscription or flat-rate models are correctly $0.') + expect(result.stdout).not.toContain('Fix: codeburn model-alias') + }) + }) + + it('reports a clean period explicitly', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-models-unpriced-empty-')) + try { + const result = runCli(['models', '--unpriced', ...range], home) + expect(result.status, result.stderr).toBe(0) + expect(result.stdout).toBe('No unpriced models found for the selected period.\n') + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('sanitizes hostile IDs in human formats while JSON stays lossless', async () => { + const hostile = `acme/alpha\u001b]0;forged\u0007click\u001b[31m\nforged-row-${'x'.repeat(300)}` + await withFixture([ + userLine('2026-05-20T10:00:00.000Z'), + assistantLine(hostile, '2026-05-20T10:01:00.000Z', 'hostile', 1_000), + ], home => { + for (const format of ['table', 'markdown', 'csv']) { + const result = runCli(['models', '--unpriced', '--format', format, ...range], home) + expect(result.status, `${format}: ${result.stderr}`).toBe(0) + expect(result.stdout).not.toMatch(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/) + expect(result.stdout).not.toContain('\nforged-row-') + expect(result.stdout).not.toContain('x'.repeat(201)) + } + const json = runCli(['models', '--unpriced', '--format', 'json', ...range], home) + expect(json.status, json.stderr).toBe(0) + expect((JSON.parse(json.stdout) as Array<{ model: string }>)[0]?.model).toBe(hostile) + }) + }, 15_000) +}) diff --git a/tests/dashboard.test.ts b/tests/dashboard.test.ts index 8f87ae6a..f4892286 100644 --- a/tests/dashboard.test.ts +++ b/tests/dashboard.test.ts @@ -395,6 +395,57 @@ describe('interactive terminal rendering', () => { expect(INTERACTIVE_RENDER_OPTIONS).toMatchObject({ alternateScreen: true }) }) + it.each([ + { columns: 42, expected: '! 10: codeburn models --unpriced' }, + { columns: 43, expected: '! 10: codeburn models --unpriced' }, + { columns: 44, expected: '! 10: codeburn models --unpriced' }, + { columns: 80, expected: '! 10 unpriced: codeburn models --unpriced' }, + ])('shows an actionable unpriced-model command in a real $columns-column Ink frame', async ({ columns, expected }) => { + const stdin = new PassThrough() as PassThrough & NodeJS.ReadStream + const stdout = new PassThrough() as PassThrough & NodeJS.WriteStream + stdin.isTTY = true + stdin.setRawMode = () => stdin + stdin.ref = () => stdin + stdin.unref = () => stdin + stdout.isTTY = true + stdout.columns = columns + stdout.rows = 100 + const frames: string[] = [] + stdout.on('data', chunk => frames.push(stripAnsi(String(chunk)))) + + const session = makeSession('unpriced-session', 0) + for (let index = 0; index < 10; index++) { + const model = `vendor-${index}/unknown-model-${index}-969` + session.modelBreakdown[model] = { + calls: 1, + costUSD: 0, + savingsUSD: 0, + tokens: { + inputTokens: 1_000, + outputTokens: 100, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 0, + webSearchRequests: 0, + }, + } + } + + const app = render(React.createElement(InteractiveDashboard, { + initialProjects: [makeProject('unpriced-project', [session])], + initialPeriod: 'today', + initialProvider: 'all', + refreshSeconds: 0, + windowColumns: columns, + }), { stdin, stdout, debug: true, interactive: true, patchConsole: false }) + onTestFinished(() => app.unmount()) + await app.waitUntilRenderFlush() + + const frame = frames.filter(value => value.trim()).at(-1) ?? '' + expect(frame).toContain(expected) + }) + it('labels claude.ai connector remediation as a manual action', async () => { const stdin = new PassThrough() as PassThrough & NodeJS.ReadStream const stdout = new PassThrough() as PassThrough & NodeJS.WriteStream