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

perf: load dashboard hourly activity without building cost reports (#6713)

[._.]/ Adam Eivy6a8d04a0452b
diff --git a/client/src/pages/Dashboard.hourlyUsage.test.jsx b/client/src/pages/Dashboard.hourlyUsage.test.jsx
new file mode 100644
index 0000000000..fe570e4357
--- /dev/null
+++ b/client/src/pages/Dashboard.hourlyUsage.test.jsx
@@ -0,0 +1,53 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, act, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../services/apiCore.js', async (importOriginal) => ({
+ ...await importOriginal(), request: vi.fn()
+}));
+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+vi.mock('../hooks/useInstanceFeatures.js', () => ({ useInstanceFeatures: () => ({ features: [] }) }));
+vi.mock('../components/onboarding/FirstRunCard.jsx', () => ({ default: () => null }));
+vi.mock('../components/dashboard/LayoutPicker', () => ({ default: () => null }));
+vi.mock('../components/dashboard/LayoutEditor', () => ({ default: () => null }));
+vi.mock('../components/dashboard/DashboardGrid.jsx', async (importOriginal) => ({
+ ...await importOriginal(),
+ default: ({ items, renderItem }) => <div data-testid="grid" data-widgets={items.map((item) => item.id).join(',')}>
+ {items.map((item) => <div key={item.id}>{renderItem(item)}</div>)}
+ </div>
+}));
+
+import { request } from '../services/apiCore.js';
+import socket from '../services/socket';
+import Dashboard from './Dashboard.jsx';
+
+// Exercise the real API wrapper, registry gate and hourly widget through Dashboard.
+describe('Dashboard hourly usage hydration', () => {
+ it('uses only the hourly endpoint on mount and app changes, preserving data and the zero gate', async () => {
+ let hourlyActivity = Array(24).fill(0);
+ hourlyActivity[9] = 7;
+ request.mockImplementation(async (path) => {
+ if (path === '/usage/hourly') return { hourlyActivity };
+ if (path === '/apps') return [];
+ if (path === '/dashboard/layouts') return {
+ layouts: [{ id: 'hourly', name: 'Hourly', widgets: ['hourly-activity'] }],
+ activeLayoutId: 'hourly'
+ };
+ return {};
+ });
+ render(<MemoryRouter><Dashboard /></MemoryRouter>);
+ expect(await screen.findByText('7 total sessions tracked')).toBeInTheDocument();
+ expect(screen.getByRole('img', { name: 'Hourly activity heatmap' }).children).toHaveLength(24);
+ expect(request.mock.calls.filter(([path]) => path === '/usage/hourly')).toEqual([
+ ['/usage/hourly', { silent: true }]
+ ]);
+ const onAppsChanged = socket.on.mock.calls.find(([event]) => event === 'apps:changed')[1];
+ hourlyActivity = Array(24).fill(0);
+ await act(async () => onAppsChanged());
+ await waitFor(() => expect(screen.queryByText('Activity by Hour')).not.toBeInTheDocument());
+ expect(screen.queryByTestId('grid')).not.toBeInTheDocument();
+ expect(screen.getByText(/This layout has no widgets/)).toBeInTheDocument();
+ expect(request.mock.calls.filter(([path]) => path === '/usage/hourly')).toHaveLength(2);
+ expect(request.mock.calls.some(([path]) => path === '/usage' || path.startsWith('/usage?'))).toBe(false);
+ });
+});
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index fbd7e32d23..4c36cc330c 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -111,7 +111,7 @@ export default function Dashboard() {
.finally(() => setAppsReadSettled(true));
const secondaryRead = Promise.all([
refreshHealth(),
- api.getUsage().catch(() => null).then(setUsage),
+ api.getHourlyUsage({ silent: true }).catch(() => null).then(setUsage),
api.getTribeCareSummary({ silent: true }).catch(() => null).then(setTribeCare),
api.getFeedStats({ silent: true }).catch(() => null).then(setFeeds),
api.getMeatspaceLoggingStats({ silent: true }).catch(() => null).then(setMeatspaceLogging),
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 8b0d9a4801..eb501751d7 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -65,7 +65,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiSchedules.js` | Automation schedules. |
| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. |
| `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. |
-| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `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. |
+| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `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. |
| `apiAuth.js` | Optional login password — status, login, set/clear password. |
| `apiLoops.js` | Scheduled loops. |
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 4de4d4ee23..7dc0e5582b 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -172,6 +172,7 @@ export const getUsage = (params = {}) => {
).toString();
return request(`/usage${qs ? `?${qs}` : ''}`);
};
+export const getHourlyUsage = (options = {}) => request('/usage/hourly', options);
export const getUsageBackfillStatus = (options = {}) => request('/usage/backfill', options);
// Monthly plan prices per provider family, used to compare subscription spend
// against the report's estimated API cost. `costs` is a partial patch: an
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 9cae041006..04138446fd 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -17,6 +17,12 @@ import {
const router = Router();
+// GET /api/usage/hourly - Fixed-size local counters, without building cost reports.
+router.get('/hourly', (req, res) => {
+ const { hourlyActivity } = usage.getUsage();
+ res.json({ hourlyActivity: Array.from({ length: 24 }, (_, hour) => hourlyActivity?.[hour] || 0) });
+});
+
// GET /api/usage - Usage summary + cost report. Accepts ?period=7d|30d|90d|all
// or an explicit ?from/?to (YYYY-MM-DD, inclusive) for the report window.
router.get('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index 805d04486e..a91dfbf240 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -68,6 +68,44 @@ describe('usage routes', () => {
vi.clearAllMocks();
});
+ it('GET /api/usage/hourly projects only counters and bypasses all reporting work', async () => {
+ const hourlyActivity = Array.from({ length: 24 }, (_, hour) => hour);
+ usage.getUsage.mockReturnValue({
+ hourlyActivity,
+ daily: Object.fromEntries(Array.from({ length: 400 }, (_, day) => [day, { tokens: 1000 }])),
+ monthly: { '2025-01': { tokens: 2000 } },
+ providers: { example: { tokens: 3000 } }
+ });
+ usage.getUsageSummary.mockReturnValue({ report: { totals: { estimatedCost: 12 } } });
+ getFleetUsage.mockResolvedValueOnce({ instances: [{ id: 'peer-a' }, { id: 'peer-b' }], totals: {} });
+ const collaborators = [usage.getUsageSummary, getAllProviders, getSubscriptionSavings,
+ getApiBilledInstanceIds, getFleetUsage];
+ const app = buildApp();
+ // Before: each dashboard refresh enters all five reporting/config/peer collaborators.
+ for (let refresh = 0; refresh < 3; refresh++) {
+ expect((await request(app).get('/api/usage')).status).toBe(200);
+ }
+ expect(collaborators.map((fn) => fn.mock.calls.length)).toEqual([3, 3, 3, 3, 3]);
+ vi.clearAllMocks();
+ // After: the same reads only serialize the 24 counters, regardless of history/peers.
+ for (let refresh = 0; refresh < 3; refresh++) {
+ const res = await request(app).get('/api/usage/hourly');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ hourlyActivity });
+ }
+ expect(usage.getUsage).toHaveBeenCalledTimes(3);
+ expect(collaborators.map((fn) => fn.mock.calls.length)).toEqual([0, 0, 0, 0, 0]);
+ expect(usage.getFirstActivityDay).not.toHaveBeenCalled();
+ expect(getProviderQuotas).not.toHaveBeenCalled();
+ });
+
+ it('GET /api/usage/hourly preserves the empty-usage zero counters', async () => {
+ usage.getUsage.mockReturnValue({ hourlyActivity: Array(24).fill(0) });
+ const res = await request(buildApp()).get('/api/usage/hourly');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ hourlyActivity: Array(24).fill(0) });
+ });
+
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');