From 3b3209e0ddd2c47ee5c8f77b5541131e0aa178fe Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 29 Oct 2026 22:31:07 +0800 Subject: [PATCH] zcode 0.1.34: a gift plan that starts later is named with its start, and gift buckets beside a Coding Plan carry their plan's name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit windy (Discord): "添加zcode供应商的时候,好像无法区分Coding Plan 和Start Plan的额度? 例如今天23点要生效的Start Plan就没显示". - A plan on /billing/balance whose starts_at is still to come serves nothing yet: startPlan no longer routes to it (an "active" plan with a future start would have been), and its buckets don't count. The card names it in an aside line "ZCode gift plan not started yet", display " · ", soonest first. - A coding account with a ZCode session reads the gift on every card read, not only while a gift is live, so a coming plan shows beside the Coding Plan. The route cache is read again when the coming plan starts. - A gift-only account whose only plan starts later gets a card with that line instead of "ended or never started". - Beside a Coding Plan, every gift bucket is prefixed with its plan's name ("Start Plan · GLM-5.1-Trial"), one plan or several. Not known: which status ZCode gives a plan that hasn't started. The fixtures use starts_at as the real balance/preview replies carry it (Unix seconds) and try both "active" and an unknown status word; any status but "expired" with a future starts_at is taken as coming. No real account with a pending plan was read. Run on mote: HOME=$(mktemp -d) bun test in packages/zcode, 142 pass 0 fail; pending.test.mjs under TZ=UTC, Pacific/Kiritimati and America/Los_Angeles, 7 pass each; bun scripts/check.mjs, every package ok. Broken by hand: with the old index.mjs, 6 of pending.test.mjs's 7 tests fail (the 7th, a plan whose start has come, passes on both). --- packages/zcode/README.md | 14 +++- packages/zcode/dual.test.mjs | 2 +- packages/zcode/index.mjs | 72 +++++++++++++---- packages/zcode/package.json | 2 +- packages/zcode/pending.test.mjs | 134 ++++++++++++++++++++++++++++++++ packages/zcode/usage.test.mjs | 2 +- 6 files changed, 207 insertions(+), 19 deletions(-) create mode 100644 packages/zcode/pending.test.mjs diff --git a/packages/zcode/README.md b/packages/zcode/README.md index d84327f..a9cc96c 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -166,7 +166,19 @@ and end. The card's plan and term stay the coding plan's. A gift read that fails leaves just the coding card — magpie hides a card's windows behind an error, so a gift hiccup must not black out a working Coding Plan. A gift that goes out of date while requests use it simply stops -showing. +showing. Beside the coding plan's windows each gift bucket is named +after its plan ("Start Plan · GLM-5.1-Trial"), one plan or several, so +the two allowances can't be read as one. + +**Gift plans that start later.** A plan on the balance whose `starts_at` +is still to come (a Start Plan taking effect at 23:00 today) serves +nothing yet: no request goes to it and its buckets don't count. The card +names it in a line set aside, "ZCode gift plan not started yet", with +the plan's name and its start in this computer's time as the display +("Start Plan · 2026-10-29 23:00"), soonest first. An account whose only +gift plan starts later gets a card with that line, not "ended or never +started". The status ZCode gives such a plan has not been seen, so any +status but `expired` is taken; `starts_at` decides it. **Resets.** A GLM Coding Plan of the account's own, and a team seat, show the resets the vendor's usage page lists diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index 03dc9ba..bf96759 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -198,7 +198,7 @@ test("the card shows the Coding windows and the gift's buckets together", async expect(u.plan).toBe("GLM Coding Pro") expect(u.signIn).toBe("kept") expect(u.error).toBeUndefined() - expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Trust Build"]) + expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Start Plan · Trust Build"]) expect(u.windows[1]).toMatchObject({ used: 25, display: "250 / 1000", models: ["GLM-5.3-Flash-Trial"] }) expect(u.until).toBeUndefined() expect(u.renew).toBeUndefined() diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 4085159..dcb3aea 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -182,7 +182,7 @@ async function startPlan(jwt, device) { for (const p of plans) { const st = String(p?.status ?? "").trim().toLowerCase() const end = num(p?.ends_at) - if (st !== "active" || (end > 0 && end <= now)) continue + if (st !== "active" || (end > 0 && end <= now) || notStarted(p, now)) continue any = true if (end > 0) ttl = Math.min(ttl, (end - now) * 1000) if (!name) name = String(p?.name ?? "").trim() @@ -520,6 +520,28 @@ function startNum(v) { return undefined } +// notStarted is a plan whose starts_at is still to come (a Start Plan +// that takes effect at 23:00 today, windy on Discord): it serves nothing +// yet, so no request is routed to it and its buckets don't count, but the +// card names it with its start. ZCode's balance gives every plan a +// starts_at in Unix seconds; which status a plan not started yet carries +// is not known, so any but "expired" is taken. +function notStarted(p, now) { + const at = startNum(p?.starts_at) + return at > now && String(p?.status ?? "").trim().toLowerCase() !== "expired" +} + +// PENDING is the card's line for a gift plan that has not started yet: a +// fixed sentence, so magpie translates it; the plan's name and its start, +// in this computer's time, are the display. Set aside: it stops nothing. +const PENDING = "ZCode gift plan not started yet" +const two = (n) => String(n).padStart(2, "0") +const localTime = (sec) => { + const d = new Date(Math.trunc(sec) * 1000) + return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}` +} +const pendingLines = (g) => (g?.pending ?? []).map((p) => ({ name: PENDING, used: 0, aside: true, display: `${p.name} · ${localTime(p.start)}` })) + // giftOf reads the balance and returns the gift's card fields: its plans and // windows. Several plans can be active at once, so every live plan's buckets // show, each keeping its own models and end; the plan and end put on the @@ -551,21 +573,28 @@ async function giftOf(s) { return keep }) + // a plan not started yet is named with its start, soonest first; its + // buckets, if the balance lists any, wait for it + const pending = plans.filter((p) => notStarted(p, now)) + .map((p) => ({ name: first(str(p.name), "Start Plan"), start: startNum(p.starts_at) })) + .sort((a, b) => a.start - b.start) + // every live plan counts as the gift: no plan-name filter decides it, // the balance says what the session can spend let active = null for (const p of plans) { - if (p.status.trim().toLowerCase() !== "active") continue + if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) continue const end = startNum(p.ends_at) if (end > 0 && end <= now) continue if (active && !(end > 0 && (!startNum(active.end) || end < startNum(active.end)))) continue active = { name: first(str(p.name), "Start Plan"), end, until: end > 0 ? new Date(Math.trunc(end) * 1000).toISOString() : "" } } - if (!active) return null - const out = { plan: active.name, windows: [] } - if (active.until) Object.assign(out, { until: active.until, renew: "off" }) + if (!active && !pending.length) return null + // with no live plan, the one starting soonest names the card + const out = { plan: active?.name ?? pending[0].name, windows: [], live: !!active, pending } + if (active?.until) Object.assign(out, { until: active.until, renew: "off" }) const live = plans.filter((p) => { - if (p.status.trim().toLowerCase() !== "active") return false + if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) return false const end = startNum(p.ends_at) return !(end > 0 && end <= now) }) @@ -678,6 +707,9 @@ async function startUsage(s) { } return { ...w, models: [...models, ...models.map(giftID)] } })) + g.windows.push(...pendingLines(g)) + delete g.live + delete g.pending return g } @@ -715,6 +747,12 @@ function bestBuckets(windows) { return best } +// giftReadable: ZCode's session can read the gift beside a coding plan, +// so the card asks for it even when no gift is live for requests: a plan +// that starts later is named on the card (windy, Discord), not left out +// because nothing could be spent yet. +const giftReadable = (s) => !!s.jwt && !jwtExpired(s.jwt) + // dualUsage shows both pools but only the pool a request can use counts // for its model. Live gift models don't spend the Coding windows; spent // or blocked gift buckets stay visible without holding up the Coding Plan. @@ -726,29 +764,32 @@ async function dualUsage(s, out) { const cached = routes.get(s.key + "\0" + s.jwt) try { const g = await giftOf(s) - const gift = g ? { name: g.plan, models: [...new Set(g.windows.filter((w) => !w._spent) + const gift = g?.live ? { name: g.plan, models: [...new Set(g.windows.filter((w) => !w._spent) .flatMap((w) => w.models ?? []).map((m) => m.toLowerCase()))], allModels: uniqueModels(g.windows.flatMap((w) => w.models ?? [])) } : null if (cached) { cached.gift = gift - const ends = g ? [g.until, ...g.windows.map((w) => w.resetsAt)].map((t) => Date.parse(t)).filter(Number.isFinite) : [] + // a plan that starts later is read again when it starts + const ends = g ? [g.until, ...g.windows.map((w) => w.resetsAt)].map((t) => Date.parse(t)) + .concat(g.pending.map((p) => p.start * 1000)).filter(Number.isFinite) : [] if (ends.length) cached.ttl = Math.min(cached.ttl, Math.max(0, Math.min(...ends) - cached.at)) } - if (g) { + if (g?.live) { // the gift's models are its trial entries alone: a plain model stays // on the coding plan, and the user picks the gift by its entry const notModels = gift.allModels.map((m) => giftID(m).toLowerCase()) if (notModels.length) out.windows = out.windows.map((w) => w.aside ? w : { ...w, notModels }) // Several buckets may serve one model: one spent sibling cannot block it. const best = bestBuckets(g.windows) - const label = byPlan(g.windows) + // beside the Coding Plan's windows every gift bucket is named after + // its plan, one plan or several: "Start Plan · GLM-5.1-Trial" can't + // be read as the Coding Plan's own (windy, Discord) + const label = (name, plan) => first(plan, "Start Plan") + " · " + name out.windows.push(...countedFirst(g.windows.map(({ _plan: p, _spent, ...w }, i) => { const selected = gift.allModels.filter((m) => best.get(m.toLowerCase()) === i) const models = selected.map(giftID) const scoped = models.length ? { ...w, models } : { ...w, aside: true } - // the card names a bucket's model as the picker does (GLM-5.3-Flash-Trial); - // no plan prefix while one plan gives them all — the card's section - // header already says the account; with several, byPlan names each + // the card names a bucket's model as the picker does (GLM-5.3-Flash-Trial) let name = w.name for (const m of selected) { const at = name.toLowerCase().indexOf(m.toLowerCase()) @@ -757,6 +798,7 @@ async function dualUsage(s, out) { return { ...scoped, name: label(name, p) } }))) } + if (g) out.windows.push(...pendingLines(g)) } catch { if (cached) { cached.gift = null @@ -2260,8 +2302,8 @@ export async function ZCodeAuthPlugin({ client }) { } } const team = await teamUsage(s, key) - card = saved(gift ? await dualUsage(s, team) : team) - } else card = saved(start ? await startUsage(s) : gift ? await dualUsage(s) : await codingUsage(s)) + card = saved(gift || giftReadable(s) ? await dualUsage(s, team) : team) + } else card = saved(start ? await startUsage(s) : gift || giftReadable(s) ? await dualUsage(s) : await codingUsage(s)) // a gift plan ZCode holds for the account but has not put on it: // named on the card, claimed in the ZCode app (its claim needs // the app's captcha attestation, see claimHint). A card that is diff --git a/packages/zcode/package.json b/packages/zcode/package.json index cd1c78e..bb07fbb 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.33", + "version": "0.1.34", "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan", "type": "module", "main": "./index.mjs", diff --git a/packages/zcode/pending.test.mjs b/packages/zcode/pending.test.mjs new file mode 100644 index 0000000..db24a92 --- /dev/null +++ b/packages/zcode/pending.test.mjs @@ -0,0 +1,134 @@ +// A gift plan that has not started yet (windy, Discord: "今天23点要生效的Start +// Plan就没显示"), and a coding account's gift buckets told apart from its +// Coding Plan windows ("无法区分Coding Plan 和Start Plan的额度"). +// +// The balance's plans are as ZCode's /billing/balance and /billing/preview +// give them: plan_id, user_plan_id, name, status, starts_at and ends_at in +// Unix seconds (usage.test.mjs's PREVIEW_CLAIMABLE is a real reply). Which +// status a plan not started yet carries has not been seen, so these tests +// give it both "active" and an unknown word: the plugin goes by starts_at. +// Nothing leaves the machine: fetch is a fake. +import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let ZCodeAuthPlugin, _internal +beforeAll(async () => { + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ ZCodeAuthPlugin, _internal } = await import("./index.mjs")) +}) +const real = globalThis.fetch +afterAll(() => (globalThis.fetch = real)) +beforeEach(() => { + globalThis.fetch = async () => { throw new Error("no network in tests") } + _internal.routes.clear() + _internal.blocked.clear() +}) + +const ok = (data) => new Response(JSON.stringify({ code: 0, data })) +function serve(route) { + const calls = [] + globalThis.fetch = async (url, init = {}) => { + const c = { url: new URL(String(url)), headers: init.headers ?? {} } + calls.push(c) + return (await route(c)) ?? new Response("", { status: 404 }) + } + return calls +} +const oauth = (state) => ({ type: "oauth", access: state.key ?? state.jwt ?? "", refresh: JSON.stringify(state), expires: 0 }) +async function usage(auth) { + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + return hooks.auth.usage(async () => auth, { id: "zcode" }) +} +const jwt = (exp) => ["{}", JSON.stringify({ exp })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" +const two = (n) => String(n).padStart(2, "0") +// the start as the card says it: this computer's time +const local = (sec) => { + const d = new Date(sec * 1000) + return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}` +} +const PENDING = "ZCode gift plan not started yet" + +const now = Math.trunc(Date.now() / 1000) +const later = now + 5 * 3600 +const live = { plan_id: "zcode-v3-start-plan", user_plan_id: "up1", name: "Start Plan", status: "active", starts_at: now - 86400, ends_at: now + 3600, + entitlements: [{ entitlement_id: "e1", period: "daily" }] } +const next = (status) => ({ plan_id: "zcode-v3-start-plan", user_plan_id: "up2", name: "Start Plan", status, starts_at: later, ends_at: later + 7 * 86400, + entitlements: [{ entitlement_id: "e2", period: "daily" }] }) +const bucket = (up, left, model = "GLM-5.1") => ({ plan_id: "zcode-v3-start-plan", user_plan_id: up, entitlement_id: up === "up1" ? "e1" : "e2", + show_name: "GLM-5.1", capabilities: ["model:" + model], total_units: 1000, used_units: 1000 - left, remaining_units: left, expires_at: up === "up1" ? now + 3600 : later + 86400 }) + +function zcode(balance, coding) { + return serve(({ url }) => { + if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok({ server_time: now, ...balance }) + if (url.pathname === "/api/v1/zcode-plan/billing/preview") return ok({ server_time: now, plans: [] }) + if (!coding) return + 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({ level: "pro", limits: [{ type: "CREDIT_LIMIT", unit: 3, number: 5, percentage: 25 }] }) + }) +} +const codingAuth = () => oauth({ site: "zai", base: "https://api.z.ai/api/anthropic", key: "k.pending", jwt: jwt(now + 86400), device: "d", plan: "GLM Coding Pro" }) +const startAuth = () => oauth({ site: "zai", jwt: jwt(now + 86400), device: "d" }) + +for (const status of ["active", "pending_unknown_word"]) { + test(`a coding account's Start Plan that starts later is named with its start (status ${status})`, async () => { + // the only gift plan has not started: before, no gift was live, so the + // card read no balance and the plan was left out + zcode({ plans: [next(status)], balances: [bucket("up2", 1000)] }, true) + const u = await usage(codingAuth()) + expect(u.plan).toBe("GLM Coding Pro") + expect(u.windows).toEqual([ + { name: "5 hours", used: 25, span: 5 * 3600 }, + { name: PENDING, used: 0, aside: true, display: `Start Plan · ${local(later)}` }, + ]) + // and nothing is routed to it before it starts: no gift for requests + const s = JSON.parse(codingAuth().refresh) + expect((await _internal.plansOf(s)).gift).toBeNull() + }) +} + +test("beside the Coding Plan, a live gift's buckets carry their plan's name, and the next plan its start", async () => { + zcode({ plans: [live, next("active")], balances: [bucket("up1", 400), bucket("up2", 1000)] }, true) + const u = await usage(codingAuth()) + expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Start Plan · GLM-5.1-Trial", PENDING]) + // the live plan's bucket is the one counted; the coming plan's full one isn't + expect(u.windows[1]).toMatchObject({ used: 60, display: "600 / 1000", models: ["GLM-5.1-Trial"] }) + expect(u.windows[2]).toEqual({ name: PENDING, used: 0, aside: true, display: `Start Plan · ${local(later)}` }) + // the Coding Plan's window leaves the gift's models to the gift + expect(u.windows[0].notModels).toEqual(["glm-5.1-trial"]) +}) + +test("a gift-only account whose next Start Plan starts later shows today's and names the next", async () => { + zcode({ plans: [live, next("active")], balances: [bucket("up1", 400), bucket("up2", 1000)] }) + const u = await usage(startAuth()) + expect(u.error).toBeUndefined() + expect(u.plan).toBe("Start Plan") + expect(u.until).toBe(new Date((now + 3600) * 1000).toISOString()) + expect(u.windows.map((w) => [w.name, w.display])).toEqual([ + ["GLM-5.1", "600 / 1000"], + [PENDING, `Start Plan · ${local(later)}`], + ]) +}) + +test("a gift-only account whose only plan starts later gets a card, not 'ended or never started'", async () => { + zcode({ plans: [{ ...next("active"), name: "ZCode Trust Build" }], balances: [] }) + const u = await usage(startAuth()) + expect(u).toEqual({ signIn: "kept", plan: "ZCode Trust Build", windows: [{ name: PENDING, used: 0, aside: true, display: `ZCode Trust Build · ${local(later)}` }] }) +}) + +test("several coming plans are each named, the soonest first; an expired one with a later start is not", async () => { + const far = { ...next("active"), user_plan_id: "up3", name: "ZCode 1024 Dev Day", starts_at: later + 86400 } + const gone = { ...next("expired"), user_plan_id: "up4", name: "Old Grant" } + zcode({ plans: [far, gone, next("active")], balances: [] }, true) + const u = await usage(codingAuth()) + expect(u.windows.filter((w) => w.name === PENDING).map((w) => w.display)).toEqual([ + `Start Plan · ${local(later)}`, + `ZCode 1024 Dev Day · ${local(later + 86400)}`, + ]) +}) + +test("a plan whose start has come is live, not coming", async () => { + zcode({ plans: [{ ...next("active"), starts_at: now }], balances: [bucket("up2", 1000)] }) + const u = await usage(startAuth()) + expect(u.windows.map((w) => w.name)).toEqual(["GLM-5.1"]) +}) diff --git a/packages/zcode/usage.test.mjs b/packages/zcode/usage.test.mjs index 763508b..e78559a 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -467,7 +467,7 @@ test("a coding account's line goes after its coding and gift windows", async () const auth = oauth({ site: "zai", key: "k", jwt: token, device: "d" }) const u = await usage(auth) expect(u.plan).toBe("GLM Coding Pro") - expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "GLM-5.1-Trial", "Gift plans to claim in the ZCode app"]) + expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Start Plan · GLM-5.1-Trial", "Gift plans to claim in the ZCode app"]) expect(u.windows.at(-1)).toEqual(TRUST_BUILD) expect(calls.filter((c) => c.url.pathname.endsWith("/preview"))).toHaveLength(1) })