Skip to content

feat(desktop): add Token Usage screen for AI provider limits, cost & usage - #5798

Closed
IkramBagban wants to merge 6 commits into
ParadevAI:mainfrom
IkramBagban:enchanting-thread
Closed

IkramBagban wants to merge 6 commits into
ParadevAI:mainfrom
IkramBagban:enchanting-thread

Conversation

@IkramBagban

@IkramBagban IkramBagban commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

What & why

fixes #5733

Adds a Token Usage screen to the desktop sidebar that shows, per AI provider, how much quota is left, when it resets, and 30-day cost — so you can see you're about to hit a rate limit before an agent run does.

Everything is computed on-device. No telemetry, nothing sent to Superset servers; credential files are read-only and refreshed tokens stay in memory.

What's included

  • Main-process collector (src/main/lib/usage/) — polls providers every 5 min, persists the last snapshot to ~/.superset/usage-snapshot.json, emits updates over an EventEmitter. Per-provider 10s timeout, 429 backoff, last-good-value fallback.
  • Real limit data (verified live):
    • Claude — reads the live OAuth token from the Claude Code-credentials Keychain entry and harvests the anthropic-ratelimit-unified-{5h,7d}-* headers from a minimal /v1/messages probe → real 5-hour + weekly windows with reserve/pace projection.
    • Codex — reads the rate_limits snapshot Codex writes into its rollout session logs (passive, zero quota cost) → real weekly/monthly + Spark windows, credits, and plan.
    • Copilot / Gemini — show identity/cost or a "not signed in" state until authed (no fabricated data).
  • Cost stats estimated locally from CLI logs at API rates, with a bundled pricing table (cache-read/write priced separately).
  • Ambient indicators — tray menu section + worst-window % tooltip, sidebar dot badge (amber ≥80%, red ≥95%), and 80%/95% native notifications. All toggleable from a settings popover.
  • tRPC router (usage.*) using the observable subscription pattern; renderer route at /usage.

No feature gating — it's a local utility that benefits every user running agents.

How I tested it

  • bun run typecheck and bun run lint both pass clean (lint exit 0, warnings-as-errors).

  • Claude limits verified live against a real Pro account — confirmed the anthropic-ratelimit-unified-5h/7d headers return real utilization + reset times.

  • Codex limits verified against real ~/.codex/sessions/**/rollout-*.jsonl files — confirmed rate_limits.primary/secondary, credits, and plan_type parse correctly.

  • Cost parsing validated against real ~/.claude/projects and ~/.codex logs; format guards return null (not a crash) on unknown shapes.

  • Renders safely with no provider credentials — every provider falls back to a "no data yet" state.

    Checklist

    • PR title follows conventional commits (type(scope): subject)
    • bun run lint and bun run typecheck pass (CI fails on lint warnings too)
    • "Allow edits from maintainers" is checked on fork PRs

Summary by cubic

Adds a Token Usage screen in the desktop app to show provider limits, remaining quota, and 30‑day cost so you can spot limits before runs fail. All data is computed on-device from provider headers and local CLI logs—no telemetry.

  • New Features

    • Main-process usage collector: polls every 5 min, 10s timeout, 429 backoff, persists last snapshot to ~/.superset/usage-snapshot.json, emits updates.
    • Providers: Claude (live unified 5h/7d headers via OAuth; plan/email), Codex (rate_limits, credits, plan from rollout logs), Copilot & Gemini (auth/plan state; no fabricated data).
    • Cost: local estimates from Claude/Codex logs with a bundled pricing table (cache reads/writes priced separately); 30‑day buckets and today’s spend.
    • UI: new /usage route with provider cards, rate‑limit bars, cost stats, and a 30‑day mini chart; “No data yet” strip for other agents.
    • Tray and alerts: tray section with per‑provider % and reset hints, “View details” action, tooltip shows worst %, sidebar dot badge (amber ≥80%, red ≥95%), native notifications at 80%/95%.
    • Settings: popover to toggle sidebar badge, tray percentage, and notifications; settings persisted per user.
    • API: usage.* tRPC router for get/refresh/subscribe plus settings; menu router gains navigate to open /usage.
    • Lifecycle: collector starts with the app and disposes on quit; tray menu/tooltip refresh on usage updates and setting changes.
  • Bug Fixes

    • Claude: surface probe failures as card messages and cancel probe response bodies to avoid socket leaks.
    • Cost data: align 30‑day buckets to local midnight and fall back to file modified time when Codex timestamps are missing.

