| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667 |
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
- import type { ApiClient, AppUsageSnapshot, ZCodeAccountAccess } from "@zcode/shared";
- import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
- import type { IZCodeAgentService } from "../src/zcode-agent/zcodeAgent.js";
- import { createUsageStatsService } from "../src/usage-stats/usageStatsService.js";
- import { resolveCodingPlanUsageTimeRange } from "../src/usage-stats/providers/bigmodelUsageMonitorRange.js";
- const TEST_BIGMODEL_PROVIDER_ID = "test-bigmodel-api-provider";
- const TEST_ZAI_PROVIDER_ID = "test-zai-api-provider";
- function createAppUsageSnapshot(): AppUsageSnapshot {
- return {
- range: "30d",
- generatedAt: 1_900_000_000_000,
- timeZone: "UTC",
- source: "agent-db",
- summary: {
- totalTokens: 104,
- inputTokens: 14,
- outputTokens: 5,
- reasoningTokens: 0,
- cacheCreationTokens: 5,
- cacheReadTokens: 80,
- cacheHitRate: 0.8,
- totalSessions: 1,
- totalTurns: 1,
- toolCallCount: 2,
- toolErrorRate: 0.5,
- modelErrorRate: 0.5,
- avgTimeToFirstTokenMs: 100,
- avgTurnDurationMs: 2000,
- activeDays: 2,
- currentStreakDays: 2,
- longestSessionMs: 2000,
- longestStreakDays: 2,
- peakDayTokens: 104,
- favoriteModel: { modelId: "model-a", totalTokens: 104, share: 1 },
- },
- heatmap: { startDate: null, endDate: null, maxTokens: 100, weeks: [] },
- dailyModelUsage: [],
- models: [],
- tools: [],
- };
- }
- interface TestUsageProvider {
- id: string;
- name: string;
- enabled: boolean;
- apiKey: string;
- }
- function createProvider(overrides: Partial<TestUsageProvider>): TestUsageProvider {
- return {
- id: TEST_BIGMODEL_PROVIDER_ID,
- name: "BigModel",
- enabled: true,
- apiKey: "bigmodel-api-key",
- ...overrides,
- };
- }
- function createJsonResponse(body: unknown): Response {
- return new Response(JSON.stringify(body), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
- }
- function createUsageStatsServiceForTest(params: {
- apiClient?: ApiClient;
- providers: TestUsageProvider[];
- env?: NodeJS.ProcessEnv;
- credentialTokens?: Record<string, string | null | undefined>;
- resolveAccountAuth?: (input: {
- providerId: string;
- accountAccess: ZCodeAccountAccess;
- }) => Promise<{ apiKey?: string }>;
- getAppUsageStats?: IZCodeAgentService["getAppUsageStats"];
- }) {
- const service = createUsageStatsService({
- apiClient: params.apiClient ?? {
- request: vi.fn(),
- },
- accountRequestAuthService: {
- resolveAccessCurrent: vi.fn(async () => null),
- resolveCurrent: vi.fn(
- params.resolveAccountAuth ??
- (async ({ providerId, accountAccess }) => {
- if (accountAccess.planKind === "team-coding-plan") {
- return {
- apiKey:
- providerId === BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
- ? "zai-team-ak.zai-team-secret"
- : "team-ak.team-secret",
- };
- }
- return {
- apiKey: params.providers.find((provider) => provider.id === providerId)?.apiKey,
- };
- }),
- ),
- assertCurrent: vi.fn(async () => undefined),
- },
- resolveApiAuthorization: vi.fn(async ({ preferredProviderId }) => {
- const provider = params.providers.find((candidate) =>
- preferredProviderId ? candidate.id === preferredProviderId : candidate.enabled,
- );
- const apiKey = provider?.apiKey?.trim() ?? "";
- if (!provider || !apiKey) return null;
- return {
- authorization: apiKey,
- quotaUrl:
- provider.id === TEST_ZAI_PROVIDER_ID
- ? "https://api.z.ai/api/monitor/usage/quota/limit"
- : "https://bigmodel.cn/api/monitor/usage/quota/limit",
- provider: { id: provider.id, name: provider.name },
- };
- }),
- credentialService: {
- load: vi.fn(async (key) => params.credentialTokens?.[key] ?? null),
- },
- env: params.env,
- zcodeAgentService: {
- getAppUsageStats: params.getAppUsageStats ?? vi.fn(async () => createAppUsageSnapshot()),
- },
- });
- return {
- ...service,
- getCodingPlanUsageSnapshot: (
- request: Parameters<typeof service.getCodingPlanUsageSnapshot>[0],
- ) =>
- service.getCodingPlanUsageSnapshot({
- ...request,
- accountAccess:
- request.accountAccess ??
- (request.organizationId && request.projectId
- ? {
- type: "zhipu-account",
- family: request.preferredProviderId?.includes("zai") ? "zai" : "bigmodel",
- planKind: "team-coding-plan",
- productId: "test-product",
- organizationId: request.organizationId,
- projectId: request.projectId,
- }
- : {
- type: "zhipu-account",
- family: request.preferredProviderId?.includes("zai") ? "zai" : "bigmodel",
- planKind: "individual-coding-plan",
- }),
- }),
- // Highspeed 的普通 TPS 查询同样按 accountAccess 鉴权;默认补个人套餐访问上下文,
- // 让用例专注缓存与诊断行为,需要 Team scope 的用例显式传入。
- getCodingPlanRegularTps: (
- request: Omit<
- Parameters<NonNullable<typeof service.getCodingPlanRegularTps>>[0],
- "accountAccess"
- > & {
- accountAccess?: ZCodeAccountAccess;
- },
- ) =>
- service.getCodingPlanRegularTps?.({
- ...request,
- accountAccess:
- request.accountAccess ??
- ({
- type: "zhipu-account",
- family: request.preferredProviderId.includes("zai") ? "zai" : "bigmodel",
- planKind: "individual-coding-plan",
- } satisfies ZCodeAccountAccess),
- }),
- };
- }
- describe("createUsageStatsService", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
- afterEach(() => {
- vi.useRealTimers();
- vi.restoreAllMocks();
- });
- it("Highspeed 普通 TPS 只请求 7 天健康接口,并缓存及合并同 key 并发请求", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async () =>
- createJsonResponse({
- code: 200,
- data: { x_time: ["2026-05-18", "2026-05-19"], proMaxDecodeSpeed: [68, 73] },
- }),
- ),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "coding-plan-api-key",
- }),
- ],
- });
- const request = {
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- };
- await expect(
- Promise.all([
- service.getCodingPlanRegularTps(request),
- service.getCodingPlanRegularTps(request),
- ]),
- ).resolves.toEqual([73, 73]);
- await expect(service.getCodingPlanRegularTps(request)).resolves.toBe(73);
- expect(apiClient.request).toHaveBeenCalledTimes(1);
- const requestedUrl = String(vi.mocked(apiClient.request).mock.calls[0]?.[0]);
- expect(requestedUrl).toContain("/model-performance-day");
- expect(requestedUrl).not.toContain("credit-usage");
- vi.advanceTimersByTime(5 * 60_000 + 1);
- await expect(service.getCodingPlanRegularTps(request)).resolves.toBe(73);
- expect(apiClient.request).toHaveBeenCalledTimes(2);
- });
- it("Highspeed 普通 TPS 按账号访问上下文隔离缓存", async () => {
- const apiClient: ApiClient = {
- request: vi.fn(async () =>
- createJsonResponse({
- code: 200,
- data: { x_time: ["2026-05-18", "2026-05-19"], proMaxDecodeSpeed: [68, 73] },
- }),
- ),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "coding-plan-api-key",
- }),
- ],
- });
- const preferredProviderId = BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan;
- await expect(
- service.getCodingPlanRegularTps({ preferredProviderId, timeZone: "UTC" }),
- ).resolves.toBe(73);
- // Team scope 已内含在 accountAccess 中;缓存键必须整体覆盖它,否则同一 provider 下
- // 切换团队项目会读到上一个项目的基准 TPS。
- await expect(
- service.getCodingPlanRegularTps({
- preferredProviderId,
- timeZone: "UTC",
- accountAccess: {
- type: "zhipu-account",
- family: "bigmodel",
- planKind: "team-coding-plan",
- productId: "test-product",
- organizationId: "org-1",
- projectId: "project-1",
- },
- }),
- ).resolves.toBe(73);
- expect(apiClient.request).toHaveBeenCalledTimes(2);
- });
- it("Highspeed 普通 TPS 健康检查失败时记录 HTTP 链路诊断", async () => {
- const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
- const apiClient: ApiClient = {
- request: vi.fn(async () =>
- Response.json(
- { code: 5030, msg: "monitor unavailable" },
- {
- status: 503,
- statusText: "Service Unavailable",
- headers: {
- "x-request-id": "req-regular-tps",
- "x-trace-id": "trace-regular-tps",
- },
- },
- ),
- ),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "coding-plan-api-key",
- }),
- ],
- });
- await expect(
- service.getCodingPlanRegularTps({
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- }),
- ).rejects.toThrow("monitor unavailable");
- expect(warn).toHaveBeenCalledWith(
- expect.any(String),
- "Highspeed 普通 TPS 健康检查失败",
- expect.objectContaining({
- providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- status: 503,
- responseHeaders: {
- "x-request-id": "req-regular-tps",
- "x-trace-id": "trace-regular-tps",
- },
- url: expect.stringContaining("/api/monitor/usage/model-performance-day"),
- }),
- );
- });
- it("Highspeed 普通 TPS 健康检查业务失败时保留 request id", async () => {
- const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
- const service = createUsageStatsServiceForTest({
- apiClient: {
- request: vi.fn(async () =>
- Response.json(
- { code: 2007, msg: "monitor dependency failed" },
- { headers: { "x-request-id": "req-regular-tps-business" } },
- ),
- ),
- },
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "coding-plan-api-key",
- }),
- ],
- });
- await expect(
- service.getCodingPlanRegularTps({
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- }),
- ).rejects.toThrow("monitor dependency failed");
- expect(warn).toHaveBeenCalledWith(
- expect.any(String),
- "Highspeed 普通 TPS 健康检查失败",
- expect.objectContaining({
- status: 200,
- responseCode: 2007,
- responseHeaders: { "x-request-id": "req-regular-tps-business" },
- }),
- );
- });
- it("Coding Plan 按当日/7日/30日生成稳定时间轴", () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const today = resolveCodingPlanUsageTimeRange({
- range: "today",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- });
- const sevenDays = resolveCodingPlanUsageTimeRange({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- });
- expect(today.granularity).toBe("hour");
- expect(today.xTime[0]).toBe("00:00:00");
- expect(today.xTime.at(-1)).toBe("23:00:00");
- expect(sevenDays.granularity).toBe("day");
- expect(sevenDays.xTime).toEqual([
- "2026-05-13",
- "2026-05-14",
- "2026-05-15",
- "2026-05-16",
- "2026-05-17",
- "2026-05-18",
- "2026-05-19",
- ]);
- });
- it("Coding Plan 时间范围按调用端 timeZone 生成自然日边界", () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T23:30:00.000Z") });
- const utc = resolveCodingPlanUsageTimeRange({
- range: "today",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- });
- const shanghai = resolveCodingPlanUsageTimeRange({
- range: "today",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "Asia/Shanghai",
- });
- expect(utc.startTime).toBe("2026-05-19 00:00:00");
- expect(utc.endTime).toBe("2026-05-19 23:59:59");
- expect(shanghai.startTime).toBe("2026-05-20 00:00:00");
- expect(shanghai.endTime).toBe("2026-05-20 23:59:59");
- });
- it("Coding Plan 自定义日期范围限制为 30 个自然日并生成日粒度时间轴", () => {
- const custom = resolveCodingPlanUsageTimeRange({
- range: "custom",
- customStartDate: "2026-05-01",
- customEndDate: "2026-05-03",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- });
- expect(custom.startTime).toBe("2026-05-01 00:00:00");
- expect(custom.endTime).toBe("2026-05-03 23:59:59");
- expect(custom.granularity).toBe("day");
- expect(custom.xTime).toEqual(["2026-05-01", "2026-05-02", "2026-05-03"]);
- expect(() =>
- resolveCodingPlanUsageTimeRange({
- range: "custom",
- customStartDate: "2026-05-01",
- customEndDate: "2026-06-01",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- }),
- ).toThrow("coding_plan_usage_custom_range_too_long");
- });
- it("App Usage 经 ZCode Protocol 读取 agent 数据库统计", async () => {
- const getAppUsageStats = vi.fn(async () => createAppUsageSnapshot());
- const apiClient: ApiClient = {
- request: vi.fn(),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [],
- getAppUsageStats,
- });
- const snapshot = await service.getAppUsageSnapshot({
- range: "30d",
- timeZone: "UTC",
- });
- // App Usage 不走 monitor HTTP,只走 agent 协议。
- expect(apiClient.request).not.toHaveBeenCalled();
- expect(getAppUsageStats).toHaveBeenCalledWith({
- range: "30d",
- timeZone: "UTC",
- });
- expect(snapshot.source).toBe("agent-db");
- expect(snapshot.summary.totalSessions).toBe(1);
- expect(snapshot.summary.totalTokens).toBe(104);
- });
- it("App Usage 不会因为存在 Coding Plan key 而切到 monitor 接口", async () => {
- const getAppUsageStats = vi.fn(async () => createAppUsageSnapshot());
- const apiClient: ApiClient = {
- request: vi.fn(),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- }),
- ],
- getAppUsageStats,
- });
- const snapshot = await service.getAppUsageSnapshot({
- range: "7d",
- timeZone: "UTC",
- });
- expect(apiClient.request).not.toHaveBeenCalled();
- expect(getAppUsageStats).toHaveBeenCalledWith({
- range: "7d",
- timeZone: "UTC",
- });
- expect(snapshot.source).toBe("agent-db");
- });
- it("App Usage 全量概览用 all range 透传到 agent 数据库统计", async () => {
- const getAppUsageStats = vi.fn(async () => ({
- ...createAppUsageSnapshot(),
- range: "all",
- }));
- const service = createUsageStatsServiceForTest({
- providers: [],
- getAppUsageStats,
- });
- const snapshot = await service.getAppUsageSnapshot({
- range: "all",
- timeZone: "Asia/Shanghai",
- });
- expect(getAppUsageStats).toHaveBeenCalledWith({
- range: "all",
- timeZone: "Asia/Shanghai",
- });
- expect(snapshot.range).toBe("all");
- });
- it("严格指定个人 Coding Plan 时使用 provider apiKey 的 monitor 数据且不回退本地", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const requestUrls: string[] = [];
- const requestHeaders: Array<HeadersInit | undefined> = [];
- const apiClient: ApiClient = {
- request: vi.fn(async (input, init) => {
- const url = input.toString();
- requestUrls.push(url);
- requestHeaders.push(init?.headers);
- expect(init?.headers).toMatchObject({
- authorization: "legacy-coding-plan-api-key",
- });
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- usage: 100,
- currentValue: 31,
- percentage: 31,
- },
- ],
- },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 200,
- data: {
- summary: {
- totalTokens: 350_720,
- peakDailyTokens: 120,
- peakDailyTokensDate: "2026-05-18",
- totalUsageDurationMs: 60_000,
- currentStreakDays: 1,
- longestStreakDays: 1,
- },
- series: [
- {
- date: "2026-05-18",
- totalTokens: 120,
- modelCallCount: 2,
- mcpCalls: 1,
- },
- ],
- },
- });
- }
- if (url.includes("/api/monitor/credit-usage/usage-detail")) {
- const usageType = new URL(url).searchParams.get("usageType");
- if (usageType === "MODEL") {
- return createJsonResponse({
- code: 200,
- data: {
- summary: {
- cacheHitRate: { value: 0.893, trend: 0.12 },
- totalCredits: { value: 28.95, trend: -0.2 },
- averageDailyCredits: { value: 4.13, trend: 0 },
- },
- modelUsage: {
- xTime: ["2026-05-18"],
- modelDataList: [
- {
- modelName: "glm-5",
- totalTokens: 120,
- totalCredits: 28.95,
- totalCreditsUsage: [28.95],
- totalTokensUsage: [120],
- cachedInputCreditsUsage: [17.68],
- uncachedInputCreditsUsage: [8.63],
- outputCreditsUsage: [2.64],
- cachedInputTokensUsage: [70],
- uncachedInputTokensUsage: [40],
- outputTokensUsage: [10],
- sortOrder: 1,
- },
- ],
- },
- },
- });
- }
- return createJsonResponse({
- code: 200,
- data: {
- summary: {
- cacheHitRate: { value: null },
- totalCredits: { value: 1, trend: 0.5 },
- averageDailyCredits: { value: 0.2, trend: 0.1 },
- },
- mcpUsage: {
- xTime: ["2026-05-18"],
- mcpDataList: [
- {
- mcpCode: "search-prime",
- mcpName: "联网搜索 MCP",
- creditsUsage: [1],
- mcpCallCount: [1],
- totalUsageCount: 1,
- totalCredits: 1,
- sortOrder: 1,
- },
- ],
- },
- },
- });
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 200,
- data: {
- x_time: ["2026-05-18", "2026-05-19"],
- proMaxDecodeSpeed: [125.4, 130.1],
- liteDecodeSpeed: [55.2, 58.8],
- },
- });
- }
- throw new Error(`unexpected request ${url}`);
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "legacy-coding-plan-api-key",
- }),
- createProvider({
- id: TEST_BIGMODEL_PROVIDER_ID,
- name: "BigModel",
- apiKey: "ordinary-api-key",
- }),
- ],
- env: {
- ZCODE_BIGMODEL_USAGE_API_KEY: "env-usage-key",
- },
- });
- const snapshot = await service.getCodingPlanUsageSnapshot({
- range: "30d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- });
- expect(requestUrls).toHaveLength(5);
- expect(requestHeaders).toEqual(
- Array.from({ length: 5 }, () =>
- expect.objectContaining({
- authorization: "legacy-coding-plan-api-key",
- }),
- ),
- );
- for (const headers of requestHeaders) {
- expect(headers).not.toMatchObject({
- "bigmodel-organization": expect.any(String),
- "bigmodel-project": expect.any(String),
- });
- }
- for (const url of requestUrls.filter((item) => item.includes("/api/monitor/usage/"))) {
- if (url.includes("/quota/limit")) {
- continue;
- }
- expect(new URL(url).searchParams.has("granularity")).toBe(false);
- }
- const modelUsageUrl = new URL(
- requestUrls.find((url) => url.includes("/usage-detail") && url.includes("MODEL")) ?? "",
- );
- const activityUrl = new URL(requestUrls.find((url) => url.includes("/activity")) ?? "");
- const quotaUrl = new URL(requestUrls.find((url) => url.includes("/quota/limit")) ?? "");
- const toolUsageUrl = new URL(
- requestUrls.find((url) => url.includes("/usage-detail") && url.includes("MCP")) ?? "",
- );
- const healthUrls = requestUrls
- .filter((url) => url.includes("/model-performance-day"))
- .map((url) => new URL(url));
- expect(quotaUrl.searchParams.has("type")).toBe(false);
- expect(activityUrl.searchParams.get("type")).toBe("1");
- expect(modelUsageUrl.searchParams.get("type")).toBe("1");
- expect(toolUsageUrl.searchParams.get("type")).toBe("1");
- expect(healthUrls).toHaveLength(1);
- expect(healthUrls.every((url) => !url.searchParams.has("type"))).toBe(true);
- expect(modelUsageUrl.searchParams.get("startTime")).toBe("2026-04-20 00:00:00");
- expect(modelUsageUrl.searchParams.get("endTime")).toBe("2026-05-19 23:59:59");
- expect(healthUrls[0]?.searchParams.get("startTime")).toBe("2026-05-13 00:00:00");
- expect(healthUrls[0]?.searchParams.get("endTime")).toBe("2026-05-19 23:59:59");
- expect(snapshot.rangeStartDate).toBe("2026-04-20");
- expect(snapshot.rangeEndDate).toBe("2026-05-19");
- expect(snapshot.sourceProvider).toMatchObject({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- });
- expect(snapshot.modelUsage.totalTokensUsage).toBe(120);
- expect(snapshot.modelUsage.granularity).toBe("day");
- expect(snapshot.modelUsage.xTime).toHaveLength(30);
- expect(snapshot.modelUsage.modelDataList[0]?.modelName).toBe("glm-5");
- expect(snapshot.modelUsage.modelDataList[0]?.tokensUsage).toContain(120);
- expect(snapshot.modelUsage.modelDataList[0]?.cachedInputCreditsUsage).toContain(17.68);
- expect(snapshot.modelUsage.modelDataList[0]?.uncachedInputCreditsUsage).toContain(8.63);
- expect(snapshot.modelUsage.modelDataList[0]?.outputCreditsUsage).toContain(2.64);
- expect(snapshot.activity.summary.totalTokens).toBe(350_720);
- expect(snapshot.detail.model.cacheHitRate).toBe(0.893);
- expect(snapshot.detail.model.cacheHitRateTrend).toBe(0.12);
- expect(snapshot.detail.model.totalCreditsTrend).toBe(-0.2);
- expect(snapshot.detail.tool.totalCredits).toBe(1);
- expect(snapshot.detail.tool.averageDailyCredits).toBe(0.2);
- expect(snapshot.toolUsage.toolDataList[0]?.toolName).toBe("联网搜索 MCP");
- expect(snapshot.toolUsage.toolDataList[0]?.usageCount).toContain(1);
- expect(snapshot.health).toEqual({
- xTime: ["2026-05-18", "2026-05-19"],
- proMaxDecodeSpeed: [125.4, 130.1],
- liteDecodeSpeed: [55.2, 58.8],
- });
- expect(snapshot.quota?.limits).toHaveLength(1);
- });
- it("Coding Plan 积分序列遇到非数字桶时归零,避免 UI 汇总显示 NaN", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: { level: "pro", limits: [] },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 200,
- data: { summary: { totalTokens: 0 }, series: [] },
- });
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 200,
- data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
- });
- }
- const usageType = new URL(url).searchParams.get("usageType");
- return createJsonResponse({
- code: 200,
- data:
- usageType === "MODEL"
- ? {
- summary: { totalCredits: { value: "bad" } },
- modelUsage: {
- xTime: ["2026-05-18", "2026-05-19"],
- modelDataList: [
- {
- modelName: "glm-5",
- totalCreditsUsage: ["bad", "28.95"],
- totalTokensUsage: ["bad", "120"],
- },
- ],
- },
- }
- : {
- mcpUsage: {
- xTime: ["2026-05-18", "2026-05-19"],
- mcpDataList: [
- {
- mcpCode: "search-prime",
- creditsUsage: ["bad", "1"],
- mcpCallCount: ["bad", "2"],
- },
- ],
- },
- },
- });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "coding-plan-api-key",
- }),
- ],
- });
- const snapshot = await service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- });
- const modelCredits = snapshot.modelUsage.modelDataList[0]?.creditsUsage ?? [];
- const modelTokens = snapshot.modelUsage.modelDataList[0]?.tokensUsage ?? [];
- const toolCredits = snapshot.toolUsage.toolDataList[0]?.creditsUsage ?? [];
- const toolCalls = snapshot.toolUsage.toolDataList[0]?.usageCount ?? [];
- expect(modelCredits.every(Number.isFinite)).toBe(true);
- expect(modelTokens.every(Number.isFinite)).toBe(true);
- expect(toolCredits.every(Number.isFinite)).toBe(true);
- expect(toolCalls.every(Number.isFinite)).toBe(true);
- expect(modelCredits.at(-2)).toBe(0);
- expect(modelCredits.at(-1)).toBe(28.95);
- expect(toolCredits.at(-2)).toBe(0);
- expect(toolCredits.at(-1)).toBe(1);
- });
- it("Coding Plan 使用详情不会把缓存输入和输出拆分桶当成模型图例", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: { level: "pro", limits: [] },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 200,
- data: { summary: { totalTokens: 0 }, series: [] },
- });
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 200,
- data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
- });
- }
- const usageType = new URL(url).searchParams.get("usageType");
- return createJsonResponse({
- code: 200,
- data:
- usageType === "MODEL"
- ? {
- summary: { totalCredits: { value: 7 } },
- modelUsage: {
- xTime: ["2026-05-18"],
- modelDataList: [
- {
- modelCode: "cached_input",
- modelName: "缓存",
- totalCreditsUsage: [1],
- totalTokensUsage: [10],
- sortOrder: 1,
- },
- {
- modelCode: "uncached_input",
- modelName: "未缓存",
- totalCreditsUsage: [2],
- totalTokensUsage: [20],
- sortOrder: 2,
- },
- {
- modelCode: "output",
- modelName: "输出",
- totalCreditsUsage: [4],
- totalTokensUsage: [40],
- sortOrder: 3,
- },
- ],
- },
- }
- : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
- });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "coding-plan-api-key",
- }),
- ],
- });
- const snapshot = await service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- });
- expect(snapshot.modelUsage.modelDataList.map((item) => item.modelName)).toEqual([]);
- expect(snapshot.modelUsage.totalTokensUsage).toBe(70);
- });
- it("Coding Plan 总用量在真实模型行与拆分桶同时返回时不会双倍计算", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: { level: "pro", limits: [] },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 200,
- data: { summary: { totalTokens: 0 }, series: [] },
- });
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 200,
- data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
- });
- }
- const usageType = new URL(url).searchParams.get("usageType");
- return createJsonResponse({
- code: 200,
- data:
- usageType === "MODEL"
- ? {
- summary: { totalCredits: { value: 7 } },
- modelUsage: {
- xTime: ["2026-05-18"],
- modelDataList: [
- {
- modelCode: "glm-5",
- modelName: "GLM-5",
- totalTokensUsage: [120],
- sortOrder: 0,
- },
- {
- modelCode: "cached_input",
- modelName: "缓存",
- totalCreditsUsage: [1],
- totalTokensUsage: [10],
- sortOrder: 1,
- },
- {
- modelCode: "uncached_input",
- modelName: "未缓存",
- totalCreditsUsage: [2],
- totalTokensUsage: [20],
- sortOrder: 2,
- },
- {
- modelCode: "output",
- modelName: "输出",
- totalCreditsUsage: [4],
- totalTokensUsage: [40],
- sortOrder: 3,
- },
- ],
- },
- }
- : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
- });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "coding-plan-api-key",
- }),
- ],
- });
- const snapshot = await service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- });
- expect(snapshot.modelUsage.modelDataList.map((item) => item.modelName)).toEqual(["GLM-5"]);
- expect(snapshot.modelUsage.totalTokensUsage).toBe(120);
- });
- it("Team Plan 用量使用 Account Auth 返回的团队项目 API Key", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const requestUrls: string[] = [];
- const requestHeaders: Array<HeadersInit | undefined> = [];
- const apiClient: ApiClient = {
- request: vi.fn(async (input, init) => {
- const url = input.toString();
- requestUrls.push(url);
- requestHeaders.push(init?.headers);
- if (url.endsWith("/api_keys")) {
- return createJsonResponse({
- code: 200,
- data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
- });
- }
- if (url.endsWith("/api_keys/copy/team-ak")) {
- return createJsonResponse({
- code: 200,
- data: { secretKey: "team-secret" },
- });
- }
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- data: {
- level: "team",
- limits: [],
- },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- data: { summary: { totalTokens: 120 }, series: [] },
- });
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
- });
- }
- expect(url).toContain("/api/monitor/credit-usage/usage-detail");
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- success: true,
- data:
- new URL(url).searchParams.get("usageType") === "MODEL"
- ? {
- modelUsage: {
- xTime: ["2026-05-18"],
- modelDataList: [
- {
- modelName: "glm-5",
- totalTokens: 120,
- totalTokensUsage: [120],
- },
- ],
- },
- }
- : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
- });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "",
- }),
- ],
- credentialTokens: {
- "oauth:bigmodel:access_token": "oauth-token",
- },
- });
- const snapshot = await service.getCodingPlanUsageSnapshot({
- range: "30d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- organizationId: "org-team-a",
- projectId: "proj-team-a",
- timeZone: "UTC",
- });
- expect(requestUrls.some((url) => url.includes("/api_keys"))).toBe(false);
- expect(requestHeaders.slice(-3)).toEqual([
- expect.objectContaining({
- authorization: "team-ak.team-secret",
- "bigmodel-organization": "org-team-a",
- "bigmodel-project": "proj-team-a",
- }),
- expect.objectContaining({
- authorization: "team-ak.team-secret",
- "bigmodel-organization": "org-team-a",
- "bigmodel-project": "proj-team-a",
- }),
- expect.objectContaining({
- authorization: "team-ak.team-secret",
- "bigmodel-organization": "org-team-a",
- "bigmodel-project": "proj-team-a",
- }),
- ]);
- const teamQuotaUrl = new URL(
- requestUrls.find((url) => url.includes("/api/monitor/usage/quota/limit")) ?? "",
- );
- const teamCreditUsageUrls = requestUrls
- .filter((url) => url.includes("/api/monitor/credit-usage/"))
- .map((url) => new URL(url));
- expect(teamQuotaUrl.searchParams.get("type")).toBe("2");
- expect(teamCreditUsageUrls).toHaveLength(3);
- expect(teamCreditUsageUrls.every((url) => url.searchParams.get("type") === "3")).toBe(true);
- expect(snapshot.modelUsage.totalTokensUsage).toBe(120);
- expect(snapshot.toolUsage.toolDataList).toEqual([]);
- expect(snapshot.sourceProvider.id).toBe(
- BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- );
- });
- it("Team Plan 用量允许已登录但被禁用的 BigModel Coding Plan provider", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const requestUrls: string[] = [];
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- requestUrls.push(url);
- if (url.endsWith("/api_keys")) {
- return createJsonResponse({
- code: 200,
- data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
- });
- }
- if (url.endsWith("/api_keys/copy/team-ak")) {
- return createJsonResponse({
- code: 200,
- data: { secretKey: "team-secret" },
- });
- }
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: { level: "team", limits: [] },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 200,
- data: { summary: { totalTokens: 0 }, series: [] },
- });
- }
- return createJsonResponse({
- code: 200,
- data:
- new URL(url).searchParams.get("usageType") === "MODEL"
- ? { modelUsage: { xTime: ["2026-05-18"], modelDataList: [] } }
- : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
- });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "",
- enabled: false,
- }),
- ],
- credentialTokens: {
- "oauth:bigmodel:access_token": "oauth-token",
- },
- });
- await service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- organizationId: "org-team-a",
- projectId: "proj-team-a",
- timeZone: "UTC",
- });
- expect(requestUrls[0]).toBe("https://bigmodel.cn/api/monitor/usage/quota/limit?type=2");
- });
- it("Z.ai Team Plan 用量使用 Account Auth 返回的团队项目 API Key(对齐 BigModel)", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const requestUrls: string[] = [];
- const requestHeaders: Array<HeadersInit | undefined> = [];
- const apiClient: ApiClient = {
- request: vi.fn(async (input, init) => {
- const url = input.toString();
- requestUrls.push(url);
- requestHeaders.push(init?.headers);
- if (url.endsWith("/api_keys")) {
- return createJsonResponse({
- code: 200,
- data: [{ apiKey: "team-ak-zai", keyType: 2, name: "zcode-team-api-key" }],
- });
- }
- if (url.endsWith("/api_keys/copy/team-ak-zai")) {
- return createJsonResponse({
- code: 200,
- data: { secretKey: "team-secret-zai" },
- });
- }
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- data: { level: "team", limits: [] },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- data: { summary: { totalTokens: 88 }, series: [] },
- });
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
- });
- }
- expect(url).toContain("/api/monitor/credit-usage/usage-detail");
- return createJsonResponse({
- code: 0,
- msg: "操作成功",
- success: true,
- data:
- new URL(url).searchParams.get("usageType") === "MODEL"
- ? {
- modelUsage: {
- xTime: ["2026-05-18"],
- modelDataList: [
- {
- modelName: "glm-5",
- totalTokens: 88,
- totalTokensUsage: [88],
- },
- ],
- },
- }
- : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
- });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai - Coding Plan",
- apiKey: "",
- }),
- ],
- credentialTokens: {
- "oauth:zai:access_token": "zai-oauth-token",
- },
- });
- const snapshot = await service.getCodingPlanUsageSnapshot({
- range: "30d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- organizationId: "org-zai-team",
- projectId: "proj-zai-team",
- timeZone: "UTC",
- });
- expect(requestUrls.some((url) => url.includes("/api_keys"))).toBe(false);
- // monitor 接口用复制的团队项目 API Key + org/project header(与 bigmodel 同构)
- expect(requestHeaders.slice(-3)).toEqual([
- expect.objectContaining({
- authorization: "zai-team-ak.zai-team-secret",
- "bigmodel-organization": "org-zai-team",
- "bigmodel-project": "proj-zai-team",
- }),
- expect.objectContaining({
- authorization: "zai-team-ak.zai-team-secret",
- "bigmodel-organization": "org-zai-team",
- "bigmodel-project": "proj-zai-team",
- }),
- expect.objectContaining({
- authorization: "zai-team-ak.zai-team-secret",
- "bigmodel-organization": "org-zai-team",
- "bigmodel-project": "proj-zai-team",
- }),
- ]);
- expect(snapshot.modelUsage.totalTokensUsage).toBe(88);
- expect(snapshot.sourceProvider.id).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
- });
- it("Z.ai Team Plan 用量允许已登录但被禁用的 Coding Plan provider(对齐 BigModel)", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const requestUrls: string[] = [];
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- requestUrls.push(url);
- if (url.endsWith("/api_keys")) {
- return createJsonResponse({
- code: 200,
- data: [{ apiKey: "team-ak-zai", keyType: 2, name: "zcode-team-api-key" }],
- });
- }
- if (url.endsWith("/api_keys/copy/team-ak-zai")) {
- return createJsonResponse({
- code: 200,
- data: { secretKey: "team-secret-zai" },
- });
- }
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: { level: "team", limits: [] },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 200,
- data: { summary: { totalTokens: 0 }, series: [] },
- });
- }
- return createJsonResponse({
- code: 200,
- data:
- new URL(url).searchParams.get("usageType") === "MODEL"
- ? { modelUsage: { xTime: ["2026-05-18"], modelDataList: [] } }
- : { mcpUsage: { xTime: ["2026-05-18"], mcpDataList: [] } },
- });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai - Coding Plan",
- apiKey: "",
- enabled: false,
- }),
- ],
- credentialTokens: {
- "oauth:zai:access_token": "zai-oauth-token",
- },
- });
- await service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- organizationId: "org-zai-team",
- projectId: "proj-zai-team",
- timeZone: "UTC",
- });
- expect(requestUrls[0]).toBe("https://api.z.ai/api/monitor/usage/quota/limit?type=2");
- });
- it("Team Plan monitor 缺少明确成功信号时不能把错误响应降级为空统计", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- if (url.endsWith("/api_keys")) {
- return createJsonResponse({
- code: 200,
- data: [{ apiKey: "team-ak", keyType: 2, name: "zcode-team-api-key" }],
- });
- }
- if (url.endsWith("/api_keys/copy/team-ak")) {
- return createJsonResponse({
- code: 200,
- data: { secretKey: "team-secret" },
- });
- }
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: { level: "team", limits: [] },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- return createJsonResponse({
- code: 200,
- data: { summary: { totalTokens: 0 }, series: [] },
- });
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 200,
- data: { x_time: [], proMaxDecodeSpeed: [], liteDecodeSpeed: [] },
- });
- }
- expect(url).toContain("/api/monitor/credit-usage/usage-detail");
- return createJsonResponse({ msg: "token expired" });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "",
- }),
- ],
- credentialTokens: {
- "oauth:bigmodel:access_token": "oauth-token",
- },
- });
- await expect(
- service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- organizationId: "org-team-a",
- projectId: "proj-team-a",
- timeZone: "UTC",
- }),
- ).rejects.toThrow("token expired");
- });
- // CR-01 回归:activity / usage-detail / model-performance-day 是可选数据面。
- // 任一接口传输层失败(HTTP 非 2xx、超时、断网)时只清空对应区域,
- // 不能让 Promise.all 提前 reject 拖垮整张 Coding Plan Usage 面板。
- it("可选 monitor 接口网络失败时只清空对应区域,quota 与其它区域正常返回", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- if (url.includes("/api/monitor/usage/quota/limit")) {
- return createJsonResponse({
- code: 200,
- data: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- usage: 100,
- currentValue: 31,
- percentage: 31,
- },
- ],
- },
- });
- }
- if (url.includes("/api/monitor/credit-usage/activity")) {
- // 传输层失败一:HTTP 非 2xx,readApiJson 会抛 ApiError。
- return new Response("Internal Server Error", { status: 500 });
- }
- if (url.includes("/api/monitor/credit-usage/usage-detail")) {
- if (new URL(url).searchParams.get("usageType") === "MODEL") {
- return createJsonResponse({
- code: 200,
- data: {
- summary: {
- cacheHitRate: { value: 0.893, trend: null },
- totalCredits: { value: 28.95, trend: null },
- averageDailyCredits: { value: 4.13, trend: null },
- },
- modelUsage: { xTime: ["2026-05-18"], modelDataList: [] },
- },
- });
- }
- // 传输层失败二:请求超时,request 直接 reject。
- throw new Error("Request timed out after 15000ms");
- }
- if (url.includes("/api/monitor/usage/model-performance-day")) {
- return createJsonResponse({
- code: 200,
- data: {
- x_time: ["2026-05-18"],
- proMaxDecodeSpeed: [125.4],
- liteDecodeSpeed: [55.2],
- },
- });
- }
- throw new Error(`unexpected request ${url}`);
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- }),
- ],
- });
- const snapshot = await service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- });
- // 未失败的区域不受影响:quota 剩余、模型维度详情和 health 都正常。
- expect(snapshot.quota?.limits).toHaveLength(1);
- expect(snapshot.detail.model.totalCredits).toBe(28.95);
- expect(snapshot.health?.xTime).toEqual(["2026-05-18"]);
- // 传输失败的区域清空为空统计,而不是拖垮整张面板。
- expect(snapshot.activity.summary.totalTokens).toBe(0);
- expect(snapshot.detail.tool.totalCredits).toBe(0);
- });
- it("quota monitor 网络失败时 Coding Plan 用量整体失败", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- if (url.includes("/api/monitor/usage/quota/limit")) {
- throw new Error("Request timed out after 15000ms");
- }
- return createJsonResponse({ code: 200, data: {} });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- }),
- ],
- });
- // quota 是面板核心数据,传输失败必须保留整体报错语义,
- // 避免“查不到额度”被伪装成一张全空面板。
- await expect(
- service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- }),
- ).rejects.toThrow("Request timed out after 15000ms");
- });
- it("严格指定 Coding Plan 缺 apiKey 时不回退普通 provider 或本地 session", async () => {
- const apiClient: ApiClient = {
- request: vi.fn(),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "",
- }),
- createProvider({
- id: TEST_BIGMODEL_PROVIDER_ID,
- name: "BigModel",
- apiKey: "ordinary-api-key",
- }),
- ],
- });
- await expect(
- service.getCodingPlanUsageSnapshot({
- range: "today",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- }),
- ).rejects.toThrow("bigmodel_coding_plan_api_key_required");
- expect(apiClient.request).not.toHaveBeenCalled();
- });
- it("个人套餐缺少 Account Auth 凭据时不再触发旧 Provider 刷新", async () => {
- const providers = [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "",
- enabled: false,
- }),
- ];
- const requestHeaders: Record<string, string>[] = [];
- const apiClient: ApiClient = {
- request: vi.fn(async (_input, init) => {
- requestHeaders.push((init?.headers ?? {}) as Record<string, string>);
- return createJsonResponse({ code: 200, data: {} });
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers,
- });
- await expect(
- service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- timeZone: "UTC",
- }),
- ).rejects.toThrow("bigmodel_coding_plan_api_key_required");
- expect(requestHeaders).toEqual([]);
- });
- it("Team Plan Account Auth 失败时透传真实错误", async () => {
- vi.useFakeTimers({ now: new Date("2026-05-19T10:00:00.000Z") });
- const apiClient: ApiClient = {
- request: vi.fn(async (input) => {
- const url = input.toString();
- if (url.endsWith("/api_keys")) {
- // 修复原因:list 无可用 key 时走 create;create 被远端拒绝并返回业务 msg,
- // 原实现只抛错误码 bigmodel_coding_plan_api_key_required,UI 无法展示真实原因。
- return createJsonResponse({
- code: 500,
- success: false,
- msg: "您当前暂无有效的团队套餐授权记录,无法创建API Key",
- });
- }
- throw new Error(`unexpected request ${url}`);
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [
- createProvider({
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel - Coding Plan",
- apiKey: "",
- }),
- ],
- resolveAccountAuth: async () => {
- throw new Error("您当前暂无有效的团队套餐授权记录,无法创建API Key");
- },
- });
- await expect(
- service.getCodingPlanUsageSnapshot({
- range: "7d",
- preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- organizationId: "org-team-a",
- projectId: "proj-team-a",
- timeZone: "UTC",
- }),
- ).rejects.toThrow("您当前暂无有效的团队套餐授权记录,无法创建API Key");
- });
- it("显式选择供应商时缺 key 不回落到本地数据", async () => {
- const service = createUsageStatsServiceForTest({
- providers: [],
- });
- await expect(
- service.getSnapshot({
- range: "all",
- preferredProviderId: TEST_BIGMODEL_PROVIDER_ID,
- timeZone: "UTC",
- }),
- ).rejects.toThrow("no_bigmodel_api_key");
- });
- it("已配置供应商但 monitor 接口失败时保留真实错误", async () => {
- const apiClient: ApiClient = {
- request: vi.fn(async () => {
- throw new Error("Request timed out after 15000ms");
- }),
- };
- const service = createUsageStatsServiceForTest({
- apiClient,
- providers: [createProvider({})],
- });
- await expect(
- service.getSnapshot({
- range: "all",
- timeZone: "UTC",
- }),
- ).rejects.toThrow("Request timed out after 15000ms");
- });
- });
|