Skip to content

fix(grok): prefer auth.x.ai session + mention Grok in OSC52 toast#8392

Merged
Jinwoo-H merged 2 commits into
stablyai:mainfrom
bbingz:fix/grok-auth-prefer-auth-x-ai
Jul 13, 2026
Merged

fix(grok): prefer auth.x.ai session + mention Grok in OSC52 toast#8392
Jinwoo-H merged 2 commits into
stablyai:mainfrom
bbingz:fix/grok-auth-prefer-auth-x-ai

Conversation

@bbingz

@bbingz bbingz commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Grok auth.json can contain multiple issuer keys. readGrokAuthSession used Object.values and returned the first tokenized entry, so a stale alternate issuer written earlier could win over the live https://auth.x.ai::... OIDC session. That makes usage/account status pick the wrong token on multi-entry files.

Also updates the OSC 52 blocked-clipboard toast copy to mention Grok (alongside SSH/tmux/Neovim/fzf) so Grok TUI copy failures deep-link to the same setting.

Root cause

  • auth.json map order is insertion order; the first key-bearing entry is not necessarily the live Grok CLI session.
  • Grok CLI's default live issuer is under https://auth.x.ai / https://auth.x.ai::....

Fix

  • Prefer a fresh key that is exactly https://auth.x.ai or starts with https://auth.x.ai::, even when an expired preferred entry appears first.
  • Treat a tokenless preferred key as signed out instead of resurrecting a stale alternate; fall back to the first tokenized entry only when no preferred key exists.
  • List Grok in the blocked OSC52 description in all five supported locales.

Merge order

