Repository navigation
feat(rate-limits): add Cursor usage tracking - #11780
dominikzabcik wants to merge 1 commit into
Conversation
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]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (41)
📝 WalkthroughWalkthroughThis 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. Comment |
Greptile SummaryThis PR adds Cursor IDE usage tracking to Orca by reading
Confidence Score: 3/5Two 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 Files Needing Attention:
|
| 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
Comments Outside Diff (1)
-
src/main/rate-limits/service.ts, line 1056-1116 (link)fetchClaudeOnlydoesn't draincursorOnlyFetchQueued, causing a permanent stallIf
refreshCursor()is called whilefetchClaudeOnlyis running,cursorOnlyFetchQueuedis set totrueand the cursor refresh awaitswaitForFetchIdle(). WhenfetchClaudeOnlyfinishes, it callsresolveFetchIdleWaiters()— but that helper returns early without resolving any waiters whencursorOnlyFetchQueuedis stilltrue(see the guard at line ~1273). Since nothing clears the flag, therefreshCursor()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*OnlyFetchQueuedflags before returning. ThefetchClaudeOnlymethod was written before Cursor was added and is missing acursorOnlyFetchQueueddrain block at the bottom of its queue-draining section (equivalent to lines 1170–1178 infetchGrokOnly).
Reviews (1): Last reviewed commit: "feat(rate-limits): add Cursor usage trac..." | Re-trigger Greptile
| 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, |
There was a problem hiding this comment.
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!
| 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 { |
There was a problem hiding this comment.
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.
| 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 { |
| 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 | ||
| } |
There was a problem hiding this comment.
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!
Summary
cursorAuth/accessTokenfrom Cursor IDEstate.vscdb, buildsWorkosCursorSessionToken, and pollscursor.com/api/usage-summary+/api/auth/me(same approach as CodexBar's Cursor provider).docs/cursor-usage-tracking.md.Test plan
pnpm testfor cursor-auth, cursor-fetcher, cursor-accounts/status, service, CursorUsagePane, CursorAccountsSection (86 tests)GET /api/usage-summarywith derived session cookie on macOSv1 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