Repository navigation
Expand file tree
/
Copy pathusage.test.mjs
More file actions
529 lines (499 loc) · 31.7 KB
/
Copy pathusage.test.mjs
File metadata and controls
529 lines (499 loc) · 31.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// auth.usage tells what magpie's built-in ZCode usage told for the same
// answers (internal/provider/zcode_test.go TestZCodeAccounts,
// zcode_start_test.go TestZCodeStartPlanOwnAccount, zcode_team_test.go).
import { test, expect, afterAll, beforeAll, beforeEach } from "bun:test"
import { homedir, tmpdir } from "node:os"
import { readFileSync, realpathSync } from "node:fs"
let ZCodeAuthPlugin, _internal
beforeAll(async () => {
// Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test, so
// no real sign-in is ever read
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"))
})
// nothing leaves the machine; the fetch this file found is put back when
// it is done, so the next test file (bun runs them all in one process)
// doesn't inherit offline or a fake of this file's
const offline = async () => { throw new Error("no network in tests") }
const real = globalThis.fetch
afterAll(() => (globalThis.fetch = real))
beforeEach(() => {
globalThis.fetch = offline
_internal.routes.clear()
_internal.teamKeys.clear()
})
const ok = (data) => new Response(JSON.stringify({ code: 0, data }))
function serve(route) {
const calls = []
globalThis.fetch = async (url, init = {}) => {
const u = new URL(String(url))
const c = { url: u, method: init.method ?? "GET", headers: init.headers ?? {}, body: init.body }
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, sets = []) {
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async (x) => sets.push(x) } } })
return hooks.auth.usage(async () => auth, { id: "zcode" })
}
const jwt = (exp) => ["{}", JSON.stringify({ exp })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
// a card read with no ZCode session says the gift plans need one: a key
// (or a sign-in with no ZCode token) reads no gift and lists no -Trial
const GIFT = "ZCode gift plans (-Trial models) need ZCode's sign-in"
const KEY_LINE = { name: GIFT, used: 0, aside: true, display: "not read with an API key: add the account with a ZCode sign-in" }
const NO_SESSION = { name: GIFT, used: 0, aside: true, display: "this sign-in has no ZCode session: sign in again" }
test("a Coding Plan's five hours and week", async () => {
const reset = Date.now() + 3600_000
const calls = serve(({ url, headers }) => {
if (headers.Authorization !== "two.secret2") return new Response("", { status: 401 })
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, usage: 2000, remaining: 1500, percentage: 25, nextResetTime: reset },
{ type: "CREDIT_LIMIT", unit: 6, number: 1, usage: 10000, remaining: 9000, percentage: 10, nextResetTime: reset },
] })
})
expect(await usage(oauth({ site: "zai", key: "two.secret2" }))).toEqual({
signIn: "kept",
plan: "GLM Coding Pro",
windows: [
{ name: "5 hours", used: 25, display: "500 / 2000", amount: 500, limit: 2000, resetsAt: new Date(reset).toISOString(), span: 5 * 3600 },
{ name: "Weekly", used: 10, display: "1000 / 10000", amount: 1000, limit: 10000, resetsAt: new Date(reset).toISOString(), span: 7 * 86400 },
NO_SESSION,
],
})
expect(calls.every((c) => c.url.origin === "https://api.z.ai")).toBe(true)
// an API key, BigModel's, is asked on its own site
const bm = serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ level: "lite", limits: [] }) : ok([{ productName: "GLM Coding Lite", status: "VALID" }])))
expect(await usage({ type: "api", key: "k", metadata: { site: "bigmodel" } })).toEqual({ signIn: "kept", plan: "GLM Coding Lite", windows: [KEY_LINE] })
expect(bm[0].url.origin).toBe("https://open.bigmodel.cn")
})
// rtbeilin (X, 10-24): ZCode 1024 Dev Day, no GLM Coding Plan, "API Key
// doesn't work". The gift is ZCode's session's alone; a key's card says
// so instead of showing nothing
test("a key with no GLM Coding Plan says a ZCode gift plan needs ZCode's sign-in", async () => {
const none = /no GLM Coding Plan; ZCode's gift plans .* are spent only with ZCode's sign-in, never with a key/
for (const site of ["zai", "bigmodel"]) {
serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [] }) : ok([])))
expect((await usage({ type: "api", key: "k", metadata: { site } })).error).toMatch(none)
// a subscription that ran out is no plan in force either
serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [] }) : ok([{ productName: "GLM Coding Lite", status: "EXPIRED" }])))
expect((await usage({ type: "api", key: "k", metadata: { site } })).error).toMatch(none)
}
// a list that couldn't be read is not "no plan"
serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [] }) : new Response("", { status: 500 })))
expect(await usage({ type: "api", key: "k", metadata: { site: "zai" } })).toEqual({ signIn: "kept", windows: [KEY_LINE] })
// a counted window or a level is a plan, whatever the list says
serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [{ unit: 3, number: 5, percentage: 3 }] }) : ok([])))
expect((await usage({ type: "api", key: "k", metadata: { site: "zai" } })).error).toBeUndefined()
serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ level: "pro", limits: [] }) : ok([])))
expect((await usage({ type: "api", key: "k", metadata: { site: "zai" } })).error).toBeUndefined()
})
test("windows, names and terms as Go reads them", () => {
const ws = _internal.limitWindows({ limits: [
{ unit: 3, usage: 1000, currentValue: 420, percentage: 42 }, // the percentage stands
{ unit: 6, usage: 800, currentValue: 200 }, // none: from the current value
{ unit: 1, number: 30, percentage: 7.5 },
{ unit: 4, number: 3 },
{ unit: 5, number: 1, usage: 0, remaining: 5 },
{ unit: 0 },
] })
expect(ws).toEqual([
{ name: "5 hours", used: 42, display: "420 / 1000", amount: 420, limit: 1000, span: 18000 },
{ name: "Weekly", used: 25, display: "200 / 800", amount: 200, limit: 800, span: 604800 },
{ name: "0 hours", used: 7.5, span: 1800 },
{ name: "3 days", used: 0, span: 3 * 86400 },
{ name: "Monthly", used: 0, aside: true, span: 30 * 86400 }, // a whole of 0: no cap
{ name: "Credits", used: 0 },
])
// Beijing times: the next renewal, auto or not; else the valid span's end
expect(_internal.termOf([{ status: "EXPIRED", nextRenewTime: "2026-01-01 00:00:00" },
{ status: "VALID", autoRenew: 1, nextRenewTime: "2026-10-18 12:00:00" }]))
.toEqual({ until: "2026-10-18T04:00:00.000Z", renew: "auto" })
expect(_internal.termOf([{ status: "valid", autoRenew: false, valid: "2026-09-18 12:00:00-2026-10-18 12:00:00" }]))
.toEqual({ until: "2026-10-18T04:00:00.000Z", renew: "off" })
expect(_internal.termOf([{ status: "VALID", autoRenew: true, valid: "2026-09-18-2026-10-18" }])).toEqual({})
expect(_internal.termOf([{ status: "VALID", valid: "2026-09-18 - 2026-10-18" }])).toEqual({ until: "2026-10-17T16:00:00.000Z", renew: "off" })
})
// #659: a window counted in amounts says the count as used or as left, as
// its share is said (magpie's QuotaWindow.Count, quotaCount in the GUI);
// amount is what is used of limit. A window that told only the vendor's
// used-first text froze that count beside a "% left" figure — ZCode's gift
// card read "28395087 / 100000000 · 71.6% left".
test("a counted window carries what is used of the whole", async () => {
serve(({ url }) => {
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: "TOKENS_LIMIT", unit: 3, number: 5, usage: 2000, remaining: 1500, percentage: 25, nextResetTime: Date.now() + 3600_000 },
] })
})
const w = (await usage(oauth({ site: "zai", key: "two.secret2" }))).windows[0]
// 500 of 2000 used: magpie says "500 / 2,000" used, "1,500 / 2,000" left
expect([w.used, w.amount, w.limit]).toEqual([25, 500, 2000])
})
// Go's TestZCodeNoMonthlyCap (#366): the month's MCP tool calls are named
// and set aside as the built-in's are, so an older plan's uncapped month,
// told as 100% used, never reads as the account run out
test("the month's MCP calls: named and set aside, an uncapped month nothing used", () => {
const reset = Date.now() + 3 * 3600_000
const month = Date.now() + 20 * 86400_000
expect(_internal.limitWindows({ level: "pro", limits: [
{ type: "TOKENS_LIMIT", unit: 3, number: 5, percentage: 0, nextResetTime: reset },
{ type: "TIME_LIMIT", unit: 5, number: 1, usage: 0, currentValue: 0, remaining: 0, percentage: 100, nextResetTime: month },
] })).toEqual([
{ name: "5 hours", used: 0, resetsAt: new Date(reset).toISOString(), span: 5 * 3600 },
{ name: "MCP · Month", used: 0, aside: true, resetsAt: new Date(month).toISOString(), span: 30 * 86400 },
])
// capped and used up: still shown as used, still aside
const ws = _internal.limitWindows({ limits: [
{ type: "TOKENS_LIMIT", unit: 3, number: 5, percentage: 10, nextResetTime: reset },
{ type: "TOKENS_LIMIT", unit: 6, number: 1, percentage: 30, nextResetTime: month },
{ type: "TIME_LIMIT", unit: 5, number: 1, usage: 100, currentValue: 100, remaining: 0, percentage: 100, nextResetTime: month },
] })
expect(ws.map((w) => [w.name, w.used, !!w.aside, w.display])).toEqual([
["5 hours", 10, false, undefined],
["Weekly", 30, false, undefined],
["MCP · Month", 100, true, "100 / 100"],
])
})
// a Start Plan with one bucket, GLM-5.1's tokens for the day, a quarter used
function startBalance(now, status) {
return { server_time: now, plans: [{ plan_id: "zai-start-plan", user_plan_id: "up1", name: "Start Plan", status, ends_at: now + 7 * 86400,
entitlements: [{ entitlement_id: "e1", period: "daily" }] }],
balances: [{ plan_id: "zai-start-plan", user_plan_id: "up1", entitlement_id: "e1", show_name: "GLM-5.1", capabilities: ["model:GLM-5.1"],
total_units: "1000000", used_units: 250000, remaining_units: 750000, expires_at: now + 3600 }] }
}
test("ZCode's Start Plan: its buckets, each for its models", async () => {
const now = Math.trunc(Date.now() / 1000)
const token = jwt(now + 86400)
let balance = startBalance(now, "active")
const calls = serve(({ url, headers }) => {
if (url.pathname !== "/api/v1/zcode-plan/billing/balance") return
if (!headers["X-Device-Mid"]) return new Response(JSON.stringify({ code: 3001, msg: "parameter error" }), { status: 400 })
if (headers.Authorization !== "Bearer " + token || !url.searchParams.get("app_version")) return new Response("", { status: 401 })
return ok(balance)
})
const auth = oauth({ site: "bigmodel", jwt: token, device: "11111111-2222-4333-8444-555555555555" })
expect(await usage(auth)).toEqual({
signIn: "kept",
plan: "Start Plan", until: new Date((now + 7 * 86400) * 1000).toISOString(), renew: "off",
windows: [{ 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"] }],
})
expect(calls[0].url.origin).toBe("https://zcode.z.ai")
expect(calls[0].headers["X-Device-Mid"]).toBe("11111111-2222-4333-8444-555555555555")
const over = { signIn: "kept", error: "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" }
balance = startBalance(now, "expired")
expect(await usage(auth)).toEqual(over)
// still "active" past its end is over too, as ZCode reads it
balance = { ...startBalance(now, "active"), server_time: now + 8 * 86400 }
expect(await usage(auth)).toEqual(over)
// a bucket counted by what remains, spanned by its period
balance = startBalance(now, "active")
balance.balances = [{ plan_id: "zai-start-plan", capabilities: [" model: GLM-5-Turbo ", "model:"], total_units: 200, remaining_units: "150",
period_start: now, period_end: now + 7 * 86400 }]
expect((await usage(auth)).windows).toEqual([{ name: "GLM-5-Turbo", used: 25, display: "50 / 200", amount: 50, limit: 200, span: 7 * 86400, models: ["GLM-5-Turbo", "GLM-5-Turbo-Trial"] }])
// its token run out
expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ signIn: "kept", error: "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" })
})
// customer-package-reset/list?targetType=PERSONAL as the reporter of
// yetone/magpie#1191 captured it on bigmodel.cn (the built-in's
// zhipu_resets_test.go zhipuResetList): one run out stays listed.
const PERSONAL_RESETS = {
code: 200, msg: "操作成功", success: true,
data: {
customerId: 0, targetType: "PERSONAL", organizationId: null, projectId: null,
lastFiveHourResetTime: "2026-10-06 21:14:03", lastWeekResetTime: null,
fiveHourResets: [{ recordId: 0, grantType: "DIRECT", expireTime: "2027-11-02 23:59:59", available: true }],
weekResets: [
{ recordId: 0, grantType: "DIRECT", expireTime: "2027-10-30 23:59:59", available: true },
{ recordId: 0, grantType: "DIRECT", expireTime: "2026-10-04 23:59:59", available: false },
],
},
}
test("a Coding Plan of a person's own shows its resets, each with its end, as the built-in's zhipuPersonalResets did", async () => {
let list = PERSONAL_RESETS
const calls = serve(({ url, headers }) => {
if (headers.Authorization !== "glm-key") return new Response("", { status: 401 })
if (url.pathname === "/api/biz/subscription/list") return ok([])
if (url.pathname === "/api/monitor/usage/quota/limit") return ok({ level: "pro", limits: [] })
if (url.pathname === "/api/biz/customer-package-reset/list" && url.searchParams.get("targetType") === "PERSONAL")
return typeof list === "number" ? new Response("", { status: list }) : new Response(JSON.stringify(list))
})
const auth = oauth({ site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", key: "glm-key" })
expect(await usage(auth)).toEqual({
signIn: "kept",
plan: "GLM Coding Pro",
windows: [NO_SESSION],
resets: { count: 2, byWindow: true, fiveHour: 1, weekly: 1, until: "2027-10-30T15:59:59.000Z", each: [
{ until: "2027-10-30T15:59:59.000Z", window: "weekly" },
{ until: "2027-11-02T15:59:59.000Z", window: "fiveHour" },
] },
})
const asked = calls.find((c) => c.url.pathname === "/api/biz/customer-package-reset/list")
expect(asked.url.origin).toBe("https://open.bigmodel.cn")
expect(asked.method).toBe("GET")
// a list that can't be read shows no count, never 0; nor does one with none left
list = 500
expect((await usage(auth)).resets).toBeUndefined()
list = { code: 200, data: { fiveHourResets: [], weekResets: [{ available: false, expireTime: "2026-10-04 23:59:59" }] } }
expect((await usage(auth)).resets).toBeUndefined()
// one with no end is listed last, with none
list = { code: 200, data: { fiveHourResets: [{ available: true }], weekResets: [{ available: true, expireTime: "2027-10-30 23:59:59" }] } }
expect((await usage(auth)).resets).toEqual({ count: 2, byWindow: true, fiveHour: 1, weekly: 1, until: "2027-10-30T15:59:59.000Z", each: [
{ until: "2027-10-30T15:59:59.000Z", window: "weekly" },
{ window: "fiveHour" },
] })
})
test("a team seat: the team plan's windows, name, end and resets, its key found and saved", async () => {
const reset = Date.now() + 2 * 3600_000
let made = null
const TOKEN = "Bearer team-token"
serve(({ url, method, headers, body }) => {
const p = url.pathname, org = headers["Bigmodel-Organization"], proj = headers["Bigmodel-Project"]
if (url.origin !== "https://bigmodel.cn") return
if (p === "/api/biz/team/subscribe/product/querySubscribeDetail" && headers.Authorization === TOKEN && org === "t1" && proj === "tp1")
return ok({ hasSubscription: true, status: "EFFECTIVE", memberGrantStatus: "VALID", productId: "prod-1", productName: "GLM Coding Team Pro",
subscribeEndTime: "2027-12-31 23:59:59" })
if (p === "/api/biz/v1/organization/t1/projects/tp1/api_keys" && headers.Authorization === TOKEN && org === "t1" && proj === "tp1") {
if (method === "POST") {
made = JSON.parse(body)
return ok({ name: "zcode-team-api-key", apiKey: "tk", keyType: 2 })
}
return ok([{ name: "zcode-team-api-key", apiKey: "wrong-type", keyType: 1 }, ...(made ? [{ name: "zcode-team-api-key", apiKey: "tk", keyType: 2 }] : [])])
}
if (p === "/api/biz/v1/organization/t1/projects/tp1/api_keys/copy/tk") return ok({ secretKey: "ts" })
if (p === "/api/biz/customer-package-reset/list" && headers.Authorization === TOKEN && org === "t1" && proj === "tp1" && url.searchParams.get("targetType") === "TEAM")
return ok({
fiveHourResets: [{ available: true, expireTime: "2027-11-30 23:59:59" }, { available: true, expireTime: 1800000000 }, { available: false, expireTime: 1 }],
weekResets: [{ available: true, expireTime: "2027-12-31 23:59:59" }],
})
if (p === "/api/monitor/usage/quota/limit") {
if (headers.Authorization !== "tk.ts" || url.searchParams.get("type") !== "2" || headers["Set-Language"] !== "zh") return ok({ limits: [] })
return ok({ limits: [
{ type: "CREDIT_LIMIT", unit: 3, percentage: 42, currentValue: 420, usage: 1000, nextResetTime: reset },
{ type: "CREDIT_LIMIT", unit: 6, percentage: 10, currentValue: 1000, usage: 10000, nextResetTime: reset + 86400000 },
] })
}
})
const sets = []
const state = { site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", token: TOKEN, org: "t1", project: "tp1", plan: "GLM Coding Team Pro" }
expect(await usage(oauth(state), sets)).toEqual({
signIn: "kept",
plan: "GLM Coding Team Pro", until: "2027-12-31T15:59:59.000Z", renew: "off",
// a team's resets say so, and each its own end, soonest first, as the
// built-in's zhipuTeamResets did
resets: { count: 3, byWindow: true, fiveHour: 2, weekly: 1, until: new Date(1800000000 * 1000).toISOString(), team: true, each: [
{ until: new Date(1800000000 * 1000).toISOString(), window: "fiveHour" },
{ until: "2027-11-30T15:59:59.000Z", window: "fiveHour" },
{ until: "2027-12-31T15:59:59.000Z", window: "weekly" },
] },
windows: [
{ name: "5 hours", used: 42, display: "420 / 1000", amount: 420, limit: 1000, resetsAt: new Date(reset).toISOString(), span: 5 * 3600 },
{ name: "Weekly", used: 10, display: "1000 / 10000", amount: 1000, limit: 10000, resetsAt: new Date(reset + 86400000).toISOString(), span: 7 * 86400 },
{ name: "ZCode gift plans (-Trial models) need ZCode's sign-in", used: 0, aside: true, display: "this sign-in has no ZCode session: sign in again" },
],
})
expect(made).toEqual({ name: "zcode-team-api-key", keyType: 2 })
expect(sets.length).toBe(1)
expect(sets[0].path).toEqual({ id: "zcode" })
expect(sets[0].body.access).toBe("tk.ts")
expect(JSON.parse(sets[0].body.refresh)).toEqual({ ...state, key: "tk.ts", device: expect.any(String) })
})
test("Z.ai's refusals are the card's error", async () => {
serve(() => new Response("", { status: 401 }))
expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ signIn: "kept", error: "Unauthorized" })
serve(() => new Response(JSON.stringify({ code: 1001, msg: "Authorization Token非法" }), { status: 401 }))
expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ signIn: "kept", error: "Authorization Token非法 (401, code 1001)" })
serve(() => new Response(JSON.stringify({ code: 500, msg: "" })))
expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ signIn: "kept", error: "error 500" })
expect(await usage(undefined)).toEqual({ signIn: "kept", error: "not signed in" })
})
// magpie's built-in starts every card from the saved plan (zcode.go
// zcodeQuota, zcode_team.go zcodeTeamQuota, zcode_start.go zcodeStartQuota)
test("the saved plan stays on the card when the reply has no level, a team detail fails, or on an error", async () => {
serve(({ url }) => {
if (url.pathname === "/api/monitor/usage/quota/limit") return ok({ limits: [] })
if (url.pathname === "/api/biz/subscription/list") return ok([])
})
const own = await usage(oauth({ site: "zai", key: "k", plan: "GLM Coding Max" }))
expect(own.plan).toBe("GLM Coding Max")
expect(own.error).toBeUndefined()
serve(({ url }) => {
if (url.pathname === "/api/monitor/usage/quota/limit") return ok({ limits: [] })
return new Response("", { status: 500 })
})
const team = { site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", key: "tk.ts", token: "Bearer t", org: "t1", project: "tp1", plan: "GLM Coding Team Pro" }
expect((await usage(oauth(team))).plan).toBe("GLM Coding Team Pro")
serve(() => new Response("", { status: 401 }))
expect(await usage(oauth({ site: "zai", key: "k", plan: "GLM Coding Max" }))).toEqual({ signIn: "kept", plan: "GLM Coding Max", error: "Unauthorized" })
})
// the built-in left a limit ZCode's config doesn't name at 0
test("a model ZCode's config gives no limits has none made up", () => {
expect(_internal.entry({ id: "GLM-9", context: 0, output: 0, efforts: [] }).limit).toEqual({ context: 0, output: 0 })
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 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,
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 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 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/marketing/touch") return touch(calls)
})
const auth = oauth({ site: "zai", jwt: token, device: "11111111-2222-4333-8444-555555555555" })
return { u: await usage(auth), calls }
}
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(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"] },
TRUST_BUILD,
])
// 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 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
// 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/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({ deliveries: [] }))
expect(u.windows.map((w) => w.name)).toEqual(["GLM-5.1"])
expect(u.error).toBeUndefined()
})
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
const refused = (await startCard(now, token, () => new Response(JSON.stringify({ code: 3007, msg: "captcha verify failed" }), { status: 400 }))).u
const thrown = (await startCard(now, token, () => {
throw new Error("no network in tests")
})).u
for (const u of [refused, thrown]) {
expect(u).toEqual(before)
expect(u.error).toBeUndefined()
expect(u.windows.some((w) => w.aside)).toBe(false)
}
// 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("/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(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/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("/claim"))).toBe(false) // nothing to put it on
})
test("several claimable plans are counted", async () => {
const now = Math.trunc(Date.now() / 1000)
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" })
})
// a coding account with gift plans: the line goes last, after both allowances
test("a coding account's line goes after its coding and gift windows", async () => {
const now = Math.trunc(Date.now() / 1000)
const token = jwt(now + 86400)
const calls = serve(({ url }) => {
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/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("/marketing/touch"))).toHaveLength(1)
})
// #503: the same card line from the real marketing/touch reply
// (testdata/touch-1030-wk.json; see checkin.test.mjs for how it was cut)
test("the real banner feed names its plan once on the card", async () => {
const now = Math.trunc(Date.now() / 1000)
const token = jwt(now + 86400)
const real = readFileSync(new URL("./testdata/touch-1030-wk.json", import.meta.url), "utf8")
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 new Response(real)
})
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 reset the list flags available but whose end has passed is not counted (nathan_ift_us on X: two cards shown, none owned)", async () => {
const list = { code: 200, data: {
fiveHourResets: [{ recordId: 0, grantType: "DIRECT", expireTime: "2020-11-08 23:59:59", available: true }],
weekResets: [{ recordId: 0, grantType: "DIRECT", expireTime: "2020-11-08 23:59:59", available: true }],
} }
serve(({ url }) => {
if (url.pathname === "/api/biz/subscription/list") return ok([])
if (url.pathname === "/api/monitor/usage/quota/limit") return ok({ level: "pro", limits: [] })
if (url.pathname === "/api/biz/customer-package-reset/list") return new Response(JSON.stringify(list))
})
const auth = oauth({ site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", key: "glm-key" })
expect((await usage(auth)).resets).toBeUndefined()
list.data.weekResets.push({ available: true, expireTime: "2099-01-01 23:59:59" })
expect((await usage(auth)).resets).toMatchObject({ count: 1, fiveHour: 0, weekly: 1 })
})