Skip to content

Fix Gemini usage via Antigravity quota - #11457

Closed
jongoks wants to merge 1 commit into
stablyai:mainfrom
jongoks:main
Closed

jongoks wants to merge 1 commit into
stablyai:mainfrom
jongoks:main

Conversation

@jongoks

@jongoks jongoks commented Jul 30, 2026 •

Copy link
Copy Markdown

English translation added for maintainers. Original 한국어 / Korean text is preserved below for reference.

English title

Fix Gemini usage via Antigravity quota

Changes

  • Fetch Gemini 5-hour / weekly usage from the Antigravity CLI loopback quota API.
  • Prefer Antigravity usage as the primary source for the Gemini status-bar item; fall back to the existing Gemini OAuth path when unavailable.
  • Select only the Gemini quota group so it is not mixed with Claude/GPT shared limits.
  • Isolate the new external path in existing Gemini tests and add parser / priority regression tests.

Root cause

Personal Gemini CLI accounts no longer provide quota (UNSUPPORTED_CLIENT), but Orca's Antigravity item was still cloning the failed Gemini snapshot. Antigravity CLI, using the logged-in keyring, exposes real Gemini quota via a local API.

Verification

  • pnpm exec vitest run --config config/vitest.config.ts src/main/rate-limits/antigravity-usage-fetcher.test.ts src/main/rate-limits/gemini-usage-fetcher.test.ts src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts src/main/rate-limits/service.test.ts (88 tests)
  • pnpm run typecheck:node
  • oxlint on changed files
  • Confirmed Gemini 5-hour / weekly buckets from a live Antigravity CLI v1.1.8 loopback response

Original (한국어 / Korean) — title: Fix Gemini usage via Antigravity quota

변경 사항

  • Antigravity CLI의 loopback quota API에서 Gemini 5시간/주간 사용량을 조회합니다.
  • Antigravity 사용량을 Gemini 상태바 항목의 우선 소스로 사용하고, 사용할 수 없을 때 기존 Gemini OAuth 경로로 fallback합니다.
  • Gemini quota 그룹만 선택해 Claude/GPT 공유 한도와 섞이지 않도록 합니다.
  • 기존 Gemini 테스트에서 새 외부 경로를 격리하고 parser/우선순위 회귀 테스트를 추가합니다.

원인

Gemini CLI 개인 계정은 UNSUPPORTED_CLIENT로 더 이상 quota를 제공하지 않지만, 현재 Orca의 Antigravity 항목은 실패한 Gemini snapshot을 그대로 복제하고 있었습니다. Antigravity CLI는 로그인된 keyring을 사용해 실제 Gemini quota를 로컬 API로 제공합니다.

검증

  • pnpm exec vitest run --config config/vitest.config.ts src/main/rate-limits/antigravity-usage-fetcher.test.ts src/main/rate-limits/gemini-usage-fetcher.test.ts src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts src/main/rate-limits/service.test.ts (88 tests)
  • pnpm run typecheck:node
  • 변경 파일 oxlint
  • 실제 Antigravity CLI v1.1.8 loopback 응답에서 Gemini 5시간/주간 bucket 확인

Comment on lines +146 to +167
async function waitForQuota(
port: number,
deadline: number
): Promise<{
session: RateLimitWindow | null
weekly: RateLimitWindow | null
}> {
let lastError: Error | null = null
while (Date.now() < deadline) {
try {
const parsed = parseAntigravityGeminiQuota(await requestQuota(port))
if (parsed) {
return parsed
}
lastError = new Error('Antigravity Gemini quota is unavailable')
} catch (error) {
lastError = error instanceof Error ? error : new Error('Antigravity quota request failed')
}
await delay(POLL_INTERVAL_MS)
}
throw lastError ?? new Error('Antigravity Gemini quota is unavailable')
}

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 Retry loop spins for the full deadline on a consistent null parse

