Skip to content

feat(usage): surface pay-as-you-go credit balances (Claude usage credits, OpenCode Go Zen balance, Codex credits) - #9363

Closed
mmarabel wants to merge 12 commits into
stablyai:mainfrom
mmarabel:feat/provider-usage-credit-balances
Closed

mmarabel wants to merge 12 commits into
stablyai:mainfrom
mmarabel:feat/provider-usage-credit-balances

Conversation

@mmarabel

@mmarabel mmarabel commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a pay-as-you-go credit balance to provider usage summaries using existing credentials. Claude and Codex use their existing usage responses; the OpenCode cookie flow adds one optional billing GET per attempted workspace:

  • Claude → "Usage credits": parses the spend object from the OAuth usage response Orca already fetches (monthly spend limit + current balance), with the legacy extra_usage shape as a fallback. This is the same data Claude Code's own /usage panel shows, including the disabled / "out of credits" state (rendered honestly, not mislabeled "off").
  • OpenCode Go → "Zen balance": requests /console/api/billing/status through the same isolated Session, proxy, console cookie, and workspace x-org-id as Go usage. Only the verified prepaid / pay-as-you-go contract is accepted: signed integer-string balanceMicroCents divided by 100,000,000 in USD. Zero and negative balances are preserved; spend and cap fields remain unknown, not invented. A verified wallet can appear without Go usage windows.
  • Codex → "Credits": parses rateLimits.credits from the same app-server RPC Orca already uses for Codex windows. Codex credits are a unitless count (e.g. 500 credits), not a currency, so the shared model gained a unit: 'currency' | 'credits' discriminator plus an unlimited flag. Hidden for accounts that never bought credits (hasCredits: false).

Behaviour:

  • Popover always shows the balance row so it's discoverable at 0% used. Claude renders a spent/limit meter plus current balance; OpenCode Go renders a plain available amount; Codex renders "N credits available" (or "Unlimited"). The row reuses the existing panel tokens (label weight, bar colours, muted/faint text) so it matches Session/Weekly exactly.
  • Compact status-bar segment stays hidden normally and reveals the remaining balance (counting down) only once a plan window caps and the balance is actually spendable — so it appears exactly when the plan starts spending into it.
  • Denomination: Claude uses the response currency; the verified OpenCode PAYG contract is USD; Codex uses a unitless credit count. Currency amounts use Intl.NumberFormat for the viewer's locale rather than a hardcoded currency symbol.

Fixes #9362

Screenshots

Compact status-bar segment, Claude "Usage credits" popover, and the row in context:

Compact status-bar segment Claude Usage credits row in the popover Usage credits row alongside Session and Weekly

Codex "Credits" row:

Codex Credits row showing 500 credits available

Testing (original implementation)

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions

Notes on pnpm test: the touched areas pass in full (Claude spend mapping incl. disabled/out-of-credits and the legacy fallback, the OpenCode Go Zen-balance parser, the currency formatter, popover rendering for enabled/disabled/uncapped, and the compact reveal incl. "disabled stays hidden"). The wider suite has a handful of failures in unrelated modules (PR-comment list, Linear prompt toast, sidebar toolbar, a flaky terminal-PTY test); these were confirmed pre-existing by re-running them with this branch's changes stashed.

New/updated tests:

  • src/shared/currency-format.test.ts — locale-safe currency formatting + malformed-code fallback.
  • Current OpenCode parsing/request coverage lives in opencode-go-status-parsing.test.ts and opencode-go-usage-fetcher.test.ts: strict billing modes and units, positive/zero/negative and unavailable balances, workspace priority, optional failure, timeout, and cleanup.
  • src/main/rate-limits/claude-fetcher.test.ts — spend → capped balance, disabled out-of-credits stays visible, legacy extra_usage fallback.
  • src/main/rate-limits/codex-fetcher.test.ts — rateLimits.credits → credit-count balance; hidden when hasCredits: false.
  • src/renderer/src/components/status-bar/tooltip.test.ts — popover render for capped/disabled/uncapped + credit-count + unlimited + per-provider labels.
  • src/renderer/src/components/status-bar/provider-segment-balance.test.tsx — compact reveal on cap, hidden with headroom, hidden when disabled, credit-count vs currency.

