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

Usage: stacked, pinnable cost chart with a Y axis and range picker (#12942)

[._.]/26a8682a7981
diff --git a/client/src/components/usage/RollingCostCard.jsx b/client/src/components/usage/RollingCostCard.jsx
index 54ff317b33..4a67b406f7 100644
--- a/client/src/components/usage/RollingCostCard.jsx
+++ b/client/src/components/usage/RollingCostCard.jsx
@@ -1,73 +1,317 @@
-import { useState } from 'react';
-import { countSparklineGeometry } from '../../lib/editorialHealth';
+import { useEffect, useMemo, useState } from 'react';
+import useContainerWidth from '../../hooks/useContainerWidth';
+import * as api from '../../services/api';
import { formatUsd } from '../../utils/formatters';
+import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
-const WIDTH = 300;
-const HEIGHT = 96;
-const PAD = 2;
+const RANGES = [
+ { id: '1m', label: '1M' },
+ { id: '3m', label: '3M' },
+ { id: '6m', label: '6M' },
+ { id: '1y', label: '1Y' },
+ { id: 'all', label: 'All' },
+];
+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];
+ const rough = max / target;
+ const magnitude = 10 ** Math.floor(Math.log10(rough));
+ const step = [1, 2, 2.5, 5, 10].map((m) => m * magnitude).find((s) => s >= rough);
+ const top = Math.ceil(max / step) * step;
+ return Array.from({ length: Math.round(top / step) + 1 }, (_, i) => Math.round(i * step * 100) / 100);
+}
// 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' });
+const compactUsd = (v) => formatUsd(v, { compact: true });
+
+// Pin labels are 10px tabular text; their width is estimated from length so
+// the row layout runs before paint. Overlapping labels move down a row.
+const labelWidthPx = (text) => text.length * 5.8 + 10;
+const LABEL_GAP_PX = 4;
+const MAX_LABEL_ROWS = 4;
+// A tap this close to an existing pin removes it rather than adding a neighbor.
+const UNPIN_SLOP_PX = 14;
/**
- * 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.
+ * Trailing-30-day estimated API cost summed across every instance, stacked by
+ * plan, one point per day over a chosen range. Tap to pin a day (date and
+ * total); tap a pin to remove it. The legend reads the newest pin, else today.
+ * Hand-drawn SVG.
*/
-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)));
+export default function RollingCostCard() {
+ const [range, setRange] = useState(() => {
+ const saved = safeReadStorage(RANGE_KEY);
+ return RANGES.some((r) => r.id === saved) ? saved : DEFAULT_RANGE;
+ });
+ // undefined = loading, null = the read failed
+ const [data, setData] = useState(undefined);
+ const [pins, setPins] = useState([]);
+ // Keyboard cursor (a point index): arrows move it, Enter/Space pins it.
+ const [cursor, setCursor] = useState(null);
+ const [plotRef, plotWidth] = useContainerWidth();
+
+ useEffect(() => {
+ let cancelled = false;
+ api.getUsageRollingCost({ range }, { silent: true })
+ .catch(() => null)
+ .then((result) => { if (!cancelled) setData(result); });
+ return () => { cancelled = true; };
+ }, [range]);
+
+ const chooseRange = (id) => {
+ setRange(id);
+ safeWriteStorage(RANGE_KEY, id);
};
+ const points = data?.points || [];
+ const series = data?.series || [];
+ const colors = useMemo(() => seriesColors(series), [series]);
+ const ticks = useMemo(() => niceTicks(Math.max(0, ...points.map((p) => p.cost))), [points]);
+ const top = ticks.at(-1);
+
+ const indexByDate = useMemo(() => new Map(points.map((p, i) => [p.date, i])), [points]);
+ const xPct = (i) => (points.length > 1 ? (i / (points.length - 1)) * 100 : 0);
+ const yPct = (v) => 100 - (v / top) * 100;
+
+ // Each plan's band sits on the sum of the plans below it.
+ const areas = useMemo(() => {
+ const x = (i) => (i / Math.max(1, points.length - 1)) * 100;
+ const y = (v) => 100 - (v / top) * 100;
+ const below = points.map(() => 0);
+ return series.map((_, j) => {
+ const lower = [...below];
+ points.forEach((p, i) => { below[i] += p.values?.[j] || 0; });
+ const upperPath = points.map((_, i) => `${i ? 'L' : 'M'}${x(i)},${y(below[i])}`).join('');
+ const lowerPath = points.map((_, i) => i).reverse().map((i) => `L${x(i)},${y(lower[i])}`).join('');
+ return `${upperPath}${lowerPath}Z`;
+ });
+ }, [points, series, top]);
+
+ if (data === null) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-sm text-gray-500">
+ Couldn&rsquo;t read the rolling API cost.
+ </div>
+ );
+ }
+
+ const visiblePins = pins.filter((date) => indexByDate.has(date));
+ const focusDate = visiblePins.at(-1) ?? points.at(-1)?.date;
+ const focus = points[indexByDate.get(focusDate)];
+ const today = points.at(-1);
+
+ const togglePin = (event) => {
+ const box = plotRef.current?.getBoundingClientRect();
+ if (!box?.width || points.length < 2) return;
+ const px = event.clientX - box.left;
+ const nearest = visiblePins
+ .map((date) => ({ date, gap: Math.abs((xPct(indexByDate.get(date)) / 100) * box.width - px) }))
+ .sort((a, b) => a.gap - b.gap)[0];
+ if (nearest && nearest.gap <= UNPIN_SLOP_PX) {
+ setPins((prev) => prev.filter((d) => d !== nearest.date));
+ return;
+ }
+ pinIndex(Math.round(Math.min(1, Math.max(0, px / box.width)) * (points.length - 1)));
+ };
+
+ function pinIndex(index) {
+ const date = points[index].date;
+ setPins((prev) => (prev.includes(date) && cursor === index
+ ? prev.filter((d) => d !== date)
+ : [...prev.filter((d) => d !== date), date]));
+ }
+
+ const onKeyDown = (event) => {
+ const last = points.length - 1;
+ const at = cursor ?? last;
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
+ event.preventDefault();
+ setCursor(Math.min(last, Math.max(0, at + (event.key === 'ArrowLeft' ? -1 : 1))));
+ } else if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ setCursor(at);
+ pinIndex(at);
+ }
+ };
+
+ // Stack labels left to right, centered on their pin unless that would run
+ // off an edge; one that would overlap the previous label in its row drops to
+ // the next row.
+ const width = plotWidth || 300;
+ const rowEnds = [];
+ const labels = [...visiblePins]
+ .sort((a, b) => indexByDate.get(a) - indexByDate.get(b))
+ .map((date) => {
+ const index = indexByDate.get(date);
+ const x = xPct(index);
+ const text = `${dayLabel(date)} · ${compactUsd(points[index].cost)}`;
+ const w = labelWidthPx(text);
+ const px = (x / 100) * width;
+ const align = px - w / 2 < 0 ? 'left' : px + w / 2 > width ? 'right' : 'center';
+ const left = align === 'left' ? px : align === 'right' ? px - w : px - w / 2;
+ let row = rowEnds.findIndex((end) => end + LABEL_GAP_PX <= left);
+ if (row === -1) row = rowEnds.length < MAX_LABEL_ROWS ? rowEnds.length : rowEnds.indexOf(Math.min(...rowEnds));
+ rowEnds[row] = left + w;
+ return { date, index, x, row, text, align };
+ });
+
return (
- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-2">
+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3">
<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>
+ <h3 className="text-sm font-medium text-gray-400">Est. API cost, rolling {data?.windowDays || 30} days</h3>
+ {data && (
+ <p className="text-[10px] sm:text-xs text-gray-500">
+ {data.instanceCount > 1 ? `${data.instanceCount} 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 className="text-xl font-bold text-port-success tabular-nums">{today ? formatUsd(today.cost) : '—'}</div>
+ <div className="text-[10px] sm:text-xs text-gray-500">Today</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 className="flex gap-1" role="group" aria-label="Chart range">
+ {RANGES.map((r) => (
+ <button
+ key={r.id}
+ type="button"
+ onClick={() => chooseRange(r.id)}
+ aria-pressed={range === r.id}
+ className={`min-h-9 px-3 rounded-full text-xs border ${range === r.id
+ ? 'bg-port-accent/20 border-port-accent text-white'
+ : 'border-port-border text-gray-400 hover:text-white'}`}
+ >
+ {r.label}
+ </button>
+ ))}
</div>
+
+ {points.length < 2 ? (
+ <div className="h-40 sm:h-48 flex items-center justify-center text-sm text-gray-500">
+ {data === undefined ? 'Loading…' : 'No usage in this range.'}
+ </div>
+ ) : (
+ <>
+ <div className="flex gap-1 pt-1">
+ <div className="relative w-11 shrink-0 h-40 sm:h-48" aria-hidden="true">
+ {ticks.map((t) => (
+ <span
+ key={t}
+ className="absolute right-0 -translate-y-1/2 text-[10px] text-gray-500 tabular-nums"
+ style={{ top: `${yPct(t)}%` }}
+ >
+ {compactUsd(t)}
+ </span>
+ ))}
+ </div>
+ <div
+ ref={plotRef}
+ className="relative flex-1 h-40 sm:h-48 cursor-crosshair select-none focus:outline-none focus-visible:ring-1 focus-visible:ring-port-accent"
+ role="group"
+ tabIndex={0}
+ aria-label="Tap a day to pin it; arrow keys and Enter pin from the keyboard"
+ onClick={togglePin}
+ onKeyDown={onKeyDown}
+ onBlur={() => setCursor(null)}
+ >
+ <svg
+ viewBox="0 0 100 100"
+ preserveAspectRatio="none"
+ className="absolute inset-0 w-full h-full overflow-visible"
+ role="img"
+ aria-label={`Rolling ${data.windowDays}-day estimated API cost from ${dayLabel(points[0].date)} to ${dayLabel(today.date)}, now ${formatUsd(today.cost)}`}
+ >
+ {ticks.map((t) => (
+ <line key={t} x1="0" x2="100" y1={yPct(t)} y2={yPct(t)} className="stroke-port-border" strokeWidth="1" vectorEffect="non-scaling-stroke" />
+ ))}
+ {areas.map((d, j) => (
+ <path key={series[j].key} d={d} style={{ fill: colors[j] }} fillOpacity="0.75" stroke={colors[j]} strokeWidth="1" vectorEffect="non-scaling-stroke" />
+ ))}
+ {cursor !== null && points[cursor] && (
+ <line x1={xPct(cursor)} x2={xPct(cursor)} y1="0" y2="100" className="stroke-port-accent" strokeWidth="1" vectorEffect="non-scaling-stroke" />
+ )}
+ {labels.map((l) => (
+ <line key={l.date} x1={l.x} x2={l.x} y1="0" y2="100" className="stroke-gray-400" strokeWidth="1" vectorEffect="non-scaling-stroke" strokeDasharray="3 3" />
+ ))}
+ </svg>
+ {labels.map((l) => (
+ <span
+ key={l.date}
+ className="absolute w-2 h-2 -ml-1 -mt-1 rounded-full bg-gray-400 pointer-events-none"
+ style={{ left: `${l.x}%`, top: `${yPct(points[l.index].cost)}%` }}
+ />
+ ))}
+ {labels.map((l) => (
+ <span
+ key={l.date}
+ className="absolute whitespace-nowrap rounded border border-port-border bg-port-card/90 px-1 text-[10px] text-white tabular-nums pointer-events-none"
+ style={{
+ left: `${l.x}%`,
+ top: l.row * 18,
+ transform: { left: 'none', right: 'translateX(-100%)', center: 'translateX(-50%)' }[l.align],
+ }}
+ >
+ {l.text}
+ </span>
+ ))}
+ </div>
+ </div>
+ <div className="flex justify-between items-center pl-12 text-[10px] sm:text-xs text-gray-500">
+ <span>{dayLabel(points[0].date)}</span>
+ {visiblePins.length > 0 && (
+ <button type="button" onClick={() => setPins([])} className="min-h-9 px-2 hover:text-white">
+ Clear pins
+ </button>
+ )}
+ <span>Today</span>
+ </div>
+ </>
+ )}
+
+ {focus && series.length > 0 && (
+ <div className="space-y-1">
+ <div className="text-[10px] sm:text-xs text-gray-500">{focusDate === today?.date ? 'Today' : dayLabel(focusDate)}</div>
+ <ul className="grid grid-cols-2 sm:grid-cols-3 gap-x-3 gap-y-1 text-xs">
+ {series.map((s, j) => (
+ <li key={s.key} className="flex items-center gap-1.5 min-w-0">
+ <span className="w-2.5 h-2.5 rounded-sm shrink-0" style={{ background: colors[j] }} />
+ <span className="truncate text-gray-300">{s.label}</span>
+ <span className="ml-auto tabular-nums text-white">{formatUsd(focus.values?.[j])}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
</div>
);
}
diff --git a/client/src/components/usage/RollingCostCard.test.jsx b/client/src/components/usage/RollingCostCard.test.jsx
index a3d386fdd8..298ae808d0 100644
--- a/client/src/components/usage/RollingCostCard.test.jsx
+++ b/client/src/components/usage/RollingCostCard.test.jsx
@@ -1,32 +1,82 @@
-import { describe, expect, it } from 'vitest';
-import { fireEvent, render, screen } from '@testing-library/react';
-import RollingCostCard from './RollingCostCard';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import RollingCostCard, { niceTicks } from './RollingCostCard';
-const rollingCost = {
+const api = vi.hoisted(() => ({ getUsageRollingCost: vi.fn() }));
+vi.mock('../../services/api', () => api);
+
+const payload = {
+ range: '3m',
windowDays: 30,
instanceCount: 3,
+ series: [{ key: 'claude', label: 'Claude Code' }, { key: 'codex', label: 'Codex' }],
points: [
- { date: '2026-10-20', cost: 10 },
- { date: '2026-10-21', cost: 25.5 },
- { date: '2026-10-22', cost: 40.25 },
+ { date: '2026-10-20', cost: 10, values: [6, 4] },
+ { date: '2026-10-21', cost: 25.5, values: [20, 5.5] },
+ { date: '2026-10-22', cost: 40.25, values: [30, 10.25] },
],
};
+beforeEach(() => {
+ localStorage.clear();
+ api.getUsageRollingCost.mockReset().mockResolvedValue(payload);
+});
+
+const plot = () => screen.getByRole('group', { name: /pin/ });
+const tapAt = (clientX) => {
+ plot().getBoundingClientRect = () => ({ left: 0, width: 300, top: 0, height: 160 });
+ fireEvent.click(plot(), { clientX });
+};
+
describe('RollingCostCard', () => {
- it('headlines today and reads a tapped day', () => {
- render(<RollingCostCard rollingCost={rollingCost} />);
- expect(screen.getByText('$40.25')).toBeTruthy();
+ it('stacks plans with a legend and pins tapped days until tapped again', async () => {
+ render(<RollingCostCard />);
+ await screen.findByText('$40.25');
expect(screen.getByText('3 instances')).toBeTruthy();
+ expect(screen.getByText('Claude Code')).toBeTruthy();
+ expect(screen.getByText('$10.25')).toBeTruthy();
+
+ tapAt(150);
+ expect(screen.getByText('Oct 21 · $25.5')).toBeTruthy();
+ // The legend follows the newest pin.
+ expect(screen.getByText('$5.50')).toBeTruthy();
+ tapAt(0);
+ expect(screen.getByText('Oct 20 · $10')).toBeTruthy();
+ expect(screen.getByText('Oct 21 · $25.5')).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();
+ tapAt(152);
+ expect(screen.queryByText('Oct 21 · $25.5')).toBeNull();
+ expect(screen.getByText('Oct 20 · $10')).toBeTruthy();
});
- it('renders nothing without a series', () => {
- const { container } = render(<RollingCostCard rollingCost={{ points: [] }} />);
- expect(container.innerHTML).toBe('');
+ it('pins from the keyboard', async () => {
+ render(<RollingCostCard />);
+ await screen.findByText('$40.25');
+ const group = screen.getByRole('group', { name: /pin/ });
+ fireEvent.keyDown(group, { key: 'ArrowLeft' });
+ fireEvent.keyDown(group, { key: 'Enter' });
+ expect(screen.getByText('Oct 21 · $25.5')).toBeTruthy();
+ fireEvent.keyDown(group, { key: 'Enter' });
+ expect(screen.queryByText('Oct 21 · $25.5')).toBeNull();
+ });
+
+ it('remembers the chosen range', async () => {
+ const { unmount } = render(<RollingCostCard />);
+ await screen.findByText('$40.25');
+ expect(api.getUsageRollingCost).toHaveBeenLastCalledWith({ range: '3m' }, { silent: true });
+ fireEvent.click(screen.getByRole('button', { name: '1Y' }));
+ await waitFor(() => expect(api.getUsageRollingCost).toHaveBeenLastCalledWith({ range: '1y' }, { silent: true }));
+ unmount();
+
+ render(<RollingCostCard />);
+ await screen.findByText('$40.25');
+ expect(api.getUsageRollingCost).toHaveBeenLastCalledWith({ range: '1y' }, { silent: true });
+ });
+});
+
+describe('niceTicks', () => {
+ it('rounds the axis top up to a friendly step from zero', () => {
+ expect(niceTicks(9428.45)).toEqual([0, 2500, 5000, 7500, 10000]);
+ expect(niceTicks(0)).toEqual([0, 1]);
});
});
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index d59c23be8a..b271681b93 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -657,7 +657,7 @@ function InternalUsageMetrics() {
<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} />
+ <RollingCostCard />
{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/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsx
index 75f1526783..79843a389f 100644
--- a/client/src/pages/UsagePage.test.jsx
+++ b/client/src/pages/UsagePage.test.jsx
@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({
getProviderUsage: vi.fn(),
getUsage: vi.fn(),
getUsageBackfillStatus: vi.fn(),
+ getUsageRollingCost: vi.fn(() => Promise.resolve({ windowDays: 30, instanceCount: 1, series: [], points: [] })),
startUsageBackfill: vi.fn(),
updateSubscriptionCosts: vi.fn()
}));
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 20495d6387..f6a6ae06f2 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -68,7 +68,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` | Atomic partial settings saves (`patchSettingsSlice`, server-queued PATCH with no browser GET/merge), 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 (`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. |
+| `apiSystem.js` | Atomic partial settings saves (`patchSettingsSlice`, server-queued PATCH with no browser GET/merge), 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 (`getUsage`, `getClaudeCodeModelUsage` (per-model token totals for all local Claude Code use, from CLI transcripts), `getUsageRollingCost` (trailing-30-day API cost across every instance, stacked by plan), `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.js
index c9339751b7..e318cf2629 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -239,6 +239,10 @@ export const getUsage = (params = {}, options = {}) => request(`/usage${usageQue
// from the CLI transcripts. Same { period } | { from, to } params as getUsage.
export const getClaudeCodeModelUsage = (params = {}, options = {}) =>
request(`/usage/claude-code/models${usageQuery(params)}`, options);
+// Trailing-30-day estimated API cost across every instance, stacked by plan.
+// `range` is the chart span: 1m|3m|6m|1y|all.
+export const getUsageRollingCost = (params = {}, options = {}) =>
+ request(`/usage/rolling-cost${usageQuery(params)}`, options);
export const getUsageBackfillStatus = (options = {}) => request('/usage/backfill', options);
// Monthly plan prices per provider family, used to compare subscription spend
// against the report's estimated API cost. `costs` is a partial patch: an
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index a26e0ddacb..0eab68dce9 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -368,6 +368,7 @@ export function formatCompactCountOrDash(n) {
// currency anchor, so there is nothing for its separators to contradict.
const GROUPED_INTEGER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });
const USD_CENTS = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+const USD_COMPACT = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 });
/**
* Thousands-separated count for a number the user is meant to read exactly:
@@ -462,15 +463,16 @@ export function formatPercent(value, { decimals = 1, fallback = '—' } = {}) {
* `trimWhole` drops the `.00` on a round figure — for a price the user typed
* ($200/mo), not for a computed total, where aligned cents are the point.
* Amounts past a thousand are grouped (`$4,610.09`) — an unseparated `$4610.09`
- * is read as the wrong order of magnitude at a glance.
+ * is read as the wrong order of magnitude at a glance. `compact` abbreviates
+ * (`$9.4K`) for chart axes and labels where width is tight.
*
* @param {number} value - Dollar amount (nullish renders as $0.00; a non-nullish
* value that fails to parse as a finite number — NaN, a broken calc — renders
* `fallback` instead, so a computation failure never masquerades as "$0.00")
- * @param {{ signed?: boolean, trimWhole?: boolean, fallback?: string, maximumFractionDigits?: number }} [options]
+ * @param {{ signed?: boolean, trimWhole?: boolean, compact?: boolean, fallback?: string, maximumFractionDigits?: number }} [options]
* @returns {string} e.g. "$12.34", "-$5.00", "$200"
*/
-export function formatUsd(value, { signed = false, trimWhole = false, fallback = '—', maximumFractionDigits = 2 } = {}) {
+export function formatUsd(value, { signed = false, trimWhole = false, compact = false, fallback = '—', maximumFractionDigits = 2 } = {}) {
const n = value === null || value === undefined ? 0 : Number(value);
if (!Number.isFinite(n)) return fallback;
// Anything under half a cent renders as zero, and Intl signs it (`-$0.00`)
@@ -480,7 +482,7 @@ export function formatUsd(value, { signed = false, trimWhole = false, fallback =
const raw = signed ? Math.abs(n) : n;
const precision = Number.isInteger(maximumFractionDigits) ? Math.max(2, Math.min(8, maximumFractionDigits)) : 2;
const magnitude = Math.abs(raw) < 0.5 * 10 ** -precision ? 0 : raw;
- const body = trimWhole && Number.isInteger(magnitude)
+ const body = compact ? USD_COMPACT.format(magnitude) : trimWhole && Number.isInteger(magnitude)
? GROUPED_INTEGER.format(magnitude)
: precision === 2 ? USD_CENTS.format(magnitude) : new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: precision }).format(magnitude);
return `${signed && n < 0 && magnitude !== 0 ? '-' : ''}$${body}`;
diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.js
index 5891085026..651035b8ab 100644
--- a/client/src/utils/formatters.test.js
+++ b/client/src/utils/formatters.test.js
@@ -111,6 +111,7 @@ describe('formatWeight', () => {
describe('formatUsd', () => {
it('renders cents by default and treats a missing amount as zero', () => {
expect(formatUsd(12.3)).toBe('$12.30');
+ expect(formatUsd(9428.45, { compact: true })).toBe('$9.4K');
expect(formatUsd(null)).toBe('$0.00');
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 2302f01deb..06c083d650 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1606,6 +1606,11 @@ export const usageQuerySchema = z.object({
to: isoDay.optional()
}).refine((q) => !(q.from && q.to) || q.from <= q.to, { message: 'from must be on or before to' });
+/** Query for GET /api/usage/rolling-cost — the chart's span, independent of the report window. */
+export const usageRollingCostQuerySchema = z.object({
+ range: z.enum(['1m', '3m', '6m', '1y', 'all']).optional()
+});
+
/** Query for GET /api/usage/providers. `family` narrows the read to a single
* quota card (the per-card Refresh on the usage page) so one slow TUI scrape
* isn't paid for every provider at once. */
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 039224a951..0aac956f05 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -5,7 +5,7 @@ import { refreshLocalTranscriptUsage } from '../services/claudeCodeTranscriptUsa
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 { 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';
@@ -40,9 +40,7 @@ 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".
- // - 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([
+ const [subscriptionSavings, fleet] = await Promise.all([
getSubscriptionSavings({
report: summary.report,
providers,
@@ -54,9 +52,17 @@ router.get('/', asyncHandler(async (req, res) => {
}),
getApiBilledInstanceIds().then((apiBilledInstanceIds) =>
getFleetUsage({ from, to, providers, apiBilledInstanceIds })),
- getFleetRollingCost({ providers }),
]);
- res.json({ ...summary, subscriptionSavings, fleet, rollingCost });
+ res.json({ ...summary, subscriptionSavings, fleet });
+}));
+
+// GET /api/usage/rolling-cost - Trailing-30-day estimated API cost summed across
+// every instance, one point per day over ?range=1m|3m|6m|1y|all (default 3m).
+router.get('/rolling-cost', asyncHandler(async (req, res) => {
+ const { range } = validateRequest(usageRollingCostQuerySchema, req.query);
+ const result = await getAllProviders();
+ const providers = Array.isArray(result) ? result : (result?.providers || []);
+ res.json(await getFleetRollingCost({ providers, range }));
}));
// GET /api/usage/subscriptions - The Subscriptions page's own model: one row
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index 99e301cdb8..8916ff5e5f 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -59,7 +59,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 } from '../services/peerUsage.js';
+import { getFleetUsage, getFleetRollingCost } from '../services/peerUsage.js';
import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';
import usageRoutes from './usage.js';
@@ -117,6 +117,13 @@ describe('usage routes', () => {
expect(res.body).toEqual({ hourlyActivity: Array(24).fill(0) });
});
+ it('GET /api/usage/rolling-cost passes the chart range through and refuses an unknown one', async () => {
+ const app = buildApp();
+ expect((await request(app).get('/api/usage/rolling-cost?range=1y')).status).toBe(200);
+ expect(getFleetRollingCost).toHaveBeenCalledWith({ providers: [], range: '1y' });
+ expect((await request(app).get('/api/usage/rolling-cost?range=5y')).status).toBe(400);
+ });
+
it('GET /api/usage returns the usage summary with the default 7d range', async () => {
usage.getUsageSummary.mockReturnValue({ totalSessions: 4, providers: ['anthropic'] });
const res = await request(buildApp()).get('/api/usage');
@@ -125,8 +132,7 @@ describe('usage routes', () => {
totalSessions: 4,
providers: ['anthropic'],
subscriptionSavings: { configured: false, families: [] },
- fleet: { instances: [], totals: null },
- rollingCost: { windowDays: 30, instanceCount: 1, points: [] }
+ fleet: { instances: [], totals: null }
});
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.js
index 0baeddf421..6f8c1a5745 100644
--- a/server/services/peerUsage.js
+++ b/server/services/peerUsage.js
@@ -34,6 +34,7 @@ import { mergeTombstones, normalizeTombstones, recordTombstone, isTombstoned } f
import { canonicalSnapshotChecksum } from '../lib/snapshotChecksum.js';
import { roundCents } from '../lib/subscriptionSavings.js';
import { isFreeProvider } from '../lib/modelPricing.js';
+import { familyForProviderId, familyLabel } from '../lib/providerFamilies.js';
import { sanitizeQuotaCards } from '../lib/fleetQuotas.js';
import { buildUsageDigest, buildUsageReport, getUsage, USAGE_FILE } from './usage.js';
import { readLocalQuotaCards, PROVIDER_QUOTAS_FILE } from './providerQuotaShare.js';
@@ -482,66 +483,145 @@ export async function getFleetUsage({ from = null, to = null, providers = [], ap
return { 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;
+// Points shown per range. `all` starts at the earliest day any instance has.
+export const ROLLING_COST_RANGES = { '1m': 30, '3m': 90, '6m': 182, '1y': 365, all: null };
-const utcDay = (date) => date.toISOString().slice(0, 10);
+const DAY_MS = 86_400_000;
+const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
+const dayMs = (day) => Date.parse(`${day}T00:00:00Z`);
-/** 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)));
+// Stacked groups beyond this many fold into "Other" so the legend stays short.
+const MAX_COST_GROUPS = 5;
+const OTHER_GROUP = 'other';
+
+/**
+ * A report's cost split by plan: a provider row belongs to its subscription
+ * family when it has one (a peer's provider may not be configured here, so the
+ * id is tried too), else it stands alone under its own name.
+ */
+function costByGroup(report, labels) {
+ const out = {};
+ for (const row of report.providers) {
+ if (!(row.estimatedCost > 0)) continue;
+ const family = row.family || familyForProviderId(row.id);
+ const key = family || `provider:${row.id}`;
+ if (!labels.has(key)) labels.set(key, family ? familyLabel(family) : row.name || row.id);
+ out[key] = (out[key] || 0) + row.estimatedCost;
+ }
+ return out;
}
+const addInto = (target, source, scale = 1) => {
+ for (const [key, cost] of Object.entries(source)) target[key] = (target[key] || 0) + cost * scale;
+};
+
/**
- * 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.
+ * 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
+ * so the series and the headline agree.
+ *
+ * Old days survive only as month buckets (a peer's digest rolls up after 120
+ * days, this machine's history after 400), so a month bucket's cost is spread
+ * evenly over that month's days that no longer have a day bucket. The month's
+ * total is exact; its shape within the month is not.
*/
-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;
+function instanceDailyCosts({ daily = {}, monthly = {} }, span, providers, labels) {
+ const missingDays = new Map();
+ for (const day of span) {
+ const month = day.slice(0, 7);
+ if (!daily[day] && monthly[month]) missingDays.set(month, (missingDays.get(month) || 0) + 1);
+ }
+ const monthShare = new Map();
+ for (const [month, count] of missingDays) {
+ const report = buildUsageReport({}, { monthlyActivity: { [month]: monthly[month] }, providers });
+ // Days of the month outside the span still carry their share, so divide by
+ // every rolled-up day of the month, not only the `count` in view.
+ 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);
+ }
+ return span.map((day) => {
+ if (daily[day]) return costByGroup(buildUsageReport({ [day]: daily[day] }, { from: day, to: day, providers }), labels);
+ return monthShare.get(day.slice(0, 7)) || {};
});
}
+function earliestDay(sources) {
+ let earliest = null;
+ for (const { daily, monthly } of sources) {
+ for (const day of Object.keys(daily || {})) if (!earliest || day < earliest) earliest = day;
+ for (const month of Object.keys(monthly || {})) if (!earliest || `${month}-01` < earliest) earliest = `${month}-01`;
+ }
+ return earliest;
+}
+
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.
+ * 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 = [], now = new Date() } = {}) {
+export async function getFleetRollingCost({ providers = [], range = '3m', 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 })),
+ { id: self?.instanceId ?? 'local', stamp: local?.lastUpdated, daily: local?.dailyActivity, monthly: local?.monthlyActivity },
+ ...peers.map((e) => ({ id: e.instanceId, stamp: e.capturedAt, daily: e.usage.dailyActivity, monthly: e.usage.monthlyActivity })),
];
- 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)])]);
+ const todayMs = dayMs(utcDay(now.getTime()));
+ const rangeId = Object.hasOwn(ROLLING_COST_RANGES, range) ? range : '3m';
+ const fixed = ROLLING_COST_RANGES[rangeId];
+ const first = earliestDay(sources);
+ const allPoints = first ? Math.floor((todayMs - dayMs(first)) / DAY_MS) + 1 : 2;
+ const pointCount = Math.max(2, fixed ?? allPoints);
+ const spanLength = pointCount + ROLLING_COST_WINDOW_DAYS - 1;
+ const span = Array.from({ length: spanLength }, (_, i) => utcDay(todayMs - (spanLength - 1 - i) * DAY_MS));
+
+ const key = JSON.stringify([rangeId, span[0], 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);
+ const labels = new Map();
+ const perDay = span.map(() => ({}));
for (const source of sources) {
- dailyCosts(source.daily, span, providers).forEach((cost, i) => { perDay[i] += cost; });
+ instanceDailyCosts(source, span, providers, labels).forEach((costs, i) => addInto(perDay[i], costs));
}
- let running = perDay.slice(0, ROLLING_COST_WINDOW_DAYS - 1).reduce((a, b) => a + b, 0);
+
+ 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 running = new Array(series.length).fill(0);
const points = [];
- for (let i = ROLLING_COST_WINDOW_DAYS - 1; i < span.length; i++) {
- running += perDay[i];
+ for (let i = 0; i < span.length; i++) {
+ daily[i].forEach((cost, j) => { running[j] += cost; });
+ if (i >= ROLLING_COST_WINDOW_DAYS) daily[i - ROLLING_COST_WINDOW_DAYS].forEach((cost, j) => { running[j] -= cost; });
+ if (i < ROLLING_COST_WINDOW_DAYS - 1) continue;
// 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 values = running.map((v) => Math.max(0, roundCents(v)));
+ points.push({ date: span[i], cost: roundCents(values.reduce((sum, v) => sum + v, 0)), values });
}
- const value = { windowDays: ROLLING_COST_WINDOW_DAYS, instanceCount: sources.length, points };
+ const value = { range: rangeId, windowDays: ROLLING_COST_WINDOW_DAYS, instanceCount: sources.length, series, points };
rollingMemo = { key, value };
return value;
}
diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.js
index a3c475267a..912dd4c78a 100644
--- a/server/services/peerUsage.test.js
+++ b/server/services/peerUsage.test.js
@@ -494,10 +494,53 @@ describe('fleet rolling 30-day cost', () => {
expect(at('2026-08-30')).toBeCloseTo(both, 2);
expect(at('2026-09-28')).toBeCloseTo(both, 2);
+ // Split by plan; a provider no subscription family claims stands alone.
+ expect(series.series).toEqual([{ key: 'provider:anthropic', label: 'Anthropic' }]);
+ expect(series.points.at(-1).values[0]).toBeCloseTo(both, 2);
+
const later = await getFleetRollingCost({ providers: [], now: new Date('2026-09-29T00:00:00Z') });
expect(later.points.at(-1).cost).toBe(0);
});
+ // Past a peer's 120-day day retention only month buckets remain; their cost
+ // is spread over the month so a long range still totals correctly.
+ it('spreads a rolled-up month over its days on a long range', async () => {
+ const rolledUp = peerEntry({
+ usage: buildUsageDigest(usageFixture({ day: '2026-03-10', tokensOut: 7000 }), {
+ retentionDays: 30, now: new Date('2026-09-01T00:00:00Z'),
+ }),
+ });
+ await applyUsageRemote({ instances: { 'inst-peer': rolledUp } });
+ const monthCost = buildUsageReport({}, { monthlyActivity: rolledUp.usage.monthlyActivity, providers: [] }).totals.estimatedCost;
+ expect(monthCost).toBeGreaterThan(0);
+
+ const series = await getFleetRollingCost({ providers: [], range: 'all', now: new Date('2026-09-01T00:00:00Z') });
+ const at = (date) => series.points.find((p) => p.date === date).cost;
+ expect(series.range).toBe('all');
+ expect(series.points[0].date).toBe('2026-03-01');
+ // 31 March days share the month; the window ending Mar 30 holds 30 of them.
+ expect(at('2026-03-30')).toBeCloseTo((monthCost * 30) / 31, 1);
+ expect(at('2026-08-30')).toBeCloseTo(dayCost(localUsage, '2026-08-30'), 2);
+
+ const year = await getFleetRollingCost({ providers: [], range: '1y', now: new Date('2026-09-01T00:00:00Z') });
+ expect(year.points).toHaveLength(365);
+ });
+
+ // Two provider records on the same plan (here one only a peer has configured)
+ // stack as one Claude Code area.
+ it('stacks providers of one plan together', async () => {
+ const asProvider = (usage, id) => {
+ const out = structuredClone(usage);
+ for (const day of Object.values(out.dailyActivity)) day.byProvider = { [id]: day.byProvider.anthropic };
+ return out;
+ };
+ localUsage = asProvider(usageFixture(), 'claude-code');
+ await applyUsageRemote({ instances: { 'inst-peer': peerEntry({ usage: buildUsageDigest(asProvider(usageFixture({ tokensOut: 4000 }), 'claude-opus-cli')) }) } });
+ const series = await getFleetRollingCost({ providers: [], now: new Date('2026-09-01T00:00:00Z') });
+ expect(series.series).toEqual([{ key: 'claude', label: 'Claude Code' }]);
+ expect(series.points.at(-1).values).toEqual([series.points.at(-1).cost]);
+ });
+
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);