When agy is running and reachable (port found, HTTP 200 returned) but the response contains no Gemini quota group, parseAntigravityGeminiQuota returns null on every iteration. The loop treats this the same as a transient error and retries every 200 ms until the 12-second deadline expires — making ~55 requests to the loopback service before propagating the error and triggering the legacy fallback. The right retry target is startup timing (service not yet ready to answer), but a successful 200 response with missing Gemini data is a stable signal that won't change on the next poll. Breaking out immediately when the response parses cleanly but yields no Gemini group would prevent the ~11-second unnecessary wait for any user whose Antigravity installation has no Gemini quota configured.

@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds a new antigravity-usage-fetcher module that spawns the agy CLI, discovers its ephemeral loopback HTTPS port from a log file, and fetches Gemini quota via a loopback gRPC-Connect call. fetchGeminiRateLimits is refactored to try Antigravity first and fall back to the existing OAuth path when Antigravity is unavailable.

  • New antigravity-usage-fetcher.ts: PTY-spawns agy, polls a log file for the HTTPS port, requests RetrieveUserQuotaSummary over loopback TLS (self-signed cert, rejectUnauthorized: false), and parses only the Gemini quota group for 5h and weekly buckets.
  • gemini-usage-fetcher.ts: The old fetchGeminiRateLimits is renamed fetchLegacyGeminiRateLimits; a new public wrapper tries Antigravity first and falls back to OAuth when status !== 'ok'.
  • Tests: Antigravity is mocked in both existing test suites; a new antigravity-usage-fetcher.test.ts covers the parser; a priority test in gemini-usage-fetcher.test.ts confirms Antigravity data takes precedence over OAuth sources.

Confidence Score: 4/5

Safe to merge with one behavioral gap worth addressing: Antigravity is never tried when the OAuth flag is off.

The new Antigravity fetcher and its parser are well-tested and the fallback chain is correct when OAuth is enabled. The one concrete gap is that fetchGeminiRateLimits short-circuits to the legacy 'OAuth disabled' response before calling fetchGeminiRateLimitsViaAntigravity whenever geminiCliOAuthEnabled is false — meaning Antigravity users who have not enabled the OAuth path in settings receive no Gemini quota data despite having the new integration available to them.

Files Needing Attention: src/main/rate-limits/gemini-usage-fetcher.ts — the fetchGeminiRateLimits wrapper needs a second look at the ordering of the geminiCliOAuthEnabled guard relative to the Antigravity call.

Important Files Changed

