chatContextUsageBreakdown.test.ts 63 KB

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