Files
plugins/packages/cursor/usage.test.mjs
T
geoqiao 8cd5a0fad8 cursor 0.2.0: the list is Cursor's picker, a model once per context size with that window; effort and fast are the request's (#51)
* cursor 0.2.0: the list is Cursor's picker, a model once for each context size with that window (claude-opus-5-5@300k, @1m), and effort and fast are the request's, sent as the variant's parameters

The usable list (AgentService/GetUsableModels) names a model once for each effort and speed, and the window was read off the name: 1M when it said 1M, else 200K. The names say 1M of models Cursor serves at 300K outside Max Mode ("Claude Opus 5.5 1M"), and nothing of the 300K Sonnet and Haiku or the 256K Grok have, so on this account 110 of 153 names gave a wrong window: Opus too large, Sonnet, Haiku and Grok too small, and the agents compacted at the wrong point. The request carried no context parameter either, so the window Cursor ran at was its own choice, not the one magpie reported. The same id could go to a 300K and a 1M variant.

Now the list is Cursor's model picker alone (AiService/AvailableModels, asked as the CLI asks it: useModelParameters, doNotUseMarkdown), the way pi-cursor-sdk lists Cursor's catalog. A model with a context parameter is offered once for each size, as <model>@<size> named "<name> @ <size>", its window that many tokens; one without is offered once, its window Cursor's contextTokenLimit (Max Mode's for a model served only there), 200K when Cursor gives none. Effort is not a model of its own: the model's efforts (effort / reasoning_effort / reasoning; extra-high is xhigh) are its variants, the request's reasoning_effort is fitted to the nearest and sent as that parameter, and none turns a Claude's thinking off. Fast is not one either: a service_tier of priority or fast sends fast=true, anything else fast=false, so it is paid for only when asked. A request goes as the variant those parameters pick, by the variant's legacySlug (claude-opus-5-5-medium): the agent API refuses the picker's base name with 502 "AI Model Not Found: Model name is not valid". It goes in Max Mode when that variant is Max Mode's (a 1M size; Opus 300K with fast), or, with no variant for the size, when the size is over Cursor's limit outside it; the "Max Mode Required" retry stays. Hidden, Tab-only and chat-only models stay out, as in the CLI.

The ids change (cursor/claude-opus-5-5 is cursor/claude-opus-5-5@300k; the -fast, -low and -thinking models are gone), so 0.2.0: a model picked in magpie or an agent's config has to be picked again. An id the list doesn't have goes to Cursor as it is named, with the default window. poolBase and firstParty take the @size off, so usage pools as before (grok-4.7@256k Cursor Models, claude-opus-5-5@300k Other Models).

context.test.mjs (new) covers the list, the windows, the variants and the request's parameters and mode; maxmode.test.mjs (rewritten) checks what reaches a fake agent API; usage.test.mjs adds the sized ids. HOME=$(mktemp -d) bun test: 45 pass, 0 fail; check.mjs cursor passes. Tried with a real Cursor account: claude-opus-5-5@300k goes as claude-opus-5-5-medium with context=300k and answers, grok-4.6 as cursor-grok-4.6-high, and pi -p --model magpie/cursor/claude-opus-5-5@300k answers; the base name got the 502 above.

* cursor 0.2.0: an id 0.1.x listed still runs as the variant it stood for, and a variant the account hasn't got is neither offered nor asked for (review of #51)

An id the new list doesn't have went to Cursor as it was named. The ids 0.1.11 listed are families of the variants' own ids (claude-opus-5-5, claude-opus-5-5-fast, claude-haiku-5-5-thinking, cursor-grok-4.6), and they are saved in agents' configs, magpie's picks and routing groups: request(raw, "claude-opus-5-5", "high") was {id: "claude-opus-5-5", params: [], maxMode: false}, the bare name the agent API answers 502 "AI Model Not Found" for, with the effort dropped.

Now an id the list doesn't have is read as one of Cursor's own (named): a variant's legacySlug is that variant; a family of them, taken apart as 0.1.x's splitID did, is the family's variant nearest the default, fast for a -fast family, thinking as the family says, at the effort the id names when the request names none; the picker's name for a model, one of its legacySlugs or idAliases, is its default. Each is at the variant's context size, the default's when two sizes share the id. The request's reasoning_effort and service_tier count as for a listed model. The family is tried before the picker's name, so claude-haiku-5-5 stays the Claude without thinking it was in 0.1.11 where Cursor has variants named so; where it has none it is the model's default. Anything else still goes as it is named.

