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
Usage: chart the rolling 30-day API cost estimate across every instance (#12939)
[._.]/e3716c004ce2
diff --git a/client/src/components/usage/RollingCostCard.jsx b/client/src/components/usage/RollingCostCard.jsxnew file mode 100644index 0000000000..54ff317b33--- /dev/null+++ b/client/src/components/usage/RollingCostCard.jsx@@ -0,0 +1,73 @@+import { useState } from 'react';+import { countSparklineGeometry } from '../../lib/editorialHealth';+import { formatUsd } from '../../utils/formatters';++const WIDTH = 300;+const HEIGHT = 96;+const PAD = 2;++// Series dates are UTC calendar days (server/services/peerUsage.js), so they+// are labeled in UTC or a west-of-UTC viewer would see every day shifted.+const dayLabel = (date) => new Date(`${date}T00:00:00Z`)+ .toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });++/**+ * Trailing-30-day estimated API cost summed across every instance, one point+ * per day. Tap or drag the chart to read a day; the headline shows today until+ * then. Hand-drawn SVG: the shape is one area and one line.+ */+export default function RollingCostCard({ rollingCost }) {+ const [selected, setSelected] = useState(null);+ const points = rollingCost?.points || [];+ if (points.length < 2) return null;++ const { coords } = countSparklineGeometry(points.map((p) => p.cost), { width: WIDTH, height: HEIGHT, pad: PAD });+ const line = coords.map((c, i) => `${i ? 'L' : 'M'}${c.x},${c.y}`).join('');+ const area = `${line}L${coords.at(-1).x},${HEIGHT}L${coords[0].x},${HEIGHT}Z`;+ const index = selected ?? points.length - 1;+ const point = points[index];+ const marker = coords[index];+ const instances = rollingCost.instanceCount || 1;++ const pick = (event) => {+ const box = event.currentTarget.getBoundingClientRect();+ if (!box.width) return;+ const fraction = Math.min(1, Math.max(0, (event.clientX - box.left) / box.width));+ setSelected(Math.round(fraction * (points.length - 1)));+ };++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-2">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <h3 className="text-sm font-medium text-gray-400">Est. API cost, rolling {rollingCost.windowDays || 30} days</h3>+ <p className="text-[10px] sm:text-xs text-gray-500">+ {instances > 1 ? `${instances} instances` : 'This machine'}+ </p>+ </div>+ <div className="text-right shrink-0">+ <div className="text-xl font-bold text-port-success tabular-nums">{formatUsd(point.cost)}</div>+ <div className="text-[10px] sm:text-xs text-gray-500">{selected === null ? 'Today' : dayLabel(point.date)}</div>+ </div>+ </div>+ <svg+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}+ preserveAspectRatio="none"+ className="w-full h-24 sm:h-32 touch-none cursor-crosshair select-none"+ role="img"+ aria-label={`Rolling ${rollingCost.windowDays || 30}-day estimated API cost from ${dayLabel(points[0].date)} to ${dayLabel(points.at(-1).date)}, now ${formatUsd(points.at(-1).cost)}`}+ onPointerDown={(event) => { event.currentTarget.setPointerCapture?.(event.pointerId); pick(event); }}+ onPointerMove={(event) => { if (event.buttons || event.pointerType === 'mouse') pick(event); }}+ onPointerLeave={(event) => { if (event.pointerType === 'mouse') setSelected(null); }}+ >+ <path d={area} className="fill-port-success/15" />+ <path d={line} fill="none" className="stroke-port-success" strokeWidth="2" vectorEffect="non-scaling-stroke" strokeLinejoin="round" />+ {selected !== null && <line x1={marker.x} x2={marker.x} y1={0} y2={HEIGHT} className="stroke-gray-500" strokeWidth="1" vectorEffect="non-scaling-stroke" strokeDasharray="3 3" />}+ </svg>+ <div className="flex justify-between text-[10px] sm:text-xs text-gray-500">+ <span>{dayLabel(points[0].date)}</span>+ <span>Today</span>+ </div>+ </div>+ );+}diff --git a/client/src/components/usage/RollingCostCard.test.jsx b/client/src/components/usage/RollingCostCard.test.jsxnew file mode 100644index 0000000000..a3d386fdd8--- /dev/null+++ b/client/src/components/usage/RollingCostCard.test.jsx@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import RollingCostCard from './RollingCostCard';++const rollingCost = {+ windowDays: 30,+ instanceCount: 3,+ points: [+ { date: '2026-10-20', cost: 10 },+ { date: '2026-10-21', cost: 25.5 },+ { date: '2026-10-22', cost: 40.25 },+ ],+};++describe('RollingCostCard', () => {+ it('headlines today and reads a tapped day', () => {+ render(<RollingCostCard rollingCost={rollingCost} />);+ expect(screen.getByText('$40.25')).toBeTruthy();+ expect(screen.getByText('3 instances')).toBeTruthy();++ const chart = screen.getByRole('img');+ chart.getBoundingClientRect = () => ({ left: 0, width: 300, top: 0, height: 96 });+ fireEvent.pointerDown(chart, { clientX: 150, pointerId: 1 });+ expect(screen.getByText('$25.50')).toBeTruthy();+ expect(screen.getByText('Oct 21')).toBeTruthy();+ });++ it('renders nothing without a series', () => {+ const { container } = render(<RollingCostCard rollingCost={{ points: [] }} />);+ expect(container.innerHTML).toBe('');+ });+});diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 8877e92f52..d59c23be8a 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -12,6 +12,7 @@ import { useQuotaUpdates } from '../hooks/useQuotaUpdates';import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';import ClaudeCodeModelTokensCard from '../components/usage/ClaudeCodeModelTokensCard';import FleetUsageCard from '../components/usage/FleetUsageCard';+import RollingCostCard from '../components/usage/RollingCostCard';import FreeTierUsageCard from '../components/usage/FreeTierUsageCard';import ProviderQuotaBody from '../components/usage/ProviderQuotaBody';import ModelsTabsHeader, { ModelsSectionLayout } from '../components/models/ModelsTabsHeader';@@ -655,6 +656,8 @@ function InternalUsageMetrics() {return (<div className="space-y-6"><h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>+ {/* Trailing 30 days across every instance — independent of the range below. */}+ <RollingCostCard rollingCost={usage.rollingCost} />{reportControls}<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">diff --git a/server/routes/usage.js b/server/routes/usage.jsindex eb38842652..039224a951 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -8,7 +8,7 @@ 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, getFleetClaudeCodeModels } from '../services/peerUsage.js';+import { getFleetUsage, getFleetClaudeCodeModels, getFleetRollingCost } from '../services/peerUsage.js';import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';import { resolveUsageRange } from '../lib/usageRange.js';import { WAIT } from '../lib/staleWhileRevalidate.js';@@ -40,7 +40,9 @@ router.get('/', asyncHandler(async (req, res) => {// same window by the same report builder. Empty on a single-machine install// (or before a peer's first usage sync) — the UI hides that section rather// than showing a one-row "fleet".- const [subscriptionSavings, fleet] = await Promise.all([+ // - rollingCost: the trailing-30-day API estimate across every instance,+ // independent of the window (memoized, so a range change re-sends it free).+ const [subscriptionSavings, fleet, rollingCost] = await Promise.all([getSubscriptionSavings({report: summary.report,providers,@@ -52,8 +54,9 @@ router.get('/', asyncHandler(async (req, res) => {}),getApiBilledInstanceIds().then((apiBilledInstanceIds) =>getFleetUsage({ from, to, providers, apiBilledInstanceIds })),+ getFleetRollingCost({ providers }),]);- res.json({ ...summary, subscriptionSavings, fleet });+ res.json({ ...summary, subscriptionSavings, fleet, rollingCost });}));// GET /api/usage/subscriptions - The Subscriptions page's own model: one rowdiff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex 319e3308a6..99e301cdb8 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -14,7 +14,8 @@ vi.mock('../services/usage.js', () => ({}));vi.mock('../services/peerUsage.js', () => ({- getFleetUsage: vi.fn(async () => ({ instances: [], totals: null }))+ getFleetUsage: vi.fn(async () => ({ instances: [], totals: null })),+ getFleetRollingCost: vi.fn(async () => ({ windowDays: 30, instanceCount: 1, points: [] }))}));vi.mock('../services/usageFleetBilling.js', () => ({@@ -124,7 +125,8 @@ describe('usage routes', () => {totalSessions: 4,providers: ['anthropic'],subscriptionSavings: { configured: false, families: [] },- fleet: { instances: [], totals: null }+ fleet: { instances: [], totals: null },+ rollingCost: { windowDays: 30, instanceCount: 1, points: [] }});const arg = usage.getUsageSummary.mock.calls[0][0];expect(arg.from).toMatch(/^\d{4}-\d{2}-\d{2}$/);diff --git a/server/services/peerUsage.js b/server/services/peerUsage.jsindex c85109b20c..0baeddf421 100644--- a/server/services/peerUsage.js+++ b/server/services/peerUsage.js@@ -33,6 +33,7 @@ import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';import { mergeTombstones, normalizeTombstones, recordTombstone, isTombstoned } from '../lib/tombstones.js';import { canonicalSnapshotChecksum } from '../lib/snapshotChecksum.js';import { roundCents } from '../lib/subscriptionSavings.js';+import { isFreeProvider } from '../lib/modelPricing.js';import { sanitizeQuotaCards } from '../lib/fleetQuotas.js';import { buildUsageDigest, buildUsageReport, getUsage, USAGE_FILE } from './usage.js';import { readLocalQuotaCards, PROVIDER_QUOTAS_FILE } from './providerQuotaShare.js';@@ -481,6 +482,70 @@ export async function getFleetUsage({ from = null, to = null, providers = [], apreturn { instances: rows, totals: sumFleetTotals(included) };}+// Peer digests keep day precision for 120 days (DIGEST_DAILY_RETENTION_DAYS in+// usage.js), so 90 points of a 30-day window (119 days of input) is the longest+// series every instance can supply at full resolution.+export const ROLLING_COST_WINDOW_DAYS = 30;+export const ROLLING_COST_POINTS = 90;++const utcDay = (date) => date.toISOString().slice(0, 10);++/** Each UTC day from `days - 1` days before `now` through `now`, oldest first. */+function trailingDays(now, days) {+ const end = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());+ return Array.from({ length: days }, (_, i) => utcDay(new Date(end - (days - 1 - i) * 86_400_000)));+}++/**+ * Estimated API cost per day, each day priced on its own through the same+ * `buildUsageReport` as the cost report so the series and the headline agree.+ */+function dailyCosts(dailyActivity, dayList, providers) {+ return dayList.map((day) => {+ const bucket = dailyActivity?.[day];+ return bucket ? buildUsageReport({ [day]: bucket }, { from: day, to: day, providers }).totals.estimatedCost : 0;+ });+}++let rollingMemo = null;++/**+ * Rolling 30-day estimated API cost summed across EVERY known instance, one+ * point per UTC day for the last 90 days. API-billed instances count here: this+ * is total spend at API rates, not the subscription-covered subset the Across+ * Instances total reports. Peers are as fresh as their last sync.+ */+export async function getFleetRollingCost({ providers = [], now = new Date() } = {}) {+ const { self, peers } = await entriesWithSelf();+ const local = getUsage();+ // This machine always reads its live maps; with no minted identity yet it+ // still has its own history to chart.+ const sources = [+ { id: self?.instanceId ?? 'local', stamp: local?.lastUpdated, daily: local?.dailyActivity },+ ...peers.map((e) => ({ id: e.instanceId, stamp: e.capturedAt, daily: e.usage.dailyActivity })),+ ];++ const span = trailingDays(now, ROLLING_COST_POINTS + ROLLING_COST_WINDOW_DAYS - 1);+ const key = JSON.stringify([span.at(-1), sources.map((s) => [s.id, s.stamp]), providers.map((p) => [p.id, isFreeProvider(p)])]);+ if (rollingMemo?.key === key) return rollingMemo.value;++ const perDay = new Array(span.length).fill(0);+ for (const source of sources) {+ dailyCosts(source.daily, span, providers).forEach((cost, i) => { perDay[i] += cost; });+ }+ let running = perDay.slice(0, ROLLING_COST_WINDOW_DAYS - 1).reduce((a, b) => a + b, 0);+ const points = [];+ for (let i = ROLLING_COST_WINDOW_DAYS - 1; i < span.length; i++) {+ running += perDay[i];+ // Clamp: the add/subtract walk can leave float dust just below zero.+ points.push({ date: span[i], cost: Math.max(0, roundCents(running)) });+ running -= perDay[i - ROLLING_COST_WINDOW_DAYS + 1];+ }+ const value = { windowDays: ROLLING_COST_WINDOW_DAYS, instanceCount: sources.length, points };+ rollingMemo = { key, value };+ return value;+}+/*** Fleet-wide Claude Code tokens per model, priced at API rates, for a window.* One row per instance that has published transcript history (this machinediff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.jsindex 4c2b931204..a3c475267a 100644--- a/server/services/peerUsage.test.js+++ b/server/services/peerUsage.test.js@@ -25,7 +25,7 @@ vi.mock('./usage.js', async () => {return { ...actual, getUsage: () => localUsage };});-const { buildUsageDigest } = await import('./usage.js');+const { buildUsageDigest, buildUsageReport } = await import('./usage.js');const {getUsageSnapshot,getUsageManifest,@@ -33,6 +33,7 @@ const {getFleetUsage,getFleetQuotaEntries,getFleetClaudeCodeModels,+ getFleetRollingCost,forgetInstanceUsage,PEER_USAGE_FILE,} = await import('./peerUsage.js');@@ -472,6 +473,38 @@ describe('fleet report', () => {});});+describe('fleet rolling 30-day cost', () => {+ const dayCost = (usage, day) => buildUsageReport({ [day]: usage.dailyActivity[day] }, { providers: [] }).totals.estimatedCost;++ // Every instance counts — including one marked API-billed, whose spend at API+ // rates is exactly what this chart totals — and a day leaves the window 30+ // days later.+ it('sums every instance over a trailing 30-day window', async () => {+ const peer = peerEntry();+ await applyUsageRemote({ instances: { 'inst-peer': peer } });+ const both = dayCost(localUsage, '2026-08-30') + dayCost(peer.usage, '2026-08-30');+ expect(both).toBeGreaterThan(0);++ const series = await getFleetRollingCost({ providers: [], now: new Date('2026-09-28T12:00:00Z') });+ expect(series.instanceCount).toBe(2);+ expect(series.points).toHaveLength(90);+ const at = (date) => series.points.find((p) => p.date === date).cost;+ expect(series.points.at(-1).date).toBe('2026-09-28');+ expect(at('2026-08-29')).toBe(0);+ expect(at('2026-08-30')).toBeCloseTo(both, 2);+ expect(at('2026-09-28')).toBeCloseTo(both, 2);++ const later = await getFleetRollingCost({ providers: [], now: new Date('2026-09-29T00:00:00Z') });+ expect(later.points.at(-1).cost).toBe(0);+ });++ it('charts this machine alone before any peer has synced', async () => {+ const series = await getFleetRollingCost({ providers: [], now: new Date('2026-09-01T00:00:00Z') });+ expect(series.instanceCount).toBe(1);+ expect(series.points.at(-1).cost).toBeCloseTo(dayCost(localUsage, '2026-08-30'), 2);+ });+});+describe('federated subscription-quota readings', () => {it('publishes this machine\'s readings and advances the LWW stamp past them', async () => {await recordLocalQuotaCards([quotaCard()]);