Skip to content

feat(rate-limits): Grok CLI OAuth weekly credit usage - #7869

Merged
brennanb2025 merged 14 commits into
stablyai:mainfrom
doanbactam:feature/grok-provider-usage-accounts
Jul 10, 2026
Merged

brennanb2025 merged 14 commits into
stablyai:mainfrom
doanbactam:feature/grok-provider-usage-accounts

Conversation

@doanbactam

@doanbactam doanbactam commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds Grok (xAI) as a usage provider: Orca reads the Grok CLI OAuth session from ~/.grok/auth.json (read-only, respects GROK_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 a grokAccounts preload stub only (no local auth file).

Screenshots

image image image

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.ts
  • pnpm run typecheck:tsc:node
  • pnpm lint (not re-run full repo in this session)
  • pnpm typecheck (full tri-project)
  • pnpm test (full suite)
  • pnpm build

Added/updated: grok-fetcher.test.ts, visibility tests (incl. grok snapshots), service.test.ts mocks for fetchGrokRateLimits / 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 grokAuthConfigured is pushed from main, and web stub parity.

Cross-platform: Uses path.join / homedir() for ~/.grok; GROK_HOME env override matches CLI semantics. No new keyboard shortcuts. Electron net.fetch for billing. Windows/Linux/macOS paths for auth file are via Node home + env, not hardcoded / only.

Addressed from review: removed billingPeriodStart as reset fallback; shared GrokAccountStatus type; hash-based locale keys; plainer code comments and Settings copy; split appearance-status-bar-grok-toggle-search.ts for max-lines.

Security Audit

  • Auth/secrets: Read-only read of user’s existing Grok CLI auth.json; Orca does not store or refresh OAuth tokens.
  • Network: HTTPS billing request with Bearer from that file; 10s timeout; no user-controlled URL (optional GROK_CLI_CHAT_PROXY_BASE_URL env for dev parity with CLI).
  • IPC: grokAccounts:getStatus returns non-secret status (signedIn, email, tokenFresh, error) — no access token exposed to renderer.
  • Command execution: None; user runs grok login outside Orca.
  • Dependencies: No new runtime deps for this feature.

Follow-up: manual smoke with real grok login on each OS if CI does not cover billing API.

Notes

  • Token refresh remains owned by Grok CLI (grok login); Orca does not rotate refresh tokens.
  • Default status bar list includes grok; item stays hidden until session file exists / visibility rules say otherwise.
  • Branch: feature/grok-provider-usage-accounts (fork doanbactam/orca).

@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.38% 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 Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the Grok CLI OAuth weekly credit usage feature.
Description check ✅ Passed The description includes all required sections and enough detail on screenshots, testing, review, security, and notes.

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

🧹 Nitpick comments (5)
src/renderer/src/components/settings/GrokAccountsSection.tsx (2)

157-189: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use 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 to en.json and run pnpm 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 win

Add a "why" comment for the usage-driven reload.

Re-running loadStatus whenever grokUsage?.updatedAt changes (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 win

Consider sharing GrokAccountStatus instead of re-declaring it.

This shape is re-declared inline (not imported) in src/preload/api-types.ts (PreloadApi.grokAccounts.getStatus) and src/preload/index.ts (the getStatus return 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 in status.ts, api-types.ts, and preload/index.ts would let TypeScript catch drift for you.


11-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No test coverage for getGrokAccountStatus's three branches.

The PR's testing notes cover grok-fetcher.test.ts, rate-limit-types.test.ts, and status-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 existing grok-fetcher.test.ts pattern for missing/expired/successful cases.

Want me to draft a status.test.ts covering the three branches?

src/main/rate-limits/grok-fetcher.test.ts (1)

73-115: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add 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 resolveBillingConfig flat-response path where data.config is absent but data.creditUsagePercent is present (line 97-99), and missing creditUsagePercent in 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.ts
  • src/main/ipc/grok-accounts.ts
  • src/main/ipc/register-core-handlers.ts
  • src/main/rate-limits/grok-auth.ts
  • src/main/rate-limits/grok-fetcher.test.ts
  • src/main/rate-limits/grok-fetcher.ts
  • src/main/rate-limits/service.test.ts
  • src/main/rate-limits/service.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/settings/AccountsPane.tsx
  • src/renderer/src/components/settings/AppearanceWindowSidebarSection.tsx
  • src/renderer/src/components/settings/GrokAccountsSection.tsx
  • src/renderer/src/components/settings/accounts-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-grok-toggle-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-search.ts
  • src/renderer/src/components/status-bar/StatusBar.tsx
  • src/renderer/src/components/status-bar/status-bar-agent-gating.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.test.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.ts
  • src/renderer/src/components/status-bar/tooltip.tsx
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/store/slices/rate-limits.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/rate-limit-types.test.ts
  • src/shared/rate-limit-types.ts
  • src/shared/status-bar-defaults.ts
  • src/shared/types.ts

Comment thread src/main/rate-limits/grok-fetcher.ts Resolved
@@ -7,6 +7,7 @@ export const DEFAULT_STATUS_BAR_ITEMS: StatusBarItem[] = [
'opencode-go',
'kimi',
'minimax',
'grok',

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.

🗄️ 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 5

Repository: 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.

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

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 win

Add the Grok status-bar catalog entry
settings.appearance.statusBar.grokToggleDescription is 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 win

Add the GrokAccountsSection keys to src/renderer/src/i18n/locales/en.json. The 13 hash-based translate keys used here are missing from the English catalog, so bootstrap:locale-catalog will 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.ts
  • src/main/rate-limits/grok-auth.ts
  • src/main/rate-limits/grok-fetcher.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/settings/GrokAccountsSection.tsx
  • src/renderer/src/components/settings/accounts-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-grok-toggle-search.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.ts
  • 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/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

@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: 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.tsx
  • src/renderer/src/components/stats/StatsPane.tsx
  • src/renderer/src/components/stats/SubscriptionUsageSection.tsx
  • src/renderer/src/components/stats/stats-search.ts
  • src/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

Comment on lines +118 to +120
<Button variant="ghost" size="icon-xs" onClick={() => void refreshRateLimits()}>
<RefreshCw className="size-3.5" />
</Button>

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.

📐 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.

Suggested change
<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>

@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

@AmethystLiang
AmethystLiang removed their request for review July 9, 2026 19:28
@brennanb2025
brennanb2025 force-pushed the feature/grok-provider-usage-accounts branch from 33db9a0 to b9a8d16 Compare July 10, 2026 04:04
@brennanb2025

brennanb2025 commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Focused affected Vitest set passed: 11 files, 233 tests.
  • pnpm typecheck passed.
  • pnpm lint passed; remaining warnings were pre-existing unrelated warnings in test files plus the local Node 26 vs repo Node 24 warning.
  • Electron smoke passed with a mock Grok billing server for signed-in, signed-out, Grok stats pane, and status bar menu states.

@brennanb2025
brennanb2025 force-pushed the feature/grok-provider-usage-accounts branch from b9a8d16 to ed2e0b0 Compare July 10, 2026 04:08
Brennan Benson added 2 commits July 9, 2026 23:25
- 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.
@brennanb2025
brennanb2025 merged commit fa2b228 into stablyai:main Jul 10, 2026
3 checks passed
bbingz added a commit to bbingz/orca that referenced this pull request Jul 10, 2026
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.
@bbingz bbingz mentioned this pull request Jul 10, 2026
4 tasks done
brennanb2025 pushed a commit to bbingz/orca that referenced this pull request Jul 10, 2026
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.
brennanb2025 pushed a commit to bbingz/orca that referenced this pull request Jul 10, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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]>
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.

2 participants