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: update provider quota cards on scrape completion (#8536)
[._.]/ Adam Eivy14a95a8e321f
diff --git a/client/src/components/models/SubscriptionsTab.jsx b/client/src/components/models/SubscriptionsTab.jsxindex 7eed33212a..38721f279e 100644--- a/client/src/components/models/SubscriptionsTab.jsx+++ b/client/src/components/models/SubscriptionsTab.jsx@@ -13,7 +13,7 @@ import {parseCostInput,rowCells,} from '../usage/SubscriptionSavingsCard';-import { useQuotaPendingPoll } from '../../hooks/useQuotaPendingPoll';+import { useQuotaUpdates } from '../../hooks/useQuotaUpdates';import useUrlParams from '../../hooks/useUrlParams';import { USAGE_PERIOD_OPTIONS, resolveUsagePeriod, DEFAULT_USAGE_PERIOD } from '../../lib/usagePeriods';@@ -224,11 +224,9 @@ export default function SubscriptionsTab() {useEffect(() => { loadSavings(); }, [loadSavings]);// A quota read never blocks the response: a family whose CLI scrape is still- // running answers `pending` and the reading lands behind it. Poll only while- // something is pending — without it this tab showed whatever stood in for the- // reading (a federated peer's older meters, or a spinner) until the user- // navigated away and back. The Usage page does the same.- useQuotaPendingPoll(loadQuotas, quotas);+ // running answers `pending`. Completion events replace that placeholder;+ // reconnect and tab-show reads recover any missed events.+ useQuotaUpdates(loadQuotas);const setPeriod = (id) => updateParams({ period: id === DEFAULT_USAGE_PERIOD ? null : id },diff --git a/client/src/components/models/SubscriptionsTab.test.jsx b/client/src/components/models/SubscriptionsTab.test.jsxindex 5401e8395c..26437ed3d3 100644--- a/client/src/components/models/SubscriptionsTab.test.jsx+++ b/client/src/components/models/SubscriptionsTab.test.jsx@@ -1,5 +1,11 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import socket from '../../services/socket';+vi.mock('../../services/socket', async () => {+ const { EventEmitter } = await import('events');+ return { default: new EventEmitter() };+});+afterEach(() => vi.useRealTimers());+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router';const api = vi.hoisted(() => ({@@ -97,6 +103,22 @@ describe('buildRowPatch', () => {});describe('SubscriptionsTab', () => {+ it('updates quota cards on completion without recurring fetches', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ renderTab();+ await screen.findByText('Weekly');+ await act(async () => { await vi.advanceTimersByTimeAsync(12_000); });+ expect(api.getProviderUsage).toHaveBeenCalledTimes(1);+ api.getProviderUsage.mockResolvedValue({ providers: [{+ family: 'claude', label: 'Claude Code', supported: true,+ limits: [{ key: 'week', label: 'Updated window', percentUsed: 73, percentRemaining: 27 }],+ }] });+ await act(async () => { socket.emit('provider-quota:updated', {}); });+ expect(await screen.findByText('Updated window')).toBeInTheDocument();+ expect(api.getProviderUsage).toHaveBeenCalledTimes(2);+ expect(api.getProviderUsage).toHaveBeenLastCalledWith({ refresh: false });+ });+it('renders one row per plan with its tier, price, spend and quota', async () => {renderTab();expect(await screen.findByText('Claude Code')).toBeInTheDocument();diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex a247406395..725d659c4d 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -40,7 +40,7 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|-| `useQuotaPendingPoll` | `useQuotaPendingPoll(reload, cards)` — re-reads provider quota cards every 4s while any is `pending` (a scrape still in flight), paused on a hidden tab. | A surface renders `ProviderQuotaBody` cards from `GET /api/usage/providers` — without it the page keeps a spinner, or a federated peer's older meters, until a manual refresh. |+| `useQuotaUpdates` | Reconcile quota cards on scrape completion, reconnect and tab show; the caller owns the entry read. | Usage, Subscriptions and Quota Burn quota cards. || `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. || `useSseJobSlot` | Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, pending, jobId, percent, stage, context, start, cancel }`; reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional `readPercent` adapts other progress scales. Pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. || `useInstallStream` | BYO-runtime install-log stream lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. `method: 'GET'` uses EventSource; `method: 'POST'` reads one fetch stream for a non-idempotent install. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes, OpenCode). Don't re-roll the teardown/onComplete-ref dance. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 2d435be8b2..0b5c8bead9 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -142,7 +142,7 @@ export * from './useProcessLogs.js';export * from './useOpenClawStream.js';export * from './usePipelineProgress.js';export * from './usePortosRestartWatch.js';-export * from './useQuotaPendingPoll.js';+export * from './useQuotaUpdates.js';export * from './useReaderPanel.js';export * from './useSeriesEditorial.js';export * from './useImageTo3dTargets.js';diff --git a/client/src/hooks/useQuotaPendingPoll.js b/client/src/hooks/useQuotaPendingPoll.jsdeleted file mode 100644index 78d1267592..0000000000--- a/client/src/hooks/useQuotaPendingPoll.js+++ /dev/null@@ -1,34 +0,0 @@-import { useAutoRefetch } from './useAutoRefetch.js';--// A scrape is a 10-20s PTY spawn, so this is a handful of polls, not a busy loop.-export const PENDING_POLL_MS = 4000;--/**- * Re-read provider quota cards while any of them is still being scraped.- *- * `GET /api/usage/providers` never blocks on a 10-20s PTY spawn: a cold cache- * answers with `pending: true` cards and the reading lands behind the response.- * Something therefore has to ask again, or the page keeps whatever stood in for- * the reading — a spinner, or a federated peer's older meters — until the user- * refreshes by hand.- *- * One hook rather than the same six lines on each surface: three pages render- * the same cards (Usage, Subscriptions, Quota Burn), and the cadence and the- * "which state keeps polling" rule are exactly the pair that must not drift- * between them — the card BODY was already extracted for that reason- * (`components/usage/ProviderQuotaBody.jsx`), and its lifecycle is the half- * that was left behind.- *- * Polling only while something is pending is the point: this is not a- * background refresh loop, and `useAutoRefetch` pauses on a hidden tab so a- * backgrounded copy can never re-request a multi-second scrape.- *- * @param {Function} reload - re-fetches the cards; called for its side effect.- * @param {Array<{pending?: boolean}>} cards - the cards currently rendered.- */-export function useQuotaPendingPoll(reload, cards) {- const anyPending = Boolean(cards?.some((card) => card?.pending));- useAutoRefetch(reload, PENDING_POLL_MS, { enabled: anyPending, immediate: false, pollOnly: true });-}--export default useQuotaPendingPoll;diff --git a/client/src/hooks/useQuotaUpdates.js b/client/src/hooks/useQuotaUpdates.jsnew file mode 100644index 0000000000..b9873cca00--- /dev/null+++ b/client/src/hooks/useQuotaUpdates.js@@ -0,0 +1,10 @@+import { useSocketResource } from './useSocketResource.js';++const EVENTS = ['provider-quota:updated'];++/** The caller owns its entry read; reconcile later cache completions and missed events. */+export function useQuotaUpdates(reload) {+ // Do not pass the resource request object as a legacy load(refresh) argument:+ // it would force another scrape on every completion and loop indefinitely.+ useSocketResource(() => reload(), { events: EVENTS, immediate: false });+}diff --git a/client/src/hooks/useSocketResource.js b/client/src/hooks/useSocketResource.jsindex 0a0716781f..dc92d488b0 100644--- a/client/src/hooks/useSocketResource.js+++ b/client/src/hooks/useSocketResource.js@@ -9,6 +9,7 @@ const visible = () => document.visibilityState !== 'hidden';* Read once, then reconcile a resource on room events, reconnect and tab show.* Omit namespace for globally broadcast events. fetchFn receives* { reconcile, events: [{ event, payload }], signal } for targeted invalidation reads.+ * Set immediate=false when the caller already owns its entry read.* Keep events stable (module-level). fetchFn returns data without setting state.* resourceKey cancels old reads; updateData applies mutation responses and* prevents an older in-flight read from overwriting them. enabled=false releases@@ -16,7 +17,7 @@ const visible = () => document.visibilityState !== 'hidden';* Optional requestTimeoutMs bounds a read; navigation/unmount aborts its signal* even without a timeout.*/-export function useSocketResource(fetchFn, { namespace, events, resourceKey = null, matchesEvent = () => true, compare, enabled = true, requestTimeoutMs }) {+export function useSocketResource(fetchFn, { namespace, events, resourceKey = null, matchesEvent = () => true, compare, enabled = true, requestTimeoutMs, immediate = true }) {const [state, setState] = useState({ key: resourceKey, data: null, loading: true, error: null });const fetchRef = useRef(fetchFn);const matchesRef = useRef(matchesEvent);@@ -106,7 +107,7 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nu// reconcile through useSocketSubscription, so never attach both paths.const reconnect = () => { if (visible()) read(); };if (!namespace) socket.on('connect', reconnect);- if (visible()) read();+ if (immediate && visible()) read();return () => {disposed = true;activeRequest?.abort();@@ -114,7 +115,7 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nufor (const [event, handler] of handlers) socket.off(event, handler);if (!namespace) socket.off('connect', reconnect);};- }, [namespace, events, resourceKey, enabled, requestTimeoutMs]);+ }, [namespace, events, resourceKey, enabled, requestTimeoutMs, immediate]);const lastVisibility = useRef(document.visibilityState);useVisibilityEvent(state => {diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsxindex fd8a78a606..bcff24609e 100644--- a/client/src/pages/QuotaBurn.jsx+++ b/client/src/pages/QuotaBurn.jsx@@ -23,7 +23,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';import FamilyCard from '../components/quotaBurn/FamilyCard';import { NumberField } from '../components/quotaBurn/fields';import * as api from '../services/api';-import { useQuotaPendingPoll } from '../hooks/useQuotaPendingPoll';+import { useQuotaUpdates } from '../hooks/useQuotaUpdates';import { mergeQuotaBurnPatch } from '../lib/quotaBurnPatch';import { buildQuotaBurnTaskCatalog, flattenTaskCatalog } from '../lib/quotaBurnTasks';import { safeReadJsonSession, safeRemoveSession, safeWriteJsonSession } from '../lib/safeStorage';@@ -254,8 +254,8 @@ export default function QuotaBurn() {// A cold quota cache comes back as `pending` families rather than holding the// response open for a 20s-per-family PTY scrape, so the page renders its plan// immediately and fills the numbers in when the scrape lands. The shared hook- // owns the cadence and the hidden-tab pause (hooks/useQuotaPendingPoll.js).- useQuotaPendingPoll(load, status?.families);+ // subscribes to completion events and reconciles after reconnect/tab show (hooks/useQuotaUpdates.js).+ useQuotaUpdates(load);// There is no Save button: an edit lands in local state immediately and is// persisted on a trailing edge. Successive edits fold into ONE patch body, sodiff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsxindex 3d0998a1a0..ad0cb3e004 100644--- a/client/src/pages/QuotaBurn.test.jsx+++ b/client/src/pages/QuotaBurn.test.jsx@@ -4,7 +4,11 @@ import { findEnabledByLabelText, findEnabledByRole } from '../test/enabledBarrieimport userEvent from '@testing-library/user-event';import { MemoryRouter, Route, Routes } from 'react-router';import QuotaBurn, { SAVE_DEBOUNCE_MS } from './QuotaBurn';-import { PENDING_POLL_MS } from '../hooks/useQuotaPendingPoll';+import socket from '../services/socket';+vi.mock('../services/socket', async () => {+ const { EventEmitter } = await import('events');+ return { default: new EventEmitter() };+});vi.mock('../services/api', () => ({getQuotaBurn: vi.fn(),@@ -126,7 +130,7 @@ const flushSave = () => act(async () => { await vi.advanceTimersByTimeAsync(SAVE// Past the debounce/poll window rather than up to its edge, so a "did not// happen" assertion runs AFTER the moment the thing would have happened.const pastSaveWindow = () => act(async () => { await vi.advanceTimersByTimeAsync(SAVE_DEBOUNCE_MS + 100); });-const pastPollWindow = () => act(async () => { await vi.advanceTimersByTimeAsync(PENDING_POLL_MS + 100); });+const pastPollWindow = () => act(async () => { await vi.advanceTimersByTimeAsync(4100); });// Mirrors UNSAVED_PATCH_KEY in the page — the session-scoped stash holding a// patch the server never accepted.@@ -155,7 +159,7 @@ describe('QuotaBurn page', () => {expect(screen.getByText('disabled')).toBeInTheDocument();});- it('renders immediately while a family\'s quota is still being read, then polls it in', async () => {+ it('renders immediately while a family\'s quota is still being read, then receives it on a quota event', async () => {vi.useFakeTimers({ shouldAdvanceTime: true });try {const pendingStatus = {@@ -169,18 +173,41 @@ describe('QuotaBurn page', () => {expect(screen.getByLabelText(/Run the quota-burn loop automatically/)).toBeInTheDocument();await pastPollWindow();+ expect(api.getQuotaBurn).toHaveBeenCalledTimes(1);+ expect(screen.getByText(/reading quota…/)).toBeInTheDocument();+ await act(async () => { socket.emit('provider-quota:updated', {}); });expect(await screen.findByText(/62% left/)).toBeInTheDocument();expect(screen.queryByText(/reading quota…/)).not.toBeInTheDocument();- // Positive control for 'does NOT poll when nothing is pending': the poll- // DOES fire inside this window, so that test's silence means the guard- // held rather than that the window was too short to observe anything.expect(api.getQuotaBurn).toHaveBeenCalledTimes(2);} finally {vi.useRealTimers();}});+ it('reconciles once on reconnect and tab show, and removes subscriptions on unmount', async () => {+ const view = renderPage();+ await screen.findByText(/62% left/);+ expect(api.getQuotaBurn).toHaveBeenCalledTimes(1);+ await act(async () => { socket.emit('connect'); });+ expect(api.getQuotaBurn).toHaveBeenCalledTimes(2);+ const visibility = vi.spyOn(document, 'visibilityState', 'get');+ visibility.mockReturnValue('hidden');+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'));+ socket.emit('provider-quota:updated', {});+ });+ expect(api.getQuotaBurn).toHaveBeenCalledTimes(2);+ visibility.mockReturnValue('visible');+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ expect(api.getQuotaBurn).toHaveBeenCalledTimes(3);+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });+ expect(api.getQuotaBurn).toHaveBeenCalledTimes(3);+ view.unmount();+ expect(socket.listenerCount('provider-quota:updated')).toBe(0);+ visibility.mockRestore();+ });+it('names WHICH window the reading describes', async () => {// A family publishes a short rolling window and a weekly one. "62% left ·// resets in 2.4h" is unreadable without knowing which allowance it is —@@ -233,9 +260,7 @@ describe('QuotaBurn page', () => {});it('does NOT poll when nothing is pending', async () => {- // Past a full poll interval, not the 100ms of wall clock this used to- // wait: a re-arming timer first fires at PENDING_POLL_MS, so a shorter- // window passed whether or not `enabled: anyPending` was there at all.+ // Advance past the retired four-second poll.vi.useFakeTimers({ shouldAdvanceTime: true });renderPage();await screen.findByText(/62% left/);@@ -890,7 +915,7 @@ describe('QuotaBurn save races', () => {expect(screen.getByText(/62% left/)).toBeInTheDocument();});- it('surfaces a background poll that failed, and clears it on the next poll that lands', async () => {+ it('surfaces a failed event refresh and clears it on reconnect', async () => {vi.useFakeTimers({ shouldAdvanceTime: true });try {const pendingStatus = {@@ -904,13 +929,13 @@ describe('QuotaBurn save races', () => {expect(await screen.findByText(/reading quota…/)).toBeInTheDocument();await act(async () => {- await vi.advanceTimersByTimeAsync(4000);+ socket.emit('provider-quota:updated', {});});expect(await screen.findByText(/Provider CLI is not responding/)).toBeInTheDocument();expect(screen.getByLabelText(/Run the quota-burn loop automatically/)).toBeInTheDocument();await act(async () => {- await vi.advanceTimersByTimeAsync(4000);+ socket.emit('connect');});expect(await screen.findByText(/62% left/)).toBeInTheDocument();expect(screen.queryByText(/Provider CLI is not responding/)).not.toBeInTheDocument();diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 6bf017407d..498c94d1c3 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -7,7 +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 { useQuotaPendingPoll } from '../hooks/useQuotaPendingPoll';+import { useQuotaUpdates } from '../hooks/useQuotaUpdates';import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';import FleetUsageCard from '../components/usage/FleetUsageCard';import FreeTierUsageCard from '../components/usage/FreeTierUsageCard';@@ -148,9 +148,8 @@ function ProviderQuotaSection() {});}, []);- // Cards still being scraped come back `pending`; the shared hook re-asks- // until the readings land. See hooks/useQuotaPendingPoll.js.- useQuotaPendingPoll(load, quotas);+ // Cards still being scraped come back `pending`; completion events reload them. See hooks/useQuotaUpdates.js.+ useQuotaUpdates(load);return (<div className="space-y-3">diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsxindex 9f05e252c4..a0bed0df2a 100644--- a/client/src/pages/UsagePage.test.jsx+++ b/client/src/pages/UsagePage.test.jsx@@ -1,5 +1,11 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import socket from '../services/socket';+vi.mock('../services/socket', async () => {+ const { EventEmitter } = await import('events');+ return { default: new EventEmitter() };+});+afterEach(() => vi.useRealTimers());+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';const api = vi.hoisted(() => ({@@ -41,6 +47,22 @@ beforeEach(() => {});describe('UsagePage subscription savings', () => {+ it('updates quota cards on completion without recurring fetches', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ render(<MemoryRouter><UsagePage /></MemoryRouter>);+ await waitFor(() => expect(api.getProviderUsage).toHaveBeenCalledTimes(1));+ await act(async () => { await vi.advanceTimersByTimeAsync(12_000); });+ expect(api.getProviderUsage).toHaveBeenCalledTimes(1);+ api.getProviderUsage.mockResolvedValue({ providers: [{+ family: 'claude', label: 'Claude Code', supported: true,+ limits: [{ key: 'week', label: 'Updated window', percentUsed: 73, percentRemaining: 27 }],+ }] });+ await act(async () => { socket.emit('provider-quota:updated', {}); });+ expect(await screen.findByText('Updated window')).toBeInTheDocument();+ expect(api.getProviderUsage).toHaveBeenCalledTimes(2);+ expect(api.getProviderUsage).toHaveBeenLastCalledWith({ refresh: false });+ });+const savings = {range: { start: '2026-02-01', end: '2026-02-07', days: 7 },configured: false,diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 554ebb6a1e..6c2323cdea 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -335,6 +335,11 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({summary: 'Invalidate one model after a persisted lifecycle change, including progress and deletion.',payloadSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } }, additionalProperties: false },},+ 'provider-quota:updated': {+ direction: 'server-to-client',+ summary: 'Invalidate quota cards after a background scrape settles, including failures; no account or quota data.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },'shell:attach': input(shellAttachSchema, 'Attach this socket to an existing terminal session.'),'shell:cd': input(shellCdSchema, 'Change an existing terminal session directory.'),'shell:input': input(shellInputSchema, 'Write bytes to an existing terminal session.'),diff --git a/server/lib/staleWhileRevalidate.js b/server/lib/staleWhileRevalidate.jsindex 8cf1643f8e..6cc5049ef7 100644--- a/server/lib/staleWhileRevalidate.js+++ b/server/lib/staleWhileRevalidate.js@@ -57,6 +57,7 @@ export const WAIT = Object.freeze({ FRESH: 'fresh', CACHED: 'cached', NEVER: 'ne* (a `/usage` panel that rendered without its limit lines); those are cached* for `partialTtlMs` so the next view self-heals — but still CACHED, because* not caching them at all turns every poll into a fresh subprocess spawn.+ * @param {() => void} [options.onSettled] Synchronous notification after success/failure is cached.* @param {number} [options.partialTtlMs] TTL for a reading `isComplete` rejects.*/export function createStaleWhileRevalidate({@@ -64,6 +65,7 @@ export function createStaleWhileRevalidate({failureBackoffMs = 30 * 1000,isComplete = () => true,partialTtlMs = 30 * 1000,+ onSettled,} = {}) {const entries = new Map(); // key -> { at, value, ttl, failedAt, inflight }@@ -86,6 +88,16 @@ export function createStaleWhileRevalidate({const { at, value, ttl } = entries.get(key) || {};entries.set(key, { at, value, ttl, failedAt: Date.now() });return { error };+ })+ .then(result => {+ // A notification failure must not turn a good reading into a failed+ // production or reject an unobserved background refresh.+ try {+ onSettled?.();+ } catch (error) {+ console.error(`❌ Cache settlement notification failed: ${error.message}`);+ }+ return result;});entries.set(key, { ...entries.get(key), inflight });return inflight;diff --git a/server/lib/staleWhileRevalidate.test.js b/server/lib/staleWhileRevalidate.test.jsindex d83d5b6ba4..1822c61b4c 100644--- a/server/lib/staleWhileRevalidate.test.js+++ b/server/lib/staleWhileRevalidate.test.js@@ -126,6 +126,22 @@ describe('createStaleWhileRevalidate', () => {expect(await cache.read('k', produce)).toBe('full'); // …and revalidated});+ it('keeps a settled reading usable when its synchronous notification throws', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const cache = createStaleWhileRevalidate({+ ttlMs: TTL, onSettled: () => { throw new Error('example listener failure'); },+ });+ const produce = vi.fn().mockResolvedValue('reading');+ expect(await cache.read('k', produce)).toBe('reading');+ expect(await cache.read('k', produce)).toBe('reading');+ expect(produce).toHaveBeenCalledTimes(1);+ expect(error).toHaveBeenCalledTimes(1);+ } finally {+ error.mockRestore();+ }+ });+it('keys entries independently and clears them', async () => {const cache = createStaleWhileRevalidate({ ttlMs: TTL });await cache.read('a', () => Promise.resolve(1));diff --git a/server/services/claudeCodeUsage.js b/server/services/claudeCodeUsage.jsindex c74102c57d..225fa82d5f 100644--- a/server/services/claudeCodeUsage.js+++ b/server/services/claudeCodeUsage.js@@ -1,3 +1,4 @@+import { notifyProviderQuotaUpdated } from './providerQuotaEvents.js';import { spawn } from '../lib/childProcess.js';import { existsSync, lstatSync, readlinkSync, readFileSync } from 'fs';import { stripAnsi } from '../lib/ansiStrip.js';@@ -199,6 +200,7 @@ export function parseUsageOutput(text, { now = Date.now(), timezone } = {}) {const CACHE_KEY = 'claude-code-usage';const usageCache = createStaleWhileRevalidate({ttlMs: CACHE_TTL_MS,+ onSettled: notifyProviderQuotaUpdated,isComplete: (data) => data.limits.length > 0,});diff --git a/server/services/providerQuotaEvents.js b/server/services/providerQuotaEvents.jsnew file mode 100644index 0000000000..bdef542827--- /dev/null+++ b/server/services/providerQuotaEvents.js@@ -0,0 +1,5 @@+import { EventEmitter } from 'node:events';++// No readings, credentials or invocation cache keys cross this boundary.+export const providerQuotaEvents = new EventEmitter();+export const notifyProviderQuotaUpdated = () => providerQuotaEvents.emit('updated', {});diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 82e2f2c59e..f3dc634e3a 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -1,3 +1,4 @@+import { notifyProviderQuotaUpdated } from './providerQuotaEvents.js';import { isProcessProvider } from '../lib/providerTypes.js';import { readdir } from 'fs/promises';import { join } from 'path';@@ -486,6 +487,7 @@ export async function fetchCodexQuota({ codexHome = codexHomeDir(), now = Date.n// (leaving it uncached turns each poll into a fresh PTY spawn).const scrapeCache = createStaleWhileRevalidate({ttlMs: 5 * 60 * 1000,+ onSettled: notifyProviderQuotaUpdated,isComplete: (card) => Boolean(card?.limits?.length),});diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsindex 223d9eb387..23b8ba1719 100644--- a/server/services/providerUsage.test.js+++ b/server/services/providerUsage.test.js@@ -1,3 +1,4 @@+import { providerQuotaEvents } from './providerQuotaEvents.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// providerUsage imports the provider config service (toolkit-backed) and the@@ -867,8 +868,9 @@ describe('TUI usage fetchers (via getProviderQuotas)', () => {const [pending] = await getProviderQuotas({ wait: 'never' });expect(pending).toMatchObject({ family: 'agy', supported: true, pending: true, limits: [] });- // The scrape was STARTED, not skipped — once it lands the next read is real.+ const updated = new Promise(resolve => providerQuotaEvents.once('updated', resolve));release(AGY_PANEL);+ expect(await updated).toEqual({});await vi.waitFor(async () => {const [card] = await getProviderQuotas({ wait: 'never' });expect(card.pending).toBeUndefined();@@ -877,6 +879,21 @@ describe('TUI usage fetchers (via getProviderQuotas)', () => {expect(scrapeTuiUsage).toHaveBeenCalledTimes(1);});+ it('notifies cold scrape failure so pending cards become errors without retrying', async () => {+ getAllProviders.mockResolvedValue({ providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });+ let reject;+ scrapeTuiUsage.mockReturnValueOnce(new Promise((_, fail) => { reject = fail; }));+ const [pending] = await getProviderQuotas({ wait: 'never' });+ expect(pending.pending).toBe(true);+ const updated = new Promise(resolve => providerQuotaEvents.once('updated', resolve));+ reject(new Error('example scrape failure'));+ expect(await updated).toEqual({});+ const [failed] = await getProviderQuotas({ wait: 'never' });+ expect(failed.pending).toBeUndefined();+ expect(failed.error).toBeTruthy();+ expect(scrapeTuiUsage).toHaveBeenCalledTimes(1);+ });+it("blocks for a real reading under the default wait and under wait:'fresh'", async () => {getAllProviders.mockResolvedValue({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);diff --git a/server/services/socket.js b/server/services/socket.jsindex 5fdc2f764c..7908f5c640 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 { providerQuotaEvents } from './providerQuotaEvents.js';import { wireProactiveTriggers } from './voice/proactiveTriggers.js';import { callStateEvents } from './voice/callSession.js';import {@@ -244,6 +245,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));+ providerQuotaEvents.on('updated', () => ioInstance?.emit('provider-quota:updated', {}));setupCosEventForwarding();setupErrorEventForwarding();setupAppsEventForwarding();diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 5b1ed3a02c..5fdb508e3e 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -6,6 +6,7 @@ import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './simport { fableLoomRunEvents } from './fableLoom/runEvents.js';import { trainingEvents } from './loraTraining/events.js';import { authEvents } from './auth.js';+import { providerQuotaEvents } from './providerQuotaEvents.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Preserve installed once-only listeners across Vitest's per-test mock-call@@ -154,6 +155,7 @@ describe('socket.js — initSocket', () => {meatspaceEvents.removeAllListeners();dashboardEvents.removeAllListeners();modelLifecycleEvents.removeAllListeners();+ providerQuotaEvents.removeAllListeners();});it('coalesces environment changes into payload-free Mind visibility invalidations for subscribers', () => {@@ -194,6 +196,12 @@ describe('socket.js — initSocket', () => {]);});+ it('forwards quota completion without leaking source data', () => {+ io.emitted.length = 0;+ providerQuotaEvents.emit('updated', { privateContent: 'example account detail' });+ expect(io.emitted).toEqual([['provider-quota:updated', {}]]);+ });+it('forwards death-clock invalidations without personal data', () => {io.emitted.length = 0;meatspaceEvents.emit('death-clock:changed', {});