codingPlanProviderAvailability.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. import { BUILTIN_MODEL_PROVIDER_IDS, type ApiClient } from "@zcode/shared";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. validateBigModelAccountProviderAvailability,
  5. validateCodingPlanProviderAvailability,
  6. validateZaiAccountProviderAvailability,
  7. type CodingPlanAvailabilityProvider,
  8. } from "../src/model-provider/codingPlanProviderAvailability.js";
  9. describe("codingPlanProviderAvailability", () => {
  10. it.each(["bigmodel", "zai"] as const)(
  11. "%s 个人订阅请求保留完整 PAT,不按旧 id.secret 截断",
  12. async (family) => {
  13. const token = [
  14. Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT", sign_type: "SIGN" })).toString(
  15. "base64url",
  16. ),
  17. Buffer.from(JSON.stringify({ token_use: "project_access", sub: "test-account" })).toString(
  18. "base64url",
  19. ),
  20. "synthetic_signature_only_for_test",
  21. ].join(".");
  22. const request = vi.fn<ApiClient["request"]>(async (_url, init) => {
  23. const authorization = new Headers(init?.headers).get("Authorization");
  24. return Response.json(
  25. {
  26. code: 200,
  27. data: [{ productId: "coding-pro", status: "VALID", inCurrentPeriod: true }],
  28. },
  29. { status: authorization === token ? 200 : 401 },
  30. );
  31. });
  32. for (const apiKey of [token, ` Bearer ${token} `]) {
  33. await expect(
  34. validateCodingPlanProviderAvailability(
  35. { providerId: "personal", family, planKind: "individual-coding-plan", apiKey },
  36. { apiClient: { request } },
  37. ),
  38. ).resolves.toEqual({ kind: "available" });
  39. }
  40. expect(request).toHaveBeenCalledTimes(2);
  41. for (const [url, init] of request.mock.calls) {
  42. expect(String(url)).toContain("/api/biz/subscription/list");
  43. expect(new Headers(init?.headers).get("Authorization")).toBe(token);
  44. }
  45. },
  46. );
  47. it.each(["bigmodel", "zai"] as const)("%s 混合列表中的有效订阅仍启用账号套餐", async (family) => {
  48. const request = vi.fn(
  49. async () =>
  50. new Response(
  51. JSON.stringify({
  52. code: 200,
  53. data: [
  54. {},
  55. { productName: "Storage" },
  56. { productId: "coding-pro", status: "VALID", inCurrentPeriod: true },
  57. ],
  58. }),
  59. ),
  60. );
  61. await expect(
  62. validateCodingPlanProviderAvailability(
  63. {
  64. providerId: "personal",
  65. family,
  66. planKind: "individual-coding-plan",
  67. apiKey: "personal-key",
  68. },
  69. { apiClient: { request } },
  70. ),
  71. ).resolves.toEqual({ kind: "available" });
  72. });
  73. it.each(["bigmodel", "zai"] as const)(
  74. "%s 团队权益仅用业务 token 查询指定项目,不获取 Key 或 quota",
  75. async (family) => {
  76. const request = vi.fn(async (url: string) => {
  77. if (url.endsWith("/customer/getCustomerInfo"))
  78. return new Response(
  79. JSON.stringify({
  80. code: 200,
  81. data: {
  82. organizations: [
  83. { organizationId: "org", projects: [{ projectId: "project", projectType: 2 }] },
  84. ],
  85. },
  86. }),
  87. );
  88. if (url.endsWith("/team/subscribe/product/querySubscribeDetail"))
  89. return new Response(
  90. JSON.stringify({
  91. success: true,
  92. data: { hasSubscription: true, status: "EFFECTIVE", memberGrantStatus: "VALID" },
  93. }),
  94. );
  95. throw new Error("权益查询不得访问其他接口");
  96. });
  97. const validate =
  98. family === "bigmodel"
  99. ? validateBigModelAccountProviderAvailability
  100. : validateZaiAccountProviderAvailability;
  101. const result = await validate(
  102. [{ providerId: "team", family, planKind: "team-coding-plan" }],
  103. {
  104. apiClient: { request },
  105. credentialService: {
  106. load: async (key) => (key === `oauth:${family}:access_token` ? "business" : null),
  107. },
  108. providerFamilyConnectionSelections: {
  109. [family]: {
  110. kind: "team-coding-plan",
  111. organizationId: "org",
  112. projectId: "project",
  113. productId: "pricing",
  114. },
  115. },
  116. },
  117. );
  118. expect(result.team).toEqual({ kind: "available" });
  119. expect(request).toHaveBeenCalledTimes(2);
  120. expect(request.mock.calls[1]?.[0]).toContain(
  121. "/api/biz/team/subscribe/product/querySubscribeDetail",
  122. );
  123. expect((request.mock.calls[1] as unknown as [string, RequestInit])[1].headers).toEqual({
  124. Authorization: family === "zai" ? "Bearer business" : "business",
  125. "bigmodel-organization": "org",
  126. "bigmodel-project": "project",
  127. });
  128. },
  129. );
  130. describe.each(["zai", "bigmodel"] as const)("%s 个人套餐缺 Key 的分类", (family) => {
  131. it.each([true, false])("有本地登录信息=%s;不能将取 Key 失败当成未连接", async (loggedIn) => {
  132. const request = vi.fn();
  133. const load = vi.fn(async (key: string) =>
  134. key === `oauth:${family}:user_info` && loggedIn ? "local-user-info" : null,
  135. );
  136. await expect(
  137. validateCodingPlanProviderAvailability(
  138. {
  139. providerId: "personal",
  140. family,
  141. planKind: "individual-coding-plan",
  142. apiKey: null,
  143. },
  144. { apiClient: { request }, credentialService: { load } },
  145. ),
  146. ).resolves.toEqual({
  147. kind: "unknown",
  148. });
  149. expect(load).not.toHaveBeenCalled();
  150. expect(request).not.toHaveBeenCalled();
  151. });
  152. });
  153. it.each([
  154. {
  155. effectiveAt: 2_000,
  156. serverTime: 1_000,
  157. expected: { kind: "pending", effectiveAt: 2_000, models: [] },
  158. },
  159. { effectiveAt: 0, serverTime: 1_000, expected: { kind: "available" } },
  160. { effectiveAt: 2_000, serverTime: 3_000, expected: { kind: "available" } },
  161. ])(
  162. "待生效按 billing 服务端秒时钟判断:$effectiveAt / $serverTime",
  163. async ({ effectiveAt, serverTime, expected }) => {
  164. const apiClient: ApiClient = {
  165. request: vi.fn(
  166. async () =>
  167. new Response(
  168. JSON.stringify({
  169. code: 200,
  170. success: true,
  171. data: {
  172. server_time: serverTime,
  173. balances: [],
  174. plans: [
  175. {
  176. plan_id: "zcode-v3-start-plan",
  177. status: "active",
  178. entitlements: [{ effective_at: effectiveAt }],
  179. },
  180. ],
  181. },
  182. }),
  183. { status: 200 },
  184. ),
  185. ),
  186. };
  187. await expect(
  188. validateCodingPlanProviderAvailability(
  189. availabilityProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan, "zai", "start-plan"),
  190. {
  191. apiClient,
  192. credentialService: {
  193. load: async (key) => (key === "zcodejwttoken" ? "jwt" : null),
  194. },
  195. },
  196. ),
  197. ).resolves.toEqual(expected);
  198. },
  199. );
  200. it("权益判定只依赖结构化 Account Access 与鉴权输入", async () => {
  201. const provider: CodingPlanAvailabilityProvider = {
  202. providerId: "provider-name-is-not-a-product-protocol",
  203. family: "zai",
  204. planKind: "individual-coding-plan",
  205. apiKey: "",
  206. };
  207. const apiClient: ApiClient = {
  208. request: vi.fn(async () => {
  209. throw new Error("缺少 API Key 时不应发起网络请求");
  210. }),
  211. };
  212. await expect(
  213. validateCodingPlanProviderAvailability(provider, {
  214. apiClient,
  215. credentialService: { load: async () => null },
  216. }),
  217. ).resolves.toEqual({ kind: "unknown" });
  218. expect(apiClient.request).not.toHaveBeenCalled();
  219. });
  220. it("Start Plan 在同一次 balance 响应中返回权益与权威模型集合", async () => {
  221. const apiClient: ApiClient = {
  222. request: vi.fn(
  223. async () =>
  224. new Response(
  225. JSON.stringify({
  226. code: 200,
  227. success: true,
  228. data: {
  229. plans: [
  230. {
  231. plan_id: "zcode-v3-start-plan",
  232. status: "active",
  233. },
  234. ],
  235. balances: [
  236. { capabilities: ["model:GLM-5.2", "model:GLM-5-Turbo"] },
  237. { capabilities: ["model:glm-5.2"] },
  238. ],
  239. },
  240. }),
  241. { status: 200, headers: { "content-type": "application/json" } },
  242. ),
  243. ),
  244. };
  245. await expect(
  246. validateCodingPlanProviderAvailability(
  247. availabilityProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan, "zai", "start-plan"),
  248. {
  249. apiClient,
  250. credentialService: {
  251. load: async (key) => (key === "zcodejwttoken" ? "jwt" : null),
  252. },
  253. },
  254. ),
  255. ).resolves.toEqual({
  256. kind: "available",
  257. models: ["GLM-5.2", "GLM-5-Turbo"],
  258. });
  259. });
  260. it("Start Plan balance 没有模型明细时保留可用状态", async () => {
  261. const apiClient: ApiClient = {
  262. request: vi.fn(
  263. async () =>
  264. new Response(
  265. JSON.stringify({
  266. code: 200,
  267. success: true,
  268. data: {
  269. plans: [
  270. {
  271. plan_id: "zcode-v3-start-plan",
  272. status: "active",
  273. },
  274. ],
  275. balances: [],
  276. },
  277. }),
  278. { status: 200, headers: { "content-type": "application/json" } },
  279. ),
  280. ),
  281. };
  282. await expect(
  283. validateCodingPlanProviderAvailability(
  284. availabilityProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan, "zai", "start-plan"),
  285. {
  286. apiClient,
  287. credentialService: {
  288. load: async (key) => (key === "zcodejwttoken" ? "jwt" : null),
  289. },
  290. },
  291. ),
  292. ).resolves.toEqual({ kind: "available" });
  293. });
  294. it("独立检查每种权益,没有 Team 身份时不猜测目标团队", async () => {
  295. const apiClient: ApiClient = {
  296. request: vi.fn(async () => {
  297. throw new Error("未登录时不应发起网络请求");
  298. }),
  299. };
  300. await expect(
  301. validateZaiAccountProviderAvailability(
  302. [
  303. availabilityProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan, "zai", "start-plan"),
  304. availabilityProvider(
  305. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  306. "zai",
  307. "individual-coding-plan",
  308. ),
  309. availabilityProvider(
  310. BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  311. "zai",
  312. "team-coding-plan",
  313. ),
  314. ],
  315. {
  316. apiClient,
  317. credentialService: { load: async () => null },
  318. providerFamilyConnectionSelections: { zai: { kind: "start-plan" } },
  319. },
  320. ),
  321. ).resolves.toEqual({
  322. [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan]: {
  323. kind: "unavailable",
  324. reason: "coding_plan_not_authenticated",
  325. },
  326. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: { kind: "unknown" },
  327. [BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan]: {
  328. kind: "unknown",
  329. },
  330. });
  331. expect(apiClient.request).not.toHaveBeenCalled();
  332. });
  333. it("Z.ai 只有 Start Plan 权益时保留 Start 并关闭 Coding", async () => {
  334. const apiClient = createZaiPairApiClient({
  335. startPlanActive: true,
  336. codingPlanActive: false,
  337. });
  338. await expect(
  339. validateZaiAccountProviderAvailability(zaiPairProviders(), {
  340. apiClient,
  341. credentialService: createZaiCredentialService(),
  342. providerFamilyConnectionSelections: { zai: { kind: "start-plan" } },
  343. }),
  344. ).resolves.toEqual({
  345. [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan]: { kind: "available" },
  346. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: {
  347. kind: "unavailable",
  348. reason: "coding_plan_not_entitled",
  349. },
  350. [BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan]: {
  351. kind: "unknown",
  352. },
  353. });
  354. });
  355. it("Individual 选择时仍独立查询 Start Plan 权益", async () => {
  356. const apiClient = createZaiPairApiClient({
  357. startPlanActive: true,
  358. codingPlanActive: true,
  359. });
  360. await expect(
  361. validateZaiAccountProviderAvailability(zaiPairProviders(), {
  362. apiClient,
  363. credentialService: createZaiCredentialService(),
  364. providerFamilyConnectionSelections: {
  365. zai: { kind: "individual-coding-plan" },
  366. },
  367. }),
  368. ).resolves.toEqual({
  369. [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan]: { kind: "available" },
  370. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: {
  371. kind: "available",
  372. },
  373. [BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan]: {
  374. kind: "unknown",
  375. },
  376. });
  377. });
  378. it("Coding Plan 查询暂时失败时仍保留已经确定的 Start Plan 权益", async () => {
  379. const apiClient = createZaiPairApiClient({
  380. startPlanActive: true,
  381. codingPlanStatus: 503,
  382. });
  383. await expect(
  384. validateZaiAccountProviderAvailability(zaiPairProviders(), {
  385. apiClient,
  386. credentialService: createZaiCredentialService(),
  387. providerFamilyConnectionSelections: {
  388. zai: { kind: "individual-coding-plan" },
  389. },
  390. }),
  391. ).resolves.toEqual({
  392. [BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan]: { kind: "available" },
  393. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: { kind: "unknown" },
  394. [BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan]: {
  395. kind: "unknown",
  396. },
  397. });
  398. });
  399. it("已选 Team Plan 但远端校验暂时失败时保留上一版连接状态", async () => {
  400. const apiClient: ApiClient = {
  401. request: vi.fn(async () => new Response("temporary unavailable", { status: 503 })),
  402. };
  403. await expect(
  404. validateBigModelAccountProviderAvailability(
  405. [
  406. availabilityProvider(
  407. BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  408. "bigmodel",
  409. "start-plan",
  410. ),
  411. availabilityProvider(
  412. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  413. "bigmodel",
  414. "individual-coding-plan",
  415. "personal-key",
  416. ),
  417. availabilityProvider(
  418. BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  419. "bigmodel",
  420. "team-coding-plan",
  421. ),
  422. ],
  423. {
  424. apiClient,
  425. credentialService: {
  426. load: async (key) => (key === "oauth:bigmodel:access_token" ? "business-token" : null),
  427. },
  428. providerFamilyConnectionSelections: {
  429. bigmodel: {
  430. kind: "team-coding-plan",
  431. productId: "product",
  432. organizationId: "organization",
  433. projectId: "project",
  434. },
  435. },
  436. },
  437. ),
  438. ).resolves.toEqual({
  439. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan]: {
  440. kind: "unavailable",
  441. reason: "coding_plan_not_authenticated",
  442. },
  443. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]: {
  444. kind: "unknown",
  445. },
  446. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan]: { kind: "unknown" },
  447. });
  448. });
  449. });
  450. function zaiPairProviders(): CodingPlanAvailabilityProvider[] {
  451. return [
  452. availabilityProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan, "zai", "start-plan"),
  453. availabilityProvider(
  454. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  455. "zai",
  456. "individual-coding-plan",
  457. "coding-plan-key",
  458. ),
  459. availabilityProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan, "zai", "team-coding-plan"),
  460. ];
  461. }
  462. function availabilityProvider(
  463. providerId: string,
  464. family: CodingPlanAvailabilityProvider["family"],
  465. planKind: CodingPlanAvailabilityProvider["planKind"],
  466. apiKey?: string,
  467. ): CodingPlanAvailabilityProvider {
  468. return {
  469. providerId,
  470. family,
  471. planKind,
  472. ...(apiKey === undefined ? {} : { apiKey }),
  473. };
  474. }
  475. function createZaiCredentialService(): {
  476. load(key: string): Promise<string | null>;
  477. } {
  478. return {
  479. load: async (key) => (key === "zcodejwttoken" ? "start-plan-jwt" : null),
  480. };
  481. }
  482. function createZaiPairApiClient(options: {
  483. startPlanActive: boolean;
  484. codingPlanActive?: boolean;
  485. codingPlanStatus?: number;
  486. }): ApiClient {
  487. return {
  488. request: vi.fn(async (input) => {
  489. const url = String(input);
  490. if (url.includes("/billing/balance")) {
  491. return new Response(
  492. JSON.stringify({
  493. code: 200,
  494. success: true,
  495. data: {
  496. plans: options.startPlanActive
  497. ? [{ plan_id: "zcode-v3-start-plan", status: "active" }]
  498. : [],
  499. },
  500. }),
  501. { status: 200, headers: { "content-type": "application/json" } },
  502. );
  503. }
  504. if (url.includes("/api/biz/subscription/list")) {
  505. if (options.codingPlanStatus && options.codingPlanStatus !== 200) {
  506. return new Response("temporary unavailable", {
  507. status: options.codingPlanStatus,
  508. });
  509. }
  510. return new Response(
  511. JSON.stringify({
  512. code: 0,
  513. success: true,
  514. data: options.codingPlanActive
  515. ? [
  516. {
  517. productId: "coding-plan-pro",
  518. status: "VALID",
  519. inCurrentPeriod: true,
  520. },
  521. ]
  522. : [],
  523. }),
  524. { status: 200, headers: { "content-type": "application/json" } },
  525. );
  526. }
  527. return new Response("not found", { status: 404 });
  528. }),
  529. };
  530. }