AI Review Report

Reviewed with the AI agent that wrote the change. Focus areas and outcomes:

  • Cross-platform (macOS / Linux / Windows): the change is pure TypeScript/React with no platform branches, keyboard shortcuts, shortcut labels, path handling, or shell execution. Currency rendering uses Intl.NumberFormat, which is available and locale-aware across all Electron targets. No metaKey/path//-vs-\ assumptions were added.
  • SSH / remote: usage reads stay on the existing execution-host HTTP/session paths. OpenCode billing reuses its existing isolated cookie Session and proxy. The optional balance travels through the existing ProviderRateLimits payload; no new stream opcode is introduced.
  • Git provider compatibility: N/A — no source-control/review code touched.
  • Data-model safety: extraUsage is additive and optional on ProviderRateLimits; existing providers that don't set it render unchanged (verified by an "omits the balance row" test).
  • Parsing robustness: billing JSON is size-guarded and accepts only the verified PAYG mode and safe signed integer strings. Other modes and malformed amounts are unavailable. Balance-only success requires HTTP-success JSON null or access:null without an error field; HTML and arbitrary malformed Go responses remain errors.
  • Flagged & addressed during review: initial version matched CodexBar and hid the row unless is_enabled, which hid a configured-but-disabled cap; reworked to show the real state after inspecting the live response. Switched from the minimal extra_usage field to the richer spend object (with fallback) so amounts, currency, and enabled state are exact. Removed temporary debug logging before commit.

Security Audit

  • Untrusted input: parsers consume provider-controlled JSON with size and type guards; no dynamic code is evaluated. Currency formatting retains its malformed-code fallback.
  • Secrets: no secrets are logged or persisted; the temporary debug logging used during investigation was removed. No credential handling changed — the feature reuses the existing OAuth token and OpenCode session cookie already in use.
  • Command execution / paths / IPC: none added. No new IPC channels; the balance rides the existing usage payload.
  • Follow-up: none required for this PR.

Notes

  • Claude API Console org credits (platform.claude.com) are a different billing system from subscription usage credits and are not covered here.
  • Codex credit unit: the app-server reports balance as a plain credit count (verified against a live account: a $20 / 500-credit purchase surfaced as balance: "500"), so it renders as "500 credits", not a dollar amount.
  • The compact balance token reveals only when a plan window is at ~100% and the balance is spendable, so it is inherently hard to exercise without hitting a real limit; the popover row is the always-visible surface.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Y891yaV8gJpLycZEX6G5gm

ELI5

Usage summaries can show pay-as-you-go credit balances for Claude, OpenCode Go Zen, and Codex when that data is already in the API response. You see remaining credits next to rate limits without extra logins.

Current cleanup validation and limits

  • Exact current head: 54d26c79ce6e5d9e20ad27e7d8cee950f4627ece. Current feature suite: 5 files / 86 tests, including 2 renderer files / 61 tests; node, web, and full typecheck pass; pinned changed-code quality has zero findings across 22 files. A fresh hidden Electron build passed both known-limit-only and depleted-balance journeys. The preceding cookie implementation passed its 5-file / 84-test OpenCode suite and balance-only wallet journey. These are fixture validations, not a private-account balance probe or a full CI/build claim.
  • Valid Go quota survives optional billing failures. Later valid Go workspaces take priority over an earlier balance-only candidate. The optional request has a five-second timeout and is settled before the next workspace or cookie cleanup; it may add latency up to that cap.
  • API-key-first success is unchanged and is not balance-enriched: an API-key billing contract remains unverified. The existing cookie fallback can return a verified wallet.
  • Codex WSL backend-first usage still returns before app-server pay-as-you-go credit mapping. Changing that source policy is explicitly held; this cleanup adds no RPC probe or WSL proxy resolver.
  • Missing Claude balances are unavailable, not zero. A known limit remains visible as Limit {{value0}} even when spend, percentage and balance are unknown; no zero or meter is invented. This caption has an English fallback; no unverified translations were added. Depleted currency balances stay visible in the popover but do not reveal an active compact balance token; credit-count and unlimited behavior are unchanged.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a shared ExtraUsageBalance model and currency formatter. Claude OAuth responses now support current and legacy extra-usage formats, while OpenCode Go pages provide parsed Zen balances. Provider rate-limit results carry these balances through merging. The status bar and tooltip render capped, uncapped, disabled, and unavailable balance states with provider-specific localized labels. Tests cover parsing, mapping, formatting, rendering, and fallback behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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 match #9362 by surfacing Claude spend data and OpenCode Go Zen balance, showing popover rows, and gating compact balance reveal correctly.
