Repository navigation
feat(rate-limits): Grok CLI OAuth weekly credit usage - #7869
brennanb2025 merged 14 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds Grok auth session parsing, Grok account status IPC/preload access, Grok billing rate-limit fetching, and rate-limit service integration. It extends shared rate-limit and status-bar types to include Grok, updates renderer settings/status-bar/stats UI to surface Grok accounts and usage, and adds related Japanese and Korean locale updates. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
src/renderer/src/components/settings/GrokAccountsSection.tsx (2)
157-189: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse hash-based locale keys for these three strings.
'auto.components.settings.GrokAccountsSection.weeklyCredits','...weeklyCreditsDesc', and'...resets'use descriptive suffixes instead of the 10-char hash suffix used everywhere else in this file (a1b2c3d4e5,f6e5d4c3b2, etc.).✏️ Proposed fix
- title={translate( - 'auto.components.settings.GrokAccountsSection.weeklyCredits', - 'Weekly credits' - )} - description={translate( - 'auto.components.settings.GrokAccountsSection.weeklyCreditsDesc', - 'Mirrors the Grok TUI /usage weekly credit meter.' - )} + title={translate( + 'auto.components.settings.GrokAccountsSection.<10-char-hash>', + 'Weekly credits' + )} + description={translate( + 'auto.components.settings.GrokAccountsSection.<10-char-hash>', + 'Mirrors the Grok TUI /usage weekly credit meter.' + )}And similarly for the
'resets'key. Then add the generated keys toen.jsonand runpnpm bootstrap:locale-catalog.Based on learnings, "use hash-based locale keys with translate('auto.components.
..<10-char-hash>', 'Default English text')... run pnpm bootstrap:locale-catalog so translations propagate."Source: Learnings
45-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a "why" comment for the usage-driven reload.
Re-running
loadStatuswhenevergrokUsage?.updatedAtchanges (rather than only on mount/manual refresh) is a non-obvious design choice — it keeps sign-in status in sync with background rate-limit polling. A brief comment would make that intent explicit.As per coding guidelines, "When writing or modifying code driven by a design doc or another non-obvious constraint, add a brief comment explaining why the code behaves that way."
Source: Coding guidelines
src/main/grok-accounts/status.ts (2)
3-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider sharing
GrokAccountStatusinstead of re-declaring it.This shape is re-declared inline (not imported) in
src/preload/api-types.ts(PreloadApi.grokAccounts.getStatus) andsrc/preload/index.ts(thegetStatusreturn type annotation). Three independent copies of the same 5-field object risk silently drifting if one is updated without the others (e.g., adding a field here won't surface a type error in preload).Extracting this type to a shared location (e.g.
src/shared/types.ts) and importing it instatus.ts,api-types.ts, andpreload/index.tswould let TypeScript catch drift for you.
11-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo test coverage for
getGrokAccountStatus's three branches.The PR's testing notes cover
grok-fetcher.test.ts,rate-limit-types.test.ts, andstatus-bar-provider-visibility.test.ts, but not this file, even though it has three distinct outcomes (missing,error,ok) worth pinning down with unit tests, similar to the existinggrok-fetcher.test.tspattern for missing/expired/successful cases.Want me to draft a
status.test.tscovering the three branches?src/main/rate-limits/grok-fetcher.test.ts (1)
73-115: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd tests for error response paths and flat billing response.
The suite covers missing auth, successful fetch, and expired token, but several distinct code paths are untested: HTTP 401/403 handling (line 154-156), non-ok HTTP (line 157-159), the
resolveBillingConfigflat-response path wheredata.configis absent butdata.creditUsagePercentis present (line 97-99), and missingcreditUsagePercentin the response (line 108-109). Adding these would guard against regressions in error handling and response-shape variations.♻️ Suggested additional test cases
it('returns error on 401 response', async () => { authState.file = freshAuthJson() netFetchMock.mockResolvedValueOnce(jsonResponse({}, 401)) const result = await fetchGrokRateLimits() expect(result.status).toBe('error') expect(result.error).toMatch(/unauthorized/i) }) it('maps flat billing response without config wrapper', async () => { authState.file = freshAuthJson() netFetchMock.mockResolvedValueOnce( jsonResponse({ creditUsagePercent: 55, billingPeriodEnd: '2026-07-07T18:36:14.268512+00:00' }) ) const result = await fetchGrokRateLimits() expect(result.status).toBe('ok') expect(result.weekly?.usedPercent).toBe(55) }) it('returns error when creditUsagePercent is missing', async () => { authState.file = freshAuthJson() netFetchMock.mockResolvedValueOnce(jsonResponse({ config: {} })) const result = await fetchGrokRateLimits() expect(result.status).toBe('error') expect(result.error).toMatch(/did not include credit usage/i) })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 1fe8621f-0363-4093-8e65-dcf8ec79d646
📥 Commits
Reviewing files that changed from the base of the PR and between 7e1a777 and 605b714a11b601ed21852b547682171966f0055b.
📒 Files selected for processing (28)
src/main/grok-accounts/status.tssrc/main/ipc/grok-accounts.tssrc/main/ipc/register-core-handlers.tssrc/main/rate-limits/grok-auth.tssrc/main/rate-limits/grok-fetcher.test.tssrc/main/rate-limits/grok-fetcher.tssrc/main/rate-limits/service.test.tssrc/main/rate-limits/service.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/settings/AccountsPane.tsxsrc/renderer/src/components/settings/AppearanceWindowSidebarSection.tsxsrc/renderer/src/components/settings/GrokAccountsSection.tsxsrc/renderer/src/components/settings/accounts-search.tssrc/renderer/src/components/settings/appearance-status-bar-grok-toggle-search.tssrc/renderer/src/components/settings/appearance-status-bar-search.tssrc/renderer/src/components/status-bar/StatusBar.tsxsrc/renderer/src/components/status-bar/status-bar-agent-gating.tssrc/renderer/src/components/status-bar/status-bar-provider-visibility.test.tssrc/renderer/src/components/status-bar/status-bar-provider-visibility.tssrc/renderer/src/components/status-bar/tooltip.tsxsrc/renderer/src/components/status-bar/usage-error-copy.tssrc/renderer/src/store/slices/rate-limits.tssrc/renderer/src/web/web-preload-api.tssrc/shared/rate-limit-types.test.tssrc/shared/rate-limit-types.tssrc/shared/status-bar-defaults.tssrc/shared/types.ts
| @@ -7,6 +7,7 @@ export const DEFAULT_STATUS_BAR_ITEMS: StatusBarItem[] = [ | |||
| 'opencode-go', | |||
| 'kimi', | |||
| 'minimax', | |||
| 'grok', | |||
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Verify StatusBarItem type includes 'grok'
rg -n "StatusBarItem" src/shared/types.ts -A 5Repository: stablyai/orca
Length of output: 526
Add 'grok' to StatusBarItem in src/shared/types.ts. DEFAULT_STATUS_BAR_ITEMS includes 'grok', but the StatusBarItem union still omits it, so this entry fails type-checking.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/renderer/src/i18n/locales/ko.json (1)
22-32: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAdd the Grok status-bar catalog entry
settings.appearance.statusBar.grokToggleDescriptionis missing from every locale file, so the Grok status-bar toggle falls back to English. Keep it in sync with the other provider descriptions.Source: Learnings
src/renderer/src/components/settings/GrokAccountsSection.tsx (1)
62-62: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd the GrokAccountsSection keys to
src/renderer/src/i18n/locales/en.json. The 13 hash-basedtranslatekeys used here are missing from the English catalog, sobootstrap:locale-catalogwill not propagate them to the other locales.Source: Learnings
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 2440e004-2017-46ca-8cee-cf049f12e539
📥 Commits
Reviewing files that changed from the base of the PR and between 605b714a11b601ed21852b547682171966f0055b and 226d544471783e8929a813918dc8d6a193cf8d95.
📒 Files selected for processing (14)
src/main/grok-accounts/status.tssrc/main/rate-limits/grok-auth.tssrc/main/rate-limits/grok-fetcher.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/settings/GrokAccountsSection.tsxsrc/renderer/src/components/settings/accounts-search.tssrc/renderer/src/components/settings/appearance-status-bar-grok-toggle-search.tssrc/renderer/src/components/status-bar/status-bar-provider-visibility.tssrc/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/rate-limit-types.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/preload/api-types.ts
- src/renderer/src/components/settings/appearance-status-bar-grok-toggle-search.ts
- src/main/rate-limits/grok-auth.ts
- src/renderer/src/components/settings/accounts-search.ts
- src/renderer/src/components/status-bar/status-bar-provider-visibility.ts
- src/main/rate-limits/grok-fetcher.ts
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 8a453fb1-3005-4f32-862d-542a22ef1736
📥 Commits
Reviewing files that changed from the base of the PR and between 8fdaaeb3a5de3a670dc426e5429dcb7ce71b3622 and dbe375edfd58929af8ab940ab3cc7a8190fa5688.
📒 Files selected for processing (5)
src/renderer/src/components/settings/Settings.tsxsrc/renderer/src/components/stats/StatsPane.tsxsrc/renderer/src/components/stats/SubscriptionUsageSection.tsxsrc/renderer/src/components/stats/stats-search.tssrc/renderer/src/hooks/useSettingsNavigationMetadata.ts
✅ Files skipped from review due to trivial changes (2)
- src/renderer/src/components/settings/Settings.tsx
- src/renderer/src/hooks/useSettingsNavigationMetadata.ts
| <Button variant="ghost" size="icon-xs" onClick={() => void refreshRateLimits()}> | ||
| <RefreshCw className="size-3.5" /> | ||
| </Button> |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add an aria-label to the icon-only refresh button.
The refresh button contains only a RefreshCw icon with no accessible label, so screen readers cannot convey its purpose.
♿ Proposed fix
- <Button variant="ghost" size="icon-xs" onClick={() => void refreshRateLimits()}>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={translate(
+ 'auto.components.stats.SubscriptionUsageSection.refreshUsage',
+ 'Refresh usage'
+ )}
+ onClick={() => void refreshRateLimits()}
+ >
<RefreshCw className="size-3.5" />
</Button>📝 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.
| <Button variant="ghost" size="icon-xs" onClick={() => void refreshRateLimits()}> | |
| <RefreshCw className="size-3.5" /> | |
| </Button> | |
| <Button | |
| variant="ghost" | |
| size="icon-xs" | |
| aria-label={translate( | |
| 'auto.components.stats.SubscriptionUsageSection.refreshUsage', | |
| 'Refresh usage' | |
| )} | |
| onClick={() => void refreshRateLimits()} | |
| > | |
| <RefreshCw className="size-3.5" /> | |
| </Button> |
|
Taking a look! |
33db9a0 to
b9a8d16
Compare
|
Maintainer update: I rebased this onto latest main and added review fixes. The Grok UI now uses a Grok-specific refresh path so clicking Grok refresh does not refresh other providers, Grok auth read errors are redacted before reaching renderer/RPC state, and localization/default visibility were aligned. Verification run locally:
|
Read ~/.grok/auth.json (read-only), fetch billing credits via cli-chat-proxy, and surface Grok in Settings, status bar toggles, and rate-limit polling alongside other usage providers.
- Shorten Why comments per AGENTS.md; fix billing period end fallback. - Share GrokAccountStatus type; hash-based locale keys; reload why in Settings.
Surface rate-limit weekly credits in Settings > Stats & Usage and link to Accounts for setup.
b9a8d16 to
ed2e0b0
Compare
- Treat a token-less auth.json (e.g. after grok logout) as signed out instead of surfacing a permanent status-bar error. - Map billing responses without credit usage to 'unavailable' so plans with no weekly credits hide the bar like Claude API-key billing. - Gate the grok status-bar item and toggle on CLI PATH detection, matching claude/codex/gemini/kimi. - Guard an empty GROK_CLI_CHAT_PROXY_BASE_URL from producing a relative billing URL. - Drop dead minimax/kimi Stats & Usage search keywords left from the removed subscription section. - Add missing grok search keyword catalog entries and translate the English-stubbed stats keywords in es/ja/ko/zh.
Prefer PR managed Grok accounts + Antigravity usage over main stablyai#7869 minimal CLI status surfaces. Deduplicate auto-merged Grok IPC/preload registrations and deep-merge locale catalogs.
Grok usage landed on main via stablyai#7869 (superseding this PR's stablyai#7901 lineage), so this merge keeps main's Grok implementation everywhere the two stacks overlapped and drops the PR-side Grok stack (managed accounts/GROK_HOME, fetcher, launch/resume env, appearance catalog). The PR now carries only the Antigravity usage surfaces.
…reconciliation The fork-side merge (3867ad0) resolved against main@fa2b228ad keeping both usage stacks. Main's Grok implementation (stablyai#7869) already covers Grok, so the maintainer-side resolution (58745b2 + 46cfc00) that reduces this PR to Antigravity-only wins; this merge records that supersession.
* feat(rate-limits): Grok CLI OAuth weekly credit usage in status bar Read ~/.grok/auth.json (read-only), fetch billing credits via cli-chat-proxy, and surface Grok in Settings, status bar toggles, and rate-limit polling alongside other usage providers. * fix(grok): clarify comments and address CodeRabbit review - Shorten Why comments per AGENTS.md; fix billing period end fallback. - Share GrokAccountStatus type; hash-based locale keys; reload why in Settings. * docs(grok): plain-language comments and Settings copy * feat(stats): subscription usage section with Grok in Stats & Usage Surface rate-limit weekly credits in Settings > Stats & Usage and link to Accounts for setup. * feat(stats): Grok tab in Usage Analytics dropdown * refactor(stats): drop Subscription usage block; align Grok pane with Codex * fix(grok): align settings copy and visibility tests * fix(grok): add localization catalog entries * fix(grok): avoid eager usage refresh fanout * fix(grok): harden usage refresh visibility * test(grok): cover account status privacy boundary * fix(grok): target refreshes and redact auth errors * fix(grok): hide usage UI for signed-out users and align empty states - Treat a token-less auth.json (e.g. after grok logout) as signed out instead of surfacing a permanent status-bar error. - Map billing responses without credit usage to 'unavailable' so plans with no weekly credits hide the bar like Claude API-key billing. - Gate the grok status-bar item and toggle on CLI PATH detection, matching claude/codex/gemini/kimi. - Guard an empty GROK_CLI_CHAT_PROXY_BASE_URL from producing a relative billing URL. - Drop dead minimax/kimi Stats & Usage search keywords left from the removed subscription section. - Add missing grok search keyword catalog entries and translate the English-stubbed stats keywords in es/ja/ko/zh. * test(ipc): mock grok account registrar in register-core-handlers test --------- Co-authored-by: Brennan Benson <[email protected]>
Summary
Adds Grok (xAI) as a usage provider: Orca reads the Grok CLI OAuth session from
~/.grok/auth.json(read-only, respectsGROK_HOME), polls weekly subscription credits from the cli-chat-proxy billing endpoint, and shows usage in Settings → Accounts (Grok) and the status bar (toggle, segment, empty-state rules). Web clients get agrokAccountspreload stub only (no local auth file).Screenshots
No screenshots attached in this PR. UI change: new Grok block under Settings → Accounts; optional Grok Usage status bar item when signed in via Grok CLI.
If reviewers want pixels: signed-in state with weekly %, signed-out CTA (
grok login), and status bar Grok segment after refresh.Testing
pnpm exec vitest run src/main/rate-limits/grok-fetcher.test.ts src/shared/rate-limit-types.test.ts src/renderer/src/components/status-bar/status-bar-provider-visibility.test.tspnpm run typecheck:tsc:nodepnpm lint(not re-run full repo in this session)pnpm typecheck(full tri-project)pnpm test(full suite)pnpm buildAdded/updated:
grok-fetcher.test.ts, visibility tests (incl.groksnapshots),service.test.tsmocks forfetchGrokRateLimits/hasGrokAuthSession.AI Review Report
Reviewed with an AI agent (CodeRabbit + follow-up edits). Checked: read-only auth file access, no token rotation in Orca, billing URL/header alignment with Grok CLI, status-bar visibility when
grokAuthConfiguredis pushed from main, and web stub parity.Cross-platform: Uses
path.join/homedir()for~/.grok;GROK_HOMEenv override matches CLI semantics. No new keyboard shortcuts. Electronnet.fetchfor billing. Windows/Linux/macOS paths for auth file are via Node home + env, not hardcoded/only.Addressed from review: removed
billingPeriodStartas reset fallback; sharedGrokAccountStatustype; hash-based locale keys; plainer code comments and Settings copy; splitappearance-status-bar-grok-toggle-search.tsfor max-lines.Security Audit
auth.json; Orca does not store or refresh OAuth tokens.GROK_CLI_CHAT_PROXY_BASE_URLenv for dev parity with CLI).grokAccounts:getStatusreturns non-secret status (signedIn, email, tokenFresh, error) — no access token exposed to renderer.grok loginoutside Orca.Follow-up: manual smoke with real
grok loginon each OS if CI does not cover billing API.Notes
grok login); Orca does not rotate refresh tokens.grok; item stays hidden until session file exists / visibility rules say otherwise.feature/grok-provider-usage-accounts(forkdoanbactam/orca).