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: reconcile historical usage transcripts (#3156)
[._.]/ Adam Eivyd2008ebf00f8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 079816d15c..829e7a678e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Usage cost reporting+- **[issue-3156] Historical usage estimates can now be reconciled against provider transcripts.** The Usage page offers an explicit, progress-reporting repair that matches transcripts only to PortOS run windows, preserves configured provider IDs, replaces each old estimate once, and rebuilds corrected totals without inventing legacy cost.- **[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, so a figure that still rests on guesswork says so. Runs on local models stay correctly free. Measurement applies to runs from here on; activity already recorded keeps its original estimate.diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex e34c33f9ef..2359370a7e 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -1,11 +1,12 @@import { useState, useEffect } from 'react';import { useSearchParams } from 'react-router-dom';-import { RefreshCw, Clock, AlertTriangle } from 'lucide-react';+import { RefreshCw, Clock, AlertTriangle, DatabaseZap } 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 { formatCompactCount } from '../utils/formatters';+import { useAsyncAction } from '../hooks/useAsyncAction';const PERIOD_OPTIONS = [{ id: '7d', label: '7 days' },@@ -347,6 +348,7 @@ function InternalUsageMetrics() {const [usage, setUsage] = useState(null);const [loading, setLoading] = useState(true);+ const [backfill, setBackfill] = useState(null);useEffect(() => {let cancelled = false;@@ -365,6 +367,45 @@ function InternalUsageMetrics() {return () => { cancelled = true; };}, [period, from, to, isCustom]);+ useEffect(() => {+ let cancelled = false;+ api.getUsageBackfillStatus({ silent: true })+ .then((status) => { if (!cancelled) setBackfill(status); })+ .catch(() => {});+ return () => { cancelled = true; };+ }, []);++ const [startBackfill, startingBackfill] = useAsyncAction(async () => {+ const status = await api.startUsageBackfill({ silent: true });+ setBackfill(status);+ }, { errorMessage: 'Failed to start historical usage reconciliation' });++ useEffect(() => {+ if (backfill?.status !== 'running') return undefined;+ let cancelled = false;+ let timer = null;+ const poll = () => {+ api.getUsageBackfillStatus({ silent: true })+ .then(async (status) => {+ if (cancelled) return;+ setBackfill(status);+ if (status?.status === 'complete') {+ const params = isCustom ? { from, to } : { period };+ const refreshed = await api.getUsage(params);+ if (!cancelled) setUsage(refreshed);+ } else if (status?.status === 'running') {+ timer = setTimeout(poll, 1000);+ }+ })+ .catch(() => {});+ };+ timer = setTimeout(poll, 1000);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [backfill?.status, isCustom, from, to, period]);+const setPeriod = (id) => {setSearchParams((prev) => {@@ -410,6 +451,40 @@ function InternalUsageMetrics() {<div className="space-y-6"><h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">+ <div>+ <div className="flex items-center gap-2 text-sm font-medium text-white">+ <DatabaseZap size={16} className="text-port-accent" />+ Reconcile historical usage+ </div>+ <p className="text-xs text-gray-500 mt-1">+ Re-read PortOS run transcripts to replace older token estimates. This changes recorded history but makes no provider calls.+ </p>+ {backfill?.status === 'running' && (+ <p className="text-xs text-port-accent mt-1" role="status">+ Processing {backfill.processed || 0} of {backfill.total || 0} runs…+ </p>+ )}+ {backfill?.status === 'complete' && (+ <p className="text-xs text-port-success mt-1" role="status">+ Corrected {backfill.corrected || 0} run{backfill.corrected === 1 ? '' : 's'}.+ </p>+ )}+ {backfill?.status === 'error' && (+ <p className="text-xs text-port-error mt-1" role="alert">{backfill.error}</p>+ )}+ </div>+ <button+ type="button"+ onClick={startBackfill}+ disabled={startingBackfill || backfill?.status === 'running'}+ className="shrink-0 inline-flex items-center justify-center gap-2 rounded-lg border border-port-border px-3 py-2 text-sm text-white hover:border-port-accent disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {(startingBackfill || backfill?.status === 'running') ? <BrailleSpinner /> : <DatabaseZap size={15} />}+ {backfill?.status === 'running' ? 'Reconciling…' : 'Reconcile now'}+ </button>+ </div>+{/* Summary Stats (all-time) */}<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">diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsxnew file mode 100644index 0000000000..b0425b9daf--- /dev/null+++ b/client/src/pages/UsagePage.test.jsx@@ -0,0 +1,50 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++const api = vi.hoisted(() => ({+ getProviderUsage: vi.fn(),+ getUsage: vi.fn(),+ getUsageBackfillStatus: vi.fn(),+ startUsageBackfill: vi.fn()+}));++vi.mock('../services/api', () => api);++const UsagePage = (await import('./UsagePage')).default;++const usage = {+ totalSessions: 1,+ totalMessages: 1,+ totalTokens: { input: 10, output: 5 },+ last7Days: [],+ hourlyActivity: Array(24).fill(0),+ topProviders: [],+ topModels: [],+ report: {+ pricingAsOf: '2026-07-01',+ providers: [],+ totals: { estimatedCost: 0, source: 'estimate' }+ }+};++beforeEach(() => {+ vi.clearAllMocks();+ api.getProviderUsage.mockResolvedValue({ providers: [] });+ api.getUsage.mockResolvedValue(usage);+ api.getUsageBackfillStatus.mockResolvedValue({ status: 'idle' });+ api.startUsageBackfill.mockResolvedValue({ status: 'complete', corrected: 2 });+});++describe('UsagePage historical reconciliation', () => {+ it('starts only from the explicit user action and reports completion', async () => {+ render(<MemoryRouter><UsagePage /></MemoryRouter>);++ const button = await screen.findByRole('button', { name: 'Reconcile now' });+ expect(api.startUsageBackfill).not.toHaveBeenCalled();++ fireEvent.click(button);+ await waitFor(() => expect(api.startUsageBackfill).toHaveBeenCalledWith({ silent: true }));+ expect(await screen.findByText('Corrected 2 runs.')).toBeInTheDocument();+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 0fa2056607..181d6009f3 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, plus the usage cost report (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`). |+| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`). || `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 c260557193..2577ff45f8 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -114,6 +114,8 @@ export const getUsage = (params = {}) => {};export const getUsageRaw = () => request('/usage/raw');export const resetUsage = () => request('/usage', { method: 'DELETE' });+export const getUsageBackfillStatus = (options = {}) => request('/usage/backfill', options);+export const startUsageBackfill = (options = {}) => request('/usage/backfill', { method: 'POST', ...options });// Subscription-quota status for every enabled provider family (claude, codex,diff --git a/server/routes/usage.js b/server/routes/usage.jsindex 29a58de176..ec8474aa46 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -6,6 +6,10 @@ import { getAllProviders } from '../services/providers.js';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest, usageQuerySchema, usageMessagesSchema } from '../lib/validation.js';import { resolveUsageRange } from '../lib/usageRange.js';+import {+ getHistoricalUsageBackfillStatus,+ startHistoricalUsageBackfill+} from '../services/usageBackfill.js';const router = Router();@@ -44,6 +48,16 @@ router.get('/raw', asyncHandler(async (req, res) => {res.json(data);}));+// Historical transcript correction is deliberately user-triggered. Starting it+// returns immediately; the worker-thread job reports progress through GET.+router.get('/backfill', asyncHandler(async (req, res) => {+ res.json(getHistoricalUsageBackfillStatus());+}));++router.post('/backfill', asyncHandler(async (req, res) => {+ res.status(202).json(startHistoricalUsageBackfill());+}));+// POST /api/usage/session - Record a sessionrouter.post('/session', asyncHandler(async (req, res) => {const { providerId, providerName, model } = req.body;diff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex 244a4b70fe..e82799b9f4 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -26,10 +26,15 @@ vi.mock('../services/claudeCodeUsage.js', () => ({getClaudeCodeUsage: vi.fn()}));+vi.mock('../services/usageBackfill.js', () => ({+ getHistoricalUsageBackfillStatus: vi.fn(),+ startHistoricalUsageBackfill: vi.fn()+}));import * as usage from '../services/usage.js';import { getAllProviders } from '../services/providers.js';import { getProviderQuotas } from '../services/providerUsage.js';+import { getHistoricalUsageBackfillStatus, startHistoricalUsageBackfill } from '../services/usageBackfill.js';import usageRoutes from './usage.js';const buildApp = () => {@@ -123,6 +128,20 @@ describe('usage routes', () => {expect(res.body.sessions[0].providerId).toBe('p1');});+ it('starts historical reconciliation only from the explicit POST and reports progress', async () => {+ getHistoricalUsageBackfillStatus.mockReturnValue({ status: 'running', processed: 2, total: 5 });+ startHistoricalUsageBackfill.mockReturnValue({ status: 'running', processed: 0, total: 0 });++ const status = await request(buildApp()).get('/api/usage/backfill');+ expect(status.status).toBe(200);+ expect(status.body).toMatchObject({ status: 'running', processed: 2, total: 5 });+ expect(startHistoricalUsageBackfill).not.toHaveBeenCalled();++ const started = await request(buildApp()).post('/api/usage/backfill');+ expect(started.status).toBe(202);+ expect(startHistoricalUsageBackfill).toHaveBeenCalledTimes(1);+ });+it('POST /api/usage/session records a session and returns its number', async () => {usage.recordSession.mockResolvedValue(42);const res = await request(buildApp())@@ -172,4 +191,3 @@ describe('usage routes', () => {expect(usage.resetUsage).toHaveBeenCalled();});});-diff --git a/server/services/usage.js b/server/services/usage.jsindex 61d283a34d..d454470e89 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -217,6 +217,164 @@ function modelDayBucket(providerDay, model) {return providerDay.byModel[model];}+const countFields = ['messages', 'tokensIn', 'tokensOut', 'cacheReadTokens', 'cacheWriteTokens'];++const recordTotals = (records) => (Array.isArray(records) ? records : [records]).reduce((total, record) => {+ for (const field of countFields) total[field] += Math.max(0, record?.[field] || 0);+ return total;+}, { messages: 0, tokensIn: 0, tokensOut: 0, cacheReadTokens: 0, cacheWriteTokens: 0 });++const adjustCounts = (bucket, counts, direction) => {+ if (!bucket) return;+ for (const field of countFields) {+ const next = (bucket[field] || 0) + direction * Math.max(0, counts?.[field] || 0);+ bucket[field] = Math.max(0, next);+ }+};++const hasUsageCounts = (bucket) => countFields.some((field) => (bucket?.[field] || 0) > 0);+const BACKFILL_YIELD_INTERVAL = 25;+const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));++const rebuildDayTotals = (day) => {+ const providers = Object.values(day.byProvider || {});+ day.sessions = providers.reduce((sum, provider) => sum + (provider.sessions || 0), 0);+ day.messages = providers.reduce((sum, provider) => sum + (provider.messages || 0), 0);+ day.tokensIn = providers.reduce((sum, provider) => sum + (provider.tokensIn || 0), 0);+ day.tokensOut = providers.reduce((sum, provider) => sum + (provider.tokensOut || 0), 0);+ day.tokens = day.tokensOut;+};++/**+ * Run ids whose completion accounting has already landed. Kept with usage.json+ * so a historical pass remains idempotent even when a run's metadata marker+ * could not be written.+ */+export function getReconciledUsageRunIds() {+ return Object.keys(usageData?.reconciledRuns || {});+}++export async function markUsageRunReconciled(runId) {+ if (!runId) return;+ if (!usageData) await loadUsage();+ usageData.reconciledRuns ??= {};+ if (usageData.reconciledRuns[runId]) return;+ usageData.reconciledRuns[runId] = new Date().toISOString();+ await saveUsage();+}++/**+ * Replace historical per-run estimates with transcript measurements.+ *+ * The original estimate is subtracted from the exact configured provider/model+ * bucket that received it, then the measured records are added. Flat day totals+ * are rebuilt from the provider split so report residual reconciliation cannot+ * resurrect the removed estimate as a synthetic legacy row.+ */+export async function applyHistoricalUsageCorrections(corrections = []) {+ if (!usageData) await loadUsage();+ usageData.reconciledRuns ??= {};+ let corrected = 0;+ const correctedRunIds = [];+ const eligible = corrections.filter((correction) => {+ const { runId, day: dayKey, providerId } = correction || {};+ return runId && !usageData.reconciledRuns[runId] && dayKey && providerId+ && usageData.dailyActivity?.[dayKey]?.byProvider?.[providerId];+ });+ const providerScopes = new Map();+ const modelScopes = new Map();+ for (const [index, correction] of eligible.entries()) {+ if (index > 0 && index % BACKFILL_YIELD_INTERVAL === 0) await yieldToEventLoop();+ const providerKey = `${correction.day}\u0000${correction.providerId}`;+ const providerDay = usageData.dailyActivity[correction.day].byProvider[correction.providerId];+ if (!providerScopes.has(providerKey)) {+ providerScopes.set(providerKey, { bucket: providerDay, original: recordTotals([providerDay]), removed: recordTotals([]) });+ }+ adjustCounts(providerScopes.get(providerKey).removed, correction.estimate, 1);+ if (correction.model && providerDay.byModel?.[correction.model]) {+ const modelKey = `${providerKey}\u0000${correction.model}`;+ const modelDay = providerDay.byModel[correction.model];+ if (!modelScopes.has(modelKey)) {+ modelScopes.set(modelKey, { bucket: modelDay, original: recordTotals([modelDay]), removed: recordTotals([]) });+ }+ adjustCounts(modelScopes.get(modelKey).removed, correction.estimate, 1);+ }+ }++ for (const [index, correction] of eligible.entries()) {+ if (index > 0 && index % BACKFILL_YIELD_INTERVAL === 0) await yieldToEventLoop();+ const { runId, day: dayKey, providerId, model, estimate, measured } = correction || {};+ const day = usageData.dailyActivity?.[dayKey];+ const providerDay = day?.byProvider?.[providerId];++ const measuredRecords = Array.isArray(measured) ? measured : [measured];+ const measuredTotals = recordTotals(measuredRecords);+ const oldModelDay = model ? providerDay.byModel?.[model] : null;++ adjustCounts(providerDay, estimate, -1);+ if (oldModelDay) {+ adjustCounts(oldModelDay, estimate, -1);+ }++ for (const record of measuredRecords) {+ adjustCounts(providerDay, record, 1);+ if (record?.model) {+ const target = modelDayBucket(providerDay, record.model);+ const hadCounts = hasUsageCounts(target);+ adjustCounts(target, record, 1);+ target.source = hadCounts ? mergeSource(target.source, 'measured') : 'measured';+ }+ }++ const delta = {+ messages: measuredTotals.messages - (estimate?.messages || 0),+ tokensIn: measuredTotals.tokensIn + measuredTotals.cacheReadTokens + measuredTotals.cacheWriteTokens+ - (estimate?.tokensIn || 0),+ tokensOut: measuredTotals.tokensOut - (estimate?.tokensOut || 0)+ };+ usageData.totalMessages = Math.max(0, (usageData.totalMessages || 0) + delta.messages);+ usageData.totalTokens.input = Math.max(0, (usageData.totalTokens.input || 0) + delta.tokensIn);+ usageData.totalTokens.output = Math.max(0, (usageData.totalTokens.output || 0) + delta.tokensOut);++ const allProvider = usageData.byProvider?.[providerId];+ if (allProvider) {+ allProvider.messages = Math.max(0, (allProvider.messages || 0) + delta.messages);+ allProvider.tokens = Math.max(0, (allProvider.tokens || 0) + delta.tokensOut);+ }+ if (model && usageData.byModel?.[model]) {+ usageData.byModel[model].messages = Math.max(0, (usageData.byModel[model].messages || 0) - (estimate?.messages || 0));+ usageData.byModel[model].tokens = Math.max(0, (usageData.byModel[model].tokens || 0) - (estimate?.tokensOut || 0));+ }+ for (const record of measuredRecords) {+ if (!record?.model) continue;+ usageData.byModel[record.model] ??= { sessions: 0, messages: 0, tokens: 0 };+ usageData.byModel[record.model].messages += record.messages || 0;+ usageData.byModel[record.model].tokens += record.tokensOut || 0;+ }++ rebuildDayTotals(day);+ usageData.reconciledRuns[runId] = new Date().toISOString();+ corrected++;+ correctedRunIds.push(runId);+ }++ const hasResidual = ({ original, removed }) => countFields+ .some((field) => (original[field] || 0) > (removed[field] || 0));+ for (const scope of providerScopes.values()) {+ scope.bucket.source = hasUsageCounts(scope.bucket)+ ? (hasResidual(scope) ? 'mixed' : 'measured')+ : null;+ }+ for (const scope of modelScopes.values()) {+ scope.bucket.source = hasUsageCounts(scope.bucket)+ ? (hasResidual(scope) ? 'mixed' : 'measured')+ : null;+ }++ if (corrected > 0) await saveUsage();+ return { corrected, correctedRunIds };+}+/*** 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 countsdiff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 36c79a5511..22db129d86 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -20,7 +20,18 @@ tryReadFile: vi.fn().mockResolvedValue(null),}));import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';-import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, recordTokens, recordRunUsage, buildUsageReport, rollupOldDailyActivity } from './usage.js';+import {+ applyHistoricalUsageCorrections,+ buildUsageReport,+ getUsage,+ getUsageSummary,+ loadUsage,+ recordMessages,+ recordRunUsage,+ recordSession,+ recordTokens,+ rollupOldDailyActivity+} from './usage.js';// Helper: produce a date string N days ago (relative to today)function daysAgo(n) {@@ -1038,6 +1049,100 @@ describe('buildUsageReport — cache pricing and source reporting', () => {});});+describe('usage.js — historical transcript corrections (#3156)', () => {+ const dayKey = '2026-07-01';+ const providerId = 'claude-code-tui';+ const model = 'claude-opus-5';++ beforeEach(async () => {+ vi.clearAllMocks();+ readJSONFile.mockResolvedValueOnce(makeUsage({+ [dayKey]: {+ sessions: 1,+ messages: 1,+ tokens: 50,+ byProvider: {+ [providerId]: {+ name: 'Claude Code TUI',+ sessions: 1,+ messages: 1,+ tokensIn: 20,+ tokensOut: 50,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'estimate',+ byModel: {+ [model]: {+ sessions: 1,+ messages: 1,+ tokensIn: 20,+ tokensOut: 50,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ source: 'estimate'+ }+ }+ }+ }+ }+ }, {+ totalSessions: 1,+ totalMessages: 1,+ totalTokens: { input: 20, output: 50 },+ byProvider: { [providerId]: { name: 'Claude Code TUI', sessions: 1, messages: 1, tokens: 50 } },+ byModel: { [model]: { sessions: 1, messages: 1, tokens: 50 } }+ }));+ await loadUsage();+ });++ it('replaces the configured-provider estimate, rebuilds flat totals, and is idempotent', async () => {+ const correction = {+ runId: 'run-example-1',+ day: dayKey,+ providerId,+ model,+ estimate: { messages: 1, tokensIn: 20, tokensOut: 50 },+ measured: [{+ providerId,+ model,+ messages: 2,+ tokensIn: 100,+ tokensOut: 200,+ cacheReadTokens: 1000,+ cacheWriteTokens: 10,+ source: 'measured'+ }]+ };++ expect(await applyHistoricalUsageCorrections([correction])).toMatchObject({ corrected: 1 });+ const afterFirst = structuredClone(getUsage());+ expect(await applyHistoricalUsageCorrections([correction])).toMatchObject({ corrected: 0 });+ expect(getUsage()).toEqual(afterFirst);++ const day = getUsage().dailyActivity[dayKey];+ expect(day).toMatchObject({ sessions: 1, messages: 2, tokens: 200, tokensIn: 100, tokensOut: 200 });+ expect(day.byProvider[providerId]).toMatchObject({+ messages: 2,+ tokensIn: 100,+ tokensOut: 200,+ cacheReadTokens: 1000,+ cacheWriteTokens: 10,+ source: 'measured'+ });+ expect(day.byProvider['claude-code']).toBeUndefined();++ const report = buildUsageReport(getUsage().dailyActivity, {+ providers: [{ id: providerId, name: 'Claude Code TUI' }],+ totalTokens: getUsage().totalTokens+ });+ expect(report.providers.find((provider) => provider.id === providerId)?.models[0]).toMatchObject({+ tokensIn: 100,+ tokensOut: 200+ });+ expect(report.providers.some((provider) => provider.id === 'legacy')).toBe(false);+ });+});+describe('buildUsageReport — local models under a paid provider', () => {diff --git a/server/services/usageBackfill.js b/server/services/usageBackfill.jsnew file mode 100644index 0000000000..26a504255a--- /dev/null+++ b/server/services/usageBackfill.js@@ -0,0 +1,114 @@+import { Worker } from 'worker_threads';+import { homedir } from 'os';+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';+import {+ applyHistoricalUsageCorrections,+ getReconciledUsageRunIds+} from './usage.js';++let job = {+ status: 'idle',+ processed: 0,+ total: 0,+ found: 0,+ corrected: 0,+ error: null,+ startedAt: null,+ completedAt: null+};++const publicJob = () => ({ ...job });++const markRunMetadata = async (corrections) => {+ for (const correction of corrections) {+ const metadata = await readJSONFile(correction.metadataPath, null);+ if (!metadata) continue;+ metadata.usageReconciled = true;+ metadata.usageReconciledAt = new Date().toISOString();+ await atomicWrite(correction.metadataPath, metadata);+ }+};++export function getHistoricalUsageBackfillStatus() {+ return publicJob();+}++/**+ * Start the one-shot historical repair. The explicit POST route is the only+ * caller; no boot hook or schedule invokes this function.+ */+export function startHistoricalUsageBackfill({+ runsDir = PATHS.runs,+ home = homedir(),+ WorkerClass = Worker+} = {}) {+ if (job.status === 'running') return publicJob();++ job = {+ status: 'running',+ processed: 0,+ total: 0,+ found: 0,+ corrected: 0,+ error: null,+ startedAt: new Date().toISOString(),+ completedAt: null+ };++ const worker = new WorkerClass(new URL('./usageBackfillWorker.js', import.meta.url), {+ workerData: {+ runsDir,+ home,+ reconciledRunIds: getReconciledUsageRunIds()+ }+ });++ let messageTail = Promise.resolve();+ worker.on('message', (message) => {+ messageTail = messageTail.then(async () => {+ if (message?.type === 'progress') {+ job = { ...job, ...message.progress };+ return;+ }+ if (message?.type === 'error') {+ job = { ...job, status: 'error', error: message.error || 'Backfill failed', completedAt: new Date().toISOString() };+ return;+ }+ if (message?.type !== 'complete') return;+ const result = message.result || {};+ const applied = await applyHistoricalUsageCorrections(result.corrections || []);+ const appliedCorrections = (result.corrections || [])+ .filter((correction) => applied.correctedRunIds.includes(correction.runId));+ await markRunMetadata(appliedCorrections);+ job = {+ ...job,+ status: 'complete',+ processed: result.processed || 0,+ total: result.total || 0,+ found: result.corrections?.length || 0,+ corrected: applied.corrected,+ completedAt: new Date().toISOString()+ };+ }).catch((error) => {+ job = { ...job, status: 'error', error: error.message, completedAt: new Date().toISOString() };+ });+ });+ worker.on('error', (error) => {+ job = { ...job, status: 'error', error: error.message, completedAt: new Date().toISOString() };+ });+ worker.unref();+ return publicJob();+}++export function __resetHistoricalUsageBackfillForTests() {+ job = {+ status: 'idle',+ processed: 0,+ total: 0,+ found: 0,+ corrected: 0,+ error: null,+ startedAt: null,+ completedAt: null+ };+}diff --git a/server/services/usageBackfill.test.js b/server/services/usageBackfill.test.jsnew file mode 100644index 0000000000..63fd6d2f14--- /dev/null+++ b/server/services/usageBackfill.test.js@@ -0,0 +1,81 @@+import { EventEmitter } from 'events';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../lib/fileUtils.js', () => ({+ atomicWrite: vi.fn(),+ PATHS: { runs: '/example/runs' },+ readJSONFile: vi.fn().mockResolvedValue(null)+}));++vi.mock('./usage.js', () => ({+ applyHistoricalUsageCorrections: vi.fn().mockResolvedValue({+ corrected: 1,+ correctedRunIds: ['run-example-1']+ }),+ getReconciledUsageRunIds: vi.fn().mockReturnValue(['run-live'])+}));++const {+ __resetHistoricalUsageBackfillForTests,+ getHistoricalUsageBackfillStatus,+ startHistoricalUsageBackfill+} = await import('./usageBackfill.js');++class FakeWorker extends EventEmitter {+ static instances = [];++ constructor(url, options) {+ super();+ this.url = url;+ this.options = options;+ FakeWorker.instances.push(this);+ }++ unref() {}+}++beforeEach(() => {+ FakeWorker.instances = [];+ __resetHistoricalUsageBackfillForTests();+});++describe('historical usage backfill job', () => {+ it('runs scanning off-thread and exposes progress through status', async () => {+ const started = startHistoricalUsageBackfill({+ runsDir: '/example/runs',+ home: '/example/home',+ WorkerClass: FakeWorker+ });+ expect(started.status).toBe('running');+ expect(FakeWorker.instances).toHaveLength(1);+ const worker = FakeWorker.instances[0];+ expect(worker.options.workerData).toMatchObject({+ runsDir: '/example/runs',+ home: '/example/home',+ reconciledRunIds: ['run-live']+ });++ worker.emit('message', { type: 'progress', progress: { processed: 2, total: 5, found: 1 } });+ await vi.waitFor(() => expect(getHistoricalUsageBackfillStatus()).toMatchObject({+ status: 'running',+ processed: 2,+ total: 5,+ found: 1+ }));++ worker.emit('message', {+ type: 'complete',+ result: {+ processed: 5,+ total: 5,+ corrections: [{ runId: 'run-example-1', metadataPath: '/example/metadata.json' }]+ }+ });+ await vi.waitFor(() => expect(getHistoricalUsageBackfillStatus()).toMatchObject({+ status: 'complete',+ corrected: 1,+ processed: 5,+ total: 5+ }));+ });+});diff --git a/server/services/usageBackfillWorker.js b/server/services/usageBackfillWorker.jsnew file mode 100644index 0000000000..b17dd43b25--- /dev/null+++ b/server/services/usageBackfillWorker.js@@ -0,0 +1,79 @@+import { isMainThread, parentPort, workerData } from 'worker_threads';+import { join } from 'path';+import { readdir } from 'fs/promises';+import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';+import { readJSONFile, tryReadFile } from '../lib/fileUtils.js';+import { reconcileRunUsage, transcriptFamily } from './usageReconciler.js';++const listRunIds = async (runsDir) => readdir(runsDir, { withFileTypes: true })+ .then((entries) => entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name))+ .catch(() => []);++const isMeasured = (record) => (Array.isArray(record) ? record : [record])+ .some((entry) => entry?.source === 'measured');++/**+ * Read historical run artifacts and produce estimate→measurement corrections.+ * This function runs inside a worker in production so parsing large JSONL files+ * never blocks the server event loop; it is exported for fixture-based tests.+ */+export async function scanHistoricalUsage({+ runsDir,+ home,+ reconciledRunIds = [],+ onProgress = () => {}+}) {+ const reconciled = new Set(reconciledRunIds);+ const candidates = [];++ for (const runId of await listRunIds(runsDir)) {+ if (reconciled.has(runId)) continue;+ const metadataPath = join(runsDir, runId, 'metadata.json');+ const metadata = await readJSONFile(metadataPath, null);+ if (!metadata || metadata.usageReconciled || !metadata.providerId || !metadata.workspacePath+ || typeof metadata.startTime !== 'string' || typeof metadata.endTime !== 'string'+ || !Number.isFinite(Date.parse(metadata.startTime)) || !Number.isFinite(Date.parse(metadata.endTime))+ || !transcriptFamily(metadata)) continue;+ candidates.push({ runId, metadataPath, metadata });+ }+ candidates.sort((a, b) => Date.parse(a.metadata.startTime) - Date.parse(b.metadata.startTime));++ const corrections = [];+ let processed = 0;+ onProgress({ processed, total: candidates.length, found: corrections.length });+ for (const candidate of candidates) {+ const output = await tryReadFile(join(runsDir, candidate.runId, 'output.txt'));+ const estimate = {+ messages: 1,+ tokensIn: estimateTokensFromChars(candidate.metadata.promptLength),+ tokensOut: estimateTokens(output || ''),+ cacheReadTokens: 0,+ cacheWriteTokens: 0+ };+ const measured = await reconcileRunUsage(candidate.metadata, estimate, { home });+ if (isMeasured(measured)) {+ corrections.push({+ runId: candidate.runId,+ metadataPath: candidate.metadataPath,+ day: candidate.metadata.endTime.slice(0, 10),+ providerId: candidate.metadata.providerId,+ model: candidate.metadata.model ?? null,+ estimate,+ measured+ });+ }+ processed++;+ onProgress({ processed, total: candidates.length, found: corrections.length });+ }++ return { corrections, processed, total: candidates.length };+}++if (!isMainThread) {+ scanHistoricalUsage({+ ...workerData,+ onProgress: (progress) => parentPort.postMessage({ type: 'progress', progress })+ })+ .then((result) => parentPort.postMessage({ type: 'complete', result }))+ .catch((error) => parentPort.postMessage({ type: 'error', error: error.message }));+}diff --git a/server/services/usageBackfillWorker.test.js b/server/services/usageBackfillWorker.test.jsnew file mode 100644index 0000000000..9a4b901ddc--- /dev/null+++ b/server/services/usageBackfillWorker.test.js@@ -0,0 +1,99 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import { __resetUsageClaims } from './usageReconciler.js';+import { scanHistoricalUsage } from './usageBackfillWorker.js';++let root;+let home;+const workspace = '/work/example-repo';++const writeRun = async (id, metadata, output = 'estimated output') => {+ const dir = join(root, id);+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'metadata.json'), JSON.stringify({ id, ...metadata }));+ await writeFile(join(dir, 'output.txt'), output);+};++const writeTranscript = async () => {+ const dir = join(home, '.claude', 'projects', '-work-example-repo');+ await mkdir(dir, { recursive: true });+ const line = {+ type: 'assistant',+ uuid: 'uuid-message-1',+ sessionId: 'session-example',+ cwd: workspace,+ timestamp: '2026-07-01T10:05:00.000Z',+ message: {+ id: 'message-1',+ model: 'claude-opus-5',+ usage: {+ input_tokens: 100,+ cache_creation_input_tokens: 10,+ cache_read_input_tokens: 1000,+ output_tokens: 200+ }+ }+ };+ await writeFile(join(dir, 'session-example.jsonl'), JSON.stringify(line));+};++beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'portos-runs-example-'));+ home = await mkdtemp(join(tmpdir(), 'portos-home-example-'));+ __resetUsageClaims();+ await writeTranscript();+});++afterEach(async () => {+ await rm(root, { recursive: true, force: true });+ await rm(home, { recursive: true, force: true });+});++describe('historical usage worker', () => {+ it('correlates by run metadata and keeps the configured provider id', async () => {+ await writeRun('run-example-1', {+ providerId: 'claude-code-tui',+ model: 'claude-opus-5',+ workspacePath: workspace,+ promptLength: 80,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ });+ await writeRun('run-outside-window', {+ providerId: 'claude-code-tui',+ model: 'claude-opus-5',+ workspacePath: workspace,+ startTime: '2026-07-02T10:00:00.000Z',+ endTime: '2026-07-02T10:10:00.000Z'+ });++ const result = await scanHistoricalUsage({ runsDir: root, home });+ expect(result.corrections).toHaveLength(1);+ expect(result.corrections[0]).toMatchObject({+ runId: 'run-example-1',+ providerId: 'claude-code-tui',+ day: '2026-07-01'+ });+ expect(result.corrections[0].measured[0]).toMatchObject({+ providerId: 'claude-code-tui',+ tokensOut: 200,+ cacheReadTokens: 1000+ });+ });++ it('skips a run already recorded by the live completion path', async () => {+ await writeRun('run-live-recorded', {+ providerId: 'claude-code-tui',+ workspacePath: workspace,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z',+ usageReconciled: true+ });++ const result = await scanHistoricalUsage({ runsDir: root, home });+ expect(result.total).toBe(0);+ expect(result.corrections).toEqual([]);+ });+});diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.jsindex a648f8af98..c2d95932a4 100644--- a/server/services/usageReconciler.js+++ b/server/services/usageReconciler.js@@ -28,7 +28,7 @@import { homedir } from 'os';import { join } from 'path';import { readdir } from 'fs/promises';-import { tryReadFile } from '../lib/fileUtils.js';+import { atomicWrite, PATHS, readJSONFile, tryReadFile } from '../lib/fileUtils.js';import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';import { isFreeModelId, resolveModelRates } from '../lib/modelPricing.js';import {@@ -38,7 +38,7 @@ import {parseCodexRollout,totalTranscriptTokens} from '../lib/providerTranscriptUsage.js';-import { recordRunUsage } from './usage.js';+import { markUsageRunReconciled, 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@@ -489,6 +489,16 @@ export async function recordCompletedRunUsage(metadata, output, { home = homedir// persisting the record — usage accounting must not surface as a run failure.await reconcileRunUsage(metadata, estimate, { home }).then(recordRunUsage)+ .then(async () => {+ if (!metadata?.id) return;+ await markUsageRunReconciled(metadata.id);+ const metadataPath = join(PATHS.runs, metadata.id, 'metadata.json');+ const persisted = await readJSONFile(metadataPath, null);+ if (!persisted) return;+ persisted.usageReconciled = true;+ persisted.usageReconciledAt = new Date().toISOString();+ await atomicWrite(metadataPath, persisted);+ }).catch((err) => {console.error(`❌ Failed to record usage: ${err.message}`);});diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.jsindex f9076f8778..4fb6b3ba81 100644--- a/server/services/usageReconciler.test.js+++ b/server/services/usageReconciler.test.js@@ -4,10 +4,11 @@ import { tmpdir } from 'os';import { join } from 'path';vi.mock('./usage.js', () => ({+ markUsageRunReconciled: vi.fn().mockResolvedValue(undefined),recordRunUsage: vi.fn().mockResolvedValue(undefined)}));-const { recordRunUsage } = await import('./usage.js');+const { markUsageRunReconciled, recordRunUsage } = await import('./usage.js');const {transcriptFamily,readMeasuredUsage,@@ -345,6 +346,20 @@ describe('recordCompletedRunUsage', () => {]);});+ it('durably marks a completed run so a later backfill skips it', async () => {+ await recordCompletedRunUsage({+ id: 'run-example-live',+ providerId: 'ollama',+ model: 'llama3',+ workspacePath: WORKSPACE,+ promptLength: 40,+ startTime: '2026-07-01T10:00:00.000Z',+ endTime: '2026-07-01T10:10:00.000Z'+ }, 'captured output');++ expect(markUsageRunReconciled).toHaveBeenCalledWith('run-example-live');+ });+it('records the estimate when no transcript exists rather than recording nothing', async () => {await recordCompletedRunUsage({providerId: 'ollama',