From 23562b09ac49994a0ae246855d78012031862181 Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:20:37 +0200 Subject: [PATCH 1/2] fix: normalize new /teams/spend response shape Cursor's /teams/spend now returns spendCents as the overage above the plan, exposes the cycle total as overallSpendCents and no longer sends includedSpendCents. The collector crashed with a NOT NULL violation on spending.included_spend_cents and would have stored 0 spend for users within plan. Normalize each member so spendCents stays the cycle total and includedSpendCents is derived (total - overage), keeping pre-2026 responses working. Tests cover both shapes. Fixes #19. Based on Marc Cobery's f15dab2 (proposed in #21, closed unmerged). Co-authored-by: Marc Cobery Co-authored-by: Cursor --- .cursor/rules/cursor-api.mdc | 17 ++++++- src/lib/cursor-client.ts | 30 +++++++++++- tests/cursor-client.test.ts | 95 ++++++++++++++++++++++++++++++++++++ 3 files changed, 140 insertions(+), 2 deletions(-) diff --git a/.cursor/rules/cursor-api.mdc b/.cursor/rules/cursor-api.mdc index 0409fd6..6dd41ea 100644 --- a/.cursor/rules/cursor-api.mdc +++ b/.cursor/rules/cursor-api.mdc @@ -32,7 +32,22 @@ Poll at most once per hour (data aggregated hourly). ### POST /teams/spend Body: `{ page, pageSize }` -Returns `{ teamMemberSpend: [{ email, spendCents, fastPremiumRequests }], subscriptionCycleStart: number, totalPages }` +Returns (post-2026 shape): +``` +{ + teamMemberSpend: [{ + userId, email, name, role, profilePictureUrl, + spendCents, // overage above plan (was cycle total in pre-2026 shape) + overallSpendCents, // cycle-to-date total (new field, post-2026) + fastPremiumRequests, + monthlyLimitDollars, hardLimitOverrideDollars, + effectivePerUserLimitDollars + }], + subscriptionCycleStart: number, + totalPages, totalMembers, limitedUsersCount, maxUserSpendCents +} +``` +Note: the meaning of `spendCents` changed in 2026. Pre-2026 it was the cycle total; post-2026 it is the overage above the plan-included amount, and `overallSpendCents` holds the cycle total. `includedSpendCents` was removed from the response. `cursor-client.ts::normalizeMemberSpend` normalizes both shapes so downstream code can rely on `spendCents` = total and `includedSpendCents` = plan-covered. See GH issue #19. ### POST /teams/filtered-usage-events Body: `{ email?, startDate?, endDate?, page, pageSize }` diff --git a/src/lib/cursor-client.ts b/src/lib/cursor-client.ts index 783cb21..c3c9f86 100644 --- a/src/lib/cursor-client.ts +++ b/src/lib/cursor-client.ts @@ -43,6 +43,30 @@ function bool(v: unknown): boolean { return v === true || v === 1 || v === "1"; } +function normalizeMemberSpend(raw: Record): MemberSpend { + const rawSpend = num(raw.spendCents); + const overall = typeof raw.overallSpendCents === "number" ? raw.overallSpendCents : undefined; + const rawIncluded = + typeof raw.includedSpendCents === "number" ? raw.includedSpendCents : undefined; + + const total = overall ?? rawSpend; + const overage = overall !== undefined ? rawSpend : 0; + const included = rawIncluded ?? Math.max(0, total - overage); + + return { + userId: str(raw, "userId"), + email: str(raw, "email"), + name: str(raw, "name"), + role: str(raw, "role"), + spendCents: total, + includedSpendCents: included, + fastPremiumRequests: num(raw.fastPremiumRequests), + monthlyLimitDollars: + typeof raw.monthlyLimitDollars === "number" ? raw.monthlyLimitDollars : null, + hardLimitOverrideDollars: num(raw.hardLimitOverrideDollars), + }; +} + function normalizeFilteredUsageEvent(raw: Record): FilteredUsageEvent { const tuRaw = raw.tokenUsage ?? raw.token_usage; let tokenUsage: FilteredUsageEvent["tokenUsage"]; @@ -193,7 +217,11 @@ export class CursorClient { cycleStart = new Date(data.subscriptionCycleStart).toISOString().split("T")[0] ?? ""; limitedUsersCount = data.limitedUsersCount ?? 0; - allMembers.push(...data.teamMemberSpend); + allMembers.push( + ...data.teamMemberSpend.map((m) => + normalizeMemberSpend(m as unknown as Record), + ), + ); if (page >= data.totalPages) break; page++; diff --git a/tests/cursor-client.test.ts b/tests/cursor-client.test.ts index 1f6e8fd..d826680 100644 --- a/tests/cursor-client.test.ts +++ b/tests/cursor-client.test.ts @@ -78,4 +78,99 @@ describe("CursorClient", () => { globalThis.fetch = originalFetch; }); + + it("normalizes new /teams/spend shape (overallSpendCents + spendCents=overage)", async () => { + const originalFetch = globalThis.fetch; + + globalThis.fetch = vi.fn(async () => { + return new Response( + JSON.stringify({ + teamMemberSpend: [ + { + userId: "user_1", + email: "a@test.com", + name: "Alice", + role: "member", + profilePictureUrl: null, + spendCents: 150, + overallSpendCents: 1000, + fastPremiumRequests: 5, + monthlyLimitDollars: 30, + hardLimitOverrideDollars: 200, + effectivePerUserLimitDollars: 30, + }, + { + userId: "user_2", + email: "b@test.com", + name: "Bob", + role: "member", + spendCents: 0, + overallSpendCents: 500, + fastPremiumRequests: 0, + monthlyLimitDollars: null, + hardLimitOverrideDollars: 0, + }, + ], + subscriptionCycleStart: 1704067200000, + totalPages: 1, + limitedUsersCount: 0, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }); + + const { members } = await client.getSpending(); + expect(members).toHaveLength(2); + + const [m0, m1] = members; + if (!m0 || !m1) throw new Error("expected two normalized members"); + + expect(m0.spendCents).toBe(1000); + expect(m0.includedSpendCents).toBe(850); + + expect(m1.spendCents).toBe(500); + expect(m1.includedSpendCents).toBe(500); + expect(m1.monthlyLimitDollars).toBeNull(); + + globalThis.fetch = originalFetch; + }); + + it("preserves old /teams/spend shape (spendCents=total, no overallSpendCents)", async () => { + const originalFetch = globalThis.fetch; + + globalThis.fetch = vi.fn(async () => { + return new Response( + JSON.stringify({ + teamMemberSpend: [ + { + userId: "user_1", + email: "a@test.com", + name: "Alice", + role: "member", + spendCents: 1000, + includedSpendCents: 800, + fastPremiumRequests: 5, + monthlyLimitDollars: 30, + hardLimitOverrideDollars: 0, + }, + ], + subscriptionCycleStart: 1704067200000, + totalPages: 1, + limitedUsersCount: 0, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }); + + const { members } = await client.getSpending(); + expect(members).toHaveLength(1); + + const [m0] = members; + if (!m0) throw new Error("expected one normalized member"); + + expect(m0.spendCents).toBe(1000); + expect(m0.includedSpendCents).toBe(800); + + globalThis.fetch = originalFetch; + }); }); From 64f98534c0730a9185d5cc03891f45084e8370a1 Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Mon, 31 Aug 2026 14:59:09 +0200 Subject: [PATCH 2/2] fix: alias usage_events in getUserCostDrivers top-model query The top-model query filtered on `ue.timestamp` (via the shared dateFilter) but selected FROM usage_events without the `ue` alias, so SQLite failed with "no such column: ue.timestamp". getUserCostDrivers is used by the z-score and trend detectors, so anomaly detection broke. Alias the table and qualify the selected/grouped column, and add a regression test. Co-authored-by: Cursor --- src/lib/data/sqlite.ts | 6 +++--- tests/db-cost-drivers.test.ts | 39 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 tests/db-cost-drivers.test.ts diff --git a/src/lib/data/sqlite.ts b/src/lib/data/sqlite.ts index 5e50fc2..3aa0c52 100644 --- a/src/lib/data/sqlite.ts +++ b/src/lib/data/sqlite.ts @@ -3328,9 +3328,9 @@ export function getUserCostDrivers(email: string, date?: string): CostDriverSumm const topModel = db .prepare( - `SELECT model, SUM(total_cents) as s FROM usage_events - WHERE user_email = ? AND ${dateFilter} AND total_cents > 0 - GROUP BY model ORDER BY s DESC LIMIT 1`, + `SELECT ue.model, SUM(ue.total_cents) as s FROM usage_events ue + WHERE ue.user_email = ? AND ${dateFilter} AND ue.total_cents > 0 + GROUP BY ue.model ORDER BY s DESC LIMIT 1`, ) .get(...params) as { model: string } | undefined; diff --git a/tests/db-cost-drivers.test.ts b/tests/db-cost-drivers.test.ts new file mode 100644 index 0000000..343e87c --- /dev/null +++ b/tests/db-cost-drivers.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; + +const TEST_DB_PATH = path.join(process.cwd(), "data", "test-cost-drivers.db"); + +type SqliteModule = typeof import("@/lib/data/sqlite"); + +describe("getUserCostDrivers", () => { + let sqlite: SqliteModule; + + beforeAll(async () => { + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + process.env.DATABASE_PATH = TEST_DB_PATH; + sqlite = await import("@/lib/data/sqlite"); + sqlite.getDb(); + }); + + afterAll(() => { + sqlite.getDb().close(); + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + delete process.env.DATABASE_PATH; + }); + + it("returns the top model for a given day", () => { + const insert = sqlite.getDb().prepare( + `INSERT INTO usage_events (user_email, timestamp, model, kind, total_cents) + VALUES (?, ?, ?, 'Included', ?)`, + ); + const ts = String(Date.UTC(2026, 5, 1, 12)); + insert.run("dev@example.com", ts, "cheap-model", 10); + insert.run("dev@example.com", ts, "expensive-model", 90); + + const drivers = sqlite.getUserCostDrivers("dev@example.com", "2026-06-01"); + + expect(drivers?.top_model).toBe("expensive-model"); + expect(drivers?.total_spend_cents).toBe(100); + }); +});