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

show Codex's 100%-used meter instead of a blank card when quota runs out

[._.]/ Adam Eivy7d54b9a2bbab
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fac9ecc0f2..570f9f1339 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -166,6 +166,8 @@
- **Chief of Staff now exposes its persistent Pause/Resume control in the UI.** Stop only tears down the current daemon process; an always-on install can start it again, which made supervised live work a race against unrelated queued agents. The header now separates queue control from process control: Pause keeps CoS healthy but blocks new task evaluation and dispatch across restarts, Resume explicitly reopens the queue, and Stop remains available as the full shutdown. The pause copy also makes clear that already-running agents are not killed, so their work can be paused individually and preserved from the Agents tab.
+- **A fully-spent Codex quota now shows its 100%-used meter and reset date, instead of going blank exactly when you need it.** The Usage page reads Codex quota out of local session telemetry, and it took the single newest `rate_limits` event in the logs. But Codex emits one such event per limit bucket, and its credits bucket reports *no meters at all* — both windows null. So the moment a quota ran out, the next session's credits event became the newest event and clobbered a perfectly good "100% used, resets Aug 15" reading recorded minutes earlier, leaving the card saying "No rate-limit data reported" — a verdict about whether PortOS could see anything, when what it had actually seen was the quota running out. The reading is now the newest telemetry that *carries a window*, so an exhausted quota renders as the full meter it is. Two knock-on corrections come with that: a window whose reset time has already passed is no longer metered at all (now that a reading can come from an older session, a week-old "100% used" bar would otherwise outlive the reset that cleared it), and when nothing anywhere reports a window the card explains why in its own words — the limit it hit, or the credit balance it has left — rather than falling through to the generic blank state. A card in that state now also keeps showing *when* its reading was taken, which used to be suppressed on exactly the cards that most needed it, and Quota Burn no longer calls such a reading a failed quota read when the read plainly succeeded.
+
## Privacy Center
- **Your PII vault stays on one machine — permanently, by decision.** The Privacy Center's vault, organization registry, change-of-address inventory and broker opt-out ledger were always machine-local, but that was recorded as a feature not yet built, which left the door open to syncing them to your other PortOS machines later. It is now a documented guarantee: none of it federates, and none of it ever will without a new decision record superseding this one. The reasoning is written up in full — chiefly that PortOS's peer-sync was built for creative work rather than identity data, that the display masks (`••••1234`, `j•••@example.com`) are readable even when the underlying values are encrypted, and that copying one encryption key to several machines would widen the exposure of every one of them. If you want the vault on a second machine, restore a backup and copy the key by hand — a deliberate act, rather than something that happens quietly in the background. Managing PII for other household members is unaffected and remains planned.
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 0d6d2e6c8a..1ac9b6e740 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -130,10 +130,16 @@ function ProviderQuotaCard({ quota, onRefresh, refreshing, disabled }) {
</div>
)}
+ {/* `error` is also how a card that read fine says it has nothing to
+ meter, so the note rides along — otherwise the one state where the
+ reading's age matters most is the one state that hides it. */}
{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>
+ <span>
+ {quota.error}
+ {quota.note && <span className="block text-xs text-gray-500 mt-1">{quota.note}</span>}
+ </span>
</div>
)}
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index a0d954253e..c191196711 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -24,7 +24,10 @@ import { enabledCloudImageModes } from './imageGen/modes.js';
* `supported: false` means the provider has no queryable usage surface at all
* (the UI renders a muted "not available" note, never an error). A supported
* adapter that fails transiently returns `error` instead of throwing so one
- * broken CLI can't 500 the whole endpoint.
+ * broken CLI can't 500 the whole endpoint. `error` also carries the reason a
+ * reading that DID succeed has nothing to meter (a spent credit balance, a
+ * degraded panel) — in both cases it is the sentence to show in place of
+ * meters, so consumers must not word it as a failure.
*
* `metrics[]` is for a backend whose quota cannot be queried at all: it renders
* as labelled stat tiles instead of a meter, so an adapter never has to invent
@@ -49,11 +52,16 @@ import { enabledCloudImageModes } from './imageGen/modes.js';
//
// The Codex CLI has no queryable usage command, but every session appends
// `token_count` events carrying `rate_limits` (used %, window minutes, reset
-// epoch, plan type) to its rollout log. Reading the newest event costs zero
-// tokens; the numbers are "as of the last Codex session activity."
+// epoch, plan type) to its rollout log. Reading those events costs zero tokens;
+// the numbers are "as of the last Codex telemetry that reported a window" —
+// which is not always the newest event (see parseCodexRateLimits).
const CODEX_SCAN_FILE_LIMIT = 15;
const CODEX_TAIL_BYTES = 256 * 1024;
+// Longest window Codex meters (7 days) plus a day of slack for the timezone
+// its day-directory names are written in. A session older than this cannot
+// hold a window that has not already reset.
+const CODEX_MAX_WINDOW_MS = 8 * 24 * 60 * 60 * 1000;
const codexHomeDir = () => process.env.CODEX_HOME || join(homedir(), '.codex');
@@ -66,12 +74,24 @@ function humanizeWindowMinutes(minutes) {
}
/**
- * Pure: extract the newest `rate_limits` payload from rollout-JSONL content.
- * Scans lines from the end. Returns `{ rateLimits, timestamp }` or null.
+ * Pure: pick the most informative `rate_limits` payload out of rollout-JSONL
+ * content, scanning lines from the end. Returns `{ rateLimits, timestamp }` or
+ * null.
+ *
+ * Most informative, NOT most recent: Codex emits a `rate_limits` event per
+ * limit bucket, and the credits bucket reports `primary: null, secondary:
+ * null` — no meters at all. Taking the newest line unconditionally let one of
+ * those wipe out a perfectly good "100% used, resets <date>" reading from a
+ * session minutes earlier, so an exhausted quota rendered as "No rate-limit
+ * data reported" instead of a full meter. So: prefer the newest payload that
+ * actually carries a usable (unexpired) window, and fall back to the newest
+ * window-less payload only when the text holds nothing better.
+ *
* Exported for tests.
*/
-export function parseCodexRateLimits(jsonlText) {
+export function parseCodexRateLimits(jsonlText, { now = Date.now() } = {}) {
const lines = String(jsonlText || '').split('\n');
+ let fallback = null;
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i];
if (!line.includes('"rate_limits"')) continue;
@@ -82,15 +102,27 @@ export function parseCodexRateLimits(jsonlText) {
continue; // tail-read can clip the oldest line in the chunk mid-JSON
}
const rateLimits = parsed?.payload?.rate_limits ?? parsed?.rate_limits;
- if (rateLimits && typeof rateLimits === 'object') {
- return { rateLimits, timestamp: parsed.timestamp || null };
- }
+ if (!rateLimits || typeof rateLimits !== 'object') continue;
+ const entry = { rateLimits, timestamp: parsed.timestamp || null };
+ if (codexUsableWindows(rateLimits, now).length) return entry;
+ fallback ??= entry;
}
- return null;
+ return fallback;
}
-function codexLimitEntry(scopeKey, window) {
+/**
+ * A window whose reset has already passed has rolled over — its used_percent
+ * describes a spent allowance, not the current one. This matters now that a
+ * reading can come from an older session: otherwise a week-old "100% used"
+ * meter would keep rendering long after the quota came back. One definition,
+ * because `codexNoWindowsMessage` explains the drop this decides.
+ */
+const codexWindowExpired = (window, now) =>
+ Number.isFinite(window?.resets_at) && window.resets_at * 1000 <= now;
+
+function codexLimitEntry(scopeKey, window, now) {
if (!window || typeof window.used_percent !== 'number') return null;
+ if (codexWindowExpired(window, now)) return null;
const windowLabel = humanizeWindowMinutes(window.window_minutes);
const percentUsed = Math.round(window.used_percent);
return {
@@ -111,36 +143,68 @@ function codexLimitEntry(scopeKey, window) {
};
}
+/** Pure: the usable (present, numeric, unexpired) meters in a payload. */
+function codexUsableWindows(rateLimits, now) {
+ return [
+ codexLimitEntry('session', rateLimits?.primary, now),
+ codexLimitEntry('week', rateLimits?.secondary, now)
+ ].filter(Boolean);
+}
+
+/**
+ * Pure: say WHY a payload produced no meters, so the card explains itself
+ * instead of falling through to the client's bare "No rate-limit data
+ * reported" — which reads as "we couldn't tell" when the telemetry actually
+ * did say something (a spent credit balance, a limit that has since reset).
+ */
+function codexNoWindowsMessage(rateLimits, now) {
+ const bucket = rateLimits?.limit_id ? ` for the "${rateLimits.limit_id}" limit` : '';
+ if (rateLimits?.rate_limit_reached_type) {
+ return `Codex reports its ${rateLimits.rate_limit_reached_type} rate limit reached${bucket}, with no window telemetry to meter.`;
+ }
+ // The windows were real and metered — they have simply rolled over since.
+ if ([rateLimits?.primary, rateLimits?.secondary].some((w) => codexWindowExpired(w, now))) {
+ return `Every rate-limit window Codex last reported${bucket} has since reset — run Codex once for a current reading.`;
+ }
+ const credits = rateLimits?.credits;
+ const balance = credits && !credits.unlimited && credits.has_credits === false
+ ? ` — credit balance ${credits.balance ?? 0}`
+ : '';
+ return `Codex reported no rate-limit windows${bucket} in its latest telemetry${balance}.`;
+}
+
/**
* Pure: map a codex `rate_limits` payload + event timestamp to the common
* quota shape. Exported for tests.
*/
-export function mapCodexQuota(rateLimits, timestamp) {
- const limits = [
- codexLimitEntry('session', rateLimits.primary),
- codexLimitEntry('week', rateLimits.secondary)
- ].filter(Boolean);
+export function mapCodexQuota(rateLimits, timestamp, { now = Date.now() } = {}) {
+ const limits = codexUsableWindows(rateLimits, now);
return {
family: 'codex',
label: 'Codex',
supported: true,
- plan: rateLimits.plan_type || 'unknown',
+ plan: rateLimits?.plan_type || 'unknown',
limits,
activity: [],
approximate: true,
+ // Wording is "telemetry", not "session activity": the reading can come from
+ // an older session than the newest one when that session reported no window.
note: timestamp
- ? `As of the last Codex session activity (${timestamp}). Local telemetry only.`
- : 'As of the last Codex session activity. Local telemetry only.',
+ ? `As of the last Codex rate-limit telemetry (${timestamp}). Local telemetry only.`
+ : 'As of the last Codex rate-limit telemetry. Local telemetry only.',
+ ...(limits.length ? {} : { error: codexNoWindowsMessage(rateLimits, now) }),
fetchedAt: new Date().toISOString()
};
}
/**
- * Newest-first rollout log paths under <codexHome>/sessions. Codex lays
- * sessions out as `sessions/YYYY/MM/DD/rollout-<ISO-timestamp>-<uuid>.jsonl`,
- * so directory and file names both sort chronologically — walk them in
- * descending lexicographic order and stop as soon as the scan limit is hit
- * (typically 1-2 leaf dirs touched, zero stat calls).
+ * Newest-first rollout logs under <codexHome>/sessions, as
+ * `{ path, dayStartMs }`. Codex lays sessions out as
+ * `sessions/YYYY/MM/DD/rollout-<ISO-timestamp>-<uuid>.jsonl`, so directory and
+ * file names both sort chronologically — walk them in descending lexicographic
+ * order and stop as soon as the scan limit is hit (typically 1-2 leaf dirs
+ * touched, zero stat calls). `dayStartMs` comes from the directory names, so
+ * a caller can age a file out without stat'ing it.
*/
async function listCodexRolloutFiles(codexHome) {
const sessionsDir = join(codexHome, 'sessions');
@@ -156,12 +220,16 @@ async function listCodexRolloutFiles(codexHome) {
for (const month of await newestFirstDirs(join(sessionsDir, year))) {
for (const day of await newestFirstDirs(join(sessionsDir, year, month))) {
const dayDir = join(sessionsDir, year, month, day);
+ // Local midnight of the directory's date — the earliest instant any
+ // session inside it can have started. NaN for a non-date dir name,
+ // which compares false against every cutoff and so is never aged out.
+ const dayStartMs = new Date(`${year}-${month}-${day}T00:00:00`).getTime();
const names = (await readdir(dayDir).catch(() => []))
.filter((n) => n.startsWith('rollout-') && n.endsWith('.jsonl'))
.sort()
.reverse();
for (const name of names) {
- files.push(join(dayDir, name));
+ files.push({ path: join(dayDir, name), dayStartMs });
if (files.length >= CODEX_SCAN_FILE_LIMIT) return files;
}
}
@@ -170,14 +238,29 @@ async function listCodexRolloutFiles(codexHome) {
return files;
}
-async function fetchCodexQuota({ codexHome = codexHomeDir() } = {}) {
+/** Exported for tests (which point `codexHome` at a fixture tree). */
+export async function fetchCodexQuota({ codexHome = codexHomeDir(), now = Date.now() } = {}) {
const files = await listCodexRolloutFiles(codexHome);
- for (const file of files) {
+ // Newest-usable-wins across files, exactly as parseCodexRateLimits applies it
+ // within one: keep the newest window-less reading as a fallback, but keep
+ // looking for one that carries a meter.
+ let fallback = null;
+ for (const { path: file, dayStartMs } of files) {
+ // Nothing older than the longest window can still hold an unexpired meter,
+ // so once a fallback is in hand those files can only repeat it — stop
+ // rather than tail-read every remaining session. Without this an install
+ // whose last Codex run has aged out re-reads the full CODEX_SCAN_FILE_LIMIT
+ // on every poll, and this adapter (unlike the others) has no cache.
+ if (fallback && dayStartMs < now - CODEX_MAX_WINDOW_MS) break;
const tail = await readFileTail(file, CODEX_TAIL_BYTES);
if (!tail) continue;
- const found = parseCodexRateLimits(tail);
- if (found) return mapCodexQuota(found.rateLimits, found.timestamp);
+ const found = parseCodexRateLimits(tail, { now });
+ if (!found) continue;
+ const quota = mapCodexQuota(found.rateLimits, found.timestamp, { now });
+ if (quota.limits.length) return quota;
+ fallback ??= quota;
}
+ if (fallback) return fallback;
return {
family: 'codex',
label: 'Codex',
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 6ac6f1e803..b32f4ecbf7 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// providerUsage imports the provider config service (toolkit-backed) and the
// claude CLI wrapper — mock both so this suite stays hermetic.
@@ -31,8 +31,12 @@ vi.mock('./imageGenQuota.js', () => ({
} : null))
}));
+import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
import {
- parseCodexRateLimits, mapCodexQuota, resolveEnabledFamilies, getProviderQuotas,
+ parseCodexRateLimits, mapCodexQuota, fetchCodexQuota, resolveEnabledFamilies, getProviderQuotas,
parseAgyUsage, parseGrokUsage, agyRefreshToIso, __resetUsageScrapeCache,
} from './providerUsage.js';
import { getAllProviders } from './providers.js';
@@ -93,21 +97,63 @@ const SAMPLE_RATE_LIMITS = {
plan_type: 'pro'
};
+// Fixed clock BEFORE both sample resets, so window-expiry filtering is
+// deterministic instead of "whenever the suite happens to run".
+const SAMPLE_NOW = Date.parse('2025-12-31T12:00:00Z');
+
+// Shape Codex emits for its window-less credits bucket: a rate_limits payload
+// with both meters null. Invented values only.
+const CREDITS_ONLY_RATE_LIMITS = {
+ limit_id: 'premium',
+ primary: null,
+ secondary: null,
+ credits: { has_credits: false, unlimited: false, balance: '0' },
+ plan_type: null,
+ rate_limit_reached_type: null
+};
+
describe('parseCodexRateLimits', () => {
it('returns the newest rate_limits event in the log', () => {
const older = codexLine({ ...SAMPLE_RATE_LIMITS, primary: { ...SAMPLE_RATE_LIMITS.primary, used_percent: 3 } }, '2026-01-01T00:00:00Z');
const newer = codexLine(SAMPLE_RATE_LIMITS, '2026-01-02T00:00:00Z');
const text = [older, '{"type":"other"}', newer, '{"type":"trailing"}'].join('\n');
- const found = parseCodexRateLimits(text);
+ const found = parseCodexRateLimits(text, { now: SAMPLE_NOW });
expect(found.timestamp).toBe('2026-01-02T00:00:00Z');
expect(found.rateLimits.primary.used_percent).toBe(7);
});
+ it('prefers an older payload WITH windows over a newer window-less one', () => {
+ // The regression: an exhausted quota's newest event is the credits bucket,
+ // which carries no meters. Taking it hid the real "100% used" reading.
+ const withWindows = codexLine({ ...SAMPLE_RATE_LIMITS, primary: { ...SAMPLE_RATE_LIMITS.primary, used_percent: 100 } }, '2026-01-01T00:00:00Z');
+ const creditsOnly = codexLine(CREDITS_ONLY_RATE_LIMITS, '2026-01-01T00:30:00Z');
+ const found = parseCodexRateLimits([withWindows, creditsOnly].join('\n'), { now: SAMPLE_NOW });
+ expect(found.timestamp).toBe('2026-01-01T00:00:00Z');
+ expect(found.rateLimits.primary.used_percent).toBe(100);
+ });
+
+ it('falls back to the newest window-less payload when nothing better exists', () => {
+ const older = codexLine({ ...CREDITS_ONLY_RATE_LIMITS, limit_id: 'stale' }, '2026-01-01T00:00:00Z');
+ const newer = codexLine(CREDITS_ONLY_RATE_LIMITS, '2026-01-01T00:30:00Z');
+ const found = parseCodexRateLimits([older, newer].join('\n'), { now: SAMPLE_NOW });
+ expect(found.timestamp).toBe('2026-01-01T00:30:00Z');
+ expect(found.rateLimits.limit_id).toBe('premium');
+ });
+
+ it('does not treat an already-reset window as a reason to prefer a payload', () => {
+ // Both windows expired, so the newest payload wins on recency alone.
+ const expired = codexLine(SAMPLE_RATE_LIMITS, '2026-01-01T00:00:00Z');
+ const creditsOnly = codexLine(CREDITS_ONLY_RATE_LIMITS, '2026-01-01T00:30:00Z');
+ const afterReset = Date.parse('2026-02-01T00:00:00Z'); // past both resets_at
+ const found = parseCodexRateLimits([expired, creditsOnly].join('\n'), { now: afterReset });
+ expect(found.timestamp).toBe('2026-01-01T00:30:00Z');
+ });
+
it('skips a clipped (unparseable) line and keeps scanning', () => {
const clipped = codexLine(SAMPLE_RATE_LIMITS).slice(20); // broken head from a tail-read
const good = codexLine(SAMPLE_RATE_LIMITS);
// clipped line is NEWER (later in file) — parser must fall back to the good one
- expect(parseCodexRateLimits([good, clipped].join('\n'))).not.toBeNull();
+ expect(parseCodexRateLimits([good, clipped].join('\n'), { now: SAMPLE_NOW })).not.toBeNull();
});
it('returns null when no rate_limits event exists', () => {
@@ -118,20 +164,117 @@ describe('parseCodexRateLimits', () => {
describe('mapCodexQuota', () => {
it('maps primary/secondary windows to the common limit shape', () => {
- const quota = mapCodexQuota(SAMPLE_RATE_LIMITS, '2026-01-02T00:00:00Z');
+ const quota = mapCodexQuota(SAMPLE_RATE_LIMITS, '2026-01-02T00:00:00Z', { now: SAMPLE_NOW });
expect(quota).toMatchObject({ family: 'codex', supported: true, plan: 'pro', approximate: true });
expect(quota.limits).toHaveLength(2);
expect(quota.limits[0]).toMatchObject({ key: 'session', label: 'Current 5h window', percentUsed: 7, percentRemaining: 93 });
expect(quota.limits[1]).toMatchObject({ key: 'week', label: 'Current week', percentUsed: 26, percentRemaining: 74 });
expect(quota.limits[0].resetsAt).toBe(new Date(1767225600 * 1000).toISOString());
expect(quota.note).toContain('2026-01-02T00:00:00Z');
+ expect(quota.error).toBeUndefined();
+ });
+
+ it('renders a fully-spent window as a 100%-used meter, not an empty card', () => {
+ const spent = { ...SAMPLE_RATE_LIMITS, primary: null, secondary: { used_percent: 100, window_minutes: 10080, resets_at: 1767830400 } };
+ const quota = mapCodexQuota(spent, '2026-01-02T00:00:00Z', { now: SAMPLE_NOW });
+ expect(quota.limits).toHaveLength(1);
+ expect(quota.limits[0]).toMatchObject({ key: 'week', percentUsed: 100, percentRemaining: 0 });
+ expect(quota.error).toBeUndefined();
});
it('omits windows with no usable used_percent', () => {
- const quota = mapCodexQuota({ primary: { used_percent: 50, window_minutes: 300 }, secondary: null, plan_type: null }, null);
+ const quota = mapCodexQuota({ primary: { used_percent: 50, window_minutes: 300 }, secondary: null, plan_type: null }, null, { now: SAMPLE_NOW });
expect(quota.limits).toHaveLength(1);
expect(quota.plan).toBe('unknown');
});
+
+ it('drops a window whose reset has already passed', () => {
+ const quota = mapCodexQuota(SAMPLE_RATE_LIMITS, null, { now: Date.parse('2026-01-05T00:00:00Z') });
+ expect(quota.limits.map((l) => l.key)).toEqual(['week']); // 5h window reset on the 1st
+ });
+
+ it('explains a window-less credits payload instead of leaving the card blank', () => {
+ const quota = mapCodexQuota(CREDITS_ONLY_RATE_LIMITS, '2026-01-01T00:30:00Z', { now: SAMPLE_NOW });
+ expect(quota.limits).toHaveLength(0);
+ expect(quota.error).toContain('credit balance 0');
+ expect(quota.error).toContain('premium');
+ });
+
+ it('names the reached limit type when the payload reports one', () => {
+ const quota = mapCodexQuota({ ...CREDITS_ONLY_RATE_LIMITS, rate_limit_reached_type: 'weekly' }, null, { now: SAMPLE_NOW });
+ expect(quota.error).toContain('weekly');
+ });
+
+ it('says the windows have reset when every reported window expired', () => {
+ const quota = mapCodexQuota(SAMPLE_RATE_LIMITS, null, { now: Date.parse('2026-02-01T00:00:00Z') });
+ expect(quota.limits).toHaveLength(0);
+ expect(quota.error).toContain('has since reset');
+ });
+});
+
+describe('fetchCodexQuota', () => {
+ // Codex lays sessions out as sessions/YYYY/MM/DD/rollout-<ISO>-<uuid>.jsonl.
+ const writeSession = async (codexHome, { day, name, lines }) => {
+ const dir = join(codexHome, 'sessions', ...day.split('-'));
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, `rollout-${name}.jsonl`), `${lines.join('\n')}\n`);
+ };
+
+ let codexHome;
+ beforeEach(async () => {
+ codexHome = await mkdtemp(join(tmpdir(), 'portos-codex-usage-'));
+ });
+ afterEach(async () => {
+ await rm(codexHome, { recursive: true, force: true });
+ });
+
+ const NOW = Date.parse('2026-01-01T06:00:00Z');
+ const liveWindow = (usedPercent) => ({
+ limit_id: 'codex',
+ primary: null,
+ secondary: { used_percent: usedPercent, window_minutes: 10080, resets_at: NOW / 1000 + 86400 },
+ plan_type: 'pro'
+ });
+
+ it('reports the spent meter from an older SESSION when the newest one has no windows', async () => {
+ // The reported bug end to end: the last session Codex ran only reported its
+ // window-less credits bucket, so the exhausted weekly meter recorded by the
+ // session before it went missing and the card read as "nothing to report".
+ await writeSession(codexHome, { day: '2026-01-01', name: '2026-01-01T04-00-00-aaa', lines: [codexLine(liveWindow(100), '2026-01-01T04:00:00Z')] });
+ await writeSession(codexHome, { day: '2026-01-01', name: '2026-01-01T05-00-00-bbb', lines: [codexLine(CREDITS_ONLY_RATE_LIMITS, '2026-01-01T05:00:00Z')] });
+
+ const quota = await fetchCodexQuota({ codexHome, now: NOW });
+ expect(quota.limits).toHaveLength(1);
+ expect(quota.limits[0]).toMatchObject({ key: 'week', percentUsed: 100 });
+ expect(quota.note).toContain('2026-01-01T04:00:00Z');
+ expect(quota.error).toBeUndefined();
+ });
+
+ it('explains itself when no session anywhere reports a window', async () => {
+ await writeSession(codexHome, { day: '2026-01-01', name: '2026-01-01T05-00-00-bbb', lines: [codexLine(CREDITS_ONLY_RATE_LIMITS, '2026-01-01T05:00:00Z')] });
+
+ const quota = await fetchCodexQuota({ codexHome, now: NOW });
+ expect(quota.limits).toHaveLength(0);
+ expect(quota.error).toContain('credit balance 0');
+ expect(quota.note).toContain('2026-01-01T05:00:00Z'); // the reading's age still travels
+ });
+
+ it('stops reading sessions older than the longest window once it has a fallback', async () => {
+ // Nothing that old can hold an unexpired meter, so re-reading it every poll
+ // is pure cost — this adapter has no cache to absorb it.
+ await writeSession(codexHome, { day: '2025-12-01', name: '2025-12-01T05-00-00-ccc', lines: [codexLine(liveWindow(42), '2025-12-01T05:00:00Z')] });
+ await writeSession(codexHome, { day: '2026-01-01', name: '2026-01-01T05-00-00-bbb', lines: [codexLine(CREDITS_ONLY_RATE_LIMITS, '2026-01-01T05:00:00Z')] });
+
+ const quota = await fetchCodexQuota({ codexHome, now: NOW });
+ expect(quota.limits).toHaveLength(0); // the month-old session was never opened
+ expect(quota.note).toContain('2026-01-01T05:00:00Z');
+ });
+
+ it('says to run Codex once when there are no session logs at all', async () => {
+ const quota = await fetchCodexQuota({ codexHome, now: NOW });
+ expect(quota).toMatchObject({ family: 'codex', supported: true, limits: [] });
+ expect(quota.error).toContain('No Codex session logs found');
+ });
});
describe('resolveEnabledFamilies', () => {
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index edd2a5ab81..0d8702b09d 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -149,7 +149,11 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}
// 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}` };
+ // `error` covers both a failed read and a successful one with nothing to
+ // meter (see the card contract in providerUsage.js) — either way there are no
+ // numbers to burn against, so the reason quotes the card rather than
+ // asserting a failure that may not have happened.
+ if (card.error) return { skipReason: `quota unavailable: ${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 a
// measured allowance. Burning against it would dispatch work to a backend that