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

rank the two Codex quota sources by meters, not by clock

[._.]/ Adam Eivyec37854cf7ae
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 0eadd8a200..adc6619fcb 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -328,16 +328,17 @@ async function readLiveCodexQuota() {
}
/**
- * Pure: does this card still describe the CURRENT allowance?
+ * Pure: the meters in a card that have NOT rolled over as of `now`.
*
- * A retained reading whose every metered window has since reset is describing a
- * spent allowance, the same way `codexWindowExpired` rules out a rolled-over
- * log entry. A window whose reset time can't be resolved hasn't been shown to
- * have passed, so it counts as live; a card with no meters at all has nothing
- * to have expired, and so never outranks a reading that does.
+ * A retained reading ages meter-by-meter, not all at once — a card holding a
+ * spent 5h window beside a live weekly one is half stale, and serving it whole
+ * shows an exhausted meter whose reset time has already passed. Same rule
+ * `codexWindowExpired` applies to a rolled-over log entry, applied at serve
+ * time because the card outlives the read that produced it. A window whose
+ * reset can't be resolved hasn't been shown to have passed, so it counts live.
*/
-const codexCardUnexpired = (card, now) =>
- (card?.limits || []).some((limit) => {
+const unexpiredLimits = (card, now) =>
+ (card?.limits || []).filter((limit) => {
const { epochMs } = normalizeResetAt(limit, { now });
return epochMs === null || epochMs > now;
});
@@ -350,8 +351,15 @@ const codexCardUnexpired = (card, now) =>
* current state, while the rollout logs only know what the last Codex TURN was
* told — which may be days stale. Serving the log tail unconditionally on
* passive reads is what made the card snap back to an old percentage as soon as
- * the user navigated away from an explicit Refresh, so the retained live
- * reading holds unless the log is genuinely fresher.
+ * the user navigated away from an explicit Refresh.
+ *
+ * METERS decide, not clocks. A card carrying no meters is the absence of a
+ * reading, not a newer one: `fetchCodexQuota` stamps its own clock on a
+ * synthetic "no session logs" card and on window-less telemetry, so ranking the
+ * two cards by `fetchedAt` alone let an empty card retire a live account
+ * reading — an install that runs Codex only through PortOS (no rollout logs at
+ * all) lost its quota meters on the very next poll. Only when both sides
+ * actually have meters is the timestamp the question.
*/
async function fetchCurrentCodexQuota({ wait = WAIT.CACHED } = {}) {
if (wait === WAIT.FRESH) {
@@ -361,9 +369,13 @@ async function fetchCurrentCodexQuota({ wait = WAIT.CACHED } = {}) {
return { ...quota, note: `Live Codex quota refresh unavailable; showing local telemetry. ${quota.note || ''}`.trim() };
}
const now = Date.now();
- const live = retainedLiveCodexCard;
const quota = await fetchCodexQuota({ now });
- if (!live || !codexCardUnexpired(live, now)) return quota;
+ // Pruned at serve time and never written back: the retained card stays the
+ // canonical reading, so a later read prunes further rather than compounding.
+ const liveLimits = unexpiredLimits(retainedLiveCodexCard, now);
+ if (!liveLimits.length) return quota;
+ const live = { ...retainedLiveCodexCard, limits: liveLimits };
+ if (!quota.limits.length) return live;
return compareNewerWins(quota.fetchedAt, live.fetchedAt) ? quota : live;
}
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index ea48743326..b07ef51588 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -899,4 +899,74 @@ describe('Codex quota freshness across a passive re-read', () => {
vi.useRealTimers();
}
});
+
+ // Reported by the agy reviewer: the picker ranked two whole cards by
+ // `fetchedAt`, but a card carrying no meters is the ABSENCE of a reading —
+ // and fetchCodexQuota stamps its own clock on the synthetic "no session logs"
+ // card, so it always looked newer.
+ it('keeps the live reading when the install has no rollout logs at all', async () => {
+ await rm(join(home, 'sessions'), { recursive: true, force: true });
+ getCodexAccountReadiness.mockResolvedValue({
+ checkedAt: Date.now() - 3600_000,
+ account: { planType: 'pro' },
+ rateLimits: {
+ primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: new Date(Date.now() + 3600000).toISOString() },
+ secondary: null,
+ },
+ });
+ await getProviderQuotas({ family: 'codex', wait: 'fresh' });
+
+ const [again] = await getProviderQuotas({ family: 'codex', wait: 'never' });
+ expect(again.limits[0].percentUsed).toBe(100);
+ expect(again.error).toBeUndefined();
+ });
+
+ // Same root cause from the other side: a turn that reported only a spent
+ // credit balance produces window-less telemetry with a NEWER timestamp.
+ it('keeps the live reading when newer telemetry carries no windows', async () => {
+ getCodexAccountReadiness.mockResolvedValue({
+ checkedAt: Date.now() - 3600_000,
+ account: { planType: 'pro' },
+ rateLimits: {
+ primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: new Date(Date.now() + 3600000).toISOString() },
+ secondary: null,
+ },
+ });
+ await getProviderQuotas({ family: 'codex', wait: 'fresh' });
+
+ await rm(join(home, 'sessions'), { recursive: true, force: true });
+ const ts = new Date(Date.now() - 60_000).toISOString();
+ await writeSession(home, {
+ day: dayOf(ts),
+ name: ts,
+ lines: [JSON.stringify({ timestamp: ts, payload: { rate_limits: { limit_id: 'premium', primary: null, secondary: null, credits: { unlimited: false, has_credits: false, balance: 0 } } } })],
+ });
+ const [again] = await getProviderQuotas({ family: 'codex', wait: 'never' });
+ expect(again.limits[0].percentUsed).toBe(100);
+ });
+
+ // A retained card ages meter-by-meter: one spent window can roll over while
+ // another is still live, and serving the card whole shows a 100% meter whose
+ // reset time has already passed.
+ it('prunes only the retained meters that have since reset', async () => {
+ getCodexAccountReadiness.mockResolvedValue({
+ checkedAt: Date.now(),
+ account: { planType: 'pro' },
+ rateLimits: {
+ primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: new Date(Date.now() + 1000).toISOString() },
+ secondary: { usedPercent: 40, windowDurationMins: 10080, resetsAt: new Date(Date.now() + 86400000).toISOString() },
+ },
+ });
+ const [fresh] = await getProviderQuotas({ family: 'codex', wait: 'fresh' });
+ expect(fresh.limits.map((l) => l.key)).toEqual(['session', 'week']);
+
+ vi.setSystemTime(new Date(Date.now() + 60_000));
+ try {
+ const [again] = await getProviderQuotas({ family: 'codex', wait: 'never' });
+ expect(again.limits.map((l) => l.key)).toEqual(['week']); // the 5h window rolled over
+ expect(again.limits[0].percentUsed).toBe(40);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});