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

accountUsage.test.ts

380 lines15.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as FetchHttpClient from "effect/http/FetchHttpClient";
7import * as HttpClient from "effect/http/HttpClient";
8import * as HttpClientError from "effect/http/HttpClientError";
9import * as HttpClientResponse from "effect/http/HttpClientResponse";
10import * as Path from "effect/Path";
11​
12import * as CursorKeychain from "./CursorKeychain.ts";
13import { readCursorAccountUsage } from "./accountUsage.ts";
14​
15const writeAuth = (accessToken: string) =>
16 Effect.gen(function* () {
17 const fileSystem = yield* FileSystem.FileSystem;
18 const path = yield* Path.Path;
19 const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "usage-reader-test-" });
20 const authPath = path.join(dir, "auth.json");
21 yield* fileSystem.writeFileString(authPath, JSON.stringify({ accessToken }));
22 return { dir, authPath };
23 });
24​
25interface DashboardRequest {
26 readonly url: string;
27 readonly init: RequestInit;
28 readonly page: number;
29 readonly headers: Headers;
31​
32const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Response>) =>
33 HttpClient.make((request, url, signal, fiber) =>
34 Effect.tryPromise({
35 try: async () => {
36 const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
37 const body =
38 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
39 const response = await answer({
40 url: url.toString(),
41 init: { ...init, signal, body },
42 page: JSON.parse(body).page,
43 headers: new Headers(request.headers),
44 });
45 return HttpClientResponse.fromWeb(request, response);
46 },
47 catch: (cause) =>
48 new HttpClientError.HttpClientError({
49 reason: new HttpClientError.TransportError({ request, cause }),
50 }),
51 }),
52 );
53​
54const readAccountUsage = (
55 credentialSource: Parameters<typeof readCursorAccountUsage>[0],
56 sinceMs: number,
57 endDate: number,
58 answer: (request: DashboardRequest) => Response | Promise<Response>,
59 keychainToken?: Parameters<typeof readCursorAccountUsage>[3],
60) =>
61 readCursorAccountUsage(credentialSource, sinceMs, endDate, keychainToken).pipe(
62 Effect.provideService(HttpClient.HttpClient, dashboard(answer)),
63 );
64​
65describe("Cursor account history", () => {
66 it.effect(
67 "reads paginated Cursor account history including headless calls with separate cache tokens",
68 () =>
69 Effect.gen(function* () {
70 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`;
71 const { authPath } = yield* writeAuth(accessToken);
72 const pages: number[] = [];
73 const signals: AbortSignal[] = [];
74 const request = ({ url, init, headers, page }: DashboardRequest) => {
75 assert.strictEqual(url, "https://cursor.com/api/dashboard/get-filtered-usage-events");
76 assert.strictEqual(init.redirect, "error");
77 assert.strictEqual(headers.get("origin"), "https://cursor.com");
78 assert.strictEqual(headers.get("content-type"), "application/json");
79 assert.include(headers.get("cookie") ?? "", "WorkosCursorSessionToken=demo%3A%3A");
80 const body = { page };
81 pages.push(body.page);
82 if (init.signal) signals.push(init.signal);
83 return Response.json({
84 totalUsageEventsCount: 1001,
85 usageEventsDisplay: Array.from({ length: body.page === 1 ? 1000 : 1 }, (_, index) => ({
86 timestamp: String(1780000000000 + ((body.page - 1) * 1000 + index) * 1000),
87 model: "claude-sonnet-4-5",
88 conversationId: `conversation-${body.page}`,
89 isHeadless: body.page === 2,
90 chargedCents: 0,
91 tokenUsage: {
92 inputTokens: 10,
93 outputTokens: 5,
94 cacheReadTokens: 30,
95 cacheWriteTokens: 2,
96 totalCents: 25,
97 },
98 })),
99 });
100 };
101 const result = yield* readAccountUsage(authPath, 0, 1781000000000, request);
102 assert.isNull(result.error);
103 assert.deepStrictEqual(pages, [1, 2]);
104 assert.lengthOf(signals, 2);
105 assert.notStrictEqual(signals[0], signals[1]);
106 assert.strictEqual(result.records.length, 1001);
107 assert.strictEqual(result.records.at(-1)?.sessionId, "conversation-2");
108 assert.deepStrictEqual(result.records[0]?.totals, {
109 uncachedInputTokens: 10,
110 cachedInputTokens: 30,
111 cacheCreationTokens: 2,
112 outputTokens: 5,
113 reasoningTokens: 0,
114 });
115 assert.strictEqual(result.records[0]?.reportedCostUsd, 0.25);
116 assert.isFalse(result.accountKey?.includes("demo") ?? true);
117 }).pipe(Effect.provide(NodeServices.layer)),
118 );
119​
120 it.effect("reads Cursor account history beyond 100 pages", () =>
121 Effect.gen(function* () {
122 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
123 const { authPath } = yield* writeAuth(accessToken);
124 const fullPage = Array.from({ length: 1000 }, () => ({ tokenUsage: null }));
125 let requests = 0;
126 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
127 requests += 1;
128 return Response.json({
129 totalUsageEventsCount: 100_001,
130 usageEventsDisplay: requests <= 100 ? fullPage : [{ tokenUsage: null }],
131 });
132 });
133 assert.isNull(result.error);
134 assert.strictEqual(requests, 101);
135 assert.deepStrictEqual(result.records, []);
136 }).pipe(Effect.provide(NodeServices.layer)),
137 );
138​
139 it.effect("accepts confirmed empty Cursor usage but rejects error envelopes", () =>
140 Effect.gen(function* () {
141 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
142 const { authPath } = yield* writeAuth(accessToken);
143 for (const body of [
144 {},
145 { totalUsageEventsCount: 0 },
146 { totalUsageEventsCount: 0, usageEventsDisplay: [] },
147 ]) {
148 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
149 Response.json(body),
150 );
151 assert.isNull(result.error);
152 assert.deepStrictEqual(result.records, []);
153 assert.isFalse(result.missing);
154 }
155 for (const body of [
156 { error: "upstream error" },
157 { detail: "unknown error envelope" },
158 { totalUsageEventsCount: 0, error: "upstream error" },
159 null,
160 [],
161 "invalid",
162 0,
163 ]) {
164 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
165 Response.json(body),
166 );
167 assert.isNotNull(result.error);
168 assert.deepStrictEqual(result.records, []);
169 }
170 }).pipe(Effect.provide(NodeServices.layer)),
171 );
172​
173 it.effect("requires a terminal Cursor page after a full page reaches the reported count", () =>
174 Effect.gen(function* () {
175 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
176 const { authPath } = yield* writeAuth(accessToken);
177 let requests = 0;
178 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
179 requests++;
180 return Response.json(
181 requests === 1
182 ? {
183 totalUsageEventsCount: 1000,
184 usageEventsDisplay: Array.from({ length: 1000 }, (_, index) => ({
185 timestamp: String(1780000000000 + index),
186 model: "gpt-5",
187 tokenUsage: { inputTokens: 10, outputTokens: 5 },
188 })),
189 }
190 : { totalUsageEventsCount: 1000 },
191 );
192 });
193 assert.isNull(result.error);
194 assert.strictEqual(result.records.length, 1000);
195 assert.strictEqual(requests, 2);
196 }).pipe(Effect.provide(NodeServices.layer)),
197 );
198​
199 it.effect(
200 "removes only count-proven Cursor boundary copies and preserves identical billed events",
201 () =>
202 Effect.gen(function* () {
203 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
204 const { authPath } = yield* writeAuth(accessToken);
205 const event = (index: number) => ({
206 timestamp: String(1780000000000 + index),
207 model: "gpt-5",
208 tokenUsage: { inputTokens: 10, outputTokens: 5, totalCents: 1 },
209 });
210 for (const total of [2000, 2001]) {
211 let requests = 0;
212 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
213 requests++;
214 return Response.json({
215 totalUsageEventsCount: total,
216 usageEventsDisplay:
217 requests === 1
218 ? Array.from({ length: 1000 }, (_, index) => event(index))
219 : requests === 2
220 ? Array.from({ length: 1000 }, (_, index) => event(999 + index))
221 : [event(1999)],
222 });
223 });
224 assert.isNull(result.error);
225 assert.strictEqual(result.records.length, total);
226 assert.strictEqual(requests, 3);
227 assert.strictEqual(result.records.at(-1)?.timestampMs, 1780000001999);
228 assert.strictEqual(
229 result.records.filter((record) => record.timestampMs === 1780000000999).length,
230 total === 2000 ? 1 : 2,
231 );
232 assert.strictEqual(new Set(result.records.map((record) => record.dedupeKey)).size, total);
233 }
234 let requests = 0;
235 const inconsistent = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
236 requests++;
237 return Response.json({
238 totalUsageEventsCount: 1001,
239 usageEventsDisplay:
240 requests === 1
241 ? Array.from({ length: 1000 }, (_, index) => event(index))
242 : [event(500), event(1000)],
243 });
244 });
245 assert.isNotNull(inconsistent.error);
246 assert.deepStrictEqual(inconsistent.records, []);
247 }).pipe(Effect.provide(NodeServices.layer)),
248 );
249​
250 it.effect(
251 "does not present truncated Cursor account pages or authentication failures as complete history",
252 () =>
253 Effect.gen(function* () {
254 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`;
255 const { dir, authPath } = yield* writeAuth(accessToken);
256 const truncated = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
257 Response.json({ totalUsageEventsCount: 101, usageEventsDisplay: [] }),
258 );
259 assert.isNotNull(truncated.error);
260 assert.deepStrictEqual(truncated.records, []);
261 const denied = yield* readAccountUsage(
262 authPath,
263 0,
264 1781000000000,
265 async () => new Response(accessToken, { status: 401 }),
266 );
267 assert.isNotNull(denied.error);
268 assert.isFalse(denied.error?.includes(accessToken) ?? true);
269 assert.deepStrictEqual(denied.records, []);
270 let requested = false;
271 const missing = yield* readAccountUsage(
272 (yield* Path.Path).join(dir, "missing.json"),
273 0,
274 1781000000000,
275 async () => {
276 requested = true;
277 return Response.json({});
278 },
279 );
280 assert.isTrue(missing.missing);
281 assert.isFalse(requested);
282 }).pipe(Effect.provide(NodeServices.layer)),
283 );
284});
285​
286describe("readCursorAccountUsage", () => {
287 it.effect("asks for Keychain approval when the prompt goes unanswered", () =>
288 Effect.gen(function* () {
289 const result = yield* readAccountUsage(
290 { kind: "keychain" },
291 0,
292 1,
293 () => {
294 throw new Error("no network expected");
295 },
296 Effect.fail(new CursorKeychain.CursorKeychainTimeoutError()),
297 );
298 assert.deepStrictEqual(result, {
299 accountKey: null,
300 records: [],
301 missing: false,
302 error: "Allow Keychain access on the Mac running T3 Code, then refresh.",
303 });
304 }).pipe(Effect.provide(NodeServices.layer)),
305 );
306​
307 it.effect("reads the pages behind the first together and keeps them in page order", () =>
308 Effect.gen(function* () {
309 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
310 let inFlight = 0;
311 let mostInFlight = 0;
312 const result = yield* readAccountUsage(
313 { kind: "keychain" },
314 0,
315 1781000000000,
316 async ({ page }) => {
317 inFlight++;
318 mostInFlight = Math.max(mostInFlight, inFlight);
319 for (let turn = page; turn < 9; turn++) await Promise.resolve();
320 inFlight--;
321 return Response.json({
322 totalUsageEventsCount: 8001,
323 usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({
324 timestamp: String(1780000000000 + (page - 1) * 1000 + index),
325 model: "gpt-5",
326 tokenUsage: { inputTokens: 1 },
327 })),
328 });
329 },
330 Effect.succeed(accessToken),
331 );
332 assert.isNull(result.error);
333 assert.strictEqual(mostInFlight, 6);
334 assert.deepStrictEqual(
335 result.records.map((record) => record.timestampMs),
336 Array.from({ length: 8001 }, (_, index) => 1780000000000 + index),
337 );
338 }).pipe(Effect.provide(NodeServices.layer)),
339 );
340​
341 it.effect("ends like a page-by-page read when a page fails, leaving no request open", () =>
342 Effect.gen(function* () {
343 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
344 const fullPage = {
345 totalUsageEventsCount: 8001,
346 usageEventsDisplay: Array.from({ length: 1000 }, () => ({ tokenUsage: null })),
347 };
348 for (const [secondPage, error] of [
349 [() => Response.json(fullPage), "Cursor account usage could not be read."],
350 [
351 () => new Response(null, { status: 401 }),
352 "Sign in to Cursor again to read account usage.",
353 ],
354 ] as const) {
355 let open = 0;
356 const result = yield* readAccountUsage(
357 { kind: "keychain" },
358 0,
359 1781000000000,
360 ({ init, page }) => {
361 if (page === 1) return Promise.resolve(Response.json(fullPage));
362 if (page === 2) return Promise.resolve(secondPage());
363 if (page === 3) return Promise.reject(new Error("connection reset"));
364 open++;
365 return new Promise((_resolve, reject) => {
366 init.signal?.addEventListener("abort", () => {
367 open--;
368 reject(init.signal?.reason);
369 });
370 });
371 },
372 Effect.succeed(accessToken),
373 );
374 assert.strictEqual(result.error, error);
375 assert.deepStrictEqual(result.records, []);
376 assert.strictEqual(open, 0);
377 }
378 }).pipe(Effect.provide(NodeServices.layer)),
379 );
380});