Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: align monthly usage with fleet costs and stack providers

[._.]/ Adam Eivy309d54a7ac9d
diff --git a/client/src/components/usage/MonthlyUsageCard.jsx b/client/src/components/usage/MonthlyUsageCard.jsx
index c958098bf2..77acee2ea4 100644
--- a/client/src/components/usage/MonthlyUsageCard.jsx
+++ b/client/src/components/usage/MonthlyUsageCard.jsx
@@ -1,47 +1,60 @@
import { ComposedChart, Bar, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { formatCount, formatCompactCount, formatMonthYear, formatUsd } from '../../utils/formatters';
+import { seriesColors } from '../../lib/usageChartColors';
const costColor = 'rgb(var(--port-chart-2))';
-const tokenColor = 'rgb(var(--port-chart-3))';
-const monthLabel = (month) => formatMonthYear(`${month}-01`);
+const tokenColor = 'rgb(var(--port-text))';
+const monthLabel = (month) => formatMonthYear(`${month}-01T00:00:00`);
const compactUsd = (value) => formatUsd(value, { compact: true });
-export default function MonthlyUsageCard({ history: points = [] }) {
+export default function MonthlyUsageCard({ history: points = [], series = [], instanceCount = 1 }) {
+ const colors = seriesColors(series);
return (
<section className="min-w-0 bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3" aria-label="Monthly estimated API cost and tokens">
<h3 className="text-sm font-medium text-gray-400">Monthly estimated API cost &amp; tokens</h3>
<p className="text-xs text-gray-500">
- Last 12 calendar months, independent of the report filter. Bars show this machine’s estimated API cost at the same rates as the cost report.
- {' '}The line shows recorded input, output and cache tokens; counts may include estimates. The current and first recorded months may have partial token history.
+ Last 12 UTC calendar months across {instanceCount > 1 ? `${formatCount(instanceCount)} instances` : 'this machine'}, including Claude Code transcripts, with the same coverage as the rolling chart. Independent of the report filter.
+ {' '}Calendar months differ from a trailing 30-day window. The current and first recorded months may be partial; peer history reflects its last sync. The line includes input, output and cache tokens, including estimates.
</p>
<div className="flex flex-wrap gap-x-5 gap-y-1 text-xs text-gray-400">
- <span style={{ color: costColor }}>■ Est. API cost (USD, left axis)</span>
+ {series.length > 0 ? series.map((provider, i) => (
+ <span key={provider.key} style={{ color: colors[i] }}>■ {provider.label} (USD)</span>
+ )) : <span style={{ color: costColor }}>■ Est. API cost (USD, left axis)</span>}
<span style={{ color: tokenColor }}>━ Tokens (right axis)</span>
</div>
{points.length === 0 ? <p className="text-sm text-gray-500">No monthly usage recorded yet.</p> : <>
- <div className="h-64 min-w-0" role="img" aria-label="Monthly estimated API cost bars with token trend; exact values in the table below">
+ <div className="h-64 min-w-0" role="img" aria-label="Monthly estimated API cost stacked by provider with token trend; exact values in the table below">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={points} margin={{ top: 8, right: 0, bottom: 0, left: 0 }}>
<CartesianGrid stroke="rgb(var(--port-border))" strokeDasharray="3 3" />
<XAxis dataKey="month" tickFormatter={monthLabel} minTickGap={30} tick={{ fontSize: 10 }} />
<YAxis yAxisId="cost" tickFormatter={compactUsd} width={55} tick={{ fontSize: 10 }} domain={[0, 'auto']} />
<YAxis yAxisId="tokens" orientation="right" tickFormatter={formatCompactCount} width={50} tick={{ fontSize: 10 }} domain={[0, 'auto']} />
- <Tooltip labelFormatter={monthLabel} formatter={(value, name) => [name === 'Est. API cost' ? formatUsd(value) : formatCount(value), name]} contentStyle={{ background: 'rgb(var(--port-card))', borderColor: 'rgb(var(--port-border))' }} />
- <Bar yAxisId="cost" dataKey="estimatedCost" name="Est. API cost" fill={costColor} maxBarSize={36} isAnimationActive={false} />
+ <Tooltip labelFormatter={monthLabel} formatter={(value, name, item) => [item.dataKey === 'tokens' ? formatCount(value) : formatUsd(value), name]} contentStyle={{ background: 'rgb(var(--port-card))', borderColor: 'rgb(var(--port-border))' }} />
+ {series.length > 0 ? series.map((provider, i) => (
+ <Bar key={provider.key} yAxisId="cost" dataKey={`values[${i}]`} stackId="cost" name={provider.label} fill={colors[i]} maxBarSize={36} isAnimationActive={false} />
+ )) : <Bar yAxisId="cost" dataKey="estimatedCost" name="Est. API cost" fill={costColor} maxBarSize={36} isAnimationActive={false} />}
<Line yAxisId="tokens" dataKey="tokens" name="Tokens" stroke={tokenColor} strokeWidth={2} dot={{ r: 3 }} isAnimationActive={false} />
</ComposedChart>
</ResponsiveContainer>
</div>
<details className="text-xs text-gray-400">
<summary className="cursor-pointer py-2">Monthly values</summary>
- <table className="w-full text-left tabular-nums">
- <thead><tr><th className="py-2">Month</th><th>Est. cost (USD)</th><th>Tokens</th></tr></thead>
- <tbody>{points.map((point) => <tr key={point.month}>
- <th className="py-2 font-normal">{monthLabel(point.month)}{point.partial ? ' (partial)' : ''}</th>
- <td>{formatUsd(point.estimatedCost)}</td>
- <td>{formatCount(point.tokens)}</td>
- </tr>)}</tbody>
- </table>
+ <div className="overflow-x-auto">
+ <table className="w-full text-left tabular-nums whitespace-nowrap">
+ <thead><tr>
+ <th className="py-2 pr-3">Month</th>
+ {series.map((provider) => <th key={provider.key} className="pr-3">{provider.label} (USD)</th>)}
+ <th className="pr-3">Est. cost (USD)</th><th>Tokens</th>
+ </tr></thead>
+ <tbody>{points.map((point) => <tr key={point.month}>
+ <th className="py-2 pr-3 font-normal">{monthLabel(point.month)}{point.partial ? ' (partial)' : ''}</th>
+ {series.map((provider, i) => <td key={provider.key} className="pr-3">{formatUsd(point.values?.[i])}</td>)}
+ <td className="pr-3">{formatUsd(point.estimatedCost)}</td>
+ <td>{formatCount(point.tokens)}</td>
+ </tr>)}</tbody>
+ </table>
+ </div>
</details>
</>}
</section>
diff --git a/client/src/components/usage/MonthlyUsageCard.test.jsx b/client/src/components/usage/MonthlyUsageCard.test.jsx
index 26cd2b3a41..54d7442e33 100644
--- a/client/src/components/usage/MonthlyUsageCard.test.jsx
+++ b/client/src/components/usage/MonthlyUsageCard.test.jsx
@@ -3,18 +3,21 @@ import { render, screen, within } from '@testing-library/react';
import MonthlyUsageCard from './MonthlyUsageCard';
const history = [
- { month: '2026-09', estimatedCost: 123.45, tokens: 1250000, partial: false },
- { month: '2026-10', estimatedCost: 0, tokens: 0, partial: true },
+ { month: '2026-09', estimatedCost: 123.45, values: [100, 23.45], tokens: 1250000, partial: false },
+ { month: '2026-10', estimatedCost: 0, values: [0, 0], tokens: 0, partial: true },
];
+const series = [{ key: 'claude', label: 'Claude Code' }, { key: 'codex', label: 'Codex' }];
describe('monthly usage', () => {
it('shows each month’s API cost and exact token totals without hover, including zero and partial months', () => {
- render(<MonthlyUsageCard history={history} />);
+ render(<MonthlyUsageCard history={history} series={series} instanceCount={3} />);
expect(screen.getByRole('heading')).toHaveTextContent('Monthly estimated API cost & tokens');
const rows = within(screen.getByRole('table')).getAllByRole('row');
- expect(rows[1]).toHaveTextContent('September 2026$123.451,250,000');
- expect(rows[2]).toHaveTextContent('October 2026 (partial)$0.000');
- expect(screen.getByRole('img')).toHaveAccessibleName(/token trend/);
+ expect(rows[0]).toHaveTextContent('MonthClaude Code (USD)Codex (USD)Est. cost (USD)Tokens');
+ expect(rows[1]).toHaveTextContent('September 2026$100.00$23.45$123.451,250,000');
+ expect(rows[2]).toHaveTextContent('October 2026 (partial)$0.00$0.00$0.000');
+ expect(screen.getByRole('img')).toHaveAccessibleName(/stacked by provider with token trend/);
+ expect(screen.getByText(/3 instances/)).toHaveTextContent('Calendar months differ from a trailing 30-day window');
});
it('shows an empty state when no monthly history is available', () => {
diff --git a/client/src/components/usage/RollingCostCard.jsx b/client/src/components/usage/RollingCostCard.jsx
index 4a67b406f7..d5764f4856 100644
--- a/client/src/components/usage/RollingCostCard.jsx
+++ b/client/src/components/usage/RollingCostCard.jsx
@@ -3,6 +3,7 @@ import useContainerWidth from '../../hooks/useContainerWidth';
import * as api from '../../services/api';
import { formatUsd } from '../../utils/formatters';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
+import { seriesColors } from '../../lib/usageChartColors';
const RANGES = [
{ id: '1m', label: '1M' },
@@ -14,28 +15,6 @@ const RANGES = [
const RANGE_KEY = 'usage:rollingCostRange';
const DEFAULT_RANGE = '3m';
-// Plans keep one color across ranges and reloads; anything else takes the
-// next free palette slot in the server's (largest-first) order.
-const FAMILY_COLORS = {
- claude: 'rgb(var(--port-chart-3))',
- codex: 'rgb(var(--port-chart-2))',
- agy: 'rgb(var(--port-chart-1))',
- grok: 'rgb(var(--port-chart-4))',
-};
-const SPARE_COLORS = ['rgb(var(--port-accent-2))', 'rgb(var(--port-chart-1))', 'rgb(var(--port-chart-2))', 'rgb(var(--port-chart-4))'];
-const OTHER_COLOR = 'rgb(156 163 175)';
-
-export function seriesColors(series) {
- const used = new Set();
- const fixed = series.map((s) => {
- const color = s.key === 'other' ? OTHER_COLOR : FAMILY_COLORS[s.key];
- if (color) used.add(color);
- return color;
- });
- const spare = SPARE_COLORS.filter((c) => !used.has(c));
- return fixed.map((color) => color || spare.shift() || OTHER_COLOR);
-}
-
/** Round axis ticks from zero: 1, 2, 2.5 or 5 × 10^n per step, about four steps. */
export function niceTicks(max, target = 4) {
if (!(max > 0)) return [0, 1];
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 220760096e..f434f01217 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -312,6 +312,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `scopeAdherenceReasons.js` | Re-export of `server/lib/scopeAdherenceReasons.js` — operator-facing labels for a scope-adherence failure code (`SCOPE_ADHERENCE_REASONS`, `SCOPE_ADHERENCE_REASON_FALLBACK`, `scopeAdherenceReasonLabel`). Every label reads as "no advisory", never as a verdict. One definition, no mirror to keep in parity. |
| `jevHeadReasons.js` | Re-export of `server/lib/jevHeadReasons.js` - operator-facing labels for why a trained jev project head cannot be adopted (`JEV_HEAD_BLOCKER_REASONS`, `JEV_HEAD_BLOCKER_FALLBACK`, `jevHeadBlockerLabel`). Each label names WHICH baseline the head lost to, because the stock scorer and the majority class send an operator to different places. One definition, no mirror to keep in parity. |
| `usagePeriods.js` | The report windows every usage-cost surface offers — `USAGE_PERIOD_OPTIONS`, `DEFAULT_USAGE_PERIOD` (what a URL with no `?period` means) and `resolveUsagePeriod`. Shared because `?period` is a URL param the user carries between the Usage and Subscriptions pages; two copies had already disagreed on the default. |
+| `usageChartColors.js` | `seriesColors(series)` — shared provider palette for rolling and monthly usage charts. |
| `usdzExport.js` | AR Quick Look (USDZ) export for the 3D viewer (#5756): `exportSceneToUsdz(scene, { maxTextureSize })` lazy-loads three's `USDZExporter` and serializes the already-decoded scene to bytes, `countSceneTriangles(object3d)` measures an object graph against `AR_TRIANGLE_BUDGET`, and `supportsArQuickLook()` feature-detects the `<a rel="ar">` handoff (Safari on iOS/iPadOS only — never sniff the user agent) so a desktop is offered a download instead of a button that does nothing. `AR_MAX_TEXTURE_SIZE` bounds the file: USDZ stores every texel raw, with no Draco/meshopt equivalent. |
| `installFailureTask.js` | Build the CoS task payload behind the installer-failure "Queue agent to investigate" button (#5981): `buildInstallFailureTask({ label, stage, error, logs, surface })` → `{ description, prompt }` carrying the installer name, failing stage, error text and a bounded log tail, and `installLogTail(logs)` (the `useInstallStream` `{ kind, text }` entries rendered as text, capped at `INSTALL_FAILURE_LOG_TAIL_LINES` / `INSTALL_FAILURE_LOG_TAIL_CHARS` so a 1000-line pip stream cannot push a huge body through `POST /api/cos/tasks`, cutting on a line boundary, redacting the home-directory paths pip/git echo, and neutralizing a log line that would close the prompt fence). Shared by both install modals and `LocalSetupPanel` so every surface queues the same reproducible context. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 8d62da17f8..35f4892235 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -270,6 +270,7 @@ export * from './riggingReasons.js';
export * from './jevHeadReasons.js';
export * from './scopeAdherenceReasons.js';
export * from './usagePeriods.js';
+export * from './usageChartColors.js';
export * from './usdzExport.js';
export * from './eidoverseFrame.js';
export * from './songBookDraft.js';
diff --git a/client/src/lib/usageChartColors.js b/client/src/lib/usageChartColors.js
new file mode 100644
index 0000000000..8ef2d09a5b
--- /dev/null
+++ b/client/src/lib/usageChartColors.js
@@ -0,0 +1,20 @@
+// Keep provider colors consistent across the rolling and calendar-month charts.
+const FAMILY_COLORS = {
+ claude: 'rgb(var(--port-chart-3))',
+ codex: 'rgb(var(--port-chart-2))',
+ agy: 'rgb(var(--port-chart-1))',
+ grok: 'rgb(var(--port-chart-4))',
+};
+const SPARE_COLORS = ['rgb(var(--port-accent-2))', 'rgb(var(--port-chart-1))', 'rgb(var(--port-chart-2))', 'rgb(var(--port-chart-4))'];
+const OTHER_COLOR = 'rgb(156 163 175)';
+
+export function seriesColors(series) {
+ const used = new Set();
+ const fixed = series.map((s) => {
+ const color = s.key === 'other' ? OTHER_COLOR : FAMILY_COLORS[s.key];
+ if (color) used.add(color);
+ return color;
+ });
+ const spare = SPARE_COLORS.filter((c) => !used.has(c));
+ return fixed.map((color) => color || spare.shift() || OTHER_COLOR);
+}
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 645fb2038a..4fdbabcfe4 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -665,7 +665,7 @@ function InternalUsageMetrics() {
<h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>
{/* Trailing 30 days across every instance — independent of the range below. */}
<RollingCostCard />
- <MonthlyUsageCard history={usage.monthlyHistory} />
+ <MonthlyUsageCard history={usage.monthlyHistory} series={usage.monthlySeries} instanceCount={usage.monthlyInstanceCount} />
{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.js
index 0aac956f05..a2d08c4d59 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, usageRollingCostQuerySchema } from '../lib/validation.js';
import { saveSubscriptionCosts, getSubscriptionSavings } from '../services/subscriptionCosts.js';
import { getSubscriptionOverview, savePlanTiers, setSubscriptionEnabled } from '../services/subscriptions.js';
-import { getFleetUsage, getFleetClaudeCodeModels, getFleetRollingCost } from '../services/peerUsage.js';
+import { getFleetUsage, getFleetClaudeCodeModels, getFleetRollingCost, getFleetMonthlyUsage } from '../services/peerUsage.js';
import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';
import { resolveUsageRange } from '../lib/usageRange.js';
import { WAIT } from '../lib/staleWhileRevalidate.js';
@@ -33,14 +33,15 @@ router.get('/', asyncHandler(async (req, res) => {
const result = await getAllProviders();
const providers = Array.isArray(result) ? result : (result?.providers || []);
const summary = usage.getUsageSummary({ from, to, providers });
- // Two independent reads over the same resolved window, so they overlap:
+ // Independent reads overlap; savings and fleet use the report window:
// - savings: what the user's flat-rate plans cost over the SAME window, so
// the headline API-rate figure has something to be compared against.
// - fleet: the per-instance breakdown across the federation, priced over the
// 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([
+ // - monthly: fixed calendar months with the rolling chart's fleet coverage.
+ const [subscriptionSavings, fleet, monthly] = await Promise.all([
getSubscriptionSavings({
report: summary.report,
providers,
@@ -52,8 +53,14 @@ router.get('/', asyncHandler(async (req, res) => {
}),
getApiBilledInstanceIds().then((apiBilledInstanceIds) =>
getFleetUsage({ from, to, providers, apiBilledInstanceIds })),
+ getFleetMonthlyUsage({ providers }),
]);
- res.json({ ...summary, subscriptionSavings, fleet });
+ res.json({
+ ...summary, subscriptionSavings, fleet,
+ monthlyHistory: monthly.history,
+ monthlySeries: monthly.series,
+ monthlyInstanceCount: monthly.instanceCount,
+ });
}));
// GET /api/usage/rolling-cost - Trailing-30-day estimated API cost summed across
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index 8916ff5e5f..1c7bf2ac7e 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -15,6 +15,7 @@ vi.mock('../services/usage.js', () => ({
vi.mock('../services/peerUsage.js', () => ({
getFleetUsage: vi.fn(async () => ({ instances: [], totals: null })),
+ getFleetMonthlyUsage: vi.fn(async () => ({ instanceCount: 1, series: [], history: [] })),
getFleetRollingCost: vi.fn(async () => ({ windowDays: 30, instanceCount: 1, points: [] }))
}));
@@ -59,7 +60,7 @@ import { getProviderQuotas } from '../services/providerUsage.js';
import { getHistoricalUsageBackfillStatus, startHistoricalUsageBackfill } from '../services/usageBackfill.js';
import { getSubscriptionSavings, saveSubscriptionCosts } from '../services/subscriptionCosts.js';
import { getSubscriptionOverview, savePlanTiers, setSubscriptionEnabled } from '../services/subscriptions.js';
-import { getFleetUsage, getFleetRollingCost } from '../services/peerUsage.js';
+import { getFleetUsage, getFleetRollingCost, getFleetMonthlyUsage } from '../services/peerUsage.js';
import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';
import usageRoutes from './usage.js';
@@ -132,7 +133,10 @@ describe('usage routes', () => {
totalSessions: 4,
providers: ['anthropic'],
subscriptionSavings: { configured: false, families: [] },
- fleet: { instances: [], totals: null }
+ fleet: { instances: [], totals: null },
+ monthlyHistory: [],
+ monthlySeries: [],
+ monthlyInstanceCount: 1,
});
const arg = usage.getUsageSummary.mock.calls[0][0];
expect(arg.from).toMatch(/^\d{4}-\d{2}-\d{2}$/);
@@ -143,6 +147,20 @@ describe('usage routes', () => {
expect(getFleetUsage).toHaveBeenCalledWith({ from: arg.from, to: null, providers: [], apiBilledInstanceIds: [] });
});
+ it('GET /api/usage returns fleet monthly history independently of the selected report window', async () => {
+ const monthly = {
+ instanceCount: 2,
+ series: [{ key: 'codex', label: 'Codex' }],
+ history: [{ month: '2026-09', estimatedCost: 12, values: [12], tokens: 1000, partial: false }],
+ };
+ getFleetMonthlyUsage.mockResolvedValueOnce(monthly);
+ usage.getUsageSummary.mockReturnValue({ totalSessions: 4 });
+ const res = await request(buildApp()).get('/api/usage?from=2026-10-01&to=2026-10-02');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ monthlyHistory: monthly.history, monthlySeries: monthly.series, monthlyInstanceCount: 2 });
+ expect(getFleetMonthlyUsage).toHaveBeenCalledWith({ providers: [] });
+ });
+
it('GET /api/usage passes an explicit from/to range through', async () => {
usage.getUsageSummary.mockReturnValue({});
getAllProviders.mockResolvedValue({ activeProvider: 'ollama', providers: [{ id: 'ollama' }] });
diff --git a/server/services/peerUsage.js b/server/services/peerUsage.js
index 166435c979..dd034b16cd 100644
--- a/server/services/peerUsage.js
+++ b/server/services/peerUsage.js
@@ -516,6 +516,16 @@ const addInto = (target, source, scale = 1) => {
for (const [key, cost] of Object.entries(source)) target[key] = (target[key] || 0) + cost * scale;
};
+const reportTokens = (row) => row.tokensIn + row.tokensOut + row.cacheReadTokens + row.cacheWriteTokens;
+
+function dailyUsage(report, labels) {
+ return {
+ costs: costByGroup(report, labels),
+ tokens: reportTokens(report.totals),
+ claudeTokens: report.providers.reduce((sum, row) => sum + ((row.family || familyForProviderId(row.id)) === 'claude' ? reportTokens(row) : 0), 0),
+ };
+}
+
/**
* Estimated API cost per day for one instance over `span`, split by plan, each
* day priced on its own through the same `buildUsageReport` as the cost report
@@ -529,7 +539,7 @@ const addInto = (target, source, scale = 1) => {
* Claude Code use outside PortOS also comes from the instance's transcript
* history (see `withTranscriptClaude`).
*/
-function instanceDailyCosts({ daily = {}, monthly = {}, transcript = {} }, span, providers, labels) {
+function instanceDailyUsage({ daily = {}, monthly = {}, transcript = {} }, span, providers, labels) {
const missingDays = new Map();
for (const day of span) {
const month = day.slice(0, 7);
@@ -543,15 +553,23 @@ function instanceDailyCosts({ daily = {}, monthly = {}, transcript = {} }, span,
const [y, m] = month.split('-').map(Number);
const daysInMonth = new Date(Date.UTC(y, m, 0)).getUTCDate();
const rolledDays = daysInMonth - Object.keys(daily).filter((d) => d.startsWith(`${month}-`)).length;
- const share = {};
- addInto(share, costByGroup(report, labels), 1 / Math.max(rolledDays, count));
- monthShare.set(month, share);
+ const divisor = Math.max(rolledDays, count);
+ const usage = dailyUsage(report, labels);
+ const costs = {};
+ addInto(costs, usage.costs, 1 / divisor);
+ monthShare.set(month, { costs, tokens: usage.tokens / divisor, claudeTokens: usage.claudeTokens / divisor });
}
return span.map((day) => {
- const costs = daily[day]
- ? costByGroup(buildUsageReport({ [day]: daily[day] }, { from: day, to: day, providers }), labels)
- : { ...(monthShare.get(day.slice(0, 7)) || {}) };
- return withTranscriptClaude(costs, transcript?.[day] && summarizeTranscriptDays({ [day]: transcript[day] }).totals.estimatedCost, labels);
+ const usage = daily[day]
+ ? dailyUsage(buildUsageReport({ [day]: daily[day] }, { from: day, to: day, providers }), labels)
+ : monthShare.get(day.slice(0, 7)) || { costs: {}, tokens: 0, claudeTokens: 0 };
+ const transcriptTotals = transcript[day] && summarizeTranscriptDays({ [day]: transcript[day] }).totals;
+ return {
+ costs: withTranscriptClaude({ ...usage.costs }, transcriptTotals?.estimatedCost, labels),
+ // Transcript sessions overlap the Claude ledger; reconcile tokens by the
+ // same per-day maximum as cost, retaining every other provider's tokens.
+ tokens: usage.tokens + Math.max(0, (transcriptTotals?.total || 0) - usage.claudeTokens),
+ };
});
}
@@ -580,23 +598,14 @@ function earliestDay(sources) {
return earliest;
}
-let rollingMemo = null;
-
-/**
- * Rolling 30-day estimated API cost summed across EVERY known instance, one
- * point per UTC day over `range` (see ROLLING_COST_RANGES). 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 = [], range = '3m', now = new Date() } = {}) {
+async function usageHistorySources() {
const { self, peers } = await entriesWithSelf();
const local = getUsage();
// An unreadable transcript store charts PortOS runs only rather than failing.
const localTranscript = await readLocalTranscriptUsage().catch(() => null);
// This machine always reads its live maps; with no minted identity yet it
// still has its own history to chart.
- const sources = [
+ return [
{
id: self?.instanceId ?? 'local',
stamp: [local?.lastUpdated, localTranscript?.updatedAt],
@@ -612,6 +621,74 @@ export async function getFleetRollingCost({ providers = [], range = '3m', now =
transcript: e.claudeCode?.days,
})),
];
+}
+
+function stackCosts(rows, labels) {
+ const totals = {};
+ for (const costs of rows) addInto(totals, costs);
+ const ranked = Object.keys(totals).sort((x, y) => totals[y] - totals[x]);
+ const kept = ranked.length > MAX_COST_GROUPS ? ranked.slice(0, MAX_COST_GROUPS - 1) : ranked;
+ const groupOf = new Map(ranked.map((key) => [key, kept.includes(key) ? key : OTHER_GROUP]));
+ const series = kept.map((key) => ({ key, label: labels.get(key) }));
+ if (kept.length < ranked.length) series.push({ key: OTHER_GROUP, label: 'Other' });
+ const slot = new Map(series.map((g, i) => [g.key, i]));
+ const values = rows.map((costs) => {
+ const row = new Array(series.length).fill(0);
+ for (const [key, cost] of Object.entries(costs)) row[slot.get(groupOf.get(key))] += cost;
+ return row;
+ });
+ return { series, values };
+}
+
+/** Calendar months over the same fleet, ledger and transcript sources as rolling cost. */
+export async function getFleetMonthlyUsage({ providers = [], now = new Date() } = {}) {
+ const sources = await usageHistorySources();
+ const first = earliestDay(sources);
+ if (!first) return { instanceCount: sources.length, series: [], history: [] };
+ const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 11, 1)).getTime();
+ const today = utcDay(now.getTime());
+ const span = Array.from({ length: Math.floor((dayMs(today) - start) / DAY_MS) + 1 }, (_, i) => utcDay(start + i * DAY_MS));
+ const months = new Map();
+ for (const day of span) {
+ if (day < first) continue;
+ const month = day.slice(0, 7);
+ if (!months.has(month)) months.set(month, { month, costs: {}, tokens: 0 });
+ }
+ const labels = new Map();
+ for (const source of sources) {
+ instanceDailyUsage(source, span, providers, labels).forEach((usage, i) => {
+ const month = months.get(span[i].slice(0, 7));
+ if (!month) return;
+ addInto(month.costs, usage.costs);
+ month.tokens += usage.tokens;
+ });
+ }
+ const rows = [...months.values()];
+ const { series, values } = stackCosts(rows.map((row) => row.costs), labels);
+ const history = rows.map((row, i) => {
+ const costs = values[i].map(roundCents);
+ return {
+ month: row.month,
+ estimatedCost: roundCents(costs.reduce((sum, cost) => sum + cost, 0)),
+ values: costs,
+ tokens: Math.round(row.tokens),
+ partial: row.month === today.slice(0, 7) || first > `${row.month}-01`,
+ };
+ });
+ return { instanceCount: sources.length, series, history };
+}
+
+let rollingMemo = null;
+
+/**
+ * Rolling 30-day estimated API cost summed across EVERY known instance, one
+ * point per UTC day over `range` (see ROLLING_COST_RANGES). 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 = [], range = '3m', now = new Date() } = {}) {
+ const sources = await usageHistorySources();
const todayMs = dayMs(utcDay(now.getTime()));
const rangeId = Object.hasOwn(ROLLING_COST_RANGES, range) ? range : '3m';
@@ -628,24 +705,11 @@ export async function getFleetRollingCost({ providers = [], range = '3m', now =
const labels = new Map();
const perDay = span.map(() => ({}));
for (const source of sources) {
- instanceDailyCosts(source, span, providers, labels).forEach((costs, i) => addInto(perDay[i], costs));
+ instanceDailyUsage(source, span, providers, labels).forEach(({ costs }, i) => addInto(perDay[i], costs));
}
- const totals = {};
- for (const costs of perDay) addInto(totals, costs);
- const ranked = Object.keys(totals).sort((x, y) => totals[y] - totals[x]);
- const kept = ranked.length > MAX_COST_GROUPS ? ranked.slice(0, MAX_COST_GROUPS - 1) : ranked;
- const groupOf = new Map(ranked.map((key) => [key, kept.includes(key) ? key : OTHER_GROUP]));
- const series = kept.map((key) => ({ key, label: labels.get(key) }));
- if (kept.length < ranked.length) series.push({ key: OTHER_GROUP, label: 'Other' });
- const slot = new Map(series.map((g, i) => [g.key, i]));
-
// Per-day cost in series order, then a trailing-window sum per slot.
- const daily = perDay.map((costs) => {
- const row = new Array(series.length).fill(0);
- for (const [key, cost] of Object.entries(costs)) row[slot.get(groupOf.get(key))] += cost;
- return row;
- });
+ const { series, values: daily } = stackCosts(perDay, labels);
const running = new Array(series.length).fill(0);
const points = [];
for (let i = 0; i < span.length; i++) {
diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.js
index bfcf60546e..a54b21e74d 100644
--- a/server/services/peerUsage.test.js
+++ b/server/services/peerUsage.test.js
@@ -34,6 +34,7 @@ const {
getFleetQuotaEntries,
getFleetClaudeCodeModels,
getFleetRollingCost,
+ getFleetMonthlyUsage,
forgetInstanceUsage,
PEER_USAGE_FILE,
} = await import('./peerUsage.js');
@@ -574,6 +575,72 @@ describe('fleet rolling 30-day cost', () => {
});
});
+describe('fleet calendar-month usage', () => {
+ it('includes local and peer transcripts and ledgers without counting overlapping Claude sessions twice', async () => {
+ const { atomicWrite } = await import('../lib/fileUtils.js');
+ localUsage = usageFixture({ day: '2026-09-10' });
+ const day = localUsage.dailyActivity['2026-09-10'];
+ day.byProvider = { 'claude-code': day.byProvider.anthropic };
+ localUsage.dailyActivity['2026-09-11'] = structuredClone(day);
+ const counts = (input, output) => ({ messages: 2, input, output, cacheRead: 100, cacheWrite: 20 });
+ await atomicWrite(TRANSCRIPT_USAGE_FILE, {
+ days: { '2026-09-10': { 'claude-opus-5': counts(2000, 4000) }, '2026-09-11': { 'claude-opus-5': counts(1, 1) } },
+ updatedAt: '2026-09-30T00:00:00Z',
+ });
+ const peerUsage = usageFixture({ day: '2026-09-12', tokensOut: 4000 });
+ const peerDay = peerUsage.dailyActivity['2026-09-12'];
+ peerDay.byProvider = { 'codex-cli': peerDay.byProvider.anthropic };
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry({
+ usage: buildUsageDigest(peerUsage),
+ claudeCode: { days: { '2026-09-12': { 'claude-opus-5': counts(7000, 8000) } }, updatedAt: '2026-09-30T00:00:00Z' },
+ }) } });
+
+ const now = new Date('2026-09-30T23:59:59Z');
+ const monthly = await getFleetMonthlyUsage({ now });
+ const rolling = await getFleetRollingCost({ now });
+ expect(monthly.instanceCount).toBe(2);
+ expect(monthly.series.map((row) => row.key).sort()).toEqual(['claude', 'codex']);
+ expect(monthly.history).toHaveLength(1);
+ expect(monthly.history[0]).toMatchObject({ month: '2026-09', tokens: 6120 + 1500 + 4500 + 15120, partial: true });
+ expect(monthly.history[0].estimatedCost).toBe(rolling.points.at(-1).cost);
+ expect(monthly.history[0].values.reduce((sum, cost) => sum + cost, 0)).toBeCloseTo(monthly.history[0].estimatedCost, 2);
+ });
+
+ it('preserves rolled-up months, cache tokens, empty months and the twelve-month limit', async () => {
+ localUsage = usageFixture({ day: '2025-06-01' });
+ localUsage.dailyActivity['2025-06-01'] = { byProvider: { example: { tokensIn: 10, tokensOut: 20, cacheReadTokens: 30, cacheWriteTokens: 40, source: 'measured' } } };
+ localUsage.monthlyActivity = { '2025-04': { tokensIn: 1000000, tokens: 2000000 } };
+ const monthly = await getFleetMonthlyUsage({ now: new Date('2025-06-30T23:59:59Z') });
+ expect(monthly.history).toEqual([
+ { month: '2025-04', estimatedCost: 33, values: [33], tokens: 3000000, partial: false },
+ { month: '2025-05', estimatedCost: 0, values: [0], tokens: 0, partial: false },
+ { month: '2025-06', estimatedCost: 0, values: [0], tokens: 100, partial: true },
+ ]);
+ const later = await getFleetMonthlyUsage({ now: new Date('2026-06-01T00:00:00Z') });
+ expect(later.history).toHaveLength(12);
+ expect(later.history[0].month).toBe('2025-07');
+ expect(later.history.at(-1).month).toBe('2026-06');
+ });
+
+ it('folds smaller providers into Other while retaining free-provider tokens', async () => {
+ localUsage = usageFixture({ day: '2026-09-01' });
+ const bucket = localUsage.dailyActivity['2026-09-01'];
+ bucket.byProvider = Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`example-${i}`, { tokensOut: (i + 1) * 1000000 }]));
+ bucket.byProvider.ollama = { tokensOut: 5000000 };
+ bucket.tokens = 26000000;
+ const monthly = await getFleetMonthlyUsage({ now: new Date('2026-09-30T00:00:00Z'), providers: [{ id: 'ollama', type: 'ollama' }] });
+ expect(monthly.series).toHaveLength(5);
+ expect(monthly.series.at(-1)).toEqual({ key: 'other', label: 'Other' });
+ expect(monthly.history[0]).toMatchObject({ estimatedCost: 315, tokens: 26000000 });
+ expect(monthly.history[0].values.reduce((sum, cost) => sum + cost, 0)).toBe(315);
+ });
+
+ it('returns empty history before any usage is recorded', async () => {
+ localUsage = { dailyActivity: {}, monthlyActivity: {}, lastUpdated: null };
+ expect(await getFleetMonthlyUsage()).toEqual({ instanceCount: 1, series: [], history: [] });
+ });
+});
+
describe('federated subscription-quota readings', () => {
it('publishes this machine\'s readings and advances the LWW stamp past them', async () => {
await recordLocalQuotaCards([quotaCard()]);
diff --git a/server/services/usage.js b/server/services/usage.js
index 3c55679022..eb543dea65 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -1132,31 +1132,6 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
};
}
-/** Calendar-month ledger totals, independent of the report filter. */
-function monthlyUsageHistory(providers) {
- const today = new Date().toISOString().slice(0, 10);
- const firstDay = getFirstActivityDay();
- if (!firstDay) return [];
- const now = new Date(`${today}T00:00:00Z`);
- return Array.from({ length: 12 }, (_, index) => {
- const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 11 + index, 1));
- const month = start.toISOString().slice(0, 7);
- const end = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).toISOString().slice(0, 10);
- if (end < firstDay) return null;
- const { totals } = buildUsageReport(usageData.dailyActivity, {
- from: `${month}-01`, to: end < today ? end : today,
- monthlyActivity: usageData.monthlyActivity, providers,
- });
- return {
- month,
- estimatedCost: totals.estimatedCost,
- tokens: totals.tokensIn + totals.tokensOut + totals.cacheReadTokens + totals.cacheWriteTokens,
- source: totals.source,
- partial: month === today.slice(0, 7) || firstDay > `${month}-01`,
- };
- }).filter(Boolean);
-}
-
/**
* Get usage summary. Optional `range` selects the cost-report window:
* `{ from, to }` as inclusive YYYY-MM-DD strings (null = unbounded), plus the
@@ -1180,7 +1155,6 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})
}
return {
...empty,
- monthlyHistory: [],
last7Days,
estimatedCost: 0,
topProviders: [],
@@ -1249,7 +1223,6 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})
.sort((a, b) => b.sessions - a.sessions)
.slice(0, 5),
report,
- monthlyHistory: monthlyUsageHistory(providers),
// Free-tier counterpart of the paid cost report: the report rows already
// free-classified (local inference, Zen quota), plus the observed limit
// blocks with ledger volume since each — the estimated-quota signal for
diff --git a/server/services/usage.test.js b/server/services/usage.test.js
index 4099a846e9..5051f5fec6 100644
--- a/server/services/usage.test.js
+++ b/server/services/usage.test.js
@@ -75,21 +75,6 @@ describe('usage.js — summary', () => {
vi.useRealTimers();
});
- it('reports calendar months independently of the filter, preserving rollups and cache tokens', async () => {
- vi.setSystemTime(new Date('2025-06-30T23:59:59Z'));
- readJSONFile.mockResolvedValueOnce(makeUsage({
- '2025-06-01': { byProvider: { example: { tokensIn: 10, tokensOut: 20, cacheReadTokens: 30, cacheWriteTokens: 40, source: 'measured' } } },
- '2025-06-10': { tokens: 5 },
- }, { monthlyActivity: { '2025-04': { tokensIn: 1000000, tokens: 2000000 } } }));
- await loadUsage();
- const history = getUsageSummary({ from: '2025-06-10', to: '2025-06-11' }).monthlyHistory;
- expect(history).toEqual([
- { month: '2025-04', estimatedCost: 33, tokens: 3000000, source: 'estimate', partial: false },
- { month: '2025-05', estimatedCost: 0, tokens: 0, source: 'estimate', partial: false },
- { month: '2025-06', estimatedCost: 0, tokens: 105, source: 'mixed', partial: true },
- ]);
- });
-
describe('summary structure', () => {
it('returns all expected fields with correct types', async () => {
readJSONFile.mockResolvedValueOnce(makeUsage({}, {