Skip to content
12 changes: 10 additions & 2 deletions src/api/providers/__tests__/friendli.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})

Expand Down
28 changes: 28 additions & 0 deletions src/api/providers/__tests__/qwen-code.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -793,6 +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 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)
Comment thread
easonLiangWorldedtech marked this conversation as resolved.
Resolved
})

it("passes the merged signal through and nothing without options", async () => {
Expand Down
10 changes: 7 additions & 3 deletions src/api/providers/friendli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@
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"
Expand Down Expand Up @@ -109,7 +109,8 @@
} catch {
// Classified below: only a cut-short wait is fatal.
}
if (isTimeoutAbort(signal)) throw createTimeoutError(this.providerName)
// The wait is the model catalog load, so a deadline seen here is model discovery.
if (isTimeoutAbort(signal)) throw createTimeoutError(this.providerName, "model discovery")
if (signal?.aborted) throw createAbortError(this.providerName)
}

Expand Down Expand Up @@ -272,7 +273,10 @@
const deadline = hasUsableTimeout(timeoutMs) ? Date.now() + timeoutMs : undefined
await this.waitForCatalog(options?.abortSignal, timeoutMs)
const remainingMs = deadline === undefined ? undefined : deadline - Date.now()
if (remainingMs !== undefined && remainingMs <= 0) throw createTimeoutError(this.providerName)
// The wait succeeded but spent the shared deadline: the completion never got a turn.
if (remainingMs !== undefined && remainingMs <= 0) {

Check warning on line 277 in src/api/providers/friendli.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/api/providers/friendli.ts:277: Survived ConditionalExpression mutant (replacement: true). See the job summary for the complete list and resolution guidance.
throw createTimeoutError(this.providerName, "completion request")
}
const { id: modelId } = this.getModel()
const friendliExtra = this.buildFriendliReasoningParams()

Expand Down
41 changes: 20 additions & 21 deletions src/api/providers/lm-studio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,16 @@ import type {
import { getModels, getModelsFromCache } from "./fetchers/modelCache"
import { getLMStudioModels } from "./fetchers/lmstudio"
import {
bridgeExternalAbortSignal,
mergeAbortSignalAndTimeout,
throwIfAborted,
createAbortError,
createTimeoutError,
isRequestAborted,
isTimeoutAbort,
settleOnAbort,
type OpenAiRequestOptions,
} from "./utils/abort-signal"
import { createTimeoutError } from "./utils/request-timeout"
import { handleOpenAIError } from "./utils/error-handler"
import { extractReasoningFromDelta } from "./utils/extract-reasoning"

Expand Down Expand Up @@ -120,22 +121,17 @@ export class LmStudioHandler extends BaseProvider implements SingleCompletionHan
return result
}

// Request-local abort controller — a class field would outlive this
// request and let concurrent requests abort each other. It is created
// before the token counts so an abort landing while either count is
// pending settles this generator promptly instead of waiting for the
// count to finish.
const requestController = new AbortController()
const onExternalAbort = () => {
requestController.abort()
}
// Request-local cancellation scope — a class field would outlive this request and let
// concurrent requests abort each other. It is established before the token counts so an
// abort landing while either count is pending settles this generator promptly instead
// of waiting for the count to finish. The bridge relays the caller's signal into the
// controller (a caller that already aborted reaches it the same way) and still hands
// back a request-local signal when the caller passed none, which the counts, the SDK
// request options and the pre-issue guard below all need.
const { controller: requestController, dispose: removeExternalAbortListener } = bridgeExternalAbortSignal(
metadata?.abortSignal,
)
const externalSignal = metadata?.abortSignal
if (externalSignal) {
// Nothing is awaited between throwIfAborted above and this registration,
// so the signal cannot have aborted in between; the listener alone covers
// an abort landing while either token count is pending.
externalSignal.addEventListener("abort", onExternalAbort)
}

try {
let inputTokens = 0
Expand Down Expand Up @@ -295,11 +291,12 @@ export class LmStudioHandler extends BaseProvider implements SingleCompletionHan
} finally {
// Cancel the in-flight SDK request if the consumer stopped iterating
// early (break or return): the external signal may never fire in that
// case, and only the request-local signal reaches the SDK.
// case, and only the request-local signal reaches the SDK. Detaching the
// bridge's listener runs on the same three paths — completion, failure
// and early exit — so no completed request leaves one attached to the
// caller's long-lived signal.
requestController.abort()
if (externalSignal) {
externalSignal.removeEventListener("abort", onExternalAbort)
}
removeExternalAbortListener()
}
}

Expand Down Expand Up @@ -330,7 +327,9 @@ export class LmStudioHandler extends BaseProvider implements SingleCompletionHan
* and the outer completion catch, so it lives in one helper.
*/
private toCompletionAbortError(requestSignal: AbortSignal | undefined): Error {
return isTimeoutAbort(requestSignal) ? createTimeoutError("LM Studio") : createAbortError("LM Studio")
return isTimeoutAbort(requestSignal)
? createTimeoutError("LM Studio", "completion request")
: createAbortError("LM Studio")
}

async completePrompt(prompt: string, options?: CompletePromptOptions): Promise<string> {
Expand Down
32 changes: 17 additions & 15 deletions src/api/providers/qwen-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@ import { BaseProvider } from "./base-provider"
import { RequestConfigBuilder } from "./config-builder/request-config-builder"
import { extractReasoningFromDelta } from "./utils/extract-reasoning"
import {
bridgeExternalAbortSignal,
mergeAbortSignalAndTimeout,
throwIfAborted,
createAbortError,
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"
Expand Down Expand Up @@ -282,16 +283,15 @@ export class QwenCodeHandler extends BaseProvider implements SingleCompletionHan
// Fast-fail if the caller’s stop signal already fired before we started.
throwIfAborted(metadata?.abortSignal)

// Request-local abort controller — a class field would outlive this
// request and let concurrent requests abort each other.
const requestController = new AbortController()
const onExternalAbort = () => {
requestController.abort()
}
// Request-local cancellation scope — a class field would outlive this request and
// let concurrent requests abort each other. The bridge relays the caller's signal
// into the controller (a caller that already aborted reaches it the same way) and
// hands back a request-local signal even when the caller passed none, which the auth
// wait and the SDK request options below both need.
const { controller: requestController, dispose: removeExternalAbortListener } = bridgeExternalAbortSignal(
metadata?.abortSignal,
)
const externalSignal = metadata?.abortSignal
if (externalSignal) {
externalSignal.addEventListener("abort", onExternalAbort)
}

try {
// A stop can land while the credential load or the token refresh
Expand Down Expand Up @@ -432,11 +432,11 @@ export class QwenCodeHandler extends BaseProvider implements SingleCompletionHan
} finally {
// Cancel the in-flight SDK request if the consumer stopped iterating
// early (break or return): the external signal may never fire in that
// case, and only the request-local signal reaches the SDK.
// case, and only the request-local signal reaches the SDK. Detaching the
// bridge's listener runs on the same three paths, so a completed request
// never leaves one attached to the caller's long-lived signal.
requestController.abort()
if (externalSignal) {
externalSignal.removeEventListener("abort", onExternalAbort)
}
removeExternalAbortListener()
}
}

Expand Down Expand Up @@ -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
}
Expand Down
98 changes: 88 additions & 10 deletions src/api/providers/utils/__tests__/abort-signal.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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", () => {
Expand Down Expand Up @@ -859,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)
})
})

Expand All @@ -879,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)
Expand All @@ -890,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)
})
Expand Down
Loading
Loading