From c6f18d3e15febd1fb0d89055f6ff15aefe16a81a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:43:42 +0800 Subject: [PATCH 1/3] feat(api): add the shared abort, timeout and error plumbing (#1311 split u0) Unit u0 of the split plan in #2799. It carries the shared helpers that the provider units of #1311 consume, and nothing provider-specific. - abort-signal.ts: mergeAbortSignalAndTimeout, rejectOnAbort, and the timeout classification helpers (isTimeoutAbort, createTimeoutError). - error-handler.ts: handleOpenAIRequestError keeps an HTTP failure's identity over a racing abort and reports a deadline as TimeoutError. - request-timeout.ts: getRequestTimeoutMs for the per-request SDK timeout. - test-utils/errors.ts: captureError, used by the cancellation rows of the provider units. Evidence: 643 rows across the utils and test-utils specs pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. --- .../utils/__tests__/abort-signal.spec.ts | 19 +++ .../utils/__tests__/error-handler.spec.ts | 123 +++++++++++++++++- .../utils/__tests__/request-timeout.spec.ts | 11 ++ src/api/providers/utils/abort-signal.ts | 11 +- src/api/providers/utils/error-handler.ts | 44 +++++++ src/api/providers/utils/request-timeout.ts | 14 +- src/eslint-suppressions.json | 7 +- src/test-utils/__tests__/errors.spec.ts | 22 ++++ src/test-utils/errors.ts | 17 +++ 9 files changed, 250 insertions(+), 18 deletions(-) create mode 100644 src/test-utils/__tests__/errors.spec.ts create mode 100644 src/test-utils/errors.ts diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550a..7159732c59e 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -600,6 +600,25 @@ describe("abort-signal utilities", () => { expect(createAbortError("Qwen Code").message).toBe("The Qwen Code request was aborted") }) + it("keeps the supplied cause under the contract name and message", () => { + const cause = new Error("socket reset by peer") + const error = createAbortError("OpenAI", cause) + + expect(error.name).toBe("AbortError") + expect(error.message).toBe("The OpenAI request was aborted") + expect(error.cause).toBe(cause) + }) + + it("leaves the cause unset when the caller supplies none", () => { + const error = createAbortError("OpenAI") + + expect(error.name).toBe("AbortError") + expect(error.message).toBe("The OpenAI request was aborted") + // A bare new Error(message, { cause: undefined }) defines the property, so the absence is + // asserted rather than compared with undefined. + expect("cause" in error).toBe(false) + }) + it("returns a fresh error on each call", () => { expect(createAbortError("X")).not.toBe(createAbortError("X")) }) diff --git a/src/api/providers/utils/__tests__/error-handler.spec.ts b/src/api/providers/utils/__tests__/error-handler.spec.ts index 3e6bfc9271a..436f05d86a6 100644 --- a/src/api/providers/utils/__tests__/error-handler.spec.ts +++ b/src/api/providers/utils/__tests__/error-handler.spec.ts @@ -1,4 +1,13 @@ -import { getNumericHttpStatus, handleOpenAIError, handleProviderError, hasNumericHttpStatus } from "../error-handler" +import { APIUserAbortError } from "openai" + +import { + getNumericHttpStatus, + handleOpenAIError, + handleOpenAIRequestError, + handleProviderError, + hasNumericHttpStatus, +} from "../error-handler" +import { isTimeoutAbort, mergeAbortSignals } from "../abort-signal" describe("handleProviderError", () => { const providerName = "TestProvider" @@ -424,3 +433,115 @@ describe("getNumericHttpStatus", () => { expect(getNumericHttpStatus(Object.assign(() => undefined, { statusCode: 429 }))).toBeUndefined() }) }) + +describe("handleOpenAIRequestError (abort awareness)", () => { + it("normalizes a generic error to a fresh AbortError when the caller signal aborted", () => { + const controller = new AbortController() + controller.abort() + const original = new Error("network failure") + + const result = handleOpenAIRequestError(original, "OpenAI", controller.signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect((result as Error & { cause?: unknown }).cause).toBe(original) + }) + + it("normalizes the SDK user-abort error when no signal was passed", () => { + const result = handleOpenAIRequestError(new APIUserAbortError(), "Zai") + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Zai request was aborted") + }) + + it("keeps a timeout-triggered SDK abort classified as a timeout when the caller did not abort", () => { + const original = new APIUserAbortError() + const requestSignal = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + + const result = handleOpenAIRequestError(original, "OpenAI", undefined, requestSignal) + + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The OpenAI completion request timed out") + expect((result as Error & { cause?: unknown }).cause).toBe(original) + }) + + it("keeps the abort contract when the request signal has not aborted", () => { + // The guard must not assume a reason exists: an SDK abort can arrive while the + // merged request signal is still live, and reading .name on an undefined reason + // would turn a cancellation into a TypeError. + const result = handleOpenAIRequestError( + new APIUserAbortError(), + "OpenAI", + undefined, + new AbortController().signal, + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + it("keeps a caller cancellation classified as an abort even when the request signal timed out", () => { + const controller = new AbortController() + controller.abort() + const requestSignal = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + + const result = handleOpenAIRequestError(new APIUserAbortError(), "OpenAI", controller.signal, requestSignal) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + it("keeps the abort contract for a caller that stops after a real merged signal timed out", () => { + // The row above approximates this interleaving with a signal it builds by hand. This one merges the + // way the providers merge: mergeAbortSignals is AbortSignal.any([caller, timeout]) (abort-signal.ts:67), + // reached from mergeAbortSignalAndTimeout (abort-signal.ts:52) and from + // config-builder/request-config-builder.ts:94 - the composition that produces the requestSignal handed + // to the guard at base-openai-compatible-provider.ts:344 and openai.ts:617. The timeout signal is + // already aborted when the merge is built, so "the deadline fired first" is a property of the fixture + // and not a race; the caller then stops its own controller, and the aggregate keeps the TimeoutError + // reason. Only the !abortSignal?.aborted term at error-handler.ts:186 can route this call to the abort + // contract, so this row is what pins "the caller's stop wins" for a genuine merged signal. + const caller = new AbortController() + const timedOut = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + const requestSignal = mergeAbortSignals(caller.signal, timedOut) + caller.abort() + + // These three assertions are the premise the classification rests on. A merged signal that stopped + // carrying a TimeoutError reason would make isTimeoutAbort false, and the fall-through at + // error-handler.ts:196-201 would then answer AbortError for the wrong reason - this row would stay + // green while the guard meant nothing. + expect(requestSignal.aborted, "the merge is already aborted by the timeout").toBe(true) + expect((requestSignal.reason as { name?: string } | undefined)?.name).toBe("TimeoutError") + expect(isTimeoutAbort(requestSignal), "the predicate the guard consults").toBe(true) + + const result = handleOpenAIRequestError(new APIUserAbortError(), "OpenAI", caller.signal, requestSignal) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("normalizes a native fetch-level AbortError when no signal was passed", () => { + const result = handleOpenAIRequestError( + Object.assign(new Error("aborted"), { name: "AbortError" }), + "Fireworks", + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Fireworks request was aborted") + }) + + it("keeps the provider-prefix wrap for a non-abort failure", () => { + const original = new Error("rate limited") + + const result = handleOpenAIRequestError(original, "OpenAI", new AbortController().signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("Error") + expect(result.message).toBe("OpenAI completion error: rate limited") + }) + + it("falls back to the provider-prefix wrap when no signal is available", () => { + const result = handleOpenAIRequestError(new Error("boom"), "Kimi Code") + + expect(result.message).toBe("Kimi Code completion error: boom") + }) +}) diff --git a/src/api/providers/utils/__tests__/request-timeout.spec.ts b/src/api/providers/utils/__tests__/request-timeout.spec.ts index 8190faebe36..c9763e759d2 100644 --- a/src/api/providers/utils/__tests__/request-timeout.spec.ts +++ b/src/api/providers/utils/__tests__/request-timeout.spec.ts @@ -1,3 +1,4 @@ +import { MAX_TIMEOUT_MS } from "../abort-signal" import { createTimeoutError, getRequestTimeoutMs } from "../request-timeout" describe("getRequestTimeoutMs", () => { @@ -35,6 +36,16 @@ describe("getRequestTimeoutMs", () => { // (e.g. user settings); the double cast exercises the typeof guard. expect(getRequestTimeoutMs("5000" as unknown as number)).toBeUndefined() }) + + it("caps timeouts past the maximum timer delay instead of letting Node clamp them", () => { + // A delay above 2^31-1 ms is not a legal timer value: Node clamps it to ~1 ms, so an + // oversized setting would abort the request almost immediately rather than wait. The + // cap belongs here because this value also goes to the SDK's own timeout option. + expect(getRequestTimeoutMs(MAX_TIMEOUT_MS)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(MAX_TIMEOUT_MS + 1)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(2 ** 32)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(Number.MAX_SAFE_INTEGER)).toBe(MAX_TIMEOUT_MS) + }) }) describe("createTimeoutError", () => { diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 6abbc124371..05fa373ae9f 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -159,8 +159,8 @@ export function isRequestAborted(error: unknown, signal?: AbortSignal): boolean * message "Request was aborted."), so raw SDK abort errors must be * normalized instead of rethrown. */ -export function createAbortError(providerName: string): Error { - const abortError = new Error(`The ${providerName} request was aborted`) +export function createAbortError(providerName: string, cause?: unknown): Error { + const abortError = new Error(`The ${providerName} request was aborted`, cause === undefined ? undefined : { cause }) abortError.name = "AbortError" return abortError } @@ -312,9 +312,10 @@ export function createTimeoutError(providerName: string): Error { * caller's stop signal. */ export function isTimeoutAbort(requestSignal: AbortSignal | undefined): boolean { - // Classify by the merged signal's retained abort reason: if its own timeout fired first, the - // reason stays the TimeoutError even when the caller aborts later, so the failure must still be - // reported as a deadline. A caller-first abort retains the caller's reason instead. + // Classify by the merged signal's retained abort reason: a deadline that fired first keeps the + // TimeoutError reason even if the caller stops later, so this answers only which signal fired + // first. handleOpenAIRequestError answers a caller that also pressed stop with the abort + // contract - error-handler.spec.ts:483-492 pins that answer for the interleaving. return Boolean( requestSignal?.aborted && (requestSignal.reason as { name?: string } | undefined)?.name === "TimeoutError", ) diff --git a/src/api/providers/utils/error-handler.ts b/src/api/providers/utils/error-handler.ts index 2247ed182c4..96ce8e1fbd8 100644 --- a/src/api/providers/utils/error-handler.ts +++ b/src/api/providers/utils/error-handler.ts @@ -9,7 +9,11 @@ * - Enables telemetry and debugging with complete error context */ +import { APIUserAbortError } from "openai" + import i18n from "../../../i18n/setup" +import { createAbortError, isTimeoutAbort } from "./abort-signal" +import { createTimeoutError } from "./request-timeout" /** * Handles API provider errors and transforms them into user-friendly messages @@ -163,3 +167,43 @@ export function handleProviderError( export function handleOpenAIError(error: unknown, providerName: string): Error { return handleProviderError(error, providerName, { messagePrefix: "completion" }) } + +/** + * Handles errors from OpenAI Node SDK request sites with abort awareness. + * + * An abort failure (the external signal already aborted, the SDK's + * APIUserAbortError, or a fetch-level AbortError) is normalized to a fresh + * Error with name "AbortError" and a message ending in "aborted" (the Task.ts + * contract) instead of being wrapped as a regular completion error, which a + * plain rethrow of the SDK abort error would produce. + */ +export function handleOpenAIRequestError( + error: unknown, + providerName: string, + abortSignal?: AbortSignal, + requestSignal?: AbortSignal, +): Error { + // A terminal HTTP failure keeps its own identity even when the caller stops in the same tick: + // backoff reads the top-level status, so masking a 401/429 as AbortError hides the provider error. + if (hasNumericHttpStatus(error)) return handleOpenAIError(error, providerName) + + // The deadline, not the caller's stop, ended this request. Classified before the abort branch so a + // native AbortError raised by the SDK's JSON body read is reported as a timeout as well. + if (!abortSignal?.aborted && isTimeoutAbort(requestSignal)) { + // The abort came from this merged signal's own deadline, not the caller's stop: a timeout + // must stay distinguishable from a user cancellation, so the shared helper's name and + // message are used and the SDK abort is attached as the cause. A caller that pressed stop + // never reaches here - error-handler.spec.ts:483-492 pins the abort for that interleaving. + const timeoutError = createTimeoutError(providerName, "completion request") + timeoutError.cause = error + return timeoutError + } + + if ( + abortSignal?.aborted || + (error instanceof Error && (error.name === "AbortError" || error instanceof APIUserAbortError)) + ) { + return createAbortError(providerName, error) + } + return handleOpenAIError(error, providerName) +} diff --git a/src/api/providers/utils/request-timeout.ts b/src/api/providers/utils/request-timeout.ts index 672922415a5..89067ac80fd 100644 --- a/src/api/providers/utils/request-timeout.ts +++ b/src/api/providers/utils/request-timeout.ts @@ -1,17 +1,19 @@ +import { hasUsableTimeout, toSdkTimeoutMs } from "./abort-signal" + /** * Returns the value to pass as a client/SDK request timeout option, or undefined. * * Per the abort-signal series contract, timeoutMs <= 0, non-finite values * (or undefined) mean 'no per-request timeout': the option is omitted * entirely, because some SDKs (e.g. the OpenAI Node SDK) treat timeout: 0 as - * an IMMEDIATE timeout. Finite values are rounded up to whole milliseconds: - * downstream AbortSignal.timeout() validates its delay as uint32 and throws - * for fractions. + * an IMMEDIATE timeout. Values that do survive validation are handed to + * toSdkTimeoutMs, which rounds fractions up (AbortSignal.timeout validates its + * delay as uint32 and throws for fractions) and caps them at the maximum timer + * delay: a Node timer clamps anything past 2^31-1 ms to ~1 ms, which would + * abort the request almost immediately instead of honouring the timeout. */ export function getRequestTimeoutMs(timeoutMs?: number): number | undefined { - return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 - ? Math.ceil(timeoutMs) - : undefined + return hasUsableTimeout(timeoutMs) ? toSdkTimeoutMs(timeoutMs) : undefined } /** diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..2c46065d858 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -74,11 +74,6 @@ "count": 1 } }, - "api/providers/__tests__/kimi-code.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, "api/providers/__tests__/lite-llm.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 26 @@ -191,7 +186,7 @@ }, "api/providers/base-openai-compatible-provider.ts": { "@typescript-eslint/no-explicit-any": { - "count": 6 + "count": 5 } }, "api/providers/base-provider.ts": { diff --git a/src/test-utils/__tests__/errors.spec.ts b/src/test-utils/__tests__/errors.spec.ts new file mode 100644 index 00000000000..c666b5e9774 --- /dev/null +++ b/src/test-utils/__tests__/errors.spec.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest" + +import { captureError } from "../errors" + +describe("error capture utility", () => { + it("returns the rejecting Error instance untouched", async () => { + const original = new Error("provider failed") + + expect(await captureError(Promise.reject(original))).toBe(original) + }) + + it("re-wraps a non-Error rejection so the original failure message stays visible", async () => { + const captured = await captureError(Promise.reject("plain string failure")) + + expect(captured).toBeInstanceOf(Error) + expect(captured.message).toBe("plain string failure") + }) + + it("rejects when the operation resolves, because resolving violates the contract", async () => { + await expect(captureError(Promise.resolve("value"))).rejects.toThrow("Expected the operation to reject") + }) +}) diff --git a/src/test-utils/errors.ts b/src/test-utils/errors.ts new file mode 100644 index 00000000000..67d897b2423 --- /dev/null +++ b/src/test-utils/errors.ts @@ -0,0 +1,17 @@ +/** + * Captures the rejection of an operation as an `Error`. + * + * Provider abort normalization always throws an `Error`, but an awaited + * operation is typed `unknown`, so the guard keeps strict typing without + * casts. A non-Error rejection is re-wrapped so the original failure message + * stays visible, and a resolving operation — the contract violation the + * surrounding test exists to catch — becomes a failing assertion. + */ +export async function captureError(operation: Promise): Promise { + try { + await operation + } catch (error) { + return error instanceof Error ? error : new Error(String(error)) + } + throw new Error("Expected the operation to reject") +} From 91c6af4bb0c46f69333372125763ab0c2207da59 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:45:22 +0800 Subject: [PATCH 2/3] feat(api): honour caller cancellation in the openai family (#1311 split u1) Unit u1 of the split plan in #2799. It carries openai.ts and the OpenAI-compatible base, with their cancellation rows. - The two abort contracts stay apart: the caller's signal goes to the request each route issues, and a mid-flight abort or a raw SDK abort becomes the provider's contract error with the failure kept as the cause. Each request site normalizes its own failure, including the Responses completion. - A stream failure is a flag beside its value, so a rejection carrying `undefined` still reaches the handler, and the recorded usage is yielded before the error. A usage frame the SDK already returned is recorded before the abort break. - The Responses completion forwards the merged caller and deadline signal, so the deadline stays armed while the SDK reads the JSON body. - Request creation is raced against the request signal, so a 429 backoff sleep cannot outlast a deadline. Evidence: openai, base-provider and cancellation rows 725 pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. --- ...openai-compatible-provider-timeout.spec.ts | 51 +- .../base-openai-compatible-provider.spec.ts | 786 +++++++++++++++++- src/api/providers/__tests__/fireworks.spec.ts | 2 + src/api/providers/__tests__/friendli.spec.ts | 8 + src/api/providers/__tests__/mimo.spec.ts | 36 +- .../__tests__/openai.cancellation.spec.ts | 333 ++++++++ src/api/providers/__tests__/openai.spec.ts | 694 +++++++++++++++- src/api/providers/__tests__/sambanova.spec.ts | 2 + .../base-openai-compatible-provider.ts | 213 +++-- src/api/providers/openai.ts | 346 ++++++-- 10 files changed, 2345 insertions(+), 126 deletions(-) create mode 100644 src/api/providers/__tests__/openai.cancellation.spec.ts diff --git a/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts b/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts index d4a4605b2f3..04a314d5c6f 100644 --- a/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts +++ b/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts @@ -13,18 +13,27 @@ import { getApiRequestTimeout } from "../utils/timeout-config" import { clearAllMocks } from "../../../test-utils/reset" -// Mock OpenAI and capture constructor calls -const mockOpenAIConstructor = vitest.fn() +// Mock OpenAI and capture constructor calls. The abort error class must stay the +// real one: error-handler classifies it with instanceof, so a stand-in would make +// the timeout assertion pass for the wrong reason. +const { mockOpenAIConstructor, mockCreate } = vitest.hoisted(() => ({ + mockOpenAIConstructor: vitest.fn(), + mockCreate: vitest.fn(), +})) -vitest.mock("openai", () => { +// The abort error class must stay the real one: error-handler classifies it with +// instanceof, so a stand-in would make the timeout assertion pass for the wrong reason. +vitest.mock("openai", async (importOriginal) => { + const actual = (await importOriginal()) as { APIUserAbortError: new () => Error } return { __esModule: true, + APIUserAbortError: actual.APIUserAbortError, default: vitest.fn().mockImplementation(function (config) { mockOpenAIConstructor(config) return { chat: { completions: { - create: vitest.fn(), + create: mockCreate, }, }, } @@ -118,4 +127,38 @@ describe("BaseOpenAiCompatibleProvider Timeout Configuration", () => { }), ) }) + + it("keeps a timeout classified as a timeout while the caller signal is still live", async () => { + vitest.mocked(getApiRequestTimeout).mockReturnValue(600000) + const provider = new TestOpenAiCompatibleProvider("test-api-key") + const controller = new AbortController() + + // The SDK reports the abort only after the merged timeout signal has fired, so + // the classification depends on the timeout reason rather than the caller signal. + const openai = await import("openai") + let requestSignal: AbortSignal | undefined + mockCreate.mockImplementation(async (_params: unknown, config: { signal?: AbortSignal }) => { + requestSignal = config.signal + // Poll the condition the classification depends on - the merged timeout signal firing - + // instead of sleeping a fixed interval that merely happens to outlast the 5 ms timeout. + await vitest.waitFor(() => { + if (!requestSignal?.aborted) { + throw new Error("the merged timeout signal has not fired yet") + } + }) + throw new openai.APIUserAbortError() + }) + + const error = await provider + .completePrompt("hi", { abortSignal: controller.signal, timeoutMs: 5 }) + .catch((caught: unknown) => caught) + + expect((error as Error).name).toBe("TimeoutError") + expect((error as Error).message).toBe("The TestProvider completion request timed out") + expect((error as Error).cause).toBeInstanceOf(openai.APIUserAbortError) + // The caller never cancelled: the timeout fired on the merged signal. + expect(controller.signal.aborted).toBe(false) + expect(requestSignal?.aborted).toBe(true) + expect(requestSignal?.reason?.name).toBe("TimeoutError") + }) }) diff --git a/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts b/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts index 1ffd63aa12a..67bbadccb74 100644 --- a/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts +++ b/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts @@ -1,18 +1,23 @@ // npx vitest run api/providers/__tests__/base-openai-compatible-provider.spec.ts import { Anthropic } from "@anthropic-ai/sdk" +import { APIUserAbortError } from "openai" import { type ModelInfo, openAiModelInfoSaneDefaults } from "@roo-code/types" import { BaseOpenAiCompatibleProvider } from "../base-openai-compatible-provider" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" +import { captureError } from "../../../test-utils/errors" +import { MAX_TIMEOUT_MS } from "../utils/abort-signal" // Create mock functions const mockCreate = vi.fn() // Mock OpenAI module vi.mock("openai", () => ({ + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, default: vi.fn(function () { return { chat: { @@ -297,6 +302,500 @@ describe("BaseOpenAiCompatibleProvider", () => { expect(firstChunk.done).toBe(false) expect(firstChunk.value).toMatchObject({ type: "usage", inputTokens: 100, outputTokens: 50 }) }) + + it("should keep the last usage when a later chunk carries none", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: {} }], + usage: { prompt_tokens: 10, completion_tokens: 5 }, + }, + { choices: [{ delta: { content: "tail" } }] }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // The recorded usage is only replaced by a chunk that actually carries + // usage; a later usage-less chunk must not wipe out the metrics. + const usageChunks = chunks.filter((chunk) => chunk.type === "usage") + expect(usageChunks).toHaveLength(1) + expect(usageChunks[0]).toMatchObject({ type: "usage", inputTokens: 10, outputTokens: 5 }) + }) + }) + + describe("stream chunk shape edge cases", () => { + it("should surface the choices access as the failure site for a null chunk", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([null, { choices: [{ delta: { content: "after" } }] }]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // A null chunk passes the base_resp guard (typeof null is "object" but + // the !== null check short-circuits) and only fails at the first choices + // access; pinning the message proves the guard is evaluated first. + expect(result.name).toBe("Error") + expect(result.message).toBe( + "TestProvider completion error: Cannot read properties of null (reading 'choices')", + ) + }) + + it("should continue streaming content after a primitive chunk", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom(["unexpected-chunk", { choices: [{ delta: { content: "after" } }] }]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + // A primitive chunk fails the base_resp guard's object check and its + // property reads short-circuit through optional chaining, so the stream + // must carry on with the next real chunk. + expect(chunks).toEqual([{ type: "text", text: "after" }]) + }) + + it("should skip an empty choices array without crashing the delta reads", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([{ choices: [] }, { choices: [{ delta: { content: "after" } }] }]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + // With no first choice, delta and finish_reason resolve to undefined; + // the optional chaining must keep the iteration alive for the next chunk. + expect(chunks).toEqual([{ type: "text", text: "after" }]) + }) + }) + + describe("abort signal wiring", () => { + it("should pass the metadata abort signal to the client request", async () => { + const controller = new AbortController() + mockCreate.mockImplementationOnce(() => asyncStreamFrom([])) + + const stream = handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + await stream.next() + + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), { + signal: controller.signal, + }) + }) + + it("should reject before issuing any request when the abort signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect(async () => { + for await (const _ of handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + })) { + // consume + } + }).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("should normalize the SDK APIUserAbortError from the stream path into the abort contract", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // The SDK error has name "Error" and a message ending in a period; the + // provider must rethrow the Task.ts contract shape instead. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should normalize a rejected-Promise APIUserAbortError from request creation", async () => { + // The provider awaits request creation so a REJECTED promise (the + // shape the SDK actually returns when the request is aborted before + // the response) reaches the abort normalization; the sync-throw test + // above would pass even if the await were removed. + mockCreate.mockRejectedValueOnce(new APIUserAbortError()) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("should normalize a rejected-Promise abort from an overriding createStream that does not await", async () => { + // Subclasses such as FriendliHandler return the SDK promise without awaiting it, + // so their own catch cannot fire. The base createMessage must normalize the + // creation-time rejection for every subclass. + class UnawaitedCreateStreamProvider extends TestOpenAiCompatibleProvider { + protected override createStream() { + return Promise.reject(new APIUserAbortError()) + } + } + + const provider = new UnawaitedCreateStreamProvider("test-api-key") + const result = await captureError( + (async () => { + for await (const _ of provider.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("should normalize an abort error raised during stream iteration into the abort contract", async () => { + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // The iterator rejects after the first chunk; the provider must normalize + // it to the Task.ts contract shape (name + message ending in "aborted"). + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should stop yielding buffered chunks and reject with the abort contract when aborted mid-stream", async () => { + let releaseSecond = () => {} + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + // The second chunk is deferred: it only becomes available after the caller + // aborts, so the loop's next for-await pull is a suspension point only the + // top-of-loop break can decide on. Removing the break leaks "world"; removing + // the post-loop check ends the stream normally instead of rejecting. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "hello " } }] } + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = handler.createMessage("system prompt", [], metadata) + + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "hello " }) + + controller.abort() + releaseSecond() + + // Anything yielded after the abort is a leak: the deferred second chunk + // must not come through an aborted stream — only the top-of-loop break + // stops the loop from processing content pulled after the abort. + const leaked: string[] = [] + const result = await captureError( + (async () => { + for await (const chunk of gen) { + if (chunk.type === "text") { + leaked.push(chunk.text) + } + } + })(), + ) + + expect(leaked).toEqual([]) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should wrap a non-abort base_resp stream error with the provider prefix through the iteration wrapper", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "partial" } }], + base_resp: { status_code: 1041, status_msg: "Invalid token" }, + }, + ]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: TestProvider API Error (1041): Invalid token") + }) + + it("should fall back to an Unknown error when a base_resp stream chunk has no status_msg", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "partial" } }], + base_resp: { status_code: 1041 }, + }, + ]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: TestProvider API Error (1041): Unknown error") + }) + + it("should ignore a zero base_resp status_code because 0 is a success sentinel", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: 0 }, + }, + ]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + expect(chunks).toEqual([{ type: "text", text: "ok" }]) + }) + + it("should ignore an empty-string base_resp status_code", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: "" }, + }, + ]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + expect(chunks).toEqual([{ type: "text", text: "ok" }]) + }) + + it("should report a string base_resp status_code with its status_msg", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + base_resp: { status_code: "1001", status_msg: "bad token" }, + }, + ]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: TestProvider API Error (1001): bad token") + }) + + it("should fall back to Unknown error when a base_resp status_msg is an empty string", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: 1041, status_msg: "" }, + }, + ]), + ) + + // Same fallback as the completePrompt path: an empty status_msg is not a + // message, so the error must not read as "API Error (1041): ". + await expect(collectStream(handler.createMessage("system prompt", []))).rejects.toThrow( + "TestProvider API Error (1041): Unknown error", + ) + }) + + it("should still report a boolean base_resp status_code, as before the guard refactor", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: true }, + }, + ]), + ) + + // The guard refactor must not change what counts as an error status: + // any truthy non-zero status_code is reported, whatever its type. + await expect(collectStream(handler.createMessage("system prompt", []))).rejects.toThrow( + "TestProvider API Error (true): Unknown error", + ) + }) + + it("should still wrap non-abort request errors with the provider prefix", async () => { + mockCreate.mockImplementationOnce(() => { + throw new Error("boom") + }) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: boom") + }) + + it("should pass the completePrompt abort signal to the client request", async () => { + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + const result = await handler.completePrompt("test prompt", { abortSignal: controller.signal }) + + expect(result).toBe("response") + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), { + signal: controller.signal, + }) + }) + + it("should merge the completePrompt abort signal and timeoutMs into one request signal", async () => { + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 5000 }) + + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + expect(requestOptions?.signal.aborted).toBe(false) + // A positive timeoutMs must be forwarded as the per-request SDK timeout. + expect(requestOptions?.timeout).toBe(5000) + // A timeout-only merged signal would still pass the assertions above; + // aborting the caller's controller proves caller cancellation survives. + controller.abort() + expect(requestOptions?.signal.aborted).toBe(true) + }) + + it("should cap an oversized completePrompt timeoutMs before handing it to the SDK", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { timeoutMs: MAX_TIMEOUT_MS + 1 }) + + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + // The SDK passes this straight to a Node timer, which clamps anything past 2^31-1 ms + // to ~1 ms: uncapped, the request would abort at once instead of waiting. + expect(requestOptions?.timeout).toBe(MAX_TIMEOUT_MS) + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + }) + + it("should omit the request timeout for a non-finite completePrompt timeoutMs", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { timeoutMs: Number.POSITIVE_INFINITY }) + + // Infinity satisfies a bare `> 0` check but is not a legal timer delay; it means + // "no explicit timeout", so no request options are sent at all. + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), undefined) + }) + + it("should abort the request when a timeout-only completePrompt timeoutMs elapses", async () => { + // Emulate the OpenAI SDK: the pending request rejects when its signal aborts. + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + // No caller signal: the timeout branch is exercised on its own. AbortSignal.timeout + // is backed by a native self-managed timer (not the fakeable global), so poll with + // vi.waitFor the same way abort-signal.spec.ts does. + const requestPromise = handler.completePrompt("test prompt", { timeoutMs: 50 }) + // Attach the rejection handler immediately so the timeout rejection + // is never observed as unhandled while we poll for the abort. + const resultPromise = captureError(requestPromise) + + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + // A timeout that fires through the merged signal is a timeout, not a user + // cancellation, so the caller must still be able to tell them apart. + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The TestProvider completion request timed out") + }) + + it("should not set a request signal for zero completePrompt timeoutMs", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { timeoutMs: 0 }) + + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), undefined) + }) + + it("should reject before any request when the completePrompt signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect( + handler.completePrompt("test prompt", { abortSignal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("should normalize the SDK APIUserAbortError from completePrompt", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError(handler.completePrompt("test prompt")) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) }) describe("getModel", () => { @@ -364,7 +863,13 @@ describe("BaseOpenAiCompatibleProvider", () => { await customHandler.completePrompt("hello") - expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "some/custom-model-not-in-list" })) + // completePrompt forwards the request config (abort signal + per-request timeout) as the + // SDK second argument. With no signal and no timeoutMs the builder returns undefined, so + // the argument is still passed - asserting it keeps the two-argument call shape pinned. + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "some/custom-model-not-in-list" }), + undefined, + ) }) }) @@ -486,5 +991,284 @@ describe("BaseOpenAiCompatibleProvider", () => { const endChunks = chunks.filter((chunk) => chunk.type === "tool_call_end") expect(endChunks).toHaveLength(0) }) + + it("should yield a tool_call_partial with undefined name and arguments when function is absent", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { tool_calls: [{ index: 0, id: "call_fn" }] } }], + }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // A first-chunk tool call may carry only its id; the optional chaining + // on function must yield undefined fields instead of throwing. + expect(chunks).toEqual([ + { type: "tool_call_partial", index: 0, id: "call_fn", name: undefined, arguments: undefined }, + ]) + }) + + it("should emit the tool_call_end after the trailing content, not before it", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + tool_calls: [ + { index: 0, id: "call_seq", function: { name: "seq_tool", arguments: "{}" } }, + ], + }, + }, + ], + }, + { choices: [{ delta: { content: "between" } }] }, + { choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // The end event must only be emitted when finish_reason arrives; + // emitting it on finish-less chunks would reorder this sequence. + expect(chunks).toEqual([ + { type: "tool_call_partial", index: 0, id: "call_seq", name: "seq_tool", arguments: "{}" }, + { type: "text", text: "between" }, + { type: "tool_call_end", id: "call_seq" }, + ]) + }) + + it("should clear the tracked tool call ids after emitting tool_call_end", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + tool_calls: [ + { index: 0, id: "call_dup", function: { name: "dup_tool", arguments: "{}" } }, + ], + }, + }, + ], + }, + { choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + { choices: [{ delta: { content: "more" } }] }, + { choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // Without the clear(), the second tool_calls finish would re-emit the + // end event for the already-finalized call. + const endChunks = chunks.filter((chunk) => chunk.type === "tool_call_end") + expect(endChunks).toEqual([{ type: "tool_call_end", id: "call_dup" }]) + }) + }) +}) + +describe("BaseOpenAiCompatibleProvider cancellation ordering (PR 1311 reviewer rows)", () => { + let handler: TestOpenAiCompatibleProvider + + beforeEach(() => { + clearAllMocks() + handler = new TestOpenAiCompatibleProvider("test-api-key") + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it("releases reasoning, content and tool events from one chunk when nothing cancels", async () => { + // Positive control for the fixture below: with no cancellation this single chunk + // yields all three event kinds, so an empty post-abort list is the guards' doing + // and not the fixture withholding content. + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + content: "plan\n\ntail", + tool_calls: [ + { index: 0, id: "call_gate", function: { name: "gate_tool", arguments: "{}" } }, + ], + }, + finish_reason: "tool_calls", + }, + ], + }, + ]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + expect(chunks.map((chunk) => chunk.type)).toEqual(["reasoning", "text", "tool_call_partial", "tool_call_end"]) + }) + + it("releases none of the remaining yields from a chunk once the caller aborts", async () => { + // The chunk above carries reasoning, content and a tool call plus its finish reason. + // Cancelling after the first yield must suppress the content and both tool events + // already parsed out of this same chunk, and the stream must reject with the abort + // contract rather than end normally after the buffered events. + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + content: "plan\n\ntail", + tool_calls: [ + { index: 0, id: "call_gate", function: { name: "gate_tool", arguments: "{}" } }, + ], + }, + finish_reason: "tool_calls", + }, + ], + }, + ]), + ) + + const controller = new AbortController() + const gen = handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await gen.next() + expect(first.done).toBe(false) + expect(first.value).toMatchObject({ type: "reasoning", text: "plan\n" }) + + controller.abort() + + const leaked: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of gen) { + leaked.push(chunk) + } + })(), + ) + + expect(leaked).toEqual([]) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("hands the captured usage record to the caller before raising the cancellation", async () => { + let releaseSecond!: () => void + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { + choices: [{ delta: { content: "hello " } }], + usage: { prompt_tokens: 3, completion_tokens: 5 }, + } + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const gen = handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await gen.next() + expect(first.value).toMatchObject({ type: "text", text: "hello " }) + + controller.abort() + releaseSecond() + + // The full post-abort list, unfiltered: the captured usage record must reach the + // caller and the deferred chunk must not. + const postAbort: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of gen) { + postAbort.push(chunk) + } + })(), + ) + + expect(postAbort).toMatchObject([{ type: "usage", inputTokens: 3, outputTokens: 5 }]) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("records the captured usage before an iterator error instead of bypassing it", async () => { + // No cancellation at all: an async iterator that fails on the next pull used to + // discard the usage record captured from the first chunk, because the catch + // normalized the error before the usage yield was reached. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { + choices: [{ delta: { content: "hello " } }], + usage: { prompt_tokens: 1, completion_tokens: 2 }, + } + throw new Error("upstream died") + })(), + ) + + const collected: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of handler.createMessage("system prompt", [])) { + collected.push(chunk) + } + })(), + ) + + expect(collected).toMatchObject([ + { type: "text", text: "hello " }, + { type: "usage", inputTokens: 1, outputTokens: 2 }, + ]) + expect(result.message).toBe("TestProvider completion error: upstream died") + }) + + it("rejects when the iterator rejects with undefined instead of completing", async () => { + // A rejection whose reason is `undefined` is still a failure. Tracking the failure only + // through the captured value made the post-loop check read "no error", so the stream + // completed normally after the partial output it had already emitted. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial " } }] } + throw undefined + })(), + ) + + const collected: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of handler.createMessage("system prompt", [])) { + collected.push(chunk) + } + })(), + ) + + expect(collected).toMatchObject([{ type: "text", text: "partial " }]) + expect(result.message).toBe("TestProvider completion error: undefined") + }) + + it("discards a completePrompt response that arrives after the caller aborted", async () => { + // The create() call resolves normally while the caller's abort lands in the same + // window: the post-await re-check must discard the response and raise the abort + // contract instead of returning its content as a completed prompt. + const controller = new AbortController() + mockCreate.mockImplementationOnce(async () => { + controller.abort() + return { choices: [{ message: { content: "answer" } }] } + }) + + await expect(handler.completePrompt("prompt", { abortSignal: controller.signal })).rejects.toMatchObject({ + name: "AbortError", + message: "The TestProvider request was aborted", + }) }) }) diff --git a/src/api/providers/__tests__/fireworks.spec.ts b/src/api/providers/__tests__/fireworks.spec.ts index 480f965894d..a7d27486d3e 100644 --- a/src/api/providers/__tests__/fireworks.spec.ts +++ b/src/api/providers/__tests__/fireworks.spec.ts @@ -23,6 +23,8 @@ vi.mock("openai", () => ({ }, } }), + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, })) describe("FireworksHandler", () => { diff --git a/src/api/providers/__tests__/friendli.spec.ts b/src/api/providers/__tests__/friendli.spec.ts index 1ff1b1475ba..dc514af0ac6 100644 --- a/src/api/providers/__tests__/friendli.spec.ts +++ b/src/api/providers/__tests__/friendli.spec.ts @@ -25,6 +25,14 @@ vi.mock("../fetchers/friendli", () => ({ getFriendliModels: mockGetFriendliModel // Mock OpenAI module vi.mock("openai", () => ({ + // 1311 adds an APIUserAbortError import at api/providers/utils/error-handler.ts:12 and reads + // it in handleOpenAIRequestError at :150 and :160, so a mock without that named export lets + // vitest's missing-export error replace the 401 job 129957461109 saw asserted at + // friendli.spec.ts:104:29 (2 failed of 66 twice at this head against 66 passed twice at + // main tip 18861b2e3572, CI ubuntu and local Windows agreeing exactly). Ten sibling + // provider specs already stub the export; this mock joins them rather than bending + // production error handling around a test double. + APIUserAbortError: class extends Error {}, default: vi.fn(function () { return { chat: { diff --git a/src/api/providers/__tests__/mimo.spec.ts b/src/api/providers/__tests__/mimo.spec.ts index 062d2fd9228..acafdb14dc0 100644 --- a/src/api/providers/__tests__/mimo.spec.ts +++ b/src/api/providers/__tests__/mimo.spec.ts @@ -4,6 +4,10 @@ import { clearAllMocks } from "../../../test-utils/reset" vi.mock("openai", () => { return { __esModule: true, + // The provider normalizes an aborted request out of an APIUserAbortError, so the mock has to + // export the class: without it the module under test destructures undefined and every abort + // row here would throw before it reaches the handler. + APIUserAbortError: class extends Error {}, default: vi.fn().mockImplementation(function () { return { chat: { @@ -39,6 +43,12 @@ import { MimoHandler } from "../mimo" import { convertToR1Format } from "../../transform/r1-format" import { sanitizeOpenAiCallId } from "../../../utils/tool-id" +// The wrapped error carries the HTTP status that Task.backoffAndAnnounce uses for its retry +// header. Read it through a shape check rather than widening the error type. +function preservedStatus(error: unknown): number | undefined { + return error instanceof Error && "status" in error ? (error as Error & { status: number }).status : undefined +} + describe("MimoHandler", () => { let handler: MimoHandler let mockOptions: ApiHandlerOptions @@ -891,9 +901,14 @@ describe("MimoHandler", () => { }) it("should handle API errors with provider prefix", async () => { - mockCreate.mockRejectedValueOnce(new Error("401 Unauthorized")) + mockCreate.mockRejectedValueOnce(Object.assign(new Error("401 Unauthorized"), { status: 401 })) - await expect(handler.completePrompt("Test prompt")).rejects.toThrow("OpenAI completion error:") + const failure = await handler.completePrompt("Test prompt").catch((error: unknown) => error) + // The prefix alone would pass on a wrapper that dropped the reason. Pin the text the SDK + // reported as well, and the status that Task.backoffAndAnnounce reads to pick a retry. + expect(failure).toBeInstanceOf(Error) + expect((failure as Error).message).toContain("OpenAI completion error: 401 Unauthorized") + expect(preservedStatus(failure)).toBe(401) }) it("should return empty string when choices array is empty", async () => { @@ -915,13 +930,24 @@ describe("MimoHandler", () => { it("should propagate network errors with provider prefix", async () => { mockCreate.mockRejectedValueOnce(new Error("ECONNREFUSED")) - await expect(handler.completePrompt("Test prompt")).rejects.toThrow("OpenAI completion error:") + const failure = await handler.completePrompt("Test prompt").catch((error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + // Containment for the same reason as the row above: the doubled prefix is real output of this + // path and is left as its own question rather than pinned as the expected shape. + expect((failure as Error).message).toContain("OpenAI completion error: ECONNREFUSED") + // A connection failure carries no HTTP status, and the wrapper must not invent one: a + // fabricated status would reach the retry header as a number nobody earned. + expect(preservedStatus(failure)).toBeUndefined() }) it("should propagate rate limit errors with provider prefix", async () => { - mockCreate.mockRejectedValueOnce(new Error("429 Too Many Requests")) + mockCreate.mockRejectedValueOnce(Object.assign(new Error("429 Too Many Requests"), { status: 429 })) - await expect(handler.completePrompt("Test prompt")).rejects.toThrow("OpenAI completion error:") + const failure = await handler.completePrompt("Test prompt").catch((error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + expect((failure as Error).message).toContain("OpenAI completion error: 429 Too Many Requests") + // 429 is the status that decides the backoff, so it has to survive the wrap. + expect(preservedStatus(failure)).toBe(429) }) it("should use correct model ID for mimo-v2.5 variant", async () => { diff --git a/src/api/providers/__tests__/openai.cancellation.spec.ts b/src/api/providers/__tests__/openai.cancellation.spec.ts new file mode 100644 index 00000000000..4e8d035b451 --- /dev/null +++ b/src/api/providers/__tests__/openai.cancellation.spec.ts @@ -0,0 +1,333 @@ +// npx vitest run api/providers/__tests__/openai.cancellation.spec.ts + +import { OpenAiHandler } from "../openai" +import { makeApiHandlerOptions, makeCreateMessageMetadata } from "../../../test-utils/api" +import { asyncStreamFrom } from "../../../test-utils/stream" +import type { ApiStreamChunk } from "../../transform/stream" + +vitest.mock("../utils/timeout-config", () => ({ + getApiRequestTimeout: vitest.fn().mockReturnValue(300_000), +})) + +const mockCreate = vitest.fn() + +vitest.mock("openai", () => { + const mockConstructor = vitest.fn() + return { + __esModule: true, + APIUserAbortError: class extends Error {}, + default: mockConstructor.mockImplementation(function () { + return { chat: { completions: { create: mockCreate } } } + }), + } +}) + +const standardHandler = () => + new OpenAiHandler( + makeApiHandlerOptions({ + openAiApiKey: "test-api-key", + openAiModelId: "gpt-4", + openAiBaseUrl: "https://api.openai.com/v1", + }), + ) + +// The O-series dispatch is a model-id check in createMessage, so the same construct is reached +// through an o3 model id on the same handler class. +const oSeriesHandler = (streamingEnabled = true) => + new OpenAiHandler( + makeApiHandlerOptions({ + openAiApiKey: "test-api-key", + openAiModelId: "o3-mini", + openAiBaseUrl: "https://api.openai.com/v1", + openAiStreamingEnabled: streamingEnabled, + }), + ) + +const standardNonStreamingHandler = () => + new OpenAiHandler( + makeApiHandlerOptions({ + openAiApiKey: "test-api-key", + openAiModelId: "gpt-4", + openAiBaseUrl: "https://api.openai.com/v1", + openAiStreamingEnabled: false, + }), + ) + +const toolCall = (index: number, id: string) => ({ + index, + id, + type: "function", + function: { name: "test_tool_" + String(index), arguments: '{"arg":' + String(index) + "}" }, +}) + +const usageFixture = { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } + +const nonStreamingResponse = (message: Record) => ({ + id: "test-completion", + choices: [{ message: { role: "assistant", refusal: null, ...message }, finish_reason: "stop", index: 0 }], + usage: usageFixture, +}) + +/** + * Consume a stream lazily, cancel the caller the moment its first event arrives, and record + * every event that still reaches the caller afterwards. The assertions ask the question the row + * asks - the complete subsequent event array must be empty - rather than checking only the + * events the provider happens to drop. + */ +async function cancelAtFirstEvent(handler: OpenAiHandler): Promise<{ + preAbort: ApiStreamChunk[] + postAbort: ApiStreamChunk[] + failure: unknown +}> { + const controller = new AbortController() + const preAbort: ApiStreamChunk[] = [] + const postAbort: ApiStreamChunk[] = [] + const consuming = (async () => { + try { + for await (const event of handler.createMessage( + "system prompt", + [], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + )) { + if (preAbort.length === 0) { + preAbort.push(event) + controller.abort() + continue + } + postAbort.push(event) + } + return null + } catch (error) { + return error + } + })() + return { preAbort, postAbort, failure: await consuming } +} + +/** + * Resolve the mocked request only once the caller has cancelled: the arrived answer exists, and + * the provider is the one that has to decide what to do with it. + */ +function resolveAfterCallerCancels(controller: AbortController, value: unknown) { + mockCreate.mockImplementationOnce(() => { + if (controller.signal.aborted) { + return Promise.resolve(value) + } + return new Promise((resolve) => { + controller.signal.addEventListener("abort", () => resolve(value), { once: true }) + }) + }) +} + +const expectAbortContract = (failure: unknown) => { + const error = failure as Error + expect(error?.name, JSON.stringify(failure)).toBe("AbortError") + expect(error.message.endsWith("request was aborted"), error.message).toBe(true) +} + +describe("OpenAiHandler cancellation", () => { + beforeEach(() => { + mockCreate.mockReset() + }) + + describe("streaming: no events after the caller cancels", () => { + it("releases nothing left in a chunk that mixed reasoning, content and tool calls (standard OpenAI)", async () => { + // One chunk carries every event class at once: reasoning, content, two tool-call + // partials and the finish_reason that would finalize them. A cancellation landing after + // the first event must stop the rest instead of draining the chunk. + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + reasoning_content: "thinking", + content: "tail", + tool_calls: [toolCall(0, "call_1"), toolCall(1, "call_2")], + }, + finish_reason: "tool_calls", + index: 0, + }, + ], + }, + ]), + ) + + const { preAbort, postAbort, failure } = await cancelAtFirstEvent(standardHandler()) + + // The reasoning event is what the cancellation lands on: with it dropped, the helper would + // cancel after the text event instead and this row would stop pinning the transition. + expect(preAbort).toEqual([{ type: "reasoning", text: "thinking" }]) + expect(postAbort).toEqual([]) + expectAbortContract(failure) + }) + + it("releases nothing left in a chunk that mixed content and tool calls (O-series)", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { content: "tail", tool_calls: [toolCall(0, "call_1"), toolCall(1, "call_2")] }, + finish_reason: "tool_calls", + index: 0, + }, + ], + }, + ]), + ) + + const { preAbort, postAbort, failure } = await cancelAtFirstEvent(oSeriesHandler()) + + expect(preAbort).toEqual([{ type: "text", text: "tail" }]) + expect(postAbort).toEqual([]) + expectAbortContract(failure) + }) + }) + + describe("non-streaming: the signal is re-read after the response arrives", () => { + const mixedToolCallResponse = nonStreamingResponse({ + content: "answer", + tool_calls: [toolCall(0, "call_1")], + }) + + const drainUntilCancelled = async (handler: OpenAiHandler, controller: AbortController) => { + const released: ApiStreamChunk[] = [] + const done = (async () => { + try { + for await (const event of handler.createMessage( + "system prompt", + [], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + )) { + released.push(event) + } + return null + } catch (error) { + return error + } + })() + controller.abort() + return { released, failure: await done } + } + + it("discards the arrived text and tool calls when the caller cancelled in flight (standard OpenAI)", async () => { + const controller = new AbortController() + resolveAfterCallerCancels(controller, mixedToolCallResponse) + + const { released, failure } = await drainUntilCancelled(standardNonStreamingHandler(), controller) + + expect(released).toEqual([]) + expectAbortContract(failure) + }) + + it("discards the arrived text and tool calls when the caller cancelled in flight (O-series)", async () => { + const controller = new AbortController() + resolveAfterCallerCancels(controller, mixedToolCallResponse) + + const { released, failure } = await drainUntilCancelled(oSeriesHandler(false), controller) + + expect(released).toEqual([]) + expectAbortContract(failure) + }) + + it("does not report a completed prompt when the caller cancelled while the answer was in flight", async () => { + const controller = new AbortController() + // The answer is resolved first and the stop is queued behind it: the answer wins the request + // race, so only the post-response signal check can keep it from being reported as completed. + mockCreate.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveAnswer = resolve + }), + ) + let resolveAnswer: (value: unknown) => void = () => {} + + const handler = standardNonStreamingHandler() + const answered = handler.completePrompt("prompt", { abortSignal: controller.signal }) + resolveAnswer(nonStreamingResponse({ content: "answer" })) + queueMicrotask(() => controller.abort()) + const failure = await answered.then( + (): unknown => null, + (error: unknown) => error, + ) + + expectAbortContract(failure) + }) + }) + + describe("non-streaming: the signal is re-read between content yields", () => { + // A yield suspends the generator, so a cancellation can land between two pieces of one arrived + // response. Each case cancels after a given number of events and then asks which events still + // reach the caller. + const cancelAfterEvents = async (handler: OpenAiHandler, pulls: number) => { + const controller = new AbortController() + const released: ApiStreamChunk[] = [] + const draining = (async () => { + try { + for await (const event of handler.createMessage( + "system prompt", + [], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + )) { + released.push(event) + if (released.length === pulls) { + controller.abort() + } + } + return null + } catch (error) { + return error + } + })() + return { released, failure: await draining } + } + + const twoToolCalls = nonStreamingResponse({ + content: "answer", + tool_calls: [toolCall(0, "call_1"), toolCall(1, "call_2")], + }) + const oneToolCall = nonStreamingResponse({ content: "answer", tool_calls: [toolCall(0, "call_1")] }) + + // openai.ts carries the non-streaming body twice: the standard dispatch and the O-series + // dispatch, so both are checked. + describe.each([ + { label: "standard OpenAI", makeHandler: standardNonStreamingHandler }, + { label: "O-series", makeHandler: () => oSeriesHandler(false) }, + ])("$label", ({ makeHandler }) => { + it("stops before the second tool call when the caller cancels after the first one", async () => { + mockCreate.mockImplementationOnce(async () => twoToolCalls) + + const { released, failure } = await cancelAfterEvents(makeHandler(), 1) + + expect(released).toEqual([ + { type: "tool_call", id: "call_1", name: "test_tool_0", arguments: '{"arg":0}' }, + ]) + expectAbortContract(failure) + }) + + it("stops before the text that follows the last tool call", async () => { + mockCreate.mockImplementationOnce(async () => oneToolCall) + + const { released, failure } = await cancelAfterEvents(makeHandler(), 1) + + expect(released).toEqual([ + { type: "tool_call", id: "call_1", name: "test_tool_0", arguments: '{"arg":0}' }, + ]) + expectAbortContract(failure) + }) + + it("stops before the usage event that follows the text", async () => { + mockCreate.mockImplementationOnce(async () => oneToolCall) + + const { released, failure } = await cancelAfterEvents(makeHandler(), 2) + + expect(released).toEqual([ + { type: "tool_call", id: "call_1", name: "test_tool_0", arguments: '{"arg":0}' }, + { type: "text", text: "answer" }, + ]) + expectAbortContract(failure) + }) + }) + }) +}) diff --git a/src/api/providers/__tests__/openai.spec.ts b/src/api/providers/__tests__/openai.spec.ts index c07ac2a3028..b77d2feaec1 100644 --- a/src/api/providers/__tests__/openai.spec.ts +++ b/src/api/providers/__tests__/openai.spec.ts @@ -9,7 +9,7 @@ import { prepareApiConversationMessage } from "../../../core/task/apiConversatio import { OpenAiHandler, getOpenAiModels } from "../openai" import { ApiHandlerOptions } from "../../../shared/api" import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI, { AzureOpenAI } from "openai" +import OpenAI, { AzureOpenAI, APIUserAbortError } from "openai" import { openAiModelInfoSaneDefaults, DEEP_SEEK_DEFAULT_TEMPERATURE, @@ -20,7 +20,10 @@ import { import { Package } from "../../../shared/package" import { makeApiHandlerOptions, makeCreateMessageMetadata } from "../../../test-utils/api" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +import { captureError } from "../../../test-utils/errors" + import { expectNoLoneSurrogates } from "../../../test-utils/surrogates" +import { MAX_TIMEOUT_MS } from "../utils/abort-signal" import axios from "axios" import { signedAssistantMessage, @@ -41,8 +44,10 @@ const mockResponsesCreate = vitest.fn() vitest.mock("openai", () => { const mockConstructor = vitest.fn() const mockAzureConstructor = vitest.fn() + const APIUserAbortError = class extends Error {} return { __esModule: true, + APIUserAbortError, default: mockConstructor.mockImplementation(function (options: { baseURL: string }) { return { baseURL: options.baseURL, @@ -502,6 +507,139 @@ describe("OpenAiHandler", () => { expect(textChunks[0].text).toBe("Test response") }) + it("should treat a streaming chunk without a delta as an empty delta", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([ + { choices: [{ delta: { content: "hello " }, index: 0 }] }, + // Some providers emit a final chunk with no delta field at all; the + // iteration must fall back to an empty object and not throw. + { choices: [{ finish_reason: "stop", index: 0 }] }, + ]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + const textChunks = chunks.filter((chunk) => chunk.type === "text") + expect(textChunks).toEqual([{ type: "text", text: "hello " }]) + }) + + it("should treat a streaming chunk without choices as an empty delta", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([ + { usage: { prompt_tokens: 1, completion_tokens: 2 } }, + { choices: [{ delta: { content: "tail" }, index: 0 }] }, + ]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + // A usage-only chunk has no choices at all; the optional chaining must + // resolve to the empty-delta fallback instead of throwing. + const textChunks = chunks.filter((chunk) => chunk.type === "text") + expect(textChunks).toEqual([{ type: "text", text: "tail" }]) + }) + + it("yields a recorded usage chunk ahead of the abort verdict when the stream is cancelled after the usage chunk", async () => { + // The abort verdict must not swallow usage the stream already reported: Task.ts prices the task + // from usage events, and the tokens behind a chunk that carried usage are spent whether or not + // the caller stops before the stream ends. Buffered matcher content stays suppressed. + const controller = new AbortController() + mockCreate.mockImplementationOnce(async () => + (async function* () { + yield { + choices: [{ delta: { content: "partial " }, index: 0 }], + usage: { prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 }, + } + controller.abort() + yield { choices: [{ delta: {}, index: 0 }] } + })(), + ) + + const emitted: Array<{ type: string; inputTokens?: number; outputTokens?: number }> = [] + let failure: Error | undefined + const stream = handler.createMessage( + systemPrompt, + messages, + makeCreateMessageMetadata({ abortSignal: controller.signal }), + ) + try { + for await (const chunk of stream) { + emitted.push(chunk) + } + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + + expect(emitted.map((chunk) => chunk.type)).toEqual(["text", "usage"]) + // Task.ts prices the task from the counts, not from the event type: a usage event with + // zero tokens would satisfy an assertion that only reads `type`. + expect(emitted[1]).toMatchObject({ inputTokens: 11, outputTokens: 7 }) + expect(failure?.name).toBe("AbortError") + expect(failure?.message).toBe("The OpenAI request was aborted") + }) + it("yields the recorded usage before an iterator error instead of discarding it", async () => { + // A stream that recorded usage and then failed on the next pull used to lose that record: + // the catch normalized the error before the usage yield was reached, so Task.ts never + // priced the tokens the stream had already reported. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { + choices: [{ delta: { content: "partial " }, index: 0 }], + usage: { prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 }, + } + throw new Error("upstream died") + })(), + ) + + const collected: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of handler.createMessage(systemPrompt, messages)) { + collected.push(chunk) + } + })(), + ) + + expect(collected).toMatchObject([ + { type: "text", text: "partial " }, + { type: "usage", inputTokens: 11, outputTokens: 7 }, + ]) + expect(result.message).toBe("OpenAI completion error: upstream died") + }) + + it("should treat a streaming chunk with an empty choices array as an empty delta", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([{ choices: [] }, { choices: [{ delta: { content: "tail" }, index: 0 }] }]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + // With no first choice, delta and finish_reason resolve to undefined; + // the optional chaining must keep the iteration alive for the next chunk. + const textChunks = chunks.filter((chunk) => chunk.type === "text") + expect(textChunks).toEqual([{ type: "text", text: "tail" }]) + }) + + it("should keep the last usage when a later chunk carries none", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([ + { + choices: [{ delta: { content: "hi" }, index: 0 }], + usage: { prompt_tokens: 7, completion_tokens: 3, total_tokens: 10 }, + }, + { choices: [{ delta: {}, index: 0 }] }, + ]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + // The recorded usage is only replaced by a chunk that actually carries + // usage; a later usage-less chunk must not wipe out the metrics. + const usageChunks = chunks.filter((chunk) => chunk.type === "usage") + expect(usageChunks).toHaveLength(1) + expect(usageChunks[0]).toMatchObject({ type: "usage", inputTokens: 7, outputTokens: 3 }) + }) + it("should forward the task abortSignal to streaming requests", async () => { const controller = new AbortController() @@ -1230,6 +1368,551 @@ describe("OpenAiHandler", () => { }) }) + describe("abort signal wiring", () => { + // toHaveBeenCalledWith compares arguments by value, so two live AbortSignals in the same state + // compare equal; the forwarded signal is the caller's own object or it is not, so it is read + // back and checked by identity. + const capturedRequestOptions = () => + mockCreate.mock.calls.at(-1)?.[1] as { path?: string; signal?: AbortSignal } | undefined + + it("should pass the metadata abort signal to the streaming createMessage request", async () => { + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = handler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: mockOptions.openAiModelId, stream: true }), + expect.anything(), + ) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should pass the metadata abort signal to the non-streaming createMessage request", async () => { + const nonStreamingHandler = new OpenAiHandler({ ...mockOptions, openAiStreamingEnabled: false }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = nonStreamingHandler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: mockOptions.openAiModelId }), + expect.anything(), + ) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should pass the metadata abort signal to the o3-family streaming request", async () => { + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = o3Handler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "o3-mini", stream: true }), + expect.anything(), + ) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should pass the metadata abort signal to the o3-family non-streaming request", async () => { + const o3Handler = new OpenAiHandler({ + ...mockOptions, + openAiModelId: "o3-mini", + openAiStreamingEnabled: false, + }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = o3Handler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "o3-mini" }), expect.anything()) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should keep the Azure AI Inference path while passing the abort signal", async () => { + const azureHandler = new OpenAiHandler({ + ...mockOptions, + openAiBaseUrl: "https://test.services.ai.azure.com", + openAiModelId: "deepseek-v3", + }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = azureHandler.createMessage("system prompt", [], metadata) + await gen.next() + expect(capturedRequestOptions()).toMatchObject({ path: "/models/chat/completions" }) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + // The Azure path test above covers createMessage and the completePrompt signal test + // uses a non-Azure handler; neither pins both options in one request config, which is + // what the Azure completePrompt branch composes (path + merged signal). + it("should keep the Azure AI Inference path while passing the completePrompt abort signal", async () => { + const azureHandler = new OpenAiHandler({ + ...mockOptions, + openAiBaseUrl: "https://test.services.ai.azure.com", + openAiModelId: "deepseek-v3", + }) + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await expect(azureHandler.completePrompt("test prompt", { abortSignal: controller.signal })).resolves.toBe( + "response", + ) + + expect(capturedRequestOptions()).toMatchObject({ path: "/models/chat/completions" }) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + it("should pass the completePrompt abort signal to the request", async () => { + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + const result = await handler.completePrompt("test prompt", { abortSignal: controller.signal }) + expect(result).toBe("response") + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should merge the completePrompt abort signal and timeout into a single request signal", async () => { + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 5000 }) + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + expect(requestOptions?.signal.aborted).toBe(false) + // The merged signal must follow the caller's controller: a regression + // that drops options.abortSignal (keeping only the timeout signal) + // would stop aborting here and fail the test. + controller.abort() + expect(requestOptions?.signal.aborted).toBe(true) + // A positive timeoutMs must be forwarded as the per-request SDK timeout. + expect(requestOptions?.timeout).toBe(5000) + }) + + it("should abort the merged request signal on the deadline while the caller signal stays live", async () => { + // The two-input branch has to merge both inputs, not forward one of them: the timeout-only + // row below cannot reach this branch, so forwarding just the raw caller signal would pass + // that row and park here forever. + const controller = new AbortController() + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const resultPromise = captureError( + handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 50 }), + ) + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + // Nobody pressed stop: the deadline expired and the caller's own signal is still live. + expect(controller.signal.aborted).toBe(false) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The OpenAI completion request timed out") + }) + + it("should pass a timeout-only request signal when completePrompt timeoutMs is positive", async () => { + // The request must actually observe the merged signal firing: resolving the mock + // immediately only proves a signal was passed, not that a live (non-aborted) + // one aborts on timeout. Keep the request parked until its signal aborts, then + // assert the abort plus the retained timeout and error contract. + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const requestPromise = handler.completePrompt("test prompt", { timeoutMs: 50 }) + const resultPromise = captureError(requestPromise) + + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + // The timeout classification must survive the outer catch, which otherwise + // re-normalizes every abort as a user cancellation. + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The OpenAI completion request timed out") + }) + + it("should not pass a request signal for zero timeoutMs in completePrompt", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + await handler.completePrompt("test prompt", { timeoutMs: 0 }) + expect(mockCreate).toHaveBeenCalledWith(expect.anything(), {}) + }) + + it("should cap an oversized completePrompt timeoutMs before handing it to the SDK", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + await handler.completePrompt("test prompt", { timeoutMs: MAX_TIMEOUT_MS + 1 }) + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + // The merged abort signal already caps the delay; the SDK timeout option is the + // same value, because an uncapped one is clamped to ~1 ms by the timer itself. + expect(requestOptions?.timeout).toBe(MAX_TIMEOUT_MS) + }) + + it("should omit the request timeout for a non-finite completePrompt timeoutMs", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + await handler.completePrompt("test prompt", { timeoutMs: Number.POSITIVE_INFINITY }) + // Infinity passes a bare `> 0` check but is not a legal timer delay, so it must + // mean "no explicit timeout" rather than reaching the SDK. + expect(mockCreate).toHaveBeenCalledWith(expect.anything(), {}) + }) + + it("should reject before issuing any request when the abort signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + await expect( + (async () => { + for await (const _ of handler.createMessage("system prompt", [], metadata)) { + // consume + } + })(), + ).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + expect(mockCreate).not.toHaveBeenCalled() + + mockCreate.mockClear() + await expect( + handler.completePrompt("test prompt", { abortSignal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("should normalize the SDK APIUserAbortError from the streaming path into the abort contract", async () => { + const controller = new AbortController() + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [], metadata)) { + // consume + } + })(), + ) + // The SDK error has name "Error" and a message ending in a period; the + // provider must rethrow the Task.ts contract shape instead. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should normalize an abort error raised during stream iteration into the abort contract", async () => { + const controller = new AbortController() + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [], metadata)) { + // consume + } + })(), + ) + + // The iterator rejects after the first chunk; the provider must normalize + // it to the Task.ts contract shape instead of leaking the raw SDK error. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("stops a second pull that is already pending and rejects with the abort contract", async () => { + let releaseSecond = () => {} + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + // The second chunk is deferred and the caller cancels while that pull is still in + // flight. The for-await has already pulled it, so only the top-of-loop break stops the + // chunk from being processed: removing the break leaks "world", and removing the + // post-loop check ends the stream normally instead of rejecting. + let secondPullStarted = false + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "hello " } }] } + secondPullStarted = true + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = handler.createMessage("system prompt", [], metadata) + + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "hello " }) + + const pendingPull = gen.next() + // Cancel while the pull is pending rather than before it starts: that is the + // interleaving the deferred chunk exists to create. + await vi.waitFor(() => expect(secondPullStarted).toBe(true)) + controller.abort() + releaseSecond() + + const leaked: string[] = [] + let failure: Error | undefined + try { + const pulled = await pendingPull + if (pulled.value?.type === "text") { + leaked.push(pulled.value.text) + } + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + + expect(leaked).toEqual([]) + expect(failure?.name).toBe("AbortError") + expect(failure?.message).toBe("The OpenAI request was aborted") + }) + + it("stops a second pull that is already pending and rejects with the abort contract (o3 family)", async () => { + let releaseSecond = () => {} + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + // The second chunk is deferred and the caller cancels while that pull is still in + // flight. The for-await has already pulled it, so only the top-of-loop break stops the + // chunk from being processed: removing the break leaks "world", and removing the + // post-loop check ends the stream normally instead of rejecting. + let secondPullStarted = false + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "hello " } }] } + secondPullStarted = true + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const gen = o3Handler.createMessage("system prompt", [], metadata) + + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "hello " }) + + const pendingPull = gen.next() + // Cancel while the pull is pending rather than before it starts: that is the + // interleaving the deferred chunk exists to create. + await vi.waitFor(() => expect(secondPullStarted).toBe(true)) + controller.abort() + releaseSecond() + + const leaked: string[] = [] + let failure: Error | undefined + try { + const pulled = await pendingPull + if (pulled.value?.type === "text") { + leaked.push(pulled.value.text) + } + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + + expect(leaked).toEqual([]) + expect(failure?.name).toBe("AbortError") + expect(failure?.message).toBe("The OpenAI request was aborted") + }) + + it("should wrap a non-abort stream error with the provider prefix when no metadata is passed", async () => { + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new Error("mid-stream boom") + })(), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // Without metadata there is no abort signal to consult; the raw error + // must still be normalized through the completion-error wrapper. + expect(result.name).toBe("Error") + expect(result.message).toBe("OpenAI completion error: mid-stream boom") + }) + + it("should normalize the SDK APIUserAbortError from completePrompt without an external signal", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const result = await captureError(handler.completePrompt("test prompt")) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize a fetch-level AbortError from completePrompt into the abort contract", async () => { + const fetchAbort = new Error("The operation was aborted.") + fetchAbort.name = "AbortError" + mockCreate.mockImplementationOnce(() => { + throw fetchAbort + }) + const result = await captureError(handler.completePrompt("test prompt")) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.cause).toBe(fetchAbort) + }) + + // The Responses route hands the caller's options straight to the SDK, so an + // APIUserAbortError raised after the signal is aborted reaches completePrompt's outer + // catch without going through the request-site handler. That is the one path that + // rebuilds the contract error, and the rebuild has to carry the failure that caused it. + it("keeps the SDK abort as the cause when the Responses route rejects it mid-flight", async () => { + const responsesHandler = new OpenAiHandler({ ...mockOptions, openAiUseResponsesApi: true }) + const controller = new AbortController() + const sdkAbort = new APIUserAbortError() + mockResponsesCreate.mockImplementationOnce(() => { + controller.abort() + throw sdkAbort + }) + const result = await captureError( + responsesHandler.completePrompt("test prompt", { abortSignal: controller.signal }), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.cause).toBe(sdkAbort) + }) + + // A native AbortError (the shape fetch raises) has no SDK identity to classify it by, so the + // Responses branch has to normalize it at its own request site: the outer catch rethrows an + // error whose name already reads AbortError, which would surface the transport's wording and + // drop the provider contract the rest of the abort paths pin. + it("normalizes a native abort raised by the Responses completion request", async () => { + const responsesHandler = new OpenAiHandler({ ...mockOptions, openAiUseResponsesApi: true }) + const controller = new AbortController() + const nativeAbort = new Error("The operation was aborted.") + nativeAbort.name = "AbortError" + mockResponsesCreate.mockImplementationOnce(() => { + controller.abort() + throw nativeAbort + }) + const result = await captureError( + responsesHandler.completePrompt("test prompt", { abortSignal: controller.signal }), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.cause).toBe(nativeAbort) + }) + + it("should normalize the SDK APIUserAbortError from the non-streaming createMessage path", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const noStreamHandler = new OpenAiHandler({ ...mockOptions, openAiStreamingEnabled: false }) + const result = await captureError( + (async () => { + for await (const _ of noStreamHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize the SDK APIUserAbortError from the o3-family streaming path", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const result = await captureError( + (async () => { + for await (const _ of o3Handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize an abort error raised during o3-family stream iteration into the abort contract", async () => { + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const result = await captureError( + (async () => { + for await (const _ of o3Handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // handleStreamResponse consumes the iterator; a mid-stream abort must be + // normalized to the Task.ts contract shape, not leak as the raw SDK error. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize the SDK APIUserAbortError from the o3-family non-streaming path", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const o3Handler = new OpenAiHandler({ + ...mockOptions, + openAiModelId: "o3-mini", + openAiStreamingEnabled: false, + }) + const result = await captureError( + (async () => { + for await (const _ of o3Handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should still wrap non-abort completion errors with the provider prefix", async () => { + mockCreate.mockImplementationOnce(() => { + throw new Error("boom") + }) + const result = await captureError(handler.completePrompt("test prompt")) + expect(result.name).toBe("Error") + // The inner catch already wraps with the provider prefix and the outer + // catch wraps again (pre-existing double-wrap of openai.ts completePrompt). + expect(result.message).toBe("OpenAI completion error: OpenAI completion error: boom") + }) + }) + describe.each([ { name: "streaming chat", openAiModelId: "custom-model", streaming: true, singleCompletion: false }, { name: "non-streaming chat", openAiModelId: "custom-model", streaming: false, singleCompletion: false }, @@ -2699,8 +3382,15 @@ describe("OpenAiHandler Responses API (openAiUseResponsesApi)", () => { store: false, service_tier: "flex", }), - { signal: controller.signal, timeout: 1234 }, + expect.anything(), ) + // The request carries the merged caller and deadline signal, so the deadline stays armed + // while the SDK reads the JSON body. + const responseOptions = mockResponsesCreate.mock.calls[0][1] + expect(responseOptions.timeout).toBe(1234) + expect(responseOptions.signal?.aborted).toBe(false) + controller.abort() + expect(responseOptions.signal?.aborted).toBe(true) expectNoLoneSurrogates(mockResponsesCreate.mock.calls[0][0]) }, ) diff --git a/src/api/providers/__tests__/sambanova.spec.ts b/src/api/providers/__tests__/sambanova.spec.ts index 2a19d5659c4..18636f9c4ff 100644 --- a/src/api/providers/__tests__/sambanova.spec.ts +++ b/src/api/providers/__tests__/sambanova.spec.ts @@ -15,6 +15,8 @@ vitest.mock("openai", () => { default: vitest.fn(function () { return { chat: { completions: { create: createMock } } } }), + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, } }) diff --git a/src/api/providers/base-openai-compatible-provider.ts b/src/api/providers/base-openai-compatible-provider.ts index b177726f852..17441e7ff8b 100644 --- a/src/api/providers/base-openai-compatible-provider.ts +++ b/src/api/providers/base-openai-compatible-provider.ts @@ -6,14 +6,17 @@ import { type ModelInfo, openAiModelInfoSaneDefaults } from "@roo-code/types" import { type ApiHandlerOptions, getModelMaxOutputTokens } from "../../shared/api" import { TagMatcher } from "../../utils/tag-matcher" import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" +import { handleOpenAIRequestError } from "./utils/error-handler" import { convertToOpenAiMessages } from "../transform/openai-format" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" import { DEFAULT_HEADERS } from "./constants" import { BaseProvider } from "./base-provider" -import { handleOpenAIError } from "./utils/error-handler" import { calculateApiCostOpenAI } from "../../shared/cost" import { extractReasoningFromDelta } from "./utils/extract-reasoning" +import { RequestConfigBuilder } from "./config-builder/request-config-builder" +import { createAbortError, mergeAbortSignalAndTimeout, rejectOnAbort, throwIfAborted } from "./utils/abort-signal" +import { getRequestTimeoutMs } from "./utils/request-timeout" type BaseOpenAiCompatibleProviderOptions = ApiHandlerOptions & { providerName: string @@ -23,6 +26,13 @@ type BaseOpenAiCompatibleProviderOptions = ApiHandlerO defaultTemperature?: number } +/** Subset of OpenAI.RequestOptions built per request for the abort-signal wiring. */ +type OpenAiRequestConfig = { + signal?: AbortSignal + /** Per-request SDK timeout (ms); overrides the client-level default when set. */ + timeout?: number +} + export abstract class BaseOpenAiCompatibleProvider extends BaseProvider implements SingleCompletionHandler @@ -67,7 +77,7 @@ export abstract class BaseOpenAiCompatibleProvider }) } - protected createStream( + protected async createStream( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, @@ -103,11 +113,10 @@ export abstract class BaseOpenAiCompatibleProvider ;(params as any).thinking = { type: "enabled" } } - try { - return this.client.chat.completions.create(params, requestOptions) - } catch (error) { - throw handleOpenAIError(error, this.providerName) - } + // Creation errors are normalized once in createMessage: subclasses can override this + // method and return the SDK promise without awaiting it, so a catch here would not + // cover every provider. + return await this.client.chat.completions.create(params, requestOptions) } override async *createMessage( @@ -115,7 +124,27 @@ export abstract class BaseOpenAiCompatibleProvider messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { - const stream = await this.createStream(systemPrompt, messages, metadata) + throwIfAborted(metadata?.abortSignal) + const signal = metadata?.abortSignal + + // Per-request abort wiring (RequestConfigBuilder adoption): subclasses inherit + // it by receiving the built config as createStream's requestOptions. + const requestConfig = new RequestConfigBuilder().setAbortSignal(metadata).build() + // Request creation can reject before the stream exists. Some subclasses return the + // SDK promise without awaiting it (e.g. FriendliHandler.createStream), so their own + // catch cannot fire; normalize creation-time failures here so an abort during request + // creation reaches Task.ts as an AbortError instead of a raw APIUserAbortError. + let stream: AsyncIterable + try { + // The SDK can sleep through a 429 backoff without observing the signal, so the creation + // await is raced against it: a stop settles the request instead of waiting out the sleep. + // Some subclasses return a thenable rather than a real promise, so normalise before racing it. + const created = () => Promise.resolve(this.createStream(systemPrompt, messages, metadata, requestConfig)) + const createdSignal = requestConfig?.signal + stream = createdSignal ? await rejectOnAbort(created(), createdSignal, this.providerName) : await created() + } catch (error) { + throw handleOpenAIRequestError(error, this.providerName, signal) + } const matcher = new TagMatcher( ["think", "thought"], @@ -129,64 +158,121 @@ export abstract class BaseOpenAiCompatibleProvider let lastUsage: OpenAI.CompletionUsage | undefined const activeToolCallIds = new Set() - for await (const chunk of stream) { - // Check for provider-specific error responses (e.g., MiniMax base_resp) - const chunkAny = chunk as any - if (chunkAny.base_resp?.status_code && chunkAny.base_resp.status_code !== 0) { - throw new Error( - `${this.providerName} API Error (${chunkAny.base_resp.status_code}): ${chunkAny.base_resp.status_msg || "Unknown error"}`, - ) - } + // An iterator error is normalized only after the usage record below has been handed to the + // caller, so a mid-stream failure cannot bypass the tokens already streamed. The failure is + // tracked beside its value because a rejection can carry `undefined`, and that rejection must + // still reach the handler instead of ending the stream normally after partial output. + let streamError: unknown = undefined + let streamFailed = false - const delta = chunk.choices?.[0]?.delta - const finishReason = chunk.choices?.[0]?.finish_reason + try { + for await (const chunk of stream) { + // Streaming-loop abort defense: the for-await above already pulled this + // chunk; the top-of-loop break stops *processing* (and yielding) buffered + // content that arrived after the caller's signal aborted. + if (signal?.aborted) { + break + } + // Check for provider-specific error responses (e.g., MiniMax base_resp). + // ChatCompletionChunk has no base_resp member, so read it through an + // unknown guard instead of casting the whole chunk. + const chunkUnknown: unknown = chunk + const baseResp: unknown = + typeof chunkUnknown === "object" && chunkUnknown !== null && "base_resp" in chunkUnknown + ? (chunkUnknown as { base_resp?: unknown }).base_resp + : undefined + const baseRespFields = + baseResp !== null && typeof baseResp === "object" + ? (baseResp as Record) + : undefined + const baseRespStatusCode = baseRespFields?.["status_code"] + const baseRespStatusMsg = baseRespFields?.["status_msg"] + if (baseRespStatusCode && baseRespStatusCode !== 0) { + throw new Error( + `${this.providerName} API Error (${baseRespStatusCode}): ${String(baseRespStatusMsg || "Unknown error")}`, + ) + } - const reasoningText = extractReasoningFromDelta(delta) - if (reasoningText) { - yield { type: "reasoning", text: reasoningText } - } + const delta = chunk.choices?.[0]?.delta + const finishReason = chunk.choices?.[0]?.finish_reason - if (delta?.content) { - for (const processedChunk of matcher.update(delta.content)) { - yield processedChunk + const reasoningText = extractReasoningFromDelta(delta) + if (reasoningText) { + yield { type: "reasoning", text: reasoningText } } - } - // Emit raw tool call chunks - NativeToolCallParser handles state management - if (delta?.tool_calls) { - for (const toolCall of delta.tool_calls) { - if (toolCall.id) { - activeToolCallIds.add(toolCall.id) + if (delta?.content) { + for (const processedChunk of matcher.update(delta.content)) { + if (signal?.aborted) { + break + } + yield processedChunk } - yield { - type: "tool_call_partial", - index: toolCall.index, - id: toolCall.id, - name: toolCall.function?.name, - arguments: toolCall.function?.arguments, + } + + // Emit raw tool call chunks - NativeToolCallParser handles state management + if (delta?.tool_calls) { + for (const toolCall of delta.tool_calls) { + if (signal?.aborted) { + break + } + if (toolCall.id) { + activeToolCallIds.add(toolCall.id) + } + yield { + type: "tool_call_partial", + index: toolCall.index, + id: toolCall.id, + name: toolCall.function?.name, + arguments: toolCall.function?.arguments, + } } } - } - // Emit tool_call_end events when finish_reason is "tool_calls" - // This ensures tool calls are finalized even if the stream doesn't properly close - if (finishReason === "tool_calls" && activeToolCallIds.size > 0) { - for (const id of activeToolCallIds) { - yield { type: "tool_call_end", id } + // Emit tool_call_end events when finish_reason is "tool_calls" + // This ensures tool calls are finalized even if the stream doesn't properly close + if (finishReason === "tool_calls" && activeToolCallIds.size > 0) { + for (const id of activeToolCallIds) { + if (signal?.aborted) { + break + } + yield { type: "tool_call_end", id } + } + activeToolCallIds.clear() } - activeToolCallIds.clear() - } - if (chunk.usage) { - lastUsage = chunk.usage + if (chunk.usage) { + lastUsage = chunk.usage + } } + } catch (error) { + // Normalize here, not after the usage yield: a caller that stops before the next pull must + // still see this failure instead of an AbortError from its own later stop. + streamError = handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) + streamFailed = true } + // Usage before the verdict: a captured usage record must reach the caller ahead of an + // abort or an iterator error, or the cost of the tokens already streamed disappears + // from the task's accounting exactly when the stream stops early. if (lastUsage) { yield this.processUsageMetrics(lastUsage, this.getModel().info) } - // Process any remaining content + if (streamFailed) { + throw streamError + } + + // Post-loop abort defense: a signal that aborted while the loop was running must + // surface the Task.ts abort contract instead of letting the stream end normally + // with the matcher.final() content below. + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } + + // Process any remaining content. No cancellation re-check is needed here: the throw above + // already covers an aborted caller signal, and matcher.final() is a synchronous array, so + // no await exists between that check and this loop in which an abort could appear. for (const processedChunk of matcher.final()) { yield processedChunk } @@ -212,7 +298,9 @@ export abstract class BaseOpenAiCompatibleProvider } } - async completePrompt(prompt: string, _options?: CompletePromptOptions): Promise { + async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + throwIfAborted(options?.abortSignal) + const { id: modelId, info: modelInfo } = this.getModel() const params: OpenAI.Chat.Completions.ChatCompletionCreateParams = { @@ -225,8 +313,31 @@ export abstract class BaseOpenAiCompatibleProvider ;(params as any).thinking = { type: "enabled" } } + // CompletePromptOptions is not ApiHandlerCreateMessageMetadata (required taskId), + // so the abort/timeout merge goes through setOption; the helper treats + // timeoutMs <= 0 as "no explicit timeout". The per-request timeout is + // forwarded as well: without it the SDK falls back to the client-level + // default, which can still expire before a larger per-request timeoutMs. + const requestTimeout = getRequestTimeoutMs(options?.timeoutMs) + const requestSignal = mergeAbortSignalAndTimeout(options?.abortSignal, options?.timeoutMs) + const requestConfig = new RequestConfigBuilder() + .setOption("signal", requestSignal) + .setOption("timeout", requestTimeout) + .build() + try { - const response = await this.client.chat.completions.create(params) + const response = await this.client.chat.completions.create(params, requestConfig) + + // A cancellation that lands while the response is in flight must not be reported as a + // completed prompt: the response is discarded and the abort contract is raised instead. + if (options?.abortSignal?.aborted) { + throw handleOpenAIRequestError( + createAbortError(this.providerName), + this.providerName, + options.abortSignal, + requestSignal, + ) + } // Check for provider-specific error responses (e.g., MiniMax base_resp) const responseAny = response as any @@ -238,7 +349,7 @@ export abstract class BaseOpenAiCompatibleProvider return response.choices?.[0]?.message.content || "" } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, options?.abortSignal, requestSignal) } } diff --git a/src/api/providers/openai.ts b/src/api/providers/openai.ts index f54a8853696..ba1e56f6a78 100644 --- a/src/api/providers/openai.ts +++ b/src/api/providers/openai.ts @@ -39,7 +39,7 @@ import { getModelParams } from "../transform/model-params" import { DEFAULT_HEADERS, NOT_PROVIDED } from "./constants" import { BaseProvider } from "./base-provider" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" -import { handleOpenAIError } from "./utils/error-handler" +import { handleOpenAIError, handleOpenAIRequestError } from "./utils/error-handler" import { applyThoughtSignatures, thoughtSignatureOrigin, ThoughtSignatureReader } from "./utils/thought-signature" import { extractReasoningFromDelta } from "./utils/extract-reasoning" import { @@ -48,7 +48,21 @@ import { isRequestAborted, hasUsableTimeout, toSdkTimeoutMs, + mergeAbortSignalAndTimeout, + throwIfAborted, + rejectOnAbort, + isTimeoutAbort, } from "./utils/abort-signal" +import { RequestConfigBuilder } from "./config-builder/request-config-builder" +import { getRequestTimeoutMs } from "./utils/request-timeout" + +/** Subset of OpenAI.RequestOptions built per request for the abort-signal wiring. */ +type OpenAiRequestConfig = { + path?: string + signal?: AbortSignal + /** Per-request SDK timeout; a positive timeoutMs overrides the client default. */ + timeout?: number +} function isAzureV1BaseUrl(baseUrl?: string): boolean { try { @@ -162,15 +176,24 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl // `reasoning_effort` combined with function tools on /chat/completions and // require /responses instead. if (this.options.openAiUseResponsesApi) { + // The Responses route hands the caller's signal to the SDK at request construction, + // where it is bridged, so the SDK rejects it there. Throwing before the handoff would + // skip the request entirely and drop the signal the caller passed. yield* this.handleResponsesApiMessage(systemPrompt, messages, metadata) return } + const signal = metadata?.abortSignal + + // The routes below attach the caller's signal to the request they issue themselves, so a + // signal that is already aborted fails before any of that work happens. The Responses route + // above hands its own bridged signal to the SDK, and is guarded there rather than here. + throwIfAborted(signal) + const { info: modelInfo, reasoning } = this.getModel() const modelUrl = this.options.openAiBaseUrl ?? "" // Stryker disable next-line LogicalOperator: equivalent. An unset option makes `&&` // yield undefined, which the parameter default in convertToolsForOpenAI turns back into - // the same strict value as `??`. const strictToolSchemas = this.options.openAiStrictToolSchemas ?? DEFAULT_OPEN_AI_STRICT_TOOL_SCHEMAS const isAzureAiInference = this._isAzureAiInference(modelUrl) const deepseekReasoner = this.usesR1Format(modelId) @@ -264,12 +287,12 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let stream try { - stream = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(isAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + stream = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(isAzureAiInference, metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } const matcher = new TagMatcher( @@ -284,36 +307,78 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let lastUsage const activeToolCallIds = new Set() - for await (const chunk of stream) { - const delta = chunk.choices?.[0]?.delta ?? {} - const finishReason = chunk.choices?.[0]?.finish_reason - signatureReader.update(delta.tool_calls) + // An iterator error is normalized only after the usage record below has been handed to + // the caller. The failure is tracked beside its value because a rejection can carry + // `undefined`, and that rejection must still reach the handler instead of completing + // the stream after partial output. + let streamError: unknown = undefined + let streamFailed = false - const reasoningText = extractReasoningFromDelta(delta) - if (reasoningText) { - yield { type: "reasoning", text: reasoningText } - } + try { + for await (const chunk of stream) { + // A frame the SDK already returned still carries its usage. Record it before the + // abort check below, or the tokens buffered behind the last text yield are lost. + if (chunk.usage) { + lastUsage = chunk.usage + } + // Streaming-loop abort defense: the for-await above already pulled this + // chunk; the top-of-loop break stops *processing* (and yielding) buffered + // content that arrived after the caller's signal aborted. + if (signal?.aborted) { + break + } + const delta = chunk.choices?.[0]?.delta ?? {} + const finishReason = chunk.choices?.[0]?.finish_reason + signatureReader.update(delta.tool_calls) - if (delta.content) { - for (const chunk of matcher.update(delta.content)) { - yield chunk + const reasoningText = extractReasoningFromDelta(delta) + if (reasoningText) { + yield { type: "reasoning", text: reasoningText } } - } - yield* this.processToolCalls(delta, finishReason, activeToolCallIds) + if (delta.content) { + for (const chunk of matcher.update(delta.content)) { + // Same-chunk abort defense: the reasoning yield above may already have been + // the last event the caller wanted, so the signal is re-read between the yields a + // single chunk produces instead of only between chunks. + if (signal?.aborted) { + break + } - if (chunk.usage) { - lastUsage = chunk.usage - } - } + yield chunk + } + } - for (const chunk of matcher.final()) { - yield chunk + yield* this.processToolCalls(delta, finishReason, activeToolCallIds, signal) + } + } catch (error) { + // Normalize here, not after the usage yield: a caller that stops before the next pull + // must still see this failure instead of an AbortError from its own later stop. + streamError = handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) + streamFailed = true } + // Usage before the verdict: a stream that recorded usage and then observed the cancellation + // still has to hand that usage record to the caller, or the cost of the tokens it already + // streamed disappears from the task's accounting exactly when the stream stops early. if (lastUsage) { yield this.processUsageMetrics(lastUsage, modelInfo) } + + if (streamFailed) { + throw streamError + } + + // Post-loop abort defense: a signal that aborted while the loop was running must + // surface the Task.ts abort contract instead of letting the stream end normally + // with the buffered matcher content below. + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } + + for (const chunk of matcher.final()) { + yield chunk + } } else { let requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = { model: modelId, @@ -336,20 +401,27 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let response try { - response = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(this._isAzureAiInference(modelUrl) ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + response = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(this._isAzureAiInference(modelUrl), metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } + // A cancellation that lands while the response is in flight must not be reported as + // completed work: the arrived text and tool calls are discarded and the abort contract + // is raised instead, so Task.ts never sees content the caller already cancelled. + this.throwIfRequestAborted(signal) + const message = response.choices?.[0]?.message signatureReader.update(message?.tool_calls) if (message?.tool_calls) { for (const toolCall of message.tool_calls) { if (toolCall.type === "function") { + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "tool_call", id: toolCall.id, @@ -360,11 +432,15 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "text", text: message?.content || "", } + // A cancellation after the last content chunk must not be reported as usage metrics. + this.throwIfRequestAborted(signal) yield this.processUsageMetrics(response.usage, modelInfo) } } @@ -525,6 +601,8 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + throwIfAborted(options?.abortSignal) + try { if (this.options.openAiUseResponsesApi) { const model = this.getModel() @@ -538,13 +616,29 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl extraBody: this.extraBody, reasoningScope: responsesReasoningScope(this.client.baseURL), }) - const response = await this.client.responses.create( - { ...body, stream: false }, - { - ...(options?.abortSignal ? { signal: options.abortSignal } : {}), - ...(hasUsableTimeout(options?.timeoutMs) ? { timeout: toSdkTimeoutMs(options.timeoutMs) } : {}), - }, - ) + // The SDK clears its own fetch timer once the headers arrive and then reads the body, so the + // deadline only stays armed if it is forwarded as this request's signal. + const requestSignal = mergeAbortSignalAndTimeout(options?.abortSignal, options?.timeoutMs) + let response + try { + response = await this.client.responses.create( + { ...body, stream: false }, + { + ...(requestSignal ? { signal: requestSignal } : {}), + ...(hasUsableTimeout(options?.timeoutMs) + ? { timeout: toSdkTimeoutMs(options.timeoutMs) } + : {}), + }, + ) + } catch (error) { + // Only an abort or a deadline is normalized here. A native abort raised while the + // Responses body is read reaches the caller as the provider's contract error, as the + // Chat Completions branch below does; any other failure is wrapped once, by the outer catch. + if (isRequestAborted(error, options?.abortSignal) || isTimeoutAbort(requestSignal)) { + throw handleOpenAIRequestError(error, this.providerName, options?.abortSignal, requestSignal) + } + throw error + } assertResponsesApiSuccess(response) return response.output .flatMap((item) => @@ -571,19 +665,50 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl requestOptions = this.withExtraBody(requestOptions) let response + const requestConfig = this.buildCompletePromptRequestConfig(isAzureAiInference, options) try { - response = await this.client.chat.completions.create( - requestOptions, - isAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}, - ) + const create = this.client.chat.completions.create(requestOptions, requestConfig) + // The SDK sleeps between retries and does not observe the merged signal: race the call so + // a deadline still settles the prompt while a 429 backoff is pending. + const requestSignal = requestConfig.signal as AbortSignal | undefined + response = requestSignal ? await rejectOnAbort(create, requestSignal, this.providerName) : await create } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError( + error, + this.providerName, + options?.abortSignal, + requestConfig.signal ?? undefined, + ) + } + + // A cancellation that lands while the response is in flight must not be reported as a + // completed prompt: the answer is discarded and the abort contract is raised instead. + // A cancellation that lands while the response is in flight must not be reported as a + // completed prompt: the answer is discarded and the abort contract is raised instead. + if (options?.abortSignal?.aborted) { + throw handleOpenAIRequestError( + createAbortError(this.providerName), + this.providerName, + options.abortSignal, + requestConfig.signal ?? undefined, + ) } return response.choices?.[0]?.message.content || "" } catch (error) { if (error instanceof OutputTokenLimitError) throw error - if (isRequestAborted(error, options?.abortSignal)) throw createAbortError(this.providerName) + if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) { + // The request-site handler already turned this into the contract error and chained + // the underlying failure as its cause. Re-wrapping it here would drop that cause, so + // name, message and cause are preserved exactly as they arrive. + throw error + } + // A raw SDK abort (name APIUserAbortError) or a signal that aborted mid-flight still + // needs the contract error, with the failure that triggered it kept as the cause. + if (isRequestAborted(error, options?.abortSignal)) { + throw createAbortError(this.providerName, error) + } + if (error instanceof Error) { const wrapped = new Error(`${this.providerName} completion error: ${error.message}`, { cause: error }) const source = error as Error & { status?: number; errorDetails?: unknown; code?: unknown } @@ -598,6 +723,44 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } + /** + * Builds the per-request OpenAI SDK options for a chat completions create + * (createMessage paths): the Azure AI Inference path when applicable, plus + * the caller's abort signal, via RequestConfigBuilder adoption. + */ + private buildChatRequestConfig( + isAzureAiInference: boolean, + metadata?: ApiHandlerCreateMessageMetadata, + ): OpenAI.RequestOptions { + return ( + new RequestConfigBuilder() + .setOption("path", isAzureAiInference ? OPENAI_AZURE_AI_INFERENCE_PATH : undefined) + .setAbortSignal(metadata) + .build() ?? {} + ) + } + + /** + * Builds the per-request options for completePrompt. CompletePromptOptions + * is not ApiHandlerCreateMessageMetadata (required taskId), so the merged + * abort/timeout signal and the per-request SDK timeout (a positive timeoutMs + * overrides the client-level default) go through setOption instead of + * setAbortSignal. + */ + private buildCompletePromptRequestConfig( + isAzureAiInference: boolean, + options?: CompletePromptOptions, + ): OpenAI.RequestOptions { + const requestTimeout = getRequestTimeoutMs(options?.timeoutMs) + return ( + new RequestConfigBuilder() + .setOption("path", isAzureAiInference ? OPENAI_AZURE_AI_INFERENCE_PATH : undefined) + .setOption("signal", mergeAbortSignalAndTimeout(options?.abortSignal, options?.timeoutMs)) + .setOption("timeout", requestTimeout) + .build() ?? {} + ) + } + private async *handleO3FamilyMessage( modelId: string, systemPrompt: string, @@ -606,10 +769,9 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl ): ApiStream { const { info: modelInfo, reasoning } = this.getModel() const methodIsAzureAiInference = this._isAzureAiInference(this.options.openAiBaseUrl) - // Stryker disable next-line LogicalOperator: equivalent. An unset option makes `&&` // yield undefined, which the parameter default in convertToolsForOpenAI turns back into - // the same strict value as `??`. const strictToolSchemas = this.options.openAiStrictToolSchemas ?? DEFAULT_OPEN_AI_STRICT_TOOL_SCHEMAS + const signal = metadata?.abortSignal if (this.options.openAiStreamingEnabled ?? true) { const isGrokXAI = this._isGrokXAI(this.options.openAiBaseUrl) @@ -641,15 +803,28 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let stream try { - stream = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(methodIsAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + stream = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(methodIsAzureAiInference, metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } - yield* this.handleStreamResponse(stream) + try { + yield* this.handleStreamResponse(stream, signal) + } catch (error) { + // The creation-site catch does not cover errors raised by the async + // iterator itself (e.g. a mid-stream abort); normalize them the same way. + throw handleOpenAIRequestError(error, this.providerName, signal) + } + + // Post-loop abort defense: a signal that aborted while the loop was running + // must surface the Task.ts abort contract instead of letting the stream end + // normally with the buffered content it may have pulled. + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } } else { let requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = { model: modelId, @@ -676,18 +851,25 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let response try { - response = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(methodIsAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + response = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(methodIsAzureAiInference, metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } + // A cancellation that lands while the response is in flight must not be reported as + // completed work: the arrived text and tool calls are discarded and the abort contract + // is raised instead, so Task.ts never sees content the caller already cancelled. + this.throwIfRequestAborted(signal) + const message = response.choices?.[0]?.message if (message?.tool_calls) { for (const toolCall of message.tool_calls) { if (toolCall.type === "function") { + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "tool_call", id: toolCall.id, @@ -698,18 +880,49 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "text", text: message?.content || "", } + // A cancellation after the last content chunk must not be reported as usage metrics. + this.throwIfRequestAborted(signal) yield this.processUsageMetrics(response.usage) } } - private async *handleStreamResponse(stream: AsyncIterable): ApiStream { + /** + * Raise the normalized abort contract for this provider when the caller has cancelled. + * + * A `yield` suspends this generator, so the caller can cancel between yields. Each piece of + * content a non-streaming response hands over is therefore re-checked before it is yielded, not + * only the first piece after the response arrives. + */ + private throwIfRequestAborted(signal?: AbortSignal): void { + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } + } + + private async *handleStreamResponse( + stream: AsyncIterable, + signal?: AbortSignal, + ): ApiStream { const activeToolCallIds = new Set() for await (const chunk of stream) { + // A usage-only frame the SDK already returned must reach the caller even when the abort + // landed in between: the break below stops content, not the token counts. + if (chunk.usage) { + yield this.processUsageMetrics(chunk.usage) + } + // Streaming-loop abort defense: the for-await above already pulled this + // chunk; the top-of-loop break stops *processing* (and yielding) buffered + // content that arrived after the caller's signal aborted. + if (signal?.aborted) { + break + } const delta = chunk.choices?.[0]?.delta const finishReason = chunk.choices?.[0]?.finish_reason @@ -721,11 +934,7 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } - yield* this.processToolCalls(delta, finishReason, activeToolCallIds) - } - - if (chunk.usage) { - yield this.processUsageMetrics(chunk.usage) + yield* this.processToolCalls(delta, finishReason, activeToolCallIds, signal) } } } @@ -736,11 +945,14 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl * @param delta - The delta object from the stream chunk * @param finishReason - The finish_reason from the stream chunk * @param activeToolCallIds - Set to track active tool call IDs (mutated in place) + * @param signal - Caller abort signal, re-read before each yield so a cancelled caller stops + * receiving tool-call events instead of draining the ones that already arrived */ protected *processToolCalls( delta: OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta | undefined, finishReason: string | null | undefined, activeToolCallIds: Set, + signal?: AbortSignal, ): Generator< | { type: "tool_call_partial"; index: number; id?: string; name?: string; arguments?: string } | { type: "tool_call_end"; id: string } @@ -750,6 +962,11 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl if (toolCall.id) { activeToolCallIds.add(toolCall.id) } + // A cancelled caller must not receive tool-call partials that arrived after the + // cancellation; the guard is read before the yield, not after it. + if (signal?.aborted) { + break + } yield { type: "tool_call_partial", index: toolCall.index, @@ -764,6 +981,9 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl // This ensures tool calls are finalized even if the stream doesn't properly close if (finishReason === "tool_calls" && activeToolCallIds.size > 0) { for (const id of activeToolCallIds) { + if (signal?.aborted) { + break + } yield { type: "tool_call_end", id } } activeToolCallIds.clear() From 847f898155ebd8bbc46238ae21e02dca65ef5e8a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:46:42 +0800 Subject: [PATCH 3/3] feat(api): honour caller cancellation in zai (#1311 split u2) Unit u2 of the split plan in #2799. Stacked on u1 (#2801). - The GLM-5.3 completion bridges the caller's signal per request and disposes the bridge in `finally`, so the SDK's listener lands on a per-request controller instead of the caller's long-lived one. - The completion is raced against the merged signal, so a 429 backoff sleep cannot outlast `timeoutMs` or delay a caller stop. Evidence: zai rows 78 pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. --- src/api/providers/__tests__/zai.spec.ts | 497 +++++++++++++++++++++++- src/api/providers/zai.ts | 80 +++- 2 files changed, 549 insertions(+), 28 deletions(-) diff --git a/src/api/providers/__tests__/zai.spec.ts b/src/api/providers/__tests__/zai.spec.ts index 0a33e7ad66f..05175499a37 100644 --- a/src/api/providers/__tests__/zai.spec.ts +++ b/src/api/providers/__tests__/zai.spec.ts @@ -1,6 +1,6 @@ // npx vitest run src/api/providers/__tests__/zai.spec.ts -import OpenAI from "openai" +import OpenAI, { APIUserAbortError } from "openai" import { Anthropic } from "@anthropic-ai/sdk" import { @@ -17,10 +17,14 @@ import { import { ZAiHandler } from "../zai" import { asyncStreamFrom } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" +import { captureError } from "../../../test-utils/errors" +import { MAX_TIMEOUT_MS } from "../utils/abort-signal" vitest.mock("openai", () => { const createMock = vitest.fn() return { + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, default: vitest.fn(function () { return { chat: { completions: { create: createMock } } } }), @@ -593,6 +597,450 @@ describe("ZAiHandler", () => { }) }) + describe("abort signal wiring", () => { + beforeEach(() => { + handler = new ZAiHandler({ zaiApiKey: "test-zai-api-key", zaiApiLine: "international_coding" }) + }) + + it("createMessage should pass the abort signal on the GLM thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // The double records the request options it received, so the signal can be compared by + // identity below: a live signal has no own properties, so a structural match would accept a + // replacement signal that is not the caller's cancellation. + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return asyncStreamFrom([]) + }) + + const gen = thinkingHandler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + await gen.next() + + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "glm-4.7", thinking: { type: "enabled" } }), + expect.anything(), + ) + expect(sentOptions?.signal).toBe(controller.signal) + }) + + it("createMessage should pass the abort signal for non-thinking models via the base path", async () => { + const plainHandler = new ZAiHandler({ + apiModelId: "glm-4.6", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // The double records the request options it received, so the signal can be compared by + // identity below: a live signal has no own properties, so a structural match would accept a + // replacement signal that is not the caller's cancellation. + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return asyncStreamFrom([]) + }) + + const gen = plainHandler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + await gen.next() + + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "glm-4.6" }), expect.anything()) + expect(sentOptions?.signal).toBe(controller.signal) + }) + + it("createMessage should reject before any request when the abort signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect(async () => { + for await (const _ of handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + })) { + // consume + } + }).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("createMessage should normalize the SDK APIUserAbortError on the thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("createMessage should normalize a rejected-Promise APIUserAbortError on the thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + // The awaited request creation rejects (the SDK's pre-abort shape); + // normalization must catch it, not only synchronous throws. + mockCreate.mockRejectedValueOnce(new APIUserAbortError()) + + const result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + }) + + it("createMessage should wrap a non-abort thinking-path creation failure exactly once", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + // The thinking override used to normalize the failure itself and the base + // createMessage normalized it again on top: doubled prefix, doubled log line. + mockCreate.mockRejectedValueOnce(new Error("boom")) + const errorLog = vitest.spyOn(console, "error").mockImplementation(() => {}) + + // captureError throws when the operation resolves instead of rejecting - the very contract + // violation this test exists to catch - so the restoration has to span the await: a restoring + // finally that starts after it leaks the console.error spy into whichever test runs next. + let result: Error + try { + result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.message).toBe("Z.ai completion error: boom") + expect(errorLog).toHaveBeenCalledTimes(1) + } finally { + errorLog.mockRestore() + } + }) + + it("createMessage leaves no console.error spy installed when the mocked create resolves", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + // The resolving shape: an empty async iterable satisfies the stream loop and rejects nothing, + // so the only failure left is captureError's own "expected a rejection" assertion. + mockCreate.mockResolvedValueOnce((async function* () {})()) + const errorLog = vitest.spyOn(console, "error").mockImplementation(() => {}) + let failure: Error | undefined + try { + failure = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } finally { + errorLog.mockRestore() + } + expect(failure?.message).toBe("Expected the operation to reject") + expect(vitest.isMockFunction(console.error), "the spy must not outlive its own test").toBe(false) + }) + + it("createMessage should normalize an abort error raised during stream iteration on the thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + + const result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // The thinking path inherits stream iteration from the base provider; a + // mid-stream abort must normalize to the Task.ts contract shape. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("completePrompt should pass the abort signal through to the client", async () => { + const controller = new AbortController() + // The double records the request options it received, so the signal can be compared by + // identity below: a live signal has no own properties, so a structural match would accept a + // replacement signal that is not the caller's cancellation. + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return Promise.resolve({ choices: [{ message: { content: "response" } }] }) + }) + + const result = await handler.completePrompt("test prompt", { abortSignal: controller.signal }) + + expect(result).toBe("response") + expect(sentOptions?.signal).toBe(controller.signal) + }) + + it("completePrompt should reject before any request when the signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect( + handler.completePrompt("test prompt", { abortSignal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("completePrompt should normalize the SDK APIUserAbortError", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError(handler.completePrompt("test prompt")) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + }) + + it("completePrompt should cap an oversized timeoutMs before handing it to the SDK", async () => { + // GLM-5.3 has its own completePrompt path; other models delegate to the base + // provider, so the override is what this test has to exercise. + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await h53.completePrompt("test prompt", { timeoutMs: MAX_TIMEOUT_MS + 1 }) + + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + // Same capped normalization as the merged abort signal: uncapped, the SDK timer + // clamps the delay to ~1 ms and aborts the request almost immediately. + expect(requestOptions?.timeout).toBe(MAX_TIMEOUT_MS) + }) + + it("completePrompt should omit the request timeout for a non-finite timeoutMs", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await h53.completePrompt("test prompt", { timeoutMs: Number.POSITIVE_INFINITY }) + + // Infinity satisfies a bare `> 0` check but is not a legal timer delay, so it has + // to mean "no explicit timeout" and leave the request config unset. + expect(mockCreate).toHaveBeenCalledWith(expect.anything(), undefined) + }) + + it("glm-5.3 completePrompt should cancel the in-flight request when the caller signal aborts", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // Emulate the OpenAI SDK: the pending request rejects when its signal aborts. + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const requestPromise = h53.completePrompt("prompt", { abortSignal: controller.signal, timeoutMs: 5000 }) + await vi.waitFor(() => expect(mockCreate).toHaveBeenCalled()) + const requestCall = mockCreate.mock.calls.at(-1) + const requestOptions = requestCall?.[1] + // The merged signal follows the caller's own stop, and it does so long before the five-second + // deadline, so a provider that forwarded only the timeout signal fails here. + expect(requestOptions?.signal?.aborted).toBe(false) + controller.abort() + expect(requestOptions?.signal?.aborted).toBe(true) + + const result = await captureError(requestPromise) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + expect(requestCall?.[0]).toEqual( + expect.objectContaining({ model: "glm-5.3", thinking: { type: "enabled", clear_thinking: false } }), + ) + // A positive timeoutMs must be forwarded as the per-request SDK timeout. + expect(requestOptions?.timeout).toBe(5000) + }) + + it("glm-5.3 completePrompt discards an answer that arrives after the caller cancelled", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // The GLM endpoint answered, and the answer arrived after the caller had already + // cancelled: the provider must not turn a cancelled request into a completed prompt. + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal }) => + new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve({ choices: [{ message: { role: "assistant", content: "late answer" } }] }) + } else { + options?.signal?.addEventListener( + "abort", + () => + resolve({ choices: [{ message: { role: "assistant", content: "late answer" } }] }), + { once: true }, + ) + } + }), + ) + + const answered = h53.completePrompt("prompt", { abortSignal: controller.signal }) + controller.abort() + const failure = await answered.then( + (): unknown => null, + (error: unknown) => error, + ) + + expect((failure as Error)?.name, JSON.stringify(failure)).toBe("AbortError") + expect(String((failure as Error)?.message)).toContain("request was aborted") + }) + + it("glm-5.3 completePrompt should normalize the SDK APIUserAbortError", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError(h53.completePrompt("prompt")) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + }) + + it("glm-5.3 completePrompt should omit the request timeout when timeoutMs is zero", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await expect(h53.completePrompt("prompt", { timeoutMs: 0 })).resolves.toBe("response") + + // Values <= 0 mean "no explicit timeout": with no caller signal either, + // the built request config is empty and nothing is forwarded to the SDK. + expect(mockCreate.mock.calls.at(-1)?.[1]).toBeUndefined() + }) + + // The pre-aborted guard in the glm-5.3 override is its own: the shared + // pre-aborted test above uses the default glm-4.7 model, which delegates to + // super.completePrompt, so it never reaches this override's throwIfAborted. + it("glm-5.3 completePrompt should reject before any request when the signal is already aborted", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + controller.abort() + + await expect(h53.completePrompt("prompt", { abortSignal: controller.signal })).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + // A timeout with no caller abort must stay a TimeoutError: the caller signal is + // absent, so only the merged request signal carries a TimeoutError reason, and the + // override's own catch is what classifies it. + it("glm-5.3 completePrompt should classify a timeout-only abort as TimeoutError", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const requestPromise = h53.completePrompt("prompt", { timeoutMs: 50 }) + const resultPromise = captureError(requestPromise) + + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The Z.ai completion request timed out") + expect(result.cause).toBeInstanceOf(Error) + }) + }) + describe("GLM-4.7 Thinking Mode", () => { it("should cap GLM-5.1 max_tokens to 20% of context window by default", async () => { const handlerWithModel = new ZAiHandler({ @@ -611,6 +1059,7 @@ describe("ZAiHandler", () => { model: "glm-5.1", max_tokens: 40_000, }), + undefined, ) }) @@ -643,6 +1092,7 @@ describe("ZAiHandler", () => { model: "glm-5.1", max_tokens: 100_000, }), + undefined, ) }) @@ -665,6 +1115,7 @@ describe("ZAiHandler", () => { model: "glm-4.7", thinking: { type: "enabled" }, }), + undefined, ) }) @@ -687,6 +1138,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled" }, reasoning_effort: "high", }), + undefined, ) }) @@ -709,6 +1161,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled" }, reasoning_effort: "max", }), + undefined, ) }) @@ -732,6 +1185,7 @@ describe("ZAiHandler", () => { reasoning_effort: "max", temperature: 1, }), + undefined, ) }) @@ -755,6 +1209,7 @@ describe("ZAiHandler", () => { reasoning_effort: "max", temperature: 1, }), + undefined, ) }) @@ -777,6 +1232,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled", clear_thinking: false }, reasoning_effort: "max", }), + undefined, ) }) @@ -791,13 +1247,16 @@ describe("ZAiHandler", () => { mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) await expect(handlerWithModel.completePrompt("prompt")).resolves.toBe("response") - expect(mockCreate).toHaveBeenCalledWith({ - model: "glm-5.3", - messages: [{ role: "user", content: "prompt" }], - temperature: 1, - thinking: { type: "enabled", clear_thinking: false }, - reasoning_effort: "low", - }) + expect(mockCreate).toHaveBeenCalledWith( + { + model: "glm-5.3", + messages: [{ role: "user", content: "prompt" }], + temperature: 1, + thinking: { type: "enabled", clear_thinking: false }, + reasoning_effort: "low", + }, + undefined, + ) }) it("should use the official GLM-5.3-Flash parameters for completePrompt", async () => { @@ -811,13 +1270,16 @@ describe("ZAiHandler", () => { mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) await expect(handlerWithModel.completePrompt("prompt")).resolves.toBe("response") - expect(mockCreate).toHaveBeenCalledWith({ - model: "glm-5.3-flash", - messages: [{ role: "user", content: "prompt" }], - temperature: 1, - thinking: { type: "enabled", clear_thinking: false }, - reasoning_effort: "low", - }) + expect(mockCreate).toHaveBeenCalledWith( + { + model: "glm-5.3-flash", + messages: [{ role: "user", content: "prompt" }], + temperature: 1, + thinking: { type: "enabled", clear_thinking: false }, + reasoning_effort: "low", + }, + undefined, + ) }) it("should omit reasoning_effort for GLM-5.2 when reasoningEffort is set to disable", async () => { @@ -857,6 +1319,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled" }, reasoning_effort: "high", }), + undefined, ) }) @@ -880,6 +1343,7 @@ describe("ZAiHandler", () => { model: "glm-4.7", thinking: { type: "disabled" }, }), + undefined, ) }) @@ -903,6 +1367,7 @@ describe("ZAiHandler", () => { model: "glm-4.7", thinking: { type: "enabled" }, }), + undefined, ) }) @@ -940,6 +1405,7 @@ describe("ZAiHandler", () => { model: "glm-5-turbo", thinking: { type: "enabled" }, }), + undefined, ) }) @@ -962,6 +1428,7 @@ describe("ZAiHandler", () => { model: "glm-5-turbo", thinking: { type: "disabled" }, }), + undefined, ) }) }) diff --git a/src/api/providers/zai.ts b/src/api/providers/zai.ts index 3e0a39a4dff..c92a183b6b4 100644 --- a/src/api/providers/zai.ts +++ b/src/api/providers/zai.ts @@ -16,7 +16,16 @@ import { convertToZAiFormat } from "../transform/zai-format" import type { ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" import { BaseOpenAiCompatibleProvider } from "./base-openai-compatible-provider" import { NOT_PROVIDED } from "./constants" -import { handleOpenAIError } from "./utils/error-handler" +import { handleOpenAIRequestError } from "./utils/error-handler" +import { RequestConfigBuilder } from "./config-builder/request-config-builder" +import { + bridgeExternalAbortSignal, + createAbortError, + mergeAbortSignalAndTimeout, + rejectOnAbort, + throwIfAborted, +} from "./utils/abort-signal" +import { getRequestTimeoutMs } from "./utils/request-timeout" // Custom interface for Z.ai params to support thinking mode and reasoning effort tiers. // Z.ai accepts the standard `reasoning_effort` ladder (none/minimal/low/medium/high/xhigh/max) @@ -27,6 +36,13 @@ type ZAiChatCompletionParams = Omit model === "glm-5.3" || model === "glm-5.3-flash" export class ZAiHandler extends BaseOpenAiCompatibleProvider { @@ -64,8 +80,10 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { const isThinkingModel = Array.isArray(info.supportsReasoningEffort) if (isThinkingModel) { - // Create the stream with our custom thinking parameter - return this.createStreamWithThinking(systemPrompt, messages, metadata) + // Create the stream with our custom thinking parameter. + // Forward the per-request options (abort signal) so the thinking path + // keeps them instead of dropping requestOptions. + return this.createStreamWithThinking(systemPrompt, messages, metadata, requestOptions) } // For non-thinking models, use the default behavior @@ -75,10 +93,11 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { /** * Creates a stream with explicit thinking control for GLM thinking-capable models. */ - private createStreamWithThinking( + private async createStreamWithThinking( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, + requestOptions?: OpenAI.RequestOptions, ) { const { id: model, info } = this.getModel() const { reasoningEffort, useReasoning } = this.getReasoningSettings(info) @@ -115,13 +134,13 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { parallel_tool_calls: metadata?.parallelToolCalls ?? true, } - try { - return this.client.chat.completions.create( - params as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming, - ) - } catch (error) { - throw handleOpenAIError(error, this.providerName) - } + // Creation errors are normalized once by the base createMessage; wrapping them here + // too doubled the prefix ("Z.ai completion error: Z.ai completion error: ...") and + // logged every thinking-path failure twice. + return await this.client.chat.completions.create( + params as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming, + requestOptions, + ) } private getReasoningSettings(info: ModelInfo) { @@ -149,6 +168,8 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { return super.completePrompt(prompt, options) } + throwIfAborted(options?.abortSignal) + const { reasoningEffort } = this.getReasoningSettings(info) const params: ZAiChatCompletionParams = { model, @@ -158,13 +179,46 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { reasoning_effort: reasoningEffort, } + // CompletePromptOptions is not ApiHandlerCreateMessageMetadata (required + // taskId), so the abort/timeout merge and the per-request SDK timeout go + // through setOption; a positive timeoutMs overrides the client default and + // values <= 0 mean "no explicit timeout". + // The SDK attaches a listener to whatever signal it is given and keeps it after the request, so + // it gets a per-request bridge instead of the caller's long-lived controller. + const bridge = bridgeExternalAbortSignal(options?.abortSignal) + const requestSignal = mergeAbortSignalAndTimeout(bridge.signal, options?.timeoutMs) + const requestConfig = new RequestConfigBuilder() + .setOption("signal", requestSignal) + .setOption("timeout", getRequestTimeoutMs(options?.timeoutMs)) + .build() + try { - const response = await this.client.chat.completions.create( + // The SDK waits out a 429 backoff without checking the signal, so the await is raced with it. + const created = this.client.chat.completions.create( params as OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming, + requestConfig, ) + const response = requestSignal + ? await rejectOnAbort(created, requestSignal, this.providerName) + : await created + + // A cancellation that lands while the GLM request is in flight must not be reported as a + // completed prompt: the arrived content is discarded and the abort contract is raised + // instead, which is the behaviour the base provider already has for every other model. + if (options?.abortSignal?.aborted) { + throw handleOpenAIRequestError( + createAbortError(this.providerName), + this.providerName, + options.abortSignal, + requestSignal, + ) + } + return response.choices?.[0]?.message.content || "" } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, options?.abortSignal, requestSignal) + } finally { + bridge.dispose() } } }