Skip to content

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.

feat(usage): read the generic limits[] contract, surfacing scoped model caps (#6)

eneskirca85ccf4a96135
diff --git a/src/core/usage/claude-usage-map.test.ts b/src/core/usage/claude-usage-map.test.ts
new file mode 100644
index 000000000..09bdefa42
--- /dev/null
+++ b/src/core/usage/claude-usage-map.test.ts
@@ -0,0 +1,157 @@
+import { describe, it, expect } from 'vitest'
+import { mapUsageLimits, parseResetTimestamp } from './claude-usage-map'
+import { findLimit, limitLabel, limitShortLabel } from '../../shared/usage-limits'
+
+/**
+ * Captured verbatim from a live GET /api/oauth/usage on a Max (default_claude_max_5x) account,
+ * trimmed to the fields we read. Two things it pins down: the per-model top-level windows
+ * (`seven_day_opus` & co.) are dead — always null — and the real per-model quota now arrives as
+ * a `weekly_scoped` entry in `limits[]` whose model rides in `scope.model.display_name`.
+ */
+const LIVE_PAYLOAD = {
+ five_hour: { utilization: 7.0, resets_at: '2026-07-19T04:09:59.841272+00:00' },
+ seven_day: { utilization: 61.0, resets_at: '2026-07-20T21:59:59.841297+00:00' },
+ seven_day_opus: null,
+ seven_day_sonnet: null,
+ limits: [
+ {
+ kind: 'session',
+ group: 'session',
+ percent: 7,
+ severity: 'normal',
+ resets_at: '2026-07-19T04:09:59.841272+00:00',
+ scope: null,
+ is_active: false
+ },
+ {
+ kind: 'weekly_all',
+ group: 'weekly',
+ percent: 61,
+ severity: 'normal',
+ resets_at: '2026-07-20T21:59:59.841297+00:00',
+ scope: null,
+ is_active: false
+ },
+ {
+ kind: 'weekly_scoped',
+ group: 'weekly',
+ percent: 87,
+ severity: 'warning',
+ resets_at: '2026-07-20T21:59:59.841724+00:00',
+ scope: { model: { id: null, display_name: 'Fable' }, surface: null },
+ is_active: true
+ }
+ ]
+}
+
+describe('mapUsageLimits', () => {
+ it('maps every limit from the live payload, including the scoped model quota', () => {
+ const limits = mapUsageLimits(LIVE_PAYLOAD)
+ expect(limits).toHaveLength(3)
+
+ const fable = limits.find((l) => l.scopeLabel === 'Fable')
+ expect(fable).toMatchObject({
+ kind: 'weekly_scoped',
+ group: 'weekly',
+ usedPercent: 87,
+ severity: 'warning',
+ scopeLabel: 'Fable',
+ isActive: true
+ })
+ })
+
+ it('keeps percentages as USED, not remaining', () => {
+ const limits = mapUsageLimits(LIVE_PAYLOAD)
+ expect(findLimit(limits, 'session')?.usedPercent).toBe(7)
+ expect(findLimit(limits, 'weekly_all')?.usedPercent).toBe(61)
+ })
+
+ it('carries an unrecognized future kind through instead of dropping it', () => {
+ // The whole point of limits[]: a kind we have never seen must still reach the UI.
+ const limits = mapUsageLimits({
+ limits: [{ kind: 'monthly_surface', percent: 42, resets_at: null }]
+ })
+ expect(limits).toHaveLength(1)
+ expect(limits[0].kind).toBe('monthly_surface')
+ expect(limits[0].usedPercent).toBe(42)
+ expect(limitLabel(limits[0].kind, null)).toBe('Monthly Surface')
+ })
+
+ it('surfaces a scoped limit for a model that does not exist yet', () => {
+ // Regression guard against re-introducing a hardcoded `fable` slot: any model name works.
+ const limits = mapUsageLimits({
+ limits: [
+ {
+ kind: 'weekly_scoped',
+ percent: 12,
+ scope: { model: { display_name: 'Mythos' } },
+ is_active: true
+ }
+ ]
+ })
+ expect(limits[0].scopeLabel).toBe('Mythos')
+ expect(limitShortLabel(limits[0].kind, limits[0].scopeLabel)).toBe('Mythos')
+ })
+
+ it('falls back to legacy fixed windows when limits[] is absent', () => {
+ const limits = mapUsageLimits({
+ five_hour: { utilization: 20, resets_at: '2026-07-19T04:09:59Z' },
+ seven_day: { utilization: 55, resets_at: '2026-07-20T21:59:59Z' }
+ })
+ expect(limits.map((l) => l.kind)).toEqual(['session', 'weekly_all'])
+ expect(limits[0].usedPercent).toBe(20)
+ })
+
+ it('falls back to legacy windows when limits[] is present but empty', () => {
+ const limits = mapUsageLimits({ limits: [], five_hour: { utilization: 20 } })
+ expect(limits).toHaveLength(1)
+ expect(limits[0].kind).toBe('session')
+ })
+
+ it('skips malformed entries rather than emitting NaN percentages', () => {
+ const limits = mapUsageLimits({
+ limits: [
+ { kind: 'session', percent: 'lots' },
+ { kind: null, percent: 10 },
+ { kind: 'weekly_all', percent: 30 }
+ ]
+ })
+ expect(limits).toHaveLength(1)
+ expect(limits[0].kind).toBe('weekly_all')
+ })
+
+ it('clamps out-of-range percentages', () => {
+ const limits = mapUsageLimits({ limits: [{ kind: 'session', percent: 140 }] })
+ expect(limits[0].usedPercent).toBe(100)
+ })
+
+ it('treats a missing is_active as unknown, not active', () => {
+ const limits = mapUsageLimits({ limits: [{ kind: 'session', percent: 10 }] })
+ expect(limits[0].isActive).toBe(false)
+ })
+
+ it('returns nothing for a junk body', () => {
+ expect(mapUsageLimits(null)).toEqual([])
+ expect(mapUsageLimits('nope')).toEqual([])
+ expect(mapUsageLimits({})).toEqual([])
+ })
+})
+
+describe('parseResetTimestamp', () => {
+ it('parses ISO strings', () => {
+ expect(parseResetTimestamp('2026-07-19T04:09:59.841272+00:00')).toBe(
+ Date.parse('2026-07-19T04:09:59.841272+00:00')
+ )
+ })
+
+ it('promotes Unix seconds to ms and leaves ms alone', () => {
+ expect(parseResetTimestamp(1_784_436_069)).toBe(1_784_436_069_000)
+ expect(parseResetTimestamp(1_784_436_069_255)).toBe(1_784_436_069_255)
+ })
+
+ it('returns null for junk', () => {
+ expect(parseResetTimestamp(null)).toBeNull()
+ expect(parseResetTimestamp('')).toBeNull()
+ expect(parseResetTimestamp('not a date')).toBeNull()
+ })
+})
diff --git a/src/core/usage/claude-usage-map.ts b/src/core/usage/claude-usage-map.ts
new file mode 100644
index 000000000..7402392d5
--- /dev/null
+++ b/src/core/usage/claude-usage-map.ts
@@ -0,0 +1,100 @@
+// Pure mapping of Anthropic's OAuth usage payload into our normalized limit list.
+// Lives in core (no electron, no fs, no fetch) so both shells share it and it stays unit-tested;
+// the impure token/keychain/HTTP work stays in the shell (main/claude-usage.ts).
+//
+// The payload carries the same facts twice. The legacy shape is a set of fixed top-level
+// windows (`five_hour`, `seven_day`, and the now-always-null `seven_day_opus` /
+// `seven_day_sonnet` / …). The current shape is a generic `limits[]` array where a per-model
+// quota is an ordinary entry carrying `scope.model.display_name`. We prefer `limits[]` and
+// treat the model name as DATA, never as a field name — that is the whole point of the new
+// contract: when the next model ships, its limit arrives as another array entry and this file
+// does not change. Binding a `fableWeekly` slot (or a `seven_day_fable` field) would recreate
+// the exact rigidity Anthropic just moved away from.
+import type { UsageLimit } from '../../shared/types'
+
+/** `percent`/`utilization` are portions USED, 0–100. Clamp — the server is not our validator. */
+function clampPercent(v: unknown): number | null {
+ if (typeof v !== 'number' || !Number.isFinite(v)) return null
+ return Math.min(100, Math.max(0, v))
+}
+
+/**
+ * Reset stamps arrive as ISO strings today, but the same field has been seen as Unix seconds
+ * and Unix ms elsewhere in this API family, so tolerate all three rather than silently
+ * producing "Resets now" on a shape change. The 1e10 cut-off separates seconds from ms
+ * (1e10 s ≈ year 2286, 1e10 ms ≈ 1970) — anything larger is already ms.
+ */
+export function parseResetTimestamp(raw: unknown): number | null {
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
+ return raw > 10_000_000_000 ? raw : raw * 1000
+ }
+ if (typeof raw === 'string') {
+ const trimmed = raw.trim()
+ if (!trimmed) return null
+ return Date.parse(trimmed) || null
+ }
+ return null
+}
+
+function mapLimit(raw: unknown): UsageLimit | null {
+ if (!raw || typeof raw !== 'object') return null
+ const l = raw as Record<string, any>
+ const kind = typeof l.kind === 'string' && l.kind ? l.kind : null
+ const usedPercent = clampPercent(l.percent)
+ if (!kind || usedPercent === null) return null
+
+ const model = l.scope?.model
+ const displayName = typeof model?.display_name === 'string' ? model.display_name.trim() : ''
+
+ return {
+ 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',
+ resetsAt: parseResetTimestamp(l.resets_at),
+ 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.
+ isActive: l.is_active === true
+ }
+}
+
+/**
+ * Fall back to the legacy fixed windows when `limits[]` is absent (older CLI/plan payloads).
+ * Only the two windows that were ever populated are reconstructed; the per-model top-level
+ * fields are dead in current responses and are deliberately not resurrected here.
+ */
+function legacyLimits(data: Record<string, any>): UsageLimit[] {
+ const out: UsageLimit[] = []
+ const add = (raw: unknown, kind: string, group: string): void => {
+ if (!raw || typeof raw !== 'object') return
+ const w = raw as Record<string, any>
+ const usedPercent = clampPercent(w.utilization ?? w.used_percentage)
+ if (usedPercent === null) return
+ out.push({
+ kind,
+ group,
+ usedPercent,
+ severity: 'normal',
+ resetsAt: parseResetTimestamp(w.resets_at),
+ scopeLabel: null,
+ isActive: false
+ })
+ }
+ add(data.five_hour, 'session', 'session')
+ add(data.seven_day, 'weekly_all', 'weekly')
+ return out
+}
+
+/** Normalize a raw `/api/oauth/usage` body into the limit list the UI renders. */
+export function mapUsageLimits(data: unknown): UsageLimit[] {
+ if (!data || typeof data !== 'object') return []
+ const body = data as Record<string, any>
+ if (Array.isArray(body.limits)) {
+ const mapped = body.limits.map(mapLimit).filter((l): l is UsageLimit => l !== null)
+ if (mapped.length > 0) return mapped
+ }
+ return legacyLimits(body)
+}
diff --git a/src/main/claude-usage.ts b/src/main/claude-usage.ts
index c0653f277..71915b4a2 100644
--- a/src/main/claude-usage.ts
+++ b/src/main/claude-usage.ts
@@ -1,6 +1,8 @@
-// Fetches Claude Code subscription usage (session + weekly) from Anthropic's OAuth usage
-// endpoint. Runs in the main process (Node) so the renderer CSP stays 'self' — the renderer
-// asks for the data over IPC. Display-only: we never write credentials or refresh tokens.
+// Fetches Claude Code subscription usage from Anthropic's OAuth usage endpoint — every limit
+// the plan exposes, including per-model scoped caps (Fable's weekly cap and whatever ships
+// next), which arrive as generic `limits[]` entries rather than fixed fields.
+// Runs in the main process (Node) so the renderer CSP stays 'self' — the renderer asks for the
+// data over IPC. Display-only: we never write credentials or refresh tokens.
import { promises as fs } from 'fs'
import os from 'os'
import path from 'path'
@@ -8,7 +10,9 @@ import { execFile } from 'child_process'
import { promisify } from 'util'
import { ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../shared/ipc'
-import type { ClaudeUsage, ClaudeUsageWindow } from '../shared/types'
+import type { ClaudeUsage, ClaudeUsageWindow, UsageLimit } from '../shared/types'
+import { mapUsageLimits } from '../core/usage/claude-usage-map'
+import { findLimit } from '../shared/usage-limits'
import { usageCredsPaths } from '../core/claude-accounts-core'
import { claudeConfigDirFor } from './claude-accounts'
@@ -104,18 +108,25 @@ async function resolveCreds(accountId?: string): Promise<OAuthCreds> {
return creds
}
-function mapWindow(raw: any): ClaudeUsageWindow | null {
- if (!raw || typeof raw.utilization !== 'number') return null
- const leftPercent = Math.min(100, Math.max(0, 100 - raw.utilization))
- const resetsAt = typeof raw.resets_at === 'string' ? Date.parse(raw.resets_at) || null : null
- return { leftPercent, resetsAt }
+/** Back-compat view of one limit as the old remaining-percent window. */
+function asWindow(limit: UsageLimit | null): ClaudeUsageWindow | null {
+ if (!limit) return null
+ return { leftPercent: 100 - limit.usedPercent, resetsAt: limit.resetsAt }
+}
+
+function emptyUsage(
+ email: string | null,
+ now: number,
+ status: ClaudeUsage['status']
+): ClaudeUsage {
+ return { limits: [], session: null, weekly: null, email, updatedAt: now, status }
}
async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {
const now = Date.now()
const { accessToken, email } = await resolveCreds(accountId)
if (!accessToken) {
- return { session: null, weekly: null, email, updatedAt: now, status: 'unavailable' }
+ return emptyUsage(email, now, 'unavailable')
}
try {
const ctrl = new AbortController()
@@ -128,18 +139,20 @@ async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {
if (!res.ok) {
// 401/403 → token is an API key or expired: no subscription windows to show.
const status = res.status === 401 || res.status === 403 ? 'unavailable' : 'error'
- return { session: null, weekly: null, email, updatedAt: now, status }
+ return emptyUsage(email, now, status)
}
const data = (await res.json()) as Record<string, any>
+ const limits = mapUsageLimits(data)
return {
- session: mapWindow(data.five_hour),
- weekly: mapWindow(data.seven_day),
+ limits,
+ session: asWindow(findLimit(limits, 'session')),
+ weekly: asWindow(findLimit(limits, 'weekly_all')),
email,
updatedAt: now,
status: 'ok'
}
} catch {
- return { session: null, weekly: null, email, updatedAt: now, status: 'error' }
+ return emptyUsage(email, now, 'error')
}
}
diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsx
index eba5bda54..698b55592 100644
--- a/src/renderer/components/UsageIndicator.tsx
+++ b/src/renderer/components/UsageIndicator.tsx
@@ -1,41 +1,50 @@
import { useEffect, useMemo, useRef, useState } from 'react'
-import type { ClaudeUsage, ClaudeUsageWindow } from '@shared/types'
+import type { ClaudeUsage, UsageLimit } from '@shared/types'
import { useSettings } from '../state/settings'
-import { barColor, formatResetCountdown, formatTimeAgo } from '../lib/usageFormat'
+import { formatResetCountdown, formatTimeAgo, severityColor } from '../lib/usageFormat'
+import { limitKey, limitLabel, limitShortLabel, primaryLimit } from '@shared/usage-limits'
import { systemAccountDisplay } from '../state/workspace'
-const SESSION_LABEL = '5h'
-const WEEKLY_LABEL = 'wk'
-
-/** A single window row in the popover: bar, "% left", reset countdown. */
-function WindowRow({ title, w }: { title: string; w: ClaudeUsageWindow }) {
- const left = Math.round(w.leftPercent)
+/**
+ * A single limit row in the popover: bar, "% left", reset countdown. Bars render REMAINING
+ * quota (the limit carries percent USED), which is the convention this pill has always used.
+ */
+function LimitRow({ limit }: { limit: UsageLimit }) {
+ const left = 100 - limit.usedPercent
return (
<div className="usage-row">
- <div className="usage-row__title">{title}</div>
+ <div className="usage-row__title">
+ {limitLabel(limit.kind, limit.scopeLabel)}
+ {/* The server flags which window is actually gating the account right now. */}
+ {limit.isActive && <span className="usage-row__active" title="Currently limiting">●</span>}
+ </div>
<div className="usage-bar">
- <div className="usage-bar__fill" style={{ width: `${w.leftPercent}%`, background: barColor(w.leftPercent) }} />
+ <div
+ className="usage-bar__fill"
+ style={{ width: `${left}%`, background: severityColor(limit.severity, left) }}
+ />
</div>
<div className="usage-row__meta">
- <span>{left}% left</span>
- <span>{formatResetCountdown(w.resetsAt)}</span>
+ <span>{Math.round(left)}% left</span>
+ <span>{formatResetCountdown(limit.resetsAt)}</span>
</div>
</div>
)
}
/**
- * One account's session/weekly bars under a label, for the multi-account popover. Reuses
- * WindowRow's markup — `u` is null while its on-demand fetch is in flight.
+ * One account's limit bars under a label, for the multi-account popover. Reuses LimitRow's
+ * markup — `u` is null while its on-demand fetch is in flight.
*/
function AccountUsageBlock({ label, email, u }: { label: string; email?: string; u: ClaudeUsage | null }) {
return (
<div className="usage-account">
<div className="usage-account__label">{label}</div>
{(email ?? u?.email) && <div className="usage-account__email">{email ?? u?.email}</div>}
- {u?.session && <WindowRow title="Session" w={u.session} />}
- {u?.weekly && <WindowRow title="Weekly" w={u.weekly} />}
- {u && !u.session && !u.weekly && <div className="usage-popover__empty">No usage data.</div>}
+ {u?.limits.map((l) => (
+ <LimitRow key={limitKey(l)} limit={l} />
+ ))}
+ {u && u.limits.length === 0 && <div className="usage-popover__empty">No usage data.</div>}
{!u && <div className="usage-popover__empty usage-pill__pulse">···</div>}
</div>
)
@@ -44,7 +53,8 @@ function AccountUsageBlock({ label, email, u }: { label: string; email?: string;
/**
* 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;
- * last-known data shown on stale/error. Compact pill = mini-bar + "62% 5h · 76% wk".
+ * last-known data shown on stale/error. Compact pill = mini-bar + one "N% label" per limit,
+ * e.g. "93% 5h · 39% wk · 13% Fable" — the bar tracks whichever limit is closest to biting.
*/
export function UsageIndicator(): JSX.Element | null {
const [usage, setUsage] = useState<ClaudeUsage | null>(null)
@@ -92,10 +102,13 @@ export function UsageIndicator(): JSX.Element | null {
if (!usage || usage.status === 'unavailable') return null
- const { session, weekly, status } = usage
- const hasData = !!session || !!weekly
+ const { limits, status } = usage
+ const hasData = limits.length > 0
const fetching = refreshing
const isError = status === 'error'
+ // The pill leads with whatever is closest to biting, so a scoped model cap that is nearly
+ // exhausted can't hide behind a comfortable 5h window.
+ const primary = primaryLimit(limits)
const refresh = async (e: React.MouseEvent): Promise<void> => {
e.stopPropagation()
@@ -116,25 +129,25 @@ export function UsageIndicator(): JSX.Element | null {
} else {
pillBody = (
<>
- {session && (
+ {primary && (
<span className="usage-pill__minibar" aria-hidden>
<span
className="usage-pill__minibar-fill"
- style={{ width: `${session.leftPercent}%`, background: barColor(session.leftPercent) }}
+ style={{
+ width: `${100 - primary.usedPercent}%`,
+ background: severityColor(primary.severity, 100 - primary.usedPercent)
+ }}
/>
</span>
)}
- {session && (
- <span className="usage-pill__num">
- {Math.round(session.leftPercent)}% {SESSION_LABEL}
+ {limits.map((l, i) => (
+ <span key={limitKey(l)}>
+ {i > 0 && <span className="usage-pill__sep">·</span>}
+ <span className="usage-pill__num">
+ {Math.round(100 - l.usedPercent)}% {limitShortLabel(l.kind, l.scopeLabel)}
+ </span>
</span>
- )}
- {session && weekly && <span className="usage-pill__sep">·</span>}
- {weekly && (
- <span className="usage-pill__num">
- {Math.round(weekly.leftPercent)}% {WEEKLY_LABEL}
- </span>
- )}
+ ))}
{isError && hasData && <span className="usage-pill__dim">⚠</span>}
</>
)
@@ -162,8 +175,9 @@ export function UsageIndicator(): JSX.Element | null {
</>
) : (
<>
- {session && <WindowRow title="Session" w={session} />}
- {weekly && <WindowRow title="Weekly" w={weekly} />}
+ {limits.map((l) => (
+ <LimitRow key={limitKey(l)} limit={l} />
+ ))}
{!hasData && <div className="usage-popover__empty">No usage data.</div>}
{usage.email && (
<div className="usage-account">
diff --git a/src/renderer/lib/usageFormat.ts b/src/renderer/lib/usageFormat.ts
index 67442a58c..5d17ebb0a 100644
--- a/src/renderer/lib/usageFormat.ts
+++ b/src/renderer/lib/usageFormat.ts
@@ -50,3 +50,23 @@ export function barColor(leftPercent: number): string {
if (leftPercent >= 20) return '#ffd60a'
return '#ff453a'
}
+
+/**
+ * Bar color for a usage limit. The server ships its own `severity` verdict, which 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).
+ */
+export function severityColor(severity: string, leftPercent: number): string {
+ switch (severity) {
+ case 'normal':
+ return '#30d158'
+ case 'warning':
+ return '#ffd60a'
+ case 'critical':
+ case 'exceeded':
+ return '#ff453a'
+ default:
+ return barColor(leftPercent)
+ }
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index ff6acfd0a..1b54da42e 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -4767,6 +4767,8 @@ body,
.usage-popover__empty { font-size: 13px; color: rgba(255, 255, 255, 0.5); }
.usage-row { margin-top: 14px; }
.usage-row__title { font-size: 14px; font-weight: 600; margin-bottom: 6px; }
+/* Marks the limit the server says is currently gating the account. */
+.usage-row__active { color: var(--accent); font-size: 9px; margin-left: 6px; vertical-align: 2px; }
.usage-bar {
height: 8px;
border-radius: 4px;
diff --git a/src/shared/types.ts b/src/shared/types.ts
index fa3cd59b9..5709688d8 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -928,8 +928,35 @@ export interface ClaudeUsageWindow {
resetsAt: number | null
}
+/**
+ * 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".
+ */
+export interface UsageLimit {
+ /** Server-assigned kind: 'session' | 'weekly_all' | 'weekly_scoped' | future values. */
+ kind: string
+ /** Coarse grouping ('session' | 'weekly'), or null when the server omits it. */
+ group: string | null
+ /** 0–100, portion consumed. */
+ usedPercent: number
+ /** Server's severity call ('normal' | 'warning' | …). Drives colour; not derived locally. */
+ severity: string
+ resetsAt: 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. */
+ isActive: boolean
+}
+
/** Claude Code subscription usage snapshot for the bottom-left indicator. */
export interface ClaudeUsage {
+ /**
+ * Every limit the plan exposes, including per-model scoped ones. Prefer this over the
+ * `session`/`weekly` fields below, which are kept only so older callers keep compiling.
+ */
+ limits: UsageLimit[]
session: ClaudeUsageWindow | null
weekly: ClaudeUsageWindow | null
/** Signed-in account email, read-only and best-effort (null if unknown). */
diff --git a/src/shared/usage-limits.test.ts b/src/shared/usage-limits.test.ts
new file mode 100644
index 000000000..ffea9b101
--- /dev/null
+++ b/src/shared/usage-limits.test.ts
@@ -0,0 +1,91 @@
+import { describe, it, expect } from 'vitest'
+import { limitLabel, limitShortLabel, primaryLimit, findLimit, limitKey } from './usage-limits'
+import type { UsageLimit } from './types'
+
+function limit(over: Partial<UsageLimit>): UsageLimit {
+ return {
+ kind: 'session',
+ group: 'session',
+ usedPercent: 0,
+ severity: 'normal',
+ resetsAt: null,
+ scopeLabel: null,
+ isActive: false,
+ ...over
+ }
+}
+
+describe('limitLabel', () => {
+ it('names the known kinds', () => {
+ expect(limitLabel('session', null)).toBe('Session')
+ expect(limitLabel('weekly_all', null)).toBe('Weekly')
+ })
+
+ it('prefers the model name for a scoped limit', () => {
+ expect(limitLabel('weekly_scoped', 'Fable')).toBe('Fable')
+ })
+
+ it('prettifies an unknown kind instead of dropping it', () => {
+ expect(limitLabel('monthly_surface', null)).toBe('Monthly Surface')
+ })
+})
+
+describe('limitShortLabel', () => {
+ it('abbreviates the known kinds for the pill', () => {
+ expect(limitShortLabel('session', null)).toBe('5h')
+ expect(limitShortLabel('weekly_all', null)).toBe('wk')
+ })
+
+ it('uses the bare model name for a scoped limit', () => {
+ expect(limitShortLabel('weekly_scoped', 'Fable')).toBe('Fable')
+ })
+})
+
+describe('primaryLimit', () => {
+ it('leads with the server-flagged active limit, not the highest percentage', () => {
+ // The 95% weekly looks worse, but the server says Fable is what is actually gating.
+ const picked = primaryLimit([
+ limit({ kind: 'weekly_all', usedPercent: 95, isActive: false }),
+ limit({ kind: 'weekly_scoped', usedPercent: 87, scopeLabel: 'Fable', isActive: true })
+ ])
+ expect(picked?.scopeLabel).toBe('Fable')
+ })
+
+ it('falls back to the highest percentage when nothing is flagged active', () => {
+ const picked = primaryLimit([
+ limit({ kind: 'session', usedPercent: 7 }),
+ limit({ kind: 'weekly_all', usedPercent: 61 }),
+ limit({ kind: 'weekly_scoped', usedPercent: 87, scopeLabel: 'Fable' })
+ ])
+ expect(picked?.usedPercent).toBe(87)
+ })
+
+ it('picks the worst among several active limits', () => {
+ const picked = primaryLimit([
+ limit({ kind: 'session', usedPercent: 30, isActive: true }),
+ limit({ kind: 'weekly_all', usedPercent: 70, isActive: true })
+ ])
+ expect(picked?.kind).toBe('weekly_all')
+ })
+
+ it('returns null for an empty list', () => {
+ expect(primaryLimit([])).toBeNull()
+ })
+})
+
+describe('findLimit', () => {
+ it('finds by kind and returns null when absent', () => {
+ const limits = [limit({ kind: 'session' }), limit({ kind: 'weekly_all' })]
+ expect(findLimit(limits, 'weekly_all')?.kind).toBe('weekly_all')
+ expect(findLimit(limits, 'monthly')).toBeNull()
+ })
+})
+
+describe('limitKey', () => {
+ it('separates scoped limits that share a kind', () => {
+ // Two per-model weekly caps are both `weekly_scoped`; keying on kind alone would collide.
+ const a = limit({ kind: 'weekly_scoped', scopeLabel: 'Fable' })
+ const b = limit({ kind: 'weekly_scoped', scopeLabel: 'Opus' })
+ expect(limitKey(a)).not.toBe(limitKey(b))
+ })
+})
diff --git a/src/shared/usage-limits.ts b/src/shared/usage-limits.ts
new file mode 100644
index 000000000..365879709
--- /dev/null
+++ b/src/shared/usage-limits.ts
@@ -0,0 +1,56 @@
+// Display + selection helpers for usage limits, shared by every surface (the renderer picks
+// what the pill leads with; the shells label rows the same way). Pure and dependency-free.
+//
+// The parsing that produces `UsageLimit[]` from a raw provider payload is service-side and
+// lives in core/usage — only the vocabulary lives here.
+import type { UsageLimit } from './types'
+
+/**
+ * Human label for a limit. A scoped limit is named by its model ("Fable"); everything else
+ * falls back to its `kind`, prettified, so an unrecognized future kind still renders as
+ * something readable instead of vanishing from the UI.
+ */
+export function limitLabel(kind: string, scopeLabel: string | null): string {
+ if (scopeLabel) return scopeLabel
+ switch (kind) {
+ case 'session':
+ return 'Session'
+ case 'weekly_all':
+ return 'Weekly'
+ case 'weekly_scoped':
+ return 'Weekly (scoped)'
+ default:
+ return kind.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
+ }
+}
+
+/** Compact label for the collapsed pill, where horizontal space is scarce. */
+export function limitShortLabel(kind: string, scopeLabel: string | null): string {
+ if (scopeLabel) return scopeLabel
+ if (kind === 'session') return '5h'
+ if (kind === 'weekly_all') return 'wk'
+ return limitLabel(kind, scopeLabel)
+}
+
+/**
+ * The one limit the collapsed pill leads with: whatever is closest to biting. The server's
+ * `is_active` flag wins over raw percentage — it knows which window is actually gating the
+ * account right now — and percentage only breaks ties.
+ */
+export function primaryLimit(limits: UsageLimit[]): UsageLimit | null {
+ if (limits.length === 0) return null
+ return limits.reduce((best, l) => {
+ if (l.isActive !== best.isActive) return l.isActive ? l : best
+ return l.usedPercent > best.usedPercent ? l : best
+ })
+}
+
+/** Find a limit by `kind`, for the back-compat `session`/`weekly` fields. */
+export function findLimit(limits: UsageLimit[], kind: string): UsageLimit | null {
+ return limits.find((l) => l.kind === kind) ?? null
+}
+
+/** Stable React key / dedupe key for a limit (kind alone repeats across scoped models). */
+export function limitKey(limit: UsageLimit): string {
+ return `${limit.kind}:${limit.scopeLabel ?? ''}`
+}