project-token-runner-recovery.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { describe, expect, it, vi } from "vitest";
  2. import { APICallError } from "@ai-sdk/provider";
  3. import { runWithModelInvocationContext } from "@zcode/contracts";
  4. import { projectAccessTokenFingerprint } from "@zcode/shared";
  5. import { TestAiSdkModelAdapter, TestProviderConfigFixture } from "./test-provider-config.js";
  6. const scope = "a".repeat(64);
  7. const unauthorized = () =>
  8. new APICallError({
  9. message: "Unauthorized",
  10. statusCode: 401,
  11. url: "https://model.test",
  12. requestBodyValues: {},
  13. });
  14. const complete = {
  15. text: "ok",
  16. finishReason: "stop",
  17. usage: { inputTokens: 1, outputTokens: 1 },
  18. totalUsage: { inputTokens: 1, outputTokens: 1 },
  19. };
  20. function fixture({
  21. alwaysFail = false,
  22. committed = false,
  23. toolOutput = false,
  24. chunkError = false,
  25. refreshFails = false,
  26. } = {}) {
  27. let attempts = 0;
  28. const seen: string[] = [];
  29. const adapter = new TestAiSdkModelAdapter({
  30. registry: new TestProviderConfigFixture({
  31. providers: {
  32. idle: { kind: "anthropic", accountMode: "off-peak", baseURL: "https://model.test" },
  33. },
  34. }),
  35. retry: { maxAttempts: 1, baseDelayMs: 0, maxDelayMs: 0, jitter: false },
  36. runtime: {
  37. async generateText(options) {
  38. attempts++;
  39. seen.push(new Headers(options.headers).get("X-Coding-Plan-Api-Key")!);
  40. if (alwaysFail || attempts === 1) throw unauthorized();
  41. return complete as never;
  42. },
  43. streamText(options) {
  44. attempts++;
  45. seen.push(new Headers(options.headers).get("X-Coding-Plan-Api-Key")!);
  46. return {
  47. fullStream: (async function* () {
  48. yield { type: "start" };
  49. if (toolOutput) {
  50. yield { type: "tool-input-start", id: "call", toolName: "Read" };
  51. yield { type: "tool-input-delta", id: "call", delta: "{}" };
  52. yield { type: "tool-input-end", id: "call" };
  53. yield { type: "tool-call", toolCallId: "call", toolName: "Read", input: "{}" };
  54. }
  55. if (committed) {
  56. yield { type: "text-start", id: "text" };
  57. yield { type: "text-delta", id: "text", text: "already visible" };
  58. }
  59. if (alwaysFail || attempts === 1) {
  60. if (chunkError) {
  61. yield { type: "error", error: unauthorized() };
  62. return;
  63. }
  64. throw unauthorized();
  65. }
  66. yield { type: "text-start", id: "text" };
  67. yield { type: "text-delta", id: "text", text: "ok" };
  68. yield { type: "text-end", id: "text" };
  69. yield {
  70. type: "finish",
  71. finishReason: "stop",
  72. totalUsage: { inputTokens: 1, outputTokens: 1 },
  73. };
  74. })(),
  75. } as never;
  76. },
  77. },
  78. });
  79. const auth = {
  80. apiKey: "jwt",
  81. accountScope: scope,
  82. headers: {
  83. Authorization: "Bearer jwt",
  84. "X-Coding-Plan-Api-Key": "initial",
  85. "X-Off-Peak-Ticket-ID": "ticket",
  86. },
  87. };
  88. const model = adapter.createModel({
  89. providerId: "idle",
  90. modelId: "glm",
  91. accountMode: "off-peak",
  92. requestDependencies: { requestAuth: { source: { resolve: async () => auth } } },
  93. });
  94. const refresh = vi.fn(async (input) => {
  95. if (input.rejectedProjectTokenFingerprint && refreshFails) throw new Error("issue failed");
  96. return {
  97. headersApplied: true,
  98. requestAuth: {
  99. apiKey: input.rejectedProjectTokenFingerprint ? "pat-2" : "pat-1",
  100. accountScope: scope,
  101. },
  102. };
  103. });
  104. const events: unknown[] = [];
  105. const run = (stream: boolean) =>
  106. runWithModelInvocationContext({ refreshRuntimeHeadersBeforeAttempt: refresh }, async () => {
  107. const request = { messages: [{ role: "user", content: "hello" }] } as const;
  108. if (!stream) return model.generateText(request as never);
  109. for await (const event of model.streamText(request as never)) events.push(event);
  110. });
  111. return { run, refresh, seen, events, attempts: () => attempts };
  112. }
  113. describe("真实 runner 的 PAT 401 恢复", () => {
  114. it.each([false, true])("stream=%s 无输出 401 换 PAT 后重试,即使普通预算为 1", async (stream) => {
  115. const f = fixture();
  116. await f.run(stream);
  117. expect(f.seen).toEqual(["pat-1", "pat-2"]);
  118. expect(f.refresh.mock.calls[1]?.[0]).toMatchObject({
  119. expectedAccountScope: scope,
  120. rejectedProjectTokenFingerprint: await projectAccessTokenFingerprint("pat-1"),
  121. });
  122. });
  123. it.each([false, true])("stream=%s 二次 401 终止", async (stream) => {
  124. const f = fixture({ alwaysFail: true });
  125. await expect(f.run(stream)).rejects.toThrow();
  126. expect(f.attempts()).toBe(2);
  127. });
  128. it("换证失败不发第二次模型请求", async () => {
  129. const f = fixture({ refreshFails: true });
  130. await expect(f.run(false)).rejects.toThrow();
  131. expect(f.attempts()).toBe(1);
  132. });
  133. it("已输出工具调用后不因 401 重放", async () => {
  134. const f = fixture({ toolOutput: true });
  135. await expect(f.run(true)).rejects.toThrow();
  136. expect(f.attempts()).toBe(1);
  137. expect(f.events).toEqual(
  138. expect.arrayContaining([expect.objectContaining({ type: "tool_call" })]),
  139. );
  140. });
  141. it("SSE 首个错误块也进入一次恢复", async () => {
  142. const f = fixture({ chunkError: true });
  143. await f.run(true);
  144. expect(f.seen).toEqual(["pat-1", "pat-2"]);
  145. });
  146. it.each([false, true])("已输出文本后不因 401 重放(错误块=%s)", async (chunkError) => {
  147. const f = fixture({ committed: true, chunkError });
  148. await expect(f.run(true)).rejects.toThrow();
  149. expect(f.attempts()).toBe(1);
  150. });
  151. });