Out of Scope Changes check ✅ Passed The added tests, currency formatting, renderer updates, and locale strings all support the requested balance-display feature and appear in scope.
Title check ✅ Passed The title clearly and concisely describes the main change: surfacing pay-as-you-go credit balances for usage providers.
Description check ✅ Passed The description is comprehensive and covers the feature scope, user-visible behavior, linked issue, screenshots, testing, compatibility, security, and limitations. It does not follow every template he…

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: 4

🧹 Nitpick comments (1)
src/main/rate-limits/opencode-go-page-scraper.ts (1)

169-219: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Extract regular expressions outside the parsing functions.

To avoid repeatedly allocating arrays and compiling RegExp objects every time the page scraper runs, consider precompiling these static regular expressions outside the function scope.

♻️ Proposed refactor
-function parseScaledBillingBalance(text: string): number | null {
-  // Require a real customerID so `customerID:null` / billing-disabled payloads
-  // (which still carry a `balance:0`) don't register as a live balance.
-  const customerRegex = /(?:"customerID"|customerID)\s*:\s*(?:\$R\[\d+\]\s*=\s*)?"[^"]+"/
-  if (!customerRegex.test(text)) {
-    return null
-  }
-  const balanceRegex = /(?:"balance"|balance)\s*:\s*(?:\$R\[\d+\]\s*=\s*)?(-?[0-9]+(?:\.[0-9]+)?)/
-  const match = balanceRegex.exec(text)
-  if (!match) {
-    return null
-  }
-  const raw = Number.parseFloat(match[1])
-  return Number.isFinite(raw) ? raw / ZEN_BILLING_SCALE : null
-}
-
-function parseExplicitZenBalance(text: string): number | null {
-  for (const key of EXPLICIT_ZEN_BALANCE_KEYS) {
-    // Key may be quoted (JSON) or bare (JS object); value may be a bare number
-    // or a quoted string with thousands separators.
-    const regex = new RegExp(
-      `(?:"${key}"|\\b${key}\\b)\\s*:\\s*(?:\\$R\\[\\d+\\]\\s*=\\s*)?"?([0-9][0-9,]*(?:\\.[0-9]+)?)"?`
-    )
-    const match = regex.exec(text)
-    if (match) {
-      const value = Number.parseFloat(match[1].replace(/,/g, ''))
-      if (Number.isFinite(value)) {
-        return value
-      }
-    }
-  }
-  return null
-}
-
-function parseDollarBalanceText(text: string): number | null {
-  const patterns = [
-    /(?:current\s+balance|zen\s+balance|現在の残高)[^$]{0,80}\$\s*([0-9][0-9,]*(?:\.[0-9]+)?)/i,
-    /(?:balance|残高)[\s\S]{0,120}?\$\s*([0-9][0-9,]*(?:\.[0-9]+)?)/i
-  ]
-  for (const pattern of patterns) {
-    const match = pattern.exec(text)
-    if (match) {
-      const value = Number.parseFloat(match[1].replace(/,/g, ''))
-      if (Number.isFinite(value)) {
-        return value
-      }
-    }
-  }
-  return null
-}
+const SCALED_CUSTOMER_REGEX = /(?:"customerID"|customerID)\s*:\s*(?:\$R\[\d+\]\s*=\s*)?"[^"]+"/
+const SCALED_BALANCE_REGEX = /(?:"balance"|balance)\s*:\s*(?:\$R\[\d+\]\s*=\s*)?(-?[0-9]+(?:\.[0-9]+)?)/
+
+const EXPLICIT_ZEN_BALANCE_REGEXES = EXPLICIT_ZEN_BALANCE_KEYS.map(
+  (key) => new RegExp(`(?:"${key}"|\\b${key}\\b)\\s*:\\s*(?:\\$R\\[\\d+\\]\\s*=\\s*)?"?([0-9][0-9,]*(?:\\.[0-9]+)?)"?`)
+)
+
+const DOLLAR_BALANCE_PATTERNS = [
+  /(?:current\s+balance|zen\s+balance|現在の残高)[^$]{0,80}\$\s*([0-9][0-9,]*(?:\.[0-9]+)?)/i,
+  /(?:balance|残高)[\s\S]{0,120}?\$\s*([0-9][0-9,]*(?:\.[0-9]+)?)/i
+]
+
+function parseScaledBillingBalance(text: string): number | null {
+  // Require a real customerID so `customerID:null` / billing-disabled payloads
+  // (which still carry a `balance:0`) don't register as a live balance.
+  if (!SCALED_CUSTOMER_REGEX.test(text)) {
+    return null
+  }
+  const match = SCALED_BALANCE_REGEX.exec(text)
+  if (!match) {
+    return null
+  }
+  const raw = Number.parseFloat(match[1])
+  return Number.isFinite(raw) ? raw / ZEN_BILLING_SCALE : null
+}
+
+function parseExplicitZenBalance(text: string): number | null {
+  for (const regex of EXPLICIT_ZEN_BALANCE_REGEXES) {
+    const match = regex.exec(text)
+    if (match) {
+      const value = Number.parseFloat(match[1].replace(/,/g, ''))
+      if (Number.isFinite(value)) {
+        return value
+      }
+    }
+  }
+  return null
+}
+
+function parseDollarBalanceText(text: string): number | null {
+  for (const pattern of DOLLAR_BALANCE_PATTERNS) {
+    const match = pattern.exec(text)
+    if (match) {
+      const value = Number.parseFloat(match[1].replace(/,/g, ''))
+      if (Number.isFinite(value)) {
+        return value
+      }
+    }
+  }
+  return null
+}

