codingPlanEntitlements.test.ts 9.5 KB

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