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
76 changes: 26 additions & 50 deletions src/api/providers/openai-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ import { NOT_PROVIDED } from "./constants"
import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index"
import { isMcpTool } from "../../utils/mcp-name"
import { sanitizeOpenAiCallId } from "../../utils/tool-id"
import { createAbortError, isRequestAborted, mergeAbortSignalAndTimeout } from "./utils/abort-signal"
import {
bridgeExternalAbortSignal,
createAbortError,
isRequestAborted,
mergeAbortSignalAndTimeout,
} from "./utils/abort-signal"
import { createTimeoutError, getRequestTimeoutMs } from "./utils/request-timeout"
import { getNumericHttpStatus, hasNumericHttpStatus } from "./utils/error-handler"

Expand Down Expand Up @@ -448,32 +453,6 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio
return body
}

/**
* Bridges an external abort signal (e.g. task cancellation) onto a request-local
* controller using the Bedrock pattern: a pre-aborted signal aborts the controller
* immediately and registers no listener; otherwise a once-only listener forwards
* the abort. Returns a cleanup function that detaches the listener (or undefined
* when no listener was registered) so the caller can release it in its finally
* block and a late abort can never reach a later request's controller.
*/
private attachExternalAbort(
externalAbortSignal: AbortSignal | undefined,
requestController: AbortController,
): (() => void) | undefined {
if (!externalAbortSignal) {
return undefined
}
if (externalAbortSignal.aborted) {
requestController.abort()
return undefined
}
const abortListener = () => requestController.abort()
externalAbortSignal.addEventListener("abort", abortListener, { once: true })
return () => {
externalAbortSignal.removeEventListener("abort", abortListener)
}
}

/**
* Streams a Responses API request through the official OpenAI SDK.
*
Expand All @@ -500,20 +479,19 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio
systemPrompt?: string,
messages?: Anthropic.Messages.MessageParam[],
): ApiStream {
// Create a request-local AbortController for cancellation. The field is still
// assigned so the finally can tell which request still owns it, but all bridging
// below captures the local reference so a late abort from an earlier request can
// never reach a later request's controller. The field is not a cancellation
// entry point and is not how a stop is delivered: the only reads of it in this
// file are the two ownership checks in the finallys, and a cancellation arrives
// from the caller's signal, bridged by attachExternalAbort below.
// Create a request-local AbortController for cancellation. The field is still assigned so
// the finally can tell which request still owns it, and so the stop-button path keeps
// observing the one controller this request is cancelled through: the bridge below is
// handed this controller instead of making its own. The field is not a cancellation entry
// point - the only reads of it in this file are the two ownership checks in the finallys -
// and a cancellation arrives from the caller's signal.
const requestController = new AbortController()
this.abortController = requestController

// Bridge the external abort signal onto the request controller; the returned
// cleanup detaches the listener in the finally block so a late abort from this
// request cannot cancel a later request's controller.
const detach = this.attachExternalAbort(metadata?.abortSignal, requestController)
// Bridge the external abort signal onto the request controller. A pre-aborted signal
// aborts it immediately and registers no listener; dispose() in the finally block detaches
// the listener so a late abort from this request cannot cancel a later request's controller.
const bridge = bridgeExternalAbortSignal(metadata?.abortSignal, { controller: requestController })

// Build per-request headers for API tracking and debugging
const userAgent = `zoo-code/${Package.version} (${os.platform()} ${os.release()}; ${os.arch()}) node/${process.version.slice(1)}`
Expand Down Expand Up @@ -616,7 +594,7 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio
} finally {
// Detach the bridging listener so a late abort from this request cannot
// cancel a later request's controller.
detach?.()
bridge.dispose()
// Only clear the field if this request still owns it (the fallback path may
// have installed its own controller, which it clears itself).
if (this.abortController === requestController) {
Expand Down Expand Up @@ -751,19 +729,17 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio
const baseUrl = this.options.openAiNativeBaseUrl || "https://api.openai.com"
const url = `${baseUrl}/v1/responses`

// Create a request-local AbortController for cancellation. The field is still
// assigned for the ownership check in the finally below, but the bridging
// listener captures the local reference so a late abort from an earlier request
// can never reach a later request's controller. Cancellation arrives through
// the caller's signal via attachExternalAbort; nothing aborts a request by
// reading this field.
// Create a request-local AbortController for cancellation. The field is still assigned for
// the ownership check in the finally below, and the bridge below is handed this same
// controller so the stop-button handle and the SSE fallback observe the controller that is
// actually cancelled. Nothing aborts a request by reading the field.
const requestController = new AbortController()
this.abortController = requestController

// Bridge the external abort signal onto the request controller; the returned
// cleanup detaches the listener in the finally block so a late abort from this
// request cannot cancel a later request's controller.
const detach = this.attachExternalAbort(metadata?.abortSignal, requestController)
// Bridge the external abort signal onto the request controller; dispose() in the finally
// block detaches the listener so a late abort from this request cannot cancel a later
// request's controller.
const bridge = bridgeExternalAbortSignal(metadata?.abortSignal, { controller: requestController })

// Build per-request headers for API tracking and debugging
const userAgent = `zoo-code/${Package.version} (${os.platform()} ${os.release()}; ${os.arch()}) node/${process.version.slice(1)}`
Expand Down Expand Up @@ -894,7 +870,7 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio
} finally {
// Detach the bridging listener so a late abort from this request cannot
// cancel a later request's controller.
detach?.()
bridge.dispose()
if (this.abortController === requestController) {
this.abortController = undefined
}
Expand Down
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