Land Grok-compat fixes in this order:

  1. fix(terminal): stop leaking Shift+Enter CSI-u without Kitty handshake #8386 - Shift/Ctrl+Enter CSI-u encoding (input correctness)
  2. Fix zero-percent Grok usage visibility #8336 - SuperGrok weekly zero usage (minimal; tracks fix(grok): tolerate missing creditUsagePercent in billing API #8298 as overreach)
  3. fix(codex): use argv-safe POSIX hook commands #8390 - Codex argv-safe POSIX hooks (tracks [Bug] Codex hooks failing when launched via Orca (from Grok) #8110)
  4. fix(preflight): do not pin empty WSL/local agent detection (#8366) #8391 - non-sticky empty WSL/local agent detection (tracks [windows] Sometimes Grok CLI is not detected in Orca but works in system terminal #8366)
  5. This PR - prefer auth.x.ai + OSC52 Grok toast copy

This PR is independent of #8386 / #8336 / #8390 / #8391 (no shared files with those diffs). It can land as soon as it is green; the order above is for review sequencing of the Grok-compat batch only.

Test plan

  • pnpm exec vitest run --config config/vitest.config.ts src/main/rate-limits/grok-auth.test.ts src/main/rate-limits/grok-fetcher.test.ts src/main/grok-accounts/status.test.ts src/main/rate-limits/service.test.ts src/renderer/src/components/terminal-pane/osc52-clipboard-blocked-toast.test.ts
  • Unit: multi-issuer auth.json prefers auth.x.ai token
  • Unit: expired/tokenless preferred entries cannot hide a usable preferred session or resurrect a stale alternate
  • Unit: alternate fallback is retained when no preferred issuer key exists
  • Unit: OSC52 toast description mentions Grok in all supported locales
  • Electron: isolated multi-key auth.json sent the preferred token to a local billing stub and rendered the expected usage/account

auth.json can hold multiple issuer keys; Object.values order could pick a
stale entry before the live auth.x.ai OIDC session. Prefer auth.x.ai keys
and fall back only when none exist. Also list Grok in the OSC52 blocked
clipboard toast so Grok TUI copy failures point at the same setting.
@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Grok authentication session reading now maps tokenized entries, prefers fresh auth.x.ai entries including client-suffixed keys, preserves expired preferred sessions over fallbacks, and returns missing status for tokenless preferred entries. Tests cover precedence, fallback, expiration, and field mapping. OSC 52 clipboard-blocked messaging now mentions Grok in the toast and all supported English, Spanish, Chinese, Japanese, and Korean locales, with corresponding assertions.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary and testing, but omits required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections, including Screenshots, AI Review Report with cross-platform checks, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the two main changes: auth.x.ai session selection and OSC52 toast copy.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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.

🧹 Nitpick comments (2)
src/main/rate-limits/grok-auth.ts (1)

70-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider narrowing parseAuthEntry's return type to eliminate the ! assertion.

sessionFromAuthEntry uses authEntry.key! because TypeScript can't propagate the runtime validation from parseAuthEntry. Having parseAuthEntry return a type with key: string (non-optional) would make the safety guarantee explicit and remove the assertion.

♻️ Optional type narrowing
+type ValidatedGrokAuthEntry = Omit<GrokAuthEntry, 'key'> & { key: string }
+
-function parseAuthEntry(value: unknown): GrokAuthEntry | null {
+function parseAuthEntry(value: unknown): ValidatedGrokAuthEntry | null {
   if (typeof value !== 'object' || value === null) {
     return null
   }
   const entry = value as GrokAuthEntry
   if (typeof entry.key !== 'string' || entry.key.length === 0) {
     return null
   }
-  return entry
+  return entry as ValidatedGrokAuthEntry
 }

-function sessionFromAuthEntry(authEntry: GrokAuthEntry): GrokAuthSession {
+function sessionFromAuthEntry(authEntry: ValidatedGrokAuthEntry): GrokAuthSession {
   return {
-    accessToken: authEntry.key!,
+    accessToken: authEntry.key,
src/main/rate-limits/grok-auth.test.ts (1)

48-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider adding a test for the exact https://auth.x.ai key (without :: suffix).

isPreferredGrokAuthKey has an exact-match branch (key === PREFERRED_GROK_AUTH_ISSUER) that isn't covered by the current tests — both fixtures use ::-suffixed keys. A quick test with the bare issuer key would close that gap.

✅ Optional test for exact-match branch
it('selects an exact auth.x.ai key without :: suffix', async () => {
  vi.doMock('node:fs', () => ({
    existsSync: vi.fn(() => true),
    readFileSync: vi.fn(() =>
      JSON.stringify({
        'https://auth.x.ai': {
          key: 'exact-token',
          user_id: 'exact-user',
          email: 'exact@example.com',
          expires_at: '2099-01-01T00:00:00.000Z'
        }
      })
    )
  }))
  const { readGrokAuthSession } = await import('./grok-auth')

  expect(readGrokAuthSession()).toEqual({
    status: 'ok',
    session: {
      accessToken: 'exact-token',
      userId: 'exact-user',
      email: 'exact@example.com',
      teamId: null,
      expiresAtMs: Date.parse('2099-01-01T00:00:00.000Z'),
      oidcClientId: null
    }
  })
})

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4c8cf3eb-7a85-4b83-b184-5c564c71e1fc

📥 Commits

Reviewing files that changed from the base of the PR and between 26934b1 and 699e232.

📒 Files selected for processing (6)
  • src/main/rate-limits/grok-auth.test.ts
  • src/main/rate-limits/grok-auth.ts
  • src/renderer/src/components/terminal-pane/osc52-clipboard-blocked-toast.test.ts
  • src/renderer/src/components/terminal-pane/osc52-clipboard-blocked-toast.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/zh.json

Co-authored-by: Orca <help@stably.ai>

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

Thanks! I reviewed and tested this against current main.

  • Hardened selection across multiple, expired, and tokenless auth.x.ai entries.
  • Preserved alternate-issuer fallback only when no preferred issuer exists.
  • Completed the OSC52 Grok copy in all supported locales.
  • Verified with 67 focused tests, typecheck/lint, and Electron validation.

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

🧹 Nitpick comments (1)
src/main/rate-limits/grok-auth.test.ts (1)

118-140: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for expired-preferred-over-fallback behavior.

The implementation (expiredPreferred ?? (preferredKeySeen ? null : fallback)) returns an expired preferred session instead of a fresh fallback when no fresh preferred entry exists. This behavior is described in the PR summary ("preserves expired preferred sessions over fallbacks") but has no test coverage. A regression like fallback ?? expiredPreferred would pass all current tests while breaking this contract.

🧪 Suggested companion test
   it('skips an expired auth.x.ai client entry when a fresh one follows it', async () => {
     // ... existing test ...
   })
+
+  it('preserves an expired auth.x.ai session over a fresh alternate issuer', async () => {
+    vi.doMock('node:fs', () => ({
+      existsSync: vi.fn(() => true),
+      readFileSync: vi.fn(() =>
+        JSON.stringify({
+          'https://alternate.example.com::client': {
+            key: 'alt-token',
+            user_id: 'alt-user',
+            expires_at: '2099-01-01T00:00:00.000Z'
+          },
+          'https://auth.x.ai::client': {
+            key: 'expired-token',
+            user_id: 'expired-user',
+            expires_at: '2020-01-01T00:00:00.000Z'
+          }
+        })
+      )
+    }))
+    const { readGrokAuthSession } = await import('./grok-auth')
+
+    expect(readGrokAuthSession()).toMatchObject({
+      status: 'ok',
+      session: { accessToken: 'expired-token' }
+    })
+  })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0d93952f-ecdc-42f4-9fd1-00b6ed3f469f

📥 Commits

Reviewing files that changed from the base of the PR and between 699e232 and 1576e8e.

📒 Files selected for processing (6)
  • src/main/rate-limits/grok-auth.test.ts
  • src/main/rate-limits/grok-auth.ts
  • src/renderer/src/components/terminal-pane/osc52-clipboard-blocked-toast.test.ts
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/rate-limits/grok-auth.ts

@Jinwoo-H Jinwoo-H merged commit 81ed573 into stablyai:main Jul 13, 2026
1 check passed
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