usageStatsService.test.ts 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import type { ApiClient, AppUsageSnapshot, ZCodeAccountAccess } from "@zcode/shared";
  3. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  4. import type { IZCodeAgentService } from "../src/zcode-agent/zcodeAgent.js";
  5. import { createUsageStatsService } from "../src/usage-stats/usageStatsService.js";
  6. import { resolveCodingPlanUsageTimeRange } from "../src/usage-stats/providers/bigmodelUsageMonitorRange.js";
  7. const TEST_BIGMODEL_PROVIDER_ID = "test-bigmodel-api-provider";
  8. const TEST_ZAI_PROVIDER_ID = "test-zai-api-provider";
  9. function createAppUsageSnapshot(): AppUsageSnapshot {
  10. return {
  11. range: "30d",
  12. generatedAt: 1_900_000_000_000,
  13. timeZone: "UTC",
  14. source: "agent-db",
  15. summary: {
  16. totalTokens: 104,
  17. inputTokens: 14,
  18. outputTokens: 5,
  19. reasoningTokens: 0,
  20. cacheCreationTokens: 5,
  21. cacheReadTokens: 80,
  22. cacheHitRate: 0.8,
  23. totalSessions: 1,
  24. totalTurns: 1,
  25. toolCallCount: 2,
  26. toolErrorRate: 0.5,
  27. modelErrorRate: 0.5,
  28. avgTimeToFirstTokenMs: 100,
  29. avgTurnDurationMs: 2000,
  30. activeDays: 2,
  31. currentStreakDays: 2,
  32. longestSessionMs: 2000,
  33. longestStreakDays: 2,
  34. peakDayTokens: 104,
  35. favoriteModel: { modelId: "model-a", totalTokens: 104, share: 1 },
  36. },
  37. heatmap: { startDate: null, endDate: null, maxTokens: 100, weeks: [] },
  38. dailyModelUsage: [],
  39. models: [],
  40. tools: [],
  41. };
  42. }
  43. interface TestUsageProvider {
  44. id: string;
  45. name: string;
  46. enabled: boolean;
  47. apiKey: string;
  48. }
  49. function createProvider(overrides: Partial<TestUsageProvider>): TestUsageProvider {
  50. return {
  51. id: TEST_BIGMODEL_PROVIDER_ID,
  52. name: "BigModel",
  53. enabled: true,
  54. apiKey: "bigmodel-api-key",
  55. ...overrides,
  56. };
  57. }
  58. function createJsonResponse(body: unknown): Response {
  59. return new Response(JSON.stringify(body), {
  60. status: 200,
  61. headers: { "Content-Type": "application/json" },
  62. });
  63. }
  64. function createUsageStatsServiceForTest(params: {
  65. apiClient?: ApiClient;
  66. providers: TestUsageProvider[];
  67. env?: NodeJS.ProcessEnv;
  68. credentialTokens?: Record<string, string | null | undefined>;
  69. resolveAccountAuth?: (input: {
  70. providerId: string;
  71. accountAccess: ZCodeAccountAccess;
  72. }) => Promise<{ apiKey?: string }>;
  73. getAppUsageStats?: IZCodeAgentService["getAppUsageStats"];
  74. }) {
  75. const service = createUsageStatsService({
  76. apiClient: params.apiClient ?? {
  77. request: vi.fn(),
  78. },
  79. accountRequestAuthService: {
  80. resolveAccessCurrent: vi.fn(async () => null),
  81. resolveCurrent: vi.fn(
  82. params.resolveAccountAuth ??
  83. (async ({ providerId, accountAccess }) => {
  84. if (accountAccess.planKind === "team-coding-plan") {
  85. return {
  86. apiKey:
  87. providerId === BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
  88. ? "zai-team-ak.zai-team-secret"
  89. : "team-ak.team-secret",
  90. };
  91. }
  92. return {
  93. apiKey: params.providers.find((provider) => provider.id === providerId)?.apiKey,
  94. };
  95. }),
  96. ),
  97. assertCurrent: vi.fn(async () => undefined),
  98. },
  99. resolveApiAuthorization: vi.fn(async ({ preferredProviderId }) => {
  100. const provider = params.providers.find((candidate) =>
  101. preferredProviderId ? candidate.id === preferredProviderId : candidate.enabled,
  102. );
  103. const apiKey = provider?.apiKey?.trim() ?? "";
  104. if (!provider || !apiKey) return null;
  105. return {
  106. authorization: apiKey,
  107. quotaUrl:
  108. provider.id === TEST_ZAI_PROVIDER_ID
  109. ? "https://api.z.ai/api/monitor/usage/quota/limit"
  110. : "https://bigmodel.cn/api/monitor/usage/quota/limit",
  111. provider: { id: provider.id, name: provider.name },
  112. };
  113. }),
  114. credentialService: {
  115. load: vi.fn(async (key) => params.credentialTokens?.[key] ?? null),
  116. },
  117. env: params.env,
  118. zcodeAgentService: {
  119. getAppUsageStats: params.getAppUsageStats ?? vi.fn(async () => createAppUsageSnapshot()),
  120. },
  121. });
  122. return {
  123. ...service,
  124. getCodingPlanUsageSnapshot: (
  125. request: Parameters<typeof service.getCodingPlanUsageSnapshot>[0],
  126. ) =>
  127. service.getCodingPlanUsageSnapshot({
  128. ...request,
  129. accountAccess:
  130. request.accountAccess ??
  131. (request.organizationId && request.projectId
  132. ? {
  133. type: "zhipu-account",
  134. family: request.preferredProviderId?.includes("zai") ? "zai" : "bigmodel",
  135. planKind: "team-coding-plan",
  136. productId: "test-product",
  137. organizationId: request.organizationId,
  138. projectId: request.projectId,
  139. }
  140. : {
  141. type: "zhipu-account",
  142. family: request.preferredProviderId?.includes("zai") ? "zai" : "bigmodel",
  143. planKind: "individual-coding-plan",
  144. }),
  145. }),
  146. // Highspeed 的普通 TPS 查询同样按 accountAccess 鉴权;默认补个人套餐访问上下文,
  147. // 让用例专注缓存与诊断行为,需要 Team scope 的用例显式传入。
  148. getCodingPlanRegularTps: (
  149. request: Omit<
  150. Parameters<NonNullable<typeof service.getCodingPlanRegularTps>>[0],
  151. "accountAccess"
  152. > & {
  153. accountAccess?: ZCodeAccountAccess;
  154. },
  155. ) =>
  156. service.getCodingPlanRegularTps?.({
  157. ...request,
  158. accountAccess:
  159. request.accountAccess ??
  160. ({
  161. type: "zhipu-account",
  162. family: request.preferredProviderId.includes("zai") ? "zai" : "bigmodel",
  163. planKind: "individual-coding-plan",
  164. } satisfies ZCodeAccountAccess),
  165. }),
  166. };
  167. }
  168. describe("createUsageStatsService", () => {
  169. beforeEach(() => {
  170. vi.clearAllMocks();
  171. });
  172. afterEach(() => {
  173. vi.useRealTimers();
  174. vi.restoreAllMocks();
  175. });
  176. it("Highspeed 普通 TPS 只请求 7 天健康接口,并缓存及合并同 key 并发请求", async () => {
  177. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  178. const apiClient: ApiClient = {
  179. request: vi.fn(async () =>
  180. createJsonResponse({
  181. code: 200,
  182. data: { x_time: ["2026-05-18", "2026-05-19"], proMaxDecodeSpeed: [68, 73] },
  183. }),
  184. ),
  185. };
  186. const service = createUsageStatsServiceForTest({
  187. apiClient,
  188. providers: [
  189. createProvider({
  190. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  191. name: "BigModel - Coding Plan",
  192. apiKey: "coding-plan-api-key",
  193. }),
  194. ],
  195. });
  196. const request = {
  197. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  198. timeZone: "UTC",
  199. };
  200. await expect(
  201. Promise.all([
  202. service.getCodingPlanRegularTps(request),
  203. service.getCodingPlanRegularTps(request),
  204. ]),
  205. ).resolves.toEqual([73, 73]);
  206. await expect(service.getCodingPlanRegularTps(request)).resolves.toBe(73);
  207. expect(apiClient.request).toHaveBeenCalledTimes(1);
  208. const requestedUrl = String(vi.mocked(apiClient.request).mock.calls[0]?.[0]);
  209. expect(requestedUrl).toContain("/model-performance-day");
  210. expect(requestedUrl).not.toContain("credit-usage");
  211. vi.advanceTimersByTime(5 * 60_000 + 1);
  212. await expect(service.getCodingPlanRegularTps(request)).resolves.toBe(73);
  213. expect(apiClient.request).toHaveBeenCalledTimes(2);
  214. });
  215. it("Highspeed 普通 TPS 按账号访问上下文隔离缓存", async () => {
  216. const apiClient: ApiClient = {
  217. request: vi.fn(async () =>
  218. createJsonResponse({
  219. code: 200,
  220. data: { x_time: ["2026-05-18", "2026-05-19"], proMaxDecodeSpeed: [68, 73] },
  221. }),
  222. ),
  223. };
  224. const service = createUsageStatsServiceForTest({
  225. apiClient,
  226. providers: [
  227. createProvider({
  228. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  229. name: "BigModel - Coding Plan",
  230. apiKey: "coding-plan-api-key",
  231. }),
  232. ],
  233. });
  234. const preferredProviderId = BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan;
  235. await expect(
  236. service.getCodingPlanRegularTps({ preferredProviderId, timeZone: "UTC" }),
  237. ).resolves.toBe(73);
  238. // Team scope 已内含在 accountAccess 中;缓存键必须整体覆盖它,否则同一 provider 下
  239. // 切换团队项目会读到上一个项目的基准 TPS。
  240. await expect(
  241. service.getCodingPlanRegularTps({
  242. preferredProviderId,
  243. timeZone: "UTC",
  244. accountAccess: {
  245. type: "zhipu-account",
  246. family: "bigmodel",
  247. planKind: "team-coding-plan",
  248. productId: "test-product",
  249. organizationId: "org-1",
  250. projectId: "project-1",
  251. },
  252. }),
  253. ).resolves.toBe(73);
  254. expect(apiClient.request).toHaveBeenCalledTimes(2);
  255. });
  256. it("Highspeed 普通 TPS 健康检查失败时记录 HTTP 链路诊断", async () => {
  257. const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  258. const apiClient: ApiClient = {
  259. request: vi.fn(async () =>
  260. Response.json(
  261. { code: 5030, msg: "monitor unavailable" },
  262. {
  263. status: 503,
  264. statusText: "Service Unavailable",
  265. headers: {
  266. "x-request-id": "req-regular-tps",
  267. "x-trace-id": "trace-regular-tps",
  268. },
  269. },
  270. ),
  271. ),
  272. };
  273. const service = createUsageStatsServiceForTest({
  274. apiClient,
  275. providers: [
  276. createProvider({
  277. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  278. name: "BigModel - Coding Plan",
  279. apiKey: "coding-plan-api-key",
  280. }),
  281. ],
  282. });
  283. await expect(
  284. service.getCodingPlanRegularTps({
  285. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  286. timeZone: "UTC",
  287. }),
  288. ).rejects.toThrow("monitor unavailable");
  289. expect(warn).toHaveBeenCalledWith(
  290. expect.any(String),
  291. "Highspeed 普通 TPS 健康检查失败",
  292. expect.objectContaining({
  293. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  294. status: 503,
  295. responseHeaders: {
  296. "x-request-id": "req-regular-tps",
  297. "x-trace-id": "trace-regular-tps",
  298. },
  299. url: expect.stringContaining("/api/monitor/usage/model-performance-day"),
  300. }),
  301. );
  302. });
  303. it("Highspeed 普通 TPS 健康检查业务失败时保留 request id", async () => {
  304. const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  305. const service = createUsageStatsServiceForTest({
  306. apiClient: {
  307. request: vi.fn(async () =>
  308. Response.json(
  309. { code: 2007, msg: "monitor dependency failed" },
  310. { headers: { "x-request-id": "req-regular-tps-business" } },
  311. ),
  312. ),
  313. },
  314. providers: [
  315. createProvider({
  316. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  317. name: "BigModel - Coding Plan",
  318. apiKey: "coding-plan-api-key",
  319. }),
  320. ],
  321. });
  322. await expect(
  323. service.getCodingPlanRegularTps({
  324. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  325. timeZone: "UTC",
  326. }),
  327. ).rejects.toThrow("monitor dependency failed");
  328. expect(warn).toHaveBeenCalledWith(
  329. expect.any(String),
  330. "Highspeed 普通 TPS 健康检查失败",
  331. expect.objectContaining({
  332. status: 200,
  333. responseCode: 2007,
  334. responseHeaders: { "x-request-id": "req-regular-tps-business" },
  335. }),
  336. );
  337. });
  338. it("Coding Plan 按当日/7日/30日生成稳定时间轴", () => {
  339. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  340. const today = resolveCodingPlanUsageTimeRange({
  341. range: "today",
  342. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  343. });
  344. const sevenDays = resolveCodingPlanUsageTimeRange({
  345. range: "7d",
  346. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  347. });
  348. expect(today.granularity).toBe("hour");
  349. expect(today.xTime[0]).toBe("00:00:00");
  350. expect(today.xTime.at(-1)).toBe("23:00:00");
  351. expect(sevenDays.granularity).toBe("day");
  352. expect(sevenDays.xTime).toEqual([
  353. "2026-05-13",
  354. "2026-05-14",
  355. "2026-05-15",
  356. "2026-05-16",
  357. "2026-05-17",
  358. "2026-05-18",
  359. "2026-05-19",
  360. ]);
  361. });
  362. it("Coding Plan 时间范围按调用端 timeZone 生成自然日边界", () => {
  363. vi.useFakeTimers({ now: new Date("2026-05-19T23:30:00.000Z") });
  364. const utc = resolveCodingPlanUsageTimeRange({
  365. range: "today",
  366. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  367. timeZone: "UTC",
  368. });
  369. const shanghai = resolveCodingPlanUsageTimeRange({
  370. range: "today",
  371. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  372. timeZone: "Asia/Shanghai",
  373. });
  374. expect(utc.startTime).toBe("2026-05-19 00:00:00");
  375. expect(utc.endTime).toBe("2026-05-19 23:59:59");
  376. expect(shanghai.startTime).toBe("2026-05-20 00:00:00");
  377. expect(shanghai.endTime).toBe("2026-05-20 23:59:59");
  378. });
  379. it("Coding Plan 自定义日期范围限制为 30 个自然日并生成日粒度时间轴", () => {
  380. const custom = resolveCodingPlanUsageTimeRange({
  381. range: "custom",
  382. customStartDate: "2026-05-01",
  383. customEndDate: "2026-05-03",
  384. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  385. timeZone: "UTC",
  386. });
  387. expect(custom.startTime).toBe("2026-05-01 00:00:00");
  388. expect(custom.endTime).toBe("2026-05-03 23:59:59");
  389. expect(custom.granularity).toBe("day");
  390. expect(custom.xTime).toEqual(["2026-05-01", "2026-05-02", "2026-05-03"]);
  391. expect(() =>
  392. resolveCodingPlanUsageTimeRange({
  393. range: "custom",
  394. customStartDate: "2026-05-01",
  395. customEndDate: "2026-06-01",
  396. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  397. timeZone: "UTC",
  398. }),
  399. ).toThrow("coding_plan_usage_custom_range_too_long");
  400. });
  401. it("App Usage 经 ZCode Protocol 读取 agent 数据库统计", async () => {
  402. const getAppUsageStats = vi.fn(async () => createAppUsageSnapshot());
  403. const apiClient: ApiClient = {
  404. request: vi.fn(),
  405. };
  406. const service = createUsageStatsServiceForTest({
  407. apiClient,
  408. providers: [],
  409. getAppUsageStats,
  410. });
  411. const snapshot = await service.getAppUsageSnapshot({
  412. range: "30d",
  413. timeZone: "UTC",
  414. });
  415. // App Usage 不走 monitor HTTP,只走 agent 协议。
  416. expect(apiClient.request).not.toHaveBeenCalled();
  417. expect(getAppUsageStats).toHaveBeenCalledWith({
  418. range: "30d",
  419. timeZone: "UTC",
  420. });
  421. expect(snapshot.source).toBe("agent-db");
  422. expect(snapshot.summary.totalSessions).toBe(1);
  423. expect(snapshot.summary.totalTokens).toBe(104);
  424. });
  425. it("App Usage 不会因为存在 Coding Plan key 而切到 monitor 接口", async () => {
  426. const getAppUsageStats = vi.fn(async () => createAppUsageSnapshot());
  427. const apiClient: ApiClient = {
  428. request: vi.fn(),
  429. };
  430. const service = createUsageStatsServiceForTest({
  431. apiClient,
  432. providers: [
  433. createProvider({
  434. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  435. name: "BigModel - Coding Plan",
  436. }),
  437. ],
  438. getAppUsageStats,
  439. });
  440. const snapshot = await service.getAppUsageSnapshot({
  441. range: "7d",
  442. timeZone: "UTC",
  443. });
  444. expect(apiClient.request).not.toHaveBeenCalled();
  445. expect(getAppUsageStats).toHaveBeenCalledWith({
  446. range: "7d",
  447. timeZone: "UTC",
  448. });
  449. expect(snapshot.source).toBe("agent-db");
  450. });
  451. it("App Usage 全量概览用 all range 透传到 agent 数据库统计", async () => {
  452. const getAppUsageStats = vi.fn(async () => ({
  453. ...createAppUsageSnapshot(),
  454. range: "all",
  455. }));
  456. const service = createUsageStatsServiceForTest({
  457. providers: [],
  458. getAppUsageStats,
  459. });
  460. const snapshot = await service.getAppUsageSnapshot({
  461. range: "all",
  462. timeZone: "Asia/Shanghai",
  463. });
  464. expect(getAppUsageStats).toHaveBeenCalledWith({
  465. range: "all",
  466. timeZone: "Asia/Shanghai",
  467. });
  468. expect(snapshot.range).toBe("all");
  469. });
  470. it("严格指定个人 Coding Plan 时使用 provider apiKey 的 monitor 数据且不回退本地", async () => {
  471. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  472. const requestUrls: string[] = [];
  473. const requestHeaders: Array<HeadersInit | undefined> = [];
  474. const apiClient: ApiClient = {
  475. request: vi.fn(async (input, init) => {
  476. const url = input.toString();
  477. requestUrls.push(url);
  478. requestHeaders.push(init?.headers);
  479. expect(init?.headers).toMatchObject({
  480. authorization: "legacy-coding-plan-api-key",
  481. });
  482. if (url.includes("/api/monitor/usage/quota/limit")) {
  483. return createJsonResponse({
  484. code: 200,
  485. data: {
  486. level: "pro",
  487. limits: [
  488. {
  489. type: "TOKENS_LIMIT",
  490. unit: 3,
  491. number: 5,
  492. usage: 100,
  493. currentValue: 31,
  494. percentage: 31,
  495. },
  496. ],
  497. },
  498. });
  499. }
  500. if (url.includes("/api/monitor/credit-usage/activity")) {
  501. return createJsonResponse({
  502. code: 200,
  503. data: {
  504. summary: {
  505. totalTokens: 350_720,
  506. peakDailyTokens: 120,
  507. peakDailyTokensDate: "2026-05-18",
  508. totalUsageDurationMs: 60_000,
  509. currentStreakDays: 1,
  510. longestStreakDays: 1,
  511. },
  512. series: [
  513. {
  514. date: "2026-05-18",
  515. totalTokens: 120,
  516. modelCallCount: 2,
  517. mcpCalls: 1,
  518. },
  519. ],
  520. },
  521. });
  522. }
  523. if (url.includes("/api/monitor/credit-usage/usage-detail")) {
  524. const usageType = new URL(url).searchParams.get("usageType");
  525. if (usageType === "MODEL") {
  526. return createJsonResponse({
  527. code: 200,
  528. data: {
  529. summary: {
  530. cacheHitRate: { value: 0.893, trend: 0.12 },
  531. totalCredits: { value: 28.95, trend: -0.2 },
  532. averageDailyCredits: { value: 4.13, trend: 0 },
  533. },
  534. modelUsage: {
  535. xTime: ["2026-05-18"],
  536. modelDataList: [
  537. {
  538. modelName: "glm-5",
  539. totalTokens: 120,
  540. totalCredits: 28.95,
  541. totalCreditsUsage: [28.95],
  542. totalTokensUsage: [120],
  543. cachedInputCreditsUsage: [17.68],
  544. uncachedInputCreditsUsage: [8.63],
  545. outputCreditsUsage: [2.64],
  546. cachedInputTokensUsage: [70],
  547. uncachedInputTokensUsage: [40],
  548. outputTokensUsage: [10],
  549. sortOrder: 1,
  550. },
  551. ],
  552. },
  553. },
  554. });
  555. }
  556. return createJsonResponse({
  557. code: 200,
  558. data: {
  559. summary: {
  560. cacheHitRate: { value: null },
  561. totalCredits: { value: 1, trend: 0.5 },
  562. averageDailyCredits: { value: 0.2, trend: 0.1 },
  563. },
  564. mcpUsage: {
  565. xTime: ["2026-05-18"],
  566. mcpDataList: [
  567. {
  568. mcpCode: "search-prime",
  569. mcpName: "联网搜索 MCP",
  570. creditsUsage: [1],
  571. mcpCallCount: [1],
  572. totalUsageCount: 1,
  573. totalCredits: 1,
  574. sortOrder: 1,
  575. },
  576. ],
  577. },
  578. },
  579. });
  580. }
  581. if (url.includes("/api/monitor/usage/model-performance-day")) {
  582. return createJsonResponse({
  583. code: 200,
  584. data: {
  585. x_time: ["2026-05-18", "2026-05-19"],
  586. proMaxDecodeSpeed: [125.4, 130.1],
  587. liteDecodeSpeed: [55.2, 58.8],
  588. },
  589. });
  590. }
  591. throw new Error(`unexpected request ${url}`);
  592. }),
  593. };
  594. const service = createUsageStatsServiceForTest({
  595. apiClient,
  596. providers: [
  597. createProvider({
  598. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  599. name: "BigModel - Coding Plan",
  600. apiKey: "legacy-coding-plan-api-key",
  601. }),
  602. createProvider({
  603. id: TEST_BIGMODEL_PROVIDER_ID,
  604. name: "BigModel",
  605. apiKey: "ordinary-api-key",
  606. }),
  607. ],
  608. env: {
  609. ZCODE_BIGMODEL_USAGE_API_KEY: "env-usage-key",
  610. },
  611. });
  612. const snapshot = await service.getCodingPlanUsageSnapshot({
  613. range: "30d",
  614. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  615. timeZone: "UTC",
  616. });
  617. expect(requestUrls).toHaveLength(5);
  618. expect(requestHeaders).toEqual(
  619. Array.from({ length: 5 }, () =>
  620. expect.objectContaining({
  621. authorization: "legacy-coding-plan-api-key",
  622. }),
  623. ),
  624. );
  625. for (const headers of requestHeaders) {
  626. expect(headers).not.toMatchObject({
  627. "bigmodel-organization": expect.any(String),
  628. "bigmodel-project": expect.any(String),
  629. });
  630. }
  631. for (const url of requestUrls.filter((item) => item.includes("/api/monitor/usage/"))) {
  632. if (url.includes("/quota/limit")) {
  633. continue;
  634. }
  635. expect(new URL(url).searchParams.has("granularity")).toBe(false);
  636. }
  637. const modelUsageUrl = new URL(
  638. requestUrls.find((url) => url.includes("/usage-detail") && url.includes("MODEL")) ?? "",
  639. );
  640. const activityUrl = new URL(requestUrls.find((url) => url.includes("/activity")) ?? "");
  641. const quotaUrl = new URL(requestUrls.find((url) => url.includes("/quota/limit")) ?? "");
  642. const toolUsageUrl = new URL(
  643. requestUrls.find((url) => url.includes("/usage-detail") && url.includes("MCP")) ?? "",
  644. );
  645. const healthUrls = requestUrls
  646. .filter((url) => url.includes("/model-performance-day"))
  647. .map((url) => new URL(url));
  648. expect(quotaUrl.searchParams.has("type")).toBe(false);
  649. expect(activityUrl.searchParams.get("type")).toBe("1");
  650. expect(modelUsageUrl.searchParams.get("type")).toBe("1");
  651. expect(toolUsageUrl.searchParams.get("type")).toBe("1");
  652. expect(healthUrls).toHaveLength(1);
  653. expect(healthUrls.every((url) => !url.searchParams.has("type"))).toBe(true);
  654. expect(modelUsageUrl.searchParams.get("startTime")).toBe("2026-04-20 00:00:00");
  655. expect(modelUsageUrl.searchParams.get("endTime")).toBe("2026-05-19 23:59:59");
  656. expect(healthUrls[0]?.searchParams.get("startTime")).toBe("2026-05-13 00:00:00");
  657. expect(healthUrls[0]?.searchParams.get("endTime")).toBe("2026-05-19 23:59:59");
  658. expect(snapshot.rangeStartDate).toBe("2026-04-20");
  659. expect(snapshot.rangeEndDate).toBe("2026-05-19");
  660. expect(snapshot.sourceProvider).toMatchObject({
  661. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  662. });
  663. expect(snapshot.modelUsage.totalTokensUsage).toBe(120);
  664. expect(snapshot.modelUsage.granularity).toBe("day");
  665. expect(snapshot.modelUsage.xTime).toHaveLength(30);
  666. expect(snapshot.modelUsage.modelDataList[0]?.modelName).toBe("glm-5");
  667. expect(snapshot.modelUsage.modelDataList[0]?.tokensUsage).toContain(120);
  668. expect(snapshot.modelUsage.modelDataList[0]?.cachedInputCreditsUsage).toContain(17.68);
  669. expect(snapshot.modelUsage.modelDataList[0]?.uncachedInputCreditsUsage).toContain(8.63);
  670. expect(snapshot.modelUsage.modelDataList[0]?.outputCreditsUsage).toContain(2.64);
  671. expect(snapshot.activity.summary.totalTokens).toBe(350_720);
  672. expect(snapshot.detail.model.cacheHitRate).toBe(0.893);
  673. expect(snapshot.detail.model.cacheHitRateTrend).toBe(0.12);
  674. expect(snapshot.detail.model.totalCreditsTrend).toBe(-0.2);
  675. expect(snapshot.detail.tool.totalCredits).toBe(1);
  676. expect(snapshot.detail.tool.averageDailyCredits).toBe(0.2);
  677. expect(snapshot.toolUsage.toolDataList[0]?.toolName).toBe("联网搜索 MCP");
  678. expect(snapshot.toolUsage.toolDataList[0]?.usageCount).toContain(1);
  679. expect(snapshot.health).toEqual({
  680. xTime: ["2026-05-18", "2026-05-19"],
  681. proMaxDecodeSpeed: [125.4, 130.1],
  682. liteDecodeSpeed: [55.2, 58.8],
  683. });
  684. expect(snapshot.quota?.limits).toHaveLength(1);
  685. });
  686. it("Coding Plan 积分序列遇到非数字桶时归零,避免 UI 汇总显示 NaN", async () => {
  687. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  688. const apiClient: ApiClient = {
  689. request: vi.fn(async (input) => {
  690. const url = input.toString();
  691. if (url.includes("/api/monitor/usage/quota/limit")) {
  692. return createJsonResponse({
  693. code: 200,
  694. data: { level: "pro", limits: [] },
  695. });
  696. }
  697. if (url.includes("/api/monitor/credit-usage/activity")) {
  698. return createJsonResponse({
  699. code: 200,
  700. data: { summary: { totalTokens: 0 }, series: [] },
  701. });
  702. }
  703. if (url.includes("/api/monitor/usage/model-performance-day")) {
  704. return createJsonResponse({
  705. code: 200,
  706. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  707. });
  708. }
  709. const usageType = new URL(url).searchParams.get("usageType");
  710. return createJsonResponse({
  711. code: 200,
  712. data:
  713. usageType === "MODEL"
  714. ? {
  715. summary: { totalCredits: { value: "bad" } },
  716. modelUsage: {
  717. xTime: ["2026-05-18", "2026-05-19"],
  718. modelDataList: [
  719. {
  720. modelName: "glm-5",
  721. totalCreditsUsage: ["bad", "28.95"],
  722. totalTokensUsage: ["bad", "120"],
  723. },
  724. ],
  725. },
  726. }
  727. : {
  728. mcpUsage: {
  729. xTime: ["2026-05-18", "2026-05-19"],
  730. mcpDataList: [
  731. {
  732. mcpCode: "search-prime",
  733. creditsUsage: ["bad", "1"],
  734. mcpCallCount: ["bad", "2"],
  735. },
  736. ],
  737. },
  738. },
  739. });
  740. }),
  741. };
  742. const service = createUsageStatsServiceForTest({
  743. apiClient,
  744. providers: [
  745. createProvider({
  746. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  747. name: "BigModel - Coding Plan",
  748. apiKey: "coding-plan-api-key",
  749. }),
  750. ],
  751. });
  752. const snapshot = await service.getCodingPlanUsageSnapshot({
  753. range: "7d",
  754. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  755. timeZone: "UTC",
  756. });
  757. const modelCredits = snapshot.modelUsage.modelDataList[0]?.creditsUsage ?? [];
  758. const modelTokens = snapshot.modelUsage.modelDataList[0]?.tokensUsage ?? [];
  759. const toolCredits = snapshot.toolUsage.toolDataList[0]?.creditsUsage ?? [];
  760. const toolCalls = snapshot.toolUsage.toolDataList[0]?.usageCount ?? [];
  761. expect(modelCredits.every(Number.isFinite)).toBe(true);
  762. expect(modelTokens.every(Number.isFinite)).toBe(true);
  763. expect(toolCredits.every(Number.isFinite)).toBe(true);
  764. expect(toolCalls.every(Number.isFinite)).toBe(true);
  765. expect(modelCredits.at(-2)).toBe(0);
  766. expect(modelCredits.at(-1)).toBe(28.95);
  767. expect(toolCredits.at(-2)).toBe(0);
  768. expect(toolCredits.at(-1)).toBe(1);
  769. });
  770. it("Coding Plan 使用详情不会把缓存输入和输出拆分桶当成模型图例", async () => {
  771. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  772. const apiClient: ApiClient = {
  773. request: vi.fn(async (input) => {
  774. const url = input.toString();
  775. if (url.includes("/api/monitor/usage/quota/limit")) {
  776. return createJsonResponse({
  777. code: 200,
  778. data: { level: "pro", limits: [] },
  779. });
  780. }
  781. if (url.includes("/api/monitor/credit-usage/activity")) {
  782. return createJsonResponse({
  783. code: 200,
  784. data: { summary: { totalTokens: 0 }, series: [] },
  785. });
  786. }
  787. if (url.includes("/api/monitor/usage/model-performance-day")) {
  788. return createJsonResponse({
  789. code: 200,
  790. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  791. });
  792. }
  793. const usageType = new URL(url).searchParams.get("usageType");
  794. return createJsonResponse({
  795. code: 200,
  796. data:
  797. usageType === "MODEL"
  798. ? {
  799. summary: { totalCredits: { value: 7 } },
  800. modelUsage: {
  801. xTime: ["2026-05-18"],
  802. modelDataList: [
  803. {
  804. modelCode: "cached_input",
  805. modelName: "缓存",
  806. totalCreditsUsage: [1],
  807. totalTokensUsage: [10],
  808. sortOrder: 1,
  809. },
  810. {
  811. modelCode: "uncached_input",
  812. modelName: "未缓存",
  813. totalCreditsUsage: [2],
  814. totalTokensUsage: [20],
  815. sortOrder: 2,
  816. },
  817. {
  818. modelCode: "output",
  819. modelName: "输出",
  820. totalCreditsUsage: [4],
  821. totalTokensUsage: [40],
  822. sortOrder: 3,
  823. },
  824. ],
  825. },
  826. }
  827. : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
  828. });
  829. }),
  830. };
  831. const service = createUsageStatsServiceForTest({
  832. apiClient,
  833. providers: [
  834. createProvider({
  835. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  836. name: "BigModel - Coding Plan",
  837. apiKey: "coding-plan-api-key",
  838. }),
  839. ],
  840. });
  841. const snapshot = await service.getCodingPlanUsageSnapshot({
  842. range: "7d",
  843. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  844. timeZone: "UTC",
  845. });
  846. expect(snapshot.modelUsage.modelDataList.map((item) => item.modelName)).toEqual([]);
  847. expect(snapshot.modelUsage.totalTokensUsage).toBe(70);
  848. });
  849. it("Coding Plan 总用量在真实模型行与拆分桶同时返回时不会双倍计算", async () => {
  850. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  851. const apiClient: ApiClient = {
  852. request: vi.fn(async (input) => {
  853. const url = input.toString();
  854. if (url.includes("/api/monitor/usage/quota/limit")) {
  855. return createJsonResponse({
  856. code: 200,
  857. data: { level: "pro", limits: [] },
  858. });
  859. }
  860. if (url.includes("/api/monitor/credit-usage/activity")) {
  861. return createJsonResponse({
  862. code: 200,
  863. data: { summary: { totalTokens: 0 }, series: [] },
  864. });
  865. }
  866. if (url.includes("/api/monitor/usage/model-performance-day")) {
  867. return createJsonResponse({
  868. code: 200,
  869. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  870. });
  871. }
  872. const usageType = new URL(url).searchParams.get("usageType");
  873. return createJsonResponse({
  874. code: 200,
  875. data:
  876. usageType === "MODEL"
  877. ? {
  878. summary: { totalCredits: { value: 7 } },
  879. modelUsage: {
  880. xTime: ["2026-05-18"],
  881. modelDataList: [
  882. {
  883. modelCode: "glm-5",
  884. modelName: "GLM-5",
  885. totalTokensUsage: [120],
  886. sortOrder: 0,
  887. },
  888. {
  889. modelCode: "cached_input",
  890. modelName: "缓存",
  891. totalCreditsUsage: [1],
  892. totalTokensUsage: [10],
  893. sortOrder: 1,
  894. },
  895. {
  896. modelCode: "uncached_input",
  897. modelName: "未缓存",
  898. totalCreditsUsage: [2],
  899. totalTokensUsage: [20],
  900. sortOrder: 2,
  901. },
  902. {
  903. modelCode: "output",
  904. modelName: "输出",
  905. totalCreditsUsage: [4],
  906. totalTokensUsage: [40],
  907. sortOrder: 3,
  908. },
  909. ],
  910. },
  911. }
  912. : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
  913. });
  914. }),
  915. };
  916. const service = createUsageStatsServiceForTest({
  917. apiClient,
  918. providers: [
  919. createProvider({
  920. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  921. name: "BigModel - Coding Plan",
  922. apiKey: "coding-plan-api-key",
  923. }),
  924. ],
  925. });
  926. const snapshot = await service.getCodingPlanUsageSnapshot({
  927. range: "7d",
  928. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  929. timeZone: "UTC",
  930. });
  931. expect(snapshot.modelUsage.modelDataList.map((item) => item.modelName)).toEqual(["GLM-5"]);
  932. expect(snapshot.modelUsage.totalTokensUsage).toBe(120);
  933. });
  934. it("Team Plan 用量使用 Account Auth 返回的团队项目 API Key", async () => {
  935. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  936. const requestUrls: string[] = [];
  937. const requestHeaders: Array<HeadersInit | undefined> = [];
  938. const apiClient: ApiClient = {
  939. request: vi.fn(async (input, init) => {
  940. const url = input.toString();
  941. requestUrls.push(url);
  942. requestHeaders.push(init?.headers);
  943. if (url.endsWith("/api_keys")) {
  944. return createJsonResponse({
  945. code: 200,
  946. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  947. });
  948. }
  949. if (url.endsWith("/api_keys/copy/team-ak")) {
  950. return createJsonResponse({
  951. code: 200,
  952. data: { secretKey: "team-secret" },
  953. });
  954. }
  955. if (url.includes("/api/monitor/usage/quota/limit")) {
  956. return createJsonResponse({
  957. code: 0,
  958. msg: "操作成功",
  959. data: {
  960. level: "team",
  961. limits: [],
  962. },
  963. });
  964. }
  965. if (url.includes("/api/monitor/credit-usage/activity")) {
  966. return createJsonResponse({
  967. code: 0,
  968. msg: "操作成功",
  969. data: { summary: { totalTokens: 120 }, series: [] },
  970. });
  971. }
  972. if (url.includes("/api/monitor/usage/model-performance-day")) {
  973. return createJsonResponse({
  974. code: 0,
  975. msg: "操作成功",
  976. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  977. });
  978. }
  979. expect(url).toContain("/api/monitor/credit-usage/usage-detail");
  980. return createJsonResponse({
  981. code: 0,
  982. msg: "操作成功",
  983. success: true,
  984. data:
  985. new URL(url).searchParams.get("usageType") === "MODEL"
  986. ? {
  987. modelUsage: {
  988. xTime: ["2026-05-18"],
  989. modelDataList: [
  990. {
  991. modelName: "glm-5",
  992. totalTokens: 120,
  993. totalTokensUsage: [120],
  994. },
  995. ],
  996. },
  997. }
  998. : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
  999. });
  1000. }),
  1001. };
  1002. const service = createUsageStatsServiceForTest({
  1003. apiClient,
  1004. providers: [
  1005. createProvider({
  1006. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1007. name: "BigModel - Coding Plan",
  1008. apiKey: "",
  1009. }),
  1010. ],
  1011. credentialTokens: {
  1012. "oauth:bigmodel:access_token": "oauth-token",
  1013. },
  1014. });
  1015. const snapshot = await service.getCodingPlanUsageSnapshot({
  1016. range: "30d",
  1017. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1018. organizationId: "org-team-a",
  1019. projectId: "proj-team-a",
  1020. timeZone: "UTC",
  1021. });
  1022. expect(requestUrls.some((url) => url.includes("/api_keys"))).toBe(false);
  1023. expect(requestHeaders.slice(-3)).toEqual([
  1024. expect.objectContaining({
  1025. authorization: "team-ak.team-secret",
  1026. "bigmodel-organization": "org-team-a",
  1027. "bigmodel-project": "proj-team-a",
  1028. }),
  1029. expect.objectContaining({
  1030. authorization: "team-ak.team-secret",
  1031. "bigmodel-organization": "org-team-a",
  1032. "bigmodel-project": "proj-team-a",
  1033. }),
  1034. expect.objectContaining({
  1035. authorization: "team-ak.team-secret",
  1036. "bigmodel-organization": "org-team-a",
  1037. "bigmodel-project": "proj-team-a",
  1038. }),
  1039. ]);
  1040. const teamQuotaUrl = new URL(
  1041. requestUrls.find((url) => url.includes("/api/monitor/usage/quota/limit")) ?? "",
  1042. );
  1043. const teamCreditUsageUrls = requestUrls
  1044. .filter((url) => url.includes("/api/monitor/credit-usage/"))
  1045. .map((url) => new URL(url));
  1046. expect(teamQuotaUrl.searchParams.get("type")).toBe("2");
  1047. expect(teamCreditUsageUrls).toHaveLength(3);
  1048. expect(teamCreditUsageUrls.every((url) => url.searchParams.get("type") === "3")).toBe(true);
  1049. expect(snapshot.modelUsage.totalTokensUsage).toBe(120);
  1050. expect(snapshot.toolUsage.toolDataList).toEqual([]);
  1051. expect(snapshot.sourceProvider.id).toBe(
  1052. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1053. );
  1054. });
  1055. it("Z.ai Team Plan 用量使用 Account Auth 返回的团队项目 API Key(对齐 BigModel)", async () => {
  1056. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1057. const requestUrls: string[] = [];
  1058. const requestHeaders: Array<HeadersInit | undefined> = [];
  1059. const apiClient: ApiClient = {
  1060. request: vi.fn(async (input, init) => {
  1061. const url = input.toString();
  1062. requestUrls.push(url);
  1063. requestHeaders.push(init?.headers);
  1064. if (url.endsWith("/api_keys")) {
  1065. return createJsonResponse({
  1066. code: 200,
  1067. data: [{ apiKey: "team-ak-zai", keyType: 2, name: "zcode-team-api-key" }],
  1068. });
  1069. }
  1070. if (url.endsWith("/api_keys/copy/team-ak-zai")) {
  1071. return createJsonResponse({
  1072. code: 200,
  1073. data: { secretKey: "team-secret-zai" },
  1074. });
  1075. }
  1076. if (url.includes("/api/monitor/usage/quota/limit")) {
  1077. return createJsonResponse({
  1078. code: 0,
  1079. msg: "操作成功",
  1080. data: { level: "team", limits: [] },
  1081. });
  1082. }
  1083. if (url.includes("/api/monitor/credit-usage/activity")) {
  1084. return createJsonResponse({
  1085. code: 0,
  1086. msg: "操作成功",
  1087. data: { summary: { totalTokens: 88 }, series: [] },
  1088. });
  1089. }
  1090. if (url.includes("/api/monitor/usage/model-performance-day")) {
  1091. return createJsonResponse({
  1092. code: 0,
  1093. msg: "操作成功",
  1094. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  1095. });
  1096. }
  1097. expect(url).toContain("/api/monitor/credit-usage/usage-detail");
  1098. return createJsonResponse({
  1099. code: 0,
  1100. msg: "操作成功",
  1101. success: true,
  1102. data:
  1103. new URL(url).searchParams.get("usageType") === "MODEL"
  1104. ? {
  1105. modelUsage: {
  1106. xTime: ["2026-05-18"],
  1107. modelDataList: [
  1108. {
  1109. modelName: "glm-5",
  1110. totalTokens: 88,
  1111. totalTokensUsage: [88],
  1112. },
  1113. ],
  1114. },
  1115. }
  1116. : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
  1117. });
  1118. }),
  1119. };
  1120. const service = createUsageStatsServiceForTest({
  1121. apiClient,
  1122. providers: [
  1123. createProvider({
  1124. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1125. name: "Z.ai - Coding Plan",
  1126. apiKey: "",
  1127. }),
  1128. ],
  1129. credentialTokens: {
  1130. "oauth:zai:access_token": "zai-oauth-token",
  1131. },
  1132. });
  1133. const snapshot = await service.getCodingPlanUsageSnapshot({
  1134. range: "30d",
  1135. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1136. organizationId: "org-zai-team",
  1137. projectId: "proj-zai-team",
  1138. timeZone: "UTC",
  1139. });
  1140. expect(requestUrls.some((url) => url.includes("/api_keys"))).toBe(false);
  1141. // monitor 接口用复制的团队项目 API Key + org/project header(与 bigmodel 同构)
  1142. expect(requestHeaders.slice(-3)).toEqual([
  1143. expect.objectContaining({
  1144. authorization: "zai-team-ak.zai-team-secret",
  1145. "bigmodel-organization": "org-zai-team",
  1146. "bigmodel-project": "proj-zai-team",
  1147. }),
  1148. expect.objectContaining({
  1149. authorization: "zai-team-ak.zai-team-secret",
  1150. "bigmodel-organization": "org-zai-team",
  1151. "bigmodel-project": "proj-zai-team",
  1152. }),
  1153. expect.objectContaining({
  1154. authorization: "zai-team-ak.zai-team-secret",
  1155. "bigmodel-organization": "org-zai-team",
  1156. "bigmodel-project": "proj-zai-team",
  1157. }),
  1158. ]);
  1159. expect(snapshot.modelUsage.totalTokensUsage).toBe(88);
  1160. expect(snapshot.sourceProvider.id).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
  1161. });
  1162. it("Team Plan monitor 缺少明确成功信号时不能把错误响应降级为空统计", async () => {
  1163. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1164. const apiClient: ApiClient = {
  1165. request: vi.fn(async (input) => {
  1166. const url = input.toString();
  1167. if (url.endsWith("/api_keys")) {
  1168. return createJsonResponse({
  1169. code: 200,
  1170. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  1171. });
  1172. }
  1173. if (url.endsWith("/api_keys/copy/team-ak")) {
  1174. return createJsonResponse({
  1175. code: 200,
  1176. data: { secretKey: "team-secret" },
  1177. });
  1178. }
  1179. if (url.includes("/api/monitor/usage/quota/limit")) {
  1180. return createJsonResponse({
  1181. code: 200,
  1182. data: { level: "team", limits: [] },
  1183. });
  1184. }
  1185. if (url.includes("/api/monitor/credit-usage/activity")) {
  1186. return createJsonResponse({
  1187. code: 200,
  1188. data: { summary: { totalTokens: 0 }, series: [] },
  1189. });
  1190. }
  1191. if (url.includes("/api/monitor/usage/model-performance-day")) {
  1192. return createJsonResponse({
  1193. code: 200,
  1194. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  1195. });
  1196. }
  1197. expect(url).toContain("/api/monitor/credit-usage/usage-detail");
  1198. return createJsonResponse({ msg: "token expired" });
  1199. }),
  1200. };
  1201. const service = createUsageStatsServiceForTest({
  1202. apiClient,
  1203. providers: [
  1204. createProvider({
  1205. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1206. name: "BigModel - Coding Plan",
  1207. apiKey: "",
  1208. }),
  1209. ],
  1210. credentialTokens: {
  1211. "oauth:bigmodel:access_token": "oauth-token",
  1212. },
  1213. });
  1214. await expect(
  1215. service.getCodingPlanUsageSnapshot({
  1216. range: "7d",
  1217. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1218. organizationId: "org-team-a",
  1219. projectId: "proj-team-a",
  1220. timeZone: "UTC",
  1221. }),
  1222. ).rejects.toThrow("token expired");
  1223. });
  1224. // CR-01 回归:activity / usage-detail / model-performance-day 是可选数据面。
  1225. // 任一接口传输层失败(HTTP 非 2xx、超时、断网)时只清空对应区域,
  1226. // 不能让 Promise.all 提前 reject 拖垮整张 Coding Plan Usage 面板。
  1227. it("可选 monitor 接口网络失败时只清空对应区域,quota 与其它区域正常返回", async () => {
  1228. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1229. const apiClient: ApiClient = {
  1230. request: vi.fn(async (input) => {
  1231. const url = input.toString();
  1232. if (url.includes("/api/monitor/usage/quota/limit")) {
  1233. return createJsonResponse({
  1234. code: 200,
  1235. data: {
  1236. level: "pro",
  1237. limits: [
  1238. {
  1239. type: "TOKENS_LIMIT",
  1240. unit: 3,
  1241. number: 5,
  1242. usage: 100,
  1243. currentValue: 31,
  1244. percentage: 31,
  1245. },
  1246. ],
  1247. },
  1248. });
  1249. }
  1250. if (url.includes("/api/monitor/credit-usage/activity")) {
  1251. // 传输层失败一:HTTP 非 2xx,readApiJson 会抛 ApiError。
  1252. return new Response("Internal Server Error", { status: 500 });
  1253. }
  1254. if (url.includes("/api/monitor/credit-usage/usage-detail")) {
  1255. if (new URL(url).searchParams.get("usageType") === "MODEL") {
  1256. return createJsonResponse({
  1257. code: 200,
  1258. data: {
  1259. summary: {
  1260. cacheHitRate: { value: 0.893, trend: null },
  1261. totalCredits: { value: 28.95, trend: null },
  1262. averageDailyCredits: { value: 4.13, trend: null },
  1263. },
  1264. modelUsage: { xTime: ["2026-05-18"], modelDataList: [] },
  1265. },
  1266. });
  1267. }
  1268. // 传输层失败二:请求超时,request 直接 reject。
  1269. throw new Error("Request timed out after 15000ms");
  1270. }
  1271. if (url.includes("/api/monitor/usage/model-performance-day")) {
  1272. return createJsonResponse({
  1273. code: 200,
  1274. data: {
  1275. x_time: ["2026-05-18"],
  1276. proMaxDecodeSpeed: [125.4],
  1277. liteDecodeSpeed: [55.2],
  1278. },
  1279. });
  1280. }
  1281. throw new Error(`unexpected request ${url}`);
  1282. }),
  1283. };
  1284. const service = createUsageStatsServiceForTest({
  1285. apiClient,
  1286. providers: [
  1287. createProvider({
  1288. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1289. name: "BigModel - Coding Plan",
  1290. }),
  1291. ],
  1292. });
  1293. const snapshot = await service.getCodingPlanUsageSnapshot({
  1294. range: "7d",
  1295. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1296. timeZone: "UTC",
  1297. });
  1298. // 未失败的区域不受影响:quota 剩余、模型维度详情和 health 都正常。
  1299. expect(snapshot.quota?.limits).toHaveLength(1);
  1300. expect(snapshot.detail.model.totalCredits).toBe(28.95);
  1301. expect(snapshot.health?.xTime).toEqual(["2026-05-18"]);
  1302. // 传输失败的区域清空为空统计,而不是拖垮整张面板。
  1303. expect(snapshot.activity.summary.totalTokens).toBe(0);
  1304. expect(snapshot.detail.tool.totalCredits).toBe(0);
  1305. });
  1306. it("quota monitor 网络失败时 Coding Plan 用量整体失败", async () => {
  1307. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1308. const apiClient: ApiClient = {
  1309. request: vi.fn(async (input) => {
  1310. const url = input.toString();
  1311. if (url.includes("/api/monitor/usage/quota/limit")) {
  1312. throw new Error("Request timed out after 15000ms");
  1313. }
  1314. return createJsonResponse({ code: 200, data: {} });
  1315. }),
  1316. };
  1317. const service = createUsageStatsServiceForTest({
  1318. apiClient,
  1319. providers: [
  1320. createProvider({
  1321. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1322. name: "BigModel - Coding Plan",
  1323. }),
  1324. ],
  1325. });
  1326. // quota 是面板核心数据,传输失败必须保留整体报错语义,
  1327. // 避免“查不到额度”被伪装成一张全空面板。
  1328. await expect(
  1329. service.getCodingPlanUsageSnapshot({
  1330. range: "7d",
  1331. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1332. timeZone: "UTC",
  1333. }),
  1334. ).rejects.toThrow("Request timed out after 15000ms");
  1335. });
  1336. it("严格指定 Coding Plan 缺 apiKey 时不回退普通 provider 或本地 session", async () => {
  1337. const apiClient: ApiClient = {
  1338. request: vi.fn(),
  1339. };
  1340. const service = createUsageStatsServiceForTest({
  1341. apiClient,
  1342. providers: [
  1343. createProvider({
  1344. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1345. name: "BigModel - Coding Plan",
  1346. apiKey: "",
  1347. }),
  1348. createProvider({
  1349. id: TEST_BIGMODEL_PROVIDER_ID,
  1350. name: "BigModel",
  1351. apiKey: "ordinary-api-key",
  1352. }),
  1353. ],
  1354. });
  1355. await expect(
  1356. service.getCodingPlanUsageSnapshot({
  1357. range: "today",
  1358. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1359. timeZone: "UTC",
  1360. }),
  1361. ).rejects.toThrow("bigmodel_coding_plan_api_key_required");
  1362. expect(apiClient.request).not.toHaveBeenCalled();
  1363. });
  1364. it("Team Plan Account Auth 失败时透传真实错误", async () => {
  1365. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1366. const apiClient: ApiClient = {
  1367. request: vi.fn(async (input) => {
  1368. const url = input.toString();
  1369. if (url.endsWith("/api_keys")) {
  1370. // 修复原因:list 无可用 key 时走 create;create 被远端拒绝并返回业务 msg,
  1371. // 原实现只抛错误码 bigmodel_coding_plan_api_key_required,UI 无法展示真实原因。
  1372. return createJsonResponse({
  1373. code: 500,
  1374. success: false,
  1375. msg: "您当前暂无有效的团队套餐授权记录,无法创建API Key",
  1376. });
  1377. }
  1378. throw new Error(`unexpected request ${url}`);
  1379. }),
  1380. };
  1381. const service = createUsageStatsServiceForTest({
  1382. apiClient,
  1383. providers: [
  1384. createProvider({
  1385. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1386. name: "BigModel - Coding Plan",
  1387. apiKey: "",
  1388. }),
  1389. ],
  1390. resolveAccountAuth: async () => {
  1391. throw new Error("您当前暂无有效的团队套餐授权记录,无法创建API Key");
  1392. },
  1393. });
  1394. await expect(
  1395. service.getCodingPlanUsageSnapshot({
  1396. range: "7d",
  1397. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1398. organizationId: "org-team-a",
  1399. projectId: "proj-team-a",
  1400. timeZone: "UTC",
  1401. }),
  1402. ).rejects.toThrow("您当前暂无有效的团队套餐授权记录,无法创建API Key");
  1403. });
  1404. it("显式选择供应商时缺 key 不回落到本地数据", async () => {
  1405. const service = createUsageStatsServiceForTest({
  1406. providers: [],
  1407. });
  1408. await expect(
  1409. service.getSnapshot({
  1410. range: "all",
  1411. preferredProviderId: TEST_BIGMODEL_PROVIDER_ID,
  1412. timeZone: "UTC",
  1413. }),
  1414. ).rejects.toThrow("no_bigmodel_api_key");
  1415. });
  1416. it("已配置供应商但 monitor 接口失败时保留真实错误", async () => {
  1417. const apiClient: ApiClient = {
  1418. request: vi.fn(async () => {
  1419. throw new Error("Request timed out after 15000ms");
  1420. }),
  1421. };
  1422. const service = createUsageStatsServiceForTest({
  1423. apiClient,
  1424. providers: [createProvider({})],
  1425. });
  1426. await expect(
  1427. service.getSnapshot({
  1428. range: "all",
  1429. timeZone: "UTC",
  1430. }),
  1431. ).rejects.toThrow("Request timed out after 15000ms");
  1432. });
  1433. });