chatContextUsageBreakdown.test.ts 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. // @vitest-environment jsdom
  2. import { createElement, type ComponentProps } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  7. import {
  8. ChatCodingPlanUsageRemainingPanel,
  9. hasChatCodingPlanUsageRemaining,
  10. shouldShowContextQuotaResetTime,
  11. } from "../src/chat-input-toolbar/CodingPlanContextUsage.js";
  12. import {
  13. ChatStartPlanBalancePanel,
  14. hasChatStartPlanBalance,
  15. } from "../src/chat-input-toolbar/StartPlanContextBalance.js";
  16. import {
  17. ChatContextUsage,
  18. buildContextUsageBreakdownSegments,
  19. formatContextCacheHitRateLabel,
  20. formatContextUsageSummary,
  21. formatContextUsageTokenCount,
  22. refreshContextUsageOnOpen,
  23. } from "../src/chat-input-toolbar/contextUsage.js";
  24. import {
  25. CodingPlanUsageRemainingPanel,
  26. type CodingPlanUsageAvailableProvider,
  27. hasCodingPlanUsageRemainingPanel,
  28. resolveCodingPlanUsageRemainingState,
  29. } from "../src/CodingPlanUsageRemainingPanel.js";
  30. import {
  31. resolveSidebarCodingPlanUpgradeFallbackProviderId,
  32. resolveSidebarCodingPlanUpgradeProviderId,
  33. } from "../src/lib/sidebarCodingPlanUpgrade.js";
  34. import { TooltipProvider } from "../src/components/ui/tooltip.js";
  35. const activeSubscription = {
  36. identityType: "unknown" as const,
  37. identityMasked: null,
  38. details: [{ productId: "coding-pro", productName: "Coding Pro" }],
  39. };
  40. const codingPlanQuotaResetUiMock = vi.hoisted(() => {
  41. const createController = () => ({
  42. entry: null,
  43. opportunityVisible: false,
  44. processing: false,
  45. done: false,
  46. statusVisible: false,
  47. reset: vi.fn(async () => undefined),
  48. });
  49. const createValue = () => ({
  50. enabled: false,
  51. ...createController(),
  52. week: createController(),
  53. reserveAutomaticCompletion: vi.fn(async () => ({ status: "blocked" })),
  54. commitAutomaticCompletion: vi.fn(() => false),
  55. releaseAutomaticCompletion: vi.fn(async () => undefined),
  56. });
  57. return { current: createValue() as unknown, createValue };
  58. });
  59. vi.mock("@/hooks/useCodingPlanQuotaResetUi.js", () => ({
  60. useCodingPlanQuotaResetUi: () => codingPlanQuotaResetUiMock.current,
  61. }));
  62. vi.mock("../src/CodingPlanBillingDiscount.js", () => ({
  63. CodingPlanBillingDiscountBadge: ({ size, variant }: { size?: string; variant?: string }) =>
  64. `billing-discount-badge:${variant ?? "gradient"}:${size ?? "default"}`,
  65. CodingPlanBillingDiscountBadgePill: ({ size, variant }: { size?: string; variant?: string }) =>
  66. `billing-discount-badge:${variant ?? "gradient"}:${size ?? "default"}`,
  67. CodingPlanBillingDiscountInfoDialog: () => "billing-discount-info",
  68. useCodingPlanBillingDiscount: () => ({ active: true, loading: false }),
  69. }));
  70. describe("context usage access refresh", () => {
  71. it("只在 Context 打开时触发后台额度刷新", () => {
  72. const onAccess = vi.fn();
  73. refreshContextUsageOnOpen(false, onAccess);
  74. refreshContextUsageOnOpen(true, onAccess);
  75. expect(onAccess).toHaveBeenCalledTimes(1);
  76. });
  77. it("无缓存快照时仍保留 hover 触发器", () => {
  78. expect(
  79. hasChatCodingPlanUsageRemaining({
  80. availableProviders: [],
  81. entitlements: [
  82. {
  83. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  84. snapshot: null,
  85. loading: false,
  86. error: null,
  87. },
  88. ],
  89. modelProvidersLoading: false,
  90. onAccess: vi.fn(),
  91. }),
  92. ).toBe(true);
  93. });
  94. });
  95. vi.mock("../src/i18n/IntlProvider.js", () => ({
  96. useZCodeIntl: () => ({
  97. locale: "en-US",
  98. intl: {
  99. formatMessage: ({ id }: { id: string }) => id,
  100. },
  101. }),
  102. }));
  103. vi.mock("@/components/ai-elements/context.js", async () => {
  104. const React = await import("react");
  105. const passthrough =
  106. (tag: "button" | "div") =>
  107. ({ children, ...props }: { children?: React.ReactNode }) =>
  108. React.createElement(tag, props, children);
  109. return {
  110. Context: passthrough("div"),
  111. ContextContent: passthrough("div"),
  112. ContextContentBody: passthrough("div"),
  113. ContextTrigger: passthrough("button"),
  114. };
  115. });
  116. afterEach(() => {
  117. codingPlanQuotaResetUiMock.current = codingPlanQuotaResetUiMock.createValue();
  118. cleanup();
  119. vi.useRealTimers();
  120. });
  121. function createCodingPlanProvider(
  122. id:
  123. | typeof BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
  124. | typeof BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  125. ): CodingPlanUsageAvailableProvider {
  126. return {
  127. providerId: id,
  128. label: id,
  129. };
  130. }
  131. function renderFiveHourResetPanel() {
  132. const availableProviders = [
  133. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  134. ];
  135. // 完成态会用 nextResetAt 兜底展示重置时间(带 Tooltip);真实应用中面板总在 TooltipProvider 下。
  136. render(
  137. createElement(
  138. TooltipProvider,
  139. null,
  140. createElement(ChatCodingPlanUsageRemainingPanel, {
  141. config: {
  142. availableProviders,
  143. entitlements: [
  144. {
  145. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  146. loading: false,
  147. error: null,
  148. snapshot: {
  149. generatedAt: 1,
  150. authenticated: true,
  151. provider: {
  152. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  153. name: "Z.ai Coding Plan",
  154. },
  155. remaining: null,
  156. subscription: activeSubscription,
  157. quota: {
  158. level: "pro",
  159. limits: [
  160. {
  161. type: "TOKENS_LIMIT",
  162. unit: 3,
  163. number: 5,
  164. percentage: 35,
  165. usageDetails: [],
  166. },
  167. ],
  168. },
  169. },
  170. },
  171. ],
  172. modelProvidersLoading: false,
  173. },
  174. intl: {
  175. formatMessage: ({ id }: { id: string }) => id,
  176. } as never,
  177. locale: "en-US",
  178. }),
  179. ),
  180. );
  181. }
  182. describe("ChatCodingPlanUsageRemainingPanel reset action", () => {
  183. it("五小时有两次重置机会时仍在额度标题旁显示直接重置按钮", () => {
  184. const reset = vi.fn(async () => undefined);
  185. codingPlanQuotaResetUiMock.current = {
  186. ...codingPlanQuotaResetUiMock.createValue(),
  187. enabled: true,
  188. entry: {
  189. status: "available",
  190. opportunityCount: 2,
  191. opportunityExpiresAt: Date.now() + 60_000,
  192. startedAt: null,
  193. completedAt: null,
  194. observedAt: null,
  195. quotaOverridePending: false,
  196. nextResetAt: null,
  197. idempotencyKey: "five-hour-two-opportunities",
  198. error: null,
  199. },
  200. opportunityVisible: true,
  201. reset,
  202. };
  203. renderFiveHourResetPanel();
  204. expect(screen.getByRole("button", { name: "codingPlan.quotaReset.openDialog" })).toBeTruthy();
  205. expect(screen.getByRole("button", { name: "codingPlan.quotaReset.resetAria" })).toBeTruthy();
  206. });
  207. it("核销一张后同类型仍有余下机会时,额度标题旁保持可点击「重置」而非「已重置」", () => {
  208. const completedAt = Date.now() - 1_000;
  209. codingPlanQuotaResetUiMock.current = {
  210. ...codingPlanQuotaResetUiMock.createValue(),
  211. enabled: true,
  212. entry: {
  213. status: "completed",
  214. opportunityCount: 1,
  215. opportunityExpiresAt: Date.now() + 60_000,
  216. startedAt: completedAt - 1_000,
  217. completedAt,
  218. observedAt: completedAt,
  219. quotaOverridePending: false,
  220. nextResetAt: completedAt + 5 * 60 * 60 * 1_000,
  221. idempotencyKey: null,
  222. error: null,
  223. },
  224. opportunityVisible: true,
  225. done: true,
  226. };
  227. renderFiveHourResetPanel();
  228. expect(screen.getByRole("button", { name: "codingPlan.quotaReset.resetAria" })).toBeTruthy();
  229. expect(screen.queryByText("codingPlan.quotaReset.completed")).toBeNull();
  230. });
  231. });
  232. describe("ChatCodingPlanUsageRemainingPanel MCP 额度", () => {
  233. it("从三类主额度与 MCP 混合快照展示真实剩余额度和桶日期", () => {
  234. codingPlanQuotaResetUiMock.current = codingPlanQuotaResetUiMock.createValue();
  235. const html = renderToStaticMarkup(
  236. createElement(ChatCodingPlanUsageRemainingPanel, {
  237. config: {
  238. availableProviders: [
  239. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  240. ],
  241. entitlements: [
  242. {
  243. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  244. loading: false,
  245. error: null,
  246. snapshot: {
  247. generatedAt: 1,
  248. authenticated: true,
  249. provider: {
  250. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  251. name: "Z.ai Coding Plan",
  252. },
  253. remaining: null,
  254. subscription: activeSubscription,
  255. quota: {
  256. level: "pro",
  257. limits: [
  258. { type: "TOKENS_LIMIT", unit: 3, number: 5, percentage: 2, usageDetails: [] },
  259. { type: "TOKENS_LIMIT", unit: 6, percentage: 1, usageDetails: [] },
  260. { type: "TIME_LIMIT", unit: 5, number: 1, percentage: 0, usageDetails: [] },
  261. ],
  262. },
  263. mcpQuota: {
  264. serverTime: 1_755_571_234_000,
  265. level: "pro",
  266. scope: { providerFamily: "zai", targetType: "PERSONAL" },
  267. buckets: [{ bucket: "search_image", used: 25, limit: 100, remaining: 75 }],
  268. aggregate: {
  269. type: "MCP_USAGE_LIMIT",
  270. percentage: 25,
  271. remaining: 75,
  272. nextResetTime: Date.UTC(2025, 7, 21),
  273. usageDetails: [],
  274. },
  275. },
  276. },
  277. },
  278. ],
  279. modelProvidersLoading: false,
  280. },
  281. intl: {
  282. formatMessage: ({ id }: { id: string }) => id,
  283. } as never,
  284. locale: "en-US",
  285. }),
  286. );
  287. expect(html).toContain('data-context-mcp-usage="inline"');
  288. expect(html).toContain('data-primary-quota-count="3"');
  289. expect(html).toContain("sidebar.usage.plan.zcodeMcp");
  290. expect(html).toContain('data-context-mcp-info="true"');
  291. expect(html).toContain('aria-label="sidebar.usage.plan.zcodeMcpDescription"');
  292. // percentage 是已使用占比,展示时反转成剩余。
  293. expect(html).toContain("75%");
  294. expect(html).toMatch(/>75%<\/span><span[^>]*> · Aug 21<\/span>/);
  295. expect(html).toContain("width:75%");
  296. });
  297. it("没有 MCP 额度时不展示 MCP", () => {
  298. codingPlanQuotaResetUiMock.current = codingPlanQuotaResetUiMock.createValue();
  299. const html = renderToStaticMarkup(
  300. createElement(ChatCodingPlanUsageRemainingPanel, {
  301. config: {
  302. availableProviders: [
  303. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  304. ],
  305. entitlements: [
  306. {
  307. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  308. loading: false,
  309. error: null,
  310. snapshot: {
  311. generatedAt: 1,
  312. authenticated: true,
  313. provider: {
  314. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  315. name: "Z.ai Coding Plan",
  316. },
  317. remaining: null,
  318. subscription: activeSubscription,
  319. quota: {
  320. level: "pro",
  321. limits: [
  322. { type: "TOKENS_LIMIT", unit: 3, number: 5, percentage: 2, usageDetails: [] },
  323. { type: "TOKENS_LIMIT", unit: 6, percentage: 1, usageDetails: [] },
  324. { type: "TIME_LIMIT", unit: 5, number: 1, percentage: 0, usageDetails: [] },
  325. ],
  326. },
  327. },
  328. },
  329. ],
  330. modelProvidersLoading: false,
  331. },
  332. intl: {
  333. formatMessage: ({ id }: { id: string }) => id,
  334. } as never,
  335. locale: "en-US",
  336. }),
  337. );
  338. expect(html).not.toContain("sidebar.usage.plan.mcp");
  339. });
  340. });
  341. describe("ChatCodingPlanUsageRemainingPanel refresh action", () => {
  342. it("远端刷新成功时用 loading 与成功勾临时代替详情入口", () => {
  343. vi.useFakeTimers();
  344. const availableProviders = [
  345. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  346. ];
  347. const entitlement = {
  348. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  349. loading: true,
  350. error: null,
  351. snapshot: {
  352. generatedAt: 1,
  353. authenticated: true,
  354. provider: {
  355. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  356. name: "Z.ai Coding Plan",
  357. },
  358. remaining: null,
  359. subscription: activeSubscription,
  360. quota: {
  361. level: "pro",
  362. limits: [
  363. {
  364. type: "TOKENS_LIMIT",
  365. unit: 3,
  366. number: 5,
  367. percentage: 35,
  368. usageDetails: [],
  369. },
  370. ],
  371. },
  372. },
  373. } satisfies ComponentProps<
  374. typeof ChatCodingPlanUsageRemainingPanel
  375. >["config"]["entitlements"][number];
  376. const props = {
  377. config: {
  378. availableProviders,
  379. entitlements: [entitlement],
  380. modelProvidersLoading: false,
  381. onUsageClick: vi.fn(),
  382. },
  383. intl: {
  384. formatMessage: ({ id }: { id: string }) => id,
  385. } as never,
  386. locale: "en-US",
  387. } satisfies ComponentProps<typeof ChatCodingPlanUsageRemainingPanel>;
  388. const view = render(createElement(ChatCodingPlanUsageRemainingPanel, props));
  389. expect(screen.queryByRole("button", { name: "sidebar.usage.plan.open" })).toBeNull();
  390. expect(screen.getByRole("status", { name: "sidebar.usage.plan.refreshing" })).toBeTruthy();
  391. view.rerender(
  392. createElement(ChatCodingPlanUsageRemainingPanel, {
  393. ...props,
  394. config: {
  395. ...props.config,
  396. entitlements: [{ ...entitlement, loading: false }],
  397. },
  398. }),
  399. );
  400. expect(screen.queryByRole("button", { name: "sidebar.usage.plan.open" })).toBeNull();
  401. expect(screen.getByRole("status", { name: "sidebar.usage.plan.updated" })).toBeTruthy();
  402. act(() => vi.advanceTimersByTime(1_000));
  403. expect(screen.queryByRole("status", { name: "sidebar.usage.plan.updated" })).toBeNull();
  404. expect(screen.getByRole("button", { name: "sidebar.usage.plan.open" })).toBeTruthy();
  405. });
  406. it("静默 access 刷新中即使缓存快照不标记 loading 也显示 loading", () => {
  407. const availableProviders = [
  408. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  409. ];
  410. const entitlement = {
  411. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  412. loading: false,
  413. error: null,
  414. snapshot: {
  415. generatedAt: 1,
  416. authenticated: true,
  417. provider: {
  418. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  419. name: "Z.ai Coding Plan",
  420. },
  421. remaining: null,
  422. subscription: activeSubscription,
  423. quota: {
  424. level: "pro",
  425. limits: [
  426. {
  427. type: "TOKENS_LIMIT",
  428. unit: 3,
  429. number: 5,
  430. percentage: 35,
  431. usageDetails: [],
  432. },
  433. ],
  434. },
  435. },
  436. } satisfies ComponentProps<
  437. typeof ChatCodingPlanUsageRemainingPanel
  438. >["config"]["entitlements"][number];
  439. render(
  440. createElement(ChatCodingPlanUsageRemainingPanel, {
  441. config: {
  442. availableProviders,
  443. entitlements: [entitlement],
  444. modelProvidersLoading: false,
  445. refreshing: true,
  446. onUsageClick: vi.fn(),
  447. },
  448. intl: {
  449. formatMessage: ({ id }: { id: string }) => id,
  450. } as never,
  451. locale: "en-US",
  452. }),
  453. );
  454. expect(screen.queryByRole("button", { name: "sidebar.usage.plan.open" })).toBeNull();
  455. expect(screen.getByRole("status", { name: "sidebar.usage.plan.refreshing" })).toBeTruthy();
  456. });
  457. it("有缓存快照刷新失败时在更多旁边显示 warning info tooltip", () => {
  458. const availableProviders = [
  459. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  460. ];
  461. const onEntitlementRefresh = vi.fn();
  462. const view = render(
  463. createElement(ChatCodingPlanUsageRemainingPanel, {
  464. config: {
  465. availableProviders,
  466. entitlements: [
  467. {
  468. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  469. loading: false,
  470. error: "usage_entitlement_request_timeout:20000",
  471. snapshot: {
  472. generatedAt: 1,
  473. authenticated: true,
  474. provider: {
  475. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  476. name: "Z.ai Coding Plan",
  477. },
  478. remaining: null,
  479. subscription: activeSubscription,
  480. quota: {
  481. level: "pro",
  482. limits: [
  483. {
  484. type: "TOKENS_LIMIT",
  485. unit: 3,
  486. number: 5,
  487. percentage: 35,
  488. usageDetails: [],
  489. },
  490. ],
  491. },
  492. },
  493. },
  494. ],
  495. modelProvidersLoading: false,
  496. onEntitlementRefresh,
  497. onUsageClick: vi.fn(),
  498. },
  499. intl: {
  500. formatMessage: ({ id }: { id: string }) => id,
  501. } as never,
  502. locale: "en-US",
  503. }),
  504. );
  505. expect(view.container.textContent).toContain("sidebar.usage.plan.fiveHour");
  506. expect(view.container.textContent).not.toContain("usage_entitlement_request_timeout");
  507. expect(screen.getByLabelText("sidebar.usage.plan.updateFailed")).toBeTruthy();
  508. expect(screen.getByRole("button", { name: "sidebar.usage.plan.open" })).toBeTruthy();
  509. expect(screen.queryByRole("button", { name: "sidebar.usage.plan.refresh" })).toBeNull();
  510. });
  511. it("无可展示额度时复用 info notice 和刷新按钮", () => {
  512. const availableProviders = [
  513. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  514. ];
  515. const onEntitlementRefresh = vi.fn();
  516. const view = render(
  517. createElement(ChatCodingPlanUsageRemainingPanel, {
  518. config: {
  519. availableProviders,
  520. entitlements: [
  521. {
  522. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  523. loading: false,
  524. error: null,
  525. snapshot: {
  526. generatedAt: 1,
  527. authenticated: true,
  528. provider: {
  529. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  530. name: "Z.ai Coding Plan",
  531. },
  532. remaining: null,
  533. subscription: activeSubscription,
  534. quota: {
  535. level: null,
  536. limits: [],
  537. },
  538. },
  539. },
  540. ],
  541. modelProvidersLoading: false,
  542. onEntitlementRefresh,
  543. },
  544. intl: {
  545. formatMessage: ({ id }: { id: string }) => id,
  546. } as never,
  547. locale: "en-US",
  548. }),
  549. );
  550. expect(view.container.textContent).toContain("sidebar.usage.plan.unavailable");
  551. expect(view.container.innerHTML).toContain("data-coding-plan-usage-notice");
  552. expect(screen.getByRole("button", { name: "sidebar.usage.plan.refresh" })).toBeTruthy();
  553. });
  554. });
  555. describe("buildContextUsageBreakdownSegments", () => {
  556. it("aggregates valid chars by source and sorts largest first", () => {
  557. expect(
  558. buildContextUsageBreakdownSegments([
  559. { source: "messages", chars: 700 },
  560. { source: "system_tool_schemas", chars: 200 },
  561. { source: "messages", chars: 100 },
  562. { source: "skills", chars: 0 },
  563. ]),
  564. ).toEqual([
  565. { source: "messages", chars: 800, percent: 0.8 },
  566. { source: "system_tool_schemas", chars: 200, percent: 0.2 },
  567. ]);
  568. });
  569. it("returns an empty list when no positive chars are available", () => {
  570. expect(
  571. buildContextUsageBreakdownSegments([
  572. { source: "messages", chars: 0 },
  573. { source: "skills", chars: -1 },
  574. ]),
  575. ).toEqual([]);
  576. });
  577. });
  578. describe("formatContextUsageTokenCount", () => {
  579. it("uses uppercase compact suffixes for English context usage", () => {
  580. expect(formatContextUsageTokenCount(399_900, "en-US")).toBe("399.9K");
  581. expect(formatContextUsageTokenCount(200_000, "en-US")).toBe("200K");
  582. expect(formatContextUsageTokenCount(1_250_000, "en-US")).toBe("1.3M");
  583. });
  584. it("uses localized compact units for Chinese context usage", () => {
  585. expect(formatContextUsageTokenCount(399_900, "zh-CN")).toBe("40万");
  586. expect(formatContextUsageTokenCount(200_000, "zh-CN")).toBe("20万");
  587. expect(formatContextUsageTokenCount(120_000_000, "zh-CN")).toBe("1.2亿");
  588. });
  589. });
  590. describe("formatContextUsageSummary", () => {
  591. it("combines compact token values and usage percentage", () => {
  592. expect(
  593. formatContextUsageSummary({
  594. locale: "en-US",
  595. percent: 1,
  596. size: 200_000,
  597. used: 399_900,
  598. }),
  599. ).toBe("399.9K/200K (100%)");
  600. });
  601. });
  602. describe("formatContextCacheHitRateLabel", () => {
  603. it("keeps the production threshold for low cache hit rates", () => {
  604. expect(formatContextCacheHitRateLabel(0.048, "en-US")).toBeNull();
  605. });
  606. it("formats low cache hit rates when development diagnostics are enabled", () => {
  607. expect(
  608. formatContextCacheHitRateLabel(0.048, "en-US", {
  609. showBelowThreshold: true,
  610. }),
  611. ).toBe("4.8%");
  612. });
  613. it("does not invent a cache hit rate when the provider omits it", () => {
  614. expect(
  615. formatContextCacheHitRateLabel(null, "en-US", {
  616. showBelowThreshold: true,
  617. }),
  618. ).toBeNull();
  619. });
  620. });
  621. describe("ChatContextUsage", () => {
  622. it("在 Context 面板外点击时关闭额度重置提醒并清理监听器", async () => {
  623. codingPlanQuotaResetUiMock.current = {
  624. ...codingPlanQuotaResetUiMock.createValue(),
  625. enabled: true,
  626. entry: {
  627. status: "available",
  628. opportunityCount: 1,
  629. opportunityExpiresAt: Date.now() + 60_000,
  630. startedAt: null,
  631. completedAt: null,
  632. observedAt: null,
  633. quotaOverridePending: false,
  634. nextResetAt: null,
  635. idempotencyKey: "context-outside-dismiss",
  636. error: null,
  637. },
  638. opportunityVisible: true,
  639. };
  640. const provider = createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
  641. render(
  642. createElement(
  643. TooltipProvider,
  644. null,
  645. createElement(ChatContextUsage, {
  646. codingPlanUsageRemaining: {
  647. availableProviders: [provider],
  648. entitlements: [
  649. {
  650. providerId: provider.providerId,
  651. loading: false,
  652. error: null,
  653. snapshot: {
  654. generatedAt: 1,
  655. authenticated: true,
  656. provider: { id: provider.providerId, name: provider.label },
  657. remaining: null,
  658. subscription: activeSubscription,
  659. quota: {
  660. level: "pro",
  661. limits: [
  662. {
  663. type: "TOKENS_LIMIT",
  664. unit: 3,
  665. number: 5,
  666. percentage: 35,
  667. usageDetails: [],
  668. },
  669. ],
  670. },
  671. },
  672. },
  673. ],
  674. modelProvidersLoading: false,
  675. },
  676. intl: {
  677. formatMessage: ({ id }: { id: string }) => id,
  678. } as never,
  679. locale: "en-US",
  680. selectedProvider: "glm",
  681. taskUsage: null,
  682. }),
  683. ),
  684. );
  685. expect(
  686. screen.getAllByText("codingPlan.quotaReset.contextReminder.expiresIn").length,
  687. ).toBeGreaterThan(0);
  688. fireEvent.pointerDown(document.body);
  689. await waitFor(() => {
  690. expect(screen.queryAllByText("codingPlan.quotaReset.contextReminder.expiresIn")).toEqual([]);
  691. });
  692. });
  693. it("does not render derived zero-usage capacity without task usage or plan data", () => {
  694. const html = renderToStaticMarkup(
  695. createElement(ChatContextUsage, {
  696. ...({
  697. contextCapacityTokens: 1_000_000,
  698. } as Partial<ComponentProps<typeof ChatContextUsage>>),
  699. intl: {
  700. formatMessage: ({ id }: { id: string }) => id,
  701. },
  702. locale: "en-US",
  703. selectedProvider: "glm",
  704. taskUsage: null,
  705. }),
  706. );
  707. expect(html).not.toContain("chat.contextUsage.title");
  708. expect(html).not.toContain("0/1M (0%)");
  709. });
  710. it("renders cache hit rate when the context usage reaches the display threshold", () => {
  711. const html = renderToStaticMarkup(
  712. createElement(ChatContextUsage, {
  713. intl: {
  714. formatMessage: ({ id }: { id: string }) => id,
  715. },
  716. locale: "en-US",
  717. selectedProvider: "glm",
  718. taskUsage: {
  719. used: 17_000,
  720. size: 1_000_000,
  721. cache: { hitRate: 0.8 },
  722. },
  723. }),
  724. );
  725. expect(html).toContain("chat.contextUsage.cacheHitRate");
  726. expect(html).toContain("80%");
  727. });
  728. it("renders a low cache hit rate in the development environment", () => {
  729. const html = renderToStaticMarkup(
  730. createElement(ChatContextUsage, {
  731. intl: {
  732. formatMessage: ({ id }: { id: string }) => id,
  733. },
  734. locale: "en-US",
  735. selectedProvider: "glm",
  736. taskUsage: {
  737. used: 17_000,
  738. size: 1_000_000,
  739. cache: { hitRate: 0.048 },
  740. },
  741. }),
  742. );
  743. expect(import.meta.env.DEV).toBe(true);
  744. expect(html).toContain("chat.contextUsage.cacheHitRate");
  745. expect(html).toContain("4.8%");
  746. });
  747. it("renders Coding Plan quota without real task context usage", () => {
  748. const availableProviders = [
  749. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  750. ];
  751. const html = renderToStaticMarkup(
  752. createElement(ChatContextUsage, {
  753. codingPlanUsageRemaining: {
  754. availableProviders,
  755. entitlements: [
  756. {
  757. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  758. loading: false,
  759. error: null,
  760. snapshot: {
  761. generatedAt: 1,
  762. authenticated: true,
  763. provider: {
  764. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  765. name: "Z.ai Coding Plan",
  766. },
  767. remaining: null,
  768. subscription: activeSubscription,
  769. quota: {
  770. level: "pro",
  771. limits: [
  772. {
  773. type: "TOKENS_LIMIT",
  774. unit: 3,
  775. number: 5,
  776. percentage: 35,
  777. usageDetails: [],
  778. },
  779. ],
  780. },
  781. },
  782. },
  783. ],
  784. modelProvidersLoading: false,
  785. },
  786. intl: {
  787. formatMessage: ({ id }: { id: string }) => id,
  788. } as never,
  789. locale: "en-US",
  790. selectedProvider: "glm",
  791. taskUsage: null,
  792. }),
  793. );
  794. expect(html).toContain("sidebar.usage.plan.title");
  795. expect(html).toContain("sidebar.usage.plan.fiveHour");
  796. });
  797. it("does not render per-source token counts in the breakdown rows", () => {
  798. const html = renderToStaticMarkup(
  799. createElement(ChatContextUsage, {
  800. intl: {
  801. formatMessage: ({ id }: { id: string }) => id,
  802. },
  803. locale: "en-US",
  804. selectedProvider: "glm",
  805. taskUsage: {
  806. used: 17_000,
  807. size: 1_000_000,
  808. breakdown: [
  809. { source: "system_tool_schemas", chars: 52_000 },
  810. { source: "messages", chars: 38_000 },
  811. ],
  812. },
  813. }),
  814. );
  815. expect(html).toContain("chat.contextUsage.breakdown.systemTools");
  816. expect(html).toContain("chat.contextUsage.breakdown.messages");
  817. expect(html).toContain("57.8%");
  818. expect(html).toContain("42.2%");
  819. expect(html).not.toContain("52K");
  820. expect(html).not.toContain("38K");
  821. });
  822. });
  823. describe("Coding Plan usage remaining panel state", () => {
  824. it("does not show the billing discount badge in sidebar usage remaining", () => {
  825. const availableProviders = [
  826. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  827. ];
  828. const html = renderToStaticMarkup(
  829. createElement(CodingPlanUsageRemainingPanel, {
  830. availableProviders,
  831. entitlements: [
  832. {
  833. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  834. loading: false,
  835. error: null,
  836. snapshot: {
  837. generatedAt: 1,
  838. authenticated: true,
  839. provider: {
  840. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  841. name: "Z.ai Coding Plan",
  842. },
  843. remaining: null,
  844. subscription: activeSubscription,
  845. quota: {
  846. level: "pro",
  847. limits: [],
  848. },
  849. },
  850. },
  851. ],
  852. modelProvidersLoading: false,
  853. }),
  854. );
  855. expect(html).toContain("sidebar.usage.plan.codingPlanTitle");
  856. expect(html).not.toContain("billing-discount-badge");
  857. });
  858. it("renders a single sidebar audience badge without source tabs", () => {
  859. const availableProviders = [
  860. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan),
  861. ];
  862. const html = renderToStaticMarkup(
  863. createElement(CodingPlanUsageRemainingPanel, {
  864. audience: "team",
  865. availableProviders,
  866. entitlements: [
  867. {
  868. sourceId: "team:bigmodel:team-pro:project-a",
  869. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  870. label: "BigModel - Project A",
  871. loading: false,
  872. error: null,
  873. snapshot: {
  874. generatedAt: 1,
  875. authenticated: true,
  876. provider: {
  877. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  878. name: "BigModel Coding Plan",
  879. },
  880. remaining: null,
  881. subscription: activeSubscription,
  882. quota: {
  883. level: "team",
  884. limits: [
  885. {
  886. type: "TOKENS_LIMIT",
  887. unit: 3,
  888. number: 5,
  889. percentage: 80,
  890. usageDetails: [],
  891. },
  892. ],
  893. },
  894. },
  895. },
  896. {
  897. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  898. loading: false,
  899. error: null,
  900. snapshot: {
  901. generatedAt: 1,
  902. authenticated: true,
  903. provider: {
  904. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  905. name: "BigModel Coding Plan",
  906. },
  907. remaining: null,
  908. subscription: activeSubscription,
  909. quota: {
  910. level: "pro",
  911. limits: [
  912. {
  913. type: "TOKENS_LIMIT",
  914. unit: 6,
  915. percentage: 50,
  916. usageDetails: [],
  917. },
  918. ],
  919. },
  920. },
  921. },
  922. ],
  923. modelProvidersLoading: false,
  924. selectedProviderId: "team:bigmodel:team-pro:project-a",
  925. }),
  926. );
  927. expect(html).toContain("sidebar.usage.plan.codingPlanTitle");
  928. expect(html).toContain("sidebar.usage.plan.audienceTeam");
  929. expect(html).not.toContain("aria-pressed");
  930. });
  931. it("会话 Coding Plan 用量面板不显示 150% 活动徽标", () => {
  932. const availableProviders = [
  933. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  934. ];
  935. const html = renderToStaticMarkup(
  936. createElement(ChatCodingPlanUsageRemainingPanel, {
  937. config: {
  938. availableProviders,
  939. entitlements: [
  940. {
  941. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  942. loading: false,
  943. error: null,
  944. snapshot: {
  945. generatedAt: 1,
  946. authenticated: true,
  947. provider: {
  948. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  949. name: "Z.ai Coding Plan",
  950. },
  951. remaining: null,
  952. subscription: activeSubscription,
  953. quota: {
  954. level: "pro",
  955. limits: [
  956. {
  957. type: "TOKENS_LIMIT",
  958. unit: 3,
  959. number: 5,
  960. percentage: 35,
  961. nextResetTime: Date.UTC(2026, 0, 2, 8, 30),
  962. usageDetails: [],
  963. },
  964. {
  965. type: "TOKENS_LIMIT",
  966. unit: 6,
  967. percentage: 45,
  968. nextResetTime: Date.UTC(2026, 0, 9, 0, 0),
  969. usageDetails: [],
  970. },
  971. {
  972. type: "TIME_LIMIT",
  973. unit: 5,
  974. number: 1,
  975. percentage: 55,
  976. nextResetTime: Date.UTC(2026, 0, 31, 0, 0),
  977. usageDetails: [],
  978. },
  979. ],
  980. },
  981. },
  982. },
  983. ],
  984. modelProvidersLoading: false,
  985. },
  986. intl: {
  987. formatMessage: ({ id }: { id: string }) => id,
  988. } as never,
  989. locale: "en-US",
  990. }),
  991. );
  992. expect(html).toContain("sidebar.usage.plan.title");
  993. expect(html).not.toContain("billing-discount-badge:gradient:compact");
  994. });
  995. it("hides a Coding Plan reset time when its full value exceeds the meter width", () => {
  996. expect(shouldShowContextQuotaResetTime({ availableWidth: 120, contentWidth: 119 })).toBe(true);
  997. expect(shouldShowContextQuotaResetTime({ availableWidth: 120, contentWidth: 121 })).toBe(false);
  998. });
  999. it("shows only time for non-today 5 hour Coding Plan reset in chat context usage", () => {
  1000. vi.useFakeTimers();
  1001. vi.setSystemTime(new Date(2026, 0, 2, 7, 0));
  1002. try {
  1003. const availableProviders = [
  1004. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  1005. ];
  1006. const html = renderToStaticMarkup(
  1007. createElement(ChatCodingPlanUsageRemainingPanel, {
  1008. config: {
  1009. availableProviders,
  1010. entitlements: [
  1011. {
  1012. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1013. loading: false,
  1014. error: null,
  1015. snapshot: {
  1016. generatedAt: 1,
  1017. authenticated: true,
  1018. provider: {
  1019. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1020. name: "Z.ai Coding Plan",
  1021. },
  1022. remaining: null,
  1023. subscription: activeSubscription,
  1024. quota: {
  1025. level: "pro",
  1026. limits: [
  1027. {
  1028. type: "TOKENS_LIMIT",
  1029. unit: 3,
  1030. number: 5,
  1031. percentage: 35,
  1032. nextResetTime: new Date(2026, 0, 3, 8, 30).getTime(),
  1033. usageDetails: [],
  1034. },
  1035. ],
  1036. },
  1037. },
  1038. },
  1039. ],
  1040. modelProvidersLoading: false,
  1041. },
  1042. intl: {
  1043. formatMessage: ({ id }: { id: string }) => id,
  1044. } as never,
  1045. locale: "en-US",
  1046. }),
  1047. );
  1048. expect(html).toContain(" · 08:30");
  1049. expect(html).not.toContain("Jan 3");
  1050. } finally {
  1051. vi.useRealTimers();
  1052. }
  1053. });
  1054. it("is renderable from entitlement data even without task context usage", () => {
  1055. const availableProviders = [
  1056. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  1057. ];
  1058. const entitlements = [
  1059. {
  1060. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1061. loading: false,
  1062. error: null,
  1063. snapshot: {
  1064. generatedAt: 1,
  1065. authenticated: true,
  1066. provider: {
  1067. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1068. name: "Z.ai Coding Plan",
  1069. },
  1070. remaining: null,
  1071. subscription: activeSubscription,
  1072. quota: {
  1073. level: "pro",
  1074. limits: [],
  1075. },
  1076. },
  1077. },
  1078. ];
  1079. expect(
  1080. hasCodingPlanUsageRemainingPanel({
  1081. availableProviders,
  1082. entitlements,
  1083. modelProvidersLoading: false,
  1084. }),
  1085. ).toBe(true);
  1086. expect(
  1087. resolveCodingPlanUsageRemainingState({
  1088. availableProviders,
  1089. entitlements,
  1090. modelProvidersLoading: false,
  1091. })?.activeProviderId,
  1092. ).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
  1093. });
  1094. it("keeps Team Plan usage renderable without a personal Coding Plan provider", () => {
  1095. const entitlements = [
  1096. {
  1097. sourceId: "team:bigmodel:team-pro:org-a:project-a",
  1098. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  1099. accountAccess: {
  1100. type: "zhipu-account" as const,
  1101. family: "bigmodel" as const,
  1102. planKind: "team-coding-plan" as const,
  1103. productId: "team-pro",
  1104. organizationId: "org-a",
  1105. projectId: "project-a",
  1106. },
  1107. label: "BigModel - Project A",
  1108. loading: false,
  1109. error: null,
  1110. snapshot: {
  1111. generatedAt: 1,
  1112. authenticated: true,
  1113. provider: {
  1114. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  1115. name: "BigModel Coding Plan",
  1116. },
  1117. remaining: null,
  1118. subscription: activeSubscription,
  1119. quota: {
  1120. level: "team",
  1121. limits: [
  1122. {
  1123. type: "TOKENS_LIMIT",
  1124. unit: 3,
  1125. number: 5,
  1126. percentage: 80,
  1127. usageDetails: [],
  1128. },
  1129. ],
  1130. },
  1131. },
  1132. },
  1133. ];
  1134. expect(
  1135. hasCodingPlanUsageRemainingPanel({
  1136. availableProviders: [],
  1137. entitlements,
  1138. modelProvidersLoading: false,
  1139. selectedProviderId: "team:bigmodel:team-pro:org-a:project-a",
  1140. }),
  1141. ).toBe(true);
  1142. expect(
  1143. resolveCodingPlanUsageRemainingState({
  1144. availableProviders: [],
  1145. entitlements,
  1146. modelProvidersLoading: false,
  1147. selectedProviderId: "team:bigmodel:team-pro:org-a:project-a",
  1148. })?.activeProviderId,
  1149. ).toBe("team:bigmodel:team-pro:org-a:project-a");
  1150. });
  1151. it("shows the sidebar upgrade entry for authenticated users without an active plan", () => {
  1152. const availableProviders = [
  1153. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  1154. ];
  1155. const entitlements = [
  1156. {
  1157. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1158. loading: false,
  1159. error: null,
  1160. snapshot: {
  1161. generatedAt: 1,
  1162. authenticated: true,
  1163. unavailableReason: "no_plan" as const,
  1164. provider: {
  1165. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1166. name: "Z.ai Coding Plan",
  1167. },
  1168. remaining: null,
  1169. subscription: null,
  1170. quota: null,
  1171. },
  1172. },
  1173. ];
  1174. expect(
  1175. resolveSidebarCodingPlanUpgradeProviderId({
  1176. availableProviders,
  1177. entitlements,
  1178. modelProvidersLoading: false,
  1179. }),
  1180. ).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
  1181. });
  1182. it("falls back to the current provider family for the profile upgrade entry", () => {
  1183. expect(resolveSidebarCodingPlanUpgradeFallbackProviderId("bigmodel")).toBe(
  1184. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1185. );
  1186. expect(resolveSidebarCodingPlanUpgradeFallbackProviderId("zai")).toBe(
  1187. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1188. );
  1189. expect(resolveSidebarCodingPlanUpgradeFallbackProviderId(null)).toBe(
  1190. BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1191. );
  1192. });
  1193. it("keeps the sidebar upgrade entry for max plan users", () => {
  1194. const availableProviders = [
  1195. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  1196. ];
  1197. const entitlements = [
  1198. {
  1199. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1200. loading: false,
  1201. error: null,
  1202. snapshot: {
  1203. generatedAt: 1,
  1204. authenticated: true,
  1205. provider: {
  1206. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1207. name: "Z.ai Coding Plan",
  1208. },
  1209. remaining: null,
  1210. subscription: {
  1211. identityType: "unknown" as const,
  1212. identityMasked: null,
  1213. details: [{ productId: "coding-max", productName: "Coding Max" }],
  1214. },
  1215. quota: {
  1216. level: "max",
  1217. limits: [],
  1218. },
  1219. },
  1220. },
  1221. ];
  1222. expect(
  1223. resolveSidebarCodingPlanUpgradeProviderId({
  1224. availableProviders,
  1225. entitlements,
  1226. modelProvidersLoading: false,
  1227. }),
  1228. ).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
  1229. });
  1230. it("hides the sidebar upgrade entry for team plan users", () => {
  1231. const availableProviders = [
  1232. createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  1233. ];
  1234. const entitlements = [
  1235. {
  1236. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1237. loading: false,
  1238. error: null,
  1239. snapshot: {
  1240. generatedAt: 1,
  1241. authenticated: true,
  1242. provider: {
  1243. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1244. name: "Z.ai Coding Plan",
  1245. },
  1246. remaining: null,
  1247. subscription: {
  1248. identityType: "unknown" as const,
  1249. identityMasked: null,
  1250. details: [
  1251. {
  1252. productId: "team-standard",
  1253. productName: "Team Standard",
  1254. },
  1255. ],
  1256. },
  1257. quota: null,
  1258. },
  1259. },
  1260. ];
  1261. expect(
  1262. resolveSidebarCodingPlanUpgradeProviderId({
  1263. availableProviders,
  1264. entitlements,
  1265. modelProvidersLoading: false,
  1266. }),
  1267. ).toBeUndefined();
  1268. });
  1269. });
  1270. describe("Start Plan context balance panel", () => {
  1271. it("renders Today's balance meters with an upgrade action", () => {
  1272. const html = renderToStaticMarkup(
  1273. createElement(ChatStartPlanBalancePanel, {
  1274. config: {
  1275. loading: false,
  1276. onUpgradeClick: vi.fn(),
  1277. snapshot: {
  1278. generatedAt: new Date(2026, 5, 13, 8, 15).getTime(),
  1279. authenticated: true,
  1280. provider: {
  1281. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  1282. name: "Z.ai Start Plan",
  1283. },
  1284. remaining: null,
  1285. subscription: {
  1286. identityType: "unknown",
  1287. identityMasked: null,
  1288. details: [
  1289. {
  1290. productId: "zcode-v3-start-plan",
  1291. productName: "ZCode Start Plan",
  1292. purchaseTime: null,
  1293. beginTime: null,
  1294. renewTime: new Date(2026, 5, 13, 10, 0).toISOString(),
  1295. expireTime: new Date(2026, 5, 20, 23, 59).toISOString(),
  1296. },
  1297. ],
  1298. },
  1299. quota: {
  1300. level: "Start",
  1301. limits: [
  1302. {
  1303. type: "TOKENS_LIMIT",
  1304. number: 1_000_000,
  1305. remaining: 750_000,
  1306. usage: 250_000,
  1307. nextResetTime: new Date(2026, 5, 14, 23, 2).getTime(),
  1308. usageDetails: [
  1309. {
  1310. modelCode: "glm-5.2",
  1311. displayName: "GLM-5.2",
  1312. usage: 250_000,
  1313. },
  1314. ],
  1315. },
  1316. ],
  1317. },
  1318. },
  1319. },
  1320. intl: {
  1321. formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
  1322. values?.value ? `${id}:${values.value}` : id,
  1323. } as never,
  1324. locale: "en-US",
  1325. }),
  1326. );
  1327. expect(html).toContain("settings.modelProvider.startPlan.balance.title");
  1328. expect(html).not.toContain("settings.modelProvider.codingPlan.expiresAt");
  1329. expect(html).toContain("GLM-5.2");
  1330. expect(html).toContain("75%");
  1331. // 桶刷新时间只来自本桶 expires_at(nextResetTime),不再采用套餐级 renewTime;
  1332. // 非当日与 Coding Plan 对齐只展示日期,不携带时间。
  1333. expect(html).toContain("Jun 14");
  1334. expect(html).not.toContain("Jun 14 23:02");
  1335. expect(html).not.toContain("Jun 13 10:00");
  1336. expect(html).not.toContain("750K");
  1337. expect(html).not.toContain("1M");
  1338. expect(html).not.toContain("settings.modelProvider.startPlan.balance.used");
  1339. expect(html).toContain("chat.quota.action.upgrade");
  1340. expect(html).toContain("billing-discount-info");
  1341. });
  1342. it("omits the date for today's Start Plan balance renew time", () => {
  1343. vi.useFakeTimers();
  1344. try {
  1345. vi.setSystemTime(new Date(2026, 5, 15, 12, 0));
  1346. const html = renderToStaticMarkup(
  1347. createElement(ChatStartPlanBalancePanel, {
  1348. config: {
  1349. loading: false,
  1350. snapshot: {
  1351. generatedAt: new Date(2026, 5, 14, 8, 15).getTime(),
  1352. authenticated: true,
  1353. provider: {
  1354. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  1355. name: "Z.ai Start Plan",
  1356. },
  1357. remaining: null,
  1358. subscription: {
  1359. identityType: "unknown",
  1360. identityMasked: null,
  1361. details: [
  1362. {
  1363. productId: "zcode-v3-start-plan",
  1364. productName: "ZCode Start Plan",
  1365. purchaseTime: null,
  1366. beginTime: null,
  1367. renewTime: null,
  1368. expireTime: new Date(2026, 5, 20, 23, 59).toISOString(),
  1369. },
  1370. ],
  1371. },
  1372. quota: {
  1373. level: "Start",
  1374. limits: [
  1375. {
  1376. type: "TOKENS_LIMIT",
  1377. number: 1_000_000,
  1378. remaining: 990_000,
  1379. nextResetTime: new Date(2026, 5, 15, 23, 2).getTime(),
  1380. usageDetails: [
  1381. {
  1382. modelCode: "glm-5.2",
  1383. displayName: "GLM-5.2",
  1384. usage: 10_000,
  1385. },
  1386. ],
  1387. },
  1388. ],
  1389. },
  1390. },
  1391. },
  1392. intl: {
  1393. formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
  1394. values?.value ? `${id}:${values.value}` : id,
  1395. } as never,
  1396. locale: "en-US",
  1397. }),
  1398. );
  1399. expect(html).toContain("99%");
  1400. expect(html).toContain("23:02");
  1401. expect(html).not.toContain("Jun 15 23:02");
  1402. } finally {
  1403. vi.useRealTimers();
  1404. }
  1405. });
  1406. it("renders each Start Plan bucket with its own reset time", () => {
  1407. vi.useFakeTimers();
  1408. try {
  1409. vi.setSystemTime(new Date(2026, 5, 15, 12, 0));
  1410. const html = renderToStaticMarkup(
  1411. createElement(ChatStartPlanBalancePanel, {
  1412. config: {
  1413. loading: false,
  1414. snapshot: {
  1415. generatedAt: new Date(2026, 5, 15, 8, 15).getTime(),
  1416. authenticated: true,
  1417. provider: {
  1418. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  1419. name: "Z.ai Start Plan",
  1420. },
  1421. remaining: {
  1422. count: 1_750_000,
  1423. isShow: true,
  1424. // 全局聚合时间(最早桶时间)不得复制到每个桶。
  1425. nextResetTime: new Date(2026, 5, 15, 20, 0).getTime(),
  1426. },
  1427. subscription: {
  1428. identityType: "unknown",
  1429. identityMasked: null,
  1430. details: [
  1431. {
  1432. productId: "start-plan-welcome",
  1433. productName: "Welcome Plan",
  1434. purchaseTime: null,
  1435. beginTime: null,
  1436. renewTime: new Date(2026, 5, 13, 10, 0).toISOString(),
  1437. expireTime: new Date(2026, 5, 20, 23, 59).toISOString(),
  1438. },
  1439. ],
  1440. },
  1441. quota: {
  1442. level: "Start",
  1443. limits: [
  1444. {
  1445. type: "welcome-glm-52",
  1446. planId: "start-plan-welcome",
  1447. number: 1_000_000,
  1448. remaining: 750_000,
  1449. nextResetTime: new Date(2026, 5, 15, 18, 45).getTime(),
  1450. usageDetails: [
  1451. {
  1452. modelCode: "glm-5.2",
  1453. displayName: "GLM-5.2",
  1454. usage: 250_000,
  1455. },
  1456. ],
  1457. },
  1458. {
  1459. type: "welcome-glm-5-turbo",
  1460. planId: "start-plan-welcome",
  1461. number: 1_000_000,
  1462. remaining: 1_000_000,
  1463. nextResetTime: new Date(2026, 5, 16, 9, 30).getTime(),
  1464. usageDetails: [
  1465. {
  1466. modelCode: "glm-5-turbo",
  1467. displayName: "GLM-5-Turbo",
  1468. usage: 0,
  1469. },
  1470. ],
  1471. },
  1472. ],
  1473. },
  1474. },
  1475. },
  1476. intl: {
  1477. formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
  1478. values?.value ? `${id}:${values.value}` : id,
  1479. } as never,
  1480. locale: "en-US",
  1481. }),
  1482. );
  1483. // 每个 meter 只展示本桶的 expires_at:当日仅 HH:mm(对齐 Coding Plan 五小时窗口),
  1484. // 非当日仅日期(对齐 Coding Plan 周/月重置),互不串用。
  1485. expect(html).toContain("18:45");
  1486. expect(html).toContain("Jun 16");
  1487. expect(html).not.toContain("Jun 16 09:30");
  1488. // 全局 remaining 聚合时间与套餐级 renewTime 不得串入任何桶。
  1489. expect(html).not.toContain("20:00");
  1490. expect(html).not.toContain("Jun 13 10:00");
  1491. } finally {
  1492. vi.useRealTimers();
  1493. }
  1494. });
  1495. it("renders both Start Plan bucket model labels", () => {
  1496. const html = renderToStaticMarkup(
  1497. createElement(ChatStartPlanBalancePanel, {
  1498. config: {
  1499. loading: false,
  1500. snapshot: {
  1501. generatedAt: 1,
  1502. authenticated: true,
  1503. provider: {
  1504. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  1505. name: "Z.ai Start Plan",
  1506. },
  1507. remaining: null,
  1508. subscription: activeSubscription,
  1509. quota: {
  1510. level: "Start",
  1511. limits: [
  1512. {
  1513. type: "TOKENS_LIMIT",
  1514. number: 1_000_000,
  1515. remaining: 750_000,
  1516. usage: 250_000,
  1517. usageDetails: [
  1518. {
  1519. modelCode: "glm-5.2",
  1520. displayName: "GLM-5.2",
  1521. usage: 250_000,
  1522. },
  1523. ],
  1524. },
  1525. {
  1526. type: "TOKENS_LIMIT",
  1527. number: 500_000,
  1528. remaining: 250_000,
  1529. usage: 250_000,
  1530. usageDetails: [
  1531. {
  1532. modelCode: "glm-5.1",
  1533. displayName: "GLM-5.1",
  1534. usage: 250_000,
  1535. },
  1536. ],
  1537. },
  1538. ],
  1539. },
  1540. },
  1541. },
  1542. intl: {
  1543. formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
  1544. values?.value ? `${id}:${values.value}` : id,
  1545. } as never,
  1546. locale: "en-US",
  1547. }),
  1548. );
  1549. expect(html).toContain("GLM-5.2");
  1550. expect(html).toContain("GLM-5.1");
  1551. });
  1552. it("is visible while loading or when displayable limits exist", () => {
  1553. expect(hasChatStartPlanBalance({ loading: true, snapshot: null })).toBe(true);
  1554. expect(
  1555. hasChatStartPlanBalance({
  1556. loading: false,
  1557. snapshot: {
  1558. generatedAt: 1,
  1559. authenticated: true,
  1560. provider: {
  1561. id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  1562. name: "Z.ai Start Plan",
  1563. },
  1564. remaining: null,
  1565. subscription: activeSubscription,
  1566. quota: { level: "Start", limits: [] },
  1567. },
  1568. }),
  1569. ).toBe(false);
  1570. });
  1571. });