Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
3b899ce
feat(api): abort signal support for openai-native provider (completeP…
easonliang28 Aug 19, 2026
d53b955
feat(api): abort signal support for openai-compatible provider (compl…
easonliang28 Aug 19, 2026
2296b74
fix(api): address CodeRabbit review on openai-native and openai-compa…
easonliang28 Aug 19, 2026
176a0fa
test(api): clear leftover guard timers in openai-compatible abort tests
easonliang28 Aug 19, 2026
cb153ec
refactor(api): adopt RequestConfigBuilder in feat/abort-r1-openai-nat…
easonliang28 Aug 20, 2026
4702738
test(api): cover primary-signal abort in builder merge regression tests
easonliang28 Aug 20, 2026
f371082
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonLiangWorldedtech Aug 30, 2026
48e30d5
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonLiangWorldedtech Sep 1, 2026
1c925d0
Merge remote-tracking branch 'upstream/main' into feat/abort-r1-opena…
easonliang28 Sep 2, 2026
7dee99d
Merge branch 'main' into feat/abort-r1-openai-native-compat
edelauna Sep 3, 2026
b16d5ad
test(api): kill abort-signal mutation survivors in openai-native/open…
easonliang28 Sep 5, 2026
118b921
test(api): exclude proven-equivalent openai-native OptionalChaining m…
easonliang28 Sep 5, 2026
ba72b77
fix(api): address reviewer abort-signal findings in openai-native and…
easonliang28 Sep 5, 2026
dfb93de
Merge remote-tracking branch 'upstream/main' into feat/abort-r1-opena…
easonliang28 Sep 5, 2026
0488a39
test(api): reuse the open-stream fetch fixture and assert listener id…
easonliang28 Sep 5, 2026
1e22dfe
Merge branch main into feat/abort-r1-openai-native-compat
easonliang28 Sep 6, 2026
ad71368
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonLiangWorldedtech Sep 15, 2026
d9ec5a3
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonliang28 Sep 28, 2026
e948680
fix(api): per-request abort check in fallback SSE loop and release bo…
easonliang28 Sep 28, 2026
df16983
fix(api): normalize completePrompt SDK aborts to the contract AbortError
easonliang28 Sep 28, 2026
bfc880c
fix(api): classify SDK cancellations from the error alone, never from…
easonliang28 Sep 28, 2026
4a07a4e
Merge remote-tracking branch 'upstream/main' into feat/abort-r1-opena…
Oct 2, 2026
3717280
preflight synthetic head
Oct 2, 2026
f9d5d00
test: kill catch-path mutants + document equivalent streamCompleted c…
Oct 2, 2026
fff974d
preflight synthetic head
Oct 2, 2026
5e983df
chore: re-trigger CI (flaky e2e-mock restart-persistence timeout)
Oct 2, 2026
8389c31
test(abort-r1): assert the fallback request signal and the empty stre…
Oct 2, 2026
32bbf6b
test(abort-r1): pin the fallback fetch to exactly one call
Oct 2, 2026
c942a45
fix(abort-r1): hand back the contract AbortError on a mid-stream abort
Oct 2, 2026
2541747
fix(abort-r1): report the contract AbortError when the SDK iterator e…
Oct 2, 2026
fa62d91
Merge commit 'refs/shapes/upstream-main' into feat/abort-r1-openai-na…
Oct 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
297 changes: 297 additions & 0 deletions src/api/providers/__tests__/openai-compatible.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,297 @@
// npx vitest run api/providers/__tests__/openai-compatible.spec.ts

import { OpenAICompatibleHandler } from "../openai-compatible"
import { makeApiHandlerOptions } from "../../../test-utils/api"
import { collectStream } from "../../../test-utils/stream"

const mockGenerateText = vitest.fn()
const mockStreamText = vitest.fn()

// The factory must not touch the mock bindings at factory-execution time (vi.mock is
// hoisted above the consts), so forward lazily through wrapper functions.
vitest.mock("ai", () => ({
generateText: (...args: unknown[]) => mockGenerateText(...(args as [])),
streamText: (...args: unknown[]) => mockStreamText(...(args as [])),
}))

// Concrete test implementation of the abstract OpenAI-compatible base class
class TestOpenAICompatibleHandler extends OpenAICompatibleHandler {
constructor(apiKey: string) {
super(makeApiHandlerOptions({ apiModelId: "test-model" }), {
providerName: "TestProvider",
baseURL: "https://test.example.com/v1",
apiKey,
modelId: "test-model",
modelInfo: {
maxTokens: 4096,
contextWindow: 128000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 1.5,
},
})
}

override getModel() {
return { id: "test-model", info: this.config.modelInfo }
}
}

function makeEmptyStreamResult() {
return {
fullStream: {
[Symbol.asyncIterator]: async function* () {
// Emit no parts
yield* []
},
},
usage: Promise.resolve(undefined),
}
}

describe("OpenAICompatibleHandler", () => {
let handler: TestOpenAICompatibleHandler

beforeEach(() => {
vi.clearAllMocks()
handler = new TestOpenAICompatibleHandler("test-api-key")
})

describe("completePrompt", () => {
it("should return message content from successful response", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

const result = await handler.completePrompt("test prompt")

expect(result).toBe("response")
expect(mockGenerateText).toHaveBeenCalledTimes(1)
expect(mockGenerateText.mock.calls[0][0].prompt).toBe("test prompt")
})

it("should pass abortSignal through to generateText", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

const controller = new AbortController()
await handler.completePrompt("test prompt", { abortSignal: controller.signal })

expect(mockGenerateText.mock.calls[0][0].abortSignal).toBe(controller.signal)
})

it("should pass timeoutMs through to generateText as a working timeout abort signal", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

await handler.completePrompt("test prompt", { timeoutMs: 50 })

const { abortSignal } = mockGenerateText.mock.calls[0][0]
expect(abortSignal).toBeInstanceOf(AbortSignal)
expect(abortSignal.aborted).toBe(false)

// A never-expiring signal (or a pre-aborted one) would fail this check:
// the signal must fire on its own ~50ms timeout without any external abort.
let guardTimer: ReturnType<typeof setTimeout> | undefined
const fired = await Promise.race([
new Promise<boolean>((resolve) => {
abortSignal.addEventListener("abort", () => resolve(true), { once: true })
}),
new Promise<boolean>((resolve) => {
guardTimer = setTimeout(() => resolve(false), 1000)
}),
])
try {
expect(fired).toBe(true)
expect(abortSignal.aborted).toBe(true)
} finally {
// Clear the guard timer so a winning abort event does not leave an
// active timer behind that delays worker teardown.
clearTimeout(guardTimer)
}
})

it("should merge signal and timeout when both are provided", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

const controller = new AbortController()
await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 50 })

const mergedSignal = mockGenerateText.mock.calls[0][0].abortSignal as AbortSignal
expect(mergedSignal).toBeInstanceOf(AbortSignal)
expect(mergedSignal.aborted).toBe(false)

// Aborting the external signal must abort the merged signal synchronously
controller.abort()
expect(mergedSignal.aborted).toBe(true)
})

