zcodeMcpQuota.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. BUILTIN_MODEL_PROVIDER_IDS,
  4. MCP_USAGE_QUOTA_LIMIT_TYPE,
  5. type ApiClient,
  6. } from "@zcode/shared";
  7. import { BigModelUsageQuotaProvider } from "../src/usage-stats/providers/bigmodelUsageQuotaProvider.js";
  8. import {
  9. buildMcpQuotaAggregateLimit,
  10. fetchMcpQuotaSnapshot,
  11. matchesMcpQuotaScope,
  12. type OfficialMcpCredentialSource,
  13. } from "../src/usage-stats/providers/zcodeMcpQuotaProvider.js";
  14. const MCP_USAGE_PATH = "/api/v1/mcp/usage";
  15. const QUOTA_LIMIT_PATH = "/api/monitor/usage/quota/limit";
  16. function createJsonResponse(body: unknown, headers: Record<string, string> = {}): Response {
  17. return new Response(JSON.stringify(body), {
  18. status: 200,
  19. headers: { "Content-Type": "application/json", ...headers },
  20. });
  21. }
  22. function createPersonalBigModelCredentialSource(): OfficialMcpCredentialSource {
  23. return {
  24. resolve: vi.fn(async () => ({
  25. ok: true as const,
  26. snapshot: {
  27. codingPlanAuthorization: "bigmodel-maas-jwt",
  28. jwt: "zcode-jwt",
  29. planScope: { targetType: "PERSONAL" as const },
  30. providerFamily: "bigmodel" as const,
  31. wireScope: { targetType: "PERSONAL" as const },
  32. },
  33. })),
  34. };
  35. }
  36. function createSuccessfulQuotaResponse(): unknown {
  37. return {
  38. code: 200,
  39. data: {
  40. level: "pro",
  41. limits: [
  42. {
  43. type: "TOKENS_LIMIT",
  44. unit: 3,
  45. number: 5,
  46. percentage: 10,
  47. remaining: 90,
  48. nextResetTime: Date.UTC(2026, 7, 19, 8),
  49. },
  50. ],
  51. },
  52. };
  53. }
  54. function createMcpUsageResponse(): unknown {
  55. return {
  56. code: 0,
  57. msg: "",
  58. data: {
  59. server_time: 1_755_571_234,
  60. next_refresh_at: 1_755_609_600,
  61. level: "pro",
  62. total_usage: { used: 71, limit: 2000, remaining: 1929 },
  63. },
  64. };
  65. }
  66. /** 服务端 2026-08 之前的形状。留着它是为了锁住"接口再换形状时必须可查"这条。 */
  67. function createLegacyBucketUsageResponse(): unknown {
  68. return {
  69. code: 0,
  70. msg: "",
  71. data: {
  72. server_time: 1_755_571_234,
  73. next_refresh_at: 1_755_609_600,
  74. level: "pro",
  75. buckets: [
  76. { bucket: "search_image", used: 5, limit: 230, remaining: 225 },
  77. { bucket: "video_edit", used: 0, limit: 200, remaining: 200 },
  78. { bucket: "finance", used: 33, limit: 800, remaining: 767 },
  79. ],
  80. },
  81. };
  82. }
  83. function createProvider(options: {
  84. apiClient: ApiClient;
  85. credentialSource?: OfficialMcpCredentialSource;
  86. }): BigModelUsageQuotaProvider {
  87. const provider = new BigModelUsageQuotaProvider({
  88. apiClient: options.apiClient,
  89. accountRequestAuthService: {
  90. resolveAccessCurrent: vi.fn(async () => null),
  91. resolveCurrent: vi.fn(async () => ({ apiKey: "bigmodel-api-key" })),
  92. assertCurrent: vi.fn(async () => undefined),
  93. },
  94. ...(options.credentialSource ? { officialMcpCredentialSource: options.credentialSource } : {}),
  95. });
  96. const getSnapshotForRequest = provider.getSnapshotForRequest.bind(provider);
  97. provider.getSnapshotForRequest = (request = {}) =>
  98. getSnapshotForRequest({
  99. ...request,
  100. accountAccess: request.accountAccess ?? {
  101. type: "zhipu-account",
  102. family: "bigmodel",
  103. planKind: "individual-coding-plan",
  104. },
  105. });
  106. return provider;
  107. }
  108. describe("官方 Server MCP 额度汇总", () => {
  109. it("total_usage 直接映射成额度条,percentage 保持已使用占比口径", () => {
  110. const aggregate = buildMcpQuotaAggregateLimit({
  111. totalUsage: { used: 198, limit: 1230, remaining: 1032 },
  112. nextResetTime: 1_755_609_600_000,
  113. });
  114. // 剩余 1032 / 额度 1230 ≈ 83.9% 剩余 → 已使用 16.1%
  115. expect(aggregate).toMatchObject({
  116. type: MCP_USAGE_QUOTA_LIMIT_TYPE,
  117. remaining: 1032,
  118. usage: 198,
  119. currentValue: 198,
  120. nextResetTime: 1_755_609_600_000,
  121. usageDetails: [],
  122. });
  123. expect(aggregate?.percentage).toBeCloseTo(100 - (1032 / 1230) * 100, 6);
  124. });
  125. it("总额度为 0 时不产出额度条", () => {
  126. expect(
  127. buildMcpQuotaAggregateLimit({ totalUsage: { used: 0, limit: 0, remaining: 0 } }),
  128. ).toBeNull();
  129. expect(
  130. buildMcpQuotaAggregateLimit({ totalUsage: { used: 5, limit: -1, remaining: 0 } }),
  131. ).toBeNull();
  132. });
  133. it("异常的 remaining 被夹在 [0, limit] 内,不产生负的已使用占比", () => {
  134. const aggregate = buildMcpQuotaAggregateLimit({
  135. totalUsage: { used: 0, limit: 100, remaining: 150 },
  136. });
  137. expect(aggregate?.remaining).toBe(100);
  138. expect(aggregate?.percentage).toBe(0);
  139. });
  140. it("归属校验要求 family 与个人 / 团队 scope 完全一致", () => {
  141. const teamScope = {
  142. providerFamily: "bigmodel" as const,
  143. targetType: "TEAM" as const,
  144. organizationId: "org-1",
  145. projectId: "proj-1",
  146. };
  147. expect(
  148. matchesMcpQuotaScope(teamScope, {
  149. providerFamily: "bigmodel",
  150. organizationId: "org-1",
  151. projectId: "proj-1",
  152. }),
  153. ).toBe(true);
  154. // 同 family 但个人 / 团队不一致
  155. expect(matchesMcpQuotaScope(teamScope, { providerFamily: "bigmodel" })).toBe(false);
  156. // 团队不同项目
  157. expect(
  158. matchesMcpQuotaScope(teamScope, {
  159. providerFamily: "bigmodel",
  160. organizationId: "org-1",
  161. projectId: "proj-2",
  162. }),
  163. ).toBe(false);
  164. // 跨 family
  165. expect(
  166. matchesMcpQuotaScope(
  167. { providerFamily: "zai", targetType: "PERSONAL" },
  168. { providerFamily: "bigmodel" },
  169. ),
  170. ).toBe(false);
  171. });
  172. it("ZAI Team 使用产品 Team scope 匹配额度,不依赖 wire Target-Type", async () => {
  173. const requests: Array<{ url: string; headers: unknown }> = [];
  174. const result = await fetchMcpQuotaSnapshot({
  175. apiClient: {
  176. request: vi.fn(async (input, init) => {
  177. requests.push({ url: input.toString(), headers: init?.headers });
  178. return createJsonResponse(createMcpUsageResponse());
  179. }),
  180. },
  181. credentialSource: {
  182. resolve: vi.fn(async () => ({
  183. ok: true as const,
  184. snapshot: {
  185. codingPlanAuthorization: "zai-maas-jwt",
  186. jwt: "zcode-jwt",
  187. planScope: {
  188. organizationId: "org-z",
  189. projectId: "project-z",
  190. targetType: "TEAM" as const,
  191. },
  192. providerFamily: "zai" as const,
  193. // 与 Off-Peak 保持一致:wire 不发送 Team identity。
  194. wireScope: null,
  195. },
  196. })),
  197. },
  198. env: {} as NodeJS.ProcessEnv,
  199. requestScope: {
  200. organizationId: "org-z",
  201. projectId: "project-z",
  202. providerFamily: "zai",
  203. },
  204. });
  205. expect(requests).toHaveLength(1);
  206. expect(requests[0]?.headers).toEqual({
  207. Authorization: "Bearer zcode-jwt",
  208. "X-Bigmodel-Authorization": "Bearer zai-maas-jwt",
  209. });
  210. expect(result?.scope).toEqual({
  211. organizationId: "org-z",
  212. projectId: "project-z",
  213. providerFamily: "zai",
  214. targetType: "TEAM",
  215. });
  216. });
  217. });
  218. describe("entitlement 快照携带官方 Server MCP 额度", () => {
  219. it("成功时用 server MCP 的 5 个身份头请求,并把 total_usage 写进 mcpQuota", async () => {
  220. const mcpRequests: Array<{ url: string; headers: unknown }> = [];
  221. const apiClient: ApiClient = {
  222. request: vi.fn(async (input, init) => {
  223. const url = input.toString();
  224. if (url.includes(MCP_USAGE_PATH)) {
  225. mcpRequests.push({ url, headers: init?.headers });
  226. return createJsonResponse(createMcpUsageResponse());
  227. }
  228. if (url.includes(QUOTA_LIMIT_PATH)) {
  229. return createJsonResponse(createSuccessfulQuotaResponse());
  230. }
  231. return createJsonResponse({
  232. code: 200,
  233. data: [
  234. {
  235. productId: "coding-pro",
  236. productName: "GLM Coding Pro",
  237. status: "VALID",
  238. inCurrentPeriod: true,
  239. },
  240. ],
  241. });
  242. }),
  243. };
  244. const provider = createProvider({
  245. apiClient,
  246. credentialSource: createPersonalBigModelCredentialSource(),
  247. });
  248. const snapshot = await provider.getSnapshotForRequest({
  249. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  250. });
  251. expect(mcpRequests).toHaveLength(1);
  252. // 身份头必须与 server MCP 调用完全一致:不改名、不补头、不换通道。
  253. expect(mcpRequests[0]?.headers).toEqual({
  254. Authorization: "Bearer zcode-jwt",
  255. "X-Bigmodel-Authorization": "Bearer bigmodel-maas-jwt",
  256. "Bigmodel-Target-Type": "PERSONAL",
  257. });
  258. expect(snapshot.mcpQuota).toMatchObject({
  259. level: "pro",
  260. scope: { providerFamily: "bigmodel", targetType: "PERSONAL" },
  261. // 接口是 Unix 秒,快照统一毫秒
  262. serverTime: 1_755_571_234_000,
  263. });
  264. expect(snapshot.mcpQuota?.aggregate).toMatchObject({
  265. nextResetTime: 1_755_609_600_000,
  266. remaining: 1929,
  267. usage: 71,
  268. });
  269. // 现有额度不受影响
  270. expect(snapshot.quota?.limits).toHaveLength(1);
  271. });
  272. it("只返回老的 buckets 形状时降级为 mcpQuota 为空,不抛错", async () => {
  273. // 这就是 2026-08 那次故障:服务端把 buckets 换成 total_usage,客户端 schema 校验失败,
  274. // 而 mcpQuota 是可选数据面(失败即静默降级),表现为额度条无声消失、其余额度照常。
  275. // 这条用例锁住"接口再换形状时只丢一行、不崩、且有日志可查"这个行为。
  276. const apiClient: ApiClient = {
  277. request: vi.fn(async (input) => {
  278. const url = input.toString();
  279. if (url.includes(MCP_USAGE_PATH)) {
  280. return createJsonResponse(createLegacyBucketUsageResponse(), {
  281. "x-request-id": "req-legacy",
  282. });
  283. }
  284. if (url.includes(QUOTA_LIMIT_PATH)) {
  285. return createJsonResponse(createSuccessfulQuotaResponse());
  286. }
  287. return createJsonResponse({
  288. code: 200,
  289. data: [
  290. {
  291. productId: "coding-pro",
  292. productName: "GLM Coding Pro",
  293. status: "VALID",
  294. inCurrentPeriod: true,
  295. },
  296. ],
  297. });
  298. }),
  299. };
  300. const provider = createProvider({
  301. apiClient,
  302. credentialSource: createPersonalBigModelCredentialSource(),
  303. });
  304. const snapshot = await provider.getSnapshotForRequest({
  305. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  306. });
  307. expect(snapshot.mcpQuota).toBeNull();
  308. // 其余 entitlement 一切照常——可选数据面绝不影响主快照
  309. expect(snapshot.quota?.level).toBe("pro");
  310. expect(snapshot.unavailableReason).toBeUndefined();
  311. });
  312. it("业务失败(code=1000 无 data)只清空 MCP 额度,其余 entitlement 字段照常", async () => {
  313. const apiClient: ApiClient = {
  314. request: vi.fn(async (input) => {
  315. const url = input.toString();
  316. if (url.includes(MCP_USAGE_PATH)) {
  317. return createJsonResponse(
  318. { code: 1000, msg: "something went wrong" },
  319. { "x-request-id": "req-1" },
  320. );
  321. }
  322. if (url.includes(QUOTA_LIMIT_PATH)) {
  323. return createJsonResponse(createSuccessfulQuotaResponse());
  324. }
  325. return createJsonResponse({
  326. code: 200,
  327. data: [
  328. {
  329. productId: "coding-pro",
  330. productName: "GLM Coding Pro",
  331. status: "VALID",
  332. inCurrentPeriod: true,
  333. },
  334. ],
  335. });
  336. }),
  337. };
  338. const provider = createProvider({
  339. apiClient,
  340. credentialSource: createPersonalBigModelCredentialSource(),
  341. });
  342. const snapshot = await provider.getSnapshotForRequest({
  343. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  344. });
  345. expect(snapshot.mcpQuota).toBeNull();
  346. expect(snapshot.quota?.level).toBe("pro");
  347. expect(snapshot.unavailableReason).toBeUndefined();
  348. });
  349. it("HTTP 失败与请求异常都降级为 mcpQuota 为空,不影响 entitlement", async () => {
  350. const apiClient: ApiClient = {
  351. request: vi.fn(async (input) => {
  352. const url = input.toString();
  353. if (url.includes(MCP_USAGE_PATH)) {
  354. return new Response("nope", { status: 500 });
  355. }
  356. if (url.includes(QUOTA_LIMIT_PATH)) {
  357. return createJsonResponse(createSuccessfulQuotaResponse());
  358. }
  359. return createJsonResponse({
  360. code: 200,
  361. data: [
  362. {
  363. productId: "coding-pro",
  364. productName: "GLM Coding Pro",
  365. status: "VALID",
  366. inCurrentPeriod: true,
  367. },
  368. ],
  369. });
  370. }),
  371. };
  372. const provider = createProvider({
  373. apiClient,
  374. credentialSource: createPersonalBigModelCredentialSource(),
  375. });
  376. const snapshot = await provider.getSnapshotForRequest({
  377. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  378. });
  379. expect(snapshot.mcpQuota).toBeNull();
  380. expect(snapshot.quota?.level).toBe("pro");
  381. });
  382. it("凭证解析判定无 Coding Plan 时零请求", async () => {
  383. const requestUrls: string[] = [];
  384. const apiClient: ApiClient = {
  385. request: vi.fn(async (input) => {
  386. const url = input.toString();
  387. requestUrls.push(url);
  388. if (url.includes(QUOTA_LIMIT_PATH)) {
  389. return createJsonResponse(createSuccessfulQuotaResponse());
  390. }
  391. return createJsonResponse({
  392. code: 200,
  393. data: [
  394. {
  395. productId: "coding-pro",
  396. productName: "GLM Coding Pro",
  397. status: "VALID",
  398. inCurrentPeriod: true,
  399. },
  400. ],
  401. });
  402. }),
  403. };
  404. const provider = createProvider({
  405. apiClient,
  406. credentialSource: {
  407. resolve: vi.fn(async () => ({
  408. ok: false as const,
  409. reason: "official_auth_plan_required" as const,
  410. })),
  411. },
  412. });
  413. const snapshot = await provider.getSnapshotForRequest({
  414. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  415. });
  416. expect(snapshot.mcpQuota).toBeNull();
  417. expect(requestUrls.some((url) => url.includes(MCP_USAGE_PATH))).toBe(false);
  418. });
  419. it("凭证归属与本次查询的连接不一致时零请求", async () => {
  420. const requestUrls: string[] = [];
  421. const apiClient: ApiClient = {
  422. request: vi.fn(async (input) => {
  423. const url = input.toString();
  424. requestUrls.push(url);
  425. if (url.includes(QUOTA_LIMIT_PATH)) {
  426. return createJsonResponse(createSuccessfulQuotaResponse());
  427. }
  428. return createJsonResponse({
  429. code: 200,
  430. data: [
  431. {
  432. productId: "coding-pro",
  433. productName: "GLM Coding Pro",
  434. status: "VALID",
  435. inCurrentPeriod: true,
  436. },
  437. ],
  438. });
  439. }),
  440. };
  441. const provider = createProvider({
  442. apiClient,
  443. credentialSource: {
  444. // 当前选中的是 Z.ai 连接,本次查询的是 BigModel 个人 Coding Plan。
  445. resolve: vi.fn(async () => ({
  446. ok: true as const,
  447. snapshot: {
  448. codingPlanAuthorization: "zai-maas-jwt",
  449. jwt: "zcode-jwt",
  450. planScope: { targetType: "PERSONAL" as const },
  451. providerFamily: "zai" as const,
  452. wireScope: { targetType: "PERSONAL" as const },
  453. },
  454. })),
  455. },
  456. });
  457. const snapshot = await provider.getSnapshotForRequest({
  458. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  459. });
  460. expect(snapshot.mcpQuota).toBeNull();
  461. expect(requestUrls.some((url) => url.includes(MCP_USAGE_PATH))).toBe(false);
  462. });
  463. it("未注入凭证来源时完全不查询 MCP 额度", async () => {
  464. const requestUrls: string[] = [];
  465. const apiClient: ApiClient = {
  466. request: vi.fn(async (input) => {
  467. const url = input.toString();
  468. requestUrls.push(url);
  469. if (url.includes(QUOTA_LIMIT_PATH)) {
  470. return createJsonResponse(createSuccessfulQuotaResponse());
  471. }
  472. return createJsonResponse({
  473. code: 200,
  474. data: [
  475. {
  476. productId: "coding-pro",
  477. productName: "GLM Coding Pro",
  478. status: "VALID",
  479. inCurrentPeriod: true,
  480. },
  481. ],
  482. });
  483. }),
  484. };
  485. const provider = createProvider({ apiClient });
  486. const snapshot = await provider.getSnapshotForRequest({
  487. preferredProviderId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  488. });
  489. expect(snapshot.mcpQuota).toBeNull();
  490. expect(requestUrls.some((url) => url.includes(MCP_USAGE_PATH))).toBe(false);
  491. });
  492. });