Filename Overview
src/main/rate-limits/gemini-usage-fetcher.ts Refactored to rename old export as fetchLegacyGeminiRateLimits and add new fetchGeminiRateLimits that tries Antigravity first. The geminiCliOAuthEnabled=false guard short-circuits before Antigravity is tried, so users with Antigravity but OAuth disabled receive no Gemini quota data.
src/main/rate-limits/antigravity-usage-fetcher.ts New module: spawns the agy PTY, polls a log file for the ephemeral HTTPS port, then fetches Gemini quota via loopback RPC with self-signed cert bypass. Logic is sound; the shared deadline between port-discovery and quota-polling can leave very little time for actual requests if startup is slow.
src/main/rate-limits/gemini-usage-fetcher.test.ts Adds Antigravity mock and a new priority test; existing auth-json tests are preserved with Antigravity stubbed to 'unavailable'. Coverage is solid.
src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts Adds Antigravity mock to the fallback suite; all existing OAuth-creds tests continue to work correctly with the mock stubbed to 'unavailable'.
src/main/rate-limits/antigravity-usage-fetcher.test.ts New unit tests for parseAntigravityGeminiQuota: covers Gemini-group filtering, correct bucket mapping, and null return when the group is absent. Correct and sufficient for the parser.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant fetchGeminiRateLimits
    participant fetchGeminiRateLimitsViaAntigravity
    participant agy as agy PTY process
    participant fetchLegacyGeminiRateLimits
    participant OAuthSources as OAuth sources

    Caller->>fetchGeminiRateLimits: geminiCliOAuthEnabled
    alt "geminiCliOAuthEnabled = false"
        fetchGeminiRateLimits->>fetchLegacyGeminiRateLimits: false
        fetchLegacyGeminiRateLimits-->>Caller: status: unavailable
    else "geminiCliOAuthEnabled = true"
        fetchGeminiRateLimits->>fetchGeminiRateLimitsViaAntigravity: (no args)
        fetchGeminiRateLimitsViaAntigravity->>agy: pty.spawn agy --log-file tmplog
        loop poll log every 200ms up to 12s
            fetchGeminiRateLimitsViaAntigravity->>fetchGeminiRateLimitsViaAntigravity: readFile → extract HTTPS port
        end
        fetchGeminiRateLimitsViaAntigravity->>agy: POST RetrieveUserQuotaSummary loopback TLS
        agy-->>fetchGeminiRateLimitsViaAntigravity: JSON quota response
        fetchGeminiRateLimitsViaAntigravity->>fetchGeminiRateLimitsViaAntigravity: parseAntigravityGeminiQuota
        alt Gemini quota parsed successfully
            fetchGeminiRateLimitsViaAntigravity-->>fetchGeminiRateLimits: status: ok
            fetchGeminiRateLimits-->>Caller: Antigravity quota
        else Antigravity unavailable
            fetchGeminiRateLimitsViaAntigravity-->>fetchGeminiRateLimits: status: unavailable
            fetchGeminiRateLimits->>fetchLegacyGeminiRateLimits: "geminiCliOAuthEnabled=true"
            fetchLegacyGeminiRateLimits->>OAuthSources: readAuthJson / readGeminiCredentials
            OAuthSources-->>fetchLegacyGeminiRateLimits: credentials
            fetchLegacyGeminiRateLimits-->>Caller: OAuth quota result
        end
    end
Loading

Reviews (2): Last reviewed commit: "Fix Gemini usage via Antigravity quota" | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an Antigravity-based Gemini quota fetcher that parses session and weekly limits, starts the local CLI, polls its HTTPS quota endpoint, and cleans up resources. Gemini rate-limit retrieval now tries Antigravity first when enabled, then falls back to the legacy OAuth implementation. Tests cover quota parsing, unavailable defaults, mocked Antigravity behavior, and precedence over auth.json.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is useful but does not follow the required template and omits the Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes sections. Reformat the description to match the template and add the missing sections, including screenshots/no visual change, test checklist, review report, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and clearly describes the main change: using Antigravity quota for Gemini usage.

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 (1)
src/main/rate-limits/antigravity-usage-fetcher.ts (1)

169-233: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Consider mocked unit tests for the pty/HTTPS polling path.

Only parseAntigravityGeminiQuota is unit-tested; the spawn/poll/timeout/cleanup logic in fetchGeminiRateLimitsViaAntigravity (process spawn failure, port-wait timeout, quota-poll timeout, cleanup ordering) has no direct coverage here. This is an external-call hazard path (process spawning, network I/O) worth exercising directly rather than only indirectly via the downstream mocked module.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0b267e44-cfb6-4e06-ab20-8ef4a9c7bacd

📥 Commits

Reviewing files that changed from the base of the PR and between 4e99602 and 9517ccd9a5e6ffe82212fd3a3e4d7b268a6af998.

📒 Files selected for processing (5)
  • src/main/rate-limits/antigravity-usage-fetcher.test.ts
  • src/main/rate-limits/antigravity-usage-fetcher.ts
  • src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts
  • src/main/rate-limits/gemini-usage-fetcher.test.ts
  • src/main/rate-limits/gemini-usage-fetcher.ts

Comment on lines +192 to +194
const deadline = Date.now() + STARTUP_TIMEOUT_MS
const port = await waitForHttpsPort(logPath, deadline)
const quota = await waitForQuota(port, deadline)

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Startup and quota-fetch phases share one 12s deadline.

