useCodingPlanQuotaResetUi.test.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. // @vitest-environment jsdom
  2. import { act, cleanup, render, renderHook, waitFor } from "@testing-library/react";
  3. import { createElement, type ReactNode } from "react";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import type { IBroadcastService, IUsageStatsService } from "@zcode/services";
  6. import type { CodingPlanResetStatusSnapshot, ZCodeAccountAccess } from "@zcode/shared";
  7. import { StoreProvider, useZCodeStore } from "@/store/StoreProvider.js";
  8. const mocks = vi.hoisted(() => ({
  9. services: null as { usageStatsService: IUsageStatsService } | null,
  10. toast: vi.fn(),
  11. }));
  12. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  13. useOptionalBaseWorkspaceServices: () => mocks.services,
  14. }));
  15. vi.mock("@/i18n/IntlProvider.js", () => ({
  16. useZCodeIntl: () => ({
  17. intl: { formatMessage: ({ id }: { id: string }) => id },
  18. locale: "zh-CN",
  19. }),
  20. }));
  21. vi.mock("@/components/ui/toast.js", () => ({
  22. toast: mocks.toast,
  23. }));
  24. import { useCodingPlanQuotaResetUi } from "@/hooks/useCodingPlanQuotaResetUi.js";
  25. const broadcastService = {
  26. send: vi.fn(async () => undefined),
  27. onMessage: () => ({ dispose: () => {} }),
  28. } as unknown as IBroadcastService;
  29. const TEST_ACCOUNT_ACCESS: ZCodeAccountAccess = {
  30. type: "zhipu-account",
  31. family: "bigmodel",
  32. planKind: "individual-coding-plan",
  33. };
  34. const TEST_TEAM_ACCOUNT_ACCESS: ZCodeAccountAccess = {
  35. type: "zhipu-account",
  36. family: "bigmodel",
  37. planKind: "team-coding-plan",
  38. productId: "product-team",
  39. organizationId: "org",
  40. projectId: "project",
  41. };
  42. function wrapper({ children }: { children: ReactNode }) {
  43. return createElement(StoreProvider, { broadcastService }, children);
  44. }
  45. function status(
  46. overrides: Partial<CodingPlanResetStatusSnapshot> = {},
  47. ): CodingPlanResetStatusSnapshot {
  48. return {
  49. availableFiveHourResets: [],
  50. availableWeekResets: [],
  51. latestFiveHourResetHistory: null,
  52. latestWeekResetHistory: null,
  53. hasUnreadHistory: false,
  54. ...overrides,
  55. };
  56. }
  57. function createUsageStatsService(overrides: Partial<IUsageStatsService> = {}): IUsageStatsService {
  58. return {
  59. getAppUsageSnapshot: vi.fn(),
  60. getCodingPlanUsageSnapshot: vi.fn(),
  61. getCodingPlanResetStatus: vi.fn(async () => status()),
  62. requestCodingPlanResetOpportunity: vi.fn(async () => ({
  63. granted: false,
  64. nextTryAt: null,
  65. })),
  66. useCodingPlanReset: vi.fn(async () => ({ used: true as const })),
  67. markCodingPlanResetHistoryRead: vi.fn(async () => undefined),
  68. getSnapshot: vi.fn(),
  69. getEntitlementSnapshot: vi.fn(),
  70. ...overrides,
  71. };
  72. }
  73. describe("useCodingPlanQuotaResetUi", () => {
  74. beforeEach(() => {
  75. mocks.toast.mockReset();
  76. Object.defineProperty(document, "visibilityState", {
  77. configurable: true,
  78. value: "visible",
  79. });
  80. });
  81. afterEach(() => {
  82. // 修复原因:该文件的 service mock 由全局变量提供;若先切换 mock 再由 Testing Library
  83. // 自动卸载,上一个 scope 的异步 effect 会短暂读到下一用例的 service,污染 history/read。
  84. cleanup();
  85. mocks.services = null;
  86. });
  87. it("首次 status 无机会时调用 opportunity,未发放则保持隐藏", async () => {
  88. const getCodingPlanResetStatus = vi.fn(async () => status());
  89. const requestCodingPlanResetOpportunity = vi.fn(async () => ({
  90. granted: false,
  91. nextTryAt: null,
  92. }));
  93. mocks.services = {
  94. usageStatsService: createUsageStatsService({
  95. getCodingPlanResetStatus,
  96. requestCodingPlanResetOpportunity,
  97. }),
  98. };
  99. const hook = renderHook(
  100. () =>
  101. useCodingPlanQuotaResetUi({
  102. sourceKey: "builtin:personal-empty",
  103. preferredProviderId: "builtin:personal-empty",
  104. accountAccess: TEST_ACCOUNT_ACCESS,
  105. }),
  106. { wrapper },
  107. );
  108. await waitFor(() => expect(requestCodingPlanResetOpportunity).toHaveBeenCalledTimes(1));
  109. expect(requestCodingPlanResetOpportunity).toHaveBeenCalledWith({
  110. preferredProviderId: "builtin:personal-empty",
  111. accountAccess: TEST_ACCOUNT_ACCESS,
  112. idempotencyKey: expect.any(String),
  113. });
  114. expect(hook.result.current.opportunityVisible).toBe(false);
  115. expect(mocks.toast).not.toHaveBeenCalled();
  116. });
  117. it("opportunity 发放成功后强制刷新 status 并展示机会", async () => {
  118. const expiresAt = Date.now() + 60_000;
  119. const getCodingPlanResetStatus = vi
  120. .fn<() => Promise<CodingPlanResetStatusSnapshot>>()
  121. .mockResolvedValueOnce(status())
  122. .mockResolvedValue(status({ availableFiveHourResets: [{ expireAt: expiresAt }] }));
  123. const requestCodingPlanResetOpportunity = vi.fn(async () => ({
  124. granted: true,
  125. nextTryAt: null,
  126. }));
  127. mocks.services = {
  128. usageStatsService: createUsageStatsService({
  129. getCodingPlanResetStatus,
  130. requestCodingPlanResetOpportunity,
  131. }),
  132. };
  133. const hook = renderHook(
  134. () =>
  135. useCodingPlanQuotaResetUi({
  136. sourceKey: "builtin:personal-granted",
  137. preferredProviderId: "builtin:personal-granted",
  138. accountAccess: TEST_ACCOUNT_ACCESS,
  139. }),
  140. { wrapper },
  141. );
  142. await waitFor(() => expect(hook.result.current.opportunityVisible).toBe(true));
  143. expect(requestCodingPlanResetOpportunity).toHaveBeenCalledTimes(1);
  144. expect(getCodingPlanResetStatus).toHaveBeenCalledTimes(2);
  145. });
  146. it("opportunity 请求失败时保留 status 状态且不弹手动重置 toast", async () => {
  147. const requestCodingPlanResetOpportunity = vi.fn(async () => {
  148. throw new Error("coding_plan_reset_api_error:2007");
  149. });
  150. mocks.services = {
  151. usageStatsService: createUsageStatsService({
  152. getCodingPlanResetStatus: vi.fn(async () => status()),
  153. requestCodingPlanResetOpportunity,
  154. }),
  155. };
  156. const hook = renderHook(
  157. () =>
  158. useCodingPlanQuotaResetUi({
  159. sourceKey: "builtin:personal-opportunity-failed",
  160. preferredProviderId: "builtin:personal-opportunity-failed",
  161. accountAccess: TEST_ACCOUNT_ACCESS,
  162. }),
  163. { wrapper },
  164. );
  165. await waitFor(() => expect(requestCodingPlanResetOpportunity).toHaveBeenCalledTimes(1));
  166. expect(hook.result.current.opportunityVisible).toBe(false);
  167. expect(mocks.toast).not.toHaveBeenCalled();
  168. });
  169. it("多个入口对相同 service + scope 合并 opportunity in-flight", async () => {
  170. let resolveOpportunity!: (value: { granted: boolean; nextTryAt: number | null }) => void;
  171. const getCodingPlanResetStatus = vi.fn(async () => status());
  172. const requestCodingPlanResetOpportunity = vi.fn(
  173. () =>
  174. new Promise<{ granted: boolean; nextTryAt: number | null }>((resolve) => {
  175. resolveOpportunity = resolve;
  176. }),
  177. );
  178. const service = createUsageStatsService({
  179. getCodingPlanResetStatus,
  180. requestCodingPlanResetOpportunity,
  181. });
  182. mocks.services = { usageStatsService: service };
  183. const options = {
  184. sourceKey: "team:bigmodel:product-team:org:project-opportunity",
  185. preferredProviderId: "builtin:team",
  186. accountAccess: TEST_TEAM_ACCOUNT_ACCESS,
  187. };
  188. const first = renderHook(() => useCodingPlanQuotaResetUi(options), {
  189. wrapper,
  190. });
  191. const second = renderHook(() => useCodingPlanQuotaResetUi(options), {
  192. wrapper,
  193. });
  194. await waitFor(() => expect(requestCodingPlanResetOpportunity).toHaveBeenCalledTimes(1));
  195. expect(requestCodingPlanResetOpportunity).toHaveBeenCalledWith({
  196. preferredProviderId: "builtin:team",
  197. accountAccess: TEST_TEAM_ACCOUNT_ACCESS,
  198. idempotencyKey: expect.any(String),
  199. });
  200. resolveOpportunity({ granted: false, nextTryAt: Date.now() + 60_000 });
  201. await waitFor(() => expect(first.result.current.opportunityVisible).toBe(false));
  202. expect(second.result.current.opportunityVisible).toBe(false);
  203. });
  204. it("本轮刚完成时跳过 opportunity(完成周期不抢发放)", async () => {
  205. const requestCodingPlanResetOpportunity = vi.fn(async () => ({
  206. granted: false,
  207. nextTryAt: null,
  208. }));
  209. // 两类历史 used_at 相等 + 单一 unread 游标 → 两类本轮同时刚发现完成:
  210. // 完成周期内已在做 history/read 与 entitlement 强刷,此刻发放必被 next_try_at 拒,故跳过。
  211. const completedUsedAt = Date.now() - 1_000;
  212. const completedService = createUsageStatsService({
  213. getCodingPlanResetStatus: vi.fn(async () =>
  214. status({
  215. latestFiveHourResetHistory: { usedAt: completedUsedAt },
  216. latestWeekResetHistory: { usedAt: completedUsedAt },
  217. hasUnreadHistory: true,
  218. }),
  219. ),
  220. requestCodingPlanResetOpportunity,
  221. });
  222. mocks.services = { usageStatsService: completedService };
  223. const completed = renderHook(
  224. () =>
  225. useCodingPlanQuotaResetUi({
  226. sourceKey: "builtin:personal-completed",
  227. preferredProviderId: "builtin:personal-completed",
  228. accountAccess: TEST_ACCOUNT_ACCESS,
  229. }),
  230. { wrapper },
  231. );
  232. await waitFor(() => expect(completed.result.current.done).toBe(true));
  233. await waitFor(() => expect(completed.result.current.week.done).toBe(true));
  234. expect(requestCodingPlanResetOpportunity).not.toHaveBeenCalled();
  235. });
  236. it("任一类型已有机会时仍调用 opportunity 以发放另一类(后端有上限不会膨胀)", async () => {
  237. // 后端对同一类型已持有未消费机会有发放上限,重复调用不叠加。因此"已有可用机会"不再阻塞
  238. // scope 级 /opportunity——否则一类挂着机会会饿死另一类的发放。
  239. const requestCodingPlanResetOpportunity = vi.fn(async () => ({
  240. granted: false,
  241. nextTryAt: null,
  242. }));
  243. // 只有五小时有券:仍调 opportunity,给周额度一次发放判断。
  244. mocks.services = {
  245. usageStatsService: createUsageStatsService({
  246. getCodingPlanResetStatus: vi.fn(async () =>
  247. status({
  248. availableFiveHourResets: [{ expireAt: Date.now() + 60_000 }],
  249. }),
  250. ),
  251. requestCodingPlanResetOpportunity,
  252. }),
  253. };
  254. const fiveHourOnly = renderHook(
  255. () =>
  256. useCodingPlanQuotaResetUi({
  257. sourceKey: "builtin:personal-five-hour-only",
  258. preferredProviderId: "builtin:personal-five-hour-only",
  259. accountAccess: TEST_ACCOUNT_ACCESS,
  260. }),
  261. { wrapper },
  262. );
  263. await waitFor(() => expect(fiveHourOnly.result.current.opportunityVisible).toBe(true));
  264. await waitFor(() => expect(requestCodingPlanResetOpportunity).toHaveBeenCalled());
  265. expect(fiveHourOnly.result.current.week.opportunityVisible).toBe(false);
  266. fiveHourOnly.unmount();
  267. requestCodingPlanResetOpportunity.mockClear();
  268. // 对称场景:只有周额度有券,同样仍触发 scope 级发放判断。
  269. mocks.services = {
  270. usageStatsService: createUsageStatsService({
  271. getCodingPlanResetStatus: vi.fn(async () =>
  272. status({ availableWeekResets: [{ expireAt: Date.now() + 60_000 }] }),
  273. ),
  274. requestCodingPlanResetOpportunity,
  275. }),
  276. };
  277. const weekOnly = renderHook(
  278. () =>
  279. useCodingPlanQuotaResetUi({
  280. sourceKey: "builtin:personal-week-only",
  281. preferredProviderId: "builtin:personal-week-only",
  282. accountAccess: TEST_ACCOUNT_ACCESS,
  283. }),
  284. { wrapper },
  285. );
  286. await waitFor(() => expect(weekOnly.result.current.week.opportunityVisible).toBe(true));
  287. await waitFor(() => expect(requestCodingPlanResetOpportunity).toHaveBeenCalled());
  288. weekOnly.unmount();
  289. requestCodingPlanResetOpportunity.mockClear();
  290. // 两类都已有券:后端有上限,重复调用不叠加,因此仍会触发一次发放判断。
  291. mocks.services = {
  292. usageStatsService: createUsageStatsService({
  293. getCodingPlanResetStatus: vi.fn(async () =>
  294. status({
  295. availableFiveHourResets: [{ expireAt: Date.now() + 60_000 }],
  296. availableWeekResets: [{ expireAt: Date.now() + 60_000 }],
  297. }),
  298. ),
  299. requestCodingPlanResetOpportunity,
  300. }),
  301. };
  302. const bothAvailable = renderHook(
  303. () =>
  304. useCodingPlanQuotaResetUi({
  305. sourceKey: "builtin:personal-both-available",
  306. preferredProviderId: "builtin:personal-both-available",
  307. accountAccess: TEST_ACCOUNT_ACCESS,
  308. }),
  309. { wrapper },
  310. );
  311. await waitFor(() => expect(bothAvailable.result.current.opportunityVisible).toBe(true));
  312. await waitFor(() => expect(bothAvailable.result.current.week.opportunityVisible).toBe(true));
  313. await waitFor(() => expect(requestCodingPlanResetOpportunity).toHaveBeenCalled());
  314. });
  315. it("多个入口对相同 service + scope 合并 status in-flight", async () => {
  316. let resolveStatus!: (value: CodingPlanResetStatusSnapshot) => void;
  317. const getCodingPlanResetStatus = vi.fn(
  318. () =>
  319. new Promise<CodingPlanResetStatusSnapshot>((resolve) => {
  320. resolveStatus = resolve;
  321. }),
  322. );
  323. const service = createUsageStatsService({ getCodingPlanResetStatus });
  324. mocks.services = { usageStatsService: service };
  325. const options = {
  326. sourceKey: "builtin:personal",
  327. preferredProviderId: "builtin:personal",
  328. accountAccess: TEST_ACCOUNT_ACCESS,
  329. };
  330. const first = renderHook(() => useCodingPlanQuotaResetUi(options), {
  331. wrapper,
  332. });
  333. const second = renderHook(() => useCodingPlanQuotaResetUi(options), {
  334. wrapper,
  335. });
  336. await waitFor(() => expect(getCodingPlanResetStatus).toHaveBeenCalledTimes(1));
  337. resolveStatus(status({ availableFiveHourResets: [{ expireAt: Date.now() + 60_000 }] }));
  338. await waitFor(() => expect(first.result.current.opportunityVisible).toBe(true));
  339. await waitFor(() => expect(second.result.current.opportunityVisible).toBe(true));
  340. });
  341. it("手动失败重试复用同一个幂等键", async () => {
  342. const getCodingPlanResetStatus = vi.fn(async () =>
  343. status({ availableFiveHourResets: [{ expireAt: Date.now() + 60_000 }] }),
  344. );
  345. const useCodingPlanReset = vi.fn(async () => {
  346. throw new Error("coding_plan_reset_api_error:2007");
  347. });
  348. mocks.services = {
  349. usageStatsService: createUsageStatsService({
  350. getCodingPlanResetStatus,
  351. useCodingPlanReset,
  352. }),
  353. };
  354. const hook = renderHook(
  355. () =>
  356. useCodingPlanQuotaResetUi({
  357. sourceKey: "builtin:personal",
  358. preferredProviderId: "builtin:personal",
  359. accountAccess: TEST_ACCOUNT_ACCESS,
  360. }),
  361. { wrapper },
  362. );
  363. await waitFor(() => expect(hook.result.current.opportunityVisible).toBe(true));
  364. await act(async () => {
  365. await expect(hook.result.current.reset()).rejects.toThrow("2007");
  366. });
  367. await waitFor(() => expect(hook.result.current.opportunityVisible).toBe(true));
  368. await act(async () => {
  369. await expect(hook.result.current.reset()).rejects.toThrow("2007");
  370. });
  371. expect(useCodingPlanReset).toHaveBeenCalledTimes(2);
  372. expect(useCodingPlanReset.mock.calls[0]?.[0].idempotencyKey).toBe(
  373. useCodingPlanReset.mock.calls[1]?.[0].idempotencyKey,
  374. );
  375. expect(mocks.toast).toHaveBeenCalledTimes(2);
  376. });
  377. it("重渲染仅更换 onEntitlementRefresh 身份时不重启轮询、不重复请求 opportunity", async () => {
  378. const getCodingPlanResetStatus = vi.fn(async () => status());
  379. const requestCodingPlanResetOpportunity = vi.fn(async () => ({
  380. granted: false,
  381. nextTryAt: null,
  382. }));
  383. mocks.services = {
  384. usageStatsService: createUsageStatsService({
  385. getCodingPlanResetStatus,
  386. requestCodingPlanResetOpportunity,
  387. }),
  388. };
  389. const hook = renderHook(
  390. ({ onEntitlementRefresh }: { onEntitlementRefresh: () => Promise<void> }) =>
  391. useCodingPlanQuotaResetUi({
  392. sourceKey: "builtin:personal-callback-identity",
  393. preferredProviderId: "builtin:personal-callback-identity",
  394. accountAccess: TEST_ACCOUNT_ACCESS,
  395. onEntitlementRefresh,
  396. }),
  397. {
  398. wrapper,
  399. initialProps: { onEntitlementRefresh: vi.fn(async () => undefined) },
  400. },
  401. );
  402. await waitFor(() => expect(requestCodingPlanResetOpportunity).toHaveBeenCalledTimes(1));
  403. const statusCalls = getCodingPlanResetStatus.mock.calls.length;
  404. // 设置页切换套餐时的 render 风暴最小复现:同一 scope、只有回调身份变化的连续重渲染。
  405. // 回调若留在依赖链上会逐次重启轮询 effect,对同一 scope 连发 /opportunity。
  406. for (let index = 0; index < 5; index += 1) {
  407. hook.rerender({ onEntitlementRefresh: vi.fn(async () => undefined) });
  408. }
  409. await act(async () => {
  410. await new Promise((resolve) => setTimeout(resolve, 50));
  411. });
  412. expect(requestCodingPlanResetOpportunity).toHaveBeenCalledTimes(1);
  413. expect(getCodingPlanResetStatus).toHaveBeenCalledTimes(statusCalls);
  414. });
  415. it("use 成功后以服务端 usedAt 完成,刷新 entitlement 并上报 history/read", async () => {
  416. const now = Date.now();
  417. const usedAt = now + 1_000;
  418. const getCodingPlanResetStatus = vi
  419. .fn<() => Promise<CodingPlanResetStatusSnapshot>>()
  420. .mockResolvedValueOnce(status({ availableFiveHourResets: [{ expireAt: now + 60_000 }] }))
  421. .mockResolvedValue(
  422. status({
  423. latestFiveHourResetHistory: { usedAt },
  424. hasUnreadHistory: true,
  425. }),
  426. );
  427. const markCodingPlanResetHistoryRead = vi.fn(async () => undefined);
  428. const onEntitlementRefresh = vi.fn(async () => undefined);
  429. mocks.services = {
  430. usageStatsService: createUsageStatsService({
  431. getCodingPlanResetStatus,
  432. markCodingPlanResetHistoryRead,
  433. }),
  434. };
  435. const hook = renderHook(
  436. () =>
  437. useCodingPlanQuotaResetUi({
  438. sourceKey: "team:bigmodel:product-team:org:project",
  439. preferredProviderId: "builtin:team",
  440. accountAccess: TEST_TEAM_ACCOUNT_ACCESS,
  441. onEntitlementRefresh,
  442. }),
  443. { wrapper },
  444. );
  445. await waitFor(() => expect(hook.result.current.opportunityVisible).toBe(true));
  446. await act(async () => {
  447. await hook.result.current.reset();
  448. });
  449. expect(hook.result.current.entry?.completedAt).toBe(usedAt);
  450. expect(onEntitlementRefresh).toHaveBeenCalledTimes(1);
  451. expect(hook.result.current.entry?.quotaOverridePending).toBe(false);
  452. await waitFor(() => expect(markCodingPlanResetHistoryRead).toHaveBeenCalledTimes(1));
  453. expect(markCodingPlanResetHistoryRead).toHaveBeenCalledWith({
  454. preferredProviderId: "builtin:team",
  455. accountAccess: TEST_TEAM_ACCOUNT_ACCESS,
  456. });
  457. });
  458. it("同一 service 下两个 scope 相同 usedAt 只上报一次 history/read(用户级共享游标契约)", async () => {
  459. // 契约回归:docs/coding-plan-quota-reset-ui.md 与 bigmodelUsageQuotaProvider 均声明
  460. // history/read 按用户共享已读游标(请求不带 scope)。去重 key 只按 usedAt;若按
  461. // scope 拆分,同 service 双 scope 相同 usedAt 会重复 POST 无目标字段的同类请求。
  462. const now = Date.now();
  463. const usedAt = now + 1_000;
  464. const opportunity = () => status({ availableFiveHourResets: [{ expireAt: now + 60_000 }] });
  465. const completed = () =>
  466. status({ latestFiveHourResetHistory: { usedAt }, hasUnreadHistory: true });
  467. // 轮询会多次消费 status;用显式相位而不是 Once 排队,保证两个 scope 各自
  468. // 在自己的窗口看到 opportunity、reset 后看到 completed。
  469. let phase: "personal-opportunity" | "team-opportunity" | "completed" = "personal-opportunity";
  470. const getCodingPlanResetStatus = vi.fn(async () => {
  471. if (phase !== "completed") return opportunity();
  472. return completed();
  473. });
  474. const markCodingPlanResetHistoryRead = vi.fn(async () => undefined);
  475. mocks.services = {
  476. usageStatsService: createUsageStatsService({
  477. getCodingPlanResetStatus,
  478. markCodingPlanResetHistoryRead,
  479. }),
  480. };
  481. const personal = renderHook(
  482. () =>
  483. useCodingPlanQuotaResetUi({
  484. sourceKey: "builtin:personal-granted",
  485. preferredProviderId: "builtin:personal-granted",
  486. accountAccess: TEST_ACCOUNT_ACCESS,
  487. }),
  488. { wrapper },
  489. );
  490. await waitFor(() => expect(personal.result.current.opportunityVisible).toBe(true));
  491. phase = "completed";
  492. await act(async () => {
  493. await personal.result.current.reset();
  494. });
  495. await waitFor(() => expect(markCodingPlanResetHistoryRead).toHaveBeenCalledTimes(1));
  496. personal.unmount();
  497. phase = "team-opportunity";
  498. const team = renderHook(
  499. () =>
  500. useCodingPlanQuotaResetUi({
  501. sourceKey: "team:bigmodel:product-team:org:project",
  502. preferredProviderId: "builtin:team",
  503. accountAccess: TEST_TEAM_ACCOUNT_ACCESS,
  504. }),
  505. { wrapper },
  506. );
  507. await waitFor(() => expect(team.result.current.opportunityVisible).toBe(true));
  508. phase = "completed";
  509. await act(async () => {
  510. await team.result.current.reset();
  511. });
  512. await act(async () => {
  513. await new Promise((resolve) => setTimeout(resolve, 20));
  514. });
  515. expect(markCodingPlanResetHistoryRead).toHaveBeenCalledTimes(1);
  516. team.unmount();
  517. });
  518. it("其他入口观察到手动重置历史时不会误触发自动重置交互", async () => {
  519. const now = Date.now();
  520. const usedAt = now + 1_000;
  521. let currentStatus = status({
  522. availableFiveHourResets: [{ expireAt: now + 60_000 }],
  523. });
  524. const getCodingPlanResetStatus = vi.fn(async () => currentStatus);
  525. const useCodingPlanReset = vi.fn(async () => {
  526. currentStatus = status({
  527. latestFiveHourResetHistory: { usedAt },
  528. hasUnreadHistory: true,
  529. });
  530. return { used: true as const };
  531. });
  532. mocks.services = {
  533. usageStatsService: createUsageStatsService({
  534. getCodingPlanResetStatus,
  535. useCodingPlanReset,
  536. }),
  537. };
  538. const scope = {
  539. preferredProviderId: "builtin:personal-shared-manual",
  540. accountAccess: TEST_ACCOUNT_ACCESS,
  541. };
  542. const settingsEntry = renderHook(
  543. () =>
  544. useCodingPlanQuotaResetUi({
  545. sourceKey: "settings:personal-shared-manual",
  546. ...scope,
  547. }),
  548. { wrapper },
  549. );
  550. const composerEntry = renderHook(
  551. () =>
  552. useCodingPlanQuotaResetUi({
  553. sourceKey: "composer:personal-shared-manual",
  554. ...scope,
  555. }),
  556. { wrapper },
  557. );
  558. await waitFor(() => expect(settingsEntry.result.current.opportunityVisible).toBe(true));
  559. await waitFor(() => expect(composerEntry.result.current.opportunityVisible).toBe(true));
  560. await act(async () => settingsEntry.result.current.reset());
  561. expect(settingsEntry.result.current.entry?.startedAt).not.toBeNull();
  562. expect(settingsEntry.result.current.statusVisible).toBe(false);
  563. act(() => document.dispatchEvent(new Event("visibilitychange")));
  564. await waitFor(() => expect(composerEntry.result.current.done).toBe(true));
  565. expect(composerEntry.result.current.entry?.completedAt).toBe(usedAt);
  566. expect(composerEntry.result.current.entry?.startedAt).not.toBeNull();
  567. expect(composerEntry.result.current.statusVisible).toBe(false);
  568. });
  569. it("其他入口的手动核销仍在进行时,第二个入口 reset 不发起第二次 /use", async () => {
  570. const now = Date.now();
  571. let currentStatus = status({
  572. availableFiveHourResets: [{ expireAt: now + 60_000 }],
  573. });
  574. const getCodingPlanResetStatus = vi.fn(async () => currentStatus);
  575. let resolveUse!: (value: { used: true }) => void;
  576. const useCodingPlanReset = vi.fn(
  577. () =>
  578. new Promise<{ used: true }>((resolve) => {
  579. resolveUse = resolve;
  580. }),
  581. );
  582. mocks.services = {
  583. usageStatsService: createUsageStatsService({
  584. getCodingPlanResetStatus,
  585. useCodingPlanReset,
  586. }),
  587. };
  588. const scope = {
  589. preferredProviderId: "builtin:personal-use-single-flight",
  590. accountAccess: TEST_ACCOUNT_ACCESS,
  591. };
  592. const settingsEntry = renderHook(
  593. () =>
  594. useCodingPlanQuotaResetUi({
  595. sourceKey: "settings:use-single-flight",
  596. ...scope,
  597. }),
  598. { wrapper },
  599. );
  600. const composerEntry = renderHook(
  601. () =>
  602. useCodingPlanQuotaResetUi({
  603. sourceKey: "composer:use-single-flight",
  604. ...scope,
  605. }),
  606. { wrapper },
  607. );
  608. await waitFor(() => expect(settingsEntry.result.current.opportunityVisible).toBe(true));
  609. await waitFor(() => expect(composerEntry.result.current.opportunityVisible).toBe(true));
  610. let settingsReset!: Promise<void>;
  611. act(() => {
  612. settingsReset = settingsEntry.result.current.reset();
  613. });
  614. await waitFor(() => expect(useCodingPlanReset).toHaveBeenCalledTimes(1));
  615. // Composer 入口尚未轮询到,仍显示 available;点击只强制对账,不得再发 /use(会用新幂等键双核销)。
  616. await act(async () => {
  617. await composerEntry.result.current.reset();
  618. });
  619. expect(useCodingPlanReset).toHaveBeenCalledTimes(1);
  620. expect(composerEntry.result.current.processing).toBe(false);
  621. const usedAt = now + 1_000;
  622. currentStatus = status({
  623. latestFiveHourResetHistory: { usedAt },
  624. hasUnreadHistory: true,
  625. });
  626. resolveUse({ used: true });
  627. await act(async () => {
  628. await settingsReset;
  629. });
  630. expect(settingsEntry.result.current.done).toBe(true);
  631. });
  632. it("手动核销完成后,尚未轮询到的入口点击 reset 只对账为手动完成,不重复核销", async () => {
  633. const now = Date.now();
  634. const usedAt = now + 1_000;
  635. let currentStatus = status({
  636. availableFiveHourResets: [{ expireAt: now + 60_000 }],
  637. });
  638. const getCodingPlanResetStatus = vi.fn(async () => currentStatus);
  639. const useCodingPlanReset = vi.fn(async () => {
  640. currentStatus = status({
  641. latestFiveHourResetHistory: { usedAt },
  642. hasUnreadHistory: true,
  643. });
  644. return { used: true as const };
  645. });
  646. mocks.services = {
  647. usageStatsService: createUsageStatsService({
  648. getCodingPlanResetStatus,
  649. useCodingPlanReset,
  650. }),
  651. };
  652. const scope = {
  653. preferredProviderId: "builtin:personal-stale-entry",
  654. accountAccess: TEST_ACCOUNT_ACCESS,
  655. };
  656. const settingsEntry = renderHook(
  657. () =>
  658. useCodingPlanQuotaResetUi({
  659. sourceKey: "settings:stale-entry",
  660. ...scope,
  661. }),
  662. { wrapper },
  663. );
  664. const composerEntry = renderHook(
  665. () =>
  666. useCodingPlanQuotaResetUi({
  667. sourceKey: "composer:stale-entry",
  668. ...scope,
  669. }),
  670. { wrapper },
  671. );
  672. await waitFor(() => expect(settingsEntry.result.current.opportunityVisible).toBe(true));
  673. await waitFor(() => expect(composerEntry.result.current.opportunityVisible).toBe(true));
  674. await act(async () => settingsEntry.result.current.reset());
  675. expect(settingsEntry.result.current.done).toBe(true);
  676. // Composer 入口仍基于旧轮询显示 available;点击后按共享轨迹识别为手动完成,不再 /use。
  677. await act(async () => composerEntry.result.current.reset());
  678. expect(useCodingPlanReset).toHaveBeenCalledTimes(1);
  679. expect(composerEntry.result.current.done).toBe(true);
  680. expect(composerEntry.result.current.entry?.startedAt).not.toBeNull();
  681. expect(composerEntry.result.current.statusVisible).toBe(false);
  682. });
  683. it("完成后同一 used_at 周期内新发放的机会恢复重置入口,无需重新登录", async () => {
  684. const now = Date.now();
  685. const usedAt = now - 1_000;
  686. let currentStatus = status({
  687. latestFiveHourResetHistory: { usedAt },
  688. hasUnreadHistory: true,
  689. });
  690. const getCodingPlanResetStatus = vi.fn(async () => currentStatus);
  691. mocks.services = {
  692. usageStatsService: createUsageStatsService({ getCodingPlanResetStatus }),
  693. };
  694. const hook = renderHook(
  695. () =>
  696. useCodingPlanQuotaResetUi({
  697. sourceKey: "builtin:personal-regrant",
  698. preferredProviderId: "builtin:personal-regrant",
  699. accountAccess: TEST_ACCOUNT_ACCESS,
  700. }),
  701. { wrapper },
  702. );
  703. await waitFor(() => expect(hook.result.current.done).toBe(true));
  704. // 用户重置后又消耗额度,后端在 used_at 未变的同一周期内重新发放机会。
  705. currentStatus = status({
  706. availableFiveHourResets: [{ expireAt: now + 120_000 }],
  707. latestFiveHourResetHistory: { usedAt },
  708. hasUnreadHistory: false,
  709. });
  710. // 等出 status 的 1.5s 新鲜度窗口,让可见性刷新拿到新快照而不是共享缓存。
  711. await act(async () => {
  712. await new Promise((resolve) => setTimeout(resolve, 1_600));
  713. });
  714. act(() => document.dispatchEvent(new Event("visibilitychange")));
  715. await waitFor(() => expect(hook.result.current.opportunityVisible).toBe(true));
  716. expect(hook.result.current.done).toBe(false);
  717. });
  718. it.each([
  719. { clearUnreadOnRead: true, label: "history/read 已清除 unread" },
  720. { clearUnreadOnRead: false, label: "unread 尚未清除" },
  721. ])(
  722. "同类型多张机会:核销一张后完成态保留余下机会,不重挂载即可再次核销($label)",
  723. async ({ clearUnreadOnRead }) => {
  724. const now = Date.now();
  725. let useCount = 0;
  726. let currentStatus = status({
  727. availableFiveHourResets: [{ expireAt: now + 60_000 }, { expireAt: now + 120_000 }],
  728. });
  729. const getCodingPlanResetStatus = vi.fn(async () => currentStatus);
  730. // 模拟服务端:每次 /use 核销最早到期的一张,并写入新的 used_at 与未读历史。
  731. const useCodingPlanReset = vi.fn(async () => {
  732. useCount += 1;
  733. currentStatus = status({
  734. availableFiveHourResets: currentStatus.availableFiveHourResets.slice(1),
  735. latestFiveHourResetHistory: { usedAt: now + 1_000 * useCount },
  736. hasUnreadHistory: true,
  737. });
  738. return { used: true as const };
  739. });
  740. const markCodingPlanResetHistoryRead = vi.fn(async () => {
  741. if (clearUnreadOnRead) {
  742. currentStatus = { ...currentStatus, hasUnreadHistory: false };
  743. }
  744. });
  745. mocks.services = {
  746. usageStatsService: createUsageStatsService({
  747. getCodingPlanResetStatus,
  748. useCodingPlanReset,
  749. markCodingPlanResetHistoryRead,
  750. }),
  751. };
  752. const scopeId = `builtin:personal-multi-${clearUnreadOnRead}`;
  753. const hook = renderHook(
  754. () =>
  755. useCodingPlanQuotaResetUi({
  756. sourceKey: scopeId,
  757. preferredProviderId: scopeId,
  758. accountAccess: TEST_ACCOUNT_ACCESS,
  759. }),
  760. { wrapper },
  761. );
  762. await waitFor(() => expect(hook.result.current.entry?.opportunityCount).toBe(2));
  763. await act(async () => hook.result.current.reset());
  764. // Bugfix 回归:完成态携带同一 status 快照里余下的一张机会,弹框/徽标据此继续展示。
  765. expect(hook.result.current.done).toBe(true);
  766. expect(hook.result.current.entry).toMatchObject({
  767. completedAt: now + 1_000,
  768. opportunityCount: 1,
  769. opportunityExpiresAt: now + 120_000,
  770. });
  771. expect(hook.result.current.opportunityVisible).toBe(true);
  772. // 不重新挂载(等价于弹框不关闭)直接再次核销:必须真实发出第二次 /use,且使用新幂等键。
  773. await act(async () => hook.result.current.reset());
  774. expect(useCodingPlanReset).toHaveBeenCalledTimes(2);
  775. expect(useCodingPlanReset.mock.calls[1]?.[0].idempotencyKey).not.toBe(
  776. useCodingPlanReset.mock.calls[0]?.[0].idempotencyKey,
  777. );
  778. expect(hook.result.current.entry).toMatchObject({
  779. status: "completed",
  780. completedAt: now + 2_000,
  781. opportunityCount: 0,
  782. opportunityExpiresAt: null,
  783. });
  784. expect(hook.result.current.opportunityVisible).toBe(false);
  785. },
  786. );
  787. // 模拟服务端读数滞后:第一张 /use 即时可见;第二张 /use 之后的前 lagReads 次 status 仍返回
  788. // 消费前快照(上一张的 used_at + 余下 1 张),之后才出现新的 used_at。
  789. function createLaggingSecondUseService(params: { lagReads: number; staleUnread: boolean }) {
  790. const now = Date.now();
  791. let useCount = 0;
  792. let lagReadsRemaining = 0;
  793. let pendingStatus: CodingPlanResetStatusSnapshot | null = null;
  794. let remaining = [{ expireAt: now + 60_000 }, { expireAt: now + 120_000 }];
  795. let currentStatus = status({ availableFiveHourResets: remaining });
  796. const getCodingPlanResetStatus = vi.fn(async () => {
  797. if (lagReadsRemaining > 0) {
  798. lagReadsRemaining -= 1;
  799. return currentStatus;
  800. }
  801. if (pendingStatus) {
  802. currentStatus = pendingStatus;
  803. pendingStatus = null;
  804. }
  805. return currentStatus;
  806. });
  807. const useCodingPlanReset = vi.fn(async () => {
  808. useCount += 1;
  809. remaining = remaining.slice(1);
  810. const next = status({
  811. availableFiveHourResets: remaining,
  812. latestFiveHourResetHistory: { usedAt: now + 1_000 * useCount },
  813. hasUnreadHistory: true,
  814. });
  815. if (useCount === 1) {
  816. currentStatus = next;
  817. } else {
  818. pendingStatus = next;
  819. lagReadsRemaining = params.lagReads;
  820. // staleUnread=false:上一张的 history/read 已生效,滞后快照不再带 unread。
  821. currentStatus = { ...currentStatus, hasUnreadHistory: params.staleUnread };
  822. }
  823. return { used: true as const };
  824. });
  825. return { now, getCodingPlanResetStatus, useCodingPlanReset };
  826. }
  827. it.each([
  828. { staleUnread: true, label: "滞后快照 unread 未清" },
  829. { staleUnread: false, label: "滞后快照 unread 已清" },
  830. ])(
  831. "完成态再次核销时 status 仍是上一张 used_at,等到新 used_at 才确认成功($label)",
  832. async ({ staleUnread }) => {
  833. const { now, getCodingPlanResetStatus, useCodingPlanReset } = createLaggingSecondUseService({
  834. lagReads: 2,
  835. staleUnread,
  836. });
  837. mocks.services = {
  838. usageStatsService: createUsageStatsService({
  839. getCodingPlanResetStatus,
  840. useCodingPlanReset,
  841. }),
  842. };
  843. const scopeId = `builtin:personal-lagging-${staleUnread}`;
  844. const hook = renderHook(
  845. () =>
  846. useCodingPlanQuotaResetUi({
  847. sourceKey: scopeId,
  848. preferredProviderId: scopeId,
  849. accountAccess: TEST_ACCOUNT_ACCESS,
  850. }),
  851. { wrapper },
  852. );
  853. await waitFor(() => expect(hook.result.current.entry?.opportunityCount).toBe(2));
  854. await act(async () => hook.result.current.reset());
  855. expect(hook.result.current.entry).toMatchObject({
  856. status: "completed",
  857. completedAt: now + 1_000,
  858. opportunityCount: 1,
  859. });
  860. // Bugfix 回归(CR-01):旧判定在 /use 后第一次(0ms)对账读到上一张的 used_at 就确认成功,
  861. // reset() 提前 resolve,弹框播放成功反馈且行内停留在消费前的 1 张。
  862. await act(async () => hook.result.current.reset());
  863. expect(useCodingPlanReset).toHaveBeenCalledTimes(2);
  864. expect(hook.result.current.entry).toMatchObject({
  865. status: "completed",
  866. completedAt: now + 2_000,
  867. opportunityCount: 0,
  868. opportunityExpiresAt: null,
  869. });
  870. expect(hook.result.current.opportunityVisible).toBe(false);
  871. },
  872. );
  873. it("完成态再次核销后 4 次对账都未见新 used_at 时走失败恢复,不静默成功", async () => {
  874. const { getCodingPlanResetStatus, useCodingPlanReset } = createLaggingSecondUseService({
  875. lagReads: 4,
  876. staleUnread: true,
  877. });
  878. mocks.services = {
  879. usageStatsService: createUsageStatsService({ getCodingPlanResetStatus, useCodingPlanReset }),
  880. };
  881. const hook = renderHook(
  882. () =>
  883. useCodingPlanQuotaResetUi({
  884. sourceKey: "builtin:personal-lagging-timeout",
  885. preferredProviderId: "builtin:personal-lagging-timeout",
  886. accountAccess: TEST_ACCOUNT_ACCESS,
  887. }),
  888. { wrapper },
  889. );
  890. await waitFor(() => expect(hook.result.current.entry?.opportunityCount).toBe(2));
  891. await act(async () => hook.result.current.reset());
  892. mocks.toast.mockReset();
  893. await act(async () => {
  894. await expect(hook.result.current.reset()).rejects.toThrow(
  895. "coding_plan_reset_status_not_confirmed",
  896. );
  897. });
  898. expect(useCodingPlanReset).toHaveBeenCalledTimes(2);
  899. // 失败恢复保留点击前的机会快照,并提示失败;不再显示为已完成。
  900. expect(hook.result.current.entry).toMatchObject({ status: "available", opportunityCount: 1 });
  901. expect(hook.result.current.entry?.error).toBe("coding_plan_reset_status_not_confirmed");
  902. expect(mocks.toast).toHaveBeenCalledTimes(1);
  903. });
  904. it("没有手动核销轨迹的新历史仍保留自动重置完成提示", async () => {
  905. mocks.services = {
  906. usageStatsService: createUsageStatsService({
  907. getCodingPlanResetStatus: vi.fn(async () =>
  908. status({
  909. latestFiveHourResetHistory: { usedAt: Date.now() - 1_000 },
  910. hasUnreadHistory: true,
  911. }),
  912. ),
  913. }),
  914. };
  915. const hook = renderHook(
  916. () =>
  917. useCodingPlanQuotaResetUi({
  918. sourceKey: "builtin:personal-automatic-remains",
  919. preferredProviderId: "builtin:personal-automatic-remains",
  920. accountAccess: TEST_ACCOUNT_ACCESS,
  921. }),
  922. { wrapper },
  923. );
  924. await waitFor(() => expect(hook.result.current.done).toBe(true));
  925. expect(hook.result.current.entry?.startedAt).toBeNull();
  926. expect(hook.result.current.statusVisible).toBe(true);
  927. });
  928. it("entitlement 刷新失败时保留乐观覆盖,并在后续状态校正时重试", async () => {
  929. const usedAt = Date.now() - 1_000;
  930. const onEntitlementRefresh = vi
  931. .fn<() => Promise<void>>()
  932. .mockRejectedValueOnce(new Error("temporary refresh failure"))
  933. .mockResolvedValue(undefined);
  934. mocks.services = {
  935. usageStatsService: createUsageStatsService({
  936. getCodingPlanResetStatus: vi.fn(async () =>
  937. status({
  938. latestFiveHourResetHistory: { usedAt },
  939. hasUnreadHistory: true,
  940. }),
  941. ),
  942. }),
  943. };
  944. const hook = renderHook(
  945. () =>
  946. useCodingPlanQuotaResetUi({
  947. sourceKey: "builtin:personal-refresh-retry",
  948. preferredProviderId: "builtin:personal-refresh-retry",
  949. accountAccess: TEST_ACCOUNT_ACCESS,
  950. onEntitlementRefresh,
  951. }),
  952. { wrapper },
  953. );
  954. await waitFor(() => expect(onEntitlementRefresh).toHaveBeenCalledTimes(1));
  955. expect(hook.result.current.entry?.quotaOverridePending).toBe(true);
  956. act(() => document.dispatchEvent(new Event("visibilitychange")));
  957. await waitFor(() => expect(onEntitlementRefresh).toHaveBeenCalledTimes(2));
  958. expect(hook.result.current.entry?.quotaOverridePending).toBe(false);
  959. });
  960. it("周额度机会独立于五小时通过 week 子控制器暴露", async () => {
  961. const expiresAt = Date.now() + 60_000;
  962. mocks.services = {
  963. usageStatsService: createUsageStatsService({
  964. getCodingPlanResetStatus: vi.fn(async () =>
  965. status({ availableWeekResets: [{ expireAt: expiresAt }] }),
  966. ),
  967. }),
  968. };
  969. const hook = renderHook(
  970. () =>
  971. useCodingPlanQuotaResetUi({
  972. sourceKey: "builtin:personal-week-available",
  973. preferredProviderId: "builtin:personal-week-available",
  974. accountAccess: TEST_ACCOUNT_ACCESS,
  975. }),
  976. { wrapper },
  977. );
  978. await waitFor(() => expect(hook.result.current.week.opportunityVisible).toBe(true));
  979. expect(hook.result.current.week.entry?.opportunityExpiresAt).toBe(expiresAt);
  980. // 五小时无机会,不应被周机会带出 available。
  981. expect(hook.result.current.opportunityVisible).toBe(false);
  982. expect(hook.result.current.entry).toBeNull();
  983. });
  984. it("周额度手动重置发送 resetType=WEEK 并以服务端 usedAt 完成", async () => {
  985. const now = Date.now();
  986. const usedAt = now + 1_000;
  987. const getCodingPlanResetStatus = vi
  988. .fn<() => Promise<CodingPlanResetStatusSnapshot>>()
  989. .mockResolvedValueOnce(status({ availableWeekResets: [{ expireAt: now + 60_000 }] }))
  990. .mockResolvedValue(
  991. status({
  992. latestWeekResetHistory: { usedAt },
  993. hasUnreadHistory: true,
  994. }),
  995. );
  996. const useCodingPlanReset = vi.fn(async () => ({ used: true as const }));
  997. mocks.services = {
  998. usageStatsService: createUsageStatsService({
  999. getCodingPlanResetStatus,
  1000. useCodingPlanReset,
  1001. }),
  1002. };
  1003. const hook = renderHook(
  1004. () =>
  1005. useCodingPlanQuotaResetUi({
  1006. sourceKey: "builtin:personal-week-reset",
  1007. preferredProviderId: "builtin:personal-week-reset",
  1008. accountAccess: TEST_ACCOUNT_ACCESS,
  1009. }),
  1010. { wrapper },
  1011. );
  1012. await waitFor(() => expect(hook.result.current.week.opportunityVisible).toBe(true));
  1013. await act(async () => {
  1014. await hook.result.current.week.reset();
  1015. });
  1016. expect(useCodingPlanReset).toHaveBeenCalledWith(expect.objectContaining({ resetType: "WEEK" }));
  1017. expect(hook.result.current.week.entry?.completedAt).toBe(usedAt);
  1018. expect(hook.result.current.week.done).toBe(true);
  1019. // 五小时子控制器不受周额度手动重置影响。
  1020. expect(hook.result.current.done).toBe(false);
  1021. });
  1022. it("周额度自动完成时只有 week 子控制器进入 done", async () => {
  1023. const usedAt = Date.now() - 1_000;
  1024. mocks.services = {
  1025. usageStatsService: createUsageStatsService({
  1026. getCodingPlanResetStatus: vi.fn(async () =>
  1027. status({
  1028. latestWeekResetHistory: { usedAt },
  1029. hasUnreadHistory: true,
  1030. }),
  1031. ),
  1032. }),
  1033. };
  1034. const hook = renderHook(
  1035. () =>
  1036. useCodingPlanQuotaResetUi({
  1037. sourceKey: "builtin:personal-week-auto",
  1038. preferredProviderId: "builtin:personal-week-auto",
  1039. accountAccess: TEST_ACCOUNT_ACCESS,
  1040. }),
  1041. { wrapper },
  1042. );
  1043. await waitFor(() => expect(hook.result.current.week.done).toBe(true));
  1044. expect(hook.result.current.week.entry?.startedAt).toBeNull();
  1045. expect(hook.result.current.week.statusVisible).toBe(true);
  1046. // 五小时无历史,共享 has_unread_history 游标不得把它带入完成态。
  1047. expect(hook.result.current.done).toBe(false);
  1048. expect(hook.result.current.entry).toBeNull();
  1049. });
  1050. it("只在鉴权会话变化后静音旧周自动完成,同会话其他入口后挂载仍展示", async () => {
  1051. const firstUsedAt = Date.now() - 10_000;
  1052. const secondUsedAt = Date.now() - 1_000;
  1053. let currentStatus = status({
  1054. latestWeekResetHistory: { usedAt: firstUsedAt },
  1055. hasUnreadHistory: true,
  1056. });
  1057. mocks.services = {
  1058. usageStatsService: createUsageStatsService({
  1059. getCodingPlanResetStatus: vi.fn(async () => currentStatus),
  1060. }),
  1061. };
  1062. // Root Store 跨鉴权页面保留;组件 key 只模拟入口/路由重挂载,鉴权 epoch 由 setUser 的登录边界推进。
  1063. const hookProps = {
  1064. sourceKey: "composer:relogin-week",
  1065. preferredProviderId: "builtin:personal-relogin-week",
  1066. accountAccess: TEST_ACCOUNT_ACCESS,
  1067. };
  1068. let latest: ReturnType<typeof useCodingPlanQuotaResetUi> | null = null;
  1069. let startAuthenticatedSession: (() => void) | null = null;
  1070. function Probe(props: Parameters<typeof useCodingPlanQuotaResetUi>[0]) {
  1071. latest = useCodingPlanQuotaResetUi(props);
  1072. return null;
  1073. }
  1074. function AuthControl() {
  1075. const setUser = useZCodeStore((state) => state.setUser);
  1076. startAuthenticatedSession = () =>
  1077. setUser({ id: "user-1", username: "tester", displayName: "Tester" });
  1078. return null;
  1079. }
  1080. function Harness({ mountKey }: { mountKey: string }) {
  1081. return createElement(
  1082. StoreProvider,
  1083. { broadcastService },
  1084. createElement(AuthControl),
  1085. createElement(Probe, { key: mountKey, ...hookProps }),
  1086. );
  1087. }
  1088. // 当前鉴权会话首次发现周自动完成,正常播放短提示,observedAt 落到共享 store。
  1089. const view = render(createElement(Harness, { mountKey: "settings-entry" }));
  1090. await waitFor(() => expect(latest?.week.done).toBe(true));
  1091. expect(latest?.week.entry?.observedAt).not.toBeNull();
  1092. expect(latest?.week.statusVisible).toBe(true);
  1093. // 同一鉴权会话内 Composer 后挂载:共享 entry 不能被误判为上一次登录历史。
  1094. view.rerender(createElement(Harness, { mountKey: "composer-same-session" }));
  1095. await waitFor(() => expect(latest?.week.done).toBe(true));
  1096. expect(latest?.week.entry?.observedAt).not.toBeNull();
  1097. expect(latest?.week.statusVisible).toBe(true);
  1098. // 真正重新登录会推进鉴权 epoch;同一 used_at 此时属于上一登录会话,必须静音。
  1099. act(() => startAuthenticatedSession?.());
  1100. view.rerender(createElement(Harness, { mountKey: "composer-next-session" }));
  1101. await waitFor(() => {
  1102. expect(latest?.week.entry?.observedAt).toBeNull();
  1103. expect(latest?.week.statusVisible).toBe(false);
  1104. });
  1105. // 同一旧 used_at 再轮询也不能把观察记录改写到新 epoch 后重播。
  1106. await act(async () => {
  1107. await new Promise((resolve) => setTimeout(resolve, 1_600));
  1108. });
  1109. act(() => document.dispatchEvent(new Event("visibilitychange")));
  1110. await waitFor(() => expect(latest?.week.entry?.observedAt).toBeNull());
  1111. expect(latest?.week.statusVisible).toBe(false);
  1112. // 新鉴权会话内到来的新一轮周重置仍照常播放动画。
  1113. currentStatus = status({
  1114. latestWeekResetHistory: { usedAt: secondUsedAt },
  1115. hasUnreadHistory: true,
  1116. });
  1117. await act(async () => {
  1118. await new Promise((resolve) => setTimeout(resolve, 1_600));
  1119. });
  1120. act(() => document.dispatchEvent(new Event("visibilitychange")));
  1121. await waitFor(() => expect(latest?.week.entry?.completedAt).toBe(secondUsedAt));
  1122. expect(latest?.week.entry?.observedAt).not.toBeNull();
  1123. expect(latest?.week.statusVisible).toBe(true);
  1124. });
  1125. });