it("should let the timeout component of a merged signal fire without the caller signal", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

await handler.completePrompt("test prompt", { abortSignal: new AbortController().signal, timeoutMs: 50 })

const mergedSignal = mockGenerateText.mock.calls[0][0].abortSignal as AbortSignal
expect(mergedSignal).toBeInstanceOf(AbortSignal)
expect(mergedSignal.aborted).toBe(false)

// With the caller signal left untouched, only the timeout component can fire
let guardTimer: ReturnType<typeof setTimeout> | undefined
const fired = await Promise.race([
new Promise<boolean>((resolve) => {
mergedSignal.addEventListener("abort", () => resolve(true), { once: true })
}),
new Promise<boolean>((resolve) => {
guardTimer = setTimeout(() => resolve(false), 1000)
}),
])
try {
expect(fired).toBe(true)
expect(mergedSignal.aborted).toBe(true)
} finally {
// Clear the guard timer so a winning abort event does not leave an
// active timer behind that delays worker teardown.
clearTimeout(guardTimer)
}
})

it("should work without options (backward compatible)", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

const result = await handler.completePrompt("test prompt")

expect(result).toBe("response")
expect(mockGenerateText.mock.calls[0][0].abortSignal).toBeUndefined()
})

it("should treat timeoutMs <= 0 as disabled", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

await handler.completePrompt("test prompt", { timeoutMs: 0 })
expect(mockGenerateText.mock.calls[0][0].abortSignal).toBeUndefined()

await handler.completePrompt("test prompt", { timeoutMs: -1 })
expect(mockGenerateText.mock.calls[1][0].abortSignal).toBeUndefined()
})

