highspeedCardService.test.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { HighspeedDrawRequest, HighspeedDrawResponse } from "@zcode/shared";
  3. import {
  4. buildHighspeedCodingPlanAuthHeaders,
  5. createHighspeedHttpTransport,
  6. HighspeedCardService,
  7. type HighspeedInferenceAuth,
  8. type HighspeedServiceTransport,
  9. } from "../src/highspeed/highspeedCardService.js";
  10. import { createHighspeedMockTransport } from "../src/highspeed/highspeedMockTransport.js";
  11. import { HIGHSPEED_REQUEST_TIMEOUT_MS } from "../src/highspeed/highspeedHttpTransport.js";
  12. function deferred<T>() {
  13. let resolve!: (value: T) => void;
  14. let reject!: (reason: unknown) => void;
  15. const promise = new Promise<T>((next, fail) => {
  16. resolve = next;
  17. reject = fail;
  18. });
  19. return { promise, resolve, reject };
  20. }
  21. /**
  22. * 排空微任务直到条件成立,避免测试绑定内部 await 数量;设上界防止实现回归时死循环空转
  23. * (纯微任务循环会饿死计时器,vitest 的用例超时也无法打断)。
  24. */
  25. async function drainUntil(condition: () => boolean, label: string): Promise<void> {
  26. for (let turn = 0; turn < 1_000; turn += 1) {
  27. if (condition()) return;
  28. await Promise.resolve();
  29. }
  30. throw new Error(`condition not reached: ${label}`);
  31. }
  32. const cardResponse = (taskId: string, now: number): HighspeedDrawResponse => ({
  33. code: 0,
  34. msg: "success",
  35. data: {
  36. card: {
  37. card_id: "hsc-1",
  38. task_id: taskId,
  39. provider: "zai",
  40. model: "glm-5",
  41. issued_at: now,
  42. expires_at: now + 15 * 60_000,
  43. },
  44. next_draw_at: now + 60 * 60_000,
  45. },
  46. });
  47. function createTransport(draw: (request: HighspeedDrawRequest) => Promise<HighspeedDrawResponse>) {
  48. const calls: HighspeedDrawRequest[] = [];
  49. const transport: HighspeedServiceTransport = {
  50. draw: async (request) => {
  51. calls.push(request);
  52. return draw(request);
  53. },
  54. healthy: async (cardId) => ({
  55. cardId,
  56. promptTokens: 0,
  57. completionTokens: 90,
  58. durationSeconds: 1,
  59. }),
  60. };
  61. return { calls, transport };
  62. }
  63. describe("HighspeedCardService", () => {
  64. it("skips draw for an automation turn without disabling the next manual turn", async () => {
  65. const now = 9_000;
  66. const { calls, transport } = createTransport(async (request) =>
  67. cardResponse(request.task_id, now),
  68. );
  69. const service = new HighspeedCardService({ transport, now: () => now });
  70. const automationResult = await service.prepareTurn({
  71. taskId: "task-1",
  72. providerId: "account:zai-team-coding-plan",
  73. model: "glm-5",
  74. automationId: "automation-1",
  75. });
  76. expect(automationResult).toMatchObject({ kind: "fallback", reason: "automation" });
  77. expect(calls).toHaveLength(0);
  78. const manualResult = await service.prepareTurn({
  79. taskId: "task-1",
  80. providerId: "account:zai-team-coding-plan",
  81. model: "glm-5",
  82. });
  83. expect(manualResult.kind).toBe("accelerated");
  84. expect(calls).toHaveLength(1);
  85. });
  86. it("only invalidates the matching current card and preserves the draw cooldown", async () => {
  87. const now = 9_500;
  88. const { calls, transport } = createTransport(async (request) =>
  89. cardResponse(request.task_id, now),
  90. );
  91. const service = new HighspeedCardService({ transport, now: () => now });
  92. await service.prepareTurn({
  93. taskId: "task-1",
  94. providerId: "account:zai-individual-coding-plan",
  95. model: "glm-5",
  96. });
  97. const before = await service.getSnapshot();
  98. await expect(service.invalidateCard("older-card")).resolves.toBe(false);
  99. expect((await service.getSnapshot()).card?.cardId).toBe("hsc-1");
  100. await expect(service.invalidateCard("hsc-1")).resolves.toBe(true);
  101. expect(await service.getSnapshot()).toEqual({
  102. card: null,
  103. nextDrawAt: before.nextDrawAt,
  104. drawing: false,
  105. });
  106. const next = await service.prepareTurn({
  107. taskId: "task-1",
  108. providerId: "account:zai-individual-coding-plan",
  109. model: "glm-5",
  110. });
  111. expect(next).toMatchObject({ kind: "fallback", reason: "cooldown" });
  112. expect(calls).toHaveLength(1);
  113. });
  114. it("sends the allowlisted builtin coding-plan id in the draw body instead of the provider id", async () => {
  115. const now = 10_000;
  116. const { calls, transport } = createTransport(async (request) =>
  117. cardResponse(request.task_id, now),
  118. );
  119. const service = new HighspeedCardService({ transport, now: () => now });
  120. const result = await service.prepareTurn({
  121. taskId: "task-1",
  122. providerId: "account:bigmodel-team-coding-plan",
  123. model: "GLM-5.3",
  124. });
  125. // 回归:曾把会话选择的完整 providerId 透传进 draw body,被服务端白名单
  126. // 以 3001 参数错误拒绝;契约要求 body 的 provider 是 builtin:*-coding-plan。
  127. expect(result.kind).toBe("accelerated");
  128. expect(calls).toHaveLength(1);
  129. expect(calls[0]).toMatchObject({
  130. task_id: "task-1",
  131. provider: "builtin:bigmodel-coding-plan",
  132. model: "GLM-5.3",
  133. });
  134. });
  135. it("falls back without drawing when the provider has no allowlisted coding-plan id", async () => {
  136. const now = 10_000;
  137. const { calls, transport } = createTransport(async (request) =>
  138. cardResponse(request.task_id, now),
  139. );
  140. const service = new HighspeedCardService({ transport, now: () => now });
  141. // Start Plan 与自定义 Provider 都不在服务端 highspeed 白名单内。
  142. const startPlan = await service.prepareTurn({
  143. taskId: "task-1",
  144. providerId: "account:zai-start-plan",
  145. model: "GLM-5.3",
  146. });
  147. expect(startPlan).toMatchObject({ kind: "fallback", reason: "unavailable" });
  148. const custom = await service.prepareTurn({
  149. taskId: "task-1",
  150. providerId: "2b05e183-7ae4-46d6-aedb-4c8f750d9811",
  151. model: "GLM-5.3",
  152. });
  153. expect(custom).toMatchObject({ kind: "fallback", reason: "unavailable" });
  154. expect(calls).toHaveLength(0);
  155. });
  156. it("gates draw on the coding-plan model catalog and keeps covered models accelerated", async () => {
  157. const now = 9_000;
  158. const { calls, transport } = createTransport(async (request) =>
  159. cardResponse(request.task_id, now),
  160. );
  161. let covered = false;
  162. const service = new HighspeedCardService({
  163. transport,
  164. now: () => now,
  165. resolveModelCovered: async () => covered,
  166. });
  167. // 回归:会话恢复出的陈旧 (coding-plan provider, 已下线模型) 组合曾照样发 draw;
  168. // 契约要求模型不在所选 Provider 模型目录内时不发接口(spec §3 规则 14)。
  169. const staleModel = await service.prepareTurn({
  170. taskId: "task-1",
  171. providerId: "account:bigmodel-team-coding-plan",
  172. model: "GLM-4.6",
  173. });
  174. expect(staleModel).toMatchObject({ kind: "fallback", reason: "unavailable" });
  175. expect(calls).toHaveLength(0);
  176. // 门禁不落冷却、不改卡状态;切回目录内模型后下一轮立即可抽。
  177. covered = true;
  178. const coveredModel = await service.prepareTurn({
  179. taskId: "task-1",
  180. providerId: "account:bigmodel-team-coding-plan",
  181. model: "GLM-5.3",
  182. });
  183. expect(coveredModel.kind).toBe("accelerated");
  184. expect(calls).toHaveLength(1);
  185. });
  186. it("treats a failing model catalog check as not covered without drawing", async () => {
  187. const now = 9_000;
  188. const { calls, transport } = createTransport(async (request) =>
  189. cardResponse(request.task_id, now),
  190. );
  191. const service = new HighspeedCardService({
  192. transport,
  193. now: () => now,
  194. resolveModelCovered: async () => {
  195. throw new Error("model selection view unavailable");
  196. },
  197. });
  198. const result = await service.prepareTurn({
  199. taskId: "task-1",
  200. providerId: "account:zai-team-coding-plan",
  201. model: "GLM-5.3",
  202. });
  203. expect(result).toMatchObject({ kind: "fallback", reason: "unavailable" });
  204. expect(calls).toHaveLength(0);
  205. });
  206. it("gates draw on Coding Plan support and keeps entitled users accelerated", async () => {
  207. const now = 9_000;
  208. const { calls, transport } = createTransport(async (request) =>
  209. cardResponse(request.task_id, now),
  210. );
  211. let supported = false;
  212. const service = new HighspeedCardService({
  213. transport,
  214. now: () => now,
  215. resolveCodingPlanSupported: async () => supported,
  216. });
  217. const gatedResult = await service.prepareTurn({
  218. taskId: "task-1",
  219. providerId: "account:zai-team-coding-plan",
  220. model: "glm-5",
  221. });
  222. expect(gatedResult).toMatchObject({ kind: "fallback", reason: "no-coding-plan" });
  223. expect(calls).toHaveLength(0);
  224. // 门禁不落冷却,不改变卡状态;用户开通 Coding Plan 后下一轮立即可抽。
  225. supported = true;
  226. const entitledResult = await service.prepareTurn({
  227. taskId: "task-1",
  228. providerId: "account:zai-team-coding-plan",
  229. model: "glm-5",
  230. });
  231. expect(entitledResult.kind).toBe("accelerated");
  232. expect(calls).toHaveLength(1);
  233. });
  234. it("treats a failing Coding Plan probe as unsupported instead of drawing", async () => {
  235. const now = 9_000;
  236. const { calls, transport } = createTransport(async (request) =>
  237. cardResponse(request.task_id, now),
  238. );
  239. const service = new HighspeedCardService({
  240. transport,
  241. now: () => now,
  242. resolveCodingPlanSupported: async () => {
  243. throw new Error("credential store unavailable");
  244. },
  245. });
  246. const result = await service.prepareTurn({
  247. taskId: "task-1",
  248. providerId: "account:zai-team-coding-plan",
  249. model: "glm-5",
  250. });
  251. expect(result).toMatchObject({ kind: "fallback", reason: "no-coding-plan" });
  252. expect(calls).toHaveLength(0);
  253. });
  254. it.each(["model catalog", "Coding Plan support"] as const)(
  255. "falls back as unavailable without drawing when the %s check outlives the send budget",
  256. async (gate) => {
  257. const now = 9_000;
  258. const { calls, transport } = createTransport(async (request) =>
  259. cardResponse(request.task_id, now),
  260. );
  261. const waits: Array<() => void> = [];
  262. // 模拟 Provider Runtime 初始化阻塞:模型选择视图 / Coding Plan 判定迟迟不返回。
  263. const blocked = deferred<boolean>();
  264. const service = new HighspeedCardService({
  265. transport,
  266. now: () => now,
  267. wait: async () => new Promise<void>((resolve) => waits.push(resolve)),
  268. ...(gate === "model catalog"
  269. ? { resolveModelCovered: () => blocked.promise }
  270. : { resolveCodingPlanSupported: () => blocked.promise }),
  271. });
  272. const params = {
  273. taskId: "task-1",
  274. providerId: "account:zai-team-coding-plan",
  275. model: "glm-5",
  276. waitBudgetMs: 1,
  277. };
  278. // 回归(CR-02):门禁 await 曾不受 1s 发送预算约束,Registry 未就绪时发送被无限期挂起。
  279. const first = service.prepareTurn(params);
  280. await drainUntil(() => waits.length > 0, "send budget timer registered");
  281. waits.shift()?.();
  282. expect(await first).toMatchObject({ kind: "fallback", reason: "unavailable" });
  283. expect(calls).toHaveLength(0);
  284. // 判定不取消,晚到的结果不补发 draw、不改变卡与冷却状态;下一轮判定命中即正常抽卡。
  285. blocked.resolve(true);
  286. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  287. expect(calls).toHaveLength(0);
  288. expect(await service.getSnapshot()).toEqual({ card: null, nextDrawAt: null, drawing: false });
  289. expect((await service.prepareTurn(params)).kind).toBe("accelerated");
  290. expect(calls).toHaveLength(1);
  291. },
  292. );
  293. it("counts the draw wait against the budget already spent on the gates", async () => {
  294. const now = 9_000;
  295. const pending = deferred<HighspeedDrawResponse>();
  296. const { calls, transport } = createTransport(async () => pending.promise);
  297. const waits: Array<() => void> = [];
  298. const catalog = deferred<boolean>();
  299. const service = new HighspeedCardService({
  300. transport,
  301. now: () => now,
  302. wait: async () => new Promise<void>((resolve) => waits.push(resolve)),
  303. resolveModelCovered: () => catalog.promise,
  304. });
  305. const result = service.prepareTurn({
  306. taskId: "task-1",
  307. providerId: "account:zai-team-coding-plan",
  308. model: "glm-5",
  309. waitBudgetMs: 1000,
  310. });
  311. // 门禁在预算内通过后进入 draw 等待:两段共享进入 prepareTurn 时的同一截止时间,
  312. // draw 不得重新获得一整段 1s,否则总等待可达「门禁耗时 + 1s」。
  313. await drainUntil(() => waits.length > 0, "send budget timer registered");
  314. catalog.resolve(true);
  315. await drainUntil(() => calls.length > 0, "draw started");
  316. expect(waits).toHaveLength(1);
  317. waits.shift()?.();
  318. expect(await result).toMatchObject({ kind: "fallback", reason: "draw-timeout" });
  319. expect((await service.getSnapshot()).drawing).toBe(true);
  320. });
  321. it("falls back as draw-timeout but keeps the card when inference auth outlives the send budget", async () => {
  322. const now = 9_000;
  323. const { calls, transport } = createTransport(async (request) =>
  324. cardResponse(request.task_id, now),
  325. );
  326. const waits: Array<() => void> = [];
  327. const auth: HighspeedInferenceAuth = {
  328. zcodeJwt: "zcode-jwt",
  329. family: "zai",
  330. codingPlanAuthorization: "coding-plan-jwt",
  331. targetType: "PERSONAL",
  332. };
  333. let pendingAuth: ReturnType<typeof deferred<HighspeedInferenceAuth>> | null = null;
  334. const service = new HighspeedCardService({
  335. transport,
  336. now: () => now,
  337. wait: async () => new Promise<void>((resolve) => waits.push(resolve)),
  338. resolveInferenceAuth: async () => (pendingAuth ? pendingAuth.promise : auth),
  339. });
  340. const params = {
  341. taskId: "task-1",
  342. providerId: "account:zai-team-coding-plan",
  343. model: "glm-5",
  344. waitBudgetMs: 1000,
  345. };
  346. expect((await service.prepareTurn(params)).kind).toBe("accelerated");
  347. waits.length = 0;
  348. // 回归(CR-02):复用卡时的加速鉴权解析曾在预算外单独 await,凭据解析卡住会让发送无限期挂起。
  349. pendingAuth = deferred<HighspeedInferenceAuth>();
  350. const blocked = service.prepareTurn(params);
  351. await drainUntil(() => waits.length > 0, "send budget timer registered");
  352. waits.shift()?.();
  353. expect(await blocked).toMatchObject({
  354. kind: "fallback",
  355. reason: "draw-timeout",
  356. card: { cardId: "hsc-1", taskId: "task-1" },
  357. });
  358. expect((await service.getSnapshot()).card?.cardId).toBe("hsc-1");
  359. // 卡保留:鉴权恢复后的下一轮直接复用该卡加速,不重新 draw。
  360. pendingAuth.resolve(auth);
  361. pendingAuth = null;
  362. const next = await service.prepareTurn(params);
  363. expect(next).toMatchObject({ kind: "accelerated", card: { cardId: "hsc-1" } });
  364. expect(calls).toHaveLength(1);
  365. });
  366. it("keeps mock card semantics but leaves inference on the normal session route", async () => {
  367. const now = 10_000;
  368. const { transport } = createTransport(async (request) => cardResponse(request.task_id, now));
  369. let resolveAuthCalls = 0;
  370. const service = new HighspeedCardService({
  371. transport,
  372. now: () => now,
  373. inferenceMode: "session-default",
  374. resolveInferenceAuth: async () => {
  375. resolveAuthCalls += 1;
  376. return {
  377. zcodeJwt: "must-not-be-used",
  378. family: "zai",
  379. codingPlanAuthorization: "must-not-be-used",
  380. targetType: "PERSONAL",
  381. };
  382. },
  383. });
  384. const result = await service.prepareTurn({
  385. taskId: "task-1",
  386. providerId: "account:zai-team-coding-plan",
  387. model: "glm-5",
  388. });
  389. expect(result).toMatchObject({
  390. kind: "accelerated",
  391. card: { taskId: "task-1", model: "glm-5" },
  392. });
  393. expect(result).not.toHaveProperty("execution");
  394. expect(resolveAuthCalls).toBe(0);
  395. });
  396. it("accelerates when the current task card arrives inside the wait budget", async () => {
  397. const now = 10_000;
  398. const { calls, transport } = createTransport(async (request) =>
  399. cardResponse(request.task_id, now),
  400. );
  401. const service = new HighspeedCardService({ transport, now: () => now });
  402. const result = await service.prepareTurn({
  403. taskId: "task-1",
  404. providerId: "account:zai-team-coding-plan",
  405. model: "glm-5",
  406. waitBudgetMs: 1000,
  407. });
  408. expect(result.kind).toBe("accelerated");
  409. expect(result.card?.taskId).toBe("task-1");
  410. // 加速轮通过标准 Selection 指向隐藏的加速卡内建 Provider;端点等静态事实来自 Provider
  411. // Config,只有卡 JWT 与卡 ID 作为本次执行的动态鉴权随 modelExecution 下发。
  412. expect(result.execution?.modelSelection).toEqual({
  413. providerId: "account:zai-highspeed-card",
  414. modelId: "glm-5",
  415. });
  416. expect(result.execution?.requestAuth.headers["X-Highspeed-Card-ID"]).toBe("hsc-1");
  417. // 加速请求任何失败都退回会话模型(spec §2.2):卡过期按 3402 单独给原因,兜底规则不带错误码。
  418. // CLI 只按声明匹配,这里的声明就是降级覆盖面的唯一事实源;退回目标 = 本次提交的会话选择,
  419. // 不依赖 CLI 内存里的常驻选择(冷恢复竞态下它可能未绑定)。
  420. expect(result.execution?.selectionFallback).toEqual({
  421. providerId: "account:zai-highspeed-card",
  422. rules: [
  423. { reason: "highspeed_card_expired", providerErrorCode: "3402" },
  424. { reason: "highspeed_request_failed" },
  425. ],
  426. target: { providerId: "account:zai-team-coding-plan", modelId: "glm-5" },
  427. });
  428. expect(calls).toHaveLength(1);
  429. });
  430. it("carries the session reasoning level into the accelerated selection options", async () => {
  431. const now = 10_000;
  432. // 复现用户命中的 BigModel 场景:卡回显 GLM-5.3,加速 Provider 按账号 Family 落到 bigmodel。
  433. const { transport } = createTransport(async (request) => ({
  434. code: 0,
  435. msg: "success",
  436. data: {
  437. card: {
  438. card_id: "hsc-1",
  439. task_id: request.task_id,
  440. provider: "bigmodel",
  441. model: "GLM-5.3",
  442. issued_at: now,
  443. expires_at: now + 15 * 60_000,
  444. },
  445. next_draw_at: now + 60 * 60_000,
  446. },
  447. }));
  448. const service = new HighspeedCardService({
  449. transport,
  450. now: () => now,
  451. resolveInferenceAuth: async () => ({
  452. zcodeJwt: "zcode-jwt",
  453. family: "bigmodel",
  454. codingPlanAuthorization: "maas-jwt",
  455. targetType: "PERSONAL",
  456. }),
  457. });
  458. const result = await service.prepareTurn({
  459. taskId: "task-1",
  460. providerId: "account:bigmodel-team-coding-plan",
  461. model: "GLM-5.3",
  462. reasoningLevel: "enabled",
  463. });
  464. // 回归:加速卡曾丢掉会话思考档位,CLI Registry 因 execution 选择缺档位报
  465. // "Reasoning level is required" 让整轮发送失败。加速只换端点不换模型,档位必须一致。
  466. expect(result.kind).toBe("accelerated");
  467. expect(result.execution?.modelSelection).toEqual({
  468. providerId: "account:bigmodel-highspeed-card",
  469. modelId: "GLM-5.3",
  470. options: { reasoningLevel: "enabled" },
  471. });
  472. // 退回目标带同一份档位:降级后的原模型请求同样不能因缺档位被 Registry 拒绝。
  473. expect(result.execution?.selectionFallback.target).toEqual({
  474. providerId: "account:bigmodel-team-coding-plan",
  475. modelId: "GLM-5.3",
  476. options: { reasoningLevel: "enabled" },
  477. });
  478. });
  479. it("carries the Coding Plan dual-JWT and team identity into the accelerated request auth", async () => {
  480. const now = 10_000;
  481. const { transport } = createTransport(async (request) => ({
  482. code: 0,
  483. msg: "success",
  484. data: {
  485. card: {
  486. card_id: "hsc-1",
  487. task_id: request.task_id,
  488. provider: "bigmodel",
  489. model: "GLM-5.3",
  490. issued_at: now,
  491. expires_at: now + 15 * 60_000,
  492. },
  493. next_draw_at: now + 60 * 60_000,
  494. },
  495. }));
  496. const service = new HighspeedCardService({
  497. transport,
  498. now: () => now,
  499. // BigModel Team:加速推理与 draw 走同一 highspeed 网关,必须带上 Coding Plan 业务 JWT
  500. // 与 Team 身份头,来自同一次 selected connection 解析。
  501. resolveInferenceAuth: async () => ({
  502. zcodeJwt: "zcode-jwt",
  503. family: "bigmodel",
  504. codingPlanAuthorization: "maas-jwt",
  505. targetType: "TEAM",
  506. organizationId: "org-1",
  507. projectId: "project-1",
  508. }),
  509. });
  510. const result = await service.prepareTurn({
  511. taskId: "task-1",
  512. providerId: "account:bigmodel-team-coding-plan",
  513. model: "GLM-5.3",
  514. });
  515. // 回归:加速推理曾只发 zcode JWT + 卡 ID,缺 Coding Plan 双 JWT + Team 身份头,
  516. // 加速网关返回 401 auth_failed。必须与 draw 携带完全一致的 Coding Plan 头,再附加卡 ID。
  517. expect(result.kind).toBe("accelerated");
  518. expect(result.execution?.requestAuth.apiKey).toBe("zcode-jwt");
  519. expect(result.execution?.requestAuth.headers).toEqual({
  520. Authorization: "Bearer zcode-jwt",
  521. "X-Bigmodel-Authorization": "Bearer maas-jwt",
  522. "Bigmodel-Target-Type": "TEAM",
  523. "Bigmodel-Organization": "org-1",
  524. "Bigmodel-Project": "project-1",
  525. "X-Highspeed-Card-ID": "hsc-1",
  526. });
  527. });
  528. it("falls back after one second but keeps the late hit for the next turn", async () => {
  529. let now = 20_000;
  530. const pending = deferred<HighspeedDrawResponse>();
  531. const { calls, transport } = createTransport(async () => pending.promise);
  532. const waits: Array<() => void> = [];
  533. const service = new HighspeedCardService({
  534. transport,
  535. now: () => now,
  536. wait: async () => new Promise<void>((resolve) => waits.push(resolve)),
  537. });
  538. const firstPromise = service.prepareTurn({
  539. taskId: "task-1",
  540. providerId: "account:zai-team-coding-plan",
  541. model: "glm-5",
  542. waitBudgetMs: 1000,
  543. });
  544. // 预算从进入 prepareTurn 起算并覆盖异步门禁(规则 11/14);排空微任务直到 draw 真正发起
  545. // 再让预算到期,避免测试绑定内部 await 数量,也避免到期落在门禁阶段。
  546. await drainUntil(() => calls.length > 0, "draw started");
  547. waits.shift()?.();
  548. expect(await firstPromise).toMatchObject({ kind: "fallback", reason: "draw-timeout" });
  549. pending.resolve(cardResponse("task-1", now));
  550. await Promise.resolve();
  551. await Promise.resolve();
  552. now += 1;
  553. const second = await service.prepareTurn({
  554. taskId: "task-1",
  555. providerId: "account:zai-team-coding-plan",
  556. model: "glm-5",
  557. waitBudgetMs: 1000,
  558. });
  559. expect(second.kind).toBe("accelerated");
  560. expect(calls).toHaveLength(1);
  561. });
  562. it("releases the in-flight draw when the background request fails and draws again next turn", async () => {
  563. // CR-01 回归:draw 请求永不返回时,1s race 只结束「本次等待」,inFlightDraw 只能在 draw Promise
  564. // settle 的 finally 里释放。transport 必须让超时请求 reject;否则后续每次发送都复用同一个
  565. // 永久 pending Promise、等 1s 再降级,整个应用生命周期内不再发起新 draw,只能靠重启恢复。
  566. let now = 40_000;
  567. const pending = deferred<HighspeedDrawResponse>();
  568. let drawCalls = 0;
  569. const { calls, transport } = createTransport(async (request) => {
  570. drawCalls += 1;
  571. return drawCalls === 1 ? pending.promise : cardResponse(request.task_id, now);
  572. });
  573. const waits: Array<() => void> = [];
  574. const service = new HighspeedCardService({
  575. transport,
  576. now: () => now,
  577. wait: async () => new Promise<void>((resolve) => waits.push(resolve)),
  578. });
  579. const params = {
  580. taskId: "task-1",
  581. providerId: "account:zai-team-coding-plan",
  582. model: "glm-5",
  583. waitBudgetMs: 1000,
  584. };
  585. const first = service.prepareTurn(params);
  586. await drainUntil(() => calls.length > 0, "draw started");
  587. waits.shift()?.();
  588. expect(await first).toMatchObject({ kind: "fallback", reason: "draw-timeout" });
  589. expect((await service.getSnapshot()).drawing).toBe(true);
  590. // 模拟 transport 在后台生命期耗尽后 abort → reject(而不是永久 pending)。
  591. pending.reject(new Error("highspeed draw request timed out after 20000ms"));
  592. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  593. expect((await service.getSnapshot()).drawing).toBe(false);
  594. now += 1;
  595. const second = await service.prepareTurn(params);
  596. expect(second.kind).toBe("accelerated");
  597. expect(calls).toHaveLength(2);
  598. });
  599. it("honors next_draw_at and silently falls back for a foreign task card", async () => {
  600. let now = 30_000;
  601. const { calls, transport } = createTransport(async () => cardResponse("task-a", now));
  602. const service = new HighspeedCardService({ transport, now: () => now });
  603. const taskA = await service.prepareTurn({
  604. taskId: "task-a",
  605. providerId: "account:zai-team-coding-plan",
  606. model: "glm-5",
  607. });
  608. expect(taskA.kind).toBe("accelerated");
  609. const taskB = await service.prepareTurn({
  610. taskId: "task-b",
  611. providerId: "account:zai-team-coding-plan",
  612. model: "glm-5",
  613. });
  614. expect(taskB).toMatchObject({ kind: "fallback", reason: "foreign-card" });
  615. expect(calls).toHaveLength(1);
  616. now += 16 * 60_000;
  617. const duringCooldown = await service.prepareTurn({
  618. taskId: "task-b",
  619. providerId: "account:zai-team-coding-plan",
  620. model: "glm-5",
  621. });
  622. expect(duringCooldown).toMatchObject({ kind: "fallback", reason: "cooldown" });
  623. expect(calls).toHaveLength(1);
  624. });
  625. });
  626. describe("Highspeed mock transport", () => {
  627. it("uses short draw cooldown and card lifetime for local verification", async () => {
  628. const now = 50_000;
  629. const hit = createHighspeedMockTransport({
  630. scenario: "hit-fast",
  631. now: () => now,
  632. delay: async () => undefined,
  633. });
  634. const miss = createHighspeedMockTransport({
  635. scenario: "miss",
  636. now: () => now,
  637. delay: async () => undefined,
  638. });
  639. const invalidModel = createHighspeedMockTransport({
  640. scenario: "hit-invalid-model",
  641. now: () => now,
  642. delay: async () => undefined,
  643. });
  644. const hitResponse = await hit.draw({ task_id: "task-1", provider: "zai", model: "glm-5" });
  645. const missResponse = await miss.draw({
  646. task_id: "task-1",
  647. provider: "zai",
  648. model: "glm-5",
  649. });
  650. const invalidModelResponse = await invalidModel.draw({
  651. task_id: "task-1",
  652. provider: "zai",
  653. model: "glm-5",
  654. });
  655. expect(hitResponse.data.card?.expires_at).toBe(now + 5 * 60_000);
  656. expect(hitResponse.data.next_draw_at).toBe(now + 2 * 60_000);
  657. expect(missResponse.data.next_draw_at).toBe(now + 2 * 60_000);
  658. expect(invalidModelResponse.data.card?.model).toBe("E2E-HIGHSPEED-MODEL-NOT-IN-REGISTRY");
  659. });
  660. });
  661. describe("Highspeed HTTP contract", () => {
  662. it("builds the shared Coding Plan headers for personal and team plans", () => {
  663. expect(
  664. buildHighspeedCodingPlanAuthHeaders({
  665. zcodeJwt: "zcode-jwt",
  666. codingPlanAuthorization: "maas-jwt",
  667. targetType: "PERSONAL",
  668. }),
  669. ).toEqual({
  670. Authorization: "Bearer zcode-jwt",
  671. // 接口契约要求 X-Bigmodel-Authorization 带 Bearer 前缀;凭据库可能存裸 token。
  672. "X-Bigmodel-Authorization": "Bearer maas-jwt",
  673. "Bigmodel-Target-Type": "PERSONAL",
  674. });
  675. expect(
  676. buildHighspeedCodingPlanAuthHeaders({
  677. zcodeJwt: "Bearer zcode-jwt",
  678. codingPlanAuthorization: "team-maas-jwt",
  679. targetType: "TEAM",
  680. organizationId: "org-1",
  681. projectId: "project-1",
  682. }),
  683. ).toEqual({
  684. Authorization: "Bearer zcode-jwt",
  685. "X-Bigmodel-Authorization": "Bearer team-maas-jwt",
  686. "Bigmodel-Target-Type": "TEAM",
  687. "Bigmodel-Organization": "org-1",
  688. "Bigmodel-Project": "project-1",
  689. });
  690. // 已带前缀的凭据不能重复加 Bearer。
  691. expect(
  692. buildHighspeedCodingPlanAuthHeaders({
  693. zcodeJwt: "zcode-jwt",
  694. codingPlanAuthorization: "Bearer already-prefixed",
  695. targetType: "PERSONAL",
  696. }),
  697. ).toMatchObject({ "X-Bigmodel-Authorization": "Bearer already-prefixed" });
  698. });
  699. it("uses Coding Plan headers only for draw and login auth for healthy", async () => {
  700. const requests: Array<{
  701. url: string;
  702. method: string;
  703. headers: Headers;
  704. body: unknown;
  705. }> = [];
  706. const transport = createHighspeedHttpTransport({
  707. drawUrl: "https://example.test/api/v1/highspeed/draw",
  708. healthyBaseUrl: "https://example.test/api/v1/highspeed/",
  709. drawHeaders: async () => ({
  710. Authorization: "Bearer zcode-jwt",
  711. "X-Bigmodel-Authorization": "maas-jwt",
  712. "Bigmodel-Target-Type": "PERSONAL",
  713. }),
  714. healthyHeaders: async () => ({ Authorization: "Bearer zcode-jwt" }),
  715. logger: { warn: vi.fn() },
  716. fetchImpl: async (input, init) => {
  717. requests.push({
  718. url: String(input),
  719. method: init?.method ?? "GET",
  720. headers: new Headers(init?.headers),
  721. body: init?.body ? JSON.parse(String(init.body)) : undefined,
  722. });
  723. if (String(input).endsWith("/draw")) {
  724. return Response.json(cardResponse("task-1", 10_000));
  725. }
  726. if (String(input).endsWith("/hsc%2F1/healthy")) {
  727. return Response.json({
  728. code: 0,
  729. msg: "success",
  730. data: {
  731. card_id: "hsc/1",
  732. prompt_tokens: 120,
  733. completion_tokens: 90,
  734. duration_seconds: 1,
  735. },
  736. });
  737. }
  738. throw new Error("unexpected request");
  739. },
  740. });
  741. await transport.draw({ task_id: "task-1", provider: "zai", model: "glm-5" });
  742. const healthy = await transport.healthy("hsc/1");
  743. expect(requests[0]?.headers.get("X-Bigmodel-Authorization")).toBe("maas-jwt");
  744. expect(requests[1]).toMatchObject({
  745. url: "https://example.test/api/v1/highspeed/hsc%2F1/healthy",
  746. method: "GET",
  747. body: undefined,
  748. });
  749. expect(requests[1]?.headers.get("Authorization")).toBe("Bearer zcode-jwt");
  750. expect(healthy).toEqual({
  751. cardId: "hsc/1",
  752. promptTokens: 120,
  753. completionTokens: 90,
  754. durationSeconds: 1,
  755. });
  756. });
  757. it("logs draw HTTP failures with safe request diagnostics", async () => {
  758. const warn = vi.fn();
  759. let requestHeaders = new Headers();
  760. const transport = createHighspeedHttpTransport({
  761. drawUrl: "https://example.test/api/v1/highspeed/draw?credential=secret",
  762. healthyBaseUrl: "https://example.test/api/v1/highspeed/",
  763. shareUrl: "https://example.test/api/v1/highspeed/share",
  764. drawHeaders: async () => ({
  765. Authorization: "Bearer must-not-be-logged",
  766. "X-Bigmodel-Authorization": "must-not-be-logged",
  767. }),
  768. healthyHeaders: async () => ({ Authorization: "Bearer must-not-be-logged" }),
  769. shareHeaders: async () => ({ Authorization: "Bearer must-not-be-logged" }),
  770. logger: { warn },
  771. fetchImpl: async (_input, init) => {
  772. requestHeaders = new Headers(init?.headers);
  773. return Response.json(
  774. { code: 4290, msg: "too many requests", token: "must-not-be-logged" },
  775. {
  776. status: 429,
  777. statusText: "Too Many Requests",
  778. headers: {
  779. "x-request-id": "req-highspeed-draw",
  780. "x-trace-id": "trace-highspeed-draw",
  781. },
  782. },
  783. );
  784. },
  785. });
  786. await expect(
  787. transport.draw({ task_id: "task-1", provider: "zai", model: "glm-5" }),
  788. ).rejects.toThrow("highspeed draw failed: 429");
  789. expect(requestHeaders.get("x-request-id")).toMatch(
  790. /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
  791. );
  792. expect(warn).toHaveBeenCalledWith(
  793. undefined,
  794. "Highspeed 接口 HTTP 请求失败",
  795. expect.objectContaining({
  796. operation: "draw",
  797. method: "POST",
  798. url: "https://example.test/api/v1/highspeed/draw",
  799. status: 429,
  800. statusText: "Too Many Requests",
  801. responseHeaders: {
  802. "x-request-id": "req-highspeed-draw",
  803. "x-trace-id": "trace-highspeed-draw",
  804. },
  805. response: { code: 4290, message: "too many requests", fields: ["code", "msg", "token"] },
  806. }),
  807. );
  808. expect(JSON.stringify(warn.mock.calls)).not.toContain("must-not-be-logged");
  809. });
  810. it("logs healthy HTTP failures without logging authorization", async () => {
  811. const warn = vi.fn();
  812. const transport = createHighspeedHttpTransport({
  813. drawUrl: "https://example.test/api/v1/highspeed/draw",
  814. healthyBaseUrl: "https://example.test/api/v1/highspeed/",
  815. shareUrl: "https://example.test/api/v1/highspeed/share",
  816. drawHeaders: async () => ({ Authorization: "Bearer draw-secret" }),
  817. healthyHeaders: async () => ({ Authorization: "Bearer healthy-secret" }),
  818. shareHeaders: async () => ({ Authorization: "Bearer share-secret" }),
  819. logger: { warn },
  820. fetchImpl: async () =>
  821. Response.json(
  822. { code: 3402, msg: "highspeed card is invalid" },
  823. { status: 404, statusText: "Not Found" },
  824. ),
  825. });
  826. await expect(transport.healthy("hsc/secret")).rejects.toThrow("highspeed healthy failed: 404");
  827. expect(warn).toHaveBeenCalledWith(
  828. undefined,
  829. "Highspeed 接口 HTTP 请求失败",
  830. expect.objectContaining({
  831. operation: "healthy",
  832. method: "GET",
  833. url: "https://example.test/api/v1/highspeed/hsc%2Fsecret/healthy",
  834. status: 404,
  835. statusText: "Not Found",
  836. }),
  837. );
  838. expect(JSON.stringify(warn.mock.calls)).not.toContain("healthy-secret");
  839. });
  840. it("rejects and logs Highspeed business envelope failures with response request id", async () => {
  841. const warn = vi.fn();
  842. const transport = createHighspeedHttpTransport({
  843. drawUrl: "https://example.test/api/v1/highspeed/draw",
  844. healthyBaseUrl: "https://example.test/api/v1/highspeed/",
  845. shareUrl: "https://example.test/api/v1/highspeed/share",
  846. drawHeaders: async () => ({}),
  847. healthyHeaders: async () => ({}),
  848. shareHeaders: async () => ({}),
  849. logger: { warn },
  850. fetchImpl: async () =>
  851. Response.json(
  852. { ...cardResponse("task-1", 10_000), code: 2007, msg: "dependency failed" },
  853. { headers: { "x-request-id": "req-highspeed-business" } },
  854. ),
  855. });
  856. await expect(
  857. transport.draw({ task_id: "task-1", provider: "zai", model: "glm-5" }),
  858. ).rejects.toThrow("highspeed draw failed: business code 2007");
  859. expect(warn).toHaveBeenCalledWith(
  860. undefined,
  861. "Highspeed 接口业务失败",
  862. expect.objectContaining({
  863. operation: "draw",
  864. status: 200,
  865. responseHeaders: { "x-request-id": "req-highspeed-business" },
  866. response: expect.objectContaining({ code: 2007, message: "dependency failed" }),
  867. }),
  868. );
  869. });
  870. it("aborts a request that never returns so the in-flight draw can be released", async () => {
  871. // CR-01 回归:fetch 过去没有任何 deadline;代理/服务端接受连接后永不返回时 Promise 永久 pending。
  872. // 请求生命期必须有界且明确大于 1s 发送等待预算,超时后 abort → reject,让调用方的 finally 得以执行。
  873. vi.useFakeTimers();
  874. try {
  875. const warn = vi.fn();
  876. let observedSignal: AbortSignal | null | undefined;
  877. const transport = createHighspeedHttpTransport({
  878. drawUrl: "https://example.test/api/v1/highspeed/draw",
  879. healthyBaseUrl: "https://example.test/api/v1/highspeed/",
  880. drawHeaders: async () => ({}),
  881. healthyHeaders: async () => ({}),
  882. logger: { warn },
  883. fetchImpl: (_input, init) =>
  884. new Promise<Response>((_resolve, reject) => {
  885. observedSignal = init?.signal;
  886. // 只有 abort 能结束这个 Promise,模拟永不返回的连接。
  887. init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
  888. once: true,
  889. });
  890. }),
  891. });
  892. const draw = transport.draw({ task_id: "task-1", provider: "zai", model: "glm-5" });
  893. const settled = draw.then(
  894. () => "resolved",
  895. () => "rejected",
  896. );
  897. expect(HIGHSPEED_REQUEST_TIMEOUT_MS).toBeGreaterThan(1000);
  898. await vi.advanceTimersByTimeAsync(HIGHSPEED_REQUEST_TIMEOUT_MS - 1);
  899. expect(observedSignal?.aborted).toBe(false);
  900. await vi.advanceTimersByTimeAsync(1);
  901. expect(observedSignal?.aborted).toBe(true);
  902. await expect(draw).rejects.toThrow(/timed out after 20000ms/);
  903. expect(await settled).toBe("rejected");
  904. expect(warn).toHaveBeenCalledWith(
  905. undefined,
  906. "Highspeed 接口网络请求失败",
  907. expect.objectContaining({ operation: "draw", method: "POST" }),
  908. );
  909. } finally {
  910. vi.useRealTimers();
  911. }
  912. });
  913. });