Skip to content

Commit 2ab42a9

Browse files
committed
fix: Cursor 사용량 정확도와 호환성 보완
1 parent a3dfbc0 commit 2ab42a9

12 files changed

Lines changed: 126 additions & 15 deletions

File tree

‎docs/reference/cursor-usage-tracking.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ Plan total lives in `monthly`. Auto and API are named `buckets` (not Session/Wee
2525

2626
| Orca field | Cursor source |
2727
|------------|----------------|
28-
| `monthly` | `individualUsage.plan.totalPercentUsed` (fallback: auto/api average, cents ratio) |
29-
| `buckets` | `Auto` ← `autoPercentUsed`, `API` ← `apiPercentUsed` |
28+
| `monthly` | `individualUsage.plan.used / limit` (fallback: `totalPercentUsed`, auto/api average) |
29+
| `buckets` | `Auto` ← `autoPercentUsed`, `API` ← `apiPercentUsed`, `On-demand` ← `onDemand.used / limit` when enabled |
3030
| `session` / `weekly` | always `null` |
3131
| Reset | `billingCycleEnd` |
3232
| Auth label | cached email, `/api/auth/me`, or membership type |
@@ -47,7 +47,6 @@ Plan total lives in `monthly`. Auto and API are named `buckets` (not Session/Wee
4747
- Browser cookie import (CodexBar macOS feature)
4848
- Manual cookie header in settings
4949
- Multi-account switching
50-
- On-demand spend as the primary meter
5150
- Historical token/cost charts from `POST /api/dashboard/get-filtered-usage-events`
5251
- Automation run usage attribution for Cursor agent sessions
5352

‎src/main/codex-accounts/service-reset-credit-test-fixtures.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,10 @@ export function createResetRateLimitState(
3535
antigravity: null,
3636
minimax: null,
3737
grok: null,
38+
cursor: null,
3839
minimaxCookieConfigured: false,
3940
grokAuthConfigured: false,
41+
cursorAuthConfigured: false,
4042
claudeTarget: { runtime: 'host', wslDistro: null },
4143
codexTarget: target,
4244
inactiveClaudeAccounts: [],

‎src/main/rate-limits/cursor-fetcher.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ const USAGE_SUMMARY = {
6565
limit: 2000,
6666
autoPercentUsed: 45,
6767
apiPercentUsed: 30,
68-
totalPercentUsed: 60
68+
totalPercentUsed: 25
6969
},
70-
onDemand: { enabled: true, used: 100, limit: 5000 }
70+
onDemand: { enabled: true, used: 1000, limit: 5000 }
7171
}
7272
}
7373

@@ -89,7 +89,7 @@ describe('fetchCursorRateLimits', () => {
8989
expect(netFetchMock).not.toHaveBeenCalled()
9090
})
9191

92-
it('maps plan total into monthly only', async () => {
92+
it('maps Cursor included and on-demand usage into monthly meters', async () => {
9393
const token = makeJwt({ sub: 'auth0|cursor-user', exp: 4_102_444_800 })
9494
dbState.token = token
9595
dbState.email = '[email protected]'
@@ -105,7 +105,8 @@ describe('fetchCursorRateLimits', () => {
105105
expect(result.weekly).toBeNull()
106106
expect(result.buckets).toEqual([
107107
expect.objectContaining({ name: 'Auto', usedPercent: 45 }),
108-
expect.objectContaining({ name: 'API', usedPercent: 30 })
108+
expect.objectContaining({ name: 'API', usedPercent: 30 }),
109+
expect.objectContaining({ name: 'On-demand', usedPercent: 20 })
109110
])
110111
expect(result.usageMetadata?.source).toBe('web')
111112
expect(result.usageMetadata?.authProvenance).toContain('[email protected]')

‎src/main/rate-limits/cursor-fetcher.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ type CursorUsageSummary = {
3030
membershipType?: string
3131
individualUsage?: {
3232
plan?: CursorPlanUsage
33+
onDemand?: {
34+
enabled?: boolean
35+
used?: number
36+
limit?: number | null
37+
}
3338
}
3439
}
3540

@@ -104,6 +109,10 @@ function makeWindow(usedPercent: number, resetsAtIso: string | undefined): RateL
104109

105110
function resolvePlanPercent(summary: CursorUsageSummary): number {
106111
const plan = summary.individualUsage?.plan
112+
const fromIncludedUsage = percentFromCents(plan?.used, plan?.limit)
113+
if (fromIncludedUsage !== null) {
114+
return fromIncludedUsage
115+
}
107116
const totalPercent = normalizePercent(plan?.totalPercentUsed)
108117
if (totalPercent !== null) {
109118
return totalPercent
@@ -119,7 +128,7 @@ function resolvePlanPercent(summary: CursorUsageSummary): number {
119128
if (autoPercent !== null) {
120129
return autoPercent
121130
}
122-
return percentFromCents(plan?.used, plan?.limit) ?? 0
131+
return 0
123132
}
124133

125134
function mapUsageSummary(
@@ -147,6 +156,16 @@ function mapUsageSummary(
147156
...makeWindow(apiPercent, summary.billingCycleEnd)
148157
})
149158
}
159+
const onDemand = summary.individualUsage?.onDemand
160+
const onDemandPercent = onDemand?.enabled
161+
? percentFromCents(onDemand.used, onDemand.limit ?? undefined)
162+
: null
163+
if (onDemandPercent !== null) {
164+
buckets.push({
165+
name: 'On-demand',
166+
...makeWindow(onDemandPercent, summary.billingCycleEnd)
167+
})
168+
}
150169

151170
return {
152171
provider: 'cursor',
@@ -198,7 +217,10 @@ function unavailableFromAuth(readResult: CursorAuthReadResult): ProviderRateLimi
198217
failureKind: 'missing-credentials'
199218
})
200219
}
201-
return result('error', readResult.error, { source: 'web' })
220+
if (readResult.status === 'error') {
221+
return result('error', readResult.error, { source: 'web' })
222+
}
223+
return result('error', 'Cursor auth state is invalid', { source: 'web' })
202224
}
203225

204226
export async function fetchCursorRateLimits(

‎src/main/rate-limits/service-refresh-orchestration.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,40 @@ describe('RateLimitService', () => {
147147
expect(service.getState().cursor?.status).toBe('ok')
148148
})
149149

150+
it('discards Cursor usage when the signed-in account changes during refresh', async () => {
151+
const firstAccount = {
152+
status: 'ok' as const,
153+
session: {
154+
accessToken: 'first-token',
155+
userId: 'user-1',
156+
157+
expiresAtMs: null
158+
}
159+
}
160+
const secondAccount = {
161+
status: 'ok' as const,
162+
session: {
163+
accessToken: 'second-token',
164+
userId: 'user-2',
165+
166+
expiresAtMs: null
167+
}
168+
}
169+
const cursor = deferred<ProviderRateLimits>()
170+
vi.mocked(readCursorAuthSession).mockReturnValue(firstAccount)
171+
vi.mocked(fetchCursorRateLimits).mockReturnValueOnce(cursor.promise)
172+
const service = new RateLimitService()
173+
174+
const refresh = service.refreshCursor()
175+
await flushMicrotasks()
176+
vi.mocked(readCursorAuthSession).mockReturnValue(secondAccount)
177+
cursor.resolve(okProvider('cursor', 60))
178+
await refresh
179+
180+
expect(service.getState().cursor).toBeNull()
181+
expect(service.getState().cursorAuthConfigured).toBe(true)
182+
})
183+
150184
it('refreshes Grok without refreshing other providers', async () => {
151185
const authReadResult = {
152186
status: 'ok' as const,

‎src/main/rate-limits/service.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import type { KimiHomeResolution } from '../kimi/kimi-runtime-home'
2525
import { fetchGrokRateLimits } from './grok-fetcher'
2626
import { readGrokAuthSession } from './grok-auth'
2727
import { fetchCursorRateLimits } from './cursor-fetcher'
28-
import { readCursorAuthSession } from './cursor-auth'
28+
import { readCursorAuthSession, type CursorAuthReadResult } from './cursor-auth'
2929
import { hasMiniMaxSessionCookie } from '../minimax/minimax-cookie-store'
3030
import { fetchMiniMaxRateLimits } from './minimax-fetcher'
3131
import { fetchOpenCodeGoRateLimits } from './opencode-go-usage-fetcher'
@@ -115,6 +115,10 @@ type InternalRateLimitState = {
115115
cursor: ProviderRateLimits | null
116116
}
117117

118+
function cursorAccountIdentity(readResult: CursorAuthReadResult): string | null {
119+
return readResult.status === 'ok' ? readResult.session.userId : null
120+
}
121+
118122
function normalizePollingInterval(ms: number): number {
119123
if (!Number.isFinite(ms)) {
120124
return DEFAULT_POLL_MS
@@ -1765,6 +1769,7 @@ export class RateLimitService {
17651769
this.grokAuthConfigured = grokAuthReadResult.status === 'ok'
17661770
const cursorAuthReadResult = readCursorAuthSession()
17671771
this.cursorAuthConfigured = cursorAuthReadResult.status === 'ok'
1772+
const cursorAccountId = cursorAccountIdentity(cursorAuthReadResult)
17681773

17691774
// Discard stale data on config change — it belongs to a different session/workspace.
17701775
const currentConfigHash = `${cookie}|${workspaceIdOverride}`
@@ -2043,6 +2048,12 @@ export class RateLimitService {
20432048
if (signal.aborted) {
20442049
return
20452050
}
2051+
const latestCursorAuthReadResult = readCursorAuthSession()
2052+
this.cursorAuthConfigured = latestCursorAuthReadResult.status === 'ok'
2053+
if (cursorAccountIdentity(latestCursorAuthReadResult) !== cursorAccountId) {
2054+
this.updateState({ ...this.state, cursor: null })
2055+
return
2056+
}
20462057
const cursor =
20472058
cursorResult.status === 'fulfilled'
20482059
? cursorResult.value
@@ -2250,6 +2261,7 @@ export class RateLimitService {
22502261
const previousState = this.state
22512262
const cursorAuthReadResult = readCursorAuthSession()
22522263
this.cursorAuthConfigured = cursorAuthReadResult.status === 'ok'
2264+
const cursorAccountId = cursorAccountIdentity(cursorAuthReadResult)
22532265

22542266
this.updateState({
22552267
...previousState,
@@ -2274,6 +2286,13 @@ export class RateLimitService {
22742286
return
22752287
}
22762288

2289+
const latestCursorAuthReadResult = readCursorAuthSession()
2290+
this.cursorAuthConfigured = latestCursorAuthReadResult.status === 'ok'
2291+
if (cursorAccountIdentity(latestCursorAuthReadResult) !== cursorAccountId) {
2292+
this.updateState({ ...this.state, cursor: null })
2293+
return
2294+
}
2295+
22772296
this.trackActiveFailureStreak('cursor', cursor)
22782297
this.updateState({
22792298
...this.state,

‎src/main/runtime/rpc/methods/client-ui-schemas.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ const StatusBarItem = z.enum([
6969
'kimi',
7070
'minimax',
7171
'grok',
72+
'cursor',
7273
'ssh',
7374
'resource-usage',
7475
'ports'
@@ -229,6 +230,7 @@ const UiUpdateFields = z
229230
_minimaxStatusBarDefaultAdded: z.boolean().optional(),
230231
_antigravityStatusBarDefaultAdded: z.boolean().optional(),
231232
_grokStatusBarDefaultAdded: z.boolean().optional(),
233+
_cursorStatusBarDefaultAdded: z.boolean().optional(),
232234
statusBarVisible: z.boolean().optional(),
233235
usagePercentageDisplay: z.enum(['used', 'remaining']).optional(),
234236
statusBarUsageMode: z.enum(['verbose', 'compact']).optional(),

‎src/renderer/src/components/settings/CursorAccountsSection.tsx‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ export function CursorAccountsSection(): React.JSX.Element {
5555
const usageWindow = cursorUsage?.monthly ?? null
5656
const autoBucket = cursorUsage?.buckets?.find((b) => b.name === 'Auto')
5757
const apiBucket = cursorUsage?.buckets?.find((b) => b.name === 'API')
58+
const onDemandBucket = cursorUsage?.buckets?.find((b) => b.name === 'On-demand')
5859

5960
return (
6061
<section id="accounts-cursor" className="space-y-4 scroll-mt-6">
@@ -154,15 +155,15 @@ export function CursorAccountsSection(): React.JSX.Element {
154155
</Button>
155156
</div>
156157

157-
{usageWindow || autoBucket || apiBucket ? (
158+
{usageWindow || autoBucket || apiBucket || onDemandBucket ? (
158159
<SearchableSetting
159160
title={translate(
160161
'auto.components.settings.CursorAccountsSection.a8f3e2c1b4',
161162
'Plan usage'
162163
)}
163164
description={translate(
164165
'auto.components.settings.CursorAccountsSection.b7e2d9f0a3',
165-
'Same plan / Auto / API % as the Cursor dashboard.'
166+
'Same plan, Auto, API, and on-demand usage as the Cursor dashboard.'
166167
)}
167168
keywords={['cursor', 'usage', 'subscription', 'plan', 'auto', 'api']}
168169
>
@@ -194,6 +195,15 @@ export function CursorAccountsSection(): React.JSX.Element {
194195
)}
195196
</Badge>
196197
) : null}
198+
{onDemandBucket ? (
199+
<Badge variant="secondary" className="tabular-nums">
200+
{translate(
201+
'auto.components.settings.CursorAccountsSection.0a1b2c3d4e',
202+
'On-demand {{pct}}%',
203+
{ pct: String(Math.round(onDemandBucket.usedPercent)) }
204+
)}
205+
</Badge>
206+
) : null}
197207
{usageWindow?.resetDescription ? (
198208
<span className="text-muted-foreground">
199209
{translate(

‎src/renderer/src/components/stats/CursorUsagePane.test.tsx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,13 @@ const mockStoreState = {
4949
windowMinutes: 43_200,
5050
resetsAt: null,
5151
resetDescription: null
52+
},
53+
{
54+
name: 'On-demand',
55+
usedPercent: 20,
56+
windowMinutes: 43_200,
57+
resetsAt: null,
58+
resetDescription: null
5259
}
5360
],
5461
updatedAt: 1,
@@ -115,6 +122,8 @@ describe('CursorUsagePane', () => {
115122
expect(screen.getByText('45%')).toBeInTheDocument()
116123
expect(screen.getByText('API')).toBeInTheDocument()
117124
expect(screen.getByText('30%')).toBeInTheDocument()
125+
expect(screen.getByText('On-demand')).toBeInTheDocument()
126+
expect(screen.getByText('20%')).toBeInTheDocument()
118127
expect(storeMocks.refreshCursorRateLimits).not.toHaveBeenCalled()
119128
})
120129

‎src/renderer/src/components/stats/CursorUsagePane.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ export function CursorUsagePane(): React.JSX.Element {
7575
const used = cursor?.buckets?.find((b) => b.name === 'API')?.usedPercent
7676
return typeof used === 'number' ? Math.round(used) : null
7777
})()
78+
const onDemandPercent = (() => {
79+
const used = cursor?.buckets?.find((b) => b.name === 'On-demand')?.usedPercent
80+
return typeof used === 'number' ? Math.round(used) : null
81+
})()
7882
const isFetching = isRefreshing || cursor?.status === 'fetching'
7983

8084
return (
@@ -119,7 +123,7 @@ export function CursorUsagePane(): React.JSX.Element {
119123
</div>
120124
</div>
121125

122-
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
126+
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
123127
<StatCard
124128
label={translate('auto.components.stats.CursorUsagePane.a1b2c3d4e5', 'Plan usage')}
125129
value={monthlyPercent !== null ? `${monthlyPercent}%` : '—'}
@@ -135,6 +139,11 @@ export function CursorUsagePane(): React.JSX.Element {
135139
value={apiPercent !== null ? `${apiPercent}%` : '—'}
136140
icon={<Sparkles className="size-4" />}
137141
/>
142+
<StatCard
143+
label={translate('auto.components.stats.CursorUsagePane.c0d1e2f3a4', 'On-demand')}
144+
value={onDemandPercent !== null ? `${onDemandPercent}%` : '—'}
145+
icon={<Sparkles className="size-4" />}
146+
/>
138147
<StatCard
139148
label={translate(
140149
'auto.components.stats.CursorUsagePane.b2c3d4e5f6',

0 commit comments

Comments
 (0)