Repository navigation
feat(desktop): add Token Usage screen for AI provider limits, cost & usage - #5798
IkramBagban wants to merge 6 commits into
Conversation
…t Codex parser, graceful Claude probe
…r logos, refined cards
…aders and rollout logs
📝 WalkthroughWalkthroughAdds 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. ChangesToken Usage feature
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
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Greptile SummaryThis 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 (
Confidence Score: 3/5Safe 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
|
| 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
%%{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
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
| "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), | ||
| }); | ||
| } |
There was a problem hiding this 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.
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.| 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), | ||
| }); |
There was a problem hiding this 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.
| 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; |
There was a problem hiding this 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 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 }, | ||
| }; | ||
|
|
There was a problem hiding this 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.
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!
There was a problem hiding this comment.
💡 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( |
There was a problem hiding this comment.
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 👍 / 👎.
| return emptySnapshot(this.providerId, "ok", { | ||
| cost, | ||
| email, | ||
| planLabel, | ||
| windows: windowsFromHeaders(response.headers), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (6)
apps/desktop/src/main/lib/usage/providers/base-provider.ts (2)
45-70: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winNon-auth failures (rate limits, timeouts, network errors) all collapse into
"auth-error".Any exception here — including
RateLimitErrorandAbortErrorfromfetchWithTimeout's 10s timeout — falls back to status"auth-error"when there's no cachedlastGood. 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 affectscopilot-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 winNon-auth failures are indistinguishable from real auth failures across providers.
ProviderStatushas 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 distinctProviderStatus(e.g."error"or"unavailable") inusage-snapshot.tsand 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.okcases, 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 winAll 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 winValidate persisted snapshots before reviving them.
entry as ProviderSnapshottrusts the on-disk shape completely; a schema check withsafeParse()inreviveSnapshots/loadPersistedwould 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 valuePolish the grammar for immediate resets.
When
formatTimeToResetreturns"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 valueSimplify grid gap classes.
gap-x-4 gap-y-4can be simplified togap-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
📒 Files selected for processing (42)
apps/desktop/src/lib/trpc/routers/index.tsapps/desktop/src/lib/trpc/routers/menu.tsapps/desktop/src/lib/trpc/routers/usage.tsapps/desktop/src/main/index.tsapps/desktop/src/main/lib/tray/index.tsapps/desktop/src/main/lib/usage/log-parsers/claude-log-parser.tsapps/desktop/src/main/lib/usage/log-parsers/codex-log-parser.tsapps/desktop/src/main/lib/usage/log-parsers/cost-aggregator.tsapps/desktop/src/main/lib/usage/log-parsers/log-files.tsapps/desktop/src/main/lib/usage/pricing-table.tsapps/desktop/src/main/lib/usage/providers/base-provider.tsapps/desktop/src/main/lib/usage/providers/claude-provider.tsapps/desktop/src/main/lib/usage/providers/codex-provider.tsapps/desktop/src/main/lib/usage/providers/codex-rate-limits.tsapps/desktop/src/main/lib/usage/providers/copilot-provider.tsapps/desktop/src/main/lib/usage/providers/credentials.tsapps/desktop/src/main/lib/usage/providers/gemini-provider.tsapps/desktop/src/main/lib/usage/providers/window-pace.tsapps/desktop/src/main/lib/usage/usage-collector.tsapps/desktop/src/main/lib/usage/usage-settings.tsapps/desktop/src/main/lib/usage/usage-snapshot.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarHeader/DashboardSidebarHeader.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/hooks/useUsageBadge/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/hooks/useUsageBadge/useUsageBadge.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/CostStats/CostStats.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/CostStats/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/DailyBarChart/DailyBarChart.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/DailyBarChart/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/NoDataStrip/NoDataStrip.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/NoDataStrip/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderCard/ProviderCard.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderCard/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderLogo/ProviderLogo.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/ProviderLogo/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/RateLimitBar/RateLimitBar.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/RateLimitBar/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageSettingsPopover/UsageSettingsPopover.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageSettingsPopover/index.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/page.tsxapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/types.tsapps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/utils/format.tsapps/desktop/src/renderer/routes/_authenticated/layout.tsx
| 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 }, | ||
| }; |
There was a problem hiding this comment.
🗄️ 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:
- 1: https://www.anthropic.com/claude/fable
- 2: https://platform.claude.com/docs/en/about-claude/models/introducing-claude-fable-5-and-claude-mythos-5
- 3: https://platform.claude.com/docs/en/about-claude/pricing
- 4: https://platform.claude.com/docs/en/about-claude/pricing.md
- 5: https://benchlm.ai/anthropic/api-pricing
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.
| 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.
…ost cutoff and Codex timestamp fallback
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
src/main/lib/usage/) — polls providers every 5 min, persists the last snapshot to~/.superset/usage-snapshot.json, emits updates over anEventEmitter. Per-provider 10s timeout, 429 backoff, last-good-value fallback.Claude Code-credentialsKeychain entry and harvests theanthropic-ratelimit-unified-{5h,7d}-*headers from a minimal/v1/messagesprobe → real 5-hour + weekly windows with reserve/pace projection.rate_limitssnapshot Codex writes into its rollout session logs (passive, zero quota cost) → real weekly/monthly + Spark windows, credits, and plan.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 typecheckandbun run lintboth pass clean (lint exit 0, warnings-as-errors).Claude limits verified live against a real Pro account — confirmed the
anthropic-ratelimit-unified-5h/7dheaders return real utilization + reset times.Codex limits verified against real
~/.codex/sessions/**/rollout-*.jsonlfiles — confirmedrate_limits.primary/secondary,credits, andplan_typeparse correctly.Cost parsing validated against real
~/.claude/projectsand~/.codexlogs; format guards returnnull(not a crash) on unknown shapes.Renders safely with no provider credentials — every provider falls back to a "no data yet" state.
Checklist
type(scope): subject)bun run lintandbun run typecheckpass (CI fails on lint warnings too)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
usage.*tRPC router for get/refresh/subscribe plus settings; menu router gainsnavigateto open /usage.Bug Fixes
Written for commit cf31b3a. Summary will update on new commits.
Summary by CodeRabbit