Skip to content

Commit f424f4d

Browse files
fix(cursor): show usage limits for browser sign-in
Browser sign-in stores a user API key. The limits reader treated that key as an explicit API key and returned unsupported before asking Cursor, so Usage → Limits omitted Cursor. Exchange the saved login for an access token and read that account's plan windows. Co-authored-by: Cursor <[email protected]>
1 parent 9826dbb commit f424f4d

5 files changed

Lines changed: 322 additions & 25 deletions

File tree

‎packages/provider-cursor/src/server/auth.ts‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,19 @@ interface AuthFlow {
2929
fiber?: Fiber.Fiber<void>;
3030
}
3131

32+
/** A Cursor login saved by T3's browser sign-in, as opposed to a configured API key. */
33+
export type CursorStoredLogin =
34+
| {
35+
readonly status: "valid";
36+
readonly apiKey: string;
37+
readonly backendUrl: string;
38+
}
39+
| { readonly status: "expired" };
40+
3241
export interface CursorAuth {
3342
readonly controller: ProviderAuthController;
3443
readonly readApiKey: Effect.Effect<string | undefined, ProviderSetupError>;
44+
readonly readStoredLogin: Effect.Effect<CursorStoredLogin | undefined, ProviderSetupError>;
3545
readonly requireApiKey: Effect.Effect<string, ProviderSetupError>;
3646
readonly usesApiKey: boolean;
3747
readonly withAccess: <A, E, R>(
@@ -74,8 +84,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
7484
state: { ...current.state, ...patch },
7585
}));
7686

77-
const readApiKey = Effect.gen(function* () {
78-
if (configuredKey) return configuredKey;
87+
const readStoredLogin: CursorAuth["readStoredLogin"] = Effect.gen(function* () {
7988
const credentials = yield* Effect.tryPromise({
8089
try: () => options.store.load(),
8190
catch: (cause) =>
@@ -86,13 +95,24 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
8695
cause,
8796
}),
8897
});
98+
if (!credentials) return undefined;
8999
const now = yield* Clock.currentTimeMillis;
90-
return credentials &&
91-
(credentials.apiKeyExpiresAtMs === undefined || credentials.apiKeyExpiresAtMs > now)
92-
? credentials.apiKey
93-
: undefined;
100+
if (credentials.apiKeyExpiresAtMs !== undefined && credentials.apiKeyExpiresAtMs <= now) {
101+
return { status: "expired" };
102+
}
103+
return {
104+
status: "valid",
105+
apiKey: credentials.apiKey,
106+
backendUrl: credentials.backendUrl,
107+
};
94108
});
95109

