diff --git a/.ai/contexts/ipc-bridge.md b/.ai/contexts/ipc-bridge.md
index 4214bff6b..b73ee13eb 100644
--- a/.ai/contexts/ipc-bridge.md
+++ b/.ai/contexts/ipc-bridge.md
@@ -516,6 +516,56 @@ uninitialised submodule refuses preview/deletion before force can hide its files
| `get-stats-from-db` | `buildStatsFromDb()`: `{dailyActivity, dailyModelTokens, modelUsage, totalMessages, totalSessions, totalToolCalls, totalTokens, firstSessionDate, lastComputedDate}` from `session_metrics` — heatmap source since PR #7 |
| `refresh-stats` | `{stats, usage}` — combined; calls `buildStatsFromDb` (using `getDailyMetrics`) + `fetchAndTransformUsage` |
| `get-usage` | rate-limits payload from Claude `/usage` |
+| `get-codex-usage` | `{limits: [...]}` containing renderable Codex rows only, or `{}` when disabled or unavailable |
+
+#### Opt-in Codex usage (#1139)
+
+Settings → Sessions → CLI Agents has **Show Codex usage**, defaulting to false
+in `SETTING_DEFAULTS`. Saving applies it immediately. Only the global setting
+with the boolean value `true` authorizes a read or request; project settings and
+renderer IPC arguments cannot enable it.
+
+`src/main/usage/codex-usage.js` reads `CODEX_HOME/auth.json`, falling back to
+`~/.codex/auth.json`, only after that check. It sends the OAuth access token and
+optional account id only to `https://chatgpt.com/backend-api/wham/usage`.
+Redirects are refused. No credentials, raw response, account metadata or error
+messages cross IPC; failures return `{}` and are never logged. This endpoint is
+undocumented and can change; unavailable usage simply disappears.
+
+A shared in-flight request covers status bar and Stats callers. An AbortController
+bounds the request and body read to ten seconds. Missing credentials, malformed
+responses, HTTP failures and timeouts back off for 30, 60, 120, 240 then 300
+seconds; HTTP 429 also honors Retry-After (seconds or HTTP date), capped at one
+hour. Success resets backoff. A saved setting change cancels the request and
+invalidates its generation; changing the toggle does not bypass backoff.
+The Settings panel applies usage only when the toggle changes, including saves
+deferred by project deletion. Disabling removes Codex rows without fetching
+either provider; enabling refreshes only Codex. The status bar tracks Claude
+and Codex requests separately so neither provider replaces the other's rows.
+Disabling invalidates pending Codex renders and keeps status-bar polling from
+fetching Codex while the saved main-process setting may still be on. Opening
+Stats also honors that renderer state. A missing Codex toggle does not apply
+an undefined value to the renderer. After a deferred enabling write succeeds,
+`flushDeferredProjectDeletionWrites` calls `refreshCodexUsage` for both surfaces
+using the current renderer state, so a newer turn-off cannot be undone. Another
+deferral or a failed write does not trigger that refresh.
+`replaceQuotaRows` removes non-row children from the shipped gauge markup before
+updating either provider; placeholders cannot keep an otherwise empty gauge visible.
+Status bar polling remains every five minutes; Stats has its own refresh button.
+
+Codex rows reuse `buildQuotaBar` and `buildUsageSection`; Claude keeps its own
+rows and error handling. Reset text shares `formatResetTime` from `claude-auth.js`.
+Model-specific status-bar labels include the limit name. Over-limit percentages
+remain visible; bar widths clamp to 100%.
+The adapted endpoint contract, duration labels and per-model filtering credit
+**Ali Basiri**, `doctly/switchboard`, commits `ee656523` and `3ca3d19d`.
+The fork adds explicit consent, quiet failure, timeout, backoff, redirect refusal
+and stale-result protection instead of porting upstream's raw error payloads.
+
+Tests use disposable auth files and stubbed fetch; they never contact the
+endpoint. The IPC test evaluates only the relevant extracted registration and
+save handler, without importing Electron. Live endpoint compatibility and the
+Electron bridge remain integration/CI verification boundaries.
### Search
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a373d9f3c..938885ed9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,9 @@ What changes for you in each release of Switchboard. How to write an entry: [doc
## Unreleased
+### New
+- Settings → Sessions → CLI Agents offers **Show Codex usage**, off by default. Turn it on to show your Codex limits in the status bar and Stats; usage hides quietly when unavailable. (#1139)
+
### Changed
- After a restart, Switchboard re-reads only Claude Code transcripts changed since the previous run. Codex history is still re-read in full. (#1144)
- Settings → Archived groups projects by host, shows their paths and archive dates, and filters by name, path or host. Restore one or several projects with Undo, or delete an archived project through the existing preview without restoring it first. For local worktree entries, Delete project explains how to delete the worktree or its repository. (#863)
diff --git a/claude-auth.js b/claude-auth.js
index 7074c6548..ffe90f017 100644
--- a/claude-auth.js
+++ b/claude-auth.js
@@ -199,4 +199,4 @@ async function fetchAndTransformUsage() {
}
}
-module.exports = { getOAuthToken, fetchUsage, fetchAndTransformUsage, getConfigDir };
+module.exports = { getOAuthToken, fetchUsage, fetchAndTransformUsage, getConfigDir, formatResetTime };
diff --git a/docs/activity-stats.md b/docs/activity-stats.md
index 84184ae03..f7b2be5ae 100644
--- a/docs/activity-stats.md
+++ b/docs/activity-stats.md
@@ -10,6 +10,10 @@ transcript. It is computed when the tab is opened.
Anthropic's usage endpoint with the CLI's OAuth credentials (the macOS
Keychain, or `~/.claude/.credentials.json`). **Refresh usage** fetches it
again. The same figures are the gauges in the [status bar](notifications.md#status-bar).
+- **Codex Rate Limits**: enable **Show Codex usage** in
+ [Settings → Sessions → CLI Agents](settings.md#cli-agents-and-codex) to show
+ Codex limits here and in the status bar. This is off by default and has its
+ own refresh button; failures hide the Codex section without affecting Claude.
- **Cards**: Total Sessions, Total Messages, Total Tokens, Tool Calls, Current
Streak and Longest Streak (in days), and one token count per model.
- **Last 30 days**: a bar per day; hovering one shows its tokens, messages and
diff --git a/docs/notifications.md b/docs/notifications.md
index f25c1aeb6..5ba6c9ded 100644
--- a/docs/notifications.md
+++ b/docs/notifications.md
@@ -93,3 +93,8 @@ in its tooltip, when it resets. They are fetched every 5 minutes from
Anthropic's usage endpoint with the CLI's own OAuth credentials (the macOS
Keychain, or `~/.claude/.credentials.json`), and are hidden when none are
available. Clicking them opens the [Stats](activity-stats.md) tab.
+
+Enable **Show Codex usage** in Settings → Sessions → CLI Agents to add Codex
+gauges alongside Claude, including named model limits. It is off by default;
+unavailable Codex usage hides quietly. See [Settings](settings.md#cli-agents-and-codex)
+for the credentials and endpoint it uses.
diff --git a/docs/settings.md b/docs/settings.md
index 73f72e9ed..9db6f3a30 100644
--- a/docs/settings.md
+++ b/docs/settings.md
@@ -93,6 +93,13 @@ A saved `chrome` setting is read as the matching Browser choice: `true` selects
The existing CLI switches and Codex sandbox, approval, model and reasoning-effort
controls are grouped here. See [Launching sessions](launching-sessions.md).
+**Show Codex usage** (`showCodexUsage`, off by default) displays Codex rate
+limits in the status bar and Stats. When enabled, it reads `CODEX_HOME/auth.json`
+(or `~/.codex/auth.json`) and calls `chatgpt.com` with the Codex login token
+and, when present, the account id in the `chatgpt-account-id` header.
+Unavailable credentials, request failures or unsupported responses hide the
+Codex gauges quietly. Saving a changed toggle applies it immediately.
+
#### Sidebar list
| Setting | Key | Default | Effect |
diff --git a/eslint.config.js b/eslint.config.js
index 97011c0cf..df20e89fb 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -24,6 +24,7 @@ const ACTIVITY_CLASS_MESSAGE = 'Only public/session-activity-dom.js may write .c
// public/sidebar.js (and equivalents). Kept readonly so reassignment
// from another file gets flagged.
const rendererCrossFileGlobals = {
+ codexQuotaEnabled: 'readonly',
projectDeletionRestoreTargets: 'readonly',
projectDeletionKey: 'readonly',
paintProjectDeletionBusy: 'readonly',
diff --git a/main.js b/main.js
index a8f7f037e..379dfd1f8 100644
--- a/main.js
+++ b/main.js
@@ -1556,6 +1556,11 @@ ipcMain.handle('refresh-stats', async () => {
});
// --- IPC: get-usage (lightweight, API-only, no PTY) ---
+const codexUsage = require('./src/main/usage/codex-usage').createCodexUsage({
+ isEnabled: () => (getSetting('global')?.showCodexUsage ?? SETTING_DEFAULTS.showCodexUsage) === true,
+});
+ipcMain.handle('get-codex-usage', () => codexUsage.getUsage());
+
ipcMain.handle('get-usage', async () => {
try {
return await fetchAndTransformUsage() || {};
@@ -1792,8 +1797,10 @@ ipcMain.handle('get-settings-by-prefix', (_event, prefix) => {
ipcMain.handle('set-setting', async (_event, key, value) => {
const disabledBefore = key === 'global' ? JSON.stringify(getSetting('global')?.disabledHarnesses || []) : null;
+ const usageBefore = key === 'global' ? getSetting('global')?.showCodexUsage : undefined;
await setSetting(key, value);
if (key === 'global') {
+ if (value?.showCodexUsage !== usageBefore) codexUsage.settingsChanged();
applyUpdateChannel();
// see .ai/contexts/cli-harnesses.md ("Picker, toggles and settings")
if (JSON.stringify(value?.disabledHarnesses || []) !== disabledBefore) {
diff --git a/preload.js b/preload.js
index 9cc64c1a8..bb77cef6e 100644
--- a/preload.js
+++ b/preload.js
@@ -5,6 +5,7 @@ contextBridge.exposeInMainWorld('api', {
getStatsFromDb: () => ipcRenderer.invoke('get-stats-from-db'),
refreshStats: () => ipcRenderer.invoke('refresh-stats'),
getUsage: () => ipcRenderer.invoke('get-usage'),
+ getCodexUsage: () => ipcRenderer.invoke('get-codex-usage'),
getMemories: () => ipcRenderer.invoke('get-memories'),
listSchedules: () => ipcRenderer.invoke('list-schedules'),
setScheduleEnabled: (filePath, enabled) => ipcRenderer.invoke('set-schedule-enabled', filePath, enabled),
diff --git a/public/app.js b/public/app.js
index c89630ae0..288d3db4f 100644
--- a/public/app.js
+++ b/public/app.js
@@ -3432,10 +3432,14 @@ window.api.onUpdaterEvent(updaterHandler);
// weekly one is the one actually running out. Rows come from the API
// self-describing, so a newly launched model gets a bar without a code change.
const quotaGaugeEl = document.getElementById('status-bar-quota');
+let quotaRequest = 0;
+let codexQuotaRequest = 0;
+let codexQuotaEnabled = true;
// Full labels ("Week (all models)") are too long for a status bar; the tooltip
// carries them in full.
function shortQuotaLabel(row) {
+ if (row.kind === 'codex') return row.label || 'Codex ' + row.short;
if (row.kind === 'session') return '5h';
if (row.kind === 'weekly_all') return 'Week';
return row.model || 'Week';
@@ -3444,6 +3448,7 @@ function shortQuotaLabel(row) {
function buildQuotaBar(row) {
const wrap = document.createElement('span');
wrap.className = 'quota-item';
+ wrap.dataset.runtime = row.kind === 'codex' ? 'codex' : 'claude';
const label = document.createElement('span');
label.className = 'quota-label';
@@ -3469,20 +3474,56 @@ function buildQuotaBar(row) {
}
async function refreshQuotaGauge() {
+ const request = ++quotaRequest;
+ const codexRefresh = refreshCodexQuotaGauge();
try {
- const usage = await window.api.getUsage();
+ const usage = await window.api.getUsage().catch(() => ({}));
+ if (request !== quotaRequest) return;
// Prefer the API's self-describing rows; fall back to the flat 5-hour keys.
const rows = Array.isArray(usage?.limits) && usage.limits.length
- ? usage.limits
+ ? [...usage.limits]
: (usage?.session !== undefined
? [{ kind: 'session', label: 'Current session', percent: usage.session, reset: usage.sessionReset }]
: []);
- if (!rows.length) { quotaGaugeEl.style.display = 'none'; return; }
+ replaceQuotaRows(rows, 'claude');
+ } catch {} finally {
+ await codexRefresh;
+ }
+}
- quotaGaugeEl.replaceChildren(...rows.map(buildQuotaBar));
- quotaGaugeEl.style.display = '';
- } catch {}
+function replaceQuotaRows(rows, runtime) {
+ [...quotaGaugeEl.children].filter(el => !el.matches('.quota-item')).forEach(el => el.remove());
+ quotaGaugeEl.querySelectorAll(`[data-runtime="${runtime}"]`).forEach(el => el.remove());
+ const bars = rows.map(buildQuotaBar);
+ if (runtime === 'claude') quotaGaugeEl.prepend(...bars);
+ else quotaGaugeEl.append(...bars);
+ quotaGaugeEl.style.display = quotaGaugeEl.children.length ? '' : 'none';
+}
+
+async function refreshCodexQuotaGauge() {
+ const request = ++codexQuotaRequest;
+ if (!codexQuotaEnabled) {
+ replaceQuotaRows([], 'codex');
+ return;
+ }
+ let usage;
+ try { usage = await window.api.getCodexUsage?.(); } catch {}
+ if (request !== codexQuotaRequest) return;
+ replaceQuotaRows(usage?.limits || [], 'codex');
+}
+
+function applyCodexUsage(enabled) {
+ codexQuotaEnabled = enabled === true;
+ return refreshCodexUsage();
+}
+
+function refreshCodexUsage() {
+ return Promise.all([
+ refreshCodexQuotaGauge(),
+ window.refreshCodexStatsUsage?.(codexQuotaEnabled),
+ ]);
}
+window._applyCodexUsage = applyCodexUsage;
refreshQuotaGauge();
setInterval(refreshQuotaGauge, 5 * 60 * 1000);
quotaGaugeEl.addEventListener('click', () => {
diff --git a/public/setting-defaults.js b/public/setting-defaults.js
index beeb487d2..10c0e670a 100644
--- a/public/setting-defaults.js
+++ b/public/setting-defaults.js
@@ -43,6 +43,7 @@ const SETTING_DEFAULTS = {
codexApproval: '',
codexModel: '',
codexEffort: '',
+ showCodexUsage: false,
};
const PROJECT_DELETE_PREVIEW_TIMEOUT_MS = 20000;
diff --git a/public/settings-panel.js b/public/settings-panel.js
index 8b94ad00a..bc0619ecf 100644
--- a/public/settings-panel.js
+++ b/public/settings-panel.js
@@ -84,6 +84,7 @@
const maxAgeValue = fieldValue('sessionMaxAgeDays');
const hideSdkValue = fieldValue('hideSdkSessions');
let appliedHideSdk = hideSdkValue;
+ let appliedCodexUsage = fieldValue('showCodexUsage') === true;
const themeValue = fieldValue('terminalTheme');
const rightClickValue = fieldValue('terminalRightClick');
const restoreStartupValue = fieldValue('restoreOnStartup');
@@ -137,6 +138,10 @@
`).join('')}
${harnessList.some(h => h.id === 'codex') ? `
+
Codex sandboxPassed as --sandbox; empty leaves codex's own config
${codexSelect('sv-codex-sandbox', 'codexSandbox', [['', 'Codex default'], ['read-only', 'Read-only'], ['workspace-write', 'Workspace write'], ['danger-full-access', 'Full access (danger)']])}
@@ -868,6 +873,8 @@
settings.preLaunchCmd = settingsViewerBody.querySelector('#sv-pre-launch').value.trim();
settings.addDirs = settingsViewerBody.querySelector('#sv-add-dirs').value.trim();
if (harnessToggles.length) settings.disabledHarnesses = harnessToggles.filter(t => !t.checked).map(t => t.dataset.harness);
+ const usageToggle = settingsViewerBody.querySelector('#sv-show-codex-usage');
+ if (usageToggle) settings.showCodexUsage = usageToggle.checked;
for (const [key, id] of [['codexSandbox', 'sv-codex-sandbox'], ['codexApproval', 'sv-codex-approval'], ['codexModel', 'sv-codex-model'], ['codexEffort', 'sv-codex-effort']]) {
const field = settingsViewerBody.querySelector('#' + id);
if (field) settings[key] = field.value;
@@ -924,6 +931,10 @@
// Update visibleSessionCount, sessionMaxAgeDays, and theme
if (!isProject) {
window._applySchedulesTab?.(settings.schedulesTab);
+ if (typeof settings.showCodexUsage === 'boolean' && settings.showCodexUsage !== appliedCodexUsage) {
+ window._applyCodexUsage?.(settings.showCodexUsage);
+ appliedCodexUsage = settings.showCodexUsage;
+ }
if (settings.visibleSessionCount && typeof window._setVisibleSessionCount === 'function') {
window._setVisibleSessionCount(settings.visibleSessionCount);
}
diff --git a/public/sidebar.js b/public/sidebar.js
index 14ca53f3a..3108252ed 100644
--- a/public/sidebar.js
+++ b/public/sidebar.js
@@ -903,7 +903,9 @@ window.flushDeferredProjectDeletionWrites = () => {
const patch = window.projectDeletionDeferredSettings, workingSet = window.projectDeletionDeferredWorkingSet;
window.projectDeletionDeferredSettings = null;
window.projectDeletionDeferredWorkingSet = null;
- if (patch) void saveGlobalSettings(patch.patch, { remove: patch.remove }).catch(() => {
+ if (patch) void saveGlobalSettings(patch.patch, { remove: patch.remove }).then(result => {
+ if (result === true && patch.patch.showCodexUsage === true) return window.refreshCodexUsage?.();
+ }).catch(() => {
showAppNotice({ id: 'settings-delete-busy', kind: 'error',
message: 'Settings could not be saved after the project deletion. Open Settings to review your values and save again.',
actionLabel: 'Open Settings', onAction: () => openSettingsViewer('global') });
diff --git a/public/stats-view.js b/public/stats-view.js
index 7b3aa5f93..207b15535 100644
--- a/public/stats-view.js
+++ b/public/stats-view.js
@@ -2,6 +2,17 @@
// Depends on globals: escapeHtml (utils.js), statsViewerBody (app.js)
let cachedUsage = null;
+let codexStatsRequest = 0;
+
+async function refreshCodexStatsUsage(enabled = true) {
+ const request = ++codexStatsRequest;
+ statsViewerBody.querySelector('.usage-container-codex')?.remove();
+ if (!enabled) return;
+ try {
+ const usage = await window.api.getCodexUsage?.();
+ if (request === codexStatsRequest && usage?.limits?.length) buildUsageSection(usage, 'codex');
+ } catch {}
+}
async function loadStats() {
statsViewerBody.innerHTML = '';
@@ -28,11 +39,6 @@ async function loadStats() {
statsViewerBody.innerHTML = '';
- if (!stats && !Object.keys(usage).length) {
- statsViewerBody.innerHTML = '
No stats data found. Run some Claude sessions first.
';
- return;
- }
-
if (stats) {
// dailyActivity is an array of {date, messageCount, sessionCount}
const rawDaily = stats.dailyActivity || [];
@@ -56,6 +62,12 @@ async function loadStats() {
buildUsageSection(usage);
}
+ await refreshCodexStatsUsage(codexQuotaEnabled);
+ if (!stats && !Object.keys(usage).length && !statsViewerBody.querySelector('.usage-container-codex')) {
+ statsViewerBody.innerHTML = '
No stats data found. Run some sessions first.
';
+ return;
+ }
+
if (stats) {
const notice = document.createElement('div');
notice.className = 'stats-notice';
@@ -65,19 +77,19 @@ async function loadStats() {
}
}
-function buildUsageSection(usage) {
+function buildUsageSection(usage, runtime = 'claude') {
// Remove existing usage container if present (for refresh)
- const existing = statsViewerBody.querySelector('.usage-container');
+ const existing = statsViewerBody.querySelector('.usage-container-' + runtime);
if (existing) existing.remove();
const container = document.createElement('div');
- container.className = 'usage-container';
+ container.className = 'usage-container usage-container-' + runtime;
const titleRow = document.createElement('div');
titleRow.className = 'usage-title-row';
const title = document.createElement('div');
title.className = 'daily-chart-title';
- title.textContent = 'Rate Limits';
+ title.textContent = runtime === 'codex' ? 'Codex Rate Limits' : 'Rate Limits';
titleRow.appendChild(title);
const refreshBtn = document.createElement('button');
@@ -88,6 +100,10 @@ function buildUsageSection(usage) {
refreshBtn.classList.add('usage-refresh-spinning');
refreshBtn.disabled = true;
try {
+ if (runtime === 'codex') {
+ await refreshCodexStatsUsage();
+ return;
+ }
const freshUsage = await window.api.getUsage();
if (freshUsage && Object.keys(freshUsage).length) {
cachedUsage = freshUsage;
diff --git a/src/main/usage/codex-usage.js b/src/main/usage/codex-usage.js
new file mode 100644
index 000000000..ab7a57762
--- /dev/null
+++ b/src/main/usage/codex-usage.js
@@ -0,0 +1,119 @@
+'use strict';
+
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { formatResetTime } = require('../../../claude-auth');
+
+function windowLabel(seconds) {
+ if (!Number.isFinite(seconds) || seconds <= 0) return 'usage';
+ if (seconds >= 2419200) return `${Math.round(seconds / 2592000)}mo`;
+ if (seconds >= 604800) return `${Math.round(seconds / 604800)}wk`;
+ if (seconds >= 86400) return `${Math.round(seconds / 86400)}d`;
+ return `${Math.max(1, Math.round(seconds / 3600))}h`;
+}
+
+function usageRows(raw) {
+ const limits = [];
+ const add = (win, model = null) => {
+ if (!win || !Number.isFinite(win.used_percent) || win.used_percent < 0) return;
+ const percent = Math.floor(win.used_percent);
+ if (model && percent === 0) return;
+ const short = windowLabel(win.limit_window_seconds);
+ limits.push({
+ kind: 'codex', short,
+ label: model ? `Codex ${model} (${short})` : `Codex ${short}`,
+ percent,
+ reset: formatResetTime(win.reset_at),
+ severity: percent >= 90 ? 'high' : 'normal',
+ });
+ };
+ add(raw?.rate_limit?.primary_window);
+ add(raw?.rate_limit?.secondary_window);
+ for (const extra of Array.isArray(raw?.additional_rate_limits) ? raw.additional_rate_limits : []) {
+ const name = typeof extra?.limit_name === 'string' ? extra.limit_name : 'model';
+ add(extra?.rate_limit?.primary_window, name);
+ add(extra?.rate_limit?.secondary_window, name);
+ }
+ return limits.length ? { limits } : {};
+}
+
+function createCodexUsage({ isEnabled, env = process.env, homedir = os.homedir,
+ readFile = fs.readFileSync, fetch = globalThis.fetch, now = Date.now,
+ setTimeout = globalThis.setTimeout, clearTimeout = globalThis.clearTimeout }) {
+ let pending = null;
+ let controller = null;
+ let generation = 0;
+ let retryAt = 0;
+ let failures = 0;
+
+ function settingsChanged() {
+ generation++;
+ controller?.abort();
+ controller = null;
+ pending = null;
+ }
+
+ async function getUsage() {
+ if (!isEnabled()) return {};
+ if (pending) return pending;
+ if (now() < retryAt) return {};
+ const requestGeneration = generation;
+ const abort = new AbortController();
+ controller = abort;
+ let timer;
+ const request = async () => {
+ let retryAfter = 0;
+ try {
+ const home = env.CODEX_HOME ? path.resolve(env.CODEX_HOME) : path.join(homedir(), '.codex');
+ const auth = JSON.parse(readFile(path.join(home, 'auth.json'), 'utf8'));
+ const token = auth?.tokens?.access_token;
+ if (typeof token !== 'string' || !token) throw new Error();
+ const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', originator: 'codex_cli_rs' };
+ if (typeof auth.tokens.account_id === 'string') headers['chatgpt-account-id'] = auth.tokens.account_id;
+ const cancelled = new Promise((_, reject) => abort.signal.addEventListener('abort', () => reject(new Error()), { once: true }));
+ timer = setTimeout(() => abort.abort(), 10000);
+ const result = await Promise.race([cancelled, (async () => {
+ const res = await fetch('https://chatgpt.com/backend-api/wham/usage', {
+ headers, signal: abort.signal, redirect: 'error',
+ });
+ if (!res.ok) {
+ if (res.status === 429) {
+ const value = res.headers?.get('retry-after');
+ const seconds = Number(value);
+ retryAfter = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - now();
+ }
+ throw new Error();
+ }
+ return usageRows(await res.json());
+ })()]);
+ if (requestGeneration !== generation || !isEnabled()) return {};
+ if (!result.limits?.length) throw new Error();
+ failures = 0;
+ retryAt = 0;
+ return result;
+ } catch {
+ if (requestGeneration === generation) {
+ const backoff = Math.min(300000, 30000 * 2 ** Math.min(failures++, 4));
+ retryAt = now() + Math.max(backoff, Number.isFinite(retryAfter) ? Math.min(3600000, retryAfter) : 0);
+ }
+ return {};
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+ pending = request();
+ try {
+ return await pending;
+ } finally {
+ if (requestGeneration === generation) {
+ pending = null;
+ controller = null;
+ }
+ }
+ }
+
+ return { getUsage, settingsChanged };
+}
+
+module.exports = { createCodexUsage };
diff --git a/test/codex-usage-ipc.test.js b/test/codex-usage-ipc.test.js
new file mode 100644
index 000000000..bfd476b93
--- /dev/null
+++ b/test/codex-usage-ipc.test.js
@@ -0,0 +1,72 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const vm = require('node:vm');
+const { createRequire } = require('node:module');
+const { SETTING_DEFAULTS } = require('../public/setting-defaults');
+
+test('main IPC enforces opt-in from saved settings and invalidates a request on Save', async t => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-ipc-1139-'));
+ const previous = process.env.CODEX_HOME;
+ process.env.CODEX_HOME = home;
+ t.after(() => {
+ if (previous === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = previous;
+ fs.rmSync(home, { recursive: true, force: true });
+ });
+ const auth = path.join(home, 'auth.json');
+ fs.writeFileSync(auth, JSON.stringify({ tokens: { access_token: 'FAKE-IPC-TOKEN' } }));
+ const filename = path.join(__dirname, '../main.js');
+ const source = fs.readFileSync(filename, 'utf8');
+ const start = source.indexOf('const codexUsage =');
+ assert.ok(start >= 0, 'main registers the opt-in service');
+ const registration = source.slice(start, source.indexOf("ipcMain.handle('get-usage'", start));
+ const saveStart = source.indexOf("ipcMain.handle('set-setting'");
+ const saveEnd = source.indexOf('\n});', saveStart) + 4;
+ const handlers = new Map();
+ let settings = {}, calls = 0, reads = 0, resolve, signal;
+ const read = fs.readFileSync;
+ t.mock.method(fs, 'readFileSync', (file, ...args) => {
+ if (String(file) === auth) { reads++; assert.equal(settings.showCodexUsage, true, 'off may not read auth'); }
+ return read(file, ...args);
+ });
+ t.mock.method(globalThis, 'fetch', (_url, options) => {
+ calls++;
+ assert.equal(settings.showCodexUsage, true, 'off may not call endpoint');
+ signal = options.signal;
+ return new Promise(done => { resolve = done; });
+ });
+ const context = vm.createContext({
+ require: createRequire(filename), SETTING_DEFAULTS,
+ ipcMain: { handle: (name, callback) => handlers.set(name, callback) },
+ getSetting: () => settings,
+ setSetting: async (_key, value) => { settings = value; },
+ applyUpdateChannel() {}, restartHarnessWatchers() {}, notifyRendererProjectsChanged() {},
+ });
+ vm.runInContext(registration, context, { filename });
+ t.after(() => vm.runInContext('codexUsage.settingsChanged()', context));
+ vm.runInContext(source.slice(saveStart, saveEnd), context, { filename });
+ const usage = handlers.get('get-codex-usage');
+ const save = value => handlers.get('set-setting')(null, 'global', value);
+ assert.deepEqual(await usage(), {});
+ assert.equal(reads, 0);
+ assert.equal(calls, 0);
+ await save({ showCodexUsage: 'true' });
+ assert.deepEqual(await usage(), {});
+ assert.equal(reads, 0);
+ await save({ showCodexUsage: true });
+ const pending = usage();
+ assert.equal(calls, 1);
+ await save({ showCodexUsage: false });
+ assert.equal(signal.aborted, true);
+ resolve({ ok: true, json: async () => ({ rate_limit: { primary_window: { used_percent: 10 } } }) });
+ assert.deepEqual(await pending, {});
+ assert.deepEqual(await usage(), {});
+ assert.equal(reads, 1);
+ assert.equal(calls, 1);
+ const preload = fs.readFileSync(path.join(__dirname, '../preload.js'), 'utf8');
+ assert.match(preload, /getCodexUsage:\s*\(\)\s*=>\s*ipcRenderer.invoke\('get-codex-usage'\)/);
+});
diff --git a/test/codex-usage-renderer.test.js b/test/codex-usage-renderer.test.js
new file mode 100644
index 000000000..4e460c2d0
--- /dev/null
+++ b/test/codex-usage-renderer.test.js
@@ -0,0 +1,199 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { JSDOM } = require('jsdom');
+const { loadAppFunctions } = require('./app-source');
+const { SETTING_DEFAULTS } = require('../public/setting-defaults');
+
+const codex = { limits: [{ kind: 'codex', short: '5h', label: 'Codex 5h', percent: 42, reset: 'tomorrow' }] };
+function setup(t) {
+ const dom = new JSDOM(fs.readFileSync(path.join(__dirname, '../public/index.html'), 'utf8'), { runScripts: 'outside-only' });
+ t.after(() => dom.window.close());
+ const w = dom.window;
+ w.statsViewerBody = w.document.querySelector('#stats-viewer-body');
+ w.api = { getUsage: async () => ({ session: 5 }), getCodexUsage: async () => codex };
+ const ctx = dom.getInternalVMContext();
+ for (const file of ['utils.js', 'stats-view.js']) {
+ const filename = path.join(__dirname, '../public', file);
+ vm.runInContext(fs.readFileSync(filename, 'utf8'), ctx, { filename });
+ }
+ loadAppFunctions(ctx, {
+ functions: ['shortQuotaLabel', 'buildQuotaBar', 'refreshQuotaGauge', 'replaceQuotaRows', 'refreshCodexQuotaGauge', 'applyCodexUsage', 'refreshCodexUsage'],
+ declarations: ['quotaGaugeEl', 'quotaRequest', 'codexQuotaRequest', 'codexQuotaEnabled'],
+ });
+ return w;
+}
+
+test('Codex usage defaults off', () => assert.equal(SETTING_DEFAULTS.showCodexUsage, false));
+
+test('shipped status bar contains only labelled quota rows after refresh', async t => {
+ const w = setup(t);
+ await w.refreshQuotaGauge();
+ const gauge = w.document.querySelector('#status-bar-quota');
+ assert.equal(gauge.children.length, 2, 'no unlabelled placeholder track remains');
+ assert.ok([...gauge.children].every(el => el.matches('.quota-item')));
+});
+
+test('shipped gauge hides when Claude is unavailable and Codex is off', async t => {
+ const w = setup(t);
+ w.api.getUsage = async () => { throw new Error('unavailable'); };
+ await w.applyCodexUsage(false);
+ await w.refreshQuotaGauge();
+ const gauge = w.document.querySelector('#status-bar-quota');
+ assert.equal(gauge.style.display, 'none', 'empty gauge must be hidden');
+ assert.equal(gauge.children.length, 0);
+});
+
+test('opening Stats during deferred turn-off does not fetch Codex', async t => {
+ const w = setup(t);
+ w.api.refreshStats = async () => ({ stats: null, usage: { session: 5 } });
+ await w.applyCodexUsage(false);
+ let calls = 0;
+ w.api.getCodexUsage = async () => { calls++; return codex; };
+ await w.loadStats();
+ assert.equal(calls, 0, 'opening Stats must honor the renderer off state');
+ assert.equal(w.document.querySelector('.usage-container-codex'), null);
+ assert.ok(w.document.querySelector('.usage-container-claude'));
+});
+
+test('Codex settings disclosure names the account-id header sent with the token', () => {
+ const docs = fs.readFileSync(path.join(__dirname, '../docs/settings.md'), 'utf8');
+ assert.match(docs, /account id[^\n]*`chatgpt-account-id`/);
+});
+
+test('status bar reuses quota bars and distinguishes Codex; failure removes only Codex', async t => {
+ const w = setup(t);
+ await w.refreshQuotaGauge();
+ assert.equal(w.document.querySelectorAll('.quota-item').length, 2);
+ assert.equal(w.document.querySelector('[data-runtime="codex"] .quota-label')?.textContent, 'Codex 5h');
+ assert.match(w.document.querySelector('[data-runtime="codex"]').title, /42%.*tomorrow/);
+ w.api.getCodexUsage = async () => { throw new Error('quiet failure'); };
+ await w.refreshQuotaGauge();
+ assert.equal(w.document.querySelectorAll('.quota-item').length, 1);
+ assert.equal(w.document.querySelector('[data-runtime="codex"]'), null);
+});
+
+test('turning off with a deferred save hides Codex without any usage request', async t => {
+ const w = setup(t);
+ await w.refreshQuotaGauge();
+ w.buildUsageSection(codex, 'codex');
+ const claude = w.document.querySelector('[data-runtime="claude"]');
+ let codexCalls = 0, claudeCalls = 0;
+ w.api.getCodexUsage = async () => { codexCalls++; return codex; };
+ w.api.getUsage = async () => { claudeCalls++; return { session: 5 }; };
+ await w.applyCodexUsage(false);
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(codexCalls, 0, 'deferred off must not fetch Codex while main still has it on');
+ assert.equal(claudeCalls, 0, 'turning Codex off must not refresh Claude');
+ assert.equal(w.document.querySelector('[data-runtime="codex"]'), null);
+ assert.equal(w.document.querySelector('.usage-container-codex'), null);
+ assert.equal(w.document.querySelector('[data-runtime="claude"]'), claude);
+});
+
+test('turning on refreshes only Codex and preserves the Claude status bar node', async t => {
+ const w = setup(t);
+ await w.refreshQuotaGauge();
+ const claude = w.document.querySelector('[data-runtime="claude"]');
+ let claudeCalls = 0, codexCalls = 0;
+ w.api.getUsage = async () => { claudeCalls++; return { session: 8 }; };
+ w.api.getCodexUsage = async () => { codexCalls++; return codex; };
+ await w.applyCodexUsage(true);
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(claudeCalls, 0, 'enabling Codex must not refresh Claude');
+ assert.ok(codexCalls > 0);
+ assert.equal(w.document.querySelector('[data-runtime="claude"]'), claude);
+ assert.equal(w.document.querySelectorAll('[data-runtime="codex"]').length, 1);
+});
+
+test('disabled Stats refresh removes Codex without fetching even if main is still enabled', async t => {
+ const w = setup(t);
+ w.buildUsageSection({ session: 5 });
+ w.buildUsageSection(codex, 'codex');
+ let calls = 0;
+ w.api.getCodexUsage = async () => { calls++; return codex; };
+ await w.refreshCodexStatsUsage(false);
+ assert.equal(calls, 0, 'disabled Stats must not fetch');
+ assert.equal(w.document.querySelector('.usage-container-codex'), null);
+ assert.ok(w.document.querySelector('.usage-container-claude'));
+});
+
+test('weekly Codex model labels differ from account labels and over-limit bars clamp', async t => {
+ const w = setup(t);
+ w.api.getCodexUsage = async () => ({ limits: [
+ { kind: 'codex', short: '1wk', label: 'Codex 1wk', percent: 15 },
+ { kind: 'codex', short: '1wk', label: 'Codex Spark (1wk)', percent: 125 },
+ ] });
+ await w.refreshQuotaGauge();
+ assert.deepEqual([...w.document.querySelectorAll('[data-runtime="codex"] .quota-label')].map(el => el.textContent),
+ ['Codex 1wk', 'Codex Spark (1wk)']);
+ const row = w.document.querySelectorAll('[data-runtime="codex"]')[1];
+ assert.equal(row.querySelector('.quota-fill').style.width, '100%');
+ assert.equal(row.querySelector('.quota-pct').textContent, '125%');
+});
+
+test('Codex still renders if Claude fails and older refreshes cannot repaint stale rows', async t => {
+ const w = setup(t);
+ w.api.getUsage = async () => { throw new Error('Claude unavailable'); };
+ await w.refreshQuotaGauge();
+ assert.equal(w.document.querySelectorAll('.quota-item').length, 1);
+ let resolve;
+ w.api.getCodexUsage = () => new Promise(done => { resolve = done; });
+ const stale = w.refreshQuotaGauge();
+ await Promise.resolve();
+ w.api.getCodexUsage = async () => ({});
+ await w.refreshQuotaGauge();
+ resolve(codex);
+ await stale;
+ assert.equal(w.document.querySelector('[data-runtime="codex"]'), null);
+ assert.equal(w.document.querySelector('#status-bar-quota').style.display, 'none');
+});
+
+test('stats render separate provider sections and Codex failure removes its cached section', async t => {
+ const w = setup(t);
+ w.buildUsageSection({ session: 5 });
+ w.buildUsageSection(codex, 'codex');
+ assert.equal(w.document.querySelectorAll('.usage-container').length, 2);
+ assert.equal(w.document.querySelector('.usage-container-codex .daily-chart-title')?.textContent, 'Codex Rate Limits');
+ w.api.getCodexUsage = async () => ({});
+ await w.document.querySelector('.usage-container-codex .usage-refresh-btn').onclick();
+ assert.equal(w.document.querySelector('.usage-container-codex'), null);
+ assert.equal(w.document.querySelectorAll('.usage-container').length, 1);
+});
+
+test('saving off hides both surfaces immediately and rejects in-flight stats repaint', async t => {
+ const w = setup(t);
+ assert.equal(typeof w.applyCodexUsage, 'function', 'runtime settings hook exists');
+ await w.refreshQuotaGauge();
+ w.buildUsageSection(codex, 'codex');
+ let resolve;
+ w.api.getCodexUsage = () => new Promise(done => { resolve = done; });
+ const stale = w.refreshCodexStatsUsage();
+ w.api.getCodexUsage = async () => ({});
+ w.applyCodexUsage(false);
+ assert.equal(w.document.querySelector('[data-runtime="codex"]'), null);
+ assert.equal(w.document.querySelector('.usage-container-codex'), null);
+ resolve(codex);
+ await stale;
+ assert.equal(w.document.querySelector('.usage-container-codex'), null);
+});
+
+test('loading stats fetches Codex without replacing Claude', async t => {
+ const w = setup(t);
+ w.api.refreshStats = async () => ({ stats: null, usage: { session: 5 } });
+ await w.loadStats();
+ assert.equal(w.document.querySelectorAll('.usage-container').length, 2);
+});
+
+test('refreshing the gauge never mutates or duplicates the supplied Claude rows', async t => {
+ const w = setup(t);
+ const claude = { limits: [{ kind: 'session', label: 'Current session', percent: 5 }] };
+ w.api.getUsage = async () => claude;
+ await w.refreshQuotaGauge();
+ await w.refreshQuotaGauge();
+ assert.equal(claude.limits.length, 1, 'Claude input rows stay unchanged');
+ assert.equal(w.document.querySelectorAll('.quota-item').length, 2);
+});
diff --git a/test/codex-usage.test.js b/test/codex-usage.test.js
new file mode 100644
index 000000000..7e902a757
--- /dev/null
+++ b/test/codex-usage.test.js
@@ -0,0 +1,219 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const filename = path.join(__dirname, '../src/main/usage/codex-usage.js');
+const implementation = fs.existsSync(filename) ? require(filename) : {};
+const secret = 'FAKE-1139-TOKEN';
+const response = () => ({
+ tokens: secret, plan_type: 'private-plan',
+ rate_limit: {
+ primary_window: { used_percent: 8.9, limit_window_seconds: 18000, reset_at: 1900000000 },
+ secondary_window: { used_percent: 92, limit_window_seconds: 604800 },
+ },
+ additional_rate_limits: [{ limit_name: 'Spark', rate_limit: {
+ primary_window: { used_percent: 0, limit_window_seconds: 18000 },
+ secondary_window: { used_percent: 12, limit_window_seconds: 604800 },
+ } }],
+});
+
+function setup(t, overrides = {}) {
+ assert.equal(typeof implementation.createCodexUsage, 'function', 'main-side Codex usage service exists');
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-usage-1139-'));
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(home, 'auth.json'), JSON.stringify({ tokens: { access_token: secret, account_id: 'fake-account' } }));
+ const state = { enabled: true, time: 0, reads: [], calls: [], timers: [] };
+ const service = implementation.createCodexUsage({
+ isEnabled: () => state.enabled,
+ env: { CODEX_HOME: home },
+ readFile: (...args) => { state.reads.push(args[0]); return fs.readFileSync(...args); },
+ fetch: async (...args) => { state.calls.push(args); return { ok: true, json: async () => response() }; },
+ now: () => state.time,
+ setTimeout: (fn, ms) => { state.timers.push(fn); state.timeoutMs = ms; return state.timers.length; },
+ clearTimeout: () => {},
+ ...overrides,
+ });
+ return { home, state, service };
+}
+
+test('off never reads even a throwing auth file and never fetches', async t => {
+ let reads = 0, calls = 0;
+ const h = setup(t, {
+ readFile: () => { reads++; throw new Error('auth must not be read'); },
+ fetch: () => { calls++; assert.fail('endpoint must not be called'); },
+ });
+ h.state.enabled = false;
+ assert.deepEqual(await h.service.getUsage(), {});
+ assert.equal(reads, 0);
+ assert.equal(calls, 0);
+});
+
+test('on uses the fake CODEX_HOME and sends only renderable rows across IPC', async t => {
+ const h = setup(t);
+ const usage = await h.service.getUsage();
+ assert.equal(h.state.reads[0], path.join(h.home, 'auth.json'));
+ assert.equal(h.state.calls.length, 1);
+ const [url, options] = h.state.calls[0];
+ assert.equal(url, 'https://chatgpt.com/backend-api/wham/usage');
+ assert.equal(options.headers.Authorization, `Bearer ${secret}`);
+ assert.equal(options.headers['chatgpt-account-id'], 'fake-account');
+ assert.deepEqual(Object.keys(options.headers).sort(), ['Authorization', 'Content-Type', 'chatgpt-account-id', 'originator'].sort());
+ const { Authorization, ...otherHeaders } = options.headers;
+ assert.equal(Authorization, `Bearer ${secret}`);
+ assert.ok(!JSON.stringify({ url, headers: otherHeaders, body: options.body }).includes(secret), 'token appears only in Authorization');
+ assert.equal(options.redirect, 'error', 'credentials must never follow a redirect');
+ assert.ok(options.signal instanceof AbortSignal);
+ assert.deepEqual(Object.keys(usage), ['limits']);
+ assert.deepEqual(usage.limits.map(row => row.percent), [8, 92, 12]);
+ assert.deepEqual(usage.limits.map(row => row.short), ['5h', '1wk', '1wk']);
+ assert.equal(usage.limits[2].label, 'Codex Spark (1wk)');
+ assert.ok(usage.limits[0].reset);
+ assert.equal(usage.limits[1].severity, 'high');
+ assert.doesNotMatch(JSON.stringify(usage), /FAKE-1139-TOKEN|private-plan|fake-account/);
+});
+
+test('no CODEX_HOME uses only the injected disposable home', async t => {
+ const h = setup(t, { env: {}, homedir: () => h.home });
+ fs.mkdirSync(path.join(h.home, '.codex'));
+ fs.renameSync(path.join(h.home, 'auth.json'), path.join(h.home, '.codex/auth.json'));
+ assert.equal((await h.service.getUsage()).limits.length, 3);
+ assert.equal(h.state.reads[0], path.join(h.home, '.codex/auth.json'));
+});
+
+for (const status of [429, 500]) {
+ test(`HTTP ${status} quietly hides rows and backs off before retry`, async t => {
+ let calls = 0;
+ const h = setup(t, { fetch: async () => {
+ calls++;
+ return calls === 1 ? { ok: false, status, headers: { get: () => '120' } } : { ok: true, json: async () => response() };
+ } });
+ assert.deepEqual(await h.service.getUsage(), {});
+ h.state.time = status === 429 ? 119999 : 29999;
+ assert.deepEqual(await h.service.getUsage(), {});
+ assert.equal(calls, 1, 'retry blocked during backoff');
+ h.state.time++;
+ assert.equal((await h.service.getUsage()).limits.length, 3);
+ assert.equal(calls, 2);
+ });
+}
+
+test('repeated failures increase backoff and never surface exception contents', async t => {
+ let calls = 0;
+ const h = setup(t, { fetch: async () => { calls++; throw new Error(secret); } });
+ const logs = [];
+ t.mock.method(console, 'error', (...args) => logs.push(args));
+ t.mock.method(console, 'warn', (...args) => logs.push(args));
+ t.mock.method(console, 'log', (...args) => logs.push(args));
+ assert.deepEqual(await h.service.getUsage(), {});
+ h.state.time = 30000;
+ assert.deepEqual(await h.service.getUsage(), {});
+ h.state.time = 89999;
+ assert.deepEqual(await h.service.getUsage(), {});
+ assert.equal(calls, 2);
+ h.state.time = 90000;
+ assert.deepEqual(await h.service.getUsage(), {});
+ assert.equal(calls, 3);
+ assert.deepEqual(logs, []);
+});
+
+test('timeout aborts a hanging request, hides rows and applies backoff', async t => {
+ let signal;
+ const h = setup(t, { fetch: async (_url, options) => {
+ signal = options.signal;
+ return new Promise(() => {});
+ } });
+ const pending = h.service.getUsage();
+ await Promise.resolve();
+ assert.equal(h.state.timers.length, 1);
+ assert.equal(h.state.timeoutMs, 10000);
+ h.state.timers[0]();
+ assert.equal(signal.aborted, true);
+ assert.deepEqual(await pending, {});
+ assert.deepEqual(await h.service.getUsage(), {});
+ assert.equal(h.state.reads.length, 1);
+});
+
+test('simultaneous calls share a request; off cancels it and on rejects its stale result', async t => {
+ let resolve, signal, calls = 0;
+ const h = setup(t, { fetch: (_url, options) => {
+ calls++;
+ signal = options.signal;
+ return new Promise(done => { resolve = done; });
+ } });
+ const first = h.service.getUsage();
+ const second = h.service.getUsage();
+ await Promise.resolve();
+ assert.equal(calls, 1);
+ h.state.enabled = false;
+ h.service.settingsChanged();
+ assert.equal(signal.aborted, true);
+ assert.deepEqual(await h.service.getUsage(), {});
+ h.state.enabled = true;
+ h.service.settingsChanged();
+ resolve({ ok: true, json: async () => response() });
+ assert.deepEqual(await first, {});
+ assert.deepEqual(await second, {});
+ const next = h.service.getUsage();
+ await Promise.resolve();
+ resolve({ ok: true, json: async () => response() });
+ assert.equal((await next).limits.length, 3);
+ assert.equal(calls, 2);
+});
+
+test('missing, malformed and non-OAuth auth files hide quietly without fetch', async t => {
+ const h = setup(t);
+ for (const auth of [null, '{broken', '{}', '{"tokens":{"access_token":42}}']) {
+ if (auth === null) fs.unlinkSync(path.join(h.home, 'auth.json'));
+ else fs.writeFileSync(path.join(h.home, 'auth.json'), auth);
+ h.state.time += 1000000;
+ assert.deepEqual(await h.service.getUsage(), {});
+ }
+ assert.equal(h.state.calls.length, 0);
+});
+
+test('malformed endpoint data is quiet and invalid percentages never render', async t => {
+ const h = setup(t, { fetch: async () => ({ ok: true, json: async () => ({ rate_limit: {
+ primary_window: { used_percent: 'private-data' }, secondary_window: { used_percent: -1 },
+ } }) }) });
+ assert.deepEqual(await h.service.getUsage(), {});
+});
+
+test('over-limit percentages remain visible for account and model windows', async t => {
+ const h = setup(t, { fetch: async () => ({ ok: true, json: async () => ({
+ rate_limit: { primary_window: { used_percent: 125.8, limit_window_seconds: 18000 } },
+ additional_rate_limits: [{ limit_name: 'Spark', rate_limit: {
+ secondary_window: { used_percent: 110, limit_window_seconds: 604800 },
+ } }],
+ }) }) });
+ const usage = await h.service.getUsage();
+ assert.deepEqual(usage.limits?.map(row => row.percent), [125, 110], 'over-limit windows must not disappear');
+ assert.ok(usage.limits.every(row => row.severity === 'high'));
+});
+
+test('turning off without a generation change discards an in-flight response', async t => {
+ let resolve;
+ const h = setup(t, { fetch: () => new Promise(done => { resolve = done; }) });
+ const pending = h.service.getUsage();
+ h.state.enabled = false;
+ resolve({ ok: true, json: async () => response() });
+ assert.deepEqual(await pending, {}, 'disabled setting must suppress the result without settingsChanged');
+});
+
+test('Retry-After longer than an hour is capped at one hour', async t => {
+ let calls = 0;
+ const h = setup(t, { fetch: async () => {
+ calls++;
+ return calls === 1 ? { ok: false, status: 429, headers: { get: () => '7200' } }
+ : { ok: true, json: async () => response() };
+ } });
+ assert.deepEqual(await h.service.getUsage(), {});
+ h.state.time = 3599999;
+ assert.deepEqual(await h.service.getUsage(), {});
+ assert.equal(calls, 1);
+ h.state.time = 3600000;
+ assert.equal((await h.service.getUsage()).limits?.length, 3, 'retry resumes at the one-hour cap');
+ assert.equal(calls, 2);
+});
diff --git a/test/dom-settings-nav.test.js b/test/dom-settings-nav.test.js
index 3f6c3b17b..7376faf67 100644
--- a/test/dom-settings-nav.test.js
+++ b/test/dom-settings-nav.test.js
@@ -13,6 +13,29 @@ const root = path.join(__dirname, '..');
const settle = () => new Promise(resolve => setImmediate(resolve));
const globalPages = ['general', 'sessions', 'keyboard', 'automation', 'remote', 'integrations', 'archived', 'advanced'];
+test('Codex usage is opt-in under CLI Agents and saving applies it without restart', async t => {
+ const h = setup(t);
+ const applied = [];
+ h.w._applyCodexUsage = value => applied.push(value);
+ await h.open();
+ const toggle = h.q('#sv-show-codex-usage');
+ assert.ok(toggle, 'Show Codex usage toggle exists');
+ assert.equal(toggle.checked, false);
+ assert.equal(toggle.closest('.settings-page').dataset.section, 'sessions');
+ assert.equal(toggle.closest('.settings-section').querySelector('.settings-section-title').textContent, 'CLI Agents');
+ assert.match(toggle.closest('.settings-field').textContent, /chatgpt.com/);
+ for (const enabled of [true, false]) {
+ toggle.checked = enabled;
+ toggle.dispatchEvent(new h.w.Event('change', { bubbles: true }));
+ h.q('#sv-save-btn').click();
+ await settle();
+ assert.equal(h.saved.global.showCodexUsage, enabled);
+ assert.equal(applied.at(-1), enabled);
+ }
+ await h.open('project');
+ assert.equal(h.q('#sv-show-codex-usage'), null);
+});
+
function setup(t) {
const dom = new JSDOM(fs.readFileSync(path.join(root, 'public/index.html'), 'utf8'), { url: 'http://localhost', runScripts: 'outside-only' });
t.after(() => dom.window.close());
@@ -58,6 +81,91 @@ function setup(t) {
return { w, q, nav, open, click, active, saved, timers, observers, ctx };
}
+test('unrelated global saves and repeated saves do not reapply Codex usage', async t => {
+ const h = setup(t);
+ const applied = [];
+ h.w._applyCodexUsage = value => applied.push(value);
+ await h.open();
+ h.q('#sv-visible-count').value = '42';
+ h.q('#sv-save-btn').click();
+ await settle();
+ assert.deepEqual(applied, [], 'unrelated Save must not refresh usage');
+ for (const enabled of [true, false]) {
+ h.q('#sv-show-codex-usage').checked = enabled;
+ h.q('#sv-save-btn').click();
+ await settle();
+ assert.equal(applied.at(-1), enabled);
+ const count = applied.length;
+ h.q('#sv-save-btn').click();
+ await settle();
+ assert.equal(applied.length, count, 'unchanged repeated Save must not refresh usage');
+ }
+ assert.deepEqual(applied, [true, false]);
+});
+
+test('saving without a registered Codex harness preserves its enabled usage state', async t => {
+ const h = setup(t);
+ h.saved.global = { showCodexUsage: true };
+ h.w.api.getHarnesses = async () => [{ id: 'claude', label: 'Claude', enabled: true }];
+ const applied = [];
+ h.w._applyCodexUsage = value => applied.push(value);
+ await h.open();
+ assert.equal(h.q('#sv-show-codex-usage'), null);
+ h.q('#sv-visible-count').value = '42';
+ h.q('#sv-save-btn').click();
+ await settle();
+ assert.equal(h.saved.global.showCodexUsage, true);
+ assert.deepEqual(applied, [], 'missing toggle must not disable renderer usage');
+});
+
+test('flushing a deferred enable refreshes Codex rows after persistence', async t => {
+ const h = setup(t);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-deferred-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const file = path.join(dir, 'global.json');
+ fs.writeFileSync(file, JSON.stringify({ showCodexUsage: false }));
+ const read = () => JSON.parse(fs.readFileSync(file, 'utf8'));
+ h.w.api.getSetting = async () => read();
+ h.w.api.setSetting = async (_key, value) => fs.writeFileSync(file, JSON.stringify(value));
+ h.w.statsViewerBody = h.q('#stats-viewer-body');
+ const statsFile = path.join(root, 'public/stats-view.js');
+ vm.runInContext(fs.readFileSync(statsFile, 'utf8'), h.ctx, { filename: statsFile });
+ loadAppFunctions(h.ctx, {
+ functions: ['shortQuotaLabel', 'buildQuotaBar', 'replaceQuotaRows', 'refreshCodexQuotaGauge', 'applyCodexUsage', 'refreshCodexUsage'],
+ declarations: ['quotaGaugeEl', 'codexQuotaRequest', 'codexQuotaEnabled'],
+ });
+ h.w._applyCodexUsage = h.w.applyCodexUsage;
+ await h.w.applyCodexUsage(false);
+ const sidebarFile = path.join(root, 'public/sidebar.js');
+ const flush = fs.readFileSync(sidebarFile, 'utf8').match(/^window\.flushDeferredProjectDeletionWrites = \(\) => \{[\s\S]*?^\};/m);
+ assert.ok(flush);
+ vm.runInContext(flush[0], h.ctx, { filename: sidebarFile });
+ let callsAfterSave = 0;
+ h.w.api.getCodexUsage = async () => {
+ if (!read().showCodexUsage) return {};
+ callsAfterSave++;
+ return { limits: [{ kind: 'codex', short: '5h', label: 'Codex 5h', percent: 42 }] };
+ };
+ await h.open();
+ h.w.api.getSetting = async () => {
+ h.w.projectDeletionWritesBlocked = true;
+ return read();
+ };
+ h.q('#sv-show-codex-usage').checked = true;
+ h.q('#sv-save-btn').click();
+ await settle();
+ assert.equal(read().showCodexUsage, false);
+ assert.equal(h.q('[data-runtime="codex"]'), null);
+ h.w.api.getSetting = async () => read();
+ h.w.projectDeletionWritesBlocked = false;
+ h.w.flushDeferredProjectDeletionWrites();
+ await settle();
+ assert.equal(read().showCodexUsage, true);
+ assert.ok(callsAfterSave > 0, 'successful flush must refresh Codex immediately');
+ assert.equal(h.q('[data-runtime="codex"] .quota-pct')?.textContent, '42%');
+ assert.ok(h.q('.usage-container-codex'));
+});
+
test('global and project navigation expose the ordered pages and named regions', async t => {
const h = setup(t);
await h.open();