Skip to content

feat(rate-limits): add Cursor usage tracking - #11780

Closed
dominikzabcik wants to merge 1 commit into
stablyai:mainfrom
dominikzabcik:feat/cursor-usage-tracking
Closed

dominikzabcik wants to merge 1 commit into
stablyai:mainfrom
dominikzabcik:feat/cursor-usage-tracking

Conversation

@dominikzabcik

Copy link
Copy Markdown
Contributor

Summary

  • Adds Cursor plan usage to Orca (status bar, usage roster, Stats pane, Accounts settings), matching the Grok/Antigravity provider pattern.
  • Auth reads cursorAuth/accessToken from Cursor IDE state.vscdb, builds WorkosCursorSessionToken, and polls cursor.com/api/usage-summary + /api/auth/me (same approach as CodexBar's Cursor provider).
  • Includes unit tests and docs/cursor-usage-tracking.md.

Test plan

  • pnpm test for cursor-auth, cursor-fetcher, cursor-accounts/status, service, CursorUsagePane, CursorAccountsSection (86 tests)
  • Verified live GET /api/usage-summary with derived session cookie on macOS
  • Manual: sign into Cursor IDE, open Orca → status bar shows Cursor meters; Stats → Cursor tab; Settings → Accounts → Cursor section

v1 scope / follow-ups

v1 is quota meters only (no historical cost charts). Documented out-of-scope items in docs/cursor-usage-tracking.md: browser cookie import, manual cookie header, multi-account switching, dashboard usage events API, automation run attribution.

Made with Cursor

Read Cursor plan usage from cursor.com via the signed-in IDE session
(state.vscdb access token), mirroring CodexBar's Cursor provider.
Surfaces meters in the status bar, usage roster, Stats pane, and
Accounts settings with tests and docs.

Co-authored-by: Cursor <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: edf74bbc-40c2-4e7c-8369-4f07cb6ab6b3

📥 Commits

Reviewing files that changed from the base of the PR and between 79251d7 and 189f61e.

📒 Files selected for processing (41)
  • src/main/cursor-accounts/status.test.ts
  • src/main/cursor-accounts/status.ts
  • src/main/ipc/cursor-accounts.ts
  • src/main/ipc/rate-limits.ts
  • src/main/ipc/register-core-handlers.ts
  • src/main/rate-limits/cursor-auth.test.ts
  • src/main/rate-limits/cursor-auth.ts
  • src/main/rate-limits/cursor-fetcher.test.ts
  • src/main/rate-limits/cursor-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/CursorAccountsSection.test.tsx
  • src/renderer/src/components/settings/CursorAccountsSection.tsx
  • src/renderer/src/components/settings/accounts-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-cursor-toggle-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-ssh-toggle-search.ts
  • src/renderer/src/components/stats/CursorUsagePane.test.tsx
  • src/renderer/src/components/stats/CursorUsagePane.tsx
  • src/renderer/src/components/stats/StatsPane.tsx
  • src/renderer/src/components/stats/stats-search.ts
  • src/renderer/src/components/status-bar/StatusBar.tsx
  • 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.test.ts
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/components/status-bar/usage-provider-settings-target.test.ts
  • src/renderer/src/components/status-bar/usage-provider-settings-target.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/store/slices/rate-limits.ts
  • src/renderer/src/store/slices/ui.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/cursor-session-paths.ts
  • src/shared/rate-limit-types.test.ts
  • src/shared/rate-limit-types.ts
  • src/shared/status-bar-defaults.ts
  • src/shared/types.ts

📝 Walkthrough

Walkthrough

This change adds Cursor authentication and rate-limit support across the application. It reads Cursor session data, fetches and maps usage data, and exposes account and refresh APIs through IPC and preload. The renderer adds Cursor account settings, usage analytics, search metadata, localized text, store state, web fallbacks, and status-bar integration. Tests cover authentication, fetching, service refresh behavior, account status, UI rendering, and provider visibility.


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.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds Cursor IDE usage tracking to Orca by reading cursorAuth/accessToken from Cursor's state.vscdb SQLite database, constructing a WorkosCursorSessionToken cookie, and polling cursor.com/api/usage-summary + /api/auth/me. The new provider follows the established Grok/Antigravity pattern and surfaces quota meters in the status bar, Stats pane, and Accounts settings.

  • Auth layer (cursor-auth.ts, cursor-session-paths.ts): decodes the JWT from the local SQLite DB, extracts userId from the sub claim, checks expiry, and builds the session cookie header — all with solid error handling and cross-platform path resolution.
  • Fetcher (cursor-fetcher.ts): maps the JSON response into ProviderRateLimits windows; when onDemand.enabled is true the monthly field is overwritten with the on-demand spending window, causing "Plan usage" labels in both CursorUsagePane and CursorAccountsSection to display the on-demand percent instead of the plan quota percent.
  • Service integration (service.ts): adds the Cursor fetch cycle and queue-draining boilerplate, but fetchClaudeOnly was not updated to drain the new cursorOnlyFetchQueued flag, which can leave a refreshCursor() call permanently awaiting waitForFetchIdle() when both are in flight together.

Confidence Score: 3/5

Two correctness issues need fixing before merge: users with on-demand billing enabled will see the wrong metric labeled as "Plan usage", and a concurrent Claude+Cursor refresh can leave the cursor refresh call permanently pending.

The auth and IPC plumbing is solid and mirrors proven patterns from Grok. However, the monthly field in mapUsageSummary is overwritten with on-demand data when on-demand billing is active, and both UI surfaces read cursor.monthly as the "Plan usage" figure — so those users see their spending rate, not their quota. Separately, fetchClaudeOnly omits the cursorOnlyFetchQueued drain that every peer fetch method added in this same PR includes, creating a scenario where a concurrent refreshCursor() call never completes. Both issues affect real users and real user flows.

Files Needing Attention: src/main/rate-limits/service.ts (missing queue drain in fetchClaudeOnly) and src/main/rate-limits/cursor-fetcher.ts (on-demand overwriting plan in the monthly field).

Important Files Changed

Filename Overview
src/main/rate-limits/service.ts Core polling service: Cursor fetch cycle and queue-draining logic added, but fetchClaudeOnly is missing the cursorOnlyFetchQueued drain that every other peer method includes — can cause a non-resolving promise when cursor refresh is queued behind a Claude-only cycle.
src/main/rate-limits/cursor-fetcher.ts Fetches /api/usage-summary and /api/auth/me with a cookie derived from the local DB token; the on-demand→monthly assignment silently overrides plan usage when on-demand billing is enabled, and the session parameter is mutated in place.
src/main/rate-limits/cursor-auth.ts Reads and decodes the Cursor IDE access token from state.vscdb; JWT parsing, userId extraction, and expiry checks are well-guarded and correctly handle SQLite errors.
src/shared/cursor-session-paths.ts Platform-specific path resolver for Cursor's state.vscdb; correctly handles macOS, Windows (APPDATA fallback), and Linux (XDG_CONFIG_HOME fallback).
src/main/cursor-accounts/status.ts Thin adapter that translates readCursorAuthSession results into CursorAccountStatus; correct and consistent with the Grok pattern.
src/renderer/src/components/stats/CursorUsagePane.tsx Stats pane for Cursor; reads cursor.monthly.usedPercent as "Plan usage" — will show on-demand usage percent (not plan quota) when on-demand billing is active on the account.
src/renderer/src/components/settings/CursorAccountsSection.tsx Settings section showing sign-in state and plan usage badge; same on-demand-vs-plan labeling concern inherited from the fetcher's monthly field assignment.
src/main/ipc/cursor-accounts.ts Minimal IPC handler wiring for cursorAccounts:getStatus; straightforward and consistent with other account handlers.
src/main/ipc/rate-limits.ts Added rateLimits:refreshCursor IPC handler; correctly wired to rateLimits.refreshCursor().
src/shared/rate-limit-types.ts Added cursor to ProviderRateLimits.provider union, CursorAccountStatus type, and cursorAuthConfigured/cursor fields in RateLimitState; clean type additions.

Sequence Diagram

sequenceDiagram
    participant R as Renderer
    participant IPC as IPC (main)
    participant SVC as RateLimitService
    participant AUTH as cursor-auth
    participant DB as state.vscdb (SQLite)
    participant API as cursor.com

    R->>IPC: rateLimits:refreshCursor
    IPC->>SVC: refreshCursor()
    SVC->>SVC: "fetchCursorOnly({ force: true })"
    SVC->>AUTH: readCursorAuthSession()
    AUTH->>DB: "SELECT value FROM ItemTable WHERE key='cursorAuth/accessToken'"
    DB-->>AUTH: accessToken (JWT)
    AUTH-->>SVC: "{ status: 'ok', session }"
    SVC->>API: GET /api/usage-summary (Cookie: WorkosCursorSessionToken)
    API-->>SVC: "{ billingCycleEnd, individualUsage, ... }"
    SVC->>API: GET /api/auth/me (Cookie: WorkosCursorSessionToken)
    API-->>SVC: "{ email, name }"
    SVC->>SVC: mapUsageSummary() → ProviderRateLimits
    SVC->>SVC: "updateState({ cursor: ... })"
    SVC-->>R: rateLimits:update (IPC push)
    IPC-->>R: RateLimitState
Loading

Comments Outside Diff (1)

  1. src/main/rate-limits/service.ts, line 1056-1116 (link)

    P1 fetchClaudeOnly doesn't drain cursorOnlyFetchQueued, causing a permanent stall

    If refreshCursor() is called while fetchClaudeOnly is running, cursorOnlyFetchQueued is set to true and the cursor refresh awaits waitForFetchIdle(). When fetchClaudeOnly finishes, it calls resolveFetchIdleWaiters() — but that helper returns early without resolving any waiters when cursorOnlyFetchQueued is still true (see the guard at line ~1273). Since nothing clears the flag, the refreshCursor() promise never resolves and the UI stays in a perpetual "refreshing" state for that call.

    Every other independently-refreshable provider's dedicated fetch method (fetchCodexOnly, fetchGrokOnly, fetchCursorOnly) drains all peer *OnlyFetchQueued flags before returning. The fetchClaudeOnly method was written before Cursor was added and is missing a cursorOnlyFetchQueued drain block at the bottom of its queue-draining section (equivalent to lines 1170–1178 in fetchGrokOnly).

Reviews (1): Last reviewed commit: "feat(rate-limits): add Cursor usage trac..." | Re-trigger Greptile

Comment on lines +175 to +205
const onDemand = summary.individualUsage?.onDemand
const onDemandPercent = percentFromCents(onDemand?.used, onDemand?.limit)
const monthlyOnDemand =
onDemand?.enabled === true && onDemandPercent !== null
? makeWindow(onDemandPercent, summary.billingCycleEnd, MONTHLY_WINDOW_MINUTES)
: null

const buckets: RateLimitBucket[] = []
if (autoPercent !== null) {
buckets.push({
name: 'Auto',
...makeWindow(autoPercent, summary.billingCycleEnd, MONTHLY_WINDOW_MINUTES)
})
}
if (apiPercent !== null) {
buckets.push({
name: 'API',
...makeWindow(apiPercent, summary.billingCycleEnd, MONTHLY_WINDOW_MINUTES)
})
}

const email = userInfo?.email?.trim()
const membership = summary.membershipType?.trim()
const authLabel = email || userInfo?.name?.trim() || 'Cursor account'
const provenance = membership ? `${authLabel} (${membership})` : authLabel

return {
provider: 'cursor',
session,
weekly,
monthly: monthlyOnDemand ?? monthly,

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 On-demand usage silently replaces plan usage under the "Plan usage" label

When onDemand.enabled === true, monthlyOnDemand is set and takes precedence over the plan window (monthly: monthlyOnDemand ?? monthly). Both CursorUsagePane ("Plan usage" stat card reads cursor?.monthly?.usedPercent) and CursorAccountsSection ("Plan usage" badge reads usageWindow = cursorUsage?.monthly ?? ...) will display the on-demand spending percentage, not the plan quota percentage — even though both are labeled "Plan usage" and described as "Same plan usage % as the Cursor dashboard."

A pro user with on-demand billing enabled would see their on-demand spending rate instead of their plan quota usage. If on-demand usage is a distinct metric worth surfacing, it should be shown in a separate named bucket rather than overwriting the primary plan window.

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!

Comment on lines +288 to +296
const userResponse = await fetchJson<CursorUserInfo>('/api/auth/me', cookieHeader, signal)
const userInfo = userResponse.ok ? userResponse.data : null
if (userInfo?.email && !session.email) {
session.email = userInfo.email
}

try {
return mapUsageSummary(summaryResponse.data, userInfo)
} catch {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Session parameter mutated in-place by fetchCursorRateLimitsForSession

The function writes session.email = userInfo.email directly on its argument. Since fetchCursorRateLimitsForSession is exported, callers that store and reuse a session object would have it silently modified. The enriched email is only needed for building the provenance string inside mapUsageSummary; it can be passed directly without touching the session.

Suggested change
const userResponse = await fetchJson<CursorUserInfo>('/api/auth/me', cookieHeader, signal)
const userInfo = userResponse.ok ? userResponse.data : null
if (userInfo?.email && !session.email) {
session.email = userInfo.email
}
try {
return mapUsageSummary(summaryResponse.data, userInfo)
} catch {
const userResponse = await fetchJson<CursorUserInfo>('/api/auth/me', cookieHeader, signal)
const userInfo = userResponse.ok ? userResponse.data : null
const resolvedEmail = userInfo?.email ?? session.email ?? null
const enrichedUserInfo = userInfo ? { ...userInfo, email: resolvedEmail } : null
try {
return mapUsageSummary(summaryResponse.data, enrichedUserInfo)
} catch {

Comment on lines +125 to +154
function resolvePlanPercent(summary: CursorUsageSummary): number {
const plan = summary.individualUsage?.plan
const totalPercent = normalizePercent(plan?.totalPercentUsed)
if (totalPercent !== null) {
return totalPercent
}
const autoPercent = normalizePercent(plan?.autoPercentUsed)
const apiPercent = normalizePercent(plan?.apiPercentUsed)
if (autoPercent !== null && apiPercent !== null) {
return clampPercent((autoPercent + apiPercent) / 2)
}
if (apiPercent !== null) {
return apiPercent
}
if (autoPercent !== null) {
return autoPercent
}
const fromCents = percentFromCents(plan?.used, plan?.limit)
if (fromCents !== null) {
return fromCents
}
const overall = summary.individualUsage?.overall
const overallPercent = percentFromCents(overall?.used, overall?.limit)
if (overallPercent !== null) {
return overallPercent
}
const pooled = summary.teamUsage?.pooled
const pooledPercent = percentFromCents(pooled?.used, pooled?.limit)
return pooledPercent ?? 0
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 resolvePlanPercent fallback averages two independent pool percentages

When totalPercentUsed is absent from the API response but both autoPercentUsed and apiPercentUsed are present, the fallback at lines 131–134 returns (autoPercent + apiPercent) / 2. This is a mathematical approximation that can mislead: if the auto pool is 80% of a 100-request budget and the API pool is 20% of a 500-request budget, the true total is 30% but the average gives 50%. Since totalPercentUsed is tried first, this only fires when the API omits that field — but the result could still surface a noticeably wrong value. A comment noting the approximation would reduce confusion.

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!

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.

1 participant