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.

fix(usage): keep the last good numbers through a failed read; name HTTP 429

review1f6a5054c244
diff --git a/CLAUDE.md b/CLAUDE.md
index ccea29e57..587be0f50 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3735,6 +3735,13 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`$HOME` + fake `curl`, the same discipline as the canvas-control shim.
3. **A read that could not run is `error`, never `unavailable`** — a dead master says nothing
about whether the account has a subscription, and 'unavailable' silently drops the row.
+ 4. **A failed read keeps the last good numbers** (`holdLastGood`, local AND remote): the
+ endpoint answers **429** on a budget every Claude CLI using the same login also spends
+ (measured on a host running 54 `claude` processes: 429 for minutes on end), and replacing
+ the bars with "Could not read usage" made rows flicker for no change in the account. The
+ held snapshot is `status: 'error'` + the old limits + the OLD `updatedAt`, so the debounce
+ must key on the READ's time (`lastFetchAt`/`remoteCache.at`), never on `updatedAt` — keying
+ it on the numbers' age re-reads on every call and hammers the endpoint that said 429.
Shape: `remoteUsageTargets` (pure) elects ONE connected project per host (several projects share
a host's `$HOME`) and offers its system `~/.claude` plus every managed account pinned to that
host. The service (`usage:remote`) caches per target under the usual debounce, evicts targets
diff --git a/src/core/usage/claude-usage-map.test.ts b/src/core/usage/claude-usage-map.test.ts
index 09bdefa42..d70c06e7f 100644
--- a/src/core/usage/claude-usage-map.test.ts
+++ b/src/core/usage/claude-usage-map.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest'
-import { mapUsageLimits, parseResetTimestamp } from './claude-usage-map'
+import {
+ HOLD_LAST_GOOD_MAX_MS,
+ emptyUsage,
+ holdLastGood,
+ mapUsageLimits,
+ parseResetTimestamp,
+ usageFromPayload
+} from './claude-usage-map'
import { findLimit, limitLabel, limitShortLabel } from '../../shared/usage-limits'
/**
@@ -155,3 +162,70 @@ describe('parseResetTimestamp', () => {
expect(parseResetTimestamp('not a date')).toBeNull()
})
})
+
+describe('holdLastGood', () => {
+ const NOW = 10_000_000
+ const good = usageFromPayload(
+ { limits: [{ kind: 'session', group: 'session', percent: 40, resets_at: (NOW + 3_600_000) / 1000 }] },
+ NOW - 60_000
+ )
+ const failed = (extra: Partial<ReturnType<typeof emptyUsage>> = {}) => ({
+ ...emptyUsage('[email protected]', NOW, 'error'),
+ ...extra
+ })
+
+ it('passes a good read straight through', () => {
+ const next = usageFromPayload({ limits: [] }, '[email protected]', NOW)
+ expect(holdLastGood(good, next, NOW)).toBe(next)
+ })
+
+ it('keeps the last numbers when the next read fails, marked as an error with their own age', () => {
+ const held = holdLastGood(good, failed({ rateLimited: true }), NOW)
+ expect(held.status).toBe('error')
+ expect(held.limits).toEqual(good.limits)
+ expect(held.session).toEqual(good.session)
+ // "Updated N ago" must describe the NUMBERS, not the failed read.
+ expect(held.updatedAt).toBe(good.updatedAt)
+ expect(held.rateLimited).toBe(true)
+ })
+
+ it('does not claim a rate limit the latest failure did not report', () => {
+ const once = holdLastGood(good, failed({ rateLimited: true }), NOW)
+ const twice = holdLastGood(once, failed(), NOW)
+ expect(twice.limits).toEqual(good.limits)
+ expect(twice.rateLimited).toBeUndefined()
+ })
+
+ it('keeps holding across repeated failures, aged from the last GOOD read', () => {
+ let u = holdLastGood(good, failed({ rateLimited: true }), NOW)
+ u = holdLastGood(u, failed({ rateLimited: true }), NOW + 60_000)
+ expect(u.limits).toEqual(good.limits)
+ const expired = holdLastGood(u, failed(), good.updatedAt + HOLD_LAST_GOOD_MAX_MS + 1)
+ expect(expired.limits).toEqual([])
+ })
+
+ it('has nothing to hold without an earlier snapshot that carried numbers', () => {
+ const next = failed()
+ expect(holdLastGood(undefined, next, NOW)).toBe(next)
+ expect(holdLastGood(emptyUsage('[email protected]', NOW, 'error'), next, NOW)).toBe(next)
+ expect(holdLastGood(emptyUsage(null, NOW, 'unavailable'), next, NOW)).toBe(next)
+ })
+
+ it('never lends one account’s numbers to another', () => {
+ const next = failed({ email: '[email protected]' })
+ expect(holdLastGood(good, next, NOW)).toBe(next)
+ })
+
+ it('drops the snapshot once one of its windows has reset — those numbers are provably wrong', () => {
+ const next = failed()
+ expect(holdLastGood(good, next, NOW + 3_600_000)).toBe(next)
+ })
+
+ it('does not hold over a logged-out or in-flight answer', () => {
+ for (const status of ['unavailable', 'fetching'] as const) {
+ const next = emptyUsage('[email protected]', NOW, status)
+ expect(holdLastGood(good, next, NOW)).toBe(next)
+ }
+ })
+})
diff --git a/src/core/usage/claude-usage-map.ts b/src/core/usage/claude-usage-map.ts
index 96d34275a..2e39dfe93 100644
--- a/src/core/usage/claude-usage-map.ts
+++ b/src/core/usage/claude-usage-map.ts
@@ -136,3 +136,39 @@ export function emptyUsage(
): ClaudeUsage {
return { limits: [], session: null, weekly: null, email, updatedAt: now, status }
}
+
+/**
+ * How long a failed read may keep showing the last good numbers. Past this the snapshot has
+ * outlived its usefulness: the pill itself carries no age stamp, and an hour-old percentage in
+ * a 5-hour window is a different number from the one the account is at now.
+ */
+export const HOLD_LAST_GOOD_MAX_MS = 60 * 60 * 1000
+
+/**
+ * Fold a new read into the previous snapshot of the SAME identity. A failed read must not erase
+ * numbers an earlier read produced: the endpoint rate-limits (HTTP 429) on a budget every Claude
+ * CLI using the same login also spends, so on a busy host reads fail intermittently, and replacing good bars with "Could not read usage" made the
+ * row flicker between numbers and an error for no change in the account at all.
+ *
+ * The held snapshot keeps the old limits AND the old `updatedAt` (so "Updated N ago" describes
+ * the numbers, not the failed read) under `status: 'error'` — the UI's existing contract for
+ * "last-known data, latest read failed". `rateLimited` reflects the LATEST failure only.
+ *
+ * Refuses to hold when doing so would show wrong numbers rather than old ones: a different
+ * account answered, the last good read is older than `HOLD_LAST_GOOD_MAX_MS`, or one of its
+ * windows has reset since.
+ */
+export function holdLastGood(
+ prev: ClaudeUsage | undefined,
+ next: ClaudeUsage,
+ now: number
+): ClaudeUsage {
+ if (next.status !== 'error' || next.limits.length > 0) return next
+ if (!prev || prev.limits.length === 0) return next
+ if (prev.status !== 'ok' && prev.status !== 'error') return next
+ if (next.email && prev.email && next.email !== prev.email) return next
+ if (now - prev.updatedAt > HOLD_LAST_GOOD_MAX_MS) return next
+ if (prev.limits.some((l) => l.resetsAt !== null && l.resetsAt <= now)) return next
+ const { rateLimited: _previousFailure, ...numbers } = prev
+ return { ...numbers, status: 'error', ...(next.rateLimited ? { rateLimited: true } : {}) }
+}
diff --git a/src/core/usage/remote-claude-usage.test.ts b/src/core/usage/remote-claude-usage.test.ts
index c8d61092e..f8d364a88 100644
--- a/src/core/usage/remote-claude-usage.test.ts
+++ b/src/core/usage/remote-claude-usage.test.ts
@@ -286,6 +286,17 @@ describe('fetchRemoteUsage', () => {
expect(u.status).toBe('unavailable')
})
+ it('says so when the endpoint rate-limited the read (429), and only then', async () => {
+ const limited = await fetchRemoteUsage(
+ target,
+ async () => reply('[email protected]', '{"error":{"type":"rate_limit_error"}}', '__NTU_HTTP__429'),
+ 1
+ )
+ expect(limited).toMatchObject({ status: 'error', rateLimited: true, email: '[email protected]' })
+ const http500 = await fetchRemoteUsage(target, async () => reply('oops', '__NTU_HTTP__500'), 1)
+ expect(http500.rateLimited).toBeUndefined()
+ })
+
it('keeps a broken read visible as an error', async () => {
const missingCurl = await fetchRemoteUsage(target, async () => reply('__NTU_STATUS__nocurl'), 1)
expect(missingCurl.status).toBe('error')
diff --git a/src/core/usage/remote-claude-usage.ts b/src/core/usage/remote-claude-usage.ts
index e404d594d..bd2b5cc34 100644
--- a/src/core/usage/remote-claude-usage.ts
+++ b/src/core/usage/remote-claude-usage.ts
@@ -214,6 +214,7 @@ export async function fetchRemoteUsage(
if (out.reason === 'nocreds') return emptyUsage(out.email, now, 'unavailable')
if (out.reason) return emptyUsage(out.email, now, 'error')
if (out.httpCode === 401 || out.httpCode === 403) return emptyUsage(out.email, now, 'unavailable')
+ if (out.httpCode === 429) return { ...emptyUsage(out.email, now, 'error'), rateLimited: true }
if (out.httpCode !== 200 || !out.body) return emptyUsage(out.email, now, 'error')
try {
return usageFromPayload(JSON.parse(out.body), out.email, now)
diff --git a/src/core/usage/usage-service.hold.test.ts b/src/core/usage/usage-service.hold.test.ts
new file mode 100644
index 000000000..a2b5acf70
--- /dev/null
+++ b/src/core/usage/usage-service.hold.test.ts
@@ -0,0 +1,99 @@
+// A failed LOCAL read must not wipe the numbers the previous read produced. The usage endpoint
+// rate-limits (HTTP 429) on a budget every Claude CLI using the same login also spends, so on a
+// busy machine reads fail intermittently — and each failure used to replace
+// the bars with "Could not read usage" until the next successful read, 5–15 minutes later.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { promises as fs } from 'fs'
+import { IPC } from '../../shared/ipc'
+import type { ClaudeUsage } from '../../shared/types'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform, type FakePlatform } from '../platform-fake'
+import { startUsageService, type UsageService } from './usage-service'
+
+const { keychain } = vi.hoisted(() => ({ keychain: vi.fn() }))
+vi.mock('child_process', () => ({ execFile: keychain }))
+vi.mock('fs', async (original) => {
+ const actual = await original<typeof import('fs')>()
+ return { ...actual, promises: { ...actual.promises, readFile: vi.fn() } }
+})
+vi.mock('os', async (original) => {
+ const actual = await original<typeof import('os')>()
+ return { ...actual, default: { ...actual, homedir: () => '/fixture-home' } }
+})
+
+const files: Record<string, string> = {
+ '/fixture-home/.claude/.credentials.json': JSON.stringify({
+ claudeAiOauth: { accessToken: 'fixture-token', email: '[email protected]' }
+ })
+}
+const ok = (): Response =>
+ new Response(JSON.stringify({ limits: [{ kind: 'session', group: 'session', percent: 40 }] }))
+const limited = (): Response =>
+ new Response('{"error":{"type":"rate_limit_error"}}', { status: 429 })
+
+let platform: FakePlatform
+let service: UsageService | undefined
+let responses: Array<() => Response>
+const fetchStub = vi.fn(async () => (responses.shift() ?? limited)())
+
+beforeEach(() => {
+ platform = fakePlatform({ userDataDir: '/fixture-data' })
+ initPlatform(platform)
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
+ vi.mocked(fs.readFile).mockImplementation(async (file) => {
+ const raw = files[String(file)]
+ if (raw === undefined) throw new Error('fixture missing')
+ return raw
+ })
+ keychain.mockImplementation((_cmd, _args, cb) => cb(new Error('fixture missing')))
+ fetchStub.mockClear()
+ vi.stubGlobal('fetch', fetchStub)
+ service = startUsageService({ shouldPoll: () => false })
+})
+
+afterEach(() => {
+ service?.dispose()
+ service = undefined
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ resetPlatformForTests()
+})
+
+const refresh = (): Promise<ClaudeUsage> => platform.handlers[IPC.usageRefresh]() as Promise<ClaudeUsage>
+const fetchCached = (): Promise<ClaudeUsage> => platform.handlers[IPC.usageFetch]() as Promise<ClaudeUsage>
+const pushed = (): ClaudeUsage[] =>
+ platform.sent.filter((m) => m.channel === IPC.usageUpdate).map((m) => m.args[0] as ClaudeUsage)
+
+describe('local usage through a failed read', () => {
+ it('keeps and pushes the last good numbers when the endpoint answers 429', async () => {
+ responses = [ok, limited]
+ const first = await refresh()
+ expect(first.status).toBe('ok')
+ const held = await refresh()
+ expect(held).toMatchObject({ status: 'error', rateLimited: true, updatedAt: first.updatedAt })
+ expect(held.limits).toEqual(first.limits)
+ // The collapsed chip is fed by the push channel — it must get the held numbers too.
+ expect(pushed().at(-1)).toEqual(held)
+ })
+
+ it('debounces from the failed read, not from the age of the numbers it kept', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(1_000_000_000)
+ responses = [ok, limited]
+ await refresh()
+ // Past the 5-minute debounce, but well inside the hold window.
+ vi.setSystemTime(1_000_000_000 + 6 * 60_000)
+ await refresh()
+ // The held snapshot's updatedAt is older than the read that produced it. Keying the debounce
+ // on it would make every cached fetch re-read — hammering exactly the endpoint that said 429.
+ await fetchCached()
+ expect(fetchStub).toHaveBeenCalledTimes(2)
+ })
+
+ it('still reports a plain failure when there was never a good read to keep', async () => {
+ responses = [limited]
+ const u = await refresh()
+ expect(u).toMatchObject({ status: 'error', rateLimited: true, limits: [] })
+ })
+})
diff --git a/src/core/usage/usage-service.remote.test.ts b/src/core/usage/usage-service.remote.test.ts
index 1002e82d4..f37e5bf0e 100644
--- a/src/core/usage/usage-service.remote.test.ts
+++ b/src/core/usage/usage-service.remote.test.ts
@@ -79,6 +79,29 @@ describe('usage:remote', () => {
expect(run).toHaveBeenCalledTimes(2)
})
+ it('keeps the last good numbers through a rate-limited read, and does not re-read inside the debounce', async () => {
+ const limited = [
+ '__NTU_BEGIN__',
+ '{"error":{"type":"rate_limit_error","message":"Rate limited. Please try again later."}}',
+ '__NTU_HTTP__429',
+ '__NTU_END__'
+ ].join('\n')
+ const replies = [OK_REPLY, limited, limited]
+ const run = vi.fn(async () => replies.shift() ?? limited)
+ start({ targets: () => [target('root@alpha')], run })
+ const [first] = await callRemote()
+ // Two readers racing the same failing read both see the held numbers, not an empty row.
+ const [[a], [b]] = await Promise.all([callRemote({ force: true }), callRemote({ force: true })])
+ for (const held of [a, b]) {
+ expect(held.usage).toMatchObject({ status: 'error', rateLimited: true, updatedAt: first.usage.updatedAt })
+ expect(held.usage.limits).toEqual(first.usage.limits)
+ }
+ // The held row is cached like any other: reopening the popover must not hammer a 429.
+ await callRemote()
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+
it('retires a host that has disconnected instead of serving its last numbers', async () => {
const run = vi.fn(async () => OK_REPLY)
let connected = [target('root@alpha')]
diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.ts
index 78baa4492..0f84ff3bf 100644
--- a/src/core/usage/usage-service.ts
+++ b/src/core/usage/usage-service.ts
@@ -17,7 +17,7 @@ import type {
RemoteAccountUsage,
RemoteUsageQuery
} from '../../shared/types'
-import { emptyUsage, usageFromPayload } from './claude-usage-map'
+import { emptyUsage, holdLastGood, usageFromPayload } from './claude-usage-map'
import {
fetchRemoteUsage,
type RemoteUsageRunner,
@@ -192,7 +192,10 @@ export 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 identify(emptyUsage(email, now, status))
+ const failed = emptyUsage(email, now, status)
+ // 429 is named, not folded into "could not read": the endpoint answered, and its budget is
+ // shared with every Claude CLI using the same login — not a network or credentials fault.
+ return identify(res.status === 429 ? { ...failed, rateLimited: true } : failed)
}
const data = (await res.json()) as Record<string, any>
return identify(usageFromPayload(data, email, now))
@@ -285,9 +288,15 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
const lastFetchAt = new Map<string, number>()
const inFlight = new Map<string, Promise<ClaudeUsage>>()
- const push = (key: string, u: ClaudeUsage): void => {
+ const push = (key: string, fresh: ClaudeUsage): ClaudeUsage => {
+ const now = Date.now()
+ // A failed read keeps the last good numbers (see holdLastGood) instead of blanking the row.
+ const u = holdLastGood(last.get(key), fresh, now)
last.set(key, u)
- lastFetchAt.set(key, u.updatedAt)
+ // The READ's time, not `u.updatedAt`: a held snapshot is older than the read that produced
+ // it, and debouncing on its age would re-read on every call — hammering the very endpoint
+ // that just answered 429.
+ lastFetchAt.set(key, now)
// Only the system account feeds the push channel — the collapsed chip tracks it.
// Best-effort: a fetch launched before shutdown (or a test's platform reset) can land after
// the shell is gone, and this runs inside an un-awaited promise chain — throwing here is an
@@ -305,18 +314,18 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
} catch {
// a mirror flush must never break the usage cache update
}
+ return u
}
const run = async (accountId?: string): Promise<ClaudeUsage> => {
const key = accountId ?? ''
const pending = inFlight.get(key)
if (pending) return pending
- const p = fetchUsage(accountId)
+ // push() is inside the shared promise so a coalesced caller gets the HELD snapshot too.
+ const p = fetchUsage(accountId).then((u) => push(key, u))
inFlight.set(key, p)
try {
- const u = await p
- push(key, u)
- return u
+ return await p
} finally {
inFlight.delete(key)
}
@@ -456,7 +465,12 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
if (pending) return pending
const p = target.provider === 'codex'
? fetchRemoteCodexUsage(target, deps.run, Date.now())
- : fetchRemoteUsage(target, deps.run, Date.now())
+ : fetchRemoteUsage(target, deps.run, Date.now()).then((fresh) => {
+ // Same rule as the local cache: a failed read keeps this host's last good numbers.
+ // Folded in here, inside the shared promise, so a coalesced reader sees them too.
+ const prev = remoteCache.get(key)?.usage
+ return prev && !('provider' in prev) ? holdLastGood(prev, fresh, Date.now()) : fresh
+ })
remoteInFlight.set(key, p)
try {
const u = await p
diff --git a/src/renderer/components/UsageIndicator.remoteCodex.test.tsx b/src/renderer/components/UsageIndicator.remoteCodex.test.tsx
index f8abf2258..1916d0728 100644
--- a/src/renderer/components/UsageIndicator.remoteCodex.test.tsx
+++ b/src/renderer/components/UsageIndicator.remoteCodex.test.tsx
@@ -74,3 +74,22 @@ it('discards an old forced refresh after switching projects and retains both Cla
await act(async () => finish?.([row('u@a', 88)]))
expect(host.querySelector('.usage-pill')?.textContent).toContain('17% Codex')
})
+
+it('names a rate-limited host read and explains kept host numbers', async () => {
+ useSettings.setState({ settings: { ...useSettings.getState().settings, hiddenUsageProviders: [] } })
+ const limits = usage(42).limits
+ const claudeRow = (u: Partial<Extract<RemoteAccountUsage, { provider?: 'claude' }>['usage']>): RemoteAccountUsage => ({
+ hostKey: 'u@a', accountId: null, label: 'u@a',
+ usage: { limits: [], session: null, weekly: null, email: '[email protected]', updatedAt: Date.now(), status: 'error', ...u }
+ })
+ await render(async () => [claudeRow({ rateLimited: true })])
+ await act(async () => (host.querySelector('.usage-pill') as HTMLButtonElement).click())
+ expect(host.textContent).toContain('Rate limited by the usage endpoint (HTTP 429) — try again in a few minutes.')
+ expect(host.textContent).not.toContain('Could not read usage on this host.')
+
+ act(() => root.unmount()); root = createRoot(host)
+ await render(async () => [claudeRow({ limits, updatedAt: Date.now() - 3 * 60_000 })])
+ await act(async () => (host.querySelector('.usage-pill') as HTMLButtonElement).click())
+ expect(host.querySelector('.usage-popover__held')?.textContent)
+ .toBe('Latest read failed — showing numbers from 3m ago.')
+})
diff --git a/src/renderer/components/UsageIndicator.test.tsx b/src/renderer/components/UsageIndicator.test.tsx
index 542418711..ae9f0cd5a 100644
--- a/src/renderer/components/UsageIndicator.test.tsx
+++ b/src/renderer/components/UsageIndicator.test.tsx
@@ -91,6 +91,31 @@ describe('Claude usage failure readout', () => {
expect(host.querySelectorAll('.usage-row')).toHaveLength(1)
})
+ it('names a rate limit instead of the generic failure, for system and managed rows', async () => {
+ await open({ ...snapshot('error'), rateLimited: true }, { ...snapshot('error'), rateLimited: true })
+ const rows = host.querySelectorAll('.usage-popover__empty')
+ expect(rows).toHaveLength(2)
+ for (const row of rows) {
+ expect(row.textContent).toBe('Rate limited by the usage endpoint (HTTP 429) — try again in a few minutes.')
+ }
+ })
+
+ it('says why kept bars are old, and how old', async () => {
+ const kept = { ...snapshot('error', [limit]), rateLimited: true, updatedAt: Date.now() - 12 * 60_000 }
+ await open(kept, kept)
+ expect(host.querySelectorAll('.usage-row')).toHaveLength(2)
+ const notes = host.querySelectorAll('.usage-popover__held')
+ expect(notes).toHaveLength(2)
+ for (const note of notes) {
+ expect(note.textContent).toBe('Latest read was rate limited (HTTP 429) — showing numbers from 12m ago.')
+ }
+ })
+
+ it('carries no held note on a good read', async () => {
+ await open(snapshot('ok', [limit]))
+ expect(host.querySelector('.usage-popover__held')).toBeNull()
+ })
+
it('preserves stale bars in the single-account view', async () => {
await open(snapshot('error', [limit]))
expect(host.querySelectorAll('.usage-row')).toHaveLength(1)
diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsx
index edc129119..b6aaeb148 100644
--- a/src/renderer/components/UsageIndicator.tsx
+++ b/src/renderer/components/UsageIndicator.tsx
@@ -19,9 +19,11 @@ import {
barFillPercent,
formatResetCountdown,
formatTimeAgo,
+ heldUsageText,
percentNumber,
percentText,
- severityColor
+ severityColor,
+ usageFailureText
} from '../lib/usageFormat'
import {
enabledProviders,
@@ -105,6 +107,12 @@ function DefaultAccountMark({
)
}
+/** Why the bars above are old — only for numbers kept through a failed read. */
+function HeldNote({ u }: { u: ClaudeUsage | null | undefined }) {
+ const text = u ? heldUsageText(u) : null
+ return text ? <div className="usage-popover__held">{text}</div> : null
+}
+
/** Where a bulk move can send an account's sessions: another account on the same machine. */
export interface MoveTarget {
id: string | undefined
@@ -194,9 +202,10 @@ function AccountUsageBlock({
{u?.limits.map((l) => (
<LimitRow key={limitKey(l)} limit={l} mode={mode} />
))}
+ <HeldNote u={u} />
{u && u.limits.length === 0 && (
<div className="usage-popover__empty">
- {u.status === 'error' ? 'Could not read usage.' : 'No usage data.'}
+ {u.status === 'error' ? usageFailureText(u) : 'No usage data.'}
</div>
)}
{!u && <div className="usage-popover__empty usage-pill__pulse">···</div>}
@@ -242,9 +251,10 @@ function RemoteUsageBlock({
{row.usage.limits.map((l) => (
<LimitRow key={limitKey(l)} limit={l} mode={mode} />
))}
+ <HeldNote u={row.usage} />
{row.usage.limits.length === 0 && (
<div className="usage-popover__empty">
- {row.usage.status === 'error' ? 'Could not read usage on this host.' : 'No usage data.'}
+ {row.usage.status === 'error' ? usageFailureText(row.usage, 'on this host') : 'No usage data.'}
</div>
)}
</div>
@@ -655,11 +665,12 @@ export function UsageIndicator({
{limits.map((l) => (
<LimitRow key={limitKey(l)} limit={l} mode={percentMode} />
))}
+ <HeldNote u={claudeUsage} />
{/* Another provider's data must not hide a failed Claude read. Keep any
last-known Claude bars instead of replacing them with the empty state. */}
{((!hasData && !providerError) || (claudeError && limits.length === 0)) && (
<div className="usage-popover__empty">
- {claudeError ? 'Could not read usage.' : 'No usage data.'}
+ {claudeError ? usageFailureText(claudeUsage) : 'No usage data.'}
</div>
)}
{(claudeUsage?.email || claudeUsage?.organization) && (
diff --git a/src/renderer/lib/usageFormat.test.ts b/src/renderer/lib/usageFormat.test.ts
index 655b97925..949e6cf3b 100644
--- a/src/renderer/lib/usageFormat.test.ts
+++ b/src/renderer/lib/usageFormat.test.ts
@@ -1,5 +1,13 @@
import { describe, expect, it } from 'vitest'
-import { barFillPercent, contextFillColor, formatModelLabel, percentNumber, severityColor } from './usageFormat'
+import {
+ barFillPercent,
+ contextFillColor,
+ formatModelLabel,
+ heldUsageText,
+ percentNumber,
+ severityColor,
+ usageFailureText
+} from './usageFormat'
describe('formatModelLabel', () => {
it('formats family + version ids', () => {
@@ -78,3 +86,29 @@ describe('contextFillColor', () => {
expect(severityColor(null, 90)).toBe('#30d158')
})
})
+
+describe('usage failure copy', () => {
+ const limit = { kind: 'session', group: 'session', usedPercent: 10, severity: null, resetsAt: null, windowMinutes: null, scopeLabel: null, isActive: false }
+
+ it('keeps the generic wording for a failure it cannot name', () => {
+ expect(usageFailureText(null)).toBe('Could not read usage.')
+ expect(usageFailureText({})).toBe('Could not read usage.')
+ expect(usageFailureText({}, 'on this host')).toBe('Could not read usage on this host.')
+ })
+
+ it('names a 429 wherever it happened', () => {
+ const text = 'Rate limited by the usage endpoint (HTTP 429) — try again in a few minutes.'
+ expect(usageFailureText({ rateLimited: true })).toBe(text)
+ expect(usageFailureText({ rateLimited: true }, 'on this host')).toBe(text)
+ })
+
+ it('explains kept numbers only when a failed read kept some', () => {
+ const now = Date.now()
+ expect(heldUsageText({ status: 'ok', limits: [limit], updatedAt: now })).toBeNull()
+ expect(heldUsageText({ status: 'error', limits: [], updatedAt: now })).toBeNull()
+ expect(heldUsageText({ status: 'error', limits: [limit], updatedAt: now }))
+ .toBe('Latest read failed — showing numbers from a moment ago.')
+ expect(heldUsageText({ status: 'error', limits: [limit], updatedAt: now - 2 * 3_600_000, rateLimited: true }))
+ .toBe('Latest read was rate limited (HTTP 429) — showing numbers from 2h ago.')
+ })
+})
diff --git a/src/renderer/lib/usageFormat.ts b/src/renderer/lib/usageFormat.ts
index 0f9df7260..83945432b 100644
--- a/src/renderer/lib/usageFormat.ts
+++ b/src/renderer/lib/usageFormat.ts
@@ -11,6 +11,34 @@ export function formatTimeAgo(ts: number): string {
return `${hours}h ago`
}
+/**
+ * The line for a Claude read that failed with no numbers to show. A 429 is named: the usage
+ * endpoint's budget is shared with every Claude CLI using the same login, and a generic
+ * "could not read" sent people debugging an SSH link and credentials that were both fine.
+ * `where` qualifies only the generic wording — a 429 says nothing about the host's link.
+ */
+export function usageFailureText(u: { rateLimited?: boolean } | null | undefined, where = ''): string {
+ if (u?.rateLimited) return 'Rate limited by the usage endpoint (HTTP 429) — try again in a few minutes.'
+ return where ? `Could not read usage ${where}.` : 'Could not read usage.'
+}
+
+/**
+ * The note under bars the service KEPT because the latest read failed (`holdLastGood`: status
+ * 'error' with limits). Null for anything else. Says how old the numbers are, since the pill
+ * above shows them without a stamp.
+ */
+export function heldUsageText(u: {
+ status: string
+ limits: readonly unknown[]
+ updatedAt: number
+ rateLimited?: boolean
+}): string | null {
+ if (u.status !== 'error' || u.limits.length === 0) return null
+ const why = u.rateLimited ? 'was rate limited (HTTP 429)' : 'failed'
+ const ago = formatTimeAgo(u.updatedAt)
+ return `Latest read ${why} — showing numbers from ${ago === 'just now' ? 'a moment ago' : ago}.`
+}
+
/** "Resets now" / "Resets in 1h 2m" / "Resets in 2d 4h". */
export function formatResetCountdown(resetsAt: number | null): string {
if (resetsAt == null) return ''
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 3190e6507..66e6401cb 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -8029,6 +8029,8 @@ button.group-node__setup:disabled {
.usage-popover__title { display: block; font-size: 15px; font-weight: 600; }
.usage-popover__ago { font-size: 12px; color: rgba(var(--tint-rgb), 0.5); }
.usage-popover__empty { font-size: 13px; color: rgba(var(--tint-rgb), 0.5); }
+/* Under bars kept through a failed read (holdLastGood): why they are old, and how old. */
+.usage-popover__held { font-size: 12px; margin-top: 10px; color: rgba(var(--tint-rgb), 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. */
diff --git a/src/shared/types.ts b/src/shared/types.ts
index fcd8467f4..65aa239d8 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2662,9 +2662,18 @@ export interface ClaudeUsage {
updatedAt: number
/**
* 'unavailable' = no OAuth subscription token (API-key billing / logged out) → hide pill.
- * 'fetching' = request in flight. 'ok' = windows present. 'error' = fetch failed.
+ * 'fetching' = request in flight. 'ok' = windows present. 'error' = fetch failed — and when
+ * `limits` is non-empty alongside it, those are the LAST GOOD numbers the service kept
+ * (`holdLastGood`), still stamped with their own `updatedAt`.
*/
status: 'unavailable' | 'fetching' | 'ok' | 'error'
+ /**
+ * The latest read was refused with HTTP 429. The usage endpoint's request budget is also
+ * spent by every Claude CLI using the same login (the CLI reads this endpoint itself), so a
+ * host running dozens of sessions can exhaust it without us. Absent = not rate limited (or
+ * not known to be).
+ */
+ rateLimited?: boolean
}
/**