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
fix(usage): retain Grok billing failure diagnostics
reviewa805b9434627
diff --git a/CLAUDE.md b/CLAUDE.mdindex c6698c072..a2ffbfdbc 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3001,6 +3001,8 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilethat host (cache eviction still runs against the FULL target list, so switching between two SSHprojects doesn't throw each host's cache away).+- **Grok billing failures** retain per-view HTTP status or a safe timeout/network/invalid-response category in `ProviderUsage.diagnostics`. The default view still runs after a credits failure; recovered limits keep their diagnostic. Only two successful empty views imply no quota. Never include raw exceptions, URLs or response bodies, or refresh/write credentials. Desktop and Server share the core reader and popover; provider-only errors must keep the pill visible.+- **Remote usage** (SSH hosts, `src/core/usage/remote-claude-usage.ts`) — the source behind theSSH scope above. v1 excluded remote accounts, which left a user whose Claude only ever runs on aserver staring at an empty indicator while the host had perfectly good numbers.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 6573d6037..f59796480 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -623,6 +623,8 @@ terminal opens keep their existing identity policy; Server Edition still requirefor every control verb. Legacy mobile/SSH callers must present this instance’s node token forcommand-bearing opens; this does not add a human-confirm dialog or change mobile transport APIs.+Grok billing diagnostics must keep HTTP codes and safe failure categories per billing view. Never send raw error messages, URLs or response bodies to the UI; credentials remain read-only. A failed view is not proof that there is no quota, even when the other view responds.+## Testing`npm test` must pass, and `npm run typecheck` is the fastest gate.diff --git a/src/core/usage/grok-diagnostics.test.ts b/src/core/usage/grok-diagnostics.test.tsnew file mode 100644index 000000000..dc02dcfa2--- /dev/null+++ b/src/core/usage/grok-diagnostics.test.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { fetchGrokUsage } from './grok-usage'+let home: string+const request = vi.fn()+beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-diagnostics-'))+ fs.writeFileSync(path.join(home, 'auth.json'), '{"auth.x.ai":{"key":"fixture-secret"}}')+ vi.stubGlobal('fetch', request.mockReset())+})+afterEach(() => {+ expect(fs.readFileSync(path.join(home, 'auth.json'), 'utf8')).toBe('{"auth.x.ai":{"key":"fixture-secret"}}')+ fs.rmSync(home, { recursive: true, force: true })+ vi.unstubAllGlobals()+ vi.useRealTimers()+})+const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body })+it.each([401, 403, 429, 500, 418])('preserves HTTP %s for both billing views without response bodies', async (status) => {+ request.mockResolvedValue({ ok: false, status, json: async () => ({ secret: 'fixture-secret' }) })+ const result = await fetchGrokUsage(home)+ expect(result).toMatchObject({ status: 'error', diagnostics: [+ { view: 'credits', reason: 'http', httpStatus: status },+ { view: 'default', reason: 'http', httpStatus: status }+ ] })+ expect(JSON.stringify(result)).not.toContain('fixture-secret')+})+it('attempts fallback after a transport failure and preserves usable data plus the reason', async () => {+ request.mockRejectedValueOnce(new Error('fixture-secret')).mockResolvedValueOnce(ok({ creditUsagePercent: 25 }))+ const result = await fetchGrokUsage(home)+ expect(result).toMatchObject({ status: 'ok', limits: [{ usedPercent: 25 }], diagnostics: [{ view: 'credits', reason: 'network' }] })+ expect(request).toHaveBeenCalledTimes(2)+ expect(JSON.stringify(result)).not.toContain('fixture-secret')+})+it.each([true, false])('does not call a partial failure unavailable (credits failed: %s)', async (firstFails) => {+ const fail = { ok: false, status: 503 }+ request.mockResolvedValueOnce(firstFails ? fail : ok({})).mockResolvedValueOnce(firstFails ? ok({}) : fail)+ expect(await fetchGrokUsage(home)).toMatchObject({ status: 'error', diagnostics: [{ view: firstFails ? 'credits' : 'default', reason: 'http', httpStatus: 503 }] })+})+it('keeps genuine no-quota responses unavailable', async () => {+ request.mockResolvedValue(ok({}))+ expect(await fetchGrokUsage(home)).toMatchObject({ status: 'unavailable' })+})+it('keeps the credits success fast path', async () => {+ request.mockResolvedValue(ok({ creditUsagePercent: 0 }))+ expect(await fetchGrokUsage(home)).toMatchObject({ status: 'ok', limits: [{ usedPercent: 0 }] })+ expect(request).toHaveBeenCalledTimes(1)+})+it('distinguishes malformed JSON from transport failures', async () => {+ request.mockResolvedValue({ ok: true, status: 200, json: async () => { throw new SyntaxError('fixture-secret') } })+ expect(await fetchGrokUsage(home)).toMatchObject({ status: 'error', diagnostics: [+ { view: 'credits', reason: 'invalid-response' }, { view: 'default', reason: 'invalid-response' }+ ] })+})+it('bounds response body reads and retains timeout reasons', async () => {+ vi.useFakeTimers()+ request.mockImplementation(async (_url, { signal }) => ({ ok: true, status: 200, json: () => new Promise((_resolve, reject) => {+ signal.addEventListener('abort', () => reject(new Error('fixture-secret')))+ }) }))+ const pending = fetchGrokUsage(home)+ // Auth reads use the real filesystem before the first request starts.+ await vi.waitFor(() => expect(request).toHaveBeenCalledTimes(1))+ await vi.advanceTimersByTimeAsync(16000)+ expect(await pending).toMatchObject({ status: 'error', diagnostics: [+ { view: 'credits', reason: 'timeout' }, { view: 'default', reason: 'timeout' }+ ] })+ expect(vi.getTimerCount()).toBe(0)+})++it.each([null, [], 'not an object'])('reports invalid top-level JSON: %j', async (body) => {+ request.mockResolvedValue(ok(body))+ expect(await fetchGrokUsage(home)).toMatchObject({ status: 'error', diagnostics: [+ { view: 'credits', reason: 'invalid-response' }, { view: 'default', reason: 'invalid-response' }+ ] })+})diff --git a/src/core/usage/grok-usage.ts b/src/core/usage/grok-usage.tsindex 7d6d8e427..a9993e8ff 100644--- a/src/core/usage/grok-usage.ts+++ b/src/core/usage/grok-usage.ts@@ -6,7 +6,7 @@import { promises as fs } from 'fs'import path from 'path'import { grokHomeDir } from '../agents/grok-paths'-import type { ProviderUsage, UsageLimit } from '../../shared/types'+import type { ProviderUsage, UsageLimit, UsageDiagnostic } from '../../shared/types'const DEFAULT_PROXY_BASE = 'https://cli-chat-proxy.grok.com/v1'const FETCH_TIMEOUT_MS = 8000@@ -139,11 +139,14 @@ export function mapGrokLimits(body: unknown): UsageLimit[] {return [mapGrokWeekly(config), mapGrokMonthly(config)].filter((l): l is UsageLimit => l !== null)}-function snapshot(limits: UsageLimit[], status: ProviderUsage['status']): ProviderUsage {- return { provider: 'grok', limits, account: null, updatedAt: Date.now(), status }+function snapshot(limits: UsageLimit[], status: ProviderUsage['status'], diagnostics: UsageDiagnostic[] = []): ProviderUsage {+ return { provider: 'grok', limits, account: null, updatedAt: Date.now(), status,+ ...(diagnostics.length ? { diagnostics } : {}) }}-async function getBilling(url: string, auth: GrokAuth): Promise<unknown | null> {+type BillingResult = { ok: true; body: unknown } | { ok: false; diagnostic: UsageDiagnostic }++async function getBilling(url: string, auth: GrokAuth, view: UsageDiagnostic['view']): Promise<BillingResult> {const headers: Record<string, string> = {authorization: `Bearer ${auth.key}`,accept: 'application/json'@@ -156,9 +159,26 @@ async function getBilling(url: string, auth: GrokAuth): Promise<unknown | null>const ctrl = new AbortController()const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)- const res = await fetch(url, { headers, signal: ctrl.signal }).finally(() => clearTimeout(t))- if (!res.ok) return null- return res.json()+ try {+ const res = await fetch(url, { headers, signal: ctrl.signal })+ if (!res.ok) return { ok: false, diagnostic: { view, reason: 'http', httpStatus: res.status } }+ try {+ const body: unknown = await res.json()+ if (!body || typeof body !== 'object' || Array.isArray(body)) {+ return { ok: false, diagnostic: { view, reason: 'invalid-response' } }+ }+ return { ok: true, body }+ } catch (error) {+ return { ok: false, diagnostic: { view, reason: ctrl.signal.aborted ? 'timeout'+ : error instanceof SyntaxError ? 'invalid-response' : 'network' } }+ }+ } catch {+ // Exception messages can contain proxy URLs or credentials. Only send a safe category.+ return { ok: false, diagnostic: { view, reason: ctrl.signal.aborted ? 'timeout' : 'network' } }+ } finally {+ // Keep the deadline active through body consumption, not just response headers.+ clearTimeout(t)+ }}/**@@ -172,17 +192,19 @@ export async function fetchGrokUsage(home = grokHome()): Promise<ProviderUsage>if (!auth.key) return snapshot([], 'unavailable')const base = proxyBase()- const credits = await getBilling(`${base}/billing?format=credits`, auth)- const fromCredits = credits ? mapGrokLimits(credits) : []+ const diagnostics: UsageDiagnostic[] = []+ const credits = await getBilling(`${base}/billing?format=credits`, auth, 'credits')+ if (!credits.ok) diagnostics.push(credits.diagnostic)+ const fromCredits = credits.ok ? mapGrokLimits(credits.body) : []if (fromCredits.length > 0) return snapshot(fromCredits, 'ok')- const dflt = await getBilling(`${base}/billing`, auth)- const fromDefault = dflt ? mapGrokLimits(dflt) : []- if (fromDefault.length > 0) return snapshot(fromDefault, 'ok')+ const dflt = await getBilling(`${base}/billing`, auth, 'default')+ if (!dflt.ok) diagnostics.push(dflt.diagnostic)+ const fromDefault = dflt.ok ? mapGrokLimits(dflt.body) : []+ if (fromDefault.length > 0) return snapshot(fromDefault, 'ok', diagnostics)// Both views answered but neither carried a quota: the account genuinely has none to show.- if (credits !== null || dflt !== null) return snapshot([], 'unavailable')- return snapshot([], 'error')+ return snapshot([], diagnostics.length ? 'error' : 'unavailable', diagnostics)} catch {return snapshot([], 'error')}diff --git a/src/renderer/components/UsageIndicator.grok.test.tsx b/src/renderer/components/UsageIndicator.grok.test.tsxnew file mode 100644index 000000000..0edb8b496--- /dev/null+++ b/src/renderer/components/UsageIndicator.grok.test.tsx@@ -0,0 +1,102 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { DEFAULT_SETTINGS, type ClaudeUsage, type ProviderUsage, type UsageLimit } from '@shared/types'+import { useSettings } from '../state/settings'+import { UsageIndicator } from './UsageIndicator'++const limit: UsageLimit = {+ kind: 'session', group: 'session', usedPercent: 37, severity: null,+ resetsAt: null, windowMinutes: 300, scopeLabel: null, isActive: false+}+const snapshot = (status: ClaudeUsage['status'], limits: UsageLimit[] = []): ClaudeUsage => ({+ status, limits, session: null, weekly: null, email: null, updatedAt: 0+})++let host: HTMLDivElement+let root: Root++beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, usagePercentMode: 'remaining' } })+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ useSettings.setState({ settings: DEFAULT_SETTINGS })+ vi.unstubAllGlobals()+})++async function open(system: ClaudeUsage, providers: ProviderUsage[] = []) {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ // No credentials, network, or running sessions: exercise the real component using bridge snapshots.+ vi.stubGlobal('nodeTerminal', { usage: {+ fetch: async () => system,+ providers: async () => providers,+ onUpdate: () => () => {}+ } })+ await act(async () => root.render(<UsageIndicator />))+ await act(async () => host.querySelector('.usage-indicator')!.dispatchEvent(+ new MouseEvent('mouseover', { bubbles: true })+ ))+}++describe('Grok billing diagnostics in the usage popover', () => {+ it.each([+ [{ reason: 'http', httpStatus: 401 }, 'Grok authentication failed (HTTP 401)'],+ [{ reason: 'http', httpStatus: 403 }, 'Grok authentication failed (HTTP 403)'],+ [{ reason: 'http', httpStatus: 429 }, 'Usage request rate limited (HTTP 429)'],+ [{ reason: 'http', httpStatus: 503 }, 'Grok returned HTTP 503'],+ [{ reason: 'http', httpStatus: 418 }, 'Usage request failed (HTTP 418)'],+ [{ reason: 'network' }, 'Could not reach Grok'],+ [{ reason: 'timeout' }, 'Usage request timed out'],+ [{ reason: 'invalid-response' }, 'Usage response could not be read']+ ] as const)('shows a safe, specific reason for %j', async (diagnostic, message) => {+ await open(snapshot('unavailable'), [{ provider: 'grok', account: null,+ status: 'error', limits: [], updatedAt: 0, diagnostics: [{ view: 'credits', ...diagnostic }] }])+ expect(host.querySelector('.usage-indicator')?.textContent).toContain('⚠')+ const text = host.querySelector('.usage-account')?.textContent+ expect(text).toContain('Credits view: ' + message)+ expect(text).not.toContain('expired')+ expect(text).not.toContain('No usage data.')+ })+ it('shows recovered limits alongside the failed view', async () => {+ await open(snapshot('unavailable'), [{ provider: 'grok', account: null,+ status: 'ok', limits: [limit], updatedAt: 0, diagnostics: [+ { view: 'credits', reason: 'network' }+ ] }])+ expect(host.querySelectorAll('.usage-row')).toHaveLength(1)+ expect(host.querySelector('.usage-account')?.textContent).toContain('Credits view: Could not reach Grok')+ })+ it('keeps distinct reasons from both views visible', async () => {+ await open(snapshot('unavailable'), [{ provider: 'grok', account: null,+ status: 'error', limits: [], updatedAt: 0, diagnostics: [+ { view: 'credits', reason: 'http', httpStatus: 401 },+ { view: 'default', reason: 'timeout' }+ ] }])+ const text = host.querySelector('.usage-account')?.textContent+ expect(text).toContain('Credits view: Grok authentication failed (HTTP 401)')+ expect(text).toContain('Default view: Usage request timed out')+ })+ it('respects the hidden-provider setting even on failure', async () => {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, hiddenUsageProviders: ['grok'] } })+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ vi.stubGlobal('nodeTerminal', { usage: {+ fetch: async () => snapshot('unavailable'),+ providers: async () => [{ provider: 'grok', status: 'error', limits: [],+ diagnostics: [{ view: 'credits', reason: 'network' }] }],+ onUpdate: () => () => {}+ } })+ await act(async () => root.render(<UsageIndicator />))+ expect(host.querySelector('.usage-indicator')).toBeNull()+ })+ it('supports older snapshots without diagnostics', async () => {+ await open(snapshot('unavailable'), [{ provider: 'grok', account: null,+ status: 'error', limits: [], updatedAt: 0 }])+ expect(host.querySelector('.usage-account')?.textContent).toContain('Could not read usage.')+ })+})diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsxindex 7599233e9..5abda29dd 100644--- a/src/renderer/components/UsageIndicator.tsx+++ b/src/renderer/components/UsageIndicator.tsx@@ -1,3 +1,4 @@+import { usageDiagnosticText } from '../lib/usageDiagnostic'import { useEffect, useMemo, useRef, useState } from 'react'import { IconReload } from './icons'import type { ClaudeUsage, ProviderUsage, RemoteAccountUsage, UsageLimit } from '@shared/types'@@ -204,7 +205,12 @@ function ProviderBlock({ u, mode }: { u: ProviderUsage; mode: 'used' | 'remainin{u.limits.map((l) => (<LimitRow key={limitKey(l)} limit={l} mode={mode} />))}- {u.limits.length === 0 && (+ {u.diagnostics?.map((diagnostic, index) => (+ <div className="usage-popover__empty" key={index}>+ {usageDiagnosticText(label, diagnostic)}+ </div>+ ))}+ {u.limits.length === 0 && !u.diagnostics?.length && (<div className="usage-popover__empty">{u.status === 'error' ? 'Could not read usage.' : 'No usage data.'}</div>@@ -398,7 +404,8 @@ export function UsageIndicator({const status = claudeUsage?.status ?? visibleRemote[0]?.usage.status ?? 'unavailable'const hasData = limits.length > 0 || enabled.length > 0const fetching = refreshing- const isError = status === 'error'+ const providerError = visibleProviders.some((p) => p.status === 'error')+ const isError = status === 'error' || providerError// 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. Considers every enabled provider, not// just Claude, so an exhausted Codex window drives the bar too.@@ -531,7 +538,7 @@ export function UsageIndicator({{limits.map((l) => (<LimitRow key={limitKey(l)} limit={l} mode={percentMode} />))}- {!hasData && <div className="usage-popover__empty">No usage data.</div>}+ {!hasData && !providerError && <div className="usage-popover__empty">No usage data.</div>}{claudeUsage?.email && (<div className="usage-account"><div className="usage-account__label">Claude Account</div>diff --git a/src/renderer/lib/usageDiagnostic.ts b/src/renderer/lib/usageDiagnostic.tsnew file mode 100644index 000000000..d3c7ced78--- /dev/null+++ b/src/renderer/lib/usageDiagnostic.ts@@ -0,0 +1,24 @@+import type { UsageDiagnostic } from '@shared/types'++/** Static copy only: diagnostics never carry provider response text or credential details. */+export function usageDiagnosticText(provider: string, diagnostic: UsageDiagnostic): string {+ const view = diagnostic.view === 'credits' ? 'Credits view' : 'Default view'+ let message: string+ switch (diagnostic.reason) {+ case 'timeout': message = 'Usage request timed out. Try again later.'; break+ case 'network': message = `Could not reach ${provider}. Check the connection and try again.`; break+ case 'invalid-response': message = 'Usage response could not be read. Try again later.'; break+ case 'http': {+ const status = diagnostic.httpStatus+ message = status === 401 || status === 403+ ? `${provider} authentication failed (HTTP ${status}). Check the CLI authentication on the machine running this project.`+ : status === 429+ ? 'Usage request rate limited (HTTP 429). Try again later.'+ : status >= 500+ ? `${provider} returned HTTP ${status}. Try again later.`+ : `Usage request failed (HTTP ${status}). Check the provider service and CLI configuration.`+ break+ }+ }+ return `${view}: ${message}`+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex f9a45f8fe..800a62af8 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2426,9 +2426,18 @@ export interface UsageLimit {* 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).*/+/** Safe billing diagnostics: never include URLs, response bodies, or exception messages. */+export type UsageDiagnostic = {+ view: 'credits' | 'default'+} & ({ reason: 'http'; httpStatus: number } | {+ reason: 'timeout' | 'network' | 'invalid-response'+})+export interface ProviderUsage {/** Agent id the limits belong to: 'claude' | 'codex' | … */provider: string+ /** Failed billing views, including failures recovered by a successful fallback. */+ diagnostics?: UsageDiagnostic[]limits: UsageLimit[]/** Signed-in identity, when the provider exposes one cheaply (email / account label). */account: string | nulldiff --git a/src/shared/usage-limits.ts b/src/shared/usage-limits.tsindex ec46dbb99..0cbf2313e 100644--- a/src/shared/usage-limits.ts+++ b/src/shared/usage-limits.ts@@ -76,7 +76,7 @@ export function hasAnyUsage(remote: readonly RemoteAccountUsage[] = []): boolean {if (claude && (claude.status === 'ok' || claude.status === 'error')) return true- if (enabledProviders(providers).length > 0) return true+ if (enabledProviders(providers).length > 0 || providers.some((p) => p.status === 'error')) return true// A remote row counts for the same reason a local Claude one does — and it is the whole point// of remote usage: someone whose Claude only ever runs on a server had no indicator at all.return remote.some((r) => r.usage.status === 'ok' || r.usage.status === 'error')