The best way to control Claude Code, Codex and more from any computer or phone
fix(cursor): use the SDK account for usage data (#32448)
Remove Cursor CLI credential and macOS Keychain fallbacks for account usage and limits, including their settings and web/mobile prompts. Preserve usage through the Cursor SDK sign-in, CURSOR_API_KEY exchange, and explicit auth tokens for limits. Verified focused Cursor tests and full CI on the final head. The scope and intended loss of usage for CLI-only environments were explicitly approved by the maintainer. Model: GPT 6.1 Sol. Harness: Codex through T3 Code.
Yash Singh committed
Nov 7, 2026 at 05:53 UTC
4c3a9d58184f20bd76833bd599c3544d2c09e3eb
40 files changed
+185
-1434
apps/mobile/src/features/usage/UsageLimitsPooled.tsx
+1
-11
@@ -408,13 +408,11 @@ export function UsageLimitsSection({
408
now,
409
failedLabels,
410
selectedEnvironmentIds,
411
- cursorPrompt,
411
wide = false,
412
}: {
413
readonly now: number;
414
readonly failedLabels: readonly string[];
415
readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
417
- readonly cursorPrompt?: ReactNode;
416
readonly wide?: boolean;
417
}) {
418
const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
@@ -426,17 +424,11 @@ export function UsageLimitsSection({
424
const notices = collectLimitNotices(selected);
425
const externalLinks = collectExternalUsageLinks(selected);
426
const colors = useProviderColors();
429
- const cursorPromptAt =
430
- Math.max(
431
- pools.findIndex((pool) => pool.driver === "codex"),
432
- pools.findIndex((pool) => pool.driver === "claudeAgent"),
433
- ) + 1;
427
return (
428
<View className="gap-6">
429
{pools.length === 0 &&
430
notices.length === 0 &&
431
failedLabels.length === 0 &&
439
- !cursorPrompt &&
432
externalLinks.length === 0 ? (
433
<Text className="py-12 text-center text-base text-foreground-muted">
434
{selected.size === 0
@@ -444,11 +436,10 @@ export function UsageLimitsSection({
436
: "No provider on the selected environments reports subscription limits."}
437
</Text>
438
) : null}
447
- {pools.map((pool, index) => {
439
+ {pools.map((pool) => {
440
const windows = displayLimitWindows(pool);
441
return (
442
<Fragment key={pool.driver}>
451
- {index === cursorPromptAt ? cursorPrompt : null}
443
<View className="gap-3">
444
<View className="flex-row items-center gap-2 px-1">
445
<ProviderIcon provider={pool.driver} size={18} />
@@ -478,7 +469,6 @@ export function UsageLimitsSection({
469
</Fragment>
470
);
471
})}
481
- {cursorPromptAt === pools.length ? cursorPrompt : null}
472
{externalLinks.map((link) => (
473
<View key={link.url} className="gap-3 rounded-xl border border-border-subtle p-4">
474
<Text className="text-base font-t3-medium text-foreground">{link.label}</Text>
apps/mobile/src/features/usage/UsageLimitsSection.tsx
+3
-6
@@ -345,18 +345,16 @@ export function useRefreshLimits(
345
.filter(([environmentId]) => failedIds.has(environmentId))
346
.map(([, presentation]) => presentation.entry.target.label);
347
348
- const refresh = (afterPending: boolean) =>
348
+ const refresh = () =>
349
Promise.all(
350
- connectedIds.map((environmentId) =>
351
- refreshEnvironmentLimits(registry, environmentId, { afterPending }),
352
- ),
350
+ connectedIds.map((environmentId) => refreshEnvironmentLimits(registry, environmentId)),
351
);
352
// Android RefreshControl needs a true-to-false cycle to stop, even with nothing to probe.
353
const refreshManually = async () => {
354
if (refreshingRef.current) return;
355
refreshingRef.current = true;
356
setRefreshing(true);
359
- await refresh(false).finally(() => {
357
+ await refresh().finally(() => {
358
refreshingRef.current = false;
359
setRefreshing(false);
360
});
@@ -366,6 +364,5 @@ export function useRefreshLimits(
364
refreshing,
365
failedLabels,
366
refresh: refreshManually,
369
- refreshAfterEnable: () => refresh(true),
367
};
368
}
apps/mobile/src/features/usage/UsageRouteScreen.tsx
+3
-163
@@ -1,10 +1,8 @@
1
-import { Button } from "../../components/ui/Button";
1
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
2
import { ChatGptUsageSummary } from "./ChatGptUsageSummary";
3
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
4
import { EnvironmentId, USAGE_CONTRACT_VERSION, type UsageProviderKind } from "@t3tools/contracts";
5
import { type RouteProp, useIsFocused, useRoute } from "@react-navigation/native";
7
-import { cursorKeychainAccessEnvironments } from "@t3tools/client-runtime/state/usage";
6
import {
7
updatingProvidersLabel,
8
usageEnvironmentProgress,
@@ -38,12 +36,9 @@ import { SegmentedControl } from "../../components/ui/SegmentedControl";
36
import { useReduceMotionEnabled } from "../../lib/appState";
37
import { AppText as Text } from "../../components/ui/AppText";
38
import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width";
41
-import { ProviderIcon } from "../../components/ProviderIcon";
39
import { cn } from "../../lib/cn";
40
import { SettingsScreen } from "../settings/components/SettingsScreen";
41
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
45
-import { serverEnvironment } from "../../state/server";
46
-import { useAtomCommand } from "../../state/use-atom-command";
42
import { SettingsSection } from "../settings/components/SettingsSection";
43
import { UsageDailyChart } from "./UsageDailyChart";
44
import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
@@ -72,7 +67,6 @@ const WIDE_CHART_HEIGHT = 260;
67
const WIDE_WIDTH = 600;
68
const MAX_CONTENT_WIDTH = 1080;
69
const providerLabel = (provider: UsageProviderKind) => PROVIDER_LABEL[provider];
75
-const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
70
71
export function UsageRouteScreen(props: { readonly workspace?: boolean }) {
72
const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>();
@@ -114,11 +108,6 @@ function UsageScreen(props: {
108
);
109
const isFocused = useIsFocused();
110
const limits = useRefreshLimits(selectedEnvironmentIds, isFocused && view === "limits");
117
- const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
118
- const refreshAfterCursorEnable = () => {
119
- void refresh();
120
- void limits.refreshAfterEnable();
121
- };
111
const sourceMessages = usageSourceMessages(
112
selectedEnvironments.flatMap((environment) => environment.summary?.sources ?? []),
113
);
@@ -183,16 +172,7 @@ function UsageScreen(props: {
172
isPast24Hours,
173
timeZone: window.timeZone,
174
};
186
- const providers = (
187
- <ProviderSection
188
- merged={merged}
189
- metric={metric}
190
- cursorAccessEnvironments={cursorAccessEnvironments}
191
- showCursorEnvironment={selectedEnvironments.length > 1}
192
- onCursorEnabled={refreshAfterCursorEnable}
193
- compact={wide}
194
- />
195
- );
175
+ const providers = <ProviderSection merged={merged} metric={metric} compact={wide} />;
176
177
const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
178
const selectEnvironment = (value: string) => {
@@ -291,14 +271,6 @@ function UsageScreen(props: {
271
failedLabels={limits.failedLabels}
272
selectedEnvironmentIds={selectedEnvironmentIds}
273
wide={wide}
294
- cursorPrompt={
295
- cursorAccessEnvironments.length > 0 ? (
296
- <CursorEnableLimits
297
- environments={cursorAccessEnvironments}
298
- onEnabled={refreshAfterCursorEnable}
299
- />
300
- ) : null
301
- }
274
/>
275
) : (
276
<>
@@ -429,105 +401,6 @@ function UsageUpdating({
401
);
402
}
403
432
-function CursorEnableAction({
433
- environmentId,
434
- label,
435
- onEnabled,
436
- buttonText = "Enable",
437
-}: {
438
- readonly environmentId: EnvironmentId;
439
- readonly label: string;
440
- readonly onEnabled: () => void;
441
- readonly buttonText?: string;
442
-}) {
443
- const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
444
- label: "enable Cursor account usage",
445
- });
446
- const [pending, setPending] = useState(false);
447
- const enable = async () => {
448
- setPending(true);
449
- const result = await updateSettings({
450
- environmentId,
451
- input: { patch: { cursorKeychainUsageEnabled: true } },
452
- }).finally(() => setPending(false));
453
- if (result._tag === "Success") onEnabled();
454
- };
455
- return (
456
- <Button
457
- label={buttonText}
458
- tone="primary"
459
- accessibilityLabel={`Enable Cursor usage from ${label}`}
460
- accessibilityHint={CURSOR_KEYCHAIN_COPY}
461
- disabled={pending}
462
- onPress={() => void enable()}
463
- loading={pending}
464
- />
465
- );
466
-}
467
-
468
-function CursorEnableRow({
469
- environmentId,
470
- label,
471
- showEnvironment,
472
- bordered,
473
- onEnabled,
474
-}: {
475
- readonly environmentId: EnvironmentId;
476
- readonly label: string;
477
- readonly showEnvironment: boolean;
478
- readonly bordered: boolean;
479
- readonly onEnabled: () => void;
480
-}) {
481
- const colors = useProviderColors();
482
- return (
483
- <View
484
- className={cn(
485
- "flex-row items-center justify-between gap-3 p-4",
486
- bordered && "border-t border-border-subtle",
487
- )}
488
- >
489
- <View className="min-w-0 flex-1 flex-row items-center gap-2">
490
- <View className="size-2.5 rounded-full" style={{ backgroundColor: colors.cursor }} />
491
- <Text className="shrink text-lg text-foreground">
492
- Cursor{showEnvironment ? ` · ${label}` : ""}
493
- </Text>
494
- </View>
495
- <CursorEnableAction environmentId={environmentId} label={label} onEnabled={onEnabled} />
496
- </View>
497
- );
498
-}
499
-
500
-function CursorEnableLimits({
501
- environments,
502
- onEnabled,
503
-}: {
504
- readonly environments: readonly EnvironmentUsageStatus[];
505
- readonly onEnabled: () => void;
506
-}) {
507
- return (
508
- <View className="gap-3">
509
- <View className="flex-row items-center gap-2 px-1">
510
- <ProviderIcon provider="cursor" size={18} />
511
- <Text className="text-base font-t3-medium text-foreground">Cursor</Text>
512
- </View>
513
- <View className="items-start gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
514
- <Text className="text-xs text-foreground-muted">{CURSOR_KEYCHAIN_COPY}</Text>
515
- <View className="flex-row flex-wrap gap-2">
516
- {environments.map((environment) => (
517
- <CursorEnableAction
518
- key={environment.environmentId}
519
- environmentId={environment.environmentId}
520
- label={environment.label}
521
- buttonText={environments.length > 1 ? `Enable on ${environment.label}` : "Enable"}
522
- onEnabled={onEnabled}
523
- />
524
- ))}
525
- </View>
526
- </View>
527
- </View>
528
- );
529
-}
530
-
404
function ChartCard(props: {
405
readonly merged: MergedUsage;
406
readonly days: readonly string[];
@@ -632,54 +505,21 @@ function UsageSummary(props: { readonly merged: MergedUsage; readonly metric: Us
505
function ProviderSection(props: {
506
readonly merged: MergedUsage;
507
readonly metric: UsageChartMetric;
635
- readonly cursorAccessEnvironments: readonly EnvironmentUsageStatus[];
636
- readonly showCursorEnvironment: boolean;
637
- readonly onCursorEnabled: () => void;
508
/** Drops the share bar so the list fits beside the chart. */
509
readonly compact: boolean;
510
}) {
511
const { merged, metric } = props;
512
const colors = useProviderColors();
643
- if (merged.providers.length === 0 && props.cursorAccessEnvironments.length === 0) return null;
513
+ if (merged.providers.length === 0) return null;
514
515
// Hermes lacks toSorted.
516
const ordered = [...merged.providers].sort((a, b) =>
517
metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
518
);
649
- const rows: Array<
650
- | { readonly kind: "usage"; readonly provider: (typeof ordered)[number] }
651
- | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
652
- > = ordered.map((provider) => ({ kind: "usage", provider }));
653
- const cursorInsertAt =
654
- Math.max(
655
- ordered.findIndex((provider) => provider.provider === "codex"),
656
- ordered.findIndex((provider) => provider.provider === "claude"),
657
- ) + 1;
658
- rows.splice(
659
- cursorInsertAt,
660
- 0,
661
- ...props.cursorAccessEnvironments.map((environment) => ({
662
- kind: "enable" as const,
663
- environment,
664
- })),
665
- );
519
520
return (
521
<SettingsSection title="Providers">
669
- {rows.map((row, index) => {
670
- if (row.kind === "enable") {
671
- return (
672
- <CursorEnableRow
673
- key={`enable:${row.environment.environmentId}`}
674
- environmentId={row.environment.environmentId}
675
- label={row.environment.label}
676
- showEnvironment={props.showCursorEnvironment}
677
- bordered={index > 0}
678
- onEnabled={props.onCursorEnabled}
679
- />
680
- );
681
- }
682
- const provider = row.provider;
522
+ {ordered.map((provider, index) => {
523
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
524
return (
525
<View
apps/mobile/src/features/usage/usageLimitsRefresh.ts
+1
-2
@@ -16,7 +16,7 @@ const limitsRefreshFailedAtom = Atom.family((environmentId: EnvironmentId) =>
16
export async function refreshEnvironmentLimits(
17
registry: AtomRegistry.AtomRegistry,
18
environmentId: EnvironmentId,
19
- options: { readonly automatic?: boolean; readonly afterPending?: boolean } = {},
19
+ options: { readonly automatic?: boolean } = {},
20
): Promise<void> {
21
// One refresh runs per environment at a time, so results land in the order
22
// they were started and the newest outcome always wins.
@@ -30,7 +30,6 @@ export async function refreshEnvironmentLimits(
30
{ reportFailure: false },
31
),
32
options.automatic,
33
- options.afterPending,
33
);
34
if (result === undefined) return;
35
registry.set(limitsRefreshFailedAtom(environmentId), result._tag === "Failure");
apps/mobile/src/state/usage.ts
+1
-11
@@ -6,11 +6,7 @@ import {
6
type UsageSummary,
7
type UsageSummaryInput,
8
} from "@t3tools/contracts";
9
-import {
10
- needsCursorKeychainAccess,
11
- refreshUsage,
12
- usageSummaryInput,
13
-} from "@t3tools/client-runtime/state/usage";
9
+import { refreshUsage, usageSummaryInput } from "@t3tools/client-runtime/state/usage";
10
import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
11
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
12
import { AsyncResult, Atom } from "effect/reactivity";
@@ -29,7 +25,6 @@ export interface EnvironmentUsageStatus {
25
readonly canReadDiagnostics: boolean;
26
readonly error: string | null;
27
readonly summary: UsageSummary | null;
32
- readonly needsCursorKeychainAccess: boolean;
28
}
29
30
const usageByWindowAtom = Atom.family((windowKey: string) =>
@@ -52,7 +47,6 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
47
isConnected: presentation.connection.phase === "connected",
48
...access,
49
summary: null,
55
- needsCursorKeychainAccess: false,
50
});
51
continue;
52
}
@@ -74,10 +68,6 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
68
canReadDiagnostics: true,
69
error: result._tag === "Failure" ? "This environment could not report usage." : null,
70
summary,
77
- needsCursorKeychainAccess: needsCursorKeychainAccess(
78
- summary,
79
- get(serverEnvironment.providersValueAtom(environmentId)),
80
- ),
71
});
72
}
73
return statuses;
apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts
-3
@@ -4,7 +4,6 @@ import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.t
4
import * as CodexAdapterV2 from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
5
import * as CursorAgentSdk from "@t3tools/provider-cursor/server/CursorAgentSdk";
6
import * as CursorSdk from "@t3tools/provider-cursor/server/CursorSdk";
7
-import * as CursorKeychain from "@t3tools/provider-cursor/server/CursorKeychain";
7
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
8
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
9
@@ -13,7 +12,6 @@ export type ProviderOrchestrationAdapterInfrastructure =
12
| CodexAdapterV2.CodexAppServerClientFactory
13
| CursorAgentSdk.CursorAgentSdkRunner
14
| CursorSdk.CursorSdk
16
- | CursorKeychain.CursorKeychain
15
| IdAllocator.IdAllocatorV2;
16
17
/** Reuse the continuation worker's exact layer reference so memoization shares one queue. */
@@ -21,7 +19,6 @@ export const layer = Layer.mergeAll(
19
ClaudeAdapterV2.layerQueryRunner,
20
CodexAdapterV2.layerAppServerClientFactory,
21
CursorAgentSdk.layer.pipe(Layer.provideMerge(CursorSdk.layer)),
24
- CursorKeychain.layer,
22
IdAllocator.layer,
23
ProviderContinuationRequests.layer,
24
);
apps/server/src/server.ts
+1
-4
@@ -195,7 +195,6 @@ import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
195
import * as AntigravityUsage from "./provider/Drivers/AntigravityUsage.ts";
196
import { MuseUsageHome } from "@t3tools/provider-muse/server";
197
import * as CursorAccountReader from "@t3tools/provider-cursor/server/CursorAccountReader";
198
-import * as CursorKeychain from "@t3tools/provider-cursor/server/CursorKeychain";
198
import * as CursorUsageAccounts from "@t3tools/provider-cursor/server/CursorUsageAccounts";
199
import * as UsageService from "./usage/UsageService.ts";
200
import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts";
@@ -297,9 +296,7 @@ const layerUsage = UsageService.layer.pipe(
296
AntigravityUsage.layer,
297
MuseUsageHome.layer,
298
CodexUsageHistory.layer,
300
- CursorUsageAccounts.layer.pipe(
301
- Layer.provide(CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer))),
302
- ),
299
+ CursorUsageAccounts.layer.pipe(Layer.provide(CursorAccountReader.layer)),
300
).pipe(Layer.provide(ProviderHostLive.layer.pipe(Layer.provide(ServerSecretStore.layer)))),
301
),
302
Layer.provide(layerServerSettings),
apps/server/src/usage/UsageService.test.ts
+17
-123
@@ -43,7 +43,6 @@ import * as ServerSettings from "../serverSettings.ts";
43
import * as Sqlite from "../persistence/Sqlite.ts";
44
import * as CodexUsageHistory from "./CodexUsageHistory.ts";
45
import * as CursorAccountReader from "@t3tools/provider-cursor/server/CursorAccountReader";
46
-import * as CursorKeychain from "@t3tools/provider-cursor/server/CursorKeychain";
46
import * as CursorUsageAccounts from "@t3tools/provider-cursor/server/CursorUsageAccounts";
47
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
48
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
@@ -159,9 +158,7 @@ const layerService = (input: {
158
readonly hostname?: string;
159
readonly secretStore?: Partial<ServerSecretStore.ServerSecretStore["Service"]>;
160
}) =>
162
- layerCursorUsageAccounts(
163
- CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer)),
164
- ).pipe(
161
+ layerCursorUsageAccounts(CursorAccountReader.layer).pipe(
162
Layer.provideMerge(AntigravityUsage.layer),
163
Layer.provideMerge(MuseUsageHome.layer),
164
Layer.provideMerge(ProviderHostLive.layer),
@@ -291,13 +288,6 @@ function makeFakeCursor() {
288
return { state, read };
289
}
290
294
-const writeCursorLogin = (home: string) =>
295
- Effect.promise(async () => {
296
- const authPath = NodePath.join(home, "config", "cursor", "auth.json");
297
- await NodeFSP.mkdir(NodePath.dirname(authPath), { recursive: true });
298
- await NodeFSP.writeFile(authPath, "{}");
299
- });
300
-
291
function cursorSource(summary: { readonly sources: readonly UsageSource[] }) {
292
return summary.sources.find((source) => source.fingerprint.provider === "cursor");
293
}
@@ -1450,29 +1440,9 @@ describe("UsageService", () => {
1440
}).pipe(Effect.scoped),
1441
);
1442
1453
- it.live("keeps Cursor credential errors visible when a saved login cannot be read", () =>
1454
- Effect.gen(function* () {
1455
- const { settings, home } = yield* setup;
1456
- const authPath = NodePath.join(home, "config", "cursor", "auth.json");
1457
- yield* Effect.promise(async () => {
1458
- await NodeFSP.mkdir(NodePath.dirname(authPath), { recursive: true });
1459
- await NodeFSP.writeFile(authPath, "invalid json");
1460
- });
1461
- const service = yield* UsageService.make.pipe(
1462
- Effect.provide(
1463
- layerService({ prefix: "usage-service-cursor-invalid-login", home, settings }),
1464
- ),
1465
- );
1466
- const summary = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1467
- const cursor = summary.sources.find((source) => source.fingerprint.provider === "cursor");
1468
- assert.strictEqual(cursor?.message, "Cursor credentials could not be read.");
1469
- }).pipe(Effect.scoped),
1470
- );
1471
-
1443
it.live("restores the Cursor account cache after a restart", () =>
1444
Effect.gen(function* () {
1445
const { settings, home } = yield* setup;
1475
- yield* writeCursorLogin(home);
1446
yield* TestClock.setTime(CURSOR_NOW);
1447
const before = makeFakeCursor();
1448
before.state.events = [
@@ -1500,104 +1470,16 @@ describe("UsageService", () => {
1470
{ sinceMs: CURSOR_NOW - HOUR_MS, untilMs: CURSOR_NOW + 2 * 60 * 1000 },
1471
]);
1472
}).pipe(
1503
- Effect.provide(layerService({ prefix: "usage-service-cursor-restart", home, settings })),
1504
- );
1505
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1506
- );
1507
-
1508
- it.live("does not read the macOS Cursor Keychain before account usage is enabled", () =>
1509
- Effect.gen(function* () {
1510
- const { settings, home } = yield* setup;
1511
- const service = yield* UsageService.make.pipe(
1473
Effect.provide(
1474
layerService({
1514
- prefix: "usage-service-cursor-keychain-disabled",
1475
+ prefix: "usage-service-cursor-restart",
1476
home,
1477
settings,
1517
- platform: "darwin",
1518
- environment: {},
1519
- }),
1520
- ),
1521
- );
1522
- const summary = yield* service.readSummary(WINDOW);
1523
- const cursor = summary.sources.find((source) => source.fingerprint.provider === "cursor");
1524
- assert.strictEqual(cursor?.status, "missing");
1525
- assert.strictEqual(cursor?.action, "enableCursorKeychain");
1526
- }).pipe(Effect.scoped),
1527
- );
1528
-
1529
- it.effect("ignores a stale macOS Keychain login when Cursor is not installed", () =>
1530
- Effect.gen(function* () {
1531
- const { settings, home } = yield* setup;
1532
- const cursor = makeFakeCursor();
1533
- cursor.state.error = "Sign in to Cursor again to read account usage.";
1534
- const readCursorSource = Effect.gen(function* () {
1535
- const service = yield* makeWithCursor(cursor.read);
1536
- const summary = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1537
- return cursorSource(summary);
1538
- }).pipe(
1539
- Effect.provide(
1540
- layerService({
1541
- prefix: "usage-service-cursor-keychain-uninstalled",
1542
- home,
1543
- settings: { ...settings, cursorKeychainUsageEnabled: true },
1544
- platform: "darwin",
1545
- environment: {},
1478
+ environment: { CURSOR_API_KEY: "test-key" },
1479
}),
1480
),
1481
);
1549
-
1550
- assert.isUndefined(yield* readCursorSource);
1551
- assert.lengthOf(cursor.state.calls, 0);
1552
-
1553
- yield* Effect.promise(() => NodeFSP.mkdir(NodePath.join(home, ".cursor")));
1554
- const installed = yield* readCursorSource;
1555
- assert.strictEqual(installed?.message, "Sign in to Cursor again to read account usage.");
1556
- assert.lengthOf(cursor.state.calls, 1);
1557
- }).pipe(Effect.scoped),
1558
- );
1559
-
1560
- it.live("ignores stale Cursor file logins when the active credential store differs", () =>
1561
- Effect.gen(function* () {
1562
- const { settings, home } = yield* setup;
1563
- for (const [index, testCase] of [
1564
- {
1565
- platform: "darwin" as const,
1566
- environment: { AGENT_CLI_CREDENTIAL_STORE: "memory" },
1567
- authPath: [".cursor", "auth.json"],
1568
- },
1569
- {
1570
- platform: "linux" as const,
1571
- environment: { AGENT_CLI_CREDENTIAL_STORE: "memory" },
1572
- authPath: ["config", "cursor", "auth.json"],
1573
- },
1574
- ].entries()) {
1575
- const authPath = NodePath.join(home, ...testCase.authPath);
1576
- yield* Effect.promise(async () => {
1577
- await NodeFSP.mkdir(NodePath.dirname(authPath), { recursive: true });
1578
- await NodeFSP.writeFile(
1579
- authPath,
1580
- encodeUnknownJsonString({ accessToken: "stale-token" }),
1581
- );
1582
- });
1583
- const service = yield* UsageService.make.pipe(
1584
- Effect.provide(
1585
- layerService({
1586
- prefix: `usage-service-cursor-store-${index}`,
1587
- home,
1588
- settings,
1589
- platform: testCase.platform,
1590
- environment: testCase.environment,
1591
- }),
1592
- ),
1593
- );
1594
- const summary = yield* service.readSummary(WINDOW);
1595
- const cursor = summary.sources.find((source) => source.fingerprint.provider === "cursor");
1596
- assert.strictEqual(cursor?.status, "missing");
1597
- assert.include(cursor?.message ?? "", "Cursor CLI login");
1598
- assert.isFalse(summary.buckets.some((bucket) => bucket.provider === "cursor"));
1599
- }
1600
- }).pipe(Effect.scoped),
1482
+ }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1483
);
1484
1485
it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () =>
@@ -1611,9 +1493,17 @@ describe("UsageService", () => {
1493
createdAtMs: 0,
1494
}),
1495
);
1496
+ yield* Effect.promise(async () => {
1497
+ await NodeFSP.mkdir(NodePath.join(home, ".cursor"), { recursive: true });
1498
+ await NodeFSP.writeFile(
1499
+ NodePath.join(home, ".cursor", "auth.json"),
1500
+ '{"accessToken":"stale-cli-token"}',
1501
+ );
1502
+ });
1503
for (const [index, testCase] of [
1504
{ environment: { CURSOR_API_KEY: "environment-key" }, stored: Option.none() },
1505
{ environment: {}, stored: Option.some(signIn) },
1506
+ { environment: {}, stored: Option.none() },
1507
].entries()) {
1508
const cursor = makeFakeCursor();
1509
const summary = yield* Effect.gen(function* () {
@@ -1631,6 +1521,11 @@ describe("UsageService", () => {
1521
}),
1522
),
1523
);
1524
+ if (index === 2) {
1525
+ assert.deepStrictEqual(cursor.state.credentials, []);
1526
+ assert.isUndefined(cursorSource(summary));
1527
+ continue;
1528
+ }
1529
assert.deepStrictEqual(cursor.state.credentials, [
1530
{ kind: "apiKey", apiKey: index === 0 ? "environment-key" : "signed-in-key" },
1531
]);
@@ -1719,7 +1614,6 @@ describe("UsageService", () => {
1614
environment: { CURSOR_API_KEY: "new-key" },
1615
},
1616
],
1722
- keychainUsageEnabled: false,
1617
windowStartMs: 0,
1618
retentionCutoffMs: 0,
1619
awaitRefresh,
apps/server/src/usage/UsageService.ts
+1
-3
@@ -546,7 +546,6 @@ export const make = Effect.gen(function* () {
546
readonly hostId?: string;
547
readonly status?: UsageSource["status"];
548
readonly message?: string;
549
- readonly action?: UsageSource["action"];
549
readonly files:
550
| readonly {
551
readonly path: string;
@@ -802,7 +801,7 @@ export const make = Effect.gen(function* () {
801
802
for (const [
803
index,
805
- { provider, dir, volumeId, files, status, message, action, refreshing, hostId: sourceHostId },
804
+ { provider, dir, volumeId, files, status, message, refreshing, hostId: sourceHostId },
805
] of scannedDirs.entries()) {
806
let scannedFiles = 0;
807
let skippedFiles = 0;
@@ -866,7 +865,6 @@ export const make = Effect.gen(function* () {
865
.filter(Boolean)
866
.join(" ")
867
: sourceMessage,
869
- ...(action ? { action } : {}),
868
...(refreshing ? { refreshing } : {}),
869
});
870
}
apps/web/src/components/settings/ProviderSettingsPanel.tsx
-17
@@ -351,25 +351,9 @@ function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
351
hasServerConfig: environment.serverConfig !== null,
352
}),
353
)?.environmentId;
354
- const searchableCursorEnvironmentId = options.find(
355
- (environment) =>
356
- environment.serverConfig?.environment.platform.os === "darwin" &&
357
- isProviderSettingsEnvironmentAvailable({
358
- connectionPhase: environment.connection.phase,
359
- hasServerConfig: true,
360
- }),
361
- )?.environmentId;
354
let searchRedirectEnvironmentId: EnvironmentId | undefined;
355
{
356
if (
365
- !target.scoped &&
366
- searchTargetId === searchableSetting("cursor-keychain-usage").id &&
367
- (!selectedEnvironmentCanRenderSettings ||
368
- selectedEnvironment?.serverConfig?.environment.platform.os !== "darwin") &&
369
- searchableCursorEnvironmentId !== undefined
370
- ) {
371
- searchRedirectEnvironmentId = searchableCursorEnvironmentId;
372
- } else if (
357
!target.scoped &&
358
(searchTargetId === searchableSetting("provider-health-check-interval").id ||
359
searchTargetId === searchableSetting("usage-providers").id) &&
@@ -1105,7 +1089,6 @@ export function EnvironmentProviderSettings({
1089
environmentId={environmentId}
1090
environmentLabel={environmentLabel}
1091
sources={settings.usageLimitSources}
1108
- cursorKeychainUsageEnabled={settings.cursorKeychainUsageEnabled}
1092
readOnly={readOnly}
1093
/>
1094
apps/web/src/components/settings/SettingsSidebarNav.tsx
+1
-4
@@ -57,7 +57,6 @@ import {
57
type SettingsSearchItem,
58
} from "./settingsSearch";
59
import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems";
60
-import { validateSettingsScopeSearch } from "./settingsScope";
60
import { useSettingsSectionNavigation } from "./useSettingsSectionNavigation";
61
import { workspaceAreaProps } from "../../lib/workspaceFocus";
62
@@ -132,8 +131,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
131
const navArea = workspaceAreaProps("settings-nav", 0, "Settings sections");
132
const navigate = useNavigate();
133
const currentHash = useLocation({ select: (location) => location.hash });
135
- const currentSearch = useLocation({ select: (location) => location.search });
136
- const scopeSearch = validateSettingsScopeSearch(currentSearch);
134
const activePath = SETTINGS_DETAIL_PAGE_PARENTS[pathname] ?? pathname;
135
const navPaths = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths);
136
const sectionNavigation = useSettingsSectionNavigation(
@@ -146,7 +143,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
143
// Below md the nav is an icon rail; searching expands it over the page.
144
const [compactSearchOpen, setCompactSearchOpen] = useState(false);
145
const [activeResultIndex, setActiveResultIndex] = useState(0);
149
- const searchableItems = useAvailableSettingsSearchItems(scopeSearch);
146
+ const searchableItems = useAvailableSettingsSearchItems();
147
const results = searchSettings(query, searchableItems);
148
const isSearching = query.trim().length > 0;
149
const hasResults = results.length > 0;
apps/web/src/components/settings/UsageProviderSettings.tsx
-42
@@ -1,11 +1,8 @@
1
import type { EnvironmentId, UnifiedSettings } from "@t3tools/contracts";
2
-import { useAtomValue } from "@effect/atom-react";
2
import { PlusIcon } from "lucide-react";
3
import { useState } from "react";
4
5
import { useUpdateEnvironmentSettings } from "../../hooks/useSettings";
7
-import { serverEnvironment } from "../../state/server";
8
-import { useAtomCommand } from "../../state/use-atom-command";
6
import {
7
AlertDialog,
8
AlertDialogClose,
@@ -16,7 +13,6 @@ import {
13
AlertDialogTitle,
14
} from "../ui/alert-dialog";
15
import { Button } from "../ui/button";
19
-import { Switch } from "../ui/switch";
16
import { AddUsageLimitSourceDialog } from "./AddUsageLimitSourceDialog";
17
import { searchableSetting } from "./settingsSearch";
18
import { SettingsRow, SettingsSection } from "./settingsLayout";
@@ -25,40 +21,17 @@ export function UsageProviderSettings({
21
environmentId,
22
environmentLabel,
23
sources,
28
- cursorKeychainUsageEnabled,
24
readOnly,
25
}: {
26
readonly environmentId: EnvironmentId;
27
readonly environmentLabel: string;
28
readonly sources: UnifiedSettings["usageLimitSources"];
34
- readonly cursorKeychainUsageEnabled: boolean;
29
readonly readOnly: boolean;
30
}) {
31
const updateSettings = useUpdateEnvironmentSettings(environmentId);
38
- const updateCursorSettings = useAtomCommand(serverEnvironment.updateSettings, {
39
- label: "update Cursor account usage",
40
- });
41
- const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
42
- reportFailure: false,
43
- });
44
- const platform = useAtomValue(serverEnvironment.configValueAtom(environmentId))?.environment
45
- .platform;
32
const [adding, setAdding] = useState(false);
47
- const [updatingCursor, setUpdatingCursor] = useState(false);
33
const entries = Object.entries(sources);
34
50
- const setCursorUsageEnabled = async (enabled: boolean) => {
51
- setUpdatingCursor(true);
52
- const result = await updateCursorSettings({
53
- environmentId,
54
- input: { patch: { cursorKeychainUsageEnabled: enabled } },
55
- });
56
- if (result._tag === "Success") {
57
- await refreshProviders({ environmentId, input: {} });
58
- }
59
- setUpdatingCursor(false);
60
- };
61
-
35
return (
36
<>
37
<SettingsSection
@@ -72,21 +45,6 @@ export function UsageProviderSettings({
45
) : null
46
}
47
>
75
- {platform?.os === "darwin" ? (
76
- <SettingsRow
77
- id="cursor-keychain-usage"
78
- title="Cursor account usage"
79
- description="Read your existing Cursor CLI login from macOS Keychain to show account history and monthly limits. macOS may ask you to allow access."
80
- control={
81
- <Switch
82
- aria-label="Cursor account usage"
83
- checked={cursorKeychainUsageEnabled}
84
- disabled={readOnly || updatingCursor}
85
- onCheckedChange={(enabled) => void setCursorUsageEnabled(enabled)}
86
- />
87
- }
88
- />
89
- ) : null}
48
{entries.length === 0 ? (
49
<SettingsRow title="No hubs configured." />
50
) : (
apps/web/src/components/settings/settingsSearch.test.ts
-4
@@ -116,7 +116,6 @@ describe("searchSettings", () => {
116
hasCloudPublicConfig: false,
117
hasEnvironment: false,
118
hasProviderSettingsEnvironment: false,
119
- hasMacProviderSettingsEnvironment: false,
119
canManageLocalBackend: false,
120
isWslSettingsRowVisible: false,
121
hasThreadAutoSettlement: false,
@@ -128,7 +127,6 @@ describe("searchSettings", () => {
127
"network-access",
128
"publish-agent-activity",
129
"provider-health-check-interval",
131
- "cursor-keychain-usage",
130
"source-control-writer-model",
131
"review-guide-model",
132
"review-guide-instructions",
@@ -150,7 +148,6 @@ describe("searchSettings", () => {
148
hasCloudPublicConfig: false,
149
hasEnvironment: true,
150
hasProviderSettingsEnvironment: true,
153
- hasMacProviderSettingsEnvironment: false,
151
canManageLocalBackend: false,
152
localEnvironmentDisabled: true,
153
isWslSettingsRowVisible: false,
@@ -265,7 +262,6 @@ describe("auto-settlement search availability", () => {
262
hasCloudPublicConfig: false,
263
hasEnvironment: true,
264
hasProviderSettingsEnvironment: true,
268
- hasMacProviderSettingsEnvironment: false,
265
canManageLocalBackend: false,
266
isWslSettingsRowVisible: false,
267
hasThreadAutoSettlement: availability.eligibleEnvironmentIds.length > 0,
apps/web/src/components/settings/settingsSearch.ts
-11
@@ -63,7 +63,6 @@ export interface SettingsSearchItem {
63
readonly cloudOnly?: boolean;
64
readonly environmentOnly?: boolean;
65
readonly providerSettingsOnly?: boolean;
66
- readonly macProviderSettingsOnly?: boolean;
66
readonly localBackendManagementOnly?: boolean;
67
readonly localEnvironmentOnly?: boolean;
68
readonly wslAvailableOnly?: boolean;
@@ -78,7 +77,6 @@ export interface SettingsSearchAvailability {
77
readonly hasCloudPublicConfig: boolean;
78
readonly hasEnvironment: boolean;
79
readonly hasProviderSettingsEnvironment: boolean;
81
- readonly hasMacProviderSettingsEnvironment: boolean;
80
readonly canManageLocalBackend: boolean;
81
readonly isWslSettingsRowVisible: boolean;
82
readonly hasThreadAutoSettlement: boolean;
@@ -936,14 +934,6 @@ export const SETTINGS_SEARCH_ITEMS = [
934
],
935
providerSettingsOnly: true,
936
},
939
- {
940
- id: "cursor-keychain-usage",
941
- title: "Cursor account usage",
942
- to: "/settings/providers",
943
- searchTerms: ["cursor macOS keychain usage tokens cost limits permission"],
944
- providerSettingsOnly: true,
945
- macProviderSettingsOnly: true,
946
- },
937
{
938
id: "provider-health-check-interval",
939
title: "Health check interval",
@@ -1449,7 +1439,6 @@ export function filterAvailableSettingsSearchItems(
1439
(!item.cloudOnly || availability.hasCloudPublicConfig) &&
1440
(!item.environmentOnly || availability.hasEnvironment) &&
1441
(!item.providerSettingsOnly || availability.hasProviderSettingsEnvironment) &&
1452
- (!item.macProviderSettingsOnly || availability.hasMacProviderSettingsEnvironment) &&
1442
(!item.localBackendManagementOnly || availability.canManageLocalBackend) &&
1443
(!item.localEnvironmentOnly || !availability.localEnvironmentDisabled) &&
1444
(!item.wslAvailableOnly || availability.isWslSettingsRowVisible) &&
apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
+1
-13
@@ -11,13 +11,12 @@ import { useEnvironmentQuery } from "~/state/query";
11
import { useEnvironmentScope } from "~/state/session";
12
import { isWslSettingsRowVisible } from "./ConnectionsSettings.logic";
13
import { isProviderSettingsEnvironmentAvailable } from "./ProviderSettingsPanel.logic";
14
-import type { SettingsScopeSearch } from "./settingsScope";
14
import {
15
filterAvailableSettingsSearchItems,
16
getThreadAutoSettlementSearchAvailability,
17
} from "./settingsSearch";
18
20
-export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch = {}) {
19
+export function useAvailableSettingsSearchItems() {
20
const { environments } = useEnvironments();
21
// Explicit booleans keep flags out of the filter cache so environment updates do not rebuild the list.
22
const hasEnvironment =
@@ -29,16 +28,6 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch
28
hasServerConfig: environment.serverConfig !== null,
29
}),
30
) === true;
32
- const hasMacProviderSettingsEnvironment =
33
- environments.some(
34
- (environment) =>
35
- (scopeSearch.machine === undefined || environment.environmentId === scopeSearch.machine) &&
36
- environment.serverConfig?.environment.platform.os === "darwin" &&
37
- isProviderSettingsEnvironmentAvailable({
38
- connectionPhase: environment.connection.phase,
39
- hasServerConfig: true,
40
- }),
41
- ) === true;
31
const hasThreadAutoSettlement =
32
getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0;
33
const primaryEnvironmentId = usePrimaryEnvironmentId();
@@ -63,7 +52,6 @@ export function useAvailableSettingsSearchItems(scopeSearch: SettingsScopeSearch
52
hasCloudPublicConfig: cloudPublicConfig,
53
hasEnvironment,
54
hasProviderSettingsEnvironment,
66
- hasMacProviderSettingsEnvironment,
55
canManageLocalBackend,
56
isWslSettingsRowVisible: wslSettingsRowVisible,
57
hasThreadAutoSettlement,
apps/web/src/components/usage/UsageLimits.tsx
+2
-4
@@ -19,7 +19,7 @@ import {
19
remainingPercent,
20
} from "@t3tools/shared/usageLimits";
21
import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
22
-import { Fragment, type ReactNode, useLayoutEffect, useState } from "react";
22
+import { Fragment, useLayoutEffect, useState } from "react";
23
24
import { usePrimarySettings } from "../../hooks/useSettings";
25
import { observeResize } from "../../lib/observeResize";
@@ -365,12 +365,10 @@ export function UsageLimitsSection({
365
selectedEnvironmentIds,
366
hiddenProviders,
367
now,
368
- cursorPrompt,
368
}: {
369
readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
370
readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
371
readonly now: number;
373
- readonly cursorPrompt?: ReactNode;
372
}) {
373
const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
374
const hiddenDrivers = new Set<ServerProvider["driver"]>(
@@ -402,5 +400,5 @@ export function UsageLimitsSection({
400
];
401
}),
402
);
405
- return <UsageLimitsPooled presentations={selected} now={now} cursorPrompt={cursorPrompt} />;
403
+ return <UsageLimitsPooled presentations={selected} now={now} />;
404
}
apps/web/src/components/usage/UsageLimitsPooled.tsx
+2
-11
@@ -605,33 +605,25 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu
605
export function UsageLimitsPooled({
606
presentations,
607
now,
608
- cursorPrompt,
608
}: {
609
readonly presentations: Parameters<typeof collectLimitAccounts>[0];
610
readonly now: number;
612
- readonly cursorPrompt?: ReactNode;
611
}) {
612
const [segmentPopover] = useState(() => PopoverCreateHandle<SegmentPayload>());
613
const segmentPopoverActions = useRef<PopoverPrimitive.Root.Actions | null>(null);
614
const pools = collectLimitPools(collectLimitAccounts(presentations), now);
615
const notices = collectLimitNotices(presentations);
616
const externalLinks = collectExternalUsageLinks(presentations);
619
- const cursorPromptAt =
620
- Math.max(
621
- pools.findIndex((pool) => pool.driver === "codex"),
622
- pools.findIndex((pool) => pool.driver === "claudeAgent"),
623
- ) + 1;
617
return (
618
<div className="flex flex-col gap-8">
626
- {pools.length === 0 && notices.length === 0 && !cursorPrompt && externalLinks.length === 0 ? (
619
+ {pools.length === 0 && notices.length === 0 && externalLinks.length === 0 ? (
620
<p className="text-sm text-muted-foreground">
621
No provider on the selected environments reports subscription limits.
622
</p>
623
) : null}
624
<SegmentPopoverContext value={segmentPopover}>
632
- {pools.map((pool, index) => (
625
+ {pools.map((pool) => (
626
<Fragment key={pool.driver}>
634
- {index === cursorPromptAt ? cursorPrompt : null}
627
<PoolSection pool={pool} now={now} />
628
</Fragment>
629
))}
@@ -649,7 +641,6 @@ export function UsageLimitsPooled({
641
) : null
642
}
643
</Popover>
652
- {cursorPromptAt === pools.length ? cursorPrompt : null}
644
{externalLinks.map((link) => (
645
<section
646
key={link.url}
apps/web/src/components/usage/UsagePage.tsx
+3
-186
@@ -4,7 +4,6 @@ import { RefreshIcon } from "~/components/ui/refresh-icon";
4
import { useAtomValue } from "@effect/atom-react";
5
import { Atom } from "effect/reactivity";
6
import {
7
- ProviderDriverKind,
7
USAGE_CONTRACT_VERSION,
8
type EnvironmentId,
9
type UsageProviderKind,
@@ -15,10 +14,7 @@ import { useEffect, useEffectEvent, useRef, useState } from "react";
14
import { settlePromise } from "@t3tools/client-runtime/state/runtime";
15
import * as AsyncResult from "effect/reactivity/AsyncResult";
16
import * as Cause from "effect/Cause";
18
-import {
19
- cursorKeychainAccessEnvironments,
20
- refreshUsageLimits,
21
-} from "@t3tools/client-runtime/state/usage";
17
+import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
18
import {
19
updatingProvidersLabel,
20
usageEnvironmentProgress,
@@ -73,7 +69,6 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../
69
import { AppRouteModal, AppRouteModalClose } from "../AppRouteModal";
70
import { Skeleton } from "../ui/skeleton";
71
import { Toggle, ToggleGroup } from "../ui/toggle-group";
76
-import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
72
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
73
import {
74
WorkspaceBreadcrumb,
@@ -227,9 +222,6 @@ export function UsagePage() {
222
const presentationsWithProviders = useAtomValue(
223
environmentPresentations.presentationsWithProvidersAtom,
224
);
230
- const cursorAccessEnvironments = hiddenProviders.has("cursor")
231
- ? []
232
- : cursorKeychainAccessEnvironments(selectedEnvironments);
225
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
226
reportFailure: false,
227
});
@@ -255,7 +247,7 @@ export function UsagePage() {
247
if (nextMetric === "limits") setLimitsNow(Date.now());
248
updatePreferences({ metric: nextMetric });
249
};
258
- const refreshLimits = (automatic = false, afterPending = false) =>
250
+ const refreshLimits = (automatic = false) =>
251
// Settled so the timestamp still advances when a refresh throws.
252
settlePromise(() =>
253
Promise.all(
@@ -266,7 +258,6 @@ export function UsagePage() {
258
environmentId,
259
() => refreshProviders({ environmentId, input: {} }),
260
automatic,
269
- afterPending,
261
);
262
}
263
}),
@@ -530,17 +521,6 @@ export function UsagePage() {
521
selectedEnvironmentIds={selectedEnvironmentIds}
522
hiddenProviders={hiddenProviders}
523
now={limitsNow}
533
- cursorPrompt={
534
- cursorAccessEnvironments.length > 0 ? (
535
- <CursorEnableLimits
536
- environments={cursorAccessEnvironments}
537
- onEnabled={() => {
538
- void refresh();
539
- void refreshLimits(false, true);
540
- }}
541
- />
542
- ) : null
543
- }
524
/>
525
) : shown === null ? (
526
<UsageSkeleton />
@@ -565,12 +545,7 @@ export function UsagePage() {
545
selectedEnvironments={selectedEnvironments}
546
hiddenProviders={hiddenProviders}
547
refreshingUsage={refreshingUsage}
568
- cursorAccessEnvironments={cursorAccessEnvironments}
548
showChatGptSharing={showChatGptSharing}
570
- onCursorEnabled={() => {
571
- void refresh();
572
- void refreshLimits(false, true);
573
- }}
549
onSelectModel={selectUsageModel}
550
/>
551
)}
@@ -618,9 +593,7 @@ function UsageOverview({
593
selectedEnvironments,
594
hiddenProviders,
595
refreshingUsage,
621
- cursorAccessEnvironments,
596
showChatGptSharing,
623
- onCursorEnabled,
597
onSelectModel,
598
}: {
599
readonly merged: MergedUsage;
@@ -633,9 +606,7 @@ function UsageOverview({
606
readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
607
readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
608
readonly refreshingUsage: boolean;
636
- readonly cursorAccessEnvironments: readonly EnvironmentUsageStatus[];
609
readonly showChatGptSharing: boolean;
638
- readonly onCursorEnabled: () => void;
610
readonly onSelectModel: (key: string) => void;
611
}) {
612
const [breakdown, setBreakdown] = useState<"model" | "time">("model");
@@ -676,20 +647,6 @@ function UsageOverview({
647
0,
648
);
649
const rankedProviders = rankProvidersByMetric(activeProviders, merged.providers, metric);
679
- const cursorInsertAt =
680
- Math.max(rankedProviders.indexOf("codex"), rankedProviders.indexOf("claude")) + 1;
681
- const summaryRows: ReadonlyArray<
682
- | { readonly kind: "usage"; readonly provider: UsageProviderKind }
683
- | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
684
- > = [
685
- ...rankedProviders
686
- .slice(0, cursorInsertAt)
687
- .map((provider) => ({ kind: "usage" as const, provider })),
688
- ...cursorAccessEnvironments.map((environment) => ({ kind: "enable" as const, environment })),
689
- ...rankedProviders
690
- .slice(cursorInsertAt)
691
- .map((provider) => ({ kind: "usage" as const, provider })),
692
- ];
650
651
return (
652
<div aria-busy={loadingPartial} className="flex flex-col gap-6">
@@ -741,19 +698,7 @@ function UsageOverview({
698
</div>
699
) : null}
700
744
- {summaryRows.map((row) => {
745
- if (row.kind === "enable") {
746
- return (
747
- <CursorEnableRow
748
- key={`enable:${row.environment.environmentId}`}
749
- environmentId={row.environment.environmentId}
750
- label={row.environment.label}
751
- showEnvironment={selectedEnvironments.length > 1}
752
- onEnabled={onCursorEnabled}
753
- />
754
- );
755
- }
756
- const provider = row.provider;
701
+ {rankedProviders.map((provider) => {
702
const totals = merged.providers.find((entry) => entry.provider === provider);
703
const share = metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
704
const providerSessions = totals?.sessions ?? 0;
@@ -1079,134 +1024,6 @@ function UsageOverview({
1024
);
1025
}
1026
1082
-const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
1083
-
1084
-function CursorEnableButton({
1085
- environmentId,
1086
- label,
1087
- onEnabled,
1088
- tooltip,
1089
- buttonText = "Enable",
1090
-}: {
1091
- readonly environmentId: EnvironmentId;
1092
- readonly label: string;
1093
- readonly onEnabled: () => void;
1094
- readonly tooltip: boolean;
1095
- readonly buttonText?: string;
1096
-}) {
1097
- const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
1098
- label: "enable Cursor account usage",
1099
- });
1100
- const [pending, setPending] = useState(false);
1101
- const enable = async () => {
1102
- setPending(true);
1103
- const result = await updateSettings({
1104
- environmentId,
1105
- input: { patch: { cursorKeychainUsageEnabled: true } },
1106
- });
1107
- if (result._tag === "Success") onEnabled();
1108
- setPending(false);
1109
- };
1110
- const button = tooltip ? (
1111
- <InlineButton
1112
- disabled={pending}
1113
- aria-busy={pending}
1114
- aria-label={`Enable Cursor usage from ${label}`}
1115
- onClick={() => void enable()}
1116
- >
1117
- {buttonText}
1118
- </InlineButton>
1119
- ) : (
1120
- <Button
1121
- size="sm"
1122
- variant="outline"
1123
- disabled={pending}
1124
- aria-busy={pending}
1125
- aria-label={`Enable Cursor usage from ${label}`}
1126
- onClick={() => void enable()}
1127
- >
1128
- {buttonText}
1129
- </Button>
1130
- );
1131
- if (!tooltip) return button;
1132
- return (
1133
- <Tooltip>
1134
- <TooltipTrigger render={button} />
1135
- <TooltipPopup>{CURSOR_KEYCHAIN_COPY}</TooltipPopup>
1136
- </Tooltip>
1137
- );
1138
-}
1139
-
1140
-function CursorEnableRow({
1141
- environmentId,
1142
- label,
1143
- showEnvironment,
1144
- onEnabled,
1145
-}: {
1146
- readonly environmentId: EnvironmentId;
1147
- readonly label: string;
1148
- readonly showEnvironment: boolean;
1149
- readonly onEnabled: () => void;
1150
-}) {
1151
- return (
1152
- <div className="flex min-w-0 items-baseline justify-between gap-4 text-sm">
1153
- <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
1154
- <span
1155
- aria-hidden
1156
- className="size-2 shrink-0 rounded-full"
1157
- style={{ backgroundColor: PROVIDER_PRESENTATION.cursor.color }}
1158
- />
1159
- <ProviderMark provider="cursor" className="size-4" />
1160
- <span className="truncate">Cursor{showEnvironment ? ` · ${label}` : ""}</span>
1161
- </span>
1162
- <CursorEnableButton
1163
- environmentId={environmentId}
1164
- label={label}
1165
- onEnabled={onEnabled}
1166
- tooltip
1167
- />
1168
- </div>
1169
- );
1170
-}
1171
-
1172
-function CursorEnableLimits({
1173
- environments,
1174
- onEnabled,
1175
-}: {
1176
- readonly environments: readonly EnvironmentUsageStatus[];
1177
- readonly onEnabled: () => void;
1178
-}) {
1179
- return (
1180
- <section className="flex flex-col gap-3">
1181
- <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
1182
- <ProviderInstanceIcon
1183
- driverKind={ProviderDriverKind.make("cursor")}
1184
- displayName="Cursor"
1185
- indicatorBackground="var(--background)"
1186
- className="size-5"
1187
- iconClassName="size-4 text-foreground/80"
1188
- />
1189
- Cursor
1190
- </h2>
1191
- <div className="flex flex-col items-start gap-3 rounded-lg border border-border/60 p-4">
1192
- <p className="text-xs text-muted-foreground">{CURSOR_KEYCHAIN_COPY}</p>
1193
- <div className="flex flex-wrap gap-2">
1194
- {environments.map((environment) => (
1195
- <CursorEnableButton
1196
- key={environment.environmentId}
1197
- environmentId={environment.environmentId}
1198
- label={environment.label}
1199
- buttonText={environments.length > 1 ? `Enable on ${environment.label}` : "Enable"}
1200
- onEnabled={onEnabled}
1201
- tooltip={false}
1202
- />
1203
- ))}
1204
- </div>
1205
- </div>
1206
- </section>
1207
- );
1208
-}
1209
-
1027
function ProviderMark({
1028
provider,
1029
className,
apps/web/src/state/usage.ts
+1
-11
@@ -8,11 +8,7 @@ import {
8
type UsageProviderKind,
9
type UsageSummaryInput,
10
} from "@t3tools/contracts";
11
-import {
12
- needsCursorKeychainAccess,
13
- refreshUsage,
14
- usageSummaryInput,
15
-} from "@t3tools/client-runtime/state/usage";
11
+import { refreshUsage, usageSummaryInput } from "@t3tools/client-runtime/state/usage";
12
import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
13
import { AsyncResult, Atom } from "effect/reactivity";
14
import { useState } from "react";
@@ -31,7 +27,6 @@ export interface EnvironmentUsageStatus {
27
readonly isConnected: boolean;
28
readonly error: string | null;
29
readonly summary: UsageSummary | null;
34
- readonly needsCursorKeychainAccess: boolean;
30
}
31
32
const usageByWindowAtom = Atom.family((windowKey: string) =>
@@ -55,7 +50,6 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
50
isConnected,
51
...access,
52
summary: null,
58
- needsCursorKeychainAccess: false,
53
});
54
continue;
55
}
@@ -77,10 +71,6 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
71
isConnected,
72
error: result._tag === "Failure" ? "This environment could not report usage." : null,
73
summary,
80
- needsCursorKeychainAccess: needsCursorKeychainAccess(
81
- summary,
82
- get(serverEnvironment.providersValueAtom(environmentId)),
83
- ),
74
});
75
}
76
return statuses;
docs/user/usage.md
+6
-11
@@ -25,13 +25,9 @@ databases, including T3-managed profiles. Set `OPENCODE_DATA_DIR` or `ANTIGRAVIT
25
server to read a different data directory; comma-separated paths read multiple directories.
26
27
Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as
28
-`CURSOR_API_KEY`, or otherwise the CLI login saved on the server.
29
-This includes headless T3 sessions and desktop usage across machines; the same account counts
30
-once across connected environments. Without any of these, T3 shows a
31
-notice instead of incomplete local totals. T3 does not estimate missing tokens from conversation text.
32
-On macOS without a T3 sign-in, choose **Enable Cursor usage** on Usage to allow T3 to read your
33
-existing CLI login from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask
34
-you to allow access on the server Mac.
28
+`CURSOR_API_KEY`. This includes headless T3 sessions and desktop usage across machines; the same
29
+account counts once across connected environments. T3 does not estimate missing tokens from
30
+conversation text.
31
32
Usage includes each configured account's history, including disabled accounts. Custom homes follow
33
the account's home setting or its `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, or `GROK_HOME` environment
@@ -161,10 +157,9 @@ in OpenCode with an API key. A Console browser sign-in alone does not report the
157
your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then
158
refresh provider status. Cursor reports
159
its monthly allowance, including separate Auto and API usage, for `CURSOR_AUTH_TOKEN` when it is set,
164
-otherwise for the account you signed in with in T3 or set as `CURSOR_API_KEY`, otherwise for the CLI
165
-login. On macOS, this includes the default Keychain login after you enable Cursor usage. Sign-in, API key,
166
-and Keychain login report limits only with Cursor's default API endpoint. If you configure a custom
167
-Cursor endpoint, use an explicit token or file-based CLI login for limits.
160
+otherwise for the account you signed in with in T3 or set as `CURSOR_API_KEY`.
161
+Sign-in and API keys report limits only with Cursor's default API endpoint. If you configure a custom
162
+Cursor endpoint, use an explicit `CURSOR_AUTH_TOKEN` for limits.
163
164
Grok reports the remaining subscription allowance and reset time for its current billing period
165
after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication
packages/client-runtime/src/state/server.ts
-1
@@ -1132,7 +1132,6 @@ export function createServerEnvironmentAtoms<R, E>(
1132
Object.keys(aliases)
1133
.sort()
1134
.map((model) => [model, aliases[model]]),
1135
- settings?.cursorKeychainUsageEnabled ?? false,
1135
]);
1136
}).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)),
1137
);
packages/client-runtime/src/state/usage.test.ts
+7
-89
@@ -1,10 +1,7 @@
1
import {
2
EnvironmentId,
3
- ProviderDriverKind,
4
- ProviderInstanceId,
3
UsageDay,
4
USAGE_CONTRACT_VERSION,
7
- type ServerProvider,
5
type UsageModelFilter,
6
type UsageSummary,
7
type UsageSummaryInput,
@@ -14,12 +11,7 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
12
13
import type { EnvironmentPresentation } from "../connection/presentation.ts";
17
-import {
18
- cursorKeychainAccessEnvironments,
19
- needsCursorKeychainAccess,
20
- refreshUsage,
21
- refreshUsageLimits,
22
-} from "./usage.ts";
14
+import { refreshUsage, refreshUsageLimits } from "./usage.ts";
15
16
const input = {
17
sinceDay: UsageDay.make("2026-09-05"),
@@ -199,91 +191,17 @@ describe("manual usage refresh", () => {
191
});
192
193
describe("limits refresh cooldown", () => {
202
- it("runs a fresh check after an in-flight check when settings change", async () => {
203
- const id = EnvironmentId.make("limits-after-enable");
194
+ it("shares an in-flight check and skips duplicate automatic refreshes", async () => {
195
+ const id = EnvironmentId.make("limits-in-flight");
196
const oldCheck = Promise.withResolvers<string>();
197
const first = refreshUsageLimits(id, () => oldCheck.promise, true);
198
const newCheck = vi.fn(async () => "new limits");
207
- const afterEnable = refreshUsageLimits(id, newCheck, false, true);
199
+ const manual = refreshUsageLimits(id, newCheck);
200
+ expect(await refreshUsageLimits(id, newCheck, true)).toBeUndefined();
201
expect(newCheck).not.toHaveBeenCalled();
202
oldCheck.resolve("old limits");
203
expect(await first).toBe("old limits");
211
- expect(await afterEnable).toBe("new limits");
212
- expect(newCheck).toHaveBeenCalledTimes(1);
213
- });
214
-});
215
-
216
-describe("needsCursorKeychainAccess", () => {
217
- const cursorPrompt: UsageSummary = {
218
- ...summary,
219
- sources: [
220
- {
221
- fingerprint: {
222
- hostId: "host",
223
- provider: "cursor",
224
- resolvedHomePath: "/Users/me/.cursor/auth.json",
225
- volumeId: "volume",
226
- },
227
- status: "ok",
228
- scannedFiles: 0,
229
- skippedFiles: 0,
230
- malformedRecords: 0,
231
- distinctSessions: 0,
232
- message: "Cursor account usage is off on this environment.",
233
- action: "enableCursorKeychain",
234
- },
235
- ],
236
- };
237
- const cursor = (status: ServerProvider["status"]): ServerProvider => ({
238
- instanceId: ProviderInstanceId.make("cursor"),
239
- driver: ProviderDriverKind.make("cursor"),
240
- enabled: status !== "disabled",
241
- installed: status === "ready",
242
- version: null,
243
- status,
244
- auth: { status: "unknown" },
245
- checkedAt: "2026-09-05T12:00:00.000Z",
246
- models: [],
247
- slashCommands: [],
248
- skills: [],
249
- });
250
-
251
- it("offers access only when Cursor is ready on that environment", () => {
252
- expect(needsCursorKeychainAccess(cursorPrompt, [cursor("ready")])).toBe(true);
253
- expect(needsCursorKeychainAccess(cursorPrompt, [cursor("error")])).toBe(false);
254
- expect(needsCursorKeychainAccess(cursorPrompt, [cursor("disabled")])).toBe(false);
255
- expect(needsCursorKeychainAccess(cursorPrompt, [])).toBe(false);
256
- expect(needsCursorKeychainAccess(cursorPrompt, null)).toBe(false);
257
- expect(needsCursorKeychainAccess(summary, [cursor("ready")])).toBe(false);
258
- });
259
-
260
- it("stops offering access once any environment reads the Cursor account", () => {
261
- const off = { summary: cursorPrompt, needsCursorKeychainAccess: true };
262
- const account: UsageSummary = {
263
- ...summary,
264
- sources: [
265
- {
266
- fingerprint: {
267
- hostId: "cursor.com",
268
- provider: "cursor",
269
- resolvedHomePath: "cursor-account:abc",
270
- volumeId: "abc",
271
- },
272
- status: "ok",
273
- scannedFiles: 1,
274
- skippedFiles: 0,
275
- malformedRecords: 0,
276
- distinctSessions: 1,
277
- message: null,
278
- },
279
- ],
280
- };
281
- expect(cursorKeychainAccessEnvironments([off, off])).toEqual([off, off]);
282
- expect(
283
- cursorKeychainAccessEnvironments([
284
- off,
285
- { summary: account, needsCursorKeychainAccess: false },
286
- ]),
287
- ).toEqual([]);
204
+ expect(await manual).toBe("old limits");
205
+ expect(newCheck).not.toHaveBeenCalled();
206
});
207
});
packages/client-runtime/src/state/usage.ts
+1
-43
@@ -1,10 +1,4 @@
1
-import type {
2
- EnvironmentId,
3
- ServerProvider,
4
- UsageModelFilter,
5
- UsageSummary,
6
- UsageSummaryInput,
7
-} from "@t3tools/contracts";
1
+import type { EnvironmentId, UsageModelFilter, UsageSummaryInput } from "@t3tools/contracts";
2
import * as Schema from "effect/Schema";
3
import type { AtomRegistry } from "effect/reactivity";
4
@@ -15,35 +9,6 @@ import type { createServerEnvironmentAtoms } from "./server.ts";
9
10
const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
11
18
-export function needsCursorKeychainAccess(
19
- summary: UsageSummary | null,
20
- providers: readonly ServerProvider[] | null,
21
-): boolean {
22
- return (
23
- summary?.sources.some((source) => source.action === "enableCursorKeychain") === true &&
24
- providers?.some((provider) => provider.driver === "cursor" && provider.status === "ready") ===
25
- true
26
- );
27
-}
28
-
29
-/**
30
- * Any environment reading a Cursor account already reports that account's
31
- * history from every machine, so the prompt only adds duplicates there.
32
- */
33
-export function cursorKeychainAccessEnvironments<
34
- E extends { readonly summary: UsageSummary | null; readonly needsCursorKeychainAccess: boolean },
35
->(environments: readonly E[]): readonly E[] {
36
- const hasCursorAccount = environments.some((environment) =>
37
- environment.summary?.sources.some(
38
- (source) =>
39
- source.fingerprint.provider === "cursor" && source.fingerprint.hostId === "cursor.com",
40
- ),
41
- );
42
- return hasCursorAccount
43
- ? []
44
- : environments.filter((environment) => environment.needsCursorKeychainAccess);
45
-}
46
-
12
/** The Usage tab asks each environment with that environment's configured model filter. */
13
export function usageSummaryInput(
14
input: UsageSummaryInput,
@@ -59,16 +24,9 @@ export async function refreshUsageLimits<A>(
24
environmentId: EnvironmentId,
25
refresh: () => Promise<A>,
26
automatic = false,
62
- afterPending = false,
27
): Promise<A | undefined> {
28
const pending = limitsRefreshes.get(environmentId);
29
if (pending !== undefined) {
66
- if (afterPending) {
67
- try {
68
- await pending;
69
- } catch {}
70
- return refreshUsageLimits(environmentId, refresh, false, true);
71
- }
30
return automatic ? undefined : ((await pending) as A);
31
}
32
const refreshAfter = limitsRefreshAfter.get(environmentId) ?? 0;
packages/contracts/src/settings.ts
-4
@@ -1449,9 +1449,6 @@ export const ServerSettings = Schema.Struct({
1449
secretProviders: Schema.Record(SecretProviderId, SecretProviderConfig).pipe(
1450
Schema.withDecodingDefault(Effect.succeed({})),
1451
),
1452
- cursorKeychainUsageEnabled: Schema.Boolean.pipe(
1453
- Schema.withDecodingDefault(Effect.succeed(false)),
1454
- ),
1452
1453
usagePriceOverrides: Schema.Record(TrimmedNonEmptyString, UsageModelPriceOverride).pipe(
1454
Schema.withDecodingDefault(Effect.succeed({})),
@@ -1806,7 +1803,6 @@ export const ServerSettingsPatch = Schema.Struct({
1803
secretProviders: Schema.optionalKey(
1804
Schema.Record(SecretProviderId, Schema.NullOr(SecretProviderConfigWrite)),
1805
),
1809
- cursorKeychainUsageEnabled: Schema.optionalKey(Schema.Boolean),
1806
1807
usagePriceOverrides: Schema.optionalKey(
1808
Schema.Record(TrimmedNonEmptyString, Schema.NullOr(UsageModelPriceOverride)),
packages/contracts/src/usage.ts
-1
@@ -91,7 +91,6 @@ export const UsageSource = Schema.Struct({
91
/** Total this count; bucket counts double-count sessions spanning days or models. */
92
distinctSessions: NonNegativeInt,
93
message: Schema.NullOr(TrimmedNonEmptyString),
94
- action: Schema.optionalKey(Schema.Literal("enableCursorKeychain")),
94
/** Cached response during refresh; repeat with awaitRefresh for fresh data. */
95
refreshing: Schema.optionalKey(Schema.Literal(true)),
96
});
packages/provider-core/src/server/usage.ts
-1
@@ -89,7 +89,6 @@ export interface ProviderUsageScan {
89
readonly hostId?: string;
90
readonly status?: UsageSource["status"];
91
readonly message?: string;
92
- readonly action?: UsageSource["action"];
92
readonly files:
93
| readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
94
| null;
packages/provider-cursor/package.json
-5
@@ -31,10 +31,6 @@
31
"types": "./src/server/CursorAccountReader.ts",
32
"import": "./src/server/CursorAccountReader.ts"
33
},
34
- "./server/CursorKeychain": {
35
- "types": "./src/server/CursorKeychain.ts",
36
- "import": "./src/server/CursorKeychain.ts"
37
- },
34
"./server/CursorUsageAccounts": {
35
"types": "./src/server/CursorUsageAccounts.ts",
36
"import": "./src/server/CursorUsageAccounts.ts"
@@ -50,7 +46,6 @@
46
},
47
"dependencies": {
48
"@cursor/sdk": "1.2.0",
53
- "@napi-rs/keyring": "^1.3.0",
49
"@t3tools/contracts": "workspace:*",
50
"@t3tools/provider-core": "workspace:*",
51
"@t3tools/shared": "workspace:*",
packages/provider-cursor/src/server/CursorAccountReader.ts
+4
-12
@@ -1,13 +1,11 @@
1
import * as Context from "effect/Context";
2
import * as Digest from "effect/crypto/Digest";
3
import * as Effect from "effect/Effect";
4
-import * as FileSystem from "effect/FileSystem";
4
import * as HttpClient from "effect/http/HttpClient";
5
import * as Layer from "effect/Layer";
6
7
import type { CursorCredentialSource } from "./accountCache.ts";
8
import { readCursorAccountUsage, type CursorAccountUsageReadResult } from "./accountUsage.ts";
10
-import * as CursorKeychain from "./CursorKeychain.ts";
9
10
export class CursorAccountReader extends Context.Service<
11
CursorAccountReader,
@@ -23,18 +21,12 @@ export class CursorAccountReader extends Context.Service<
21
export const layer = Layer.effect(
22
CursorAccountReader,
23
Effect.gen(function* () {
26
- const keychain = yield* CursorKeychain.CursorKeychain;
27
- const context = yield* Effect.context<
28
- FileSystem.FileSystem | Digest.Digest | HttpClient.HttpClient
29
- >();
24
+ const context = yield* Effect.context<Digest.Digest | HttpClient.HttpClient>();
25
return CursorAccountReader.of({
26
read: Effect.fn("CursorAccountReader.read")(function (credentialSource, sinceMs, untilMs) {
32
- return readCursorAccountUsage(
33
- credentialSource,
34
- sinceMs,
35
- untilMs,
36
- keychain.accessToken,
37
- ).pipe(Effect.provideContext(context));
27
+ return readCursorAccountUsage(credentialSource, sinceMs, untilMs).pipe(
28
+ Effect.provideContext(context),
29
+ );
30
}),
31
});
32
}),
packages/provider-cursor/src/server/CursorKeychain.ts
deleted
-102
@@ -1,102 +0,0 @@
1
-// Remote clients cannot answer macOS prompts; time out reads but retain the in-flight request for reuse.
2
-import * as NodeModule from "node:module";
3
-
4
-import * as Clock from "effect/Clock";
5
-import * as Context from "effect/Context";
6
-import * as Deferred from "effect/Deferred";
7
-import * as Duration from "effect/Duration";
8
-import * as Effect from "effect/Effect";
9
-import * as Layer from "effect/Layer";
10
-import * as Option from "effect/Option";
11
-import * as Schema from "effect/Schema";
12
-
13
-const CACHE_MS = 5 * 60_000;
14
-const DEFAULT_TIMEOUT = Duration.seconds(30);
15
-
16
-const requireForKeyring = NodeModule.createRequire(import.meta.url);
17
-
18
-export class CursorKeychainTimeoutError extends Schema.TaggedError<CursorKeychainTimeoutError>()(
19
- "CursorKeychainTimeoutError",
20
- {},
21
-) {
22
- override get message(): string {
23
- return "Timed out waiting for Keychain access.";
24
- }
25
-}
26
-
27
-export const isCursorKeychainTimeoutError = Schema.is(CursorKeychainTimeoutError);
28
-
29
-export class CursorKeychainReadError extends Schema.TaggedError<CursorKeychainReadError>()(
30
- "CursorKeychainReadError",
31
- { cause: Schema.Defect() },
32
-) {
33
- override get message(): string {
34
- return "Cursor Keychain credentials could not be read.";
35
- }
36
-}
37
-
38
-export class CursorKeychain extends Context.Service<
39
- CursorKeychain,
40
- {
41
- readonly accessToken: Effect.Effect<
42
- string | null,
43
- CursorKeychainTimeoutError | CursorKeychainReadError
44
- >;
45
- }
46
->()("@t3tools/provider-cursor/server/CursorKeychain") {}
47
-
48
-const readKeychainEntry = Effect.tryPromise({
49
- try: async () => {
50
- const { AsyncEntry } = requireForKeyring(
51
- "@napi-rs/keyring",
52
- ) as typeof import("@napi-rs/keyring");
53
- return (await new AsyncEntry("cursor-access-token", "cursor-user").getPassword()) ?? null;
54
- },
55
- catch: (cause) => new CursorKeychainReadError({ cause }),
56
-});
57
-
58
-const make = (
59
- read: Effect.Effect<string | null, CursorKeychainReadError> = readKeychainEntry,
60
- timeout: Duration.Input = DEFAULT_TIMEOUT,
61
-): CursorKeychain["Service"] => {
62
- let cached: { readonly token: string; readonly untilMs: number } | null = null;
63
- let pending: Deferred.Deferred<string | null, CursorKeychainReadError> | null = null;
64
-
65
- const startRead = Effect.uninterruptible(
66
- Effect.gen(function* () {
67
- if (pending !== null) return pending;
68
- const done = Deferred.makeUnsafe<string | null, CursorKeychainReadError>();
69
- pending = done;
70
- yield* read.pipe(
71
- Effect.tap((token) =>
72
- Clock.currentTimeMillis.pipe(
73
- Effect.map((nowMs) => {
74
- cached = token ? { token, untilMs: nowMs + CACHE_MS } : null;
75
- }),
76
- ),
77
- ),
78
- Effect.onExit((exit) =>
79
- Effect.suspend(() => {
80
- pending = null;
81
- return Deferred.done(done, exit);
82
- }),
83
- ),
84
- Effect.forkDetach,
85
- );
86
- return done;
87
- }),
88
- );
89
-
90
- const accessToken = Effect.gen(function* () {
91
- const nowMs = yield* Clock.currentTimeMillis;
92
- if (cached !== null && cached.untilMs > nowMs) return cached.token;
93
- const done = yield* startRead;
94
- const token = yield* Deferred.await(done).pipe(Effect.timeoutOption(timeout));
95
- if (Option.isNone(token)) return yield* new CursorKeychainTimeoutError();
96
- return token.value;
97
- });
98
-
99
- return CursorKeychain.of({ accessToken });
100
-};
101
-
102
-export const layer = Layer.sync(CursorKeychain, () => make());
packages/provider-cursor/src/server/CursorUsageAccounts.ts
+4
-86
@@ -2,7 +2,6 @@ import type { ProviderInstanceId } from "@t3tools/contracts";
2
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
3
import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage";
4
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
5
-import * as HostProcess from "@t3tools/shared/HostProcess";
5
import * as Clock from "effect/Clock";
6
import * as Context from "effect/Context";
7
import * as Digest from "effect/crypto/Digest";
@@ -44,7 +43,6 @@ export class CursorUsageAccounts extends Context.Service<
43
readonly instanceId: ProviderInstanceId;
44
readonly environment: NodeJS.ProcessEnv;
45
}>;
47
- readonly keychainUsageEnabled: boolean;
46
readonly windowStartMs: number;
47
readonly retentionCutoffMs: number;
48
readonly awaitRefresh: boolean;
@@ -58,8 +56,6 @@ const make = Effect.gen(function* () {
56
const path = yield* Path.Path;
57
const host = yield* ProviderHost.ProviderHost;
58
const accountReader = yield* CursorAccountReader.CursorAccountReader;
61
- const hostEnvironment = yield* HostProcess.Environment;
62
- const platform = yield* HostProcess.Platform;
59
const digest = yield* Digest.Digest;
60
61
const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME);
@@ -190,34 +186,12 @@ const make = Effect.gen(function* () {
186
187
const accountSource = Effect.fn("CursorUsageAccounts.accountSource")(function* (
188
credential: CursorCredentialSource,
193
- authPath: string,
189
windowStartMs: number,
190
retentionStartMs: number,
191
awaitRefresh: boolean,
192
) {
198
- // A Keychain login outlives an uninstalled Cursor, so it also needs Cursor's local directory.
199
- const localLogin =
200
- typeof credential === "string"
201
- ? credential
202
- : credential.kind === "keychain"
203
- ? path.dirname(authPath)
204
- : null;
205
- if (
206
- localLogin !== null &&
207
- !(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true)))
208
- ) {
209
- return null;
210
- }
193
yield* ensureLoaded;
212
- const credentialKey =
213
- typeof credential === "string"
214
- ? credential
215
- : credential.kind === "apiKey"
216
- ? // A fingerprint, so a replaced key never reads the previous account's cache.
217
- `api-key:${Hex.encode(
218
- yield* digest.digest(Digest.sha256, new TextEncoder().encode(credential.apiKey)),
219
- )}`
220
- : "keychain";
194
+ const credentialKey = `api-key:${Hex.encode(yield* digest.digest(Digest.sha256, new TextEncoder().encode(credential.apiKey)))}`;
195
const nowMs = yield* Clock.currentTimeMillis;
196
const recentFailure = failures.get(credentialKey);
197
let refreshing = false;
@@ -236,8 +210,7 @@ const make = Effect.gen(function* () {
210
if (failureMessage === null) return null;
211
if (cache === undefined) {
212
return {
239
- dir: authPath,
240
- // Never combine a local fallback with another server's account-wide history.
213
+ dir: "cursor-account",
214
...(refreshing
215
? { files: [], refreshing: true }
216
: { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
@@ -263,30 +236,7 @@ const make = Effect.gen(function* () {
236
});
237
238
const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
266
- function* ({
267
- instances,
268
- keychainUsageEnabled,
269
- windowStartMs,
270
- retentionCutoffMs,
271
- awaitRefresh,
272
- }) {
273
- const home = yield* HostProcess.HomeDirectory;
274
- const userHome =
275
- (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
276
- const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
277
- const cursorHome =
278
- platform === "darwin"
279
- ? path.join(userHome, "Library", "Application Support")
280
- : platform === "win32"
281
- ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming")
282
- : configHome && path.isAbsolute(configHome)
283
- ? configHome
284
- : path.join(userHome, ".config");
285
- const authPath =
286
- platform === "darwin"
287
- ? path.join(userHome, ".cursor", "auth.json")
288
- : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
289
- // T3's Cursor sign-in and CURSOR_API_KEY name the account the agent uses, so they win.
239
+ function* ({ instances, windowStartMs, retentionCutoffMs, awaitRefresh }) {
240
const apiKeys = yield* Effect.forEach(instances, ({ instanceId, environment }) =>
241
environment.CURSOR_API_KEY?.trim()
242
? Effect.succeed(environment.CURSOR_API_KEY.trim())
@@ -302,7 +252,6 @@ const make = Effect.gen(function* () {
252
(apiKey) =>
253
accountSource(
254
{ kind: "apiKey", apiKey },
305
- authPath,
255
windowStartMs,
256
retentionCutoffMs,
257
awaitRefresh,
@@ -323,38 +272,7 @@ const make = Effect.gen(function* () {
272
}
273
return [...byAccount.values()];
274
}
326
- const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
327
- const loginUnavailable =
328
- Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || credentialStore === "memory";
329
- const useKeychain = platform === "darwin" && credentialStore !== "file";
330
- if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
331
- return [
332
- {
333
- dir: authPath,
334
- volumeId: "",
335
- files: null,
336
- message: "Cursor account usage is off on this environment.",
337
- action: "enableCursorKeychain",
338
- },
339
- ];
340
- }
341
- if (loginUnavailable) {
342
- return [
343
- {
344
- dir: authPath,
345
- files: null,
346
- message: "Cursor account history needs a Cursor CLI login on this server.",
347
- },
348
- ];
349
- }
350
- const source = yield* accountSource(
351
- useKeychain ? { kind: "keychain" } : authPath,
352
- authPath,
353
- windowStartMs,
354
- retentionCutoffMs,
355
- awaitRefresh,
356
- );
357
- return source === null ? [] : [source];
275
+ return [];
276
},
277
);
278
packages/provider-cursor/src/server/accountCache.ts
+1
-4
@@ -2,10 +2,7 @@
2
import { cursorRateModel } from "./accountUsage.ts";
3
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
4
5
-export type CursorCredentialSource =
6
- | string
7
- | { readonly kind: "keychain" }
8
- | { readonly kind: "apiKey"; readonly apiKey: string };
5
+export type CursorCredentialSource = { readonly kind: "apiKey"; readonly apiKey: string };
6
7
export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000;
8
packages/provider-cursor/src/server/accountUsage.test.ts
+33
-69
@@ -5,27 +5,14 @@ import { assert, describe, it } from "@effect/vitest";
5
import * as Context from "effect/Context";
6
import * as Effect from "effect/Effect";
7
import * as Fiber from "effect/Fiber";
8
-import * as FileSystem from "effect/FileSystem";
8
import * as FetchHttpClient from "effect/http/FetchHttpClient";
9
import * as HttpClient from "effect/http/HttpClient";
10
import * as HttpClientError from "effect/http/HttpClientError";
11
import * as HttpClientResponse from "effect/http/HttpClientResponse";
13
-import * as Path from "effect/Path";
12
import * as TestClock from "effect/testing/TestClock";
13
16
-import * as CursorKeychain from "./CursorKeychain.ts";
14
import { readCursorAccountUsage } from "./accountUsage.ts";
15
19
-const writeAuth = (accessToken: string) =>
20
- Effect.gen(function* () {
21
- const fileSystem = yield* FileSystem.FileSystem;
22
- const path = yield* Path.Path;
23
- const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "usage-reader-test-" });
24
- const authPath = path.join(dir, "auth.json");
25
- yield* fileSystem.writeFileString(authPath, JSON.stringify({ accessToken }));
26
- return { dir, authPath };
27
- });
28
-
16
interface DashboardRequest {
17
readonly url: string;
18
readonly init: RequestInit;
@@ -40,6 +27,15 @@ const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Res
27
const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
28
const body =
29
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
30
+ if (
31
+ url.pathname === "/auth/exchange_user_api_key" &&
32
+ request.headers.authorization?.startsWith("Bearer header.")
33
+ ) {
34
+ return HttpClientResponse.fromWeb(
35
+ request,
36
+ Response.json({ accessToken: request.headers.authorization.slice(7) }),
37
+ );
38
+ }
39
const response = await answer({
40
url: url.toString(),
41
init: { ...init, signal, body },
@@ -60,9 +56,8 @@ const readAccountUsage = (
56
sinceMs: number,
57
endDate: number,
58
answer: (request: DashboardRequest) => Response | Promise<Response>,
63
- keychainToken?: Parameters<typeof readCursorAccountUsage>[3],
59
) =>
65
- readCursorAccountUsage(credentialSource, sinceMs, endDate, keychainToken).pipe(
60
+ readCursorAccountUsage(credentialSource, sinceMs, endDate).pipe(
61
Effect.provideService(HttpClient.HttpClient, dashboard(answer)),
62
);
63
@@ -72,15 +67,18 @@ describe("Cursor account history", () => {
67
() =>
68
Effect.gen(function* () {
69
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`;
75
- const { authPath } = yield* writeAuth(accessToken);
70
+ const credential = { kind: "apiKey", apiKey: accessToken } as const;
71
const pages: number[] = [];
72
const signals: AbortSignal[] = [];
73
const request = ({ url, init, headers, page }: DashboardRequest) => {
79
- assert.strictEqual(url, "https://cursor.com/api/dashboard/get-filtered-usage-events");
74
+ assert.strictEqual(
75
+ url,
76
+ "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents",
77
+ );
78
assert.strictEqual(init.redirect, "error");
81
- assert.strictEqual(headers.get("origin"), "https://cursor.com");
79
+ assert.strictEqual(headers.get("connect-protocol-version"), "1");
80
assert.strictEqual(headers.get("content-type"), "application/json");
83
- assert.include(headers.get("cookie") ?? "", "WorkosCursorSessionToken=demo%3A%3A");
81
+ assert.strictEqual(headers.get("authorization"), `Bearer ${accessToken}`);
82
const body = { page };
83
pages.push(body.page);
84
if (init.signal) signals.push(init.signal);
@@ -102,7 +100,7 @@ describe("Cursor account history", () => {
100
})),
101
});
102
};
105
- const result = yield* readAccountUsage(authPath, 0, 1781000000000, request);
103
+ const result = yield* readAccountUsage(credential, 0, 1781000000000, request);
104
assert.isNull(result.error);
105
assert.deepStrictEqual(pages, [1, 2]);
106
assert.lengthOf(signals, 2);
@@ -124,10 +122,10 @@ describe("Cursor account history", () => {
122
it.effect("reads Cursor account history beyond 100 pages", () =>
123
Effect.gen(function* () {
124
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
127
- const { authPath } = yield* writeAuth(accessToken);
125
+ const credential = { kind: "apiKey", apiKey: accessToken } as const;
126
const fullPage = Array.from({ length: 1000 }, () => ({ tokenUsage: null }));
127
let requests = 0;
130
- const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
128
+ const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => {
129
requests += 1;
130
return Response.json({
131
totalUsageEventsCount: 100_001,
@@ -143,13 +141,13 @@ describe("Cursor account history", () => {
141
it.effect("accepts confirmed empty Cursor usage but rejects error envelopes", () =>
142
Effect.gen(function* () {
143
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
146
- const { authPath } = yield* writeAuth(accessToken);
144
+ const credential = { kind: "apiKey", apiKey: accessToken } as const;
145
for (const body of [
146
{},
147
{ totalUsageEventsCount: 0 },
148
{ totalUsageEventsCount: 0, usageEventsDisplay: [] },
149
]) {
152
- const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
150
+ const result = yield* readAccountUsage(credential, 0, 1781000000000, async () =>
151
Response.json(body),
152
);
153
assert.isNull(result.error);
@@ -165,7 +163,7 @@ describe("Cursor account history", () => {
163
"invalid",
164
0,
165
]) {
168
- const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
166
+ const result = yield* readAccountUsage(credential, 0, 1781000000000, async () =>
167
Response.json(body),
168
);
169
assert.isNotNull(result.error);
@@ -177,9 +175,9 @@ describe("Cursor account history", () => {
175
it.effect("requires a terminal Cursor page after a full page reaches the reported count", () =>
176
Effect.gen(function* () {
177
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
180
- const { authPath } = yield* writeAuth(accessToken);
178
+ const credential = { kind: "apiKey", apiKey: accessToken } as const;
179
let requests = 0;
182
- const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
180
+ const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => {
181
requests++;
182
return Response.json(
183
requests === 1
@@ -205,7 +203,7 @@ describe("Cursor account history", () => {
203
() =>
204
Effect.gen(function* () {
205
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
208
- const { authPath } = yield* writeAuth(accessToken);
206
+ const credential = { kind: "apiKey", apiKey: accessToken } as const;
207
const event = (index: number) => ({
208
timestamp: String(1780000000000 + index),
209
model: "gpt-5",
@@ -213,7 +211,7 @@ describe("Cursor account history", () => {
211
});
212
for (const total of [2000, 2001]) {
213
let requests = 0;
216
- const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
214
+ const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => {
215
requests++;
216
return Response.json({
217
totalUsageEventsCount: total,
@@ -236,7 +234,7 @@ describe("Cursor account history", () => {
234
assert.strictEqual(new Set(result.records.map((record) => record.dedupeKey)).size, total);
235
}
236
let requests = 0;
239
- const inconsistent = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
237
+ const inconsistent = yield* readAccountUsage(credential, 0, 1781000000000, async () => {
238
requests++;
239
return Response.json({
240
totalUsageEventsCount: 1001,
@@ -256,14 +254,14 @@ describe("Cursor account history", () => {
254
() =>
255
Effect.gen(function* () {
256
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`;
259
- const { dir, authPath } = yield* writeAuth(accessToken);
260
- const truncated = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
257
+ const credential = { kind: "apiKey", apiKey: accessToken } as const;
258
+ const truncated = yield* readAccountUsage(credential, 0, 1781000000000, async () =>
259
Response.json({ totalUsageEventsCount: 101, usageEventsDisplay: [] }),
260
);
261
assert.isNotNull(truncated.error);
262
assert.deepStrictEqual(truncated.records, []);
263
const denied = yield* readAccountUsage(
266
- authPath,
264
+ credential,
265
0,
266
1781000000000,
267
async () => new Response(accessToken, { status: 401 }),
@@ -271,18 +269,6 @@ describe("Cursor account history", () => {
269
assert.isNotNull(denied.error);
270
assert.isFalse(denied.error?.includes(accessToken) ?? true);
271
assert.deepStrictEqual(denied.records, []);
274
- let requested = false;
275
- const missing = yield* readAccountUsage(
276
- (yield* Path.Path).join(dir, "missing.json"),
277
- 0,
278
- 1781000000000,
279
- async () => {
280
- requested = true;
281
- return Response.json({});
282
- },
283
- );
284
- assert.isTrue(missing.missing);
285
- assert.isFalse(requested);
272
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
273
);
274
});
@@ -336,33 +322,13 @@ describe("readCursorAccountUsage", () => {
322
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
323
);
324
339
- it.effect("asks for Keychain approval when the prompt goes unanswered", () =>
340
- Effect.gen(function* () {
341
- const result = yield* readAccountUsage(
342
- { kind: "keychain" },
343
- 0,
344
- 1,
345
- () => {
346
- throw new Error("no network expected");
347
- },
348
- Effect.fail(new CursorKeychain.CursorKeychainTimeoutError()),
349
- );
350
- assert.deepStrictEqual(result, {
351
- accountKey: null,
352
- records: [],
353
- missing: false,
354
- error: "Allow Keychain access on the Mac running T3 Code, then refresh.",
355
- });
356
- }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
357
- );
358
-
325
it.effect("reads the pages behind the first together and keeps them in page order", () =>
326
Effect.gen(function* () {
327
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
328
let inFlight = 0;
329
let mostInFlight = 0;
330
const result = yield* readAccountUsage(
365
- { kind: "keychain" },
331
+ { kind: "apiKey", apiKey: accessToken },
332
0,
333
1781000000000,
334
async ({ page }) => {
@@ -379,7 +345,6 @@ describe("readCursorAccountUsage", () => {
345
})),
346
});
347
},
382
- Effect.succeed(accessToken),
348
);
349
assert.isNull(result.error);
350
assert.strictEqual(mostInFlight, 6);
@@ -406,7 +371,7 @@ describe("readCursorAccountUsage", () => {
371
] as const) {
372
let open = 0;
373
const result = yield* readAccountUsage(
409
- { kind: "keychain" },
374
+ { kind: "apiKey", apiKey: accessToken },
375
0,
376
1781000000000,
377
({ init, page }) => {
@@ -421,7 +386,6 @@ describe("readCursorAccountUsage", () => {
386
});
387
});
388
},
424
- Effect.succeed(accessToken),
389
);
390
assert.strictEqual(result.error, error);
391
assert.deepStrictEqual(result.records, []);
packages/provider-cursor/src/server/accountUsage.ts
+11
-84
@@ -5,17 +5,14 @@ import * as Effect from "effect/Effect";
5
import * as Base64Url from "effect/encoding/Base64Url";
6
import * as Hex from "effect/encoding/Hex";
7
import * as Fiber from "effect/Fiber";
8
-import * as FileSystem from "effect/FileSystem";
8
import * as FetchHttpClient from "effect/http/FetchHttpClient";
9
import * as HttpClient from "effect/http/HttpClient";
10
import * as HttpClientRequest from "effect/http/HttpClientRequest";
12
-import * as PlatformError from "effect/PlatformError";
11
import * as Result from "effect/Result";
12
import * as Schema from "effect/Schema";
13
14
import type { CursorCredentialSource } from "./accountCache.ts";
15
import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
18
-import * as CursorKeychain from "./CursorKeychain.ts";
16
17
function object(value: unknown): Record<string, unknown> {
18
return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -87,84 +84,25 @@ function boundaryOverlap(previous: readonly string[], current: readonly string[]
84
return lengths.at(-1) ?? 0;
85
}
86
90
-const DASHBOARD_USAGE_URL = "https://cursor.com/api/dashboard/get-filtered-usage-events";
91
-
92
-/** The session cookie must never follow a redirect off cursor.com. */
87
+/** Never forward the access token through a redirect. */
88
const NO_REDIRECT: RequestInit = { redirect: "error" };
89
90
export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(function* (
91
credentialSource: CursorCredentialSource,
92
sinceMs: number,
93
endDate: number,
99
- keychainToken: Effect.Effect<
100
- string | null,
101
- | CursorKeychain.CursorKeychainTimeoutError
102
- | CursorKeychain.CursorKeychainReadError
103
- | CursorAccountUsageInvalidError
104
- > = invalid("No Keychain reader"),
105
-): Effect.fn.Return<
106
- CursorAccountUsageReadResult,
107
- never,
108
- FileSystem.FileSystem | Digest.Digest | HttpClient.HttpClient
109
-> {
110
- const fileSystem = yield* FileSystem.FileSystem;
94
+): Effect.fn.Return<CursorAccountUsageReadResult, never, Digest.Digest | HttpClient.HttpClient> {
95
const httpClient = yield* HttpClient.HttpClient;
112
- const credential = yield* Effect.result<
113
- unknown,
114
- | PlatformError.PlatformError
115
- | Schema.SchemaError
116
- | CursorKeychain.CursorKeychainTimeoutError
117
- | CursorKeychain.CursorKeychainReadError
118
- | CursorAccountUsageInvalidError,
119
- never
120
- >(
121
- typeof credentialSource === "string"
122
- ? fileSystem.readFileString(credentialSource).pipe(
123
- Effect.flatMap(decodeJson),
124
- Effect.map((credentials) => object(credentials).accessToken),
125
- )
126
- : credentialSource.kind === "apiKey"
127
- ? exchangeCursorApiKey(credentialSource.apiKey).pipe(
128
- Effect.provideService(HttpClient.HttpClient, httpClient),
129
- Effect.mapError(
130
- () => new CursorAccountUsageInvalidError({ reason: "Invalid API key" }),
131
- ),
132
- )
133
- : keychainToken,
134
- );
96
+ const credential = yield* Effect.result(exchangeCursorApiKey(credentialSource.apiKey));
97
if (Result.isFailure(credential)) {
136
- const cause = credential.failure;
137
- const missing =
138
- typeof credentialSource === "string" &&
139
- PlatformError.isPlatformError(cause) &&
140
- cause.reason._tag === "NotFound";
98
return {
99
accountKey: null,
100
records: [],
144
- missing,
145
- error: missing
146
- ? null
147
- : typeof credentialSource === "string"
148
- ? "Cursor credentials could not be read."
149
- : credentialSource.kind === "apiKey"
150
- ? "Cursor account usage could not be read."
151
- : CursorKeychain.isCursorKeychainTimeoutError(cause)
152
- ? "Allow Keychain access on the Mac running T3 Code, then refresh."
153
- : "Cursor Keychain credentials could not be read.",
101
+ missing: false,
102
+ error: "Cursor account usage could not be read.",
103
};
104
}
105
const accessToken = credential.success;
157
- if (typeof accessToken !== "string" || !accessToken) {
158
- return {
159
- accountKey: null,
160
- records: [],
161
- missing: true,
162
- error:
163
- typeof credentialSource === "string"
164
- ? null
165
- : "Cursor account history needs a macOS Keychain CLI login on this server.",
166
- };
167
- }
106
let accountKey: string | null = null;
107
const read = Effect.gen(function* () {
108
const payload = Base64Url.decodeString(accessToken.split(".")[1] ?? "");
@@ -175,26 +113,15 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
113
),
114
).sub;
115
if (typeof subject !== "string" || !subject) return yield* invalid("Invalid authentication");
178
- const userId = subject.split("|").at(-1);
179
- if (!userId) return yield* invalid("Invalid authentication");
116
accountKey = yield* accountHash(subject);
117
if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate)
118
return yield* invalid("Invalid date window");
183
- // The web dashboard rejects API-key tokens; Cursor's RPC API accepts them.
184
- const pageRequest =
185
- typeof credentialSource !== "string" && credentialSource.kind === "apiKey"
186
- ? HttpClientRequest.post(
187
- `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`,
188
- ).pipe(
189
- HttpClientRequest.bearerToken(accessToken),
190
- HttpClientRequest.setHeader("connect-protocol-version", "1"),
191
- )
192
- : HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe(
193
- HttpClientRequest.setHeaders({
194
- Origin: "https://cursor.com",
195
- Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`,
196
- }),
197
- );
119
+ const pageRequest = HttpClientRequest.post(
120
+ `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`,
121
+ ).pipe(
122
+ HttpClientRequest.bearerToken(accessToken),
123
+ HttpClientRequest.setHeader("connect-protocol-version", "1"),
124
+ );
125
const records: UsageRecord[] = [];
126
const occurrences = new Map<string, number>();
127
const pages: unknown[][] = [];
packages/provider-cursor/src/server/driver.test.ts
-6
@@ -34,7 +34,6 @@ import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
34
import { CursorDriver } from "./driver.ts";
35
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
36
import * as CursorSdk from "./CursorSdk.ts";
37
-import * as CursorKeychain from "./CursorKeychain.ts";
37
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
39
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -52,11 +51,6 @@ const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe(
51
open: () => Effect.die("Maintenance resolution must not open a Cursor session"),
52
}),
53
),
55
- Layer.provideMerge(
56
- Layer.succeed(CursorKeychain.CursorKeychain, {
57
- accessToken: Effect.die("The driver test must not read the Keychain"),
58
- }),
59
- ),
54
Layer.provideMerge(
55
Layer.succeed(
56
ProviderEventLoggers.ProviderEventLoggers,
packages/provider-cursor/src/server/driver.ts
+6
-17
@@ -37,7 +37,6 @@ import { makeCursorAuth } from "./auth.ts";
37
import * as CursorCredentialStore from "./credentialStore.ts";
38
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
39
import * as CursorSdk from "./CursorSdk.ts";
40
-import * as CursorKeychain from "./CursorKeychain.ts";
40
import * as CursorUsageAccounts from "./CursorUsageAccounts.ts";
41
42
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
@@ -56,8 +55,7 @@ export type CursorDriverEnv =
55
| Path.Path
56
| HttpClient.HttpClient
57
| CursorSdk.CursorSdk
59
- | ProviderHost.ProviderHost
60
- | CursorKeychain.CursorKeychain;
58
+ | ProviderHost.ProviderHost;
59
60
export const CursorDriver: ProviderDriver<
61
CursorSettings,
@@ -74,12 +72,11 @@ export const CursorDriver: ProviderDriver<
72
usage: {
73
kind: "scan",
74
provider: "cursor",
77
- scan: ({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
75
+ scan: ({ instances, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
76
CursorUsageAccounts.CursorUsageAccounts.pipe(
77
Effect.flatMap((accounts) =>
78
accounts.scan({
79
instances,
82
- keychainUsageEnabled: settings.cursorKeychainUsageEnabled,
80
windowStartMs,
81
retentionCutoffMs,
82
awaitRefresh,
@@ -99,7 +96,6 @@ export const CursorDriver: ProviderDriver<
96
const fileSystem = yield* FileSystem.FileSystem;
97
const path = yield* Path.Path;
98
const httpClient = yield* HttpClient.HttpClient;
102
- const keychain = yield* CursorKeychain.CursorKeychain;
99
const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
100
const processEnv = yield* mergeProviderInstanceEnvironment(environment);
101
const continuationIdentity = defaultProviderContinuationIdentity({
@@ -233,22 +229,15 @@ export const CursorDriver: ProviderDriver<
229
snapshot.auth.status === "authenticated"
230
),
231
(snapshot) =>
236
- host.settings.get.pipe(
237
- Effect.flatMap((settings) =>
238
- readCursorUsageLimits(
239
- effectiveConfig,
240
- { ...processEnv, CURSOR_API_KEY: apiKey },
241
- settings.cursorKeychainUsageEnabled,
242
- ),
243
- ),
244
- Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
245
- ),
232
+ readCursorUsageLimits(effectiveConfig, {
233
+ ...processEnv,
234
+ CURSOR_API_KEY: apiKey,
235
+ }).pipe(Effect.map((usageLimits) => ({ ...snapshot, usageLimits }))),
236
),
237
),
238
),
239
Effect.provideService(FileSystem.FileSystem, fileSystem),
240
Effect.provideService(Path.Path, path),
251
- Effect.provideService(CursorKeychain.CursorKeychain, keychain),
241
Effect.map(stampSnapshot),
242
Effect.tap((provider) =>
243
Effect.sync(() => {
packages/provider-cursor/src/server/usageLimits.test.ts
+69
-207
@@ -1,25 +1,9 @@
1
import { describe, expect, it } from "@effect/vitest";
2
-import { NodeServices } from "@effect/platform-node";
3
-import * as HostProcess from "@t3tools/shared/HostProcess";
2
import * as Effect from "effect/Effect";
5
-import * as FileSystem from "effect/FileSystem";
6
-import * as Path from "effect/Path";
3
import * as HttpClient from "effect/http/HttpClient";
4
import * as HttpClientResponse from "effect/http/HttpClientResponse";
9
-import * as CursorKeychain from "./CursorKeychain.ts";
5
import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts";
6
12
-const withNodeServices = <A, E>(
13
- effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | CursorKeychain.CursorKeychain>,
14
- accessToken: CursorKeychain.CursorKeychain["Service"]["accessToken"] = Effect.die(
15
- "must not read Keychain",
16
- ),
17
-) =>
18
- effect.pipe(
19
- Effect.provideService(CursorKeychain.CursorKeychain, { accessToken }),
20
- Effect.provide(NodeServices.layer),
21
- );
22
-
7
describe("Cursor usage limits", () => {
8
const checkedAt = "2026-09-16T00:00:00.000Z";
9
@@ -70,227 +54,105 @@ describe("Cursor usage limits", () => {
54
).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 100 }]);
55
});
56
73
- it.effect("reads the instance's credentials and endpoint even when usage enabled is false", () =>
74
- withNodeServices(
75
- Effect.gen(function* () {
76
- const fs = yield* FileSystem.FileSystem;
77
- const path = yield* Path.Path;
78
- const directory = yield* fs.makeTempDirectoryScoped();
79
- yield* fs.makeDirectory(path.join(directory, "cursor"));
80
- yield* fs.writeFileString(
81
- path.join(directory, "cursor", "auth.json"),
82
- '{"accessToken":"instance-token"}',
83
- );
84
- const client = HttpClient.make((request) => {
85
- expect(request.url).toBe(
86
- "https://cursor.example/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
87
- );
88
- expect(request.method).toBe("POST");
89
- expect(request.headers.authorization).toBe("Bearer instance-token");
90
- expect(request.headers["connect-protocol-version"]).toBe("1");
91
- return Effect.succeed(
92
- HttpClientResponse.fromWeb(
93
- request,
94
- Response.json({ enabled: false, planUsage: { totalPercentUsed: 42 } }),
95
- ),
96
- );
97
- });
98
- yield* fs.makeDirectory(path.join(directory, ".cursor"));
99
- yield* fs.writeFileString(
100
- path.join(directory, ".cursor", "auth.json"),
101
- '{"accessToken":"instance-token"}',
102
- );
103
- for (const platform of ["linux", "darwin"] as const) {
104
- const limits = yield* readCursorUsageLimits(
105
- { apiEndpoint: "https://cursor.example/" },
106
- { XDG_CONFIG_HOME: directory, HOME: directory, AGENT_CLI_CREDENTIAL_STORE: "file" },
107
- ).pipe(
108
- Effect.provideService(HostProcess.Platform, platform),
109
- Effect.provideService(HttpClient.HttpClient, client),
110
- );
111
- expect(limits.windows[0]?.usedPercent).toBe(42);
112
- }
113
- }).pipe(Effect.scoped),
114
- ),
115
- );
116
-
117
- it.effect(
118
- "never reads stale files for keychain or memory logins, but accepts an explicit auth token",
119
- () =>
120
- Effect.gen(function* () {
121
- for (const platform of ["linux", "darwin"] as const) {
122
- for (const token of [undefined, "explicit-token"]) {
123
- const limits = yield* withNodeServices(
124
- readCursorUsageLimits(
125
- { apiEndpoint: "" },
126
- {
127
- AGENT_CLI_CREDENTIAL_STORE: platform === "linux" ? "memory" : "default",
128
- ...(token ? { CURSOR_AUTH_TOKEN: token } : {}),
129
- },
130
- false,
131
- ).pipe(
132
- Effect.provideService(HostProcess.Platform, platform),
133
- Effect.provideService(
134
- FileSystem.FileSystem,
135
- FileSystem.makeNoop({
136
- readFileString: () => Effect.die("must not read an unrelated credential file"),
137
- }),
138
- ),
139
- Effect.provideService(
140
- HttpClient.HttpClient,
141
- HttpClient.make((request) => {
142
- expect(token).toBe("explicit-token");
143
- expect(request.headers.authorization).toBe("Bearer explicit-token");
144
- return Effect.succeed(
145
- HttpClientResponse.fromWeb(
146
- request,
147
- Response.json({ planUsage: { totalPercentUsed: 10 } }),
148
- ),
149
- );
150
- }),
151
- ),
152
- ),
153
- );
154
- if (token) expect(limits.windows[0]?.usedPercent).toBe(10);
155
- else expect(limits.unavailable?.reason).toBe("unsupported");
156
- }
157
- }
158
- }),
159
- );
160
-
161
- it.effect("reports failed requests without exposing credentials or response bodies", () =>
57
+ it.effect("requires explicit credentials and accepts an auth token", () =>
58
Effect.gen(function* () {
163
- const limits = yield* withNodeServices(
164
- readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_AUTH_TOKEN: "private-token" }).pipe(
59
+ for (const token of [undefined, "explicit-token"]) {
60
+ const limits = yield* readCursorUsageLimits(
61
+ { apiEndpoint: "" },
62
+ token ? { CURSOR_AUTH_TOKEN: token } : {},
63
+ ).pipe(
64
Effect.provideService(
65
HttpClient.HttpClient,
167
- HttpClient.make((request) =>
168
- Effect.succeed(
66
+ HttpClient.make((request) => {
67
+ expect(token).toBe("explicit-token");
68
+ expect(request.headers.authorization).toBe("Bearer explicit-token");
69
+ return Effect.succeed(
70
HttpClientResponse.fromWeb(
71
request,
171
- new Response("private response", { status: 401 }),
72
+ Response.json({ planUsage: { totalPercentUsed: 10 } }),
73
),
173
- ),
174
- ),
175
- ),
176
- ),
177
- );
178
- expect(limits.unavailable).toEqual({
179
- reason: "probeFailed",
180
- message: "Cursor could not read usage limits.",
181
- });
182
- }),
183
- );
184
-
185
- it.effect("reads an API key's own account instead of a stored login", () =>
186
- Effect.gen(function* () {
187
- for (const platform of ["linux", "darwin"] as const) {
188
- const requests: Array<readonly [string, string | undefined]> = [];
189
- const limits = yield* withNodeServices(
190
- readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "api-key" }, true).pipe(
191
- Effect.provideService(HostProcess.Platform, platform),
192
- Effect.provideService(
193
- FileSystem.FileSystem,
194
- FileSystem.makeNoop({
195
- readFileString: () => Effect.die("must not read a stored login"),
196
- }),
197
- ),
198
- Effect.provideService(
199
- HttpClient.HttpClient,
200
- HttpClient.make((request) => {
201
- requests.push([request.url, request.headers.authorization]);
202
- return Effect.succeed(
203
- HttpClientResponse.fromWeb(
204
- request,
205
- Response.json(
206
- request.url.endsWith("/auth/exchange_user_api_key")
207
- ? { accessToken: "api-key-access-token" }
208
- : { planUsage: { totalPercentUsed: 37 } },
209
- ),
210
- ),
211
- );
212
- }),
213
- ),
74
+ );
75
+ }),
76
),
77
);
216
- expect(requests).toEqual([
217
- ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"],
218
- [
219
- "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
220
- "Bearer api-key-access-token",
221
- ],
222
- ]);
223
- expect(limits.windows[0]?.usedPercent).toBe(37);
78
+ if (token) expect(limits.windows[0]?.usedPercent).toBe(10);
79
+ else expect(limits.unavailable?.reason).toBe("unsupported");
80
}
81
}),
82
);
83
228
- it.effect("reads the default macOS Cursor login from Keychain for limits", () =>
84
+ it.effect("reports failed requests without exposing credentials or response bodies", () =>
85
Effect.gen(function* () {
230
- const limits = yield* withNodeServices(
231
- readCursorUsageLimits({ apiEndpoint: "" }, {}, true).pipe(
232
- Effect.provideService(HostProcess.Platform, "darwin"),
233
- Effect.provideService(
234
- FileSystem.FileSystem,
235
- FileSystem.makeNoop({
236
- readFileString: () => Effect.die("must not read a stale credential file"),
237
- }),
238
- ),
239
- Effect.provideService(
240
- HttpClient.HttpClient,
241
- HttpClient.make((request) => {
242
- expect(request.headers.authorization).toBe("Bearer keychain-token");
243
- return Effect.succeed(
244
- HttpClientResponse.fromWeb(
245
- request,
246
- Response.json({ planUsage: { totalPercentUsed: 42 } }),
247
- ),
248
- );
249
- }),
86
+ const limits = yield* readCursorUsageLimits(
87
+ { apiEndpoint: "" },
88
+ { CURSOR_AUTH_TOKEN: "private-token" },
89
+ ).pipe(
90
+ Effect.provideService(
91
+ HttpClient.HttpClient,
92
+ HttpClient.make((request) =>
93
+ Effect.succeed(
94
+ HttpClientResponse.fromWeb(
95
+ request,
96
+ new Response("private response", { status: 401 }),
97
+ ),
98
+ ),
99
),
100
),
252
- Effect.succeed("keychain-token"),
101
);
254
- expect(limits.windows[0]?.usedPercent).toBe(42);
102
+ expect(limits.unavailable).toEqual({
103
+ reason: "probeFailed",
104
+ message: "Cursor could not read usage limits.",
105
+ });
106
}),
107
);
108
258
- it.effect("reports a Keychain initialization failure without failing the provider refresh", () =>
109
+ it.effect("exchanges an API key to read its account limits", () =>
110
Effect.gen(function* () {
260
- const limits = yield* withNodeServices(
261
- readCursorUsageLimits({ apiEndpoint: "" }, {}, true).pipe(
262
- Effect.provideService(HostProcess.Platform, "darwin"),
263
- Effect.provideService(
264
- HttpClient.HttpClient,
265
- HttpClient.make(() => Effect.die("must not request limits without a login")),
266
- ),
267
- ),
268
- Effect.fail(
269
- new CursorKeychain.CursorKeychainReadError({
270
- cause: new Error("Keychain initialization failed"),
111
+ const requests: Array<readonly [string, string | undefined]> = [];
112
+ const limits = yield* readCursorUsageLimits(
113
+ { apiEndpoint: "" },
114
+ { CURSOR_API_KEY: "api-key" },
115
+ ).pipe(
116
+ Effect.provideService(
117
+ HttpClient.HttpClient,
118
+ HttpClient.make((request) => {
119
+ requests.push([request.url, request.headers.authorization]);
120
+ return Effect.succeed(
121
+ HttpClientResponse.fromWeb(
122
+ request,
123
+ Response.json(
124
+ request.url.endsWith("/auth/exchange_user_api_key")
125
+ ? { accessToken: "api-key-access-token" }
126
+ : { planUsage: { totalPercentUsed: 37 } },
127
+ ),
128
+ ),
129
+ );
130
}),
131
),
132
);
274
- expect(limits.unavailable?.reason).toBe("probeFailed");
133
+ expect(requests).toEqual([
134
+ ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"],
135
+ [
136
+ "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
137
+ "Bearer api-key-access-token",
138
+ ],
139
+ ]);
140
+ expect(limits.windows[0]?.usedPercent).toBe(37);
141
}),
142
);
143
278
- it.effect("does not send a Keychain login or API key to a custom endpoint", () =>
144
+ it.effect("does not send an API key to a custom endpoint", () =>
145
Effect.gen(function* () {
146
for (const [apiEndpoint, environment] of [
281
- ["http://localhost:3000", {}],
282
- ["", { CURSOR_API_ENDPOINT: "http://localhost:3000" }],
283
- ["https://cursor-proxy.example", {}],
284
- ["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example" }],
147
+ ["http://localhost:3000", { CURSOR_API_KEY: "api-key" }],
148
+ ["", { CURSOR_API_ENDPOINT: "http://localhost:3000", CURSOR_API_KEY: "api-key" }],
149
+ ["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example", CURSOR_API_KEY: "api-key" }],
150
["https://cursor-proxy.example", { CURSOR_API_KEY: "api-key" }],
151
] as const) {
287
- const limits = yield* withNodeServices(
288
- readCursorUsageLimits({ apiEndpoint }, environment, true).pipe(
289
- Effect.provideService(HostProcess.Platform, "darwin"),
290
- Effect.provideService(
291
- HttpClient.HttpClient,
292
- HttpClient.make(() => Effect.die("must not send a Keychain credential to a proxy")),
293
- ),
152
+ const limits = yield* readCursorUsageLimits({ apiEndpoint }, environment).pipe(
153
+ Effect.provideService(
154
+ HttpClient.HttpClient,
155
+ HttpClient.make(() => Effect.die("must not send an API key to a proxy")),
156
),
157
);
158
expect(limits.unavailable?.reason).toBe("unsupported");
packages/provider-cursor/src/server/usageLimits.ts
-53
@@ -1,12 +1,9 @@
1
import type { ServerProviderUsageWindow } from "@t3tools/contracts";
2
import type { CursorSettings } from "../settings.ts";
3
-import * as HostProcess from "@t3tools/shared/HostProcess";
3
import { CURSOR_USAGE_WINDOWS } from "@t3tools/shared/usageLimits";
4
import * as DateTime from "effect/DateTime";
5
import * as Effect from "effect/Effect";
7
-import * as FileSystem from "effect/FileSystem";
6
import * as Option from "effect/Option";
9
-import * as Path from "effect/Path";
7
import * as Schema from "effect/Schema";
8
import * as HttpClient from "effect/http/HttpClient";
9
import * as HttpClientRequest from "effect/http/HttpClientRequest";
@@ -17,10 +14,7 @@ import {
14
makeUsageLimits,
15
} from "@t3tools/provider-core/server/usageLimits";
16
import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
20
-import * as CursorKeychain from "./CursorKeychain.ts";
17
22
-const CursorCredentials = Schema.Struct({ accessToken: Schema.optional(Schema.String) });
23
-const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(CursorCredentials));
18
const CursorUsageResponse = Schema.Struct({
19
billingCycleEnd: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
20
planUsage: Schema.optional(
@@ -64,13 +58,9 @@ export function cursorUsageResponseToLimits(
58
export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function* (
59
settings: Pick<CursorSettings, "apiEndpoint">,
60
environment: NodeJS.ProcessEnv = process.env,
67
- allowKeychain = false,
61
) {
62
const checkedAt = DateTime.formatIso(yield* DateTime.now);
63
return yield* Effect.gen(function* () {
71
- const fs = yield* FileSystem.FileSystem;
72
- const path = yield* Path.Path;
73
- const platform = yield* HostProcess.Platform;
64
const endpoint = (
65
settings.apiEndpoint?.trim() ||
66
environment.CURSOR_API_ENDPOINT?.trim() ||
@@ -78,8 +68,6 @@ export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function
68
).replace(/\/$/, "");
69
let token = environment.CURSOR_AUTH_TOKEN?.trim();
70
const apiKey = environment.CURSOR_API_KEY?.trim();
81
- const credentialStore = environment.AGENT_CLI_CREDENTIAL_STORE;
82
- // An API key can name a different account from the stored login, so read the key's own.
71
if (!token && apiKey) {
72
if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) {
73
return makeUnavailableUsageLimits({
@@ -89,47 +77,6 @@ export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function
77
});
78
}
79
token = yield* exchangeCursorApiKey(apiKey);
92
- } else if (!token && credentialStore === "memory") {
93
- return makeUnavailableUsageLimits({
94
- checkedAt,
95
- reason: "unsupported",
96
- message: "Cursor usage requires a CLI login or CURSOR_AUTH_TOKEN.",
97
- });
98
- } else if (!token && platform === "darwin" && credentialStore !== "file") {
99
- if (!allowKeychain) {
100
- return makeUnavailableUsageLimits({
101
- checkedAt,
102
- reason: "unsupported",
103
- message: "Enable Cursor account usage in T3 Code to read its Keychain login.",
104
- });
105
- }
106
- if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) {
107
- return makeUnavailableUsageLimits({
108
- checkedAt,
109
- reason: "unsupported",
110
- message: "Cursor account usage requires the default Cursor endpoint when using Keychain.",
111
- });
112
- }
113
- const keychain = yield* CursorKeychain.CursorKeychain;
114
- token = (yield* keychain.accessToken)?.trim();
115
- } else if (!token) {
116
- const home =
117
- (platform === "win32" ? environment.USERPROFILE : environment.HOME) ||
118
- (yield* HostProcess.HomeDirectory);
119
- const directory =
120
- platform === "win32"
121
- ? path.join(environment.APPDATA || path.join(home, "AppData", "Roaming"), "Cursor")
122
- : platform === "darwin"
123
- ? path.join(home, ".cursor")
124
- : path.join(environment.XDG_CONFIG_HOME || path.join(home, ".config"), "cursor");
125
- const credentials = yield* fs.readFileString(path.join(directory, "auth.json")).pipe(
126
- Effect.catchTags({
127
- PlatformError: (error) =>
128
- error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
129
- }),
130
- Effect.flatMap(decodeCredentials),
131
- );
132
- token = credentials.accessToken?.trim();
80
}
81
if (!token) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
82
const client = yield* HttpClient.HttpClient;
packages/shared/src/usageFormat.test.ts
+1
-2
@@ -116,12 +116,11 @@ describe("usage source messages", () => {
116
]);
117
});
118
119
- it("omits empty missing sources, healthy sources, and diagnostics handled by an action", () => {
119
+ it("omits empty missing sources and healthy sources", () => {
120
expect(
121
usageSourceMessages([
122
malformedSource(0, { status: "missing" }),
123
malformedSource(1, { status: "ok" }),
124
- malformedSource(1, { action: "enableCursorKeychain" }),
124
]),
125
).toEqual([]);
126
expect(usageSourceMessages([])).toEqual([]);
packages/shared/src/usageFormat.ts
+4
-5
@@ -26,11 +26,10 @@ export function usageSourceMessages(sources: readonly UsageSource[]): readonly s
26
const malformedBySource = new Map<string, number>();
27
for (const source of sources) {
28
if (
29
- source.action ||
30
- (source.status !== "partial" &&
31
- source.status !== "failed" &&
32
- source.fingerprint.provider !== "cursor" &&
33
- !(source.status === "missing" && source.malformedRecords > 0))
29
+ source.status !== "partial" &&
30
+ source.status !== "failed" &&
31
+ source.fingerprint.provider !== "cursor" &&
32
+ !(source.status === "missing" && source.malformedRecords > 0)
33
) {
34
continue;
35
}
pnpm-lock.yaml
-3
@@ -1709,9 +1709,6 @@ importers:
1709
'@cursor/sdk':
1710
specifier: 1.2.0
1711
version: 1.2.0(zod@4.6.5)
1712
- '@napi-rs/keyring':
1713
- specifier: ^1.3.0
1714
- version: 1.3.0
1712
'@t3tools/contracts':
1713
specifier: workspace:*
1714
version: link:../contracts