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
feat(usage): report Claude Code tokens per model across federated peers
[._.]/ Adam Eivya32bedcb00dc
diff --git a/.env.example b/.env.exampleindex 42268b1343..1b7e41336e 100644--- a/.env.example+++ b/.env.example@@ -343,3 +343,7 @@ PGPASSWORD=portos# Set by AI Providers > Model host setup after successful dedicated setup.# Restores the authenticated queue; the container restart policy restores Qwen.# PORTOS_FLEET_LLM_ENABLED=0++# Claude Code config directory whose `projects/` transcripts feed the per-model+# token report on the Usage page (claudeCodeTranscriptUsage.js; default: ~/.claude)+# CLAUDE_CONFIG_DIR=/path/to/claude-configdiff --git a/client/src/components/usage/ClaudeCodeModelTokensCard.jsx b/client/src/components/usage/ClaudeCodeModelTokensCard.jsxnew file mode 100644index 0000000000..9f41d32414--- /dev/null+++ b/client/src/components/usage/ClaudeCodeModelTokensCard.jsx@@ -0,0 +1,116 @@+import { useEffect, useState } from 'react';+import * as api from '../../services/api';+import BrailleSpinner from '../BrailleSpinner';+import { formatCount, formatUsd, timeAgo } from '../../utils/formatters';++const COLUMNS = [+ { key: 'messages', label: 'Msgs' },+ { key: 'input', label: 'Input' },+ { key: 'output', label: 'Output' },+ { key: 'cacheRead', label: 'Cache read' },+ { key: 'cacheWrite', label: 'Cache write' },+ { key: 'total', label: 'Total' },+ { key: 'estimatedCost', label: 'Est. API cost', format: formatUsd }+];++const Cells = ({ row, bold = false }) => (+ <>+ {COLUMNS.map((c) => (+ <td key={c.key} className={`py-1.5 px-2 text-right tabular-nums ${bold && c.format ? 'text-port-success' : ''}`}>+ {(c.format || formatCount)(row[c.key])}+ </td>+ ))}+ </>+);++function ModelTable({ models, totals }) {+ return (+ <div className="overflow-x-auto">+ <table className="w-full text-xs sm:text-sm">+ <thead>+ <tr className="text-left text-gray-500 border-b border-port-border">+ <th className="py-1.5 pr-2 font-medium">Model</th>+ {COLUMNS.map((c) => <th key={c.key} className="py-1.5 px-2 font-medium text-right whitespace-nowrap">{c.label}</th>)}+ </tr>+ </thead>+ <tbody>+ {models.map((row) => (+ <tr key={row.model} className="border-b border-port-border last:border-0 text-gray-300">+ <td className="py-1.5 pr-2 font-mono text-white whitespace-nowrap">{row.model}</td>+ <Cells row={row} />+ </tr>+ ))}+ <tr className="text-white font-medium">+ <td className="py-1.5 pr-2">Total</td>+ <Cells row={totals} bold />+ </tr>+ </tbody>+ </table>+ </div>+ );+}++/**+ * Claude Code tokens per model across the fleet, priced at API rates, for the+ * same window as the cost report above. Each machine reads its own local CLI+ * transcripts (so it counts sessions run outside PortOS) and federates the+ * per-day totals; peers show as of their last sync.+ */+export default function ClaudeCodeModelTokensCard({ period, from, to, isCustom }) {+ // undefined = still loading, null = the read failed+ const [report, setReport] = useState(undefined);+ const loading = report === undefined;++ useEffect(() => {+ let cancelled = false;+ setReport(undefined);+ api.getClaudeCodeModelUsage(isCustom ? { from, to } : { period }, { silent: true })+ .catch(() => null)+ .then((data) => { if (!cancelled) setReport(data); });+ return () => { cancelled = true; };+ }, [period, from, to, isCustom]);++ const instances = report?.instances || [];++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-sm font-medium text-gray-400">+ Claude Code tokens by model{instances.length > 1 ? ' — all instances' : ''}+ </h3>+ {loading && <BrailleSpinner />}+ </div>+ {report === null && <p className="text-xs text-port-error" role="alert">Could not read Claude Code usage.</p>}+ {report && report.models.length === 0 && (+ <p className="text-xs text-gray-500">No Claude Code usage found in this window.</p>+ )}+ {report && report.models.length > 0 && <ModelTable models={report.models} totals={report.totals} />}+ {instances.length > 1 && (+ <div className="space-y-2">+ <h4 className="text-xs font-medium text-gray-500">By instance</h4>+ {instances.map((i) => (+ <details key={i.instanceId} className="border border-port-border rounded-lg px-2 py-1">+ <summary className="cursor-pointer text-xs sm:text-sm text-white flex flex-wrap items-center justify-between gap-2">+ <span>+ {i.name}{i.self ? ' (this machine)' : ''}+ {!i.usesSubscriptions && <span className="text-port-warning"> · API-billed, not in total</span>}+ </span>+ <span className="text-gray-400 tabular-nums">+ {formatCount(i.totals.total)} tokens · {formatUsd(i.totals.estimatedCost)}+ {!i.self && <> · synced {timeAgo(new Date(i.capturedAt), 'unknown')}</>}+ </span>+ </summary>+ <div className="pt-2"><ModelTable models={i.models} totals={i.totals} /></div>+ </details>+ ))}+ </div>+ )}+ <p className="text-[10px] sm:text-xs text-gray-500">+ Read from each machine’s local Claude Code session transcripts, so it includes sessions run outside PortOS, and+ history is kept after the CLI prunes old transcripts. Cost is an informational API-rate equivalent from the shared+ pricing table (cache reads and writes at their own tiers; local models free). Instances on an older PortOS build+ contribute nothing until they update. claude.ai and unfederated devices are not included.+ </p>+ </div>+ );+}diff --git a/client/src/components/usage/ClaudeCodeModelTokensCard.test.jsx b/client/src/components/usage/ClaudeCodeModelTokensCard.test.jsxnew file mode 100644index 0000000000..dbbac70bd3--- /dev/null+++ b/client/src/components/usage/ClaudeCodeModelTokensCard.test.jsx@@ -0,0 +1,35 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';++vi.mock('../../services/api', () => ({ getClaudeCodeModelUsage: vi.fn() }));+import * as api from '../../services/api';+import ClaudeCodeModelTokensCard from './ClaudeCodeModelTokensCard';++const totals = { messages: 2, input: 1200, output: 34, cacheRead: 5, cacheWrite: 6, total: 1245, estimatedCost: 12.5 };+const row = { model: 'model-x', ...totals };++describe('ClaudeCodeModelTokensCard', () => {+ beforeEach(() => vi.clearAllMocks());++ it('renders fleet models with API-equivalent cost and a per-instance breakdown', async () => {+ api.getClaudeCodeModelUsage.mockResolvedValue({+ models: [row], totals,+ instances: [+ { instanceId: 'a', name: 'Box A', self: true, capturedAt: '2026-09-20T00:00:00Z', usesSubscriptions: true, models: [row], totals },+ { instanceId: 'b', name: 'Box B', self: false, capturedAt: '2026-09-20T00:00:00Z', usesSubscriptions: false, models: [row], totals }+ ]+ });+ render(<ClaudeCodeModelTokensCard period="30d" from="" to="" isCustom={false} />);+ expect(await screen.findByText(/all instances/)).toBeTruthy();+ expect(screen.getAllByText('model-x').length).toBeGreaterThan(0);+ expect(screen.getByText(/API-billed, not in total/)).toBeTruthy();+ expect(api.getClaudeCodeModelUsage).toHaveBeenCalledWith({ period: '30d' }, { silent: true });+ });++ it('sends the explicit range for a custom window and reports a failed read', async () => {+ api.getClaudeCodeModelUsage.mockRejectedValue(new Error('boom'));+ render(<ClaudeCodeModelTokensCard period="7d" from="2026-09-01" to="2026-09-15" isCustom />);+ expect(await screen.findByRole('alert')).toBeTruthy();+ expect(api.getClaudeCodeModelUsage).toHaveBeenCalledWith({ from: '2026-09-01', to: '2026-09-15' }, { silent: true });+ });+});diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 4b7b8af4a6..90ec04e413 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -10,6 +10,7 @@ import { useAsyncAction } from '../hooks/useAsyncAction';import { useSocketResource } from '../hooks/useSocketResource';import { useQuotaUpdates } from '../hooks/useQuotaUpdates';import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';+import ClaudeCodeModelTokensCard from '../components/usage/ClaudeCodeModelTokensCard';import FleetUsageCard from '../components/usage/FleetUsageCard';import FreeTierUsageCard from '../components/usage/FreeTierUsageCard';import ProviderQuotaBody from '../components/usage/ProviderQuotaBody';@@ -726,6 +727,9 @@ function InternalUsageMetrics() {observed limit blocks that stand in for a quota meter. */}<FreeTierUsageCard freeTier={usage.freeTier} />+ {/* Claude Code tokens per model (all instances) for the same window. */}+ <ClaudeCodeModelTokensCard period={period} from={from} to={to} isCustom={isCustom} />+{/* Same window, split by machine — renders only once a peer's usage hassynced, so a single-machine install sees no change. */}<FleetUsageCard fleet={usage.fleet} onSaved={fetchUsage} />diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsxindex 1cac68b7e4..54fc5f86f0 100644--- a/client/src/pages/UsagePage.test.jsx+++ b/client/src/pages/UsagePage.test.jsx@@ -9,6 +9,7 @@ import { act, fireEvent, render, screen, waitFor, within } from '@testing-librarimport { MemoryRouter } from 'react-router';const api = vi.hoisted(() => ({+ getClaudeCodeModelUsage: vi.fn(() => Promise.resolve({ filesScanned: 0, models: [], totals: {} })),getProviderUsage: vi.fn(),getUsage: vi.fn(),getUsageBackfillStatus: vi.fn(),diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 71f1c45517..217be4ef46 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -66,7 +66,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiSchedules.js` | Automation schedules. || `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. || `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. |-| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing (`getSystemActivity` for the bounded snapshot, `getGpuTelemetry` for visible-only GPU samples) and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. |+| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing (`getSystemActivity` for the bounded snapshot, `getGpuTelemetry` for visible-only GPU samples) and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getClaudeCodeModelUsage` (per-model token totals for all local Claude Code use, from CLI transcripts), `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. || `apiAuth.js` | Optional login password — status, login, set/clear password, list/revoke sessions, and read-only password-risk status. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 6a370dbf91..14d1bb03e4 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -233,12 +233,17 @@ export const patchSettingsSlice = async (slicePath, partial, options = {}) => {// Usage. `params` selects the cost-report window: { period } (7d|30d|90d|all)// or { from, to } (YYYY-MM-DD).-export const getUsage = (params = {}) => {+const usageQuery = (params) => {const qs = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null && v !== '')).toString();- return request(`/usage${qs ? `?${qs}` : ''}`);+ return qs ? `?${qs}` : '';};+export const getUsage = (params = {}) => request(`/usage${usageQuery(params)}`);+// Per-model token totals for every Claude Code session on this machine, read+// from the CLI transcripts. Same { period } | { from, to } params as getUsage.+export const getClaudeCodeModelUsage = (params = {}, options = {}) =>+ request(`/usage/claude-code/models${usageQuery(params)}`, options);export const getHourlyUsage = (options = {}) => request('/usage/hourly', options);export const getUsageBackfillStatus = (options = {}) => request('/usage/backfill', options);// Monthly plan prices per provider family, used to compare subscription spenddiff --git a/docs/decisions/2026-09-01-federated-usage-metrics.md b/docs/decisions/2026-09-01-federated-usage-metrics.mdindex f90afc7334..adc3c904d6 100644--- a/docs/decisions/2026-09-01-federated-usage-metrics.md+++ b/docs/decisions/2026-09-01-federated-usage-metrics.md@@ -223,3 +223,27 @@ Privacy is unchanged in kind — a quota card carries provider ids, percentages,reset times and the publishing instance's name; no prompts, no transcripts, noPII. The peer payload is rebuilt to the wire shape on arrival for the samerecursion-depth reason the usage digest is.++## Addendum: Claude Code transcript token history (per model, per day)++The `usage` category also carries an optional `claudeCode` field per instance: a+`{ updatedAt, days: { <YYYY-MM-DD>: { <model>: { messages, input, output,+cacheRead, cacheWrite } } } }` map derived from the Claude Code CLI's local+transcripts, so it covers sessions run outside PortOS. It exists so the Usage+page can total tokens per model across the fleet and price them at API rates+(`server/services/claudeCodeTranscriptUsage.js`, `getFleetClaudeCodeModels` in+`peerUsage.js`).++- **Additive and optional**, like `quotas`: an older peer drops the field and+ contributes nothing to that report; no schema-version bump.+- **Privacy:** model ids, UTC day buckets and token counts only — never prompts,+ project paths, session ids or transcript text. Peer-supplied maps are rebuilt to+ this fixed shape (day/model caps) before storage.+- **Persisted locally** in `data/claude-code-transcript-usage.json` (per-field max+ merge), so history survives the CLI pruning old transcripts. It is a derived+ local cache: it ships no `data.reference/` seed and needs no migration — it is+ rebuilt from the transcripts still on disk.+- **Freshness:** refreshed lazily when the report is read and by a 30-minute+ local file scan that starts after boot. No provider calls are made.+- `capturedAt` is the newest of usage / quotas / transcript `updatedAt`, so a+ transcript refresh alone still advances the slot peers pull.diff --git a/server/index.js b/server/index.jsindex 81aa34ea8b..e82e25b94c 100644--- a/server/index.js+++ b/server/index.js@@ -554,4 +554,8 @@ runBootSequence({ io, httpServer, localHttpServer, httpsEnabled, port: PORT, hosif (!isSmokeBoot()) {import('./services/fleetLlmHost.js').then(({ startFleetLlmHost }) => startFleetLlmHost()).catch(() => console.error('❌ Dedicated model host listener could not start; open AI Providers → Model host setup.'));+ // Local file scan only (no provider calls); keeps the federated Claude Code+ // token history current even when the usage page is never opened.+ import('./services/claudeCodeTranscriptUsage.js').then(({ startTranscriptUsageRefresh }) => startTranscriptUsageRefresh())+ .catch((err) => console.error(`❌ Claude Code transcript usage refresh could not start: ${err.message}`));}diff --git a/server/routes/usage.js b/server/routes/usage.jsindex 983d096963..eb38842652 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -1,13 +1,14 @@import { Router } from 'express';import * as usage from '../services/usage.js';import { getClaudeCodeUsage } from '../services/claudeCodeUsage.js';+import { refreshLocalTranscriptUsage } from '../services/claudeCodeTranscriptUsage.js';import { getProviderQuotas } from '../services/providerUsage.js';import { getAllProviders } from '../services/providers.js';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest, usageQuerySchema, usageMessagesSchema, usageTokensSchema, usageSessionSchema, providerUsageQuerySchema, subscriptionsUpdateSchema, subscriptionEnabledSchema, usageFleetBillingSchema } from '../lib/validation.js';import { saveSubscriptionCosts, getSubscriptionSavings } from '../services/subscriptionCosts.js';import { getSubscriptionOverview, savePlanTiers, setSubscriptionEnabled } from '../services/subscriptions.js';-import { getFleetUsage } from '../services/peerUsage.js';+import { getFleetUsage, getFleetClaudeCodeModels } from '../services/peerUsage.js';import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';import { resolveUsageRange } from '../lib/usageRange.js';import { WAIT } from '../lib/staleWhileRevalidate.js';@@ -137,6 +138,17 @@ router.get('/claude-code', asyncHandler(async (req, res) => {res.json(data);}));+// GET /api/usage/claude-code/models - Claude Code tokens per model, priced at+// API rates, across the fleet: every instance's per-day transcript history+// (this machine's is refreshed first if stale) plus a combined per-model list.+// Same ?period=7d|30d|90d|all or ?from/?to window as GET /api/usage.+router.get('/claude-code/models', asyncHandler(async (req, res) => {+ const { from, to } = resolveUsageRange(validateRequest(usageQuerySchema, req.query));+ await refreshLocalTranscriptUsage();+ const apiBilledInstanceIds = await getApiBilledInstanceIds();+ res.json({ from, to, ...(await getFleetClaudeCodeModels({ from, to, apiBilledInstanceIds })) });+}));+// GET /api/usage/raw - Get raw usage datarouter.get('/raw', asyncHandler(async (req, res) => {const data = usage.getUsage();diff --git a/server/services/claudeCodeModelReport.js b/server/services/claudeCodeModelReport.jsnew file mode 100644index 0000000000..4b2cfbdb2d--- /dev/null+++ b/server/services/claudeCodeModelReport.js@@ -0,0 +1,50 @@+import { isFreeModelId, resolveModelRates, estimateCostUsd } from '../lib/modelPricing.js';+import { roundCents } from '../lib/subscriptionSavings.js';++/**+ * Pure report math over Claude Code per-day, per-model token counts (the shape+ * `claudeCodeTranscriptUsage.js` stores and federates): window sums, API-rate+ * pricing from the shared table, and fleet-wide merging. No I/O.+ */++const COUNT_FIELDS = ['messages', 'input', 'output', 'cacheRead', 'cacheWrite'];+const SUM_FIELDS = [...COUNT_FIELDS, 'total', 'estimatedCost'];++// Group rows by model, sum every field, round the money, and total — the one+// rollup behind both a single instance's window and the fleet-wide merge.+function rollUp(rows) {+ const byModel = new Map();+ for (const row of rows) {+ const acc = byModel.get(row.model) || { model: row.model, ...Object.fromEntries(SUM_FIELDS.map((f) => [f, 0])) };+ for (const f of SUM_FIELDS) acc[f] += row[f] || 0;+ byModel.set(row.model, acc);+ }+ const models = [...byModel.values()]+ .map((row) => ({ ...row, estimatedCost: roundCents(row.estimatedCost) }))+ .sort((a, b) => b.estimatedCost - a.estimatedCost || b.total - a.total);+ const totals = Object.fromEntries(SUM_FIELDS.map((f) => [f, models.reduce((sum, row) => sum + row[f], 0)]));+ totals.estimatedCost = roundCents(totals.estimatedCost);+ return { models, totals };+}++/**+ * Sum a day map over an inclusive window into per-model rows (highest cost+ * first), each priced at API rates. Cache tiers bill at their own rates;+ * local/free model ids cost nothing.+ */+export function summarizeTranscriptDays(days, { from = null, to = null } = {}) {+ const rows = [];+ for (const [day, models] of Object.entries(days || {})) {+ if ((from && day < from) || (to && day > to)) continue;+ for (const [model, c] of Object.entries(models)) {+ const cost = isFreeModelId(model)+ ? 0+ : estimateCostUsd(c.input, c.output, resolveModelRates('claude-code', model), { cacheReadTokens: c.cacheRead, cacheWriteTokens: c.cacheWrite });+ rows.push({ model, ...c, total: c.input + c.output + c.cacheRead + c.cacheWrite, estimatedCost: cost });+ }+ }+ return rollUp(rows);+}++/** Combine several instances' per-model rows into one fleet-wide per-model list. */+export const mergeModelRows = (rowSets) => rollUp(rowSets.flat());diff --git a/server/services/claudeCodeModelReport.test.js b/server/services/claudeCodeModelReport.test.jsnew file mode 100644index 0000000000..e6857f7c53--- /dev/null+++ b/server/services/claudeCodeModelReport.test.js@@ -0,0 +1,17 @@+import { describe, it, expect } from 'vitest';+import { summarizeTranscriptDays, mergeModelRows } from './claudeCodeModelReport.js';++describe('claude code model report', () => {+ it('prices per model at API rates and merges instances into a fleet list', async () => {+ const days = { '2026-09-10': { 'claude-opus-5-5': { messages: 1, input: 1_000_000, output: 1_000_000, cacheRead: 0, cacheWrite: 0 }, 'qwen3-coder:30b': { messages: 1, input: 5e6, output: 5e6, cacheRead: 0, cacheWrite: 0 } } };+ const a = summarizeTranscriptDays(days, { from: '2026-09-01', to: '2026-09-30' });+ const opus = a.models.find((m) => m.model === 'claude-opus-5-5');+ expect(opus.estimatedCost).toBeGreaterThan(0);+ expect(a.models.find((m) => m.model.startsWith('qwen')).estimatedCost).toBe(0);+ expect(summarizeTranscriptDays(days, { from: '2026-10-01' }).models).toEqual([]);+ const fleet = mergeModelRows([a.models, a.models]);+ expect(fleet.totals.estimatedCost).toBeCloseTo(opus.estimatedCost * 2, 1);+ expect(fleet.models.find((m) => m.model === 'claude-opus-5-5').messages).toBe(2);+ });++});diff --git a/server/services/claudeCodeTranscriptUsage.js b/server/services/claudeCodeTranscriptUsage.jsnew file mode 100644index 0000000000..c2dd918650--- /dev/null+++ b/server/services/claudeCodeTranscriptUsage.js@@ -0,0 +1,194 @@+import { createReadStream } from 'fs';+import { readdir, stat } from 'fs/promises';+import { homedir } from 'os';+import { join } from 'path';+import { createInterface } from 'readline';+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { createMutex } from '../lib/asyncMutex.js';+import { isPlainObject } from '../lib/objects.js';+import { isNonBlankStr } from '../lib/textUtils.js';++/**+ * Per-model token usage for EVERY Claude Code session on this machine —+ * including ones PortOS never spawned — read from the CLI's own transcripts+ * (`~/.claude/projects/**\/*.jsonl`, subagent sidechains included).+ *+ * The CLI has no structured usage endpoint, but each assistant line carries+ * `timestamp`, `message.model`, and `message.usage`. Two hazards:+ * - a streamed response is logged on several lines with growing counts, and+ * resumed/forked sessions replay earlier history into a new file, so lines+ * are de-duplicated by `message.id` + `requestId` (the last copy wins);+ * - the CLI prunes old transcripts. So the scan is folded into a persisted+ * per-day, per-model store (`data/claude-code-transcript-usage.json`) that+ * keeps history the CLI has since deleted.+ *+ * That store is what federates: `peerUsage.js` publishes it on the `usage` sync+ * category so a fleet report can total tokens per model across machines and+ * price them at API rates. It carries model ids, day buckets and token counts+ * only — never prompts, paths or session ids.+ *+ * Scans are user- or timer-triggered file reads (no provider calls). Days are+ * UTC calendar days, matching `usageRange.js`.+ */++export const TRANSCRIPT_USAGE_FILE = join(PATHS.data, 'claude-code-transcript-usage.json');++const SYNTHETIC_MODEL = '<synthetic>';+const FIELDS = ['messages', 'input', 'output', 'cacheRead', 'cacheWrite'];+// Bounds on stored/peer-supplied maps (see the digest caps in peerUsage.js).+const MAX_DAYS = 800;+const MAX_MODELS_PER_DAY = 100;+// An incremental refresh re-reads recent days only; a first run reads all.+const REFRESH_LOOKBACK_DAYS = 3;+const REFRESH_STALE_MS = 5 * 60_000;++const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;+const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);+const withLock = createMutex();++const projectsRoot = () => join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');+const zeroCounts = () => Object.fromEntries(FIELDS.map((f) => [f, 0]));++async function listTranscripts(root, fromMs) {+ const entries = await readdir(root, { recursive: true, withFileTypes: true }).catch(() => []);+ const files = [];+ for (const entry of entries) {+ if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue;+ const path = join(entry.parentPath ?? entry.path, entry.name);+ if (fromMs == null) { files.push(path); continue; }+ // A file last written before `from` cannot hold a line in range.+ const info = await stat(path).catch(() => null);+ if (info && info.mtimeMs >= fromMs) files.push(path);+ }+ return files;+}++async function collectFile(path, from, seen) {+ const lines = createInterface({ input: createReadStream(path, { encoding: 'utf8' }), crlfDelay: Infinity });+ for await (const line of lines) {+ if (!line.includes('"usage"')) continue;+ let row;+ try { row = JSON.parse(line); } catch { continue; }+ const message = row.message;+ const usage = message?.usage;+ if (row.type !== 'assistant' || !usage || !message.model || message.model === SYNTHETIC_MODEL) continue;+ const day = String(row.timestamp).slice(0, 10);+ if (!DAY_RE.test(day) || (from && day < from)) continue;+ const key = message.id ? `${message.id}:${row.requestId || ''}` : row.uuid;+ if (!key) continue;+ seen.set(key, {+ day,+ model: message.model,+ input: usage.input_tokens || 0,+ output: usage.output_tokens || 0,+ cacheRead: usage.cache_read_input_tokens || 0,+ cacheWrite: usage.cache_creation_input_tokens || 0+ });+ }+}++/**+ * Scan transcripts from `from` (YYYY-MM-DD, null = everything on disk) into+ * `{ days: { <day>: { <model>: counts } }, filesScanned }`.+ */+async function scanTranscriptDays({ from = null, root = projectsRoot() } = {}) {+ const files = await listTranscripts(root, from ? Date.parse(`${from}T00:00:00Z`) : null);+ const seen = new Map();+ for (const file of files) {+ // Non-strict: a transcript deleted or truncated mid-scan drops out of the+ // report rather than failing the whole read.+ await collectFile(file, from, seen).catch((err) => {+ console.warn(`⚠️ Skipped unreadable Claude Code transcript: ${err.message}`);+ });+ }+ const days = {};+ for (const entry of seen.values()) {+ const row = ((days[entry.day] ||= {})[entry.model] ||= zeroCounts());+ row.messages += 1;+ for (const f of FIELDS) if (f !== 'messages') row[f] += entry[f];+ }+ return { days, filesScanned: files.length };+}++/**+ * Rebuild a day → model → counts map to the known shape, dropping anything+ * else. Used for both the stored file and peer-supplied digests, so depth and+ * size are fixed by construction.+ */+export function sanitizeTranscriptDays(raw) {+ const out = {};+ if (!isPlainObject(raw)) return out;+ const dayKeys = Object.keys(raw).filter((d) => DAY_RE.test(d)).sort().slice(-MAX_DAYS);+ for (const day of dayKeys) {+ if (!isPlainObject(raw[day])) continue;+ for (const [model, counts] of Object.entries(raw[day]).slice(0, MAX_MODELS_PER_DAY)) {+ if (!isNonBlankStr(model)) continue;+ (out[day] ||= {})[model.slice(0, 200)] = Object.fromEntries(FIELDS.map((f) => [f, num(counts?.[f])]));+ }+ }+ return out;+}++// Per (day, model) field, the larger count wins: a re-scan of a day whose+// oldest transcripts were pruned must never shrink what an earlier scan saw.+function mergeDays(stored, scanned) {+ const merged = { ...stored };+ for (const [day, models] of Object.entries(scanned)) {+ const target = { ...(merged[day] || {}) };+ for (const [model, row] of Object.entries(models)) {+ const prev = target[model] || zeroCounts();+ target[model] = Object.fromEntries(FIELDS.map((f) => [f, Math.max(prev[f], row[f])]));+ }+ merged[day] = target;+ }+ return sanitizeTranscriptDays(merged);+}++// The store is read on every sync snapshot/manifest/checksum, so the sanitized+// copy is memoized against the file's identity (mtime + size) — the same idea+// as peerUsage's digest memo — instead of re-parsing and rebuilding up to+// MAX_DAYS x MAX_MODELS_PER_DAY rows per call.+let storeMemo = null;++/** The persisted local store: `{ days, updatedAt }` (`updatedAt` null before the first scan). */+export async function readLocalTranscriptUsage() {+ const info = await stat(TRANSCRIPT_USAGE_FILE).catch(() => null);+ const key = info ? `${TRANSCRIPT_USAGE_FILE}|${info.mtimeMs}|${info.size}` : null;+ if (key && storeMemo?.key === key) return storeMemo.value;+ const raw = await readJSONFile(TRANSCRIPT_USAGE_FILE, null);+ const value = {+ days: sanitizeTranscriptDays(raw?.days),+ updatedAt: isNonBlankStr(raw?.updatedAt) ? raw.updatedAt : null+ };+ storeMemo = key ? { key, value } : null;+ return value;+}++/**+ * Fold a fresh scan into the persisted store. The first run reads every+ * transcript on disk; later runs re-read only the last few days. Skipped when+ * the store is younger than `staleMs` unless `force`.+ */+export function refreshLocalTranscriptUsage({ root, force = false, staleMs = REFRESH_STALE_MS } = {}) {+ return withLock(async () => {+ const stored = await readLocalTranscriptUsage();+ const age = stored.updatedAt ? Date.now() - Date.parse(stored.updatedAt) : Infinity;+ if (!force && age < staleMs) return { ...stored, filesScanned: 0, refreshed: false };+ const from = stored.updatedAt+ ? new Date(Date.now() - REFRESH_LOOKBACK_DAYS * 86_400_000).toISOString().slice(0, 10)+ : null;+ const { days: scanned, filesScanned } = await scanTranscriptDays({ from, root });+ const next = { days: mergeDays(stored.days, scanned), updatedAt: new Date().toISOString() };+ await atomicWrite(TRANSCRIPT_USAGE_FILE, next);+ return { ...next, filesScanned, refreshed: true };+ });+}++/** Background keep-fresh so peers get current numbers even if the page is never opened. */+export function startTranscriptUsageRefresh({ intervalMs = 30 * 60_000, firstDelayMs = 60_000 } = {}) {+ const run = () => refreshLocalTranscriptUsage({ force: true }).catch((err) => {+ console.error(`❌ Claude Code transcript usage refresh failed: ${err.message}`);+ });+ setTimeout(run, firstDelayMs).unref();+ setInterval(run, intervalMs).unref();+}diff --git a/server/services/claudeCodeTranscriptUsage.test.js b/server/services/claudeCodeTranscriptUsage.test.jsnew file mode 100644index 0000000000..e0ca176a20--- /dev/null+++ b/server/services/claudeCodeTranscriptUsage.test.js@@ -0,0 +1,65 @@+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-cc-transcripts-' });+vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));+afterAll(cleanup);++const line = (id, model, timestamp, usage) => JSON.stringify({+ type: 'assistant', timestamp, requestId: `req-${id}`, message: { id, model, usage }+});+const u = (o) => ({ input_tokens: 1, output_tokens: o, cache_read_input_tokens: 10, cache_creation_input_tokens: 100 });++describe('claude code transcript usage', () => {+ let root;+ let svc;+ beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'cc-usage-'));+ vi.resetModules();+ svc = await import('./claudeCodeTranscriptUsage.js');+ // The data root is shared by every case in this file; start each with no store.+ await rm(svc.TRANSCRIPT_USAGE_FILE, { force: true });+ await mkdir(join(root, 'proj-a', 'sess', 'subagents'), { recursive: true });+ await mkdir(join(root, 'proj-b'), { recursive: true });+ });+ afterEach(async () => {+ await rm(root, { recursive: true, force: true });+ });++ it('buckets by day and model, dedupes streamed/forked copies (last wins), reads subagent files', async () => {+ await writeFile(join(root, 'proj-a', 's1.jsonl'), [+ line('m1', 'model-x', '2026-09-10T01:00:00Z', u(5)),+ line('m1', 'model-x', '2026-09-10T01:00:01Z', u(50)), // streamed rewrite — last wins+ line('m2', 'model-y', '2026-09-11T01:00:00Z', u(7)),+ line('ms', '<synthetic>', '2026-09-10T02:00:00Z', u(1)),+ JSON.stringify({ type: 'user', message: { usage: u(1) } }),+ 'not json "usage"'+ ].join('\n'));+ await writeFile(join(root, 'proj-b', 's2.jsonl'), line('m1', 'model-x', '2026-09-10T01:00:01Z', u(50)) + '\n'); // forked replay+ await writeFile(join(root, 'proj-a', 'sess', 'subagents', 'a.jsonl'), line('m3', 'model-x', '2026-09-12T00:00:00Z', u(3)) + '\n');++ const { days } = await svc.refreshLocalTranscriptUsage({ root, force: true });+ expect(days['2026-09-10']['model-x']).toEqual({ messages: 1, input: 1, output: 50, cacheRead: 10, cacheWrite: 100 });+ expect(Object.keys(days).sort()).toEqual(['2026-09-10', '2026-09-11', '2026-09-12']);+ expect(days['2026-09-12']['model-x'].output).toBe(3);+ });++ it('persists history past transcript pruning and never shrinks a stored day', async () => {+ const file = join(root, 'proj-b', 's.jsonl');+ await writeFile(file, [line('a', 'model-x', '2026-01-05T00:00:00Z', u(9)), line('b', 'model-x', '2026-01-05T00:00:01Z', u(9))].join('\n'));+ await svc.refreshLocalTranscriptUsage({ root, force: true });+ await rm(file); // the CLI prunes the transcript+ await svc.refreshLocalTranscriptUsage({ root, force: true });+ const { days, updatedAt } = await svc.readLocalTranscriptUsage();+ expect(days['2026-01-05']['model-x'].messages).toBe(2);+ expect(updatedAt).toBeTruthy();+ });++ it('rebuilds peer-supplied days to the fixed shape', () => {+ const out = svc.sanitizeTranscriptDays({ '2026-09-10': { m: { messages: 1, input: -5, evil: 9, output: 'x' } }, bad: { m: {} }, '2026-09-11': 'nope' });+ expect(out).toEqual({ '2026-09-10': { m: { messages: 1, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } } });+ });+});diff --git a/server/services/peerUsage.js b/server/services/peerUsage.jsindex 7704b60a98..26e2e117b2 100644--- a/server/services/peerUsage.js+++ b/server/services/peerUsage.js@@ -37,6 +37,8 @@ import { sanitizeQuotaCards } from '../lib/fleetQuotas.js';import { buildUsageDigest, buildUsageReport, getUsage, USAGE_FILE } from './usage.js';import { readLocalQuotaCards, PROVIDER_QUOTAS_FILE } from './providerQuotaShare.js';import { isNonBlankStr } from '../lib/textUtils.js';+import { readLocalTranscriptUsage, sanitizeTranscriptDays, TRANSCRIPT_USAGE_FILE } from './claudeCodeTranscriptUsage.js';+import { summarizeTranscriptDays, mergeModelRows } from './claudeCodeModelReport.js';const PEER_USAGE_FILE = join(PATHS.data, 'peer-usage.json');@@ -167,6 +169,16 @@ async function readStore() {};}+/**+ * A peer's Claude Code per-day, per-model token history, or null when it sent+ * none (or an unorderable one). Rebuilt to the fixed day → model → counts shape.+ */+function sanitizeClaudeCode(raw) {+ if (!isPlainObject(raw) || parseTsMs(raw.updatedAt) === null) return null;+ const days = sanitizeTranscriptDays(raw.days);+ return Object.keys(days).length > 0 ? { updatedAt: raw.updatedAt, days } : null;+}+/*** Coerce one wire entry into a stored entry, or null when it can't be trusted.* Pins identity (the entry must belong to the map key it arrived under),@@ -187,6 +199,9 @@ function sanitizeEntry(entry, expectedId) {// Optional: a peer running an older build publishes no quota readings, and// the fleet quota view simply has one fewer contributor.quotas: sanitizeQuotaCards(entry.quotas),+ // Optional and additive, like `quotas`: a peer on an older build publishes+ // no Claude Code token history and simply contributes nothing to that report.+ claudeCode: sanitizeClaudeCode(entry.claudeCode),};}@@ -215,8 +230,13 @@ async function buildSelfEntry() {if (!instanceId) return null;const usage = selfDigest(getUsage());const { quotas, capturedAt: quotasAt } = await readLocalQuotaCards();- const capturedAt = compareNewerWins(quotasAt, usage.lastUpdated) ? quotasAt : usage.lastUpdated;- return { instanceId, name: name || instanceId, capturedAt, usage, quotas };+ const local = await readLocalTranscriptUsage();+ const claudeCode = local.updatedAt && Object.keys(local.days).length > 0 ? local : null;+ // capturedAt is the LWW stamp AND manifest fingerprint: the newest of every+ // component, so a transcript-store refresh alone still gets pulled by peers.+ const capturedAt = [usage.lastUpdated, quotasAt, claudeCode?.updatedAt].reduce(+ (newest, ts) => (compareNewerWins(ts, newest) ? ts : newest));+ return { instanceId, name: name || instanceId, capturedAt, usage, quotas, ...(claudeCode && { claudeCode }) };}/**@@ -459,6 +479,28 @@ export async function getFleetUsage({ from = null, to = null, providers = [], apreturn { instances: rows, totals: sumFleetTotals(included) };}+/**+ * Fleet-wide Claude Code tokens per model, priced at API rates, for a window.+ * One row per instance that has published transcript history (this machine+ * reads its live store), plus a combined per-model list. As with `getFleetUsage`,+ * an instance the viewer marked as API-billed stays listed but does not feed the+ * combined figures. Peer rows are as fresh as the last sync (`capturedAt`).+ */+export async function getFleetClaudeCodeModels({ from = null, to = null, apiBilledInstanceIds = [] } = {}) {+ const { self, peers } = await entriesWithSelf();+ const apiBilled = new Set(Array.isArray(apiBilledInstanceIds) ? apiBilledInstanceIds : []);+ const row = (e, isSelf) => {+ const { models, totals } = summarizeTranscriptDays(e.claudeCode.days, { from, to });+ return { instanceId: e.instanceId, name: e.name || e.instanceId, self: isSelf, capturedAt: e.claudeCode.updatedAt, models, totals, usesSubscriptions: !apiBilled.has(e.instanceId) };+ };+ const instances = [+ ...(self?.claudeCode ? [row(self, true)] : []),+ ...peers.filter((e) => e.claudeCode).map((e) => row(e, false)),+ ];+ const combined = mergeModelRows(instances.filter((i) => i.usesSubscriptions).map((i) => i.models));+ return { instances, ...combined };+}+/*** Every OTHER instance's last-known subscription-quota readings, for unifying* them with this machine's cards (`lib/fleetQuotas.js`).@@ -501,6 +543,6 @@ export async function forgetInstanceUsage(instanceId) {// Files whose fingerprint invalidates the category's checksum cache. The// instances file is in the set because the manifest is keyed by this instance's// ID — a re-identified machine must re-checksum even when no counter moved.-export const USAGE_CHECKSUM_PATHS = [USAGE_FILE, PEER_USAGE_FILE, PROVIDER_QUOTAS_FILE, dataPath('instances.json')];+export const USAGE_CHECKSUM_PATHS = [USAGE_FILE, PEER_USAGE_FILE, PROVIDER_QUOTAS_FILE, TRANSCRIPT_USAGE_FILE, dataPath('instances.json')];export { PEER_USAGE_FILE };diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.jsindex c7610323a6..66d19587c3 100644--- a/server/services/peerUsage.test.js+++ b/server/services/peerUsage.test.js@@ -32,9 +32,11 @@ const {applyUsageRemote,getFleetUsage,getFleetQuotaEntries,+ getFleetClaudeCodeModels,forgetInstanceUsage,PEER_USAGE_FILE,} = await import('./peerUsage.js');+const { TRANSCRIPT_USAGE_FILE } = await import('./claudeCodeTranscriptUsage.js');const { recordLocalQuotaCards, readLocalQuotaCards, PROVIDER_QUOTAS_FILE } = await import('./providerQuotaShare.js');afterAll(cleanup);@@ -99,6 +101,7 @@ beforeEach(async () => {const { atomicWrite } = await import('../lib/fileUtils.js');await atomicWrite(PEER_USAGE_FILE, { instances: {} });await atomicWrite(PROVIDER_QUOTAS_FILE, { quotas: [] });+ await atomicWrite(TRANSCRIPT_USAGE_FILE, { days: {}, updatedAt: null });});const quotaCard = (over = {}) => ({@@ -531,3 +534,35 @@ describe('federated subscription-quota readings', () => {expect(await getFleetQuotaEntries()).toEqual([]);});});++describe('federated Claude Code tokens per model', () => {+ const counts = (o) => ({ messages: 2, input: 1_000_000, output: o, cacheRead: 0, cacheWrite: 0 });+ const days = (o) => ({ '2026-09-10': { 'claude-opus-5-5': counts(o) }, '2026-08-01': { 'claude-opus-5-5': counts(o) } });++ it('publishes this machine\'s history, moves the LWW stamp with it, and totals it with a peer', async () => {+ const { atomicWrite } = await import('../lib/fileUtils.js');+ await atomicWrite(TRANSCRIPT_USAGE_FILE, { days: days(1_000_000), updatedAt: '2026-09-20T00:00:00.000Z' });+ const { data } = await getUsageSnapshot();+ expect(data.instances['inst-self'].claudeCode.days['2026-09-10']['claude-opus-5-5'].output).toBe(1_000_000);+ expect(Date.parse(data.instances['inst-self'].capturedAt)).toBeGreaterThanOrEqual(Date.parse('2026-09-20T00:00:00.000Z'));++ await applyUsageRemote({ instances: { 'inst-peer': { ...peerEntry(), claudeCode: { updatedAt: '2026-09-21T00:00:00.000Z', days: days(3_000_000) } } } });+ const fleet = await getFleetClaudeCodeModels({ from: '2026-09-01', to: '2026-09-30' });+ expect(fleet.instances.map((i) => i.instanceId).sort()).toEqual(['inst-peer', 'inst-self']);+ // Window scoping: the 2026-08-01 day is excluded from every row and the total.+ expect(fleet.models).toEqual([expect.objectContaining({ model: 'claude-opus-5-5', messages: 4, output: 4_000_000 })]);+ expect(fleet.totals.estimatedCost).toBeGreaterThan(0);+ });++ it('keeps an API-billed instance listed but out of the combined figures, and tolerates a peer with no history', async () => {+ await applyUsageRemote({ instances: { 'inst-peer': { ...peerEntry(), claudeCode: { updatedAt: '2026-09-21T00:00:00.000Z', days: days(3_000_000) } }, 'inst-old': peerEntry() } });+ const fleet = await getFleetClaudeCodeModels({ apiBilledInstanceIds: ['inst-peer'] });+ expect(fleet.instances).toEqual([expect.objectContaining({ instanceId: 'inst-peer', usesSubscriptions: false })]);+ expect(fleet.totals.total).toBe(0);+ });++ it('rebuilds a hostile peer history to the fixed shape', async () => {+ await applyUsageRemote({ instances: { 'inst-peer': { ...peerEntry(), claudeCode: { updatedAt: '2026-09-21T00:00:00.000Z', days: { '2026-09-10': { m: { messages: 1, evil: 5 } }, junk: {} } } } } });+ expect((await readStoreFile()).instances['inst-peer'].claudeCode.days).toEqual({ '2026-09-10': { m: { messages: 1, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } } });+ });+});