Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stream historical usage reconciliation progress (#8536)
[._.]/ Adam Eivy2afccac10ee7
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 498c94d1c3..30b6e7155e 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -7,6 +7,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';import Pill from '../components/ui/Pill';import { formatCompactCountOrDash as formatNumber, formatCount, formatUsd, timeAgo } from '../utils/formatters';import { useAsyncAction } from '../hooks/useAsyncAction';+import { useSocketResource } from '../hooks/useSocketResource';import { useQuotaUpdates } from '../hooks/useQuotaUpdates';import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';import FleetUsageCard from '../components/usage/FleetUsageCard';@@ -16,6 +17,8 @@ import ModelsTabsHeader, { ModelsSectionLayout } from '../components/models/Modeimport { USAGE_PERIOD_OPTIONS, DEFAULT_USAGE_PERIOD } from '../lib/usagePeriods';+const BACKFILL_EVENTS = ['usage-backfill:updated'];+// A subscription is one account across every federated instance, but each// instance can only read its own CLI's panel. When peers have contributed a// reading, say so on the card and name them — the meters are the freshest@@ -530,7 +533,10 @@ function InternalUsageMetrics() {const [usage, setUsage] = useState(null);const [loading, setLoading] = useState(true);- const [backfill, setBackfill] = useState(null);+ const { data: backfill, updateData: setBackfill, refetch: refreshBackfill } = useSocketResource(+ () => api.getUsageBackfillStatus({ silent: true }),+ { events: BACKFILL_EVENTS },+ );// One fetch for every trigger — the range effect, the backfill-complete// refetch, and a subscription-price save (which re-derives the savings block@@ -554,42 +560,17 @@ function InternalUsageMetrics() {fetchUsage().finally(() => setLoading(false));}, [fetchUsage]);- useEffect(() => {- let cancelled = false;- api.getUsageBackfillStatus({ silent: true })- .then((status) => { if (!cancelled) setBackfill(status); })- .catch(() => {});- return () => { cancelled = true; };- }, []);-const [startBackfill, startingBackfill] = useAsyncAction(async () => {const status = await api.startUsageBackfill({ silent: true });setBackfill(status);+ // A fast worker can finish before the POST response arrives. Reconcile+ // once so that response cannot overwrite an already-observed completion.+ if (status?.status === 'running') await refreshBackfill();}, { errorMessage: 'Failed to start historical usage reconciliation' });useEffect(() => {- if (backfill?.status !== 'running') return undefined;- let cancelled = false;- let timer = null;- const poll = () => {- api.getUsageBackfillStatus({ silent: true })- .then(async (status) => {- if (cancelled) return;- setBackfill(status);- if (status?.status === 'complete') {- await fetchUsage();- } else if (status?.status === 'running') {- timer = setTimeout(poll, 1000);- }- })- .catch(() => {});- };- timer = setTimeout(poll, 1000);- return () => {- cancelled = true;- clearTimeout(timer);- };- }, [backfill?.status, fetchUsage]);+ if (backfill?.status === 'complete') fetchUsage();+ }, [backfill, fetchUsage]);const setPeriod = (id) => {diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsxindex a0bed0df2a..f1efdb5ce7 100644--- a/client/src/pages/UsagePage.test.jsx+++ b/client/src/pages/UsagePage.test.jsx@@ -3,7 +3,7 @@ vi.mock('../services/socket', async () => {const { EventEmitter } = await import('events');return { default: new EventEmitter() };});-afterEach(() => vi.useRealTimers());+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { MemoryRouter } from 'react-router';@@ -98,6 +98,44 @@ describe('UsagePage subscription savings', () => {});describe('UsagePage historical reconciliation', () => {+ it('renders backfill events without polling and reconciles missed updates', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ api.getUsageBackfillStatus.mockResolvedValue({ status: 'running', processed: 1, total: 5 });+ render(<MemoryRouter><UsagePage /></MemoryRouter>);+ expect(await screen.findByText('Processing 1 of 5 runs…')).toBeInTheDocument();+ await act(async () => { await vi.advanceTimersByTimeAsync(5000); });+ expect(api.getUsageBackfillStatus).toHaveBeenCalledTimes(1);+ api.getUsageBackfillStatus.mockResolvedValue({ status: 'running', processed: 3, total: 5 });+ await act(async () => { socket.emit('usage-backfill:updated', {}); });+ expect(await screen.findByText('Processing 3 of 5 runs…')).toBeInTheDocument();+ expect(api.getUsageBackfillStatus).toHaveBeenCalledTimes(2);+ const usageReads = api.getUsage.mock.calls.length;+ api.getUsageBackfillStatus.mockResolvedValue({ status: 'complete', corrected: 4 });+ await act(async () => { socket.emit('usage-backfill:updated', {}); });+ expect(await screen.findByText('Corrected 4 runs.')).toBeInTheDocument();+ expect(api.getUsage.mock.calls.length).toBe(usageReads + 1);+ await act(async () => { socket.emit('connect'); });+ expect(api.getUsageBackfillStatus).toHaveBeenCalledTimes(4);+ const visibility = vi.spyOn(document, 'visibilityState', 'get');+ visibility.mockReturnValue('hidden');+ act(() => document.dispatchEvent(new Event('visibilitychange')));+ api.getUsageBackfillStatus.mockResolvedValue({ status: 'error', error: 'Example scan failed' });+ visibility.mockReturnValue('visible');+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));+ expect(api.getUsageBackfillStatus).toHaveBeenCalledTimes(5);+ expect(await screen.findByText('Example scan failed')).toBeInTheDocument();+ });++ it('reconciles a completion that beats the start response', async () => {+ api.startUsageBackfill.mockResolvedValue({ status: 'running' });+ render(<MemoryRouter><UsagePage /></MemoryRouter>);+ const button = await screen.findByRole('button', { name: 'Reconcile now' });+ api.getUsageBackfillStatus.mockResolvedValue({ status: 'complete', corrected: 3 });+ fireEvent.click(button);+ expect(await screen.findByText('Corrected 3 runs.')).toBeInTheDocument();+ expect(api.startUsageBackfill).toHaveBeenCalledTimes(1);+ });+it('starts only from the explicit user action and reports completion', async () => {render(<MemoryRouter><UsagePage /></MemoryRouter>);diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 3a2695286e..05ffac30af 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -57,6 +57,11 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({additionalProperties: false,},},+ 'usage-backfill:updated': {+ direction: 'server-to-client',+ summary: 'Invalidate historical usage backfill status after progress or a durable terminal transition.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },'cos:day:changed': {direction: 'server-to-client',summary: 'Invalidate UTC-day aggregates when the current activity-calendar day expires.',diff --git a/server/services/socket.js b/server/services/socket.jsindex 7a051aa353..a636e776eb 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -36,6 +36,7 @@ import { musicVideoEvents } from './musicVideo/events.js';import { videoGenEvents } from './videoGen/events.js';import { audioGenEvents } from './audioGen/events.js';import { aiStatusEvents } from './aiStatusEvents.js';+import { usageBackfillEvents } from './usageBackfillEvents.js';import { providerQuotaEvents } from './providerQuotaEvents.js';import { wireProactiveTriggers } from './voice/proactiveTriggers.js';import { callStateEvents } from './voice/callSession.js';@@ -245,6 +246,7 @@ function setupEventForwarding() {modelLifecycleEvents.on('image-to-3d:changed', data => ioInstance?.emit('image-to-3d:changed', data));modelLifecycleEvents.on('threejs-model:changed', data => ioInstance?.emit('threejs-model:changed', data));meatspaceEvents.on('death-clock:changed', data => ioInstance?.emit('meatspace:death-clock:changed', data));+ usageBackfillEvents.on('updated', () => ioInstance?.emit('usage-backfill:updated', {}));providerQuotaEvents.on('updated', () => ioInstance?.emit('provider-quota:updated', {}));setupCosEventForwarding();setupErrorEventForwarding();diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 6e614a6ed2..8c67064226 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -7,6 +7,7 @@ import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './simport { fableLoomRunEvents } from './fableLoom/runEvents.js';import { trainingEvents } from './loraTraining/events.js';import { authEvents } from './auth.js';+import { usageBackfillEvents } from './usageBackfillEvents.js';import { providerQuotaEvents } from './providerQuotaEvents.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';@@ -155,6 +156,7 @@ describe('socket.js — initSocket', () => {meatspaceEvents.removeAllListeners();modelLifecycleEvents.removeAllListeners();providerQuotaEvents.removeAllListeners();+ usageBackfillEvents.removeAllListeners();});it('coalesces environment changes into payload-free Mind visibility invalidations for subscribers', () => {@@ -195,6 +197,12 @@ describe('socket.js — initSocket', () => {]);});+ it('forwards historical usage progress without worker details', () => {+ io.emitted.length = 0;+ usageBackfillEvents.emit('updated', { metadataPath: '/example/private-run.json' });+ expect(io.emitted).toEqual([['usage-backfill:updated', {}]]);+ });+it('forwards quota completion without leaking source data', () => {io.emitted.length = 0;providerQuotaEvents.emit('updated', { privateContent: 'example account detail' });diff --git a/server/services/usageBackfill.js b/server/services/usageBackfill.jsindex db4c6885ff..5fb7380cdc 100644--- a/server/services/usageBackfill.js+++ b/server/services/usageBackfill.js@@ -1,3 +1,4 @@+import { notifyUsageBackfillUpdated } from './usageBackfillEvents.js';import { Worker } from 'worker_threads';import { homedir } from 'os';import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';@@ -71,6 +72,8 @@ export async function startHistoricalUsageBackfill({completedAt: null};+ notifyUsageBackfillUpdated();+// Resolved HERE, not inside the worker: the toolkit singleton that backs// `listProviders()` is never initialized in a worker thread, so a worker-side// lookup would silently find no provider to attribute a nested session to.@@ -98,10 +101,12 @@ export async function startHistoricalUsageBackfill({messageTail = messageTail.then(async () => {if (message?.type === 'progress') {job = { ...job, ...message.progress };+ notifyUsageBackfillUpdated();return;}if (message?.type === 'error') {job = { ...job, status: 'error', error: message.error || 'Backfill failed', completedAt: new Date().toISOString() };+ notifyUsageBackfillUpdated();return;}if (message?.type !== 'complete') return;@@ -120,12 +125,15 @@ export async function startHistoricalUsageBackfill({corrected: applied.corrected,completedAt: new Date().toISOString()};+ notifyUsageBackfillUpdated();}).catch((error) => {job = { ...job, status: 'error', error: error.message, completedAt: new Date().toISOString() };+ notifyUsageBackfillUpdated();});});worker.on('error', (error) => {job = { ...job, status: 'error', error: error.message, completedAt: new Date().toISOString() };+ notifyUsageBackfillUpdated();});worker.unref();return publicJob();diff --git a/server/services/usageBackfill.test.js b/server/services/usageBackfill.test.jsindex 003fad9a66..dbe9839d4f 100644--- a/server/services/usageBackfill.test.js+++ b/server/services/usageBackfill.test.js@@ -1,3 +1,4 @@+import { usageBackfillEvents } from './usageBackfillEvents.js';import { EventEmitter } from 'events';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -42,18 +43,22 @@ class FakeWorker extends EventEmitter {}beforeEach(() => {+ usageBackfillEvents.removeAllListeners();FakeWorker.instances = [];__resetHistoricalUsageBackfillForTests();});describe('historical usage backfill job', () => {it('runs scanning off-thread and exposes progress through status', async () => {+ const updates = [];+ usageBackfillEvents.on('updated', () => updates.push(getHistoricalUsageBackfillStatus()));const started = await startHistoricalUsageBackfill({runsDir: '/example/runs',home: '/example/home',WorkerClass: FakeWorker});expect(started.status).toBe('running');+ expect(updates).toHaveLength(1);expect(FakeWorker.instances).toHaveLength(1);const worker = FakeWorker.instances[0];expect(worker.options.workerData).toMatchObject({@@ -77,6 +82,10 @@ describe('historical usage backfill job', () => {found: 1}));+ expect(updates.at(-1)).toMatchObject({ status: 'running', processed: 2 });+ const { applyHistoricalUsageCorrections } = await import('./usage.js');+ let finishWrite;+ applyHistoricalUsageCorrections.mockImplementationOnce(() => new Promise(resolve => { finishWrite = resolve; }));worker.emit('message', {type: 'complete',result: {@@ -85,11 +94,25 @@ describe('historical usage backfill job', () => {corrections: [{ runId: 'run-example-1', metadataPath: '/example/metadata.json' }]}});+ await vi.waitFor(() => expect(finishWrite).toBeTypeOf('function'));+ expect(updates.at(-1).status).toBe('running');+ finishWrite({ corrected: 1, correctedRunIds: ['run-example-1'] });await vi.waitFor(() => expect(getHistoricalUsageBackfillStatus()).toMatchObject({status: 'complete',corrected: 1,processed: 5,total: 5}));+ expect(updates.at(-1)).toMatchObject({ status: 'complete', corrected: 1 });});});++it('notifies clients when the worker fails', async () => {+ const updated = vi.fn();+ usageBackfillEvents.on('updated', updated);+ await startHistoricalUsageBackfill({ WorkerClass: FakeWorker, providers: [] });+ updated.mockClear();+ FakeWorker.instances[0].emit('error', new Error('Example worker failure'));+ expect(updated).toHaveBeenCalledWith({});+ expect(getHistoricalUsageBackfillStatus()).toMatchObject({ status: 'error', error: 'Example worker failure' });+});diff --git a/server/services/usageBackfillEvents.js b/server/services/usageBackfillEvents.jsnew file mode 100644index 0000000000..defb5844a9--- /dev/null+++ b/server/services/usageBackfillEvents.js@@ -0,0 +1,5 @@+import { EventEmitter } from 'node:events';++// Invalidation only: run paths and worker errors stay on the status endpoint.+export const usageBackfillEvents = new EventEmitter();+export const notifyUsageBackfillUpdated = () => usageBackfillEvents.emit('updated', {});