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
stop the Codex usage card regressing to stale rollout-log telemetry
[._.]/ Adam Eivy93d2f04665bf
diff --git a/server/lib/staleWhileRevalidate.js b/server/lib/staleWhileRevalidate.jsindex 8cf1643f8e..69c40c7288 100644--- a/server/lib/staleWhileRevalidate.js+++ b/server/lib/staleWhileRevalidate.js@@ -125,11 +125,26 @@ export function createStaleWhileRevalidate({return settled.value;}+ /**+ * The last successful reading for `key`, or `undefined` — without producing+ * one, and WITHOUT applying the TTL.+ *+ * For a caller that has a cheaper second source and wants to pick between+ * them by the readings' own `fetchedAt` rather than by this cache's clock: an+ * expensive reading taken an hour ago can still be the more current of the+ * two, and `read` would either hide it (TTL lapsed → produce) or pay for a+ * spawn to re-confirm it. Since values carry their own age, the caller can+ * judge staleness itself; what it cannot do is afford the production.+ */+ function peek(key) {+ return entries.get(key)?.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 };+ return { read, peek, clear };}diff --git a/server/lib/staleWhileRevalidate.test.js b/server/lib/staleWhileRevalidate.test.jsindex d83d5b6ba4..165a803533 100644--- a/server/lib/staleWhileRevalidate.test.js+++ b/server/lib/staleWhileRevalidate.test.js@@ -126,6 +126,25 @@ describe('createStaleWhileRevalidate', () => {expect(await cache.read('k', produce)).toBe('full'); // …and revalidated});+ // For a caller that has a second, cheap source and picks between them by the+ // readings' own `fetchedAt`: the expensive reading is still the answer long+ // after the TTL lapses, and paying for a respawn to re-confirm it is the cost+ // `read` cannot avoid.+ it('peeks the last reading without producing one, and without applying the TTL', async () => {+ vi.useFakeTimers();+ const cache = createStaleWhileRevalidate({ ttlMs: TTL });+ const produce = vi.fn().mockResolvedValue('reading');+ expect(cache.peek('k')).toBeUndefined(); // cold: nothing to hand back++ await cache.read('k', produce);+ vi.advanceTimersByTime(TTL * 10);+ expect(cache.peek('k')).toBe('reading');+ expect(produce).toHaveBeenCalledTimes(1);++ cache.clear('k');+ expect(cache.peek('k')).toBeUndefined();+ });+it('keys entries independently and clears them', async () => {const cache = createStaleWhileRevalidate({ ttlMs: TTL });await cache.read('a', () => Promise.resolve(1));diff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.jsindex 712512086b..97043a932f 100644--- a/server/services/peerUsage.test.js+++ b/server/services/peerUsage.test.js@@ -465,6 +465,20 @@ describe('federated subscription-quota readings', () => {expect((await recordLocalQuotaCards([quotaCard({ limits: [] })])).changed).toBe(true);});+ // Codex cards are stamped with the TELEMETRY that produced them, not the+ // clock they were read at, so a rollout-log tail can arrive AFTER a live+ // account reading while describing an older moment. Letting it through would+ // publish a reading this machine already knows is superseded.+ it('keeps the newer reading when an older card for the same family arrives after it', async () => {+ const spent = [{ key: 'week', label: 'Current week', percentUsed: 100, percentRemaining: 0, resetsAt: null, timezone: null }];+ const live = quotaCard({ family: 'codex', label: 'Codex', fetchedAt: '2026-08-31T12:00:00.000Z', limits: spent });+ const stale = quotaCard({ family: 'codex', label: 'Codex', fetchedAt: '2026-08-29T09:00:00.000Z' });+ expect((await recordLocalQuotaCards([live])).changed).toBe(true);+ expect((await recordLocalQuotaCards([stale])).changed).toBe(false);+ const { quotas } = await readLocalQuotaCards();+ expect(quotas.find((q) => q.family === 'codex').limits[0].percentUsed).toBe(100);+ });+it('merges a narrowed read instead of retiring the families it skipped', async () => {await recordLocalQuotaCards([quotaCard(), quotaCard({ family: 'codex', label: 'Codex' })]);await recordLocalQuotaCards([quotaCard({ activity: [{ period: 'Last 24h', requests: 99, sessions: 3, notes: [] }] })]);diff --git a/server/services/providerQuotaShare.js b/server/services/providerQuotaShare.jsindex cf8cf05a62..4bcb2d7003 100644--- a/server/services/providerQuotaShare.js+++ b/server/services/providerQuotaShare.js@@ -19,6 +19,7 @@ import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import { createMutex } from '../lib/asyncMutex.js';import { sanitizeQuotaCards, latestFetchedAt } from '../lib/fleetQuotas.js';+import { parseTsMs } from '../lib/lwwTimestamp.js';export const PROVIDER_QUOTAS_FILE = join(PATHS.data, 'provider-quotas.json');@@ -43,6 +44,18 @@ export async function readLocalQuotaCards() {*/const claimOf = ({ fetchedAt, ...rest }) => JSON.stringify(rest);+/**+ * Is `card` a reading taken BEFORE `incumbent`?+ *+ * Unparseable on either side is "can't tell", which answers false — the caller+ * then falls through to its normal last-write-wins, exactly as before.+ */+function isOlderReading(card, incumbent) {+ const cardMs = parseTsMs(card?.fetchedAt);+ const incumbentMs = parseTsMs(incumbent?.fetchedAt);+ return cardMs !== null && incumbentMs !== null && cardMs < incumbentMs;+}+/*** Merge a batch of freshly-read cards into the store, keyed by family.*@@ -65,6 +78,14 @@ export async function recordLocalQuotaCards(cards) {for (const card of incoming) {const incumbent = byFamily.get(card.family);if (incumbent && claimOf(incumbent) === claimOf(card)) continue;+ // A reading taken EARLIER than the one on file is not an update. Adapters+ // differ in how stale their source can be — a Codex card derived from+ // rollout-log telemetry is stamped with the turn that produced it and can+ // be days old, while the same install's live account reading is minutes+ // old — so an older card arriving second must not retire a newer one.+ // Federation merges these by `fetchedAt`, so letting it through would+ // hand every peer a reading this machine already knows is superseded.+ if (incumbent && isOlderReading(card, incumbent)) continue;byFamily.set(card.family, card);changed = true;}diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 8c12529dbe..ba32b22879 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -48,7 +48,8 @@ import { enabledCloudImageModes } from './imageGen/modes.js';** Caching: the claude adapter carries its own 60s cache + single-flight inside* claudeCodeUsage.js; the codex adapter is a bounded local-file tail read (1-2- * leaf dirs on a typical layout); the Antigravity/Grok adapters carry a 5-min+ * leaf dirs on a typical layout) plus a retained copy of the last LIVE account+ * reading, which a passive read serves whenever it is the newer of the two; the Antigravity/Grok adapters carry a 5-min* cache + single-flight here (`cachedScrape`) because each TUI scrape costs* ~10-15s (spawn + sign-in + render), too slow to repeat per page poll.*/@@ -215,10 +216,23 @@ export function mapCodexQuota(rateLimits, timestamp, {routingOverridden ? CODEX_ROUTING_CAVEAT : null,].filter(Boolean).join(' '),...(limits.length ? {} : { error: codexNoWindowsMessage(rateLimits, now) }),- fetchedAt: new Date().toISOString()+ // The TELEMETRY's own timestamp, not the clock we read it at. Codex only+ // emits `rate_limits` while a turn is running, so this reading can be days+ // old — and `fetchedAt` is what every consumer ages it by: the federated+ // merge picks the freshest reading per limit key, and the quota store keeps+ // the newest card per family. Stamping "now" on a stale log tail made it+ // win both, so a machine that had not run Codex since Tuesday kept+ // overwriting a peer's (and this machine's own) current account reading.+ fetchedAt: telemetryIso(timestamp) || new Date().toISOString()};}+/** An ISO string for a telemetry timestamp, or null when it isn't a usable date. */+function telemetryIso(timestamp) {+ const ms = timestamp == null ? NaN : Date.parse(timestamp);+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;+}+/*** Newest-first rollout logs under <codexHome>/sessions, as* `{ path, dayStartMs }`. Codex lays sessions out as@@ -260,31 +274,90 @@ async function listCodexRolloutFiles(codexHome) {return files;}-// Passive reads stay local. A fresh request queries quota without starting a turn.-async function fetchCurrentCodexQuota({ wait }) {- if (wait !== WAIT.FRESH) return fetchCodexQuota();+/**+ * The last live account reading, kept so a passive page load can serve it.+ *+ * `codexAppServer` caches readiness for 15s — long enough to coalesce one+ * render, far too short to survive navigating away and back, which is exactly+ * when the user sees the number regress. A live reading is retained here until+ * something more current replaces it, and `peek` hands it back without ever+ * spawning the app-server on a passive read.+ */+const codexLiveCache = createStaleWhileRevalidate({+ ttlMs: 60 * 1000,+ isComplete: (card) => Boolean(card?.limits?.length),+});+const CODEX_LIVE_KEY = 'codex:account';++/** Test-only: forget the retained live Codex account reading. */+export function __resetCodexLiveQuotaCache() {+ codexLiveCache.clear();+}++/**+ * Query the signed-in ChatGPT account's quota through the Codex app-server.+ * Starts no turn and spends no tokens. Throws when the account can't answer, so+ * the stale-while-revalidate cache backs off instead of respawning per request.+ */+async function readLiveCodexQuota() {const { getCodexAccountReadiness } = await import('./codexAppServer.js');- const readiness = await getCodexAccountReadiness({ fresh: true }).catch(() => null);- if (readiness?.rateLimits != null) {- const window = (value) => value && ({- used_percent: value.usedPercent,- window_minutes: value.windowDurationMins,- resets_at: value.resetsAt ? Date.parse(value.resetsAt) / 1000 : null,- });- const quota = mapCodexQuota({- primary: window(readiness.rateLimits.primary),- secondary: window(readiness.rateLimits.secondary),- plan_type: readiness.account?.planType,- }, null);- return {- ...quota,- approximate: false,- fetchedAt: new Date(readiness.checkedAt).toISOString(),- note: ['Live Codex account quota.', readCodexRoutingOverride()?.overridden === true ? CODEX_ROUTING_CAVEAT : null].filter(Boolean).join(' '),- };+ const readiness = await getCodexAccountReadiness({ fresh: true });+ if (readiness?.rateLimits == null) throw new Error('Codex reported no account rate limits');+ const window = (value) => value && ({+ used_percent: value.usedPercent,+ window_minutes: value.windowDurationMins,+ resets_at: value.resetsAt ? Date.parse(value.resetsAt) / 1000 : null,+ });+ const quota = mapCodexQuota({+ primary: window(readiness.rateLimits.primary),+ secondary: window(readiness.rateLimits.secondary),+ plan_type: readiness.account?.planType,+ }, null);+ const checkedAt = Number.isFinite(readiness.checkedAt) ? readiness.checkedAt : Date.now();+ return {+ ...quota,+ approximate: false,+ fetchedAt: new Date(checkedAt).toISOString(),+ note: ['Live Codex account quota.', readCodexRoutingOverride()?.overridden === true ? CODEX_ROUTING_CAVEAT : null].filter(Boolean).join(' '),+ };+}++/**+ * Pure: does this card still describe the CURRENT allowance?+ *+ * 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 card with no meters at all has nothing to have expired, so it+ * never outranks a reading that does.+ */+const codexCardUnexpired = (card, now) =>+ (card?.limits || []).some((limit) => !limit.resetsAt || Date.parse(limit.resetsAt) > now);++/**+ * Passive reads stay local; a fresh request queries the account without+ * starting a turn.+ *+ * The two sources disagree by design: the app-server knows the account's+ * 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 a retained live reading+ * wins whenever it is genuinely the newer of the two.+ */+async function fetchCurrentCodexQuota({ wait = WAIT.CACHED } = {}) {+ if (wait === WAIT.FRESH) {+ const live = await codexLiveCache.read(CODEX_LIVE_KEY, readLiveCodexQuota, { wait }).catch(() => null);+ if (live) return live;+ const quota = await fetchCodexQuota();+ return { ...quota, note: `Live Codex quota refresh unavailable; showing local telemetry. ${quota.note || ''}`.trim() };}- const quota = await fetchCodexQuota();- return { ...quota, note: `Live Codex quota refresh unavailable; showing local telemetry. ${quota.note || ''}`.trim() };+ const now = Date.now();+ const live = codexLiveCache.peek(CODEX_LIVE_KEY);+ const quota = await fetchCodexQuota({ now });+ if (!live || !codexCardUnexpired(live, now)) return quota;+ const liveMs = Date.parse(live.fetchedAt);+ const logMs = Date.parse(quota.fetchedAt);+ return Number.isFinite(liveMs) && (!Number.isFinite(logMs) || liveMs >= logMs) ? live : quota;}/** Exported for tests (which point `codexHome` at a fixture tree). */diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsindex 93bb0da121..ea48743326 100644--- a/server/services/providerUsage.test.js+++ b/server/services/providerUsage.test.js@@ -60,7 +60,7 @@ import { join } from 'path';import {parseCodexRateLimits, mapCodexQuota, fetchCodexQuota, resolveEnabledFamilies, getProviderQuotas,- parseAgyUsage, parseGrokUsage, agyRefreshToIso, __resetUsageScrapeCache,+ parseAgyUsage, parseGrokUsage, agyRefreshToIso, __resetUsageScrapeCache, __resetCodexLiveQuotaCache,} from './providerUsage.js';import { getAllProviders } from './providers.js';import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';@@ -785,3 +785,118 @@ describe('Codex explicit quota refresh', () => {expect(getCodexAccountReadiness).not.toHaveBeenCalled();});});++// The bug this covers: the usage page showed the true (exhausted) Codex quota+// right after an explicit Refresh, then snapped back to a stale percentage as+// soon as the user navigated away and returned. Passive reads served the+// rollout-log tail unconditionally, and that tail only knows what the last+// Codex TURN was told — which can be days old.+describe('Codex quota freshness across a passive re-read', () => {+ let home;+ let staleTs;+ // A turn that reported plenty of headroom, recorded two days before "now".+ const staleTurn = (day, timestamp) => ({+ day,+ name: timestamp,+ lines: [JSON.stringify({+ timestamp,+ payload: {+ rate_limits: {+ plan_type: 'pro',+ primary: { used_percent: 7, window_minutes: 300, resets_at: Math.floor(Date.now() / 1000) + 3600 },+ secondary: null,+ },+ },+ })],+ });++ 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`);+ };++ const isoDaysAgo = (days) => new Date(Date.now() - days * 86400000).toISOString();+ const dayOf = (iso) => iso.slice(0, 10);++ beforeEach(async () => {+ home = await mkdtemp(join(tmpdir(), 'portos-codex-freshness-'));+ vi.stubEnv('CODEX_HOME', home);+ getAllProviders.mockResolvedValue({ providers: [{ id: 'codex', enabled: true, type: 'cli', command: 'codex' }] });+ getCodexAccountReadiness.mockReset();+ __resetCodexLiveQuotaCache();+ staleTs = isoDaysAgo(2);+ await writeSession(home, staleTurn(dayOf(staleTs), staleTs));+ });++ afterEach(async () => {+ __resetCodexLiveQuotaCache();+ vi.unstubAllEnvs();+ await rm(home, { recursive: true, force: true });+ });++ it('stamps a log-derived card with the TELEMETRY timestamp, not the read clock', async () => {+ const [card] = await getProviderQuotas({ family: 'codex', wait: 'never' });+ expect(card.limits).toHaveLength(1);+ // Stamping "now" here is what let a two-day-old reading outrank both a+ // peer's current one and this machine's own live account reading.+ expect(Date.parse(card.fetchedAt)).toBe(Date.parse(staleTs));+ });++ it('keeps serving the live account reading after a refresh, instead of regressing to the log tail', async () => {+ getCodexAccountReadiness.mockResolvedValue({+ checkedAt: Date.now(),+ account: { planType: 'pro' },+ rateLimits: {+ primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: new Date(Date.now() + 3600000).toISOString() },+ secondary: null,+ },+ });+ const [refreshed] = await getProviderQuotas({ family: 'codex', wait: 'fresh' });+ expect(refreshed.limits[0].percentUsed).toBe(100);++ // Navigating back re-reads passively. The app-server must not be spawned+ // again, and the two-day-old "7% used" log tail must not win.+ getCodexAccountReadiness.mockClear();+ const [again] = await getProviderQuotas({ family: 'codex', wait: 'never' });+ expect(getCodexAccountReadiness).not.toHaveBeenCalled();+ expect(again.limits[0].percentUsed).toBe(100);+ expect(again.note).toContain('Live Codex account quota');+ });++ it('yields to the rollout log once a Codex turn has reported something newer', 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' });++ const ts = new Date(Date.now() - 60_000).toISOString();+ await writeSession(home, staleTurn(dayOf(ts), ts));+ const [again] = await getProviderQuotas({ family: 'codex', wait: 'never' });+ expect(again.limits[0].percentUsed).toBe(7); // the turn happened after the account read+ });++ it('drops a retained live reading whose metered window has 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: null,+ },+ });+ await getProviderQuotas({ family: 'codex', wait: 'fresh' });+ vi.setSystemTime(new Date(Date.now() + 60_000));+ try {+ const [again] = await getProviderQuotas({ family: 'codex', wait: 'never' });+ expect(again.limits[0]?.percentUsed).toBe(7); // the spent window rolled over+ } finally {+ vi.useRealTimers();+ }+ });+});