refactor(usage): Cursor account usage comes from provider-cursor #17578
t3/usage-opencode-reader fromrefs/pull/17578/head·merged by juliusmarminge View on GitHubUsageService owned Cursor's account usage: the dashboard reader, the in-memory and persisted account cache, TTL, failure memo, in-flight refresh dedupe, and the login/Keychain gating. Separately, keychainToken.ts in provider-cursor kept module-level memo state and threw a plain Error.
- These move into a
CursorUsageAccountsservice in provider-cursor, behind ascanreader onCursorDriver.usage. It persists to the sameusage-cursor-account-cache-v1.jsonunderProviderHost.paths.stateDir, so existing caches survive. cursorKeychainUsageEnabledis read throughProviderHost.settings.keychainToken.tsbecomes aCursorKeychainservice; its errors areSchema.TaggedErrors.
User-visible messages are unchanged.
Review note: CursorKeychain.layer is provided both in the adapter infrastructure and under layerUsage. Effect memoizes by layer reference, so this should build one instance (one Keychain prompt for usage limits and usage history), but that hasn't been verified at runtime on macOS.
🤖 Generated with Claude Code (Claude Opus 5.5, Claude Code harness)
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/provider-cursor/src/server/CursorUsageAccounts.ts lines 176 to 176OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +156,21 @@156+ if (result.missing || result.error !== null || result.accountKey === null) {157+ failures.set(credentialKey, {158+ atMs: nowMs,159+ error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR,160+ });161+ yield* schedulePersist;162+ return;163+ }164+ const merged = mergeCursorFetch(165+ base,166+ result.accountKey,167+ range,168+ result.records,169+ nowMs,170+ retentionStartMs,171+ );172+ caches.set(credentialKey, merged.cache);173+ failures.delete(credentialKey);174+ // An unchanged edge is not worth rewriting the file for: after a restart175+ // the cache just refetches a slightly wider edge.176+ if (merged.changed) {
🟡 Medium
server/CursorUsageAccounts.ts:176After a transient cache-write failure, later successful refreshes with unchanged records never persist the fetched history, so a restart loses the cache and forces another slow fetch.
persistrestorescacheDirty, but this block schedules a write only whenmerged.changedis true; also schedule one whencacheDirtyis already set.- if (merged.changed) { + if (merged.changed || cacheDirty) {🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @packages/provider-cursor/src/server/CursorUsageAccounts.ts around line 176: After a transient cache-write failure, later successful refreshes with unchanged records never persist the fetched history, so a restart loses the cache and forces another slow fetch. `persist` restores `cacheDirty`, but this block schedules a write only when `merged.changed` is true; also schedule one when `cacheDirty` is already set.Fixed in 6c5f9b7. A successful refresh now always calls
schedulePersist. That's a no-op when nothing is dirty, and it retries a write that failed earlier. This also matches main, where every finished scan scheduled a persist. Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
ℹ️ No successful
mainbaseline artifact is available yet. This run establishes the initial measurement.Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire — 5.0 KiB — 6.8 KiB ✅ Codex Thread snapshot wire — 3.8 KiB — 4.9 KiB ✅ Codex Live turn WebSocket wire — 1.2 KiB — 2.0 KiB ✅ Codex Live turn WebSocket decoded — 20.9 KiB — 29.3 KiB ✅ Codex Live turn messages — 2 — 8 ✅ Claude Total thread wire — 5.0 KiB — 6.8 KiB ✅ Claude Thread snapshot wire — 3.8 KiB — 4.9 KiB ✅ Claude Live turn WebSocket wire — 1.2 KiB — 2.0 KiB ✅ Claude Live turn WebSocket decoded — 21.2 KiB — 29.3 KiB ✅ Claude Live turn messages — 2 — 8 ✅ Baseline: unavailable · PR result:
aec4a9f· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 108.5 KiB
- Claude decoded thread snapshot: 108.8 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
Approvability#
Verdict: Not approved
Macroscope's review found this PR not approvable — This production refactor introduces substantial new Cursor usage and Keychain service wiring across the provider runtime, with cache, refresh, and credential behavior spanning multiple packages. It also adds a static-analysis suppression directive, so the change warrants direct human review.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Team
- Run ID:
6a2aab68-d981-45f7-b46c-bf90a467c0c7
📥 Commits
Reviewing files that changed from the base of the PR and between 6c5f9b759c520c544b9a73234ff183025a2ee6b1 and aec4a9fc48c62e7007014d5224313eda4695f4ea.
📒 Files selected for processing (4)
apps/server/src/usage/UsageService.tspackages/provider-core/src/server/usage.tspackages/provider-cursor/src/server/CursorUsageAccounts.tspackages/provider-cursor/src/server/driver.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.
📝 Walkthrough
Walkthrough#
Cursor account-usage reading, Keychain access, and persisted scan caching now reside in the provider package. The server registers Cursor as a built-in usage driver.
UsageServiceremoves its dedicated Cursor account-refresh and cache path.Changes#
Cursor provider usage
Layer / File(s) Summary Keychain access and account reading
packages/provider-cursor/src/server/CursorKeychain.ts,packages/provider-cursor/src/server/CursorAccountReader.ts,packages/provider-cursor/src/server/accountUsage.ts,packages/provider-cursor/src/server/usageLimits.ts,packages/provider-cursor/package.json,packages/provider-cursor/src/server.ts,packages/provider-cursor/src/server/*test.tsAdds a Keychain service that shares in-flight reads, caches non-null tokens for five minutes, and reports timeout or read errors. Adds CursorAccountReaderand uses the Keychain service for usage-limit reads. Account-usage tests cover pagination, response validation, and failure paths. The package exports the new server modules.Cached Cursor usage scans
packages/provider-cursor/src/server/CursorUsageAccounts.ts,packages/provider-cursor/src/server/accountCache.ts,packages/provider-cursor/src/server/accountCache.test.tsAdds per-credential persisted usage caches, refresh coordination, failure handling, and filtered scan results. Provider and server wiring
packages/provider-cursor/src/server/driver.ts,packages/provider-cursor/src/server/driver.test.ts,apps/server/src/provider/*,apps/server/src/provider/builtInDrivers.ts,apps/server/src/server.tsCursorDriverdelegates usage scans toCursorUsageAccountsand includesCursorKeychainin its environment. The server registers Cursor in its built-in drivers and provides the provider usage layers.UsageService migration and tests
packages/provider-core/src/server/usage.ts,apps/server/src/usage/UsageService.ts,apps/server/src/usage/UsageService.test.ts,apps/server/src/usage/*test.tsProviderUsageScanInputnow includes a settings snapshot.UsageServiceremoves Cursor-specific account-cache persistence and refresh logic. Usage-service tests use the provider account layer; Cursor account-history tests are removed from the server usage tests.Priority: ⬇️ Low
Estimated code review effort: 4 (Complex) | ~45 minutes
Change: Refactor
Sequence Diagram(s)#
sequenceDiagram participant CursorDriver participant CursorUsageAccounts participant CursorAccountReader participant CursorKeychain participant readCursorAccountUsage CursorDriver->>CursorUsageAccounts: scan window and refresh options CursorUsageAccounts->>CursorAccountReader: read account history CursorAccountReader->>CursorKeychain: retrieve token for Keychain credentials CursorAccountReader->>readCursorAccountUsage: read usage for the requested time range readCursorAccountUsage-->>CursorUsageAccounts: account usage result CursorUsageAccounts-->>CursorDriver: filtered usage scan
Merge Risk: ⚪ Minimal · up to
aec4aCursor usage tracking moves into the Cursor provider package, and existing caches are preserved. No concrete defects were identified, so the change appears ready to merge. Someone with a Mac should confirm that the Keychain prompt appears only once.
Pre-merge checks |
3 | 1❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Description check The description explains the problem and the planned change, but it does not include the required Scope and approval or Verification sections. It also does not state focused test results or manual che… Add the required Problem, Change, Scope and approval, and Verification sections. Include the triaged issue or maintainer approval, focused test commands with observed results, and any checks not performed, including the unverified macOS lay… ✅ Passed checks (3 passed)
Check name Status Explanation Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Title check The title clearly and concisely describes the main change: moving Cursor account usage handling into provider-cursor.
Full details: Description check
Explanation
The description explains the problem and the planned change, but it does not include the required Scope and approval or Verification sections. It also does not state focused test results or manual checks.
Resolution
Add the required Problem, Change, Scope and approval, and Verification sections. Include the triaged issue or maintainer approval, focused test commands with observed results, and any checks not performed, including the unverified macOS layer-memoization behavior.
- Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
- Commit to this branch
- Create a new PR
📝 Generate docstrings
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
- Commit to this branch
- Create a new PR
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Comment `@coderabbitai help` to get the list of available commands.juliusmarminge merged this5a9c664
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed