Skip to content

Show provider credit balances alongside usage limits - #25408

Merged
nwparker merged 3 commits into
mainfrom
nwparker/provider-credit-balances-current
Oct 5, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/provider-credit-balances-current

Conversation

@nwparker

@nwparker nwparker commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1392 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1388
Prod 21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​621 $\color{#cf222e}{\Huge{\mathbf{−}}}$​31 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​590

ELI5

Show available provider credits alongside usage limits. A missing balance stays unknown; a failed refresh is shown clearly.

What Changed

This takes over @mmarabel’s provider-balance contribution in #9363 and adapts it to current main. The existing usage collector and status-bar menu now show Claude usage credits, OpenCode Zen balance, and Codex credit counts when the response supplies them. The compact segment reveals a spendable balance when a plan window caps.

OpenCode cookie discovery accepts organization workspace IDs. Its optional billing request uses the existing isolated session and workspace, while API-key usage keeps its existing priority. A missing key-response balance shows “Unavailable”; a failed cookie billing request shows “Refresh failed” without hiding valid Go quotas. Missing or invalid Claude and Codex values stay unknown, while known zero and unlimited credits remain valid.

Why

Whether a balance is known depends on the provider response and credential source. Keeping that distinction in the existing collector and menu gives users the credit information beside their limits without a separate login or a fabricated zero balance.

Linked Issue

Fixes #8145 and #9362. Supersedes the original contribution #9363, with credit to @mmarabel.

Visual Proof

The same controlled organization-cookie response reproduces the missing-workspace state before the fix and shows the balance after it. The additional captures show billing failure and installed-CLI API-key precedence. These are actual hidden-renderer captures from Orca on macOS; the HTTP responses are controlled test fixtures.

Before: organization cookie was not discovered

Before: organization cookie was not discovered

After: known Zen balance alongside Go quotas

After: known Zen balance alongside Go quotas

After: billing failure remains explicit

After: billing failure remains explicit

After: API-key usage does not invent a balance

After: API-key usage does not invent a balance

Testing

  • Manually exercised the real collector and opened provider menu in background Orca, using installed OpenCode 2.0.16 and private profiles.
  • Verified the collector equals the rendered store for a known $27.87 balance, billing failure, and API-key usage without a balance. The key was written through OpenCode’s integration API; its writer finished through stdin EOF before the refresh.
  • Focused tests cover parsing, malformed and unknown values, zero and unlimited credits, currency, menu content, and language fallback. The guard regression controls fail before the repair and pass after it.
  • Node, CLI, and renderer typechecks, lint, quality gates, and app, relay, and CLI validation builds passed on the original qualified source. The review correction passes 67 focused tests, renderer typecheck, lint, format, catalog, extraction, coverage, and changed-code quality checks. Its new Spanish and French message-order tests fail before the correction and pass after it. The current-main merge preserves the reviewed source and unrelated main changes, including the English catalog entries.

The two remaining UI cases completed with app exit and close code 0, CLI waits, and checked private endpoint closure. The earlier before and known-balance runs stopped during cleanup; their collector and menu observations are retained as partial evidence. This validates controlled responses, not a live wallet, paid provider turn, or every platform.

Review

Credit to @mmarabel for the original implementation. Unknown values are never converted to zero. Claude’s richer spend fields are retained for response compatibility; they are not asserted as a verified current live account contract.

Agent skill upstream boundary

  • Not applicable; no upstream skill implementation was copied.

Notes

Balance fields are optional in the existing payload. Credential-source precedence, remote execution ownership, and wire operations are preserved. Currency uses the existing locale-aware formatter. Complete translated balance messages control label and amount order; untranslated copy uses the existing English fallback. No new platform-dependent process or path handling is introduced.

Checklist

  • The user-visible before/after, mechanism, and choice of approach are described.
  • Actual before/after screenshots are attached without adding them to the source diff.
  • Correctness, security, performance, cross-platform, and SSH boundaries reviewed.
  • Relevant local tests, typechecks, lint, and builds passed; fresh public CI will run on this head.

Adapt the original provider-balance contribution to current main, preserve unknown values, and expose OpenCode balance refresh failures.

Co-authored-by: mmarabel <[email protected]>
@nwparker
nwparker marked this pull request as ready for review October 5, 2026 04:55
@nwparker
nwparker requested a review from brennanb2025 as a code owner October 5, 2026 04:55
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e9d6e0e1-d2f2-48eb-aa88-be8e757d4f4c
📥 Commits

Reviewing files that changed from the base of the PR and between e55b91d and f74ca2a.

📒 Files selected for processing (10)
  • src/main/proxy-guarded-fetch-call-site-audit.test.ts
  • src/renderer/src/components/status-bar/StatusBarProviderSegment.tsx
  • src/renderer/src/components/status-bar/provider-segment-balance.test.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/i18n/provider-credit-balance-locales.test.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/i18n/locales/fr.json

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

The change adds a shared extra-usage balance type to provider rate limits and maps balance data from Claude OAuth, Codex RPC, and OpenCode Go billing responses. OpenCode Go fetching now supports organization workspace IDs and can return balance-only results for explicit no-access usage responses. The status bar and tooltip display currency balances, credit counts, availability states, and capped-usage details. Locale strings and tests cover mapping, fetching, formatting, and display behavior.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to f74ca

The change shows provider balances in the status bar and tooltip. Compact balance labels are now localized as a single message, so word order is correct in each language. No merge-blocking risk remains from the reviewed evidence.

Security Architecture Review

Security architecture risk: 🔵 Low · up to f74ca

The additional billing read preserves existing credential isolation and separates balance failures from valid usage results. No introduced exploitable path was established in the examined changes. Provider-side organization authorization and portions of the affected scope remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new sensitive outcome is disclosure of billing-balance information to the application's usage display under the supplied console identity and selected organization. The inspected request targets a fixed provider origin and performs a read, not a billing mutation. Its effective organization scope depends on remote authorization.

Trust Boundaries and Controls

  • observed — Cookie input is restricted to known OpenCode authentication-cookie names. The existing isolated Electron session clears its cookie jar, applies proxy configuration before requests, installs secure cookies, and performs cleanup on completion or cookie-installation failure.
  • inferred — Accepting org_ identifiers expands the supported organization-selector namespace, not locally granted authority. Identifier validation is syntactic; the provider must authorize the supplied x-org-id against the authenticated session. Local evidence does not establish whether that remote check succeeds or fails.

Resilience and Maintainability Implications

  • observed — The production refresh queue keeps its fetching guard until the awaited cycle finishes. Result application rejects aborted cycles and mismatched credential generations; invalidating OpenCode credentials clears the visible snapshot. These existing fences also govern the newly added balance data.
  • observed — The fixed cookie-session partition and absence of caller-cancellation propagation into cookie fetches are pre-existing limitations. The new billing request adds in-flight work, but the inspected production caller remains the serialized service path; an independently reachable concurrent-call regression was not established.
🚥 Pre-merge checks | ✅ 3 | ❌ 1 | ❓ 1

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.91% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 44 functions across 26 files. (6 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive The PR description also claims to fix #9362, and the change adds Claude- and Codex-specific balance collection and display. The supplied linked-issue details cover only #8145, so I cannot determine wh… Provide #9362's direct-link status and issue text, including its coding requirements, to determine whether the Claude and Codex changes are in scope.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed [ #8145 ] The OpenCode Go collector adds optional Zen billing data, accepts organization workspace IDs, and preserves Go quota results when billing fails. The status-bar details show the balance or a …
Title check ✅ Passed The title clearly summarizes the main change: displaying provider credit balances alongside usage limits.
Description check ✅ Passed The description explains the balance display, provider-specific behavior, implementation, and testing. It is directly related to the changeset.
Full details: Out of Scope Changes check

Explanation

The PR description also claims to fix #9362, and the change adds Claude- and Codex-specific balance collection and display. The supplied linked-issue details cover only #8145, so I cannot determine whether those provider changes meet #9362 or are unrelated to the active issue scope.

Full details: Docstring Coverage

Explanation

Docstring coverage is 15.91% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 44 functions across 26 files. (6 skipped: 6 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@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: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2d9105d7-8470-4c8b-adf1-25c1ce303cda
📥 Commits

Reviewing files that changed from the base of the PR and between 16d937d and e55b91d.

📒 Files selected for processing (31)
  • src/main/rate-limits/claude-fetcher-extra-usage.test.ts
  • src/main/rate-limits/claude-oauth-usage-request.ts
  • src/main/rate-limits/claude-usage-credits.ts
  • src/main/rate-limits/claude-usage-result.ts
  • src/main/rate-limits/codex-credit-balance.ts
  • src/main/rate-limits/codex-fetcher-credit-balance.test.ts
  • src/main/rate-limits/codex-rate-limit-window-classification.ts
  • src/main/rate-limits/codex-rpc-rate-limit-probe.ts
  • src/main/rate-limits/opencode-go-status-parsing.test.ts
  • src/main/rate-limits/opencode-go-status-parsing.ts
  • src/main/rate-limits/opencode-go-usage-fetcher.test.ts
  • src/main/rate-limits/opencode-go-usage-fetcher.ts
  • src/main/rate-limits/opencode-go-usage-source-selection.test.ts
  • src/main/rate-limits/opencode-go-usage-source-selection.ts
  • src/renderer/src/components/status-bar/StatusBarProviderSegment.tsx
  • src/renderer/src/components/status-bar/provider-extra-usage-section.tsx
  • src/renderer/src/components/status-bar/provider-segment-balance.test.tsx
  • src/renderer/src/components/status-bar/tooltip.test.ts
  • src/renderer/src/components/status-bar/tooltip.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/i18n/provider-credit-balance-locales.test.ts
  • src/shared/credit-count-format.test.ts
  • src/shared/credit-count-format.ts
  • src/shared/currency-format.test.ts
  • src/shared/currency-format.ts
  • src/shared/rate-limit-types.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — read the complete diff end-to-end (31 files), traced each provider path into its consumers, and verified the changed suite, typechecks, and repo gates locally.

  • Shared credit model: optional extraUsage on ProviderRateLimits, modeled as a discriminated union so currency balances (unit: 'currency', nullable balance) and unitless credit counts (unit: 'credits', unlimited) can't be confused.
  • Claude: OAuth spend object → cap/balance/spent-percent mapping with a legacy extra_usage fallback; a missing balance stays unknown rather than becoming zero, and mergeClaudeUsageWindows preserves the field when the CLI supplements windows.
  • Codex: rateLimits.credits mapped to a credit count on the RPC probe path, hidden unless the account actually has credits.
  • OpenCode Go: org_ workspace IDs accepted, an optional console billing GET run concurrently with each candidate's status fetch (5s cap, always aborted and awaited before advancing), a strict prepaid/pay-as-you-go parser, honest unavailable/refresh-failed states, and unchanged API-key precedence.
  • Renderer: popover extras section plus a compact token gated on both a capped window and a spendable balance.
  • i18n / formatters: new currency-format and credit-count-format helpers with malformed-input fallbacks; sparse locale catalogs intentionally omit copied English balance strings and resolve them from the call-site defaults.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Keep the proxy audit current for the isolated billing request.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes — re-reviewed the delta since the prior pullfrog review at e55b91d: the translation-ordering commit and the merge of main.

  • Localized compact balance: Replaced label/amount string concatenation in formatCompactExtraUsage with placeholder messages ('{{value0}} credits', '{{value0}} bal') so translated catalogs can order the label before or after the amount.
  • Catalog alignment: Updated en.json and the es/fr/ja/ko/zh catalogs to carry the {{value0}} placeholder, and covered runtime fallback/interpolation in provider-credit-balance-locales.test.ts.
  • Ordering regression test: Added a provider-segment-balance.test.tsx case that drives Spanish/French reordered copy through the mocked translate, verifying the component forwards value0; it fails against the prior concatenation.
  • Proxy audit: Bumped the audited non-net .fetch( count for opencode-go-usage-fetcher.ts from 2 to 3 to cover the optional billing request.

I checked the one risk this change opens — a catalog that carries a translated 4fba7dc1e7 without the {{value0}} placeholder would silently drop the amount. Only the five updated catalogs contain that key, and each now includes the placeholder, so the English fallback is never shadowed by stale copy. Focused tests and the localization extraction/coverage/runtime-catalog gates pass locally at this head.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 2b0ce17 into main Oct 5, 2026
33 checks passed
AmethystLiang added a commit that referenced this pull request Oct 8, 2026
Scan the merged PRs since the 2026-10-05 scan (d3943c6): 331 new en keys,
33 removed, 15 changed values. All five target locales were missing the same
187 keys; 11 are provider credit-balance keys intentionally left to the English
sparse fallback (#25408), so this adds the remaining 176 keys to each locale
(es 177: it alone was missing TerminalErrorToast.heldByPreviousRelay).

Also fix two stale changed-English values ("Git AI Author changes" -> "AI
settings") that still read "AI changes"/"移動" in es/fr/ja.

Additive only: +881 target values, 0 removed. The repair pipeline normalized
ja 新しい->新規, エージェント->Agent, and retry/待っている.

Three review rounds (5 reviewers each): R1 fixed 14, R2 fixed 13, R3 clean.
Gates: catalog verify, coverage --check, extraction, runtime-catalog, and the
locale vitest suites (43 files, 386 tests) all pass.
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.

[Feature]: Show OpenCode Zen balance alongside OpenCode Go usage

1 participant