110+
const readApiKey = configuredKey
111+
? Effect.succeed(configuredKey)
112+
: readStoredLogin.pipe(
113+
Effect.map((login) => (login?.status === "valid" ? login.apiKey : undefined)),
114+
);
115+
96116
const requireApiKey = Effect.gen(function* () {
97117
if (operation !== "idle") {
98118
return yield* new ProviderSetupError({
@@ -497,6 +517,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
497517
return {
498518
controller,
499519
readApiKey,
520+
readStoredLogin,
500521
requireApiKey,
501522
withAccess,
502523
usesApiKey: configuredKey !== undefined,

‎packages/provider-cursor/src/server/driver.test.ts‎

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import * as Layer from "effect/Layer";
2020
import * as Option from "effect/Option";
2121
import * as Stream from "effect/Stream";
2222
import { vi } from "vite-plus/test";
23+
import * as HttpClientResponse from "effect/http/HttpClientResponse";
2324
import * as HttpClient from "effect/http/HttpClient";
2425

2526
import {
@@ -29,6 +30,7 @@ import {
2930
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
3031
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
3132
import { CursorDriver } from "./driver.ts";
33+
import { makeCursorCredentialStore } from "./credentialStore.ts";
3234
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
3335
import * as CursorSdk from "./CursorSdk.ts";
3436
import * as CursorKeychain from "./CursorKeychain.ts";
@@ -107,7 +109,30 @@ it.layer(layerTest)("CursorDriver", (it) => {
107109
};
108110
const openedKeys: Array<string | undefined> = [];
109111
let closed = 0;
112+
const requests: string[] = [];
113+
let failureUrl: string | undefined;
114+
let failureStatus = 500;
115+
const usageClient = HttpClient.make((request) => {
116+
requests.push(request.url);
117+
const exchange = request.url.endsWith("/auth/exchange_user_api_key");
118+
expect(request.headers.authorization).toBe(
119+
exchange ? "Bearer instance-browser-key" : "Bearer browser-access-token",
120+
);
121+
return Effect.succeed(
122+
HttpClientResponse.fromWeb(
123+
request,
124+
request.url === failureUrl
125+
? new Response(null, { status: failureStatus })
126+
: Response.json(
127+
exchange
128+
? { accessToken: "browser-access-token" }
129+
: { planUsage: { totalPercentUsed: 23 } },
130+
),
131+
),
132+
);
133+
});
110134
const instance = yield* CursorDriver.create(input).pipe(
135+
Effect.provideService(HttpClient.HttpClient, usageClient),
111136
Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
112137
assertComplete: Effect.void,
113138
open: (request) =>
@@ -134,6 +159,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
134159
expect(me).toHaveBeenCalledWith({ apiKey: "instance-browser-key" });
135160
expect(yield* instance.snapshot.getSnapshot).toMatchObject({
136161
status: "ready",
162+
usageLimits: { windows: [{ id: "totalPercentUsed", usedPercent: 23 }] },
137163
auth: {
138164
status: "authenticated",
139165
type: "browser",
@@ -158,8 +184,43 @@ it.layer(layerTest)("CursorDriver", (it) => {
158184
yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
159185
expect(openedKeys).toEqual(["instance-browser-key"]);
160186
expect(closed).toBe(0);
161-
const recreated = yield* CursorDriver.create(input);
187+
expect(requests.slice(0, 2)).toEqual([
188+
"https://api2.cursor.sh/auth/exchange_user_api_key",
189+
"https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
190+
]);
191+
const recreated = yield* CursorDriver.create(input).pipe(
192+
Effect.provideService(HttpClient.HttpClient, usageClient),
193+
);
162194
expect((yield* recreated.snapshot.refresh).auth.status).toBe("authenticated");
195+
for (const url of requests.slice(0, 2)) {
196+
failureUrl = url;
197+
const snapshot = yield* instance.snapshot.refresh;
198+
expect(snapshot).toMatchObject({
199+
status: "ready",
200+
auth: { status: "authenticated" },
201+
usageLimits: { windows: [{ id: "totalPercentUsed", usedPercent: 23 }] },
202+
});
203+
expect(snapshot.message).toBeUndefined();
204+
}
205+
failureUrl = requests[0];
206+
failureStatus = 401;
207+
expect(yield* instance.snapshot.refresh).toMatchObject({
208+
status: "ready",
209+
auth: { status: "authenticated" },
210+
usageLimits: { windows: [], unavailable: { reason: "unsupported" } },
211+
});
212+
failureUrl = undefined;
213+
expect((yield* instance.snapshot.refresh).usageLimits?.windows[0]?.usedPercent).toBe(23);
214+
const { store } = yield* makeCursorCredentialStore(input.instanceId);
215+
yield* Effect.promise(async () => {
216+
const credentials = await store.load();
217+
await store.save({ ...credentials!, apiKeyExpiresAtMs: 0 });
218+
});
219+
const requestCount = requests.length;
220+
const expired = yield* instance.snapshot.refresh;
221+
expect(expired.auth.status).toBe("unauthenticated");
222+
expect(expired.usageLimits).toBeUndefined();
223+
expect(requests).toHaveLength(requestCount);
163224
yield* instance.auth!.logout(Effect.void);
164225
expect(closed).toBe(1);
165226
expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unauthenticated");
@@ -173,6 +234,56 @@ it.layer(layerTest)("CursorDriver", (it) => {
173234
}).pipe(Effect.scoped),
174235
);
175236

237+
it.effect(
238+
"keeps a configured CURSOR_API_KEY instance off its stored browser login for limits",
239+
() =>
240+
Effect.gen(function* () {
241+
const me = vi.spyOn(Cursor, "me").mockResolvedValue({
242+
apiKeyName: "Configured key",
243+
createdAt: "2026-01-01T00:00:00.000Z",
244+
});
245+
const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]);
246+
yield* Effect.addFinalizer(() =>
247+
Effect.sync(() => {
248+
me.mockRestore();
249+
models.mockRestore();
250+
}),
251+
);
252+
const instanceId = ProviderInstanceId.make("cursor-configured-key-with-login");
253+
const { store } = yield* makeCursorCredentialStore(instanceId);
254+
yield* Effect.promise(() =>
255+
store.save({
256+
version: 1,
257+
backendUrl: "https://api2.cursor.sh",
258+
apiKey: "stored-browser-key",
259+
createdAtMs: 0,
260+
apiKeyExpiresAtMs: 4_000_000_000_000,
261+
}),
262+
);
263+
const requests: string[] = [];
264+
const instance = yield* CursorDriver.create({
265+
instanceId,
266+
displayName: "Configured Cursor",
267+
enabled: true,
268+
environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }],
269+
config: CursorDriver.defaultConfig(),
270+
}).pipe(
271+
Effect.provideService(
272+
HttpClient.HttpClient,
273+
HttpClient.make((request) => {
274+
requests.push(request.url);
275+
return Effect.die("must not exchange credentials or request usage");
276+
}),
277+
),
278+
);
279+
expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe(
280+
"unsupported",
281+
);
282+
expect(requests).toEqual([]);
283+
expect(me).toHaveBeenCalledWith({ apiKey: "configured-key" });
284+
}).pipe(Effect.scoped),
285+
);
286+
176287
it.effect("budgets handoffs for the SDK model across catalog refreshes and option changes", () =>
177288
Effect.gen(function* () {
178289
const fileSystem = yield* FileSystem.FileSystem;

‎packages/provider-cursor/src/server/driver.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,9 +213,18 @@ export const CursorDriver: ProviderDriver<
213213
auth.withAccess,
214214
);
215215

216-
const checkProvider = auth.readApiKey.pipe(
217-
Effect.orElseSucceed(() => undefined),
218-
Effect.flatMap((apiKey) =>
216+
const checkProvider = Effect.gen(function* () {
217+
const storedLogin = auth.usesApiKey
218+
? undefined
219+
: yield* auth.readStoredLogin.pipe(Effect.orElseSucceed(() => undefined));
220+
const apiKey = auth.usesApiKey
221+
? yield* auth.readApiKey.pipe(Effect.orElseSucceed(() => undefined))
222+
: storedLogin?.status === "valid"
223+
? storedLogin.apiKey
224+
: undefined;
225+
return { storedLogin, apiKey };
226+
}).pipe(
227+
Effect.flatMap(({ storedLogin, apiKey }) =>
219228
checkCursorProviderStatus(
220229
effectiveConfig,
221230
{
@@ -238,6 +247,7 @@ export const CursorDriver: ProviderDriver<
238247
effectiveConfig,
239248
{ ...processEnv, CURSOR_API_KEY: apiKey },
240249
settings.cursorKeychainUsageEnabled,
250+
storedLogin,
241251
),
242252
),
243253
Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),

‎packages/provider-cursor/src/server/usageLimits.test.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
55
import * as FileSystem from "effect/FileSystem";
66
import * as Path from "effect/Path";
77
import * as HttpClient from "effect/http/HttpClient";
8+
import type * as HttpClientRequest from "effect/http/HttpClientRequest";
89
import * as HttpClientResponse from "effect/http/HttpClientResponse";
910
import * as CursorKeychain from "./CursorKeychain.ts";
1011
import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts";
@@ -268,4 +269,103 @@ describe("Cursor usage limits", () => {
268269
}
269270
}),
270271
);
272+
273+
describe("T3 browser login", () => {
274+
const exchangeUrl = "https://instance.example/auth/exchange_user_api_key";
275+
const usageUrl = "https://instance.example/aiserver.v1.DashboardService/GetCurrentPeriodUsage";
276+
const login = {
277+
status: "valid",
278+
apiKey: "stored-browser-key",
279+
backendUrl: "https://instance.example/path",
280+
} as const;
281+
// A stored login names this instance's account, so host CLI files and Keychain must stay untouched.
282+
const readWithLogin = (
283+
storedLogin: Parameters<typeof readCursorUsageLimits>[3],
284+
respond: (request: HttpClientRequest.HttpClientRequest) => Response,
285+
) => {
286+
const requests: Array<{
287+
url: string;
288+
authorization: string | undefined;
289+
body: string | null;
290+
}> = [];
291+
const read = withNodeServices(
292+
readCursorUsageLimits(
293+
{ apiEndpoint: "https://settings.example" },
294+
{ CURSOR_AUTH_TOKEN: "other-host-account-token" },
295+
true,
296+
storedLogin,
297+
).pipe(
298+
Effect.provideService(HostProcess.Platform, "darwin"),
299+
Effect.provideService(
300+
FileSystem.FileSystem,
301+
FileSystem.makeNoop({
302+
readFileString: () => Effect.die("must not read the host CLI login"),
303+
}),
304+
),
305+
Effect.provideService(
306+
HttpClient.HttpClient,
307+
HttpClient.make((request) => {
308+
requests.push({
309+
url: request.url,
310+
authorization: request.headers.authorization,
311+
body:
312+
request.body._tag === "Uint8Array"
313+
? new TextDecoder().decode(request.body.body)
314+
: null,
315+
});
316+
return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
317+
}),
318+
),
319+
),
320+
);
321+
return { read, requests };
322+
};
323+
324+
it.effect(
325+
"exchanges the stored key at the stored backend and reads usage with the result",
326+
() =>
327+
Effect.gen(function* () {
328+
const { read, requests } = readWithLogin(login, (request) =>
329+
request.url === exchangeUrl
330+
? Response.json({ accessToken: "exchanged-access-token" })
331+
: Response.json({ planUsage: { totalPercentUsed: 37 } }),
332+
);
333+
expect((yield* read).windows[0]?.usedPercent).toBe(37);
334+
expect(requests).toEqual([
335+
{ url: exchangeUrl, authorization: "Bearer stored-browser-key", body: "{}" },
336+
{ url: usageUrl, authorization: "Bearer exchanged-access-token", body: "{}" },
337+
]);
338+
}),
339+
);
340+
341+
it.effect(
342+
"clears expired or rejected login usage and reports transient failures without using host logins",
343+
() =>
344+
Effect.gen(function* () {
345+
const expired = readWithLogin({ status: "expired" }, () => {
346+
throw new Error("must not request usage for an expired login");
347+
});
348+
const rejected = readWithLogin(login, () => new Response("rejected", { status: 401 }));
349+
for (const { read } of [expired, rejected]) {
350+
expect(yield* read).toMatchObject({
351+
windows: [],
352+
unavailable: {
353+
reason: "unsupported",
354+
message: expect.stringContaining("Sign in again"),
355+
},
356+
});
357+
}
358+
for (const failedUrl of [exchangeUrl, usageUrl]) {
359+
const transient = readWithLogin(login, (request) =>
360+
request.url === failedUrl
361+
? new Response(null, { status: 500 })
362+
: Response.json({ accessToken: "exchanged-access-token" }),
363+
);
364+
expect((yield* transient.read).unavailable?.reason).toBe("probeFailed");
365+
}
366+
expect(expired.requests).toEqual([]);
367+
expect(rejected.requests.map((request) => request.url)).toEqual([exchangeUrl]);
368+
}),
369+
);
370+
});
271371
});

0 commit comments

Comments
 (0)