appUsagePanel.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // @vitest-environment jsdom
  2. import { createElement, type ReactNode } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { render, screen, waitFor } from "@testing-library/react";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { readFile } from "node:fs/promises";
  7. import type { AppUsageRange, AppUsageSnapshot } from "@zcode/shared";
  8. import type { IServiceAccessor } from "@zcode/services";
  9. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  10. import { ServiceProvider } from "@/hooks/useServices.js";
  11. import {
  12. AppUsageLifetimeSummaryStrip,
  13. AppUsagePanel,
  14. } from "@/settings/usage-stats/AppUsagePanel.js";
  15. vi.mock("@/ControlHintTooltip.js", () => ({
  16. ControlHintTooltip: ({ children, title }: { children: ReactNode; title: string }) =>
  17. createElement("span", { "data-tooltip-title": title }, children),
  18. }));
  19. function createSnapshot(
  20. overrides: Partial<AppUsageSnapshot> & { range?: AppUsageRange } = {},
  21. ): AppUsageSnapshot {
  22. return {
  23. range: overrides.range ?? "all",
  24. generatedAt: 0,
  25. timeZone: "UTC",
  26. source: "agent-db",
  27. summary: {
  28. totalTokens: 20_650_000_000,
  29. inputTokens: 0,
  30. outputTokens: 0,
  31. reasoningTokens: 0,
  32. cacheCreationTokens: 0,
  33. cacheReadTokens: 0,
  34. cacheHitRate: 0,
  35. totalSessions: 0,
  36. totalTurns: 0,
  37. toolCallCount: 0,
  38. toolErrorRate: 0,
  39. modelErrorRate: 0,
  40. avgTimeToFirstTokenMs: null,
  41. avgTurnDurationMs: null,
  42. activeDays: 0,
  43. currentStreakDays: 5,
  44. longestSessionMs: 2 * 60 * 60 * 1000 + 15 * 60 * 1000,
  45. longestStreakDays: 34,
  46. peakDayTokens: 370_000_000,
  47. favoriteModel: null,
  48. },
  49. heatmap: {
  50. startDate: null,
  51. endDate: null,
  52. maxTokens: 370_000_000,
  53. weeks: [],
  54. },
  55. dailyModelUsage: [],
  56. models: [],
  57. tools: [],
  58. ...overrides,
  59. };
  60. }
  61. function createOneDayHeatmap(totalTokens: number): AppUsageSnapshot["heatmap"] {
  62. return {
  63. startDate: "2026-08-15",
  64. endDate: "2026-08-15",
  65. maxTokens: totalTokens,
  66. weeks: [
  67. {
  68. weekIndex: 0,
  69. days: [
  70. {
  71. date: "2026-08-15",
  72. level: 1,
  73. totalTokens,
  74. turnCount: 1,
  75. toolCallCount: 0,
  76. },
  77. ],
  78. },
  79. ],
  80. };
  81. }
  82. function createServices(): IServiceAccessor {
  83. return {
  84. usageStatsService: {
  85. getAppUsageSnapshot: vi.fn(async ({ range }: { range: AppUsageRange }) =>
  86. createSnapshot({
  87. range,
  88. heatmap: range === "all" ? createOneDayHeatmap(99) : createOneDayHeatmap(10),
  89. summary: {
  90. ...createSnapshot().summary,
  91. totalTokens: range === "all" ? 20_650_000_000 : 389_000,
  92. totalSessions: 4,
  93. totalTurns: 8,
  94. activeDays: 1,
  95. favoriteModel:
  96. range === "all"
  97. ? null
  98. : {
  99. modelId: "glm-5.3",
  100. totalTokens: 280_080,
  101. share: 0.72,
  102. },
  103. },
  104. }),
  105. ),
  106. },
  107. } as unknown as IServiceAccessor;
  108. }
  109. afterEach(() => {
  110. vi.restoreAllMocks();
  111. });
  112. describe("AppUsageLifetimeSummaryStrip", () => {
  113. it("renders all-time app usage metrics independent of the selected range", () => {
  114. const html = renderToStaticMarkup(
  115. createElement(
  116. ZCodeIntlProvider,
  117. { initialLocale: "zh-CN" },
  118. createElement(AppUsageLifetimeSummaryStrip, {
  119. snapshot: createSnapshot(),
  120. }),
  121. ),
  122. );
  123. expect(html).toContain("累计 Token 数");
  124. expect(html).toContain("峰值 Token 数");
  125. expect(html).toContain("最长聊天时长");
  126. expect(html).toContain("当前连续天数");
  127. expect(html).toContain("最长连续天数");
  128. expect(html).toContain("206.5 亿");
  129. expect(html).toContain("3.7 亿");
  130. expect(html).toContain("2 小时 15 分");
  131. expect(html).toContain("5 天");
  132. expect(html).toContain("34 天");
  133. expect(html).toContain("rounded-xl");
  134. expect(html).toContain("h-7");
  135. expect(html).toContain("w-px");
  136. expect(html).not.toContain("border-border");
  137. expect(html).not.toContain("border-t");
  138. expect(html).not.toContain("sm:border-l");
  139. });
  140. it("keeps the selected range for charts but removes the old range metric cards", async () => {
  141. // Bugfix: 两张图表是 lazy(() => import(...))(产品侧为了不让 Recharts/decimal.js 拖慢
  142. // 启动才按需加载),全量高负载下测试 worker 现场编译图表模块图会超过 waitFor 5s,
  143. // 「正在统计中」Suspense fallback 消失不了(a7cade07fb 曾放宽到 5s 仍不够)。
  144. // 渲染前用与组件内 lazy 完全一致的 specifier 预热模块,动态 import 命中缓存立即
  145. // resolve,占位不再依赖机器负载;若图表模块本身加载失败,预热会在此处直接报错。
  146. await Promise.all([
  147. import("@/settings/usage-stats/AppUsageDailyModelTrendChart.js"),
  148. import("@/settings/usage-stats/AppUsageModelUsagePieChart.js"),
  149. ]);
  150. render(
  151. createElement(
  152. ServiceProvider,
  153. { services: createServices() },
  154. createElement(ZCodeIntlProvider, { initialLocale: "zh-CN" }, createElement(AppUsagePanel)),
  155. ),
  156. );
  157. await screen.findByText("累计 Token 数");
  158. // Bugfix: 加载过程中"正在统计中"占位会同时出现多个,queryByText 命中多元素时
  159. // 直接抛错(全量负载下 waitFor 默认 1s 内未收敛就以 multiple elements 超时)。
  160. // 改用 queryAllByText 断言占位全部消失,并放宽到 5s 容忍负载下慢收敛。
  161. await waitFor(
  162. () => {
  163. expect(screen.queryAllByText("正在统计中")).toHaveLength(0);
  164. },
  165. { timeout: 5000 },
  166. );
  167. const lifetimeTitle = screen.getByText("累计 Token 数");
  168. const tokenActivityTitle = screen.getByText("Token 活动");
  169. const rangeTitle = screen.getByText("时间范围");
  170. expect(
  171. lifetimeTitle.compareDocumentPosition(tokenActivityTitle) & Node.DOCUMENT_POSITION_FOLLOWING,
  172. ).toBeTruthy();
  173. expect(
  174. tokenActivityTitle.compareDocumentPosition(rangeTitle) & Node.DOCUMENT_POSITION_FOLLOWING,
  175. ).toBeTruthy();
  176. expect(rangeTitle).toBeTruthy();
  177. expect(document.body.innerHTML).toContain("99");
  178. const sevenDayTab = screen.getByText("近 7 日");
  179. const thirtyDayTab = screen.getByText("近 30 日");
  180. expect(sevenDayTab.getAttribute("aria-selected")).toBe("true");
  181. expect(thirtyDayTab.getAttribute("aria-selected")).toBe("false");
  182. expect(await screen.findByText("每日 Token 趋势图")).toBeTruthy();
  183. expect(screen.queryByText("趋势图")).toBeNull();
  184. expect(screen.queryByText("按天 Token 趋势")).toBeNull();
  185. expect(document.body.innerHTML).toContain("rounded-full bg-surface");
  186. expect(document.body.innerHTML).toContain("group-data-horizontal/tabs:h-7");
  187. expect(document.body.innerHTML).toContain("px-2.5 py-0 text-ui-sm");
  188. expect(document.body.innerHTML).not.toContain("w-16");
  189. expect(document.body.innerHTML).not.toContain("rounded-lg border border-border");
  190. expect(screen.queryByText("tokens 用量")).toBeNull();
  191. expect(screen.queryByText("会话数量")).toBeNull();
  192. expect(screen.queryByText("消息数量")).toBeNull();
  193. expect(screen.queryByText("活跃天数")).toBeNull();
  194. expect(screen.queryByText("最常用模型")).toBeNull();
  195. });
  196. it("keeps chart color indicators above the charts", async () => {
  197. const dailyChartSource = await readFile(
  198. "packages/ui/src/settings/usage-stats/AppUsageDailyModelTrendChart.tsx",
  199. "utf8",
  200. );
  201. const modelChartSource = await readFile(
  202. "packages/ui/src/settings/usage-stats/AppUsageModelUsagePieChart.tsx",
  203. "utf8",
  204. );
  205. const dailyLegendIndex = dailyChartSource.indexOf('role="list"');
  206. const modelLegendIndex = modelChartSource.indexOf('role="list"');
  207. expect(dailyLegendIndex).toBeGreaterThan(-1);
  208. expect(modelLegendIndex).toBeGreaterThan(-1);
  209. expect(dailyLegendIndex).toBeLessThan(dailyChartSource.indexOf("<ChartContainer"));
  210. expect(modelLegendIndex).toBeGreaterThan(modelChartSource.indexOf("<ChartContainer"));
  211. expect(modelChartSource).toContain("md:grid-cols-2");
  212. expect(modelChartSource).toContain("grid grid-cols-[auto_minmax(0,1fr)_auto]");
  213. expect(modelChartSource).toContain("size-2 shrink-0 self-center rounded-full");
  214. expect(modelChartSource).not.toContain("h-2.5 w-1");
  215. expect(modelChartSource).not.toContain("mt-0.5");
  216. expect(dailyChartSource).not.toContain("rounded-md bg-surface/60");
  217. expect(modelChartSource).not.toContain("rounded-md bg-surface/60");
  218. expect(dailyChartSource).toContain('className="space-y-3 rounded-xl bg-surface p-4"');
  219. expect(modelChartSource).toContain('className="space-y-3 rounded-xl bg-surface p-4"');
  220. });
  221. it("uses small typography for chart content while keeping chart titles unchanged", async () => {
  222. const [
  223. chartUiSource,
  224. dailyChartSource,
  225. modelChartSource,
  226. heatmapSource,
  227. codingPlanSource,
  228. codingPlanLineSource,
  229. ] = await Promise.all(
  230. [
  231. "packages/ui/src/components/ui/chart.tsx",
  232. "packages/ui/src/settings/usage-stats/AppUsageDailyModelTrendChart.tsx",
  233. "packages/ui/src/settings/usage-stats/AppUsageModelUsagePieChart.tsx",
  234. "packages/ui/src/settings/usage-stats/UsageHeatmap.tsx",
  235. "packages/ui/src/settings/usage-stats/CodingPlanUsagePanel.tsx",
  236. "packages/ui/src/settings/usage-stats/CodingPlanUsageLineChart.tsx",
  237. ].map((path) => readFile(path, "utf8")),
  238. );
  239. expect(chartUiSource).toContain("justify-center text-ui-sm");
  240. expect(chartUiSource).toContain("text-ui-sm/relaxed");
  241. expect(dailyChartSource).toContain('className="flex min-w-0 items-center gap-2 text-ui-sm"');
  242. expect(dailyChartSource).toContain('<h3 className="text-ui-base font-medium text-foreground">');
  243. expect(modelChartSource).toContain("font-mono text-ui-sm text-foreground");
  244. expect(modelChartSource).toContain("font-mono text-ui-sm text-foreground-subtle tabular-nums");
  245. expect(modelChartSource).toContain('<h3 className="text-ui-base font-medium text-foreground">');
  246. expect(heatmapSource).toContain(
  247. 'className="min-w-0 truncate text-ui-sm text-foreground-subtle"',
  248. );
  249. expect(heatmapSource).toContain(
  250. '<h3 className="min-w-0 truncate text-ui-base font-medium text-foreground">',
  251. );
  252. expect(codingPlanSource).toContain(
  253. 'className="mt-3 flex flex-wrap items-center gap-3 text-ui-sm"',
  254. );
  255. expect(codingPlanSource).toContain(
  256. 'className="flex min-w-0 items-center gap-1 rounded-md px-2 py-1 text-ui-sm"',
  257. );
  258. expect(codingPlanLineSource).toContain(
  259. 'className="flex min-w-0 items-center gap-2 text-ui-sm"',
  260. );
  261. });
  262. });