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

fix([issue-3124]): correct usage cost reporting

[._.]/ Adam Eivy0137afe30efe
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a9de5062d4..5bd10c93dc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## 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.
+
## Navigation
- Third-level Create navigation for Series and Universes can now be collapsed and expanded independently.
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 1bdeb2d74c..58f0e31a1c 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -237,7 +237,12 @@ function ProviderCostRows({ provider }) {
<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">{formatNumber(provider.tokensOut)}</td>
- <td className="py-2 pl-2 text-right">{formatCost(provider.estimatedCost)}</td>
+ <td
+ className="py-2 pl-2 text-right"
+ title={approxMark(provider.rateMatch) ? 'Approximate — provider or legacy usage uses fallback pricing' : undefined}
+ >
+ {approxMark(provider.rateMatch)}{formatCost(provider.estimatedCost)}
+ </td>
</tr>
{provider.models.map((m) => (
<tr key={m.model} className="text-gray-400">
@@ -366,7 +371,7 @@ function InternalUsageMetrics() {
<h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>
{/* Summary Stats (all-time) */}
- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
<div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">
<div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalSessions)}</div>
<div className="text-xs sm:text-sm text-gray-400">Sessions</div>
@@ -375,10 +380,6 @@ function InternalUsageMetrics() {
<div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalMessages)}</div>
<div className="text-xs sm:text-sm text-gray-400">Messages</div>
</div>
- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">
- <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalToolCalls)}</div>
- <div className="text-xs sm:text-sm text-gray-400">Tool Calls</div>
- </div>
<div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">
<div className="text-xl sm:text-2xl font-bold text-white">{formatNumber((usage.totalTokens?.input ?? 0) + (usage.totalTokens?.output ?? 0))}</div>
<div className="text-xs sm:text-sm text-gray-400">Tokens</div>
@@ -388,15 +389,22 @@ function InternalUsageMetrics() {
{/* Cost report — range-filtered per-provider/per-model breakdown */}
<div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
- <h3 className="text-sm font-medium text-gray-400">Est. API Cost Report</h3>
+ <div>
+ <h3 className="text-sm font-medium text-gray-400">Est. API Cost Report</h3>
+ {report?.breakdownSince && (
+ <p className="text-[10px] sm:text-xs text-port-warning">
+ Provider/model detail starts {report.breakdownSince}; earlier usage is grouped as legacy.
+ </p>
+ )}
+ </div>
<span className="text-xl font-bold text-port-success">{formatCost(report?.totals?.estimatedCost)}</span>
</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).
- Token counts are partially estimated; rates as of {report?.pricingAsOf || 'the last update'}, excluding prompt-caching and batch discounts.
- {report?.breakdownSince && <> Per-provider breakdown available from {report.breakdownSince}.</>}
+ 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.
{' '}Rows marked ~ use an approximated rate.
</p>
</div>
diff --git a/scripts/migrations/208-rename-undefined-usage-provider.js b/scripts/migrations/208-rename-undefined-usage-provider.js
new file mode 100644
index 0000000000..bb3de023f2
--- /dev/null
+++ b/scripts/migrations/208-rename-undefined-usage-provider.js
@@ -0,0 +1,64 @@
+/**
+ * Rename usage provider buckets accidentally stored under the JavaScript key
+ * "undefined" to the explicit, displayable "unknown" provider id.
+ *
+ * The usage store is file-primary and exists only after activity is recorded,
+ * so a missing file is a normal no-op. Existing unknown buckets are merged
+ * additively to preserve every count across partial/manual prior repairs.
+ */
+
+import { readFile, rename, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const mergeObjects = (target, source) => {
+ const merged = { ...(target || {}) };
+ for (const [key, value] of Object.entries(source || {})) {
+ if (key === 'name') continue;
+ if (typeof value === 'number') {
+ merged[key] = (typeof merged[key] === 'number' ? merged[key] : 0) + value;
+ } else if (value && typeof value === 'object' && !Array.isArray(value)) {
+ merged[key] = mergeObjects(merged[key], value);
+ } else if (merged[key] === undefined) {
+ merged[key] = value;
+ }
+ }
+ return merged;
+};
+
+const renameProviderBucket = (byProvider) => {
+ if (!byProvider || typeof byProvider !== 'object' || !Object.hasOwn(byProvider, 'undefined')) {
+ return false;
+ }
+ byProvider.unknown = {
+ ...mergeObjects(byProvider.unknown, byProvider.undefined),
+ name: 'Unknown provider'
+ };
+ delete byProvider.undefined;
+ return true;
+};
+
+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 = renameProviderBucket(usage.byProvider);
+ for (const bucket of Object.values(usage.dailyActivity || {})) {
+ changed = renameProviderBucket(bucket?.byProvider) || changed;
+ }
+ for (const bucket of Object.values(usage.monthlyActivity || {})) {
+ changed = renameProviderBucket(bucket?.byProvider) || changed;
+ }
+ if (!changed) return;
+
+ const tempPath = `${usagePath}.208.tmp`;
+ await writeFile(tempPath, `${JSON.stringify(usage, null, 2)}\n`);
+ await rename(tempPath, usagePath);
+ console.log('📊 Migration 208: renamed undefined usage providers to unknown');
+}
+
+export default { up };
diff --git a/scripts/migrations/208-rename-undefined-usage-provider.test.js b/scripts/migrations/208-rename-undefined-usage-provider.test.js
new file mode 100644
index 0000000000..26ee4e6570
--- /dev/null
+++ b/scripts/migrations/208-rename-undefined-usage-provider.test.js
@@ -0,0 +1,80 @@
+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 './208-rename-undefined-usage-provider.js';
+
+const roots = [];
+
+const makeRoot = async () => {
+ const root = await mkdtemp(join(tmpdir(), 'migration-208-'));
+ roots.push(root);
+ await mkdir(join(root, 'data'), { recursive: true });
+ return root;
+};
+
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+});
+
+describe('migration 208 — undefined usage provider', () => {
+ it('renames and merges top-level, daily, and monthly provider buckets', async () => {
+ const rootDir = await makeRoot();
+ const usagePath = join(rootDir, 'data', 'usage.json');
+ await writeFile(usagePath, JSON.stringify({
+ byProvider: {
+ unknown: { name: 'Unknown provider', sessions: 2, messages: 1, tokens: 10 },
+ undefined: { sessions: 3, messages: 4, tokens: 20 }
+ },
+ dailyActivity: {
+ '2026-07-20': {
+ byProvider: {
+ undefined: { sessions: 1, messages: 2, tokensIn: 3, tokensOut: 4, byModel: {} }
+ }
+ }
+ },
+ monthlyActivity: {
+ '2026-06': {
+ byProvider: {
+ unknown: { name: 'Unknown provider', sessions: 1, byModel: { model: { sessions: 1 } } },
+ undefined: { sessions: 2, byModel: { model: { sessions: 2 } } }
+ }
+ }
+ }
+ }));
+
+ await up({ rootDir });
+
+ const usage = JSON.parse(await readFile(usagePath, 'utf8'));
+ expect(usage.byProvider.undefined).toBeUndefined();
+ expect(usage.byProvider.unknown).toMatchObject({
+ name: 'Unknown provider',
+ sessions: 5,
+ messages: 5,
+ tokens: 30
+ });
+ expect(usage.dailyActivity['2026-07-20'].byProvider).toEqual({
+ unknown: {
+ name: 'Unknown provider',
+ sessions: 1,
+ messages: 2,
+ tokensIn: 3,
+ tokensOut: 4,
+ byModel: {}
+ }
+ });
+ expect(usage.monthlyActivity['2026-06'].byProvider.unknown.byModel.model.sessions).toBe(3);
+ });
+
+ it('is a no-op when usage.json is absent or already normalized', async () => {
+ const missingRoot = await makeRoot();
+ await expect(up({ rootDir: missingRoot })).resolves.toBeUndefined();
+
+ const normalizedRoot = await makeRoot();
+ const usagePath = join(normalizedRoot, 'data', 'usage.json');
+ const raw = JSON.stringify({ byProvider: { codex: { sessions: 1 } } });
+ await writeFile(usagePath, raw);
+ await up({ rootDir: normalizedRoot });
+ expect(await readFile(usagePath, 'utf8')).toBe(raw);
+ });
+});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index b7ed4615af..f275623d8b 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -157,6 +157,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD
});
},
onRunCompleted: (metadata, output) => {
+ if (!metadata.providerId) return;
const estimatedTokens = estimateTokens(output);
const inputTokens = estimateTokensFromChars(metadata.promptLength);
recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens, inputTokens).catch(err => {
diff --git a/server/services/usage.js b/server/services/usage.js
index 217ac21c5d..6de640b624 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -13,6 +13,22 @@ const ROLLUP_RETENTION_DAYS = 400;
const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
let usageData = null;
+const UNKNOWN_PROVIDER_ID = 'unknown';
+const UNKNOWN_PROVIDER_NAME = 'Unknown provider';
+const LEGACY_PROVIDER_ID = 'legacy';
+const LEGACY_PROVIDER_NAME = 'Pre-breakdown (legacy)';
+
+const normalizeProvider = (providerId, providerName = null) => {
+ const id = typeof providerId === 'string' && providerId.trim() && providerId.trim() !== 'undefined'
+ ? providerId.trim()
+ : UNKNOWN_PROVIDER_ID;
+ return {
+ id,
+ name: id === UNKNOWN_PROVIDER_ID
+ ? UNKNOWN_PROVIDER_NAME
+ : (providerName || id)
+ };
+};
/**
* Initialize usage data structure
@@ -134,15 +150,16 @@ export function getUsage() {
/**
* Per-day per-provider per-model bucket inside dailyActivity — the additive
- * shape that makes arbitrary-period cost breakdowns possible. Legacy day
- * buckets (pre-upgrade) lack `byProvider`; breakdown reports are forward-only
- * from the first day that has it (see `breakdownSince`).
+ * shape that makes arbitrary-period cost breakdowns possible. Missing provider
+ * ids are attributed to a named `unknown` bucket rather than becoming the
+ * JavaScript property string "undefined".
*/
function providerDayBucket(day, providerId, providerName) {
+ const provider = normalizeProvider(providerId, providerName);
if (!day.byProvider) day.byProvider = {};
- if (!day.byProvider[providerId]) {
- day.byProvider[providerId] = {
- name: providerName || providerId,
+ if (!day.byProvider[provider.id]) {
+ day.byProvider[provider.id] = {
+ name: provider.name,
sessions: 0,
messages: 0,
tokensIn: 0,
@@ -150,7 +167,7 @@ function providerDayBucket(day, providerId, providerName) {
byModel: {}
};
}
- return day.byProvider[providerId];
+ return day.byProvider[provider.id];
}
function modelDayBucket(providerDay, model) {
@@ -173,14 +190,15 @@ function todayBucket() {
*/
export async function recordSession(providerId, providerName, model) {
if (!usageData) await loadUsage();
+ const provider = normalizeProvider(providerId, providerName);
usageData.totalSessions++;
// Track by provider
- if (!usageData.byProvider[providerId]) {
- usageData.byProvider[providerId] = { name: providerName, sessions: 0, messages: 0, tokens: 0 };
+ if (!usageData.byProvider[provider.id]) {
+ usageData.byProvider[provider.id] = { name: provider.name, sessions: 0, messages: 0, tokens: 0 };
}
- usageData.byProvider[providerId].sessions++;
+ usageData.byProvider[provider.id].sessions++;
// Track by model
if (model) {
@@ -193,7 +211,7 @@ export async function recordSession(providerId, providerName, model) {
// Track daily activity (with the per-provider/per-model split)
const day = todayBucket();
day.sessions++;
- const providerDay = providerDayBucket(day, providerId, providerName);
+ const providerDay = providerDayBucket(day, provider.id, provider.name);
providerDay.sessions++;
if (model) modelDayBucket(providerDay, model).sessions++;
@@ -212,6 +230,7 @@ export async function recordSession(providerId, providerName, model) {
*/
export async function recordMessages(providerId, model, messageCount, outputTokens = 0, inputTokens = 0) {
if (!usageData) await loadUsage();
+ const provider = normalizeProvider(providerId);
usageData.totalMessages += messageCount;
@@ -225,10 +244,11 @@ export async function recordMessages(providerId, model, messageCount, outputToke
// Track by provider / by model (the legacy all-time entries keep their
// output-only `tokens` field for old readers — the in/out split lives only
// in the day buckets, which is what the cost report aggregates)
- if (usageData.byProvider[providerId]) {
- usageData.byProvider[providerId].messages += messageCount;
- usageData.byProvider[providerId].tokens = (usageData.byProvider[providerId].tokens || 0) + outputTokens;
+ if (!usageData.byProvider[provider.id]) {
+ usageData.byProvider[provider.id] = { name: provider.name, sessions: 0, messages: 0, tokens: 0 };
}
+ usageData.byProvider[provider.id].messages += messageCount;
+ usageData.byProvider[provider.id].tokens = (usageData.byProvider[provider.id].tokens || 0) + outputTokens;
if (model && usageData.byModel[model]) {
usageData.byModel[model].messages += messageCount;
usageData.byModel[model].tokens = (usageData.byModel[model].tokens || 0) + outputTokens;
@@ -244,8 +264,8 @@ export async function recordMessages(providerId, model, messageCount, outputToke
const day = todayBucket();
day.messages = (day.messages || 0) + messageCount;
day.tokens = (day.tokens || 0) + outputTokens;
- const providerName = usageData.byProvider[providerId]?.name;
- const providerDay = providerDayBucket(day, providerId, providerName);
+ const providerName = usageData.byProvider[provider.id]?.name;
+ const providerDay = providerDayBucket(day, provider.id, providerName);
bumpDayBucket(providerDay);
if (model) bumpDayBucket(modelDayBucket(providerDay, model));
@@ -342,11 +362,6 @@ function findLongestStreak(dailyActivity) {
const roundCents = (n) => Math.round(n * 100) / 100;
-// The historical flat blended rate the all-time `estimatedCost` field has
-// always used — kept so that field's meaning doesn't silently change for
-// existing consumers. The accurate per-model number is `report.totals`.
-const LEGACY_BLENDED_RATES = { inputPer1M: 3.0, outputPer1M: 15.0 };
-
/**
* Aggregate the per-day per-provider per-model buckets over a date range into
* a cost report. `from`/`to` are inclusive `YYYY-MM-DD` strings (null = open
@@ -367,13 +382,18 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
const agg = new Map(); // providerId -> { name, sessions, messages, tokensIn, tokensOut, byModel: Map }
let breakdownSince = null;
+ const ensureAggregate = (pid, name) => {
+ if (!agg.has(pid)) {
+ agg.set(pid, { name, sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, byModel: new Map() });
+ }
+ return agg.get(pid);
+ };
+
// Fold one bucket's per-provider/per-model splits into the running aggregate.
const foldBucket = (bucket) => {
for (const [pid, pDay] of Object.entries(bucket.byProvider)) {
- if (!agg.has(pid)) {
- agg.set(pid, { name: pDay.name || pid, sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, byModel: new Map() });
- }
- const p = agg.get(pid);
+ const normalized = normalizeProvider(pid, pDay.name);
+ const p = ensureAggregate(normalized.id, normalized.name);
p.sessions += pDay.sessions || 0;
p.messages += pDay.messages || 0;
p.tokensIn += pDay.tokensIn || 0;
@@ -391,26 +411,43 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
}
};
+ // Buckets written before per-provider capture still represent real usage.
+ // Keep them in a synthetic fallback-priced row while leaving breakdownSince
+ // to mean "the first date with actual provider/model detail".
+ const foldLegacyBucket = (bucket) => {
+ const p = ensureAggregate(LEGACY_PROVIDER_ID, LEGACY_PROVIDER_NAME);
+ p.sessions += bucket.sessions || 0;
+ p.messages += bucket.messages || 0;
+ p.tokensIn += bucket.tokensIn || 0;
+ p.tokensOut += typeof bucket.tokensOut === 'number' ? bucket.tokensOut : (bucket.tokens || 0);
+ };
+
// Rolled-up monthly buckets first, so `breakdownSince` reflects the earliest
// month once old days have been collapsed. A `YYYY-MM` key overlaps the range
// whenever its month is within the from/to months (compared at month prefix).
const fromMonth = from ? from.slice(0, 7) : null;
const toMonth = to ? to.slice(0, 7) : null;
for (const [month, bucket] of Object.entries(monthlyActivity || {})) {
- if (!bucket?.byProvider) continue;
- const monthStart = `${month}-01`;
- if (!breakdownSince || monthStart < breakdownSince) breakdownSince = monthStart;
if (fromMonth && month < fromMonth) continue;
if (toMonth && month > toMonth) continue;
- foldBucket(bucket);
+ if (bucket?.byProvider) {
+ const monthStart = `${month}-01`;
+ if (!breakdownSince || monthStart < breakdownSince) breakdownSince = monthStart;
+ foldBucket(bucket);
+ } else if (bucket) {
+ foldLegacyBucket(bucket);
+ }
}
for (const [date, day] of Object.entries(dailyActivity || {})) {
- if (!day?.byProvider) continue;
- if (!breakdownSince || date < breakdownSince) breakdownSince = date;
if (from && date < from) continue;
if (to && date > to) continue;
- foldBucket(day);
+ if (day?.byProvider) {
+ if (!breakdownSince || date < breakdownSince) breakdownSince = date;
+ foldBucket(day);
+ } else if (day) {
+ foldLegacyBucket(day);
+ }
}
const totals = { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, estimatedCost: 0 };
@@ -419,6 +456,7 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
for (const [pid, p] of agg.entries()) {
const config = configById.get(pid);
const free = isFreeProvider(config || pid);
+ const providerRates = free ? null : resolveModelRates(pid === LEGACY_PROVIDER_ID ? null : pid, null);
const models = [];
let providerCost = 0;
@@ -448,7 +486,7 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
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, resolveModelRates(pid, null));
+ providerCost += estimateCostUsd(unattributedIn, unattributedOut, providerRates);
}
totals.sessions += p.sessions;
@@ -466,6 +504,11 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
tokensIn: p.tokensIn,
tokensOut: p.tokensOut,
estimatedCost: roundCents(providerCost),
+ rateMatch: pid === LEGACY_PROVIDER_ID
+ ? 'fallback'
+ : (models.some((model) => model.rateMatch !== 'exact' && model.rateMatch !== 'free') || unattributedIn > 0 || unattributedOut > 0
+ ? (providerRates?.matched || 'fallback')
+ : (free ? 'free' : 'exact')),
models
});
}
@@ -530,13 +573,19 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})
const longestStreak = findLongestStreak(usageData.dailyActivity);
const report = buildUsageReport(usageData.dailyActivity, { from, to, providers, monthlyActivity: usageData.monthlyActivity });
+ const allTimeReport = from || to
+ ? buildUsageReport(usageData.dailyActivity, { providers, monthlyActivity: usageData.monthlyActivity })
+ : report;
return {
totalSessions: usageData.totalSessions,
totalMessages: usageData.totalMessages,
totalToolCalls: usageData.totalToolCalls,
totalTokens: usageData.totalTokens,
- estimatedCost: roundCents(estimateCostUsd(usageData.totalTokens.input, usageData.totalTokens.output, LEGACY_BLENDED_RATES)),
+ // Backward-compatible field, now sourced from the same complete,
+ // per-model/fallback-priced report as the headline instead of a second
+ // contradictory blended-rate calculation.
+ estimatedCost: allTimeReport.totals.estimatedCost,
currentStreak,
longestStreak,
last7Days,
diff --git a/server/services/usage.test.js b/server/services/usage.test.js
index 5b518baf3a..fa7bb94e4e 100644
--- a/server/services/usage.test.js
+++ b/server/services/usage.test.js
@@ -208,13 +208,41 @@ describe('usage.js — streak calculations', () => {
expect(typeof today.label).toBe('string');
});
- it('estimatedCost keeps its all-time legacy-blended semantics ($3/$15 per 1M)', async () => {
- readJSONFile.mockResolvedValueOnce(makeUsage({}, {
- totalTokens: { input: 1_000_000, output: 500_000 }
+ it('estimatedCost agrees with the unbounded report total', async () => {
+ readJSONFile.mockResolvedValueOnce(makeUsage({
+ '2025-05-01': { sessions: 1, messages: 1, tokens: 500_000 },
+ '2025-06-01': {
+ sessions: 1,
+ messages: 1,
+ tokens: 1_000_000,
+ byProvider: {
+ codex: {
+ name: 'Codex',
+ sessions: 1,
+ messages: 1,
+ tokensIn: 1_000_000,
+ tokensOut: 1_000_000,
+ byModel: {}
+ }
+ }
+ }
}));
await loadUsage();
const summary = getUsageSummary();
- expect(summary.estimatedCost).toBeCloseTo(10.5); // 1M×$3 + 0.5M×$15
+ expect(summary.estimatedCost).toBe(summary.report.totals.estimatedCost);
+ expect(summary.estimatedCost).toBeCloseTo(23.25);
+ });
+
+ it('keeps estimatedCost all-time when the visible report is range-filtered', async () => {
+ readJSONFile.mockResolvedValueOnce(makeUsage({
+ '2025-05-01': { sessions: 1, messages: 1, tokens: 1_000_000 },
+ '2025-06-01': { sessions: 1, messages: 1, tokens: 500_000 }
+ }));
+ await loadUsage();
+
+ const summary = getUsageSummary({ from: '2025-06-01', to: '2025-06-01' });
+ expect(summary.report.totals.estimatedCost).toBe(7.5);
+ expect(summary.estimatedCost).toBe(22.5);
});
});
@@ -239,6 +267,56 @@ describe('usage.js — streak calculations', () => {
expect(day.byProvider['claude-code'].byModel.opus.sessions).toBe(1);
});
+ it('attributes missing provider ids to a named unknown bucket', async () => {
+ readJSONFile.mockResolvedValueOnce(makeUsage({}));
+ await loadUsage();
+ await recordSession(undefined, undefined, null);
+ await recordMessages(undefined, null, 1, 40, 10);
+
+ const usage = getUsage();
+ expect(usage.byProvider.undefined).toBeUndefined();
+ expect(usage.byProvider.unknown).toMatchObject({
+ name: 'Unknown provider',
+ sessions: 1,
+ messages: 1,
+ tokens: 40
+ });
+ const day = usage.dailyActivity[daysAgo(0)];
+ expect(day.byProvider.unknown).toMatchObject({
+ name: 'Unknown provider',
+ sessions: 1,
+ messages: 1,
+ tokensIn: 10,
+ tokensOut: 40
+ });
+ });
+
+ it('normalizes a persisted string "undefined" provider in reports', () => {
+ const report = buildUsageReport({
+ [daysAgo(0)]: {
+ sessions: 1,
+ messages: 1,
+ tokens: 20,
+ byProvider: {
+ undefined: {
+ sessions: 1,
+ messages: 1,
+ tokensIn: 10,
+ tokensOut: 20,
+ byModel: {}
+ }
+ }
+ }
+ });
+ expect(report.providers).toEqual([
+ expect.objectContaining({
+ id: 'unknown',
+ name: 'Unknown provider',
+ sessions: 1
+ })
+ ]);
+ });
+
it('recordMessages attributes input and output tokens to provider, model, and day', async () => {
readJSONFile.mockResolvedValueOnce(makeUsage({}));
await loadUsage();
@@ -331,16 +409,42 @@ describe('usage.js — streak calculations', () => {
expect(report.totals.estimatedCost).toBe(0);
});
- it('reports breakdownSince as the earliest day with a provider split, ignoring legacy days', () => {
+ it('includes legacy days in a fallback-priced row without changing breakdownSince', () => {
const daily = {
- '2025-05-01': { sessions: 3, messages: 3, tokens: 100 }, // legacy — no byProvider
+ '2025-05-01': { sessions: 3, messages: 3, tokens: 1_000_000 }, // legacy — no byProvider
'2025-06-03': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 10 }),
'2025-06-01': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 10 })
};
const report = buildUsageReport(daily, {});
expect(report.breakdownSince).toBe('2025-06-01');
- // legacy day contributes nothing to the breakdown
- expect(report.totals.sessions).toBe(2);
+ expect(report.totals.sessions).toBe(5);
+ expect(report.totals.tokensOut).toBe(1_000_020);
+ expect(report.providers.find((provider) => provider.id === 'legacy')).toMatchObject({
+ name: 'Pre-breakdown (legacy)',
+ sessions: 3,
+ tokensOut: 1_000_000,
+ estimatedCost: 15,
+ rateMatch: 'fallback'
+ });
+ });
+
+ it('folds legacy monthly buckets into the requested range', () => {
+ const report = buildUsageReport({}, {
+ from: '2024-05-01',
+ to: '2024-07-31',
+ monthlyActivity: {
+ '2024-01': { sessions: 1, messages: 1, tokens: 10 },
+ '2024-06': { sessions: 2, messages: 3, tokens: 500 }
+ }
+ });
+ expect(report.providers).toEqual([
+ expect.objectContaining({
+ id: 'legacy',
+ sessions: 2,
+ messages: 3,
+ tokensOut: 500
+ })
+ ]);
});
it('prices provider-level tokens missing a model split at the provider default', () => {