useCodingPlanEntryPlanList.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import {
  4. act,
  5. cleanup,
  6. renderHook,
  7. waitFor,
  8. render,
  9. screen,
  10. fireEvent,
  11. } from "@testing-library/react";
  12. import { afterEach, expect, it, vi } from "vitest";
  13. import { BUILTIN_MODEL_PROVIDER_IDS as ids } from "@zcode/shared";
  14. import type { ProviderSettingsView } from "@zcode/services";
  15. const h = vi.hoisted(() => ({
  16. user: { id: "first" },
  17. view: {
  18. revision: 1,
  19. providers: [],
  20. providerOrder: [],
  21. addableProviders: [],
  22. } as ProviderSettingsView,
  23. readError: false,
  24. reload: vi.fn(),
  25. entitlements: {} as Record<string, unknown>,
  26. load: vi.fn(),
  27. pricing: vi.fn(),
  28. entitlementsHook: vi.fn(),
  29. refresh: vi.fn().mockResolvedValue(undefined),
  30. }));
  31. vi.mock("@/hooks/useProviderSettingsView.js", () => ({
  32. useProviderSettingsView: () => ({
  33. state: h.readError
  34. ? { status: "error", error: new Error("read failed") }
  35. : { status: "ready", view: h.view },
  36. reload: h.reload,
  37. }),
  38. }));
  39. vi.mock("@/hooks/useServices.js", () => {
  40. const services = {
  41. credentialService: { load: h.load },
  42. codingPlanSubscriptionService: { getEnterprisePricing: h.pricing },
  43. };
  44. return { useServices: () => services };
  45. });
  46. vi.mock("@/store/StoreProvider.js", () => ({
  47. useZCodeStore: (select: (state: unknown) => unknown) => select({ user: h.user }),
  48. }));
  49. vi.mock("@/settings/model-provider-section/useCodingPlanEntitlements.js", () => ({
  50. useCodingPlanEntitlements: (params: unknown) => {
  51. h.entitlementsHook(params);
  52. return { entitlements: h.entitlements, refresh: h.refresh };
  53. },
  54. }));
  55. import { useCodingPlanEntryPlanList } from "@/hooks/useCodingPlanEntryPlanList.js";
  56. vi.mock("@/settings/CodingPlanUpgradeDialogProvider.js", () => ({
  57. useOptionalCodingPlanUpgradeDialog: () => ({ inventory: useCodingPlanEntryPlanList() }),
  58. }));
  59. vi.mock("@/i18n/IntlProvider.js", () => ({
  60. useZCodeIntl: () => ({ intl: { formatMessage: ({ id }: { id: string }) => id } }),
  61. }));
  62. import { CodingPlanEntryButton } from "@/settings/CodingPlanEntryButton.js";
  63. afterEach(() => {
  64. cleanup();
  65. vi.clearAllMocks();
  66. h.readError = false;
  67. });
  68. function setProviders(ids: string[]) {
  69. h.view = {
  70. revision: h.view.revision + 1,
  71. providerOrder: [],
  72. addableProviders: [],
  73. providers: ids.map((providerId) => ({
  74. providerId,
  75. enabled: false,
  76. executable: false,
  77. issues: [],
  78. models: [],
  79. effectiveConfig: {
  80. access: {
  81. type: "zhipu-account",
  82. accountType: "bigmodel",
  83. mode: providerId.includes("start-plan") ? "start-plan" : "individual-coding-plan",
  84. entitled: true,
  85. },
  86. builtinModelIds: [],
  87. },
  88. })),
  89. };
  90. }
  91. it("includes disabled owned connections and authenticated teams; drops team data after account change", async () => {
  92. setProviders([ids.bigmodelIndividualCodingPlan, ids.bigmodelStartPlan]);
  93. h.entitlements = Object.fromEntries(
  94. h.view.providers.map(({ providerId: id }) => [
  95. id,
  96. {
  97. snapshot: {
  98. authenticated: true,
  99. provider: { id },
  100. subscription: {
  101. details: [
  102. {
  103. productId: id === ids.bigmodelStartPlan ? "start-v3" : "lite",
  104. productName: "",
  105. expireTime: null,
  106. },
  107. ],
  108. },
  109. },
  110. },
  111. ]),
  112. );
  113. h.load.mockResolvedValue("token");
  114. h.pricing.mockResolvedValue({
  115. productList: [{ subscribed: true, tier: "PRO", productId: "team-pro" }],
  116. });
  117. const view = renderHook(() => useCodingPlanEntryPlanList());
  118. await waitFor(() =>
  119. expect(view.result.current.entryPlanList).toBe(
  120. "coding_plan__personal_lite,coding_plan__team_pro,start_plan__start_v3",
  121. ),
  122. );
  123. expect(h.entitlementsHook).toHaveBeenCalledWith({
  124. providerSettingsView: h.view,
  125. suppressProviderFingerprintAutoRefresh: true,
  126. });
  127. expect(h.pricing).toHaveBeenCalledWith({ authenticated: true, family: "bigmodel" });
  128. expect(h.pricing).toHaveBeenCalledWith({ authenticated: true, family: "zai" });
  129. h.user = { id: "second" };
  130. h.load.mockResolvedValue(null);
  131. view.rerender();
  132. expect(view.result.current.status).toBe("loading");
  133. await waitFor(() => expect(h.load).toHaveBeenCalledTimes(4));
  134. });
  135. it("waits for slow team queries and exposes retry after a failed query", async () => {
  136. setProviders([]);
  137. h.entitlements = {};
  138. h.load.mockResolvedValue("token");
  139. let rejectQuery!: (reason: Error) => void;
  140. h.pricing.mockImplementation(
  141. () =>
  142. new Promise((_resolve, reject) => {
  143. rejectQuery = reject;
  144. }),
  145. );
  146. // 两个 family 中仅 bigmodel 登录,避免测试悬挂的另一条请求。
  147. h.load.mockImplementation(async (key: string) => (key.includes("bigmodel") ? "token" : null));
  148. const view = renderHook(() => useCodingPlanEntryPlanList());
  149. expect(view.result.current.status).toBe("loading");
  150. await waitFor(() => expect(h.pricing).toHaveBeenCalledTimes(1));
  151. expect(view.result.current.status).toBe("loading");
  152. await act(async () => {
  153. rejectQuery(new Error("offline"));
  154. });
  155. await waitFor(() => expect(view.result.current.status).toBe("error"));
  156. h.pricing.mockResolvedValue({ productList: [] });
  157. act(() => view.result.current.retry());
  158. expect(view.result.current.status).toBe("loading");
  159. await waitFor(() => expect(view.result.current.status).toBe("ready"));
  160. expect(view.result.current.entryPlanList).toBe("");
  161. });
  162. it("does not treat a missing configured entitlement as successful empty inventory", async () => {
  163. setProviders([ids.bigmodelIndividualCodingPlan]);
  164. h.entitlements = {
  165. [ids.bigmodelIndividualCodingPlan]: { snapshot: null, loading: false, error: "offline" },
  166. };
  167. h.load.mockResolvedValue(null);
  168. const view = renderHook(() => useCodingPlanEntryPlanList());
  169. await waitFor(() => expect(view.result.current.status).toBe("error"));
  170. h.entitlements = {
  171. [ids.bigmodelIndividualCodingPlan]: {
  172. snapshot: { unavailableReason: "no_plan" },
  173. loading: false,
  174. error: null,
  175. },
  176. };
  177. view.rerender();
  178. expect(view.result.current.status).toBe("ready");
  179. });
  180. it("does not expose empty success when Settings failed; retry reloads the shared view", async () => {
  181. h.readError = true;
  182. const view = renderHook(() => useCodingPlanEntryPlanList());
  183. expect(view.result.current.status).toBe("error");
  184. expect(h.pricing).not.toHaveBeenCalled();
  185. act(() => view.result.current.retry());
  186. expect(h.reload).toHaveBeenCalledOnce();
  187. });
  188. it("uses valid personal and Start snapshots during refresh and after failure", async () => {
  189. setProviders([ids.bigmodelIndividualCodingPlan, ids.bigmodelStartPlan]);
  190. h.load.mockResolvedValue(null);
  191. h.entitlements = Object.fromEntries(
  192. h.view.providers.map(({ providerId }) => [
  193. providerId,
  194. {
  195. snapshot: {
  196. authenticated: true,
  197. provider: { id: providerId },
  198. subscription: { details: [{ productId: "lite", productName: "", expireTime: null }] },
  199. },
  200. loading: true,
  201. error: "offline",
  202. },
  203. ]),
  204. );
  205. const view = renderHook(() => useCodingPlanEntryPlanList());
  206. await waitFor(() => expect(view.result.current.status).toBe("ready"));
  207. expect(view.result.current.entryPlanList).toContain("coding_plan__personal_lite");
  208. });
  209. it("keeps a confirmed no_plan despite a later refresh error", async () => {
  210. setProviders([ids.bigmodelIndividualCodingPlan]);
  211. h.load.mockResolvedValue(null);
  212. h.entitlements = {
  213. [ids.bigmodelIndividualCodingPlan]: {
  214. snapshot: { unavailableReason: "no_plan" },
  215. error: "offline",
  216. },
  217. };
  218. const view = renderHook(() => useCodingPlanEntryPlanList());
  219. await waitFor(() => expect(view.result.current.status).toBe("ready"));
  220. expect(view.result.current.entryPlanList).toBe("");
  221. });
  222. it("retains team results on failure, replaces them on success, and isolates changed credentials", async () => {
  223. setProviders([]);
  224. h.entitlements = {};
  225. h.load.mockImplementation(async (key: string) => (key.includes("bigmodel") ? "token-a" : null));
  226. h.pricing.mockResolvedValue({
  227. productList: [{ subscribed: true, tier: "PRO", productId: "team-pro" }],
  228. });
  229. const view = renderHook(() => useCodingPlanEntryPlanList());
  230. await waitFor(() => expect(view.result.current.entryPlanList).toBe("coding_plan__team_pro"));
  231. h.pricing.mockRejectedValue(new Error("offline"));
  232. await act(async () => view.result.current.retry());
  233. expect(view.result.current.status).toBe("ready");
  234. expect(view.result.current.entryPlanList).toBe("coding_plan__team_pro");
  235. h.pricing.mockResolvedValue({ productList: [] });
  236. await act(async () => view.result.current.retry());
  237. expect(view.result.current.entryPlanList).toBe("");
  238. h.pricing.mockRejectedValue(new Error("offline"));
  239. await act(async () => view.result.current.retry());
  240. expect(view.result.current.status).toBe("ready");
  241. h.load.mockImplementation(async (key: string) => (key.includes("bigmodel") ? "token-b" : null));
  242. await act(async () => view.result.current.retry());
  243. expect(view.result.current.status).toBe("error");
  244. });
  245. it("retains team data across a view refresh but never across account changes", async () => {
  246. setProviders([]);
  247. h.entitlements = {};
  248. h.load.mockResolvedValue("token");
  249. h.pricing.mockResolvedValue({
  250. productList: [{ subscribed: true, tier: "PRO", productId: "team-pro" }],
  251. });
  252. const view = renderHook(() => useCodingPlanEntryPlanList());
  253. await waitFor(() => expect(view.result.current.entryPlanList).toBe("coding_plan__team_pro"));
  254. h.pricing.mockRejectedValue(new Error("offline"));
  255. setProviders([]);
  256. await act(async () => view.rerender());
  257. expect(view.result.current.status).toBe("ready");
  258. h.user = { id: "new-account" };
  259. view.rerender();
  260. expect(view.result.current.entryPlanList).toBe("");
  261. await waitFor(() => expect(view.result.current.status).toBe("error"));
  262. });
  263. it("allows the purchase button to open with a successful snapshot and a refresh error", async () => {
  264. setProviders([ids.bigmodelIndividualCodingPlan]);
  265. h.load.mockResolvedValue(null);
  266. h.entitlements = {
  267. [ids.bigmodelIndividualCodingPlan]: {
  268. snapshot: { authenticated: true, unavailableReason: "no_plan" },
  269. error: "HTTP 429",
  270. loading: false,
  271. },
  272. };
  273. const purchase = vi.fn();
  274. render(createElement(CodingPlanEntryButton, { onClick: purchase }, "Upgrade"));
  275. await waitFor(() => expect(screen.getByRole("button").textContent).toBe("Upgrade"));
  276. fireEvent.click(screen.getByRole("button"));
  277. expect(purchase).toHaveBeenCalledOnce();
  278. });
  279. it("does not accept an unavailable snapshot as a successful empty result", async () => {
  280. setProviders([ids.bigmodelIndividualCodingPlan]);
  281. h.load.mockResolvedValue(null);
  282. h.entitlements = {
  283. [ids.bigmodelIndividualCodingPlan]: {
  284. snapshot: { authenticated: true, unavailableReason: "unavailable" },
  285. loading: false,
  286. },
  287. };
  288. const view = renderHook(() => useCodingPlanEntryPlanList());
  289. await waitFor(() => expect(view.result.current.status).toBe("error"));
  290. });
  291. it("ignores an old account's pending team response after switching accounts", async () => {
  292. setProviders([]);
  293. h.entitlements = {};
  294. h.load.mockImplementation(async (key: string) => (key.includes("bigmodel") ? "token" : null));
  295. let finish!: (value: unknown) => void;
  296. h.pricing.mockImplementationOnce(
  297. () =>
  298. new Promise((resolve) => {
  299. finish = resolve;
  300. }),
  301. );
  302. const view = renderHook(() => useCodingPlanEntryPlanList());
  303. await waitFor(() => expect(h.pricing).toHaveBeenCalledOnce());
  304. h.user = { id: "switched-while-pending" };
  305. h.load.mockResolvedValue(null);
  306. view.rerender();
  307. await waitFor(() => expect(view.result.current.status).toBe("ready"));
  308. await act(async () =>
  309. finish({ productList: [{ subscribed: true, tier: "PRO", productId: "team-pro" }] }),
  310. );
  311. expect(view.result.current.entryPlanList).toBe("");
  312. });