@@ -2,6 +2,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
2 | 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
3 | 3 | import * as Layer from "effect/Layer"; |
4 | 4 | import { assert, describe, it } from "@effect/vitest"; |
| 5 | +import * as Deferred from "effect/Deferred"; |
| 6 | +import * as Queue from "effect/Queue"; |
5 | 7 | import * as Context from "effect/Context"; |
6 | 8 | import * as Effect from "effect/Effect"; |
7 | 9 | import * as Fiber from "effect/Fiber"; |
@@ -11,7 +13,10 @@ import * as HttpClientError from "effect/http/HttpClientError"; |
11 | 13 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
12 | 14 | import * as TestClock from "effect/testing/TestClock"; |
13 | 15 |
|
14 | | -import { readCursorAccountUsage } from "./accountUsage.ts"; |
| 16 | +import * as CursorAccountReader from "./CursorAccountReader.ts"; |
| 17 | + |
| 18 | +import { makeCursorAccountUsageReader } from "./accountUsage.ts"; |
| 19 | +import type { CursorCredentialSource } from "./accountCache.ts"; |
15 | 20 |
|
16 | 21 | interface DashboardRequest { |
17 | 22 | readonly url: string; |
@@ -20,7 +25,10 @@ interface DashboardRequest { |
20 | 25 | readonly headers: Headers; |
21 | 26 | } |
22 | 27 |
|
23 | | -const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Response>) => |
| 28 | +const dashboard = ( |
| 29 | + answer: (request: DashboardRequest) => Response | Promise<Response>, |
| 30 | + membership = { userId: 1, teamIds: [] as number[] }, |
| 31 | +) => |
24 | 32 | HttpClient.make((request, url, signal, fiber) => |
25 | 33 | Effect.tryPromise({ |
26 | 34 | try: async () => { |
@@ -36,6 +44,15 @@ const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Res |
36 | 44 | Response.json({ accessToken: request.headers.authorization.slice(7) }), |
37 | 45 | ); |
38 | 46 | } |
| 47 | + if (url.pathname.endsWith("/GetMe")) { |
| 48 | + return HttpClientResponse.fromWeb(request, Response.json({ userId: membership.userId })); |
| 49 | + } |
| 50 | + if (url.pathname.endsWith("/GetTeams")) { |
| 51 | + return HttpClientResponse.fromWeb( |
| 52 | + request, |
| 53 | + Response.json({ teams: membership.teamIds.map((id) => ({ id })) }), |
| 54 | + ); |
| 55 | + } |
39 | 56 | const response = await answer({ |
40 | 57 | url: url.toString(), |
41 | 58 | init: { ...init, signal, body }, |
@@ -52,13 +69,15 @@ const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Res |
52 | 69 | ); |
53 | 70 |
|
54 | 71 | const readAccountUsage = ( |
55 | | - credentialSource: Parameters<typeof readCursorAccountUsage>[0], |
| 72 | + credentialSource: CursorCredentialSource, |
56 | 73 | sinceMs: number, |
57 | 74 | endDate: number, |
58 | 75 | answer: (request: DashboardRequest) => Response | Promise<Response>, |
| 76 | + membership?: { userId: number; teamIds: number[] }, |
59 | 77 | ) => |
60 | | - readCursorAccountUsage(credentialSource, sinceMs, endDate).pipe( |
61 | | - Effect.provideService(HttpClient.HttpClient, dashboard(answer)), |
| 78 | + makeCursorAccountUsageReader.pipe( |
| 79 | + Effect.flatMap((read) => read(credentialSource, sinceMs, endDate)), |
| 80 | + Effect.provideService(HttpClient.HttpClient, dashboard(answer, membership)), |
62 | 81 | ); |
63 | 82 |
|
64 | 83 | describe("Cursor account history", () => { |
@@ -123,6 +142,157 @@ describe("Cursor account history", () => { |
123 | 142 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
124 | 143 | ); |
125 | 144 |
|
| 145 | + it.effect("includes each team's own-user history alongside personal history", () => |
| 146 | + Effect.gen(function* () { |
| 147 | + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 148 | + const scopes: unknown[] = []; |
| 149 | + const result = yield* readAccountUsage( |
| 150 | + { kind: "apiKey", apiKey: accessToken }, |
| 151 | + 0, |
| 152 | + 1781000000000, |
| 153 | + async ({ init }) => { |
| 154 | + const body = JSON.parse(String(init.body)); |
| 155 | + scopes.push([body.teamId, body.userId]); |
| 156 | + const team = body.teamId !== undefined; |
| 157 | + return Response.json({ |
| 158 | + totalUsageEventsCount: 1, |
| 159 | + usageEventsDisplay: [ |
| 160 | + { |
| 161 | + timestamp: "1780000000000", |
| 162 | + model: "gpt-5", |
| 163 | + conversationId: "same-conversation", |
| 164 | + tokenUsage: { cacheReadTokens: team ? 5_000_000 : 10 }, |
| 165 | + }, |
| 166 | + ], |
| 167 | + }); |
| 168 | + }, |
| 169 | + { userId: 42, teamIds: [7, 8, 7] }, |
| 170 | + ); |
| 171 | + assert.isNull(result.error); |
| 172 | + assert.deepStrictEqual(scopes, [ |
| 173 | + [undefined, undefined], |
| 174 | + [7, 42], |
| 175 | + [8, 42], |
| 176 | + ]); |
| 177 | + assert.strictEqual( |
| 178 | + result.records.reduce((sum, row) => sum + row.totals.cachedInputTokens, 0), |
| 179 | + 10_000_010, |
| 180 | + ); |
| 181 | + assert.strictEqual(new Set(result.records.map((row) => row.dedupeKey)).size, 3); |
| 182 | + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 183 | + ); |
| 184 | + |
| 185 | + it.effect("rejects unscoped or incomplete team history without keeping personal totals", () => |
| 186 | + Effect.gen(function* () { |
| 187 | + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 188 | + for (const userId of [0, 42]) { |
| 189 | + const scopes: unknown[] = []; |
| 190 | + const result = yield* readAccountUsage( |
| 191 | + { kind: "apiKey", apiKey: accessToken }, |
| 192 | + 0, |
| 193 | + 1781000000000, |
| 194 | + async ({ init }) => { |
| 195 | + const body = JSON.parse(String(init.body)); |
| 196 | + scopes.push(body.teamId); |
| 197 | + return body.teamId === undefined |
| 198 | + ? Response.json({ |
| 199 | + totalUsageEventsCount: 1, |
| 200 | + usageEventsDisplay: [ |
| 201 | + { |
| 202 | + timestamp: "1780000000000", |
| 203 | + model: "gpt-5", |
| 204 | + tokenUsage: { inputTokens: 10 }, |
| 205 | + }, |
| 206 | + ], |
| 207 | + }) |
| 208 | + : new Response(null, { status: 403 }); |
| 209 | + }, |
| 210 | + { userId, teamIds: [7] }, |
| 211 | + ); |
| 212 | + assert.isNotNull(result.error); |
| 213 | + assert.deepStrictEqual(result.records, []); |
| 214 | + assert.deepStrictEqual(scopes, userId === 0 ? [] : [undefined, 7]); |
| 215 | + } |
| 216 | + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 217 | + ); |
| 218 | + |
| 219 | + it.effect.each([ |
| 220 | + { exp: undefined, lifetime: "5 minutes" }, |
| 221 | + { exp: 90, lifetime: "1 minute" }, |
| 222 | + ] as const)( |
| 223 | + "reuses discovery for $lifetime, invalidates rejected auth, and isolates API keys", |
| 224 | + ({ exp, lifetime }) => |
| 225 | + Effect.gen(function* () { |
| 226 | + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp })).toString("base64url")}.signature`; |
| 227 | + const requests: string[] = []; |
| 228 | + let rejected = false; |
| 229 | + const client = dashboard( |
| 230 | + () => (rejected ? new Response(null, { status: 401 }) : Response.json({})), |
| 231 | + { userId: 42, teamIds: [7] }, |
| 232 | + ).pipe( |
| 233 | + HttpClient.mapRequest((request) => { |
| 234 | + requests.push(request.url.split("/").at(-1)!); |
| 235 | + return request; |
| 236 | + }), |
| 237 | + ); |
| 238 | + yield* Effect.gen(function* () { |
| 239 | + const reader = yield* CursorAccountReader.CursorAccountReader; |
| 240 | + const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 241 | + assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 242 | + requests.length = 0; |
| 243 | + assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 244 | + assert.deepStrictEqual(requests, ["GetFilteredUsageEvents", "GetFilteredUsageEvents"]); |
| 245 | + rejected = true; |
| 246 | + assert.isNotNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 247 | + rejected = false; |
| 248 | + requests.length = 0; |
| 249 | + assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 250 | + assert.include(requests, "GetTeams"); |
| 251 | + requests.length = 0; |
| 252 | + yield* TestClock.adjust(lifetime); |
| 253 | + yield* reader.read(credential, 0, 1781000000000); |
| 254 | + assert.include(requests, "GetTeams"); |
| 255 | + requests.length = 0; |
| 256 | + yield* reader.read({ ...credential, apiKey: accessToken + "other" }, 0, 1781000000000); |
| 257 | + assert.include(requests, "GetTeams"); |
| 258 | + }).pipe( |
| 259 | + Effect.provide( |
| 260 | + CursorAccountReader.layer.pipe( |
| 261 | + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), |
| 262 | + ), |
| 263 | + ), |
| 264 | + ); |
| 265 | + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 266 | + ); |
| 267 | + |
| 268 | + it.effect("starts personal and team reads together without waiting for either response", () => |
| 269 | + Effect.gen(function* () { |
| 270 | + const personal = yield* Deferred.make<void>(); |
| 271 | + const team = yield* Deferred.make<void>(); |
| 272 | + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 273 | + const client = dashboard(() => Response.json({}), { userId: 42, teamIds: [7] }).pipe( |
| 274 | + HttpClient.transform((response, request) => { |
| 275 | + if (!request.url.endsWith("/GetFilteredUsageEvents")) return response; |
| 276 | + const body = |
| 277 | + request.body._tag === "Uint8Array" |
| 278 | + ? JSON.parse(new TextDecoder().decode(request.body.body)) |
| 279 | + : {}; |
| 280 | + const isPersonal = body.teamId === undefined; |
| 281 | + return Effect.gen(function* () { |
| 282 | + yield* Deferred.succeed(isPersonal ? personal : team, undefined); |
| 283 | + yield* Deferred.await(isPersonal ? team : personal); |
| 284 | + return yield* response; |
| 285 | + }); |
| 286 | + }), |
| 287 | + ); |
| 288 | + const result = yield* makeCursorAccountUsageReader.pipe( |
| 289 | + Effect.flatMap((read) => read({ kind: "apiKey", apiKey: accessToken }, 0, 1781000000000)), |
| 290 | + Effect.provideService(HttpClient.HttpClient, client), |
| 291 | + ); |
| 292 | + assert.isNull(result.error); |
| 293 | + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 294 | + ); |
| 295 | + |
126 | 296 | it.effect("reads Cursor account history beyond 100 pages", () => |
127 | 297 | Effect.gen(function* () { |
128 | 298 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
@@ -341,37 +511,76 @@ describe("readCursorAccountUsage", () => { |
341 | 511 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
342 | 512 | ); |
343 | 513 |
|
344 | | - it.effect("reads the pages behind the first together and keeps them in page order", () => |
345 | | - Effect.gen(function* () { |
346 | | - const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
347 | | - let inFlight = 0; |
348 | | - let mostInFlight = 0; |
349 | | - const result = yield* readAccountUsage( |
350 | | - { kind: "apiKey", apiKey: accessToken }, |
351 | | - 0, |
352 | | - 1781000000000, |
353 | | - async ({ page }) => { |
354 | | - inFlight++; |
355 | | - mostInFlight = Math.max(mostInFlight, inFlight); |
356 | | - for (let turn = page; turn < 9; turn++) await Promise.resolve(); |
357 | | - inFlight--; |
358 | | - return Response.json({ |
359 | | - totalUsageEventsCount: 8001, |
360 | | - usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({ |
361 | | - timestamp: String(1780000000000 + (page - 1) * 1000 + index), |
362 | | - model: "gpt-5", |
363 | | - tokenUsage: { inputTokens: 1 }, |
364 | | - })), |
365 | | - }); |
366 | | - }, |
367 | | - ); |
368 | | - assert.isNull(result.error); |
369 | | - assert.strictEqual(mostInFlight, 6); |
370 | | - assert.deepStrictEqual( |
371 | | - result.records.map((record) => record.timestampMs), |
372 | | - Array.from({ length: 8001 }, (_, index) => 1780000000000 + index), |
373 | | - ); |
374 | | - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 514 | + it.effect.each([{ queued: false }, { queued: true }])( |
| 515 | + "reads concurrent pages in order with a full request deadline after queuing: $queued", |
| 516 | + ({ queued }) => |
| 517 | + Effect.gen(function* () { |
| 518 | + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 519 | + const started = yield* Queue.unbounded<void>(); |
| 520 | + const firstBatch = yield* Deferred.make<void>(); |
| 521 | + const secondBatch = yield* Deferred.make<void>(); |
| 522 | + let delayedRequests = 0; |
| 523 | + let inFlight = 0; |
| 524 | + let mostInFlight = 0; |
| 525 | + const client = dashboard( |
| 526 | + async ({ page }) => { |
| 527 | + inFlight++; |
| 528 | + mostInFlight = Math.max(mostInFlight, inFlight); |
| 529 | + for (let turn = page; turn < 9; turn++) await Promise.resolve(); |
| 530 | + inFlight--; |
| 531 | + return Response.json({ |
| 532 | + totalUsageEventsCount: 8001, |
| 533 | + usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({ |
| 534 | + timestamp: String(1780000000000 + (page - 1) * 1000 + index), |
| 535 | + model: "gpt-5", |
| 536 | + tokenUsage: { inputTokens: 1 }, |
| 537 | + })), |
| 538 | + }); |
| 539 | + }, |
| 540 | + { userId: 42, teamIds: queued ? [7] : [] }, |
| 541 | + ).pipe( |
| 542 | + HttpClient.transform((response, request) => { |
| 543 | + if (!queued || !request.url.endsWith("/GetFilteredUsageEvents")) return response; |
| 544 | + const body = |
| 545 | + request.body._tag === "Uint8Array" |
| 546 | + ? JSON.parse(new TextDecoder().decode(request.body.body)) |
| 547 | + : {}; |
| 548 | + if (body.page === 1) return response; |
| 549 | + return Effect.gen(function* () { |
| 550 | + const batch = delayedRequests++ < 6 ? firstBatch : secondBatch; |
| 551 | + yield* Queue.offer(started, undefined); |
| 552 | + yield* Deferred.await(batch); |
| 553 | + return yield* response; |
| 554 | + }); |
| 555 | + }), |
| 556 | + ); |
| 557 | + const read = yield* Effect.forkChild( |
| 558 | + makeCursorAccountUsageReader.pipe( |
| 559 | + Effect.flatMap((reader) => |
| 560 | + reader({ kind: "apiKey", apiKey: accessToken }, 0, 1781000000000), |
| 561 | + ), |
| 562 | + Effect.provideService(HttpClient.HttpClient, client), |
| 563 | + ), |
| 564 | + ); |
| 565 | + if (queued) { |
| 566 | + yield* Effect.all(Array.from({ length: 6 }, () => Queue.take(started))); |
| 567 | + yield* TestClock.adjust("6 seconds"); |
| 568 | + yield* Deferred.succeed(firstBatch, undefined); |
| 569 | + yield* Effect.all(Array.from({ length: 6 }, () => Queue.take(started))); |
| 570 | + yield* TestClock.adjust("6 seconds"); |
| 571 | + yield* Deferred.succeed(secondBatch, undefined); |
| 572 | + } |
| 573 | + const result = yield* Fiber.join(read); |
| 574 | + assert.isNull(result.error); |
| 575 | + assert.strictEqual(mostInFlight, 6); |
| 576 | + assert.deepStrictEqual( |
| 577 | + result.records.map((record) => record.timestampMs), |
| 578 | + Array.from( |
| 579 | + { length: queued ? 16002 : 8001 }, |
| 580 | + (_, index) => 1780000000000 + (index % 8001), |
| 581 | + ), |
| 582 | + ); |
| 583 | + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
375 | 584 | ); |
376 | 585 |
|
377 | 586 | it.effect("ends like a page-by-page read when a page fails, leaving no request open", () => |
|