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
6 changes: 4 additions & 2 deletions src/api/providers/lm-studio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ import {
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 @@ -330,7 +330,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
81 changes: 36 additions & 45 deletions src/api/providers/native-ollama.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { getOllamaModels, isSecureOllamaEndpoint } from "./fetchers/ollama"
import { MODEL_CATALOG_FETCH_TIMEOUT_MS } from "./fetchers/modelCache"
import {
bridgeExternalAbortSignal,
createAbortError,
hasUsableTimeout,
mergeAbortSignalAndTimeout,
Expand Down Expand Up @@ -466,20 +467,16 @@
throw createAbortError("Ollama")
}

const requestController = new AbortController()

let onExternalAbort: (() => void) | undefined
// The client is created inside the try below, so the hook reads it through a
// binding: an abort landing before the assignment has no client to cancel yet.
let client: Ollama | undefined
const bridge = bridgeExternalAbortSignal(externalAbortSignal, {
onAbort: () => client?.abort(),

Check warning on line 474 in src/api/providers/native-ollama.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/api/providers/native-ollama.ts:474: Survived OptionalChaining mutant (replacement: client.abort). See the job summary for the complete list and resolution guidance.
})
try {
// Inside the try so a constructor error gets the same handling as a
// request error.
const client = this._createOllamaClient(requestController.signal)
if (externalAbortSignal) {
onExternalAbort = () => {
requestController.abort()
client.abort()
}
externalAbortSignal.addEventListener("abort", onExternalAbort)
}
client = this._createOllamaClient(bridge.controller.signal)

// Cancel this wait without cancelling discovery for other requests.
// Do not start chat after this request is aborted.
Expand Down Expand Up @@ -640,17 +637,15 @@
console.error(`Ollama API error (${statusCode || "unknown"}): ${errorMessage}`)
throw error
} finally {
// Detach the external-signal listener so it cannot outlive this request,
// including when model discovery rejects before the chat request starts.
if (onExternalAbort && externalAbortSignal) {
externalAbortSignal.removeEventListener("abort", onExternalAbort)
}
// Detach the bridge listener so it cannot outlive this request, including when
// model discovery rejects before the chat request starts.
bridge.dispose()
// A consumer that stops iterating early (break/return) would otherwise
// leave the in-flight response body open, and when metadata.abortSignal
// is undefined no abort bridge exists at all. The per-request controller
// drives the injected fetch transport, so aborting it here releases the
// body; after normal completion the abort is a no-op.
requestController.abort()
bridge.controller.abort()
}
}

Expand Down Expand Up @@ -689,15 +684,26 @@
// per-call signal, so every request uses a per-request client. The
// per-request controller drives the abortable transport injected into the
// client, so the in-flight POST itself is cancellable.
const requestController = new AbortController()
const controller = new AbortController()
let timeoutId: ReturnType<typeof setTimeout> | undefined
let onAbort: (() => void) | undefined
let detachBridge: (() => void) | undefined
const abortSignal = options?.abortSignal
let client: Ollama | undefined

try {
// Inside the try so a constructor error gets the same wrap as a
// request error.
const client = this._createOllamaClient(requestController.signal)
client = this._createOllamaClient(controller.signal)

// Bridge after the client exists: the helper runs onAbort right away when the caller's
// signal was already aborted at call time, so the client-level cancel this path used to
// duplicate in its pre-abort branch now arrives through the same hook a live abort
// uses. The listener is registered with { once: true } and detachBridge drops it.
const bridge = bridgeExternalAbortSignal(abortSignal, {
controller,
onAbort: () => client?.abort(),

Check warning on line 704 in src/api/providers/native-ollama.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/api/providers/native-ollama.ts:704: Survived OptionalChaining mutant (replacement: client.abort). See the job summary for the complete list and resolution guidance.
})
detachBridge = bridge.dispose

// Handle timeoutMs if provided (the client exists, so the timer can
// abort both the per-request transport and the client)
Expand All @@ -706,35 +712,21 @@
// toSdkTimeoutMs rounds up and caps the delay (Node clamps larger
// values to 1 ms), matching mergeAbortSignalAndTimeout.
timeoutId = setTimeout(() => {
requestController.abort()
client.abort()
controller.abort()
client?.abort()

Check warning on line 716 in src/api/providers/native-ollama.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/api/providers/native-ollama.ts:716: Survived OptionalChaining mutant (replacement: client.abort). See the job summary for the complete list and resolution guidance.
}, toSdkTimeoutMs(timeoutMs))
}

// Propagate abortSignal into the per-request client via client.abort()
// and the per-request transport. Set this up before fetchModel() so an
// already-aborted signal (or one that aborts during the model-list
// fetch) is honored before the request proceeds.
if (abortSignal) {
if (abortSignal.aborted) {
requestController.abort()
client.abort()
throw createAbortError("Ollama")
} else {
onAbort = () => {
requestController.abort()
client.abort()
// The per-request timeout is cleared by the finally block when this prompt
// settles; an external abort always settles it promptly (the discovery race
// or the injected transport rejects), so no timer clear is needed here.
}
abortSignal.addEventListener("abort", onAbort, { once: true })
}
// A caller that aborted before this call started: the bridge already cancelled both
// the transport and the client through the hook, so only the contract error is
// produced here.
if (abortSignal?.aborted) {

Check warning on line 723 in src/api/providers/native-ollama.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/api/providers/native-ollama.ts:723: Survived ConditionalExpression mutant (replacement: false). See the job summary for the complete list and resolution guidance.
throw createAbortError("Ollama")
}

// The request deadline cancels this wait. Shared discovery keeps its
// own timeout so other requests can still use the result.
const discoverySignal = mergeAbortSignalAndTimeout(requestController.signal, options?.timeoutMs)
const discoverySignal = mergeAbortSignalAndTimeout(controller.signal, options?.timeoutMs)
// mergeAbortSignalAndTimeout yields undefined when neither an external
// signal nor a positive timeout applies; no race is needed then.
const { id: modelId } = discoverySignal
Expand Down Expand Up @@ -766,9 +758,8 @@
throw error
} finally {
clearTimeout(timeoutId)
if (onAbort && abortSignal) {
abortSignal.removeEventListener("abort", onAbort)
}
// Detach the bridge listener whether or not a client was ever created.
detachBridge?.()
}
}
}
6 changes: 4 additions & 2 deletions src/api/providers/qwen-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
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
Loading
Loading