(Note: The static analysis warnings flagging lines 177, 192, and 209 as command injections are false positives, incorrectly conflating RegExp.exec with child_process.exec. These can be safely ignored.)


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 851e4fe0-6482-43e0-a91b-f49ec722dbaa

📥 Commits

Reviewing files that changed from the base of the PR and between 54cb772 and 019347a0a0d1f195b9c26a64778097b11e71ce5d.

📒 Files selected for processing (17)
  • src/main/rate-limits/claude-fetcher.test.ts
  • src/main/rate-limits/claude-fetcher.ts
  • src/main/rate-limits/opencode-go-page-scraper.test.ts
  • src/main/rate-limits/opencode-go-page-scraper.ts
  • src/main/rate-limits/opencode-go-usage-fetcher.ts
  • src/renderer/src/components/status-bar/StatusBar.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/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/shared/currency-format.test.ts
  • src/shared/currency-format.ts
  • src/shared/rate-limit-types.ts

Comment thread src/renderer/src/i18n/locales/ja.json Resolved
Comment thread src/shared/currency-format.test.ts Resolved
@mmarabel

Copy link
Copy Markdown
Contributor Author

Thanks @coderabbitai — addressed the two substantive items in 9d0333a:

  • Nested PanelBalanceSection → plain render function. Converted it to renderBalanceSection(...) called directly, so React keeps the DOM node and the progress bar's transition-all width animation survives re-renders. (Left the pre-existing PanelWindowSection as-is to keep this PR single-topic — it has the same pattern and is worth a separate cleanup.)
  • Compact bal label localized. Set proper translations instead of the English placeholder: 残高 (ja), 余额 (zh), 잔액 (ko), saldo (es). English stays bal.

