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 quota-burn reset parsing and stop status reads blocking on a PTY scrape
[._.]/ Adam Eivyd064096fc118
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7f8f154693..5c354683df 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -49,3 +49,6 @@- **"Continue Today's Routine" no longer dead-ends on the drill you just finished.** The handler navigated straight to the top recommendation's deep link with no check that it pointed somewhere else — and a sub-50% run makes the drill just missed the very item the scheduler resurfaces first, so Continue on Element Flash re-navigated to the URL already in the address bar and left the completion panel untouched. A self-referential recommendation now restarts the drill in place: a `run` nonce goes into the query string (preserving unrelated params like Morse's `?ref=`) and flows into the key of every surface the handler drives — Elements, Morse, Wordplay, and memory practice — so the drill remounts for a fresh run. Recommendations pointing elsewhere navigate exactly as before, and the comparison is path-only so a deep link carrying its own query string is still recognized as self-referential. (#3428)- **Quota-burn plan editor: nothing spends or destroys on one click any more.** The row's ▶ force-dispatched the job past the window/reserve/cap gates on a single click, sitting in a strip of small icons on a page that has no Save button — so it reads as "save" and got hit by accident. It now arms first, like the row's delete (and arming either disarms the other). Two more one-click losses went with it: the job-type picker no longer wipes `params`, so clicking through it can't silently destroy a long work prompt, and a preset asks before overwriting prompt text the user wrote. The page header now says "Changes save automatically" / "Saving changes…" — the missing feedback that sent people hunting for a save button in the first place. The step-name box also stopped using the job-type label ("Agent prompt") as its placeholder, which made it look like a second prompt field next to the real Work prompt, and a collapsed family card now shows its job count so "healthy window, no plan" is visible without expanding.- **Quota-burn work prompts ship with presets.** A burn window is spent unattended, so a blank "what should this provider spend its remaining quota on?" textarea was the weakest part of the feature. Ten ready-made prompts (`server/lib/quotaBurnPresets.js`, served in the config catalog) each run ONE narrow audit — UX, accessibility, mobile, failure paths, performance, test gaps, dead code, data/upgrade safety, docs drift, security — the single-focus form of `/do:better --issues`: read real code in a bounded slice, de-dupe against open issues, file at most five decision-complete GitHub issues, change nothing. They run in the app's own checkout with no worktree at all — they read code and file issues, so there is nothing to isolate, and `useWorktree: true` + `openPR: false` is in fact the *auto-merge* posture (the agent's branch is merged onto the managed app's default branch on success, unreviewed), meaning "isolating an audit for safety" would hand it a way to land code. Instead `agent-prompt` gains two distinct never-lands-code params (both default `false`, so jobs meant to land code are unchanged): `noCodeOutput` — the deliverable is what the agent DOES during the run, used by the presets — and `discardWorktree`, for a job that does want a scratch checkout (to build or test) whose contents must never land. Either one forces `openPR`/`simplify` off (an `openPR` that can never produce a PR makes the spawner report `pr-missing` and *retry*, burning up to five agent runs per window) and marks a clean tree as success. `noCodeOutput` also strips every commit/push/PR instruction from the prompt — including the Git Hygiene arm that told a no-worktree task to `/do:push` **to the branch it is standing on**, which for a task in the app's live checkout is its default branch; that arm also covered the Creative Director agents, which run in the same shape. The shared contract also requires scratch files go to `mktemp`, that the run leave the tree and branch exactly as it found them (it is the user's working copy), and that secrets, hostnames, and personal records are redacted before anything is filed — an issue is world-readable the moment it exists. There is a `curl` fallback so a `gh` network failure doesn't end the window having filed nothing. Add one from a family card ("Add a preset job", inheriting the plan's app) or a job row ("Start from a preset"). Presets are templates — picking one copies the text into the job, so editing a preset never rewrites a configured job on any install.+- **Quota Burn opens instantly, and the claude family can finally burn.** Two bugs, both on the page's critical path. (1) `normalizeResetAt` fed the provider's reset string straight to `Date.parse`, which claude's `Aug 4 at 1:59pm` (an " at " separator, a meridiem glued to the minutes, and sometimes no minutes at all — `Jul 7 at 2pm`) returns `NaN` for, so EVERY claude window read as "no window states a reset time" and the family was permanently unburnable — invisibly, since that reason looks like a provider fault. A year-less reset (grok's `August 10, 06:07`) had the mirror problem: `Date.parse` resolves it to **2001**, so the roll-forward fired against a date 25 years back and landed on 2002, leaving grok reporting "window already reset" forever. The string is now reshaped before parsing and the year stamped from `now` in the provider's own zone — before the DST offset lookup, which is a per-year table. (2) A status read blocked on a live quota reading: measured **30s** to open the page after five idle minutes and **21s** on the first load after a restart, for a 10-20s PTY spawn per provider family, over percentages that move by single digits an hour. Page load is now ~9ms in both cases. Every cycle also logs its verdict now — "Evaluate now" previously left no trace in the server log at all, so a cycle that correctly declined was indistinguishable from one that never ran. (Follow-up #3433: the two adapters that emit a raw CLI reset string rather than ISO should normalize in the adapter, which is also why the Usage page still prints `Aug 4 at 1:59pm` unlocalized.)+- **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.diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsxindex 8acfae1ada..7831a789da 100644--- a/client/src/components/quotaBurn/FamilyCard.jsx+++ b/client/src/components/quotaBurn/FamilyCard.jsx@@ -8,6 +8,7 @@*/import { ChevronDown, ChevronRight, Flame, Plus } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';import JobRow from './JobRow';import PresetPicker from './PresetPicker';import { jobFromPreset } from '../../lib/quotaBurnPatch';@@ -82,7 +83,15 @@ export default function FamilyCard({{status?.label || familyId}</label>- {status?.willBurn ? (+ {/* Pending is its own state, ahead of the verdict: reading this family's+ quota is a multi-second CLI/TUI spawn that the page deliberately does+ not block on, and "no window states a reset time" would read as a+ verdict when the reading simply hasn't landed yet. */}+ {status?.pending ? (+ <span className="inline-flex items-center gap-1 text-xs text-gray-400">+ <BrailleSpinner /> reading quota…+ </span>+ ) : status?.willBurn ? (<span className="inline-flex items-center gap-1 text-xs text-emerald-400"><Flame size={13} />{status.percentRemaining}% left · resets in {status.hoursUntilReset}h · {status.dispatchesUsed}/{config.maxDispatchesPerWindow} useddiff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsxindex cc6221d506..7ef30e32b2 100644--- a/client/src/pages/QuotaBurn.jsx+++ b/client/src/pages/QuotaBurn.jsx@@ -21,6 +21,7 @@ import BrailleSpinner from '../components/BrailleSpinner';import FamilyCard from '../components/quotaBurn/FamilyCard';import { NumberField } from '../components/quotaBurn/fields';import * as api from '../services/api';+import { useAutoRefetch } from '../hooks/useAutoRefetch';import { mergeQuotaBurnPatch } from '../lib/quotaBurnPatch';import { coalesce } from '../utils/coalesce';import { timeAgo } from '../utils/formatters';@@ -30,6 +31,10 @@ import { timeAgo } from '../utils/formatters';// every universe bible — one full scan per character typed.const SAVE_DEBOUNCE_MS = 500;+// How often to re-ask while a family's quota scrape is still running. A scrape+// is a 10-20s PTY spawn, so this is a handful of polls, not a busy loop.+const PENDING_POLL_MS = 4000;+const EMPTY_CATALOG = { jobTypes: [], apps: [], universes: [], imageModes: [] };export default function QuotaBurn() {@@ -84,6 +89,16 @@ export default function QuotaBurn() {]).finally(() => setLoading(false));}, [load]);+ // 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. Enabled ONLY+ // while something is actually pending — this is not a background refresh loop+ // — and `useAutoRefetch` (rather than a hand-rolled timer) so it pauses on a+ // hidden tab: re-requesting a multi-second scrape behind a backgrounded tab is+ // the one thing this poll must not do.+ const anyPending = (status?.families || []).some((row) => row.pending);+ useAutoRefetch(load, PENDING_POLL_MS, { enabled: anyPending, immediate: false, pollOnly: true });+// 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, so// the PUT carries every change rather than just the last field touched.diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsxindex 8d4eff99fc..d469d4df83 100644--- a/client/src/pages/QuotaBurn.test.jsx+++ b/client/src/pages/QuotaBurn.test.jsx@@ -3,6 +3,7 @@ import { act, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter, Route, Routes } from 'react-router';import QuotaBurn from './QuotaBurn';+import { sleep } from '../utils/sleep';vi.mock('../services/api', () => ({getQuotaBurn: vi.fn(),@@ -90,6 +91,36 @@ 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 () => {+ // The server does not hold the response open for a 10-20s CLI/TUI spawn on a+ // cold cache — it answers with `pending` and the page fills the number in.+ // "reading quota…" must not be confused with a verdict: a pending family+ // has no reading yet, so neither "will burn" nor a skip reason is true.+ const pendingStatus = {+ ...status,+ families: [{ ...status.families[0], willBurn: false, percentRemaining: null, skipReason: 'reading provider quota…', pending: true }, status.families[1]],+ };+ api.getQuotaBurn.mockResolvedValueOnce({ config, status: pendingStatus });+ renderPage();++ expect(await screen.findByText(/reading quota…/)).toBeInTheDocument();+ // The plan itself rendered on that same first paint — the page is usable+ // before any provider has answered.+ expect(screen.getByLabelText(/Run the quota-burn loop automatically/)).toBeInTheDocument();++ // The poll (default mock: no longer pending) replaces it with the reading.+ expect(await screen.findByText(/62% left/, undefined, { timeout: 8000 })).toBeInTheDocument();+ expect(screen.queryByText(/reading quota…/)).not.toBeInTheDocument();+ });++ it('does NOT poll when nothing is pending', async () => {+ renderPage();+ await screen.findByText(/62% left/);+ // One load on mount, and no timer re-arming behind it.+ await sleep(100);+ expect(api.getQuotaBurn).toHaveBeenCalledTimes(1);+ });+it('saves the master switch as a partial patch', async () => {const user = userEvent.setup();renderPage();diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex c90f7ab285..351d41a8df 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useCallback, useState, useEffect } from 'react';import { useSearchParams } from 'react-router';import { RefreshCw, Clock, AlertTriangle, DatabaseZap } from 'lucide-react';import * as api from '../services/api';@@ -7,6 +7,11 @@ import PageSkeleton from '../components/ui/PageSkeleton';import Pill from '../components/ui/Pill';import { formatCompactCount } from '../utils/formatters';import { useAsyncAction } from '../hooks/useAsyncAction';+import { useAutoRefetch } from '../hooks/useAutoRefetch';++// How often to re-ask while a provider's quota reading is still being taken. A+// CLI/TUI scrape is a 10-20s spawn, so this is a handful of polls, not a loop.+const PENDING_POLL_MS = 4000;const PERIOD_OPTIONS = [{ id: '7d', label: '7 days' },@@ -94,14 +99,25 @@ function ProviderQuotaCard({ quota }) {<p className="text-sm text-gray-500">{quota.note || 'Usage reporting is not available for this provider.'}</p>)}- {quota.supported && quota.error && (+ {/* The reading is still being taken. It comes BEFORE the error and empty+ branches because a pending card has no limits — rendering it through+ those says "No rate-limit data reported", which is a verdict about the+ provider rather than a statement about a scrape still in flight. */}+ {quota.supported && quota.pending && (+ <div className="flex items-center gap-2 text-sm text-gray-400 py-1">+ <BrailleSpinner />+ <span>{quota.note || 'Reading quota…'}</span>+ </div>+ )}++ {quota.supported && !quota.pending && quota.error && (<div className="flex items-start gap-2 text-sm text-gray-400 py-1"><AlertTriangle size={15} className="text-port-warning mt-0.5 shrink-0" /><span>{quota.error}</span></div>)}- {quota.supported && !quota.error && (+ {quota.supported && !quota.pending && !quota.error && (<div className="space-y-2">{quota.limits?.length > 0 && (<div>@@ -160,7 +176,7 @@ function ProviderQuotaSection() {const [loading, setLoading] = useState(true);const [error, setError] = useState(false);- const load = async (refresh = false) => {+ const load = useCallback(async (refresh = false) => {setLoading(true);setError(false);const result = await api.getProviderUsage({ refresh }).catch(() => null);@@ -171,9 +187,16 @@ function ProviderQuotaSection() {setError(true);}setLoading(false);- };+ }, []);++ useEffect(() => { load(); }, [load]);- useEffect(() => { load(); }, []);+ // 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+ // while something is pending — the section does not otherwise auto-refresh.+ const anyPending = (quotas || []).some((quota) => quota.pending);+ useAutoRefetch(load, PENDING_POLL_MS, { enabled: anyPending, immediate: false, pollOnly: true });return (<div className="space-y-3">diff --git a/server/lib/README.md b/server/lib/README.mdindex c5dece4cb8..efebff0581 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -310,6 +310,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. Over `SLASHDO_INLINE_BUDGET_CHARS` (24,000) with a `bodyPath` it emits a filesystem pointer instead of the text — #3110), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. || `slashdoLoader.js` | Loads bundled slashdo command/lib markdown (`lib/slashdo/` submodule) and resolves it the way slashdo's own per-environment installer would, since PortOS inlines these bodies into CoS-agent prompts WITHOUT running that installer. `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals, with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Split out of `fileUtils.js` (a generic file-utilities module) as its own feature module — pairs with `slashdoInvocation.js`, which resolves how a workflow is TYPED per host CLI rather than how its body is loaded. || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |+| `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. || `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |diff --git a/server/lib/index.js b/server/lib/index.jsindex a766d73745..7a6abe08d0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -280,6 +280,7 @@ export * from './slashdoCatalog.js';export * from './slashdoInvocation.js';export * from './slashdoLoader.js';export * from './singleFlight.js';+export * from './staleWhileRevalidate.js';export * from './staticImportGraph.js';export * from './streamBackpressure.js';export * from './sseUtils.js';diff --git a/server/lib/quotaReset.js b/server/lib/quotaReset.jsindex fc4f0382b3..91cc078737 100644--- a/server/lib/quotaReset.js+++ b/server/lib/quotaReset.js@@ -23,37 +23,86 @@ function zoneOffsetMs(epochMs, timeZone) {return (Number(match[2]) * 60 + Number(match[3])) * 60 * 1000 * (match[1] === '+' ? 1 : -1);}-function parseInZone(value, timeZone) {- const parsed = Date.parse(`${value} UTC`);- if (!Number.isFinite(parsed)) return null;- const offset = zoneOffsetMs(parsed, timeZone);- return offset === null ? null : parsed - offset;+/**+ * Reshape a human-rendered reset into something `Date.parse` accepts. These are+ * CLI panel strings, not machine formats, and two shapes off live CLIs defeat a+ * bare parse:+ *+ * claude `Aug 4 at 1:59pm` — an " at " separator and a meridiem glued to+ * the minutes; `Date.parse` returns NaN, so+ * EVERY claude window read as "no window states+ * a reset time" and the family could never burn.+ * claude `Jul 7 at 2pm` — the same, on the hour: no minutes at all.+ * grok `August 10, 06:07` — parses, but see `stampYear` below.+ *+ * Pure.+ */+function normalizeSeparators(value) {+ return value+ .replace(/\s+at\s+/gi, ' ')+ // `1:59pm` → `1:59 pm`, and `2pm` → `2:00 pm` (a bare hour with a meridiem+ // is not a time `Date.parse` accepts).+ .replace(/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b/gi, (_, hour, minute, meridiem) => `${hour}:${minute || '00'} ${meridiem}`);+}++/** The calendar year `now` falls in, as `timeZone` renders it (local when absent). */+function zoneYear(now, timeZone) {+ const at = new Date(now);+ if (!timeZone) return at.getFullYear();+ return Number(new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric' }).format(at));+}++/**+ * Replace the year of a wall-clock instant.+ *+ * A year-less string does NOT default to the current year — `Date.parse('Aug 4+ * 1:59 pm')` resolves to **2001**. The old roll-forward then fired against a+ * date 25 years in the past and landed on 2002, so a grok window reported+ * "already reset" forever. Stamping the year up front also fixes the offset+ * lookup: DST rules are per-year (US rules changed in 2007), so resolving a+ * 2026 reset through a 2001 instant's offset can be off by an hour.+ */+function stampYear(wallMs, year) {+ const date = new Date(wallMs);+ date.setUTCFullYear(year);+ return date.getTime();}/*** @returns {{ epochMs: number|null, source: 'iso'|'parsed'|'unknown' }}*/export function normalizeResetAt(limit, { now = Date.now(), timeZone } = {}) {- const value = typeof limit?.resetsAt === 'string' ? limit.resetsAt.trim() : '';- if (!value) return { epochMs: null, source: 'unknown' };+ const raw = typeof limit?.resetsAt === 'string' ? limit.resetsAt.trim() : '';+ if (!raw) return { epochMs: null, source: 'unknown' };- if (hasExplicitZone(value)) {- const epochMs = Date.parse(value);+ if (hasExplicitZone(raw)) {+ const epochMs = Date.parse(raw);return Number.isFinite(epochMs) ? { epochMs, source: 'iso' } : { epochMs: null, source: 'unknown' };}+ 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' };+const zone = limit?.timezone || timeZone;- let epochMs = zone ? parseInZone(value, zone) : Date.parse(value);- if (!Number.isFinite(epochMs)) return { epochMs: null, source: 'unknown' };-- // Grok omits a year. Treat an already-passed date as the next occurrence,- // avoiding the accidental "reset now" interpretation at year boundaries.- if (!/\b\d{4}\b/.test(value) && epochMs < now - HOUR_MS) {- const date = new Date(epochMs);- date.setUTCFullYear(date.getUTCFullYear() + 1);- epochMs = date.getTime();- }- return { epochMs, source: 'parsed' };+ // 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;+ 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));+ // 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));+ return epochMs === null ? { epochMs: null, source: 'unknown' } : { epochMs, source: 'parsed' };}export function hoursUntilReset(limit, opts = {}) {diff --git a/server/lib/quotaReset.test.js b/server/lib/quotaReset.test.jsindex 37077fb2a6..a3b647ac17 100644--- a/server/lib/quotaReset.test.js+++ b/server/lib/quotaReset.test.js@@ -18,4 +18,47 @@ describe('quota reset normalization', () => {const result = normalizeResetAt({ resetsAt: 'July 27, 2026 08:00:00', timezone: 'America/Los_Angeles' }, { now });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.+ 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' });+ expect(normalizeResetAt({ resetsAt: 'Jul 27 at 11:19am', timezone: 'America/Los_Angeles' }, { now }))+ .toEqual({ epochMs: Date.parse('2026-07-27T18:19:00.000Z'), source: 'parsed' });+ });++ it('parses a claude reset on the hour, which states no minutes at all', () => {+ // `Jul 7 at 2pm` — the shape claudeCodeUsage's own parser fixture emits.+ expect(normalizeResetAt({ resetsAt: 'Jul 27 at 2pm', timezone: 'UTC' }, { now }).epochMs)+ .toBe(Date.parse('2026-07-27T14:00:00.000Z'));+ // Midnight and noon are the two the 12-hour clock gets wrong most often.+ expect(normalizeResetAt({ resetsAt: 'Jul 27 at 12am', timezone: 'UTC' }, { now }).epochMs)+ .toBe(Date.parse('2026-07-27T00:00:00.000Z'));+ expect(normalizeResetAt({ resetsAt: 'Jul 27 at 12pm', timezone: 'UTC' }, { now }).epochMs)+ .toBe(Date.parse('2026-07-27T12:00:00.000Z'));+ });++ it('stamps a year-less reset with the CURRENT year, not Date.parse\'s 2001 default', () => {+ // Grok: `August 10, 06:07`, no year, no zone stated.+ const { epochMs, source } = normalizeResetAt({ resetsAt: 'August 10, 06:07', timezone: 'UTC' }, { now });+ expect(source).toBe('parsed');+ expect(epochMs).toBe(Date.parse('2026-08-10T06:07:00.000Z'));+ expect(hoursUntilReset({ resetsAt: 'August 10, 06:07', timezone: 'UTC' }, { now })).toBeCloseTo(354.1, 0);+ });++ it('rolls a year-less reset that already passed to next year', () => {+ // Read on Dec 31, a "Jan 2" reset belongs to the coming year.+ const newYearsEve = Date.parse('2026-12-31T18:00:00.000Z');+ expect(normalizeResetAt({ resetsAt: 'Jan 2 at 9:00am', timezone: 'UTC' }, { now: newYearsEve }).epochMs)+ .toBe(Date.parse('2027-01-02T09:00:00.000Z'));+ });++ it('keeps a reset that just passed in the past rather than pushing it a year out', () => {+ const justPassed = normalizeResetAt({ resetsAt: 'Jul 26 at 11:30am', timezone: 'UTC' }, { now });+ expect(justPassed.epochMs).toBe(Date.parse('2026-07-26T11:30:00.000Z'));+ expect(hoursUntilReset({ resetsAt: 'Jul 26 at 11:30am', timezone: 'UTC' }, { now })).toBeCloseTo(-0.5, 5);+ });});diff --git a/server/lib/staleWhileRevalidate.js b/server/lib/staleWhileRevalidate.jsnew file mode 100644index 0000000000..8cf1643f8e--- /dev/null+++ b/server/lib/staleWhileRevalidate.js@@ -0,0 +1,135 @@+/**+ * Keyed stale-while-revalidate cache for readings that are EXPENSIVE to take and+ * SLOW to change — provider quota panels, scraped usage, anything behind a+ * multi-second CLI/PTY spawn.+ *+ * The problem it solves: a plain TTL cache blocks the first caller after the TTL+ * lapses. When producing a value costs 10-20 seconds, that caller is a page load+ * rendering nothing, and the number it waited for had moved by single digits. So+ * a stale reading is served IMMEDIATELY and the refresh lands behind the+ * response. Values carry their own `fetchedAt`, so serving stale never makes the+ * reported age dishonest — it only stops that age being paid for synchronously.+ *+ * Three things a naive serve-stale loop gets wrong, handled here once:+ *+ * 1. **A background refresh must not reject unhandled.** The stored promise+ * always resolves to `{ value }` or `{ error }`. A caller served stale never+ * awaits it, and an unawaited rejection takes the process down.+ * 2. **A failure keeps the last good value** rather than flipping a healthy card+ * to an error state on one transient hiccup — and records `failedAt`, so a+ * persistently broken producer is retried on a backoff instead of respawned+ * by every caller. Without that, "serve stale and revalidate" degrades into+ * "spawn a subprocess per request" exactly when the subprocess is broken.+ * 3. **Waiting is terminal.** A cold cache can answer `PENDING` for callers that+ * render "still reading" and poll — but a cold cache whose producer has+ * already FAILED throws instead, because `PENDING` there promises a reading+ * that is never coming and the poller never stops.+ *+ * `wait` is a three-state enum rather than a pair of booleans on purpose: the+ * combination "give me a live reading, but also don't wait for one" has no+ * meaning, and encoding it as two flags forces a precedence rule at every layer+ * that threads them.+ *+ * @see server/lib/singleFlight.js — the bare in-flight coalescer, with no cache.+ */++/** A cold cache whose first reading is still being produced. */+export const PENDING = Symbol('stale-while-revalidate:pending');++/**+ * What a reader is willing to wait for:+ * - `fresh` — bypass the cache and block for a live reading (an explicit+ * Refresh, or work that is about to spend real money on the result).+ * - `cached` — serve whatever is cached, revalidating behind the caller; block+ * only when nothing is cached at all. The default.+ * - `never` — as `cached`, but a cold cache returns `PENDING` instead of+ * blocking.+ */+export const WAIT = Object.freeze({ FRESH: 'fresh', CACHED: 'cached', NEVER: 'never' });++/**+ * @param {object} options+ * @param {number} options.ttlMs How long a reading counts as fresh.+ * @param {number} [options.failureBackoffMs] Minimum gap between attempts after a+ * failure. Paces a broken producer without making a healthy one wait.+ * @param {(value:any)=>boolean} [options.isComplete] Whether a SUCCESSFUL reading+ * earns a full TTL. A producer can succeed and still return something degraded+ * (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 {number} [options.partialTtlMs] TTL for a reading `isComplete` rejects.+ */+export function createStaleWhileRevalidate({+ ttlMs,+ failureBackoffMs = 30 * 1000,+ isComplete = () => true,+ partialTtlMs = 30 * 1000,+} = {}) {+ const entries = new Map(); // key -> { at, value, ttl, failedAt, inflight }++ /**+ * Start one production and fold concurrent callers into it. The returned+ * promise NEVER rejects (see the docblock) — callers wanting the error unwrap+ * `{ error }` themselves.+ */+ function start(key, produce) {+ const inflight = Promise.resolve()+ .then(produce)+ .then((value) => {+ entries.set(key, { at: Date.now(), value, ttl: isComplete(value) ? ttlMs : partialTtlMs });+ return { value };+ })+ .catch((error) => {+ // Keep the last good reading and record WHEN this failed, so the backoff+ // can pace the retry. Dropping the entry here is what would let every+ // subsequent poll start a fresh spawn.+ const { at, value, ttl } = entries.get(key) || {};+ entries.set(key, { at, value, ttl, failedAt: Date.now() });+ return { error };+ });+ entries.set(key, { ...entries.get(key), inflight });+ return inflight;+ }++ /**+ * @param {any} key+ * @param {() => Promise<any>} produce+ * @param {{ wait?: 'fresh'|'cached'|'never' }} [options]+ * @returns {Promise<any|PENDING>} the reading, or `PENDING` on a cold cache+ * under `wait: 'never'`. Throws when production failed with nothing cached+ * to fall back on.+ */+ async function read(key, produce, { wait = WAIT.CACHED } = {}) {+ const live = wait === WAIT.FRESH;+ const hit = entries.get(key);+ const cached = hit?.value !== undefined;+ if (!live && cached && Date.now() - hit.at < (hit.ttl ?? ttlMs)) return hit.value;++ // Don't hammer a producer that just failed — unless the caller explicitly+ // asked for a live reading, which is a user waiting on a button.+ if (!live && hit?.failedAt !== undefined && Date.now() - hit.failedAt < failureBackoffMs) {+ if (cached) return hit.value; // stale, but real+ // Nothing cached and the producer is failing. `PENDING` here would promise+ // a reading that is not coming, and the caller would poll forever — so+ // fail, and let it render an error instead.+ throw new Error('the previous attempt failed; backing off before retrying');+ }++ const inflight = hit?.inflight || start(key, produce);+ if (!live) {+ if (cached) return hit.value; // stale-while-revalidate+ if (wait === WAIT.NEVER) return PENDING;+ }+ const settled = await inflight;+ if (settled.error) throw settled.error;+ return settled.value;+ }++ /** Test seam / explicit invalidation. Omit `key` to clear everything. */+ function clear(key) {+ if (key === undefined) entries.clear();+ else entries.delete(key);+ }++ return { read, clear };+}diff --git a/server/lib/staleWhileRevalidate.test.js b/server/lib/staleWhileRevalidate.test.jsnew file mode 100644index 0000000000..d83d5b6ba4--- /dev/null+++ b/server/lib/staleWhileRevalidate.test.js@@ -0,0 +1,142 @@+import { describe, expect, it, vi, afterEach } from 'vitest';+import { createStaleWhileRevalidate, PENDING, WAIT } from './staleWhileRevalidate.js';++afterEach(() => { vi.useRealTimers(); });++const TTL = 60_000;++describe('createStaleWhileRevalidate', () => {+ it('caches within the TTL and folds concurrent callers into one production', async () => {+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ const produce = vi.fn().mockResolvedValue('a');+ const [one, two] = await Promise.all([+ cache.read('k', produce),+ cache.read('k', produce),+ ]);+ expect([one, two]).toEqual(['a', 'a']);+ expect(await cache.read('k', produce)).toBe('a');+ expect(produce).toHaveBeenCalledTimes(1);+ });++ // The point of the whole module: a caller must never pay for a slow producer+ // just because a timer lapsed.+ it('serves a STALE value immediately and revalidates behind the caller', async () => {+ vi.useFakeTimers();+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ await cache.read('k', () => Promise.resolve('old'));++ vi.advanceTimersByTime(TTL + 1);+ let release;+ const slow = () => new Promise((resolve) => { release = resolve; });+ // A blocking cache would hang here — this producer never settles on its own.+ expect(await cache.read('k', slow)).toBe('old');++ release('new');+ await vi.advanceTimersByTimeAsync(0);+ expect(await cache.read('k', slow)).toBe('new');+ });++ it("returns PENDING on a cold cache under wait:'never', and starts the production", async () => {+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ let release;+ const produce = vi.fn(() => new Promise((resolve) => { release = resolve; }));++ expect(await cache.read('k', produce, { wait: WAIT.NEVER })).toBe(PENDING);+ release('a');+ await vi.waitFor(async () => {+ expect(await cache.read('k', produce, { wait: WAIT.NEVER })).toBe('a');+ });+ expect(produce).toHaveBeenCalledTimes(1); // started once, not per poll+ });++ it("wait:'fresh' bypasses a perfectly fresh value and waits for a live one", async () => {+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ await cache.read('k', () => Promise.resolve('old'));+ expect(await cache.read('k', () => Promise.resolve('new'), { wait: WAIT.FRESH })).toBe('new');+ });++ // A transient failure must not flip a healthy reading to an error state.+ it('keeps the last good value when a revalidation fails', async () => {+ vi.useFakeTimers();+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ await cache.read('k', () => Promise.resolve('good'));++ vi.advanceTimersByTime(TTL + 1);+ expect(await cache.read('k', () => Promise.reject(new Error('boom')))).toBe('good');+ await vi.advanceTimersByTimeAsync(0);+ expect(await cache.read('k', () => Promise.reject(new Error('boom')))).toBe('good');+ });++ // Without the backoff, "serve stale + revalidate" becomes "start a new+ // subprocess on every request" exactly when the subprocess is broken.+ it('backs off instead of re-running a producer that just failed', async () => {+ vi.useFakeTimers();+ const cache = createStaleWhileRevalidate({ ttlMs: TTL, failureBackoffMs: 30_000 });+ await cache.read('k', () => Promise.resolve('good'));+ vi.advanceTimersByTime(TTL + 1);++ const failing = vi.fn().mockRejectedValue(new Error('boom'));+ await cache.read('k', failing);+ await vi.advanceTimersByTimeAsync(0);++ // Three more reads inside the backoff window: still one attempt total.+ for (let i = 0; i < 3; i += 1) await cache.read('k', failing);+ expect(failing).toHaveBeenCalledTimes(1);++ // Past the window it tries again.+ vi.advanceTimersByTime(30_001);+ await cache.read('k', failing);+ expect(failing).toHaveBeenCalledTimes(2);+ });++ // PENDING promises a reading that is coming. When production has already+ // failed with nothing cached, it isn't — so a poller would never stop.+ it('throws rather than answering PENDING when a cold production has failed', async () => {+ vi.useFakeTimers();+ const cache = createStaleWhileRevalidate({ ttlMs: TTL, failureBackoffMs: 30_000 });+ const failing = vi.fn().mockRejectedValue(new Error('boom'));++ expect(await cache.read('k', failing, { wait: WAIT.NEVER })).toBe(PENDING);+ await vi.advanceTimersByTimeAsync(0);+ await expect(cache.read('k', failing, { wait: WAIT.NEVER })).rejects.toThrow(/backing off/);+ });++ it('propagates the error to a caller that chose to wait', async () => {+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ await expect(cache.read('k', () => Promise.reject(new Error('boom')))).rejects.toThrow('boom');+ });++ // A degraded-but-successful reading is still cached — not caching it at all is+ // what turns every poll into a fresh spawn — it just expires sooner.+ it('gives an incomplete reading the short TTL so the next view self-heals', async () => {+ vi.useFakeTimers();+ const cache = createStaleWhileRevalidate({+ ttlMs: TTL, partialTtlMs: 1000, isComplete: (v) => v !== 'partial',+ });+ const produce = vi.fn().mockResolvedValueOnce('partial').mockResolvedValueOnce('full');++ expect(await cache.read('k', produce)).toBe('partial');+ vi.advanceTimersByTime(500);+ expect(await cache.read('k', produce)).toBe('partial'); // still inside the short TTL+ expect(produce).toHaveBeenCalledTimes(1);++ vi.advanceTimersByTime(600); // past partialTtlMs, far short of ttlMs+ expect(await cache.read('k', produce)).toBe('partial'); // stale-served…+ await vi.advanceTimersByTimeAsync(0);+ expect(await cache.read('k', produce)).toBe('full'); // …and revalidated+ });++ it('keys entries independently and clears them', async () => {+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ await cache.read('a', () => Promise.resolve(1));+ await cache.read('b', () => Promise.resolve(2));+ expect(await cache.read('a', () => Promise.resolve(99))).toBe(1);++ cache.clear('a');+ expect(await cache.read('a', () => Promise.resolve(99))).toBe(99);+ expect(await cache.read('b', () => Promise.resolve(99))).toBe(2);++ cache.clear();+ expect(await cache.read('b', () => Promise.resolve(99))).toBe(99);+ });+});diff --git a/server/routes/usage.js b/server/routes/usage.jsindex ec8474aa46..663be345c0 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -6,6 +6,7 @@ import { getAllProviders } from '../services/providers.js';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest, usageQuerySchema, usageMessagesSchema } from '../lib/validation.js';import { resolveUsageRange } from '../lib/usageRange.js';+import { WAIT } from '../lib/staleWhileRevalidate.js';import {getHistoricalUsageBackfillStatus,startHistoricalUsageBackfill@@ -26,19 +27,30 @@ router.get('/', asyncHandler(async (req, res) => {// GET /api/usage/providers - Subscription-quota status for every enabled// provider family (claude, codex, agy, grok). Providers without a queryable-// usage surface report `supported: false`. `?refresh=1` bypasses the cache.+// usage surface report `supported: false`.+//+// ONE policy for every status read: it never blocks on a slow reading. A cached+// one is served immediately (and revalidated behind the response); a cold one+// comes back as a `pending: true` card the UI renders as "reading…" and polls.+// 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.router.get('/providers', asyncHandler(async (req, res) => {const refresh = req.query.refresh === '1' || req.query.refresh === 'true';- const providers = await getProviderQuotas({ refresh });+ const providers = await getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER });res.json({ providers });}));// GET /api/usage/claude-code - Claude Code SUBSCRIPTION rate-limit usage,// parsed from the CLI's `/usage` output. Kept for back-compat — the usage page// now reads the generalized /providers endpoint. `?refresh=1` bypasses cache.+//+// This one still BLOCKS on a cold cache: its response is the reading itself,+// with no card shape to carry a `pending` flag, so a caller has nothing to+// render or poll on. The wait is bounded by the CLI's own spawn timeout.router.get('/claude-code', asyncHandler(async (req, res) => {const refresh = req.query.refresh === '1' || req.query.refresh === 'true';- const data = await getClaudeCodeUsage({ refresh });+ const data = await getClaudeCodeUsage({ wait: refresh ? WAIT.FRESH : WAIT.CACHED });res.json(data);}));diff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex e82799b9f4..e00cd02fc8 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -110,7 +110,7 @@ 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({ refresh: true });+ expect(getProviderQuotas).toHaveBeenCalledWith({ wait: 'fresh' });});it('POST /api/usage/messages rejects negative or non-integer token counts', async () => {diff --git a/server/services/claudeCodeUsage.js b/server/services/claudeCodeUsage.jsindex fb83b742c1..5a65892e8b 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 { createStaleWhileRevalidate, WAIT } from '../lib/staleWhileRevalidate.js';/*** Claude Code SUBSCRIPTION usage — the plan rate-limit numbers surfaced by the@@ -169,8 +170,25 @@ export function parseUsageOutput(text) {// --- fetch + cache --------------------------------------------------------let cache = null; // { data, at }-let inflight = null;+// One reading, so one cache key. Stale-while-revalidate for the same reason the+// TUI scrapes use it: the CLI spawn costs seconds, and on a 60s TTL nearly every+// page load paid for it while rendering nothing — a usage percentage one minute+// old is not a wrong answer, and the payload carries its own `fetchedAt`.+//+// A read that produced no rate-limit lines is a degraded `/usage` (a transient+// hiccup can drop them), so it earns only the short TTL and the next view+// self-heals. It is still CACHED, though: an API-key user legitimately has no+// limit lines, and not caching that turned every poll into a fresh CLI spawn.+const CACHE_KEY = 'claude-code-usage';+const usageCache = createStaleWhileRevalidate({+ ttlMs: CACHE_TTL_MS,+ isComplete: (data) => data.limits.length > 0,+});++/** Test-only: drop the cached reading so a suite isn't order-dependent. */+export function __resetClaudeCodeUsageCache() {+ usageCache.clear();+}/*** Spawn the Claude Code CLI in print mode, feed `/usage` on stdin, and resolve@@ -231,29 +249,17 @@ function runUsageCli() {}/**- * Get parsed Claude Code subscription usage, cached for 60s. Concurrent callers- * share one in-flight CLI run. `refresh: true` bypasses the cache.+ * Get parsed Claude Code subscription usage. Concurrent callers share one+ * in-flight CLI run; see the cache above for the staleness contract.+ *+ * `wait` (see lib/staleWhileRevalidate.js): `'cached'` (default) serves what is+ * cached and blocks only when nothing is; `'never'` returns the `PENDING`+ * sentinel on a cold cache, for callers that render "still reading" and poll —+ * the CLI run starts either way; `'fresh'` bypasses the cache and waits.*/-export async function getClaudeCodeUsage({ refresh = false } = {}) {- if (!refresh && cache && Date.now() - cache.at < CACHE_TTL_MS) {- return cache.data;- }- if (inflight) return inflight;-- inflight = runUsageCli()- .then((stdout) => {- const parsed = parseUsageOutput(stdout);- const data = { ...parsed, fetchedAt: new Date().toISOString() };- // Only cache a read that actually produced rate-limit lines. A transient- // degraded /usage (e.g. the live-limit lines dropped by a hiccup) would- // otherwise poison the panel with an empty state for the full 60s TTL; not- // caching it lets the next view self-heal. A subscription always has limit- // lines — an API-key user legitimately has none, but re-reading on each- // view for that minority is cheap (the call is 0-token).- if (data.limits.length > 0) cache = { data, at: Date.now() };- return data;- })- .finally(() => { inflight = null; });-- return inflight;+export async function getClaudeCodeUsage({ wait = WAIT.CACHED } = {}) {+ return usageCache.read(CACHE_KEY, async () => {+ const stdout = await runUsageCli();+ return { ...parseUsageOutput(stdout), fetchedAt: new Date().toISOString() };+ }, { wait });}diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 0613388f4d..3ae49d5f92 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -6,6 +6,7 @@ import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';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 { getSettings } from './settings.js';import { getImageGenQuota } from './imageGenQuota.js';import { enabledCloudImageModes } from './imageGen/modes.js';@@ -205,33 +206,27 @@ async function fetchCodexQuota({ codexHome = codexHomeDir() } = {}) {// sandbox PTY (see lib/tuiUsageScrape.js) and parse the rendered screen. The// slash command renders synchronously (no LLM turn) → 0-token, user-triggered.-// A short TTL cache: a TUI scrape costs ~10-15s (spawn + sign-in + render), far-// too slow to repeat on every page poll. `refresh: true` bypasses it. Single--// user install, single process — a plain module-level map is sufficient.-const SCRAPE_CACHE_TTL_MS = 5 * 60 * 1000;-const scrapeCache = new Map(); // familyId -> { at, value } | { inflight }+// A TUI scrape costs ~10-15s (spawn + sign-in + render) — far too slow to repeat+// on every page poll, and far too slow to BLOCK one on. Stale-while-revalidate:+// a cached reading goes out immediately and the refresh lands behind the+// response, so only a genuinely cold cache (or an explicit `wait: 'fresh'`) ever+// waits. Each card stamps its own `fetchedAt` inside the producer, so a served+// stale reading still reports its real age. See lib/staleWhileRevalidate.js for+// the failure-backoff and PENDING contracts.+//+// A scrape that produced NO limits is a degraded panel, not a real reading — it+// gets the short TTL so the next view self-heals, while still being cached+// (leaving it uncached turns each poll into a fresh PTY spawn).+const scrapeCache = createStaleWhileRevalidate({+ ttlMs: 5 * 60 * 1000,+ isComplete: (card) => Boolean(card?.limits?.length),+});/** Test-only: clear the TUI-scrape TTL cache so a suite isn't order-dependent. */export function __resetUsageScrapeCache() {scrapeCache.clear();}-async function cachedScrape(familyId, { refresh }, produce) {- const hit = scrapeCache.get(familyId);- if (!refresh && hit?.value && Date.now() - hit.at < SCRAPE_CACHE_TTL_MS) return hit.value;- if (hit?.inflight) return hit.inflight; // fold concurrent callers into one scrape- const inflight = (async () => {- const value = await produce();- scrapeCache.set(familyId, { at: Date.now(), value });- return value;- })().catch((err) => {- scrapeCache.delete(familyId);- throw err;- });- scrapeCache.set(familyId, { inflight });- return inflight;-}-/*** Render an acronym-preserving title label from an ALL-CAPS token: long words* become Title Case (`GEMINI` → `Gemini`), short all-caps tokens stay as-is@@ -402,7 +397,7 @@ function pickScrapeProvider(providers, binary) {* than a blank card. `name` is the human product name spliced into the copy.*/function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name, readyMarker }) {- return ({ refresh = false, providers = [] } = {}) => {+ return async ({ wait = WAIT.CACHED, providers = [] } = {}) => {const base = { family: id, label, plan: null, activity: [], approximate: true, fetchedAt: new Date().toISOString() };const provider = pickScrapeProvider(providers, binary);// No CLI/TUI provider (e.g. only the API provider is enabled) → unsupported.@@ -426,20 +421,40 @@ function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name, rea// provider edit (different account via envVars, tui↔cli switch, arg change)// doesn't serve the previous account's quota from a stale entry.const cacheKey = `${id}:${command}:${provider.type}:${JSON.stringify(env)}:${JSON.stringify(args)}`;- return cachedScrape(cacheKey, { refresh }, async () => {+ const card = await scrapeCache.read(cacheKey, async () => {const text = await scrapeTuiUsage({ command, args, slashCommand, env, readyMarker });const { limits } = parse(text);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.` };- });+ }, { wait });+ return card === PENDING ? pendingCard(base, name) : card;};}+/**+ * A cold-cache placeholder: the reading has STARTED but there is none yet.+ *+ * Distinct from both an error card and an empty one — `pending` is what lets a+ * consumer say "still reading" and come back, rather than rendering a provider+ * that looks broken or out of quota. It carries no limits, so every gate that+ * needs a number fails closed on it (see `evaluateFamily`). One definition, used+ * by every family: a field added here must reach the claude card too.+ */+const pendingCard = (base, name) => ({+ ...base, supported: true, limits: [], pending: true,+ note: `Reading the ${name} /usage panel…`,+});+// --- Claude: wrap the existing /usage CLI parser ----------------------------async function fetchClaudeQuota({ refresh = false } = {}) {- const data = await getClaudeCodeUsage({ refresh });+const CLAUDE_BASE = { family: 'claude', label: 'Claude Code', plan: null, activity: [], approximate: true };++async function fetchClaudeQuota({ wait = WAIT.CACHED } = {}) {+ const data = await getClaudeCodeUsage({ wait });+ // Cold cache and the caller can poll — the CLI run has been started, so the+ // next read gets a real card.+ if (data === PENDING) return pendingCard({ ...CLAUDE_BASE, fetchedAt: new Date().toISOString() }, 'Claude Code');return {family: 'claude',label: 'Claude Code',@@ -500,8 +515,8 @@ export function resolveEnabledFamilies(providers) {return FAMILIES.filter((family) => enabled.some((p) => family.matches(p)));}-const fetchFamilyQuota = (family, { refresh, providers }) =>- Promise.resolve(family.fetch({ refresh, providers })).catch((err) => ({+const fetchFamilyQuota = (family, { wait, providers }) =>+ Promise.resolve(family.fetch({ wait, providers })).catch((err) => ({family: family.id,label: family.label,supported: true,@@ -513,19 +528,24 @@ const fetchFamilyQuota = (family, { refresh, providers }) =>}));/**- * Quota status for every enabled provider family. `refresh: true` bypasses- * the claude adapter's 60s cache. Never rejects — per-family failures surface- * as `error` entries. Each family fetch receives the enabled providers that- * matched it, so TUI-scrape adapters drive the actual configured provider- * (command + envVars), not a hardcoded binary.+ * Quota status for every enabled provider family. Never rejects — per-family+ * failures surface as `error` entries. Each family fetch receives the enabled+ * providers that matched it, so TUI-scrape adapters drive the actual configured+ * provider (command + envVars), not a hardcoded binary.+ *+ * `wait` (see lib/staleWhileRevalidate.js) decides what a slow reading costs the+ * caller. The default `'cached'` serves what is cached and blocks only on a cold+ * 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.*/-export async function getProviderQuotas({ refresh = false } = {}) {+export async function getProviderQuotas({ wait = WAIT.CACHED } = {}) {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, { refresh, providers: enabled.filter((p) => family.matches(p)) })));+ fetchFamilyQuota(family, { wait, providers: enabled.filter((p) => family.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 againstdiff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsindex c999b41b2f..4d32165b94 100644--- a/server/services/providerUsage.test.js+++ b/server/services/providerUsage.test.js@@ -392,7 +392,78 @@ describe('TUI usage fetchers (via getProviderQuotas)', () => {await getProviderQuotas();await getProviderQuotas(); // cache hit — no second scrapeexpect(scrapeTuiUsage).toHaveBeenCalledTimes(1);- await getProviderQuotas({ refresh: true }); // bypasses cache+ await getProviderQuotas({ wait: 'fresh' }); // bypasses cacheexpect(scrapeTuiUsage).toHaveBeenCalledTimes(2);});++ // A scrape is a multi-second PTY spawn. Blocking on the TTL lapse is what made+ // the Quota Burn / Usage pages take ~7s to open after a few idle minutes.+ it('serves a STALE reading without waiting on the revalidating scrape', async () => {+ vi.useFakeTimers();+ getAllProviders.mockResolvedValue({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });+ scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);+ const [first] = await getProviderQuotas();++ // Past the 5-minute TTL, with a scrape that never settles: a blocking cache+ // would hang here forever. Stale-while-revalidate answers immediately.+ vi.advanceTimersByTime(6 * 60 * 1000);+ scrapeTuiUsage.mockReturnValueOnce(new Promise(() => {}));+ const [stale] = await getProviderQuotas();+ expect(stale.fetchedAt).toBe(first.fetchedAt); // the honest age of what we served+ expect(scrapeTuiUsage).toHaveBeenCalledTimes(2); // …and the refresh did start+ vi.useRealTimers();+ });++ // The cold case a stale value can't cover: nothing cached at all, e.g. the+ // first page load after a server restart.+ it("returns a pending card instead of blocking on a COLD cache under wait:'never'", async () => {+ getAllProviders.mockResolvedValue({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });+ let release;+ scrapeTuiUsage.mockReturnValueOnce(new Promise((resolve) => { release = resolve; }));++ 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.+ release(AGY_PANEL);+ await vi.waitFor(async () => {+ const [card] = await getProviderQuotas({ wait: 'never' });+ expect(card.pending).toBeUndefined();+ expect(card.limits).toHaveLength(4);+ });+ 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);+ const [card] = await getProviderQuotas(); // default 'cached': cold ⇒ waits+ expect(card.pending).toBeUndefined();+ expect(card.limits).toHaveLength(4);++ scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);+ const [refreshed] = await getProviderQuotas({ wait: 'fresh' });+ expect(refreshed.pending).toBeUndefined();+ expect(refreshed.limits).toHaveLength(4);+ });++ it('keeps the last good reading when a background revalidation fails', async () => {+ vi.useFakeTimers();+ getAllProviders.mockResolvedValue({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });+ scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);+ const [first] = await getProviderQuotas();++ vi.advanceTimersByTime(6 * 60 * 1000);+ scrapeTuiUsage.mockRejectedValueOnce(new Error('pty spawn failed'));+ const [served] = await getProviderQuotas();+ expect(served.limits).toHaveLength(4); // stale, not an error card+ await vi.advanceTimersByTimeAsync(0); // let the failed revalidation settle++ // A transient PTY hiccup must not evict the entry and force the next caller+ // to block on a full scrape.+ scrapeTuiUsage.mockReturnValueOnce(new Promise(() => {}));+ const [afterFailure] = await getProviderQuotas();+ expect(afterFailure.fetchedAt).toBe(first.fetchedAt);+ vi.useRealTimers();+ });});diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex 15a9b20ccd..5a3fe23e87 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -154,6 +154,12 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}}if (!card) return { skipReason: 'no enabled provider in this family' };if (card.supported === false) return { skipReason: 'provider has no queryable quota surface' };+ // The reading is still being taken (a cold-cache status read starts the scrape+ // rather than blocking the page on a 20s PTY spawn). NOT an error and NOT an+ // empty allowance — it is "ask again in a moment". A candidate here would burn+ // against a card with no numbers on it, so it fails closed like every other+ // unknown, and holds even under force.+ if (card.pending) return { skipReason: 'reading provider quota…' };if (card.error) return { skipReason: `quota read failed: ${card.error}` };// A card can declare it carries no spendable headroom (`burnable: false`) —// e.g. the Image Gen card, whose 0%-left meter is an OBSERVED refusal, not adiff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.jsindex 4f776c3624..5838ec721c 100644--- a/server/services/quotaBurn.test.js+++ b/server/services/quotaBurn.test.js@@ -30,6 +30,21 @@ describe('selectBurnCandidates', () => {expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], config, { now: NOW })).toHaveLength(1);});+ it('never burns against a card whose reading is still PENDING', () => {+ // A cold-cache status read starts the scrape and returns `pending` rather+ // than holding the page for a 20s PTY spawn. The card carries real-looking+ // fields but no reading — it must fail closed, and say so as its own state+ // rather than borrowing an error or empty-quota verdict.+ const pending = { family: 'grok', supported: true, pending: true, limits: [] };+ expect(selectBurnCandidates([pending], config, { now: NOW })).toEqual([]);+ const [verdict] = evaluateFamilies([pending], config, { now: NOW }).filter((row) => row.family.id === 'grok');+ expect(verdict.candidate).toBeUndefined();+ expect(verdict.skipReason).toMatch(/reading provider quota/i);++ // Pending holds even under force — a forced run can't invent a reading.+ expect(selectBurnCandidates([pending], config, { now: NOW, bypassGatesFor: 'grok' })).toEqual([]);+ });+it('selects burnable windows by reset time then priority', () => {const candidates = selectBurnCandidates([quota('codex', '2026-07-27T00:00:00.000Z'),diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex 4e9010f34d..97d8e4452e 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -24,6 +24,7 @@ import { getQuotaBurnDispatches, evaluateFamilies, recordQuotaBurnDispatch, seleimport { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quotaBurnStore.js';import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';import { familyIsActionable } from '../lib/quotaBurnConfig.js';+import { WAIT } from '../lib/staleWhileRevalidate.js';const TICK_MS = 60_000;@@ -109,6 +110,13 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// automatic cycle a full interval out — on a 12-hour interval, one curiosity// click can defer the tick past the reset the feature exists to spend.if (trigger === 'scheduled') lastRunAt = Date.now();+ // Every cycle says what it decided. Previously ONLY the error paths logged,+ // so clicking "Evaluate now" — which can spend a provider's quota — left no+ // trace in the server log at all, and a cycle that correctly declined was+ // indistinguishable from one that never ran.+ console.log(entry.dispatched+ ? `🔥 Quota-burn ${trigger}: dispatched ${entry.familyId}/${entry.jobId} — ${entry.summary}`+ : `💤 Quota-burn ${trigger}: nothing dispatched — ${entry.reason}`);await recordQuotaBurnRun({ trigger, ...entry });return entry;};@@ -122,7 +130,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// the log with "disabled" rows and bury the last real run.if (!config.enabled && trigger === 'scheduled') return { skipped: 'disabled' };- // Check the plan BEFORE the quota read. `getProviderQuotas({ refresh: true })`+ // Check the plan BEFORE the quota read. `getProviderQuotas({ wait: WAIT.FRESH })`// spawns a multi-second TUI scrape per enabled family; with no actionable// family configured that scrape could never produce a dispatch, and it would// otherwise run every `checkIntervalMinutes` forever.@@ -136,7 +144,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,return finish({ dispatched: false, reason: 'no families enabled' });}- const quotas = await getProviderQuotas({ refresh: true }).catch((err) => {+ const quotas = await getProviderQuotas({ wait: WAIT.FRESH }).catch((err) => {console.error(`❌ Quota-burn could not read provider quota: ${err.message}`);return null;});@@ -210,16 +218,22 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,* burn on the next tick (and if not, exactly why) and each job's pending count.** Returns the config it loaded so the route doesn't read and normalize the same- * file a second time. Reads quota from cache by default — the page's explicit- * Refresh passes `refresh: true` — so opening the page doesn't spawn a TUI- * scrape per family.+ * file a second time.+ *+ * NEVER blocks on a quota reading. A cached one is served immediately (and+ * refreshed behind the response once stale); a cold cache comes back as a+ * `pending: true` card while the scrape runs, which `evaluateFamily` reports as+ * "reading provider quota…" and never turns into a burn. Waiting instead cost+ * this page 20-30s per open — a PTY spawn per family — for numbers that move by+ * single digits an hour. The page's explicit Refresh passes `refresh: true` and+ * does wait, because that click IS the request for a live reading.*/export async function getQuotaBurnStatus({ refresh = false } = {}) {// Independent reads: only `quotas` is slow (a PTY scrape on the Refresh path),// and nothing else waits on it.const [config, quotas, dispatches, runs] = await Promise.all([getQuotaBurnConfig(),- getProviderQuotas({ refresh }).catch((err) => {+ getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER }).catch((err) => {console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);return [];}),@@ -227,24 +241,31 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {getQuotaBurnRuns(),]);+ const cards = new Map(quotas.map((card) => [card.family, card]));// ONE pass over the gate ladder the runner uses — the page's "will burn" and// its reason come from the same verdict, so they can't contradict each other.const families = await Promise.all(evaluateFamilies(quotas, config, { dispatches })- .map(async ({ family, candidate, skipReason }) => ({- id: family.id,- label: candidate?.card?.label || quotas.find((entry) => entry.family === family.id)?.label || family.id,- percentRemaining: candidate?.limit?.percentRemaining ?? null,- hoursUntilReset: candidate ? Math.round(candidate.hoursUntilReset * 10) / 10 : null,- dispatchesUsed: candidate?.dispatchesUsed ?? null,- willBurn: Boolean(candidate),- skipReason: skipReason || null,- // Probe pending work only for families the user actually enabled — a probe- // is not free (the universe job reads every bible), and a disabled- // family's counts are never acted on.- jobs: family.enabled- ? await Promise.all(family.jobs.map(async (job) => ({ id: job.id, pending: await countJobPending({ job, family }) })))- : family.jobs.map((job) => ({ id: job.id, pending: null })),- })));+ .map(async ({ family, candidate, skipReason }) => {+ const card = cards.get(family.id);+ return {+ id: family.id,+ label: candidate?.card?.label || card?.label || family.id,+ percentRemaining: candidate?.limit?.percentRemaining ?? null,+ hoursUntilReset: candidate ? Math.round(candidate.hoursUntilReset * 10) / 10 : null,+ dispatchesUsed: candidate?.dispatchesUsed ?? null,+ willBurn: Boolean(candidate),+ skipReason: skipReason || null,+ // The reading for this family is being taken right now — the page polls+ // again instead of leaving a card that looks like it has no quota.+ pending: Boolean(card?.pending),+ // Probe pending work only for families the user actually enabled — a probe+ // is not free (the universe job reads every bible), and a disabled+ // family's counts are never acted on.+ jobs: family.enabled+ ? await Promise.all(family.jobs.map(async (job) => ({ id: job.id, pending: await countJobPending({ job, family }) })))+ : family.jobs.map((job) => ({ id: job.id, pending: null })),+ };+ }));return { config, status: { running, families, runs } };}