codingPlanEntitlements.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { renderToString } from "react-dom/server";
  4. import { renderHook } from "@testing-library/react";
  5. import { describe, expect, it, vi } from "vitest";
  6. import type { ProviderSettingsView } from "@zcode/services";
  7. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  8. import {
  9. resolveCodingPlanProviderFingerprintAutoRefresh,
  10. useCodingPlanAccessRefresh,
  11. useCodingPlanEntitlements,
  12. } from "@/settings/model-provider-section/useCodingPlanEntitlements.js";
  13. const { usageEntitlementCalls, usageEntitlementRefresh } = vi.hoisted(() => ({
  14. usageEntitlementCalls: [] as Array<Record<string, unknown>>,
  15. usageEntitlementRefresh: vi.fn(async () => undefined),
  16. }));
  17. vi.mock("@/hooks/useUsageEntitlement.js", () => ({
  18. useUsageEntitlement: (options: Record<string, unknown>) => {
  19. usageEntitlementCalls.push(options);
  20. return {
  21. error: null,
  22. loading: false,
  23. refresh: usageEntitlementRefresh,
  24. snapshot: null,
  25. };
  26. },
  27. }));
  28. function HookProbe({
  29. connectionSelections,
  30. providerSettingsView,
  31. }: {
  32. connectionSelections?: Parameters<typeof useCodingPlanEntitlements>[0]["connectionSelections"];
  33. providerSettingsView: ProviderSettingsView | null;
  34. }) {
  35. useCodingPlanEntitlements({
  36. connectionSelections,
  37. providerSettingsView,
  38. });
  39. return null;
  40. }
  41. function createProviderSettingsView(
  42. providers: Array<{
  43. providerId: string;
  44. access?: Record<string, string | boolean>;
  45. }>,
  46. ): ProviderSettingsView {
  47. return {
  48. revision: 1,
  49. addableProviders: [],
  50. providerOrder: [],
  51. providers: providers.map(({ access, providerId }) => ({
  52. providerId,
  53. enabled: true,
  54. executable: Boolean(access),
  55. effectiveConfig: {
  56. ...(access
  57. ? {
  58. access: {
  59. type: "zhipu-account" as const,
  60. entitled: true,
  61. ...access,
  62. },
  63. }
  64. : {}),
  65. api: {
  66. type: "anthropic-messages" as const,
  67. baseUrl: "https://example.com",
  68. },
  69. builtinModelIds: [],
  70. },
  71. issues: [],
  72. models: [],
  73. })),
  74. };
  75. }
  76. describe("useCodingPlanEntitlements", () => {
  77. it("等价 Family 权益事实重新渲染时保持返回引用稳定", () => {
  78. usageEntitlementCalls.length = 0;
  79. const providerSettingsView = createProviderSettingsView([
  80. {
  81. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  82. access: {
  83. accountType: "bigmodel",
  84. mode: "team-coding-plan",
  85. },
  86. },
  87. ]);
  88. const initialSelection = {
  89. bigmodel: {
  90. kind: "team-coding-plan" as const,
  91. productId: "team-pro",
  92. organizationId: "org-a",
  93. projectId: "project-a",
  94. },
  95. };
  96. const hook = renderHook(
  97. ({ connectionSelections }) =>
  98. useCodingPlanEntitlements({ connectionSelections, providerSettingsView }),
  99. { initialProps: { connectionSelections: initialSelection } },
  100. );
  101. const firstResult = hook.result.current;
  102. hook.rerender({
  103. connectionSelections: {
  104. bigmodel: { ...initialSelection.bigmodel },
  105. },
  106. });
  107. expect(hook.result.current).toBe(firstResult);
  108. });
  109. it("BigModel Team Plan 选中时仍独立刷新 Start Plan entitlement", () => {
  110. usageEntitlementCalls.length = 0;
  111. renderToString(
  112. createElement(HookProbe, {
  113. connectionSelections: {
  114. bigmodel: {
  115. kind: "team-coding-plan",
  116. productId: "team-pro",
  117. organizationId: "org-a",
  118. projectId: "project-a",
  119. },
  120. },
  121. providerSettingsView: createProviderSettingsView([
  122. {
  123. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  124. access: {
  125. accountType: "bigmodel",
  126. mode: "team-coding-plan",
  127. },
  128. },
  129. {
  130. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  131. access: {
  132. accountType: "bigmodel",
  133. mode: "start-plan",
  134. },
  135. },
  136. ]),
  137. }),
  138. );
  139. const bigmodelCall = usageEntitlementCalls.find(
  140. (call) => call.preferredProviderId === BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  141. );
  142. expect(bigmodelCall).toMatchObject({
  143. allowDisabledPreferredProvider: true,
  144. enabled: true,
  145. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  146. accountAccess: expect.objectContaining({
  147. organizationId: "org-a",
  148. projectId: "project-a",
  149. }),
  150. requirePreferredProvider: true,
  151. refreshOnMount: false,
  152. });
  153. expect(String(bigmodelCall?.cacheKey)).toContain("bigmodel-team");
  154. const bigmodelStartCall = usageEntitlementCalls.find(
  155. (call) => call.preferredProviderId === BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  156. );
  157. expect(bigmodelStartCall?.enabled).toBe(true);
  158. });
  159. it("Account Provider 没有已启用连接时不把旧静态入口当作可查询连接", () => {
  160. usageEntitlementCalls.length = 0;
  161. renderToString(
  162. createElement(HookProbe, {
  163. providerSettingsView: createProviderSettingsView([
  164. { providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan },
  165. { providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan },
  166. ]),
  167. }),
  168. );
  169. const calls = usageEntitlementCalls.filter((call) =>
  170. [
  171. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  172. BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  173. ].includes(String(call.preferredProviderId)),
  174. );
  175. expect(calls).toHaveLength(2);
  176. expect(calls.every((call) => call.enabled === false)).toBe(true);
  177. });
  178. it("权益缓存身份跟随结构化 Account 连接而不是 Renderer 中的 API Key", () => {
  179. usageEntitlementCalls.length = 0;
  180. const providerId = BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan;
  181. renderToString(
  182. createElement(HookProbe, {
  183. providerSettingsView: createProviderSettingsView([
  184. {
  185. providerId,
  186. access: {
  187. accountType: "zai",
  188. mode: "individual-coding-plan",
  189. },
  190. },
  191. ]),
  192. }),
  193. );
  194. const firstCacheKey = usageEntitlementCalls.find(
  195. (call) => call.preferredProviderId === providerId,
  196. )?.cacheKey;
  197. usageEntitlementCalls.length = 0;
  198. renderToString(
  199. createElement(HookProbe, {
  200. connectionSelections: {
  201. zai: {
  202. kind: "team-coding-plan",
  203. productId: "team",
  204. organizationId: "org-a",
  205. projectId: "project-a",
  206. },
  207. },
  208. providerSettingsView: createProviderSettingsView([
  209. {
  210. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  211. access: {
  212. accountType: "zai",
  213. mode: "team-coding-plan",
  214. },
  215. },
  216. ]),
  217. }),
  218. );
  219. const secondCacheKey = usageEntitlementCalls.find(
  220. (call) => call.preferredProviderId === BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  221. )?.cacheKey;
  222. expect(firstCacheKey).not.toBe(secondCacheKey);
  223. expect(String(firstCacheKey)).toContain(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
  224. // 缓存键包含规范化的请求身份;不依赖其中快照 JSON 的转义/序列化层数。
  225. expect(String(firstCacheKey)).toContain('"planKind":"individual-coding-plan"');
  226. expect(String(secondCacheKey)).toContain(BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan);
  227. expect(String(secondCacheKey)).toContain('"organizationId":"org-a"');
  228. });
  229. });
  230. describe("useCodingPlanAccessRefresh", () => {
  231. it("只在套餐选择身份变化时刷新权益", () => {
  232. const refresh = vi.fn(async () => undefined);
  233. const hook = renderHook(
  234. ({ selectedPlanKey }) => useCodingPlanAccessRefresh({ refresh, selectedPlanKey }),
  235. { initialProps: { selectedPlanKey: null as string | null } },
  236. );
  237. expect(refresh).not.toHaveBeenCalled();
  238. hook.rerender({ selectedPlanKey: "coding-plan:bigmodel-individual" });
  239. expect(refresh).toHaveBeenCalledTimes(1);
  240. expect(refresh).toHaveBeenLastCalledWith({ silent: true, reason: "access" });
  241. hook.rerender({ selectedPlanKey: "coding-plan:bigmodel-individual" });
  242. expect(refresh).toHaveBeenCalledTimes(1);
  243. hook.rerender({ selectedPlanKey: "team-plan:bigmodel:project-a" });
  244. expect(refresh).toHaveBeenCalledTimes(2);
  245. hook.rerender({ selectedPlanKey: null });
  246. expect(refresh).toHaveBeenCalledTimes(2);
  247. });
  248. });
  249. describe("resolveCodingPlanProviderFingerprintAutoRefresh", () => {
  250. it("连接方式同步期间跳过一次 provider 指纹自动刷新", () => {
  251. const skipped = resolveCodingPlanProviderFingerprintAutoRefresh({
  252. loading: false,
  253. providerFingerprint: "provider-key:v2",
  254. skippedProviderFingerprint: "",
  255. suppressAutoRefresh: true,
  256. });
  257. expect(skipped).toEqual({
  258. shouldRefresh: false,
  259. skippedProviderFingerprint: "provider-key:v2",
  260. });
  261. expect(
  262. resolveCodingPlanProviderFingerprintAutoRefresh({
  263. loading: false,
  264. providerFingerprint: "provider-key:v2",
  265. skippedProviderFingerprint: skipped.skippedProviderFingerprint,
  266. suppressAutoRefresh: false,
  267. }),
  268. ).toEqual({
  269. shouldRefresh: false,
  270. skippedProviderFingerprint: "",
  271. });
  272. });
  273. });