Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import { NodeServices } from "@effect/platform-node";
3import { HostProcessPlatform } 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 { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts";
10
11const withNodeServices = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>) =>
12 effect.pipe(Effect.provide(NodeServices.layer));
13
14describe("Cursor usage limits", () => {
15 const checkedAt = "2026-09-16T00:00:00.000Z";
16
17 it("uses the advertised percentages and billing-cycle reset", () => {
18 const limits = cursorUsageResponseToLimits(
19 {
20 billingCycleEnd: "1789876386000",
21 planUsage: { totalPercentUsed: 72.4, autoPercentUsed: 69.5, apiPercentUsed: 100 },
22 },
23 checkedAt,
24 );
25 expect(limits.windows).toEqual(
26 expect.arrayContaining([
27 {
28 id: "totalPercentUsed",
29 kind: "monthly",
30 label: "Overall",
31 usedPercent: 72.4,
32 resetsAt: "2026-09-20T03:53:06.000Z",
33 },
34 {
35 id: "autoPercentUsed",
36 kind: "monthly",
37 label: "Cursor Models",
38 usedPercent: 69.5,
39 resetsAt: "2026-09-20T03:53:06.000Z",
40 },
41 {
42 id: "apiPercentUsed",
43 kind: "monthly",
44 label: "Other Models",
45 usedPercent: 100,
46 resetsAt: "2026-09-20T03:53:06.000Z",
47 },
48 ]),
49 );
50 });
51
52 it("does not invent unused allowance for absent buckets", () => {
53 expect(cursorUsageResponseToLimits({ planUsage: {} }, checkedAt).unavailable?.reason).toBe(
54 "unsupported",
55 );
56 expect(
57 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 0 } }, checkedAt).windows,
58 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 0 }]);
59 expect(
60 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 150 } }, checkedAt).windows,
61 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 100 }]);
62 });
63
64 it.effect("reads the instance's credentials and endpoint even when usage enabled is false", () =>
65 Effect.gen(function* () {
66 yield* withNodeServices(
67 Effect.gen(function* () {
68 const fs = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const directory = yield* fs.makeTempDirectoryScoped();
71 yield* fs.makeDirectory(path.join(directory, "cursor"));
72 yield* fs.writeFileString(
73 path.join(directory, "cursor", "auth.json"),
74 '{"accessToken":"instance-token"}',
75 );
76 const client = HttpClient.make((request) => {
77 expect(request.url).toBe(
78 "https://cursor.example/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
79 );
80 expect(request.method).toBe("POST");
81 expect(request.headers.authorization).toBe("Bearer instance-token");
82 expect(request.headers["connect-protocol-version"]).toBe("1");
83 return Effect.succeed(
84 HttpClientResponse.fromWeb(
85 request,
86 Response.json({ enabled: false, planUsage: { totalPercentUsed: 42 } }),
87 ),
88 );
89 });
90 yield* fs.makeDirectory(path.join(directory, ".cursor"));
91 yield* fs.writeFileString(
92 path.join(directory, ".cursor", "auth.json"),
93 '{"accessToken":"instance-token"}',
94 );
95 for (const platform of ["linux", "darwin"] as const) {
96 const limits = yield* readCursorUsageLimits(
97 { apiEndpoint: "https://cursor.example/" },
98 { XDG_CONFIG_HOME: directory, HOME: directory, AGENT_CLI_CREDENTIAL_STORE: "file" },
99 ).pipe(
100 Effect.provideService(HostProcessPlatform, platform),
101 Effect.provideService(HttpClient.HttpClient, client),
102 );
103 expect(limits.windows[0]?.usedPercent).toBe(42);
104 }
105 }).pipe(Effect.scoped),
106 );
107 }),
108 );
109
110 it.effect(
111 "never reads stale files for keychain or memory logins, but accepts an explicit auth token",
112 () =>
113 Effect.gen(function* () {
114 for (const platform of ["linux", "darwin"] as const) {
115 for (const token of [undefined, "explicit-token"]) {
116 const limits = yield* withNodeServices(
117 readCursorUsageLimits(
118 { apiEndpoint: "" },
119 {
120 AGENT_CLI_CREDENTIAL_STORE: platform === "linux" ? "memory" : "default",
121 ...(token ? { CURSOR_AUTH_TOKEN: token } : {}),
122 },
123 false,
124 async () => {
125 throw new Error("must not read Keychain before opt-in");
126 },
127 ).pipe(
128 Effect.provideService(HostProcessPlatform, platform),
129 Effect.provideService(
130 FileSystem.FileSystem,
131 FileSystem.makeNoop({
132 readFileString: () => Effect.die("must not read an unrelated credential file"),
133 }),
134 ),
135 Effect.provideService(
136 HttpClient.HttpClient,
137 HttpClient.make((request) => {
138 expect(token).toBe("explicit-token");
139 expect(request.headers.authorization).toBe("Bearer explicit-token");
140 return Effect.succeed(
141 HttpClientResponse.fromWeb(
142 request,
143 Response.json({ planUsage: { totalPercentUsed: 10 } }),
144 ),
145 );
146 }),
147 ),
148 ),
149 );
150 if (token) expect(limits.windows[0]?.usedPercent).toBe(10);
151 else expect(limits.unavailable?.reason).toBe("unsupported");
152 }
153 }
154 }),
155 );
156
157 it.effect("reports failed requests without exposing credentials or response bodies", () =>
158 Effect.gen(function* () {
159 const limits = yield* withNodeServices(
160 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_AUTH_TOKEN: "private-token" }).pipe(
161 Effect.provideService(
162 HttpClient.HttpClient,
163 HttpClient.make((request) =>
164 Effect.succeed(
165 HttpClientResponse.fromWeb(
166 request,
167 new Response("private response", { status: 401 }),
168 ),
169 ),
170 ),
171 ),
172 ),
173 );
174 expect(limits.unavailable).toEqual({
175 reason: "probeFailed",
176 message: "Cursor could not read usage limits.",
177 });
178 }),
179 );
180
181 it.effect("does not use a stored login for an explicit API key", () =>
182 Effect.gen(function* () {
183 const limits = yield* withNodeServices(
184 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe(
185 Effect.provideService(
186 HttpClient.HttpClient,
187 HttpClient.make(() => Effect.die("must not request usage")),
188 ),
189 ),
190 );
191 expect(limits.unavailable?.reason).toBe("unsupported");
192 }),
193 );
194
195 it.effect("reads the default macOS Cursor login from Keychain for limits", () =>
196 Effect.gen(function* () {
197 const limits = yield* withNodeServices(
198 readCursorUsageLimits({ apiEndpoint: "" }, {}, true, async () => "keychain-token").pipe(
199 Effect.provideService(HostProcessPlatform, "darwin"),
200 Effect.provideService(
201 FileSystem.FileSystem,
202 FileSystem.makeNoop({
203 readFileString: () => Effect.die("must not read a stale credential file"),
204 }),
205 ),
206 Effect.provideService(
207 HttpClient.HttpClient,
208 HttpClient.make((request) => {
209 expect(request.headers.authorization).toBe("Bearer keychain-token");
210 return Effect.succeed(
211 HttpClientResponse.fromWeb(
212 request,
213 Response.json({ planUsage: { totalPercentUsed: 42 } }),
214 ),
215 );
216 }),
217 ),
218 ),
219 );
220 expect(limits.windows[0]?.usedPercent).toBe(42);
221 }),
222 );
223
224 it.effect("reports a Keychain initialization failure without failing the provider refresh", () =>
225 Effect.gen(function* () {
226 const limits = yield* withNodeServices(
227 readCursorUsageLimits({ apiEndpoint: "" }, {}, true, async () => {
228 throw new Error("Keychain initialization failed");
229 }).pipe(
230 Effect.provideService(HostProcessPlatform, "darwin"),
231 Effect.provideService(
232 HttpClient.HttpClient,
233 HttpClient.make(() => Effect.die("must not request limits without a login")),
234 ),
235 ),
236 );
237 expect(limits.unavailable?.reason).toBe("probeFailed");
238 }),
239 );
240
241 it.effect("does not read Keychain or send its token to a custom endpoint", () =>
242 Effect.gen(function* () {
243 for (const [apiEndpoint, environment] of [
244 ["http://localhost:3000", {}],
245 ["", { CURSOR_API_ENDPOINT: "http://localhost:3000" }],
246 ["https://cursor-proxy.example", {}],
247 ["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example" }],
248 ] as const) {
249 const limits = yield* withNodeServices(
250 readCursorUsageLimits({ apiEndpoint }, environment, true, async () => {
251 throw new Error("must not read Keychain for a custom endpoint");
252 }).pipe(
253 Effect.provideService(HostProcessPlatform, "darwin"),
254 Effect.provideService(
255 HttpClient.HttpClient,
256 HttpClient.make(() => Effect.die("must not send a Keychain credential to a proxy")),
257 ),
258 ),
259 );
260 expect(limits.unavailable?.reason).toBe("unsupported");
261 expect(limits.unavailable?.message).toContain("default Cursor endpoint");
262 }
263 }),
264 );
265});