Repository navigation
Conversation
|
Important Review skippedWe 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 You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughAdds a shared 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
src/main/rate-limits/opencode-go-page-scraper.ts (1)
169-219: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueExtract regular expressions outside the parsing functions.
To avoid repeatedly allocating arrays and compiling
RegExpobjects 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.execwithchild_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.tssrc/main/rate-limits/claude-fetcher.tssrc/main/rate-limits/opencode-go-page-scraper.test.tssrc/main/rate-limits/opencode-go-page-scraper.tssrc/main/rate-limits/opencode-go-usage-fetcher.tssrc/renderer/src/components/status-bar/StatusBar.tsxsrc/renderer/src/components/status-bar/provider-segment-balance.test.tsxsrc/renderer/src/components/status-bar/tooltip.test.tssrc/renderer/src/components/status-bar/tooltip.tsxsrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/shared/currency-format.test.tssrc/shared/currency-format.tssrc/shared/rate-limit-types.ts
|
Thanks @coderabbitai — addressed the two substantive items in 9d0333a:
Two I'm intentionally leaving:
The "resolve merge conflict" pre-merge check predates the |
|
Tip For best results, initiate chat on the files or code changes.
Thanks—this addresses both substantive items. The balance rendering and localized compact label look correct in the screenshots. Your rationale for retaining the hookless 🐇✨ ✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! |
|
Taking a look! |
d9fd641 to
99a2be8
Compare
|
Thanks for the contribution — I rebased this onto current |
|
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 One related scope question while this PR is being revived: could the new
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. |
…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.
99a2be8 to
8b19f9a
Compare
|
Rebased onto current Credit-balance parsing/UI was re-applied onto the current rate-limit modules:
Force-pushed |
# Conflicts: # src/renderer/src/components/status-bar/StatusBarProviderSegment.tsx # src/renderer/src/i18n/locales/es.json # src/shared/rate-limit-types.ts
|
| const wrapper = message.result as RpcRateLimitsResponse | undefined | ||
| const classified = classifyCodexRateLimitWindows(wrapper?.rateLimits) | ||
| const credits = mapRpcRateLimitResetCredits(wrapper?.rateLimitResetCredits) | ||
| const extraUsage = mapCodexCredits(wrapper?.rateLimits?.credits) |
There was a problem hiding this comment.
There was a problem hiding this comment.
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.
| "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}}", |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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.
|
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. |
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:
spendobject from the OAuth usage response Orca already fetches (monthly spend limit + current balance), with the legacyextra_usageshape as a fallback. This is the same data Claude Code's own/usagepanel shows, including the disabled / "out of credits" state (rendered honestly, not mislabeled "off")./console/api/billing/statusthrough the same isolated Session, proxy, console cookie, and workspacex-org-idas Go usage. Only the verifiedprepaid/pay-as-you-gocontract is accepted: signed integer-stringbalanceMicroCentsdivided 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.rateLimits.creditsfrom 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 aunit: 'currency' | 'credits'discriminator plus anunlimitedflag. Hidden for accounts that never bought credits (hasCredits: false).Behaviour:
Intl.NumberFormatfor 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:
Codex "Credits" row:
Testing (original implementation)
pnpm lintpnpm typecheckpnpm testpnpm buildNotes on
pnpm test: the touched areas pass in full (Claudespendmapping 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.opencode-go-status-parsing.test.tsandopencode-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, legacyextra_usagefallback.src/main/rate-limits/codex-fetcher.test.ts—rateLimits.credits→ credit-count balance; hidden whenhasCredits: 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:
Intl.NumberFormat, which is available and locale-aware across all Electron targets. NometaKey/path//-vs-\assumptions were added.ProviderRateLimitspayload; no new stream opcode is introduced.extraUsageis additive and optional onProviderRateLimits; existing providers that don't set it render unchanged (verified by an "omits the balance row" test).nulloraccess:nullwithout an error field; HTML and arbitrary malformed Go responses remain errors.is_enabled, which hid a configured-but-disabled cap; reworked to show the real state after inspecting the live response. Switched from the minimalextra_usagefield to the richerspendobject (with fallback) so amounts, currency, and enabled state are exact. Removed temporary debug logging before commit.Security Audit
Notes
balanceas a plain credit count (verified against a live account: a $20 / 500-credit purchase surfaced asbalance: "500"), so it renders as "500 credits", not a dollar amount.🤖 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
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.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.