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

fix: fetch live Codex subscription quota on refresh

Adam Eivyfc31caf723f5
diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.js
index 3fed83646f..075f102a69 100644
--- a/server/lib/codexAccount.js
+++ b/server/lib/codexAccount.js
@@ -203,7 +203,9 @@ const normalizeWindow = (raw) => {
const windowDurationMins = typeof raw.windowDurationMins === 'number' && Number.isFinite(raw.windowDurationMins)
? raw.windowDurationMins
: null;
- const resetsAt = trimmedString(raw.resetsAt);
+ const resetsAt = typeof raw.resetsAt === 'number' && Number.isFinite(raw.resetsAt) && Math.abs(raw.resetsAt) <= 8.64e12
+ ? new Date(raw.resetsAt * 1000).toISOString()
+ : trimmedString(raw.resetsAt);
const limitName = trimmedString(raw.limitName);
if (usedPercent === null && windowDurationMins === null && resetsAt === null) return null;
return { usedPercent, windowDurationMins, resetsAt, limitName };
diff --git a/server/lib/codexAccount.test.js b/server/lib/codexAccount.test.js
index 30045bd91e..83ed654cc9 100644
--- a/server/lib/codexAccount.test.js
+++ b/server/lib/codexAccount.test.js
@@ -77,6 +77,11 @@ describe('normalizeCodexAccount', () => {
});
describe('normalizeCodexRateLimits', () => {
+ it('normalizes Unix-second reset times from app-server', () => {
+ const resetsAt = 1800000000;
+ expect(normalizeCodexRateLimits({ rateLimits: { primary: { usedPercent: 42, resetsAt } } }).primary.resetsAt)
+ .toBe(new Date(resetsAt * 1000).toISOString());
+ });
it('reports a fetched-but-empty window as an object, not as a failed fetch', () => {
// The sentinel that matters: `null` is reserved for "could not read".
expect(normalizeCodexRateLimits({ rateLimits: {} })).toEqual({ primary: null, secondary: null, credits: null });
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 3a784385f8..8c12529dbe 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -43,7 +43,7 @@ import { enabledCloudImageModes } from './imageGen/modes.js';
* AI Provider Usage Policy: these fetches run only on user request from the
* usage page — never at server boot — and none of them consume tokens (the
* Claude `/usage` print-mode call is 0-token; the Codex adapter only reads
- * local session logs; the Antigravity/Grok adapters drive an interactive
+ * local session logs or reads account quota via app-server; the Antigravity/Grok adapters drive an interactive
* `/usage` slash command that renders synchronously, with no LLM turn).
*
* Caching: the claude adapter carries its own 60s cache + single-flight inside
@@ -260,6 +260,33 @@ 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();
+ 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 quota = await fetchCodexQuota();
+ return { ...quota, note: `Live Codex quota refresh unavailable; showing local telemetry. ${quota.note || ''}`.trim() };
+}
+
/** Exported for tests (which point `codexHome` at a fixture tree). */
export async function fetchCodexQuota({ codexHome = codexHomeDir(), now = Date.now() } = {}) {
const routingOverridden = readCodexRoutingOverride()?.overridden === true;
@@ -625,7 +652,7 @@ async function fetchClaudeQuota({ wait = WAIT.CACHED } = {}) {
*/
const FAMILY_FETCHERS = {
claude: fetchClaudeQuota,
- codex: () => fetchCodexQuota(),
+ codex: fetchCurrentCodexQuota,
agy: makeTuiUsageFetcher({ id: 'agy', binary: 'agy', slashCommand: '/usage', label: 'Antigravity', parse: parseAgyUsage, name: 'Antigravity CLI', readyMarker: /Weekly Limit(?:\s+Remaining)?|Five Hour Limit(?:\s+Remaining)?|Models & Quota/i }),
grok: makeTuiUsageFetcher({ id: 'grok', binary: 'grok', slashCommand: '/usage show', label: 'Grok', parse: parseGrokUsage, name: 'Grok Build CLI', readyMarker: /(Weekly|Monthly) limit/i })
};
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 12613d1acb..93bb0da121 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -51,6 +51,9 @@ vi.mock('./usageFleetBilling.js', () => ({
getApiBilledInstanceIds: vi.fn().mockResolvedValue([])
}));
+vi.mock('./codexAppServer.js', () => ({ getCodexAccountReadiness: vi.fn() }));
+import { getCodexAccountReadiness } from './codexAppServer.js';
+
import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -743,3 +746,42 @@ describe('TUI usage fetchers (via getProviderQuotas)', () => {
vi.useRealTimers();
});
});
+
+describe('Codex explicit quota refresh', () => {
+ let home;
+ beforeEach(async () => {
+ home = await mkdtemp(join(tmpdir(), 'portos-codex-refresh-'));
+ vi.stubEnv('CODEX_HOME', home);
+ getAllProviders.mockResolvedValue({ providers: [{ id: 'codex', enabled: true, type: 'cli', command: 'codex' }] });
+ getCodexAccountReadiness.mockReset();
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(home, { recursive: true, force: true });
+ });
+
+ it('reads live quota on refresh and publishes only the quota projection', async () => {
+ getCodexAccountReadiness.mockResolvedValue({
+ checkedAt: Date.now(), account: { planType: 'pro', email: '[email protected]' },
+ rateLimits: { primary: { usedPercent: 27, windowDurationMins: 300, resetsAt: new Date(Date.now() + 3600000).toISOString() }, secondary: null },
+ });
+ const [card] = await getProviderQuotas({ family: 'codex', wait: 'fresh' });
+ expect(getCodexAccountReadiness).toHaveBeenCalledWith({ fresh: true });
+ expect(card).toMatchObject({ approximate: false, plan: 'pro', limits: [{ percentUsed: 27, periodHours: 5 }] });
+ expect(JSON.stringify(card)).not.toContain('[email protected]');
+ expect(card.note).toContain('Live Codex account quota');
+ });
+
+ it('keeps a successful empty quota empty and explains a failed live refresh', async () => {
+ getCodexAccountReadiness.mockResolvedValue({ checkedAt: Date.now(), rateLimits: { primary: null, secondary: null } });
+ const [empty] = await getProviderQuotas({ family: 'codex', wait: 'fresh' });
+ expect(empty).toMatchObject({ approximate: false, limits: [] });
+ getCodexAccountReadiness.mockResolvedValue({ rateLimits: null });
+ const [fallback] = await getProviderQuotas({ family: 'codex', wait: 'fresh' });
+ expect(fallback.note).toContain('Live Codex quota refresh unavailable');
+ getCodexAccountReadiness.mockClear();
+ await getProviderQuotas({ family: 'codex', wait: 'never' });
+ expect(getCodexAccountReadiness).not.toHaveBeenCalled();
+ });
+});