zcode 0.1.39: gift plans are also claimed from the ZCode app's banner feed (#503)

kongbai01203 found on 10-30 that a ZCode claim banner's plan (ZCODE
WEEKEND BUILD, 500M GLM-5.3-Flash tokens) is in neither
/billing/preview nor /billing/current while the app shows the banner,
so 0.1.35's daily claim said "no ZCode gift plan to claim". The app
reads the banner from GET /api/v1/marketing/touch?seq=<n>: each
delivery's banner button with action type claim_zcode_plan carries the
plan_id, and the claim is the same POST /billing/claim. Their capture
has a real code 0 claim reply ("Plan claimed successfully.").

- toClaim reads both lists (the feed first, then the preview) and keeps
  each plan_id once; claimDaily and the card's claim line use it.
- The feed goes out with what the capture shows the app sends: the
  session, X-Device-Mid, X-ZCode-App-Version and X-Client-Language
  (the system locale), seq counting up from 0 per process.
- A list that doesn't read is failed (asked again later), never
  "nothing to claim"; a plan claimed beside it is still named.
- claimOne is unchanged; README says the two lists and that a plan just
  claimed may show in neither billing list until its effective_at.

Run on mote (macOS, Bun 1.4.2, temp HOME), on eee889a:
- packages/zcode `bun test`: 178 pass 0 fail.
- Red on the old index.mjs (origin/main's, with the new tests): 3 fail
  (the banner claimed from the feed, an unreadable feed is failed, the
  banner named on the card).
- Broken by hand: claiming each plan per list (no dedupe) and dropping
  the "list unread with nothing listed" return: 3 fail (plan both lists
  name claimed once, unreadable feed, unreadable preview).
- Full `HOME=$(mktemp -d) bun test` from the root: first run 3870 pass
  1 fail, its name lost (the log was cut by tail); two reruns with the
  whole log kept: 3871 pass 0 fail. `bun scripts/check.mjs`: ok.

Not tried: a real claim through the plugin. The feed fixture is built
from the capture's description of its fields, not its literal bytes
(only the claim reply was posted whole); the touch/action call the app
makes for a banner's confirm/close is not sent.
This commit is contained in:
yetone
2026-10-30 23:08:10 +08:00
parent b177d69b83
commit 2e580cfead
5 changed files with 207 additions and 40 deletions
+11 -4
View File
@@ -233,8 +233,11 @@ left, shows no count.
**Gift plans ZCode holds but has not granted.** ZCode hands out one-off
trust-build / gift plans (a day's ZCode Trust Build, say) that are not
on the account until the ZCode app claims them. The plugin reads the
app's own list of them (`GET /api/v1/zcode-plan/billing/preview`) with
the card and names them there — the window is named "Gift plans to
app's own lists of them with the card and names them there: its claim
banners' feed (`GET /api/v1/marketing/touch`, each delivery's
`claim_zcode_plan` button) and `GET /api/v1/zcode-plan/billing/preview`.
A banner plan (a weekend's ZCODE WEEKEND BUILD, 10-30) is in the feed
alone, never in the preview (#503) — the window is named "Gift plans to
claim in the ZCode app" and the display shows "1 · ZCode Trust Build"
— set aside, so the line stops nothing and routing, usage caps and the
menu bar pass it over. The name is a fixed sentence magpie can
@@ -249,13 +252,17 @@ the next read shows it as an ordinary gift bucket.
With ZCode turned on in magpie's Settings → Daily check-in (it is off
until you turn it on), magpie has the plugin claim each account's gift
plans once a day (`auth.checkin`; `magpie accounts checkin` asks now). It
reads the app's preview list and posts each plan it lists to
reads both lists above (the banners' feed and the preview, each plan
once) and posts each plan to
`POST /api/v1/zcode-plan/billing/claim` (`{"plan_id": …}`) with the
account's ZCode session, as the app does. The answer is judged by the
body's code, not the HTTP status:
- nothing listed: *inactive* (ZCode answers an account with nothing to
claim `{"code":0,"msg":""}`, with no list at all);
claim `{"code":0,"msg":""}`, with no list at all). A list that doesn't
read is *failed*, never nothing to claim. A plan just claimed may show
in neither `billing/preview` nor `billing/current` until its
`effective_at`, so neither list is read as "claimed or not";
- code 0: *claimed* (the next request uses the plan);
- code 1003 "target already exists" (HTTP 200): *done*, claimed before;
- code 3007 "captcha verify failed": *captcha*, the plan is claimed in
+85 -4
View File
@@ -65,17 +65,22 @@ const PREVIEW_ONE = {
const PREVIEW_TWO = { ...PREVIEW_ONE, data: { ...PREVIEW_ONE.data, plans: [...PREVIEW_ONE.data.plans, { plan_id: "zcode-v3-start-plan-1029", name: "ZCODE GLOBAL BUILD", status: "active" }] } }
// #503's reply to claiming a plan claimed before, as it came
const CLAIMED_BEFORE = '{"code":1003,"msg":"target already exists","data":{"server_time":1793318302,"message":"You have already claimed this plan."},"logid":"202610292358223079156af0f90065850e"}'
// a code 0 claim: only the code is known
// a code 0 claim: only the code is read
const CLAIMED_NOW = '{"code":0,"msg":""}'
// the 10-06 answer to a claim without the app's captcha (#30)
const CAPTCHA = '{"code":3007,"msg":"captcha verify failed"}'
const PREVIEW = "/api/v1/zcode-plan/billing/preview"
const CLAIM = "/api/v1/zcode-plan/billing/claim"
// claimWith serves the preview and answers each claim with claim(plan_id)
function claimWith(preview, claim) {
const TOUCH = "/api/v1/marketing/touch"
// the marketing feed of an account with no banner up
const TOUCH_NONE = '{"code":0,"msg":"","data":{"deliveries":[]}}'
// claimWith serves the preview (and the feed, touch) and answers each
// claim with claim(plan_id)
function claimWith(preview, claim, touch = TOUCH_NONE) {
return serve(({ url, method, body }) => {
if (url.pathname === PREVIEW && method === "GET") return json(preview)
if (url.pathname === TOUCH && method === "GET") return typeof touch === "function" ? touch() : json(touch)
if (url.pathname === CLAIM && method === "POST") return claim(JSON.parse(body).plan_id)
})
}
@@ -87,7 +92,7 @@ test("nothing to claim: inactive, and no claim is asked", async () => {
expect(r).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim" })
expect(claims(calls)).toEqual([])
// the preview went out as the app's billing calls do
const p = calls[0]
const p = calls.find((c) => c.url.pathname === PREVIEW)
expect(p.url.pathname).toBe(PREVIEW)
expect(p.url.searchParams.get("app_version")).toBe("3.16.3")
expect(p.url.searchParams.get("platform")).toBe(`${process.platform}-${process.arch}`)
@@ -191,3 +196,79 @@ test("an account with no ZCode session asks nothing", async () => {
expect(expired.signIn).toBeUndefined()
expect(calls).toEqual([])
})
// #503, 10-30 (kongbai01203): the ZCode app's claim banner comes from its
// marketing feed, and the plan is in neither /billing/preview nor
// /billing/current while the banner is up. The delivery is shaped as the
// capture describes it (data.deliveries[].banner.buttons[].action and
// banner.background.args.zcode_plan); the claim reply is the capture's own.
const WEEKEND = "zcode-v3-start-plan-1030-wk"
const touchOf = (...plans) => ({
code: 0, msg: "",
data: {
deliveries: plans.map((id) => ({
campaign_id: "2101141259813175296",
banner: {
background: { type: "zcode_plan", args: { zcode_plan: { plan_id: id, name: "ZCODE WEEKEND BUILD", grant_units: 500000000, period: "one_time" } } },
buttons: [
{ text: "领取", action: { type: "claim_zcode_plan", args: { plan_id: id } } },
{ text: "关闭", action: { type: "close", args: {} } },
],
},
})),
},
})
const CLAIMED_WEEKEND = '{"code":0,"msg":"","data":{"server_time":1793369500,"plan":{"user_plan_id":"upl_2116171180260274176","plan_id":"zcode-v3-start-plan-1030-wk","name":"ZCODE WEEKEND BUILD","description":"","priority":101,"status":"active","starts_at":1793369500,"ends_at":1793581200,"entitlements":[{"entitlement_id":"ent-zcode-v3-start-plan-1030-wk-1","show_name":"GLM-5.3-Flash","meter":"model_usage","unit_type":"token","capabilities":["model:glm-5.3-flash"],"grant_units":500000000,"period":"one_time","priority":101,"effective_at":1793372400}]},"message":"Plan claimed successfully."},"logid":"202610301411405bf5f9f3da141d910e7e"}'
test("a banner plan the preview doesn't list is claimed from the app's marketing feed", async () => {
const calls = claimWith(PREVIEW_NO_DATA, (id) => (id === WEEKEND ? json(CLAIMED_WEEKEND) : json("", 404)), touchOf(WEEKEND))
expect(await checkin()).toEqual({ outcome: "claimed", message: "claimed ZCODE WEEKEND BUILD" })
expect(claims(calls).map((c) => JSON.parse(c.body))).toEqual([{ plan_id: WEEKEND }])
// the feed went out as the app asks it
const t = calls.find((c) => c.url.pathname === TOUCH)
expect(t.method).toBe("GET")
expect(Number(t.url.searchParams.get("seq"))).toBeGreaterThanOrEqual(0)
expect(t.headers.Authorization).toBe("Bearer " + TOKEN)
expect(t.headers["X-Device-Mid"]).toBe(DEVICE)
expect(t.headers["X-ZCode-App-Version"]).toBe("3.16.3")
expect(t.headers["X-Client-Language"]).toBeTruthy()
// asked again, the plan answers 1003: done
claimWith(PREVIEW_NO_DATA, () => json(CLAIMED_BEFORE), touchOf(WEEKEND))
expect(await checkin()).toEqual({ outcome: "done", message: "already claimed: ZCODE WEEKEND BUILD" })
})
test("a plan both lists name is claimed once", async () => {
const both = { code: 0, msg: "", data: { plans: [{ plan_id: WEEKEND, name: "ZCODE WEEKEND BUILD" }] } }
const calls = claimWith(both, () => json(CLAIMED_WEEKEND), touchOf(WEEKEND))
expect((await checkin()).outcome).toBe("claimed")
expect(claims(calls)).toHaveLength(1)
})
test("a feed with no claim button, or nothing in it, is nothing to claim", async () => {
const closeOnly = { code: 0, msg: "", data: { deliveries: [{ campaign_id: "1", banner: { buttons: [{ action: { type: "close", args: {} } }] } }] } }
for (const feed of [TOUCH_NONE, '{"code":0,"msg":""}', closeOnly]) {
const calls = claimWith(PREVIEW_NO_DATA, () => json(CLAIMED_NOW), feed)
expect(await checkin()).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim" })
expect(claims(calls)).toEqual([])
}
})
test("a feed that doesn't read is failed (unknown), never nothing to claim", async () => {
for (const feed of [
() => json("", 500),
() => json("garbled"),
() => json('{"code":0,"data":{"deliveries":"x"}}'),
() => { throw new Error("no network in tests") },
]) {
claimWith(PREVIEW_NO_DATA, () => json(CLAIMED_NOW), feed)
const r = await checkin()
expect(r.outcome).toBe("failed")
expect(r.signIn).toBeUndefined()
}
// a preview plan is still claimed beside it, and the check-in is asked again
const calls = claimWith(PREVIEW_ONE, () => json(CLAIMED_NOW), () => json("", 502))
const r = await checkin()
expect(r.outcome).toBe("failed")
expect(r.message).toStartWith("claimed ZCode Trust Build; gift plans to claim: ")
expect(claims(calls)).toHaveLength(1)
})
+94 -31
View File
@@ -644,7 +644,8 @@ async function giftOf(s) {
const CLAIM_HINT = "Gift plans to claim in the ZCode app"
// claimHint is the card's line for gift plans ZCode is holding for the
// account but has not put on it: GET /billing/preview lists them. The
// account but has not put on it: the app's banners (marketing/touch) and
// GET /billing/preview list them (toClaim). The
// card only names them: they are claimed in the ZCode app, or by the
// daily claim (claimDaily) when the user turned it on; on 10-06 a claim
// without the app's Aliyun captcha attestation was refused (3007). A window, set aside (it is no
@@ -657,16 +658,10 @@ const CLAIM_HINT = "Gift plans to claim in the ZCode app"
// own.
async function claimHint(s) {
if (!s.jwt || jwtExpired(s.jwt)) return null
let d
try {
d = await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/preview?app_version=${APP_VERSION}&platform=${platform()}`, { auth: "Bearer " + s.jwt, device: s.device })
} catch {
return null
}
const plans = (previewPlans(d) ?? []).filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim())
const { plans } = await toClaim(s)
if (!plans.length) return null
const n = plans.length
const plan = first(...plans.map((p) => (typeof p?.name === "string" ? p.name : "")), "ZCode gift plan")
const plan = first(...plans.map((p) => p.name), "ZCode gift plan")
return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
}
@@ -691,8 +686,8 @@ const zcodeHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform":
// "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the
// claim wants the app's captcha), else "failed" with why. Only a body
// that reads decides: an HTTP error without one, or text that isn't
// JSON, is failed (unknown), never claimed. The code 0 body hasn't been
// seen yet, so nothing but its code is read.
// JSON, is failed (unknown), never claimed. Only the code is read (#503
// has a real code 0 reply, "Plan claimed successfully.").
async function claimOne(s, planID) {
let res, text
try {
@@ -732,41 +727,109 @@ function previewPlans(d) {
return Array.isArray(d.plans) ? d.plans : null
}
// claimDaily claims every gift plan ZCode's preview lists for the account
// (#503), as auth.checkin's answer: inactive when it lists none, claimed
// when one was claimed now, done when each was claimed before, captcha
// when ZCode wants the app's captcha for one (it is claimed in the ZCode
// app), failed when the list or a claim can't be read. A failed one is
// asked again later in the day, when a plan claimed now answers 1003.
// TOUCH is ZCode's marketing feed: the ZCode app's claim banners come
// from it, not from /billing/preview. A banner plan ("ZCODE WEEKEND
// BUILD", 10-30) is in neither /billing/preview nor /billing/current
// while the app shows its banner, and the app claims it through the same
// /billing/claim (#503's capture of 10-30, kongbai01203: GET
// /api/v1/marketing/touch?seq=<n, counting up from 0> with the session,
// X-Device-Mid, X-Client-Language and X-ZCode-App-Version, answered
// data.deliveries[].banner.buttons[].action = {"type":"claim_zcode_plan",
// "args":{"plan_id":…}} and the plan's name in
// banner.background.args.zcode_plan.name).
const TOUCH = "/api/v1/marketing/touch"
const CLAIM_ACTION = "claim_zcode_plan"
let touchSeq = 0
const clientLanguage = () => {
try {
return Intl.DateTimeFormat().resolvedOptions().locale || "en-US"
} catch {
return "en-US"
}
}
// touchPlans is the plans marketing/touch's deliveries offer to claim:
// [{plan_id, name}], [] for a feed with no deliveries, null for one that
// doesn't read. Each delivery is searched for its claim_zcode_plan
// actions and its zcode_plan's name, wherever the banner keeps them, so
// a button moved inside the banner is still found.
function touchPlans(d) {
if (d == null) return []
if (typeof d !== "object" || Array.isArray(d)) return null
if (d.deliveries == null) return []
if (!Array.isArray(d.deliveries)) return null
const out = []
for (const dv of d.deliveries) {
const ids = [], names = []
const walk = (v, depth) => {
if (!v || typeof v !== "object" || depth > 12) return
if (Array.isArray(v)) return v.forEach((x) => walk(x, depth + 1))
if (v.type === CLAIM_ACTION && typeof v.args?.plan_id === "string" && v.args.plan_id.trim()) ids.push(v.args.plan_id.trim())
if (v.zcode_plan && typeof v.zcode_plan === "object" && typeof v.zcode_plan.name === "string") names.push(v.zcode_plan.name)
for (const k of Object.keys(v)) walk(v[k], depth + 1)
}
walk(dv, 0)
for (const id of ids) out.push({ plan_id: id, name: first(names[0] ?? "", id) })
}
return out
}
// toClaim is every gift plan the account can claim: what the app's
// marketing feed offers (its banners) and what /billing/preview lists,
// once each by plan_id. unread names a list that didn't read: its
// plans are unknown, never none.
async function toClaim(s) {
const plans = [], unread = []
const add = (p) => {
if (!plans.some((q) => q.plan_id === p.plan_id)) plans.push(p)
}
const ask = async (what, url, headers, read) => {
let d
try {
d = await call("GET", url, { auth: "Bearer " + s.jwt, device: s.device, headers })
} catch (e) {
return unread.push(`${what}: ${e?.message ?? String(e)}`)
}
const got = read(d)
if (!got) return unread.push(`${what}: the plan list doesn't read`)
got.forEach(add)
}
await ask("gift plans to claim", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { "X-ZCode-App-Version": APP_VERSION, "X-Client-Language": clientLanguage() }, touchPlans)
await ask("gift plans to claim", `${ZCODE}/api/v1/zcode-plan/billing/preview?app_version=${APP_VERSION}&platform=${platform()}`, zcodeHeaders(), (d) => {
const l = previewPlans(d)
return l && l.filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim()).map((p) => ({ plan_id: p.plan_id.trim(), name: first(typeof p.name === "string" ? p.name : "", p.plan_id.trim()) }))
})
return { plans, unread }
}
// claimDaily claims every gift plan ZCode offers the account (#503:
// toClaim, the app's banners and its preview), as auth.checkin's answer:
// inactive when neither lists one, claimed when one was claimed now,
// done when each was claimed before, captcha when ZCode wants the app's
// captcha for one (it is claimed in the ZCode app), failed when a list
// or a claim can't be read. A failed one is asked again later in the
// day, when a plan claimed now answers 1003.
// Nothing here marks the account: a failed claim keeps its sign-in.
async function claimDaily(s) {
if (!s?.jwt) return { outcome: "ineligible", message: "ZCode's gift plans are claimed with a ZCode sign-in; this account has none" }
if (jwtExpired(s.jwt)) return { outcome: "failed", message: EXPIRED }
let d
try {
d = await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/preview?app_version=${APP_VERSION}&platform=${platform()}`, { auth: "Bearer " + s.jwt, device: s.device, headers: zcodeHeaders() })
} catch (e) {
return { outcome: "failed", message: `gift plans to claim: ${e?.message ?? String(e)}` }
}
const listed = previewPlans(d)
if (!listed) return { outcome: "failed", message: "gift plans to claim: the plan list doesn't read" }
const plans = listed.filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim())
const { plans, unread } = await toClaim(s)
if (!plans.length && unread.length) return { outcome: "failed", message: unread.join("; ") }
if (!plans.length) return { outcome: "inactive", message: "no ZCode gift plan to claim" }
const got = []
for (const p of plans) {
const name = first(typeof p.name === "string" ? p.name : "", p.plan_id)
got.push({ name, ...(await claimOne(s, p.plan_id.trim())) })
}
for (const p of plans) got.push({ name: p.name, ...(await claimOne(s, p.plan_id)) })
const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name)
const claimed = named("claimed")
const said = [
claimed.length ? `claimed ${claimed.join(", ")}` : "",
...got.filter((g) => g.outcome === "captcha").map((g) => `${g.name}: claim it in the ZCode app (${g.why})`),
...got.filter((g) => g.outcome === "failed").map((g) => `${g.name}: ${g.why}`),
...unread,
].filter(Boolean).join("; ")
// a plan claimed now is used by the next request, not ten minutes on
if (claimed.length) routes.delete(s.key + "\0" + s.jwt)
if (got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said }
// a list that didn't read may hold a plan not claimed: asked again
if (unread.length || got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said }
if (got.some((g) => g.outcome === "captcha")) return { outcome: "captcha", message: said }
if (claimed.length) return { outcome: "claimed", message: said }
return { outcome: "done", message: `already claimed: ${named("done").join(", ")}` }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-zcode-auth",
"version": "0.1.38",
"version": "0.1.39",
"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, and claims its gift plans daily",
"type": "module",
"main": "./index.mjs",
+16
View File
@@ -408,6 +408,22 @@ test("a gift plan ZCode holds but has not granted is named on the card, to claim
expect(calls.some((c) => c.url.pathname.endsWith("/claim"))).toBe(false)
})
// #503, 10-30: a banner plan is in the app's marketing feed and in no
// preview; the card names it too, and still claims nothing
test("a banner plan from the app's marketing feed is named on the card", async () => {
const now = Math.trunc(Date.now() / 1000)
const token = jwt(now + 86400)
const calls = serve(({ url }) => {
if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok(startBalance(now, "active"))
if (url.pathname === "/api/v1/zcode-plan/billing/preview") return ok(PREVIEW_CLAIMED)
if (url.pathname === "/api/v1/marketing/touch")
return ok({ deliveries: [{ banner: { background: { args: { zcode_plan: { name: "ZCODE WEEKEND BUILD" } } }, buttons: [{ action: { type: "claim_zcode_plan", args: { plan_id: "zcode-v3-start-plan-1030-wk" } } }] } }] })
})
const u = await usage(oauth({ site: "zai", jwt: token, device: "11111111-2222-4333-8444-555555555555" }))
expect(u.windows.at(-1)).toEqual({ name: "Gift plans to claim in the ZCode app", used: 0, aside: true, display: "1 · ZCODE WEEKEND BUILD" })
expect(calls.some((c) => c.url.pathname.endsWith("/claim"))).toBe(false)
})
test("a claimed account's card has no line at all", async () => {
const now = Math.trunc(Date.now() / 1000)
const { u } = await startCard(now, jwt(now + 86400), () => ok(PREVIEW_CLAIMED))