Written for commit cf31b3a. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features
    • Added a Token Usage dashboard with provider cards, cost/token summaries, daily activity charts, and rate-limit windows, plus a manual refresh action.
    • Added live usage tracking for major providers and a sidebar gauge badge that reflects the worst active window, with optional notifications.
    • Enhanced the desktop tray with provider usage/tooltips and a “view details” section, kept in sync automatically; added settings to control badge and percentage display.
  • Bug Fixes
    • Improved resilience for missing/expired credentials, partial/unavailable usage data, rate-limit backoff behavior, and approximate cost reporting.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds desktop token usage collection for Claude, Codex, Copilot, and Gemini, including local log-based cost aggregation, rate-limit snapshots, persistence, tray integration, notifications, tRPC APIs, and a new Token Usage dashboard with sidebar indicators.

Changes

Token Usage feature

Layer / File(s) Summary
Usage data and cost pipeline
apps/desktop/src/main/lib/usage/usage-snapshot.ts, apps/desktop/src/main/lib/usage/pricing-table.ts, apps/desktop/src/main/lib/usage/log-parsers/*
Defines usage contracts, provider pricing, log discovery and parsing, and 30-day cost aggregation.
Provider collectors and rate limits
apps/desktop/src/main/lib/usage/providers/*
Adds shared collection behavior, credential helpers, provider collectors, rate-limit parsing, and pace estimation.
Snapshot lifecycle and settings
apps/desktop/src/main/lib/usage/usage-collector.ts, apps/desktop/src/main/lib/usage/usage-settings.ts
Polls providers, persists snapshots, emits updates, sends threshold notifications, and stores display settings.
Desktop runtime, tray, and tRPC wiring
apps/desktop/src/main/index.ts, apps/desktop/src/main/lib/tray/index.ts, apps/desktop/src/lib/trpc/routers/*
Starts and disposes collection, exposes usage procedures and navigation events, and updates tray usage information.
Token Usage dashboard
apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/*
Adds the usage route, provider cards, rate-limit bars, cost statistics, charts, settings, logos, and formatting utilities.
Usage navigation and sidebar badge
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/*, apps/desktop/src/renderer/routes/_authenticated/_dashboard/hooks/useUsageBadge/*, apps/desktop/src/renderer/routes/_authenticated/layout.tsx
Adds the Token Usage sidebar entry, live threshold badge state, and menu-driven navigation to /usage.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DesktopApp
  participant UsageCollector
  participant ProviderCLIs
  participant UsageRouter
  participant UsageDashboard
  participant Tray
  DesktopApp->>UsageCollector: start polling
  UsageCollector->>ProviderCLIs: read credentials, logs, and rate limits
  ProviderCLIs-->>UsageCollector: provider snapshots and cost data
  UsageCollector->>UsageRouter: emit usage-updated
  UsageRouter-->>UsageDashboard: publish snapshot updates
  UsageCollector->>Tray: refresh tooltip and menu
  UsageDashboard->>UsageRouter: request refresh or update settings
  UsageRouter->>UsageCollector: refresh collection or apply settings
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.59% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes implement the Token Usage screen, provider windows, costs, badges, notifications, collector, and supported providers requested in #5733.
Out of Scope Changes check ✅ Passed The PR stays focused on the Token Usage feature set and its supporting plumbing, with no clear unrelated additions.
Title check ✅ Passed The title is conventional, concise, and accurately summarizes the new Token Usage screen and related desktop usage features.
Description check ✅ Passed The description covers What & why, How I tested it, and the checklist, matching the template aside from missing screenshots.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a Token Usage screen to the desktop sidebar that shows per-provider rate-limit windows, 30-day cost estimates, and ambient indicators (tray tooltip, sidebar badge, native notifications). All data is collected on-device by a new main-process polling module (src/main/lib/usage/) wired over tRPC to the renderer.

  • Main-process collector polls Claude (live OAuth probe), Codex (passive log parsing), Copilot, and Gemini every 5 minutes, persists a snapshot to ~/.superset/usage-snapshot.json, and emits usage-updated events consumed by the tray and the tRPC subscription.
  • Renderer adds a /usage route with per-provider cards showing rate-limit progress bars, a 30-day cost bar chart, and a settings popover; a sidebar badge and tray tooltip reflect the worst-window utilization in real time.
  • Log parsers walk ~/.claude/projects and ~/.codex/sessions JSONL/JSON files to estimate costs from a bundled pricing table.

Confidence Score: 3/5

Safe to merge after addressing the three defects in claude-provider and the notification loop; none affect user data but two cause real behavioral gaps.

The Claude provider makes a live API call on every poll but leaves the response body unconsumed (TCP connection not returned to the pool) and silently returns a healthy snapshot for 5xx responses, hiding Anthropic outages from the UI. The notification loop uses break where continue is needed, meaning the 80% warning is permanently skipped whenever usage jumps past the 80% mark in a single 5-minute poll window. These three issues are in the same provider file and the notification path — the rest of the feature (log parsers, Codex/Copilot/Gemini providers, tRPC wiring, renderer) looks solid.

claude-provider.ts (response body leak + error status handling) and usage-collector.ts (notification threshold loop) need fixes before the feature works as described in all edge cases.

Important Files Changed

Filename Overview
apps/desktop/src/main/lib/usage/providers/claude-provider.ts Probes Anthropic's /v1/messages endpoint every 5 minutes; response body is never consumed (connection leak), and non-401/403 HTTP errors fall through to an "ok" snapshot.
apps/desktop/src/main/lib/usage/usage-collector.ts Orchestrates 5-minute polling, persistence, and threshold notifications; break in maybeNotify skips the 80% threshold when the 95% key was already recorded.
apps/desktop/src/main/lib/usage/pricing-table.ts Hardcoded pricing rates with prefix-match fallback; contains an unrecognized model entry ("claude-fable-5") that could silently mis-price unknown Claude models.
apps/desktop/src/main/lib/usage/providers/codex-provider.ts Reads Codex auth and passively parses session rollout logs for rate limits; logic is sound with graceful fallbacks.
apps/desktop/src/main/lib/usage/providers/credentials.ts Reads keychain/JSON credentials and decodes JWT payloads without verification; appropriate for local display-only use.
apps/desktop/src/main/lib/usage/log-parsers/cost-aggregator.ts Aggregates token usage entries into 30-day cost stats with per-session and per-model breakdowns; logic is correct.
apps/desktop/src/main/lib/usage/providers/window-pace.ts Projects whether current burn rate lasts until reset; the 0.01 minimum elapsed-fraction clamp can produce very pessimistic reserve estimates at the very start of a window.
apps/desktop/src/lib/trpc/routers/usage.ts tRPC router wiring getSnapshot, refresh, subscribe (observable), and settings endpoints; clean and correct.
apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/page.tsx Usage page that seeds from getSnapshot query and updates via subscription; dual-source (query + subscription) logic is handled correctly.
apps/desktop/src/main/lib/tray/index.ts Adds usage section (worst-window % + reset time) to the tray menu and tooltip; reads snapshots from the shared collector correctly.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant Timer as Poll Timer (5 min)
    participant Collector as UsageCollector
    participant Claude as ClaudeProvider
    participant Codex as CodexProvider
    participant Snapshot as usage-snapshot.json
    participant Tray as Tray Menu
    participant tRPC as tRPC Router
    participant UI as Renderer (UsagePage)

    Timer->>Collector: poll()
    par
        Collector->>Claude: fetchSnapshot()
        Claude-->>Claude: readKeychainSecret / readJsonFile
        Claude->>Claude: POST /v1/messages (1-token probe)
        Claude-->>Collector: ProviderSnapshot (headers)
    and
        Collector->>Codex: fetchSnapshot()
        Codex-->>Codex: readJsonFile(auth.json)
        Codex-->>Codex: readLatestCodexRateLimits (JSONL scan)
        Codex-->>Collector: ProviderSnapshot
    end
    Collector->>Snapshot: writeFileSync (persist)
    Collector->>Tray: emit(usage-updated)
    Collector->>tRPC: emit(usage-updated)
    tRPC-->>UI: subscription onData(snapshots)
    UI-->>UI: setSnapshots → re-render cards + badge
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant Timer as Poll Timer (5 min)
    participant Collector as UsageCollector
    participant Claude as ClaudeProvider
    participant Codex as CodexProvider
    participant Snapshot as usage-snapshot.json
    participant Tray as Tray Menu
    participant tRPC as tRPC Router
    participant UI as Renderer (UsagePage)

    Timer->>Collector: poll()
    par
        Collector->>Claude: fetchSnapshot()
        Claude-->>Claude: readKeychainSecret / readJsonFile
        Claude->>Claude: POST /v1/messages (1-token probe)
        Claude-->>Collector: ProviderSnapshot (headers)
    and
        Collector->>Codex: fetchSnapshot()
        Codex-->>Codex: readJsonFile(auth.json)
        Codex-->>Codex: readLatestCodexRateLimits (JSONL scan)
        Codex-->>Collector: ProviderSnapshot
    end
    Collector->>Snapshot: writeFileSync (persist)
    Collector->>Tray: emit(usage-updated)
    Collector->>tRPC: emit(usage-updated)
    tRPC-->>UI: subscription onData(snapshots)
    UI-->>UI: setSnapshots → re-render cards + badge
Loading
Prompt To Fix All With AI
Fix the following 4 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 4
apps/desktop/src/main/lib/usage/providers/claude-provider.ts:126-150
Non-2xx status codes other than 401/403 (e.g. 500, 503) fall through to the `ok` return path. `windowsFromHeaders` returns `[]` because the error response carries no rate-limit headers, so the snapshot shows `status: "ok"` with empty windows. A transient Anthropic outage would silently clear the displayed rate-limit data and show the provider as healthy.

### Issue 2 of 4
apps/desktop/src/main/lib/usage/providers/claude-provider.ts:135-149
The response body stream is opened by `fetchWithTimeout` but never consumed or cancelled. Node.js undici (the underlying fetch implementation) holds the TCP socket open until the body is drained or the connection times out, preventing connection reuse. Since this probe fires every 5 minutes, sockets accumulate. Drain or cancel the body after reading the headers.

```suggestion
		// Drain the body regardless of status to release the TCP connection.
		await response.body?.cancel().catch(() => undefined);

		if (response.status === 401 || response.status === 403) {
			return emptySnapshot(this.providerId, "auth-error", {
				cost,
				email,
				planLabel,
				errorMessage: "Session expired — re-authenticate the Claude CLI.",
			});
		}

		if (!response.ok) {
			return emptySnapshot(this.providerId, "auth-error", {
				cost,
				email,
				planLabel,
				errorMessage: `Anthropic API returned ${response.status} — usage data unavailable.`,
			});
		}

		return emptySnapshot(this.providerId, "ok", {
			cost,
			email,
			planLabel,
			windows: windowsFromHeaders(response.headers),
		});
```

### Issue 3 of 4
apps/desktop/src/main/lib/usage/usage-collector.ts:120
Using `break` here exits the entire threshold loop when the 95% threshold was already notified, so the 80% threshold is never independently evaluated. If a window jumps from below 80% to above 95% in a single poll cycle (e.g. 74% → 97%), the 95% notification fires and `break`s — the 80% notification is silently skipped for the rest of that reset cycle. This line should use `continue` instead of `break` to allow each threshold to be checked independently.

### Issue 4 of 4
apps/desktop/src/main/lib/usage/pricing-table.ts:36
`"claude-fable-5"` does not appear in Anthropic's published model catalogue. If users run a session with an unrelated model whose name happens to start with `claude-fable-5`, the prefix-match logic in `matchModelRate` would apply these rates silently. Consider removing or verifying this entry against the official pricing page referenced in the file's comment.

Reviews (1): Last reviewed commit: "feat(desktop): show real Claude and Code..." | Re-trigger Greptile

Comment on lines +126 to +150
"content-type": "application/json",
},
body: JSON.stringify({
model: PROBE_MODEL,
max_tokens: 1,
messages: [{ role: "user", content: "hi" }],
}),
});

if (response.status === 401 || response.status === 403) {
return emptySnapshot(this.providerId, "auth-error", {
cost,
email,
planLabel,
errorMessage: "Session expired — re-authenticate the Claude CLI.",
});
}

return emptySnapshot(this.providerId, "ok", {
cost,
email,
planLabel,
windows: windowsFromHeaders(response.headers),
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Non-2xx status codes other than 401/403 (e.g. 500, 503) fall through to the ok return path. windowsFromHeaders returns [] because the error response carries no rate-limit headers, so the snapshot shows status: "ok" with empty windows. A transient Anthropic outage would silently clear the displayed rate-limit data and show the provider as healthy.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/usage/providers/claude-provider.ts
Line: 126-150

Comment:
Non-2xx status codes other than 401/403 (e.g. 500, 503) fall through to the `ok` return path. `windowsFromHeaders` returns `[]` because the error response carries no rate-limit headers, so the snapshot shows `status: "ok"` with empty windows. A transient Anthropic outage would silently clear the displayed rate-limit data and show the provider as healthy.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +135 to +149
if (response.status === 401 || response.status === 403) {
return emptySnapshot(this.providerId, "auth-error", {
cost,
email,
planLabel,
errorMessage: "Session expired — re-authenticate the Claude CLI.",
});
}

return emptySnapshot(this.providerId, "ok", {
cost,
email,
planLabel,
windows: windowsFromHeaders(response.headers),
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 The response body stream is opened by fetchWithTimeout but never consumed or cancelled. Node.js undici (the underlying fetch implementation) holds the TCP socket open until the body is drained or the connection times out, preventing connection reuse. Since this probe fires every 5 minutes, sockets accumulate. Drain or cancel the body after reading the headers.

Suggested change
if (response.status === 401 || response.status === 403) {
return emptySnapshot(this.providerId, "auth-error", {
cost,
email,
planLabel,
errorMessage: "Session expired — re-authenticate the Claude CLI.",
});
}
return emptySnapshot(this.providerId, "ok", {
cost,
email,
planLabel,
windows: windowsFromHeaders(response.headers),
});
// Drain the body regardless of status to release the TCP connection.
await response.body?.cancel().catch(() => undefined);
if (response.status === 401 || response.status === 403) {
return emptySnapshot(this.providerId, "auth-error", {
cost,
email,
planLabel,
errorMessage: "Session expired — re-authenticate the Claude CLI.",
});
}
if (!response.ok) {
return emptySnapshot(this.providerId, "auth-error", {
cost,
email,
planLabel,
errorMessage: `Anthropic API returned ${response.status} — usage data unavailable.`,
});
}
return emptySnapshot(this.providerId, "ok", {
cost,
email,
planLabel,
windows: windowsFromHeaders(response.headers),
});
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/usage/providers/claude-provider.ts
Line: 135-149

Comment:
The response body stream is opened by `fetchWithTimeout` but never consumed or cancelled. Node.js undici (the underlying fetch implementation) holds the TCP socket open until the body is drained or the connection times out, preventing connection reuse. Since this probe fires every 5 minutes, sockets accumulate. Drain or cancel the body after reading the headers.

```suggestion
		// Drain the body regardless of status to release the TCP connection.
		await response.body?.cancel().catch(() => undefined);

		if (response.status === 401 || response.status === 403) {
			return emptySnapshot(this.providerId, "auth-error", {
				cost,
				email,
				planLabel,
				errorMessage: "Session expired — re-authenticate the Claude CLI.",
			});
		}

		if (!response.ok) {
			return emptySnapshot(this.providerId, "auth-error", {
				cost,
				email,
				planLabel,
				errorMessage: `Anthropic API returned ${response.status} — usage data unavailable.`,
			});
		}

		return emptySnapshot(this.providerId, "ok", {
			cost,
			email,
			planLabel,
			windows: windowsFromHeaders(response.headers),
		});
```

How can I resolve this? If you propose a fix, please make it concise.


const resetCycle = window.resetAt?.toISOString() ?? "none";
const key = `${snapshot.providerId}:${window.label}:${threshold}:${resetCycle}`;
if (this.notifiedKeys.has(key)) break;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Using break here exits the entire threshold loop when the 95% threshold was already notified, so the 80% threshold is never independently evaluated. If a window jumps from below 80% to above 95% in a single poll cycle (e.g. 74% → 97%), the 95% notification fires and breaks — the 80% notification is silently skipped for the rest of that reset cycle. This line should use continue instead of break to allow each threshold to be checked independently.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/usage/usage-collector.ts
Line: 120

Comment:
Using `break` here exits the entire threshold loop when the 95% threshold was already notified, so the 80% threshold is never independently evaluated. If a window jumps from below 80% to above 95% in a single poll cycle (e.g. 74% → 97%), the 95% notification fires and `break`s — the 80% notification is silently skipped for the rest of that reset cycle. This line should use `continue` instead of `break` to allow each threshold to be checked independently.

How can I resolve this? If you propose a fix, please make it concise.

"gpt-4.1": { inputPerMillion: 2, outputPerMillion: 8 },
"gpt-4.5": { inputPerMillion: 75, outputPerMillion: 150 },
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 "claude-fable-5" does not appear in Anthropic's published model catalogue. If users run a session with an unrelated model whose name happens to start with claude-fable-5, the prefix-match logic in matchModelRate would apply these rates silently. Consider removing or verifying this entry against the official pricing page referenced in the file's comment.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/usage/pricing-table.ts
Line: 36

Comment:
`"claude-fable-5"` does not appear in Anthropic's published model catalogue. If users run a session with an unrelated model whose name happens to start with `claude-fable-5`, the prefix-match logic in `matchModelRate` would apply these rates silently. Consider removing or verifying this entry against the official pricing page referenced in the file's comment.

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3fbb429f83

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const retryMs = retryAfter
? Number.parseInt(retryAfter, 10) * 1000
: DEFAULT_BACKOFF_MS;
throw new RateLimitError(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve Claude quota headers on 429

When the Claude probe itself is rate-limited, the response is the one most likely to contain the limit/reset headers this feature needs, but throwing here discards it before ClaudeProvider can parse those headers. On a first launch with no lastGood snapshot, collect() converts that into an auth-error “Rate limited” snapshot, so the page/tray show no 100% window or reset time exactly when the user is out of quota.

Useful? React with 👍 / 👎.

Comment on lines +144 to +148
return emptySnapshot(this.providerId, "ok", {
cost,
email,
planLabel,
windows: windowsFromHeaders(response.headers),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject failed Claude probes before caching

If the Claude probe returns any non-auth failure, such as a 400 from a model/beta mismatch or a transient 5xx/529, this still marks the snapshot as ok. Because ProviderCollector.collect() caches every ok snapshot as lastGood, a failed response with no unified headers replaces a previously valid quota reading with empty windows instead of preserving the last good data or surfacing an error.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (6)
apps/desktop/src/main/lib/usage/providers/base-provider.ts (2)

45-70: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Non-auth failures (rate limits, timeouts, network errors) all collapse into "auth-error".

Any exception here — including RateLimitError and AbortError from fetchWithTimeout's 10s timeout — falls back to status "auth-error" when there's no cached lastGood. This is misleading: the UI status implies a credentials problem when the actual cause could be a transient outage or rate limit. See consolidated comment for the full cross-file picture (also affects copilot-provider.ts).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/main/lib/usage/providers/base-provider.ts` around lines 45 -
70, Update collect() in the base provider to preserve distinct failure statuses
instead of returning "auth-error" for every exception. Map RateLimitError,
timeout/AbortError, and other network or transient failures to the appropriate
non-auth status while retaining "auth-error" only for credential-related
failures; keep the existing lastGood fallback and rate-limit backoff behavior
unchanged.

1-1: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Non-auth failures are indistinguishable from real auth failures across providers. ProviderStatus has no status for generic/transient errors, so both the shared collector's catch-all and Copilot's failure branch report unrelated failures (rate limits, timeouts, network errors, 5xx) as "auth-error", which can send users to needlessly re-authenticate CLIs.

  • apps/desktop/src/main/lib/usage/providers/base-provider.ts#L58-69: add a distinct ProviderStatus (e.g. "error" or "unavailable") in usage-snapshot.ts and use it here for non-credential exceptions (rate limits, timeouts, parse errors), reserving "auth-error" for actual 401/403-style failures.
  • apps/desktop/src/main/lib/usage/providers/copilot-provider.ts#L52-56: use the new generic status (and a non-"session expired" message) for non-401/403 !response.ok cases, keeping "Session expired — re-authenticate" only for actual auth failures.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/main/lib/usage/providers/base-provider.ts` at line 1,
Distinguish generic provider failures from authentication failures by adding a
new status such as "error" or "unavailable" to ProviderStatus in
usage-snapshot.ts. Update the shared collector catch-all in the base provider to
use this status for non-credential exceptions, reserving "auth-error" for
401/403-style failures. In Copilot’s non-OK response branch, use the generic
status and a message other than “Session expired — re-authenticate” unless the
response indicates an actual 401/403 authentication failure.
apps/desktop/src/main/lib/usage/providers/copilot-provider.ts (1)

52-56: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

All non-ok responses labeled "Session expired," even for transient/server errors.

Any failure from the token endpoint (including 5xx) is reported with the same "re-authenticate the Copilot CLI" messaging. See consolidated comment for the cross-file picture with base-provider.ts.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/main/lib/usage/providers/copilot-provider.ts` around lines
52 - 56, Update the non-ok response handling in the Copilot provider’s token
request so only authentication-specific failures produce the “Session expired —
re-authenticate the Copilot CLI.” message; classify transient and server-side
responses separately using the existing error categories or response status,
while preserving the emptySnapshot return flow.
apps/desktop/src/main/lib/usage/usage-collector.ts (1)

23-36: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Validate persisted snapshots before reviving them. entry as ProviderSnapshot trusts the on-disk shape completely; a schema check with safeParse() in reviveSnapshots/loadPersisted would fall back to [] on version drift instead of spreading malformed data into the UI/tRPC contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/main/lib/usage/usage-collector.ts` around lines 23 - 36,
Validate each persisted entry with the existing snapshot schema’s safeParse in
reviveSnapshots (or its loadPersisted caller) before converting dates or
spreading fields. If the raw value or any entry fails validation, return []
rather than reviving malformed data; preserve the current date conversion for
valid ProviderSnapshot values.
apps/desktop/src/main/lib/tray/index.ts (1)

228-229: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Polish the grammar for immediate resets.

When formatTimeToReset returns "now", the suffix string currently becomes " · resets in now", which reads a bit awkwardly. Consider adjusting the ternary logic to handle the immediate reset case more naturally.

✨ Proposed fix
-		const resetLabel = formatTimeToReset(window.resetAt);
-		const suffix = resetLabel ? ` · resets in ${resetLabel}` : "";
+		const resetLabel = formatTimeToReset(window.resetAt);
+		const suffix = resetLabel === "now" ? " · resetting now" : resetLabel ? ` · resets in ${resetLabel}` : "";
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/main/lib/tray/index.ts` around lines 228 - 229, Update the
suffix construction alongside formatTimeToReset so a "now" reset produces
natural immediate-reset wording instead of appending "resets in now"; preserve
the existing countdown wording for other non-empty reset labels and the empty
suffix when no label is returned.
apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/CostStats/CostStats.tsx (1)

24-26: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify grid gap classes.

gap-x-4 gap-y-4 can be simplified to gap-4.

♻️ Proposed refactor
-		<div className="grid grid-cols-2 gap-x-4 gap-y-4">
+		<div className="grid grid-cols-2 gap-4">
 			<StatCell label="Today" value={`${prefix}$${formatUsd(cost.todayUsd)}`} />
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/CostStats/CostStats.tsx`
around lines 24 - 26, In the CostStats component’s returned grid container,
replace the separate gap-x-4 and gap-y-4 classes with the equivalent gap-4
utility while preserving the existing layout and StatCell rendering.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/desktop/src/main/lib/usage/log-parsers/cost-aggregator.ts`:
- Around line 54-60: Align the cutoff used by the cost totals with the oldest
calendar-day bucket created in the bucket initialization loop. Update the cutoff
calculation near localDateKey and buckets so entries included in thirtyDayUsd
and thirtyDayTokens always map to one of the WINDOW_DAYS daily buckets,
preserving the existing bucket range and aggregation behavior.

In `@apps/desktop/src/main/lib/usage/pricing-table.ts`:
- Around line 24-29: Update the claude-fable-5 entry in CLAUDE_MODELS to use
inputPerMillion 10 and outputPerMillion 50, leaving all other model rates
unchanged.

In `@apps/desktop/src/main/lib/usage/providers/claude-provider.ts`:
- Around line 135-150: Update the response-status handling in the Claude
provider method around the 401/403 branch so every non-2xx response is reported
as an error rather than falling through to the `"ok"` snapshot. Preserve the
existing auth-specific message for 401/403, and return an appropriate error
snapshot with a descriptive errorMessage for other failure statuses; only
successful responses should use windowsFromHeaders and status `"ok"`.

In `@apps/desktop/src/main/lib/usage/providers/codex-rate-limits.ts`:
- Around line 95-102: Update the timestamp selection in the rate-limit reading
logic to detect when new Date(parsed.timestamp).getTime() returns NaN and fall
back to file.mtimeMs. Preserve valid parsed timestamps and the existing
latestTime comparison so valid rate-limit data is not discarded.

---

Nitpick comments:
In `@apps/desktop/src/main/lib/tray/index.ts`:
- Around line 228-229: Update the suffix construction alongside
formatTimeToReset so a "now" reset produces natural immediate-reset wording
instead of appending "resets in now"; preserve the existing countdown wording
for other non-empty reset labels and the empty suffix when no label is returned.

In `@apps/desktop/src/main/lib/usage/providers/base-provider.ts`:
- Around line 45-70: Update collect() in the base provider to preserve distinct
failure statuses instead of returning "auth-error" for every exception. Map
RateLimitError, timeout/AbortError, and other network or transient failures to
the appropriate non-auth status while retaining "auth-error" only for
credential-related failures; keep the existing lastGood fallback and rate-limit
backoff behavior unchanged.
- Line 1: Distinguish generic provider failures from authentication failures by
adding a new status such as "error" or "unavailable" to ProviderStatus in
usage-snapshot.ts. Update the shared collector catch-all in the base provider to
use this status for non-credential exceptions, reserving "auth-error" for
401/403-style failures. In Copilot’s non-OK response branch, use the generic
status and a message other than “Session expired — re-authenticate” unless the
response indicates an actual 401/403 authentication failure.

In `@apps/desktop/src/main/lib/usage/providers/copilot-provider.ts`:
- Around line 52-56: Update the non-ok response handling in the Copilot
provider’s token request so only authentication-specific failures produce the
“Session expired — re-authenticate the Copilot CLI.” message; classify transient
and server-side responses separately using the existing error categories or
response status, while preserving the emptySnapshot return flow.

In `@apps/desktop/src/main/lib/usage/usage-collector.ts`:
- Around line 23-36: Validate each persisted entry with the existing snapshot
schema’s safeParse in reviveSnapshots (or its loadPersisted caller) before
converting dates or spreading fields. If the raw value or any entry fails
validation, return [] rather than reviving malformed data; preserve the current
date conversion for valid ProviderSnapshot values.

In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/CostStats/CostStats.tsx`:
- Around line 24-26: In the CostStats component’s returned grid container,
replace the separate gap-x-4 and gap-y-4 classes with the equivalent gap-4
utility while preserving the existing layout and StatCell rendering.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fa1c9252-4a74-4e79-bae5-9bb7abe3c765

📥 Commits

Reviewing files that changed from the base of the PR and between 2ce34e6 and 3fbb429.

📒 Files selected for processing (42)
  • apps/desktop/src/lib/trpc/routers/index.ts
  • apps/desktop/src/lib/trpc/routers/menu.ts
  • apps/desktop/src/lib/trpc/routers/usage.ts
  • apps/desktop/src/main/index.ts
  • apps/desktop/src/main/lib/tray/index.ts
  • apps/desktop/src/main/lib/usage/log-parsers/claude-log-parser.ts
  • apps/desktop/src/main/lib/usage/log-parsers/codex-log-parser.ts
  • apps/desktop/src/main/lib/usage/log-parsers/cost-aggregator.ts
  • apps/desktop/src/main/lib/usage/log-parsers/log-files.ts
  • apps/desktop/src/main/lib/usage/pricing-table.ts
  • apps/desktop/src/main/lib/usage/providers/base-provider.ts
  • apps/desktop/src/main/lib/usage/providers/claude-provider.ts
  • apps/desktop/src/main/lib/usage/providers/codex-provider.ts
  • apps/desktop/src/main/lib/usage/providers/codex-rate-limits.ts
  • apps/desktop/src/main/lib/usage/providers/copilot-provider.ts
  • apps/desktop/src/main/lib/usage/providers/credentials.ts
  • apps/desktop/src/main/lib/usage/providers/gemini-provider.ts
  • apps/desktop/src/main/lib/usage/providers/window-pace.ts
  • apps/desktop/src/main/lib/usage/usage-collector.ts
  • apps/desktop/src/main/lib/usage/usage-settings.ts
  • apps/desktop/src/main/lib/usage/usage-snapshot.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarHeader/DashboardSidebarHeader.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/hooks/useUsageBadge/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/hooks/useUsageBadge/useUsageBadge.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/CostStats/CostStats.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/CostStats/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/DailyBarChart/DailyBarChart.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/DailyBarChart/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/NoDataStrip/NoDataStrip.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/NoDataStrip/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderCard/ProviderCard.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderCard/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderLogo/ProviderLogo.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderLogo/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/RateLimitBar/RateLimitBar.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/RateLimitBar/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageSettingsPopover/UsageSettingsPopover.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageSettingsPopover/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/page.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/types.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/utils/format.ts
  • apps/desktop/src/renderer/routes/_authenticated/layout.tsx

Comment on lines +24 to +29
const CLAUDE_MODELS: Record<string, ModelRate> = {
"claude-opus-4": { inputPerMillion: 15, outputPerMillion: 75 },
"claude-sonnet-4": { inputPerMillion: 3, outputPerMillion: 15 },
"claude-haiku-4": { inputPerMillion: 1, outputPerMillion: 5 },
"claude-fable-5": { inputPerMillion: 5, outputPerMillion: 25 },
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

What is the current API pricing for Anthropic Claude Fable 5, per million input and output tokens?

💡 Result:

As of July 20, 2026, the standard API pricing for Anthropic Claude Fable 5 is $10 USD per million input tokens and $50 USD per million output tokens [1][2][3]. Additionally, Anthropic offers discounted rates for specific use cases: - Batch API pricing is $5 per million input tokens and $25 per million output tokens [4][5]. - Prompt caching is available, with cache write and read costs structured according to standard platform rates [4][3]. - For workloads requiring US-only inference, pricing is typically subject to a 1.1x multiplier [1].

Citations:


Claude Fable 5 rate is wrong — off by 2x.
claude-fable-5 should be $10/$50 per million tokens, not $5/$25. Exact matches are treated as authoritative here, so this undercounts Fable 5 usage and hides the error from the approximate fallback.

🐛 Proposed fix
-	"claude-fable-5": { inputPerMillion: 5, outputPerMillion: 25 },
+	"claude-fable-5": { inputPerMillion: 10, outputPerMillion: 50 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const CLAUDE_MODELS: Record<string, ModelRate> = {
"claude-opus-4": { inputPerMillion: 15, outputPerMillion: 75 },
"claude-sonnet-4": { inputPerMillion: 3, outputPerMillion: 15 },
"claude-haiku-4": { inputPerMillion: 1, outputPerMillion: 5 },
"claude-fable-5": { inputPerMillion: 5, outputPerMillion: 25 },
};
const CLAUDE_MODELS: Record<string, ModelRate> = {
"claude-opus-4": { inputPerMillion: 15, outputPerMillion: 75 },
"claude-sonnet-4": { inputPerMillion: 3, outputPerMillion: 15 },
"claude-haiku-4": { inputPerMillion: 1, outputPerMillion: 5 },
"claude-fable-5": { inputPerMillion: 10, outputPerMillion: 50 },
};
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/main/lib/usage/pricing-table.ts` around lines 24 - 29,
Update the claude-fable-5 entry in CLAUDE_MODELS to use inputPerMillion 10 and
outputPerMillion 50, leaving all other model rates unchanged.

@Kitenite

Copy link
Copy Markdown
Member

Closing: main already ships this. Usage tab shipped in 60c4d27 (#6530) + 1bc9ab6 (#6585). Thanks for the PR; if you think the shipped version misses a case, open an issue and link this.

@Kitenite Kitenite closed this Aug 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Token Usage screen: provider quotas, cost stats, and tray/badge indicators

2 participants