codingPlanUsagePanel.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. import { readSourceTextAsync } from "./readSourceText.js";
  2. import { describe, expect, it } from "vitest";
  3. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  4. import {
  5. buildCodingPlanModelLineChartSeries,
  6. buildCodingPlanToolLineChartSeries,
  7. buildCodingPlanUsageDetailLineChartSeries,
  8. } from "@/settings/usage-stats/codingPlanUsageChartSeries.js";
  9. import { calculateCodingPlanBarChartMaxValue } from "@/settings/usage-stats/CodingPlanUsageBarChart.js";
  10. import {
  11. buildCodingPlanUsageSources,
  12. formatUsageStatsQuotaResetTime,
  13. hasCodingPlanCreditUsageData,
  14. resolveCodingPlanUsageProviderName,
  15. shouldShowCodingPlanUsageDetailSummary,
  16. } from "@/settings/usage-stats/CodingPlanUsagePanel.js";
  17. import enMessages from "@/i18n/locales/en-US.js";
  18. import zhMessages from "@/i18n/locales/zh-CN.js";
  19. import {
  20. findCodingPlanQuotaLimit,
  21. formatQuotaRemainingPercentage,
  22. formatQuotaResetTime,
  23. getQuotaRemainingPercentage,
  24. } from "@/lib/codingPlanQuotaPresentation.js";
  25. import {
  26. buildPersonalCodingPlanUsageSource,
  27. matchesTeamPlanUsageSourceKey,
  28. resolveSidebarCurrentCodingPlanUsageSource,
  29. } from "@/lib/codingPlanUsageSources.js";
  30. import { formatSummaryCompactTokenUsage } from "@/settings/usage-stats/usageStatsUiParts.js";
  31. describe("CodingPlanUsagePanel", () => {
  32. it("个人与团队套餐的中文 Token 摘要在数字和单位之间保留空格", () => {
  33. expect(formatSummaryCompactTokenUsage("zh-CN", 370_000_000)).toBe("3.7 亿");
  34. expect(formatSummaryCompactTokenUsage("en-US", 370_000_000)).toBe("370M");
  35. });
  36. it("Usage stats 和模型设置的 ZCode MCP 卡片都提供统一 info tooltip", async () => {
  37. const [usageSource, modelSettingsSource] = await Promise.all([
  38. readSourceTextAsync(
  39. new URL("../src/settings/usage-stats/CodingPlanUsagePanel.tsx", import.meta.url),
  40. "utf8",
  41. ),
  42. readSourceTextAsync(
  43. new URL("../src/settings/model-provider-section/StatusCards.tsx", import.meta.url),
  44. "utf8",
  45. ),
  46. ]);
  47. expect(usageSource).toContain('data-zcode-mcp-info="usage-stats"');
  48. expect(modelSettingsSource).toContain('data-zcode-mcp-info="model-settings"');
  49. expect(usageSource).toContain('id: "sidebar.usage.plan.zcodeMcpDescription"');
  50. expect(modelSettingsSource).toContain('id: "sidebar.usage.plan.zcodeMcpDescription"');
  51. });
  52. it("统一使用工具调用和 ZCode MCP 的额度名称", () => {
  53. expect(zhMessages["settings.usage.entitlementMonthlyMcpUsage"]).toBe("工具调用");
  54. expect(enMessages["settings.usage.entitlementMonthlyMcpUsage"]).toBe("Tool calls");
  55. expect(zhMessages["settings.usage.entitlementServerMcpUsage"]).toBe("ZCode MCP");
  56. expect(enMessages["settings.usage.entitlementServerMcpUsage"]).toBe("ZCode MCP");
  57. expect(zhMessages["sidebar.usage.plan.mcp"]).toBe("ZCode MCP");
  58. expect(enMessages["sidebar.usage.plan.mcp"]).toBe("ZCode MCP");
  59. });
  60. it("个人套餐来源使用 Account Access,而不是请求凭据", () => {
  61. expect(
  62. buildPersonalCodingPlanUsageSource({
  63. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  64. accountAccess: {
  65. type: "zhipu-account",
  66. family: "zai",
  67. planKind: "individual-coding-plan",
  68. },
  69. label: "Z.ai - Coding Plan",
  70. }),
  71. ).toEqual({
  72. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  73. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  74. accountAccess: {
  75. type: "zhipu-account",
  76. family: "zai",
  77. planKind: "individual-coding-plan",
  78. },
  79. label: "Z.ai - Coding Plan",
  80. });
  81. });
  82. it("把已购 Team Plan 展开为可查询的 usage source", () => {
  83. const sources = buildCodingPlanUsageSources({
  84. accountAccesses: {
  85. bigmodel: {
  86. type: "zhipu-account",
  87. family: "bigmodel",
  88. mode: "team-coding-plan",
  89. },
  90. },
  91. subscribedTeamProducts: [
  92. {
  93. productId: "product-team",
  94. productName: "Pro",
  95. projectName: "Team A",
  96. subscribed: true,
  97. teamProjects: [
  98. {
  99. organizationId: "org-team",
  100. organizationName: "Org",
  101. projectId: "proj-team",
  102. projectName: "Team A",
  103. },
  104. ],
  105. } as never,
  106. ],
  107. });
  108. expect(sources).toEqual([
  109. {
  110. id: "team:bigmodel:product-team:org-team:proj-team",
  111. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  112. accountAccess: {
  113. type: "zhipu-account",
  114. family: "bigmodel",
  115. planKind: "team-coding-plan",
  116. productId: "product-team",
  117. organizationId: "org-team",
  118. projectId: "proj-team",
  119. },
  120. label: "BigModel - Org",
  121. },
  122. ]);
  123. });
  124. it("把 zai 已购 Team Plan 展开为带 zai providerId 和 Z.ai 品牌前缀的 usage source", () => {
  125. const sources = buildCodingPlanUsageSources({
  126. accountAccesses: {
  127. zai: {
  128. type: "zhipu-account",
  129. family: "zai",
  130. mode: "team-coding-plan",
  131. },
  132. },
  133. subscribedTeamProducts: [
  134. {
  135. productId: "zai-product-team",
  136. productName: "Pro",
  137. projectName: "ZAI Team A",
  138. subscribed: true,
  139. family: "zai",
  140. teamProjects: [
  141. {
  142. organizationId: "zai-org",
  143. organizationName: "ZAI Org",
  144. projectId: "zai-proj",
  145. projectName: "ZAI Team A",
  146. },
  147. ],
  148. } as never,
  149. ],
  150. });
  151. expect(sources).toEqual([
  152. {
  153. id: "team:zai:zai-product-team:zai-org:zai-proj",
  154. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  155. accountAccess: {
  156. type: "zhipu-account",
  157. family: "zai",
  158. planKind: "team-coding-plan",
  159. productId: "zai-product-team",
  160. organizationId: "zai-org",
  161. projectId: "zai-proj",
  162. },
  163. label: "Z.ai - ZAI Org",
  164. },
  165. ]);
  166. });
  167. it("resolveSidebarCurrentCodingPlanUsageSource 把 zai team selectedKey 解析成 team source", () => {
  168. const teamSources = buildCodingPlanUsageSources({
  169. accountAccesses: {
  170. zai: {
  171. type: "zhipu-account",
  172. family: "zai",
  173. mode: "team-coding-plan",
  174. },
  175. },
  176. subscribedTeamProducts: [
  177. {
  178. productId: "zai-product-team",
  179. productName: "Pro",
  180. projectName: "ZAI Team A",
  181. subscribed: true,
  182. family: "zai",
  183. teamProjects: [
  184. {
  185. organizationId: "zai-org",
  186. organizationName: "ZAI Org",
  187. projectId: "zai-proj",
  188. projectName: "ZAI Team A",
  189. },
  190. ],
  191. } as never,
  192. ],
  193. });
  194. const resolved = resolveSidebarCurrentCodingPlanUsageSource({
  195. selections: {
  196. zai: {
  197. kind: "team-coding-plan",
  198. productId: "zai-product-team",
  199. organizationId: "zai-org",
  200. projectId: "zai-proj",
  201. },
  202. },
  203. selectedProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  204. accountAccesses: {},
  205. teamSources,
  206. });
  207. expect(resolved).toEqual({
  208. audience: "team",
  209. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  210. sourceId: "team:zai:zai-product-team:zai-org:zai-proj",
  211. teamSource: teamSources[0],
  212. });
  213. });
  214. it("resolveSidebarCurrentCodingPlanUsageSource 在 zai team key 未匹配 source 时返回 null(不回退 individual)", () => {
  215. const resolved = resolveSidebarCurrentCodingPlanUsageSource({
  216. selections: {
  217. zai: {
  218. kind: "team-coding-plan",
  219. productId: "unknown",
  220. organizationId: "unknown",
  221. projectId: "unknown",
  222. },
  223. },
  224. selectedProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan,
  225. accountAccesses: {},
  226. teamSources: [],
  227. });
  228. expect(resolved).toBeNull();
  229. });
  230. it("resolveSidebarCurrentCodingPlanUsageSource 把 zai 个人 coding-plan key 解析成 individual", () => {
  231. const resolved = resolveSidebarCurrentCodingPlanUsageSource({
  232. selections: { zai: { kind: "individual-coding-plan" } },
  233. selectedProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  234. accountAccesses: {
  235. zai: {
  236. type: "zhipu-account",
  237. family: "zai",
  238. mode: "individual-coding-plan",
  239. },
  240. },
  241. teamSources: [],
  242. });
  243. expect(resolved).toEqual({
  244. audience: "individual",
  245. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  246. sourceId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  247. accountAccess: {
  248. type: "zhipu-account",
  249. family: "zai",
  250. mode: "individual-coding-plan",
  251. },
  252. });
  253. });
  254. it("matchesTeamPlanUsageSourceKey 对 zai team sourceId/selectedKey 正确匹配", () => {
  255. const zaiSourceId = "team:zai:prod:org:proj";
  256. const zaiSelectedKey = "team:zai:prod:org:proj";
  257. expect(matchesTeamPlanUsageSourceKey(zaiSourceId, zaiSelectedKey)).toBe(true);
  258. // 不同 projectId 不匹配
  259. expect(matchesTeamPlanUsageSourceKey(zaiSourceId, "team:zai:prod:org:other")).toBe(false);
  260. });
  261. it("缺少组织名称时不生成空白 Team Plan usage source", () => {
  262. const sources = buildCodingPlanUsageSources({
  263. accountAccesses: {
  264. bigmodel: {
  265. type: "zhipu-account",
  266. family: "bigmodel",
  267. planKind: "team-coding-plan",
  268. productId: "product-team",
  269. organizationId: "org-team",
  270. projectId: "proj-team",
  271. },
  272. },
  273. subscribedTeamProducts: [
  274. {
  275. productId: "product-team",
  276. productName: "Pro",
  277. projectName: "Team A",
  278. subscribed: true,
  279. teamProjects: [
  280. {
  281. organizationId: "org-team",
  282. organizationName: null,
  283. projectId: "proj-team",
  284. projectName: "Team A",
  285. },
  286. ],
  287. } as never,
  288. ],
  289. });
  290. expect(sources).toEqual([]);
  291. });
  292. it("Team Plan 剩余额度标题优先显示团队项目名称", () => {
  293. expect(
  294. resolveCodingPlanUsageProviderName({
  295. fallbackProviderName: "BigModel - Coding Plan",
  296. source: {
  297. id: "team:bigmodel:product-team:org-team:proj-team",
  298. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  299. label: "BigModel - Team A",
  300. accountAccess: {
  301. type: "zhipu-account",
  302. family: "bigmodel",
  303. planKind: "team-coding-plan",
  304. productId: "product-team",
  305. organizationId: "org-team",
  306. projectId: "proj-team",
  307. },
  308. },
  309. snapshot: {
  310. sourceProvider: {
  311. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  312. name: "BigModel - Coding Plan",
  313. },
  314. } as never,
  315. }),
  316. ).toBe("BigModel - Team A");
  317. });
  318. it("个人套餐剩余额度标题不显示 BigModel 内建连接名", () => {
  319. expect(
  320. resolveCodingPlanUsageProviderName({
  321. fallbackProviderName: "BigModel - Coding Plan",
  322. source: {
  323. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  324. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  325. label: "BigModel - Coding Plan",
  326. },
  327. snapshot: {
  328. sourceProvider: {
  329. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  330. name: "BigModel - Coding Plan",
  331. },
  332. } as never,
  333. }),
  334. ).toBeUndefined();
  335. });
  336. it("使用统计编程套餐不再跟随当前 workspace 连接方式", async () => {
  337. const source = await readSourceTextAsync(
  338. new URL("../src/settings/usage-stats/CodingPlanUsagePanel.tsx", import.meta.url),
  339. "utf8",
  340. );
  341. expect(source).not.toContain("selectWorkspaceZCodeState");
  342. expect(source).not.toContain("parseCustomProviderIdFromSupplierKey");
  343. expect(source).not.toContain("resolveSidebarCurrentCodingPlanUsageSource");
  344. expect(source).toContain("selectedSource");
  345. expect(source).not.toContain("function ProviderSelector");
  346. expect(source).not.toContain("onSourceChange");
  347. });
  348. it("使用统计顶部把 Coding Plan sources 展开成独立 tab", async () => {
  349. const source = await readSourceTextAsync(
  350. new URL("../src/SettingsPage.tsx", import.meta.url),
  351. "utf8",
  352. );
  353. expect(source).toContain("createSettingsUsageCodingPlanTabId");
  354. expect(source).toContain("usageCodingPlanSources");
  355. expect(source).toContain("codingPlanSources.map");
  356. // 修复原因:JSX 格式化可能把属性换行,断言应验证绑定语义而不是排版。
  357. expect(source).toMatch(/selectedCodingPlanSource=\{\s*selectedUsageCodingPlanSource\s*\}/);
  358. });
  359. it("使用统计打开时主动探测个人 Coding Plan entitlement", async () => {
  360. const source = await readSourceTextAsync(
  361. new URL("../src/SettingsPage.tsx", import.meta.url),
  362. "utf8",
  363. );
  364. // Bugfix 回归:个人 source 依赖 entitlement snapshot。冷启动无缓存时必须先进行
  365. // access 探测,否则 source 不会出现,子面板也没有机会触发后续刷新。
  366. const usageEntitlementBlock = source.slice(
  367. source.indexOf("const usageZaiEntitlement"),
  368. source.indexOf("const usageBigmodelEnterpriseProducts"),
  369. );
  370. expect(usageEntitlementBlock.match(/refreshOnMount: true/g)).toHaveLength(2);
  371. });
  372. it("使用统计个人 Coding Plan tab 显示个人套餐文案", () => {
  373. expect(zhMessages["settings.usage.tab.codingPlan"]).toBe("个人套餐");
  374. expect(enMessages["settings.usage.tab.codingPlan"]).toBe("Individual Plan");
  375. });
  376. it("把 Coding Plan 模型和工具用量映射为图表 series", () => {
  377. expect(
  378. buildCodingPlanModelLineChartSeries([
  379. {
  380. modelName: "glm-4.5",
  381. sortOrder: 1,
  382. tokensUsage: [10, 20],
  383. totalTokens: 30,
  384. },
  385. ]),
  386. ).toEqual([{ name: "glm-4.5", values: [10, 20] }]);
  387. expect(
  388. buildCodingPlanToolLineChartSeries([
  389. {
  390. toolCode: "search",
  391. toolName: "Search",
  392. sortOrder: 1,
  393. usageCount: [1, 2],
  394. totalUsageCount: 3,
  395. },
  396. ]),
  397. ).toEqual([{ name: "Search", values: [1, 2] }]);
  398. });
  399. it("使用详情的新旧数据都统一通过 Recharts 柱状图展示", async () => {
  400. const source = await readSourceTextAsync(
  401. new URL("../src/settings/usage-stats/CodingPlanUsagePanel.tsx", import.meta.url),
  402. "utf8",
  403. );
  404. const barChartSource = await readSourceTextAsync(
  405. new URL("../src/settings/usage-stats/CodingPlanUsageBarChart.tsx", import.meta.url),
  406. "utf8",
  407. );
  408. const lineChartSource = await readSourceTextAsync(
  409. new URL("../src/settings/usage-stats/CodingPlanUsageLineChart.tsx", import.meta.url),
  410. "utf8",
  411. );
  412. const uiPartsSource = await readSourceTextAsync(
  413. new URL("../src/settings/usage-stats/usageStatsUiParts.tsx", import.meta.url),
  414. "utf8",
  415. );
  416. expect(source).not.toMatch(/series=\{snapshot\.[^}]+\.map\(/);
  417. expect(source).toContain("buildCodingPlanUsageDetailLineChartSeries");
  418. expect(source).toContain("buildCodingPlanModelLineChartSeries");
  419. expect(source).toContain("buildCodingPlanToolLineChartSeries");
  420. expect(source).toContain("series={visibleSeries}");
  421. expect(source).toContain("{hasCreditUsageData ? (");
  422. expect(source).toContain('<div className="mt-3 flex flex-wrap items-center gap-3 text-ui-sm">');
  423. expect(source).not.toContain(
  424. '{hasCreditUsageData ? (\n <div className="mt-3 flex flex-wrap items-center gap-3 text-ui-sm">',
  425. );
  426. expect(source).toContain("<CodingPlanUsageBarChart");
  427. expect(source.match(/<CodingPlanUsageLineChart/g)).toHaveLength(1);
  428. expect(source).not.toContain("legacyChartMeta");
  429. expect(source).toContain("aria-pressed={!hidden}");
  430. expect(source).toContain('<Check className="size-3" aria-hidden="true" />');
  431. expect(source).toContain("CODING_PLAN_DETAIL_SERIES_COLORS");
  432. expect(source).toContain("MAX_SELECTED_CODING_PLAN_DETAIL_SERIES");
  433. expect(source).toContain("settings.usage.activityTitle");
  434. // 修复回归:summary.totalUsageDurationMs 是累计使用时长,曾被错标成
  435. // “最长聊天时长”(longestSessionMs 是 App Usage 侧字段,Coding Plan 快照没有)。
  436. expect(source).toContain("settings.usage.totalUsageDuration");
  437. expect(source).not.toContain("settings.usage.longestSession");
  438. expect(source).not.toContain("settings.usage.favoriteModel");
  439. expect(source).not.toContain("favoriteModelName");
  440. expect(source).toContain(
  441. '<div className="truncate text-ui-lg font-medium text-foreground">{item.value}</div>',
  442. );
  443. expect(source).toContain(
  444. '<div className="mt-1 flex min-w-0 items-center gap-2 text-ui-base text-foreground-subtle">',
  445. );
  446. expect(source).not.toContain(
  447. '<div className="truncate text-ui-xl font-semibold text-foreground">\n {item.value}',
  448. );
  449. expect(source).not.toContain(
  450. '<div className="mt-2 flex min-w-0 items-center gap-2 text-ui-lg text-foreground-subtle">',
  451. );
  452. expect(zhMessages["settings.usage.activityTitle"]).toBe("活跃度");
  453. expect(enMessages["settings.usage.activityTitle"]).toBe("Activity");
  454. expect(source).toContain("setSelectedSeriesNames");
  455. expect(source).toContain("return [...current.slice(1), name];");
  456. expect(source).toContain("borderColor: hidden ? undefined : seriesColor");
  457. expect(source).toContain("bg-input border-border text-transparent");
  458. expect(source).toContain("text-foreground-subtle");
  459. expect(source).toContain('className="font-mono font-medium"');
  460. expect(barChartSource).toContain('className="text-foreground-subtle">tokens/s</span>');
  461. expect(lineChartSource).toContain('className="text-foreground-subtle">tokens/s</span>');
  462. expect(barChartSource).not.toContain("`${formatCompactNumber(locale, value)} tokens/s`");
  463. expect(lineChartSource).not.toContain("`${formatCompactNumber(locale, value)} tokens/s`");
  464. expect(source).toMatch(/const detailUnit =\s*valueKind === "token"/);
  465. expect(source).toContain('id: "settings.usage.creditUnit"');
  466. expect(source).toContain("{detailUnit}</span>");
  467. expect(barChartSource.match(/valueKind === "token"/g)?.length).toBeGreaterThanOrEqual(4);
  468. expect(barChartSource.match(/\{tokenUnit\}<\/span>/g)?.length).toBeGreaterThanOrEqual(2);
  469. expect(barChartSource).toContain(
  470. 'const creditUnit = intl.formatMessage({ id: "settings.usage.creditUnit" })',
  471. );
  472. expect(barChartSource.match(/\{creditUnit\}<\/span>/g)?.length).toBeGreaterThanOrEqual(2);
  473. expect(zhMessages["settings.usage.creditUnit"]).toBe("积分");
  474. expect(enMessages["settings.usage.creditUnit"]).toBe("credits");
  475. expect(source).not.toContain('className="font-medium text-foreground"');
  476. expect(source).not.toContain('className="truncate">{item.name}:');
  477. expect(source).toContain("USAGE_STATS_TABS_LIST_CLASS");
  478. expect(source).toContain("USAGE_STATS_TABS_TRIGGER_CLASS");
  479. expect(uiPartsSource).toContain("px-2.5 py-0 text-ui-sm");
  480. expect(uiPartsSource).not.toContain("w-16");
  481. expect(uiPartsSource).not.toContain("px-0 py-0 text-ui-sm");
  482. expect(source).toContain('className="h-4 w-px bg-border"');
  483. expect(source).not.toContain('className="h-7 w-px bg-border"');
  484. expect(source).not.toContain("onRefresh: () => void");
  485. expect(source).not.toContain("onClick={onRefresh}");
  486. expect(source).toContain("RefreshCw");
  487. expect(source).toContain('variant="ghost"');
  488. expect(source).not.toContain('variant="outline"\n size="icon-sm"');
  489. expect(source).toContain('size="icon-sm"');
  490. expect(source).not.toContain('className="h-8 rounded-md bg-background"');
  491. expect(source).toContain('aria-label={intl.formatMessage({ id: "settings.usage.refresh" })}');
  492. expect(source).not.toContain("providerName={effectiveProviderName}");
  493. expect(source).not.toContain("{providerName ? (");
  494. expect(source).not.toContain("BarChart3");
  495. expect(source).not.toContain("settings.usage.charts");
  496. expect(source).not.toContain("handleScrollToCharts");
  497. expect(source).toContain("handleUsageStatsRefresh");
  498. expect(source).toContain("refreshCodingPlanUsage({ force: true })");
  499. expect(source).not.toContain("document.getElementById(CODING_PLAN_USAGE_TRENDS_SECTION_ID)");
  500. expect(source).toContain('const options: CodingPlanUsageTrendRange[] = ["7d", "30d"];');
  501. expect(source).not.toContain('"today", "7d", "30d", "custom"');
  502. expect(source).not.toContain('range === "custom"');
  503. expect(source).not.toContain('type="date"');
  504. expect(source).not.toContain(
  505. 'className="flex h-8 rounded-lg border border-border bg-background p-1"',
  506. );
  507. expect(source).toContain(
  508. '<div className="rounded-xl bg-surface/70 p-3">\n <UsageChartLoadBoundary\n scope="settings.usage.coding-plan-health-chart"',
  509. );
  510. expect(barChartSource).toContain("BarChart");
  511. expect(barChartSource).toContain("<Bar");
  512. expect(barChartSource).not.toContain("rounded-lg bg-surface/60");
  513. expect(lineChartSource).not.toContain("rounded-lg bg-surface/60");
  514. expect(lineChartSource).toContain(
  515. "const CODING_PLAN_LINE_CHART_MARGIN = { top: 8, right: 24, left: 24 } as const;",
  516. );
  517. expect(lineChartSource).not.toContain(
  518. "const CODING_PLAN_LINE_CHART_MARGIN = { top: 8, right: 12, left: 8 } as const;",
  519. );
  520. expect(barChartSource).toContain('className="max-w-96 min-w-72"');
  521. expect(barChartSource).toContain("getModelBreakdownColor");
  522. expect(barChartSource).toContain("getModelColor(index, item.color)");
  523. expect(barChartSource).toContain("color-mix");
  524. expect(barChartSource).not.toContain("BREAKDOWN_COLORS");
  525. expect(barChartSource).toContain("radius: [4, 4, 0, 0]");
  526. expect(barChartSource).toContain("radius: [0, 0, 0, 0]");
  527. expect(barChartSource).toContain("radius={item.radius}");
  528. expect(barChartSource).toContain("CODING_PLAN_BAR_CHART_MAX_BAR_SIZE");
  529. expect(barChartSource).toContain("CODING_PLAN_BAR_CHART_MAX_BAR_SIZE = 24");
  530. expect(barChartSource).toContain("maxBarSize={CODING_PLAN_BAR_CHART_MAX_BAR_SIZE}");
  531. expect(barChartSource).toContain("name={item.label}");
  532. expect(barChartSource).toContain("backgroundColor: indicatorColor");
  533. expect(barChartSource).toContain("return (");
  534. expect(barChartSource).toContain('className="text-foreground-subtle"');
  535. expect(barChartSource).toContain(
  536. 'className="mt-3 flex items-center justify-between gap-8 text-foreground"',
  537. );
  538. expect(barChartSource).toContain('className="mt-3 border-t border-border"');
  539. expect(barChartSource).toContain("settings.usage.codingPlanLegendTotal");
  540. expect(barChartSource).toContain("size-2 shrink-0 self-center rounded-full");
  541. expect(barChartSource).toContain("min-w-0 flex-1 truncate text-foreground-subtle");
  542. expect(barChartSource).not.toContain("whitespace-normal break-words");
  543. expect(barChartSource).not.toContain("mt-1 size-2");
  544. expect(lineChartSource).toContain("size-2 shrink-0 self-center rounded-full");
  545. expect(lineChartSource).not.toContain("h-2.5 w-1");
  546. expect(lineChartSource).toContain('role="list"');
  547. expect(lineChartSource.indexOf('role="list"')).toBeLessThan(
  548. lineChartSource.indexOf("<ChartContainer"),
  549. );
  550. expect(lineChartSource).not.toContain("ChartLegend");
  551. expect(lineChartSource).not.toContain("ChartLegendContent");
  552. expect(barChartSource).not.toContain("LineChart");
  553. expect(barChartSource).not.toContain("<Line");
  554. });
  555. it("使用详情模型维度按真实模型生成柱状图 series", () => {
  556. expect(
  557. buildCodingPlanUsageDetailLineChartSeries({
  558. metric: "credits",
  559. subject: "model",
  560. modelDataList: [
  561. {
  562. modelName: "glm-5",
  563. sortOrder: 1,
  564. tokensUsage: [10, 20],
  565. creditsUsage: [1, 2],
  566. cachedInputCreditsUsage: [0.4, 0.8],
  567. uncachedInputCreditsUsage: [0.5, 1],
  568. outputCreditsUsage: [0.1, 0.2],
  569. totalTokens: 30,
  570. totalCredits: 3,
  571. },
  572. ],
  573. toolDataList: [],
  574. }),
  575. ).toEqual([
  576. {
  577. breakdown: {
  578. cachedInput: [0.4, 0.8],
  579. output: [0.1, 0.2],
  580. uncachedInput: [0.5, 1],
  581. },
  582. name: "glm-5",
  583. values: [1, 2],
  584. },
  585. ]);
  586. });
  587. it("Coding Plan 柱状图按单个并排柱高度计算 Y 轴最大值", () => {
  588. expect(
  589. calculateCodingPlanBarChartMaxValue(
  590. [
  591. {
  592. name: "GLM-5.3",
  593. values: [100],
  594. breakdown: {
  595. cachedInput: [70],
  596. uncachedInput: [20],
  597. output: [10],
  598. },
  599. },
  600. {
  601. name: "GLM-5-Turbo",
  602. values: [90],
  603. breakdown: {
  604. cachedInput: [60],
  605. uncachedInput: [20],
  606. output: [10],
  607. },
  608. },
  609. ],
  610. 1,
  611. ),
  612. ).toBe(100);
  613. });
  614. it("旧版 Coding Plan 只有 token 用量时不展示积分摘要卡", () => {
  615. const legacyUsage = {
  616. summary: {
  617. cacheHitRate: 0.894,
  618. cacheHitRateTrend: -0.06,
  619. totalCredits: 0,
  620. totalCreditsTrend: 0,
  621. averageDailyCredits: 0,
  622. averageDailyCreditsTrend: 0,
  623. },
  624. modelDataList: [
  625. {
  626. modelName: "GLM-5.2",
  627. sortOrder: 1,
  628. tokensUsage: [12_950_000],
  629. totalTokens: 12_950_000,
  630. },
  631. ],
  632. toolDataList: [],
  633. };
  634. expect(hasCodingPlanCreditUsageData(legacyUsage)).toBe(false);
  635. expect(shouldShowCodingPlanUsageDetailSummary(legacyUsage)).toBe(false);
  636. });
  637. it("新版 Coding Plan 有 credits 数据时展示积分摘要卡", () => {
  638. const creditUsage = {
  639. summary: {
  640. cacheHitRate: 0.89,
  641. cacheHitRateTrend: null,
  642. totalCredits: 28.95,
  643. totalCreditsTrend: null,
  644. averageDailyCredits: 28.95,
  645. averageDailyCreditsTrend: null,
  646. },
  647. modelDataList: [
  648. {
  649. modelName: "GLM-5.3",
  650. sortOrder: 1,
  651. tokensUsage: [120],
  652. creditsUsage: [28.95],
  653. totalTokens: 120,
  654. totalCredits: 28.95,
  655. },
  656. ],
  657. toolDataList: [],
  658. };
  659. expect(hasCodingPlanCreditUsageData(creditUsage)).toBe(true);
  660. expect(shouldShowCodingPlanUsageDetailSummary(creditUsage)).toBe(true);
  661. });
  662. it("打开 Coding Plan Usage 页会同步刷新 entitlement quota", async () => {
  663. const source = await readSourceTextAsync(
  664. new URL("../src/settings/usage-stats/CodingPlanUsagePanel.tsx", import.meta.url),
  665. "utf8",
  666. );
  667. expect(source).toContain(
  668. 'void effectiveEntitlementRefresh({ silent: true, reason: "access" });',
  669. );
  670. expect(source).not.toContain("void refresh({ force: true });");
  671. });
  672. it("系统健康度固定展示近 7 日且不提供范围筛选", async () => {
  673. const source = await readSourceTextAsync(
  674. new URL("../src/settings/usage-stats/CodingPlanUsagePanel.tsx", import.meta.url),
  675. "utf8",
  676. );
  677. const healthSection = source.slice(
  678. source.indexOf("function CodingPlanHealthSection"),
  679. source.indexOf("function formatCodingPlanRate"),
  680. );
  681. expect(healthSection).toContain('id: "settings.usage.healthRange.7d"');
  682. expect(healthSection).not.toContain("<SegmentedTabs");
  683. expect(healthSection).not.toContain("setRange");
  684. expect(healthSection).not.toContain('"30d"');
  685. });
  686. it("峰值 Token 卡片只显示固定标题,并通过信息图标展示峰值日期", async () => {
  687. const source = await readSourceTextAsync(
  688. new URL("../src/settings/usage-stats/CodingPlanUsagePanel.tsx", import.meta.url),
  689. "utf8",
  690. );
  691. expect(source).toContain("peakDailyTokensDate: summary.peakDailyTokensDate");
  692. expect(source).toContain("<InfoIcon");
  693. expect(source).toContain("title={formatFullDay(locale, item.peakDailyTokensDate)}");
  694. expect(source).not.toContain(
  695. '? `${intl.formatMessage({ id: "settings.usage.lifetimePeakTokens" })}',
  696. );
  697. });
  698. it("缺少重置时间时不展示兜底文案", async () => {
  699. const sources = await Promise.all(
  700. [
  701. "../src/settings/usage-stats/CodingPlanUsagePanel.tsx",
  702. "../src/WorkspaceSidebarFooterUsageSummary.tsx",
  703. "../src/i18n/locales/en-US.ts",
  704. "../src/i18n/locales/zh-CN.ts",
  705. ].map((path) => readSourceTextAsync(new URL(path, import.meta.url), "utf8")),
  706. );
  707. expect(sources.join("\n")).not.toContain("∞");
  708. expect(sources.join("\n")).not.toContain("sidebar.usage.plan.unlimited");
  709. expect(sources.join("\n")).not.toContain("settings.usage.entitlementNoReset");
  710. expect(sources.join("\n")).not.toContain("No reset time");
  711. expect(sources.join("\n")).not.toContain("暂无重置时间");
  712. });
  713. it("个人套餐 quota 卡片把重置时间放在百分比同一信息行", async () => {
  714. const source = await readSourceTextAsync(
  715. new URL("../src/settings/usage-stats/CodingPlanUsagePanel.tsx", import.meta.url),
  716. "utf8",
  717. );
  718. const quotaCardBlock = source.slice(
  719. source.indexOf('className="min-w-0 flex-1 rounded-xl bg-surface/70 p-4"'),
  720. source.indexOf("function CodingPlanUsageTrendsSection"),
  721. );
  722. expect(quotaCardBlock).not.toBe("");
  723. expect(quotaCardBlock.indexOf("formatQuotaRemainingPercentage")).toBeLessThan(
  724. quotaCardBlock.indexOf("{resetTime ? ("),
  725. );
  726. expect(quotaCardBlock.indexOf("{resetTime ? (")).toBeLessThan(
  727. quotaCardBlock.indexOf('className="mt-3 h-2 overflow-hidden rounded-full bg-background"'),
  728. );
  729. });
  730. it("quota 卡片显示剩余额度百分比而不是已用百分比", () => {
  731. const limit = {
  732. type: "TOKENS_LIMIT",
  733. unit: 3,
  734. number: 5,
  735. percentage: 25,
  736. usageDetails: [],
  737. };
  738. expect(getQuotaRemainingPercentage(limit)).toBe(75);
  739. expect(formatQuotaRemainingPercentage("en-US", limit)).toBe("75%");
  740. });
  741. it("三个剩余用量入口的重置按钮都只打开统一弹窗", async () => {
  742. const sources = await Promise.all(
  743. [
  744. "../src/settings/usage-stats/CodingPlanUsagePanel.tsx",
  745. "../src/settings/model-provider-section/StatusCards.tsx",
  746. "../src/chat-input-toolbar/CodingPlanContextUsage.tsx",
  747. ].map((path) => readSourceTextAsync(new URL(path, import.meta.url))),
  748. );
  749. for (const source of sources) {
  750. expect(source).toContain("onOpenDialog={() => setQuotaResetDialogOpen(true)}");
  751. expect(source).not.toContain("onReset={resetUi.reset}");
  752. expect(source).not.toContain("onReset={resetUi.week.reset}");
  753. }
  754. });
  755. it("Usage 页和 Usage Remaining 菜单复用相同重置时间格式", () => {
  756. const resetAt = new Date(2026, 6, 10, 8, 30).getTime();
  757. expect(
  758. formatQuotaResetTime({
  759. locale: "en-US",
  760. value: resetAt,
  761. format: "dateTime",
  762. }),
  763. ).toBe("Jul 10, 08:30");
  764. expect(
  765. formatQuotaResetTime({
  766. locale: "en-US",
  767. value: resetAt,
  768. format: "date",
  769. }),
  770. ).toBe("Jul 10");
  771. });
  772. it("只有 Usage stats 的额度卡统一显示月日和时分", () => {
  773. const resetAt = new Date(2026, 8, 16, 23, 0).getTime();
  774. expect(formatUsageStatsQuotaResetTime("zh-CN", resetAt)).toBe("9月16日 23:00");
  775. expect(formatUsageStatsQuotaResetTime("zh-CN", undefined)).toBeUndefined();
  776. });
  777. // 修复原因:zai 业务后端 Team Plan 的 quota/limit 用 CREDIT_LIMIT 作为 type,
  778. // bigmodel 用 TOKENS_LIMIT。unit/number 语义一致,消费方按 TOKENS_LIMIT 查询时
  779. // 必须命中 CREDIT_LIMIT,否则 zai team plan 的 5 小时/每周配额卡不会渲染。
  780. it("findCodingPlanQuotaLimit 按 TOKENS_LIMIT 查询时等价命中 CREDIT_LIMIT", () => {
  781. const zaiTeamLimits = [
  782. {
  783. type: "CREDIT_LIMIT",
  784. unit: 3,
  785. number: 5,
  786. percentage: 27,
  787. usageDetails: [],
  788. },
  789. {
  790. type: "CREDIT_LIMIT",
  791. unit: 6,
  792. number: 1,
  793. percentage: 10,
  794. usageDetails: [],
  795. },
  796. ];
  797. // 5 小时窗口(unit=3, number=5)
  798. expect(findCodingPlanQuotaLimit(zaiTeamLimits, "TOKENS_LIMIT", 3, 5)).toEqual(zaiTeamLimits[0]);
  799. // 每周(unit=6)
  800. expect(findCodingPlanQuotaLimit(zaiTeamLimits, "TOKENS_LIMIT", 6)).toEqual(zaiTeamLimits[1]);
  801. // 缺失的 monthly tool 仍返回 null
  802. expect(findCodingPlanQuotaLimit(zaiTeamLimits, "TIME_LIMIT", 5, 1)).toBeNull();
  803. });
  804. it("findCodingPlanQuotaLimit 对 bigmodel TOKENS_LIMIT 保持原行为", () => {
  805. const bigmodelLimits = [
  806. {
  807. type: "TOKENS_LIMIT",
  808. unit: 3,
  809. number: 5,
  810. percentage: 40,
  811. usageDetails: [],
  812. },
  813. {
  814. type: "TIME_LIMIT",
  815. unit: 5,
  816. number: 1,
  817. percentage: 15,
  818. usageDetails: [],
  819. },
  820. ];
  821. expect(findCodingPlanQuotaLimit(bigmodelLimits, "TOKENS_LIMIT", 3, 5)).toEqual(
  822. bigmodelLimits[0],
  823. );
  824. expect(findCodingPlanQuotaLimit(bigmodelLimits, "TIME_LIMIT", 5, 1)).toEqual(bigmodelLimits[1]);
  825. // CREDIT_LIMIT 不会误匹配 TIME_LIMIT 查询
  826. expect(findCodingPlanQuotaLimit(bigmodelLimits, "CREDIT_LIMIT", 5, 1)).toBeNull();
  827. });
  828. });