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/2] 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 8dc468bd627c66979ab9ed72fe9af7a9af1aaa1c Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:13:19 +0800 Subject: [PATCH 2/2] fix(api): clear the abort-plumbing lint and knip gates (#1311 split u0) The shared abort, timeout and error helpers landed with two required checks red: compile (eslint) and knip. This commit clears both without re-inflating suppressions, and adds the test that the guard was missing. compile: ESLint 9.39.5 count-based suppressions are all-or-nothing. In suppressions-service.js:171 a file is suppressed only while violationsCount <= suppressionsCount, and :177 rewrites the remainder only when violationsCount < suppressionsCount, so a file that is over its count reports every violation rather than the excess. The previous commit lowered base-openai-compatible-provider.ts from 6 to 5 while the file still held 6 assertions, and deleted the kimi-code.spec.ts entry while that file still held 1, which turned all 7 into reported errors. The fix retypes only what costs nothing. modelInfo goes from any to ModelInfo: the type is already imported in this file and calculateApiCostOpenAI in shared/cost.ts is its only consumer, so the assertion disappears without new machinery and the file drops to exactly its remaining count of 5. The kimi mock reaches the handler's protected client by bracket access, with the seam narrowed to the one create call it replaces - the shape anthropic-vertex.spec.ts:277 and :581 already use. Bracket access alone was not enough: it produced a fresh TS2739 on the ChatCompletionMessage mock literal, so the seam type is load-bearing and not decoration. Its suppression entry stays deleted because the file now asserts nothing, so a count of zero is the honest count rather than an allowance. The other five assertions stay suppressed on purpose: they sit on lines the suite never executes. Coverage over the 18 provider and api specs reports zero hits for both thinking assignments (lines 103 and 225) and for both base_resp throws (lines 136 and 234). Retyping an unexecuted line only moves it into the mutation cell, where no existing test could kill a mutant, and the file is upstream-owned (blame 6cfa82f57103, #11462) rather than part of this unit, as is the mock's owner (78c1410d1db9, #945). Type-checking adds nothing here either way: tsc over src reports the same diagnostics before and after this change. knip: handleOpenAIRequestError has no production importer in this unit - only error-handler.spec.ts imports it, and the request sites arrive with the later splits - so knip --production reports it while dev knip does not, which is the difference between the two runs rather than a finding about the code being wrong. Marked @internal with the reason: an intentional direct-test seam, the exception docs/development-quality-checks.md sanctions and abort-signal.ts:254 already uses in this same directory. The new row is coverage-closing, not a red-first repro: the status-first guard already behaved correctly, but no row reached it because none of the abort-awareness inputs carries a numeric status, so its early return had nothing executing it. It is not free-standing either: deleting the guard fails exactly this row - "expected 'AbortError' to be 'Error'" - while the other 49 rows keep passing. Suppression debt moves down, and the baseline is the merge-base dd30249147159dad2d410845527a14a8e55d1463, which is what AGENTS.md states the rule against - not the PR head: 261 entries and 2844 suppressed occurrences there, 260 and 2842 here. The provider entry stays at 5 and the kimi entry stays gone, so a prune run leaves the count map unchanged and only reflows indentation. Cost against that same base, on the mutation gate's own measure: this cell reports 19 changed executable lines against a cap of 500, one more than the 18 the previous commit measured, and that one line is the retyped signature. Not closed by this commit: - the five remaining provider assertions, which are worth typing only once tests execute the thinking and base_resp paths, and only next to the splits that make them live code - production importers for handleOpenAIRequestError, which arrive with split/1311-u1-openai-family and its siblings - the whole-file typed removal for the provider, sketched during this investigation: it clears all 5 remaining assertions but raises the cell from 18 to 33 changed executable lines, so it should land after the two unexecuted paths have tests of their own --- src/api/providers/__tests__/kimi-code.spec.ts | 8 +++++++- .../base-openai-compatible-provider.ts | 2 +- .../utils/__tests__/error-handler.spec.ts | 18 ++++++++++++++++++ src/api/providers/utils/error-handler.ts | 4 ++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/api/providers/__tests__/kimi-code.spec.ts b/src/api/providers/__tests__/kimi-code.spec.ts index a190ef3e7b7..e8ad4c28e82 100644 --- a/src/api/providers/__tests__/kimi-code.spec.ts +++ b/src/api/providers/__tests__/kimi-code.spec.ts @@ -10,6 +10,9 @@ const { mockGetAccessToken, mockForceRefreshAccessToken, mockGetModels } = vi.ho mockGetModels: vi.fn(), })) +/** The one production call this test replaces: a non-streaming chat completion. */ +type CompletionCreateSeam = { create: (body: unknown) => Promise } + vi.mock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { getAccessToken: mockGetAccessToken, @@ -138,7 +141,10 @@ describe("KimiCodeHandler", () => { const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) const unauthorized = Object.assign(new Error("Unauthorized"), { status: 401 }) const createCompletion = vi - .spyOn((handler as any).client.chat.completions, "create") + // `client` is protected on the handler, so the mock reaches it by bracket + // access; the seam is narrowed to the single create call the mock replaces + // (same shape as anthropic-vertex.spec.ts:277/581) instead of widening to `any`. + .spyOn(handler["client"].chat.completions as unknown as CompletionCreateSeam, "create") .mockRejectedValueOnce(unauthorized) .mockResolvedValueOnce({ choices: [{ message: { content: "retried" } }] }) diff --git a/src/api/providers/base-openai-compatible-provider.ts b/src/api/providers/base-openai-compatible-provider.ts index b177726f852..9211c1d4412 100644 --- a/src/api/providers/base-openai-compatible-provider.ts +++ b/src/api/providers/base-openai-compatible-provider.ts @@ -192,7 +192,7 @@ export abstract class BaseOpenAiCompatibleProvider } } - protected processUsageMetrics(usage: any, modelInfo?: any): ApiStreamUsageChunk { + protected processUsageMetrics(usage: any, modelInfo?: ModelInfo): ApiStreamUsageChunk { const inputTokens = usage?.prompt_tokens || 0 const outputTokens = usage?.completion_tokens || 0 const cacheWriteTokens = usage?.prompt_tokens_details?.cache_write_tokens || 0 diff --git a/src/api/providers/utils/__tests__/error-handler.spec.ts b/src/api/providers/utils/__tests__/error-handler.spec.ts index 436f05d86a6..17dfa0b1a1d 100644 --- a/src/api/providers/utils/__tests__/error-handler.spec.ts +++ b/src/api/providers/utils/__tests__/error-handler.spec.ts @@ -448,6 +448,24 @@ describe("handleOpenAIRequestError (abort awareness)", () => { expect((result as Error & { cause?: unknown }).cause).toBe(original) }) + it("keeps a terminal HTTP failure status-classified when the caller has already aborted", () => { + // Coverage-closing row for the status-first early return in handleOpenAIRequestError, not + // repro: the guard already works, but no row above reaches it because none of their inputs + // carries a numeric status, so that early return had nothing executing it. A 401/429 that + // lands in the same tick as the caller's stop must keep its own identity - backoff and the + // UI read the top-level status, and masking it as AbortError would hide the provider error. + const original = Object.assign(new Error("Too many requests"), { status: 429 }) + const controller = new AbortController() + controller.abort() + + const result = handleOpenAIRequestError(original, "OpenAI", controller.signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("Error") + expect(result.message).toBe("OpenAI completion error: Too many requests") + expect((result as Error & { status?: number }).status).toBe(429) + }) + it("normalizes the SDK user-abort error when no signal was passed", () => { const result = handleOpenAIRequestError(new APIUserAbortError(), "Zai") diff --git a/src/api/providers/utils/error-handler.ts b/src/api/providers/utils/error-handler.ts index 96ce8e1fbd8..4adffa14fb8 100644 --- a/src/api/providers/utils/error-handler.ts +++ b/src/api/providers/utils/error-handler.ts @@ -176,6 +176,10 @@ export function handleOpenAIError(error: unknown, providerName: string): Error { * 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. + * + * @internal Exported for the provider request sites that adopt it in the follow-up + * #1311 splits; direct contract tests cover it here (docs/development-quality-checks.md + * "intentional direct-test seam"). */ export function handleOpenAIRequestError( error: unknown,