waitForHttpsPort and waitForQuota both race against the same deadline computed once at line 192. If CLI startup takes most of STARTUP_TIMEOUT_MS, waitForQuota starts with almost no budget left and immediately throws "Antigravity Gemini quota is unavailable," even though the CLI itself started fine. Since this fallback path lands on the legacy Gemini OAuth flow — which is increasingly broken for accounts hitting UNSUPPORTED_CLIENT (the very problem this PR fixes) — a slow-but-successful Antigravity startup can silently degrade users back to a broken fallback.

Consider giving quota polling its own budget independent of startup time.

🔧 Proposed fix: separate startup and quota deadlines
-    disposables.push(registerHiddenRateLimitPty(term))
-    const deadline = Date.now() + STARTUP_TIMEOUT_MS
-    const port = await waitForHttpsPort(logPath, deadline)
-    const quota = await waitForQuota(port, deadline)
+    disposables.push(registerHiddenRateLimitPty(term))
+    const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS
+    const port = await waitForHttpsPort(logPath, startupDeadline)
+    const quotaDeadline = Date.now() + QUOTA_TIMEOUT_MS
+    const quota = await waitForQuota(port, quotaDeadline)

Comment on lines +251 to +262
export async function fetchGeminiRateLimits(
geminiCliOAuthEnabled = false
): Promise<ProviderRateLimits> {
if (!geminiCliOAuthEnabled) {
return fetchLegacyGeminiRateLimits(false)
}

const antigravity = await fetchGeminiRateLimitsViaAntigravity()
return antigravity.status === 'ok'
? antigravity
: fetchLegacyGeminiRateLimits(geminiCliOAuthEnabled)
}

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect where fetchGeminiRateLimits is called and how geminiCliOAuthEnabled is sourced/defaulted.
rg -n -B3 -A3 'fetchGeminiRateLimits\(' src/main --type=ts -g '!*.test.ts'
rg -n 'geminiCliOAuthEnabled' src/main --type=ts -g '!*.test.ts'

Repository: stablyai/orca

Length of output: 2965


🏁 Script executed:

#!/bin/bash
# Read the relevant sections of the file and settings definition without executing repository code.
wc -l src/main/rate-limits/gemini-usage-fetcher.ts src/main/rate-limits/service.ts
sed -n '1,275p' src/main/rate-limits/gemini-usage-fetcher.ts
sed -n '1530,1625p' src/main/rate-limits/service.ts
rg -n -B2 -A8 'geminiCliOAuthEnabled|Gemini CLI OAuth|geminiCli' src --type=ts --type=tsx --type=sh --type=ps1 -g '!*.test.ts'

Repository: stablyai/orca

Length of output: 13013


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf 'Files mentioning geminiCliOAuthEnabled:\n'
rg -n -B3 -A5 'geminiCliOAuthEnabled|Gemini CLI OAuth|geminiCli' src --glob '!*.test.ts'

printf '\nSettings type/definition candidates:\n'
rg -n -B2 -A8 'interface .*Setting|type .*Setting|geminiCliOAuthEnabled' src/shared src/main/preload src/**/*.ts --glob '!*.test.ts' 2>/dev/null || true

printf '\nStatus fetch behavior around previous gemini result:\n'
sed -n '1670,1760p' src/main/rate-limits/service.ts

Repository: stablyai/orca

Length of output: 50369


Don’t gate Antigravity behind geminiCliOAuthEnabled.

geminiCliOAuthEnabled is false by default and controls the legacy OAuth sources that touch Gemini CLI data folders. fetchGeminiRateLimits() currently returns before fetchGeminiRateLimitsViaAntigravity() runs when the legacy toggle is off, so the Antigravity usage path can be disabled by a setting that only exists to avoid unrelated OAuth filesystem access. Fetch Antigravity independently or through its own opt-in.

