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

feat: show imagegen renders per week, month, and reset period on usage page

Adam Eivy3d96a9303646
diff --git a/client/src/components/usage/ProviderQuotaBody.jsx b/client/src/components/usage/ProviderQuotaBody.jsx
index 0f4a76b6c8..6b39407f49 100644
--- a/client/src/components/usage/ProviderQuotaBody.jsx
+++ b/client/src/components/usage/ProviderQuotaBody.jsx
@@ -1,3 +1,4 @@
+import { useState, useMemo } from 'react';
import { AlertTriangle } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import UsageMeter from './UsageMeter';
@@ -32,7 +33,32 @@ export function StatTile({ label, value, detail }) {
}
export default function ProviderQuotaBody({ quota, showActivity = true, showNote = true }) {
+ const [selectedPeriod, setSelectedPeriod] = useState(quota?.period || '24h');
+
+ const hasPeriods = Boolean(
+ quota?.metrics?.some((m) => m.periods && Object.keys(m.periods).length > 0)
+ );
+
+ const availablePeriods = useMemo(() => {
+ if (!hasPeriods || !quota?.metrics) return [];
+ const keys = new Set();
+ for (const m of quota.metrics) {
+ if (m.periods) {
+ for (const k of Object.keys(m.periods)) keys.add(k);
+ }
+ }
+ const order = ['24h', '7d', '30d', 'reset'];
+ const labels = {
+ '24h': '24h',
+ '7d': 'Week',
+ '30d': 'Month',
+ reset: 'Reset',
+ };
+ return order.filter((k) => keys.has(k)).map((k) => ({ key: k, label: labels[k] || k }));
+ }, [hasPeriods, quota?.metrics]);
+
if (!quota) return null;
+
// Whether this card has anything to put on screen — the pending branch and the
// empty state ask the same question from opposite sides, so they ask it once.
const hasReadings = Boolean(quota.limits?.length || quota.metrics?.length);
@@ -103,13 +129,39 @@ export default function ProviderQuotaBody({ quota, showActivity = true, showNote
{/* Backends with no queryable quota report observed counts instead of
a meter — a percentage we cannot measure must not be invented. */}
{quota.metrics?.length > 0 && (
- // One tile per row on a phone: these cells sit inside an already
- // half-width mobile card, and two columns of it wrapped a tile's
- // label and detail onto four lines apiece.
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
- {quota.metrics.map((m) => (
- <StatTile key={m.key} label={m.label} value={m.value} detail={m.detail} />
- ))}
+ <div className="space-y-1.5 sm:space-y-2">
+ {availablePeriods.length > 1 && (
+ <div className="flex items-center gap-1" role="group" aria-label="Usage period">
+ {availablePeriods.map((p) => {
+ const active = selectedPeriod === p.key;
+ return (
+ <button
+ key={p.key}
+ type="button"
+ onClick={() => setSelectedPeriod(p.key)}
+ className={`px-2 py-0.5 rounded text-[10px] sm:text-xs font-medium transition-colors ${
+ active
+ ? 'bg-port-accent text-white shadow-xs'
+ : 'text-gray-400 hover:text-white bg-port-bg border border-port-border'
+ }`}
+ >
+ {p.label}
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ {quota.metrics.map((m) => {
+ const periodData = m.periods?.[selectedPeriod];
+ const value = periodData?.value ?? m.value;
+ const detail = periodData?.detail ?? m.detail;
+ return (
+ <StatTile key={m.key} label={m.label} value={value} detail={detail} />
+ );
+ })}
+ </div>
</div>
)}
diff --git a/client/src/components/usage/ProviderQuotaBody.test.jsx b/client/src/components/usage/ProviderQuotaBody.test.jsx
new file mode 100644
index 0000000000..dcfaf1a4df
--- /dev/null
+++ b/client/src/components/usage/ProviderQuotaBody.test.jsx
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import ProviderQuotaBody from './ProviderQuotaBody';
+
+describe('ProviderQuotaBody', () => {
+ it('renders unsupported message when supported is false', () => {
+ render(<ProviderQuotaBody quota={{ supported: false, note: 'Not supported' }} />);
+ expect(screen.getByText('Not supported')).toBeInTheDocument();
+ });
+
+ it('renders pending state when pending is true without readings', () => {
+ render(<ProviderQuotaBody quota={{ supported: true, pending: true, limits: [], metrics: [] }} />);
+ expect(screen.getByText('Reading quota…')).toBeInTheDocument();
+ });
+
+ it('renders error state when error is present', () => {
+ render(<ProviderQuotaBody quota={{ supported: true, error: 'Network error', limits: [], metrics: [] }} />);
+ expect(screen.getByRole('status')).toHaveTextContent('Network error');
+ });
+
+ it('renders metric without periods in single grid', () => {
+ const quota = {
+ supported: true,
+ limits: [],
+ metrics: [
+ { key: 'm1', label: 'Codex · image_gen', value: '3 renders · 24h', detail: 'quota not reported' },
+ ],
+ };
+ render(<ProviderQuotaBody quota={quota} />);
+ expect(screen.getByText('Codex · image_gen')).toBeInTheDocument();
+ expect(screen.getByText('3 renders · 24h')).toBeInTheDocument();
+ expect(screen.getByText('quota not reported')).toBeInTheDocument();
+ expect(screen.queryByRole('group', { name: 'Usage period' })).not.toBeInTheDocument();
+ });
+
+ it('renders period toggle and updates metric tiles when toggling periods', () => {
+ const quota = {
+ supported: true,
+ limits: [],
+ period: '24h',
+ metrics: [
+ {
+ key: 'imagegen-agy',
+ label: 'Agy · generate_image',
+ value: '1 render · 24h',
+ detail: 'quota not reported by this CLI',
+ periods: {
+ '24h': { key: '24h', label: '24h', count: 1, failed: 0, value: '1 render · 24h', detail: 'quota not reported by this CLI' },
+ '7d': { key: '7d', label: 'Week', count: 5, failed: 1, value: '5 renders · week', detail: '1 failed' },
+ '30d': { key: '30d', label: 'Month', count: 14, failed: 2, value: '14 renders · month', detail: '2 failed' },
+ reset: { key: 'reset', label: 'Reset', count: 3, failed: 0, value: '3 renders · reset', detail: 'since last reset' },
+ },
+ },
+ ],
+ };
+
+ render(<ProviderQuotaBody quota={quota} />);
+
+ // Period buttons should be present
+ const group = screen.getByRole('group', { name: 'Usage period' });
+ expect(group).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: '24h' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Week' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Month' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Reset' })).toBeInTheDocument();
+
+ // Default 24h view
+ expect(screen.getByText('1 render · 24h')).toBeInTheDocument();
+
+ // Switch to Week
+ fireEvent.click(screen.getByRole('button', { name: 'Week' }));
+ expect(screen.getByText('5 renders · week')).toBeInTheDocument();
+ expect(screen.getByText('1 failed')).toBeInTheDocument();
+
+ // Switch to Month
+ fireEvent.click(screen.getByRole('button', { name: 'Month' }));
+ expect(screen.getByText('14 renders · month')).toBeInTheDocument();
+ expect(screen.getByText('2 failed')).toBeInTheDocument();
+
+ // Switch to Reset
+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }));
+ expect(screen.getByText('3 renders · reset')).toBeInTheDocument();
+ expect(screen.getByText('since last reset')).toBeInTheDocument();
+
+ // Switch back to 24h
+ fireEvent.click(screen.getByRole('button', { name: '24h' }));
+ expect(screen.getByText('1 render · 24h')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsx
index da82bb9404..26675881f4 100644
--- a/client/src/pages/UsagePage.test.jsx
+++ b/client/src/pages/UsagePage.test.jsx
@@ -471,6 +471,42 @@ describe('UsagePage mobile provider-card layout', () => {
expect.arrayContaining(['grid-cols-1', 'sm:grid-cols-2'])
);
});
+
+ it('supports toggling imagegen render periods between 24h, week, and month', async () => {
+ const cardWithPeriods = {
+ family: 'imagegen',
+ label: 'Image Gen',
+ supported: true,
+ limits: [],
+ activity: [],
+ period: '24h',
+ metrics: [
+ {
+ key: 'imagegen-agy',
+ label: 'Agy · generate_image',
+ value: '2 renders · 24h',
+ detail: 'quota not reported by this CLI',
+ periods: {
+ '24h': { key: '24h', label: '24h', count: 2, failed: 0, value: '2 renders · 24h', detail: 'quota not reported by this CLI' },
+ '7d': { key: '7d', label: 'Week', count: 7, failed: 1, value: '7 renders · week', detail: '1 failed' },
+ '30d': { key: '30d', label: 'Month', count: 25, failed: 1, value: '25 renders · month', detail: '1 failed' },
+ },
+ },
+ ],
+ };
+
+ api.getProviderUsage.mockResolvedValue({ providers: [cardWithPeriods] });
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+
+ await screen.findByRole('heading', { name: 'Image Gen' });
+ expect(screen.getByText('2 renders · 24h')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Week' }));
+ expect(screen.getByText('7 renders · week')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Month' }));
+ expect(screen.getByText('25 renders · month')).toBeInTheDocument();
+ });
});
describe('arrangeQuotaCells', () => {
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 3fed9a08ce..18130350f7 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -290,10 +290,11 @@ export const startUsageBackfill = (options = {}) => request('/usage/backfill', {
// 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 } = {}) => {
+export const getProviderUsage = ({ refresh = false, family = null, period = null, ...options } = {}) => {
const qs = new URLSearchParams();
if (refresh) qs.set('refresh', '1');
if (family) qs.set('family', family);
+ if (period) qs.set('period', period);
const query = qs.toString();
return request(`/usage/providers${query ? `?${query}` : ''}`, { silent: true, ...options });
};
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 41baec6096..9f1dda39bd 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1696,7 +1696,8 @@ export const usageRollingCostQuerySchema = z.object({
* 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()
+ family: z.string().regex(/^[a-z0-9-]{1,32}$/, 'family must be a provider family id').optional(),
+ period: z.enum(['24h', '7d', '30d', 'week', 'month', 'reset']).optional(),
});
/** Body for POST /api/usage/messages — token counts persist forever, so
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 826f1a3339..89bef8a2f6 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -140,9 +140,13 @@ router.put('/fleet-billing', asyncHandler(async (req, res) => {
// 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: refreshParam, family } = validateRequest(providerUsageQuerySchema, req.query);
+ const { refresh: refreshParam, family, period } = validateRequest(providerUsageQuerySchema, req.query);
const refresh = refreshParam === '1' || refreshParam === 'true';
- const providers = await getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER, family: family ?? null });
+ const providers = await getProviderQuotas({
+ wait: refresh ? WAIT.FRESH : WAIT.NEVER,
+ family: family ?? null,
+ ...(period ? { period } : {}),
+ });
res.json({ providers });
}));
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index b99ce4cc65..d2b4687c5b 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -405,6 +405,19 @@ describe('usage routes', () => {
expect(getProviderQuotas).toHaveBeenCalledWith({ wait: 'fresh', family: 'grok' });
});
+ it('GET /api/usage/providers forwards the period query parameter', async () => {
+ getProviderQuotas.mockResolvedValue([{ family: 'imagegen', supported: true, limits: [], metrics: [] }]);
+ const res = await request(buildApp()).get('/api/usage/providers?period=week');
+ expect(res.status).toBe(200);
+ expect(getProviderQuotas).toHaveBeenCalledWith({ wait: 'never', family: null, period: 'week' });
+ });
+
+ it('GET /api/usage/providers rejects an invalid period parameter', async () => {
+ const res = await request(buildApp()).get('/api/usage/providers?period=invalid');
+ expect(res.status).toBe(400);
+ expect(getProviderQuotas).not.toHaveBeenCalled();
+ });
+
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);
diff --git a/server/services/imageGenQuota.js b/server/services/imageGenQuota.js
index 7c6a830793..1321d6efeb 100644
--- a/server/services/imageGenQuota.js
+++ b/server/services/imageGenQuota.js
@@ -40,11 +40,15 @@ import { isObservedBlockActive, parseObservedReset } from '../lib/quotaReset.js'
const STATE_FILE = () => join(PATHS.data, 'imagegen-quota.json');
-// Renders older than this drop out of the rolling activity window.
-const ACTIVITY_WINDOW_MS = 24 * 60 * 60 * 1000;
-// Cap the retained render log so a batch run can't grow the file without
-// bound. Both bounds do work: a batch can exceed this inside one 24h window.
-const MAX_RENDER_SAMPLES = 200;
+export const WINDOW_24H_MS = 24 * 60 * 60 * 1000;
+export const WINDOW_7D_MS = 7 * 24 * 60 * 60 * 1000;
+export const WINDOW_30D_MS = 30 * 24 * 60 * 60 * 1000;
+export const ACTIVITY_WINDOW_MS = WINDOW_24H_MS;
+
+// Retain up to 35 days so rolling 30-day (month) and 7-day (week) counts are preserved.
+const RETENTION_WINDOW_MS = 35 * 24 * 60 * 60 * 1000;
+// Cap the retained render log so a batch run can't grow the file without bound.
+const MAX_RENDER_SAMPLES = 2000;
// How long a block whose refusal stated no reset time stays shown. Bounds an
// otherwise-permanent block on an install that stops rendering (a successful
// render clears it immediately, but nothing forces one to happen).
@@ -141,11 +145,16 @@ export async function recordImageGenOutcome({ mode, ok, error = '', at = Date.no
// Epoch ms, not ISO: every read filters this array by a time window, and
// storing strings means re-parsing each one on every pass.
- entry.renders = [...(entry.renders || []), { at, ok: ok === true }].slice(-MAX_RENDER_SAMPLES);
+ const cutoff = at - RETENTION_WINDOW_MS;
+ const existing = (entry.renders || []).filter((r) => r.at >= cutoff);
+ entry.renders = [...existing, { at, ok: ok === true }].slice(-MAX_RENDER_SAMPLES);
if (ok) {
// A render that succeeded proves the backend is serving again — clear a
// block that outlived its stated reset (providers round "approximately").
+ if (entry.blockedUntil && (!entry.lastResetAt || entry.blockedUntil > entry.lastResetAt)) {
+ entry.lastResetAt = entry.blockedUntil;
+ }
entry.blockedAt = null;
entry.blockedUntil = null;
} else {
@@ -160,6 +169,9 @@ export async function recordImageGenOutcome({ mode, ok, error = '', at = Date.no
// active block typically returns a bare 429 without restating the reset
// the first one gave us, which would otherwise erase it.
entry.blockedUntil = signal.resetsAt ?? entry.blockedUntil ?? null;
+ if (signal.resetsAt) {
+ entry.lastResetAt = signal.resetsAt;
+ }
}
}
await atomicWrite(STATE_FILE(), ledger);
@@ -232,7 +244,7 @@ export async function __drainImageGenQuotaHookForTests() {
*
* @param {string[]} enabledModes - cloud image modes currently enabled
*/
-export async function getImageGenQuota({ enabledModes = [], now = Date.now() } = {}) {
+export async function getImageGenQuota({ enabledModes = [], now = Date.now(), period = '24h' } = {}) {
const tracked = enabledModes.filter(isQuotaTrackedImageMode);
if (!tracked.length) return null;
@@ -254,7 +266,19 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =
error: 'Could not read the observed image-quota ledger — render counts and any active limit are unavailable.',
};
}
- const cutoff = now - ACTIVITY_WINDOW_MS;
+
+ const normalizedPeriod = (period === 'week' || period === '7d')
+ ? '7d'
+ : (period === 'month' || period === '30d')
+ ? '30d'
+ : period === 'reset'
+ ? 'reset'
+ : '24h';
+
+ const cutoff24h = now - WINDOW_24H_MS;
+ const cutoff7d = now - WINDOW_7D_MS;
+ const cutoff30d = now - WINDOW_30D_MS;
+
const limits = [];
const metrics = [];
for (const mode of tracked) {
@@ -284,13 +308,78 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =
});
continue;
}
- const recent = (entry.renders || []).filter((r) => r.at >= cutoff);
- const failed = recent.filter((r) => !r.ok).length;
+
+ const allRenders = entry.renders || [];
+ const recent24h = allRenders.filter((r) => r.at >= cutoff24h);
+ const recent7d = allRenders.filter((r) => r.at >= cutoff7d);
+ const recent30d = allRenders.filter((r) => r.at >= cutoff30d);
+
+ const failed24h = recent24h.filter((r) => !r.ok).length;
+ const failed7d = recent7d.filter((r) => !r.ok).length;
+ const failed30d = recent30d.filter((r) => !r.ok).length;
+
+ const periods = {
+ '24h': {
+ key: '24h',
+ label: '24h',
+ count: recent24h.length,
+ failed: failed24h,
+ value: recent24h.length ? `${recent24h.length} render${recent24h.length === 1 ? '' : 's'} · 24h` : 'No renders · 24h',
+ detail: failed24h ? `${failed24h} failed` : 'quota not reported by this CLI',
+ },
+ '7d': {
+ key: '7d',
+ label: 'Week',
+ count: recent7d.length,
+ failed: failed7d,
+ value: recent7d.length ? `${recent7d.length} render${recent7d.length === 1 ? '' : 's'} · week` : 'No renders · week',
+ detail: failed7d ? `${failed7d} failed` : 'quota not reported by this CLI',
+ },
+ '30d': {
+ key: '30d',
+ label: 'Month',
+ count: recent30d.length,
+ failed: failed30d,
+ value: recent30d.length ? `${recent30d.length} render${recent30d.length === 1 ? '' : 's'} · month` : 'No renders · month',
+ detail: failed30d ? `${failed30d} failed` : 'quota not reported by this CLI',
+ },
+ };
+
+ const lastReset = entry.lastResetAt ?? (entry.blockedUntil && now >= entry.blockedUntil ? entry.blockedUntil : null);
+ if (lastReset && lastReset <= now) {
+ const recentReset = allRenders.filter((r) => r.at >= lastReset);
+ const failedReset = recentReset.filter((r) => !r.ok).length;
+ periods.reset = {
+ key: 'reset',
+ label: 'Reset',
+ count: recentReset.length,
+ failed: failedReset,
+ value: recentReset.length ? `${recentReset.length} render${recentReset.length === 1 ? '' : 's'} · reset` : 'No renders · reset',
+ detail: failedReset ? `${failedReset} failed` : 'since last reset',
+ resetsAt: new Date(lastReset).toISOString(),
+ };
+ }
+
+ const active = periods[normalizedPeriod] || periods['24h'];
+
metrics.push({
key,
label,
- value: recent.length ? `${recent.length} render${recent.length === 1 ? '' : 's'} · 24h` : 'No renders · 24h',
- detail: failed ? `${failed} failed` : 'quota not reported by this CLI',
+ value: active.value,
+ detail: active.detail,
+ counts: {
+ day: recent24h.length,
+ week: recent7d.length,
+ month: recent30d.length,
+ ...(periods.reset ? { reset: periods.reset.count } : {}),
+ },
+ failed: {
+ day: failed24h,
+ week: failed7d,
+ month: failed30d,
+ ...(periods.reset ? { reset: periods.reset.failed } : {}),
+ },
+ periods,
});
}
@@ -305,6 +394,7 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =
limits,
activity: [],
metrics,
+ period: normalizedPeriod,
approximate: true,
fetchedAt: new Date(now).toISOString(),
note: 'These image backends expose no quota API, so PortOS reports what it observes: a limit appears only after a render is actually refused. The CLI\'s own usage panel covers the agent model, not the image backend.',
diff --git a/server/services/imageGenQuota.test.js b/server/services/imageGenQuota.test.js
index 20e3f37749..095a09a8b9 100644
--- a/server/services/imageGenQuota.test.js
+++ b/server/services/imageGenQuota.test.js
@@ -332,4 +332,54 @@ describe('getImageGenQuota', () => {
const card = await getImageGenQuota({ enabledModes: ['agy'], now });
expect(card.metrics[0].value).toBe('1 render · 24h');
});
+
+ it('reports counts across 24h, week (7d), and month (30d) periods', async () => {
+ // 10 days ago (outside 7d, inside 30d)
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now - 10 * 24 * 60 * 60 * 1000 });
+ // 3 days ago (outside 24h, inside 7d & 30d)
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now - 3 * 24 * 60 * 60 * 1000 });
+ // 2 hours ago (inside 24h, 7d & 30d)
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now - 2 * 60 * 60 * 1000 });
+
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ const metric = card.metrics[0];
+ expect(metric.value).toBe('1 render · 24h');
+ expect(metric.counts).toEqual({ day: 1, week: 2, month: 3 });
+ expect(metric.periods['24h'].value).toBe('1 render · 24h');
+ expect(metric.periods['7d'].value).toBe('2 renders · week');
+ expect(metric.periods['30d'].value).toBe('3 renders · month');
+ });
+
+ it('selects week or month as the primary period when requested', async () => {
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now - 3 * 24 * 60 * 60 * 1000 });
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: now - 2 * 60 * 60 * 1000 });
+
+ const weekCard = await getImageGenQuota({ enabledModes: ['agy'], now, period: 'week' });
+ expect(weekCard.period).toBe('7d');
+ expect(weekCard.metrics[0].value).toBe('2 renders · week');
+
+ const monthCard = await getImageGenQuota({ enabledModes: ['agy'], now, period: '30d' });
+ expect(monthCard.period).toBe('30d');
+ expect(monthCard.metrics[0].value).toBe('2 renders · month');
+ });
+
+ it('tracks renders since the last observed reset', async () => {
+ const resetTime = now - 2 * 60 * 60 * 1000;
+ // Before reset
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: resetTime - 60_000 });
+ // Simulate active block with reset
+ await recordImageGenOutcome({ mode: 'agy', ok: false, error: `quota will reset in approximately 2 hours (around ${new Date(resetTime).toISOString()})`, at: resetTime - 7200_000 });
+ // Successful render after reset
+ await recordImageGenOutcome({ mode: 'agy', ok: true, at: resetTime + 60_000 });
+
+ const card = await getImageGenQuota({ enabledModes: ['agy'], now });
+ const metric = card.metrics[0];
+ expect(metric.periods.reset).toBeDefined();
+ expect(metric.periods.reset.count).toBe(1);
+ expect(metric.periods.reset.value).toBe('1 render · reset');
+
+ const resetCard = await getImageGenQuota({ enabledModes: ['agy'], now, period: 'reset' });
+ expect(resetCard.period).toBe('reset');
+ expect(resetCard.metrics[0].value).toBe('1 render · reset');
+ });
});
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index c60bdb62e7..766eda6baa 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -890,8 +890,8 @@ const fetchFamilyQuota = (family, { wait, providers }) =>
* therefore unified with what peers published for the same family before it is
* returned — see `lib/fleetQuotas.js` for the two merge rules.
*/
-export async function getProviderQuotas({ wait = WAIT.CACHED, family = null } = {}) {
- const cards = await readProviderQuotas({ wait, family });
+export async function getProviderQuotas({ wait = WAIT.CACHED, family = null, period } = {}) {
+ const cards = await readProviderQuotas({ wait, family, period });
// Publish this machine's reading to the fleet and fold in every peer's. The
// two are independent — the peer read excludes our own slot — so they
// overlap. Recording is awaited rather than fired off so a caller that
@@ -913,7 +913,7 @@ export async function getProviderQuotas({ wait = WAIT.CACHED, family = null } =
}
/** The local readings, before any federated merge. */
-async function readProviderQuotas({ wait, family }) {
+async function readProviderQuotas({ wait, family, period }) {
const result = await getAllProviders();
const providers = Array.isArray(result) ? result : (result?.providers || []);
const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true && p.lmstudioBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true && p.vllmBacked !== true && p.sglangBacked !== true);
@@ -931,7 +931,7 @@ async function readProviderQuotas({ wait, family }) {
const now = Date.now();
const prune = (cards) => cards.map((card) => stampReadAt(pruneExpiredWindows(card, now), now));
if (family && family !== IMAGE_GEN_FAMILY) return prune(familyCards);
- const imageCard = await fetchImageGenQuota();
+ const imageCard = await fetchImageGenQuota({ period });
return prune(imageCard ? [...familyCards, imageCard] : familyCards);
}
@@ -945,7 +945,7 @@ async function readProviderQuotas({ wait, family }) {
* Never rejects — a broken read must not 500 the whole usage page, and no card
* is a better answer than a card asserting a quota state we failed to read.
*/
-const fetchImageGenQuota = async () => {
+const fetchImageGenQuota = async ({ period } = {}) => {
// A settings read that FAILS is not "no cloud backend enabled" — without it
// we can't tell which backends to report, and silently dropping the card is
// indistinguishable from the user running local-only. Say so in the log.
@@ -956,7 +956,7 @@ const fetchImageGenQuota = async () => {
// Only quota-window backends — a fal.ai-only install has no quota to show.
const enabledModes = enabledCloudImageModes(settings).filter(isQuotaTrackedImageMode);
if (!enabledModes.length) return null; // no quota-tracked cloud image backend → no card
- return getImageGenQuota({ enabledModes }).catch((err) => {
+ return getImageGenQuota({ enabledModes, ...(period ? { period } : {}) }).catch((err) => {
console.error(`❌ Image-gen quota card failed: ${err?.message || err}`);
return null;
});
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index fe95874732..370257bb41 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -404,6 +404,13 @@ describe('getProviderQuotas', () => {
expect(getImageGenQuota).toHaveBeenCalledWith({ enabledModes: ['agy'] });
});
+ it('forwards the requested period to getImageGenQuota', async () => {
+ getAllProviders.mockResolvedValueOnce({ activeProvider: null, providers: [] });
+ getSettings.mockResolvedValueOnce({ imageGen: { agy: { enabled: true } } });
+ await getProviderQuotas({ period: 'week' });
+ expect(getImageGenQuota).toHaveBeenCalledWith({ enabledModes: ['agy'], period: 'week' });
+ });
+
it('omits the image-gen card entirely when only local image gen is on', async () => {
getAllProviders.mockResolvedValueOnce({ activeProvider: null, providers: [] });
getSettings.mockResolvedValueOnce({ imageGen: { local: { enabled: true } } });