usageStatsService.test.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  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("Team Plan 用量允许已登录但被禁用的 BigModel Coding Plan provider", async () => {
  1056. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1057. const requestUrls: string[] = [];
  1058. const apiClient: ApiClient = {
  1059. request: vi.fn(async (input) => {
  1060. const url = input.toString();
  1061. requestUrls.push(url);
  1062. if (url.endsWith("/api_keys")) {
  1063. return createJsonResponse({
  1064. code: 200,
  1065. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  1066. });
  1067. }
  1068. if (url.endsWith("/api_keys/copy/team-ak")) {
  1069. return createJsonResponse({
  1070. code: 200,
  1071. data: { secretKey: "team-secret" },
  1072. });
  1073. }
  1074. if (url.includes("/api/monitor/usage/quota/limit")) {
  1075. return createJsonResponse({
  1076. code: 200,
  1077. data: { level: "team", limits: [] },
  1078. });
  1079. }
  1080. if (url.includes("/api/monitor/credit-usage/activity")) {
  1081. return createJsonResponse({
  1082. code: 200,
  1083. data: { summary: { totalTokens: 0 }, series: [] },
  1084. });
  1085. }
  1086. return createJsonResponse({
  1087. code: 200,
  1088. data:
  1089. new URL(url).searchParams.get("usageType") === "MODEL"
  1090. ? { modelUsage: { xTime: ["2026-05-18"], modelDataList: [] } }
  1091. : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
  1092. });
  1093. }),
  1094. };
  1095. const service = createUsageStatsServiceForTest({
  1096. apiClient,
  1097. providers: [
  1098. createProvider({
  1099. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1100. name: "BigModel - Coding Plan",
  1101. apiKey: "",
  1102. enabled: false,
  1103. }),
  1104. ],
  1105. credentialTokens: {
  1106. "oauth:bigmodel:access_token": "oauth-token",
  1107. },
  1108. });
  1109. await service.getCodingPlanUsageSnapshot({
  1110. range: "7d",
  1111. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1112. organizationId: "org-team-a",
  1113. projectId: "proj-team-a",
  1114. timeZone: "UTC",
  1115. });
  1116. expect(requestUrls[0]).toBe("https://bigmodel.cn/api/monitor/usage/quota/limit?type=2");
  1117. });
  1118. it("Z.ai Team Plan 用量使用 Account Auth 返回的团队项目 API Key(对齐 BigModel)", async () => {
  1119. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1120. const requestUrls: string[] = [];
  1121. const requestHeaders: Array<HeadersInit | undefined> = [];
  1122. const apiClient: ApiClient = {
  1123. request: vi.fn(async (input, init) => {
  1124. const url = input.toString();
  1125. requestUrls.push(url);
  1126. requestHeaders.push(init?.headers);
  1127. if (url.endsWith("/api_keys")) {
  1128. return createJsonResponse({
  1129. code: 200,
  1130. data: [{ apiKey: "team-ak-zai", keyType: 2, name: "zcode-team-api-key" }],
  1131. });
  1132. }
  1133. if (url.endsWith("/api_keys/copy/team-ak-zai")) {
  1134. return createJsonResponse({
  1135. code: 200,
  1136. data: { secretKey: "team-secret-zai" },
  1137. });
  1138. }
  1139. if (url.includes("/api/monitor/usage/quota/limit")) {
  1140. return createJsonResponse({
  1141. code: 0,
  1142. msg: "操作成功",
  1143. data: { level: "team", limits: [] },
  1144. });
  1145. }
  1146. if (url.includes("/api/monitor/credit-usage/activity")) {
  1147. return createJsonResponse({
  1148. code: 0,
  1149. msg: "操作成功",
  1150. data: { summary: { totalTokens: 88 }, series: [] },
  1151. });
  1152. }
  1153. if (url.includes("/api/monitor/usage/model-performance-day")) {
  1154. return createJsonResponse({
  1155. code: 0,
  1156. msg: "操作成功",
  1157. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  1158. });
  1159. }
  1160. expect(url).toContain("/api/monitor/credit-usage/usage-detail");
  1161. return createJsonResponse({
  1162. code: 0,
  1163. msg: "操作成功",
  1164. success: true,
  1165. data:
  1166. new URL(url).searchParams.get("usageType") === "MODEL"
  1167. ? {
  1168. modelUsage: {
  1169. xTime: ["2026-05-18"],
  1170. modelDataList: [
  1171. {
  1172. modelName: "glm-5",
  1173. totalTokens: 88,
  1174. totalTokensUsage: [88],
  1175. },
  1176. ],
  1177. },
  1178. }
  1179. : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
  1180. });
  1181. }),
  1182. };
  1183. const service = createUsageStatsServiceForTest({
  1184. apiClient,
  1185. providers: [
  1186. createProvider({
  1187. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1188. name: "Z.ai - Coding Plan",
  1189. apiKey: "",
  1190. }),
  1191. ],
  1192. credentialTokens: {
  1193. "oauth:zai:access_token": "zai-oauth-token",
  1194. },
  1195. });
  1196. const snapshot = await service.getCodingPlanUsageSnapshot({
  1197. range: "30d",
  1198. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1199. organizationId: "org-zai-team",
  1200. projectId: "proj-zai-team",
  1201. timeZone: "UTC",
  1202. });
  1203. expect(requestUrls.some((url) => url.includes("/api_keys"))).toBe(false);
  1204. // monitor 接口用复制的团队项目 API Key + org/project header(与 bigmodel 同构)
  1205. expect(requestHeaders.slice(-3)).toEqual([
  1206. expect.objectContaining({
  1207. authorization: "zai-team-ak.zai-team-secret",
  1208. "bigmodel-organization": "org-zai-team",
  1209. "bigmodel-project": "proj-zai-team",
  1210. }),
  1211. expect.objectContaining({
  1212. authorization: "zai-team-ak.zai-team-secret",
  1213. "bigmodel-organization": "org-zai-team",
  1214. "bigmodel-project": "proj-zai-team",
  1215. }),
  1216. expect.objectContaining({
  1217. authorization: "zai-team-ak.zai-team-secret",
  1218. "bigmodel-organization": "org-zai-team",
  1219. "bigmodel-project": "proj-zai-team",
  1220. }),
  1221. ]);
  1222. expect(snapshot.modelUsage.totalTokensUsage).toBe(88);
  1223. expect(snapshot.sourceProvider.id).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
  1224. });
  1225. it("Z.ai Team Plan 用量允许已登录但被禁用的 Coding Plan provider(对齐 BigModel)", async () => {
  1226. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1227. const requestUrls: string[] = [];
  1228. const apiClient: ApiClient = {
  1229. request: vi.fn(async (input) => {
  1230. const url = input.toString();
  1231. requestUrls.push(url);
  1232. if (url.endsWith("/api_keys")) {
  1233. return createJsonResponse({
  1234. code: 200,
  1235. data: [{ apiKey: "team-ak-zai", keyType: 2, name: "zcode-team-api-key" }],
  1236. });
  1237. }
  1238. if (url.endsWith("/api_keys/copy/team-ak-zai")) {
  1239. return createJsonResponse({
  1240. code: 200,
  1241. data: { secretKey: "team-secret-zai" },
  1242. });
  1243. }
  1244. if (url.includes("/api/monitor/usage/quota/limit")) {
  1245. return createJsonResponse({
  1246. code: 200,
  1247. data: { level: "team", limits: [] },
  1248. });
  1249. }
  1250. if (url.includes("/api/monitor/credit-usage/activity")) {
  1251. return createJsonResponse({
  1252. code: 200,
  1253. data: { summary: { totalTokens: 0 }, series: [] },
  1254. });
  1255. }
  1256. return createJsonResponse({
  1257. code: 200,
  1258. data:
  1259. new URL(url).searchParams.get("usageType") === "MODEL"
  1260. ? { modelUsage: { xTime: ["2026-05-18"], modelDataList: [] } }
  1261. : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
  1262. });
  1263. }),
  1264. };
  1265. const service = createUsageStatsServiceForTest({
  1266. apiClient,
  1267. providers: [
  1268. createProvider({
  1269. id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1270. name: "Z.ai - Coding Plan",
  1271. apiKey: "",
  1272. enabled: false,
  1273. }),
  1274. ],
  1275. credentialTokens: {
  1276. "oauth:zai:access_token": "zai-oauth-token",
  1277. },
  1278. });
  1279. await service.getCodingPlanUsageSnapshot({
  1280. range: "7d",
  1281. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1282. organizationId: "org-zai-team",
  1283. projectId: "proj-zai-team",
  1284. timeZone: "UTC",
  1285. });
  1286. expect(requestUrls[0]).toBe("https://api.z.ai/api/monitor/usage/quota/limit?type=2");
  1287. });
  1288. it("Team Plan monitor 缺少明确成功信号时不能把错误响应降级为空统计", async () => {
  1289. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1290. const apiClient: ApiClient = {
  1291. request: vi.fn(async (input) => {
  1292. const url = input.toString();
  1293. if (url.endsWith("/api_keys")) {
  1294. return createJsonResponse({
  1295. code: 200,
  1296. data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
  1297. });
  1298. }
  1299. if (url.endsWith("/api_keys/copy/team-ak")) {
  1300. return createJsonResponse({
  1301. code: 200,
  1302. data: { secretKey: "team-secret" },
  1303. });
  1304. }
  1305. if (url.includes("/api/monitor/usage/quota/limit")) {
  1306. return createJsonResponse({
  1307. code: 200,
  1308. data: { level: "team", limits: [] },
  1309. });
  1310. }
  1311. if (url.includes("/api/monitor/credit-usage/activity")) {
  1312. return createJsonResponse({
  1313. code: 200,
  1314. data: { summary: { totalTokens: 0 }, series: [] },
  1315. });
  1316. }
  1317. if (url.includes("/api/monitor/usage/model-performance-day")) {
  1318. return createJsonResponse({
  1319. code: 200,
  1320. data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
  1321. });
  1322. }
  1323. expect(url).toContain("/api/monitor/credit-usage/usage-detail");
  1324. return createJsonResponse({ msg: "token expired" });
  1325. }),
  1326. };
  1327. const service = createUsageStatsServiceForTest({
  1328. apiClient,
  1329. providers: [
  1330. createProvider({
  1331. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1332. name: "BigModel - Coding Plan",
  1333. apiKey: "",
  1334. }),
  1335. ],
  1336. credentialTokens: {
  1337. "oauth:bigmodel:access_token": "oauth-token",
  1338. },
  1339. });
  1340. await expect(
  1341. service.getCodingPlanUsageSnapshot({
  1342. range: "7d",
  1343. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1344. organizationId: "org-team-a",
  1345. projectId: "proj-team-a",
  1346. timeZone: "UTC",
  1347. }),
  1348. ).rejects.toThrow("token expired");
  1349. });
  1350. // CR-01 回归:activity / usage-detail / model-performance-day 是可选数据面。
  1351. // 任一接口传输层失败(HTTP 非 2xx、超时、断网)时只清空对应区域,
  1352. // 不能让 Promise.all 提前 reject 拖垮整张 Coding Plan Usage 面板。
  1353. it("可选 monitor 接口网络失败时只清空对应区域,quota 与其它区域正常返回", async () => {
  1354. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1355. const apiClient: ApiClient = {
  1356. request: vi.fn(async (input) => {
  1357. const url = input.toString();
  1358. if (url.includes("/api/monitor/usage/quota/limit")) {
  1359. return createJsonResponse({
  1360. code: 200,
  1361. data: {
  1362. level: "pro",
  1363. limits: [
  1364. {
  1365. type: "TOKENS_LIMIT",
  1366. unit: 3,
  1367. number: 5,
  1368. usage: 100,
  1369. currentValue: 31,
  1370. percentage: 31,
  1371. },
  1372. ],
  1373. },
  1374. });
  1375. }
  1376. if (url.includes("/api/monitor/credit-usage/activity")) {
  1377. // 传输层失败一:HTTP 非 2xx,readApiJson 会抛 ApiError。
  1378. return new Response("Internal Server Error", { status: 500 });
  1379. }
  1380. if (url.includes("/api/monitor/credit-usage/usage-detail")) {
  1381. if (new URL(url).searchParams.get("usageType") === "MODEL") {
  1382. return createJsonResponse({
  1383. code: 200,
  1384. data: {
  1385. summary: {
  1386. cacheHitRate: { value: 0.893, trend: null },
  1387. totalCredits: { value: 28.95, trend: null },
  1388. averageDailyCredits: { value: 4.13, trend: null },
  1389. },
  1390. modelUsage: { xTime: ["2026-05-18"], modelDataList: [] },
  1391. },
  1392. });
  1393. }
  1394. // 传输层失败二:请求超时,request 直接 reject。
  1395. throw new Error("Request timed out after 15000ms");
  1396. }
  1397. if (url.includes("/api/monitor/usage/model-performance-day")) {
  1398. return createJsonResponse({
  1399. code: 200,
  1400. data: {
  1401. x_time: ["2026-05-18"],
  1402. proMaxDecodeSpeed: [125.4],
  1403. liteDecodeSpeed: [55.2],
  1404. },
  1405. });
  1406. }
  1407. throw new Error(`unexpected request ${url}`);
  1408. }),
  1409. };
  1410. const service = createUsageStatsServiceForTest({
  1411. apiClient,
  1412. providers: [
  1413. createProvider({
  1414. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1415. name: "BigModel - Coding Plan",
  1416. }),
  1417. ],
  1418. });
  1419. const snapshot = await service.getCodingPlanUsageSnapshot({
  1420. range: "7d",
  1421. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1422. timeZone: "UTC",
  1423. });
  1424. // 未失败的区域不受影响:quota 剩余、模型维度详情和 health 都正常。
  1425. expect(snapshot.quota?.limits).toHaveLength(1);
  1426. expect(snapshot.detail.model.totalCredits).toBe(28.95);
  1427. expect(snapshot.health?.xTime).toEqual(["2026-05-18"]);
  1428. // 传输失败的区域清空为空统计,而不是拖垮整张面板。
  1429. expect(snapshot.activity.summary.totalTokens).toBe(0);
  1430. expect(snapshot.detail.tool.totalCredits).toBe(0);
  1431. });
  1432. it("quota monitor 网络失败时 Coding Plan 用量整体失败", async () => {
  1433. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1434. const apiClient: ApiClient = {
  1435. request: vi.fn(async (input) => {
  1436. const url = input.toString();
  1437. if (url.includes("/api/monitor/usage/quota/limit")) {
  1438. throw new Error("Request timed out after 15000ms");
  1439. }
  1440. return createJsonResponse({ code: 200, data: {} });
  1441. }),
  1442. };
  1443. const service = createUsageStatsServiceForTest({
  1444. apiClient,
  1445. providers: [
  1446. createProvider({
  1447. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1448. name: "BigModel - Coding Plan",
  1449. }),
  1450. ],
  1451. });
  1452. // quota 是面板核心数据,传输失败必须保留整体报错语义,
  1453. // 避免“查不到额度”被伪装成一张全空面板。
  1454. await expect(
  1455. service.getCodingPlanUsageSnapshot({
  1456. range: "7d",
  1457. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1458. timeZone: "UTC",
  1459. }),
  1460. ).rejects.toThrow("Request timed out after 15000ms");
  1461. });
  1462. it("严格指定 Coding Plan 缺 apiKey 时不回退普通 provider 或本地 session", async () => {
  1463. const apiClient: ApiClient = {
  1464. request: vi.fn(),
  1465. };
  1466. const service = createUsageStatsServiceForTest({
  1467. apiClient,
  1468. providers: [
  1469. createProvider({
  1470. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1471. name: "BigModel - Coding Plan",
  1472. apiKey: "",
  1473. }),
  1474. createProvider({
  1475. id: TEST_BIGMODEL_PROVIDER_ID,
  1476. name: "BigModel",
  1477. apiKey: "ordinary-api-key",
  1478. }),
  1479. ],
  1480. });
  1481. await expect(
  1482. service.getCodingPlanUsageSnapshot({
  1483. range: "today",
  1484. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1485. timeZone: "UTC",
  1486. }),
  1487. ).rejects.toThrow("bigmodel_coding_plan_api_key_required");
  1488. expect(apiClient.request).not.toHaveBeenCalled();
  1489. });
  1490. it("个人套餐缺少 Account Auth 凭据时不再触发旧 Provider 刷新", async () => {
  1491. const providers = [
  1492. createProvider({
  1493. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1494. name: "BigModel - Coding Plan",
  1495. apiKey: "",
  1496. enabled: false,
  1497. }),
  1498. ];
  1499. const requestHeaders: Record<string, string>[] = [];
  1500. const apiClient: ApiClient = {
  1501. request: vi.fn(async (_input, init) => {
  1502. requestHeaders.push((init?.headers ?? {}) as Record<string, string>);
  1503. return createJsonResponse({ code: 200, data: {} });
  1504. }),
  1505. };
  1506. const service = createUsageStatsServiceForTest({
  1507. apiClient,
  1508. providers,
  1509. });
  1510. await expect(
  1511. service.getCodingPlanUsageSnapshot({
  1512. range: "7d",
  1513. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1514. timeZone: "UTC",
  1515. }),
  1516. ).rejects.toThrow("bigmodel_coding_plan_api_key_required");
  1517. expect(requestHeaders).toEqual([]);
  1518. });
  1519. it("Team Plan Account Auth 失败时透传真实错误", async () => {
  1520. vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
  1521. const apiClient: ApiClient = {
  1522. request: vi.fn(async (input) => {
  1523. const url = input.toString();
  1524. if (url.endsWith("/api_keys")) {
  1525. // 修复原因:list 无可用 key 时走 create;create 被远端拒绝并返回业务 msg,
  1526. // 原实现只抛错误码 bigmodel_coding_plan_api_key_required,UI 无法展示真实原因。
  1527. return createJsonResponse({
  1528. code: 500,
  1529. success: false,
  1530. msg: "您当前暂无有效的团队套餐授权记录,无法创建API Key",
  1531. });
  1532. }
  1533. throw new Error(`unexpected request ${url}`);
  1534. }),
  1535. };
  1536. const service = createUsageStatsServiceForTest({
  1537. apiClient,
  1538. providers: [
  1539. createProvider({
  1540. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1541. name: "BigModel - Coding Plan",
  1542. apiKey: "",
  1543. }),
  1544. ],
  1545. resolveAccountAuth: async () => {
  1546. throw new Error("您当前暂无有效的团队套餐授权记录,无法创建API Key");
  1547. },
  1548. });
  1549. await expect(
  1550. service.getCodingPlanUsageSnapshot({
  1551. range: "7d",
  1552. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1553. organizationId: "org-team-a",
  1554. projectId: "proj-team-a",
  1555. timeZone: "UTC",
  1556. }),
  1557. ).rejects.toThrow("您当前暂无有效的团队套餐授权记录,无法创建API Key");
  1558. });
  1559. it("显式选择供应商时缺 key 不回落到本地数据", async () => {
  1560. const service = createUsageStatsServiceForTest({
  1561. providers: [],
  1562. });
  1563. await expect(
  1564. service.getSnapshot({
  1565. range: "all",
  1566. preferredProviderId: TEST_BIGMODEL_PROVIDER_ID,
  1567. timeZone: "UTC",
  1568. }),
  1569. ).rejects.toThrow("no_bigmodel_api_key");
  1570. });
  1571. it("已配置供应商但 monitor 接口失败时保留真实错误", async () => {
  1572. const apiClient: ApiClient = {
  1573. request: vi.fn(async () => {
  1574. throw new Error("Request timed out after 15000ms");
  1575. }),
  1576. };
  1577. const service = createUsageStatsServiceForTest({
  1578. apiClient,
  1579. providers: [createProvider({})],
  1580. });
  1581. await expect(
  1582. service.getSnapshot({
  1583. range: "all",
  1584. timeZone: "UTC",
  1585. }),
  1586. ).rejects.toThrow("Request timed out after 15000ms");
  1587. });
  1588. });