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

add a per-provider refresh button to the Usage page's subscription cards

[._.]/ Adam Eivy6795e814205c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8c572cd268..492b38c5ad 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -56,3 +56,4 @@
- **A provider's reset time is an instant, not the wording its CLI happened to use.** Two of the four quota adapters put a raw panel string on the wire — claude's `Aug 4 at 1:59pm` plus a separate `timezone` field, grok's year-less `August 10, 06:07` — so the Usage page printed those two verbatim while codex and agy rendered properly: the same field, formatted two ways on one screen, with no localization and no relative time. The parsing stays in `server/lib/quotaReset.js` but is now exported as `parseHumanReset(str, { now, timezone })` and called from `parseLimitLine` and `parseGrokUsage`, so `resetsAt` is ISO 8601 (or `null` when unreadable) for all four families and a fifth provider's dialect belongs in its own adapter rather than in the shared choke point. Both parsers take `now` explicitly, as `parseAgyUsage` already did. `normalizeResetAt` keeps its wall-clock fallback — a reading off an older federated peer still carries the raw string and must not regress to "no window states a reset time" — but every in-tree adapter now hits its `hasExplicitZone` fast path. The Usage page localizes the instant and adds the countdown (`Aug 4, 1:59 PM (in 3h)`). (#3433)
- **Unarchiving your last archived app no longer strands you on a blank Apps page.** The Active/Archived toggle only rendered while at least one archived app existed, and `showArchived` was local state with nothing to reset it — so unarchiving the last one unmounted the only control on screen and left a permanently empty "No archived apps" card, recoverable only by navigating away and back. The filter now lives in the URL (`/apps?view=archived`), so the archived list is linkable and reload-safe; the toggle stays mounted while the archived view is open even once it empties (reading `Active (N)`), and the empty state gained a "Back to active apps" button. (#3434)
- **"Open in Xcode" opens the actual project instead of guessing its filename.** The button built `<display name>.xcodeproj` on the client and navigated to an `xcode://` URL, so any app whose display name wasn't byte-identical to its project on disk ("My Client" → `MyClient.xcodeproj`) got a path that doesn't exist — and a custom-scheme navigation reports nothing either way, so the click was a silent no-op, doubly so from a phone where the scheme isn't registered at all. The new `POST /api/apps/:id/open-xcode` resolves the real target the same way the Xcode script generators do (`deriveProjectInfo`: `project.yml` `name:` → the `*.xcodeproj` on disk → the sanitized app name), prefers a `.xcworkspace` over the `.xcodeproj` it wraps, and opens it on the machine Xcode is installed on. A `swift` SPM package — which has no `.xcodeproj` at all — falls back to its `Package.swift`, and a repo with none of the three comes back as a 404 naming everything it looked for, so the click always ends in a visible toast. (#3438)
+- **Each provider card on the Usage page refreshes on its own.** Every family's reading is an independent 10-20s CLI/TUI scrape, so the single "Refresh" button made re-checking one provider cost a spawn for all of them — and reset every other card's reading age in the process. `GET /api/usage/providers` now takes `?family=<id>`, `getProviderQuotas({ family })` resolves just that card (the derived image-gen card included), and each card carries its own refresh control that swaps in only its own result. A family that no longer resolves — its provider was disabled since the page loaded — comes back as an empty list and the card is dropped rather than left with a reading it can never refresh again. The section button is now "Refresh all".
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index b9b4f505cf..8d782db7b5 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -90,14 +90,29 @@ function StatTile({ label, value, detail }) {
// One subscription-quota card per enabled provider family. Providers with no
// queryable usage surface (supported: false) render a muted note, never an
// error; a supported adapter that failed transiently shows a soft warning.
-function ProviderQuotaCard({ quota }) {
+function ProviderQuotaCard({ quota, onRefresh, refreshing, disabled }) {
return (
<div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">
- <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center justify-between gap-2 mb-2">
<h3 className="text-base font-semibold text-white">{quota.label}</h3>
- {quota.plan && quota.plan !== 'unknown' && (
- <Pill tone="context" size="xs">{quota.plan}</Pill>
- )}
+ <div className="flex items-center gap-2 shrink-0">
+ {quota.plan && quota.plan !== 'unknown' && (
+ <Pill tone="context" size="xs">{quota.plan}</Pill>
+ )}
+ {/* Per-card refresh: every family's reading is its own multi-second
+ CLI/TUI scrape, so re-reading one provider must not respawn all
+ of them. */}
+ <button
+ type="button"
+ onClick={() => onRefresh(quota.family)}
+ disabled={refreshing || disabled}
+ className="text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed"
+ title={`Refresh ${quota.label} usage`}
+ aria-label={`Refresh ${quota.label} usage`}
+ >
+ <RefreshCw size={14} className={refreshing ? 'animate-spin' : ''} />
+ </button>
+ </div>
</div>
{!quota.supported && (
@@ -180,6 +195,7 @@ function ProviderQuotaSection() {
const [quotas, setQuotas] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
+ const [refreshingFamilies, setRefreshingFamilies] = useState(() => new Set());
const load = useCallback(async (refresh = false) => {
setLoading(true);
@@ -196,6 +212,31 @@ function ProviderQuotaSection() {
useEffect(() => { load(); }, [load]);
+ // Refresh ONE provider card. The whole-section Refresh spawns every family's
+ // scrape at once (10-20s each); this asks for the single card the user
+ // clicked and swaps it in when the reading lands, leaving every other card's
+ // reading — and its age — untouched. A failure toasts through the request
+ // helper; the catch here only clears the spinner, it owns no error UI.
+ const refreshFamily = useCallback(async (family) => {
+ setRefreshingFamilies((prev) => new Set(prev).add(family));
+ const result = await api.getProviderUsage({ refresh: true, family, silent: false }).catch(() => null);
+ if (result?.providers) {
+ const card = result.providers.find((q) => q.family === family);
+ // No card back for a family we asked for means it is no longer enabled
+ // (its provider was turned off) — drop it rather than leave a reading
+ // that can never refresh again. `prev` is always an array here: the
+ // button that got us here only renders once quotas have loaded.
+ setQuotas((prev) => (card
+ ? prev.map((q) => (q.family === family ? card : q))
+ : prev.filter((q) => q.family !== family)));
+ }
+ setRefreshingFamilies((prev) => {
+ const next = new Set(prev);
+ next.delete(family);
+ return next;
+ });
+ }, []);
+
// A quota read never blocks the response: a cold cache answers with `pending`
// cards and the reading lands behind it. Without this poll those cards would
// sit on "reading quota…" until the user hit Refresh by hand. Enabled only
@@ -211,9 +252,9 @@ function ProviderQuotaSection() {
onClick={() => load(true)}
disabled={loading}
className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-400 hover:text-white disabled:opacity-50"
- title="Refresh provider usage"
+ title="Refresh every provider's usage"
>
- <RefreshCw size={15} className={loading ? 'animate-spin' : ''} /> Refresh
+ <RefreshCw size={15} className={loading ? 'animate-spin' : ''} /> Refresh all
</button>
</div>
@@ -231,7 +272,13 @@ function ProviderQuotaSection() {
{quotas && (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3 sm:gap-4">
{quotas.map((quota) => (
- <ProviderQuotaCard key={quota.family} quota={quota} />
+ <ProviderQuotaCard
+ key={quota.family}
+ quota={quota}
+ onRefresh={refreshFamily}
+ refreshing={refreshingFamilies.has(quota.family)}
+ disabled={loading}
+ />
))}
{quotas.length === 0 && (
<div className="text-gray-500 text-sm">No enabled providers report subscription usage.</div>
diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsx
index 78c927baf8..67c6bd8db5 100644
--- a/client/src/pages/UsagePage.test.jsx
+++ b/client/src/pages/UsagePage.test.jsx
@@ -104,6 +104,48 @@ describe('UsagePage breakdown visualization and responsiveness', () => {
});
});
+describe('UsagePage per-provider refresh', () => {
+ const card = (family, label, percentUsed) => ({
+ family,
+ label,
+ supported: true,
+ limits: [{ key: 'week', label: 'Weekly', percentUsed, percentRemaining: 100 - percentUsed }],
+ activity: [],
+ approximate: true,
+ fetchedAt: new Date().toISOString()
+ });
+
+ beforeEach(() => {
+ api.getProviderUsage.mockResolvedValue({ providers: [card('claude', 'Claude Code', 10), card('grok', 'Grok', 20)] });
+ });
+
+ it('re-reads only the clicked provider and swaps that card in', async () => {
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+
+ await screen.findByText('Grok');
+ expect(await screen.findByText('20% used')).toBeInTheDocument();
+
+ api.getProviderUsage.mockResolvedValueOnce({ providers: [card('grok', 'Grok', 77)] });
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh Grok usage' }));
+
+ await waitFor(() => expect(api.getProviderUsage).toHaveBeenCalledWith({ refresh: true, family: 'grok', silent: false }));
+ // The refreshed card updates; the untouched Claude card keeps its reading.
+ expect(await screen.findByText('77% used')).toBeInTheDocument();
+ expect(screen.getByText('10% used')).toBeInTheDocument();
+ });
+
+ it('drops a card whose provider is no longer enabled', async () => {
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+ await screen.findByText('Grok');
+
+ api.getProviderUsage.mockResolvedValueOnce({ providers: [] });
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh Grok usage' }));
+
+ await waitFor(() => expect(screen.queryByText('Grok')).not.toBeInTheDocument());
+ expect(screen.getByText('Claude Code')).toBeInTheDocument();
+ });
+});
+
describe('UsagePage provider reset times', () => {
it('localizes an ISO reset and adds the relative countdown', async () => {
// A minute past the 3h mark, so the floor in `timeUntil` can't round to 2h.
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 2577ff45f8..06638926ba 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -119,9 +119,16 @@ export const startUsageBackfill = (options = {}) => request('/usage/backfill', {
// Subscription-quota status for every enabled provider family (claude, codex,
-// agy, grok). Callers own their inline error UI — silent by default.
-export const getProviderUsage = ({ refresh = false, ...options } = {}) =>
- request(`/usage/providers${refresh ? '?refresh=1' : ''}`, { silent: true, ...options });
+// agy, grok). Callers own their inline error UI — silent by default. `family`
+// narrows the read to a single card (the usage page's per-card Refresh) so one
+// provider's multi-second scrape isn't paid for all of them.
+export const getProviderUsage = ({ refresh = false, family = null, ...options } = {}) => {
+ const qs = new URLSearchParams();
+ if (refresh) qs.set('refresh', '1');
+ if (family) qs.set('family', family);
+ const query = qs.toString();
+ return request(`/usage/providers${query ? `?${query}` : ''}`, { silent: true, ...options });
+};
// Backup
export const getBackupStatus = (options) => request('/backup/status', options);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index e1f8c3e8ca..9eac3ca2a2 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -801,6 +801,14 @@ 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/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. */
+export const providerUsageQuerySchema = z.object({
+ refresh: z.enum(['0', '1', 'true', 'false']).optional(),
+ family: z.string().regex(/^[a-z0-9-]{1,32}$/, 'family must be a provider family id').optional()
+});
+
/** Body for POST /api/usage/messages — token counts persist forever, so
* reject non-integer/negative garbage instead of coercing it into counters. */
export const usageMessagesSchema = z.object({
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 663be345c0..48c6616d7f 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -4,7 +4,7 @@ import { getClaudeCodeUsage } from '../services/claudeCodeUsage.js';
import { getProviderQuotas } from '../services/providerUsage.js';
import { getAllProviders } from '../services/providers.js';
import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest, usageQuerySchema, usageMessagesSchema } from '../lib/validation.js';
+import { validateRequest, usageQuerySchema, usageMessagesSchema, providerUsageQuerySchema } from '../lib/validation.js';
import { resolveUsageRange } from '../lib/usageRange.js';
import { WAIT } from '../lib/staleWhileRevalidate.js';
import {
@@ -35,9 +35,15 @@ router.get('/', asyncHandler(async (req, res) => {
// Holding an HTTP response open for a 10-20s PTY spawn is what made this page —
// and Quota Burn — look broken, and it is the shape that trips proxy timeouts.
// `?refresh=1` is the explicit "get me a live reading" and does wait.
+//
+// `?family=<id>` narrows the read to a single card, so the page's per-card
+// Refresh re-reads only the provider the user clicked instead of respawning
+// every provider's TUI scrape. An id that no longer resolves to an enabled
+// family answers with an empty list — the card is gone, not broken.
router.get('/providers', asyncHandler(async (req, res) => {
- const refresh = req.query.refresh === '1' || req.query.refresh === 'true';
- const providers = await getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER });
+ const { refresh: refreshParam, family } = validateRequest(providerUsageQuerySchema, req.query);
+ const refresh = refreshParam === '1' || refreshParam === 'true';
+ const providers = await getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER, family: family ?? null });
res.json({ providers });
}));
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index e00cd02fc8..bbd50b6b7f 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -110,7 +110,21 @@ describe('usage routes', () => {
const res = await request(buildApp()).get('/api/usage/providers?refresh=1');
expect(res.status).toBe(200);
expect(res.body.providers).toHaveLength(2);
- expect(getProviderQuotas).toHaveBeenCalledWith({ wait: 'fresh' });
+ expect(getProviderQuotas).toHaveBeenCalledWith({ wait: 'fresh', family: null });
+ });
+
+ it('GET /api/usage/providers narrows the read to one family', async () => {
+ getProviderQuotas.mockResolvedValue([{ family: 'grok', supported: true, limits: [] }]);
+ const res = await request(buildApp()).get('/api/usage/providers?refresh=1&family=grok');
+ expect(res.status).toBe(200);
+ expect(res.body.providers).toEqual([{ family: 'grok', supported: true, limits: [] }]);
+ expect(getProviderQuotas).toHaveBeenCalledWith({ wait: 'fresh', family: 'grok' });
+ });
+
+ it('GET /api/usage/providers rejects a malformed family id', async () => {
+ const res = await request(buildApp()).get('/api/usage/providers?family=../etc');
+ expect(res.status).toBe(400);
+ expect(getProviderQuotas).not.toHaveBeenCalled();
});
it('POST /api/usage/messages rejects negative or non-integer token counts', async () => {
diff --git a/server/services/imageGenQuota.js b/server/services/imageGenQuota.js
index 617b6342ee..83d02530b2 100644
--- a/server/services/imageGenQuota.js
+++ b/server/services/imageGenQuota.js
@@ -63,6 +63,10 @@ const MODE_LABELS = Object.freeze({
export const isQuotaTrackedImageMode = (mode) => CLOUD_IMAGE_GEN_MODES.includes(mode);
+/** Card id for the image-gen quota card, in the same namespace as the provider
+ * family ids in providerUsage.js — a per-family read has to be able to name it. */
+export const IMAGE_GEN_FAMILY = 'imagegen';
+
const rowLabel = (mode) =>
`${MODE_LABELS[mode] || mode} · ${IMAGE_TOOL_NAMES[mode] || 'image tool'}`;
@@ -240,7 +244,7 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =
// to avoid. Say so instead.
if (!ledger) {
return {
- family: 'imagegen',
+ family: IMAGE_GEN_FAMILY,
label: 'Image Gen',
supported: true,
burnable: false,
@@ -291,7 +295,7 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =
}
return {
- family: 'imagegen',
+ family: IMAGE_GEN_FAMILY,
label: 'Image Gen',
supported: true,
// Not a burnable quota target: these cards carry no measurable headroom,
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index d548b059fc..70c81584ef 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -9,7 +9,7 @@ import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';
import { parseHumanReset } from '../lib/quotaReset.js';
import { getSettings } from './settings.js';
-import { getImageGenQuota } from './imageGenQuota.js';
+import { getImageGenQuota, IMAGE_GEN_FAMILY } from './imageGenQuota.js';
import { enabledCloudImageModes } from './imageGen/modes.js';
/**
@@ -544,18 +544,25 @@ const fetchFamilyQuota = (family, { wait, providers }) =>
* one; `'never'` answers a cold cache with a `pending: true` card, for pages
* that render "still reading" and poll; `'fresh'` bypasses the caches entirely
* and waits — an explicit Refresh, or a burn cycle about to spend real quota.
+ *
+ * `family` narrows the read to one card. Each family's reading is an
+ * independent multi-second scrape, so the usage page's per-card Refresh asks
+ * for exactly the one the user clicked instead of respawning every provider's
+ * TUI. A family id that isn't enabled resolves to an empty list — the caller
+ * reads that as "this card is gone", not as an error.
*/
-export async function getProviderQuotas({ wait = WAIT.CACHED } = {}) {
+export async function getProviderQuotas({ wait = WAIT.CACHED, family = null } = {}) {
const result = await getAllProviders();
const providers = Array.isArray(result) ? result : (result?.providers || []);
const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true);
- const families = resolveEnabledFamilies(providers);
- const familyCards = await Promise.all(families.map((family) =>
- fetchFamilyQuota(family, { wait, providers: enabled.filter((p) => family.matches(p)) })));
+ const families = resolveEnabledFamilies(providers).filter((f) => !family || f.id === family);
+ const familyCards = await Promise.all(families.map((f) =>
+ fetchFamilyQuota(f, { wait, providers: enabled.filter((p) => f.matches(p)) })));
// Image gen last: it is a derived/observed card, not a provider-family
// scrape, and it reads as a footnote to the model-quota cards above it. Not
// raced with the family scrapes — this is two small local file reads against
// their multi-second TUI PTY spawns, so concurrency would buy no wall-clock.
+ if (family && family !== IMAGE_GEN_FAMILY) return familyCards;
const imageCard = await fetchImageGenQuota();
return imageCard ? [...familyCards, imageCard] : familyCards;
}
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 9c0e62c5cb..044a46b25d 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -23,6 +23,7 @@ vi.mock('./settings.js', () => ({
getSettings: vi.fn().mockResolvedValue({ imageGen: {} })
}));
vi.mock('./imageGenQuota.js', () => ({
+ IMAGE_GEN_FAMILY: 'imagegen',
getImageGenQuota: vi.fn(async ({ enabledModes }) => (enabledModes.length ? {
family: 'imagegen', label: 'Image Gen', supported: true, burnable: false,
limits: [], activity: [], metrics: enabledModes.map((m) => ({ key: m, label: m, value: '0 renders · 24h' })),
@@ -164,6 +165,14 @@ describe('resolveEnabledFamilies', () => {
});
describe('getProviderQuotas', () => {
+ // The TUI-scrape cache and the mock call counts both outlive a single test —
+ // reset so the per-family assertions below aren't order-dependent.
+ beforeEach(() => {
+ __resetUsageScrapeCache();
+ scrapeTuiUsage.mockReset();
+ getImageGenQuota.mockClear();
+ });
+
it('unwraps the { providers } object shape from getAllProviders', async () => {
// Regression: getAllProviders returns { activeProvider, providers }, not a
// bare array — passing the object straight into resolveEnabledFamilies threw
@@ -195,6 +204,40 @@ describe('getProviderQuotas', () => {
getSettings.mockResolvedValueOnce({ imageGen: { local: { enabled: true } } });
expect(await getProviderQuotas()).toEqual([]);
});
+
+ it('reads only the requested family — the point of the per-card refresh', async () => {
+ // A second family's reading is a second multi-second TUI spawn, so asking
+ // for one card must not scrape the other (nor derive the image card).
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: null,
+ providers: [
+ { id: 'grok', enabled: true, type: 'tui', command: 'grok' },
+ { id: 'agy', enabled: true, type: 'tui', command: 'agy' }
+ ]
+ });
+ getSettings.mockResolvedValueOnce({ imageGen: { agy: { enabled: true } } });
+ scrapeTuiUsage.mockResolvedValue('Weekly limit: 5% Next reset: Jan 1, 00:00');
+ const quotas = await getProviderQuotas({ family: 'grok' });
+ expect(quotas.map((q) => q.family)).toEqual(['grok']);
+ expect(scrapeTuiUsage).toHaveBeenCalledTimes(1);
+ expect(getImageGenQuota).not.toHaveBeenCalled();
+ });
+
+ it('reads the image-gen card alone when it is the requested family', async () => {
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: null,
+ providers: [{ id: 'grok', enabled: true, type: 'tui', command: 'grok' }]
+ });
+ getSettings.mockResolvedValueOnce({ imageGen: { agy: { enabled: true } } });
+ const quotas = await getProviderQuotas({ family: 'imagegen' });
+ expect(quotas.map((q) => q.family)).toEqual(['imagegen']);
+ expect(scrapeTuiUsage).not.toHaveBeenCalled();
+ });
+
+ it('returns nothing for a family that is no longer enabled', async () => {
+ getAllProviders.mockResolvedValueOnce({ activeProvider: null, providers: [] });
+ expect(await getProviderQuotas({ family: 'grok' })).toEqual([]);
+ });
});
describe('agyRefreshToIso', () => {