Why: 0.1.8 sent every request for a gift-served model to the gift first, so a user who meant to spend the coding plan had no say, and the card hid the gift's models behind notModels. The gift is an allowance outside the plan; spending it should be a choice. What: every model a live gift bucket serves is listed again as <model>-Trial, in the catalog's spelling (GLM-5.3-Flash-Trial), and a request for that entry goes to the gift dressed as ZCode's own; a plain model always spends the coding plan. A trial entry whose bucket is spent or blocked answers 429 without touching the coding plan, as do the gift's quota errors (1113, 1005 inside a 200); any other gift answer goes on as it came. The usage card names the gift window by its trial model, drops the plan prefix, and puts MCP - Month last. Tests: dual.test.mjs rewritten for the new routing (a plain model to the coding plan whatever the gift holds, a trial entry to the gift), usage.test.mjs and gift.test.mjs follow the naming; bun test (65 pass in the package, 516 in the repo) and bun scripts/check.mjs zcode pass.
189 lines
9.7 KiB
JavaScript
189 lines
9.7 KiB
JavaScript
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"
|
|
import { homedir, tmpdir } from "node:os"
|
|
import { 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
|
|
|
|
beforeEach(() => {
|
|
_internal.routes.clear()
|
|
_internal.blocked.clear()
|
|
sent.length = 0
|
|
paid = 100
|
|
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) })
|
|
return url.origin === "https://zcode.z.ai" ? giftReply.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])
|
|
})
|
|
|
|
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")
|
|
})
|
|
|
|
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()
|
|
}
|
|
})
|