Two I'm intentionally leaving:

  • ProviderPanel({ p }) direct call in tooltip.test.ts. This matches the file's existing convention — every ProviderPanel render test in that file calls it directly, and the component is hookless — so I kept it consistent rather than introducing a mixed createElement/direct-call style in one file. Happy to convert the whole file in a follow-up if preferred.
  • Docstring coverage (50% < 80%). The repo's AGENTS.md explicitly asks for short "why"-only comments and discourages restating what code does, so I've kept comments to the non-obvious rationale per that convention rather than padding to hit the threshold.

The "resolve merge conflict" pre-merge check predates the main merge I pushed earlier — the branch is now MERGEABLE.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@gatsby74 — The Comment images show:

  • A compact dark status bar with an OpenCode Go token, a depleted five-hour window (“0% left 5h”), a weekly window (“20% left wk”), and the newly visible balance token: “$13.56 bal”.
  • An OpenCode Go popover showing Session at “0% left,” Weekly at “20% left,” Monthly at “60% left,” and a “Zen balance” section with “$13.56 available.”
  • A Claude popover showing Session at “93% left,” Weekly at “100% left,” plus a “Usage credits” meter with “€0.00 / €2,000.00,” “100% left,” and “Balance €0.00.”

Thanks—this addresses both substantive items. The balance rendering and localized compact label look correct in the screenshots.

Your rationale for retaining the hookless ProviderPanel({ p }) test convention and avoiding non-rationale docstring padding is reasonable; no follow-up is needed in this PR. The pre-merge conflict status clarification is noted as well.

🐇✨


✏️ Learnings added
Learnt from: gatsby74
URL: https://github.com/stablyai/orca/pull/9363

Timestamp: 2026-07-18T18:22:51.747Z
Learning: In this repository, `AGENTS.md` directs contributors to use short comments that explain non-obvious rationale and to avoid comments that merely restate code behavior; documentation coverage thresholds should not be met by adding redundant implementation descriptions.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@mmarabel mmarabel changed the title feat(usage): surface pay-as-you-go credit balances (Claude usage credits, OpenCode Go Zen balance) feat(usage): surface pay-as-you-go credit balances (Claude usage credits, OpenCode Go Zen balance, Codex credits) Jul 18, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

@brennanb2025
brennanb2025 force-pushed the feat/provider-usage-credit-balances branch from d9fd641 to 99a2be8 Compare July 21, 2026 02:52
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the contribution — I rebased this onto current main and tightened the implementation while applying the remaining review feedback. The balance scraper now uses bounded, billing-record-scoped parsing instead of broad page-wide matches, preserves granted credit without requiring a payment customer, and only exposes the compact balance when overage spending is actually enabled; currency and credit balances now have distinct typed shapes, credit counts are localized, and malformed money data is handled defensively. The 161 focused usage/UI tests, full typecheck, touched-file lint and format checks, localization catalog verification, max-lines guard, and changed-files React checks all pass.

@euclodius

Copy link
Copy Markdown

Thanks for the work on this — this PR appears to implement the OpenCode Zen balance requested in #8145 directly. I noticed the branch is currently conflicting with main. Is the rebase still planned? I would be happy to help validate the refreshed implementation on Windows with WSL once it is ready.

One related scope question while this PR is being revived: could the new ExtraUsageBalance model remain provider-agnostic so it can support Grok and Cline credit balances in follow-ups?

  • Grok: Orca's existing billing payload already exposes onDemandCap, onDemandUsed, and prepaidBalance; the current fetcher maps only the subscription windows. This looks like a natural follow-up once the shared balance model lands.
  • Cline: ClinePass subscription quota and Cline's pay-as-you-go credit balance are separate billing surfaces. PR feat(rate-limits): add API-key-based ClinePass usage tracking #13827 covers the ClinePass 5h/weekly/monthly quota, while Cline credits would require confirming the balance endpoint and whether the same API key can access it.

