bg5eau on X (11-14): through magpie ZCode's gift quota stopped going down while the account's pay-as-you-go balance was charged. Two routes in the plugin let a key with no GLM Coding Plan spend money while its free Start Plan quota sat unspent: - A gift-only account sends every request to the Start Plan, whatever the model. ZCode's app offers such an account only the models its balance names (resolveStartPlanBalanceAvailability in 3.18.2); an agent left on another model (GLM-5.2 while the gift serves only GLM-5.3-Flash) spent none of the gift. Such a request is now answered 400 with the models the balance names and is not sent. The balance is the one the model list already reads (aloneSeen, ten minutes); only a model it doesn't name has it read again, so a gift claimed since is sent, and a request whose model it names reads nothing. A balance not read yet, one that fails, or one naming none leaves the request as it was (unknown is not a refusal). - plansOf's catch path: a plan-list read that failed sent every key account down the dual route, to api.z.ai / open.bigmodel.cn's /api/anthropic with its key, which bills a key with no plan pay-as-you-go. An account whose last read found no plan now stays on the Start Plan for the minute. A key with no earlier read still takes the dual route, as before. Not known: which of the two was bg5eau's (no request log from them). No 503 is made by the plugin (skykiahhub's 503 on X is the vendor's or one of magpie's own, each of which says why). Run (mote, load ~130-180, mica's disk was full; HOME=$(mktemp -d)): bun test packages/zcode 271 pass 0 fail; bun scripts/check.mjs zcode ok. Broken by hand: the guard off, "a gift-only account's model its balance doesn't name is not sent" fails; the catch-path change off, "a gift-only account stays on the Start Plan when its plan list stops reading" fails (it sent GLM-5.2 to api.z.ai). Not tried: a real gift-only account (the owner's has a coding plan and no gift), a real pay-as-you-go charge, Windows and Linux.
643 lines
37 KiB
JavaScript
643 lines
37 KiB
JavaScript
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"
|
|
import { homedir, tmpdir } from "node:os"
|
|
import { readFileSync, realpathSync } from "node:fs"
|
|
|
|
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run in an isolated home")
|
|
const { ZCodeAuthPlugin, _internal } = await import("./index.mjs")
|
|
const now = Math.trunc(Date.now() / 1000)
|
|
const jwt = ["{}", JSON.stringify({ exp: now + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".synthetic"
|
|
const state = { site: "zai", base: "https://api.z.ai/api/anthropic", key: "synthetic-key", jwt, device: "11111111-2222-4333-8444-555555555555", plan: "GLM Coding Pro" }
|
|
const auth = { type: "oauth", access: state.key, refresh: JSON.stringify(state), expires: 0 }
|
|
const original = "glm-limited-preview"
|
|
const alias = original + "-Trial"
|
|
const MSG = "https://api.z.ai/api/anthropic/v1/messages"
|
|
const ok = (data) => new Response(JSON.stringify({ code: 0, data }), { headers: { "content-type": "application/json" } })
|
|
const real = globalThis.fetch
|
|
const sent = []
|
|
let balance, paid, giftReply, planReply
|
|
|
|
beforeEach(() => {
|
|
_internal.routes.clear()
|
|
_internal.blocked.clear()
|
|
_internal.aloneSeen.clear()
|
|
sent.length = 0
|
|
paid = 100
|
|
planReply = null
|
|
giftReply = new Response(JSON.stringify({ type: "message", content: [] }), { headers: { "content-type": "application/json" } })
|
|
balance = {
|
|
server_time: now,
|
|
plans: [{ plan_id: "grant", user_plan_id: "g1", name: "Festival Grant", status: "active", ends_at: now + 86400 }],
|
|
balances: [{ plan_id: "grant", user_plan_id: "g1", show_name: "Limited credit", capabilities: ["model:" + original], total_units: 100, used_units: 25, remaining_units: 75, expires_at: now + 3600 }],
|
|
}
|
|
globalThis.fetch = async (input, init = {}) => {
|
|
const url = new URL(input instanceof Request ? input.url : String(input))
|
|
if (url.pathname === "/api/biz/subscription/list") return ok([{ productName: "GLM Coding Pro", status: "VALID" }])
|
|
if (url.pathname === "/api/monitor/usage/quota/limit") return ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: paid, nextResetTime: (now + 86400) * 1000 }] })
|
|
if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok(balance)
|
|
if (url.pathname.endsWith("/messages")) {
|
|
const text = init.body ?? (input instanceof Request ? await input.text() : undefined)
|
|
sent.push({ origin: url.origin, path: url.pathname, body: JSON.parse(text), headers: new Headers(init.headers ?? (input instanceof Request ? input.headers : {})) })
|
|
return url.origin === "https://zcode.z.ai" ? giftReply.clone() : planReply ? planReply.clone() : ok({ type: "message", content: [] })
|
|
}
|
|
throw new Error("unmocked request blocked: " + url.pathname)
|
|
}
|
|
})
|
|
afterEach(() => { globalThis.fetch = real })
|
|
const hooks = async () => (await ZCodeAuthPlugin({ client: {} }))
|
|
const send = async (model = alias, credentials = auth) => {
|
|
const loader = await (await hooks()).auth.loader(async () => credentials, { id: "zcode" })
|
|
return loader.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }], max_tokens: 10 }) })
|
|
}
|
|
|
|
test("real balance data adds a gift model absent from the coding catalog", async () => {
|
|
const h = await hooks()
|
|
const plan = await h.provider.models({ models: {} }, { auth: { type: "api", key: state.key } })
|
|
const models = await h.provider.models({ models: {} }, { auth })
|
|
expect(plan[original]).toBeUndefined()
|
|
expect(models[alias]).toMatchObject({ id: alias, name: alias, api: { id: alias } })
|
|
for (const [id, m] of Object.entries(plan)) expect(models[id]).toEqual(m)
|
|
expect(Object.keys(models).filter((id) => id.endsWith("-Trial"))).toEqual([alias])
|
|
})
|
|
|
|
// plugins#438 (takomitkm): a GLM Coding Plan model's weekly limit (1310)
|
|
// rested the whole account, -Trial entries too, which the gift's own
|
|
// buckets serve. The trial entries are marked free, as they are: magpie
|
|
// then rests a refused coding plan model alone and still asks the trial
|
|
// entries. The plan's own models are not free, and an account with no gift
|
|
// lists nothing free, so its quota refusal rests it as before.
|
|
test("a dual account's trial entries are free, its coding plan models are not (plugins#438)", async () => {
|
|
const h = await hooks()
|
|
const plan = await h.provider.models({ models: {} }, { auth: { type: "api", key: state.key } })
|
|
const models = await h.provider.models({ models: {} }, { auth })
|
|
expect(models[alias].free).toBe(true)
|
|
for (const [id, m] of Object.entries(models)) expect(m.free === true).toBe(id.endsWith("-Trial"))
|
|
expect(Object.values(plan).some((m) => m.free)).toBe(false)
|
|
})
|
|
|
|
test("an exhausted but active limited grant remains discoverable", async () => {
|
|
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
|
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
|
expect(models[alias]?.name).toBe(alias)
|
|
})
|
|
|
|
test("gift model names come from every live grant, not a fixed Flash model", async () => {
|
|
balance.balances[0].capabilities = ["model:" + original, "model:glm-another-preview", "tool:web-search"]
|
|
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
|
expect(Object.keys(models).filter((id) => id.endsWith("-Trial")).sort()).toEqual(["glm-another-preview-Trial", alias].sort())
|
|
expect(Object.keys(models).some((id) => id.includes("tool:"))).toBe(false)
|
|
})
|
|
|
|
test("expired grants do not add gift model entries", async () => {
|
|
balance.plans[0].ends_at = now - 1
|
|
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
|
expect(models[alias]).toBeUndefined()
|
|
})
|
|
|
|
test("fresh usage keeps gift discovery available after a bucket is spent", async () => {
|
|
const h = await hooks()
|
|
await h.auth.usage(async () => auth, { id: "zcode" })
|
|
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
|
await h.auth.usage(async () => auth, { id: "zcode" })
|
|
const models = await h.provider.models({ models: {} }, { auth })
|
|
expect(models[alias]?.name).toBe(alias)
|
|
})
|
|
|
|
test("a gift alias sends the original model only to the limited-quota endpoint", async () => {
|
|
expect((await send()).status).toBe(200)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0]).toMatchObject({ origin: "https://zcode.z.ai", body: { model: original } })
|
|
expect(JSON.stringify(sent[0].body)).not.toContain(alias)
|
|
})
|
|
|
|
test("a gift alias in a Request body is restored before sending upstream", async () => {
|
|
const loader = await (await hooks()).auth.loader(async () => auth, { id: "zcode" })
|
|
const request = new Request(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: alias, messages: [{ role: "user", content: "hi" }] }) })
|
|
expect((await loader.fetch(request)).status).toBe(200)
|
|
expect(sent[0]).toMatchObject({ origin: "https://zcode.z.ai", body: { model: original } })
|
|
})
|
|
|
|
test("a gift refusal does not spend the paid plan", async () => {
|
|
paid = 0
|
|
giftReply = new Response(JSON.stringify({ error: { message: "unavailable" } }), { status: 403, headers: { "content-type": "application/json" } })
|
|
expect((await send()).status).toBe(403)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
|
})
|
|
|
|
test("a gift quota error inside HTTP 200 becomes 429 without paid fallback", async () => {
|
|
paid = 0
|
|
giftReply = new Response(JSON.stringify({ code: "1005", msg: "exceed quota limit" }), { headers: { "content-type": "application/json" } })
|
|
expect((await send()).status).toBe(429)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
|
})
|
|
|
|
// plugins#817 (zane668): a gift-only account's own model, not a -Trial
|
|
// entry, out of its bucket for the day is answered 200 "exceed quota
|
|
// limit" as the trial entry's is. It says 429 too, its words kept, so
|
|
// magpie rests that model and not the account, whose other buckets
|
|
// (GLM-5.3-Flash's) still serve.
|
|
test("a gift-only account's plain model spent inside HTTP 200 becomes 429", async () => {
|
|
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ ...state, key: undefined, plan: undefined }), expires: 0 }
|
|
const said = { code: 1005, msg: "exceed quota limit", logid: "x" }
|
|
giftReply = new Response(JSON.stringify(said), { headers: { "content-type": "application/json" } })
|
|
const res = await send(original, only)
|
|
expect(res.status).toBe(429)
|
|
expect(await res.json()).toEqual(said)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0]).toMatchObject({ origin: "https://zcode.z.ai", body: { model: original } })
|
|
// an answer that is a reply stays the reply it was
|
|
giftReply = new Response(JSON.stringify({ type: "message", content: [{ type: "text", text: "1005" }] }), { headers: { "content-type": "application/json" } })
|
|
const fine = await send(original, only)
|
|
expect(fine.status).toBe(200)
|
|
expect((await fine.json()).content[0].text).toBe("1005")
|
|
})
|
|
|
|
// the coding plan's own spent answer inside a 200 is said the same way
|
|
test("the coding plan's spent answer inside HTTP 200 becomes 429", async () => {
|
|
planReply = new Response(JSON.stringify({ code: 1113, msg: "Insufficient balance or no resource package. Please recharge." }), { headers: { "content-type": "application/json" } })
|
|
const res = await send("glm-5.3")
|
|
expect(res.status).toBe(429)
|
|
expect((await res.json()).code).toBe(1113)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0].origin).toBe("https://api.z.ai")
|
|
})
|
|
|
|
test("an exhausted gift alias is refused locally without a paid request", async () => {
|
|
paid = 0
|
|
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
|
expect((await send()).status).toBe(429)
|
|
expect(sent).toHaveLength(0)
|
|
})
|
|
|
|
test("gift-only accounts can use their real gift alias", async () => {
|
|
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ ...state, key: undefined, plan: undefined }), expires: 0 }
|
|
expect((await send(alias, only)).status).toBe(200)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0].body.model).toBe(original)
|
|
})
|
|
|
|
test("gift quota applies to the alias without the paid-week constraint", async () => {
|
|
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
|
expect(u.windows[0].notModels).toContain(alias.toLowerCase())
|
|
expect(u.windows[1].models).toContain(alias)
|
|
expect(u.windows[1].used).toBe(25)
|
|
})
|
|
|
|
test("an exhausted gift remains scoped to its alias while paid quota stays usable", async () => {
|
|
paid = 20
|
|
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
|
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
|
expect(u.windows[0].notModels).toContain(alias.toLowerCase())
|
|
expect(u.windows[1].models).toEqual([alias])
|
|
expect(u.windows[1].used).toBe(100)
|
|
expect(u.windows[1].aside).not.toBe(true)
|
|
})
|
|
|
|
test("a spent sibling does not exhaust a gift alias with a live bucket", async () => {
|
|
balance.balances.push({ ...balance.balances[0], show_name: "Spent sibling", used_units: 100, remaining_units: 0 })
|
|
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
|
expect(u.windows[1].models).toContain(alias)
|
|
expect(u.windows[2].aside).toBe(true)
|
|
})
|
|
|
|
test("a temporary gift block never turns an alias into a paid request", async () => {
|
|
paid = 0
|
|
_internal.blocked.set(state.key + "\0" + jwt + "\0" + original, Date.now() + 60_000)
|
|
expect((await send()).status).toBe(429)
|
|
expect(sent).toHaveLength(0)
|
|
})
|
|
|
|
test("case variants of the same grant model keep one stable gift entry after usage refresh", async () => {
|
|
balance.balances[0].capabilities = ["model:" + original.toUpperCase()]
|
|
balance.balances.push({ ...balance.balances[0], capabilities: ["model:" + original], used_units: 100, remaining_units: 0 })
|
|
const h = await hooks()
|
|
const before = await h.provider.models({ models: {} }, { auth })
|
|
await h.auth.usage(async () => auth, { id: "zcode" })
|
|
const after = await h.provider.models({ models: {} }, { auth })
|
|
const ids = (m) => Object.keys(m).filter((id) => id.endsWith("-Trial"))
|
|
expect(ids(before)).toEqual([original.toUpperCase() + "-Trial"])
|
|
expect(ids(after)).toEqual(ids(before))
|
|
})
|
|
|
|
test("a grant ending before the normal route TTL is removed on the next model read", async () => {
|
|
balance.plans[0].ends_at = now + 30
|
|
const clientStart = now * 1000 + 1500
|
|
const clock = spyOn(Date, "now").mockReturnValue(clientStart)
|
|
try {
|
|
const h = await hooks()
|
|
expect((await h.provider.models({ models: {} }, { auth }))[alias]).toBeDefined()
|
|
balance.server_time = now + 31
|
|
clock.mockReturnValue(clientStart + 31_000)
|
|
expect((await h.provider.models({ models: {} }, { auth }))[alias]).toBeUndefined()
|
|
} finally {
|
|
clock.mockRestore()
|
|
}
|
|
})
|
|
|
|
test("a gift-only account's spent Start Plan bucket doesn't hold up a model its Trust Build still has", async () => {
|
|
// ganlerk's account (Discord): Trust Build's GLM-5.3-Flash 14.5% used,
|
|
// the Start Plan's GLM-5.3-Flash all used, its GLM-5.3 untouched
|
|
balance.plans = [
|
|
{ plan_id: "trust", user_plan_id: "t1", name: "ZCode Trust Build", status: "active", ends_at: now + 86400 },
|
|
{ plan_id: "start", user_plan_id: "s1", name: "ZCode Start Plan", status: "active", ends_at: now + 7 * 86400 },
|
|
]
|
|
balance.balances = [
|
|
{ plan_id: "start", user_plan_id: "s1", show_name: "GLM-5.3", capabilities: ["model:GLM-5.3"], total_units: 3_000_000, used_units: 0, remaining_units: 3_000_000 },
|
|
{ plan_id: "start", user_plan_id: "s1", show_name: "GLM-5.3-Flash", capabilities: ["model:GLM-5.3-Flash"], total_units: 5_000_000, used_units: 5_000_000, remaining_units: 0 },
|
|
{ plan_id: "trust", user_plan_id: "t1", show_name: "GLM-5.3-Flash", capabilities: ["model:GLM-5.3-Flash"], total_units: 100_000_000, used_units: 14_501_196, remaining_units: 85_498_804, expires_at: now + 3600 },
|
|
]
|
|
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ ...state, key: undefined, plan: undefined }), expires: 0 }
|
|
const u = await (await hooks()).auth.usage(async () => only, { id: "zcode" })
|
|
const counting = (m) => u.windows.filter((w) => !w.aside && w.models?.some((x) => x.toLowerCase() === m.toLowerCase()))
|
|
for (const m of ["GLM-5.3-Flash", "GLM-5.3-Flash-Trial"]) {
|
|
expect(counting(m)).toHaveLength(1)
|
|
expect(counting(m)[0].used).toBeCloseTo(14.5, 1)
|
|
}
|
|
expect(counting("GLM-5.3")[0].used).toBe(0)
|
|
// the spent bucket is still on the card, as ZCode shows it
|
|
expect(u.windows.find((w) => w.used === 100)).toMatchObject({ name: "GLM-5.3-Flash · ZCode Start Plan", aside: true })
|
|
expect(u.windows).toHaveLength(3)
|
|
})
|
|
|
|
test("a gift-only account lists its gift's models by their own names, as ZCode does (#1261)", async () => {
|
|
// sun1090's account: no GLM Coding Plan, the Start Plan's GLM-5.3 and
|
|
// GLM-5.3-Flash buckets; the card counted GLM-5.3 while the list had only
|
|
// GLM-5.3-Trial, as the Start Plan's config leaves GLM-5.3 out
|
|
balance.plans = [{ plan_id: "start", user_plan_id: "s1", name: "ZCode Start Plan", status: "active", ends_at: now + 7 * 86400 }]
|
|
balance.balances = [
|
|
{ plan_id: "start", user_plan_id: "s1", show_name: "GLM-5.3", capabilities: ["model:GLM-5.3"], total_units: 3_000_000, used_units: 41_030, remaining_units: 2_958_970 },
|
|
{ plan_id: "start", user_plan_id: "s1", show_name: "GLM-5.3-Flash", capabilities: ["model:GLM-5.3-Flash"], total_units: 5_000_000, used_units: 170_088, remaining_units: 4_829_912 },
|
|
]
|
|
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ ...state, key: undefined, plan: undefined }), expires: 0 }
|
|
const h = await hooks()
|
|
const models = await h.provider.models({ models: {} }, { auth: only })
|
|
expect(models["GLM-5.3"]).toMatchObject({ id: "GLM-5.3", name: "GLM-5.3", api: { id: "GLM-5.3" } })
|
|
expect(Object.keys(models["GLM-5.3"].variants ?? {})).toEqual(["low", "high", "max"])
|
|
// the trial entries a user may have picked stay, and nothing is listed twice
|
|
expect(models["GLM-5.3-Trial"]).toBeDefined()
|
|
expect(models["GLM-5.3-Flash-Trial"]).toBeDefined()
|
|
const ids = Object.keys(models).map((id) => id.toLowerCase())
|
|
expect(new Set(ids).size).toBe(ids.length)
|
|
// every model the card counts is one the list has
|
|
const u = await h.auth.usage(async () => only, { id: "zcode" })
|
|
for (const w of u.windows) for (const m of w.models ?? []) expect(models[m]).toBeDefined()
|
|
// and a request for it goes to the Start Plan
|
|
const loader = await h.auth.loader(async () => only, { id: "zcode" })
|
|
await loader.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "GLM-5.3", messages: [{ role: "user", content: "hi" }], max_tokens: 10 }) })
|
|
expect(sent.at(-1)).toMatchObject({ origin: "https://zcode.z.ai", body: { model: "GLM-5.3" } })
|
|
})
|
|
|
|
test("a coding plan account's gift stays on its trial entries alone", async () => {
|
|
balance.balances[0].capabilities = ["model:GLM-5.3"]
|
|
const coding = await (await hooks()).provider.models({ models: {} }, { auth: { type: "api", key: state.key } })
|
|
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
|
expect(Object.keys(models).filter((id) => !(id in coding))).toEqual(["GLM-5.3-Trial"])
|
|
})
|
|
|
|
// 01huadalang's account (Discord, 10-24): the new-user Start Plan and the
|
|
// 1024 Dev Day plan both give GLM-5.3, and the new-user one is spent. The
|
|
// 1024 plan's id, name, show_names, capabilities and grant_units are the
|
|
// real /billing/preview bytes of an account it was offered to; its balance
|
|
// rows are written in the shape the balance gives (no 1024 balance was
|
|
// read), with the Start Plan's name as ganlerk's balance has it.
|
|
const twoPlans = () => {
|
|
balance.plans = [
|
|
{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", name: "ZCode Start Plan", status: "active", ends_at: now + 7 * 86400 },
|
|
{ plan_id: "zcode-v3-start-plan-1024", user_plan_id: "d1", name: "ZCode 1024 Dev Day", status: "active", ends_at: now + 30 * 86400 },
|
|
]
|
|
balance.balances = [
|
|
{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", show_name: "GLM-5.3", capabilities: ["model:glm-5.3"], total_units: 3_000_000, used_units: 3_000_000, remaining_units: 0 },
|
|
{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", show_name: "GLM-5.3-Flash", capabilities: ["model:glm-5.3-flash"], total_units: 5_000_000, used_units: 0, remaining_units: 5_000_000 },
|
|
{ plan_id: "zcode-v3-start-plan-1024", user_plan_id: "d1", entitlement_id: "ent-zcode-v3-start-plan-1024-1", show_name: "GLM-5.3-Flash", capabilities: ["model:glm-5.3-flash"], total_units: 300_000_000, used_units: 30_000_000, remaining_units: 270_000_000 },
|
|
{ plan_id: "zcode-v3-start-plan-1024", user_plan_id: "d1", entitlement_id: "ent-zcode-v3-start-plan-1024-2", show_name: "GLM-5.3", capabilities: ["model:glm-5.3"], total_units: 200_000_000, used_units: 50_000_000, remaining_units: 150_000_000 },
|
|
]
|
|
}
|
|
|
|
test("two gift plans' GLM-5.3 each show, named by plan, the live one first (01huadalang)", async () => {
|
|
twoPlans()
|
|
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ ...state, key: undefined, plan: undefined }), expires: 0 }
|
|
const u = await (await hooks()).auth.usage(async () => only, { id: "zcode" })
|
|
const names = u.windows.map((w) => w.name)
|
|
expect(new Set(names).size).toBe(names.length)
|
|
// the 1024 plan's GLM-5.3 shows its own amount left, and counts the model
|
|
expect(u.windows.find((w) => w.name === "GLM-5.3 · ZCode 1024 Dev Day")).toMatchObject({ used: 25, amount: 50_000_000, limit: 200_000_000, models: ["glm-5.3", "GLM-5.3-Trial"] })
|
|
expect(u.windows.find((w) => w.name === "GLM-5.3 · ZCode 1024 Dev Day").aside).toBeUndefined()
|
|
// the spent new-user plan's GLM-5.3 still shows, used up, set aside
|
|
expect(u.windows.find((w) => w.name === "GLM-5.3 · ZCode Start Plan")).toMatchObject({ used: 100, amount: 3_000_000, aside: true })
|
|
// magpie's account row shows a card's first two windows: what is spent now
|
|
expect(u.windows.slice(0, 2).every((w) => !w.aside)).toBe(true)
|
|
expect(u.windows.slice(0, 2).some((w) => w.name === "GLM-5.3 · ZCode 1024 Dev Day")).toBe(true)
|
|
})
|
|
|
|
test("a coding plan account's two gift plans' GLM-5.3 each show, named by plan", async () => {
|
|
twoPlans()
|
|
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
|
const gift = u.windows.slice(1)
|
|
expect(gift.map((w) => w.name)).toEqual([
|
|
"GLM-5.3-Flash-Trial · ZCode Start Plan",
|
|
"GLM-5.3-Trial · ZCode 1024 Dev Day",
|
|
"GLM-5.3 · ZCode Start Plan",
|
|
"GLM-5.3-Flash · ZCode 1024 Dev Day",
|
|
])
|
|
expect(gift[1]).toMatchObject({ used: 25, models: ["GLM-5.3-Trial"] })
|
|
expect(gift[2]).toMatchObject({ used: 100, aside: true })
|
|
})
|
|
|
|
// bigsteven (Discord, 10-24): GLM Coding Plan spent, no GLM-5.3-Trial in
|
|
// the list. ZCode's config out of reach marks the list a fallback, and
|
|
// magpie then keeps the list it was told last, from before the gift: the
|
|
// -Trial entries just read went with it. A list with trial entries is
|
|
// told as it is.
|
|
test("ZCode's config out of reach still tells a gift's -Trial entries, not a fallback", async () => {
|
|
_internal.config(null)
|
|
try {
|
|
balance.balances[0].capabilities = ["model:glm-5.3"]
|
|
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
|
expect(models["GLM-5.3-Trial"]?.name).toBe("GLM-5.3-Trial")
|
|
expect(models[Symbol.for("magpie.fellBack")]).toBeUndefined()
|
|
// with no gift there is nothing new to tell: still a fallback
|
|
_internal.routes.clear()
|
|
balance.plans = []
|
|
const none = await (await hooks()).provider.models({ models: {} }, { auth })
|
|
expect(Object.keys(none).some((id) => id.endsWith("-Trial"))).toBe(false)
|
|
expect(none[Symbol.for("magpie.fellBack")]).toBe(true)
|
|
} finally {
|
|
_internal.config(undefined)
|
|
}
|
|
})
|
|
|
|
test("a gift read that failed lists its -Trial entries again a minute later", async () => {
|
|
balance.balances[0].capabilities = ["model:glm-5.3"]
|
|
const good = balance
|
|
balance = null
|
|
const was = globalThis.fetch
|
|
globalThis.fetch = async (input, init) => {
|
|
if (balance === null && new URL(String(input)).pathname === "/api/v1/zcode-plan/billing/balance") return new Response("", { status: 502 })
|
|
return was(input, init)
|
|
}
|
|
const h = await hooks()
|
|
expect((await h.provider.models({ models: {} }, { auth }))["GLM-5.3-Trial"]).toBeUndefined()
|
|
balance = good
|
|
const r = _internal.routes.get(state.key + "\0" + jwt)
|
|
r.at -= 61_000
|
|
expect((await h.provider.models({ models: {} }, { auth }))["GLM-5.3-Trial"]?.name).toBe("GLM-5.3-Trial")
|
|
})
|
|
|
|
// a key, or a sign-in whose ZCode session ran out, reads no gift: the card
|
|
// says why there are no -Trial entries instead of leaving them out unsaid
|
|
test("a coding plan with no live ZCode session says its gift plans need ZCode's sign-in", async () => {
|
|
const line = (u) => u.windows.find((w) => w.name === "ZCode gift plans (-Trial models) need ZCode's sign-in")
|
|
const h = await hooks()
|
|
const key = await h.auth.usage(async () => ({ type: "api", key: state.key }), { id: "zcode" })
|
|
expect(line(key)).toEqual({ name: "ZCode gift plans (-Trial models) need ZCode's sign-in", used: 0, aside: true, display: "not read with an API key: add the account with a ZCode sign-in" })
|
|
expect(Object.keys(await h.provider.models({ models: {} }, { auth: { type: "api", key: state.key } })).some((id) => id.endsWith("-Trial"))).toBe(false)
|
|
const dead = ["{}", JSON.stringify({ exp: now - 60 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".synthetic"
|
|
const aged = { ...auth, refresh: JSON.stringify({ ...state, jwt: dead }) }
|
|
const u = await h.auth.usage(async () => aged, { id: "zcode" })
|
|
expect(u.error).toBeUndefined()
|
|
expect(line(u)?.display).toBe("ZCode's sign-in has expired: sign in again")
|
|
expect(Object.keys(await h.provider.models({ models: {} }, { auth: aged })).some((id) => id.endsWith("-Trial"))).toBe(false)
|
|
// a live session reads the gift: no such line, its -Trial entries listed
|
|
const live = await h.auth.usage(async () => auth, { id: "zcode" })
|
|
expect(line(live)).toBeUndefined()
|
|
expect(live.windows.some((w) => w.name.includes("-Trial") || (w.models ?? []).some((m) => m.endsWith("-Trial")))).toBe(true)
|
|
})
|
|
|
|
// Danbuth (plugins#504): a GLM Coding Max account that claimed ZCode's
|
|
// Start Plan (plan_id zcode-v3-start-plan-1029, named "ZCODE GLOBAL
|
|
// BUILD") found no Start Plan on the card. It was there, as the third
|
|
// window, but magpie's ring and account row cut a long name short and
|
|
// "ZCODE GLOBAL BUI…" named neither the model nor the plan's kind. The
|
|
// Coding windows are a real /quota/limit reply (the owner's account, 10-30);
|
|
// the plan row is the real /billing/balance plan kongbai01203 read in
|
|
// #503, its times moved to now; its buckets have the shape of ganlerk's
|
|
// Start Plan balance (no balance of this plan was read). ZCode's own
|
|
// "Today's balance" lists a bucket by its show_name, so the window's name
|
|
// starts with it and the plan follows.
|
|
test("a coding plan account's ZCODE GLOBAL BUILD gift is named by its model first (Danbuth, #504)", async () => {
|
|
const limit = { limits: [{ type: "CREDIT_LIMIT", unit: 3, number: 5, usage: 2000, currentValue: 0, remaining: 2000, percentage: 0 }, { type: "CREDIT_LIMIT", unit: 6, number: 1, usage: 10000, currentValue: 68, remaining: 9931, percentage: 1, nextResetTime: (now + 86400) * 1000 }], level: "lite" }
|
|
const mocked = globalThis.fetch
|
|
globalThis.fetch = async (input, init) => new URL(String(input)).pathname === "/api/monitor/usage/quota/limit"
|
|
? new Response(JSON.stringify({ code: 200, msg: "Operation successful", data: limit, success: true }), { headers: { "content-type": "application/json" } })
|
|
: mocked(input, init)
|
|
balance.plans = [{ plan_id: "zcode-v3-start-plan-1029", name: "ZCODE GLOBAL BUILD", status: "active", starts_at: now - 45440, ends_at: now + 3737 }]
|
|
balance.balances = [
|
|
{ plan_id: "zcode-v3-start-plan-1029", show_name: "GLM-5.3", capabilities: ["model:GLM-5.3"], total_units: 3_000_000, used_units: 450_000, remaining_units: 2_550_000 },
|
|
{ plan_id: "zcode-v3-start-plan-1029", show_name: "GLM-5.3-Flash", capabilities: ["model:GLM-5.3-Flash"], total_units: 5_000_000, used_units: 0, remaining_units: 5_000_000 },
|
|
]
|
|
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
|
expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Weekly", "GLM-5.3-Trial · ZCODE GLOBAL BUILD", "GLM-5.3-Flash-Trial · ZCODE GLOBAL BUILD"])
|
|
expect(u.windows[2]).toMatchObject({ used: 15, amount: 450_000, limit: 3_000_000, models: ["GLM-5.3-Trial"] })
|
|
expect(u.windows[3]).toMatchObject({ used: 0, limit: 5_000_000, models: ["GLM-5.3-Flash-Trial"] })
|
|
})
|
|
|
|
test("a flash gift goes out under ZCode's registry spelling, as the app sends it", async () => {
|
|
balance.balances[0].capabilities = ["model:glm-5.3-flash"]
|
|
expect((await send("GLM-5.3-Flash-Trial")).status).toBe(200)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
|
expect(sent[0].body.model).toBe("GLM-5.3-Flash")
|
|
})
|
|
|
|
test("a refused-then-rested gift says why it is refused locally", async () => {
|
|
giftReply = new Response(JSON.stringify({ error: { code: "1302", message: "rate limit" } }), { status: 429, headers: { "content-type": "application/json" } })
|
|
expect((await send()).status).toBe(429)
|
|
const again = await send()
|
|
expect(again.status).toBe(429)
|
|
expect(sent).toHaveLength(1)
|
|
expect((await again.json()).error.message).toContain("not asked again for a minute")
|
|
})
|
|
|
|
// young02036 (Discord, 11-05): two ZCode accounts, one with no GLM Coding
|
|
// Plan whose Start Plan holds only GLM-5.3-Flash, one subscribed whose
|
|
// gift is GLM-5.3-Flash-Trial. The gift-only account listed every model
|
|
// the Start Plan's config names (GLM-5.2, GLM-5-Turbo…), so magpie sent it
|
|
// models its balance has no bucket for, which the ZCode app never offers:
|
|
// the app lists a Start Plan account's models from its balance alone
|
|
// (resolveStartPlanBalanceAvailability). Now the gift-only account lists
|
|
// what its balance names, and a request for anything else is never routed
|
|
// to it. The config's list stands only when the balance names no model.
|
|
test("a gift-only account lists only the models its balance names (young02036)", async () => {
|
|
_internal.config({
|
|
revision: 1,
|
|
config: {
|
|
providerConfigRules: { providerRules: [{ providerId: "account:zai-start-plan", builtinModelIds: ["GLM-5.3-Flash", "GLM-5.2", "GLM-5-Turbo"] }] },
|
|
modelConfigRules: { modelRules: [{ modelMatch: "GLM-5\\.3-Flash", config: { properties: { contextWindow: 1_000_000 }, optionSpecs: { maxOutputTokens: { max: 128_000 }, reasoningLevel: { values: ["low", "high", "max"] } } } }] },
|
|
},
|
|
})
|
|
try {
|
|
balance.plans = [{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", name: "ZCode Start Plan", status: "active", ends_at: now + 7 * 86400 }]
|
|
balance.balances = [{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", show_name: "GLM-5.3-Flash", capabilities: ["model:glm-5.3-flash"], total_units: 5_000_000, used_units: 0, remaining_units: 5_000_000 }]
|
|
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ ...state, key: undefined, plan: undefined }), expires: 0 }
|
|
const models = await (await hooks()).provider.models({ models: {} }, { auth: only })
|
|
expect(Object.keys(models).sort()).toEqual(["GLM-5.3-Flash", "GLM-5.3-Flash-Trial"])
|
|
expect(models["GLM-5.3-Flash"].limit.context).toBe(1_000_000)
|
|
// a balance that names no model leaves the config's list standing
|
|
_internal.routes.clear()
|
|
balance.balances = []
|
|
const bare = await (await hooks()).provider.models({ models: {} }, { auth: only })
|
|
expect(Object.keys(bare).sort()).toEqual(["GLM-5-Turbo", "GLM-5.2", "GLM-5.3-Flash"])
|
|
} finally {
|
|
_internal.config(undefined)
|
|
}
|
|
})
|
|
|
|
// heduian and bg5eau on X (11-14): on a weekend the GLM-5.3-Flash-Trial
|
|
// pick answered only "no active limited quota". The weekend plan
|
|
// (ZCODE WEEKEND BUILD, testdata/touch-1030-wk.json, the feed's real
|
|
// reply) is a gift ZCode holds until it is claimed, and its claim needs
|
|
// the ZCode app's captcha, which the plugin doesn't post. The refusal
|
|
// now names the held plan and where it is claimed; it still asks no
|
|
// model and posts no claim, and the feed is read once for a retry.
|
|
test("a -Trial pick with no gift names the weekend plan ZCode holds unclaimed", async () => {
|
|
const touch = readFileSync(new URL("./testdata/touch-1030-wk.json", import.meta.url), "utf8")
|
|
balance = { server_time: now, plans: [], balances: [] }
|
|
_internal.unclaimedSeen.clear()
|
|
const asked = []
|
|
const base = globalThis.fetch
|
|
globalThis.fetch = async (input, init = {}) => {
|
|
const url = new URL(input instanceof Request ? input.url : String(input))
|
|
if (url.pathname === "/api/v1/marketing/touch") {
|
|
asked.push((init.method ?? "GET").toUpperCase())
|
|
return new Response(touch, { headers: { "content-type": "application/json" } })
|
|
}
|
|
if (url.pathname === "/api/v1/zcode-plan/billing/claim") throw new Error("a claim was posted")
|
|
return base(input, init)
|
|
}
|
|
for (let i = 0; i < 2; i++) {
|
|
const res = await send("GLM-5.3-Flash-Trial")
|
|
expect(res.status).toBe(400)
|
|
const { error } = await res.json()
|
|
expect(error.message).toStartWith("ZCode has no active limited quota for GLM-5.3-Flash-Trial. ")
|
|
expect(error.message).toContain("ZCODE WEEKEND BUILD")
|
|
expect(error.message).toContain("claim it in the ZCode app")
|
|
}
|
|
expect(asked).toEqual(["GET"])
|
|
expect(sent).toHaveLength(0)
|
|
})
|
|
|
|
test("a -Trial pick with no gift and nothing held says only that there is none", async () => {
|
|
balance = { server_time: now, plans: [], balances: [] }
|
|
_internal.unclaimedSeen.clear()
|
|
const base = globalThis.fetch
|
|
globalThis.fetch = async (input, init = {}) => {
|
|
const url = new URL(input instanceof Request ? input.url : String(input))
|
|
if (url.pathname === "/api/v1/marketing/touch") return ok({ deliveries: [] })
|
|
return base(input, init)
|
|
}
|
|
const res = await send("GLM-5.3-Flash-Trial")
|
|
expect(res.status).toBe(400)
|
|
expect((await res.json()).error.message).toBe("ZCode has no active limited quota for GLM-5.3-Flash-Trial")
|
|
expect(sent).toHaveLength(0)
|
|
})
|
|
|
|
test("a -Trial pick whose feed doesn't read says only that there is none, and asks the feed again", async () => {
|
|
balance = { server_time: now, plans: [], balances: [] }
|
|
_internal.unclaimedSeen.clear()
|
|
let reads = 0
|
|
const base = globalThis.fetch
|
|
globalThis.fetch = async (input, init = {}) => {
|
|
const url = new URL(input instanceof Request ? input.url : String(input))
|
|
if (url.pathname === "/api/v1/marketing/touch") return reads++, new Response("bad gateway", { status: 502 })
|
|
return base(input, init)
|
|
}
|
|
for (let i = 0; i < 2; i++) expect((await (await send("GLM-5.3-Flash-Trial")).json()).error.message).toBe("ZCode has no active limited quota for GLM-5.3-Flash-Trial")
|
|
expect(reads).toBe(2)
|
|
})
|
|
|
|
// bg5eau on X (11-14): "the gift isn't spent, pay-as-you-go is charged".
|
|
// A key with no coding plan sends every request to the Start Plan, which
|
|
// serves the models its balance names; ZCode's app offers only those
|
|
// (resolveStartPlanBalanceAvailability). Another model the agent was left
|
|
// on spent none of the gift. It is now answered here, and a plan-list read
|
|
// that fails no longer moves such an account onto the coding plan's host,
|
|
// where its key is billed pay-as-you-go.
|
|
const giftOnly = (subs) => {
|
|
balance.plans = [{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", name: "ZCode Start Plan", status: "active", ends_at: now + 7 * 86400 }]
|
|
balance.balances = [{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", show_name: "GLM-5.3-Flash", capabilities: ["model:glm-5.3-flash"], total_units: 5_000_000, used_units: 0, remaining_units: 5_000_000 }]
|
|
const base = globalThis.fetch
|
|
globalThis.fetch = async (input, init = {}) => {
|
|
const url = new URL(input instanceof Request ? input.url : String(input))
|
|
if (url.pathname === "/api/biz/subscription/list") return subs()
|
|
return base(input, init)
|
|
}
|
|
}
|
|
const noPlan = { type: "oauth", access: state.key, refresh: JSON.stringify({ ...state, plan: undefined }), expires: 0 }
|
|
|
|
const listed = async (credentials = noPlan) => (await hooks()).provider.models({ models: {} }, { auth: credentials })
|
|
|
|
test("a gift-only account's model its balance doesn't name is not sent (bg5eau)", async () => {
|
|
giftOnly(() => ok([]))
|
|
expect(Object.keys(await listed())).toContain("GLM-5.3-Flash")
|
|
const res = await send("GLM-5.2", noPlan)
|
|
expect(res.status).toBe(400)
|
|
const { error } = await res.json()
|
|
expect(error.message).toContain("serves GLM-5.3-Flash;")
|
|
expect(error.message).toContain("GLM-5.2 is not among them")
|
|
expect(sent).toHaveLength(0)
|
|
expect((await send("GLM-5.3-Flash", noPlan)).status).toBe(200)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0]).toMatchObject({ origin: "https://zcode.z.ai", body: { model: "GLM-5.3-Flash" } })
|
|
})
|
|
|
|
test("a gift-only account reads no balance for a request whose model the list's balance names", async () => {
|
|
giftOnly(() => ok([]))
|
|
await listed()
|
|
let reads = 0
|
|
const base = globalThis.fetch
|
|
globalThis.fetch = async (input, init = {}) => {
|
|
if (new URL(input instanceof Request ? input.url : String(input)).pathname === "/api/v1/zcode-plan/billing/balance") reads++
|
|
return base(input, init)
|
|
}
|
|
for (let i = 0; i < 3; i++) expect((await send("GLM-5.3-Flash", noPlan)).status).toBe(200)
|
|
expect(reads).toBe(0)
|
|
})
|
|
|
|
test("a gift claimed since the list was read is sent, not refused", async () => {
|
|
giftOnly(() => ok([]))
|
|
await listed()
|
|
balance.balances.push({ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", show_name: "GLM-5.2", capabilities: ["model:glm-5.2"], total_units: 100, used_units: 0, remaining_units: 100 })
|
|
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
|
})
|
|
|
|
test("a gift-only account whose balance doesn't read again sends the request as before", async () => {
|
|
giftOnly(() => ok([]))
|
|
await listed()
|
|
const base = globalThis.fetch
|
|
globalThis.fetch = async (input, init = {}) => {
|
|
const url = new URL(input instanceof Request ? input.url : String(input))
|
|
if (url.pathname === "/api/v1/zcode-plan/billing/balance") return new Response("bad gateway", { status: 502 })
|
|
return base(input, init)
|
|
}
|
|
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
|
expect(sent).toHaveLength(1)
|
|
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
|
})
|
|
|
|
test("a gift-only account stays on the Start Plan when its plan list stops reading (bg5eau)", async () => {
|
|
let down = false
|
|
giftOnly(() => (down ? new Response("bad gateway", { status: 502 }) : ok([])))
|
|
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
|
// GLM-5.2, which the gift doesn't serve: free first would take a
|
|
// gift model to the gift on either route
|
|
// the route's ten minutes pass, and the next plan-list read fails
|
|
for (const r of _internal.routes.values()) r.at = 0
|
|
down = true
|
|
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
|
expect(sent.map((x) => x.origin)).toEqual(["https://zcode.z.ai", "https://zcode.z.ai"])
|
|
})
|
|
|
|
test("a coding plan account whose plan list stops reading still takes the plan", async () => {
|
|
let down = false
|
|
giftOnly(() => (down ? new Response("bad gateway", { status: 502 }) : ok([{ productName: "GLM Coding Pro", status: "VALID" }])))
|
|
balance.balances = []
|
|
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
|
for (const r of _internal.routes.values()) r.at = 0
|
|
down = true
|
|
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
|
expect(sent.map((x) => x.origin)).toEqual(["https://api.z.ai", "https://api.z.ai"])
|
|
})
|