highspeedCardService.test.ts 38 KB

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