Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-3124]): measure real token usage from provider CLI transcripts
[._.]/ Adam Eivyaebf37ed74cb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c6812aa8c7..c7f7b4db3c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Usage cost reporting- **[issue-3124] Usage cost estimates now include pre-breakdown history** — Older activity is grouped as legacy usage, conflicting totals agree, missing provider IDs are labeled clearly, and the report explains which token costs remain uncounted.+- **[issue-3124] The cost report now measures real token usage instead of guessing at it.** Claude Code and Codex runs read their actual per-message token counts — full conversation context plus prompt-cache reads and writes — from the transcripts those tools already keep on your machine, so nothing is sent anywhere and no AI credits are spent. Cache reads and writes are priced at their own published rates and shown in their own columns. Since repeated context and cache traffic are the bulk of what agentic coding actually costs, the report was previously understating real spend by roughly ten times. Every row is now labeled Measured or Estimated, and a "Measure from transcripts" button re-reads past activity to correct history you've already accumulated. Runs on local models stay correctly free.## Quota-burn automationdiff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 58f0e31a1c..61a46c160c 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -1,10 +1,12 @@import { useState, useEffect } from 'react';import { useSearchParams } from 'react-router-dom';-import { RefreshCw, Clock, AlertTriangle } from 'lucide-react';+import { RefreshCw, Clock, AlertTriangle, FileSearch } from 'lucide-react';import * as api from '../services/api';import BrailleSpinner from '../components/BrailleSpinner';import PageSkeleton from '../components/ui/PageSkeleton';import Pill from '../components/ui/Pill';+import { useAsyncAction } from '../hooks/useAsyncAction';+import toast from '../components/ui/Toast';import { formatCompactCount } from '../utils/formatters';const PERIOD_OPTIONS = [@@ -189,18 +191,40 @@ function ProviderQuotaSection() {// Approximate-rate marker: anything other than an exact model-id rate match.const approxMark = (rateMatch) => (rateMatch === 'exact' || rateMatch === 'free' ? '' : '~');+// How a row's token counts were obtained. `measured` rows are summed from the+// provider CLI's own transcript; `estimate` rows are derived from prompt length+// and captured stdout and understate real usage substantially. Distinguishing+// them is the point of #3124 — a headline figure that mixes the two silently is+// what made the old report unusable.+const SOURCE_LABELS = {+ measured: { label: 'Measured', tone: 'success', title: 'Token counts read from the provider CLI’s own transcript' },+ mixed: { label: 'Part est.', tone: 'warning', title: 'Some counts measured from the provider transcript, some estimated' },+ estimate: { label: 'Estimated', tone: 'context', title: 'Estimated from prompt length and captured output — understates per-turn context and cache traffic' }+};++function SourcePill({ source, className = '' }) {+ const meta = SOURCE_LABELS[source] || SOURCE_LABELS.estimate;+ return (+ <Pill tone={meta.tone} size="xs" className={className} title={meta.title}>{meta.label}</Pill>+ );+}+function CostReportTable({ report }) {if (!report?.providers?.length) {return <div className="text-gray-500 text-sm py-4">No per-provider usage recorded in this period.</div>;}return (<div className="overflow-x-auto">- <table className="w-full text-sm min-w-[560px]">+ <table className="w-full text-sm min-w-[680px]"><thead><tr className="text-left text-xs text-gray-500 border-b border-port-border"><th className="py-2 pr-2 font-medium">Provider / Model</th><th className="py-2 px-2 font-medium text-right">Sessions</th><th className="py-2 px-2 font-medium text-right">Tokens In</th>+ {/* Cache columns collapse below md — the mobile-responsive rule; the+ per-row title attributes keep the numbers reachable there. */}+ <th className="py-2 px-2 font-medium text-right hidden md:table-cell">Cache Read</th>+ <th className="py-2 px-2 font-medium text-right hidden md:table-cell">Cache Write</th><th className="py-2 px-2 font-medium text-right">Tokens Out</th><th className="py-2 pl-2 font-medium text-right">Est. API Cost</th></tr>@@ -215,6 +239,8 @@ function CostReportTable({ report }) {<td className="py-2 pr-2">Total</td><td className="py-2 px-2 text-right">{formatNumber(report.totals.sessions)}</td><td className="py-2 px-2 text-right">{formatNumber(report.totals.tokensIn)}</td>+ <td className="py-2 px-2 text-right hidden md:table-cell">{formatNumber(report.totals.cacheReadTokens)}</td>+ <td className="py-2 px-2 text-right hidden md:table-cell">{formatNumber(report.totals.cacheWriteTokens)}</td><td className="py-2 px-2 text-right">{formatNumber(report.totals.tokensOut)}</td><td className="py-2 pl-2 text-right text-port-success">{formatCost(report.totals.estimatedCost)}</td></tr>@@ -224,6 +250,11 @@ function CostReportTable({ report }) {);}+// Cache token counts, with the hidden-on-mobile columns' values folded into a+// title so the numbers stay reachable when the columns collapse.+const cacheTitle = (row) =>+ `Cache read ${(row.cacheReadTokens ?? 0).toLocaleString()} · cache write ${(row.cacheWriteTokens ?? 0).toLocaleString()} tokens`;+function ProviderCostRows({ provider }) {return (<>@@ -233,9 +264,12 @@ function ProviderCostRows({ provider }) {{provider.free && (<Pill tone="success" size="xs" className="ml-2 uppercase tracking-wide">Local — free</Pill>)}+ {!provider.free && <SourcePill source={provider.source} className="ml-2" />}</td>- <td className="py-2 px-2 text-right">{formatNumber(provider.sessions)}</td>- <td className="py-2 px-2 text-right">{formatNumber(provider.tokensIn)}</td>+ <td className="py-2 px-2 text-right" title={cacheTitle(provider)}>{formatNumber(provider.sessions)}</td>+ <td className="py-2 px-2 text-right" title={cacheTitle(provider)}>{formatNumber(provider.tokensIn)}</td>+ <td className="py-2 px-2 text-right hidden md:table-cell">{formatNumber(provider.cacheReadTokens)}</td>+ <td className="py-2 px-2 text-right hidden md:table-cell">{formatNumber(provider.cacheWriteTokens)}</td><td className="py-2 px-2 text-right">{formatNumber(provider.tokensOut)}</td><tdclassName="py-2 pl-2 text-right"@@ -246,11 +280,18 @@ function ProviderCostRows({ provider }) {</tr>{provider.models.map((m) => (<tr key={m.model} className="text-gray-400">- <td className="py-1.5 pr-2 pl-4 sm:pl-6 font-mono text-xs truncate max-w-[220px]" title={m.rateModel ? `Priced as ${m.rateModel} ($${m.inputPer1M}/$${m.outputPer1M} per 1M)` : undefined}>+ <td+ className="py-1.5 pr-2 pl-4 sm:pl-6 font-mono text-xs truncate max-w-[220px]"+ title={m.rateModel+ ? `Priced as ${m.rateModel} ($${m.inputPer1M}/$${m.outputPer1M} per 1M in/out; $${m.cacheReadPer1M}/$${m.cacheWritePer1M} per 1M cache read/write)`+ : undefined}+ >{m.model}</td><td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.sessions)}</td>- <td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.tokensIn)}</td>+ <td className="py-1.5 px-2 text-right text-xs" title={cacheTitle(m)}>{formatNumber(m.tokensIn)}</td>+ <td className="py-1.5 px-2 text-right text-xs hidden md:table-cell">{formatNumber(m.cacheReadTokens)}</td>+ <td className="py-1.5 px-2 text-right text-xs hidden md:table-cell">{formatNumber(m.cacheWriteTokens)}</td><td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.tokensOut)}</td><td className="py-1.5 pl-2 text-right text-xs" title={approxMark(m.rateMatch) ? 'Approximate — no exact published rate for this model id' : undefined}>{approxMark(m.rateMatch)}{formatCost(m.estimatedCost)}@@ -308,6 +349,8 @@ function InternalUsageMetrics() {const [usage, setUsage] = useState(null);const [loading, setLoading] = useState(true);+ // Bumped after a backfill so the effect below re-reads the corrected buckets.+ const [reloadKey, setReloadKey] = useState(0);useEffect(() => {let cancelled = false;@@ -324,7 +367,20 @@ function InternalUsageMetrics() {setLoading(false);});return () => { cancelled = true; };- }, [period, from, to, isCustom]);+ }, [period, from, to, isCustom, reloadKey]);++ // Re-read the provider CLIs' local transcripts and replace estimated counts+ // with measured ones. `silent: true` because useAsyncAction owns the error+ // toast (the custom-catch ⇒ silent convention).+ const [runBackfill, backfilling] = useAsyncAction(async () => {+ const summary = await api.backfillUsage({ silent: true });+ const measured = summary?.sessions || 0;+ toast.success(measured+ ? `Measured ${measured.toLocaleString()} sessions across ${summary.days} days from ${summary.families.join(' + ')} transcripts.`+ : 'No provider transcripts found to measure — counts stay estimated.');+ setReloadKey((n) => n + 1);+ return summary;+ }, { errorMessage: 'Failed to read provider transcripts' });const setPeriod = (id) => {setSearchParams((prev) => {@@ -397,14 +453,32 @@ function InternalUsageMetrics() {</p>)}</div>- <span className="text-xl font-bold text-port-success">{formatCost(report?.totals?.estimatedCost)}</span>+ <div className="flex items-center gap-2">+ {report?.totals?.source && <SourcePill source={report.totals.source} />}+ <span className="text-xl font-bold text-port-success">{formatCost(report?.totals?.estimatedCost)}</span>+ </div>+ </div>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} />+ <button+ onClick={runBackfill}+ disabled={backfilling}+ className="flex items-center gap-1.5 px-3 py-1 rounded-full text-xs sm:text-sm border border-port-border text-gray-400 hover:text-white disabled:opacity-50"+ title="Re-read the provider CLIs' local transcripts to replace estimated token counts with measured ones. Reads local files only — no AI provider call."+ >+ <FileSearch size={14} className={backfilling ? 'animate-pulse' : ''} />+ {backfilling ? 'Reading transcripts…' : 'Measure from transcripts'}+ </button></div>- <CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} /><CostReportTable report={report} /><p className="text-[10px] sm:text-xs text-gray-500">Informational estimate of what this usage would have cost under API billing (PortOS runs on subscriptions).- Current token counts estimate each run from its initial prompt and captured output; repeated per-turn context and prompt-cache reads/writes are not counted.- Rates are as of {report?.pricingAsOf || 'the last update'} and exclude cache tiers, batch pricing, and long-context tiers.+ {' '}<span className="text-gray-400">Measured</span> rows are the provider CLI’s own per-message counts, read from its local+ transcript — full per-turn input, output, and prompt-cache reads/writes, each priced at its own rate.+ {' '}<span className="text-gray-400">Estimated</span> rows are runs with no readable transcript (local models, or a provider+ that writes none): input is approximated from the initial prompt only and cache traffic is not counted, so those rows+ understate real usage substantially.+ Rates are as of {report?.pricingAsOf || 'the last update'} and exclude batch and long-context tiers.{' '}Rows marked ~ use an approximated rate.</p></div>diff --git a/client/src/services/README.md b/client/src/services/README.mdindex ebf5738654..3ad7b04b44 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -58,7 +58,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiRuns.js` | Agent run history. || `apiScaffold.js` | App scaffolding templates. || `apiSchedules.js` | Automation schedules. |-| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter. |+| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, and `backfillUsage` — re-reads the provider CLIs' local transcripts to replace estimated token counts with measured ones). || `apiAuth.js` | Optional login password — status, login/logout, set/clear password. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex fe44d6b685..62d4596902 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -115,6 +115,12 @@ export const getUsage = (params = {}) => {export const getUsageRaw = () => request('/usage/raw');export const resetUsage = () => request('/usage', { method: 'DELETE' });+// Re-read the provider CLIs' local transcripts and replace estimated token+// counts with measured ones. Explicit user action only (see the route comment).+// `since` is an optional inclusive YYYY-MM-DD floor.+export const backfillUsage = ({ since = null, ...options } = {}) =>+ request('/usage/backfill', { method: 'POST', body: JSON.stringify({ since }), ...options });+// Subscription-quota status for every enabled provider family (claude, codex,// agy, grok). Callers own their inline error UI — silent by default.export const getProviderUsage = ({ refresh = false, ...options } = {}) =>diff --git a/scripts/migrations/210-usage-cache-token-fields.js b/scripts/migrations/210-usage-cache-token-fields.jsnew file mode 100644index 0000000000..0070cd7adc--- /dev/null+++ b/scripts/migrations/210-usage-cache-token-fields.js@@ -0,0 +1,79 @@+/**+ * Seed the prompt-cache token fields and the measured/estimate provenance flag+ * onto existing usage day/month buckets (#3124 Phase 2).+ *+ * Every bucket written before this change holds counts that were ESTIMATED —+ * output from captured stdout, input from the initial prompt length — with no+ * cache-tier counts at all. Stamping them explicitly is what lets the cost+ * report distinguish a measured row from an estimated one instead of leaving+ * older rows unlabeled (and therefore ambiguous).+ *+ * The reader tolerates the absent fields (`?? 0` / `source ?? 'estimate'`), so+ * this migration is a labeling pass, not a correctness prerequisite — but it+ * ships so an install's on-disk shape matches what the code writes, per the+ * distribution rules in CLAUDE.md. The usage store is file-primary and only+ * exists after activity is recorded, so a missing file is a normal no-op.+ */++import { readFile, rename, writeFile } from 'fs/promises';+import { join } from 'path';++/** Add the additive fields to one provider or model bucket. Returns true if it changed. */+function seedBucket(bucket) {+ if (!bucket || typeof bucket !== 'object') return false;+ let changed = false;+ if (typeof bucket.cacheReadTokens !== 'number') {+ bucket.cacheReadTokens = 0;+ changed = true;+ }+ if (typeof bucket.cacheWriteTokens !== 'number') {+ bucket.cacheWriteTokens = 0;+ changed = true;+ }+ if (typeof bucket.source !== 'string') {+ // Pre-existing counts are estimates by definition. A bucket holding no+ // counts yet gets `null` so its first real record decides its provenance.+ const hasCounts = (bucket.tokensIn || 0) > 0 || (bucket.tokensOut || 0) > 0 || (bucket.messages || 0) > 0;+ bucket.source = hasCounts ? 'estimate' : null;+ changed = true;+ }+ return changed;+}++/** Walk a day/month bucket's provider split and its nested per-model splits. */+function seedActivityBucket(bucket) {+ let changed = false;+ for (const providerBucket of Object.values(bucket?.byProvider || {})) {+ changed = seedBucket(providerBucket) || changed;+ for (const modelBucket of Object.values(providerBucket?.byModel || {})) {+ changed = seedBucket(modelBucket) || changed;+ }+ }+ return changed;+}++export async function up({ rootDir }) {+ const usagePath = join(rootDir, 'data', 'usage.json');+ const raw = await readFile(usagePath, 'utf8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return;++ const usage = JSON.parse(raw);+ let changed = false;+ for (const bucket of Object.values(usage.dailyActivity || {})) {+ changed = seedActivityBucket(bucket) || changed;+ }+ for (const bucket of Object.values(usage.monthlyActivity || {})) {+ changed = seedActivityBucket(bucket) || changed;+ }+ if (!changed) return;++ const tempPath = `${usagePath}.210.tmp`;+ await writeFile(tempPath, `${JSON.stringify(usage, null, 2)}\n`);+ await rename(tempPath, usagePath);+ console.log('📊 Migration 210: seeded usage cache-token fields and estimate provenance');+}++export default { up };diff --git a/scripts/migrations/210-usage-cache-token-fields.test.js b/scripts/migrations/210-usage-cache-token-fields.test.jsnew file mode 100644index 0000000000..2f23cc2327--- /dev/null+++ b/scripts/migrations/210-usage-cache-token-fields.test.js@@ -0,0 +1,136 @@+import { afterEach, describe, expect, it } from 'vitest';+import { mkdtemp, readFile, rm, writeFile, mkdir } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { up } from './210-usage-cache-token-fields.js';++const roots = [];++const makeRoot = async () => {+ const root = await mkdtemp(join(tmpdir(), 'migration-210-'));+ roots.push(root);+ await mkdir(join(root, 'data'), { recursive: true });+ return root;+};++const readUsage = async (rootDir) =>+ JSON.parse(await readFile(join(rootDir, 'data', 'usage.json'), 'utf8'));++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++describe('migration 210 — usage cache token fields', () => {+ it('seeds cache fields and stamps existing counts as estimates', async () => {+ const rootDir = await makeRoot();+ await writeFile(join(rootDir, 'data', 'usage.json'), JSON.stringify({+ dailyActivity: {+ '2026-07-20': {+ sessions: 1,+ messages: 2,+ tokens: 400,+ byProvider: {+ 'claude-code': {+ name: 'Claude Code',+ sessions: 1,+ messages: 2,+ tokensIn: 30,+ tokensOut: 400,+ byModel: {+ 'claude-opus-5': { sessions: 1, messages: 2, tokensIn: 30, tokensOut: 400 }+ }+ }+ }+ }+ },+ monthlyActivity: {+ '2026-06': {+ byProvider: {+ codex: { name: 'Codex', sessions: 5, messages: 5, tokensIn: 10, tokensOut: 900, byModel: {} }+ }+ }+ }+ }));++ await up({ rootDir });+ const usage = await readUsage(rootDir);++ const provider = usage.dailyActivity['2026-07-20'].byProvider['claude-code'];+ expect(provider).toMatchObject({ cacheReadTokens: 0, cacheWriteTokens: 0, source: 'estimate' });+ expect(provider.byModel['claude-opus-5']).toMatchObject({ cacheReadTokens: 0, cacheWriteTokens: 0, source: 'estimate' });+ expect(usage.monthlyActivity['2026-06'].byProvider.codex).toMatchObject({ source: 'estimate' });+ // Existing counts are untouched — this is a labeling pass, not a rewrite.+ expect(provider.tokensOut).toBe(400);+ expect(provider.tokensIn).toBe(30);+ });++ it('leaves a bucket with no counts unlabeled so its first record decides', async () => {+ const rootDir = await makeRoot();+ await writeFile(join(rootDir, 'data', 'usage.json'), JSON.stringify({+ dailyActivity: {+ '2026-07-20': {+ sessions: 1,+ byProvider: {+ 'claude-code': { name: 'Claude Code', sessions: 1, messages: 0, tokensIn: 0, tokensOut: 0, byModel: {} }+ }+ }+ }+ }));++ await up({ rootDir });+ const usage = await readUsage(rootDir);+ expect(usage.dailyActivity['2026-07-20'].byProvider['claude-code'].source).toBeNull();+ });++ it('preserves an already-measured source and existing cache counts', async () => {+ const rootDir = await makeRoot();+ await writeFile(join(rootDir, 'data', 'usage.json'), JSON.stringify({+ dailyActivity: {+ '2026-07-20': {+ byProvider: {+ 'claude-code': {+ name: 'Claude Code',+ sessions: 1, messages: 1, tokensIn: 5, tokensOut: 9,+ cacheReadTokens: 1234, cacheWriteTokens: 56, source: 'measured',+ byModel: {}+ }+ }+ }+ }+ }));++ await up({ rootDir });+ const usage = await readUsage(rootDir);+ expect(usage.dailyActivity['2026-07-20'].byProvider['claude-code']).toMatchObject({+ cacheReadTokens: 1234, cacheWriteTokens: 56, source: 'measured'+ });+ });++ it('is idempotent', async () => {+ const rootDir = await makeRoot();+ await writeFile(join(rootDir, 'data', 'usage.json'), JSON.stringify({+ dailyActivity: {+ '2026-07-20': {+ byProvider: { codex: { name: 'Codex', sessions: 1, messages: 1, tokensIn: 1, tokensOut: 2, byModel: {} } }+ }+ }+ }));++ await up({ rootDir });+ const first = await readUsage(rootDir);+ await up({ rootDir });+ expect(await readUsage(rootDir)).toEqual(first);+ });++ it('is a no-op when the usage file does not exist yet', async () => {+ const rootDir = await makeRoot();+ await expect(up({ rootDir })).resolves.toBeUndefined();+ });++ it('tolerates a file with no activity maps at all', async () => {+ const rootDir = await makeRoot();+ await writeFile(join(rootDir, 'data', 'usage.json'), JSON.stringify({ totalSessions: 0 }));+ await expect(up({ rootDir })).resolves.toBeUndefined();+ expect(await readUsage(rootDir)).toEqual({ totalSessions: 0 });+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex d992617820..ab701685a5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -100,8 +100,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `promptPartials.js` | Mustache-style partial expansion. || `mediaModels.js` | Single source of truth for image/video model metadata. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`) plus reasoning-effort helpers for the claude/codex/agy CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, and `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`) plus codex startup-arg helpers (`CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal). |-| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd`, `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); excludes cache/batch/tier discounts. |+| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). |+| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring the models map under `provider.ollama.models` (bare ids) for Ollama-backed OpenCode providers. Fixes --model rejection. || `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. || `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 8e30079e7b..38455d272e 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -106,6 +106,7 @@ export * from './promptPartials.js';export * from './promptRunner.js';export * from './promptTemplate.js';export * from './providerModels.js';+export * from './providerTranscriptUsage.js';export * from './quotaReset.js';export * from './opencodeConfig.js';// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live indiff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsindex 8752472692..1ec0b75582 100644--- a/server/lib/modelPricing.js+++ b/server/lib/modelPricing.js@@ -4,10 +4,18 @@* informational only — they answer "what would the recorded usage have cost* under API billing," never an actual bill.*- * Rates are USD per 1M tokens (standard input/output only — prompt-caching,- * batch, and long-context tier discounts are deliberately ignored; PortOS does- * not capture cache hits, and the UI discloses the approximation). Verified- * against the official pricing pages on PRICING_AS_OF:+ * Rates are USD per 1M tokens. Standard input/output come from the table below;+ * the prompt-cache tiers are derived from the input rate by the multipliers in+ * `CACHE_MULTIPLIERS` (every vendor publishes caching as a fixed ratio of the+ * base input rate, so one multiplier per family beats 4 hand-maintained numbers+ * per model). Batch and long-context tier discounts are still ignored, and the+ * UI discloses the approximation.+ *+ * Cache tiers are NOT a rounding detail: for agentic CLI use, cache reads are+ * >90% of input volume, so pricing them at the standard input rate (or, as+ * PortOS did before #3124, not counting the tokens at all) is the single largest+ * source of error in the estimate. Verified against the official pricing pages+ * on PRICING_AS_OF:* - https://platform.claude.com/docs/en/about-claude/pricing* - https://developers.openai.com/api/docs/pricing* - https://docs.x.ai/docs/pricing@@ -118,17 +126,67 @@ const PROVIDER_DEFAULT_RULES = [// provider/model pair nothing above recognizes.const FALLBACK_RATES = { rateModel: null, inputPer1M: 3.0, outputPer1M: 15.0 };-const toRates = (rateModel) => ({+/**+ * Prompt-cache rates as multipliers of a model's BASE INPUT rate. Every vendor+ * publishes caching as a fixed ratio rather than a standalone number, so one+ * pair per family stays correct when a model's input rate changes and avoids+ * four hand-maintained columns per row in EXACT_RATES.+ *+ * `read` is a cache hit; `write` is the surcharge for first storing content.+ * Verified on PRICING_AS_OF against the pages listed in the header:+ * - Anthropic: 0.1x read, 1.25x 5-minute write (2x for the 1-hour TTL, which+ * Claude Code does not use — `cache_creation_input_tokens` is 5-minute).+ * - OpenAI: 0.1x cached input; only gpt-5.6 lists a separate cache-write rate+ * (~1.25x), and Codex reports no cache-write tokens at all.+ * - xAI: cached prompt tokens run 0.15-0.20x depending on the model (0.15x on+ * grok-4.5); no published cache-write surcharge.+ * - Google: 0.1x cached input, plus an hourly storage fee we do not model+ * (PortOS records no cache duration to price it against).+ *+ * The default matches Anthropic/OpenAI (0.1x / 1.25x), which covers every+ * provider that actually reports cache tokens to PortOS today — Claude Code and+ * Codex are the only CLIs that write per-message cache counts to disk (see+ * `lib/providerTranscriptUsage.js`), so any other family's multiplier applies to+ * a token count that is currently always 0.+ */+const DEFAULT_CACHE_MULTIPLIERS = { read: 0.1, write: 1.25 };+const CACHE_MULTIPLIER_RULES = [+ { test: /^grok/, read: 0.15, write: 1.25 },+];++const cacheMultipliers = (rateModel) => {+ const id = typeof rateModel === 'string' ? rateModel : '';+ return CACHE_MULTIPLIER_RULES.find((rule) => rule.test.test(id)) || DEFAULT_CACHE_MULTIPLIERS;+};++/**+ * Expand a base input/output rate pair with its derived cache-tier rates. Used+ * for both table hits and the generic fallback so every rate object carries the+ * same four fields — a caller can price cache tokens without checking which+ * tier answered.+ */+const withCacheRates = (rates) => {+ const { read, write } = cacheMultipliers(rates.rateModel);+ return {+ ...rates,+ cacheReadPer1M: rates.inputPer1M * read,+ cacheWritePer1M: rates.inputPer1M * write,+ };+};++const toRates = (rateModel) => withCacheRates({rateModel,inputPer1M: EXACT_RATES[rateModel][0],outputPer1M: EXACT_RATES[rateModel][1],});/**- * Resolve billing rates for a (providerId, model) pair.+ * Resolve billing rates for a (providerId, model) pair. `cacheReadPer1M` /+ * `cacheWritePer1M` are derived from the input rate (see CACHE_MULTIPLIER_RULES).* @param {string|null|undefined} providerId* @param {string|null|undefined} model* @returns {{ rateModel: string|null, inputPer1M: number, outputPer1M: number,+ * cacheReadPer1M: number, cacheWritePer1M: number,* matched: 'exact'|'family'|'providerDefault'|'fallback' }}*/export function resolveModelRates(providerId, model) {@@ -154,7 +212,7 @@ export function resolveModelRates(providerId, model) {return { ...toRates(rule.rateModel), matched: 'providerDefault' };}}- return { ...FALLBACK_RATES, matched: 'fallback' };+ return { ...withCacheRates(FALLBACK_RATES), matched: 'fallback' };}// Mirrors promptRunner.js's LOCAL_ENDPOINT_RE (scheme optional, unbracketed@@ -164,6 +222,30 @@ export function resolveModelRates(providerId, model) {const LOCALHOST_ENDPOINT = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;const FREE_ID = /ollama|lmstudio|lm-studio/i;+// Ollama/LM Studio name their models `family:tag` (`qwen3.6:35b`,+// `llama3.1:8b-instruct-q8_0`) or `org/repo` for a pulled GGUF. No hosted+// model id in EXACT_RATES contains a colon, so the tag is an unambiguous+// local-inference marker.+const LOCAL_MODEL_ID = /:|^[\w.-]+\/[\w.-]+$/;++/**+ * True when a MODEL id is local-inference (free), independent of which provider+ * ran it. Needed because a Claude-Code-flavored CLI can be pointed at an Ollama+ * backend: its transcript records `qwen3.6:35b`, which would otherwise resolve+ * through the `claude` provider default and be billed at Sonnet rates. Used by+ * the transcript backfill, where the model id is the only attribution available+ * (a transcript does not record which PortOS provider config invoked it).+ * @param {string|null|undefined} model+ * @returns {boolean}+ */+export function isFreeModelId(model) {+ const id = typeof model === 'string' ? model.trim() : '';+ if (!id) return false;+ // A hosted id we have a real rate for is never local, whatever its shape.+ if (EXACT_RATES[id]) return false;+ return FREE_ID.test(id) || LOCAL_MODEL_ID.test(id);+}+/*** True when a provider's usage is free — local inference (Ollama, LM Studio,* any `ollamaBacked` CLI wrapper, or an API provider pointed at localhost).@@ -185,13 +267,25 @@ export function isFreeProvider(providerOrId) {/*** Estimated USD cost for a token count under the given rates. Returns the raw* float — callers round for display.- * @param {number} tokensIn+ *+ * `tokensIn` is the UNCACHED input only; cache reads and writes are billed at+ * their own tiers via the optional 4th argument. Passing them as `tokensIn`+ * would overcharge a cache read by 10x — for agentic CLI runs, where cache reads+ * are >90% of input volume, that dwarfs every other error in the estimate.+ *+ * The cache argument is optional so the three-positional-argument form keeps+ * working for records that predate cache capture (absent = 0, no cache cost).+ *+ * @param {number} tokensIn uncached input tokens* @param {number} tokensOut- * @param {{inputPer1M: number, outputPer1M: number}} rates+ * @param {{inputPer1M: number, outputPer1M: number, cacheReadPer1M?: number, cacheWritePer1M?: number}} rates+ * @param {{cacheReadTokens?: number, cacheWriteTokens?: number}} [cache]* @returns {number}*/-export function estimateCostUsd(tokensIn, tokensOut, rates) {- const input = ((tokensIn || 0) / 1_000_000) * (rates?.inputPer1M || 0);- const output = ((tokensOut || 0) / 1_000_000) * (rates?.outputPer1M || 0);- return input + output;+export function estimateCostUsd(tokensIn, tokensOut, rates, cache = null) {+ const perMillion = (tokens, rate) => ((tokens || 0) / 1_000_000) * (rate || 0);+ return perMillion(tokensIn, rates?.inputPer1M)+ + perMillion(tokensOut, rates?.outputPer1M)+ + perMillion(cache?.cacheReadTokens, rates?.cacheReadPer1M)+ + perMillion(cache?.cacheWriteTokens, rates?.cacheWritePer1M);}diff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.jsindex 5cbd253012..3ff0f526c6 100644--- a/server/lib/modelPricing.test.js+++ b/server/lib/modelPricing.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { resolveModelRates, isFreeProvider, estimateCostUsd, PRICING_AS_OF } from './modelPricing.js';+import { resolveModelRates, isFreeProvider, isFreeModelId, estimateCostUsd, PRICING_AS_OF } from './modelPricing.js';describe('resolveModelRates', () => {it('matches exact model ids', () => {@@ -119,4 +119,102 @@ describe('estimateCostUsd', () => {expect(estimateCostUsd(null, undefined, { inputPer1M: 3, outputPer1M: 15 })).toBe(0);expect(estimateCostUsd(1000, 1000, null)).toBe(0);});++ it('prices cache read and cache write at their own per-1M rates', () => {+ const rates = { inputPer1M: 5, outputPer1M: 25, cacheReadPer1M: 0.5, cacheWritePer1M: 6.25 };+ const cost = estimateCostUsd(0, 0, rates, { cacheReadTokens: 1_000_000, cacheWriteTokens: 1_000_000 });+ expect(cost).toBeCloseTo(0.5 + 6.25);+ });++ it('omits cache cost entirely when the 4th argument is absent (back-compat)', () => {+ const rates = resolveModelRates('claude-code', 'claude-opus-5');+ expect(estimateCostUsd(1_000_000, 0, rates)).toBeCloseTo(5);+ });++ it('bills a cache read at 10% of the input rate for an Anthropic model', () => {+ const rates = resolveModelRates('claude-code', 'claude-opus-5');+ const inputCost = estimateCostUsd(1_000_000, 0, rates);+ const cacheReadCost = estimateCostUsd(0, 0, rates, { cacheReadTokens: 1_000_000 });+ expect(cacheReadCost).toBeCloseTo(inputCost * 0.1);+ expect(cacheReadCost).toBeCloseTo(0.5); // $5/MTok input → $0.50/MTok cache hit+ });++ it('bills a 5-minute cache write at 1.25x the input rate', () => {+ const rates = resolveModelRates('claude-code', 'claude-opus-5');+ expect(estimateCostUsd(0, 0, rates, { cacheWriteTokens: 1_000_000 })).toBeCloseTo(6.25);+ });++ // The #3124 regression in one assertion: charging cache reads at the standard+ // input rate overstates them 10x, and not counting them at all understates the+ // whole run by ~90% of its real input volume.+ it('prices a cache-heavy agentic run far below the same volume as fresh input', () => {+ const rates = resolveModelRates('claude-code', 'claude-opus-5');+ const asCacheReads = estimateCostUsd(0, 0, rates, { cacheReadTokens: 10_000_000 });+ const asFreshInput = estimateCostUsd(10_000_000, 0, rates);+ expect(asCacheReads).toBeCloseTo(asFreshInput * 0.1);+ // …but is emphatically NOT free, which is what omitting the tier implied.+ expect(asCacheReads).toBeGreaterThan(0);+ });+});++describe('cache-tier rates on resolveModelRates', () => {+ it('derives both cache tiers from the input rate on every match tier', () => {+ for (const [providerId, model] of [+ ['claude-code', 'claude-opus-5'], // exact+ ['claude-code', 'opus'], // family+ ['claude-code', 'no-such-model'], // providerDefault+ ['who-knows', 'no-such-model'] // fallback+ ]) {+ const rates = resolveModelRates(providerId, model);+ expect(rates.cacheReadPer1M).toBeCloseTo(rates.inputPer1M * 0.1);+ expect(rates.cacheWritePer1M).toBeCloseTo(rates.inputPer1M * 1.25);+ }+ });++ it('uses xAI\'s higher published cached-input ratio for grok', () => {+ const rates = resolveModelRates('grok', 'grok-4.5');+ expect(rates.inputPer1M).toBe(2);+ expect(rates.cacheReadPer1M).toBeCloseTo(0.3); // 0.15x per docs.x.ai+ });++ it('keeps the OpenAI/Codex 10% cached-input ratio', () => {+ const rates = resolveModelRates('codex', 'gpt-5.3-codex');+ expect(rates.cacheReadPer1M).toBeCloseTo(rates.inputPer1M * 0.1);+ });+});++describe('isFreeModelId', () => {+ it('treats Ollama/LM Studio family:tag ids as local (free)', () => {+ for (const id of ['qwen3.6:35b', 'llama3.1:8b-instruct-q8_0', 'gpt-oss:120b', 'deepseek-r1:7b']) {+ expect(isFreeModelId(id)).toBe(true);+ }+ });++ it('treats an org/repo GGUF reference as local', () => {+ expect(isFreeModelId('unsloth/Qwen3-30B')).toBe(true);+ });++ it('does NOT treat hosted model ids as local', () => {+ for (const id of [+ 'claude-opus-5', 'claude-fable-5', 'gpt-5.3-codex', 'grok-4.5',+ 'gemini-3.1-pro-preview', 'global.anthropic.claude-opus-5', 'opus', 'sonnet'+ ]) {+ expect(isFreeModelId(id)).toBe(false);+ }+ });++ it('is false for empty/nullish input', () => {+ expect(isFreeModelId(null)).toBe(false);+ expect(isFreeModelId('')).toBe(false);+ expect(isFreeModelId(undefined)).toBe(false);+ });++ // Regression: a Claude-Code CLI pointed at an Ollama backend records the LOCAL+ // model id in its transcript. Billing it through the `claude` provider default+ // invented ~$166 of cost on a real install.+ it('keeps a local model free even when it arrives via a claude provider', () => {+ expect(isFreeModelId('qwen3.6:35b')).toBe(true);+ // The provider-level check can't catch this on its own — hence the model check.+ expect(isFreeProvider('claude-code')).toBe(false);+ });});diff --git a/server/lib/providerTranscriptUsage.js b/server/lib/providerTranscriptUsage.jsnew file mode 100644index 0000000000..c4a1f464cd--- /dev/null+++ b/server/lib/providerTranscriptUsage.js@@ -0,0 +1,275 @@+/**+ * Parsers for the per-message token counts the coding CLIs already write to+ * disk. PortOS's own accounting (`services/usage.js`) can only *estimate*+ * tokens — output from captured stdout (a repainted screen for TUI providers)+ * and input from the initial prompt length, which misses the per-turn context+ * replay and prompt-cache traffic that dominate real API cost. These files are+ * ground truth, cost 0 tokens to read, and are written by the CLI itself:+ *+ * Claude Code — ~/.claude/projects/<cwd-slug>/<session>.jsonl+ * One JSON object per line. Assistant lines carry+ * `message.usage = { input_tokens, cache_creation_input_tokens,+ * cache_read_input_tokens, output_tokens }` plus `message.model`; most+ * lines also carry `cwd`, `sessionId`, and `timestamp`.+ *+ * Codex — ~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<uuid>.jsonl+ * Line 1 is a `session_meta` payload with `id`/`cwd`/`cli_version`. Later+ * `event_msg`/`token_count` lines carry a CUMULATIVE `total_token_usage`+ * plus the per-turn `last_token_usage`.+ *+ * Both formats have a de-duplication hazard that makes naive summing wrong by+ * a large factor, documented at each parser. Both parsers are pure (text in,+ * totals out), tolerant of truncated trailing lines (a session still being+ * written), and ignore unknown fields so a CLI update can't break them.+ */++/**+ * Slugify a working directory the way Claude Code names its project folder:+ * every `/` and `.` becomes `-`. An absolute POSIX path therefore keeps its+ * leading `-` (`/Users/x/repo` → `-Users-x-repo`), which is what the CLI does.+ * @param {string} cwd+ * @returns {string}+ */+export function claudeProjectSlug(cwd) {+ return String(cwd || '').replace(/[/.]/g, '-');+}++/**+ * Parse newline-delimited JSON, skipping blank lines and any line that doesn't+ * parse. A partially-flushed final line is the common case for a session still+ * being appended to, so an unparseable line is normal input, not an error.+ * @param {string} text+ * @returns {object[]}+ */+function parseJsonLines(text) {+ const out = [];+ for (const line of String(text || '').split('\n')) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ // A truncated mid-write line is expected — skip it rather than throw.+ // (JSON.parse has no non-throwing form, so this try/catch is the parse.)+ try {+ const parsed = JSON.parse(trimmed);+ if (parsed && typeof parsed === 'object') out.push(parsed);+ } catch {+ continue;+ }+ }+ return out;+}++const num = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0);++const emptyTotals = () => ({+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0+});++/** ISO timestamp → epoch ms, or null when absent/unparseable. */+const toEpoch = (value) => {+ if (typeof value !== 'string' || !value) return null;+ const ms = Date.parse(value);+ return Number.isNaN(ms) ? null : ms;+};++/**+ * True when `ts` falls inside `[from, to]`. A null bound is open; a null `ts`+ * is treated as inside the window — a line whose timestamp we can't read is+ * better attributed to the run we're reconciling (the file was located by cwd+ * slug) than silently dropped, which would under-count.+ */+const inWindow = (ts, from, to) => {+ if (ts == null) return true;+ if (from != null && ts < from) return false;+ if (to != null && ts > to) return false;+ return true;+};++/**+ * Parse a Claude Code session transcript.+ *+ * **De-duplication is load-bearing.** One API response is written to the+ * transcript as SEVERAL lines that share the same `message.id`, `requestId`,+ * and an identical `message.usage` — the CLI re-emits the assistant record as+ * it streams/annotates content blocks. On a measured session, 1,734 assistant+ * lines represented only 740 distinct responses, so summing per line inflates+ * every token count (and therefore the cost) by ~2.3×. We count each+ * `message.id` exactly once. Lines with no id fall back to their own `uuid`+ * so they still count once rather than being dropped.+ *+ * Sub-agent (`isSidechain`) messages ARE counted: their tokens are billed to+ * the same account, and PortOS records one run per parent invocation.+ *+ * @param {string} jsonlText raw file contents (may end mid-line)+ * @param {{ from?: number|null, to?: number|null }} [window] epoch-ms bounds;+ * assistant messages outside the window are excluded (used to attribute a+ * long-lived CLI session to one PortOS run).+ * @returns {{ sessionId: string|null, cwd: string|null, model: string|null,+ * models: string[], messages: number, tokensIn: number, tokensOut: number,+ * cacheReadTokens: number, cacheWriteTokens: number,+ * firstTs: string|null, lastTs: string|null }}+ */+export function parseClaudeTranscript(jsonlText, { from = null, to = null } = {}) {+ const totals = emptyTotals();+ const seen = new Set();+ const modelCounts = new Map();+ let sessionId = null;+ let cwd = null;+ let firstTs = null;+ let lastTs = null;++ for (const entry of parseJsonLines(jsonlText)) {+ if (!sessionId && typeof entry.sessionId === 'string') sessionId = entry.sessionId;+ if (!cwd && typeof entry.cwd === 'string') cwd = entry.cwd;++ const usage = entry.type === 'assistant' ? entry.message?.usage : null;+ if (!usage || typeof usage !== 'object') continue;++ const ts = toEpoch(entry.timestamp);+ if (!inWindow(ts, from, to)) continue;++ // One response spans multiple lines with identical usage — count it once.+ const dedupeKey = entry.message?.id || entry.uuid;+ if (dedupeKey) {+ if (seen.has(dedupeKey)) continue;+ seen.add(dedupeKey);+ }++ totals.messages += 1;+ totals.tokensIn += num(usage.input_tokens);+ totals.tokensOut += num(usage.output_tokens);+ totals.cacheReadTokens += num(usage.cache_read_input_tokens);+ totals.cacheWriteTokens += num(usage.cache_creation_input_tokens);++ const model = typeof entry.message?.model === 'string' ? entry.message.model : null;+ if (model) modelCounts.set(model, (modelCounts.get(model) || 0) + 1);++ if (typeof entry.timestamp === 'string' && entry.timestamp) {+ if (!firstTs || entry.timestamp < firstTs) firstTs = entry.timestamp;+ if (!lastTs || entry.timestamp > lastTs) lastTs = entry.timestamp;+ }+ }++ // A session can switch models mid-run (/model, or a fallback). Report every+ // model seen, plus the most-used one as the single `model` attribution.+ const models = [...modelCounts.keys()];+ const model = models.length+ ? [...modelCounts.entries()].sort((a, b) => b[1] - a[1])[0][0]+ : null;++ return { sessionId, cwd, model, models, ...totals, firstTs, lastTs };+}++/**+ * Parse a Codex rollout transcript.+ *+ * **`total_token_usage` is cumulative, and its events repeat.** Every+ * `event_msg`/`token_count` line restates the running total for the whole+ * session, and consecutive lines commonly repeat an unchanged total. So+ * neither summing `total_token_usage` (which would multiply the session by its+ * event count) nor summing `last_token_usage` (which double-counts, because a+ * repeated event repeats its `last` block too) is correct. We take the LAST+ * total in range — the cumulative figure already is the session sum.+ *+ * `input_tokens` is the *total* input including the cached portion, so the+ * uncached input we bill at the standard rate is `input - cached`, with+ * `cached` priced at the provider's cached-input rate. Codex reports no+ * cache-write tier, so `cacheWriteTokens` is always 0. `reasoning_output_tokens`+ * is a subset of `output_tokens` (already billed as output), not an addition.+ *+ * When a window is supplied and no in-range event exists but earlier events do,+ * the delta from the last pre-window total is used, so a rollout spanning two+ * PortOS runs attributes each run only its own increment.+ *+ * @param {string} jsonlText raw file contents (may end mid-line)+ * @param {{ from?: number|null, to?: number|null }} [window] epoch-ms bounds+ * @returns {{ sessionId: string|null, cwd: string|null, model: string|null,+ * models: string[], messages: number, tokensIn: number, tokensOut: number,+ * cacheReadTokens: number, cacheWriteTokens: number,+ * firstTs: string|null, lastTs: string|null }}+ */+export function parseCodexRollout(jsonlText, { from = null, to = null } = {}) {+ let sessionId = null;+ let cwd = null;+ let model = null;+ let messages = 0;+ let firstTs = null;+ let lastTs = null;+ // Cumulative snapshots: the last one before the window start is the+ // baseline; the last one inside the window is the end state.+ let baseline = null;+ let latest = null;++ for (const entry of parseJsonLines(jsonlText)) {+ const payload = entry.payload;+ if (entry.type === 'session_meta' && payload && typeof payload === 'object') {+ if (typeof payload.id === 'string') sessionId ??= payload.id;+ if (typeof payload.cwd === 'string') cwd ??= payload.cwd;+ if (typeof payload.model === 'string') model ??= payload.model;+ continue;+ }+ // The model can also arrive on a per-turn context record.+ if (entry.type === 'turn_context' && typeof payload?.model === 'string') {+ model ??= payload.model;+ }+ if (payload?.type === 'agent_message') messages += 1;+ if (payload?.type !== 'token_count') continue;++ const total = payload.info?.total_token_usage;+ if (!total || typeof total !== 'object') continue;++ const ts = toEpoch(entry.timestamp);+ if (from != null && ts != null && ts < from) {+ baseline = total; // pre-window state — subtract it below+ continue;+ }+ if (to != null && ts != null && ts > to) continue;++ latest = total;+ if (typeof entry.timestamp === 'string' && entry.timestamp) {+ if (!firstTs || entry.timestamp < firstTs) firstTs = entry.timestamp;+ if (!lastTs || entry.timestamp > lastTs) lastTs = entry.timestamp;+ }+ }++ if (!latest) {+ return { sessionId, cwd, model, models: model ? [model] : [], ...emptyTotals(), firstTs, lastTs };+ }++ // Cumulative delta against the pre-window baseline (0 when unwindowed).+ const delta = (key) => Math.max(0, num(latest[key]) - num(baseline?.[key]));+ const cachedIn = delta('cached_input_tokens');+ const totalIn = delta('input_tokens');++ return {+ sessionId,+ cwd,+ model,+ models: model ? [model] : [],+ // Codex reports no per-message split; a rollout is one recorded exchange+ // when it produced any assistant message.+ messages: messages || 1,+ // `input_tokens` INCLUDES the cached portion — split it so each tier is+ // priced at its own rate instead of billing cache reads as fresh input.+ tokensIn: Math.max(0, totalIn - cachedIn),+ tokensOut: delta('output_tokens'),+ cacheReadTokens: cachedIn,+ cacheWriteTokens: 0,+ firstTs,+ lastTs+ };+}++/**+ * Sum of every billable token bucket — the "did we measure anything" test used+ * by the reconciler to decide between a measured record and the estimate.+ * @param {{ tokensIn?: number, tokensOut?: number, cacheReadTokens?: number, cacheWriteTokens?: number }} totals+ * @returns {number}+ */+export function totalTranscriptTokens(totals) {+ return num(totals?.tokensIn) + num(totals?.tokensOut)+ + num(totals?.cacheReadTokens) + num(totals?.cacheWriteTokens);+}diff --git a/server/lib/providerTranscriptUsage.test.js b/server/lib/providerTranscriptUsage.test.jsnew file mode 100644index 0000000000..bed9045409--- /dev/null+++ b/server/lib/providerTranscriptUsage.test.js@@ -0,0 +1,287 @@+import { describe, it, expect } from 'vitest';+import {+ claudeProjectSlug,+ parseClaudeTranscript,+ parseCodexRollout,+ totalTranscriptTokens+} from './providerTranscriptUsage.js';++// Fixtures are hand-authored to match the real formats (verified against a live+// install) with invented paths/ids — never a transcribed real record, per the+// Sensitive Data rules in CLAUDE.md.++const claudeLine = (overrides = {}) => JSON.stringify({+ type: 'assistant',+ uuid: overrides.uuid ?? 'uuid-1',+ sessionId: 'sess-abc',+ cwd: '/work/example-repo',+ timestamp: overrides.timestamp ?? '2026-07-01T10:00:00.000Z',+ requestId: overrides.requestId ?? 'req_1',+ message: {+ id: overrides.id ?? 'msg_1',+ model: overrides.model ?? 'claude-opus-5',+ role: 'assistant',+ usage: {+ input_tokens: overrides.input ?? 10,+ cache_creation_input_tokens: overrides.cacheWrite ?? 100,+ cache_read_input_tokens: overrides.cacheRead ?? 1000,+ output_tokens: overrides.output ?? 50,+ ...(overrides.usageExtras || {})+ }+ }+});++describe('claudeProjectSlug', () => {+ it('replaces slashes and dots the way the CLI names its project directory', () => {+ expect(claudeProjectSlug('/work/github.com/acme/Example'))+ .toBe('-work-github-com-acme-Example');+ });++ it('tolerates nullish input', () => {+ expect(claudeProjectSlug(null)).toBe('');+ });+});++describe('parseClaudeTranscript', () => {+ it('sums a complete session across every token tier', () => {+ const text = [+ claudeLine({ id: 'msg_1', uuid: 'u1' }),+ claudeLine({ id: 'msg_2', uuid: 'u2', input: 5, cacheWrite: 20, cacheRead: 500, output: 25 })+ ].join('\n');++ const result = parseClaudeTranscript(text);+ expect(result).toMatchObject({+ sessionId: 'sess-abc',+ cwd: '/work/example-repo',+ model: 'claude-opus-5',+ messages: 2,+ tokensIn: 15,+ cacheWriteTokens: 120,+ cacheReadTokens: 1500,+ tokensOut: 75+ });+ });++ // The load-bearing behavior: the CLI writes one API response as SEVERAL lines+ // sharing a message.id and an identical usage block. Summing per line inflated+ // a measured session's counts ~2.3x.+ it('counts a response ONCE even when repeated across lines with the same message.id', () => {+ const text = [+ claudeLine({ id: 'msg_dup', uuid: 'u1' }),+ claudeLine({ id: 'msg_dup', uuid: 'u2' }),+ claudeLine({ id: 'msg_dup', uuid: 'u3' })+ ].join('\n');++ const result = parseClaudeTranscript(text);+ expect(result.messages).toBe(1);+ expect(result.tokensOut).toBe(50);+ expect(result.cacheReadTokens).toBe(1000);+ });++ it('still counts a line with no message.id, keyed by its own uuid', () => {+ const noId = JSON.parse(claudeLine({ uuid: 'u9' }));+ delete noId.message.id;+ const text = [JSON.stringify(noId), JSON.stringify(noId)].join('\n');+ // Both lines carry the same uuid, so it is still one response.+ expect(parseClaudeTranscript(text).messages).toBe(1);+ });++ it('tolerates a truncated final line (session still being written)', () => {+ const text = `${claudeLine({ id: 'msg_1' })}\n{"type":"assistant","message":{"id":"msg_2","usa`;+ const result = parseClaudeTranscript(text);+ expect(result.messages).toBe(1);+ expect(result.tokensOut).toBe(50);+ });++ it('returns zeroes for a session with no assistant messages', () => {+ const text = [+ JSON.stringify({ type: 'user', sessionId: 'sess-abc', cwd: '/work/example-repo', message: { role: 'user' } }),+ JSON.stringify({ type: 'system', sessionId: 'sess-abc' })+ ].join('\n');++ const result = parseClaudeTranscript(text);+ expect(result).toMatchObject({ messages: 0, tokensIn: 0, tokensOut: 0, cacheReadTokens: 0, cacheWriteTokens: 0 });+ // Session metadata is still recovered from non-assistant lines.+ expect(result.sessionId).toBe('sess-abc');+ expect(result.cwd).toBe('/work/example-repo');+ expect(totalTranscriptTokens(result)).toBe(0);+ });++ it('ignores unknown and extra fields', () => {+ const text = claudeLine({+ usageExtras: { server_tool_use: { web_search_requests: 2 }, service_tier: 'standard', brand_new_field: 7 }+ });+ const result = parseClaudeTranscript(text);+ expect(result.tokensOut).toBe(50);+ expect(result.messages).toBe(1);+ });++ it('windows by timestamp so one CLI session can split across two runs', () => {+ const text = [+ claudeLine({ id: 'early', timestamp: '2026-07-01T09:00:00.000Z' }),+ claudeLine({ id: 'late', timestamp: '2026-07-01T12:00:00.000Z' })+ ].join('\n');++ const windowed = parseClaudeTranscript(text, { from: Date.parse('2026-07-01T11:00:00.000Z') });+ expect(windowed.messages).toBe(1);+ expect(windowed.tokensOut).toBe(50);+ });++ it('reports every model seen and attributes the most-used one', () => {+ const text = [+ claudeLine({ id: 'a', model: 'claude-sonnet-5' }),+ claudeLine({ id: 'b', model: 'claude-opus-5' }),+ claudeLine({ id: 'c', model: 'claude-opus-5' })+ ].join('\n');++ const result = parseClaudeTranscript(text);+ expect(result.model).toBe('claude-opus-5');+ expect(result.models.sort()).toEqual(['claude-opus-5', 'claude-sonnet-5']);+ });++ it('ignores negative or non-numeric token values', () => {+ // Build the usage block directly — the fixture helper's `??` defaults would+ // swallow an explicit null before it reached the parser.+ const text = JSON.stringify({+ type: 'assistant',+ uuid: 'u1',+ message: {+ id: 'msg_1',+ model: 'claude-opus-5',+ usage: {+ input_tokens: -5,+ output_tokens: 'lots',+ cache_read_input_tokens: null,+ cache_creation_input_tokens: 10+ }+ }+ });+ const result = parseClaudeTranscript(text);+ expect(result).toMatchObject({ tokensIn: 0, tokensOut: 0, cacheReadTokens: 0, cacheWriteTokens: 10 });+ });+});++const codexMeta = (cwd = '/work/example-repo') => JSON.stringify({+ timestamp: '2026-07-01T10:00:00.000Z',+ type: 'session_meta',+ payload: { id: 'rollout-abc', cwd, cli_version: '0.0.0', originator: 'codex_cli_rs', model: 'gpt-5.3-codex' }+});++const codexTokenCount = ({ timestamp, input, cached, output, reasoning = 0 }) => JSON.stringify({+ timestamp,+ type: 'event_msg',+ payload: {+ type: 'token_count',+ info: {+ total_token_usage: {+ input_tokens: input,+ cached_input_tokens: cached,+ output_tokens: output,+ reasoning_output_tokens: reasoning,+ total_tokens: input + output+ },+ last_token_usage: { input_tokens: input, cached_input_tokens: cached, output_tokens: output }+ }+ }+});++describe('parseCodexRollout', () => {+ // total_token_usage is CUMULATIVE and its events repeat verbatim — summing+ // either the totals or the per-turn `last` blocks over-counts badly.+ it('takes the final cumulative total rather than summing repeated events', () => {+ const text = [+ codexMeta(),+ codexTokenCount({ timestamp: '2026-07-01T10:00:01.000Z', input: 1000, cached: 800, output: 100 }),+ codexTokenCount({ timestamp: '2026-07-01T10:00:02.000Z', input: 1000, cached: 800, output: 100 }),+ codexTokenCount({ timestamp: '2026-07-01T10:00:03.000Z', input: 3000, cached: 2400, output: 250 })+ ].join('\n');++ const result = parseCodexRollout(text);+ // input_tokens INCLUDES the cached portion, so uncached input is 3000-2400.+ expect(result).toMatchObject({+ sessionId: 'rollout-abc',+ cwd: '/work/example-repo',+ model: 'gpt-5.3-codex',+ tokensIn: 600,+ cacheReadTokens: 2400,+ tokensOut: 250,+ cacheWriteTokens: 0+ });+ });++ it('windows by taking the delta from the last pre-window total', () => {+ const text = [+ codexMeta(),+ codexTokenCount({ timestamp: '2026-07-01T09:00:00.000Z', input: 1000, cached: 800, output: 100 }),+ codexTokenCount({ timestamp: '2026-07-01T12:00:00.000Z', input: 3000, cached: 2400, output: 250 })+ ].join('\n');++ // A rollout spanning two PortOS runs bills each only its own increment.+ const result = parseCodexRollout(text, { from: Date.parse('2026-07-01T11:00:00.000Z') });+ expect(result.tokensOut).toBe(150); // 250 - 100+ expect(result.cacheReadTokens).toBe(1600); // 2400 - 800+ expect(result.tokensIn).toBe(400); // (3000-2400) - (1000-800)+ });++ it('tolerates a truncated final line', () => {+ const text = [+ codexMeta(),+ codexTokenCount({ timestamp: '2026-07-01T10:00:01.000Z', input: 1000, cached: 800, output: 100 }),+ '{"timestamp":"2026-07-01T10:00:02.000Z","type":"event_msg","payload":{"type":"token_c'+ ].join('\n');++ const result = parseCodexRollout(text);+ expect(result.tokensOut).toBe(100);+ expect(result.sessionId).toBe('rollout-abc');+ });++ it('returns zeroes for a rollout with no token_count events', () => {+ const result = parseCodexRollout(codexMeta());+ expect(result).toMatchObject({ messages: 0, tokensIn: 0, tokensOut: 0, cacheReadTokens: 0 });+ // Metadata is still recovered so the caller can match on cwd.+ expect(result.cwd).toBe('/work/example-repo');+ expect(totalTranscriptTokens(result)).toBe(0);+ });++ it('ignores unknown line and payload types', () => {+ const text = [+ codexMeta(),+ JSON.stringify({ timestamp: '2026-07-01T10:00:01.000Z', type: 'brand_new_type', payload: { type: 'whatever', info: { total_token_usage: { input_tokens: 999999 } } } }),+ JSON.stringify({ timestamp: '2026-07-01T10:00:02.000Z', type: 'event_msg', payload: { type: 'agent_message', message: 'hi' } }),+ codexTokenCount({ timestamp: '2026-07-01T10:00:03.000Z', input: 500, cached: 0, output: 20 })+ ].join('\n');++ const result = parseCodexRollout(text);+ expect(result.tokensIn).toBe(500);+ expect(result.tokensOut).toBe(20);+ expect(result.messages).toBe(1); // the one agent_message+ });++ it('handles an empty file', () => {+ expect(parseCodexRollout('')).toMatchObject({ sessionId: null, tokensIn: 0, tokensOut: 0 });+ });++ it('never returns a negative delta when a total appears to regress', () => {+ const text = [+ codexMeta(),+ codexTokenCount({ timestamp: '2026-07-01T09:00:00.000Z', input: 5000, cached: 4000, output: 500 }),+ codexTokenCount({ timestamp: '2026-07-01T12:00:00.000Z', input: 1000, cached: 800, output: 100 })+ ].join('\n');++ const result = parseCodexRollout(text, { from: Date.parse('2026-07-01T11:00:00.000Z') });+ expect(result.tokensIn).toBe(0);+ expect(result.tokensOut).toBe(0);+ expect(result.cacheReadTokens).toBe(0);+ });+});++describe('totalTranscriptTokens', () => {+ it('sums every billable bucket', () => {+ expect(totalTranscriptTokens({ tokensIn: 1, tokensOut: 2, cacheReadTokens: 3, cacheWriteTokens: 4 })).toBe(10);+ });++ it('treats missing buckets as zero', () => {+ expect(totalTranscriptTokens({})).toBe(0);+ expect(totalTranscriptTokens(null)).toBe(0);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 3da9729b8e..854271ee01 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -707,6 +707,16 @@ export const usageMessagesSchema = z.object({inputTokenCount: z.number().int().nonnegative().optional().default(0)});+/**+ * Body for POST /api/usage/backfill — re-read the provider CLIs' on-disk+ * transcripts and replace estimated day buckets with measured counts. `since`+ * bounds how far back to walk (inclusive YYYY-MM-DD); omitted means every+ * transcript on disk.+ */+export const usageBackfillSchema = z.object({+ since: isoDay.nullish()+});+// =============================================================================// PORTS// =============================================================================diff --git a/server/routes/usage.js b/server/routes/usage.jsindex 29a58de176..8259758aa5 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -4,7 +4,8 @@ import { getClaudeCodeUsage } from '../services/claudeCodeUsage.js';import { getProviderQuotas } from '../services/providerUsage.js';import { getAllProviders } from '../services/providers.js';import { asyncHandler } from '../lib/errorHandler.js';-import { validateRequest, usageQuerySchema, usageMessagesSchema } from '../lib/validation.js';+import { validateRequest, usageQuerySchema, usageMessagesSchema, usageBackfillSchema } from '../lib/validation.js';+import { backfillMeasuredUsage } from '../services/usageReconciler.js';import { resolveUsageRange } from '../lib/usageRange.js';const router = Router();@@ -58,6 +59,18 @@ router.post('/messages', asyncHandler(async (req, res) => {res.json({ success: true });}));+// POST /api/usage/backfill - Re-read the provider CLIs' on-disk transcripts and+// replace estimated day buckets with their measured token counts (input, output,+// and the prompt-cache tiers). Reads local JSONL only — no provider call, no+// tokens spent — but it rewrites recorded history and can walk a large tree, so+// it is reachable ONLY from this explicit user action (never boot, never a+// schedule).+router.post('/backfill', asyncHandler(async (req, res) => {+ const { since } = validateRequest(usageBackfillSchema, req.body ?? {});+ const summary = await backfillMeasuredUsage({ since: since ?? null });+ res.json(summary);+}));+// POST /api/usage/tokens - Record token usagerouter.post('/tokens', asyncHandler(async (req, res) => {const { inputTokens, outputTokens } = req.body;diff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex 0517f2be87..b02fbe26bc 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -26,9 +26,14 @@ vi.mock('../services/claudeCodeUsage.js', () => ({getClaudeCodeUsage: vi.fn()}));+vi.mock('../services/usageReconciler.js', () => ({+ backfillMeasuredUsage: vi.fn()+}));+import * as usage from '../services/usage.js';import { getAllProviders } from '../services/providers.js';import { getProviderQuotas } from '../services/providerUsage.js';+import { backfillMeasuredUsage } from '../services/usageReconciler.js';import usageRoutes from './usage.js';const buildApp = () => {@@ -171,3 +176,41 @@ describe('usage routes', () => {expect(usage.resetUsage).toHaveBeenCalled();});});++describe('POST /api/usage/backfill', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('runs the transcript backfill and returns its summary', async () => {+ backfillMeasuredUsage.mockResolvedValue({+ days: 3, sessions: 12, tokensIn: 100, tokensOut: 200,+ cacheReadTokens: 900, cacheWriteTokens: 50, families: ['claude']+ });++ const res = await request(buildApp()).post('/api/usage/backfill').send({});+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ days: 3, sessions: 12, families: ['claude'] });+ expect(backfillMeasuredUsage).toHaveBeenCalledWith({ since: null });+ });++ it('passes an explicit since floor through', async () => {+ backfillMeasuredUsage.mockResolvedValue({ days: 1, sessions: 1, families: ['codex'] });+ const res = await request(buildApp()).post('/api/usage/backfill').send({ since: '2026-07-01' });+ expect(res.status).toBe(200);+ expect(backfillMeasuredUsage).toHaveBeenCalledWith({ since: '2026-07-01' });+ });++ it('works with no body at all', async () => {+ backfillMeasuredUsage.mockResolvedValue({ days: 0, sessions: 0, families: [] });+ const res = await request(buildApp()).post('/api/usage/backfill');+ expect(res.status).toBe(200);+ expect(backfillMeasuredUsage).toHaveBeenCalledWith({ since: null });+ });++ it('rejects a malformed since date', async () => {+ const res = await request(buildApp()).post('/api/usage/backfill').send({ since: 'yesterday' });+ expect(res.status).toBe(400);+ expect(backfillMeasuredUsage).not.toHaveBeenCalled();+ });+});diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex 1830aa357f..909ab2fcd8 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -7,10 +7,10 @@import { join } from 'path';import { writeFile, mkdir } from 'fs/promises';import { v4 as uuidv4 } from '../lib/uuid.js';-import { recordSession, recordMessages } from './usage.js';+import { recordSession } from './usage.js';+import { recordCompletedRunUsage } from './usageReconciler.js';import { bufferedSpawn } from '../lib/bufferedSpawn.js';import { atomicWrite, ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';-import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';const RUNS_DIR = PATHS.runs;@@ -142,13 +142,13 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorAawait atomicWrite(metaPath, metadata);await writeFile(join(runDir, 'output.txt'), output || '');- // Record usage for successful CoS agent runs (token counts are estimated)+ // Record usage for successful CoS agent runs. Prefers the provider CLI's own+ // per-message token counts (read from its on-disk transcript, including the+ // prompt-cache tiers) and falls back to the prompt-length/stdout estimate.+ // `metadata` already carries the endTime stamped above, which bounds the+ // transcript window. Owns its own error handling.if (exitCode === 0 && metadata.providerId && metadata.model) {- const estimatedTokens = estimateTokens(output);- const inputTokens = estimateTokensFromChars(metadata.promptLength);- recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens, inputTokens).catch(err => {- console.error(`❌ Failed to record usage: ${err.message}`);- });+ recordCompletedRunUsage(metadata, output);}}diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex b7ed4615af..3ce2907cce 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -20,7 +20,6 @@* every scheduler here is off by default or user-configured.*/import { join } from 'path';-import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';import { resolveInstallRoot } from '../lib/dataRoot.js';import { PORTS } from '../lib/ports.js';import { getSelfHost } from '../lib/peerSelfHost.js';@@ -34,7 +33,8 @@ import { runMigrations } from '../../scripts/run-migrations.js';import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './localLlm.js';import { ensureProviderReady as ensureOllamaProviderReady, ensureRunning as ensureOllamaRunning } from './ollamaManager.js';-import { recordSession, recordMessages } from './usage.js';+import { recordSession } from './usage.js';+import { recordCompletedRunUsage } from './usageReconciler.js';import { setAIToolkit as setProvidersToolkit } from './providers.js';import { setAIToolkit as setRunnerToolkit, executeCliRun as executeCliRunFixed } from './runner.js';import { setAIToolkit as setPromptsToolkit } from './promptService.js';@@ -157,11 +157,11 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD});},onRunCompleted: (metadata, output) => {- const estimatedTokens = estimateTokens(output);- const inputTokens = estimateTokensFromChars(metadata.promptLength);- recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens, inputTokens).catch(err => {- console.error(`❌ Failed to record usage: ${err.message}`);- });+ // Reads the provider CLI's own transcript for real token counts (including+ // the prompt-cache tiers that dominate cost), falling back to the+ // prompt-length/stdout estimate when none is found. Owns its own error+ // handling — a usage-accounting failure must not fail the run.+ recordCompletedRunUsage(metadata, output);},onRunFailed: (metadata, error) => {const errorMessage = error?.message ?? String(error);diff --git a/server/services/usage.js b/server/services/usage.jsindex d3dd01664e..9844f828f2 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -186,6 +186,16 @@ function providerDayBucket(day, providerId, providerName) {messages: 0,tokensIn: 0,tokensOut: 0,+ // Prompt-cache tiers, captured only for providers whose CLI writes a+ // transcript we can read (see services/usageReconciler.js). Additive:+ // absent on every bucket written before #3124 and read as 0.+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ // How this bucket's counts were obtained. `measured` = summed from the+ // provider's own transcript; `estimate` = derived from prompt length and+ // captured stdout. A bucket that accumulated both is `mixed`, so the+ // report never claims a partially-estimated row is measured.+ source: null,byModel: {}};}@@ -194,11 +204,36 @@ function providerDayBucket(day, providerId, providerName) {function modelDayBucket(providerDay, model) {if (!providerDay.byModel[model]) {- providerDay.byModel[model] = { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0 };+ providerDay.byModel[model] = {+ sessions: 0,+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: null+ };}return providerDay.byModel[model];}+/**+ * Merge a new measurement source into a bucket's existing one. A bucket that has+ * only ever seen one kind keeps that kind; mixing measured and estimated counts+ * downgrades it to `mixed` so the UI can't present a partly-estimated row as+ * ground truth. Absent (legacy buckets) is treated as `estimate` — that is what+ * every pre-#3124 bucket actually holds.+ */+function mergeSource(existing, incoming) {+ if (!incoming) return existing ?? null;+ // `null` = a bucket we just created that holds no counts yet, so the incoming+ // source becomes its source outright. `undefined` = a bucket written before+ // this field existed, whose counts are estimates by definition.+ const current = existing === null ? null : (existing ?? 'estimate');+ if (!current) return incoming;+ return current === incoming ? current : 'mixed';+}+function todayBucket() {const today = new Date().toISOString().split('T')[0];if (!usageData.dailyActivity[today]) {@@ -249,18 +284,30 @@ export async function recordSession(providerId, providerName, model) {* Record messages in a session. `outputTokens`/`inputTokens` are estimates* (or real counts when the runner reports them) attributed to the provider,* model, and current day.+ *+ * `extra` carries the prompt-cache tiers and provenance a transcript-reconciled+ * run supplies (`recordRunUsage`). It is optional and defaults to "no cache+ * tokens, estimated" so every existing caller — and the+ * `POST /api/usage/messages` route — keeps its current behavior.*/-export async function recordMessages(providerId, model, messageCount, outputTokens = 0, inputTokens = 0) {+export async function recordMessages(providerId, model, messageCount, outputTokens = 0, inputTokens = 0, extra = {}) {if (!usageData) await loadUsage();const provider = normalizeProvider(providerId);+ const cacheReadTokens = Math.max(0, extra?.cacheReadTokens || 0);+ const cacheWriteTokens = Math.max(0, extra?.cacheWriteTokens || 0);+ const source = extra?.source === 'measured' ? 'measured' : 'estimate';usageData.totalMessages += messageCount;if (outputTokens > 0) {usageData.totalTokens.output += outputTokens;}- if (inputTokens > 0) {- usageData.totalTokens.input += inputTokens;+ // All-time input counts every billable input tier — a cache read is an input+ // token the user was charged for, so omitting it from the headline "Tokens"+ // figure would reproduce the #3124 understatement one level up.+ const totalInputTokens = inputTokens + cacheReadTokens + cacheWriteTokens;+ if (totalInputTokens > 0) {+ usageData.totalTokens.input += totalInputTokens;}// Track by provider / by model (the legacy all-time entries keep their@@ -282,6 +329,12 @@ export async function recordMessages(providerId, model, messageCount, outputTokebucket.messages += messageCount;bucket.tokensIn += inputTokens;bucket.tokensOut += outputTokens;+ // `??= 0` seeds the field on buckets created before it existed, so a+ // pre-#3124 install starts accumulating cache counts without a migration+ // pass over its whole history.+ bucket.cacheReadTokens = (bucket.cacheReadTokens ?? 0) + cacheReadTokens;+ bucket.cacheWriteTokens = (bucket.cacheWriteTokens ?? 0) + cacheWriteTokens;+ bucket.source = mergeSource(bucket.source, source);};const day = todayBucket();day.messages = (day.messages || 0) + messageCount;@@ -294,6 +347,101 @@ export async function recordMessages(providerId, model, messageCount, outputTokeawait saveUsage();}+/**+ * Record one completed AI run from a reconciled usage record — the shape+ * `services/usageReconciler.reconcileRunUsage` returns, carrying either the+ * provider's own measured counts or the caller's estimate, tagged with which.+ *+ * This is the preferred entry point for run-completion hooks: it keeps the+ * cache tiers and the `measured`/`estimate` provenance together, so a row in+ * the cost report can say whether it was measured. `recordMessages` remains the+ * primitive (and the API route's path) for callers with nothing but a token+ * count.+ *+ * @param {{ providerId: string|null, model: string|null, messages?: number,+ * tokensIn?: number, tokensOut?: number, cacheReadTokens?: number,+ * cacheWriteTokens?: number, source?: 'measured'|'estimate' }} record+ */+export async function recordRunUsage(record) {+ const {+ providerId = null,+ model = null,+ messages = 1,+ tokensIn = 0,+ tokensOut = 0,+ cacheReadTokens = 0,+ cacheWriteTokens = 0,+ source = 'estimate'+ } = record || {};+ await recordMessages(providerId, model, messages, tokensOut, tokensIn, {+ cacheReadTokens,+ cacheWriteTokens,+ source+ });+}++/**+ * REPLACE a given day's measured provider/model buckets with `records` — the+ * write half of the transcript backfill (`usageReconciler.backfillMeasuredUsage`).+ *+ * Replace, not add, so re-running the backfill is idempotent: a second pass over+ * the same transcripts must not double the day. Only the buckets named in+ * `records` are touched — a provider whose usage that day came from somewhere+ * else (a local model, an API provider) keeps its existing estimate.+ *+ * The day's flat `sessions`/`messages`/`tokens` fields are deliberately left+ * alone: they are the legacy all-time-ish counters the report already reconciles+ * as residuals, and rewriting them from a partial (transcript-only) view of the+ * day would drop the providers this pass cannot see.+ *+ * @param {string} dayKey `YYYY-MM-DD`+ * @param {Array<{ providerId: string, model: string|null, sessions?: number,+ * messages?: number, tokensIn?: number, tokensOut?: number,+ * cacheReadTokens?: number, cacheWriteTokens?: number }>} records+ */+export async function replaceMeasuredDayUsage(dayKey, records) {+ if (!usageData) await loadUsage();+ if (!DAY_KEY_RE.test(dayKey || '') || !Array.isArray(records) || records.length === 0) return;++ if (!usageData.dailyActivity[dayKey]) {+ usageData.dailyActivity[dayKey] = { sessions: 0, messages: 0, tokens: 0 };+ }+ const day = usageData.dailyActivity[dayKey];++ // Reset only the buckets this pass will rewrite, so a partial re-run can't+ // leave a stale half-count behind.+ for (const { providerId, model } of records) {+ const providerDay = providerDayBucket(day, providerId, null);+ const target = model ? modelDayBucket(providerDay, model) : providerDay;+ for (const bucket of new Set([providerDay, target])) {+ bucket.sessions = 0;+ bucket.messages = 0;+ bucket.tokensIn = 0;+ bucket.tokensOut = 0;+ bucket.cacheReadTokens = 0;+ bucket.cacheWriteTokens = 0;+ bucket.source = null;+ }+ }++ for (const record of records) {+ const providerDay = providerDayBucket(day, record.providerId, null);+ const apply = (bucket) => {+ bucket.sessions += record.sessions || 0;+ bucket.messages += record.messages || 0;+ bucket.tokensIn += record.tokensIn || 0;+ bucket.tokensOut += record.tokensOut || 0;+ bucket.cacheReadTokens += record.cacheReadTokens || 0;+ bucket.cacheWriteTokens += record.cacheWriteTokens || 0;+ bucket.source = mergeSource(bucket.source, 'measured');+ };+ apply(providerDay);+ if (record.model) apply(modelDayBucket(providerDay, record.model));+ }++ await saveUsage();+}+/*** Record tool calls*/@@ -403,6 +551,10 @@ const roundCents = (n) => Math.round(n * 100) / 100;* keeps long-range totals accurate across the rollup boundary. A month bucket* is whole-month-granular: it is included whenever its month overlaps* `[from, to]` (rolled-up months are far older than any day-precise range).+ *+ * Every row carries `cacheReadTokens`/`cacheWriteTokens` (priced at their own+ * per-1M tiers) and a `source` of `measured` | `estimate` | `mixed` — buckets+ * written before #3124 report `estimate`, since that is what their counts are.*/export function buildUsageReport(dailyActivity, { from = null, to = null, providers = [], monthlyActivity = null, totalTokens = null } = {}) {const configById = new Map((providers || []).map((p) => [p.id, p]));@@ -411,7 +563,17 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providconst ensureAggregate = (pid, name) => {if (!agg.has(pid)) {- agg.set(pid, { name, sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, byModel: new Map() });+ agg.set(pid, {+ name,+ sessions: 0,+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: null,+ byModel: new Map()+ });}return agg.get(pid);};@@ -431,19 +593,40 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providp.messages += pDay.messages || 0;p.tokensIn += pDay.tokensIn || 0;p.tokensOut += pDay.tokensOut || 0;+ p.cacheReadTokens += pDay.cacheReadTokens || 0;+ p.cacheWriteTokens += pDay.cacheWriteTokens || 0;+ // A bucket with counts but no `source` predates the field — those counts+ // are estimates, so fold it in as such rather than leaving the row+ // unlabeled and letting the UI imply it was measured.+ if ((pDay.tokensIn || pDay.tokensOut || pDay.cacheReadTokens || pDay.cacheWriteTokens || pDay.messages) && !pDay.source) {+ p.source = mergeSource(p.source, 'estimate');+ } else {+ p.source = mergeSource(p.source, pDay.source);+ }representedSessions += pDay.sessions || 0;representedMessages += pDay.messages || 0;representedTokensIn += pDay.tokensIn || 0;representedTokensOut += pDay.tokensOut || 0;for (const [model, mDay] of Object.entries(pDay.byModel || {})) {if (!p.byModel.has(model)) {- p.byModel.set(model, { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0 });+ p.byModel.set(model, {+ sessions: 0,+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: null+ });}const m = p.byModel.get(model);m.sessions += mDay.sessions || 0;m.messages += mDay.messages || 0;m.tokensIn += mDay.tokensIn || 0;m.tokensOut += mDay.tokensOut || 0;+ m.cacheReadTokens += mDay.cacheReadTokens || 0;+ m.cacheWriteTokens += mDay.cacheWriteTokens || 0;+ m.source = mergeSource(m.source, mDay.source || (mDay.tokensIn || mDay.tokensOut || mDay.messages ? 'estimate' : null));}}const residualSessions = Math.max(0, (bucket.sessions || 0) - representedSessions);@@ -457,6 +640,8 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providlegacy.messages += residualMessages;legacy.tokensIn += residualTokensIn;legacy.tokensOut += residualTokensOut;+ // Flat legacy counts predate cache capture by definition.+ legacy.source = mergeSource(legacy.source, 'estimate');}};@@ -487,7 +672,11 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid// by day/month buckets without double-counting normal recorded messages.if (totalTokens) {const represented = [...agg.values()].reduce((sum, provider) => ({- input: sum.input + provider.tokensIn,+ // `totalTokens.input` counts every billable input tier (see+ // recordMessages), so the represented side must include the cache tiers+ // too — otherwise a measured run's cache reads look unaccounted-for and+ // get re-added as a legacy residual, double-billing them.+ input: sum.input + provider.tokensIn + provider.cacheReadTokens + provider.cacheWriteTokens,output: sum.output + provider.tokensOut}), { input: 0, output: 0 });const residualIn = Math.max(0, (totalTokens.input || 0) - represented.input);@@ -496,10 +685,19 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providconst legacy = ensureAggregate(LEGACY_PROVIDER_ID, LEGACY_PROVIDER_NAME);legacy.tokensIn += residualIn;legacy.tokensOut += residualOut;+ legacy.source = mergeSource(legacy.source, 'estimate');}}- const totals = { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, estimatedCost: 0 };+ const totals = {+ sessions: 0,+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ estimatedCost: 0+ };const providerRows = [];for (const [pid, p] of agg.entries()) {@@ -511,7 +709,7 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providfor (const [model, m] of p.byModel.entries()) {const rates = free ? null : resolveModelRates(pid, model);- const cost = free ? 0 : estimateCostUsd(m.tokensIn, m.tokensOut, rates);+ const cost = free ? 0 : estimateCostUsd(m.tokensIn, m.tokensOut, rates, m);providerCost += cost;models.push({model,@@ -519,11 +717,16 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providmessages: m.messages,tokensIn: m.tokensIn,tokensOut: m.tokensOut,+ cacheReadTokens: m.cacheReadTokens,+ cacheWriteTokens: m.cacheWriteTokens,+ source: m.source || 'estimate',estimatedCost: roundCents(cost),rateModel: rates?.rateModel ?? null,rateMatch: free ? 'free' : rates.matched,inputPer1M: rates?.inputPer1M ?? 0,- outputPer1M: rates?.outputPer1M ?? 0+ outputPer1M: rates?.outputPer1M ?? 0,+ cacheReadPer1M: rates?.cacheReadPer1M ?? 0,+ cacheWritePer1M: rates?.cacheWritePer1M ?? 0});}models.sort((a, b) => b.estimatedCost - a.estimatedCost || b.tokensOut - a.tokensOut);@@ -532,16 +735,25 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid// toward the provider row; price them at the provider-default rate.const modelTokensIn = models.reduce((s, m) => s + m.tokensIn, 0);const modelTokensOut = models.reduce((s, m) => s + m.tokensOut, 0);+ const modelCacheRead = models.reduce((s, m) => s + m.cacheReadTokens, 0);+ const modelCacheWrite = models.reduce((s, m) => s + m.cacheWriteTokens, 0);const unattributedIn = Math.max(0, p.tokensIn - modelTokensIn);const unattributedOut = Math.max(0, p.tokensOut - modelTokensOut);- if (!free && (unattributedIn > 0 || unattributedOut > 0)) {- providerCost += estimateCostUsd(unattributedIn, unattributedOut, providerRates);+ const unattributedCacheRead = Math.max(0, p.cacheReadTokens - modelCacheRead);+ const unattributedCacheWrite = Math.max(0, p.cacheWriteTokens - modelCacheWrite);+ if (!free && (unattributedIn > 0 || unattributedOut > 0 || unattributedCacheRead > 0 || unattributedCacheWrite > 0)) {+ providerCost += estimateCostUsd(unattributedIn, unattributedOut, providerRates, {+ cacheReadTokens: unattributedCacheRead,+ cacheWriteTokens: unattributedCacheWrite+ });}totals.sessions += p.sessions;totals.messages += p.messages;totals.tokensIn += p.tokensIn;totals.tokensOut += p.tokensOut;+ totals.cacheReadTokens += p.cacheReadTokens;+ totals.cacheWriteTokens += p.cacheWriteTokens;totals.estimatedCost += providerCost;providerRows.push({@@ -552,6 +764,9 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providmessages: p.messages,tokensIn: p.tokensIn,tokensOut: p.tokensOut,+ cacheReadTokens: p.cacheReadTokens,+ cacheWriteTokens: p.cacheWriteTokens,+ source: p.source || 'estimate',estimatedCost: roundCents(providerCost),rateMatch: pid === LEGACY_PROVIDER_ID? 'fallback'@@ -564,6 +779,10 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providproviderRows.sort((a, b) => b.estimatedCost - a.estimatedCost || b.tokensOut - a.tokensOut);totals.estimatedCost = roundCents(totals.estimatedCost);+ // Report-level provenance: `measured` only when every row that carries counts+ // was read from a provider transcript, so the UI can state plainly whether the+ // headline figure rests on measurements or estimates.+ totals.source = providerRows.reduce((acc, row) => mergeSource(acc, row.source), null) || 'estimate';return {range: { from, to },diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 6efac0a29d..e6e48e3997 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -20,7 +20,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),}));import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';-import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, recordTokens, buildUsageReport, rollupOldDailyActivity } from './usage.js';+import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, recordTokens, recordRunUsage, replaceMeasuredDayUsage, buildUsageReport, rollupOldDailyActivity } from './usage.js';// Helper: produce a date string N days ago (relative to today)function daysAgo(n) {@@ -821,3 +821,277 @@ describe('usage.js — loadUsage rollup integration', () => {expect(data.totalSessions).toBe(7);});});++describe('usage.js — cache tiers and measured/estimate provenance (#3124 Phase 2)', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(FIXED_DATE);+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ const today = '2025-06-11';++ it('records cache tokens and a measured source through recordRunUsage', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();+ await recordSession('claude-code', 'Claude Code', 'claude-opus-5');+ await recordRunUsage({+ providerId: 'claude-code',+ model: 'claude-opus-5',+ messages: 3,+ tokensIn: 1500,+ tokensOut: 800,+ cacheReadTokens: 3_500_000,+ cacheWriteTokens: 280_000,+ source: 'measured'+ });++ const providerDay = getUsage().dailyActivity[today].byProvider['claude-code'];+ expect(providerDay).toMatchObject({+ messages: 3,+ tokensIn: 1500,+ tokensOut: 800,+ cacheReadTokens: 3_500_000,+ cacheWriteTokens: 280_000,+ source: 'measured'+ });+ expect(providerDay.byModel['claude-opus-5']).toMatchObject({+ cacheReadTokens: 3_500_000,+ source: 'measured'+ });+ });++ it('counts every billable input tier in the all-time input total', () => {+ // A cache read is an input token the user was charged for — the headline+ // "Tokens" figure must not omit it (that was the #3124 understatement).+ expect(getUsage().totalTokens.input).toBe(1500 + 3_500_000 + 280_000);+ });++ it('defaults recordMessages to an estimate source with no cache tokens', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();+ await recordMessages('codex', 'gpt-5.3-codex', 1, 400, 30);++ expect(getUsage().dailyActivity[today].byProvider.codex).toMatchObject({+ tokensIn: 30,+ tokensOut: 400,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'estimate'+ });+ });++ it('downgrades a bucket to mixed when measured and estimated counts land together', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();+ await recordRunUsage({ providerId: 'claude-code', model: 'claude-opus-5', tokensOut: 10, source: 'measured' });+ await recordRunUsage({ providerId: 'claude-code', model: 'claude-opus-5', tokensOut: 10, source: 'estimate' });++ expect(getUsage().dailyActivity[today].byProvider['claude-code'].source).toBe('mixed');+ });++ it('accumulates cache tokens onto a legacy bucket that predates the fields', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({+ [today]: {+ sessions: 1,+ messages: 1,+ tokens: 100,+ // Pre-#3124 shape: no cacheReadTokens/cacheWriteTokens/source at all.+ byProvider: { 'claude-code': { name: 'Claude Code', sessions: 1, messages: 1, tokensIn: 20, tokensOut: 100, byModel: {} } }+ }+ }));+ await loadUsage();+ await recordRunUsage({+ providerId: 'claude-code',+ model: null,+ tokensOut: 50,+ cacheReadTokens: 900,+ source: 'measured'+ });++ const bucket = getUsage().dailyActivity[today].byProvider['claude-code'];+ expect(bucket.cacheReadTokens).toBe(900);+ expect(bucket.tokensOut).toBe(150);+ // The pre-existing 100 output tokens were estimates, so the merged bucket+ // must not claim to be purely measured.+ expect(bucket.source).toBe('mixed');+ });+});++describe('buildUsageReport — cache pricing and source reporting', () => {+ const providers = [{ id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude' }];++ it('prices cache read and write tiers into the estimated cost', () => {+ const daily = {+ '2026-07-01': {+ sessions: 1,+ messages: 1,+ byProvider: {+ 'claude-code': {+ name: 'Claude Code',+ sessions: 1,+ messages: 1,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 1_000_000,+ cacheWriteTokens: 1_000_000,+ source: 'measured',+ byModel: {+ 'claude-opus-5': {+ sessions: 1, messages: 1, tokensIn: 0, tokensOut: 0,+ cacheReadTokens: 1_000_000, cacheWriteTokens: 1_000_000, source: 'measured'+ }+ }+ }+ }+ }+ };++ const report = buildUsageReport(daily, { providers });+ // claude-opus-5: $5/MTok input → $0.50 cache read + $6.25 cache write.+ expect(report.totals.estimatedCost).toBeCloseTo(6.75, 2);+ expect(report.totals.cacheReadTokens).toBe(1_000_000);+ expect(report.totals.cacheWriteTokens).toBe(1_000_000);+ expect(report.totals.source).toBe('measured');+ expect(report.providers[0].source).toBe('measured');+ expect(report.providers[0].models[0]).toMatchObject({+ cacheReadTokens: 1_000_000,+ cacheWritePer1M: 6.25,+ cacheReadPer1M: 0.5+ });+ });++ it('reports legacy buckets with no source field as estimates', () => {+ const daily = {+ '2026-07-01': {+ sessions: 1,+ messages: 1,+ byProvider: {+ 'claude-code': {+ name: 'Claude Code', sessions: 1, messages: 1, tokensIn: 10, tokensOut: 100, byModel: {}+ }+ }+ }+ };++ const report = buildUsageReport(daily, { providers });+ expect(report.providers[0].source).toBe('estimate');+ expect(report.providers[0].cacheReadTokens).toBe(0);+ expect(report.totals.source).toBe('estimate');+ });++ it('marks a range spanning legacy and measured buckets as mixed', () => {+ const daily = {+ '2026-07-01': {+ sessions: 1, messages: 1,+ byProvider: { 'claude-code': { name: 'Claude Code', sessions: 1, messages: 1, tokensIn: 10, tokensOut: 100, byModel: {} } }+ },+ '2026-07-02': {+ sessions: 1, messages: 1,+ byProvider: { 'claude-code': { name: 'Claude Code', sessions: 1, messages: 1, tokensIn: 10, tokensOut: 100, cacheReadTokens: 500, source: 'measured', byModel: {} } }+ }+ };++ const report = buildUsageReport(daily, { providers });+ expect(report.providers[0].source).toBe('mixed');+ });++ it('never charges a free local provider for cache tokens', () => {+ const daily = {+ '2026-07-01': {+ sessions: 1, messages: 1,+ byProvider: { ollama: { name: 'Ollama', sessions: 1, messages: 1, tokensIn: 100, tokensOut: 100, cacheReadTokens: 5_000_000, source: 'measured', byModel: {} } }+ }+ };++ const report = buildUsageReport(daily, { providers: [{ id: 'ollama', name: 'Ollama' }] });+ expect(report.totals.estimatedCost).toBe(0);+ });++ it('does not re-add measured cache tokens as a legacy residual', () => {+ // totalTokens.input includes the cache tiers, so the residual reconciliation+ // must count them as represented or it double-bills them as legacy.+ const daily = {+ '2026-07-01': {+ sessions: 1, messages: 1,+ byProvider: {+ 'claude-code': {+ name: 'Claude Code', sessions: 1, messages: 1,+ tokensIn: 1000, tokensOut: 500,+ cacheReadTokens: 2_000_000, cacheWriteTokens: 100_000,+ source: 'measured', byModel: {}+ }+ }+ }+ };++ const report = buildUsageReport(daily, {+ providers,+ totalTokens: { input: 1000 + 2_000_000 + 100_000, output: 500 }+ });++ expect(report.providers.find((p) => p.id === 'legacy')).toBeUndefined();+ });+});++describe('replaceMeasuredDayUsage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('is idempotent — a second identical backfill does not double the day', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();++ const records = [{+ providerId: 'claude-code',+ model: 'claude-opus-5',+ sessions: 2,+ messages: 5,+ tokensIn: 100,+ tokensOut: 200,+ cacheReadTokens: 9000,+ cacheWriteTokens: 300+ }];++ await replaceMeasuredDayUsage('2026-07-01', records);+ await replaceMeasuredDayUsage('2026-07-01', records);++ const bucket = getUsage().dailyActivity['2026-07-01'].byProvider['claude-code'];+ expect(bucket).toMatchObject({+ sessions: 2, messages: 5, tokensIn: 100, tokensOut: 200,+ cacheReadTokens: 9000, cacheWriteTokens: 300, source: 'measured'+ });+ expect(bucket.byModel['claude-opus-5']).toMatchObject({ tokensOut: 200, cacheReadTokens: 9000 });+ });++ it('leaves other providers in the same day untouched', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({+ '2026-07-01': {+ sessions: 1, messages: 1, tokens: 40,+ byProvider: { ollama: { name: 'Ollama', sessions: 1, messages: 1, tokensIn: 5, tokensOut: 40, byModel: {} } }+ }+ }));+ await loadUsage();++ await replaceMeasuredDayUsage('2026-07-01', [+ { providerId: 'claude-code', model: null, sessions: 1, messages: 1, tokensOut: 10 }+ ]);++ const day = getUsage().dailyActivity['2026-07-01'];+ expect(day.byProvider.ollama).toMatchObject({ tokensOut: 40, tokensIn: 5 });+ expect(day.byProvider['claude-code'].source).toBe('measured');+ });++ it('rejects a malformed day key or empty record list', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();+ await replaceMeasuredDayUsage('not-a-day', [{ providerId: 'claude-code' }]);+ await replaceMeasuredDayUsage('2026-07-01', []);+ expect(Object.keys(getUsage().dailyActivity)).toHaveLength(0);+ });+});diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.jsnew file mode 100644index 0000000000..71ee8429f0--- /dev/null+++ b/server/services/usageReconciler.js@@ -0,0 +1,417 @@+/**+ * Replace PortOS's estimated per-run token counts with the CLI's own measured+ * counts, read from the transcripts the coding CLIs already write to disk.+ *+ * PortOS estimates output from captured stdout (a repainted ANSI screen for TUI+ * providers) and input from `promptLength` — the initial task description only,+ * which omits the per-turn context replay and prompt-cache traffic that dominate+ * real API cost. The result understated cost by orders of magnitude (#3124).+ * Claude Code and Codex both write real per-message counts locally, so the fix+ * is to read them: no provider call, no tokens spent, no network.+ *+ * Correlation has no shared identifier to work with — PortOS never captured the+ * CLI's own session id — so a run is matched to a transcript by+ * (a) working directory and (b) timestamp overlap with `[startTime, endTime]`:+ *+ * Claude Code — the project directory name IS the slugified cwd, so the+ * candidate set is exact; each session file is then windowed by timestamp.+ * Codex — rollouts are filed by date, so we scan the run's date directories+ * and keep sessions whose `session_meta.cwd` matches.+ *+ * When nothing matches (a provider that writes no transcript, an unreadable+ * home directory, an ambiguous window) the caller falls back to the existing+ * estimate — `reconcileRunUsage` reports which happened via `source`, so the+ * report can mark measured rows apart from estimated ones. Reading a transcript+ * is best-effort by design: a failure here must never fail the run it describes.+ */++import { homedir } from 'os';+import { join } from 'path';+import { readdir } from 'fs/promises';+import { tryReadFile } from '../lib/fileUtils.js';+import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';+import { isFreeModelId } from '../lib/modelPricing.js';+import {+ claudeProjectSlug,+ parseClaudeTranscript,+ parseCodexRollout,+ totalTranscriptTokens+} from '../lib/providerTranscriptUsage.js';+import { recordRunUsage, replaceMeasuredDayUsage } from './usage.js';++// Widen the correlation window past the recorded run bounds: the CLI writes its+// first line slightly before PortOS stamps startTime, and flushes its last+// after the process exits. A minute of slack captures both without reaching+// into a neighbouring run (PortOS runs of the same provider in the same cwd are+// serialized well outside this margin).+const WINDOW_SLACK_MS = 60_000;++// A run is attributed only to transcripts whose cwd matches. A CoS agent works+// in a git worktree under the install's data dir, so the worktree path — not the+// install root — is what the CLI records; matching is therefore exact on the+// recorded `workspacePath`, with a prefix allowance for a CLI invoked in a+// subdirectory of the workspace (`server/`, `client/`).+const cwdMatches = (transcriptCwd, workspacePath) => {+ if (!transcriptCwd || !workspacePath) return false;+ if (transcriptCwd === workspacePath) return true;+ return transcriptCwd.startsWith(`${workspacePath}/`);+};++const CLAUDE_ID = /claude/i;+const CODEX_ID = /codex/i;++// A transcript records the CLI that wrote it, not which PortOS provider config+// invoked it (a single CLI backs several: `claude-code`, `claude-code-tui`,+// `claude-code-tui-bedrock`, …). The backfill therefore attributes to one+// stable per-CLI id rather than guessing a config. These ids intentionally match+// the canonical provider ids so `resolveModelRates`/`isFreeProvider` classify+// them correctly, and a later per-run reconcile refines the attribution.+const CLAUDE_BACKFILL_PROVIDER = 'claude-code';+const CODEX_BACKFILL_PROVIDER = 'codex';+// Where a transcript whose model id is local inference gets attributed, so+// `isFreeProvider` prices it at $0 instead of the hosted provider's rates.+const FREE_LOCAL_PROVIDER = 'ollama';++/**+ * Which transcript family a provider writes, or null for providers that write+ * none (ollama, LM Studio, agy, grok, any API provider). Keyed off the provider+ * id and command, mirroring `providerModels.js`'s predicates — but kept local so+ * this service stays reachable from the completion hook without pulling in the+ * provider graph.+ * @param {{ providerId?: string|null, command?: string|null }} run+ * @returns {'claude'|'codex'|null}+ */+export function transcriptFamily({ providerId = null, command = null } = {}) {+ const haystack = `${providerId || ''} ${command || ''}`;+ // Order matters: a `claude-code` provider id contains neither codex nor grok,+ // but check codex first so a hypothetical `codex-claude` wrapper resolves to+ // the CLI that actually writes the rollout.+ if (CODEX_ID.test(haystack)) return 'codex';+ if (CLAUDE_ID.test(haystack)) return 'claude';+ return null;+}++/** List a directory, returning [] when it doesn't exist or can't be read. */+const listDir = async (dir) => readdir(dir).catch(() => []);++/**+ * Every date directory (`YYYY/MM/DD`) a run could have written a Codex rollout+ * into. A run spanning midnight (or a UTC/local boundary) touches two days, so+ * the window's start and end days are both included.+ */+function codexDateDirs(root, fromMs, toMs) {+ const days = new Set();+ const start = Number.isFinite(fromMs) ? fromMs : Date.now();+ const end = Number.isFinite(toMs) ? toMs : start;+ // Step a day at a time from start to end, plus a day either side for+ // timezone skew between the CLI's clock and ours.+ for (let ms = start - 86_400_000; ms <= end + 86_400_000; ms += 86_400_000) {+ const d = new Date(ms);+ days.add(join(+ root,+ String(d.getUTCFullYear()),+ String(d.getUTCMonth() + 1).padStart(2, '0'),+ String(d.getUTCDate()).padStart(2, '0')+ ));+ // The CLI files rollouts by LOCAL date; add that path too.+ days.add(join(+ root,+ String(d.getFullYear()),+ String(d.getMonth() + 1).padStart(2, '0'),+ String(d.getDate()).padStart(2, '0')+ ));+ }+ return [...days];+}++/**+ * Sum every transcript that overlaps a run's window in its working directory.+ * Returns null when no transcript could be attributed (so the caller keeps its+ * estimate rather than recording a measured zero).+ *+ * @param {object} run+ * @param {string} run.workspacePath cwd the run executed in+ * @param {string|null} run.startTime ISO+ * @param {string|null} run.endTime ISO+ * @param {'claude'|'codex'} run.family+ * @param {string} [run.home] override for tests+ * @returns {Promise<null|{ source: 'measured', family: string, sessions: number,+ * model: string|null, messages: number, tokensIn: number, tokensOut: number,+ * cacheReadTokens: number, cacheWriteTokens: number }>}+ */+export async function readMeasuredUsage({ workspacePath, startTime, endTime, family, home = homedir() } = {}) {+ if (!workspacePath || !family) return null;++ const startMs = Date.parse(startTime || '');+ const endMs = Date.parse(endTime || '');+ const from = Number.isNaN(startMs) ? null : startMs - WINDOW_SLACK_MS;+ const to = Number.isNaN(endMs) ? null : endMs + WINDOW_SLACK_MS;++ const totals = {+ source: 'measured',+ family,+ sessions: 0,+ model: null,+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0+ };+ const modelCounts = new Map();++ const fold = (parsed) => {+ if (!parsed || totalTranscriptTokens(parsed) === 0) return;+ totals.sessions += 1;+ totals.messages += parsed.messages || 0;+ totals.tokensIn += parsed.tokensIn || 0;+ totals.tokensOut += parsed.tokensOut || 0;+ totals.cacheReadTokens += parsed.cacheReadTokens || 0;+ totals.cacheWriteTokens += parsed.cacheWriteTokens || 0;+ for (const model of parsed.models?.length ? parsed.models : [parsed.model]) {+ if (model) modelCounts.set(model, (modelCounts.get(model) || 0) + 1);+ }+ };++ if (family === 'claude') {+ // The project directory name is the slugified cwd — an exact lookup, with+ // no directory scan and no chance of picking up another repo's sessions.+ const projectDir = join(home, '.claude', 'projects', claudeProjectSlug(workspacePath));+ for (const file of await listDir(projectDir)) {+ if (!file.endsWith('.jsonl')) continue;+ const text = await tryReadFile(join(projectDir, file));+ if (!text) continue;+ fold(parseClaudeTranscript(text, { from, to }));+ }+ } else {+ const sessionsRoot = join(home, '.codex', 'sessions');+ for (const dir of codexDateDirs(sessionsRoot, from ?? Date.now(), to ?? from ?? Date.now())) {+ for (const file of await listDir(dir)) {+ if (!file.startsWith('rollout-') || !file.endsWith('.jsonl')) continue;+ const text = await tryReadFile(join(dir, file));+ if (!text) continue;+ // Rollouts are filed by date, not cwd — confirm the cwd before folding.+ const parsed = parseCodexRollout(text, { from, to });+ if (!cwdMatches(parsed.cwd, workspacePath)) continue;+ fold(parsed);+ }+ }+ }++ if (totals.sessions === 0) return null;+ totals.model = [...modelCounts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;+ return totals;+}++/**+ * Measured counts for a completed run, or the caller's estimate when no+ * transcript can be attributed. Always resolves — a transcript read must never+ * fail the run it describes — and always returns a usable record, so a run with+ * no transcript still contributes its estimate rather than recording nothing.+ *+ * @param {object} run PortOS run metadata (`providerId`, `model`,+ * `workspacePath`, `startTime`, `endTime`)+ * @param {{ tokensIn: number, tokensOut: number }} estimate fallback counts+ * @param {{ home?: string }} [opts]+ * @returns {Promise<{ providerId: string|null, model: string|null, messages: number,+ * tokensIn: number, tokensOut: number, cacheReadTokens: number,+ * cacheWriteTokens: number, source: 'measured'|'estimate' }>}+ */+export async function reconcileRunUsage(run, estimate, { home = homedir() } = {}) {+ const fallback = {+ providerId: run?.providerId ?? null,+ model: run?.model ?? null,+ messages: 1,+ tokensIn: Math.max(0, estimate?.tokensIn || 0),+ tokensOut: Math.max(0, estimate?.tokensOut || 0),+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'estimate'+ };++ const family = transcriptFamily({ providerId: run?.providerId, command: run?.command });+ if (!family) return fallback;++ // Best-effort: an unreadable home dir, a permissions error, or a CLI format+ // change must degrade to the estimate, never throw into the completion hook.+ const measured = await readMeasuredUsage({+ workspacePath: run?.workspacePath,+ startTime: run?.startTime,+ endTime: run?.endTime,+ family,+ home+ }).catch((err) => {+ console.error(`❌ Usage reconcile failed for ${run?.providerId}: ${err.message}`);+ return null;+ });+ if (!measured) return fallback;++ return {+ providerId: run?.providerId ?? null,+ // Prefer the model PortOS recorded (it carries the provider's own id shape,+ // e.g. a Bedrock-prefixed id the pricing table resolves); fall back to the+ // transcript's when PortOS captured none.+ model: run?.model ?? measured.model ?? null,+ messages: measured.messages || 1,+ tokensIn: measured.tokensIn,+ tokensOut: measured.tokensOut,+ cacheReadTokens: measured.cacheReadTokens,+ cacheWriteTokens: measured.cacheWriteTokens,+ source: 'measured'+ };+}++/**+ * The run-completion usage path, shared by the AI Toolkit hook+ * (`services/bootstrap.js`) and CoS agent runs+ * (`services/agentRunTracking.js`) so both record the same shape from the same+ * logic. Estimates tokens the legacy way, upgrades to the provider's measured+ * counts when a transcript can be found, and persists the result.+ *+ * Fire-and-forget by design — the callers invoke it from a completion hook, so+ * it owns its own error handling and never rejects into them. Runs with no+ * `providerId` are skipped rather than attributed to an `unknown` bucket.+ *+ * @param {object} metadata PortOS run metadata+ * @param {string} output captured stdout+ * @param {{ home?: string }} [opts] `home` overrides the transcript root (tests)+ * @returns {Promise<void>}+ */+export async function recordCompletedRunUsage(metadata, output, { home = homedir() } = {}) {+ if (!metadata?.providerId) return;++ const estimate = {+ tokensOut: estimateTokens(output),+ tokensIn: estimateTokensFromChars(metadata.promptLength)+ };+ // One catch for the whole chain: whatever fails — reading a transcript or+ // persisting the record — usage accounting must not surface as a run failure.+ await reconcileRunUsage(metadata, estimate, { home })+ .then(recordRunUsage)+ .catch((err) => {+ console.error(`❌ Failed to record usage: ${err.message}`);+ });+}++/**+ * Re-read every readable transcript in the retained window and REPLACE the+ * recorded per-provider/per-model day buckets with the measured counts.+ *+ * Reconciliation normally happens per-run at completion, so this exists for the+ * history recorded before that landed — an install upgrading to #3124 Phase 2+ * has months of estimated buckets it can now correct in place.+ *+ * **Explicitly user-triggered only.** Reading local JSONL spends no tokens and+ * makes no provider call, so this does not engage the AI-provider policy — but a+ * from-zero bulk pass over a large `~/.claude/projects` tree is slow and+ * rewrites recorded history, so it must never run from boot or a schedule. The+ * only caller is `POST /api/usage/backfill`.+ *+ * Buckets are keyed by the transcript's own day, so a session is attributed to+ * the day it ran rather than today. Days with no transcript keep their existing+ * estimate untouched.+ *+ * @param {{ home?: string, since?: string|null }} [opts] `since` is an inclusive+ * `YYYY-MM-DD` floor; transcripts older than it are skipped.+ * @returns {Promise<{ days: number, sessions: number, tokensIn: number,+ * tokensOut: number, cacheReadTokens: number, cacheWriteTokens: number,+ * families: string[] }>}+ */+export async function backfillMeasuredUsage({ home = homedir(), since = null } = {}) {+ const byDay = new Map(); // 'YYYY-MM-DD' -> Map<providerKey, totals>+ const families = new Set();+ const summary = {+ days: 0,+ sessions: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ families: []+ };++ const collect = (parsed, family, providerId) => {+ if (!parsed || totalTranscriptTokens(parsed) === 0) return;+ // Attribute to the day the session ENDED — the same day PortOS's own+ // recording would have used, since it records at run completion.+ const day = (parsed.lastTs || parsed.firstTs || '').slice(0, 10);+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return;+ if (since && day < since) return;++ families.add(family);+ if (!byDay.has(day)) byDay.set(day, new Map());+ const dayMap = byDay.get(day);+ const model = parsed.model || null;+ // A Claude-Code-flavored CLI can be pointed at a local Ollama/LM Studio+ // backend, and the transcript then records the LOCAL model id+ // (`qwen3.6:35b`). Attributing that to `claude-code` would bill free local+ // inference at Anthropic rates — measured against a real install, ~$166 of+ // cost that was never incurred. Route it to `ollama`, which+ // `isFreeProvider` prices at $0. The model id is the only signal available+ // here: a transcript does not record which PortOS provider invoked it.+ const effectiveProvider = isFreeModelId(model) ? FREE_LOCAL_PROVIDER : providerId;+ const key = `${effectiveProvider} ${model ?? ''}`;+ if (!dayMap.has(key)) {+ dayMap.set(key, {+ providerId: effectiveProvider,+ model,+ sessions: 0,+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0+ });+ }+ const bucket = dayMap.get(key);+ bucket.sessions += 1;+ bucket.messages += parsed.messages || 0;+ bucket.tokensIn += parsed.tokensIn || 0;+ bucket.tokensOut += parsed.tokensOut || 0;+ bucket.cacheReadTokens += parsed.cacheReadTokens || 0;+ bucket.cacheWriteTokens += parsed.cacheWriteTokens || 0;+ };++ // Claude Code — every project directory, since a PortOS install drives runs in+ // the repo, its worktrees, and its subdirectories, each a separate slug.+ const projectsRoot = join(home, '.claude', 'projects');+ for (const project of await listDir(projectsRoot)) {+ for (const file of await listDir(join(projectsRoot, project))) {+ if (!file.endsWith('.jsonl')) continue;+ const text = await tryReadFile(join(projectsRoot, project, file));+ if (!text) continue;+ collect(parseClaudeTranscript(text), 'claude', CLAUDE_BACKFILL_PROVIDER);+ }+ }++ // Codex — walk the YYYY/MM/DD tree rather than guessing dates.+ const sessionsRoot = join(home, '.codex', 'sessions');+ for (const year of await listDir(sessionsRoot)) {+ for (const month of await listDir(join(sessionsRoot, year))) {+ for (const dayDir of await listDir(join(sessionsRoot, year, month))) {+ const dir = join(sessionsRoot, year, month, dayDir);+ for (const file of await listDir(dir)) {+ if (!file.startsWith('rollout-') || !file.endsWith('.jsonl')) continue;+ const text = await tryReadFile(join(dir, file));+ if (!text) continue;+ collect(parseCodexRollout(text), 'codex', CODEX_BACKFILL_PROVIDER);+ }+ }+ }+ }++ for (const [day, dayMap] of byDay) {+ await replaceMeasuredDayUsage(day, [...dayMap.values()]);+ summary.days += 1;+ for (const bucket of dayMap.values()) {+ summary.sessions += bucket.sessions;+ summary.tokensIn += bucket.tokensIn;+ summary.tokensOut += bucket.tokensOut;+ summary.cacheReadTokens += bucket.cacheReadTokens;+ summary.cacheWriteTokens += bucket.cacheWriteTokens;+ }+ }+ summary.families = [...families];+ console.log(`📊 Usage backfill: ${summary.sessions} sessions across ${summary.days} days from ${summary.families.join(', ') || 'no'} transcripts`);+ return summary;+}diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.jsnew file mode 100644index 0000000000..c43f134a1f--- /dev/null+++ b/server/services/usageReconciler.test.js@@ -0,0 +1,467 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++vi.mock('./usage.js', () => ({+ recordRunUsage: vi.fn().mockResolvedValue(undefined),+ replaceMeasuredDayUsage: vi.fn().mockResolvedValue(undefined)+}));++const { recordRunUsage, replaceMeasuredDayUsage } = await import('./usage.js');+const {+ transcriptFamily,+ readMeasuredUsage,+ reconcileRunUsage,+ recordCompletedRunUsage,+ backfillMeasuredUsage+} = await import('./usageReconciler.js');++// Fake HOME per test so the parsers read fixtures, never the developer's real+// ~/.claude or ~/.codex (which hold private session data — see CLAUDE.md).+let home;+const WORKSPACE = '/work/example-repo';+// claudeProjectSlug(WORKSPACE) — the CLI names its project dir after the cwd.+const PROJECT_SLUG = '-work-example-repo';++const claudeAssistant = ({ id, timestamp, input = 10, cacheWrite = 100, cacheRead = 1000, output = 50, model = 'claude-opus-5' }) =>+ JSON.stringify({+ type: 'assistant',+ uuid: `uuid-${id}`,+ sessionId: 'sess-1',+ cwd: WORKSPACE,+ timestamp,+ message: {+ id,+ model,+ usage: {+ input_tokens: input,+ cache_creation_input_tokens: cacheWrite,+ cache_read_input_tokens: cacheRead,+ output_tokens: output+ }+ }+ });++const writeClaudeSession = async (file, lines, slug = PROJECT_SLUG) => {+ const dir = join(home, '.claude', 'projects', slug);+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, file), lines.join('\n'));+};++const codexRollout = ({ cwd = WORKSPACE, timestamp, input, cached, output }) => [+ JSON.stringify({+ timestamp,+ type: 'session_meta',+ payload: { id: 'rollout-1', cwd, cli_version: '0.0.0', model: 'gpt-5.3-codex' }+ }),+ JSON.stringify({+ timestamp,+ type: 'event_msg',+ payload: {+ type: 'token_count',+ info: {+ total_token_usage: {+ input_tokens: input,+ cached_input_tokens: cached,+ output_tokens: output,+ total_tokens: input + output+ }+ }+ }+ })+].join('\n');++const writeCodexRollout = async (dateParts, file, text) => {+ const dir = join(home, '.codex', 'sessions', ...dateParts);+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, file), text);+};++beforeEach(async () => {+ home = await mkdtemp(join(tmpdir(), 'portos-usage-'));+ vi.clearAllMocks();+});++afterEach(async () => {+ await rm(home, { recursive: true, force: true });+});++describe('transcriptFamily', () => {+ it('maps every claude-flavored provider id to the claude family', () => {+ for (const providerId of ['claude-code', 'claude-code-tui', 'claude-code-tui-bedrock']) {+ expect(transcriptFamily({ providerId })).toBe('claude');+ }+ });++ it('maps codex provider ids to the codex family', () => {+ expect(transcriptFamily({ providerId: 'codex' })).toBe('codex');+ expect(transcriptFamily({ providerId: 'codex-tui' })).toBe('codex');+ });++ it('resolves from the launch command when the id is uninformative', () => {+ expect(transcriptFamily({ providerId: 'custom', command: '/usr/local/bin/claude' })).toBe('claude');+ });++ it('returns null for providers that write no transcript', () => {+ for (const providerId of ['ollama', 'lmstudio', 'agy', 'grok', 'kimi', '', null]) {+ expect(transcriptFamily({ providerId })).toBeNull();+ }+ });+});++describe('readMeasuredUsage', () => {+ it('sums every session in the run window from the cwd-slug project directory', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })+ ]);+ await writeClaudeSession('b.jsonl', [+ claudeAssistant({ id: 'm2', timestamp: '2026-07-01T10:06:00.000Z', output: 25, cacheRead: 500 })+ ]);++ const result = await readMeasuredUsage({+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ family: 'claude',+ home+ });++ expect(result).toMatchObject({+ source: 'measured',+ sessions: 2,+ tokensOut: 75,+ cacheReadTokens: 1500,+ cacheWriteTokens: 200,+ model: 'claude-opus-5'+ });+ });++ it('excludes sessions outside the run window', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'yesterday', timestamp: '2026-06-30T10:00:00.000Z' }),+ claudeAssistant({ id: 'inRun', timestamp: '2026-07-01T10:05:00.000Z' })+ ]);++ const result = await readMeasuredUsage({+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ family: 'claude',+ home+ });++ expect(result.messages).toBe(1);+ expect(result.tokensOut).toBe(50);+ });++ it('returns null when another repo owns the only sessions', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })+ ], '-work-some-other-repo');++ const result = await readMeasuredUsage({+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ family: 'claude',+ home+ });+ expect(result).toBeNull();+ });++ it('returns null when the home directory has no transcripts at all', async () => {+ const result = await readMeasuredUsage({+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ family: 'claude',+ home+ });+ expect(result).toBeNull();+ });++ it('matches a codex rollout by its session_meta cwd', async () => {+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', codexRollout({+ timestamp: '2026-07-01T10:05:00.000Z', input: 3000, cached: 2400, output: 250+ }));++ const result = await readMeasuredUsage({+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ family: 'codex',+ home+ });++ expect(result).toMatchObject({ sessions: 1, tokensIn: 600, cacheReadTokens: 2400, tokensOut: 250 });+ });++ it('skips a codex rollout from a different cwd', async () => {+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', codexRollout({+ cwd: '/work/other', timestamp: '2026-07-01T10:05:00.000Z', input: 3000, cached: 2400, output: 250+ }));++ const result = await readMeasuredUsage({+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ family: 'codex',+ home+ });+ expect(result).toBeNull();+ });++ it('accepts a CLI invoked in a subdirectory of the workspace', async () => {+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', codexRollout({+ cwd: `${WORKSPACE}/server`, timestamp: '2026-07-01T10:05:00.000Z', input: 1000, cached: 0, output: 40+ }));++ const result = await readMeasuredUsage({+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ family: 'codex',+ home+ });+ expect(result?.tokensOut).toBe(40);+ });+});++describe('reconcileRunUsage', () => {+ const run = {+ providerId: 'claude-code-tui',+ model: 'claude-opus-5',+ workspacePath: WORKSPACE,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ };++ it('returns measured counts that match the transcript sums EXACTLY', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', input: 10, cacheWrite: 100, cacheRead: 1000, output: 50 }),+ claudeAssistant({ id: 'm2', timestamp: '2026-07-01T10:06:00.000Z', input: 5, cacheWrite: 20, cacheRead: 500, output: 25 })+ ]);++ // The estimate is deliberately nothing like the truth — a measured result+ // must not blend it in.+ const result = await reconcileRunUsage(run, { tokensIn: 30, tokensOut: 9999 }, { home });++ expect(result).toEqual({+ providerId: 'claude-code-tui',+ model: 'claude-opus-5',+ messages: 2,+ tokensIn: 15,+ tokensOut: 75,+ cacheReadTokens: 1500,+ cacheWriteTokens: 120,+ source: 'measured'+ });+ });++ it('falls back to the estimate when no transcript matches', async () => {+ const result = await reconcileRunUsage(run, { tokensIn: 30, tokensOut: 400 }, { home });+ expect(result).toMatchObject({+ tokensIn: 30,+ tokensOut: 400,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'estimate'+ });+ });++ it('falls back to the estimate for a provider that writes no transcript', async () => {+ const result = await reconcileRunUsage(+ { ...run, providerId: 'ollama', model: 'llama3' },+ { tokensIn: 12, tokensOut: 340 },+ { home }+ );+ expect(result).toMatchObject({ providerId: 'ollama', tokensOut: 340, source: 'estimate' });+ });++ it('clamps a negative estimate to zero', async () => {+ const result = await reconcileRunUsage(run, { tokensIn: -5, tokensOut: -1 }, { home });+ expect(result).toMatchObject({ tokensIn: 0, tokensOut: 0 });+ });++ it('keeps PortOS\'s recorded model id over the transcript\'s', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', model: 'claude-opus-5' })+ ]);+ // A Bedrock-prefixed id is what the pricing table needs to resolve.+ const bedrock = { ...run, model: 'global.anthropic.claude-opus-5[1m]' };+ const result = await reconcileRunUsage(bedrock, { tokensIn: 1, tokensOut: 1 }, { home });+ expect(result.model).toBe('global.anthropic.claude-opus-5[1m]');+ expect(result.source).toBe('measured');+ });+});++describe('recordCompletedRunUsage', () => {+ it('persists measured counts for a run with a transcript', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })+ ]);++ await recordCompletedRunUsage({+ providerId: 'claude-code',+ model: 'claude-opus-5',+ workspacePath: WORKSPACE,+ promptLength: 80,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ }, 'some captured output', { home });++ expect(recordRunUsage).toHaveBeenCalledTimes(1);+ expect(recordRunUsage.mock.calls[0][0]).toMatchObject({+ source: 'measured',+ tokensOut: 50,+ cacheReadTokens: 1000+ });+ });++ it('records the estimate when no transcript exists rather than recording nothing', async () => {+ await recordCompletedRunUsage({+ providerId: 'ollama',+ model: 'llama3',+ workspacePath: WORKSPACE,+ promptLength: 400,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ }, 'x'.repeat(4000));++ expect(recordRunUsage).toHaveBeenCalledTimes(1);+ const record = recordRunUsage.mock.calls[0][0];+ expect(record.source).toBe('estimate');+ expect(record.tokensOut).toBeGreaterThan(0);+ expect(record.tokensIn).toBeGreaterThan(0);+ });++ it('skips a run with no providerId instead of creating an unknown bucket', async () => {+ await recordCompletedRunUsage({ workspacePath: WORKSPACE, promptLength: 10 }, 'out');+ expect(recordRunUsage).not.toHaveBeenCalled();+ });++ it('swallows a persistence failure so usage accounting never fails the run', async () => {+ recordRunUsage.mockRejectedValueOnce(new Error('disk full'));+ await expect(recordCompletedRunUsage({+ providerId: 'claude-code',+ model: 'claude-opus-5',+ workspacePath: WORKSPACE,+ promptLength: 10,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ }, 'out')).resolves.toBeUndefined();+ });+});++describe('backfillMeasuredUsage', () => {+ it('attributes each session to the day it ran and reports a summary', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })+ ]);+ await writeClaudeSession('b.jsonl', [+ claudeAssistant({ id: 'm2', timestamp: '2026-07-02T10:05:00.000Z', output: 25 })+ ]);++ const summary = await backfillMeasuredUsage({ home });++ expect(summary).toMatchObject({ days: 2, sessions: 2, tokensOut: 75, families: ['claude'] });+ const days = replaceMeasuredDayUsage.mock.calls.map(([day]) => day).sort();+ expect(days).toEqual(['2026-07-01', '2026-07-02']);+ // Provider attribution is the canonical per-CLI id, since a transcript does+ // not record which PortOS provider config invoked it.+ expect(replaceMeasuredDayUsage.mock.calls[0][1][0]).toMatchObject({ providerId: 'claude-code' });+ });++ it('honors the since floor', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'old', timestamp: '2026-06-01T10:00:00.000Z' })+ ]);+ await writeClaudeSession('b.jsonl', [+ claudeAssistant({ id: 'new', timestamp: '2026-07-02T10:00:00.000Z' })+ ]);++ const summary = await backfillMeasuredUsage({ home, since: '2026-07-01' });+ expect(summary.days).toBe(1);+ expect(replaceMeasuredDayUsage.mock.calls.map(([day]) => day)).toEqual(['2026-07-02']);+ });++ it('walks every project directory, not just the current workspace', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z' })+ ], '-work-repo-one');+ await writeClaudeSession('b.jsonl', [+ claudeAssistant({ id: 'm2', timestamp: '2026-07-01T11:00:00.000Z' })+ ], '-work-repo-two');++ const summary = await backfillMeasuredUsage({ home });+ expect(summary.sessions).toBe(2);+ });++ it('includes codex rollouts alongside claude sessions', async () => {+ await writeClaudeSession('a.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z' })+ ]);+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', codexRollout({+ timestamp: '2026-07-01T11:00:00.000Z', input: 1000, cached: 400, output: 60+ }));++ const summary = await backfillMeasuredUsage({ home });+ expect(summary.sessions).toBe(2);+ expect(summary.families.sort()).toEqual(['claude', 'codex']);+ const records = replaceMeasuredDayUsage.mock.calls[0][1];+ expect(records.map((r) => r.providerId).sort()).toEqual(['claude-code', 'codex']);+ });++ it('is a clean no-op on a home with no transcripts', async () => {+ const summary = await backfillMeasuredUsage({ home });+ expect(summary).toMatchObject({ days: 0, sessions: 0, families: [] });+ expect(replaceMeasuredDayUsage).not.toHaveBeenCalled();+ });++ it('ignores transcripts with zero measurable tokens', async () => {+ await writeClaudeSession('empty.jsonl', [+ JSON.stringify({ type: 'user', cwd: WORKSPACE, sessionId: 'sess-1' })+ ]);+ const summary = await backfillMeasuredUsage({ home });+ expect(summary.sessions).toBe(0);+ });+});++describe('backfillMeasuredUsage — local-model attribution (regression)', () => {+ // A Claude-Code-flavored CLI pointed at an Ollama backend writes its+ // transcript under ~/.claude/projects but records the LOCAL model id.+ // Attributing that to `claude-code` billed free inference at Anthropic rates.+ it('routes a local model id to the free ollama provider, not claude-code', async () => {+ await writeClaudeSession('local.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z', model: 'qwen3.6:35b' })+ ]);++ await backfillMeasuredUsage({ home });+ const records = replaceMeasuredDayUsage.mock.calls[0][1];+ expect(records).toHaveLength(1);+ expect(records[0]).toMatchObject({ providerId: 'ollama', model: 'qwen3.6:35b' });+ });++ it('still attributes hosted models to their own CLI provider', async () => {+ await writeClaudeSession('hosted.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z', model: 'claude-opus-5' })+ ]);++ await backfillMeasuredUsage({ home });+ expect(replaceMeasuredDayUsage.mock.calls[0][1][0]).toMatchObject({ providerId: 'claude-code' });+ });++ it('splits a day that mixed local and hosted models into separate rows', async () => {+ await writeClaudeSession('local.jsonl', [+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z', model: 'qwen3.6:35b' })+ ]);+ await writeClaudeSession('hosted.jsonl', [+ claudeAssistant({ id: 'm2', timestamp: '2026-07-01T11:00:00.000Z', model: 'claude-opus-5' })+ ]);++ await backfillMeasuredUsage({ home });+ const records = replaceMeasuredDayUsage.mock.calls[0][1];+ expect(records.map((r) => r.providerId).sort()).toEqual(['claude-code', 'ollama']);+ });+});