I would not want either addition to delay #9363 — landing the generic balance model and OpenCode Zen support first is the priority. It would still be useful to keep these providers explicitly in scope for follow-up work.

Please keep #8145 linked through merge/release as well.

mmarabel and others added 4 commits August 15, 2026 12:11
…its, OpenCode Go Zen balance)

Add an extra-usage balance to the provider usage summaries for the two
providers where the data is already reachable, without any new network
call or credential:

- Claude: parse the OAuth usage response's `spend` object (monthly spend
  limit + current balance), falling back to the legacy `extra_usage`
  shape. This is the same "Usage credits" data Claude Code's own /usage
  panel shows, including the disabled/out-of-credits state.
- OpenCode Go: parse the "Zen" pay-as-you-go balance from the workspace
  page Orca already scrapes.

Rendering:
- Popover always shows a balance row (Claude: spent/limit meter + current
  balance; OpenCode Go: plain available amount), reusing the existing
  panel tokens so it matches the other rows.
- Compact status-bar segment stays hidden until a plan window caps and the
  balance is spendable, then reveals the remaining amount counting down.
- Currency comes from the provider response and is formatted with
  Intl.NumberFormat, so it adapts to the account's currency and locale.

Codex/OpenAI credit balance is intentionally left as a follow-up since it
needs a separate credential and settings UI.

Fixes stablyai#9362

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y891yaV8gJpLycZEX6G5gm
…ize compact label

- Call the balance renderer as a plain function instead of a nested
  component so React keeps the DOM node and the progress bar's width
  transition animates (per CodeRabbit).
- Translate the compact "bal" label for ja/zh/ko/es (残高 / 余额 / 잔액 /
  saldo) instead of shipping the English placeholder.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y891yaV8gJpLycZEX6G5gm
Codex reports a pay-as-you-go credit balance inside the same rate-limit
RPC response Orca already fetches (`rateLimits.credits`) — parse it into
the shared ExtraUsageBalance model like Claude/OpenCode Go.

Codex credits are a unitless count, not a currency, so the balance model
gains a `unit: 'currency' | 'credits'` discriminator plus an `unlimited`
flag. The popover renders "500 credits available" (or "Unlimited"), and
the compact segment reveals "500 credits" when a window caps. The row is
hidden for accounts with no credits (hasCredits false).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y891yaV8gJpLycZEX6G5gm
Bind scraped balances to their billing record and gate compact display on actual spendability.

Use distinct currency and credit models, localize credit counts, harden malformed money input, and cover the review feedback.
@mmarabel
mmarabel force-pushed the feat/provider-usage-credit-balances branch from 99a2be8 to 8b19f9a Compare August 15, 2026 10:27
@mmarabel

Copy link
Copy Markdown
Contributor Author

Rebased onto current upstream/main (5b7f44278a).

Credit-balance parsing/UI was re-applied onto the current rate-limit modules:

  • Claude extra-usage tests now live in claude-fetcher-extra-usage.test.ts (the old claude-fetcher.test.ts was split on main).
  • Codex credits parse through CodexRateLimitWindowsSnapshot.credits rather than the deleted RpcRateLimitsResult type.
  • Compact status-bar and tooltip keep main's current window layout and add the overage-balance rows.

Force-pushed feat/provider-usage-credit-balances.

# Conflicts:
#	src/renderer/src/components/status-bar/StatusBarProviderSegment.tsx
#	src/renderer/src/i18n/locales/es.json
#	src/shared/rate-limit-types.ts
@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[Medium risk] Adds pay-as-you-go credit balance display to the status bar.

The PR does not yet appear safe to merge because WSL Codex users still cannot receive the credit balance.

Findings

  1. P1 WSL path omits Codex credits ▶
  2. P2 New balance copy remains English ▶

