Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(usage): generalize to multiple providers and add Codex (#9)
eneskirca553c1d14c34a
diff --git a/src/core/usage/claude-usage-map.ts b/src/core/usage/claude-usage-map.tsindex 7402392d5..7bb4a0365 100644--- a/src/core/usage/claude-usage-map.ts+++ b/src/core/usage/claude-usage-map.ts@@ -50,10 +50,13 @@ function mapLimit(raw: unknown): UsageLimit | null {kind,group: typeof l.group === 'string' && l.group ? l.group : null,usedPercent,- // Severity is the server's own call. Deriving it from percent thresholds locally would- // desync from the plan the account is actually on.- severity: typeof l.severity === 'string' && l.severity ? l.severity : 'normal',+ // Severity is the server's own call — deriving it from percent thresholds locally would+ // desync from the plan the account is actually on. Absent means "not reported", NOT+ // 'normal': defaulting it green would hide an exhausted window on any payload that omits it.+ severity: typeof l.severity === 'string' && l.severity ? l.severity : null,resetsAt: parseResetTimestamp(l.resets_at),+ // Claude does not report bucket durations; `kind` is the only window hint it gives.+ windowMinutes: null,scopeLabel: displayName || null,// Absent `is_active` means "unknown", not "inactive" — an older payload that omits the// field must not have every limit silently treated as dormant.@@ -77,8 +80,10 @@ function legacyLimits(data: Record<string, any>): UsageLimit[] {kind,group,usedPercent,- severity: 'normal',+ // Legacy payloads carry no severity — leave it to the local percentage thresholds.+ severity: null,resetsAt: parseResetTimestamp(w.resets_at),+ windowMinutes: null,scopeLabel: null,isActive: false})diff --git a/src/core/usage/codex-usage.test.ts b/src/core/usage/codex-usage.test.tsnew file mode 100644index 000000000..8b3b777ee--- /dev/null+++ b/src/core/usage/codex-usage.test.ts@@ -0,0 +1,161 @@+import { describe, it, expect } from 'vitest'+import { mapCodexWindow, mapCodexLimits, readCodexAuth, codexHome } from './codex-usage'+import { primaryLimit, limitShortLabel } from '../../shared/usage-limits'+import fs from 'fs'+import os from 'os'+import path from 'path'++/**+ * The ChatGPT backend's `wham/usage` rate_limit block, matching Codex's own+ * RateLimitStatusPayload: `used_percent`, `limit_window_seconds` (the bucket's real duration)+ * and `reset_at` as Unix SECONDS.+ *+ * NOTE: unlike the Claude fixtures, this was NOT captured from a live account — no Codex+ * install or credentials were available on the machine this was written on. It follows the+ * field contract Codex's client uses; the numbers are illustrative.+ */+const BACKEND_RATE_LIMIT = {+ primary_window: { used_percent: 42.5, limit_window_seconds: 18_000, reset_at: 1_784_436_069 },+ secondary_window: { used_percent: 71, limit_window_seconds: 604_800, reset_at: 1_784_800_000 }+}++/** The app-server JSON-RPC shape: same facts, camelCase keys. */+const RPC_RATE_LIMITS = {+ primary: { usedPercent: 42.5, limitWindowSeconds: 18_000, resetsAt: 1_784_436_069 },+ secondary: { usedPercent: 71, limitWindowSeconds: 604_800, resetsAt: 1_784_800_000 }+}++describe('mapCodexLimits', () => {+ it('maps the backend snake_case payload', () => {+ const limits = mapCodexLimits(BACKEND_RATE_LIMIT)+ expect(limits.map((l) => l.kind)).toEqual(['session', 'weekly_all'])+ expect(limits[0].usedPercent).toBe(42.5)+ expect(limits[1].usedPercent).toBe(71)+ })++ it('maps the app-server camelCase payload identically', () => {+ // Both transports must normalize to the same thing, or which tier answered would leak+ // into the UI as a different-looking row.+ expect(mapCodexLimits(RPC_RATE_LIMITS)).toEqual(mapCodexLimits(BACKEND_RATE_LIMIT))+ })++ it('promotes Unix-seconds reset stamps to ms', () => {+ // Codex sends seconds; rendering them raw would put every reset in January 1970.+ expect(mapCodexLimits(BACKEND_RATE_LIMIT)[0].resetsAt).toBe(1_784_436_069_000)+ })++ it('takes the window duration from the payload, not from position', () => {+ // 18000s = 5h, 604800s = 7d.+ const limits = mapCodexLimits(BACKEND_RATE_LIMIT)+ expect(limits[0].windowMinutes).toBe(300)+ expect(limits[1].windowMinutes).toBe(10_080)+ })++ it('honours a non-standard bucket duration instead of assuming 5h', () => {+ // The backend varies this by plan; labelling a 7h window "5h" would be a lie.+ const limits = mapCodexLimits({+ primary_window: { used_percent: 10, limit_window_seconds: 25_200 }+ })+ expect(limits[0].windowMinutes).toBe(420)+ })++ it('rounds a partial minute up, matching Codex window_minutes_from_seconds', () => {+ const limits = mapCodexLimits({ primary_window: { used_percent: 1, limit_window_seconds: 90 } })+ expect(limits[0].windowMinutes).toBe(2)+ })++ it('falls back to the standard durations when the payload omits them', () => {+ const limits = mapCodexLimits({+ primary_window: { used_percent: 5 },+ secondary_window: { used_percent: 6 }+ })+ expect(limits[0].windowMinutes).toBe(300)+ expect(limits[1].windowMinutes).toBe(10_080)+ })++ it('reports NO severity so the bar falls back to percentage thresholds', () => {+ // Codex ships no severity. Defaulting it to 'normal' would paint an exhausted window green.+ for (const l of mapCodexLimits(BACKEND_RATE_LIMIT)) expect(l.severity).toBeNull()+ })++ it('drops a window with no usable percentage rather than emitting NaN', () => {+ const limits = mapCodexLimits({+ primary_window: { limit_window_seconds: 18_000 },+ secondary_window: { used_percent: 50 }+ })+ expect(limits).toHaveLength(1)+ expect(limits[0].kind).toBe('weekly_all')+ })++ it('clamps out-of-range percentages', () => {+ expect(mapCodexLimits({ primary_window: { used_percent: 130 } })[0].usedPercent).toBe(100)+ expect(mapCodexLimits({ primary_window: { used_percent: -5 } })[0].usedPercent).toBe(0)+ })++ it('returns nothing for a junk block', () => {+ expect(mapCodexLimits(null)).toEqual([])+ expect(mapCodexLimits('nope')).toEqual([])+ expect(mapCodexLimits({})).toEqual([])+ })+})++describe('mapCodexWindow', () => {+ it('marks no window as gating, since Codex does not say', () => {+ const l = mapCodexWindow({ used_percent: 99 }, 'session', 'session', 300)+ expect(l?.isActive).toBe(false)+ })++ it('carries no scope label — Codex has no per-model caps', () => {+ const l = mapCodexWindow({ used_percent: 10 }, 'session', 'session', 300)+ expect(l?.scopeLabel).toBeNull()+ })+})++describe('shared helpers over Codex limits', () => {+ it('picks the worst window, since none is flagged active', () => {+ const picked = primaryLimit(mapCodexLimits(BACKEND_RATE_LIMIT))+ expect(picked?.kind).toBe('weekly_all')+ expect(picked?.usedPercent).toBe(71)+ })++ it('labels Codex windows with the same vocabulary as Claude', () => {+ const limits = mapCodexLimits(BACKEND_RATE_LIMIT)+ expect(limitShortLabel(limits[0].kind, limits[0].scopeLabel)).toBe('5h')+ expect(limitShortLabel(limits[1].kind, limits[1].scopeLabel)).toBe('wk')+ })+})++describe('readCodexAuth', () => {+ it('reads the access token and account id', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-auth-'))+ fs.writeFileSync(+ path.join(dir, 'auth.json'),+ JSON.stringify({ tokens: { access_token: 'tok-abc', account_id: 'acct-1' } })+ )+ await expect(readCodexAuth(dir)).resolves.toEqual({+ accessToken: 'tok-abc',+ accountId: 'acct-1'+ })+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('returns nulls for a missing or malformed file rather than throwing', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-auth-'))+ await expect(readCodexAuth(dir)).resolves.toEqual({ accessToken: null, accountId: null })+ fs.writeFileSync(path.join(dir, 'auth.json'), 'not json')+ await expect(readCodexAuth(dir)).resolves.toEqual({ accessToken: null, accountId: null })+ fs.rmSync(dir, { recursive: true, force: true })+ })+})++describe('codexHome', () => {+ it('honours CODEX_HOME over the default', () => {+ const prev = process.env.CODEX_HOME+ process.env.CODEX_HOME = '/tmp/custom-codex'+ expect(codexHome()).toBe('/tmp/custom-codex')+ process.env.CODEX_HOME = ''+ expect(codexHome()).toBe(path.join(os.homedir(), '.codex'))+ if (prev === undefined) delete process.env.CODEX_HOME+ else process.env.CODEX_HOME = prev+ })+})diff --git a/src/core/usage/codex-usage.ts b/src/core/usage/codex-usage.tsnew file mode 100644index 000000000..2e45a07a3--- /dev/null+++ b/src/core/usage/codex-usage.ts@@ -0,0 +1,245 @@+// Codex (ChatGPT) subscription usage. Two independent sources, tried in order:+//+// 1. The ChatGPT backend endpoint Codex itself reads (`backend-client`'s+// `get_rate_limit_status`). Cheap: one HTTPS request with the token already on disk.+// 2. The `codex app-server` JSON-RPC surface. Costs a subprocess, so it is only a fallback —+// but it is the one that works when the backend contract shifts under us.+//+// A third tier (driving the interactive CLI in a PTY) is deliberately NOT here; see the note on+// `fetchCodexUsage` below.+//+// Read-only, like the Claude provider: we never write or refresh `auth.json`. The Codex CLI+// rotates those tokens itself, and rewriting the file would log out a live `codex` session.+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import { spawn } from 'child_process'+import type { ProviderUsage, UsageLimit } from '../../shared/types'+import { parseResetTimestamp } from './claude-usage-map'++const BACKEND_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage'+const FETCH_TIMEOUT_MS = 8000+const APP_SERVER_TIMEOUT_MS = 10_000++/** Fallback bucket durations, used only when the backend omits `limit_window_seconds`. */+const PRIMARY_WINDOW_MINUTES = 300 // 5h+const SECONDARY_WINDOW_MINUTES = 10_080 // 7d++/** `~/.codex`, or `$CODEX_HOME` when the user has relocated it. */+export function codexHome(): string {+ return process.env.CODEX_HOME?.trim() || path.join(os.homedir(), '.codex')+}++interface CodexAuth {+ accessToken: string | null+ accountId: string | null+}++/** Read the access token Codex stores after `codex login`. Never written back. */+export async function readCodexAuth(home = codexHome()): Promise<CodexAuth> {+ try {+ const raw = await fs.readFile(path.join(home, 'auth.json'), 'utf-8')+ const j = JSON.parse(raw) as Record<string, any>+ const tokens = j.tokens as Record<string, any> | undefined+ return {+ accessToken: typeof tokens?.access_token === 'string' ? tokens.access_token : null,+ accountId: typeof tokens?.account_id === 'string' ? tokens.account_id : null+ }+ } catch {+ return { accessToken: null, accountId: null }+ }+}++function clampPercent(v: unknown): number | null {+ if (typeof v !== 'number' || !Number.isFinite(v)) return null+ return Math.min(100, Math.max(0, v))+}++/**+ * Map one Codex rate-limit window. `limit_window_seconds` is the bucket's REAL duration and the+ * backend varies it by plan, so it wins over the caller's fallback — labelling a 7h window "5h"+ * because of its position in the payload would be a lie. Rounds partial minutes up, matching+ * Codex's own `window_minutes_from_seconds`.+ */+export function mapCodexWindow(+ raw: unknown,+ kind: string,+ group: string,+ fallbackWindowMinutes: number+): UsageLimit | null {+ if (!raw || typeof raw !== 'object') return null+ const w = raw as Record<string, any>+ const usedPercent = clampPercent(w.used_percent ?? w.usedPercent)+ if (usedPercent === null) return null++ const seconds = w.limit_window_seconds ?? w.limitWindowSeconds+ const windowMinutes =+ typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0+ ? Math.ceil(seconds / 60)+ : fallbackWindowMinutes++ return {+ kind,+ group,+ usedPercent,+ // Codex reports no severity — leave it to the local percentage thresholds. Defaulting to+ // 'normal' here would paint an exhausted Codex window green.+ severity: null,+ // Codex sends `reset_at` as Unix SECONDS; parseResetTimestamp promotes those to ms.+ resetsAt: parseResetTimestamp(w.reset_at ?? w.resetsAt),+ windowMinutes,+ scopeLabel: null,+ // Codex flags no "currently gating" window; the UI falls back to worst-percentage.+ isActive: false+ }+}++/** Normalize either transport's payload — the backend and app-server shapes differ only in case. */+export function mapCodexLimits(rateLimit: unknown): UsageLimit[] {+ if (!rateLimit || typeof rateLimit !== 'object') return []+ const r = rateLimit as Record<string, any>+ const primary = r.primary_window ?? r.primary+ const secondary = r.secondary_window ?? r.secondary+ return [+ mapCodexWindow(primary, 'session', 'session', PRIMARY_WINDOW_MINUTES),+ mapCodexWindow(secondary, 'weekly_all', 'weekly', SECONDARY_WINDOW_MINUTES)+ ].filter((l): l is UsageLimit => l !== null)+}++function snapshot(limits: UsageLimit[], status: ProviderUsage['status']): ProviderUsage {+ return { provider: 'codex', limits, account: null, updatedAt: Date.now(), status }+}++/** Tier 1: the endpoint the Codex CLI itself reads. */+async function fetchViaBackend(home: string): Promise<ProviderUsage | null> {+ const { accessToken, accountId } = await readCodexAuth(home)+ if (!accessToken) return null++ const headers: Record<string, string> = {+ authorization: `Bearer ${accessToken}`,+ // Codex's own client identity. The backend gates on these, so they are not decoration.+ 'user-agent': 'codex-cli',+ 'openai-beta': 'codex-1',+ originator: 'Codex Desktop'+ }+ if (accountId) headers['chatgpt-account-id'] = accountId++ const ctrl = new AbortController()+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)+ const res = await fetch(BACKEND_USAGE_URL, { signal: ctrl.signal, headers }).finally(() =>+ clearTimeout(t)+ )+ if (!res.ok) return null++ const payload = (await res.json()) as Record<string, any>+ // `plan_type` is required by Codex's own RateLimitStatusPayload. Without it we are looking at+ // something else that merely returned 200 (a captive portal, an error envelope) — reject so+ // the app-server tier still gets its turn instead of reporting a confidently empty snapshot.+ if (typeof payload.plan_type !== 'string') return null++ return snapshot(mapCodexLimits(payload.rate_limit), 'ok')+}++/**+ * Tier 2: `codex app-server` speaks JSON-RPC over stdio. Costs a subprocess, so it runs only+ * when the backend tier declined. Sandboxed read-only/untrusted — this must never be a way for+ * a quota refresh to touch the user's files.+ */+async function fetchViaAppServer(home: string): Promise<ProviderUsage | null> {+ return new Promise<ProviderUsage | null>((resolve) => {+ let child: ReturnType<typeof spawn>+ try {+ child = spawn('codex', ['-s', 'read-only', '-a', 'untrusted', 'app-server'], {+ env: { ...process.env, CODEX_HOME: home },+ stdio: ['pipe', 'pipe', 'ignore']+ })+ } catch {+ resolve(null)+ return+ }++ let settled = false+ const finish = (v: ProviderUsage | null): void => {+ if (settled) return+ settled = true+ try {+ child.kill()+ } catch {+ // already gone+ }+ resolve(v)+ }++ const timer = setTimeout(() => finish(null), APP_SERVER_TIMEOUT_MS)+ timer.unref?.()++ // A missing `codex` binary surfaces here, not as a spawn throw.+ child.on('error', () => finish(null))+ child.on('exit', () => finish(null))++ let buf = ''+ child.stdout?.on('data', (chunk: Buffer) => {+ buf += chunk.toString()+ // Line-delimited JSON-RPC; a partial trailing line stays in the buffer.+ const lines = buf.split('\n')+ buf = lines.pop() ?? ''+ for (const line of lines) {+ if (!line.trim()) continue+ let msg: Record<string, any>+ try {+ msg = JSON.parse(line)+ } catch {+ continue+ }+ if (msg.id === 1) {+ // initialize acked → announce, then ask for the limits.+ child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', method: 'initialized' }) + '\n')+ child.stdin?.write(+ JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'account/rateLimits/read' }) + '\n'+ )+ } else if (msg.id === 2) {+ const limits = mapCodexLimits(msg.result?.rateLimits)+ finish(limits.length > 0 ? snapshot(limits, 'ok') : null)+ }+ }+ })++ child.stdin?.write(+ JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: { clientInfo: { name: 'nodeterm', version: '1' } }+ }) + '\n'+ )+ })+}++/**+ * Codex usage, backend first and app-server second.+ *+ * No PTY tier. Orca has one — it drives the interactive CLI and scrapes the TUI — and it exists+ * mainly to serve users whose auth the HTTP path cannot use. Adding it here means owning hidden+ * PTY lifecycle and screen-scraping regexes, and Claude needs the same machinery for the same+ * reason, so it belongs in one shared piece of work rather than being written twice.+ *+ * Never rejects: an unreachable backend and a missing CLI are both "we don't know", and the+ * caller renders that as no data rather than an error the user can't act on.+ */+export async function fetchCodexUsage(home = codexHome()): Promise<ProviderUsage> {+ try {+ const viaBackend = await fetchViaBackend(home)+ if (viaBackend) return viaBackend+ } catch {+ // fall through to the app-server tier+ }+ try {+ const viaAppServer = await fetchViaAppServer(home)+ if (viaAppServer) return viaAppServer+ } catch {+ // fall through to 'unavailable'+ }+ // Not signed in, no CLI, or both transports declined — nothing to show, same as Claude on+ // API-key billing. 'unavailable' hides the provider rather than showing a broken row.+ return snapshot([], 'unavailable')+}diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.tsindex 30e3afaad..68487f66d 100644--- a/src/core/usage/usage-service.ts+++ b/src/core/usage/usage-service.ts@@ -11,9 +11,15 @@ import path from 'path'import { execFile } from 'child_process'import { promisify } from 'util'import { IPC } from '../../shared/ipc'-import type { ClaudeUsage, ClaudeUsageWindow, UsageLimit } from '../../shared/types'+import type {+ ClaudeUsage,+ ClaudeUsageWindow,+ ProviderUsage,+ UsageLimit+} from '../../shared/types'import { findLimit } from '../../shared/usage-limits'import { mapUsageLimits } from './claude-usage-map'+import { fetchCodexUsage } from './codex-usage'import { usageCredsPaths } from '../claude-accounts-core'import { claudeConfigDirFor } from '../claude-config-dir'import { platform } from '../platform'@@ -32,6 +38,15 @@ interface OAuthCreds {email: string | null}+/**+ * Providers other than Claude. Claude keeps its own channels because it alone is account-aware+ * (managed config dirs, a per-account popover row); everything else answers one snapshot.+ * Adding a provider is one entry here plus its fetcher — no changes to the service or the UI.+ */+const OTHER_PROVIDERS: { id: string; fetch: () => Promise<ProviderUsage> }[] = [+ { id: 'codex', fetch: fetchCodexUsage }+]+/** Parse a credentials JSON blob; tokens may sit at top level or under `claudeAiOauth`. */export function parseCreds(raw: string): OAuthCreds {try {@@ -221,6 +236,46 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService})platform().handle(IPC.usageRefresh, (accountId?: string) => run(accountId))+ // Non-Claude providers. Fetched on demand (when the popover opens) rather than polled: each+ // one costs its own network round-trip — and, on the app-server fallback, a subprocess — so+ // polling them all on the Claude cadence would multiply that cost for data nobody is looking+ // at. Cached under the same debounce.+ let providersAt = 0+ let providersCache: ProviderUsage[] = []+ let providersInFlight: Promise<ProviderUsage[]> | null = null++ const runProviders = async (): Promise<ProviderUsage[]> => {+ if (providersInFlight) return providersInFlight+ // One slow provider must not withhold the others — settle each independently.+ providersInFlight = Promise.all(+ OTHER_PROVIDERS.map((p) =>+ p.fetch().catch(+ (): ProviderUsage => ({+ provider: p.id,+ limits: [],+ account: null,+ updatedAt: Date.now(),+ status: 'error'+ })+ )+ )+ )+ try {+ providersCache = await providersInFlight+ providersAt = Date.now()+ return providersCache+ } finally {+ providersInFlight = null+ }+ }++ platform().handle(IPC.usageProviders, (force?: boolean) => {+ if (!force && providersAt && Date.now() - providersAt < REFETCH_DEBOUNCE_MS) {+ return providersCache+ }+ return runProviders()+ })+// The warm-up fetch goes through the same gate as the poll: it IS a poll, just the first one.// On desktop a focused window warms the cache before the pill mounts; on the server, boot// happens with no browser attached, so this correctly does nothing until someone connectsdiff --git a/src/preload/index.ts b/src/preload/index.tsindex 6c507cfd7..59bb78fe2 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -323,6 +323,7 @@ const api: NodeTerminalApi = {usage: {fetch: (accountId?: string) => ipcRenderer.invoke(IPC.usageFetch, accountId),refresh: (accountId?: string) => ipcRenderer.invoke(IPC.usageRefresh, accountId),+ providers: (force?: boolean) => ipcRenderer.invoke(IPC.usageProviders, force),onUpdate: (listener) => {const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)ipcRenderer.on(IPC.usageUpdate, handler)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 1836f6970..fccf0f468 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -224,6 +224,9 @@ export function buildStubApi(): Omit<// `Promise<ClaudeUsage | null>`, a public-API change tracked separately.fetch: (): Promise<ClaudeUsage> => Promise.resolve(null as unknown as ClaudeUsage),refresh: U('usage.refresh'),+ // Empty, not a reject: "no providers configured" is a real answer and the popover+ // renders it as nothing. This one needs no cast — the honest type already fits.+ providers: () => Promise.resolve([]),onUpdate: noopUnsub},claude: {diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex c22891fdf..82dfb915b 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -28,6 +28,7 @@ import {type PtyCreateOptions,type SettingsApi,type ClaudeUsage,+ type ProviderUsage,type Settings,type SpeechApi,type SpeechModelInfo,@@ -482,6 +483,8 @@ function buildUsageApi(client: RpcClient): Pick<NodeTerminalApi, 'usage'> {client.request(IPC.usageFetch, accountId) as Promise<ClaudeUsage>,refresh: (accountId?: string) =>client.request(IPC.usageRefresh, accountId) as Promise<ClaudeUsage>,+ providers: (force?: boolean) =>+ client.request(IPC.usageProviders, force) as Promise<ProviderUsage[]>,onUpdate: (listener) => client.subscribe(IPC.usageUpdate, listener as Listener)}}diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsxindex 698b55592..d0cfd5383 100644--- a/src/renderer/components/UsageIndicator.tsx+++ b/src/renderer/components/UsageIndicator.tsx@@ -1,5 +1,6 @@import { useEffect, useMemo, useRef, useState } from 'react'-import type { ClaudeUsage, UsageLimit } from '@shared/types'+import type { ClaudeUsage, ProviderUsage, UsageLimit } from '@shared/types'+import { AGENT_CONFIG } from '@shared/agents/config'import { useSettings } from '../state/settings'import { formatResetCountdown, formatTimeAgo, severityColor } from '../lib/usageFormat'import { limitKey, limitLabel, limitShortLabel, primaryLimit } from '@shared/usage-limits'@@ -50,6 +51,33 @@ function AccountUsageBlock({ label, email, u }: { label: string; email?: string;)}+/**+ * One non-Claude provider's section in the popover. Providers that aren't signed in report+ * 'unavailable' and are skipped entirely — showing an empty Codex row to someone who has never+ * run Codex is noise, not information. An 'error' provider IS shown, because that is a+ * configured provider failing and hiding it would make the popover flap between refreshes.+ */+function ProviderBlock({ u }: { u: ProviderUsage }) {+ if (u.status === 'unavailable') return null+ // AGENT_CONFIG is keyed by the builtin ids; `provider` is an open string, so a provider that+ // is not a builtin agent (a billing-only one) falls back to its own id rather than blanking.+ const label = (AGENT_CONFIG as Record<string, { label?: string } | undefined>)[u.provider]?.label ?? u.provider+ return (+ <div className="usage-account">+ <div className="usage-account__label">{label}</div>+ {u.account && <div className="usage-account__email">{u.account}</div>}+ {u.limits.map((l) => (+ <LimitRow key={limitKey(l)} limit={l} />+ ))}+ {u.limits.length === 0 && (+ <div className="usage-popover__empty">+ {u.status === 'error' ? 'Could not read usage.' : 'No usage data.'}+ </div>+ )}+ </div>+ )+}+/*** Bottom-left Claude usage pill + popover. Renders to the right of the React Flow Controls.* States: hidden when 'unavailable'; '···' while first-fetching; '⚠' on error w/o data;@@ -61,6 +89,7 @@ export function UsageIndicator(): JSX.Element | null {const [open, setOpen] = useState(false)const [refreshing, setRefreshing] = useState(false)const [acctUsage, setAcctUsage] = useState<Record<string, ClaudeUsage | null>>({})+ const [providers, setProviders] = useState<ProviderUsage[]>([])const popRef = useRef<HTMLDivElement>(null)const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)@@ -76,6 +105,19 @@ export function UsageIndicator(): JSX.Element | null {return window.nodeTerminal.usage.onUpdate(setUsage)}, [])+ // Other providers are fetched only while the popover is open — each costs a network call (and+ // possibly a subprocess), so polling them for a collapsed pill would spend that for nothing.+ useEffect(() => {+ if (!open) return+ let cancelled = false+ void window.nodeTerminal.usage.providers().then((ps) => {+ if (!cancelled) setProviders(ps)+ })+ return () => {+ cancelled = true+ }+ }, [open])+// Fetch each account's usage on demand when the popover opens (system row uses `usage`).useEffect(() => {if (!open || accounts.length === 0) return@@ -187,6 +229,9 @@ export function UsageIndicator(): JSX.Element | null {)}</>)}+ {providers.map((p) => (+ <ProviderBlock key={p.provider} u={p} />+ ))}</div>)}<button className="usage-pill" onClick={() => setOpen((v) => !v)} title="Claude usage">diff --git a/src/renderer/lib/usageFormat.ts b/src/renderer/lib/usageFormat.tsindex 5d17ebb0a..254541c95 100644--- a/src/renderer/lib/usageFormat.ts+++ b/src/renderer/lib/usageFormat.ts@@ -52,12 +52,12 @@ export function barColor(leftPercent: number): string {}/**- * Bar color for a usage limit. The server ships its own `severity` verdict, which knows the+ * Bar color for a usage limit. A provider that ships its own `severity` verdict knows the* account's plan and how close the window really is to biting — prefer it, and fall back to- * our own percentage thresholds only for a severity we don't recognize (or a legacy payload- * that never carried one).+ * our own percentage thresholds when it is null (most providers report none) or a value we+ * don't recognize.*/-export function severityColor(severity: string, leftPercent: number): string {+export function severityColor(severity: string | null, leftPercent: number): string {switch (severity) {case 'normal':return '#30d158'diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 84daf0f12..6341d930c 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -73,6 +73,8 @@ export const IPC = {usageFetch: 'usage:fetch',usageRefresh: 'usage:refresh',usageUpdate: 'usage:update',+ /** Non-Claude providers (codex, …) as one list; Claude keeps its own account-aware channels. */+ usageProviders: 'usage:providers',contextUpdate: 'context:update',contextEnsure: 'context:ensure',// Team presence (docs/team-presence.md). `presence:hello` is a REQUEST: its response tells thediff --git a/src/shared/types.ts b/src/shared/types.tsindex 5709688d8..77d51184e 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -929,27 +929,59 @@ export interface ClaudeUsageWindow {}/**- * One entry from the usage endpoint's `limits[]` array — the current, open-ended contract.- * A per-model quota (Fable's weekly cap, say) is an ordinary entry whose model name rides in- * `scopeLabel`, so a new model needs no new field here. Percentages are portions USED, which- * is the server's own convention; the UI inverts for display where it shows "left".+ * One usage window, normalized across providers. Claude's endpoint hands these over directly+ * as its open-ended `limits[]` array — a per-model quota (Fable's weekly cap, say) is an+ * ordinary entry whose model name rides in `scopeLabel`, so a new model needs no new field.+ * Other providers (Codex's primary/secondary windows, …) are mapped into the same shape.+ *+ * Percentages are portions USED, which is the providers' own convention; the UI inverts for+ * display where it shows "left".*/export interface UsageLimit {- /** Server-assigned kind: 'session' | 'weekly_all' | 'weekly_scoped' | future values. */+ /** Provider-assigned kind: 'session' | 'weekly_all' | 'weekly_scoped' | future values. */kind: string- /** Coarse grouping ('session' | 'weekly'), or null when the server omits it. */+ /** Coarse grouping ('session' | 'weekly'), or null when the provider omits it. */group: string | null/** 0–100, portion consumed. */usedPercent: number- /** Server's severity call ('normal' | 'warning' | …). Drives colour; not derived locally. */- severity: string+ /**+ * The provider's own severity call ('normal' | 'warning' | 'critical' | …), or **null when+ * the provider does not report one** — which is the common case (only Claude does today).+ * Null means "derive from the percentage locally"; it must NOT be defaulted to 'normal',+ * or every provider without severity would paint a permanently green bar.+ */+ severity: string | nullresetsAt: number | null+ /**+ * The bucket's real duration in minutes, when the provider reports it (Codex sends+ * `limit_window_seconds`), else null. Providers can and do vary this per plan, so labelling+ * a window "5h" from its `kind` alone can be a lie.+ */+ windowMinutes: number | null/** Model display name for a scoped limit (e.g. 'Fable'), else null. */scopeLabel: string | null- /** Server says this window is the one currently gating the account. */+ /** The provider says this window is the one currently gating the account. */isActive: boolean}+/**+ * One provider's usage snapshot. `ClaudeUsage` below is the Claude-shaped superset kept for the+ * existing pill; new providers use this leaner shape (they have no per-account story yet).+ */+export interface ProviderUsage {+ /** Agent id the limits belong to: 'claude' | 'codex' | … */+ provider: string+ limits: UsageLimit[]+ /** Signed-in identity, when the provider exposes one cheaply (email / account label). */+ account: string | null+ updatedAt: number+ /**+ * 'unavailable' = not signed in / no subscription to report → hide this provider entirely.+ * 'fetching' = request in flight. 'ok' = limits present. 'error' = the fetch failed.+ */+ status: 'unavailable' | 'fetching' | 'ok' | 'error'+}+/** Claude Code subscription usage snapshot for the bottom-left indicator. */export interface ClaudeUsage {/**@@ -976,6 +1008,10 @@ export interface UsageApi {fetch(accountId?: string): Promise<ClaudeUsage>/** Forces a fresh fetch, bypassing the focus debounce. Optional account id as `fetch`. */refresh(accountId?: string): Promise<ClaudeUsage>+ /** Snapshots for every non-Claude provider (codex, …). Fetched on demand, not polled — pass+ * `force` to bypass the cache debounce. Providers that aren't signed in come back+ * 'unavailable' rather than being omitted, so the caller can tell "off" from "broken". */+ providers(force?: boolean): Promise<ProviderUsage[]>/** Fires whenever main pushes a new snapshot (poll/refresh). Returns unsubscribe. */onUpdate(listener: (usage: ClaudeUsage) => void): () => void}diff --git a/src/shared/usage-limits.test.ts b/src/shared/usage-limits.test.tsindex ffea9b101..130e13794 100644--- a/src/shared/usage-limits.test.ts+++ b/src/shared/usage-limits.test.ts@@ -9,6 +9,7 @@ function limit(over: Partial<UsageLimit>): UsageLimit {usedPercent: 0,severity: 'normal',resetsAt: null,+ windowMinutes: null,scopeLabel: null,isActive: false,...over