useUsageEntitlement.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import { BigModelUsageQuotaProvider } from "../../services/src/usage-stats/providers/bigmodelUsageQuotaProvider.js";
  2. import type { ReactElement } from "react";
  3. import type { Root } from "react-dom/client";
  4. import type { UsageEntitlementSnapshot, ZCodeAccountAccess } from "@zcode/shared";
  5. import { readCachedUsageEntitlementSnapshot } from "@/lib/usageEntitlementCache.js";
  6. import {
  7. buildEntitlementFreshnessKey,
  8. hasSharedEntitlementFailure,
  9. shouldDeferSharedEntitlementRefresh,
  10. readSharedEntitlementSnapshot,
  11. } from "@/lib/usageEntitlementRefreshPolicy.js";
  12. import type { IUsageStatsService, IServiceAccessor } from "@zcode/services";
  13. import { act, createElement } from "react";
  14. import { createRoot } from "react-dom/client";
  15. import { afterEach, describe, expect, it, vi } from "vitest";
  16. import {
  17. useUsageEntitlement,
  18. useUsageEntitlementWithService,
  19. withUsageEntitlementTimeout,
  20. } from "@/hooks/useUsageEntitlement.js";
  21. import { ServiceProvider } from "@/hooks/useServices.js";
  22. import {
  23. registerBaseWorkspaceServices,
  24. useRemoteWorkspaceSessionStore,
  25. } from "@/store/remoteWorkspaceSessionStore.js";
  26. function createMinimalElement(ownerDocument?: Document, tagName = "div"): Element {
  27. const element = {
  28. appendChild: (child: { parentNode?: unknown }) => {
  29. child.parentNode = element;
  30. return child;
  31. },
  32. childNodes: [] as unknown[],
  33. addEventListener: () => {},
  34. getAttribute: () => null,
  35. insertBefore: (child: { parentNode?: unknown }) => {
  36. child.parentNode = element;
  37. return child;
  38. },
  39. nodeName: tagName.toUpperCase(),
  40. nodeType: 1,
  41. ownerDocument,
  42. parentNode: null as unknown,
  43. removeAttribute: () => {},
  44. removeChild: (child: { parentNode?: unknown }) => {
  45. child.parentNode = null;
  46. return child;
  47. },
  48. removeEventListener: () => {},
  49. setAttribute: () => {},
  50. style: {},
  51. tagName: tagName.toUpperCase(),
  52. };
  53. return element as unknown as Element;
  54. }
  55. function installMinimalDom() {
  56. const storage = new Map<string, string>();
  57. const documentMock = {
  58. addEventListener: () => {},
  59. createElement: (tagName: string) =>
  60. createMinimalElement(documentMock as unknown as Document, tagName),
  61. createTextNode: (nodeValue: string) => ({
  62. nodeType: 3,
  63. nodeValue,
  64. ownerDocument: documentMock,
  65. parentNode: null,
  66. }),
  67. nodeType: 9,
  68. removeEventListener: () => {},
  69. visibilityState: "visible",
  70. } as unknown as Document;
  71. const windowMock = {
  72. addEventListener: () => {},
  73. clearInterval,
  74. clearTimeout,
  75. document: documentMock,
  76. HTMLIFrameElement: function HTMLIFrameElement() {},
  77. HTMLElement: function HTMLElement() {},
  78. localStorage: {
  79. getItem: (key: string) => storage.get(key) ?? null,
  80. removeItem: (key: string) => {
  81. storage.delete(key);
  82. },
  83. setItem: (key: string, value: string) => {
  84. storage.set(key, value);
  85. },
  86. },
  87. Node: function Node() {},
  88. removeEventListener: () => {},
  89. setInterval,
  90. setTimeout,
  91. };
  92. Object.defineProperty(globalThis, "document", {
  93. configurable: true,
  94. value: documentMock,
  95. });
  96. Object.defineProperty(globalThis, "window", {
  97. configurable: true,
  98. value: windowMock,
  99. });
  100. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  101. configurable: true,
  102. value: true,
  103. });
  104. return createMinimalElement(documentMock);
  105. }
  106. function createSnapshot(params: {
  107. organizationId: string;
  108. projectId: string;
  109. }): UsageEntitlementSnapshot {
  110. return {
  111. generatedAt: Date.now(),
  112. authenticated: true,
  113. context: {
  114. scope: "team",
  115. organizationId: params.organizationId,
  116. projectId: params.projectId,
  117. },
  118. provider: {
  119. id: "account:bigmodel-individual-coding-plan",
  120. name: "BigModel Coding Plan",
  121. },
  122. remaining: {
  123. count: params.projectId === "proj-a" ? 10 : 20,
  124. isShow: true,
  125. },
  126. subscription: null,
  127. quota: {
  128. level: null,
  129. limits: [],
  130. },
  131. };
  132. }
  133. function flushPromises() {
  134. return new Promise<void>((resolve) => {
  135. setTimeout(resolve, 0);
  136. });
  137. }
  138. afterEach(() => {
  139. vi.restoreAllMocks();
  140. });
  141. describe("useUsageEntitlement timeout", () => {
  142. it("权益查询长时间不返回时进入失败路径", async () => {
  143. vi.useFakeTimers();
  144. try {
  145. const request = new Promise<string>(() => {});
  146. const result = withUsageEntitlementTimeout(request, 5);
  147. const assertion = expect(result).rejects.toThrow("usage_entitlement_request_timeout:5");
  148. await vi.advanceTimersByTimeAsync(5);
  149. await assertion;
  150. } finally {
  151. vi.useRealTimers();
  152. }
  153. });
  154. it("权益查询正常返回时清理超时计时器", async () => {
  155. vi.useFakeTimers();
  156. try {
  157. await expect(withUsageEntitlementTimeout(Promise.resolve("ok"), 5)).resolves.toBe("ok");
  158. expect(vi.getTimerCount()).toBe(0);
  159. } finally {
  160. vi.useRealTimers();
  161. }
  162. });
  163. });
  164. describe("useUsageEntitlement team context refresh", () => {
  165. it("远端 workspace 等待 services 时权益查询仍走 app-global base host", async () => {
  166. const baseGetEntitlementSnapshot = vi.fn(async () =>
  167. createSnapshot({ organizationId: "org-base", projectId: "proj-base" }),
  168. );
  169. const remoteGetEntitlementSnapshot = vi.fn(async () =>
  170. createSnapshot({ organizationId: "org-remote", projectId: "proj-remote" }),
  171. );
  172. const baseServices = {
  173. usageStatsService: { getEntitlementSnapshot: baseGetEntitlementSnapshot },
  174. } as unknown as IServiceAccessor;
  175. const remoteContextServices = {
  176. usageStatsService: { getEntitlementSnapshot: remoteGetEntitlementSnapshot },
  177. } as unknown as IServiceAccessor;
  178. registerBaseWorkspaceServices(baseServices);
  179. function Probe() {
  180. useUsageEntitlement({
  181. enabled: true,
  182. preferredProviderId: "account:bigmodel-individual-coding-plan",
  183. cacheKey: "base-host-routing",
  184. refreshOnMount: true,
  185. });
  186. return null;
  187. }
  188. const root: Root = createRoot(installMinimalDom());
  189. try {
  190. await act(async () => {
  191. root.render(
  192. createElement(ServiceProvider, { services: remoteContextServices }, createElement(Probe)),
  193. );
  194. await flushPromises();
  195. });
  196. } finally {
  197. await act(async () => {
  198. root.unmount();
  199. });
  200. useRemoteWorkspaceSessionStore.setState({ baseServices: null });
  201. }
  202. expect(baseGetEntitlementSnapshot).toHaveBeenCalledTimes(1);
  203. expect(remoteGetEntitlementSnapshot).not.toHaveBeenCalled();
  204. });
  205. it("Team Plan freshness key 变化后会重新请求新团队权益", async () => {
  206. const calls: Array<{ organizationId?: string | null; projectId?: string | null }> = [];
  207. const usageStatsService = {
  208. getEntitlementSnapshot: vi.fn(async (request) => {
  209. calls.push({
  210. organizationId: request.accountAccess?.organizationId,
  211. projectId: request.accountAccess?.projectId,
  212. });
  213. return createSnapshot({
  214. organizationId: request.accountAccess?.organizationId ?? "",
  215. projectId: request.accountAccess?.projectId ?? "",
  216. });
  217. }),
  218. };
  219. const services = {
  220. usageStatsService,
  221. } as unknown as IServiceAccessor;
  222. const accountAccessByProject = new Map<string, ZCodeAccountAccess>();
  223. function getTeamAccess(organizationId: string, projectId: string): ZCodeAccountAccess {
  224. const key = `${organizationId}:${projectId}`;
  225. const existing = accountAccessByProject.get(key);
  226. if (existing) return existing;
  227. const access: ZCodeAccountAccess = {
  228. type: "zhipu-account",
  229. family: "bigmodel",
  230. planKind: "team-coding-plan",
  231. productId: "product-team",
  232. organizationId,
  233. projectId,
  234. };
  235. accountAccessByProject.set(key, access);
  236. return access;
  237. }
  238. function Probe(props: { organizationId: string; projectId: string }) {
  239. useUsageEntitlement({
  240. enabled: true,
  241. preferredProviderId: "account:bigmodel-team-coding-plan",
  242. accountAccess: getTeamAccess(props.organizationId, props.projectId),
  243. allowDisabledPreferredProvider: true,
  244. requirePreferredProvider: true,
  245. allowEnvApiKey: false,
  246. cacheKey: `team:${props.organizationId}:${props.projectId}`,
  247. refreshOnMount: true,
  248. });
  249. return null;
  250. }
  251. function renderProbe(props: { organizationId: string; projectId: string }): ReactElement {
  252. return createElement(ServiceProvider, { services }, createElement(Probe, props));
  253. }
  254. const root: Root = createRoot(installMinimalDom());
  255. try {
  256. await act(async () => {
  257. root.render(renderProbe({ organizationId: "org-a", projectId: "proj-a" }));
  258. await flushPromises();
  259. });
  260. await act(async () => {
  261. root.render(renderProbe({ organizationId: "org-b", projectId: "proj-b" }));
  262. await flushPromises();
  263. });
  264. } finally {
  265. await act(async () => {
  266. root.unmount();
  267. });
  268. }
  269. expect(calls).toEqual([
  270. { organizationId: "org-a", projectId: "proj-a" },
  271. { organizationId: "org-b", projectId: "proj-b" },
  272. ]);
  273. });
  274. });
  275. describe("刷新失败保留已确认订阅", () => {
  276. it.each(["personal", "team"] as const)(
  277. "%s 真实订阅服务失败保留快照和退避,明确无套餐才清除",
  278. async (scope) => {
  279. let mode: "active" | "failure" | "unknown" | "none" = "active";
  280. const accountAccess: ZCodeAccountAccess =
  281. scope === "team"
  282. ? {
  283. type: "zhipu-account",
  284. family: "bigmodel",
  285. planKind: "team-coding-plan",
  286. organizationId: "org",
  287. projectId: "project",
  288. }
  289. : { type: "zhipu-account", family: "bigmodel", planKind: "individual-coding-plan" };
  290. const providerId = `account:bigmodel-${scope === "team" ? "team" : "individual"}-coding-plan`;
  291. const provider = new BigModelUsageQuotaProvider({
  292. env: { ZCODE_ENV: "production" },
  293. credentialService: { load: async () => "business" },
  294. accountRequestAuthService: {
  295. resolveAccessCurrent: vi.fn(),
  296. resolveCurrent: vi.fn(async () => ({ apiKey: "personal.secret" })),
  297. assertCurrent: vi.fn(),
  298. },
  299. apiClient: {
  300. request: vi.fn(async (url) => {
  301. if (mode === "failure") throw new Error("network offline");
  302. const subscription =
  303. String(url).includes("subscription/list") ||
  304. String(url).includes("querySubscribeDetail");
  305. // quota 始终失败,确认有效订阅仍可独立展示。
  306. if (!subscription) throw new Error("quota offline");
  307. const data =
  308. mode === "unknown"
  309. ? { invalid: true }
  310. : scope === "team"
  311. ? {
  312. hasSubscription: mode !== "none",
  313. status: "EFFECTIVE",
  314. memberGrantStatus: "VALID",
  315. productId: "coding",
  316. productName: "Team Coding",
  317. }
  318. : mode === "none"
  319. ? []
  320. : [
  321. {
  322. productId: "coding",
  323. productName: "GLM Coding Lite",
  324. status: "VALID",
  325. inCurrentPeriod: true,
  326. },
  327. ];
  328. return new Response(JSON.stringify({ success: true, data }));
  329. }),
  330. },
  331. });
  332. const getEntitlementSnapshot = vi.fn(() =>
  333. provider.getSnapshotForRequest({ preferredProviderId: providerId, accountAccess }),
  334. );
  335. const usageStatsService = { getEntitlementSnapshot } as unknown as IUsageStatsService;
  336. const cacheKey = `service-failure-${scope}`;
  337. const freshnessKey = buildEntitlementFreshnessKey({
  338. cacheKey,
  339. options: {
  340. includeSubscription: false,
  341. preferredProviderId: providerId,
  342. accountAccess,
  343. allowDisabledPreferredProvider: false,
  344. requirePreferredProvider: false,
  345. },
  346. });
  347. let state!: ReturnType<typeof useUsageEntitlementWithService>;
  348. function Probe() {
  349. state = useUsageEntitlementWithService(usageStatsService, {
  350. enabled: true,
  351. cacheKey,
  352. preferredProviderId: providerId,
  353. accountAccess,
  354. refreshOnMount: true,
  355. });
  356. return null;
  357. }
  358. const root = createRoot(installMinimalDom());
  359. try {
  360. await act(async () => {
  361. root.render(createElement(Probe));
  362. await flushPromises();
  363. });
  364. const confirmed = state.snapshot;
  365. expect(confirmed?.subscription?.details[0]?.productId).toBe("coding");
  366. for (const failure of ["failure", "unknown"] as const) {
  367. mode = failure;
  368. await act(async () => {
  369. await state.refresh({ force: true, reason: "manual" });
  370. });
  371. expect(state.snapshot).toEqual(confirmed);
  372. expect(state.error).toBeTruthy();
  373. expect(readCachedUsageEntitlementSnapshot({ cacheKey })).toEqual(confirmed);
  374. expect(hasSharedEntitlementFailure({ usageStatsService, freshnessKey })).toBe(true);
  375. expect(
  376. shouldDeferSharedEntitlementRefresh({
  377. usageStatsService,
  378. freshnessKey,
  379. now: Date.now(),
  380. }),
  381. ).toBe(true);
  382. }
  383. mode = "none";
  384. await act(async () => {
  385. await state.refresh({ force: true, reason: "manual" });
  386. });
  387. expect(state.error).toBeNull();
  388. expect(state.snapshot?.subscription).toBeNull();
  389. expect(state.snapshot?.unavailableReason).toBe("no_plan");
  390. expect(readCachedUsageEntitlementSnapshot({ cacheKey })?.subscription).toBeNull();
  391. expect(hasSharedEntitlementFailure({ usageStatsService, freshnessKey })).toBe(false);
  392. } finally {
  393. await act(async () => root.unmount());
  394. }
  395. },
  396. );
  397. it("手动刷新遇到 429 保留同一身份的套餐,并暴露错误;购买刷新传递失效标记", async () => {
  398. const snapshot = createSnapshot({ organizationId: "org", projectId: "project" });
  399. snapshot.subscription = {
  400. identityType: "unknown",
  401. identityMasked: null,
  402. details: [{ productId: "start", productName: "Start Plan" }],
  403. };
  404. const getEntitlementSnapshot = vi
  405. .fn()
  406. .mockResolvedValueOnce(snapshot)
  407. .mockRejectedValueOnce(new Error("HTTP 429"))
  408. .mockResolvedValue(snapshot);
  409. const services = {
  410. usageStatsService: { getEntitlementSnapshot },
  411. } as unknown as IServiceAccessor;
  412. registerBaseWorkspaceServices(services);
  413. let state!: ReturnType<typeof useUsageEntitlement>;
  414. function Probe() {
  415. state = useUsageEntitlement({
  416. enabled: true,
  417. cacheKey: "keep-confirmed-subscription",
  418. preferredProviderId: "account:bigmodel-start-plan",
  419. refreshOnMount: true,
  420. });
  421. return null;
  422. }
  423. const root = createRoot(installMinimalDom());
  424. try {
  425. await act(async () => {
  426. root.render(createElement(ServiceProvider, { services }, createElement(Probe)));
  427. await flushPromises();
  428. });
  429. await act(async () => {
  430. await state.refresh({ force: true, reason: "manual" });
  431. });
  432. expect(state.snapshot).toBe(snapshot);
  433. expect(state.error).toBe("HTTP 429");
  434. await act(async () => {
  435. await state.refresh({ force: true, reason: "purchase" });
  436. });
  437. expect(getEntitlementSnapshot.mock.lastCall?.[0]).toMatchObject({
  438. invalidateBalanceCache: true,
  439. });
  440. } finally {
  441. await act(async () => root.unmount());
  442. useRemoteWorkspaceSessionStore.setState({ baseServices: null });
  443. }
  444. });
  445. });
  446. describe("跨组件购买刷新代次", () => {
  447. it.each(["success", "failure"])("购买成功后忽略旧请求的 %s,隔离其他身份", async (outcome) => {
  448. const pending: Array<{
  449. resolve: (s: UsageEntitlementSnapshot) => void;
  450. reject: (e: Error) => void;
  451. }> = [];
  452. const service = {
  453. getEntitlementSnapshot: vi.fn(
  454. () =>
  455. new Promise<UsageEntitlementSnapshot>((resolve, reject) =>
  456. pending.push({ resolve, reject }),
  457. ),
  458. ),
  459. } as unknown as IUsageStatsService;
  460. const states: Array<ReturnType<typeof useUsageEntitlementWithService>> = [];
  461. const requestOptions = {
  462. includeSubscription: false,
  463. preferredProviderId: "account:bigmodel-start-plan",
  464. allowDisabledPreferredProvider: false,
  465. requirePreferredProvider: false,
  466. };
  467. const cacheKey = "purchase-generation";
  468. const freshnessKey = buildEntitlementFreshnessKey({ cacheKey, options: requestOptions });
  469. function Probe({ index }: { index: number }) {
  470. states[index] = useUsageEntitlementWithService(service, {
  471. ...requestOptions,
  472. preferredProviderId: index === 2 ? "other-provider" : requestOptions.preferredProviderId,
  473. cacheKey: index === 2 ? "other-identity" : cacheKey,
  474. });
  475. return null;
  476. }
  477. const root = createRoot(installMinimalDom());
  478. const fresh = createSnapshot({ organizationId: "org", projectId: "new" });
  479. fresh.subscription = {
  480. identityType: "unknown",
  481. identityMasked: null,
  482. details: [{ productId: "start", productName: "Start Plan" }],
  483. };
  484. const old = createSnapshot({ organizationId: "org", projectId: "old" });
  485. const other = createSnapshot({ organizationId: "other", projectId: "other" });
  486. try {
  487. await act(async () => {
  488. root.render(
  489. createElement(
  490. "div",
  491. null,
  492. ...[0, 1, 2].map((index) => createElement(Probe, { index, key: index })),
  493. ),
  494. );
  495. });
  496. let oldRequest!: Promise<void>;
  497. let otherRequest!: Promise<void>;
  498. let purchase!: Promise<void>;
  499. await act(async () => {
  500. oldRequest = states[0]!.refresh();
  501. otherRequest = states[2]!.refresh();
  502. });
  503. expect(pending).toHaveLength(2);
  504. await act(async () => {
  505. purchase = states[1]!.refresh({ reason: "purchase", force: true });
  506. });
  507. await act(async () => {
  508. pending[2]!.resolve(fresh);
  509. await purchase;
  510. });
  511. // 购买后的普通刷新也不能重新加入仍未完成的旧代次请求。
  512. let followUp!: Promise<void>;
  513. await act(async () => {
  514. followUp = states[1]!.refresh();
  515. });
  516. expect(pending).toHaveLength(4);
  517. await act(async () => {
  518. pending[3]!.resolve(fresh);
  519. await followUp;
  520. });
  521. await act(async () => {
  522. if (outcome === "success") pending[0]!.resolve(old);
  523. else pending[0]!.reject(new Error("old HTTP 429"));
  524. pending[1]!.resolve(other);
  525. await Promise.all([oldRequest, otherRequest]);
  526. });
  527. for (const state of states.slice(0, 2)) {
  528. expect(state.snapshot).toEqual(fresh);
  529. expect(state.error).toBeNull();
  530. expect(state.loading).toBe(false);
  531. }
  532. expect(states[2]!.snapshot).toEqual(other);
  533. expect(readCachedUsageEntitlementSnapshot({ cacheKey })).toEqual(fresh);
  534. expect(readSharedEntitlementSnapshot({ usageStatsService: service, freshnessKey })).toEqual(
  535. fresh,
  536. );
  537. expect(hasSharedEntitlementFailure({ usageStatsService: service, freshnessKey })).toBe(false);
  538. } finally {
  539. await act(async () => root.unmount());
  540. }
  541. });
  542. });