Comment on lines +251 to +262
export async function fetchGeminiRateLimits(
geminiCliOAuthEnabled = false
): Promise<ProviderRateLimits> {
if (!geminiCliOAuthEnabled) {
return fetchLegacyGeminiRateLimits(false)
}

const antigravity = await fetchGeminiRateLimitsViaAntigravity()
return antigravity.status === 'ok'
? antigravity
: fetchLegacyGeminiRateLimits(geminiCliOAuthEnabled)
}

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 Antigravity bypassed when geminiCliOAuthEnabled is false

The guard on line 254 routes directly to fetchLegacyGeminiRateLimits(false) — which immediately returns status: 'unavailable' — without ever calling fetchGeminiRateLimitsViaAntigravity. The macOS privacy concern that motivated the geminiCliOAuthEnabled gate (noted in the comment inside fetchLegacyGeminiRateLimits: "the OAuth sources include other apps' data folders") does not apply to Antigravity's loopback RPC, which makes no filesystem access into other applications' directories. As a result, any user who has Antigravity installed but has the OAuth path disabled in settings will never receive Gemini quota data through the new integration — exactly the case this PR is meant to serve.

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

♻️ Duplicate comments (2)
src/main/rate-limits/antigravity-usage-fetcher.ts (1)

169-233: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Startup and quota-fetch phases still share one deadline.

waitForHttpsPort (line 193) and waitForQuota (line 194) both race against the single deadline computed at line 192. A slow-but-successful CLI startup leaves little/no budget for quota polling, causing an immediate "Antigravity Gemini quota is unavailable" failure and silent fallback to the legacy OAuth path — the very path this PR is meant to route around for UNSUPPORTED_CLIENT accounts. This was flagged on a previous revision and remains unresolved.

🔧 Proposed fix: separate startup and quota deadlines
-    const deadline = Date.now() + STARTUP_TIMEOUT_MS
-    const port = await waitForHttpsPort(logPath, deadline)
-    const quota = await waitForQuota(port, deadline)
+    const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS
+    const port = await waitForHttpsPort(logPath, startupDeadline)
+    const quotaDeadline = Date.now() + QUOTA_TIMEOUT_MS
+    const quota = await waitForQuota(port, quotaDeadline)
src/main/rate-limits/gemini-usage-fetcher.ts (1)

251-262: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Antigravity is still gated behind geminiCliOAuthEnabled.

When geminiCliOAuthEnabled is false (the default), fetchGeminiRateLimits returns at line 255 before ever calling fetchGeminiRateLimitsViaAntigravity(). That flag exists to gate the legacy OAuth path's access to other apps' data folders (see the fetchLegacyGeminiRateLimits comment at lines 208-209) — it has no relation to Antigravity's local keyring/RPC mechanism. This means users with the OAuth toggle off (the default) never benefit from the Antigravity fix for UNSUPPORTED_CLIENT, contradicting the PR's stated goal that "Antigravity usage becomes the primary source ... with fallback to the existing Gemini OAuth path." This exact gating was flagged on a prior revision and remains unresolved.

🔧 Proposed fix: fetch Antigravity independently of the OAuth toggle
 export async function fetchGeminiRateLimits(
   geminiCliOAuthEnabled = false
 ): Promise<ProviderRateLimits> {
-  if (!geminiCliOAuthEnabled) {
-    return fetchLegacyGeminiRateLimits(false)
-  }
-
   const antigravity = await fetchGeminiRateLimitsViaAntigravity()
   return antigravity.status === 'ok'
     ? antigravity
     : fetchLegacyGeminiRateLimits(geminiCliOAuthEnabled)
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d7d54de5-4074-428d-9aa9-402657c5de10

📥 Commits

Reviewing files that changed from the base of the PR and between 9517ccd9a5e6ffe82212fd3a3e4d7b268a6af998 and 21783f2.

📒 Files selected for processing (5)
  • src/main/rate-limits/antigravity-usage-fetcher.test.ts
  • src/main/rate-limits/antigravity-usage-fetcher.ts
  • src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts
  • src/main/rate-limits/gemini-usage-fetcher.test.ts
  • src/main/rate-limits/gemini-usage-fetcher.ts

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.

3 participants