From 49c11e57b61f7a2a0235c071333bf08291d72528 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:02:33 +0800 Subject: [PATCH 1/5] feat(api): give the abort bridge a controller and an onAbort hook bridgeExternalAbortSignal now returns its AbortController and accepts optional hooks: a caller-supplied controller for providers that keep a class-level controller as their stop handle, and an onAbort side effect for the cancellations a plain signal relay cannot express (client-level aborts, host cancellation tokens, an aborted-by-caller flag). The hook runs after the per-request controller aborts, and it also runs when the caller signal was already aborted at call time, so a pre-aborted caller reaches the same side effect as a live abort. Default behaviour is unchanged: with no external signal `signal` is still undefined and `dispose` a noop, the listener is still registered once with { once: true }, and dispose still detaches the exact retained callback. Part of #2486 (unit U0a): this is the hook the U1-U6 provider migrations need before they can drop their hand-written bridges. --- .../utils/__tests__/abort-signal.spec.ts | 79 +++++++++++++++++++ src/api/providers/utils/abort-signal.ts | 64 +++++++++++++-- 2 files changed, 135 insertions(+), 8 deletions(-) diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550a..c60b7dcb830 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -829,6 +829,85 @@ describe("bridgeExternalAbortSignal", () => { controller.abort() expect(signal?.aborted).toBe(false) }) + + it("hands back a request-local controller when there is no external signal", () => { + const bridge = bridgeExternalAbortSignal() + expect(bridge.signal).toBeUndefined() + // Providers like lm-studio and qwen-code need a signal for their own races even + // when the caller passed none; the controller is that signal. + expect(bridge.controller.signal.aborted).toBe(false) + bridge.controller.abort() + expect(bridge.controller.signal.aborted).toBe(true) + }) + + it("returns the signal of the controller it created", () => { + const external = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal) + expect(bridge.signal).toBe(bridge.controller.signal) + }) + + it("bridges onto a caller-supplied controller instead of creating one", () => { + const external = new AbortController() + const requestController = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal, { controller: requestController }) + // openai-native keeps its class-level controller as the stop-button handle; the + // bridge must abort that same controller, not a private one. + expect(bridge.controller).toBe(requestController) + expect(bridge.signal).toBe(requestController.signal) + external.abort() + expect(requestController.signal.aborted).toBe(true) + }) + + it("runs the onAbort hook once, after the request signal aborts", () => { + const external = new AbortController() + const requestController = new AbortController() + const reason = new Error("caller stop") + const seen: { calls: number; abortedDuringHook: boolean; hookReason: unknown } = { + calls: 0, + abortedDuringHook: false, + hookReason: undefined, + } + // Providers pass their own controller exactly this way, so the hook can observe + // it directly instead of a mutable local. + bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: (hookReason) => { + seen.calls += 1 + seen.abortedDuringHook = requestController.signal.aborted + seen.hookReason = hookReason + }, + }) + external.abort(reason) + expect(seen.calls).toBe(1) + // A hook that threw must never be the reason a request signal stays un-settled, + // so the controller aborts first. + expect(seen.abortedDuringHook).toBe(true) + expect(seen.hookReason).toBe(reason) + }) + + it("runs the onAbort hook when the external signal was already aborted", () => { + const external = new AbortController() + const reason = new Error("already stopped") + external.abort(reason) + const hook = vitest.fn() + // native-ollama aborts its client and vscode-lm cancels its token source on the + // same signal: a caller that stopped before we started must reach that side + // effect too, not only the live-abort path. + const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + expect(bridge.controller.signal.aborted).toBe(true) + expect(hook).toHaveBeenCalledTimes(1) + expect(hook).toHaveBeenCalledWith(reason) + }) + + it("neither aborts nor runs the hook for an abort that lands after dispose", () => { + const external = new AbortController() + const hook = vitest.fn() + const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + bridge.dispose() + external.abort() + expect(hook).not.toHaveBeenCalled() + expect(bridge.controller.signal.aborted).toBe(false) + }) }) describe("hasUsableTimeout", () => { diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 6abbc124371..167c4f7597b 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -1,4 +1,4 @@ -/** +/** * Whether a timeout value is usable as an SDK `timeout` option: a finite * number greater than zero. * @@ -67,6 +67,30 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: return AbortSignal.any([primarySignal, secondarySignal]) } +/** + * Optional hooks for {@link bridgeExternalAbortSignal}: the cancellation side effects a + * provider needs that a plain signal relay cannot express. + */ +export type AbortBridgeHooks = { + /** + * Run this when the external signal aborts - a client-level `abort()` on a transport + * that owns its own connection, a host cancellation token, or a flag recording that the + * caller rather than a timeout ended the request. + * + * It also runs when the external signal was already aborted at call time, so a + * pre-aborted caller reaches the same side effect as a live abort. The per-request + * controller aborts before the hook runs, so a hook that throws cannot leave a + * request signal that never settles. + */ + onAbort?: (reason?: unknown) => void + /** + * Bridge onto this controller instead of creating one. Providers that keep a + * class-level controller as the stop-button handle pass it here so the bridge and + * that path share one controller. + */ + controller?: AbortController +} + /** * Bridge an optional caller-owned (external) abort signal to a per-request * signal, with an explicit detach handle. @@ -78,30 +102,54 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: * left attached would outlive the request and retain the per-request * controller for every completed request. * - * With no external signal, returns `{ signal: undefined, dispose: noop }` so - * the client-level timeout remains the only cancellation mechanism. + * With no external signal, `signal` is `undefined` and `dispose` is a noop, so the + * client-level timeout remains the only cancellation mechanism; the returned + * `controller` is still a usable request-local signal for a provider that needs + * one without relaying anything. */ -export function bridgeExternalAbortSignal(externalSignal?: AbortSignal): { +export function bridgeExternalAbortSignal( + externalSignal?: AbortSignal, + hooks?: AbortBridgeHooks, +): { signal?: AbortSignal + controller: AbortController dispose: () => void } { + const controller = hooks?.controller ?? new AbortController() + // The hook is invoked from one place per abort path so a provider side effect + // cannot be run twice for the same cancellation. + const notify = (reason?: unknown): void => { + if (!hooks?.onAbort) { + return + } + hooks.onAbort(reason) + } + if (!externalSignal) { - return { signal: undefined, dispose: () => {} } + // No caller signal: the request-local controller is still handed back, so a + // provider that needs a signal for its own races or timer keeps one without + // relaying anything. + return { signal: undefined, controller, dispose: () => {} } } - const controller = new AbortController() if (externalSignal.aborted) { controller.abort() - return { signal: controller.signal, dispose: () => {} } + notify(externalSignal.reason) + return { signal: controller.signal, controller, dispose: () => {} } } // Retain the callback so the listener can be detached once this request // ends: an anonymous listener on a long-lived external signal would // outlive the request and retain the per-request controller. - const onExternalAbort = () => controller.abort() + const onExternalAbort = (): void => { + const reason = externalSignal.reason + controller.abort() + notify(reason) + } externalSignal.addEventListener("abort", onExternalAbort, { once: true }) return { signal: controller.signal, + controller, dispose: () => externalSignal.removeEventListener("abort", onExternalAbort), } } From 694e8ee34e8f20c447addd56175fcea6bf529545 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:50:45 +0800 Subject: [PATCH 2/5] fix(api): save the abort bridge without a byte-order mark The invisible-chars pipeline reports U+FEFF at line 1 of abort-signal.ts while main has none, so the branch's copy is saved as plain UTF-8. No code change - the bridge behaviour and its 75-test suite are untouched. --- src/api/providers/utils/abort-signal.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 167c4f7597b..8ec9b49ba0b 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -1,4 +1,4 @@ -/** +/** * Whether a timeout value is usable as an SDK `timeout` option: a finite * number greater than zero. * From 4e8b168ef625ddc5c042b584b1ae89b5d5f52c70 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:52:27 +0800 Subject: [PATCH 3/5] refactor(api): collapse the duplicate timeout error into the phase-aware one Two modules built the same report: abort-signal.ts exported a phase-less createTimeoutError(providerName) while request-timeout.ts exported a phase-aware createTimeoutError(providerName, phase) that produced the same message for a completion request. This keeps the phase-aware one as the only home, adds the optional cause the deadline call sites need, and switches the three remaining callers to name their phase. - friendli.ts: the catalog wait is model discovery, so a deadline seen there is reported as one; the shared-deadline guard after a successful wait still names the completion phase. - lm-studio.ts and qwen-code.ts: import line plus one argument - the message is byte-identical to what their specs already pin. - qwen-code.ts is the first caller that passes cause: its TimeoutError is classified from an abort-shaped failure already in hand, so it keeps it. Part of #2486 (unit U0b). Merge after U0a (#2626); the U1-U6 provider units rebase onto both. --- src/api/providers/__tests__/friendli.spec.ts | 12 ++++++++-- src/api/providers/__tests__/qwen-code.spec.ts | 4 ++++ src/api/providers/friendli.ts | 12 ++++++---- src/api/providers/lm-studio.ts | 6 +++-- src/api/providers/qwen-code.ts | 8 ++++--- .../utils/__tests__/abort-signal.spec.ts | 19 +++++++-------- .../utils/__tests__/request-timeout.spec.ts | 24 +++++++++++++++++++ src/api/providers/utils/abort-signal.ts | 13 +--------- src/api/providers/utils/request-timeout.ts | 21 ++++++++++++---- 9 files changed, 82 insertions(+), 37 deletions(-) diff --git a/src/api/providers/__tests__/friendli.spec.ts b/src/api/providers/__tests__/friendli.spec.ts index 1ff1b1475ba..fb68ef2f787 100644 --- a/src/api/providers/__tests__/friendli.spec.ts +++ b/src/api/providers/__tests__/friendli.spec.ts @@ -337,14 +337,22 @@ describe("FriendliHandler", () => { return {} }) - await expect(handler.completePrompt("a", { timeoutMs: 3000 })).rejects.toMatchObject({ name: "TimeoutError" }) + // The wait succeeded but consumed the shared deadline: the completion never ran. + await expect(handler.completePrompt("a", { timeoutMs: 3000 })).rejects.toMatchObject({ + name: "TimeoutError", + message: "The Friendli completion request timed out", + }) expect(mockCreate).not.toHaveBeenCalled() }) it("completePrompt should time out without a chat request when the catalog wait uses the deadline", async () => { mockGetModels.mockReturnValueOnce(new Promise(() => {})) - await expect(handler.completePrompt("a", { timeoutMs: 20 })).rejects.toMatchObject({ name: "TimeoutError" }) + // The catalog wait itself hit the deadline: that is model discovery, not a completion. + await expect(handler.completePrompt("a", { timeoutMs: 20 })).rejects.toMatchObject({ + name: "TimeoutError", + message: "The Friendli model discovery timed out", + }) expect(mockCreate).not.toHaveBeenCalled() }) diff --git a/src/api/providers/__tests__/qwen-code.spec.ts b/src/api/providers/__tests__/qwen-code.spec.ts index 5d81e90230a..8a7afdb099f 100644 --- a/src/api/providers/__tests__/qwen-code.spec.ts +++ b/src/api/providers/__tests__/qwen-code.spec.ts @@ -793,6 +793,10 @@ describe("QwenCodeHandler abort wiring", () => { expect(caught).toBeInstanceOf(Error) expect((caught as Error).name).toBe("TimeoutError") expect((caught as Error).message).toBe("The Qwen Code completion request timed out") + // The race inside settleOnAbort rejects with the contract AbortError once the merged + // signal fires; the TimeoutError keeps that failure as its cause instead of + // discarding it. + expect((caught as { cause?: { name?: string } }).cause?.name).toBe("AbortError") }) it("passes the merged signal through and nothing without options", async () => { diff --git a/src/api/providers/friendli.ts b/src/api/providers/friendli.ts index 1c8c276ce69..f56ba8e8f0e 100644 --- a/src/api/providers/friendli.ts +++ b/src/api/providers/friendli.ts @@ -1,4 +1,4 @@ -import { Anthropic } from "@anthropic-ai/sdk" +import { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" import { @@ -21,13 +21,13 @@ import { handleOpenAIError } from "./utils/error-handler" import { bridgeExternalAbortSignal, createAbortError, - createTimeoutError, hasUsableTimeout, isRequestAborted, isTimeoutAbort, mergeAbortSignalAndTimeout, toSdkTimeoutMs, } from "./utils/abort-signal" +import { createTimeoutError } from "./utils/request-timeout" import { NOT_PROVIDED } from "./constants" import { getModels } from "./fetchers/modelCache" import { getFriendliModels } from "./fetchers/friendli" @@ -109,7 +109,8 @@ export class FriendliHandler extends BaseOpenAiCompatibleProvider { diff --git a/src/api/providers/qwen-code.ts b/src/api/providers/qwen-code.ts index 23cb3806efb..cdbaaf977dc 100644 --- a/src/api/providers/qwen-code.ts +++ b/src/api/providers/qwen-code.ts @@ -1,4 +1,4 @@ -import { promises as fs } from "node:fs" +import { promises as fs } from "node:fs" import { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" import * as os from "os" @@ -21,9 +21,9 @@ import { isRequestAborted, settleOnAbort, type OpenAiRequestOptions, - createTimeoutError, isTimeoutAbort, } from "./utils/abort-signal" +import { createTimeoutError } from "./utils/request-timeout" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" const QWEN_OAUTH_BASE_URL = "https://chat.qwen.ai" @@ -492,7 +492,9 @@ export class QwenCodeHandler extends BaseProvider implements SingleCompletionHan // TimeoutError when the merged signal ended because its own timer // elapsed. The auth wait and the request both settle through here. if (isRequestAborted(error, requestSignal) && isTimeoutAbort(requestSignal)) { - throw createTimeoutError("Qwen Code") + // The deadline was classified from an abort-shaped failure already in hand; + // keep it as cause so the report holds both the deadline and what it was seen through. + throw createTimeoutError("Qwen Code", "completion request", error) } throw error } diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index c60b7dcb830..a0cbe099b7d 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -12,9 +12,9 @@ import { throwIfAborted, MAX_TIMEOUT_MS, toSdkTimeoutMs, - createTimeoutError, isTimeoutAbort, } from "../abort-signal" +import { createTimeoutError } from "../request-timeout" import { withSettleGuard } from "../../../../test-utils/settle-guard" import { flushMacrotasks } from "../../../../test-utils/timers" @@ -938,13 +938,12 @@ describe("toSdkTimeoutMs", () => { }) }) -describe("createTimeoutError", () => { - it("builds a TimeoutError naming the provider", () => { - const error = createTimeoutError("LM Studio") - - expect(error).toBeInstanceOf(Error) - expect(error.name).toBe("TimeoutError") - expect(error.message).toBe("The LM Studio completion request timed out") +describe("abort-signal module surface", () => { + it("does not re-declare the timeout error next to the phase-aware one", async () => { + // request-timeout.ts is the error's only home. A second definition here - or a + // re-export of it - is what this unit removed, and it would let the two drift again. + const abortSignalModule = await import("../abort-signal") + expect("createTimeoutError" in abortSignalModule).toBe(false) }) }) @@ -958,7 +957,7 @@ describe("isTimeoutAbort", () => { const timeout = new AbortController() const caller = new AbortController() const merged = mergeAbortSignals(timeout.signal, caller.signal) - timeout.abort(createTimeoutError("Qwen Code")) + timeout.abort(createTimeoutError("Qwen Code", "completion request")) caller.abort() expect(isTimeoutAbort(merged)).toBe(true) @@ -969,7 +968,7 @@ describe("isTimeoutAbort", () => { const caller = new AbortController() const merged = mergeAbortSignals(timeout.signal, caller.signal) caller.abort(new Error("user stop")) - timeout.abort(createTimeoutError("Qwen Code")) + timeout.abort(createTimeoutError("Qwen Code", "completion request")) expect(isTimeoutAbort(merged)).toBe(false) }) diff --git a/src/api/providers/utils/__tests__/request-timeout.spec.ts b/src/api/providers/utils/__tests__/request-timeout.spec.ts index 8190faebe36..3d20482288d 100644 --- a/src/api/providers/utils/__tests__/request-timeout.spec.ts +++ b/src/api/providers/utils/__tests__/request-timeout.spec.ts @@ -44,4 +44,28 @@ describe("createTimeoutError", () => { expect(error.name).toBe("TimeoutError") expect(error.message).toBe("The Gemini completion request timed out") }) + + it("names the phase that the phase-less build dropped", () => { + // A catalog wait is model discovery. Collapsing the duplicate definition into + // this one is what lets a caller report the phase that actually stalled. + const error = createTimeoutError("Friendli", "model discovery") + expect(error.name).toBe("TimeoutError") + expect(error.message).toBe("The Friendli model discovery timed out") + }) + + it("carries the failure the deadline was detected through", () => { + // A stalled response body or a late SDK rejection is not the deadline itself; + // cause keeps both facts in one report. + const cause = new Error("Response body stalled") + const error = createTimeoutError("Unbound", "completion request", cause) + expect(error.message).toBe("The Unbound completion request timed out") + expect(error.cause).toBe(cause) + }) + + it("leaves cause unset when the caller has no underlying failure", () => { + // A timer that elapsed on its own has nothing to attribute. Passing an + // undefined cause would make the error look attributed when it is not. + const error = createTimeoutError("Vercel AI Gateway", "model discovery") + expect("cause" in error).toBe(false) + }) }) diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 8ec9b49ba0b..e973e346ea0 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -1,4 +1,4 @@ -/** +/** * Whether a timeout value is usable as an SDK `timeout` option: a finite * number greater than zero. * @@ -344,17 +344,6 @@ export function settleOnAbort( return signal ? rejectOnAbort(pending, signal, providerName) : pending } -/** - * A per-request timeout is not a caller cancellation: report it as the distinct TimeoutError so - * callers can tell a stalled request from a user stop. A caller stop keeps using - * {@link createAbortError}; this error is only for a deadline the request itself hit. - */ -export function createTimeoutError(providerName: string): Error { - const timeoutError = new Error(`The ${providerName} completion request timed out`) - timeoutError.name = "TimeoutError" - return timeoutError -} - /** * Whether an abort-shaped failure came from the merged signal's own timeout rather than from the * caller's stop signal. diff --git a/src/api/providers/utils/request-timeout.ts b/src/api/providers/utils/request-timeout.ts index 672922415a5..3aaa32dc836 100644 --- a/src/api/providers/utils/request-timeout.ts +++ b/src/api/providers/utils/request-timeout.ts @@ -1,4 +1,4 @@ -/** +/** * 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 @@ -18,10 +18,23 @@ export function getRequestTimeoutMs(timeoutMs?: number): number | undefined { * Fresh error for a per-request deadline elapsing in a given phase. * * Distinct from the abort contract error on purpose: a timeout is not a user - * cancellation, and callers treat the two differently. + * cancellation, and callers treat the two differently. This is the only place the + * timeout error is built: `abort-signal.ts` used to carry a second, phase-less + * definition, so callers of the two modules assembled the same report from + * different code. + * + * `cause` carries the failure a deadline was detected through - a stalled response + * body, an SDK rejection raised after the timer fired - so the report keeps both + * the deadline that elapsed and what the request was waiting on. It is left unset + * when the caller has no underlying failure to report. */ -export function createTimeoutError(providerName: string, phase: "model discovery" | "completion request"): Error { - const timeoutError = new Error(`The ${providerName} ${phase} timed out`) +export function createTimeoutError( + providerName: string, + phase: "model discovery" | "completion request", + cause?: unknown, +): Error { + const message = `The ${providerName} ${phase} timed out` + const timeoutError = cause === undefined ? new Error(message) : new Error(message, { cause }) timeoutError.name = "TimeoutError" return timeoutError } From 5cfc463685db5b506ab2125b48d18ff76e0b9784 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:50:40 +0800 Subject: [PATCH 4/5] fix(api): drop the added byte-order marks and pin the cause by identity The invisible-chars pipeline reports the U+FEFF this branch put at the start of friendli.ts, qwen-code.ts, abort-signal.ts and request-timeout.ts; main has none, so all four are saved as plain UTF-8. The cause assertion now checks object identity. callApiWithRetry normalizes the SDK abort rejection into a fresh contract AbortError before the provider wraps it, so asserting only the cause's name would pass even if the provider threw a newly invented error away. The spec records the instances the contract helper creates - every other export still delegates to the real implementation - and asserts the TimeoutError's cause is one of them. --- src/api/providers/__tests__/qwen-code.spec.ts | 32 ++++++++++++++++--- src/api/providers/friendli.ts | 2 +- src/api/providers/qwen-code.ts | 2 +- src/api/providers/utils/abort-signal.ts | 2 +- src/api/providers/utils/request-timeout.ts | 2 +- 5 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/api/providers/__tests__/qwen-code.spec.ts b/src/api/providers/__tests__/qwen-code.spec.ts index 8a7afdb099f..123c784b362 100644 --- a/src/api/providers/__tests__/qwen-code.spec.ts +++ b/src/api/providers/__tests__/qwen-code.spec.ts @@ -8,6 +8,26 @@ vi.mock("node:fs", () => ({ }, })) +// callApiWithRetry normalizes any abort failure into a fresh contract AbortError before the +// provider's catch wraps it, so asserting that the TimeoutError carries *this request's* +// abort failure (not a newly invented one) requires recording the instances the contract +// helper creates. Every other export delegates to the real implementation. +const abortFailures = vi.hoisted(function (): Error[] { + return [] +}) +vi.mock("../utils/abort-signal", async (importOriginal) => { + // The factory's importOriginal is typed as unknown; recover the module's real type so + // the rest of the contract can be spread without `any`. + const actual = (await importOriginal()) as typeof import("../utils/abort-signal") + return { + ...actual, + createAbortError: function (providerName: string): Error { + const abortError = actual.createAbortError(providerName) + abortFailures.push(abortError) + return abortError + }, + } +}) const mockCreate = vi.fn() import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" @@ -793,10 +813,14 @@ describe("QwenCodeHandler abort wiring", () => { expect(caught).toBeInstanceOf(Error) expect((caught as Error).name).toBe("TimeoutError") expect((caught as Error).message).toBe("The Qwen Code completion request timed out") - // The race inside settleOnAbort rejects with the contract AbortError once the merged - // signal fires; the TimeoutError keeps that failure as its cause instead of - // discarding it. - expect((caught as { cause?: { name?: string } }).cause?.name).toBe("AbortError") + // The SDK rejection is normalized into a fresh contract AbortError by callApiWithRetry + // before the provider wraps it, so the cause can only be one of the abort errors this + // request actually created - not a discarded cause, and not an unrelated error. + const cause = (caught as { cause?: unknown }).cause + expect(cause).toBeInstanceOf(Error) + expect((cause as Error).name).toBe("AbortError") + expect((cause as Error).message).toBe("The Qwen Code request was aborted") + expect(abortFailures).toContain(cause) }) it("passes the merged signal through and nothing without options", async () => { diff --git a/src/api/providers/friendli.ts b/src/api/providers/friendli.ts index f56ba8e8f0e..95c904d6e1f 100644 --- a/src/api/providers/friendli.ts +++ b/src/api/providers/friendli.ts @@ -1,4 +1,4 @@ -import { Anthropic } from "@anthropic-ai/sdk" +import { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" import { diff --git a/src/api/providers/qwen-code.ts b/src/api/providers/qwen-code.ts index cdbaaf977dc..6f3db5816e5 100644 --- a/src/api/providers/qwen-code.ts +++ b/src/api/providers/qwen-code.ts @@ -1,4 +1,4 @@ -import { promises as fs } from "node:fs" +import { promises as fs } from "node:fs" import { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" import * as os from "os" diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index e973e346ea0..09d8bfdbb6c 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -1,4 +1,4 @@ -/** +/** * Whether a timeout value is usable as an SDK `timeout` option: a finite * number greater than zero. * diff --git a/src/api/providers/utils/request-timeout.ts b/src/api/providers/utils/request-timeout.ts index 3aaa32dc836..a725a19b6f3 100644 --- a/src/api/providers/utils/request-timeout.ts +++ b/src/api/providers/utils/request-timeout.ts @@ -1,4 +1,4 @@ -/** +/** * 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 From ca7513bad42c10a2268ccd4258d71a9a5de96177 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:34:07 +0800 Subject: [PATCH 5/5] refactor(api): bridge the Codex caller signal through the shared abort helper executeRequest built its own AbortController, linked the caller's signal to it by hand, and detached that listener with a removeEventListener call in the finally block. bridgeExternalAbortSignal does all three now: it hands back the request-local controller both transports abort through, relays a caller abort into it (a caller that already aborted reaches it the same way a live one does), and returns the detach handle the finally runs. Both transports keep using the controller's signal, so the abort verdicts, the messages and the SSE fallback stay exactly as they were. Two tests come with the move: the detach had no coverage before it, so dropping the call leaked the caller's listener silently. --- .../providers/__tests__/openai-codex.spec.ts | 67 +++++++++++++++++++ src/api/providers/openai-codex.ts | 31 ++++----- 2 files changed, 81 insertions(+), 17 deletions(-) diff --git a/src/api/providers/__tests__/openai-codex.spec.ts b/src/api/providers/__tests__/openai-codex.spec.ts index 216bf07c411..15a762331ff 100644 --- a/src/api/providers/__tests__/openai-codex.spec.ts +++ b/src/api/providers/__tests__/openai-codex.spec.ts @@ -1888,6 +1888,73 @@ describe("OpenAiCodexHandler.createMessage abort bridging", () => { await expect(collectStream(iter)).rejects.toThrow(/connectionFailed|stream torn down/) expect(captureException).toHaveBeenCalledTimes(2) }) + + // The bridge registers on the caller's long-lived signal, so a request that finishes + // normally has to detach it: a listener left behind retains this request's controller for + // as long as that signal lives, which is every completed request rather than the one in + // flight. + it("detaches the caller's abort listener when the stream completes", async () => { + const handler = createHandler() + const caller = new AbortController() + const addSpy = vitest.spyOn(caller.signal, "addEventListener") + const removeSpy = vitest.spyOn(caller.signal, "removeEventListener") + const create = vitest.fn().mockResolvedValue(createCompletedStream()) + Reflect.set(handler, "client", { responses: { create } }) + + await collectStream( + handler.createMessage("System", [{ role: "user", content: "Hello" }], { + taskId: "task-test", + abortSignal: caller.signal, + }), + ) + + // Every listener this request attached to the caller's signal must be detached again: + // the race on the token lookup and the bridge both register on it. + const added = addSpy.mock.calls.filter(([type]) => type === "abort").map(([, listener]) => listener) + const detached = removeSpy.mock.calls.filter(([type]) => type === "abort").map(([, listener]) => listener) + expect(added.length).toBeGreaterThan(0) + expect(detached).toEqual(expect.arrayContaining(added)) + }) + + // Only the consumer stopping the iteration can end this request: the SDK stream yields + // one event and then stays pending. Detaching the caller's listener has to run on that + // path too, or the generator that owned the request leaves a listener attached to a + // signal that outlives it. + it("detaches the caller's abort listener when the consumer stops early", async () => { + const handler = createHandler() + const caller = new AbortController() + const addSpy = vitest.spyOn(caller.signal, "addEventListener") + const removeSpy = vitest.spyOn(caller.signal, "removeEventListener") + let signalDuringRequest: AbortSignal | undefined + const create = vitest.fn().mockImplementation((_body: unknown, options: { signal: AbortSignal }) => { + signalDuringRequest = options.signal + return Promise.resolve( + (async function* () { + yield { type: "response.output_text.delta", delta: "first" } + await new Promise(() => {}) + })(), + ) + }) + Reflect.set(handler, "client", { responses: { create } }) + + const iter = handler.createMessage("System", [{ role: "user", content: "Hello" }], { + taskId: "task-test", + abortSignal: caller.signal, + }) + const first = await iter.next() + expect(first.value).toMatchObject({ type: "text", text: "first" }) + // The transport is handed the request-local controller's signal, never the caller's. + expect(signalDuringRequest).toBeInstanceOf(AbortSignal) + expect(signalDuringRequest).not.toBe(caller.signal) + + await iter.return(undefined) + + // The consumer stopping early ends the generator, and the detach runs on that path too. + const added = addSpy.mock.calls.filter(([type]) => type === "abort").map(([, listener]) => listener) + const detached = removeSpy.mock.calls.filter(([type]) => type === "abort").map(([, listener]) => listener) + expect(added.length).toBeGreaterThan(0) + expect(detached).toEqual(expect.arrayContaining(added)) + }) }) describe("OpenAiCodexHandler verbosity", () => { diff --git a/src/api/providers/openai-codex.ts b/src/api/providers/openai-codex.ts index 65a32f3928e..b827abb1676 100644 --- a/src/api/providers/openai-codex.ts +++ b/src/api/providers/openai-codex.ts @@ -30,6 +30,7 @@ import { sanitizeOpenAiCallId } from "../../utils/tool-id" import { openAiCodexOAuthManager } from "../../integrations/openai-codex/oauth" import { t } from "../../i18n" import { + bridgeExternalAbortSignal, createAbortError, isRequestAborted, mergeAbortSignalAndTimeout, @@ -510,22 +511,14 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion effectiveSessionId: string, abortSignal?: AbortSignal, ): ApiStream { - // Request-local controller: a stale abort arriving after this request finishes must never - // reach the controller of a later request, so the bridge listener captures this controller - // directly. - const abortController = new AbortController() - - // A caller's signal has to be linked rather than used directly, since both transports below - // abort through the request controller. Without this the signal never reaches the wire. - const abortFromCaller = () => abortController.abort() - - if (abortSignal) { - if (abortSignal.aborted) { - abortController.abort() - } else { - abortSignal.addEventListener("abort", abortFromCaller, { once: true }) - } - } + // A caller's signal has to be linked rather than used directly, since both transports + // below abort through one request-local controller: a stale abort arriving after this + // request finishes must never reach the controller of a later one. The bridge hands + // back that controller, relays a caller abort into it (a caller that already aborted + // reaches it the same way a live one does) and returns the handle the `finally` below + // uses to detach it. + const { controller: abortController, dispose: removeExternalAbortListener } = + bridgeExternalAbortSignal(abortSignal) try { // Prefer OpenAI SDK streaming (same approach as openai-native) so event handling @@ -609,7 +602,11 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion ) } } finally { - abortSignal?.removeEventListener("abort", abortFromCaller) + // Detach the bridge's listener from the caller's long-lived signal: this runs on + // completion, on failure, and on the consumer stopping the iteration early, so a + // finished request never leaves a listener (and this request's controller) retained + // by a signal that outlives it. + removeExternalAbortListener() } }