Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions .ai/contexts/ipc-bridge.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion claude-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,4 @@ async function fetchAndTransformUsage() {
}
}

module.exports = { getOAuthToken, fetchUsage, fetchAndTransformUsage, getConfigDir };
module.exports = { getOAuthToken, fetchUsage, fetchAndTransformUsage, getConfigDir, formatResetTime };
4 changes: 4 additions & 0 deletions docs/activity-stats.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
7 changes: 7 additions & 0 deletions docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
7 changes: 7 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
}

// Shell profiles → shell-profiles.js
const { discoverShellProfiles, getShellProfiles, resolveShell, isWindows, isWslShell, windowsToWslPath, shellArgs, quoteArgvForShell, claudeCommand, headlessClaudeLaunch } = require('./src/main/terminals/shell-profiles');

Check warning on line 88 in main.js

View workflow job for this annotation

GitHub Actions / lint

'discoverShellProfiles' is assigned a value but never used. Allowed unused vars must match /^_/u
const { startScheduler, scheduleLaunchRefusal, resolveScheduleSandbox, initialScheduleProjects, scanSchedules, setScheduleEnabled } = require('./src/main/schedules/schedule-runner');
const { buildScheduleList } = require('./src/main/schedules/schedule-list');
const { archivePlanForGroups, validArchiveGroups } = require('./archived-projects');
Expand Down Expand Up @@ -627,8 +627,8 @@
getMainWindow: () => mainWindow,
log,
});
const { readSessionFile, readFolderFromFilesystem,

Check warning on line 630 in main.js

View workflow job for this annotation

GitHub Actions / lint

'readFolderFromFilesystem' is assigned a value but never used. Allowed unused vars must match /^_/u

Check warning on line 630 in main.js

View workflow job for this annotation

GitHub Actions / lint

'readSessionFile' is assigned a value but never used. Allowed unused vars must match /^_/u
backfillEntrypoints, backfillCustomTitles, revealIfSdkSession, notifyRendererProjectsChanged, sendStatus, populateCacheViaWorker,

Check warning on line 631 in main.js

View workflow job for this annotation

GitHub Actions / lint

'sendStatus' is assigned a value but never used. Allowed unused vars must match /^_/u
scanFoldersViaWorker, setRemoteRoots, resolveFolderDir, isIndexingFinished } = sessionCache;
// see .ai/contexts/session-cache.md ("Projects query worker")
const { createProjectsWorkerClient } = require('./projects-worker-client');
Expand Down Expand Up @@ -1556,6 +1556,11 @@
});

// --- 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() || {};
Expand Down Expand Up @@ -1792,8 +1797,10 @@

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) {
Expand Down Expand Up @@ -3166,7 +3173,7 @@
// WSL profiles only work for plain terminals — Claude CLI sessions need the
// Windows shell because session data lives on the Windows filesystem.
const requestedProfile = resolveShell(effectiveProfileId);
const useWslProfile = isWslShell(requestedProfile.path) && isPlainTerminal;

Check warning on line 3176 in main.js

View workflow job for this annotation

GitHub Actions / lint

'useWslProfile' is assigned a value but never used. Allowed unused vars must match /^_/u
const shellProfile = (isWslShell(requestedProfile.path) && !isPlainTerminal)
? resolveShell('auto')
: requestedProfile;
Expand Down
1 change: 1 addition & 0 deletions preload.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
53 changes: 47 additions & 6 deletions public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand All @@ -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', () => {
Expand Down
1 change: 1 addition & 0 deletions public/setting-defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const SETTING_DEFAULTS = {
codexApproval: '',
codexModel: '',
codexEffort: '',
showCodexUsage: false,
};

const PROJECT_DELETE_PREVIEW_TIMEOUT_MS = 20000;
Expand Down
11 changes: 11 additions & 0 deletions public/settings-panel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -137,6 +138,10 @@
</div>
</div>`).join('')}
${harnessList.some(h => h.id === 'codex') ? `
<div class="settings-field">
<div class="settings-field-info"><span class="settings-label">Show Codex usage</span><div class="settings-description" id="sv-show-codex-usage-help">Off by default. Uses your local Codex sign-in to request usage from chatgpt.com. Hides quietly when unavailable.</div></div>
<div class="settings-field-control"><label class="settings-toggle"><input type="checkbox" id="sv-show-codex-usage" aria-label="Show Codex usage" aria-describedby="sv-show-codex-usage-help" ${fieldValue('showCodexUsage') ? 'checked' : ''}><span class="settings-toggle-slider"></span></label></div>
</div>
<div class="settings-field">
<div class="settings-field-info"><span class="settings-label">Codex sandbox</span><div class="settings-description">Passed as <code>--sandbox</code>; empty leaves codex's own config</div></div>
<div class="settings-field-control">${codexSelect('sv-codex-sandbox', 'codexSandbox', [['', 'Codex default'], ['read-only', 'Read-only'], ['workspace-write', 'Workspace write'], ['danger-full-access', 'Full access (danger)']])}</div>
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand Down
4 changes: 3 additions & 1 deletion public/sidebar.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') });
Expand Down
34 changes: 25 additions & 9 deletions public/stats-view.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';
Expand All @@ -28,11 +39,6 @@ async function loadStats() {

statsViewerBody.innerHTML = '';

if (!stats && !Object.keys(usage).length) {
statsViewerBody.innerHTML = '<div class="plans-empty">No stats data found. Run some Claude sessions first.</div>';
return;
}

if (stats) {
// dailyActivity is an array of {date, messageCount, sessionCount}
const rawDaily = stats.dailyActivity || [];
Expand All @@ -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 = '<div class="plans-empty">No stats data found. Run some sessions first.</div>';
return;
}

if (stats) {
const notice = document.createElement('div');
notice.className = 'stats-notice';
Expand All @@ -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');
Expand All @@ -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;
Expand Down
Loading
Loading