The usable list (AgentService/GetUsableModels) is read again, beside the picker: a variant whose legacySlug isn't in it is dropped, the model's efforts and sizes are the ones its remaining variants have, and a request no remaining variant matches goes as the nearest of them, not as the default's id with parameters the account hasn't got. A model the usable list has nothing of is the picker's alone (GLM-5.3, as 0.1.7 found) and is kept whole; a usable list Cursor can't give leaves the picker as it is.

answerOf's comment says what pick does with no service_tier (fast off). context.test.mjs checks the PICKER_SKIP names stay out (claude-4.5-haiku, claude-haiku-4-5), each id 0.1.11's offered() gives for the fixture's slugs, variant ids and a model's legacy slug, and the usable list's filter; maxmode.test.mjs checks claude-opus-5-5 reaches the fake agent API as claude-opus-5-5-medium. On b33ec2f's index.mjs the three new context tests and that maxmode test fail. HOME=$(mktemp -d) bun test: 48 pass, 0 fail; check.mjs cursor passes. Not tried with a real Cursor account, and not read against cursor-agent's source (neither is on this machine): the old-id rules follow the review's description and 0.1.11's splitID.
2026-10-08 22:03:11 +08:00

147 lines
7.5 KiB
JavaScript

// auth.usage tells what magpie's built-in Cursor account shows
// (internal/provider/cursor_usage.go), against Cursor's replies as its tests
// give them (cursor_usage_test.go).
import "./nonet.mjs" // first: no request leaves this machine
import { afterEach, expect, test } from "bun:test"
import { CursorAuthPlugin, _internal } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
// a token that runs out in an hour
const jwt = (exp) => ["e30", Buffer.from(JSON.stringify({ exp })).toString("base64url"), "sig"].join(".")
const tok = jwt(Math.floor(Date.now() / 1000) + 3600)
const auth = { type: "oauth", access: tok, refresh: "", expires: 0, accountId: "a@b.c" }
// a sign-in of its own, so no plan asked before is remembered for it
let n = 0
const fresh = () => ({ ...auth, access: jwt(Math.floor(Date.now() / 1000) + 7200 + ++n) })
const firstParty = ["grok-4.7@256k", "grok-4.7@500k", "grok-4.6", "grok-4.7-xhigh-fast", "cursor-grok-4.7-high-fast", "cursor-grok-4.6-high-fast", "grok-4.5-fast-high", "auto", "default", "composer-2.5", "COMPOSER-2.5-FAST", "composer"]
const bucketed = ["future-first-party", "grok-4.8-high", "cursor-grok-4.8-xhigh-fast"]
const others = ["claude-opus-5-5@300k", "claude-opus-5-5@1m", "claude-opus-5-5", "gpt-5.6-sol", "gemini-3.1-pro", "grok-3", "grok-4.70", "grok-4.80-high", "unknown-model"]
const provider = { models: Object.fromEntries([...firstParty, ...bucketed, ...others].map((id) => [id, { id }])) }
async function run(a, reply) {
const seen = []
globalThis.fetch = async (url, init) => {
seen.push({ url: String(url), method: init.method, headers: init.headers, body: init.body })
return reply(String(url))
}
const hooks = await CursorAuthPlugin()
return { u: await hooks.auth.usage(async () => a, provider), seen }
}
// counts is whether a window counts model, as magpie reads the lists
// (internal/provider/plugin_usage.go)
function counts(w, model) {
const m = model.toLowerCase()
if (w.models?.length) return w.models.some((x) => x.toLowerCase() === m)
if (w.notModels?.length) return !w.notModels.some((x) => x.toLowerCase() === m)
return true
}
const PERIOD = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage"
const PLAN = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetPlanInfo"
test("the period's three windows, reset at the cycle's end", async () => {
const { u, seen } = await run(auth, (url) =>
url === PLAN
? Response.json({ planInfo: { planName: "Pro" } })
: Response.json({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: 12.5, apiPercentUsed: 40, totalPercentUsed: 20 } }),
)
expect(seen.find((r) => r.url === PERIOD)).toEqual({
url: PERIOD,
method: "POST",
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
body: "{}",
})
const at = new Date(1792833042000).toISOString()
expect(u.windows.map(({ models, notModels, ...w }) => w)).toEqual([
{ name: "Cursor Models", used: 12.5, resetsAt: at },
{ name: "Other Models", used: 40, resetsAt: at },
{ name: "Total", used: 20, resetsAt: at, aside: true },
])
expect(u.error).toBeUndefined()
})
test("the card names the plan as cursor-agent about does (GetPlanInfo's planName), asked once an hour", async () => {
const a = fresh()
const reply = (url) =>
url === PLAN ? Response.json({ planInfo: { planName: "Pro+" } }) : Response.json({ planUsage: { autoPercentUsed: 1, apiPercentUsed: 2, totalPercentUsed: 3 } })
const first = await run(a, reply)
expect(first.u.plan).toBe("Pro+")
const plan = first.seen.find((r) => r.url === PLAN)
expect(plan.method).toBe("POST")
expect(plan.headers.Authorization).toBe(`Bearer ${a.access}`)
const again = await run(a, reply)
expect(again.u.plan).toBe("Pro+")
expect(again.seen.map((r) => r.url)).toEqual([PERIOD])
})
test("a plan Cursor doesn't say leaves the card's plan out", async () => {
const a = fresh()
const { u } = await run(a, (url) => (url === PLAN ? new Response("no", { status: 500 }) : Response.json({ planUsage: { autoPercentUsed: 1 } })))
expect(u.plan).toBeUndefined()
expect(u.windows.length).toBe(3)
})
for (const bucket of [["default", "composer-2.5", "cursor-grok-4.5-high", "future-first-party", "Grok-4.8"], undefined]) {
test(`each model counts in the pool magpie puts it in (autoBucketModels ${bucket ? "given" : "left out"})`, async () => {
const { u } = await run(auth, () =>
Response.json({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: 25, apiPercentUsed: 100, totalPercentUsed: 100 }, autoBucketModels: bucket }),
)
const [cursor, other, total] = u.windows
const pool = bucket ? [...firstParty, ...bucketed] : firstParty
const rest = bucket ? others : [...others, ...bucketed]
for (const m of pool) expect([m, counts(cursor, m), counts(other, m)]).toEqual([m, true, false])
for (const m of rest) expect([m, counts(cursor, m), counts(other, m)]).toEqual([m, false, true])
expect(total.models).toBeUndefined()
expect(total.notModels).toBeUndefined()
})
}
test("an enterprise plan's spend is no window", async () => {
expect((await run(fresh(), () => Response.json({ spendLimitUsage: {} }))).u).toEqual({ windows: [], signIn: "kept" })
})
test("a refused token is the status magpie says", async () => {
expect((await run(fresh(), () => new Response("no", { status: 401 }))).u).toEqual({ error: "Unauthorized", windows: [], signIn: "kept" })
})
test("a run-out sign-in says so, and asks nothing", async () => {
const { u, seen } = await run({ ...auth, access: jwt(1) }, () => Response.json({}))
expect(u).toEqual({ error: "Cursor's sign-in has run out; sign in to Cursor again", windows: [], signIn: "kept" })
expect(seen).toEqual([])
})
// the built-in's 401 for any "expired", a token's or a trial's, which marked
// no account (errorResponse says kept)
test("anything expired is the built-in's 401", () => {
const { failure } = _internal
const says = (msg) => failure(400, JSON.stringify({ code: "failed_precondition", message: msg }))
for (const m of ["Your access token has expired", "Session expired, please log in again", "Your free trial has expired", "This link has expired"])
expect(says(m)).toEqual({ status: 401, message: m + " — sign in to Cursor again in magpie" })
})
// The built-in's usage read neither marked nor cleared the account, so each
// read says kept, a clean one too.
test("a usage read keeps the account, clean or not", async () => {
const PERIOD_OK = () => Response.json({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: 1, apiPercentUsed: 2, totalPercentUsed: 3 } })
expect((await run(fresh(), PERIOD_OK)).u.signIn).toBe("kept")
expect((await run(fresh(), () => new Response("no", { status: 401 }))).u.signIn).toBe("kept")
expect((await run({ ...auth, access: jwt(1) }, PERIOD_OK)).u.signIn).toBe("kept")
})
// the gateway names the provider before a plugin's error
test("an error doesn't name Cursor again", () => {
const f = _internal.failure(429, JSON.stringify({ code: "resource_exhausted", message: "slow down" }))
expect(f).toEqual({ status: 429, message: "usage limit reached: slow down" })
})
test("a model list Cursor couldn't give fails, not shrinks to the configured few", async () => {
globalThis.fetch = async () => new Response("down", { status: 503 })
const hooks = await CursorAuthPlugin()
const configured = { models: { auto: { id: "auto" } } }
await expect(hooks.provider.models(configured, { auth: fresh() })).rejects.toThrow()
})