it("should pass the caller signal unchanged when timeoutMs is 0", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

const controller = new AbortController()
await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 0 })

// A disabled timeout must not drop the caller's cancellation signal
expect(mockGenerateText.mock.calls[0][0].abortSignal).toBe(controller.signal)
})

it("should pass the caller signal unchanged when timeoutMs is negative", async () => {
mockGenerateText.mockResolvedValue({ text: "response" })

const controller = new AbortController()
await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: -1 })

expect(mockGenerateText.mock.calls[0][0].abortSignal).toBe(controller.signal)
})

it("should reject with AbortError when abortSignal is already aborted before request", async () => {
Comment thread
easonLiangWorldedtech marked this conversation as resolved.
Outdated
mockGenerateText.mockImplementation((options: { abortSignal?: AbortSignal }) => {
if (options.abortSignal?.aborted) {
const error = new Error("This operation was aborted")
error.name = "AbortError"
return Promise.reject(error)
}
return Promise.resolve({ text: "response" })
})

const controller = new AbortController()
controller.abort()

await expect(
handler.completePrompt("test prompt", { abortSignal: controller.signal }),
).rejects.toMatchObject({
name: "AbortError",
})
})

it("should throw handled error when API call fails", async () => {
mockGenerateText.mockRejectedValue(new Error("Network error"))

await expect(handler.completePrompt("test prompt")).rejects.toThrow("Network error")
})
})

describe("createMessage", () => {
it("should pass the external abortSignal to streamText", async () => {
mockStreamText.mockReturnValue(makeEmptyStreamResult())

const controller = new AbortController()
const stream = handler.createMessage("You are helpful.", [], {
taskId: "test",
abortSignal: controller.signal,
})
await collectStream(stream)

expect(mockStreamText).toHaveBeenCalledTimes(1)
expect(mockStreamText.mock.calls[0][0].abortSignal).toBe(controller.signal)
})

it("should not set an abortSignal when metadata has none", async () => {
mockStreamText.mockReturnValue(makeEmptyStreamResult())

const stream = handler.createMessage("You are helpful.", [], { taskId: "test" })
await collectStream(stream)

expect(mockStreamText.mock.calls[0][0].abortSignal).toBeUndefined()
})

it("should reject with AbortError when the external abortSignal is pre-aborted", async () => {
mockStreamText.mockImplementation((options: { abortSignal?: AbortSignal }) => ({
fullStream: {
[Symbol.asyncIterator]: async function* () {
if (options.abortSignal?.aborted) {
const error = new Error("This operation was aborted")
error.name = "AbortError"
throw error
}
yield* []
},
},
usage: Promise.resolve(undefined),
}))

const controller = new AbortController()
controller.abort()

const stream = handler.createMessage("You are helpful.", [], {
taskId: "test",
abortSignal: controller.signal,
})
await expect(collectStream(stream)).rejects.toMatchObject({ name: "AbortError" })
})

it("should abort the stream when the external abortSignal is aborted mid-request", async () => {
mockStreamText.mockImplementation((options: { abortSignal?: AbortSignal }) => ({
fullStream: {
[Symbol.asyncIterator]: async function* () {
// Emulate a slow model response that ends when the request is aborted
await new Promise<void>((resolve) => {
options.abortSignal?.addEventListener("abort", () => resolve(), { once: true })
})
yield* []
const error = new Error("This operation was aborted")
error.name = "AbortError"
throw error
},
},
usage: Promise.resolve(undefined),
}))

const controller = new AbortController()
const stream = handler.createMessage("You are helpful.", [], {
taskId: "test",
abortSignal: controller.signal,
})
const collected = collectStream(stream)
setTimeout(() => controller.abort(), 10)

await expect(collected).rejects.toMatchObject({ name: "AbortError" })
})
})
})
Loading
Loading