diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 94fea63..e26c37e 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -273,12 +273,14 @@ 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 both lists above (the banners' feed and the preview, each plan -once) and posts each plan to +reads the banner feed above — the v3.17 client replaced the old preview +polling with the feed alone, and the feed is gated on the client's +version, so the plugin asks as the current client (3.17.2) sends — and +posts each plan the feed offers to `POST /api/v1/zcode-plan/billing/claim` (`{"plan_id": …}`) with the account's ZCode session, as the app does. An answer of nothing to claim carries an `until` half an hour out, so magpie's loop asks again then, -and again, all day while neither list names a plan — two GETs, nothing +and again, all day while the feed names no plan — one GET, nothing posted: ZCode drops plans into the feed on its own schedule (a weekend banner starting at 19:00 Beijing, say), and one that arrives after the day's ask used to sit unclaimed past its short life. The @@ -291,20 +293,25 @@ after one was claimed, is seen the next day. 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). 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"; + claim `{"code":0,"msg":""}`, with no list at all). A feed that doesn't + read is *failed*, never nothing to claim; - 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 - the ZCode app (on 10-06 ZCode wanted the app's Aliyun captcha for a - claim; whether it still does for a fresh plan is not known yet); + the ZCode app — the claim is gated on the Aliyun captcha the app's + renderer answers, and a claim from outside the app is refused it + (11-03: seven accounts' ZCODE GLOBAL BUILD all answered 3007). Once + claimed there, the gift lands on the account and freeFirst spends it + like any other; - anything else, an HTTP error without a code, or a reply that isn't JSON: *failed*, which magpie asks again later that day. It is never taken as claimed, and a failed claim leaves the account's sign-in alone. +The rewards center in the client (奖励中心, the embedded +`zcode.z.ai/{cn|en}/rewards` page) is the referral program's website, +separate from these gift plans; its rewards are claimed on that page. + An account added with a GLM Coding Plan key has no ZCode session to claim with (*ineligible*). diff --git a/packages/zcode/checkin.test.mjs b/packages/zcode/checkin.test.mjs index c2ee866..ecfcb39 100644 --- a/packages/zcode/checkin.test.mjs +++ b/packages/zcode/checkin.test.mjs @@ -1,8 +1,12 @@ -// auth.checkin claims the gift plans ZCode's preview lists for an account -// (magpie-community/plugins#503). The preview and the "already claimed" -// replies are real (#503's capture of 10-29, the 10-06 preview in -// usage.test.mjs); the code 0 claim reply has not been seen yet, so its -// fixture carries only the code. +// auth.checkin claims the gift plans the app's marketing feed (touch) +// offers for an account (magpie-community/plugins#503). The feed and the +// "already claimed" replies are real (#503's captures of 10-29 and 10-30, +// touch-1030-wk.json, the 10-06 preview in usage.test.mjs); the code 0 +// claim reply has not been seen yet, so its fixture carries only the +// code. The v3.17 client replaced the old preview polling with the feed +// alone (docs/marketing-touch-client.md), so the preview is read no +// more; the rewards center's gifts are website-side — claimed in the +// client, spent here by freeFirst once they land on the account. import { test, expect, afterAll, beforeAll, beforeEach } from "bun:test" import { homedir, tmpdir } from "node:os" import { readFileSync, realpathSync } from "node:fs" @@ -62,7 +66,6 @@ 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 read @@ -75,11 +78,12 @@ const CLAIM = "/api/v1/zcode-plan/billing/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) { +// claimWith serves the feed (touch) and answers each claim with +// claim(plan_id). The preview is served with a forever-broken answer: the +// v3.17 client reads it no more, and a check-in that still did would fail. +function claimWith(claim, touch = TOUCH_NONE) { return serve(({ url, method, body }) => { - if (url.pathname === PREVIEW && method === "GET") return json(preview) + if (url.pathname === PREVIEW && method === "GET") return json("", 500) 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) }) @@ -100,46 +104,66 @@ test("an inactive says until half an hour out; claimed, done, captcha and failed expect(t).toBeLessThan(Date.now() + 35 * 60_000) } const none = (r) => expect(r.until).toBeUndefined() - claimWith(PREVIEW_NONE, () => json(CLAIMED_NOW)) + claimWith(() => json(CLAIMED_NOW)) soon(await checkin()) - claimWith(PREVIEW_ONE, () => json(CLAIMED_NOW)) + claimWith(() => json(CLAIMED_NOW), touchOf(WEEKEND)) none(await checkin()) - claimWith(PREVIEW_ONE, () => json(CLAIMED_BEFORE)) + claimWith(() => json(CLAIMED_BEFORE), touchOf(WEEKEND)) none(await checkin()) - claimWith(PREVIEW_ONE, () => json(CAPTCHA, 400)) + claimWith(() => json(CAPTCHA, 400), touchOf(WEEKEND)) none(await checkin()) - claimWith("", () => json(CLAIMED_NOW)) + // a failed check-in settles for none: magpie asks a failed again itself + claimWith(() => json(CLAIMED_NOW), () => { throw new Error("feed unreachable") }) none(await checkin()) }) test("nothing to claim: inactive, and no claim is asked", async () => { - const calls = claimWith(PREVIEW_NONE, () => json(CLAIMED_NOW)) + const calls = claimWith(() => json(CLAIMED_NOW)) const r = await checkin() expect(r).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim", until: expect.any(String) }) expect(claims(calls)).toEqual([]) - // the preview went out as the app's billing calls do - 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}`) - expect(p.headers.Authorization).toBe("Bearer " + TOKEN) - expect(p.headers["X-Device-Mid"]).toBe(DEVICE) - expect(p.headers["X-ZCode-App-Version"]).toBe("3.16.3") - expect(p.headers["X-Platform"]).toBe(`${process.platform}-${process.arch}`) + // the touch feed went out as the app's billing calls do (the seq counts + // up across the process's asks) + const t = calls.find((c) => c.url.pathname === TOUCH) + 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.17.2") + expect(t.headers["X-Client-Language"]).toBeTruthy() +}) + +// the v3.17 client replaced the preview polling with the feed alone +// (docs/marketing-touch-client.md), so whatever the preview answers is +// nothing to claim, and it is not asked at all +test("the preview is not read anymore", async () => { + for (const answer of [ + PREVIEW_NONE, + PREVIEW_NO_DATA, + () => json(PREVIEW_ONE), + () => json("", 500), + () => json("garbled"), + () => json('{"code":401,"msg":"token invalid"}', 401), + () => { throw new Error("no network in tests") }, + ]) { + const calls = serve(({ url }) => (url.pathname === PREVIEW ? (typeof answer === "function" ? answer() : json(answer)) : json(CLAIMED_NOW))) + expect(await checkin()).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim", until: expect.any(String) }) + expect(calls.filter((c) => c.url.pathname === PREVIEW)).toHaveLength(0) + expect(claims(calls)).toEqual([]) + } }) test("one plan to claim, claimed with code 0", async () => { _internal.routes.set("\0" + TOKEN, { stale: true }) - const calls = claimWith(PREVIEW_ONE, () => json(CLAIMED_NOW)) + const calls = claimWith(() => json(CLAIMED_NOW), touchOf([TRUST, "ZCode Trust Build"])) const r = await checkin() expect(r).toEqual({ outcome: "claimed", message: "claimed ZCode Trust Build" }) const [c] = claims(calls) expect(claims(calls).length).toBe(1) expect(c.url.origin).toBe("https://zcode.z.ai") - expect(JSON.parse(c.body)).toEqual({ plan_id: "zcode-v3-start-plan-trust-1006" }) + expect(JSON.parse(c.body)).toEqual({ plan_id: TRUST }) expect(c.headers.Authorization).toBe("Bearer " + TOKEN) expect(c.headers["X-Device-Mid"]).toBe(DEVICE) - expect(c.headers["X-ZCode-App-Version"]).toBe("3.16.3") + expect(c.headers["X-ZCode-App-Version"]).toBe("3.17.2") expect(c.headers["X-Platform"]).toBe(`${process.platform}-${process.arch}`) expect(c.headers["Content-Type"]).toBe("application/json") // the route is read again, so the next request uses the plan @@ -147,12 +171,12 @@ test("one plan to claim, claimed with code 0", async () => { }) test("a plan claimed before (HTTP 200, code 1003) is done, not a failure", async () => { - claimWith(PREVIEW_ONE, () => json(CLAIMED_BEFORE)) + claimWith(() => json(CLAIMED_BEFORE), touchOf([TRUST, "ZCode Trust Build"])) expect(await checkin()).toEqual({ outcome: "done", message: "already claimed: ZCode Trust Build" }) }) test("a claim ZCode wants the app's captcha for is captcha: claimed in the ZCode app", async () => { - claimWith(PREVIEW_ONE, () => json(CAPTCHA, 400)) + claimWith(() => json(CAPTCHA, 400), touchOf([TRUST, "ZCode Trust Build"])) const r = await checkin() expect(r.outcome).toBe("captcha") expect(r.message).toContain("ZCode Trust Build: claim it in the ZCode app (captcha verify failed)") @@ -168,7 +192,7 @@ test("a claim that doesn't read is failed (unknown), never claimed", async () => () => json('{"code":1001,"msg":"system busy"}'), () => { throw new Error("socket hang up") }, ]) { - claimWith(PREVIEW_ONE, answer) + claimWith(answer, touchOf([TRUST, "ZCode Trust Build"])) const r = await checkin() expect(r.outcome).toBe("failed") expect(r.message).toStartWith("ZCode Trust Build: ") @@ -177,38 +201,13 @@ test("a claim that doesn't read is failed (unknown), never claimed", async () => } }) -test("a preview with nothing in it is nothing to claim, not a failed check-in", async () => { - for (const body of [PREVIEW_NO_DATA, '{"code":0,"msg":"","data":null}', '{"code":0,"msg":"","data":{"server_time":1793318263}}', '{"code":0,"msg":"","data":{"plans":null}}']) { - const calls = serve(({ url }) => (url.pathname === PREVIEW ? json(body) : json(CLAIMED_NOW))) - expect(await checkin()).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim", until: expect.any(String) }) - expect(claims(calls)).toEqual([]) - } -}) - -test("a preview that doesn't read is failed (unknown), and nothing is claimed", async () => { - for (const answer of [ - () => json("", 500), - () => json("garbled"), - () => json('{"code":0,"data":{"plans":"zcode-v3-start-plan-1029"}}'), // a plan list that isn't a list - () => json('{"code":0,"data":"plans"}'), // data that isn't an object - () => json('{"code":401,"msg":"token invalid"}', 401), - () => { throw new Error("no network in tests") }, - ]) { - const calls = serve(({ url }) => (url.pathname === PREVIEW ? answer() : json(CLAIMED_NOW))) - const r = await checkin() - expect(r.outcome).toBe("failed") - expect(r.signIn).toBeUndefined() - expect(claims(calls)).toEqual([]) - } -}) - test("one claimed and one failed is failed, naming the claimed one, so it is asked again", async () => { - claimWith(PREVIEW_TWO, (id) => (id === "zcode-v3-start-plan-1029" ? json("", 503) : json(CLAIMED_NOW))) + claimWith((id) => (id === GLOBAL ? json("", 503) : json(CLAIMED_NOW)), touchOf([TRUST, "ZCode Trust Build"], [GLOBAL, "ZCODE GLOBAL BUILD"])) const r = await checkin() expect(r.outcome).toBe("failed") expect(r.message).toBe("claimed ZCode Trust Build; ZCODE GLOBAL BUILD: HTTP 503, unreadable reply (empty)") // asked again: the one claimed answers 1003 now - claimWith(PREVIEW_TWO, (id) => (id === "zcode-v3-start-plan-1029" ? json(CLAIMED_NOW) : json(CLAIMED_BEFORE))) + claimWith((id) => (id === GLOBAL ? json(CLAIMED_NOW) : json(CLAIMED_BEFORE)), touchOf([TRUST, "ZCode Trust Build"], [GLOBAL, "ZCODE GLOBAL BUILD"])) expect(await checkin()).toEqual({ outcome: "claimed", message: "claimed ZCODE GLOBAL BUILD" }) }) @@ -229,25 +228,32 @@ test("an account with no ZCode session asks nothing", async () => { // 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 TRUST = "zcode-v3-start-plan-trust-1006" +const GLOBAL = "zcode-v3-start-plan-1029" +// touchOf is a feed whose banners each claim one plan: an entry is a +// plan_id, or [plan_id, name] 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: {} } }, - ], - }, - })), + deliveries: plans.map((p) => { + const [id, name = "ZCODE WEEKEND BUILD"] = Array.isArray(p) ? p : [p] + return { + campaign_id: "2101141259813175296", + banner: { + background: { type: "zcode_plan", args: { zcode_plan: { plan_id: id, name, 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)) +test("a banner plan is claimed from the app's marketing feed", async () => { + const calls = claimWith((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 @@ -256,24 +262,17 @@ test("a banner plan the preview doesn't list is claimed from the app's marketing 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-ZCode-App-Version"]).toBe("3.17.2") expect(t.headers["X-Client-Language"]).toBeTruthy() // asked again, the plan answers 1003: done - claimWith(PREVIEW_NO_DATA, () => json(CLAIMED_BEFORE), touchOf(WEEKEND)) + claimWith(() => 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) + const calls = claimWith(() => json(CLAIMED_NOW), feed) expect(await checkin()).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim", until: expect.any(String) }) expect(claims(calls)).toEqual([]) } @@ -286,17 +285,11 @@ test("a feed that doesn't read is failed (unknown), never nothing to claim", asy () => json('{"code":0,"data":{"deliveries":"x"}}'), () => { throw new Error("no network in tests") }, ]) { - claimWith(PREVIEW_NO_DATA, () => json(CLAIMED_NOW), feed) + claimWith(() => 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) }) // #503, 10-30 22:11 +08:00 (kongbai01203, comment 6526694290): the real @@ -312,7 +305,7 @@ test("a feed that doesn't read is failed (unknown), never nothing to claim", asy const TOUCH_REAL = readFileSync(new URL("./testdata/touch-1030-wk.json", import.meta.url), "utf8") test("the real banner feed: its one claim button is claimed, by the plan's name", async () => { - const calls = claimWith(PREVIEW_NO_DATA, (id) => (id === WEEKEND ? json(CLAIMED_WEEKEND) : json("", 404)), TOUCH_REAL) + const calls = claimWith((id) => (id === WEEKEND ? json(CLAIMED_WEEKEND) : json("", 404)), TOUCH_REAL) expect(await checkin()).toEqual({ outcome: "claimed", message: "claimed ZCODE WEEKEND BUILD" }) // one claim, of the claim button's plan_id, with the body the app sends; // the close button and the success popup's buttons claim nothing @@ -333,7 +326,7 @@ test("the real delivery without its claim button is nothing to claim", async () // the zcode_plan it still describes (background, success popup) is no // offer to claim expect(JSON.stringify(feed)).toContain('"zcode_plan":{"plan_id":"zcode-v3-start-plan-1030-wk"') - const calls = claimWith(PREVIEW_NO_DATA, () => json(CLAIMED_WEEKEND), feed) + const calls = claimWith(() => json(CLAIMED_WEEKEND), feed) expect(await checkin()).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim", until: expect.any(String) }) expect(claims(calls)).toEqual([]) }) @@ -346,7 +339,7 @@ test("after the claim the feed has no delivery: nothing to claim, not a failure" // (checkin.go, claimedOn) over this later inactive. const after = JSON.parse(TOUCH_REAL) after.data.deliveries = [] - const calls = claimWith(PREVIEW_NO_DATA, () => json(CLAIMED_WEEKEND), after) + const calls = claimWith(() => json(CLAIMED_WEEKEND), after) expect(await checkin()).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim", until: expect.any(String) }) expect(claims(calls)).toEqual([]) }) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 7d34784..c926f32 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -644,8 +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: the app's banners (marketing/touch) and -// GET /billing/preview list them (toClaim). The +// account but has not put on it: the app's banners (marketing/touch) +// 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 @@ -678,9 +678,12 @@ const CLAIMED_ALREADY = 1003 const CAPTCHA = 3007 const CAPTCHA_WORDS = /captcha/i -// zcodeHeaders are what the ZCode app sends on its billing calls beside -// the session (#503's capture): its version and platform. -const zcodeHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform": platform() }) +// The marketing feed and the claim are gated on the client's version: +// under an older version's header the feed answers empty (11-03: the +// day's banner showed for 3.17.2 and for no older one), so they go as +// the current client (3.17.2) sends them. +const MARKETING_VERSION = "3.17.2" +const marketingHeaders = () => ({ "X-ZCode-App-Version": MARKETING_VERSION, "X-Platform": platform(), "X-Client-Language": clientLanguage() }) // claimOne asks /billing/claim for one plan and says what its body says: // "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the @@ -693,7 +696,7 @@ async function claimOne(s, planID) { try { res = await fetch(`${ZCODE}/api/v1/zcode-plan/billing/claim`, { method: "POST", - headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA, Authorization: "Bearer " + s.jwt, "X-Device-Mid": s.device || anyDevice, ...zcodeHeaders() }, + headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA, Authorization: "Bearer " + s.jwt, "X-Device-Mid": s.device || anyDevice, ...marketingHeaders() }, body: JSON.stringify({ plan_id: planID }), }) text = await res.text() @@ -713,30 +716,17 @@ async function claimOne(s, planID) { return { outcome: "failed", why: `${msg || "error"} (HTTP ${res.status}, code ${code})` } } -// previewPlans is /billing/preview's plan list. An account with nothing to -// claim is answered {"code":0,"msg":"","logid":…}: no data at all, not -// "plans": [] (the owner's account read 10-30 for hykql's report on -// Discord; the list is left out when it is empty). call has already judged the code, so a reply -// without data, or data without plans, is a list of none. Only data that -// isn't an object, or plans that are there and aren't a list, don't read -// (null, unknown). -function previewPlans(d) { - if (d == null) return [] - if (typeof d !== "object" || Array.isArray(d)) return null - if (d.plans == null) return [] - return Array.isArray(d.plans) ? d.plans : null -} - // 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 +// from it. A banner plan ("ZCODE WEEKEND BUILD", 10-30) is served only // 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= 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). +// banner.background.args.zcode_plan.name). The v3.17 client reads this +// feed alone: the old preview polling is gone, and the rewards center's +// gifts are the rewards website's, claimed in the client. const TOUCH = "/api/v1/marketing/touch" const CLAIM_ACTION = "claim_zcode_plan" let touchSeq = 0 @@ -775,30 +765,27 @@ function touchPlans(d) { } // 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. +// marketing feed offers (its banners). The v3.17 client replaced the old +// preview polling with the feed alone (docs/marketing-touch-client.md in +// zai-org/ZCode), so the preview is read no more; a rewards center's gift +// lives on the rewards website, outside this API, and is claimed in the +// client. unread names a feed 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) + let d + try { + d = await call("GET", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { auth: "Bearer " + s.jwt, device: s.device, headers: marketingHeaders() }) + } catch (e) { + unread.push(`gift plans to claim: ${e?.message ?? String(e)}`) + return { plans, unread } } - 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()) })) - }) + const got = touchPlans(d) + if (!got) unread.push("gift plans to claim: the plan list doesn't read") + else got.forEach(add) return { plans, unread } } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index 9721324..d552e28 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.44", + "version": "0.1.45", "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": "./opencode.mjs", diff --git a/packages/zcode/pending.test.mjs b/packages/zcode/pending.test.mjs index 048e6ff..b0a817a 100644 --- a/packages/zcode/pending.test.mjs +++ b/packages/zcode/pending.test.mjs @@ -2,9 +2,9 @@ // 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 +// The balance's plans are as ZCode's /billing/balance says them // 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 +// Unix seconds (usage.test.mjs's fixtures are real replies). 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. @@ -61,7 +61,7 @@ const bucket = (up, left, model = "GLM-5.1") => ({ plan_id: "zcode-v3-start-plan 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 (url.pathname === "/api/v1/marketing/touch") return ok({ deliveries: [] }) 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 }] }) diff --git a/packages/zcode/team-gift.test.mjs b/packages/zcode/team-gift.test.mjs index f2c3626..f996664 100644 --- a/packages/zcode/team-gift.test.mjs +++ b/packages/zcode/team-gift.test.mjs @@ -31,7 +31,7 @@ beforeEach(() => { case "/api/monitor/usage/quota/limit": return ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: 90 }] }) case "/api/biz/team/subscribe/product/querySubscribeDetail": return ok({ hasSubscription: true, status: "EFFECTIVE", memberGrantStatus: "VALID", productName: "Team Max" }) case "/api/biz/customer-package-reset/list": return ok({}) - case "/api/v1/zcode-plan/billing/preview": return ok({ plans: [{ plan_id: "trust", name: "Trust Build" }] }) + case "/api/v1/marketing/touch": return ok({ deliveries: [{ banner: { background: { args: { zcode_plan: { name: "Trust Build" } } }, buttons: [{ action: { type: "claim_zcode_plan", args: { plan_id: "trust" } } }] } }] }) case "/api/anthropic/v1/messages": case "/api/v1/zcode-plan/anthropic/v1/messages": return ok({ type: "message", content: [] }) default: return new Response("", { status: 404 }) diff --git a/packages/zcode/usage.test.mjs b/packages/zcode/usage.test.mjs index 045c9be..fa85075 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -356,31 +356,35 @@ test("a model ZCode's config gives no limits has none made up", () => { expect(_internal.entry({ id: "GLM-9", context: 300_000, output: 8_000, efforts: [] }).limit).toEqual({ context: 300_000, output: 8_000 }) }) -// The ZCode app's own list of manual-claim gift plans: GET /billing/preview -// is read with the usage card, and a plan it lists that the balance does not -// hold is named on the card, to be claimed in the ZCode app (the claim needs -// the app's captcha attestation, see claimHint). Both fixtures are real -// responses: one account's preview while the day's ZCode Trust Build was -// still unclaimed, and one after it had claimed it. Reading the card never asks -// the claim endpoint. The window's name is the fixed sentence magpie -// translates; the count and the plan's own name are the display. -const PREVIEW_CLAIMABLE = { +// The ZCode app's list of claimable gift plans is its marketing feed +// (touch; see checkin.test.mjs). The v3.17 client reads the feed alone — +// the old preview polling is gone — and the rewards center's gifts are +// the rewards website's, claimed in the client. Two fixtures: the day's +// ZCode Trust Build still in the feed, and the feed after it was claimed. +// Reading the card never asks the claim endpoint. The window's name is +// the fixed sentence magpie translates; the count and the plan's own +// name are the display. +const TOUCH_TRUST = { server_time: 1791216750, - plans: [{ - user_plan_id: "upl_2107141892427358208", plan_id: "zcode-v3-start-plan-trust-1006", name: "ZCode Trust Build", - description: "ZCode Global Build", priority: 110, status: "active", starts_at: 1791216750, ends_at: 1791302400, - entitlements: [{ entitlement_id: "zcode-v3-start-plan-trust-1006", show_name: "GLM-5.3-Flash", meter: "model_usage", - unit_type: "token", capabilities: ["model:glm-5.3-flash"], grant_units: 100000000, period: "one_time", priority: 110, effective_at: 0 }], + deliveries: [{ + campaign_id: "2101141259813175296", priority: 100, resource_position: "banner", + banner: { + layout: "", + background: { type: "zcode_plan", args: { zcode_plan: { plan_id: "zcode-v3-start-plan-trust-1006", name: "ZCode Trust Build", grant_units: 100000000, period: "one_time" } } }, + buttons: [ + { text: { format: "", content: "领取" }, action: { type: "claim_zcode_plan", args: { plan_id: "zcode-v3-start-plan-trust-1006" } } }, + { text: { format: "", content: "关闭" }, action: { type: "close" } }, + ], + }, }], } -const PREVIEW_CLAIMED = { server_time: 1791276990, plans: [] } const TRUST_BUILD = { name: "Gift plans to claim in the ZCode app", used: 0, aside: true, display: "1 · ZCode Trust Build" } -// the Start Plan's own card, with the preview answering what preview says -async function startCard(now, token, preview) { +// the Start Plan's own card, with the feed answering what the app reads +async function startCard(now, token, touch) { 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 preview(calls) + if (url.pathname === "/api/v1/marketing/touch") return touch(calls) }) const auth = oauth({ site: "zai", jwt: token, device: "11111111-2222-4333-8444-555555555555" }) return { u: await usage(auth), calls } @@ -389,7 +393,7 @@ async function startCard(now, token, preview) { test("a gift plan ZCode holds but has not granted is named on the card, to claim in the app", async () => { const now = Math.trunc(Date.now() / 1000) const token = jwt(now + 86400) - const { u, calls } = await startCard(now, token, () => ok(PREVIEW_CLAIMABLE)) + const { u, calls } = await startCard(now, token, () => ok(TOUCH_TRUST)) expect(u.windows).toEqual([ { name: "GLM-5.1", used: 25, display: "250000 / 1000000", amount: 250000, limit: 1000000, resetsAt: new Date((now + 3600) * 1000).toISOString(), span: 86400, models: ["GLM-5.1", "GLM-5.1-Trial"] }, @@ -397,15 +401,18 @@ test("a gift plan ZCode holds but has not granted is named on the card, to claim ]) // it is no allowance: set aside, so routing, caps and the menu bar pass it over expect(u.windows.at(-1).aside).toBe(true) - // the preview went out as ZCode's own client asks it - const p = calls.find((c) => c.url.pathname.endsWith("/preview")) - expect(p.method).toBe("GET") - expect(p.url.searchParams.get("app_version")).toBe("3.16.3") - expect(p.url.searchParams.get("platform")).toBe(`${process.platform}-${process.arch}`) - expect(p.headers.Authorization).toBe("Bearer " + token) - expect(p.headers["X-Device-Mid"]).toBe("11111111-2222-4333-8444-555555555555") + // the feed went out as ZCode's own client asks it + const t = calls.find((c) => c.url.pathname.endsWith("/marketing/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("11111111-2222-4333-8444-555555555555") + expect(t.headers["X-ZCode-App-Version"]).toBe("3.17.2") + expect(t.headers["X-Client-Language"]).toBeTruthy() // nothing claims it here expect(calls.some((c) => c.url.pathname.endsWith("/claim"))).toBe(false) + // the preview is not asked anymore (the v3.17 client reads the feed alone) + expect(calls.some((c) => c.url.pathname.endsWith("/preview"))).toBe(false) }) // #503, 10-30: a banner plan is in the app's marketing feed and in no @@ -415,7 +422,6 @@ test("a banner plan from the app's marketing feed is named on the card", async ( 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" } } }] } }] }) }) @@ -426,12 +432,12 @@ test("a banner plan from the app's marketing feed is named on the card", async ( 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)) + const { u } = await startCard(now, jwt(now + 86400), () => ok({ deliveries: [] })) expect(u.windows.map((w) => w.name)).toEqual(["GLM-5.1"]) expect(u.error).toBeUndefined() }) -test("a preview that fails shows nothing and leaves the card as it was", async () => { +test("a feed that fails shows nothing and leaves the card as it was", async () => { const now = Math.trunc(Date.now() / 1000) const token = jwt(now + 86400) const before = (await startCard(now, token, () => new Response("", { status: 404 }))).u @@ -444,28 +450,30 @@ test("a preview that fails shows nothing and leaves the card as it was", async ( expect(u.error).toBeUndefined() expect(u.windows.some((w) => w.aside)).toBe(false) } - // an expired sign-in is no preview request either + // an expired sign-in is no feed request either const calls = serve(() => undefined) expect((await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).error).toContain("sign-in has expired") - expect(calls.some((c) => c.url.pathname.endsWith("/preview"))).toBe(false) + expect(calls.some((c) => c.url.pathname.endsWith("/marketing/touch"))).toBe(false) }) test("the card's error stays the error: no line is added over it", async () => { const now = Math.trunc(Date.now() / 1000) - const { u } = await startCard(now, jwt(now + 86400), () => ok(PREVIEW_CLAIMABLE)) + const { u } = await startCard(now, jwt(now + 86400), () => ok(TOUCH_TRUST)) expect(u.windows.at(-1)).toEqual(TRUST_BUILD) // a working card gets it const calls = serve(({ url }) => { if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok(startBalance(now, "expired")) - if (url.pathname === "/api/v1/zcode-plan/billing/preview") return ok(PREVIEW_CLAIMABLE) + if (url.pathname === "/api/v1/marketing/touch") return ok(TOUCH_TRUST) }) const over = await usage(oauth({ site: "zai", jwt: jwt(now + 86400), device: "d" })) expect(over).toEqual({ signIn: "kept", error: "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" }) - expect(calls.some((c) => c.url.pathname.endsWith("/preview"))).toBe(false) // nothing to put it on + expect(calls.some((c) => c.url.pathname.endsWith("/claim"))).toBe(false) // nothing to put it on }) test("several claimable plans are counted", async () => { const now = Math.trunc(Date.now() / 1000) - const two = { ...PREVIEW_CLAIMABLE, plans: [PREVIEW_CLAIMABLE.plans[0], { plan_id: "zcode-v3-start-plan-trust-1007", name: "ZCode Trust Build", status: "active" }] } + const first = TOUCH_TRUST.deliveries[0] + const second = { ...first, campaign_id: "2101141259813175297", banner: { ...first.banner, background: { type: "zcode_plan", args: { zcode_plan: { plan_id: "zcode-v3-start-plan-trust-1007", name: "ZCode Trust Build", grant_units: 100000000, period: "one_time" } } }, buttons: [{ text: { format: "", content: "领取" }, action: { type: "claim_zcode_plan", args: { plan_id: "zcode-v3-start-plan-trust-1007" } } }, { text: { format: "", content: "关闭" }, action: { type: "close" } }] } } + const two = { server_time: TOUCH_TRUST.server_time, deliveries: [first, second] } const { u } = await startCard(now, jwt(now + 86400), () => ok(two)) expect(u.windows.at(-1)).toEqual({ name: "Gift plans to claim in the ZCode app", used: 0, aside: true, display: "2 · ZCode Trust Build" }) }) @@ -478,14 +486,14 @@ test("a coding account's line goes after its coding and gift windows", async () 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 }] }) 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_CLAIMABLE) + if (url.pathname === "/api/v1/marketing/touch") return ok(TOUCH_TRUST) }) 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 · Start Plan", "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) + expect(calls.filter((c) => c.url.pathname.endsWith("/marketing/touch"))).toHaveLength(1) }) // #503: the same card line from the real marketing/touch reply