codingPlanQuotaResetAutoPlayBroadcast.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. // @vitest-environment jsdom
  2. // 跨窗口自动完成提示抑制:一个窗口播放后,其他窗口不得再播放(Tooltip/撒花)。
  3. // 覆盖 store 广播/接收、hook 创建期抑制、history/read 提前上报与撒花 arm 清理。
  4. import { act, renderHook, waitFor } from "@testing-library/react";
  5. import { createElement, type ReactNode } from "react";
  6. import { beforeEach, describe, expect, it, vi } from "vitest";
  7. import type { BroadcastMessage, IBroadcastService, IUsageStatsService } from "@zcode/services";
  8. import type { CodingPlanResetStatusSnapshot, ZCodeAccountAccess } from "@zcode/shared";
  9. import { StoreContext } from "@/store/StoreProvider.js";
  10. const mocks = vi.hoisted(() => ({
  11. services: null as { usageStatsService: IUsageStatsService } | null,
  12. toast: vi.fn(),
  13. }));
  14. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  15. useOptionalBaseWorkspaceServices: () => mocks.services,
  16. }));
  17. vi.mock("@/i18n/IntlProvider.js", () => ({
  18. useZCodeIntl: () => ({
  19. intl: { formatMessage: ({ id }: { id: string }) => id },
  20. locale: "zh-CN",
  21. }),
  22. }));
  23. vi.mock("@/components/ui/toast.js", () => ({
  24. toast: mocks.toast,
  25. }));
  26. import { useCodingPlanQuotaResetUi } from "@/hooks/useCodingPlanQuotaResetUi.js";
  27. import { coordinateCodingPlanQuotaResetAutoPlay } from "@/chat-input-toolbar/codingPlanQuotaResetAutoPlay.js";
  28. import { pruneCodingPlanQuotaResetConfettiArms } from "@/lib/codingPlanQuotaResetUi.js";
  29. import { CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL } from "@/store/codingPlanQuotaResetState.js";
  30. import { createZCodeStore } from "@/store/index.js";
  31. import type { ZCodeStore } from "@/store/index.js";
  32. const TEST_ACCOUNT_ACCESS: ZCodeAccountAccess = {
  33. type: "zhipu-account",
  34. family: "bigmodel",
  35. planKind: "individual-coding-plan",
  36. };
  37. type BroadcastListener = (message: BroadcastMessage) => void;
  38. function createBroadcastHarness({
  39. claimStatus = "acquired",
  40. }: {
  41. claimStatus?: "acquired" | "busy" | "committed";
  42. } = {}) {
  43. const listeners = new Set<BroadcastListener>();
  44. const send = vi.fn(async () => undefined);
  45. const acquireClaim = vi.fn(async (key: string) =>
  46. claimStatus === "acquired"
  47. ? { status: "acquired" as const, lease: { key, token: "claim-token" } }
  48. : claimStatus === "busy"
  49. ? { status: "busy" as const, retryAfterMs: 100 }
  50. : { status: "committed" as const },
  51. );
  52. const commitClaim = vi.fn(async () => undefined);
  53. const releaseClaim = vi.fn(async () => undefined);
  54. const tryClaim = vi.fn(async () => false);
  55. const service = {
  56. send,
  57. acquireClaim,
  58. commitClaim,
  59. releaseClaim,
  60. tryClaim,
  61. onMessage: (listener: BroadcastListener) => {
  62. listeners.add(listener);
  63. return { dispose: () => listeners.delete(listener) };
  64. },
  65. } as unknown as IBroadcastService;
  66. return {
  67. service,
  68. send,
  69. acquireClaim,
  70. commitClaim,
  71. releaseClaim,
  72. tryClaim,
  73. emit: (message: BroadcastMessage) => {
  74. for (const listener of listeners) {
  75. listener(message);
  76. }
  77. },
  78. };
  79. }
  80. function automaticCompletedEntry(completedAt: number, observedAt: number | null) {
  81. return {
  82. status: "completed" as const,
  83. opportunityCount: 0,
  84. opportunityExpiresAt: null,
  85. startedAt: null,
  86. completedAt,
  87. observedAt,
  88. quotaOverridePending: true,
  89. nextResetAt: completedAt + 5 * 60 * 60 * 1_000,
  90. idempotencyKey: null,
  91. error: null,
  92. };
  93. }
  94. function manualCompletedEntry(completedAt: number, startedAt: number) {
  95. return { ...automaticCompletedEntry(completedAt, null), startedAt };
  96. }
  97. function status(
  98. overrides: Partial<CodingPlanResetStatusSnapshot> = {},
  99. ): CodingPlanResetStatusSnapshot {
  100. return {
  101. availableFiveHourResets: [],
  102. availableWeekResets: [],
  103. latestFiveHourResetHistory: null,
  104. latestWeekResetHistory: null,
  105. hasUnreadHistory: false,
  106. ...overrides,
  107. };
  108. }
  109. function createUsageStatsService(overrides: Partial<IUsageStatsService> = {}): IUsageStatsService {
  110. return {
  111. getAppUsageSnapshot: vi.fn(),
  112. getCodingPlanUsageSnapshot: vi.fn(),
  113. getCodingPlanResetStatus: vi.fn(async () => status()),
  114. requestCodingPlanResetOpportunity: vi.fn(async () => ({
  115. granted: false,
  116. nextTryAt: null,
  117. })),
  118. useCodingPlanReset: vi.fn(async () => ({ used: true as const })),
  119. markCodingPlanResetHistoryRead: vi.fn(async () => undefined),
  120. getSnapshot: vi.fn(),
  121. getEntitlementSnapshot: vi.fn(),
  122. ...overrides,
  123. };
  124. }
  125. function wrapperFor(store: ZCodeStore) {
  126. return ({ children }: { children: ReactNode }) =>
  127. createElement(StoreContext.Provider, { value: store }, children);
  128. }
  129. describe("coding plan quota reset autoplay broadcast (store)", () => {
  130. it("status 写入只记录 observation,非 Composer 入口不占用播放资格", () => {
  131. const harness = createBroadcastHarness();
  132. const store = createZCodeStore(harness.service);
  133. act(() => {
  134. store
  135. .getState()
  136. .setCodingPlanQuotaResetUiEntry(
  137. "src",
  138. "FIVE_HOUR",
  139. automaticCompletedEntry(1_000, 2_000),
  140. 0,
  141. );
  142. });
  143. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src).toBeUndefined();
  144. expect(harness.acquireClaim).not.toHaveBeenCalled();
  145. expect(harness.send).not.toHaveBeenCalled();
  146. });
  147. it("Composer reservation winner 在 commit 前不写 played、不广播", async () => {
  148. const harness = createBroadcastHarness();
  149. const store = createZCodeStore(harness.service);
  150. act(() => {
  151. store
  152. .getState()
  153. .setCodingPlanQuotaResetUiEntry(
  154. "src",
  155. "FIVE_HOUR",
  156. automaticCompletedEntry(1_000, 2_000),
  157. 0,
  158. );
  159. });
  160. const attempt = await store
  161. .getState()
  162. .reserveCodingPlanQuotaResetAutoPlay("src", "FIVE_HOUR", 1_000);
  163. expect(attempt).toEqual({
  164. status: "reserved",
  165. reservation: expect.objectContaining({
  166. sourceKey: "src",
  167. resetType: "FIVE_HOUR",
  168. completedAt: 1_000,
  169. }),
  170. });
  171. expect(harness.acquireClaim).toHaveBeenCalledWith(
  172. "coding-plan-reset-autoplay:src:FIVE_HOUR:1000",
  173. );
  174. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src).toBeUndefined();
  175. expect(harness.send).not.toHaveBeenCalled();
  176. if (attempt.status !== "reserved") {
  177. throw new Error("expected reservation");
  178. }
  179. expect(store.getState().commitCodingPlanQuotaResetAutoPlay(attempt.reservation)).toBe(true);
  180. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src?.fiveHour).toBe(1_000);
  181. expect(harness.commitClaim).toHaveBeenCalledWith(attempt.reservation.lease);
  182. expect(harness.send).toHaveBeenCalledWith({
  183. channel: CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL,
  184. payload: { sourceKey: "src", resetType: "FIVE_HOUR", completedAt: 1_000 },
  185. });
  186. expect(store.getState().codingPlanQuotaResetUiBySource.src?.fiveHour?.observedAt).toBe(2_000);
  187. });
  188. it("Composer acquire busy 保留 observed_at,不把占用误当成 played", async () => {
  189. const harness = createBroadcastHarness({ claimStatus: "busy" });
  190. const store = createZCodeStore(harness.service);
  191. act(() => {
  192. store
  193. .getState()
  194. .setCodingPlanQuotaResetUiEntry("src", "WEEK", automaticCompletedEntry(3_000, 4_000), 0);
  195. });
  196. await expect(
  197. store.getState().reserveCodingPlanQuotaResetAutoPlay("src", "WEEK", 3_000),
  198. ).resolves.toEqual({ status: "retry", retryAfterMs: 100 });
  199. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src).toBeUndefined();
  200. expect(store.getState().codingPlanQuotaResetUiBySource.src?.week?.observedAt).toBe(4_000);
  201. expect(harness.send).not.toHaveBeenCalled();
  202. });
  203. it("reservation 释放时不写 played,后续窗口仍可继续争抢", async () => {
  204. const harness = createBroadcastHarness();
  205. const store = createZCodeStore(harness.service);
  206. act(() => {
  207. store
  208. .getState()
  209. .setCodingPlanQuotaResetUiEntry("src", "WEEK", automaticCompletedEntry(3_000, 4_000), 0);
  210. });
  211. const attempt = await store
  212. .getState()
  213. .reserveCodingPlanQuotaResetAutoPlay("src", "WEEK", 3_000);
  214. if (attempt.status !== "reserved") {
  215. throw new Error("expected reservation");
  216. }
  217. await store.getState().releaseCodingPlanQuotaResetAutoPlay(attempt.reservation);
  218. expect(harness.releaseClaim).toHaveBeenCalledWith(attempt.reservation.lease);
  219. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src).toBeUndefined();
  220. expect(store.getState().codingPlanQuotaResetUiBySource.src?.week?.observedAt).toBe(4_000);
  221. expect(harness.send).not.toHaveBeenCalled();
  222. });
  223. it("手动完成不会被 claim 成自动播放", async () => {
  224. const harness = createBroadcastHarness();
  225. const store = createZCodeStore(harness.service);
  226. act(() => {
  227. store
  228. .getState()
  229. .setCodingPlanQuotaResetUiEntry("src", "FIVE_HOUR", manualCompletedEntry(1_000, 900), 0);
  230. });
  231. await expect(
  232. store.getState().reserveCodingPlanQuotaResetAutoPlay("src", "FIVE_HOUR", 1_000),
  233. ).resolves.toEqual({ status: "blocked" });
  234. expect(harness.acquireClaim).not.toHaveBeenCalled();
  235. });
  236. it("收到跨窗口广播后抑制本窗口正在等待 claim 的同 used_at 自动完成", () => {
  237. const harness = createBroadcastHarness();
  238. const store = createZCodeStore(harness.service);
  239. act(() => {
  240. store
  241. .getState()
  242. .setCodingPlanQuotaResetUiEntry(
  243. "src",
  244. "FIVE_HOUR",
  245. automaticCompletedEntry(1_000, Date.now()),
  246. 0,
  247. );
  248. harness.emit({
  249. channel: CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL,
  250. payload: {
  251. sourceKey: "src",
  252. resetType: "FIVE_HOUR",
  253. completedAt: 1_000,
  254. },
  255. sourceWindowId: 7,
  256. });
  257. });
  258. expect(store.getState().codingPlanQuotaResetUiBySource.src?.fiveHour?.observedAt).toBeNull();
  259. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src?.fiveHour).toBe(1_000);
  260. });
  261. it("本地回声(无 sourceWindowId)不抑制 winner 的播放", async () => {
  262. const harness = createBroadcastHarness();
  263. const store = createZCodeStore(harness.service);
  264. act(() => {
  265. store
  266. .getState()
  267. .setCodingPlanQuotaResetUiEntry(
  268. "src",
  269. "FIVE_HOUR",
  270. automaticCompletedEntry(1_000, Date.now()),
  271. 0,
  272. );
  273. });
  274. const attempt = await store
  275. .getState()
  276. .reserveCodingPlanQuotaResetAutoPlay("src", "FIVE_HOUR", 1_000);
  277. if (attempt.status !== "reserved") {
  278. throw new Error("expected reservation");
  279. }
  280. store.getState().commitCodingPlanQuotaResetAutoPlay(attempt.reservation);
  281. act(() => {
  282. harness.emit({
  283. channel: CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL,
  284. payload: {
  285. sourceKey: "src",
  286. resetType: "FIVE_HOUR",
  287. completedAt: 1_000,
  288. },
  289. });
  290. });
  291. expect(
  292. store.getState().codingPlanQuotaResetUiBySource.src?.fiveHour?.observedAt,
  293. ).not.toBeNull();
  294. });
  295. it("旧广播晚到不会把较新的 played 记录回退", () => {
  296. const harness = createBroadcastHarness();
  297. const store = createZCodeStore(harness.service);
  298. act(() => {
  299. store.setState({
  300. codingPlanQuotaResetAutoPlayedBySource: {
  301. src: { fiveHour: 2_000, week: null },
  302. },
  303. });
  304. harness.emit({
  305. channel: CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL,
  306. payload: {
  307. sourceKey: "src",
  308. resetType: "FIVE_HOUR",
  309. completedAt: 1_000,
  310. },
  311. sourceWindowId: 7,
  312. });
  313. });
  314. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src?.fiveHour).toBe(2_000);
  315. });
  316. it("used_at 不匹配的广播只合并 played 记录,不改写 entry", () => {
  317. const harness = createBroadcastHarness();
  318. const store = createZCodeStore(harness.service);
  319. act(() => {
  320. store
  321. .getState()
  322. .setCodingPlanQuotaResetUiEntry(
  323. "src",
  324. "WEEK",
  325. automaticCompletedEntry(5_000, Date.now()),
  326. 0,
  327. );
  328. harness.emit({
  329. channel: CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL,
  330. payload: { sourceKey: "src", resetType: "WEEK", completedAt: 9_999 },
  331. sourceWindowId: 7,
  332. });
  333. });
  334. const entry = store.getState().codingPlanQuotaResetUiBySource.src?.week;
  335. expect(entry?.completedAt).toBe(5_000);
  336. expect(entry?.observedAt).not.toBeNull();
  337. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource.src?.week).toBe(9_999);
  338. });
  339. it("非法 payload 的广播被忽略", () => {
  340. const harness = createBroadcastHarness();
  341. const store = createZCodeStore(harness.service);
  342. expect(() => {
  343. act(() => {
  344. harness.emit({
  345. channel: CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL,
  346. payload: { sourceKey: "src" },
  347. sourceWindowId: 7,
  348. });
  349. harness.emit({
  350. channel: CODING_PLAN_QUOTA_RESET_AUTO_PLAYED_CHANNEL,
  351. payload: { sourceKey: "src", resetType: "BAD", completedAt: 1 },
  352. sourceWindowId: 7,
  353. });
  354. });
  355. }).not.toThrow();
  356. expect(store.getState().codingPlanQuotaResetAutoPlayedBySource).toEqual({});
  357. });
  358. });
  359. describe("coordinateCodingPlanQuotaResetAutoPlay", () => {
  360. it("reservation 返回前组件已卸载时只 release,不 commit played", async () => {
  361. const reservation = {
  362. sourceKey: "src",
  363. resetType: "FIVE_HOUR" as const,
  364. completedAt: 1_000,
  365. lease: { key: "claim-key", token: "claim-token" },
  366. };
  367. let resolveAttempt!: (attempt: { status: "reserved"; reservation: typeof reservation }) => void;
  368. const reserve = vi.fn(
  369. () =>
  370. new Promise<{ status: "reserved"; reservation: typeof reservation }>((resolve) => {
  371. resolveAttempt = resolve;
  372. }),
  373. );
  374. let current = true;
  375. const commit = vi.fn(() => true);
  376. const release = vi.fn(async () => undefined);
  377. const onCommitted = vi.fn();
  378. const pending = coordinateCodingPlanQuotaResetAutoPlay({
  379. reserve,
  380. isCurrent: () => current,
  381. commit,
  382. release,
  383. onCommitted,
  384. });
  385. current = false;
  386. resolveAttempt({ status: "reserved", reservation });
  387. await expect(pending).resolves.toEqual({ status: "released" });
  388. expect(release).toHaveBeenCalledWith(reservation);
  389. expect(commit).not.toHaveBeenCalled();
  390. expect(onCommitted).not.toHaveBeenCalled();
  391. });
  392. it("仍是当前候选时在同一展示边界 commit 并升级本组件状态", async () => {
  393. const reservation = {
  394. sourceKey: "src",
  395. resetType: "WEEK" as const,
  396. completedAt: 2_000,
  397. lease: { key: "claim-key", token: "claim-token" },
  398. };
  399. const commit = vi.fn(() => true);
  400. const release = vi.fn(async () => undefined);
  401. const onCommitted = vi.fn();
  402. await expect(
  403. coordinateCodingPlanQuotaResetAutoPlay({
  404. reserve: async () => ({ status: "reserved", reservation }),
  405. isCurrent: () => true,
  406. commit,
  407. release,
  408. onCommitted,
  409. }),
  410. ).resolves.toEqual({ status: "committed" });
  411. expect(commit).toHaveBeenCalledWith(reservation);
  412. expect(onCommitted).toHaveBeenCalledWith(reservation);
  413. expect(release).not.toHaveBeenCalled();
  414. });
  415. it("展示边界再次校验失败时 release reservation", async () => {
  416. const reservation = {
  417. sourceKey: "src",
  418. resetType: "WEEK" as const,
  419. completedAt: 2_000,
  420. lease: { key: "claim-key", token: "claim-token" },
  421. };
  422. const release = vi.fn(async () => undefined);
  423. const onCommitted = vi.fn();
  424. await expect(
  425. coordinateCodingPlanQuotaResetAutoPlay({
  426. reserve: async () => ({ status: "reserved", reservation }),
  427. isCurrent: () => true,
  428. commit: () => false,
  429. release,
  430. onCommitted,
  431. }),
  432. ).resolves.toEqual({ status: "released" });
  433. expect(release).toHaveBeenCalledWith(reservation);
  434. expect(onCommitted).not.toHaveBeenCalled();
  435. });
  436. });
  437. describe("coding plan quota reset autoplay broadcast (hook)", () => {
  438. beforeEach(() => {
  439. mocks.toast.mockReset();
  440. Object.defineProperty(document, "visibilityState", {
  441. configurable: true,
  442. value: "visible",
  443. });
  444. });
  445. it("played 记录已存在时,轮询进入完成态但不播放提示", async () => {
  446. const harness = createBroadcastHarness();
  447. const store = createZCodeStore(harness.service);
  448. const usedAt = 12_345;
  449. act(() => {
  450. store.setState({
  451. codingPlanQuotaResetAutoPlayedBySource: {
  452. src: { fiveHour: usedAt, week: null },
  453. },
  454. });
  455. });
  456. const getCodingPlanResetStatus = vi.fn(async () =>
  457. status({
  458. hasUnreadHistory: true,
  459. latestFiveHourResetHistory: { usedAt },
  460. }),
  461. );
  462. mocks.services = {
  463. usageStatsService: createUsageStatsService({
  464. getCodingPlanResetStatus,
  465. }),
  466. };
  467. const hook = renderHook(
  468. () =>
  469. useCodingPlanQuotaResetUi({
  470. sourceKey: "src",
  471. preferredProviderId: "p",
  472. accountAccess: TEST_ACCOUNT_ACCESS,
  473. }),
  474. { wrapper: wrapperFor(store) },
  475. );
  476. await waitFor(() => expect(hook.result.current.done).toBe(true));
  477. expect(hook.result.current.entry?.completedAt).toBe(usedAt);
  478. expect(hook.result.current.entry?.observedAt).toBeNull();
  479. expect(hook.result.current.statusVisible).toBe(false);
  480. expect(harness.send).not.toHaveBeenCalled();
  481. });
  482. it("Hook 观察完成后不自动占用,Composer 显式 claim 才播放", async () => {
  483. const harness = createBroadcastHarness();
  484. const store = createZCodeStore(harness.service);
  485. const usedAt = 23_456;
  486. mocks.services = {
  487. usageStatsService: createUsageStatsService({
  488. getCodingPlanResetStatus: vi.fn(async () =>
  489. status({
  490. hasUnreadHistory: true,
  491. latestFiveHourResetHistory: { usedAt },
  492. }),
  493. ),
  494. }),
  495. };
  496. const hook = renderHook(
  497. () =>
  498. useCodingPlanQuotaResetUi({
  499. sourceKey: "src",
  500. preferredProviderId: "p",
  501. accountAccess: TEST_ACCOUNT_ACCESS,
  502. }),
  503. { wrapper: wrapperFor(store) },
  504. );
  505. await waitFor(() => expect(hook.result.current.done).toBe(true));
  506. expect(harness.acquireClaim).not.toHaveBeenCalled();
  507. let attempt: Awaited<ReturnType<typeof hook.result.current.reserveAutomaticCompletion>>;
  508. await act(async () => {
  509. attempt = await hook.result.current.reserveAutomaticCompletion("FIVE_HOUR", usedAt);
  510. });
  511. expect(attempt!).toEqual(expect.objectContaining({ status: "reserved" }));
  512. expect(harness.acquireClaim).toHaveBeenCalledTimes(1);
  513. if (attempt!.status !== "reserved") {
  514. throw new Error("expected reservation");
  515. }
  516. expect(hook.result.current.commitAutomaticCompletion(attempt!.reservation)).toBe(true);
  517. expect(
  518. store.getState().codingPlanQuotaResetUiBySource.src?.fiveHour?.observedAt,
  519. ).not.toBeNull();
  520. });
  521. it("Hook acquire busy 时保留自动完成候选", async () => {
  522. const harness = createBroadcastHarness({ claimStatus: "busy" });
  523. const store = createZCodeStore(harness.service);
  524. const usedAt = 34_567;
  525. mocks.services = {
  526. usageStatsService: createUsageStatsService({
  527. getCodingPlanResetStatus: vi.fn(async () =>
  528. status({
  529. hasUnreadHistory: true,
  530. latestWeekResetHistory: { usedAt },
  531. }),
  532. ),
  533. }),
  534. };
  535. const hook = renderHook(
  536. () =>
  537. useCodingPlanQuotaResetUi({
  538. sourceKey: "src",
  539. preferredProviderId: "p",
  540. accountAccess: TEST_ACCOUNT_ACCESS,
  541. }),
  542. { wrapper: wrapperFor(store) },
  543. );
  544. await waitFor(() => expect(hook.result.current.week.done).toBe(true));
  545. let attempt: Awaited<ReturnType<typeof hook.result.current.reserveAutomaticCompletion>>;
  546. await act(async () => {
  547. attempt = await hook.result.current.reserveAutomaticCompletion("WEEK", usedAt);
  548. });
  549. expect(attempt!).toEqual({ status: "retry", retryAfterMs: 100 });
  550. expect(store.getState().codingPlanQuotaResetUiBySource.src?.week?.observedAt).not.toBeNull();
  551. });
  552. it("观察到未读完成后立即上报 history/read,不等待 entitlement 刷新", async () => {
  553. const harness = createBroadcastHarness();
  554. const store = createZCodeStore(harness.service);
  555. const usedAt = 45_678;
  556. const markCodingPlanResetHistoryRead = vi.fn(async () => undefined);
  557. mocks.services = {
  558. usageStatsService: createUsageStatsService({
  559. getCodingPlanResetStatus: vi.fn(async () =>
  560. status({
  561. hasUnreadHistory: true,
  562. latestFiveHourResetHistory: { usedAt },
  563. }),
  564. ),
  565. markCodingPlanResetHistoryRead,
  566. }),
  567. };
  568. renderHook(
  569. () =>
  570. useCodingPlanQuotaResetUi({
  571. sourceKey: "src",
  572. preferredProviderId: "p",
  573. accountAccess: TEST_ACCOUNT_ACCESS,
  574. // 永不 resolve:旧实现 await 刷新后才上报已读,此测试会超时失败。
  575. onEntitlementRefresh: () => new Promise<void>(() => {}),
  576. }),
  577. { wrapper: wrapperFor(store) },
  578. );
  579. await waitFor(() => expect(markCodingPlanResetHistoryRead).toHaveBeenCalledTimes(1));
  580. });
  581. });
  582. describe("pruneCodingPlanQuotaResetConfettiArms", () => {
  583. it("清除已被抑制或被新 used_at 取代的补播撒花 arm", () => {
  584. expect(
  585. pruneCodingPlanQuotaResetConfettiArms(
  586. { FIVE_HOUR: 100, WEEK: 200 },
  587. { FIVE_HOUR: null, WEEK: null },
  588. ),
  589. ).toEqual({ FIVE_HOUR: null, WEEK: null });
  590. expect(
  591. pruneCodingPlanQuotaResetConfettiArms(
  592. { FIVE_HOUR: 100, WEEK: 200 },
  593. { FIVE_HOUR: 300, WEEK: 200 },
  594. ),
  595. ).toEqual({ FIVE_HOUR: null, WEEK: 200 });
  596. const unchanged = { FIVE_HOUR: 100 as number | null, WEEK: null };
  597. expect(
  598. pruneCodingPlanQuotaResetConfettiArms(unchanged, {
  599. FIVE_HOUR: 100,
  600. WEEK: null,
  601. }),
  602. ).toBe(unchanged);
  603. });
  604. });