Summary

The PR adds pay-as-you-go balances to Claude, OpenCode Go, and Codex usage summaries. Since the previous review, it hides depleted currency balances from the compact segment and shows a known Claude cap when the balance and usage percentage are unavailable.

Reviews (4) · Last reviewed commit: "fix(usage): preserve depleted balance se..."

const wrapper = message.result as RpcRateLimitsResponse | undefined
const classified = classifyCodexRateLimitWindows(wrapper?.rateLimits)
const credits = mapRpcRateLimitResetCredits(wrapper?.rateLimitResetCredits)
const extraUsage = mapCodexCredits(wrapper?.rateLimits?.credits)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 WSL path omits Codex credits

If a Codex account uses a WSL home and the backend usage fetch succeeds, the fetcher returns that result before reaching this RPC mapping. The backend result has no credits field, so those accounts receive rate-limit windows but no credit balance.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed: a successful WSL backend-first fetch returns before app-server pay-as-you-go credit mapping, so that balance is still unavailable on this path. The PR Notes explicitly defer changing that source policy. This review update (1d8ec3a279e8d4fa5e14a38c0502578b476b9025) preserves the hold: no extra RPC/proxy probe or source-selection change, and this finding is not claimed fixed.

The existing WSL backend consumer regression passes and verifies that successful backend usage does not spawn Codex; the separate RPC credit-mapping regression also passes. Reset-redemption credits are distinct from the missing pay-as-you-go balance.

Comment thread src/renderer/src/i18n/locales/es.json Outdated
Comment on lines +3516 to +3523
"d1b7f509ac": "Run grok in a terminal on the computer running Orca and wait for it to start. If prompted, complete sign-in, then retry usage. You do not need to send a chat message.",
"f90b3d7a16": "Run Kimi to refresh",
"a37e8c15d4": "Run kimi in a terminal on the computer running Orca and wait for it to start, then retry usage.",
"fbc80d8be2": "Zen balance",
"c03c61f53f": "Balance",
"f6a27a3c0a": "{{value0}} available",
"7404abbece": "Usage credits",
"473d45cd0f": "Balance {{value0}}",

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 New balance copy remains English

Several new strings here, including “Usage credits,” “Unlimited,” and “{{value0}} credits available,” remain in English. The new compact strings do too, and the same pattern appears in French, Japanese, Korean, and Chinese. Users of those locales will see mixed-language balance UI; translating the new entries would avoid that.

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!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Corrected the target catalogs in 1d8ec3a279e8d4fa5e14a38c0502578b476b9025 using Orca’s established English-only feature / sparse-target policy. Removed only this PR’s 50 copied-English entries across es/fr/ja/ko/zh; preserved every genuine translation, including all five translated compact-balance labels, and every English source key.

Missing translations still display English through the existing fallback, rather than being recorded as completed translations. No new target-language translations are claimed. Eleven isolated i18next regressions cover omission, real fallback/interpolation and retained labels; five failed before the correction. Parent reran 149 focused tests, full pnpm tc, sparse-catalog verification, normal hooks and the unchanged original-head quality gate; all pass.

nwparker added a commit that referenced this pull request Oct 5, 2026
Display provider credit and currency balances separately from rate limits. Preserve quotas when balance data is unavailable and translate complete labels.

Supersedes #9363; credit to @mmarabel for the original implementation.

Co-authored-by: mmarabel <166927047+mmarabel@users.noreply.github.com>
@nwparker

nwparker commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Superseded by merged #25408. Thanks @mmarabel for the original implementation; the merge commit retains your co-author credit.

The takeover preserves provider quotas, distinct currency/credit balances, unavailable states, and existing remote usage paths. It includes the optional OpenCode billing request and localized complete balance labels, with real installed-OpenCode controlled-response UI checks and passing CI. API-key billing and Claude Console credits remain outside the verified contract.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Surface pay-as-you-go usage-credit balances (Claude usage credits, OpenCode Go Zen balance) in usage summaries

4 participants