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

normalize provider resetsAt to ISO at the adapter (#3433)

[._.]/ Adam Eivy088547fe227d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b13e328878..8d7e1a4713 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -53,3 +53,4 @@
- **Slow provider readings are stale-while-revalidate, in one place.** `server/lib/staleWhileRevalidate.js` — `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` — replaces the hand-rolled TTL+in-flight caches in `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`, which had drifted into two shapes of the same tricky async contract. A cached reading is served immediately and refreshed behind the caller; only a cold cache waits. Three things the naive version got wrong are now handled once: a background revalidation resolves `{value}|{error}` so an unawaited rejection can't kill the process; a failure keeps the last good value AND records `failedAt`, so a broken producer backs off instead of being respawned by every caller (serve-stale without that degrades into one subprocess per request exactly when the subprocess is broken); and `PENDING` is terminal — a cold cache whose producer already failed throws rather than promising a reading that is never coming, which a poller would wait on forever. `wait` is one three-state enum (`fresh` / `cached` / `never`) rather than the two booleans it started as, because "give me a live reading but don't wait for one" has no meaning and encoding it as flags forces a precedence rule at every layer that threads them.
- **A quota status read never blocks — on either page.** `/api/quota-burn` and `/api/usage/providers` answer a cold cache with `pending: true` cards; the UI renders "reading quota…" and polls (via the shared `useAutoRefetch`, so it pauses on a hidden tab) until the readings land. `pending` is its own state ahead of the verdict everywhere it is rendered: on a Quota Burn family card, and on the Usage page's `ProviderQuotaCard`, which would otherwise have shown a pending provider as "No rate-limit data reported" — a verdict about the provider rather than a statement about a scrape still in flight. It fails closed in the burn gate ladder, ahead of the error branch and holding even under force, so a card with no numbers on it can never become a burn candidate. `?refresh=1` — the Refresh button, and every runner cycle about to spend real quota — still waits for a live reading.
- **Quota-burn agents run as TUI, so a burn can be watched and steered.** A burn runs unattended for minutes on the user's own subscription, and the family's provider was picked with a plain `find` over the enabled CLI/TUI providers — which returns the CLI, because that is what sorts first. Every dispatch therefore went to a headless run that could only be read after it finished. The picker now prefers the TUI (the same preference `pickScrapeProvider` applies when reading `/usage`), so the agent shows up in Active Agents with a live terminal. Two selection bugs came out with it: the whole **`agy` family was unreachable** — its providers ship as `antigravity-cli`/`antigravity-tui`, neither of which contains "agy", so a configured Antigravity plan reported "no enabled CLI/TUI provider" forever while the quota card above it showed a healthy window (the card's matcher checks the *command*; the burn picker only checked the id, and now checks both) — and an **ollama-backed wrapper was eligible**: `claude-ollama-tui` matches the claude family and is a TUI, but it runs a local model, so burning through it spends nothing and lets the window it was meant to drain expire unused. `resolveEnabledFamilies` already excludes those from the quota cards for the same reason; the burn picker now excludes them too, explicit pin included.
+- **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)
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 351d41a8df..b9b4f505cf 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -5,7 +5,7 @@ import * as api from '../services/api';
import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import Pill from '../components/ui/Pill';
-import { formatCompactCount } from '../utils/formatters';
+import { formatCompactCount, timeUntil } from '../utils/formatters';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
@@ -25,12 +25,17 @@ const formatNumber = (num) => (num == null ? '—' : formatCompactCount(num));
const formatCost = (cost) => `$${(cost ?? 0).toFixed(2)}`;
-// Reset times arrive either as human text from the Claude CLI ("Jul 15, 3am")
-// or as an ISO timestamp from telemetry-based adapters — localize the latter.
+// Every provider adapter normalizes its reset to ISO before it reaches here, so
+// this localizes and adds the relative "in 3h" that makes a reset time useful at
+// a glance. The raw-text fallback stays for a reading off an older peer that
+// still emits its CLI's own wording.
const formatResetsAt = (resetsAt) => {
if (!resetsAt || !/^\d{4}-\d{2}-\d{2}T/.test(resetsAt)) return resetsAt;
const d = new Date(resetsAt);
- return Number.isNaN(d.getTime()) ? resetsAt : d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
+ if (Number.isNaN(d.getTime())) return resetsAt;
+ const local = d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
+ const relative = timeUntil(d, '');
+ return relative ? `${local} (${relative})` : local;
};
// Color a usage meter by how much is consumed: comfortable → warning → critical.
diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsx
index 40493b28ca..78c927baf8 100644
--- a/client/src/pages/UsagePage.test.jsx
+++ b/client/src/pages/UsagePage.test.jsx
@@ -104,3 +104,28 @@ describe('UsagePage breakdown visualization and responsiveness', () => {
});
});
+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.
+ const resetsAt = new Date(Date.now() + 3 * 60 * 60 * 1000 + 60_000).toISOString();
+ api.getProviderUsage.mockResolvedValue({
+ providers: [{
+ family: 'claude',
+ label: 'Claude',
+ supported: true,
+ limits: [{ key: 'week', label: 'Weekly', percentUsed: 40, percentRemaining: 60, resetsAt, timezone: 'UTC' }],
+ activity: [],
+ approximate: true,
+ fetchedAt: new Date().toISOString()
+ }]
+ });
+
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+
+ // Every adapter emits ISO now, so the card must never show a CLI's own
+ // wording — it shows a localized instant plus "in 3h".
+ const reset = await screen.findByText(/resets .*\(in 3h\)/);
+ expect(reset).toBeInTheDocument();
+ expect(reset.textContent).not.toContain(resetsAt);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index efebff0581..24a296f906 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -30,7 +30,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Pure — no storage, no provider I/O. |
| `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body). |
-| `quotaReset.js` | Normalizes provider quota reset timestamps and computes time remaining without treating unknown values as imminent resets. |
+| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets. |
| `appleHealthValidation.js` | Apple Health import payloads. |
| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |
diff --git a/server/lib/quotaReset.js b/server/lib/quotaReset.js
index 91cc078737..4810bea000 100644
--- a/server/lib/quotaReset.js
+++ b/server/lib/quotaReset.js
@@ -2,6 +2,10 @@
* Normalize the reset times emitted by the provider quota adapters. A missing
* or ambiguous reset is deliberately represented as null: a scheduled quota
* burn must park rather than guess that a provider is about to reset.
+ *
+ * `parseHumanReset` is the adapter-facing half — each provider adapter calls it
+ * so `resetsAt` is ISO 8601 on the wire; `normalizeResetAt`/`hoursUntilReset`
+ * are the consumer-facing half that does arithmetic on that instant.
*/
const HOUR_MS = 60 * 60 * 1000;
@@ -69,39 +73,75 @@ function stampYear(wallMs, year) {
}
/**
- * @returns {{ epochMs: number|null, source: 'iso'|'parsed'|'unknown' }}
+ * Resolve a human wall-clock reset string to an epoch instant in `timezone`
+ * (the server's own zone when none is stated). Returns null when the string
+ * states no parseable date/time.
*/
-export function normalizeResetAt(limit, { now = Date.now(), timeZone } = {}) {
- const raw = typeof limit?.resetsAt === 'string' ? limit.resetsAt.trim() : '';
- if (!raw) return { epochMs: null, source: 'unknown' };
-
- if (hasExplicitZone(raw)) {
- const epochMs = Date.parse(raw);
- return Number.isFinite(epochMs) ? { epochMs, source: 'iso' } : { epochMs: null, source: 'unknown' };
- }
-
+function resolveWallClock(raw, { now, timezone }) {
const value = normalizeSeparators(raw);
// Read the string's fields as if they were UTC, so the year can be corrected
// before any zone offset is applied to them.
const wall = Date.parse(`${value} UTC`);
- if (!Number.isFinite(wall)) return { epochMs: null, source: 'unknown' };
+ if (!Number.isFinite(wall)) return null;
- const zone = limit?.timezone || timeZone;
// The instant that wall clock names in the provider's zone — or, with no zone
// stated, in the server's own (which is what `Date.parse` assumed before).
const resolve = (wallMs) => {
- const offset = zone ? zoneOffsetMs(wallMs, zone) : -new Date(wallMs).getTimezoneOffset() * 60_000;
+ const offset = timezone ? zoneOffsetMs(wallMs, timezone) : -new Date(wallMs).getTimezoneOffset() * 60_000;
return offset === null ? null : wallMs - offset;
};
// `null` year = the string states its own and needs no stamping.
- const year = /\b\d{4}\b/.test(value) ? null : zoneYear(now, zone);
- let epochMs = resolve(year === null ? wall : stampYear(wall, year));
+ const year = /\b\d{4}\b/.test(value) ? null : zoneYear(now, timezone);
+ const epochMs = resolve(year === null ? wall : stampYear(wall, year));
// A year-less reset stamped with the current year can still land in the past
// across a year boundary (a "Jan 2" reset read on Dec 31). Roll to the next
// occurrence — re-resolving the offset, since it is a per-year lookup. The
// hour of grace keeps a reset that just passed from being pushed a year out.
- if (year !== null && epochMs !== null && epochMs < now - HOUR_MS) epochMs = resolve(stampYear(wall, year + 1));
+ if (year !== null && epochMs !== null && epochMs < now - HOUR_MS) return resolve(stampYear(wall, year + 1));
+ return epochMs;
+}
+
+/**
+ * Turn one provider CLI's human reset string into an ISO 8601 instant — the
+ * shape every quota adapter is expected to put on the wire, so the client can
+ * localize it and `normalizeResetAt` stays pure arithmetic.
+ *
+ * Call this from the ADAPTER (`parseLimitLine`, `parseGrokUsage`, …), not from
+ * a shared choke point: a new provider dialect belongs in its own adapter.
+ * Already-ISO input passes through (normalized to UTC), so it is idempotent.
+ *
+ * @param {string} value - e.g. `Aug 4 at 1:59pm`, `2pm`, `August 10, 06:07`
+ * @param {{ now?: number, timezone?: string }} [opts] - `timezone` is the IANA
+ * zone the CLI rendered in (the server's own when absent); `now` anchors the
+ * year a year-less string omits.
+ * @returns {string|null} ISO 8601 instant, or null when unparseable
+ */
+export function parseHumanReset(value, { now = Date.now(), timezone } = {}) {
+ const raw = typeof value === 'string' ? value.trim() : '';
+ if (!raw) return null;
+ const epochMs = hasExplicitZone(raw) ? Date.parse(raw) : resolveWallClock(raw, { now, timezone });
+ return Number.isFinite(epochMs) ? new Date(epochMs).toISOString() : null;
+}
+
+/**
+ * Every in-tree adapter now emits ISO, so this hits the `hasExplicitZone` fast
+ * path. The wall-clock fallback stays for a limit that arrives from an older
+ * federated peer (or a future adapter that hasn't migrated) — dropping it would
+ * regress those to "no window states a reset time".
+ *
+ * @returns {{ epochMs: number|null, source: 'iso'|'parsed'|'unknown' }}
+ */
+export function normalizeResetAt(limit, { now = Date.now(), timeZone } = {}) {
+ const raw = typeof limit?.resetsAt === 'string' ? limit.resetsAt.trim() : '';
+ if (!raw) return { epochMs: null, source: 'unknown' };
+
+ if (hasExplicitZone(raw)) {
+ const epochMs = Date.parse(raw);
+ return Number.isFinite(epochMs) ? { epochMs, source: 'iso' } : { epochMs: null, source: 'unknown' };
+ }
+
+ const epochMs = resolveWallClock(raw, { now, timezone: limit?.timezone || timeZone });
return epochMs === null ? { epochMs: null, source: 'unknown' } : { epochMs, source: 'parsed' };
}
diff --git a/server/lib/quotaReset.test.js b/server/lib/quotaReset.test.js
index a3b647ac17..37fad97789 100644
--- a/server/lib/quotaReset.test.js
+++ b/server/lib/quotaReset.test.js
@@ -1,5 +1,41 @@
import { describe, expect, it } from 'vitest';
-import { hoursUntilReset, normalizeResetAt } from './quotaReset.js';
+import { hoursUntilReset, normalizeResetAt, parseHumanReset } from './quotaReset.js';
+
+// The adapter-facing half: every provider adapter runs its CLI's reset string
+// through this, so `resetsAt` is ISO 8601 on the wire and the Usage page can
+// localize it instead of printing the CLI's own wording.
+describe('parseHumanReset', () => {
+ const now = Date.parse('2026-07-26T12:00:00.000Z');
+
+ it('reads the claude panel shape — an " at " separator and a glued meridiem', () => {
+ expect(parseHumanReset('Jul 27 at 1:59pm', { now, timezone: 'America/Los_Angeles' }))
+ .toBe('2026-07-27T20:59:00.000Z');
+ });
+
+ it('reads a bare hour, which states no minutes at all', () => {
+ expect(parseHumanReset('Jul 27 at 2pm', { now, timezone: 'UTC' })).toBe('2026-07-27T14:00:00.000Z');
+ });
+
+ it('reads midnight and noon, the two a 12-hour clock gets wrong most often', () => {
+ expect(parseHumanReset('Jul 27 at 12am', { now, timezone: 'UTC' })).toBe('2026-07-27T00:00:00.000Z');
+ expect(parseHumanReset('Jul 27 at 12pm', { now, timezone: 'UTC' })).toBe('2026-07-27T12:00:00.000Z');
+ });
+
+ it('stamps a year-less date (the grok panel shape) with the year `now` falls in', () => {
+ expect(parseHumanReset('August 10, 06:07', { now, timezone: 'UTC' })).toBe('2026-08-10T06:07:00.000Z');
+ });
+
+ it('passes an already-ISO instant through, so re-normalizing is a no-op', () => {
+ expect(parseHumanReset('2026-07-27T12:00:00.000Z', { now })).toBe('2026-07-27T12:00:00.000Z');
+ });
+
+ it('returns null for a missing or unreadable reset rather than guessing one', () => {
+ expect(parseHumanReset(null, { now })).toBeNull();
+ expect(parseHumanReset('', { now })).toBeNull();
+ expect(parseHumanReset(' ', { now })).toBeNull();
+ expect(parseHumanReset('not a date', { now })).toBeNull();
+ });
+});
describe('quota reset normalization', () => {
const now = Date.parse('2026-07-26T12:00:00.000Z');
@@ -19,10 +55,11 @@ describe('quota reset normalization', () => {
expect(result).toEqual({ epochMs: Date.parse('2026-07-27T15:00:00.000Z'), source: 'parsed' });
});
- // The exact strings the live CLIs emit. Both defeated a bare `Date.parse`:
- // claude's " at " + glued meridiem returned NaN (every window read as "no
- // reset time", so the family never burned), and a year-less string resolves
- // to 2001 rather than the current year.
+ // In-tree adapters now hand this an ISO instant, so the cases below are the
+ // BACKWARD-COMPAT path: a limit off an older federated peer still carries the
+ // raw CLI string. Both shapes defeat a bare `Date.parse` — claude's " at " +
+ // glued meridiem returns NaN (every window would read as "no reset time", so
+ // the family never burns), and a year-less string resolves to 2001.
it('parses the claude panel shape — " at " separator and a glued meridiem', () => {
expect(normalizeResetAt({ resetsAt: 'Jul 27 at 1:59pm', timezone: 'America/Los_Angeles' }, { now }))
.toEqual({ epochMs: Date.parse('2026-07-27T20:59:00.000Z'), source: 'parsed' });
diff --git a/server/services/claudeCodeUsage.js b/server/services/claudeCodeUsage.js
index 5a65892e8b..8ff26f2b22 100644
--- a/server/services/claudeCodeUsage.js
+++ b/server/services/claudeCodeUsage.js
@@ -1,6 +1,7 @@
import { spawn } from 'child_process';
import { existsSync, lstatSync, readlinkSync, readFileSync } from 'fs';
import { stripAnsi } from '../lib/ansiStrip.js';
+import { parseHumanReset } from '../lib/quotaReset.js';
import { createStaleWhileRevalidate, WAIT } from '../lib/staleWhileRevalidate.js';
/**
@@ -77,21 +78,29 @@ function resolveSystemTimeZone() {
/**
* Parse one `Current …: N% used · resets <when> (<tz>)` limit line.
* Returns null when the line isn't a limit line.
+ *
+ * `resetsAt` is emitted as ISO 8601 (null when the CLI stated no reset, or
+ * stated one this parser couldn't read) — normalizing at the adapter is the
+ * convention every provider family follows, and it is what lets the Usage page
+ * localize the time instead of printing `Aug 4 at 1:59pm` verbatim. The CLI
+ * renders in a zone it names in a trailing `(…)`; `timezone` falls back to it
+ * for a line that omits the suffix. `now` anchors the year the CLI omits.
*/
-function parseLimitLine(line) {
+function parseLimitLine(line, { now, timezone: fallbackZone } = {}) {
const match = line.match(/^(Current [^:]+):\s*(\d+)%\s*used(?:\s*·\s*resets\s+(.+?))?$/i);
if (!match) return null;
const label = match[1].trim();
const percentUsed = toInt(match[2]);
- let resetsAt = match[3] ? match[3].trim() : null;
+ let rawReset = match[3] ? match[3].trim() : null;
let timezone = null;
- if (resetsAt) {
- const tz = resetsAt.match(/\(([^)]+)\)\s*$/);
+ if (rawReset) {
+ const tz = rawReset.match(/\(([^)]+)\)\s*$/);
if (tz) {
timezone = tz[1];
- resetsAt = resetsAt.slice(0, tz.index).trim();
+ rawReset = rawReset.slice(0, tz.index).trim();
}
}
+ const resetsAt = parseHumanReset(rawReset, { now, timezone: timezone || fallbackZone });
// Derive a stable key + optional model from the label.
// "Current session" → session; "Current week (all models)" → week (model: all models);
// "Current week (Fable)" → week (model: Fable).
@@ -107,6 +116,9 @@ function parseLimitLine(line) {
percentUsed,
percentRemaining: percentUsed == null ? null : Math.max(0, 100 - percentUsed),
resetsAt,
+ // The zone the CLI labelled the reset with, kept for display/diagnostics.
+ // `resetsAt` no longer depends on it (it carries its own offset), but
+ // `normalizeResetAt` still reads it off limits from older peers.
timezone,
};
}
@@ -121,10 +133,15 @@ function parseActivityHeader(line) {
}
/**
- * Pure parser: `/usage` text → structured object. Tolerant of absent lines so a
- * future CLI format tweak degrades gracefully instead of throwing.
+ * Parser: `/usage` text → structured object. Tolerant of absent lines so a
+ * future CLI format tweak degrades gracefully instead of throwing. Pure given
+ * `now` (which reset lines need, since the CLI states no year).
+ *
+ * `timezone` is the zone the CLI rendered in, used only for a reset line that
+ * carries no `(zone)` suffix; the caller passes `systemTimeZone()`, the same
+ * zone it forces on the child process.
*/
-export function parseUsageOutput(text) {
+export function parseUsageOutput(text, { now = Date.now(), timezone } = {}) {
const raw = (text || '').trim();
const lines = stripAnsi(raw).split('\n');
@@ -140,7 +157,7 @@ export function parseUsageOutput(text) {
const line = rawLine.replace(/\s+$/, '');
const trimmed = line.trim();
- const limit = parseLimitLine(trimmed);
+ const limit = parseLimitLine(trimmed, { now, timezone });
if (limit) {
limits.push(limit);
currentActivity = null;
@@ -260,6 +277,6 @@ function runUsageCli() {
export async function getClaudeCodeUsage({ wait = WAIT.CACHED } = {}) {
return usageCache.read(CACHE_KEY, async () => {
const stdout = await runUsageCli();
- return { ...parseUsageOutput(stdout), fetchedAt: new Date().toISOString() };
+ return { ...parseUsageOutput(stdout, { timezone: systemTimeZone() }), fetchedAt: new Date().toISOString() };
}, { wait });
}
diff --git a/server/services/claudeCodeUsage.test.js b/server/services/claudeCodeUsage.test.js
index 4b29989630..80a089c03a 100644
--- a/server/services/claudeCodeUsage.test.js
+++ b/server/services/claudeCodeUsage.test.js
@@ -23,12 +23,16 @@ Last 7d · 17034 requests · 125 sessions
Top plugins: do 22%, superpowers 5%`;
describe('parseUsageOutput', () => {
+ // The CLI states no year, so every reset resolves against a `now` — pin it so
+ // the ISO assertions below don't drift with the wall clock.
+ const now = Date.parse('2026-07-06T12:00:00.000Z');
+
it('detects a subscription plan', () => {
expect(parseUsageOutput(SAMPLE).plan).toBe('subscription');
});
- it('parses each limit line with percent, remaining, reset time and timezone', () => {
- const { limits } = parseUsageOutput(SAMPLE);
+ it('parses each limit line with percent, remaining, an ISO reset and the stated timezone', () => {
+ const { limits } = parseUsageOutput(SAMPLE, { now });
expect(limits).toHaveLength(3);
expect(limits[0]).toMatchObject({
@@ -38,7 +42,9 @@ describe('parseUsageOutput', () => {
model: null,
percentUsed: 4,
percentRemaining: 96,
- resetsAt: 'Jul 7 at 2:59am',
+ // `Jul 7 at 2:59am (America/Los_Angeles)` → normalized at the adapter, so
+ // the Usage page localizes it instead of printing the CLI's own wording.
+ resetsAt: '2026-07-07T09:59:00.000Z',
timezone: 'America/Los_Angeles',
});
@@ -100,9 +106,14 @@ describe('parseUsageOutput', () => {
expect(limits[0]).toMatchObject({ percentUsed: 50, resetsAt: null, timezone: null });
});
- it('keeps a reset time that has no (timezone) suffix', () => {
- const { limits } = parseUsageOutput('Current session: 10% used · resets Jul 7 at 2pm');
- expect(limits[0]).toMatchObject({ resetsAt: 'Jul 7 at 2pm', timezone: null });
+ it('resolves a reset with no (timezone) suffix against the zone the caller passes', () => {
+ const { limits } = parseUsageOutput('Current session: 10% used · resets Jul 7 at 2pm', { now, timezone: 'UTC' });
+ expect(limits[0]).toMatchObject({ resetsAt: '2026-07-07T14:00:00.000Z', timezone: null });
+ });
+
+ it('emits a null reset when the CLI states one this parser cannot read', () => {
+ const { limits } = parseUsageOutput('Current session: 10% used · resets whenever', { now });
+ expect(limits[0]).toMatchObject({ percentUsed: 10, resetsAt: null });
});
it('detects an API (pay-as-you-go) plan', () => {
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 3ae49d5f92..d548b059fc 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -7,6 +7,7 @@ import { commandBasename, isClaudeCommand } from '../lib/providerModels.js';
import { isGrokCommand } from '../lib/grok.js';
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 { enabledCloudImageModes } from './imageGen/modes.js';
@@ -335,11 +336,16 @@ const GROK_WINDOWS = { weekly: { label: 'Weekly', scope: 'week' }, monthly: { la
/**
* Parse the Grok Build `/usage show` panel text. Emits one row per usage window
* present (`Weekly limit: N%` and/or `Monthly limit: N%`, percent USED) plus a
- * shared `Next reset: <date>`. Exported for tests. Pure.
+ * shared `Next reset: <date>`. Exported for tests. Pure given `now`.
+ *
+ * The panel's reset is a local-time date with no year and no zone (`August 10,
+ * 06:07`); it is normalized to ISO here, at the adapter, so the Usage page can
+ * localize it. `timezone` is the zone the TUI rendered in — the fetcher forces
+ * the machine's zone on the child, so it passes the same one back in.
*
* @returns {{ limits: Array }}
*/
-export function parseGrokUsage(text) {
+export function parseGrokUsage(text, { now = Date.now(), timezone } = {}) {
const str = String(text || '');
// Append-only terminal stream: a repaint leaves an older copy of a line ahead
// of the newer one, so keep the LAST value seen per window (freshest frame) —
@@ -350,7 +356,7 @@ export function parseGrokUsage(text) {
}
if (!byWindow.size) return { limits: [] };
const resets = [...str.matchAll(/next reset:\s*([A-Za-z0-9 ,:]+?)(?:\s{2,}|$)/gi)];
- const resetsAt = resets.length ? resets[resets.length - 1][1].trim() : null;
+ const resetsAt = resets.length ? parseHumanReset(resets[resets.length - 1][1], { now, timezone }) : null;
const limits = [...byWindow].map(([window, percentUsed]) => ({
key: window,
label: GROK_WINDOWS[window].label,
@@ -358,8 +364,6 @@ export function parseGrokUsage(text) {
model: null,
percentUsed,
percentRemaining: Math.max(0, 100 - percentUsed),
- // Grok gives a local-time date string without a year/zone; pass it through
- // verbatim (the UI renders non-ISO reset strings as-is).
resetsAt,
timezone: null,
}));
@@ -423,7 +427,9 @@ function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name, rea
const cacheKey = `${id}:${command}:${provider.type}:${JSON.stringify(env)}:${JSON.stringify(args)}`;
const card = await scrapeCache.read(cacheKey, async () => {
const text = await scrapeTuiUsage({ command, args, slashCommand, env, readyMarker });
- const { limits } = parse(text);
+ // The panel's reset is relative (agy) or zone-less (grok) — both resolve
+ // against the read's own clock and the zone the child rendered in.
+ const { limits } = parse(text, { now: Date.now(), timezone: tz });
return limits.length
? { ...base, supported: true, limits, note: `Scraped from the ${name} /usage panel — local, approximate.` }
: { ...base, supported: true, limits: [], error: `No quota data found in the ${name} /usage panel.` };
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 4d32165b94..9c0e62c5cb 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -267,21 +267,29 @@ describe('parseAgyUsage', () => {
});
describe('parseGrokUsage', () => {
- it('reads the weekly limit as percent USED and passes the reset string through', () => {
- const { limits } = parseGrokUsage(GROK_PANEL);
+ // The panel's `Next reset` states no year and no zone, so it resolves against
+ // an injected `now` + the zone the fetcher forced on the child.
+ const opts = { now: Date.parse('2026-07-26T12:00:00.000Z'), timezone: 'UTC' };
+
+ it('reads the weekly limit as percent USED and normalizes the reset to ISO', () => {
+ const { limits } = parseGrokUsage(GROK_PANEL, opts);
expect(limits).toHaveLength(1);
- expect(limits[0]).toMatchObject({ key: 'weekly', label: 'Weekly', percentUsed: 42, percentRemaining: 58, resetsAt: 'August 1, 06:07' });
+ expect(limits[0]).toMatchObject({ key: 'weekly', label: 'Weekly', percentUsed: 42, percentRemaining: 58, resetsAt: '2026-08-01T06:07:00.000Z' });
});
it('returns no limits when the panel has no weekly-limit line', () => {
- expect(parseGrokUsage('Grok Build Beta 0.2.101').limits).toEqual([]);
- expect(parseGrokUsage(undefined).limits).toEqual([]);
+ expect(parseGrokUsage('Grok Build Beta 0.2.101', opts).limits).toEqual([]);
+ expect(parseGrokUsage(undefined, opts).limits).toEqual([]);
});
it('takes the freshest (last) frame when the panel is repainted', () => {
const repainted = 'Weekly limit: 10% Next reset: July 1, 00:00\nWeekly limit: 73% Next reset: August 1, 06:07';
- const { limits } = parseGrokUsage(repainted);
- expect(limits[0]).toMatchObject({ percentUsed: 73, percentRemaining: 27, resetsAt: 'August 1, 06:07' });
+ const { limits } = parseGrokUsage(repainted, opts);
+ expect(limits[0]).toMatchObject({ percentUsed: 73, percentRemaining: 27, resetsAt: '2026-08-01T06:07:00.000Z' });
+ });
+
+ it('emits a null reset rather than a raw string when the panel states none', () => {
+ expect(parseGrokUsage('Weekly limit: 42%', opts).limits[0]).toMatchObject({ percentUsed: 42, resetsAt: null });
});
it('parses a Monthly window and both windows when present', () => {