Skip to content

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

address review (codex): stop four ways transcript tokens could be billed twice or to the wrong model

[._.]/ Adam Eivyeb3ffde4a7c1
diff --git a/server/lib/README.md b/server/lib/README.md
index ab701685a5..0c547c7144 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -102,7 +102,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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; 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`. |
+| `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. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. 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/providerTranscriptUsage.js b/server/lib/providerTranscriptUsage.js
index c4a1f464cd..c37231197f 100644
--- a/server/lib/providerTranscriptUsage.js
+++ b/server/lib/providerTranscriptUsage.js
@@ -76,13 +76,18 @@ const toEpoch = (value) => {
};
/**
- * 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.
+ * True when `ts` falls inside `[from, to]`. A null bound is open.
+ *
+ * A message with NO readable timestamp is EXCLUDED whenever a bound is supplied.
+ * Counting it would be worse than dropping it: a bounded window means the caller
+ * is attributing one run's share of a possibly long-lived session, and a
+ * timestamp-less line can't be placed in any run — so accepting it hands the same
+ * tokens to every run that ever reads this file, turning one unparseable line
+ * into permanent double-billing on every completion. With no bounds at all
+ * (a whole-file read) there is nothing to double-count against, so it's kept.
*/
const inWindow = (ts, from, to) => {
- if (ts == null) return true;
+ if (ts == null) return from == null && to == null;
if (from != null && ts < from) return false;
if (to != null && ts > to) return false;
return true;
@@ -104,18 +109,26 @@ const inWindow = (ts, from, 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).
+ * @param {{ from?: number|null, to?: number|null, exclude?: Set<string>|null }} [opts]
+ * `from`/`to` are epoch-ms bounds; assistant messages outside the window are
+ * excluded (used to attribute a long-lived CLI session to one PortOS run).
+ * `exclude` is a set of message keys already billed to another run — those are
+ * skipped, and the keys this call DID count come back as `countedKeys` so the
+ * caller can claim them. Without this, two runs whose windows overlap both
+ * fold the same messages and the cost doubles.
* @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 }}
+ * models: string[], byModel: object, messages: number, tokensIn: number,
+ * tokensOut: number, cacheReadTokens: number, cacheWriteTokens: number,
+ * countedKeys: string[], firstTs: string|null, lastTs: string|null }}
*/
-export function parseClaudeTranscript(jsonlText, { from = null, to = null } = {}) {
+export function parseClaudeTranscript(jsonlText, { from = null, to = null, exclude = null } = {}) {
const totals = emptyTotals();
const seen = new Set();
const modelCounts = new Map();
+ // Per-model token buckets, so a session that switched models mid-run
+ // (`/model`, or a fallback) can be priced at each model's own rate instead of
+ // billing the whole aggregate at whichever model happened to run most.
+ const byModel = new Map();
let sessionId = null;
let cwd = null;
let firstTs = null;
@@ -135,6 +148,9 @@ export function parseClaudeTranscript(jsonlText, { from = null, to = null } = {}
const dedupeKey = entry.message?.id || entry.uuid;
if (dedupeKey) {
if (seen.has(dedupeKey)) continue;
+ // Already billed to another run whose window also covers this message —
+ // skip it so overlapping runs can't each claim the same tokens.
+ if (exclude?.has(dedupeKey)) continue;
seen.add(dedupeKey);
}
@@ -145,7 +161,16 @@ export function parseClaudeTranscript(jsonlText, { from = null, to = null } = {}
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 (model) {
+ modelCounts.set(model, (modelCounts.get(model) || 0) + 1);
+ if (!byModel.has(model)) byModel.set(model, emptyTotals());
+ const bucket = byModel.get(model);
+ bucket.messages += 1;
+ bucket.tokensIn += num(usage.input_tokens);
+ bucket.tokensOut += num(usage.output_tokens);
+ bucket.cacheReadTokens += num(usage.cache_read_input_tokens);
+ bucket.cacheWriteTokens += num(usage.cache_creation_input_tokens);
+ }
if (typeof entry.timestamp === 'string' && entry.timestamp) {
if (!firstTs || entry.timestamp < firstTs) firstTs = entry.timestamp;
@@ -154,13 +179,27 @@ export function parseClaudeTranscript(jsonlText, { from = null, to = null } = {}
}
// 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.
+ // model seen, plus the most-used one as the single `model` attribution — and
+ // `byModel`, so a caller can price each model's own tokens at its own rate
+ // rather than billing the whole aggregate at the majority model.
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 };
+ return {
+ sessionId,
+ cwd,
+ model,
+ models,
+ byModel: Object.fromEntries(byModel),
+ // The message keys this call counted — the caller claims them so a later,
+ // overlapping run can pass them back as `exclude` instead of re-billing.
+ countedKeys: [...seen],
+ ...totals,
+ firstTs,
+ lastTs
+ };
}
/**
@@ -215,7 +254,14 @@ export function parseCodexRollout(jsonlText, { from = null, to = null } = {}) {
if (entry.type === 'turn_context' && typeof payload?.model === 'string') {
model ??= payload.model;
}
- if (payload?.type === 'agent_message') messages += 1;
+ // Count assistant messages only inside the window, the same way the token
+ // totals below are windowed. A rollout can span several PortOS runs, so
+ // counting every `agent_message` in the file would hand each later run the
+ // earlier runs' message counts while its tokens are correctly a delta.
+ if (payload?.type === 'agent_message') {
+ if (inWindow(toEpoch(entry.timestamp), from, to)) messages += 1;
+ continue;
+ }
if (payload?.type !== 'token_count') continue;
const total = payload.info?.total_token_usage;
@@ -236,7 +282,7 @@ export function parseCodexRollout(jsonlText, { from = null, to = null } = {}) {
}
if (!latest) {
- return { sessionId, cwd, model, models: model ? [model] : [], ...emptyTotals(), firstTs, lastTs };
+ return { sessionId, cwd, model, models: model ? [model] : [], byModel: {}, ...emptyTotals(), firstTs, lastTs };
}
// Cumulative delta against the pre-window baseline (0 when unwindowed).
@@ -244,11 +290,7 @@ export function parseCodexRollout(jsonlText, { from = null, to = null } = {}) {
const cachedIn = delta('cached_input_tokens');
const totalIn = delta('input_tokens');
- return {
- sessionId,
- cwd,
- model,
- models: model ? [model] : [],
+ const totals = {
// Codex reports no per-message split; a rollout is one recorded exchange
// when it produced any assistant message.
messages: messages || 1,
@@ -257,7 +299,19 @@ export function parseCodexRollout(jsonlText, { from = null, to = null } = {}) {
tokensIn: Math.max(0, totalIn - cachedIn),
tokensOut: delta('output_tokens'),
cacheReadTokens: cachedIn,
- cacheWriteTokens: 0,
+ cacheWriteTokens: 0
+ };
+
+ return {
+ sessionId,
+ cwd,
+ model,
+ models: model ? [model] : [],
+ // Codex reports one model per rollout (no mid-session switch in the format),
+ // so the whole delta is that model's — mirrored into `byModel` for shape
+ // parity with the Claude parser so callers need no per-family branch.
+ byModel: model ? { [model]: { ...totals } } : {},
+ ...totals,
firstTs,
lastTs
};
diff --git a/server/lib/providerTranscriptUsage.test.js b/server/lib/providerTranscriptUsage.test.js
index bed9045409..502737d347 100644
--- a/server/lib/providerTranscriptUsage.test.js
+++ b/server/lib/providerTranscriptUsage.test.js
@@ -285,3 +285,80 @@ describe('totalTranscriptTokens', () => {
expect(totalTranscriptTokens(null)).toBe(0);
});
});
+
+describe('windowing excludes un-placeable messages', () => {
+ // A line with no readable timestamp can't be placed in any run. Accepting it
+ // under a bounded window would hand the same tokens to EVERY run that reads
+ // the file — one unparseable line becoming permanent double-billing.
+ it('excludes a timestamp-less Claude message when a window is supplied', () => {
+ const noTs = JSON.parse(claudeLine({ id: 'no-ts' }));
+ delete noTs.timestamp;
+ const text = [
+ JSON.stringify(noTs),
+ claudeLine({ id: 'in-window', timestamp: '2026-07-01T10:05:00.000Z' })
+ ].join('\n');
+
+ const windowed = parseClaudeTranscript(text, {
+ from: Date.parse('2026-07-01T10:00:00.000Z'),
+ to: Date.parse('2026-07-01T10:10:00.000Z')
+ });
+ expect(windowed.messages).toBe(1);
+ expect(windowed.tokensOut).toBe(50);
+ });
+
+ it('still counts a timestamp-less message on an UNBOUNDED read', () => {
+ const noTs = JSON.parse(claudeLine({ id: 'no-ts' }));
+ delete noTs.timestamp;
+ // No window means no other run to double-count against, so keeping it is
+ // strictly better than dropping real tokens.
+ expect(parseClaudeTranscript(JSON.stringify(noTs)).messages).toBe(1);
+ });
+
+ it('windows Codex agent_message counts alongside the token delta', () => {
+ const text = [
+ codexMeta(),
+ JSON.stringify({ timestamp: '2026-07-01T09:00:00.000Z', type: 'event_msg', payload: { type: 'agent_message', message: 'earlier run' } }),
+ codexTokenCount({ timestamp: '2026-07-01T09:00:01.000Z', input: 1000, cached: 800, output: 100 }),
+ JSON.stringify({ timestamp: '2026-07-01T12:00:00.000Z', type: 'event_msg', payload: { type: 'agent_message', message: 'this run' } }),
+ codexTokenCount({ timestamp: '2026-07-01T12:00:01.000Z', input: 3000, cached: 2400, output: 250 })
+ ].join('\n');
+
+ // The later run's tokens are a delta, so its message count must be too —
+ // otherwise it also claims the earlier run's messages.
+ const result = parseCodexRollout(text, { from: Date.parse('2026-07-01T11:00:00.000Z') });
+ expect(result.messages).toBe(1);
+ expect(result.tokensOut).toBe(150);
+ });
+});
+
+describe('per-model token buckets', () => {
+ it('splits a model switch into per-model buckets that sum to the totals', () => {
+ const text = [
+ claudeLine({ id: 'a', model: 'claude-opus-5', output: 50, cacheRead: 1000, input: 10, cacheWrite: 100 }),
+ claudeLine({ id: 'b', model: 'claude-haiku-4-5', output: 25, cacheRead: 500, input: 5, cacheWrite: 20 })
+ ].join('\n');
+
+ const result = parseClaudeTranscript(text);
+ expect(Object.keys(result.byModel).sort()).toEqual(['claude-haiku-4-5', 'claude-opus-5']);
+ expect(result.byModel['claude-opus-5']).toMatchObject({ messages: 1, tokensOut: 50, cacheReadTokens: 1000, cacheWriteTokens: 100 });
+ expect(result.byModel['claude-haiku-4-5']).toMatchObject({ messages: 1, tokensOut: 25, cacheReadTokens: 500, cacheWriteTokens: 20 });
+ // No tokens invented or lost by the split.
+ const sum = (field) => Object.values(result.byModel).reduce((s, b) => s + b[field], 0);
+ expect(sum('tokensOut')).toBe(result.tokensOut);
+ expect(sum('tokensIn')).toBe(result.tokensIn);
+ expect(sum('cacheReadTokens')).toBe(result.cacheReadTokens);
+ expect(sum('cacheWriteTokens')).toBe(result.cacheWriteTokens);
+ });
+
+ it('mirrors the Codex rollout total into byModel for shape parity', () => {
+ const text = [
+ codexMeta(),
+ codexTokenCount({ timestamp: '2026-07-01T10:00:01.000Z', input: 3000, cached: 2400, output: 250 })
+ ].join('\n');
+
+ const result = parseCodexRollout(text);
+ expect(result.byModel['gpt-5.3-codex']).toMatchObject({
+ tokensIn: 600, cacheReadTokens: 2400, tokensOut: 250, cacheWriteTokens: 0
+ });
+ });
+});
diff --git a/server/services/usage.js b/server/services/usage.js
index 71ee43b583..61d283a34d 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -1,6 +1,6 @@
import { join } from 'path';
import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
-import { resolveModelRates, isFreeProvider, estimateCostUsd, PRICING_AS_OF } from '../lib/modelPricing.js';
+import { resolveModelRates, isFreeProvider, isFreeModelId, estimateCostUsd, PRICING_AS_OF } from '../lib/modelPricing.js';
const DATA_DIR = PATHS.data;
const USAGE_FILE = join(DATA_DIR, 'usage.json');
@@ -358,11 +358,23 @@ export async function recordMessages(providerId, model, messageCount, outputToke
* primitive (and the API route's path) for callers with nothing but a token
* count.
*
+ * Accepts a single record OR an array of them — a run whose session switched
+ * models mid-flight yields one record per model, so each is priced at its own
+ * rate rather than the whole aggregate at the launch-time model.
+ *
* @param {{ providerId: string|null, model: string|null, messages?: number,
* tokensIn?: number, tokensOut?: number, cacheReadTokens?: number,
- * cacheWriteTokens?: number, source?: 'measured'|'estimate' }} record
+ * cacheWriteTokens?: number, source?: 'measured'|'estimate' }
+ * | Array<object>} record
*/
export async function recordRunUsage(record) {
+ // A single run can produce several records when its session switched models
+ // mid-flight (see usageReconciler.reconcileRunUsage) — record each so every
+ // model's tokens are priced at that model's own rate.
+ if (Array.isArray(record)) {
+ for (const entry of record) await recordRunUsage(entry);
+ return;
+ }
const {
providerId = null,
model = null,
@@ -646,8 +658,15 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
let providerCost = 0;
for (const [model, m] of p.byModel.entries()) {
- const rates = free ? null : resolveModelRates(pid, model);
- const cost = free ? 0 : estimateCostUsd(m.tokensIn, m.tokensOut, rates, m);
+ // The MODEL can be free even when the provider isn't: a Claude-Code-flavored
+ // CLI pointed at a local Ollama/LM Studio backend keeps its `claude-*`
+ // provider id (which `isFreeProvider` correctly reads as paid) while running
+ // `qwen3.6:35b`. Without this per-model check the row resolves through the
+ // `claude` provider default and invents cost for free local inference —
+ // measured at $131 for one day of it.
+ const freeModel = free || isFreeModelId(model);
+ const rates = freeModel ? null : resolveModelRates(pid, model);
+ const cost = freeModel ? 0 : estimateCostUsd(m.tokensIn, m.tokensOut, rates, m);
providerCost += cost;
models.push({
model,
@@ -660,7 +679,7 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
source: m.source || 'estimate',
estimatedCost: roundCents(cost),
rateModel: rates?.rateModel ?? null,
- rateMatch: free ? 'free' : rates.matched,
+ rateMatch: freeModel ? 'free' : rates.matched,
inputPer1M: rates?.inputPer1M ?? 0,
outputPer1M: rates?.outputPer1M ?? 0,
cacheReadPer1M: rates?.cacheReadPer1M ?? 0,
diff --git a/server/services/usage.test.js b/server/services/usage.test.js
index 849aa0e827..36c79a5511 100644
--- a/server/services/usage.test.js
+++ b/server/services/usage.test.js
@@ -1039,3 +1039,68 @@ describe('buildUsageReport — cache pricing and source reporting', () => {
});
+
+describe('buildUsageReport — local models under a paid provider', () => {
+ // A Claude-Code-flavored CLI can be pointed at a local Ollama backend. Its
+ // provider id stays `claude-*` (correctly PAID to isFreeProvider) while the
+ // model is `qwen3.6:35b`. Before the per-model check, that row resolved
+ // through the `claude` provider default and invented ~$131 of cost for a day
+ // of free local inference. This test bills through the REPORT, not the
+ // predicate, so it fails if the wiring is ever dropped.
+ const paidClaudeProvider = [{ id: 'claude-code-tui', name: 'Claude Code TUI', type: 'cli', command: 'claude' }];
+ const dayWith = (model) => ({
+ '2026-07-01': {
+ sessions: 1, messages: 1,
+ byProvider: {
+ 'claude-code-tui': {
+ name: 'Claude Code TUI', sessions: 1, messages: 1,
+ tokensIn: 5000, tokensOut: 100_000,
+ cacheReadTokens: 370_000_000, cacheWriteTokens: 5_000_000,
+ source: 'measured',
+ byModel: {
+ [model]: {
+ sessions: 1, messages: 1, tokensIn: 5000, tokensOut: 100_000,
+ cacheReadTokens: 370_000_000, cacheWriteTokens: 5_000_000, source: 'measured'
+ }
+ }
+ }
+ }
+ }
+ });
+
+ it('prices a local model at zero even under a paid provider id', () => {
+ const report = buildUsageReport(dayWith('qwen3.6:35b'), { providers: paidClaudeProvider });
+ expect(report.totals.estimatedCost).toBe(0);
+ expect(report.providers[0].models[0].rateMatch).toBe('free');
+ // The tokens are still reported — only the cost is zero.
+ expect(report.totals.cacheReadTokens).toBe(370_000_000);
+ });
+
+ it('still bills a hosted model on the same provider', () => {
+ const report = buildUsageReport(dayWith('claude-opus-5'), { providers: paidClaudeProvider });
+ expect(report.totals.estimatedCost).toBeGreaterThan(100);
+ expect(report.providers[0].models[0].rateMatch).toBe('exact');
+ });
+
+ it('bills only the hosted half of a mixed local/hosted day', () => {
+ const daily = {
+ '2026-07-01': {
+ sessions: 2, messages: 2,
+ byProvider: {
+ 'claude-code-tui': {
+ name: 'Claude Code TUI', sessions: 2, messages: 2,
+ tokensIn: 0, tokensOut: 2_000_000, cacheReadTokens: 0, cacheWriteTokens: 0,
+ source: 'measured',
+ byModel: {
+ 'qwen3.6:35b': { sessions: 1, messages: 1, tokensIn: 0, tokensOut: 1_000_000, cacheReadTokens: 0, cacheWriteTokens: 0, source: 'measured' },
+ 'claude-opus-5': { sessions: 1, messages: 1, tokensIn: 0, tokensOut: 1_000_000, cacheReadTokens: 0, cacheWriteTokens: 0, source: 'measured' }
+ }
+ }
+ }
+ }
+ };
+ const report = buildUsageReport(daily, { providers: paidClaudeProvider });
+ // 1M output on claude-opus-5 = $25; the local million is free.
+ expect(report.totals.estimatedCost).toBeCloseTo(25, 2);
+ });
+});
diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.js
index e17819ed66..263088dfcc 100644
--- a/server/services/usageReconciler.js
+++ b/server/services/usageReconciler.js
@@ -40,11 +40,30 @@ import { recordRunUsage } 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).
+// after the process exits. A minute of slack captures both.
+//
+// The slack does NOT make attribution exclusive: PortOS runs are NOT serialized
+// per cwd (the runner allows several concurrent), and measured against this
+// install's run history there are 39 genuinely overlapping same-cwd run pairs —
+// 144 once this slack is applied. Two overlapping runs would each fold the whole
+// overlap and double-bill it, so exclusivity is enforced separately by the
+// per-message claim below, not by the window.
const WINDOW_SLACK_MS = 60_000;
+// Messages already billed to a run, keyed `<transcript-key>:<message-key>`.
+// A transcript message must be counted exactly ONCE across every run that can
+// see it: without this, two concurrent runs in the same cwd (or one run whose
+// window overlaps a neighbour's through WINDOW_SLACK_MS) each fold the same
+// tokens and the cost report doubles. Process-local by design — it guards the
+// live completion path, which is the only writer; a restart loses the ledger,
+// but a run that already completed is never reconciled again.
+const claimedMessages = new Set();
+
+/** Test-only: forget every claim so suites start from a clean ledger. */
+export function __resetUsageClaims() {
+ claimedMessages.clear();
+}
+
// 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
@@ -147,6 +166,10 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
cacheWriteTokens: 0
};
const modelCounts = new Map();
+ // Per-model token buckets across every folded session, so a run that switched
+ // models is priced at each model's own rate rather than billing the whole
+ // aggregate at the majority model.
+ const byModel = new Map();
const fold = (parsed) => {
if (!parsed || totalTranscriptTokens(parsed) === 0) return;
@@ -159,6 +182,33 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
for (const model of parsed.models?.length ? parsed.models : [parsed.model]) {
if (model) modelCounts.set(model, (modelCounts.get(model) || 0) + 1);
}
+ for (const [model, bucket] of Object.entries(parsed.byModel || {})) {
+ if (!byModel.has(model)) {
+ byModel.set(model, { messages: 0, tokensIn: 0, tokensOut: 0, cacheReadTokens: 0, cacheWriteTokens: 0 });
+ }
+ const target = byModel.get(model);
+ target.messages += bucket.messages || 0;
+ target.tokensIn += bucket.tokensIn || 0;
+ target.tokensOut += bucket.tokensOut || 0;
+ target.cacheReadTokens += bucket.cacheReadTokens || 0;
+ target.cacheWriteTokens += bucket.cacheWriteTokens || 0;
+ }
+ };
+
+ // Keys counted by THIS call, claimed only once the whole read succeeds — so a
+ // mid-read failure can't strand messages as billed-to-nobody.
+ const toClaim = [];
+ // Per-file view of the global ledger: a message key is only meaningful within
+ // its own transcript, so scope the claim by file path to avoid a same-id
+ // collision across two different sessions.
+ const excludeFor = (fileKey) => {
+ const prefix = `${fileKey}:`;
+ return {
+ has: (messageKey) => claimedMessages.has(prefix + messageKey)
+ };
+ };
+ const claimFrom = (fileKey, parsed) => {
+ for (const key of parsed.countedKeys || []) toClaim.push(`${fileKey}:${key}`);
};
if (family === 'claude') {
@@ -167,27 +217,39 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
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));
+ const path = join(projectDir, file);
+ const text = await tryReadFile(path);
if (!text) continue;
- fold(parseClaudeTranscript(text, { from, to }));
+ const parsed = parseClaudeTranscript(text, { from, to, exclude: excludeFor(path) });
+ claimFrom(path, parsed);
+ fold(parsed);
}
} 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));
+ const path = join(dir, file);
+ const text = await tryReadFile(path);
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;
+ // A Codex rollout is billed as a cumulative DELTA, so its claim is the
+ // end snapshot it consumed: a second overlapping run that reads the same
+ // rollout must not re-bill the same delta.
+ const snapshotKey = `${path}:${parsed.lastTs || ''}`;
+ if (claimedMessages.has(snapshotKey)) continue;
+ toClaim.push(snapshotKey);
fold(parsed);
}
}
}
if (totals.sessions === 0) return null;
+ for (const key of toClaim) claimedMessages.add(key);
totals.model = [...modelCounts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
+ totals.byModel = Object.fromEntries(byModel);
return totals;
}
@@ -200,10 +262,15 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
* @param {object} run PortOS run metadata (`providerId`, `model`,
* `workspacePath`, `startTime`, `endTime`)
* @param {{ tokensIn: number, tokensOut: number }} estimate fallback counts
+ * Returns a single record, or an ARRAY of them when the transcript names more
+ * than one model (a mid-run `/model` switch or a fallback) — `recordRunUsage`
+ * accepts either, and splitting is what keeps each model priced at its own rate.
+ *
* @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' }>}
+ * cacheWriteTokens: number, source: 'measured'|'estimate' }
+ * | Array<object>>}
*/
export async function reconcileRunUsage(run, estimate, { home = homedir() } = {}) {
const fallback = {
@@ -234,6 +301,28 @@ export async function reconcileRunUsage(run, estimate, { home = homedir() } = {}
});
if (!measured) return fallback;
+ // A session can switch models mid-run, so split the record per model the
+ // transcript actually names — billing every token at the launch-time model
+ // would price a run that started on Opus and finished on Haiku entirely at
+ // Opus rates. `byModel` is authoritative when present; fall back to one
+ // aggregate record when the transcript named no model at all.
+ const perModel = Object.entries(measured.byModel || {});
+ if (perModel.length > 0) {
+ return perModel.map(([model, bucket]) => ({
+ providerId: run?.providerId ?? null,
+ // Keep PortOS's recorded model id when the transcript agrees on the single
+ // model it ran — PortOS's id carries the provider's own shape (e.g. a
+ // Bedrock prefix the pricing table resolves) that the transcript strips.
+ model: perModel.length === 1 ? (run?.model ?? model) : model,
+ messages: bucket.messages || 0,
+ tokensIn: bucket.tokensIn,
+ tokensOut: bucket.tokensOut,
+ cacheReadTokens: bucket.cacheReadTokens,
+ cacheWriteTokens: bucket.cacheWriteTokens,
+ source: 'measured'
+ }));
+ }
+
return {
providerId: run?.providerId ?? null,
// Prefer the model PortOS recorded (it carries the provider's own id shape,
diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.js
index dec11b8921..901995aea0 100644
--- a/server/services/usageReconciler.test.js
+++ b/server/services/usageReconciler.test.js
@@ -12,7 +12,8 @@ const {
transcriptFamily,
readMeasuredUsage,
reconcileRunUsage,
- recordCompletedRunUsage
+ recordCompletedRunUsage,
+ __resetUsageClaims
} = await import('./usageReconciler.js');
// Fake HOME per test so the parsers read fixtures, never the developer's real
@@ -79,6 +80,9 @@ const writeCodexRollout = async (dateParts, file, text) => {
beforeEach(async () => {
home = await mkdtemp(join(tmpdir(), 'portos-usage-'));
vi.clearAllMocks();
+ // The claim ledger is module-level, so a stale claim from a prior test would
+ // make a later read skip messages it should count.
+ __resetUsageClaims();
});
afterEach(async () => {
@@ -245,7 +249,8 @@ describe('reconcileRunUsage', () => {
// must not blend it in.
const result = await reconcileRunUsage(run, { tokensIn: 30, tokensOut: 9999 }, { home });
- expect(result).toEqual({
+ // One model in the transcript → one record, carrying PortOS's model id.
+ expect(result).toEqual([{
providerId: 'claude-code-tui',
model: 'claude-opus-5',
messages: 2,
@@ -254,7 +259,30 @@ describe('reconcileRunUsage', () => {
cacheReadTokens: 1500,
cacheWriteTokens: 120,
source: 'measured'
- });
+ }]);
+ });
+
+ // A session that switched models must be split, or the whole run prices at
+ // whichever model happened to run most — e.g. Haiku tokens billed at Opus.
+ it('splits a model switch into one record per model', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', model: 'claude-opus-5', output: 50, cacheRead: 1000, cacheWrite: 100, input: 10 }),
+ claudeAssistant({ id: 'm2', timestamp: '2026-07-01T10:06:00.000Z', model: 'claude-haiku-4-5', output: 25, cacheRead: 500, cacheWrite: 20, input: 5 })
+ ]);
+
+ const result = await reconcileRunUsage(run, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(Array.isArray(result)).toBe(true);
+ expect(result).toHaveLength(2);
+
+ const byModel = Object.fromEntries(result.map((r) => [r.model, r]));
+ expect(byModel['claude-opus-5']).toMatchObject({ tokensOut: 50, cacheReadTokens: 1000, cacheWriteTokens: 100, source: 'measured' });
+ expect(byModel['claude-haiku-4-5']).toMatchObject({ tokensOut: 25, cacheReadTokens: 500, cacheWriteTokens: 20, source: 'measured' });
+ // With >1 model the transcript's own ids win — PortOS recorded only the
+ // launch-time model, which would misattribute the other one's tokens.
+ expect(byModel['claude-haiku-4-5'].model).toBe('claude-haiku-4-5');
+ // Split records must still sum to the session totals — no tokens lost.
+ expect(result.reduce((s, r) => s + r.tokensOut, 0)).toBe(75);
+ expect(result.reduce((s, r) => s + r.cacheReadTokens, 0)).toBe(1500);
});
it('falls back to the estimate when no transcript matches', async () => {
@@ -289,8 +317,9 @@ describe('reconcileRunUsage', () => {
// 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');
+ expect(result).toHaveLength(1);
+ expect(result[0].model).toBe('global.anthropic.claude-opus-5[1m]');
+ expect(result[0].source).toBe('measured');
});
});
@@ -310,11 +339,10 @@ describe('recordCompletedRunUsage', () => {
}, 'some captured output', { home });
expect(recordRunUsage).toHaveBeenCalledTimes(1);
- expect(recordRunUsage.mock.calls[0][0]).toMatchObject({
- source: 'measured',
- tokensOut: 50,
- cacheReadTokens: 1000
- });
+ // One model → an array of one (recordRunUsage accepts either shape).
+ expect(recordRunUsage.mock.calls[0][0]).toEqual([
+ expect.objectContaining({ source: 'measured', tokensOut: 50, cacheReadTokens: 1000 })
+ ]);
});
it('records the estimate when no transcript exists rather than recording nothing', async () => {
@@ -353,3 +381,69 @@ describe('recordCompletedRunUsage', () => {
});
+
+describe('overlapping runs must not double-bill one transcript', () => {
+ // PortOS runs are NOT serialized per cwd (the runner allows several
+ // concurrent), and WINDOW_SLACK_MS widens each window by a minute — measured
+ // against real run history, 39 same-cwd run pairs genuinely overlap and 144 do
+ // once slack is applied. Without a claim, each overlapping run folds the whole
+ // overlap and the reported cost doubles.
+ const runA = {
+ providerId: 'claude-code-tui',
+ model: 'claude-opus-5',
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z'
+ };
+ const runB = { ...runA, startTime: '2026-07-01T10:02:00.000Z', endTime: '2026-07-01T10:12:00.000Z' };
+
+ it('bills each message exactly once across two overlapping runs', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', output: 50, cacheRead: 1000, cacheWrite: 100, input: 10 }),
+ claudeAssistant({ id: 'm2', timestamp: '2026-07-01T10:06:00.000Z', output: 25, cacheRead: 500, cacheWrite: 20, input: 5 })
+ ]);
+
+ const first = await readMeasuredUsage({ ...runA, family: 'claude', home });
+ const second = await readMeasuredUsage({ ...runB, family: 'claude', home });
+
+ // The first run takes both messages; the second finds them already claimed
+ // and reports nothing rather than re-billing them.
+ expect(first.tokensOut).toBe(75);
+ expect(first.cacheReadTokens).toBe(1500);
+ expect(second).toBeNull();
+
+ // The union across both runs equals the transcript, not double it.
+ const billedOut = (first?.tokensOut || 0) + (second?.tokensOut || 0);
+ expect(billedOut).toBe(75);
+ });
+
+ it('lets a second run claim only the messages the first did not', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'early', timestamp: '2026-07-01T10:05:00.000Z', output: 50, cacheRead: 0, cacheWrite: 0, input: 0 }),
+ claudeAssistant({ id: 'late', timestamp: '2026-07-01T10:11:00.000Z', output: 25, cacheRead: 0, cacheWrite: 0, input: 0 })
+ ]);
+
+ // runA's window ends at 10:10 (+60s slack → 10:11), so it takes both.
+ // Narrow runA so only `early` is in range, leaving `late` for runB.
+ const narrowA = { ...runA, endTime: '2026-07-01T10:06:00.000Z' };
+ const first = await readMeasuredUsage({ ...narrowA, family: 'claude', home });
+ const second = await readMeasuredUsage({ ...runB, family: 'claude', home });
+
+ expect(first.tokensOut).toBe(50);
+ expect(second.tokensOut).toBe(25);
+ // Together they account for the session exactly once.
+ expect(first.tokensOut + second.tokensOut).toBe(75);
+ });
+
+ it('does not double-bill a codex rollout read by two overlapping runs', async () => {
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', codexRollout({
+ timestamp: '2026-07-01T10:05:00.000Z', input: 3000, cached: 2400, output: 250
+ }));
+
+ const first = await readMeasuredUsage({ ...runA, family: 'codex', home });
+ const second = await readMeasuredUsage({ ...runB, family: 'codex', home });
+
+ expect(first.tokensOut).toBe(250);
+ expect(second).toBeNull();
+ });
+});