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: keep usage estimates tied to their loaded range (#10687)

Adam Eivy096f7c4b226c
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 90ec04e413..8877e92f52 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -552,6 +552,8 @@ function InternalUsageMetrics() {
const [usage, setUsage] = useState(null);
const [loading, setLoading] = useState(true);
+ const [readError, setReadError] = useState(false);
+ const [loadedRange, setLoadedRange] = useState(null);
const { data: backfill, updateData: setBackfill, refetch: refreshBackfill } = useSocketResource(
() => api.getUsageBackfillStatus({ silent: true }),
{ events: BACKFILL_EVENTS },
@@ -565,18 +567,26 @@ function InternalUsageMetrics() {
const fetchUsage = useCallback(async () => {
const token = ++requestRef.current;
const params = isCustom ? { from, to } : { period };
- const data = await api.getUsage(params).catch(() => null);
- // Keep the previously-loaded metrics on a failed fetch (e.g. an in-progress
- // custom range where from > to briefly 400s) so the filter controls stay on
- // screen for the user to correct the range — and drop a response a newer
- // request has already superseded.
- if (data && token === requestRef.current) setUsage(data);
+ const rangeLabel = isCustom
+ ? `${from || 'Beginning'} to ${to || 'Today'}`
+ : (USAGE_PERIOD_OPTIONS.find((option) => option.id === period)?.label || period);
+ setLoading(true);
+ setReadError(false);
+ const data = await api.getUsage(params, { silent: true }).catch(() => null);
+ if (token === requestRef.current) {
+ if (data) {
+ setUsage(data);
+ setLoadedRange(rangeLabel);
+ }
+ setReadError(!data);
+ setLoading(false);
+ }
return data;
}, [period, from, to, isCustom]);
useEffect(() => {
- setLoading(true);
- fetchUsage().finally(() => setLoading(false));
+ fetchUsage();
+ return () => { requestRef.current += 1; };
}, [fetchUsage]);
const [startBackfill, startingBackfill] = useAsyncAction(async () => {
@@ -612,21 +622,28 @@ function InternalUsageMetrics() {
}, { replace: true });
};
- if (loading && !usage) {
- return (
- <PageSkeleton
- label="Loading usage data"
- titleWidthClass="w-44"
- showAction={false}
- layout="grid"
- gridColsClass="grid-cols-2 sm:grid-cols-4"
- cards={4}
- />
- );
- }
+ const reportControls = (
+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3">
+ <CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} />
+ {usage && <p className="text-sm text-gray-400">Showing usage for {loadedRange}.{(loading || readError) && ' Retained figures may be stale.'}</p>}
+ {loading && <p className="text-sm text-gray-400" role="status">Loading selected usage range…</p>}
+ {readError && (
+ <div role="alert" className="text-sm text-port-warning flex flex-wrap items-center gap-3">
+ <span>Usage unavailable for the selected range.</span>
+ <button type="button" onClick={fetchUsage} className="min-h-11 px-3 rounded-lg border border-port-border hover:border-port-accent">Retry usage</button>
+ </div>
+ )}
+ </div>
+ );
if (!usage) {
- return <div className="text-center py-8 text-gray-500">No usage data available</div>;
+ return (
+ <div className="space-y-6">
+ <h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>
+ {reportControls}
+ {loading && <PageSkeleton label="Loading usage data" titleWidthClass="w-44" showAction={false} layout="grid" gridColsClass="grid-cols-2 sm:grid-cols-4" cards={4} />}
+ </div>
+ );
}
const maxActivity = Math.max(1, ...(usage.last7Days?.map(d => d.sessions) || []));
@@ -638,6 +655,7 @@ function InternalUsageMetrics() {
return (
<div className="space-y-6">
<h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>
+ {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">
<div>
@@ -705,7 +723,6 @@ function InternalUsageMetrics() {
<span className="text-xl font-bold text-port-success">{formatUsd(report?.totals?.estimatedCost)}</span>
</div>
</div>
- <CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} />
<CostReportTable report={report} />
<p className="text-[10px] sm:text-xs text-gray-500">
Informational estimate of what this usage would have cost under API billing (PortOS runs on subscriptions).
diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsx
index c3cdb209a9..75f1526783 100644
--- a/client/src/pages/UsagePage.test.jsx
+++ b/client/src/pages/UsagePage.test.jsx
@@ -597,3 +597,62 @@ describe('UsagePage custom date range inputs', () => {
expect(from.value).toBe('2026-09-29');
});
});
+
+describe('UsagePage report range freshness (#10687)', () => {
+ const pricedUsage = (estimatedCost) => ({ ...usage, report: { ...usage.report, totals: { estimatedCost } } });
+
+ it('labels retained figures during a pending and failed replacement, then clears the error on retry', async () => {
+ api.getUsage.mockResolvedValueOnce(pricedUsage(123.45));
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+ expect(await screen.findByText('$123.45')).toBeInTheDocument();
+ let rejectRange;
+ api.getUsage.mockReturnValueOnce(new Promise((_resolve, reject) => { rejectRange = reject; }));
+ fireEvent.click(screen.getByRole('button', { name: '30 days' }));
+ expect(await screen.findByText('Loading selected usage range…')).toBeInTheDocument();
+ expect(screen.getByText('Showing usage for 7 days. Retained figures may be stale.')).toBeInTheDocument();
+ expect(screen.getByText('$123.45')).toBeInTheDocument();
+ await act(async () => rejectRange(new Error('Example unavailable')));
+ expect(screen.getByRole('alert')).toHaveTextContent('Usage unavailable for the selected range.');
+ expect(screen.getByText('Showing usage for 7 days. Retained figures may be stale.')).toBeInTheDocument();
+ api.getUsage.mockResolvedValueOnce(pricedUsage(456.78));
+ fireEvent.click(screen.getByRole('button', { name: 'Retry usage' }));
+ expect(await screen.findByText('$456.78')).toBeInTheDocument();
+ expect(screen.getByText('Showing usage for 30 days.')).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(api.getUsage).toHaveBeenLastCalledWith({ period: '30d' }, { silent: true });
+ });
+
+ it('keeps controls and retry available after an initial invalid custom-range failure', async () => {
+ api.getUsage.mockRejectedValueOnce(new Error('Example invalid range'));
+ render(<MemoryRouter initialEntries={['/?from=2026-09-30&to=2026-09-01']}><UsagePage /></MemoryRouter>);
+ expect(await screen.findByRole('alert')).toHaveTextContent('Usage unavailable');
+ expect(screen.queryByText('No usage data available')).not.toBeInTheDocument();
+ const from = screen.getByLabelText('From date');
+ expect(from).toHaveValue('2026-09-30');
+ expect(screen.getByRole('button', { name: 'Retry usage' })).toBeEnabled();
+ api.getUsage.mockResolvedValueOnce(pricedUsage(12.34));
+ fireEvent.change(from, { target: { value: '2026-08-01' } });
+ expect(await screen.findByText('$12.34')).toBeInTheDocument();
+ expect(screen.getByText('Showing usage for 2026-08-01 to 2026-09-01.')).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('ignores a superseded failure without clearing the latest pending request or successful report', async () => {
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+ await screen.findByText('Showing usage for 7 days.');
+ let rejectOlder;
+ let resolveLatest;
+ api.getUsage.mockReturnValueOnce(new Promise((_resolve, reject) => { rejectOlder = reject; }));
+ fireEvent.click(screen.getByRole('button', { name: '30 days' }));
+ api.getUsage.mockReturnValueOnce(new Promise((resolve) => { resolveLatest = resolve; }));
+ fireEvent.click(screen.getByRole('button', { name: '90 days' }));
+ await act(async () => rejectOlder(new Error('Example stale failure')));
+ expect(screen.getByText('Loading selected usage range…')).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ await act(async () => resolveLatest(pricedUsage(90)));
+ expect(screen.getByText('Showing usage for 90 days.')).toBeInTheDocument();
+ expect(screen.getByText('$90.00')).toBeInTheDocument();
+ expect(screen.queryByText('Loading selected usage range…')).not.toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 0e2c1e2888..5598a84d4e 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -239,7 +239,7 @@ const usageQuery = (params) => {
).toString();
return qs ? `?${qs}` : '';
};
-export const getUsage = (params = {}) => request(`/usage${usageQuery(params)}`);
+export const getUsage = (params = {}, options = {}) => request(`/usage${usageQuery(params)}`, options);
// Per-model token totals for every Claude Code session on this machine, read
// from the CLI transcripts. Same { period } | { from, to } params as getUsage.
export const getClaudeCodeModelUsage = (params = {}, options = {}) =>