startPlanContextBalanceRefresh.test.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // @vitest-environment jsdom
  2. // 修复原因:Start Plan 今日余额原先没有 hover 刷新入口(onAccess 只挂在 Coding Plan 配置上,
  3. // 两段互斥导致 start plan 用户 hover 时整条刷新链路不触发),也没有跟随 hover promise 的
  4. // loading 反馈。本文件锁定补齐后的三条语义:hover 触发、refreshing spinner、触发器兜底。
  5. import { createElement, type ComponentProps } from "react";
  6. import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
  7. import { afterEach, describe, expect, it, vi } from "vitest";
  8. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  9. import {
  10. ChatStartPlanBalancePanel,
  11. hasChatStartPlanBalance,
  12. } from "../src/chat-input-toolbar/StartPlanContextBalance.js";
  13. import { ChatContextUsage } from "../src/chat-input-toolbar/contextUsage.js";
  14. import { renderToStaticMarkup } from "react-dom/server";
  15. vi.mock("../src/i18n/IntlProvider.js", () => ({
  16. useZCodeIntl: () => ({
  17. locale: "en-US",
  18. intl: {
  19. formatMessage: ({ id }: { id: string }) => id,
  20. },
  21. }),
  22. }));
  23. vi.mock("../src/CodingPlanBillingDiscount.js", () => ({
  24. CodingPlanBillingDiscountBadgePill: () => "billing-discount-badge",
  25. CodingPlanBillingDiscountInfoDialog: () => "billing-discount-info",
  26. useCodingPlanBillingDiscount: () => ({ active: false, loading: false }),
  27. }));
  28. vi.mock("@/components/ai-elements/context.js", async () => {
  29. const React = await import("react");
  30. const passthrough =
  31. (tag: "button" | "div") =>
  32. ({ children, ...props }: { children?: React.ReactNode }) =>
  33. React.createElement(tag, props, children);
  34. return {
  35. Context: ({
  36. children,
  37. onOpenChange,
  38. }: {
  39. children?: React.ReactNode;
  40. onOpenChange?: (open: boolean) => void;
  41. }) =>
  42. React.createElement("div", {}, [
  43. React.createElement(
  44. "button",
  45. {
  46. key: "open",
  47. "data-testid": "context-open",
  48. onClick: () => onOpenChange?.(true),
  49. },
  50. "open",
  51. ),
  52. React.createElement(
  53. "button",
  54. {
  55. key: "close",
  56. "data-testid": "context-close",
  57. onClick: () => onOpenChange?.(false),
  58. },
  59. "close",
  60. ),
  61. React.createElement(React.Fragment, { key: "children" }, children),
  62. ]),
  63. ContextContent: passthrough("div"),
  64. ContextContentBody: passthrough("div"),
  65. ContextTrigger: passthrough("button"),
  66. };
  67. });
  68. afterEach(() => {
  69. cleanup();
  70. });
  71. function createStartPlanSnapshot(): NonNullable<
  72. ComponentProps<typeof ChatStartPlanBalancePanel>["config"]["snapshot"]
  73. > {
  74. return {
  75. generatedAt: 1,
  76. authenticated: true,
  77. provider: {
  78. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  79. name: "Z.ai Start Plan",
  80. },
  81. remaining: null,
  82. subscription: null,
  83. quota: {
  84. level: "Start",
  85. limits: [
  86. {
  87. type: "TOKENS_LIMIT",
  88. number: 1_000_000,
  89. remaining: 750_000,
  90. usageDetails: [
  91. {
  92. modelCode: "glm-5.2",
  93. displayName: "GLM-5.2",
  94. usage: 250_000,
  95. },
  96. ],
  97. },
  98. ],
  99. },
  100. };
  101. }
  102. function createIntl(): ComponentProps<typeof ChatContextUsage>["intl"] {
  103. return {
  104. formatMessage: ({ id }: { id: string }) => id,
  105. } as never;
  106. }
  107. describe("hasChatStartPlanBalance hover 入口兜底", () => {
  108. it("无缓存快照且未 loading 时,onAccess 存在仍保留触发器", () => {
  109. expect(hasChatStartPlanBalance({ loading: false, snapshot: null })).toBe(false);
  110. expect(
  111. hasChatStartPlanBalance({
  112. loading: false,
  113. snapshot: null,
  114. onAccess: vi.fn(),
  115. }),
  116. ).toBe(true);
  117. });
  118. });
  119. describe("ChatStartPlanBalancePanel refreshing spinner", () => {
  120. const baseProps = {
  121. intl: createIntl(),
  122. locale: "en-US",
  123. } satisfies Partial<ComponentProps<typeof ChatStartPlanBalancePanel>>;
  124. it("静默 hover 刷新(refreshing)时即使 loading=false 也显示 spinner", () => {
  125. const html = renderToStaticMarkup(
  126. createElement(ChatStartPlanBalancePanel, {
  127. ...baseProps,
  128. config: {
  129. loading: false,
  130. refreshing: true,
  131. snapshot: createStartPlanSnapshot(),
  132. },
  133. }),
  134. );
  135. expect(html).toContain("settings.modelProvider.startPlan.balance.title");
  136. expect(html).toContain("animate-spin");
  137. });
  138. it("无刷新进行中时不显示 spinner", () => {
  139. const html = renderToStaticMarkup(
  140. createElement(ChatStartPlanBalancePanel, {
  141. ...baseProps,
  142. config: {
  143. loading: false,
  144. snapshot: createStartPlanSnapshot(),
  145. },
  146. }),
  147. );
  148. expect(html).not.toContain("animate-spin");
  149. });
  150. });
  151. describe("ChatContextUsage start plan hover 刷新", () => {
  152. it("只有 startPlanBalance.onAccess 时 hover 打开触发一次静默刷新,关闭不触发", async () => {
  153. let resolveAccess!: () => void;
  154. const onAccess = vi.fn(
  155. () =>
  156. new Promise<void>((resolve) => {
  157. resolveAccess = resolve;
  158. }),
  159. );
  160. render(
  161. createElement(ChatContextUsage, {
  162. startPlanBalance: {
  163. loading: false,
  164. onAccess,
  165. snapshot: createStartPlanSnapshot(),
  166. },
  167. intl: createIntl(),
  168. locale: "en-US",
  169. selectedProvider: "glm",
  170. taskUsage: null,
  171. }),
  172. );
  173. expect(document.querySelector(".animate-spin")).toBeNull();
  174. fireEvent.click(screen.getByTestId("context-open"));
  175. expect(onAccess).toHaveBeenCalledTimes(1);
  176. // hover 触发的静默刷新进行中:spinner 跟随本次 promise,而不是 entitlement.loading。
  177. expect(document.querySelector(".animate-spin")).not.toBeNull();
  178. await act(async () => {
  179. resolveAccess();
  180. });
  181. expect(document.querySelector(".animate-spin")).toBeNull();
  182. fireEvent.click(screen.getByTestId("context-close"));
  183. expect(onAccess).toHaveBeenCalledTimes(1);
  184. });
  185. it("Coding Plan 与 Start Plan 同时提供 onAccess 时互斥只触发 Coding Plan 一侧", () => {
  186. const codingPlanOnAccess = vi.fn();
  187. const startPlanOnAccess = vi.fn();
  188. render(
  189. createElement(ChatContextUsage, {
  190. codingPlanUsageRemaining: {
  191. availableProviders: [],
  192. entitlements: [
  193. {
  194. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  195. snapshot: null,
  196. loading: false,
  197. error: null,
  198. },
  199. ],
  200. modelProvidersLoading: false,
  201. onAccess: codingPlanOnAccess,
  202. },
  203. startPlanBalance: {
  204. loading: false,
  205. onAccess: startPlanOnAccess,
  206. snapshot: createStartPlanSnapshot(),
  207. },
  208. intl: createIntl(),
  209. locale: "en-US",
  210. selectedProvider: "glm",
  211. taskUsage: null,
  212. }),
  213. );
  214. fireEvent.click(screen.getByTestId("context-open"));
  215. expect(codingPlanOnAccess).toHaveBeenCalledTimes(1);
  216. expect(startPlanOnAccess).not.toHaveBeenCalled();
  217. });
  218. });