Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageLimits.test.ts

301 lines11.3 KB

1import { describe, expect, it } from "@effect/vitest";
2import { NodeServices } from "@effect/platform-node";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as HttpClient from "effect/http/HttpClient";
8import * as HttpClientResponse from "effect/http/HttpClientResponse";
9import * as CursorKeychain from "./CursorKeychain.ts";
10import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts";
11​
12const 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​
23describe("Cursor usage limits", () => {
24 const checkedAt = "2026-09-16T00:00:00.000Z";
25​
26 it("uses the advertised percentages and billing-cycle reset", () => {
27 const limits = cursorUsageResponseToLimits(
28 {
29 billingCycleEnd: "1789876386000",
30 planUsage: { totalPercentUsed: 72.4, autoPercentUsed: 69.5, apiPercentUsed: 100 },
31 },
32 checkedAt,
33 );
34 expect(limits.windows).toEqual(
35 expect.arrayContaining([
36 {
37 id: "totalPercentUsed",
38 kind: "monthly",
39 label: "Overall",
40 usedPercent: 72.4,
41 resetsAt: "2026-09-20T03:53:06.000Z",
42 },
43 {
44 id: "autoPercentUsed",
45 kind: "monthly",
46 label: "Cursor Models",
47 usedPercent: 69.5,
48 resetsAt: "2026-09-20T03:53:06.000Z",
49 },
50 {
51 id: "apiPercentUsed",
52 kind: "monthly",
53 label: "Other Models",
54 usedPercent: 100,
55 resetsAt: "2026-09-20T03:53:06.000Z",
56 },
57 ]),
58 );
59 });
60​
61 it("does not invent unused allowance for absent buckets", () => {
62 expect(cursorUsageResponseToLimits({ planUsage: {} }, checkedAt).unavailable?.reason).toBe(
63 "unsupported",
64 );
65 expect(
66 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 0 } }, checkedAt).windows,
67 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 0 }]);
68 expect(
69 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 150 } }, checkedAt).windows,
70 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 100 }]);
71 });
72​
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", () =>
162 Effect.gen(function* () {
163 const limits = yield* withNodeServices(
164 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_AUTH_TOKEN: "private-token" }).pipe(
165 Effect.provideService(
166 HttpClient.HttpClient,
167 HttpClient.make((request) =>
168 Effect.succeed(
169 HttpClientResponse.fromWeb(
170 request,
171 new Response("private response", { status: 401 }),
172 ),
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 ),
214 ),
215 );
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);
224 }
225 }),
226 );
227​
228 it.effect("reads the default macOS Cursor login from Keychain for limits", () =>
229 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 }),
250 ),
251 ),
252 Effect.succeed("keychain-token"),
253 );
254 expect(limits.windows[0]?.usedPercent).toBe(42);
255 }),
256 );
257​
258 it.effect("reports a Keychain initialization failure without failing the provider refresh", () =>
259 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"),
271 }),
272 ),
273 );
274 expect(limits.unavailable?.reason).toBe("probeFailed");
275 }),
276 );
277​
278 it.effect("does not send a Keychain login or API key to a custom endpoint", () =>
279 Effect.gen(function* () {
280 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" }],
285 ["https://cursor-proxy.example", { CURSOR_API_KEY: "api-key" }],
286 ] 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 ),
294 ),
295 );
296 expect(limits.unavailable?.reason).toBe("unsupported");
297 expect(limits.unavailable?.message).toContain("default Cursor endpoint");
298 }
299 }),
300 );
301});