bigmodelUsageQuotaProvider.test.ts 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  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 requestUrls: string[] = [];
  1075. const apiClient: ApiClient = {
  1076. request: vi.fn(async (input, init) => {
  1077. requestHeaders.push(init?.headers);
  1078. const url = input.toString();
  1079. requestUrls.push(url);
  1080. if (url.endsWith("/api_keys")) {
  1081. return createJsonResponse({
  1082. code: 200,
  1083. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  1084. });
  1085. }
  1086. if (url.endsWith("/api_keys/copy/team-ak")) {
  1087. return createJsonResponse({
  1088. code: 200,
  1089. data: { secretKey: "team-secret" },
  1090. });
  1091. }
  1092. if (url.endsWith("/api/biz/team/subscribe/product/querySubscribeDetail")) {
  1093. return createJsonResponse({
  1094. code: 200,
  1095. data: {
  1096. hasSubscription: true,
  1097. status: "EFFECTIVE",
  1098. memberGrantStatus: "VALID",
  1099. productId: "team-max",
  1100. productName: "团队套餐",
  1101. },
  1102. });
  1103. }
  1104. return createJsonResponse({
  1105. code: 200,
  1106. data: {
  1107. level: "team",
  1108. limits: [],
  1109. },
  1110. });
  1111. }),
  1112. };
  1113. const provider = createProviderForTest({
  1114. apiClient,
  1115. modelProviderService: {
  1116. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1117. } as LegacyModelProviderReader,
  1118. credentialService: {
  1119. load: vi.fn(async (key) => (key === "oauth:bigmodel:access_token" ? "oauth-token" : null)),
  1120. },
  1121. });
  1122. await provider.getSnapshotForRequest({
  1123. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1124. organizationId: "org-team-a",
  1125. projectId: "proj-team-a",
  1126. });
  1127. expect(requestHeaders.at(-1)).toMatchObject({
  1128. authorization: "team-ak.team-secret",
  1129. "bigmodel-organization": "org-team-a",
  1130. "bigmodel-project": "proj-team-a",
  1131. });
  1132. expect(requestUrls.at(-1)).toBe("https://bigmodel.cn/api/monitor/usage/quota/limit?type=2");
  1133. });
  1134. it("BigModel Team Plan 的用量层不再创建项目 API Key", async () => {
  1135. const requestHeaders: Array<HeadersInit | undefined> = [];
  1136. const requestMethods: Array<string | undefined> = [];
  1137. const requestUrls: string[] = [];
  1138. const apiClient: ApiClient = {
  1139. request: vi.fn(async (input, init) => {
  1140. const url = input.toString();
  1141. requestHeaders.push(init?.headers);
  1142. requestMethods.push(init?.method);
  1143. requestUrls.push(url);
  1144. if (url.endsWith("/api_keys") && init?.method === "GET") {
  1145. return createJsonResponse({
  1146. code: 200,
  1147. data: [
  1148. {
  1149. apiKey: "wrong-type-ak",
  1150. keyType: 1,
  1151. name: "zcode-team-api-key",
  1152. },
  1153. { name: "zcode-api-key" },
  1154. ],
  1155. });
  1156. }
  1157. if (url.endsWith("/api_keys") && init?.method === "POST") {
  1158. expect(init.headers).toMatchObject({
  1159. "bigmodel-organization": "org-team-a",
  1160. "bigmodel-project": "proj-team-a",
  1161. });
  1162. expect(init.body).toBe(JSON.stringify({ name: "zcode-team-api-key", keyType: 2 }));
  1163. return createJsonResponse({
  1164. code: 200,
  1165. data: {
  1166. apiKey: "created-team-ak",
  1167. keyType: 2,
  1168. name: "zcode-team-api-key",
  1169. },
  1170. });
  1171. }
  1172. if (url.endsWith("/api_keys/copy/created-team-ak")) {
  1173. return createJsonResponse({
  1174. code: 200,
  1175. data: { secretKey: "created-team-secret" },
  1176. });
  1177. }
  1178. if (url.endsWith("/api/biz/team/subscribe/product/querySubscribeDetail")) {
  1179. return createJsonResponse({
  1180. code: 200,
  1181. data: {
  1182. hasSubscription: true,
  1183. status: "EFFECTIVE",
  1184. memberGrantStatus: "VALID",
  1185. productId: "team-max",
  1186. productName: "团队套餐",
  1187. },
  1188. });
  1189. }
  1190. if (url.endsWith("/api/monitor/usage/quota/limit?type=2")) {
  1191. return createJsonResponse({
  1192. code: 200,
  1193. data: {
  1194. level: "team",
  1195. limits: [],
  1196. },
  1197. });
  1198. }
  1199. throw new Error(`unexpected request: ${url}`);
  1200. }),
  1201. };
  1202. const provider = createProviderForTest({
  1203. apiClient,
  1204. modelProviderService: {
  1205. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1206. } as LegacyModelProviderReader,
  1207. credentialService: {
  1208. load: vi.fn(async (key) => (key === "oauth:bigmodel:access_token" ? "oauth-token" : null)),
  1209. },
  1210. });
  1211. const snapshot = await provider.getSnapshotForRequest({
  1212. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1213. organizationId: "org-team-a",
  1214. projectId: "proj-team-a",
  1215. });
  1216. expect(requestMethods).toEqual(["GET", "GET"]);
  1217. expect(requestUrls).toEqual([
  1218. "https://bigmodel.cn/api/biz/team/subscribe/product/querySubscribeDetail",
  1219. "https://bigmodel.cn/api/monitor/usage/quota/limit?type=2",
  1220. ]);
  1221. expect(requestHeaders.at(-1)).toMatchObject({
  1222. authorization: "team-ak.team-secret",
  1223. "bigmodel-organization": "org-team-a",
  1224. "bigmodel-project": "proj-team-a",
  1225. });
  1226. expect(snapshot).toMatchObject({
  1227. context: {
  1228. scope: "team",
  1229. organizationId: "org-team-a",
  1230. projectId: "proj-team-a",
  1231. },
  1232. provider: {
  1233. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1234. },
  1235. });
  1236. });
  1237. it("BigModel Team Plan quota 使用 type=2 且不回退企业余额", async () => {
  1238. const requestUrls: string[] = [];
  1239. const apiClient: ApiClient = {
  1240. request: vi.fn(async (input) => {
  1241. const url = input.toString();
  1242. requestUrls.push(url);
  1243. if (url.endsWith("/api_keys")) {
  1244. return createJsonResponse({
  1245. code: 200,
  1246. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  1247. });
  1248. }
  1249. if (url.endsWith("/api_keys/copy/team-ak")) {
  1250. return createJsonResponse({
  1251. code: 200,
  1252. data: { secretKey: "team-secret" },
  1253. });
  1254. }
  1255. if (url.endsWith("/api/biz/team/subscribe/product/querySubscribeDetail")) {
  1256. return createJsonResponse({
  1257. code: 200,
  1258. data: {
  1259. hasSubscription: true,
  1260. status: "EFFECTIVE",
  1261. memberGrantStatus: "VALID",
  1262. productId: "team-max",
  1263. productName: "团队套餐",
  1264. },
  1265. });
  1266. }
  1267. if (url === "https://bigmodel.cn/api/monitor/usage/quota/limit?type=2") {
  1268. return createJsonResponse({
  1269. code: 200,
  1270. data: {
  1271. level: "team",
  1272. limits: [
  1273. {
  1274. type: "TIME_LIMIT",
  1275. remaining: 1000,
  1276. currentValue: 0,
  1277. percentage: 0,
  1278. },
  1279. ],
  1280. },
  1281. });
  1282. }
  1283. return createJsonResponse({
  1284. code: 500,
  1285. success: false,
  1286. msg: "当前用户不存在coding plan",
  1287. });
  1288. }),
  1289. };
  1290. const provider = createProviderForTest({
  1291. apiClient,
  1292. modelProviderService: {
  1293. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1294. } as LegacyModelProviderReader,
  1295. credentialService: {
  1296. load: vi.fn(async (key) => (key === "oauth:bigmodel:access_token" ? "oauth-token" : null)),
  1297. },
  1298. });
  1299. const snapshot = await provider.getSnapshotForRequest({
  1300. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1301. organizationId: "org-team-a",
  1302. projectId: "proj-team-a",
  1303. });
  1304. expect(snapshot.unavailableReason).toBeUndefined();
  1305. expect(snapshot.quota?.limits[0]).toMatchObject({
  1306. type: "TIME_LIMIT",
  1307. remaining: 1000,
  1308. percentage: 0,
  1309. });
  1310. expect(
  1311. requestUrls.some((url) => url.endsWith("/api/biz/subscription/enterprise/v2/balance")),
  1312. ).toBe(false);
  1313. });
  1314. it("没有 Coding Plan apiKey 时不调用 quota 和套餐预览接口", async () => {
  1315. const apiClient: ApiClient = {
  1316. request: vi.fn(async () =>
  1317. createJsonResponse({
  1318. code: 200,
  1319. data: {
  1320. level: "pro",
  1321. limits: [
  1322. {
  1323. type: "TIME_LIMIT",
  1324. remaining: 5,
  1325. nextResetTime: Date.UTC(2026, 4, 26),
  1326. },
  1327. ],
  1328. },
  1329. }),
  1330. ),
  1331. };
  1332. const provider = createProviderForTest({
  1333. apiClient,
  1334. modelProviderService: {
  1335. getAllCached: vi.fn(async () => [
  1336. {
  1337. ...createBigModelCodingPlanProvider(),
  1338. apiKey: "",
  1339. },
  1340. ]),
  1341. } as LegacyModelProviderReader,
  1342. accountRequestAuthService: {
  1343. resolveAccessCurrent: vi.fn(async () => null),
  1344. resolveCurrent: vi.fn(async () => ({ apiKey: undefined })),
  1345. assertCurrent: vi.fn(async () => undefined),
  1346. },
  1347. });
  1348. const snapshot = await provider.getSnapshotForRequest({
  1349. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1350. requirePreferredProvider: true,
  1351. allowEnvApiKey: false,
  1352. });
  1353. expect(apiClient.request).not.toHaveBeenCalled();
  1354. expect(snapshot.unavailableReason).toBe("not_configured");
  1355. expect(snapshot.provider).toBeNull();
  1356. });
  1357. it("严格指定 Coding Plan 时不会回退到普通 API Key provider", async () => {
  1358. const apiClient: ApiClient = {
  1359. request: vi.fn(),
  1360. };
  1361. const provider = createProviderForTest({
  1362. apiClient,
  1363. modelProviderService: {
  1364. getAllCached: vi.fn(async () => [
  1365. {
  1366. ...createBigModelCodingPlanProvider(),
  1367. apiKey: "",
  1368. },
  1369. createBigModelApiKeyProvider(),
  1370. ]),
  1371. } as LegacyModelProviderReader,
  1372. });
  1373. const snapshot = await provider.getSnapshotForRequest({
  1374. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1375. requirePreferredProvider: true,
  1376. allowEnvApiKey: false,
  1377. });
  1378. expect(apiClient.request).not.toHaveBeenCalled();
  1379. expect(snapshot.unavailableReason).toBe("not_configured");
  1380. expect(snapshot.provider).toBeNull();
  1381. });
  1382. it("严格指定 Coding Plan 时不会被环境变量 usage key 覆盖", async () => {
  1383. const apiClient: ApiClient = {
  1384. request: vi.fn(async (_input, init) => {
  1385. if (String(_input).includes("subscription/list")) {
  1386. expect(init?.headers).toMatchObject({ Authorization: "bigmodel-api-key" });
  1387. return createJsonResponse({ code: 200, data: [] });
  1388. }
  1389. expect(init?.headers).toMatchObject({
  1390. authorization: "bigmodel-api-key",
  1391. });
  1392. return createJsonResponse({
  1393. code: 200,
  1394. data: {
  1395. level: "pro",
  1396. limits: [],
  1397. },
  1398. });
  1399. }),
  1400. };
  1401. const provider = createProviderForTest({
  1402. apiClient,
  1403. modelProviderService: {
  1404. getAllCached: vi.fn(async () => [createBigModelCodingPlanProvider()]),
  1405. } as LegacyModelProviderReader,
  1406. env: {
  1407. ZCODE_BIGMODEL_USAGE_API_KEY: "env-usage-key",
  1408. },
  1409. });
  1410. const snapshot = await provider.getSnapshotForRequest({
  1411. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1412. requirePreferredProvider: true,
  1413. includeSubscription: false,
  1414. });
  1415. expect(apiClient.request).toHaveBeenCalledTimes(2);
  1416. expect(snapshot.provider).toMatchObject({
  1417. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1418. });
  1419. });
  1420. it("Z.ai Coding Plan 用量权益直接使用 provider apiKey 请求 quota", async () => {
  1421. const requestUrls: string[] = [];
  1422. const apiClient: ApiClient = {
  1423. request: vi.fn(async (input, init) => {
  1424. const url = input.toString();
  1425. requestUrls.push(url);
  1426. if (url.includes("subscription/list")) {
  1427. expect(init?.headers).toMatchObject({ Authorization: "zai-api-key" });
  1428. return createJsonResponse({ code: 200, data: [] });
  1429. }
  1430. expect(url).toBe("https://api.z.ai/api/monitor/usage/quota/limit");
  1431. expect(init?.headers).toMatchObject({
  1432. authorization: "zai-api-key",
  1433. });
  1434. return createJsonResponse({
  1435. code: 200,
  1436. data: {
  1437. level: "pro",
  1438. limits: [],
  1439. },
  1440. });
  1441. }),
  1442. };
  1443. const provider = createProviderForTest({
  1444. apiClient,
  1445. modelProviderService: {
  1446. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1447. } as LegacyModelProviderReader,
  1448. });
  1449. const snapshot = await provider.getSnapshotForRequest({
  1450. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1451. requirePreferredProvider: true,
  1452. includeSubscription: false,
  1453. });
  1454. expect(requestUrls).toEqual([
  1455. "https://api.z.ai/api/biz/subscription/list",
  1456. "https://api.z.ai/api/monitor/usage/quota/limit",
  1457. ]);
  1458. expect(snapshot.provider).toMatchObject({
  1459. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1460. });
  1461. });
  1462. it("Z.ai Coding Plan 团队授权不可用时不会回退个人 key 发送 team quota header", async () => {
  1463. const requestHeaders: Array<HeadersInit | undefined> = [];
  1464. const apiClient: ApiClient = {
  1465. request: vi.fn(async (_input, init) => {
  1466. requestHeaders.push(init?.headers);
  1467. return createJsonResponse({
  1468. code: 200,
  1469. data: {
  1470. level: "pro",
  1471. limits: [],
  1472. },
  1473. });
  1474. }),
  1475. };
  1476. const provider = createProviderForTest({
  1477. apiClient,
  1478. modelProviderService: {
  1479. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1480. } as LegacyModelProviderReader,
  1481. accountRequestAuthService: {
  1482. resolveAccessCurrent: vi.fn(async () => null),
  1483. resolveCurrent: vi.fn(async () => ({ apiKey: undefined })),
  1484. assertCurrent: vi.fn(async () => undefined),
  1485. },
  1486. });
  1487. await expect(
  1488. provider.getSnapshotForRequest({
  1489. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1490. requirePreferredProvider: true,
  1491. includeSubscription: false,
  1492. organizationId: "org-should-ignore",
  1493. projectId: "proj-should-ignore",
  1494. }),
  1495. ).rejects.toThrow("Coding Plan entitlement refresh failed");
  1496. // 修复原因:误传 team context 时不能把个人 Z.ai Coding Plan key 和 team header 混用。
  1497. // 团队业务登录态和调用 Key 均缺失时权益未知,不能回退个人 Key。
  1498. expect(requestHeaders).toEqual([]);
  1499. });
  1500. it("Z.ai Coding Plan 用 provider apiKey 读取订阅状态和到期时间", async () => {
  1501. const requestUrls: string[] = [];
  1502. const apiClient: ApiClient = {
  1503. request: vi.fn(async (input, init) => {
  1504. const url = input.toString();
  1505. requestUrls.push(url);
  1506. if (url.endsWith("/api/monitor/usage/quota/limit")) {
  1507. expect(init?.headers).toMatchObject({
  1508. authorization: "zai-api-key",
  1509. });
  1510. return createJsonResponse({
  1511. code: 200,
  1512. data: {
  1513. level: "pro",
  1514. limits: [],
  1515. },
  1516. });
  1517. }
  1518. expect(url).toBe("https://api.z.ai/api/biz/subscription/list");
  1519. expect(init?.headers).toMatchObject({
  1520. Authorization: "zai-api-key",
  1521. });
  1522. return createJsonResponse({
  1523. code: 200,
  1524. data: [
  1525. {
  1526. productId: "product-zai-pro-quarter",
  1527. productName: "GLM Coding Pro",
  1528. status: "VALID",
  1529. inCurrentPeriod: true,
  1530. billingCycle: "quarterly",
  1531. nextRenewTime: "2026-07-10",
  1532. valid: "2026-04-10 16:32:00-2026-07-10 10:00:00",
  1533. },
  1534. ],
  1535. });
  1536. }),
  1537. };
  1538. const provider = createProviderForTest({
  1539. apiClient,
  1540. modelProviderService: {
  1541. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1542. } as LegacyModelProviderReader,
  1543. });
  1544. const snapshot = await provider.getSnapshotForRequest({
  1545. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1546. requirePreferredProvider: true,
  1547. });
  1548. expect(requestUrls).toEqual([
  1549. "https://api.z.ai/api/biz/subscription/list",
  1550. "https://api.z.ai/api/monitor/usage/quota/limit",
  1551. ]);
  1552. expect(snapshot.subscription?.details[0]).toMatchObject({
  1553. productId: "product-zai-pro-quarter",
  1554. productName: "GLM Coding Pro",
  1555. billingCycle: "quarterly",
  1556. renewTime: null,
  1557. expireTime: new Date("2026-07-10").toISOString(),
  1558. });
  1559. });
  1560. it("Z.ai Coding Plan quota 失败时仍用订阅列表判断已购买状态", async () => {
  1561. const requestUrls: string[] = [];
  1562. const apiClient: ApiClient = {
  1563. request: vi.fn(async (input, init) => {
  1564. const url = input.toString();
  1565. requestUrls.push(url);
  1566. if (url.endsWith("/api/biz/subscription/list")) {
  1567. expect(init?.headers).toMatchObject({
  1568. Authorization: "zai-api-key",
  1569. });
  1570. return createJsonResponse({
  1571. code: 200,
  1572. data: [
  1573. {
  1574. productId: "product-zai-pro-quarter",
  1575. productName: "GLM Coding Pro",
  1576. status: "VALID",
  1577. inCurrentPeriod: true,
  1578. billingCycle: "quarterly",
  1579. nextRenewTime: "2026-07-10",
  1580. },
  1581. ],
  1582. });
  1583. }
  1584. expect(url).toBe("https://api.z.ai/api/monitor/usage/quota/limit");
  1585. expect(init?.headers).toMatchObject({
  1586. authorization: "zai-api-key",
  1587. });
  1588. return createJsonResponse({
  1589. code: 401,
  1590. msg: "token expired or incorrect",
  1591. success: false,
  1592. });
  1593. }),
  1594. };
  1595. const provider = createProviderForTest({
  1596. apiClient,
  1597. modelProviderService: {
  1598. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1599. } as LegacyModelProviderReader,
  1600. });
  1601. const snapshot = await provider.getSnapshotForRequest({
  1602. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1603. requirePreferredProvider: true,
  1604. });
  1605. expect(requestUrls).toEqual([
  1606. "https://api.z.ai/api/biz/subscription/list",
  1607. "https://api.z.ai/api/monitor/usage/quota/limit",
  1608. ]);
  1609. expect(snapshot.unavailableReason).toBeUndefined();
  1610. expect(snapshot.subscription?.details[0]).toMatchObject({
  1611. productId: "product-zai-pro-quarter",
  1612. productName: "GLM Coding Pro",
  1613. billingCycle: "quarterly",
  1614. renewTime: null,
  1615. expireTime: new Date("2026-07-10").toISOString(),
  1616. });
  1617. expect(snapshot.quota).toBeNull();
  1618. });
  1619. it("Z.ai Coding Plan 订阅列表有效时不被 quota no_plan 覆盖", async () => {
  1620. const apiClient: ApiClient = {
  1621. request: vi.fn(async (input, init) => {
  1622. const url = input.toString();
  1623. if (url.endsWith("/api/biz/subscription/list")) {
  1624. expect(init?.headers).toMatchObject({
  1625. Authorization: "zai-api-key",
  1626. });
  1627. return createJsonResponse({
  1628. code: 200,
  1629. data: [
  1630. {
  1631. productId: "product-zai-pro-monthly",
  1632. productName: "GLM Coding Pro",
  1633. status: "VALID",
  1634. inCurrentPeriod: true,
  1635. billingCycle: "monthly",
  1636. nextRenewTime: "2026-07-10",
  1637. },
  1638. ],
  1639. });
  1640. }
  1641. expect(url).toBe("https://api.z.ai/api/monitor/usage/quota/limit");
  1642. expect(init?.headers).toMatchObject({
  1643. authorization: "zai-api-key",
  1644. });
  1645. return createJsonResponse({
  1646. code: 500,
  1647. msg: "不存在coding plan",
  1648. success: false,
  1649. });
  1650. }),
  1651. };
  1652. const provider = createProviderForTest({
  1653. apiClient,
  1654. modelProviderService: {
  1655. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1656. } as LegacyModelProviderReader,
  1657. });
  1658. const snapshot = await provider.getSnapshotForRequest({
  1659. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1660. requirePreferredProvider: true,
  1661. });
  1662. expect(snapshot.unavailableReason).toBeUndefined();
  1663. expect(snapshot.subscription?.details[0]).toMatchObject({
  1664. productId: "product-zai-pro-monthly",
  1665. productName: "GLM Coding Pro",
  1666. });
  1667. expect(snapshot.quota).toBeNull();
  1668. });
  1669. it("Z.ai Coding Plan token 失效时返回同步失败而不是未开通", async () => {
  1670. const apiClient: ApiClient = {
  1671. request: vi.fn(async (input, init) => {
  1672. expect(input.toString()).toBe("https://api.z.ai/api/biz/subscription/list");
  1673. expect(init?.headers).toMatchObject({ Authorization: "zai-api-key" });
  1674. return createJsonResponse({
  1675. code: 401,
  1676. msg: "token expired or incorrect",
  1677. success: false,
  1678. });
  1679. }),
  1680. };
  1681. const provider = createProviderForTest({
  1682. apiClient,
  1683. modelProviderService: {
  1684. getAllCached: vi.fn(async () => [createZaiCodingPlanProvider()]),
  1685. } as LegacyModelProviderReader,
  1686. });
  1687. await expect(
  1688. provider.getSnapshotForRequest({
  1689. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1690. requirePreferredProvider: true,
  1691. includeSubscription: false,
  1692. }),
  1693. ).rejects.toThrow("Coding Plan entitlement refresh failed");
  1694. });
  1695. it("Z.ai Coding Plan provider 未同步时不会回退 OAuth token 查询权益", async () => {
  1696. const apiClient: ApiClient = {
  1697. request: vi.fn(),
  1698. };
  1699. const provider = createProviderForTest({
  1700. apiClient,
  1701. modelProviderService: {
  1702. getAllCached: vi.fn(async () => []),
  1703. } as LegacyModelProviderReader,
  1704. credentialService: {
  1705. load: vi.fn(async () => "zai-oauth-token"),
  1706. },
  1707. });
  1708. const snapshot = await provider.getSnapshotForRequest({
  1709. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1710. requirePreferredProvider: true,
  1711. includeSubscription: false,
  1712. });
  1713. expect(apiClient.request).not.toHaveBeenCalled();
  1714. expect(snapshot.unavailableReason).toBe("not_configured");
  1715. expect(snapshot.provider).toBeNull();
  1716. });
  1717. it("Z.ai Coding Plan 空 apiKey 时按未配置权益处理且不回退 OAuth token", async () => {
  1718. const apiClient: ApiClient = {
  1719. request: vi.fn(),
  1720. };
  1721. const provider = createProviderForTest({
  1722. apiClient,
  1723. modelProviderService: {
  1724. getAllCached: vi.fn(async () => [
  1725. {
  1726. ...createZaiCodingPlanProvider(),
  1727. apiKey: "",
  1728. },
  1729. ]),
  1730. } as LegacyModelProviderReader,
  1731. credentialService: {
  1732. load: vi.fn(async () => "zai-oauth-token"),
  1733. },
  1734. });
  1735. const snapshot = await provider.getSnapshotForRequest({
  1736. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1737. requirePreferredProvider: true,
  1738. includeSubscription: false,
  1739. });
  1740. expect(apiClient.request).not.toHaveBeenCalled();
  1741. expect(snapshot.unavailableReason).toBe("not_configured");
  1742. expect(snapshot.provider).toBeNull();
  1743. });
  1744. });