highspeedSend.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { HighspeedPrepareTurnResult, HighspeedTurnExecution } from "@zcode/shared";
  3. import {
  4. HIGHSPEED_REGULAR_TPS_WAIT_BUDGET_MS,
  5. HIGHSPEED_SEND_WAIT_BUDGET_MS,
  6. buildHighspeedRuntimeOverride,
  7. prepareHighspeedSendContext,
  8. readRegularTpsWithinSendBudget,
  9. } from "../../src/highspeed/highspeedSend.js";
  10. const card = {
  11. cardId: "hsc-1",
  12. taskId: "task-1",
  13. provider: "zai",
  14. model: "glm-5",
  15. issuedAt: 1_000,
  16. expiresAt: 10_000,
  17. };
  18. /**
  19. * 加速执行材料只带「本轮选哪个模型」和「本次执行鉴权」:端点、API 形态、模型能力都由
  20. * 隐藏内建 Provider Config 提供,不再随单次发送下发 provider 定义。
  21. */
  22. const execution = {
  23. modelSelection: { providerId: "account:zai-highspeed-card", modelId: "glm-5" },
  24. requestAuth: {
  25. apiKey: "jwt",
  26. headers: { Authorization: "Bearer jwt", "X-Highspeed-Card-ID": "hsc-1" },
  27. },
  28. selectionFallback: {
  29. providerId: "account:zai-highspeed-card",
  30. rules: [
  31. { reason: "highspeed_card_expired", providerErrorCode: "3402" },
  32. { reason: "highspeed_request_failed" },
  33. ],
  34. target: { providerId: "account:zai-team-coding-plan", modelId: "glm-5" },
  35. },
  36. } satisfies HighspeedTurnExecution;
  37. describe("buildHighspeedRuntimeOverride", () => {
  38. it("persists card metadata without overriding the normal route for an accelerated mock card", () => {
  39. const result: HighspeedPrepareTurnResult = {
  40. kind: "accelerated",
  41. card,
  42. nextDrawAt: 20_000,
  43. };
  44. expect(buildHighspeedRuntimeOverride(result)).toEqual({
  45. highspeedMeta: {
  46. schemaVersion: 1,
  47. ...card,
  48. },
  49. });
  50. });
  51. it("injects the Highspeed selection and execution-scoped auth for a real accelerated card", () => {
  52. const result: HighspeedPrepareTurnResult = {
  53. kind: "accelerated",
  54. card,
  55. nextDrawAt: 20_000,
  56. execution,
  57. };
  58. expect(buildHighspeedRuntimeOverride(result)).toEqual({
  59. highspeedMeta: {
  60. schemaVersion: 1,
  61. ...card,
  62. },
  63. modelSelection: execution.modelSelection,
  64. // selectionScope=execution 是加速轮的关键约束:只作用于本轮执行,不写 Session Selection。
  65. modelExecution: {
  66. selectionScope: "execution",
  67. requestAuth: execution.requestAuth,
  68. selectionFallback: execution.selectionFallback,
  69. },
  70. });
  71. });
  72. });
  73. describe("prepareHighspeedSendContext", () => {
  74. it("uses one prepared result for both command payload and visual card tracking", async () => {
  75. const result: HighspeedPrepareTurnResult = {
  76. kind: "accelerated",
  77. card,
  78. nextDrawAt: 20_000,
  79. execution,
  80. };
  81. await expect(
  82. prepareHighspeedSendContext("task-1", async (taskId) => {
  83. expect(taskId).toBe("task-1");
  84. return result;
  85. }),
  86. ).resolves.toEqual({
  87. override: {
  88. highspeedMeta: { schemaVersion: 1, ...card },
  89. modelSelection: execution.modelSelection,
  90. modelExecution: {
  91. selectionScope: "execution",
  92. requestAuth: execution.requestAuth,
  93. selectionFallback: execution.selectionFallback,
  94. },
  95. },
  96. acceleratedCard: card,
  97. });
  98. });
  99. it("keeps fallback sends free of Highspeed payload and visual state", async () => {
  100. await expect(
  101. prepareHighspeedSendContext("task-1", async () => ({
  102. kind: "fallback",
  103. reason: "cooldown",
  104. nextDrawAt: null,
  105. })),
  106. ).resolves.toEqual({ override: {} });
  107. });
  108. });
  109. describe("readRegularTpsWithinSendBudget", () => {
  110. // 可控的等待器:记录每次请求的预算,并允许测试手动唤醒,避免绑定真实计时器。
  111. function manualWait() {
  112. const waits: Array<{ ms: number; resolve: () => void }> = [];
  113. const wait = (ms: number) => new Promise<void>((resolve) => waits.push({ ms, resolve }));
  114. return { waits, wait };
  115. }
  116. it("returns the TPS when the read settles inside the budget", async () => {
  117. const { wait } = manualWait();
  118. await expect(
  119. readRegularTpsWithinSendBudget({ read: async () => 42, elapsedMs: 100, wait }),
  120. ).resolves.toBe(42);
  121. });
  122. it("gives up after the budget and lets the read finish in the background", async () => {
  123. // CR-02 回归:TPS monitor 配 15s 超时,曾在抽中后同步 await,把 1s 发送承诺拉长到最多 16s。
  124. const { waits, wait } = manualWait();
  125. let resolveRead!: (value: number) => void;
  126. const onTimeout = vi.fn();
  127. const pending = readRegularTpsWithinSendBudget({
  128. read: () =>
  129. new Promise<number>((resolve) => {
  130. resolveRead = resolve;
  131. }),
  132. elapsedMs: 0,
  133. onTimeout,
  134. wait,
  135. });
  136. while (waits.length === 0) await Promise.resolve();
  137. expect(waits[0]?.ms).toBe(HIGHSPEED_REGULAR_TPS_WAIT_BUDGET_MS);
  138. waits.shift()?.resolve();
  139. await expect(pending).resolves.toBeUndefined();
  140. expect(onTimeout).toHaveBeenCalledWith(HIGHSPEED_REGULAR_TPS_WAIT_BUDGET_MS);
  141. // 后台迟到的结果不抛错、不影响已提交的发送。
  142. resolveRead(42);
  143. await Promise.resolve();
  144. });
  145. it("caps the wait by the remaining send budget and skips waiting once it is spent", async () => {
  146. const remaining = manualWait();
  147. const slow = readRegularTpsWithinSendBudget({
  148. read: () => new Promise<number>(() => {}),
  149. elapsedMs: HIGHSPEED_SEND_WAIT_BUDGET_MS - 100,
  150. wait: remaining.wait,
  151. });
  152. while (remaining.waits.length === 0) await Promise.resolve();
  153. expect(remaining.waits[0]?.ms).toBe(100);
  154. remaining.waits.shift()?.resolve();
  155. await expect(slow).resolves.toBeUndefined();
  156. const spent = manualWait();
  157. const read = vi.fn(async () => 42);
  158. const onTimeout = vi.fn();
  159. await expect(
  160. readRegularTpsWithinSendBudget({
  161. read,
  162. elapsedMs: HIGHSPEED_SEND_WAIT_BUDGET_MS,
  163. onTimeout,
  164. wait: spent.wait,
  165. }),
  166. ).resolves.toBeUndefined();
  167. // 预算耗尽仍发起一次请求预热 Service 缓存,但不再等待。
  168. expect(read).toHaveBeenCalledTimes(1);
  169. expect(onTimeout).toHaveBeenCalledWith(0);
  170. expect(spent.waits).toHaveLength(0);
  171. });
  172. it("treats read failures as missing TPS without blocking the send", async () => {
  173. const { wait } = manualWait();
  174. const onError = vi.fn();
  175. await expect(
  176. readRegularTpsWithinSendBudget({
  177. read: async () => {
  178. throw new Error("monitor down");
  179. },
  180. elapsedMs: 0,
  181. onError,
  182. wait,
  183. }),
  184. ).resolves.toBeUndefined();
  185. expect(onError).toHaveBeenCalledWith(expect.any(Error));
  186. });
  187. });