bigmodelUsageQuotaProvider.test.ts 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. BIGMODEL_PROVIDER_ID,
  4. BUILTIN_MODEL_PROVIDER_IDS,
  5. ZCODE_VERSION,
  6. type ApiClient,
  7. } from "@zcode/shared";
  8. import { BigModelUsageQuotaProvider } from "../src/usage-stats/providers/bigmodelUsageQuotaProvider.js";
  9. const TEST_BIGMODEL_PROVIDER_ID = "test-bigmodel-api-provider";
  10. interface TestUsageProvider {
  11. id: string;
  12. apiKey: string;
  13. name?: string;
  14. }
  15. interface LegacyModelProviderReader {
  16. getAllCached(): Promise<TestUsageProvider[]>;
  17. }
  18. type LegacyQuotaProviderTestOptions = Omit<
  19. ConstructorParameters<typeof BigModelUsageQuotaProvider>[0],
  20. "accountRequestAuthService"
  21. > & {
  22. modelProviderService?: LegacyModelProviderReader;
  23. accountRequestAuthService?: ConstructorParameters<
  24. typeof BigModelUsageQuotaProvider
  25. >[0]["accountRequestAuthService"];
  26. };
  27. /**
  28. * 这些测试原本直接把旧 ModelProviderService 注入 quota provider。
  29. * 迁移后凭据由 Account Request Auth 提供;这里仅保留测试数据装配,避免测试继续
  30. * 把旧 Provider Config 当成生产事实来源。
  31. */
  32. function createProviderForTest(
  33. options: LegacyQuotaProviderTestOptions,
  34. ): BigModelUsageQuotaProvider {
  35. const provider = new BigModelUsageQuotaProvider({
  36. ...options,
  37. accountRequestAuthService: options.accountRequestAuthService ?? {
  38. resolveAccessCurrent: vi.fn(async () => null),
  39. resolveCurrent: vi.fn(async ({ providerId, accountAccess }) => {
  40. if (accountAccess.planKind === "team-coding-plan") {
  41. return {
  42. apiKey:
  43. providerId === BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
  44. ? "team-ak-zai.team-secret-zai"
  45. : "team-ak.team-secret",
  46. };
  47. }
  48. if (providerId.includes("start-plan")) {
  49. const token = await options.credentialService?.load("zcodejwttoken");
  50. return { apiKey: token ?? undefined };
  51. }
  52. const providers = await options.modelProviderService?.getAllCached();
  53. return {
  54. apiKey: providers?.find((candidate) => candidate.id === providerId)?.apiKey,
  55. };
  56. }),
  57. assertCurrent: vi.fn(async () => undefined),
  58. },
  59. });
  60. const getSnapshotForRequest = provider.getSnapshotForRequest.bind(provider);
  61. provider.getSnapshotForRequest = (request = {}) =>
  62. getSnapshotForRequest(withTestAccountAccess(request));
  63. return provider;
  64. }
  65. function withTestAccountAccess(
  66. request: Parameters<BigModelUsageQuotaProvider["getSnapshotForRequest"]>[0] = {},
  67. ) {
  68. const providerId = request.preferredProviderId ?? "";
  69. const family = providerId.includes("zai") ? ("zai" as const) : ("bigmodel" as const);
  70. if (request.organizationId && request.projectId) {
  71. return {
  72. ...request,
  73. accountAccess: {
  74. type: "zhipu-account" as const,
  75. family,
  76. planKind: "team-coding-plan" as const,
  77. productId: "test-product",
  78. organizationId: request.organizationId,
  79. projectId: request.projectId,
  80. },
  81. };
  82. }
  83. return {
  84. ...request,
  85. accountAccess: {
  86. type: "zhipu-account" as const,
  87. family,
  88. planKind: providerId.includes("start-plan")
  89. ? ("start-plan" as const)
  90. : ("individual-coding-plan" as const),
  91. },
  92. };
  93. }
  94. function createBigModelCodingPlanProvider(): TestUsageProvider {
  95. return {
  96. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  97. apiKey: "bigmodel-api-key",
  98. };
  99. }
  100. function createBigModelApiKeyProvider(): TestUsageProvider {
  101. return {
  102. ...createBigModelCodingPlanProvider(),
  103. id: TEST_BIGMODEL_PROVIDER_ID,
  104. apiKey: "ordinary-api-key",
  105. };
  106. }
  107. function createZaiCodingPlanProvider(): TestUsageProvider {
  108. return {
  109. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  110. apiKey: "zai-api-key",
  111. };
  112. }
  113. function createZaiStartPlanProvider(): TestUsageProvider {
  114. return {
  115. ...createZaiCodingPlanProvider(),
  116. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  117. apiKey: "provider-zcode-jwt",
  118. };
  119. }
  120. function createJsonResponse(body: unknown): Response {
  121. return new Response(JSON.stringify(body), {
  122. status: 200,
  123. headers: { "Content-Type": "application/json", Date: "Tue, 02 Jun 2026 00:00:00 GMT" },
  124. });
  125. }
  126. describe("BigModelUsageQuotaProvider", () => {
  127. afterEach(() => {
  128. vi.unstubAllEnvs();
  129. });
  130. it("旧 active 响应超过 HTTP Date 有效期后返回过期无权益快照", async () => {
  131. const provider = createProviderForTest({
  132. apiClient: {
  133. request: vi.fn(
  134. async () =>
  135. new Response(
  136. JSON.stringify({
  137. code: 0,
  138. data: {
  139. server_time: 1788448680,
  140. plans: [
  141. { plan_id: "zcode-v3-start-plan", status: "active", ends_at: 1788796799 },
  142. ],
  143. balances: [{ plan_id: "zcode-v3-start-plan", remaining_units: 3000000 }],
  144. },
  145. }),
  146. { headers: { Date: "Thu, 17 Sep 2026 13:42:46 GMT" } },
  147. ),
  148. ),
  149. },
  150. modelProviderService: {
  151. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  152. } as LegacyModelProviderReader,
  153. credentialService: { load: vi.fn(async () => "credential-zcode-jwt") },
  154. });
  155. expect(
  156. await provider.getSnapshotForRequest({
  157. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  158. requirePreferredProvider: true,
  159. }),
  160. ).toMatchObject({
  161. unavailableReason: "no_plan",
  162. startPlanExpired: true,
  163. subscription: null,
  164. quota: null,
  165. remaining: null,
  166. });
  167. });
  168. it("Z.ai Start Plan 用 zcodejwttoken 读取当前套餐和到期时间", async () => {
  169. const balanceUrl = `https://zcode.z.ai/api/v1/zcode-plan/billing/balance?app_version=${ZCODE_VERSION}`;
  170. const requestUrls: string[] = [];
  171. const apiClient: ApiClient = {
  172. request: vi.fn(async (input, init) => {
  173. const url = input.toString();
  174. requestUrls.push(url);
  175. expect(init?.headers).toMatchObject({
  176. Authorization: "Bearer credential-zcode-jwt",
  177. });
  178. expect(url).toBe(balanceUrl);
  179. return createJsonResponse({
  180. code: 0,
  181. msg: "ok",
  182. data: {
  183. server_time: 1_780_400_123,
  184. plans: [
  185. {
  186. plan_id: "zcode-v3-start-plan",
  187. name: "ZCode V3 Start Plan",
  188. status: "active",
  189. starts_at: 1_780_291_200,
  190. ends_at: 1_781_500_800,
  191. entitlements: [
  192. {
  193. entitlement_id: "ent_zcode_v3_glm_52",
  194. meter: "model_usage",
  195. period: "daily",
  196. },
  197. ],
  198. },
  199. ],
  200. balances: [
  201. {
  202. bucket_id: "bucket-glm-52",
  203. user_plan_id: "user-plan-52",
  204. period_start: 1_780_416_000,
  205. period_end: 1_780_502_399,
  206. meter: "model_usage",
  207. unit_type: "token",
  208. plan_id: "zcode-v3-start-plan",
  209. entitlement_id: "ent_zcode_v3_glm_52",
  210. show_name: "GLM-5.2",
  211. capabilities: ["model:glm-5.2"],
  212. total_units: 3_000_000,
  213. used_units: 500_000,
  214. remaining_units: 2_500_000,
  215. available_units: 2_500_000,
  216. expires_at: 1_780_502_400,
  217. },
  218. ],
  219. },
  220. });
  221. }),
  222. };
  223. const provider = createProviderForTest({
  224. apiClient,
  225. modelProviderService: {
  226. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  227. } as LegacyModelProviderReader,
  228. credentialService: {
  229. load: vi.fn(async (key: string) =>
  230. key === "zcodejwttoken" ? "credential-zcode-jwt" : null,
  231. ),
  232. },
  233. });
  234. const snapshot = await provider.getSnapshotForRequest({
  235. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  236. requirePreferredProvider: true,
  237. });
  238. expect(requestUrls).toEqual([balanceUrl]);
  239. expect(snapshot.serverTime).toBe(1_780_400_123_000);
  240. expect(snapshot.provider).toMatchObject({
  241. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  242. name: "Z.ai - Coding Plan",
  243. });
  244. expect(snapshot.subscription?.details[0]).toMatchObject({
  245. productId: "zcode-v3-start-plan",
  246. productName: "ZCode V3 Start Plan",
  247. billingCycle: "daily",
  248. // Start Plan 卡片不再展示套餐级续期时间;桶刷新时间由各 limit 的 nextResetTime 表达。
  249. renewTime: null,
  250. expireTime: new Date(1_781_500_800 * 1000).toISOString(),
  251. });
  252. expect(snapshot.quota).toMatchObject({
  253. level: "Start",
  254. limits: [
  255. {
  256. type: "ent_zcode_v3_glm_52",
  257. bucketId: "bucket-glm-52",
  258. userPlanId: "user-plan-52",
  259. periodStart: 1_780_416_000_000,
  260. periodEnd: 1_780_502_399_000,
  261. period: "daily",
  262. meter: "model_usage",
  263. unitType: "token",
  264. number: 3_000_000,
  265. usage: 500_000,
  266. remaining: 2_500_000,
  267. usageDetails: [{ modelCode: "glm-5.2", displayName: "GLM-5.2", usage: 500_000 }],
  268. },
  269. ],
  270. });
  271. expect(snapshot.remaining).toMatchObject({
  272. count: 2_500_000,
  273. isShow: true,
  274. nextResetTime: 1_780_502_400 * 1000,
  275. });
  276. });
  277. it("Z.ai Start Plan 保留多个套餐顺序和额度桶 plan id", async () => {
  278. const apiClient: ApiClient = {
  279. request: vi.fn(async () =>
  280. createJsonResponse({
  281. code: 0,
  282. msg: "ok",
  283. data: {
  284. plans: [
  285. {
  286. plan_id: "start-plan-welcome",
  287. name: "Welcome Plan",
  288. status: "active",
  289. ends_at: 1_781_500_800,
  290. },
  291. {
  292. plan_id: "start-plan-bonus",
  293. name: "Bonus Plan",
  294. status: "active",
  295. ends_at: 1_782_105_600,
  296. },
  297. ],
  298. balances: [
  299. {
  300. plan_id: "start-plan-welcome",
  301. entitlement_id: "welcome-glm-52",
  302. show_name: "GLM-5.2",
  303. capabilities: ["model:glm-5.2"],
  304. total_units: 3_000_000,
  305. remaining_units: 2_500_000,
  306. expires_at: 1_780_506_000,
  307. },
  308. {
  309. plan_id: "start-plan-bonus",
  310. entitlement_id: "bonus-glm-5-turbo",
  311. show_name: "GLM-5-Turbo",
  312. capabilities: ["model:glm-5-turbo"],
  313. total_units: 1_000_000,
  314. remaining_units: 750_000,
  315. expires_at: 1_781_110_800,
  316. },
  317. ],
  318. },
  319. }),
  320. ),
  321. };
  322. const provider = createProviderForTest({
  323. apiClient,
  324. modelProviderService: {
  325. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  326. } as LegacyModelProviderReader,
  327. credentialService: {
  328. load: vi.fn(async () => "credential-zcode-jwt"),
  329. },
  330. });
  331. const snapshot = await provider.getSnapshotForRequest({
  332. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  333. requirePreferredProvider: true,
  334. });
  335. expect(snapshot.subscription?.details).toMatchObject([
  336. {
  337. productId: "start-plan-welcome",
  338. productName: "Welcome Plan",
  339. expireTime: new Date(1_781_500_800 * 1000).toISOString(),
  340. },
  341. {
  342. productId: "start-plan-bonus",
  343. productName: "Bonus Plan",
  344. expireTime: new Date(1_782_105_600 * 1000).toISOString(),
  345. },
  346. ]);
  347. expect(snapshot.quota?.limits).toMatchObject([
  348. {
  349. type: "welcome-glm-52",
  350. planId: "start-plan-welcome",
  351. nextResetTime: 1_780_506_000 * 1000,
  352. },
  353. {
  354. type: "bonus-glm-5-turbo",
  355. planId: "start-plan-bonus",
  356. nextResetTime: 1_781_110_800 * 1000,
  357. },
  358. ]);
  359. });
  360. it("Z.ai Start Plan 过期套餐不进入 subscription 且移除其额度桶", async () => {
  361. // 固化服务端契约被破坏时的行为:subscription 只含 active 套餐;
  362. // 无法归属的桶由 provider 原样透传(设置页归属层会丢弃,聊天气泡仍展示),
  363. // 同时 provider 会打 warn tripwire 日志(见 warnOnUnattributedStartPlanBuckets)。
  364. const apiClient: ApiClient = {
  365. request: vi.fn(async () =>
  366. createJsonResponse({
  367. code: 0,
  368. msg: "ok",
  369. data: {
  370. plans: [
  371. {
  372. plan_id: "start-plan-welcome",
  373. name: "ZCode V3 Start Plan",
  374. status: "active",
  375. ends_at: 1_781_500_800,
  376. },
  377. {
  378. plan_id: "start-plan-expired",
  379. name: "Expired Plan",
  380. status: "expired",
  381. ends_at: 1_780_000_000,
  382. },
  383. ],
  384. balances: [
  385. {
  386. plan_id: "start-plan-welcome",
  387. entitlement_id: "welcome-glm-52",
  388. show_name: "GLM-5.2",
  389. capabilities: ["model:glm-5.2"],
  390. total_units: 3_000_000,
  391. remaining_units: 2_500_000,
  392. expires_at: 1_780_506_000,
  393. },
  394. {
  395. plan_id: "start-plan-expired",
  396. entitlement_id: "expired-glm-52",
  397. show_name: "GLM-5.2",
  398. capabilities: ["model:glm-5.2"],
  399. total_units: 900_000,
  400. remaining_units: 800_000,
  401. expires_at: 1_780_506_000,
  402. },
  403. ],
  404. },
  405. }),
  406. ),
  407. };
  408. const provider = createProviderForTest({
  409. apiClient,
  410. modelProviderService: {
  411. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  412. } as LegacyModelProviderReader,
  413. credentialService: {
  414. load: vi.fn(async () => "credential-zcode-jwt"),
  415. },
  416. });
  417. const snapshot = await provider.getSnapshotForRequest({
  418. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  419. requirePreferredProvider: true,
  420. });
  421. expect(snapshot.subscription?.details).toMatchObject([{ productId: "start-plan-welcome" }]);
  422. expect(snapshot.quota?.limits).toMatchObject([
  423. { type: "welcome-glm-52", planId: "start-plan-welcome" },
  424. ]);
  425. });
  426. it("Z.ai Start Plan 乱序穿插非active套餐时保持服务端相对顺序", async () => {
  427. const apiClient: ApiClient = {
  428. request: vi.fn(async () =>
  429. createJsonResponse({
  430. code: 0,
  431. msg: "ok",
  432. data: {
  433. plans: [
  434. {
  435. plan_id: "start-plan-expired-a",
  436. name: "Expired A",
  437. status: "expired",
  438. ends_at: 1,
  439. },
  440. {
  441. plan_id: "start-plan-active-1",
  442. name: "Active One",
  443. status: "active",
  444. ends_at: 1_781_500_800,
  445. },
  446. {
  447. plan_id: "start-plan-expired-b",
  448. name: "Expired B",
  449. status: "cancelled",
  450. ends_at: 1,
  451. },
  452. {
  453. plan_id: "start-plan-active-2",
  454. name: "Active Two",
  455. status: "active",
  456. ends_at: 1_782_105_600,
  457. },
  458. ],
  459. balances: [
  460. {
  461. plan_id: "start-plan-active-1",
  462. entitlement_id: "active-1-glm-52",
  463. show_name: "GLM-5.2",
  464. capabilities: ["model:glm-5.2"],
  465. total_units: 3_000_000,
  466. remaining_units: 2_500_000,
  467. expires_at: 1_780_506_000,
  468. },
  469. {
  470. plan_id: "start-plan-active-2",
  471. entitlement_id: "active-2-glm-5-turbo",
  472. show_name: "GLM-5-Turbo",
  473. capabilities: ["model:glm-5-turbo"],
  474. total_units: 1_000_000,
  475. remaining_units: 750_000,
  476. expires_at: 1_781_110_800,
  477. },
  478. ],
  479. },
  480. }),
  481. ),
  482. };
  483. const provider = createProviderForTest({
  484. apiClient,
  485. modelProviderService: {
  486. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  487. } as LegacyModelProviderReader,
  488. credentialService: {
  489. load: vi.fn(async () => "credential-zcode-jwt"),
  490. },
  491. });
  492. const snapshot = await provider.getSnapshotForRequest({
  493. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  494. requirePreferredProvider: true,
  495. });
  496. expect(snapshot.subscription?.details?.map((detail) => detail.productId)).toEqual([
  497. "start-plan-active-1",
  498. "start-plan-active-2",
  499. ]);
  500. });
  501. it("Z.ai Start Plan 桶缺失 expires_at 时 nextResetTime 为 undefined 且不抛错", async () => {
  502. const apiClient: ApiClient = {
  503. request: vi.fn(async () =>
  504. createJsonResponse({
  505. code: 0,
  506. msg: "ok",
  507. data: {
  508. plans: [
  509. {
  510. plan_id: "zcode-v3-start-plan",
  511. name: "ZCode V3 Start Plan",
  512. status: "active",
  513. ends_at: 1_781_500_800,
  514. },
  515. ],
  516. balances: [
  517. {
  518. plan_id: "zcode-v3-start-plan",
  519. entitlement_id: "ent_zcode_v3_glm_52",
  520. show_name: "GLM-5.2",
  521. capabilities: ["model:glm-5.2"],
  522. total_units: 3_000_000,
  523. remaining_units: 2_500_000,
  524. // 服务端契约保证 expires_at 存在;缺失时桶刷新时间退化为 undefined,
  525. // 快照构建不能抛错。
  526. },
  527. ],
  528. },
  529. }),
  530. ),
  531. };
  532. const provider = createProviderForTest({
  533. apiClient,
  534. modelProviderService: {
  535. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  536. } as LegacyModelProviderReader,
  537. credentialService: {
  538. load: vi.fn(async () => "credential-zcode-jwt"),
  539. },
  540. });
  541. const snapshot = await provider.getSnapshotForRequest({
  542. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  543. requirePreferredProvider: true,
  544. });
  545. expect(snapshot.quota?.limits).toMatchObject([
  546. {
  547. type: "ent_zcode_v3_glm_52",
  548. remaining: 2_500_000,
  549. nextResetTime: undefined,
  550. },
  551. ]);
  552. expect(snapshot.remaining).toMatchObject({ count: 2_500_000 });
  553. });
  554. it("Z.ai Start Plan 余额展示优先使用 remaining_units 而不是 available_units", async () => {
  555. const apiClient: ApiClient = {
  556. request: vi.fn(async (input) => {
  557. const url = input.toString();
  558. expect(url).toContain("/billing/balance");
  559. return createJsonResponse({
  560. code: 0,
  561. msg: "ok",
  562. data: {
  563. plans: [
  564. {
  565. plan_id: "zcode-v3-start-plan",
  566. name: "ZCode V3 Start Plan",
  567. status: "active",
  568. },
  569. ],
  570. balances: [
  571. {
  572. entitlement_id: "ent_zcode_v3_glm_52",
  573. show_name: "GLM-5.2",
  574. capabilities: ["model:glm-5.2"],
  575. total_units: 3_000_000,
  576. used_units: 266_000,
  577. reserved_units: 1_775_000,
  578. remaining_units: 2_734_000,
  579. available_units: 959_000,
  580. expires_at: 1_780_502_400,
  581. },
  582. ],
  583. },
  584. });
  585. }),
  586. };
  587. const provider = createProviderForTest({
  588. apiClient,
  589. modelProviderService: {
  590. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  591. } as LegacyModelProviderReader,
  592. credentialService: {
  593. load: vi.fn(async (key: string) =>
  594. key === "zcodejwttoken" ? "credential-zcode-jwt" : null,
  595. ),
  596. },
  597. });
  598. const snapshot = await provider.getSnapshotForRequest({
  599. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  600. requirePreferredProvider: true,
  601. });
  602. expect(snapshot.quota?.limits[0]).toMatchObject({
  603. number: 3_000_000,
  604. usage: 266_000,
  605. remaining: 2_734_000,
  606. percentage: 2_734_000 / 3_000_000,
  607. });
  608. expect(snapshot.remaining).toMatchObject({
  609. count: 2_734_000,
  610. percentage: 2_734_000 / 3_000_000,
  611. });
  612. });
  613. it("Z.ai Start Plan 只请求一次 billing/balance 并从 plans 判定套餐", async () => {
  614. const balanceUrl = `https://zcode.z.ai/api/v1/zcode-plan/billing/balance?app_version=${ZCODE_VERSION}`;
  615. const requestOrder: string[] = [];
  616. const apiClient: ApiClient = {
  617. request: vi.fn(async (input) => {
  618. const url = input.toString();
  619. expect(url).toBe(balanceUrl);
  620. requestOrder.push("balance");
  621. return createJsonResponse({
  622. code: 0,
  623. msg: "ok",
  624. data: {
  625. plans: [
  626. {
  627. plan_id: "zcode-v3-start-plan",
  628. name: "ZCode V3 Start Plan",
  629. status: "active",
  630. starts_at: 1_787_900_000,
  631. entitlements: [
  632. {
  633. entitlement_id: "ent_zcode_v3_glm_52",
  634. show_name: "GLM-5.2",
  635. period: "one_time",
  636. effective_at: 1_788_000_000,
  637. },
  638. ],
  639. },
  640. ],
  641. balances: [
  642. {
  643. entitlement_id: "ent_zcode_v3_glm_52",
  644. show_name: "GLM-5.2",
  645. capabilities: ["model:glm-5.2"],
  646. total_units: 100,
  647. used_units: 25,
  648. remaining_units: 75,
  649. },
  650. ],
  651. },
  652. });
  653. }),
  654. };
  655. const provider = createProviderForTest({
  656. apiClient,
  657. modelProviderService: {
  658. getAllCached: vi.fn(async () => [createZaiStartPlanProvider()]),
  659. } as LegacyModelProviderReader,
  660. credentialService: {
  661. load: vi.fn(async (key: string) =>
  662. key === "zcodejwttoken" ? "credential-zcode-jwt" : null,
  663. ),
  664. },
  665. });
  666. const snapshot = await provider.getSnapshotForRequest({
  667. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  668. requirePreferredProvider: true,
  669. });
  670. expect(requestOrder).toEqual(["balance"]);
  671. expect(apiClient.request).toHaveBeenCalledTimes(1);
  672. expect(snapshot.quota?.limits[0]).toMatchObject({
  673. type: "ent_zcode_v3_glm_52",
  674. remaining: 75,
  675. });
  676. expect(snapshot.subscription?.details[0]?.entitlements).toEqual([
  677. {
  678. entitlementId: "ent_zcode_v3_glm_52",
  679. showName: "GLM-5.2",
  680. effectiveTime: new Date(1_788_000_000 * 1_000).toISOString(),
  681. },
  682. ]);
  683. });
  684. it("Z.ai Start Plan 缺少 zcodejwttoken 时不调用远端状态接口", async () => {
  685. const apiClient: ApiClient = {
  686. request: vi.fn(async () =>
  687. createJsonResponse({
  688. code: 0,
  689. data: { plans: [] },
  690. }),
  691. ),
  692. };
  693. const provider = createProviderForTest({
  694. apiClient,
  695. modelProviderService: {
  696. getAllCached: vi.fn(async () => [
  697. {
  698. ...createZaiStartPlanProvider(),
  699. apiKey: "",
  700. },
  701. ]),
  702. } as LegacyModelProviderReader,
  703. credentialService: {
  704. load: vi.fn(async () => null),
  705. },
  706. });
  707. const snapshot = await provider.getSnapshotForRequest({
  708. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  709. requirePreferredProvider: true,
  710. });
  711. expect(apiClient.request).not.toHaveBeenCalled();
  712. expect(snapshot.unavailableReason).toBe("not_configured");
  713. expect(snapshot.provider).toBeNull();
  714. });
  715. it("BigModel Start Plan 使用 OAuth callback 已落盘的 zcode JWT 读取当前套餐", async () => {
  716. const requestHeaders: Array<HeadersInit | undefined> = [];
  717. const apiClient: ApiClient = {
  718. request: vi.fn(async (input, init) => {
  719. const url = input.toString();
  720. requestHeaders.push(init?.headers);
  721. expect(url).toContain("/billing/balance");
  722. return createJsonResponse({
  723. code: 0,
  724. msg: "ok",
  725. data: {
  726. plans: [
  727. {
  728. plan_id: "zcode-v3-start-plan",
  729. name: "ZCode V3 Start Plan",
  730. status: "active",
  731. starts_at: 1_780_291_200,
  732. ends_at: 1_781_500_800,
  733. },
  734. ],
  735. balances: [
  736. {
  737. entitlement_id: "ent_bigmodel_glm_52",
  738. show_name: "GLM-5.2",
  739. capabilities: ["model:glm-5.2"],
  740. total_units: 100,
  741. used_units: 25,
  742. remaining_units: 75,
  743. expires_at: 1_780_502_400,
  744. },
  745. {
  746. entitlement_id: "ent_bigmodel_glm_5turbo",
  747. show_name: "GLM-5-Turbo",
  748. capabilities: ["model:glm-5-turbo"],
  749. total_units: 50,
  750. used_units: 0,
  751. remaining_units: 50,
  752. expires_at: 1_780_502_400,
  753. },
  754. ],
  755. },
  756. });
  757. }),
  758. };
  759. const provider = createProviderForTest({
  760. apiClient,
  761. modelProviderService: {
  762. getAllCached: vi.fn(async () => [
  763. {
  764. ...createZaiStartPlanProvider(),
  765. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  766. name: "BigModel- Coding Plan",
  767. apiKey: "stale-bigmodel-token",
  768. },
  769. ]),
  770. } as LegacyModelProviderReader,
  771. credentialService: {
  772. load: vi.fn(async (key: string) =>
  773. key === "oauth:active_provider"
  774. ? BIGMODEL_PROVIDER_ID
  775. : key === "zcodejwttoken"
  776. ? "bigmodel-zcode-jwt"
  777. : null,
  778. ),
  779. },
  780. });
  781. const snapshot = await provider.getSnapshotForRequest({
  782. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  783. requirePreferredProvider: true,
  784. });
  785. expect(requestHeaders).toEqual([
  786. expect.objectContaining({ Authorization: "Bearer bigmodel-zcode-jwt" }),
  787. ]);
  788. expect(apiClient.request).toHaveBeenCalledTimes(1);
  789. expect(apiClient.request).not.toHaveBeenCalledWith(
  790. "https://zcode.z.ai/api/v1/oauth/token",
  791. expect.anything(),
  792. );
  793. expect(snapshot.provider).toMatchObject({
  794. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  795. name: "BigModel - Coding Plan",
  796. });
  797. expect(snapshot.quota?.limits[0]).toMatchObject({
  798. type: "ent_bigmodel_glm_52",
  799. remaining: 75,
  800. usageDetails: [{ modelCode: "glm-5.2", displayName: "GLM-5.2", usage: 25 }],
  801. });
  802. expect(snapshot.quota?.limits[1]).toMatchObject({
  803. type: "ent_bigmodel_glm_5turbo",
  804. remaining: 50,
  805. usageDetails: [{ modelCode: "glm-5-turbo", displayName: "GLM-5-Turbo", usage: 0 }],
  806. });
  807. });
  808. it("自动续费套餐用订阅列表的 nextRenewTime 推导续费时间", async () => {
  809. const requestUrls: string[] = [];
  810. const apiClient: ApiClient = {
  811. request: vi.fn(async (input, init) => {
  812. const url = input.toString();
  813. requestUrls.push(url);
  814. if (url.endsWith("/api/monitor/usage/quota/limit")) {
  815. expect(init?.headers).toMatchObject({
  816. authorization: "bigmodel-api-key",
  817. });
  818. return createJsonResponse({
  819. code: 200,
  820. data: {
  821. level: "pro",
  822. limits: [
  823. {
  824. type: "TIME_LIMIT",
  825. remaining: 5,
  826. percentage: 10,
  827. nextResetTime: Date.UTC(2026, 4, 26),
  828. },
  829. ],
  830. },
  831. });
  832. }
  833. expect(url).toBe("https://bigmodel.cn/api/biz/subscription/list");
  834. expect(init?.headers).toMatchObject({
  835. Authorization: "bigmodel-api-key",
  836. });
  837. return createJsonResponse({
  838. code: 200,
  839. data: [
  840. {
  841. productId: "product-pro-quarter",
  842. productName: "GLM Coding Pro",
  843. status: "VALID",
  844. inCurrentPeriod: true,
  845. autoRenew: 1,
  846. billingCycle: "monthly",
  847. nextRenewTime: "2026-06-26",
  848. valid: "2026-06-26 10:00:00-2026-09-26 10:00:00",
  849. },
  850. {
  851. productId: "product-pro-month",
  852. productName: "GLM Coding Pro",
  853. status: "VALID",
  854. inCurrentPeriod: false,
  855. nextRenewTime: "2026-07-26",
  856. valid: "2026-06-26 10:00:00-2026-07-26 10:00:00",
  857. },
  858. ],
  859. });
  860. }),
  861. };
  862. const provider = createProviderForTest({
  863. apiClient,
  864. modelProviderService: {
  865. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  866. } as LegacyModelProviderReader,
  867. });
  868. const snapshot = await provider.getSnapshotForRequest({
  869. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  870. });
  871. expect(requestUrls).toEqual([
  872. "https://bigmodel.cn/api/biz/subscription/list",
  873. "https://bigmodel.cn/api/monitor/usage/quota/limit",
  874. ]);
  875. expect(snapshot.subscription?.details[0]).toMatchObject({
  876. productId: "product-pro-quarter",
  877. productName: "GLM Coding Pro",
  878. billingCycle: "monthly",
  879. renewTime: new Date("2026-06-26").toISOString(),
  880. expireTime: new Date("2026-09-26T10:00:00").toISOString(),
  881. });
  882. expect(snapshot.remaining?.nextResetTime).toBe(Date.UTC(2026, 4, 26));
  883. });
  884. it("缺少订阅时不会用 quota level 伪造商品和权益", async () => {
  885. const apiClient: ApiClient = {
  886. request: vi.fn(async (input) => {
  887. const url = input.toString();
  888. if (url.endsWith("/api/biz/subscription/list")) {
  889. return createJsonResponse({ code: 200, data: [] });
  890. }
  891. return createJsonResponse({
  892. code: 200,
  893. data: {
  894. level: "pro",
  895. limits: [
  896. {
  897. type: "TIME_LIMIT",
  898. remaining: 5,
  899. },
  900. ],
  901. },
  902. });
  903. }),
  904. };
  905. const provider = createProviderForTest({
  906. apiClient,
  907. modelProviderService: {
  908. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  909. } as LegacyModelProviderReader,
  910. });
  911. const snapshot = await provider.getSnapshotForRequest({
  912. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  913. });
  914. expect(snapshot.subscription).toBeNull();
  915. expect(snapshot.unavailableReason).toBe("no_plan");
  916. expect(snapshot.quota?.level).toBe("pro");
  917. });
  918. it("quota 业务失败时保留已读取的 Coding Plan 订阅快照", async () => {
  919. const apiClient: ApiClient = {
  920. request: vi.fn(async (input) => {
  921. const url = input.toString();
  922. if (url.endsWith("/api/biz/subscription/list")) {
  923. return createJsonResponse({
  924. code: 200,
  925. data: [
  926. {
  927. productId: "product-pro",
  928. productName: "GLM Coding Pro",
  929. status: "VALID",
  930. inCurrentPeriod: true,
  931. },
  932. ],
  933. });
  934. }
  935. return createJsonResponse({ code: 500, msg: "quota unavailable" });
  936. }),
  937. };
  938. const provider = createProviderForTest({
  939. apiClient,
  940. modelProviderService: {
  941. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  942. } as LegacyModelProviderReader,
  943. });
  944. const snapshot = await provider.getSnapshotForRequest({
  945. includeSubscription: true,
  946. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  947. });
  948. expect(snapshot).toMatchObject({
  949. provider: { id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan },
  950. subscription: {
  951. details: [{ productId: "product-pro", productName: "GLM Coding Pro" }],
  952. },
  953. quota: null,
  954. remaining: null,
  955. });
  956. expect(snapshot.unavailableReason).toBeUndefined();
  957. });
  958. it("ZCODE_ENV=test 时 BigModel Coding Plan quota 使用 bigmodel.cn", async () => {
  959. const requestUrls: string[] = [];
  960. const apiClient: ApiClient = {
  961. request: vi.fn(async (input) => {
  962. const url = input.toString();
  963. requestUrls.push(url);
  964. if (url.endsWith("/api/biz/subscription/list")) {
  965. return createJsonResponse({ code: 200, data: [] });
  966. }
  967. return createJsonResponse({
  968. code: 200,
  969. data: {
  970. level: "pro",
  971. limits: [],
  972. },
  973. });
  974. }),
  975. };
  976. const provider = createProviderForTest({
  977. apiClient,
  978. env: {
  979. ZCODE_ENV: "test",
  980. },
  981. modelProviderService: {
  982. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  983. } as LegacyModelProviderReader,
  984. });
  985. await provider.getSnapshotForRequest({
  986. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  987. });
  988. expect(requestUrls).toEqual([
  989. "https://bigmodel.cn/api/biz/subscription/list",
  990. "https://bigmodel.cn/api/monitor/usage/quota/limit",
  991. ]);
  992. });
  993. it("BigModel Team Plan 权益查询会携带组织和项目 header", async () => {
  994. const requestHeaders: Array<HeadersInit | undefined> = [];
  995. const requestUrls: string[] = [];
  996. const apiClient: ApiClient = {
  997. request: vi.fn(async (input, init) => {
  998. requestHeaders.push(init?.headers);
  999. const url = input.toString();
  1000. requestUrls.push(url);
  1001. if (url.endsWith("/api_keys")) {
  1002. return createJsonResponse({
  1003. code: 200,
  1004. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  1005. });
  1006. }
  1007. if (url.endsWith("/api_keys/copy/team-ak")) {
  1008. return createJsonResponse({
  1009. code: 200,
  1010. data: { secretKey: "team-secret" },
  1011. });
  1012. }
  1013. if (url.endsWith("/api/biz/team/subscribe/product/querySubscribeDetail")) {
  1014. return createJsonResponse({
  1015. code: 200,
  1016. data: {
  1017. hasSubscription: true,
  1018. status: "EFFECTIVE",
  1019. memberGrantStatus: "VALID",
  1020. productId: "team-max",
  1021. productName: "团队套餐",
  1022. },
  1023. });
  1024. }
  1025. expect(url).toBe("https://bigmodel.cn/api/monitor/usage/quota/limit?type=2");
  1026. return createJsonResponse({
  1027. code: 200,
  1028. data: {
  1029. level: "team",
  1030. limits: [],
  1031. },
  1032. });
  1033. }),
  1034. };
  1035. const provider = createProviderForTest({
  1036. apiClient,
  1037. modelProviderService: {
  1038. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1039. } as LegacyModelProviderReader,
  1040. credentialService: {
  1041. load: vi.fn(async (key) => (key === "oauth:bigmodel:access_token" ? "oauth-token" : null)),
  1042. },
  1043. });
  1044. await provider.getSnapshotForRequest({
  1045. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1046. organizationId: "org-team-a",
  1047. projectId: "proj-team-a",
  1048. });
  1049. expect(requestUrls.some((url) => url.includes("/api_keys"))).toBe(false);
  1050. expect(requestHeaders[0]).toMatchObject({
  1051. Authorization: "oauth-token",
  1052. "bigmodel-organization": "org-team-a",
  1053. "bigmodel-project": "proj-team-a",
  1054. });
  1055. expect(requestHeaders.slice(-2)).toEqual([
  1056. expect.objectContaining({
  1057. Authorization: "oauth-token",
  1058. "bigmodel-organization": "org-team-a",
  1059. "bigmodel-project": "proj-team-a",
  1060. }),
  1061. expect.objectContaining({
  1062. authorization: "team-ak.team-secret",
  1063. "bigmodel-organization": "org-team-a",
  1064. "bigmodel-project": "proj-team-a",
  1065. }),
  1066. ]);
  1067. expect(requestUrls).toEqual([
  1068. "https://bigmodel.cn/api/biz/team/subscribe/product/querySubscribeDetail",
  1069. "https://bigmodel.cn/api/monitor/usage/quota/limit?type=2",
  1070. ]);
  1071. });
  1072. it("BigModel Team Plan 的用量层不再创建项目 API Key", async () => {
  1073. const requestHeaders: Array<HeadersInit | undefined> = [];
  1074. const requestMethods: Array<string | undefined> = [];
  1075. const requestUrls: string[] = [];
  1076. const apiClient: ApiClient = {
  1077. request: vi.fn(async (input, init) => {
  1078. const url = input.toString();
  1079. requestHeaders.push(init?.headers);
  1080. requestMethods.push(init?.method);
  1081. requestUrls.push(url);
  1082. if (url.endsWith("/api_keys") && init?.method === "GET") {
  1083. return createJsonResponse({
  1084. code: 200,
  1085. data: [
  1086. {
  1087. apiKey: "wrong-type-ak",
  1088. keyType: 1,
  1089. name: "zcode-team-api-key",
  1090. },
  1091. { name: "zcode-api-key" },
  1092. ],
  1093. });
  1094. }
  1095. if (url.endsWith("/api_keys") && init?.method === "POST") {
  1096. expect(init.headers).toMatchObject({
  1097. "bigmodel-organization": "org-team-a",
  1098. "bigmodel-project": "proj-team-a",
  1099. });
  1100. expect(init.body).toBe(JSON.stringify({ name: "zcode-team-api-key", keyType: 2 }));
  1101. return createJsonResponse({
  1102. code: 200,
  1103. data: {
  1104. apiKey: "created-team-ak",
  1105. keyType: 2,
  1106. name: "zcode-team-api-key",
  1107. },
  1108. });
  1109. }
  1110. if (url.endsWith("/api_keys/copy/created-team-ak")) {
  1111. return createJsonResponse({
  1112. code: 200,
  1113. data: { secretKey: "created-team-secret" },
  1114. });
  1115. }
  1116. if (url.endsWith("/api/biz/team/subscribe/product/querySubscribeDetail")) {
  1117. return createJsonResponse({
  1118. code: 200,
  1119. data: {
  1120. hasSubscription: true,
  1121. status: "EFFECTIVE",
  1122. memberGrantStatus: "VALID",
  1123. productId: "team-max",
  1124. productName: "团队套餐",
  1125. },
  1126. });
  1127. }
  1128. if (url.endsWith("/api/monitor/usage/quota/limit?type=2")) {
  1129. return createJsonResponse({
  1130. code: 200,
  1131. data: {
  1132. level: "team",
  1133. limits: [],
  1134. },
  1135. });
  1136. }
  1137. throw new Error(`unexpected request: ${url}`);
  1138. }),
  1139. };
  1140. const provider = createProviderForTest({
  1141. apiClient,
  1142. modelProviderService: {
  1143. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1144. } as LegacyModelProviderReader,
  1145. credentialService: {
  1146. load: vi.fn(async (key) => (key === "oauth:bigmodel:access_token" ? "oauth-token" : null)),
  1147. },
  1148. });
  1149. const snapshot = await provider.getSnapshotForRequest({
  1150. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1151. organizationId: "org-team-a",
  1152. projectId: "proj-team-a",
  1153. });
  1154. expect(requestMethods).toEqual(["GET", "GET"]);
  1155. expect(requestUrls).toEqual([
  1156. "https://bigmodel.cn/api/biz/team/subscribe/product/querySubscribeDetail",
  1157. "https://bigmodel.cn/api/monitor/usage/quota/limit?type=2",
  1158. ]);
  1159. expect(requestHeaders.at(-1)).toMatchObject({
  1160. authorization: "team-ak.team-secret",
  1161. "bigmodel-organization": "org-team-a",
  1162. "bigmodel-project": "proj-team-a",
  1163. });
  1164. expect(snapshot).toMatchObject({
  1165. context: {
  1166. scope: "team",
  1167. organizationId: "org-team-a",
  1168. projectId: "proj-team-a",
  1169. },
  1170. provider: {
  1171. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1172. },
  1173. });
  1174. });
  1175. it("BigModel Team Plan quota 使用 type=2 且不回退企业余额", async () => {
  1176. const requestUrls: string[] = [];
  1177. const apiClient: ApiClient = {
  1178. request: vi.fn(async (input) => {
  1179. const url = input.toString();
  1180. requestUrls.push(url);
  1181. if (url.endsWith("/api_keys")) {
  1182. return createJsonResponse({
  1183. code: 200,
  1184. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  1185. });
  1186. }
  1187. if (url.endsWith("/api_keys/copy/team-ak")) {
  1188. return createJsonResponse({
  1189. code: 200,
  1190. data: { secretKey: "team-secret" },
  1191. });
  1192. }
  1193. if (url.endsWith("/api/biz/team/subscribe/product/querySubscribeDetail")) {
  1194. return createJsonResponse({
  1195. code: 200,
  1196. data: {
  1197. hasSubscription: true,
  1198. status: "EFFECTIVE",
  1199. memberGrantStatus: "VALID",
  1200. productId: "team-max",
  1201. productName: "团队套餐",
  1202. },
  1203. });
  1204. }
  1205. if (url === "https://bigmodel.cn/api/monitor/usage/quota/limit?type=2") {
  1206. return createJsonResponse({
  1207. code: 200,
  1208. data: {
  1209. level: "team",
  1210. limits: [
  1211. {
  1212. type: "TIME_LIMIT",
  1213. remaining: 1000,
  1214. currentValue: 0,
  1215. percentage: 0,
  1216. },
  1217. ],
  1218. },
  1219. });
  1220. }
  1221. return createJsonResponse({
  1222. code: 500,
  1223. success: false,
  1224. msg: "当前用户不存在coding plan",
  1225. });
  1226. }),
  1227. };
  1228. const provider = createProviderForTest({
  1229. apiClient,
  1230. modelProviderService: {
  1231. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1232. } as LegacyModelProviderReader,
  1233. credentialService: {
  1234. load: vi.fn(async (key) => (key === "oauth:bigmodel:access_token" ? "oauth-token" : null)),
  1235. },
  1236. });
  1237. const snapshot = await provider.getSnapshotForRequest({
  1238. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1239. organizationId: "org-team-a",
  1240. projectId: "proj-team-a",
  1241. });
  1242. expect(snapshot.unavailableReason).toBeUndefined();
  1243. expect(snapshot.quota?.limits[0]).toMatchObject({
  1244. type: "TIME_LIMIT",
  1245. remaining: 1000,
  1246. percentage: 0,
  1247. });
  1248. expect(
  1249. requestUrls.some((url) => url.endsWith("/api/biz/subscription/enterprise/v2/balance")),
  1250. ).toBe(false);
  1251. });
  1252. it("没有 Coding Plan apiKey 时不调用 quota 和套餐预览接口", async () => {
  1253. const apiClient: ApiClient = {
  1254. request: vi.fn(async () =>
  1255. createJsonResponse({
  1256. code: 200,
  1257. data: {
  1258. level: "pro",
  1259. limits: [
  1260. {
  1261. type: "TIME_LIMIT",
  1262. remaining: 5,
  1263. nextResetTime: Date.UTC(2026, 4, 26),
  1264. },
  1265. ],
  1266. },
  1267. }),
  1268. ),
  1269. };
  1270. const provider = createProviderForTest({
  1271. apiClient,
  1272. modelProviderService: {
  1273. getAllCached: vi.fn(async () => [
  1274. {
  1275. ...createBigModelCodingPlanProvider(),
  1276. apiKey: "",
  1277. },
  1278. ]),
  1279. } as LegacyModelProviderReader,
  1280. accountRequestAuthService: {
  1281. resolveAccessCurrent: vi.fn(async () => null),
  1282. resolveCurrent: vi.fn(async () => ({ apiKey: undefined })),
  1283. assertCurrent: vi.fn(async () => undefined),
  1284. },
  1285. });
  1286. const snapshot = await provider.getSnapshotForRequest({
  1287. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1288. requirePreferredProvider: true,
  1289. allowEnvApiKey: false,
  1290. });
  1291. expect(apiClient.request).not.toHaveBeenCalled();
  1292. expect(snapshot.unavailableReason).toBe("not_configured");
  1293. expect(snapshot.provider).toBeNull();
  1294. });
  1295. it("严格指定 Coding Plan 时不会回退到普通 API Key provider", async () => {
  1296. const apiClient: ApiClient = {
  1297. request: vi.fn(),
  1298. };
  1299. const provider = createProviderForTest({
  1300. apiClient,
  1301. modelProviderService: {
  1302. getAllCached: vi.fn(async () => [
  1303. {
  1304. ...createBigModelCodingPlanProvider(),
  1305. apiKey: "",
  1306. },
  1307. createBigModelApiKeyProvider(),
  1308. ]),
  1309. } as LegacyModelProviderReader,
  1310. });
  1311. const snapshot = await provider.getSnapshotForRequest({
  1312. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1313. requirePreferredProvider: true,
  1314. allowEnvApiKey: false,
  1315. });
  1316. expect(apiClient.request).not.toHaveBeenCalled();
  1317. expect(snapshot.unavailableReason).toBe("not_configured");
  1318. expect(snapshot.provider).toBeNull();
  1319. });
  1320. it("严格指定 Coding Plan 时不会被环境变量 usage key 覆盖", async () => {
  1321. const apiClient: ApiClient = {
  1322. request: vi.fn(async (_input, init) => {
  1323. if (String(_input).includes("subscription/list")) {
  1324. expect(init?.headers).toMatchObject({ Authorization: "bigmodel-api-key" });
  1325. return createJsonResponse({ code: 200, data: [] });
  1326. }
  1327. expect(init?.headers).toMatchObject({
  1328. authorization: "bigmodel-api-key",
  1329. });
  1330. return createJsonResponse({
  1331. code: 200,
  1332. data: {
  1333. level: "pro",
  1334. limits: [],
  1335. },
  1336. });
  1337. }),
  1338. };
  1339. const provider = createProviderForTest({
  1340. apiClient,
  1341. modelProviderService: {
  1342. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1343. } as LegacyModelProviderReader,
  1344. env: {
  1345. ZCODE_BIGMODEL_USAGE_API_KEY: "env-usage-key",
  1346. },
  1347. });
  1348. const snapshot = await provider.getSnapshotForRequest({
  1349. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1350. requirePreferredProvider: true,
  1351. includeSubscription: false,
  1352. });
  1353. expect(apiClient.request).toHaveBeenCalledTimes(2);
  1354. expect(snapshot.provider).toMatchObject({
  1355. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1356. });
  1357. });
  1358. it("Z.ai Coding Plan 用量权益直接使用 provider apiKey 请求 quota", async () => {
  1359. const requestUrls: string[] = [];
  1360. const apiClient: ApiClient = {
  1361. request: vi.fn(async (input, init) => {
  1362. const url = input.toString();
  1363. requestUrls.push(url);
  1364. if (url.includes("subscription/list")) {
  1365. expect(init?.headers).toMatchObject({ Authorization: "zai-api-key" });
  1366. return createJsonResponse({ code: 200, data: [] });
  1367. }
  1368. expect(url).toBe("https://api.z.ai/api/monitor/usage/quota/limit");
  1369. expect(init?.headers).toMatchObject({
  1370. authorization: "zai-api-key",
  1371. });
  1372. return createJsonResponse({
  1373. code: 200,
  1374. data: {
  1375. level: "pro",
  1376. limits: [],
  1377. },
  1378. });
  1379. }),
  1380. };
  1381. const provider = createProviderForTest({
  1382. apiClient,
  1383. modelProviderService: {
  1384. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1385. } as LegacyModelProviderReader,
  1386. });
  1387. const snapshot = await provider.getSnapshotForRequest({
  1388. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1389. requirePreferredProvider: true,
  1390. includeSubscription: false,
  1391. });
  1392. expect(requestUrls).toEqual([
  1393. "https://api.z.ai/api/biz/subscription/list",
  1394. "https://api.z.ai/api/monitor/usage/quota/limit",
  1395. ]);
  1396. expect(snapshot.provider).toMatchObject({
  1397. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1398. });
  1399. });
  1400. it("Z.ai Coding Plan 团队授权不可用时不会回退个人 key 发送 team quota header", async () => {
  1401. const requestHeaders: Array<HeadersInit | undefined> = [];
  1402. const apiClient: ApiClient = {
  1403. request: vi.fn(async (_input, init) => {
  1404. requestHeaders.push(init?.headers);
  1405. return createJsonResponse({
  1406. code: 200,
  1407. data: {
  1408. level: "pro",
  1409. limits: [],
  1410. },
  1411. });
  1412. }),
  1413. };
  1414. const provider = createProviderForTest({
  1415. apiClient,
  1416. modelProviderService: {
  1417. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1418. } as LegacyModelProviderReader,
  1419. accountRequestAuthService: {
  1420. resolveAccessCurrent: vi.fn(async () => null),
  1421. resolveCurrent: vi.fn(async () => ({ apiKey: undefined })),
  1422. assertCurrent: vi.fn(async () => undefined),
  1423. },
  1424. });
  1425. await expect(
  1426. provider.getSnapshotForRequest({
  1427. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1428. requirePreferredProvider: true,
  1429. includeSubscription: false,
  1430. organizationId: "org-should-ignore",
  1431. projectId: "proj-should-ignore",
  1432. }),
  1433. ).rejects.toThrow("Coding Plan entitlement refresh failed");
  1434. // 修复原因:误传 team context 时不能把个人 Z.ai Coding Plan key 和 team header 混用。
  1435. // 团队业务登录态和调用 Key 均缺失时权益未知,不能回退个人 Key。
  1436. expect(requestHeaders).toEqual([]);
  1437. });
  1438. it("Z.ai Coding Plan 用 provider apiKey 读取订阅状态和到期时间", async () => {
  1439. const requestUrls: string[] = [];
  1440. const apiClient: ApiClient = {
  1441. request: vi.fn(async (input, init) => {
  1442. const url = input.toString();
  1443. requestUrls.push(url);
  1444. if (url.endsWith("/api/monitor/usage/quota/limit")) {
  1445. expect(init?.headers).toMatchObject({
  1446. authorization: "zai-api-key",
  1447. });
  1448. return createJsonResponse({
  1449. code: 200,
  1450. data: {
  1451. level: "pro",
  1452. limits: [],
  1453. },
  1454. });
  1455. }
  1456. expect(url).toBe("https://api.z.ai/api/biz/subscription/list");
  1457. expect(init?.headers).toMatchObject({
  1458. Authorization: "zai-api-key",
  1459. });
  1460. return createJsonResponse({
  1461. code: 200,
  1462. data: [
  1463. {
  1464. productId: "product-zai-pro-quarter",
  1465. productName: "GLM Coding Pro",
  1466. status: "VALID",
  1467. inCurrentPeriod: true,
  1468. billingCycle: "quarterly",
  1469. nextRenewTime: "2026-07-10",
  1470. valid: "2026-04-10 16:32:00-2026-07-10 10:00:00",
  1471. },
  1472. ],
  1473. });
  1474. }),
  1475. };
  1476. const provider = createProviderForTest({
  1477. apiClient,
  1478. modelProviderService: {
  1479. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1480. } as LegacyModelProviderReader,
  1481. });
  1482. const snapshot = await provider.getSnapshotForRequest({
  1483. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1484. requirePreferredProvider: true,
  1485. });
  1486. expect(requestUrls).toEqual([
  1487. "https://api.z.ai/api/biz/subscription/list",
  1488. "https://api.z.ai/api/monitor/usage/quota/limit",
  1489. ]);
  1490. expect(snapshot.subscription?.details[0]).toMatchObject({
  1491. productId: "product-zai-pro-quarter",
  1492. productName: "GLM Coding Pro",
  1493. billingCycle: "quarterly",
  1494. renewTime: null,
  1495. expireTime: new Date("2026-07-10").toISOString(),
  1496. });
  1497. });
  1498. it("Z.ai Coding Plan quota 失败时仍用订阅列表判断已购买状态", async () => {
  1499. const requestUrls: string[] = [];
  1500. const apiClient: ApiClient = {
  1501. request: vi.fn(async (input, init) => {
  1502. const url = input.toString();
  1503. requestUrls.push(url);
  1504. if (url.endsWith("/api/biz/subscription/list")) {
  1505. expect(init?.headers).toMatchObject({
  1506. Authorization: "zai-api-key",
  1507. });
  1508. return createJsonResponse({
  1509. code: 200,
  1510. data: [
  1511. {
  1512. productId: "product-zai-pro-quarter",
  1513. productName: "GLM Coding Pro",
  1514. status: "VALID",
  1515. inCurrentPeriod: true,
  1516. billingCycle: "quarterly",
  1517. nextRenewTime: "2026-07-10",
  1518. },
  1519. ],
  1520. });
  1521. }
  1522. expect(url).toBe("https://api.z.ai/api/monitor/usage/quota/limit");
  1523. expect(init?.headers).toMatchObject({
  1524. authorization: "zai-api-key",
  1525. });
  1526. return createJsonResponse({
  1527. code: 401,
  1528. msg: "token expired or incorrect",
  1529. success: false,
  1530. });
  1531. }),
  1532. };
  1533. const provider = createProviderForTest({
  1534. apiClient,
  1535. modelProviderService: {
  1536. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1537. } as LegacyModelProviderReader,
  1538. });
  1539. const snapshot = await provider.getSnapshotForRequest({
  1540. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1541. requirePreferredProvider: true,
  1542. });
  1543. expect(requestUrls).toEqual([
  1544. "https://api.z.ai/api/biz/subscription/list",
  1545. "https://api.z.ai/api/monitor/usage/quota/limit",
  1546. ]);
  1547. expect(snapshot.unavailableReason).toBeUndefined();
  1548. expect(snapshot.subscription?.details[0]).toMatchObject({
  1549. productId: "product-zai-pro-quarter",
  1550. productName: "GLM Coding Pro",
  1551. billingCycle: "quarterly",
  1552. renewTime: null,
  1553. expireTime: new Date("2026-07-10").toISOString(),
  1554. });
  1555. expect(snapshot.quota).toBeNull();
  1556. });
  1557. it("Z.ai Coding Plan 订阅列表有效时不被 quota no_plan 覆盖", async () => {
  1558. const apiClient: ApiClient = {
  1559. request: vi.fn(async (input, init) => {
  1560. const url = input.toString();
  1561. if (url.endsWith("/api/biz/subscription/list")) {
  1562. expect(init?.headers).toMatchObject({
  1563. Authorization: "zai-api-key",
  1564. });
  1565. return createJsonResponse({
  1566. code: 200,
  1567. data: [
  1568. {
  1569. productId: "product-zai-pro-monthly",
  1570. productName: "GLM Coding Pro",
  1571. status: "VALID",
  1572. inCurrentPeriod: true,
  1573. billingCycle: "monthly",
  1574. nextRenewTime: "2026-07-10",
  1575. },
  1576. ],
  1577. });
  1578. }
  1579. expect(url).toBe("https://api.z.ai/api/monitor/usage/quota/limit");
  1580. expect(init?.headers).toMatchObject({
  1581. authorization: "zai-api-key",
  1582. });
  1583. return createJsonResponse({
  1584. code: 500,
  1585. msg: "不存在coding plan",
  1586. success: false,
  1587. });
  1588. }),
  1589. };
  1590. const provider = createProviderForTest({
  1591. apiClient,
  1592. modelProviderService: {
  1593. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1594. } as LegacyModelProviderReader,
  1595. });
  1596. const snapshot = await provider.getSnapshotForRequest({
  1597. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1598. requirePreferredProvider: true,
  1599. });
  1600. expect(snapshot.unavailableReason).toBeUndefined();
  1601. expect(snapshot.subscription?.details[0]).toMatchObject({
  1602. productId: "product-zai-pro-monthly",
  1603. productName: "GLM Coding Pro",
  1604. });
  1605. expect(snapshot.quota).toBeNull();
  1606. });
  1607. it("Z.ai Coding Plan token 失效时返回同步失败而不是未开通", async () => {
  1608. const apiClient: ApiClient = {
  1609. request: vi.fn(async (input, init) => {
  1610. expect(input.toString()).toBe("https://api.z.ai/api/biz/subscription/list");
  1611. expect(init?.headers).toMatchObject({ Authorization: "zai-api-key" });
  1612. return createJsonResponse({
  1613. code: 401,
  1614. msg: "token expired or incorrect",
  1615. success: false,
  1616. });
  1617. }),
  1618. };
  1619. const provider = createProviderForTest({
  1620. apiClient,
  1621. modelProviderService: {
  1622. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1623. } as LegacyModelProviderReader,
  1624. });
  1625. await expect(
  1626. provider.getSnapshotForRequest({
  1627. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1628. requirePreferredProvider: true,
  1629. includeSubscription: false,
  1630. }),
  1631. ).rejects.toThrow("Coding Plan entitlement refresh failed");
  1632. });
  1633. it("Z.ai Coding Plan provider 未同步时不会回退 OAuth token 查询权益", async () => {
  1634. const apiClient: ApiClient = {
  1635. request: vi.fn(),
  1636. };
  1637. const provider = createProviderForTest({
  1638. apiClient,
  1639. modelProviderService: {
  1640. getAllCached: vi.fn(async () => []),
  1641. } as LegacyModelProviderReader,
  1642. credentialService: {
  1643. load: vi.fn(async () => "zai-oauth-token"),
  1644. },
  1645. });
  1646. const snapshot = await provider.getSnapshotForRequest({
  1647. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1648. requirePreferredProvider: true,
  1649. includeSubscription: false,
  1650. });
  1651. expect(apiClient.request).not.toHaveBeenCalled();
  1652. expect(snapshot.unavailableReason).toBe("not_configured");
  1653. expect(snapshot.provider).toBeNull();
  1654. });
  1655. it("Z.ai Coding Plan 空 apiKey 时按未配置权益处理且不回退 OAuth token", async () => {
  1656. const apiClient: ApiClient = {
  1657. request: vi.fn(),
  1658. };
  1659. const provider = createProviderForTest({
  1660. apiClient,
  1661. modelProviderService: {
  1662. getAllCached: vi.fn(async () => [
  1663. {
  1664. ...createZaiCodingPlanProvider(),
  1665. apiKey: "",
  1666. },
  1667. ]),
  1668. } as LegacyModelProviderReader,
  1669. credentialService: {
  1670. load: vi.fn(async () => "zai-oauth-token"),
  1671. },
  1672. });
  1673. const snapshot = await provider.getSnapshotForRequest({
  1674. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1675. requirePreferredProvider: true,
  1676. includeSubscription: false,
  1677. });
  1678. expect(apiClient.request).not.toHaveBeenCalled();
  1679. expect(snapshot.unavailableReason).toBe("not_configured");
  1680. expect(snapshot.provider).toBeNull();
  1681. });
  1682. });