diff --git a/docs/architecture/tla/KimiOAuthRefresh.Variant.cfg b/docs/architecture/tla/KimiOAuthRefresh.Variant.cfg new file mode 100644 index 00000000000..7f1c0dbf724 --- /dev/null +++ b/docs/architecture/tla/KimiOAuthRefresh.Variant.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sabotage = TRUE +INVARIANTS TypeOK IssuedPairKept SignOutWins diff --git a/docs/architecture/tla/KimiOAuthRefresh.cfg b/docs/architecture/tla/KimiOAuthRefresh.cfg new file mode 100644 index 00000000000..e7226529786 --- /dev/null +++ b/docs/architecture/tla/KimiOAuthRefresh.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sabotage = FALSE +INVARIANTS TypeOK IssuedPairKept SignOutWins diff --git a/docs/architecture/tla/KimiOAuthRefresh.tla b/docs/architecture/tla/KimiOAuthRefresh.tla new file mode 100644 index 00000000000..7773f40ce80 --- /dev/null +++ b/docs/architecture/tla/KimiOAuthRefresh.tla @@ -0,0 +1,111 @@ +---- MODULE KimiOAuthRefresh ---- +EXTENDS Naturals +\* Models the shared refresh state in src/integrations/kimi-code/oauth.ts. +\* Source: the caller detach in awaitRefresh. Sink: the credential write in writeCredentials. +\* Failure 1: a waiter that detaches while the server is answering drops the pair the server issued. +\* The provider rotated the refresh token, so that pair is the only copy of it. +\* Failure 2: a sign-out that lands during a refresh still lets that refresh write its pair. +\* Invariants: IssuedPairKept (failure 1), SignOutWins (failure 2). +\* Expected before any run: both invariants hold in the model. The sabotage variant fails in 2 states. +\* Run status: TLC was NOT run for this file. The machine that wrote it has no Java and no TLA+ jar, +\* so ./check.sh could not be executed. Run it before merging: TLA_JAR= ./check.sh KimiOAuthRefresh +\* Cost: 7 actions, 1 constant, 6 variables. The state space is small; expect under a second. +\* Not modeled: the device-flow polling, the request deadline, and the write chain ordering of two +\* concurrent saves. Those are covered by the unit rows in __tests__/oauth.spec.ts. +\* Review: written after the change. It is not an independent first pass. + +CONSTANT Sabotage \* TRUE runs the sabotage variant: a detach during the answer drops the pair + +VARIABLE phase \* "idle", "posted", "answered", "done" +VARIABLE waiters \* 0..2 callers enrolled in the one shared refresh +VARIABLE saved \* "old", "new", or "absent": the persisted pair +VARIABLE signedOut \* TRUE after a sign-out +VARIABLE gen \* credentials generation, the token a write must still hold +VARIABLE captured \* the generation the running refresh captured + +vars == <> + +TypeOK == + /\ phase \in {"idle", "posted", "answered", "done"} + /\ waiters \in 0..2 + /\ saved \in {"old", "new", "absent"} + /\ signedOut \in BOOLEAN + /\ gen \in 0..2 + /\ captured \in 0..2 + +Init == + /\ phase = "idle" + /\ waiters = 0 + /\ saved = "old" + /\ signedOut = FALSE + /\ gen = 0 + /\ captured = 0 + +\* A caller starts the shared refresh and captures the generation it will write under. +Start == + /\ phase = "idle" + /\ phase' = "posted" + /\ captured' = gen + /\ waiters' = 1 + /\ UNCHANGED <> + +\* A second caller joins the same shared POST while another is still enrolled. +Join == + /\ phase = "posted" + /\ waiters >= 1 + /\ waiters < 2 + /\ waiters' = waiters + 1 + /\ UNCHANGED <> + +\* The server answers. The rotated pair now exists in the response body. +Answer == + /\ phase = "posted" + /\ phase' = "answered" + /\ UNCHANGED <> + +\* A caller detaches. Cancelling one wait is allowed, and so is cancelling the last one; dropping +\* the answered pair is not. +Detach == + /\ waiters > 0 + /\ waiters' = waiters - 1 + /\ IF Sabotage /\ waiters = 1 /\ phase = "answered" + THEN /\ phase' = "done" + /\ saved' = "old" + /\ UNCHANGED <> + ELSE UNCHANGED <> + +\* The write runs under the ownership check: the captured generation must still be current. +Store == + /\ phase = "answered" + /\ captured = gen + /\ ~signedOut + /\ phase' = "done" + /\ saved' = "new" + /\ UNCHANGED <> + +\* A refresh can settle without a write only when a sign-out already took the credentials. +Settle == + /\ phase = "answered" + /\ signedOut + /\ phase' = "done" + /\ UNCHANGED <> + +\* Sign-out advances the generation and deletes the pair, during a refresh or after it. The +\* post-delete state is "absent": keeping the old pair is not a completed sign-out. +SignOut == + /\ ~signedOut + /\ signedOut' = TRUE + /\ gen' = gen + 1 + /\ saved' = "absent" + /\ UNCHANGED <> + +Next == Start \/ Join \/ Answer \/ Detach \/ Store \/ Settle \/ SignOut + +Spec == Init /\ [][Next]_vars + +\* Failure 1: the server answered and nobody signed out, so the persisted pair is the issued one. +IssuedPairKept == phase = "done" /\ ~signedOut => saved = "new" + +\* Failure 2: a sign-out during a refresh keeps the store from landing after it. +SignOutWins == signedOut => saved = "absent" +==== diff --git a/docs/architecture/tla/ProviderAbortBridge.EarlyDispose.cfg b/docs/architecture/tla/ProviderAbortBridge.EarlyDispose.cfg new file mode 100644 index 00000000000..71c4285923d --- /dev/null +++ b/docs/architecture/tla/ProviderAbortBridge.EarlyDispose.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + DisposesEarly <- EarlyRelease +INVARIANTS TypeOK NoStrandedAbort diff --git a/docs/architecture/tla/ProviderAbortBridge.Leak.cfg b/docs/architecture/tla/ProviderAbortBridge.Leak.cfg new file mode 100644 index 00000000000..f56ea27108c --- /dev/null +++ b/docs/architecture/tla/ProviderAbortBridge.Leak.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Bridged <- UnbridgedShape +INVARIANTS TypeOK NoCallerHoldAfterSettle diff --git a/docs/architecture/tla/ProviderAbortBridge.NoDispose.cfg b/docs/architecture/tla/ProviderAbortBridge.NoDispose.cfg new file mode 100644 index 00000000000..6ad4384b3e3 --- /dev/null +++ b/docs/architecture/tla/ProviderAbortBridge.NoDispose.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + DisposesOnSettle <- NeverDisposes +INVARIANTS TypeOK NoCallerHoldAfterSettle diff --git a/docs/architecture/tla/ProviderAbortBridge.cfg b/docs/architecture/tla/ProviderAbortBridge.cfg new file mode 100644 index 00000000000..e5b9c79a6fc --- /dev/null +++ b/docs/architecture/tla/ProviderAbortBridge.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS TypeOK NoCallerHoldAfterSettle NoStrandedAbort diff --git a/docs/architecture/tla/ProviderAbortBridge.tla b/docs/architecture/tla/ProviderAbortBridge.tla new file mode 100644 index 00000000000..467ef71c900 --- /dev/null +++ b/docs/architecture/tla/ProviderAbortBridge.tla @@ -0,0 +1,142 @@ +---- MODULE ProviderAbortBridge ---- +\* Source: completePrompt builds the signal it hands the SDK for one request. +\* Sink: the abort listener attached to the caller signal for that request. +\* Failure: a settled request leaves a hold on the caller signal, so a task that +\* reuses one controller pays a retained controller per completed request. +\* Invariant: NoCallerHoldAfterSettle. +\* Failure: the bridge is released before the request settles, so an abort that +\* arrives while the request is open has nothing left to carry it. Invariant: +\* NoStrandedAbort. +\* Expected before the run: the unbridged shape fails NoCallerHoldAfterSettle +\* after one settled request, because its listener rides on the caller signal and +\* nothing removes it; the never-dispose shape fails the same invariant; the +\* early-dispose shape fails NoStrandedAbort; the fixed shape holds both. +\* Actual findings after the run, over all four configs: the plain config holds both +\* invariants (14 states generated, 10 distinct states). Leak and NoDispose each +\* fail NoCallerHoldAfterSettle along Init then Start then Settle (4 states). +\* EarlyDispose fails NoStrandedAbort along Init then Start then EarlyDispose then +\* Abort (9 states generated, 8 distinct). The fixed shape is a null result: no +\* failure beyond the two the invariants were written for. A null result is data. +\* The first run found a bug in the spec, not in the code: the action line that +\* assigns stranded' reads stranded' = stranded \/ (...), and that parses as +\* (stranded' = stranded) \/ (...), because = binds tighter than \/, so Abort +\* left stranded unassigned and TLC reported "Successor state is not +\* completely specified by action Abort". The plain config looked like a pass only +\* because DisposesEarly is FALSE in the fixed shape, so the second disjunct was +\* always false. The disjunction is parenthesised now and all four configs were +\* re-run; the numbers above are from the re-run. +\* Toolchain: this Windows install has no java - where java exits 1 and java +\* -version reports "is not recognized as an internal or external command". WSL +\* ships OpenJDK 21.0.13.1, so the runs went through bash against tla2tools.jar +\* 2.19 of 08 August 2024, sha256 +\* 936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88, downloaded +\* into a scratch directory; the jar is not committed and no javac ships in WSL. +\* check.sh still needs java plus TLA_JAR, and no workflow runs check.sh, so on a +\* Windows-only box the gate stays unrunnable; reproduce with TLA_JAR= +\* ./check.sh ProviderAbortBridge under any shell that has a JVM. +\* Cost: about 12 agent minutes to write, about 8 more to locate a JVM, fetch the +\* jar and run the four configs; the four checks themselves took seconds. +\* Review counts for this spec: 0 covered, 1 added, 0 gap. The added row is PR +\* #1311 thread 4773886064, which asks for a request-local signal disposed in the +\* request finally. Stance caveat, recorded honestly: this first version was +\* written after the fix had landed, so the invariants could not be drafted before +\* reading the fix. That is why the row counts as added and not covered. +\* Replay on the real code: openai.ts completePrompt passes the output of +\* mergeAbortSignalAndTimeout to the SDK, and without a bridge and without a +\* usable timeout that output is the caller signal itself. The installed openai +\* client.mjs attaches a listener per attempt inside fetchWithTimeout, at :351, in +\* a file that contains no removeEventListener. That hold is what NoCallerHold- +\* AfterSettle models; the two in-flight rows model the stranded half. +\* The tests that mirror these invariants are the request-local rows and the two +\* in-flight rows in api/providers/__tests__/openai.spec.ts. +\* Scope, stated so a reader does not over-read it: one prompt at a time, as the +\* sibling StreamReadCancellation does. Concurrent prompts, SDK retries and the +\* createMessage generator-abandon path are outside this model. The model also +\* counts holds rather than garbage collection: it says nothing about whether the +\* runtime frees an unreachable signal. +EXTENDS Naturals + +\* Bridged == TRUE is the fixed shape: the SDK gets a request-local signal, and +\* the caller signal only carries the bridge listener, which the request finally +\* releases. Bridged == FALSE is the shape the review thread flagged: the caller +\* signal is handed to the SDK and every attempt leaves a listener on it. +Bridged == TRUE +DisposesOnSettle == TRUE +DisposesEarly == FALSE + +\* callerHolds counts what still pins the caller signal: the bridge listener while +\* it is attached, or, in the unbridged shape, one SDK listener per request. +VARIABLES requests, inFlight, callerHolds, bridgeAttached, aborted, stranded + +vars == <> + +TypeOK == + /\ requests \in 0..2 + /\ inFlight \in BOOLEAN + /\ callerHolds \in 0..2 + /\ bridgeAttached \in BOOLEAN + /\ aborted \in BOOLEAN + /\ stranded \in BOOLEAN + +Init == + /\ requests = 0 + /\ inFlight = FALSE + /\ callerHolds = 0 + /\ bridgeAttached = FALSE + /\ aborted = FALSE + /\ stranded = FALSE + +\* Whichever signal the SDK is handed, its attempt listener lands on that signal. +\* In the bridged shape the hold on the caller signal is the bridge listener +\* instead, and it is one per request rather than one per attempt. +Start == + /\ ~inFlight + /\ requests < 2 + /\ requests' = requests + 1 + /\ inFlight' = TRUE + /\ bridgeAttached' = Bridged + /\ callerHolds' = callerHolds + 1 + /\ UNCHANGED <> + +\* Sabotage shape, driven by DisposesEarly: the bridge is released while the +\* request is still open. +EarlyDispose == + /\ inFlight + /\ DisposesEarly + /\ bridgeAttached + /\ bridgeAttached' = FALSE + /\ callerHolds' = callerHolds - 1 + /\ UNCHANGED <> + +\* The attempt settles. The SDK never removes the listener it attached; only the +\* bridge releases its hold on the caller signal, and only when it disposes. +Settle == + /\ inFlight + /\ inFlight' = FALSE + /\ bridgeAttached' = IF DisposesOnSettle /\ ~DisposesEarly THEN FALSE ELSE bridgeAttached + /\ callerHolds' = + IF DisposesOnSettle /\ ~DisposesEarly /\ bridgeAttached + THEN callerHolds - 1 + ELSE callerHolds + /\ UNCHANGED <> + +\* An abort arrives. It still reaches the open request while the bridge is +\* attached, or when there is no bridge at all; it is stranded only when a bridge +\* existed and has already been released. +Abort == + /\ ~aborted + /\ aborted' = TRUE + /\ stranded' = (stranded \/ (inFlight /\ DisposesEarly /\ ~bridgeAttached)) + /\ UNCHANGED <> + +Next == Start \/ EarlyDispose \/ Settle \/ Abort + +Spec == Init /\ [][Next]_vars /\ WF_vars(Start) /\ WF_vars(Settle) + +\* Opposite of "a settled request leaves a hold on the caller signal". +NoCallerHoldAfterSettle == ~inFlight => callerHolds = 0 + +\* Opposite of "an abort that arrives during an open request is stranded by a +\* dispose that ran too early". +NoStrandedAbort == ~stranded +==== diff --git a/docs/architecture/tla/ProviderAbortBridgeMC.tla b/docs/architecture/tla/ProviderAbortBridgeMC.tla new file mode 100644 index 00000000000..4c3153dd6cb --- /dev/null +++ b/docs/architecture/tla/ProviderAbortBridgeMC.tla @@ -0,0 +1,6 @@ +---- MODULE ProviderAbortBridgeMC ---- +EXTENDS ProviderAbortBridge +UnbridgedShape == FALSE +NeverDisposes == FALSE +EarlyRelease == TRUE +==== diff --git a/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts b/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts index d4a4605b2f3..04a314d5c6f 100644 --- a/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts +++ b/src/api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts @@ -13,18 +13,27 @@ import { getApiRequestTimeout } from "../utils/timeout-config" import { clearAllMocks } from "../../../test-utils/reset" -// Mock OpenAI and capture constructor calls -const mockOpenAIConstructor = vitest.fn() +// Mock OpenAI and capture constructor calls. The abort error class must stay the +// real one: error-handler classifies it with instanceof, so a stand-in would make +// the timeout assertion pass for the wrong reason. +const { mockOpenAIConstructor, mockCreate } = vitest.hoisted(() => ({ + mockOpenAIConstructor: vitest.fn(), + mockCreate: vitest.fn(), +})) -vitest.mock("openai", () => { +// The abort error class must stay the real one: error-handler classifies it with +// instanceof, so a stand-in would make the timeout assertion pass for the wrong reason. +vitest.mock("openai", async (importOriginal) => { + const actual = (await importOriginal()) as { APIUserAbortError: new () => Error } return { __esModule: true, + APIUserAbortError: actual.APIUserAbortError, default: vitest.fn().mockImplementation(function (config) { mockOpenAIConstructor(config) return { chat: { completions: { - create: vitest.fn(), + create: mockCreate, }, }, } @@ -118,4 +127,38 @@ describe("BaseOpenAiCompatibleProvider Timeout Configuration", () => { }), ) }) + + it("keeps a timeout classified as a timeout while the caller signal is still live", async () => { + vitest.mocked(getApiRequestTimeout).mockReturnValue(600000) + const provider = new TestOpenAiCompatibleProvider("test-api-key") + const controller = new AbortController() + + // The SDK reports the abort only after the merged timeout signal has fired, so + // the classification depends on the timeout reason rather than the caller signal. + const openai = await import("openai") + let requestSignal: AbortSignal | undefined + mockCreate.mockImplementation(async (_params: unknown, config: { signal?: AbortSignal }) => { + requestSignal = config.signal + // Poll the condition the classification depends on - the merged timeout signal firing - + // instead of sleeping a fixed interval that merely happens to outlast the 5 ms timeout. + await vitest.waitFor(() => { + if (!requestSignal?.aborted) { + throw new Error("the merged timeout signal has not fired yet") + } + }) + throw new openai.APIUserAbortError() + }) + + const error = await provider + .completePrompt("hi", { abortSignal: controller.signal, timeoutMs: 5 }) + .catch((caught: unknown) => caught) + + expect((error as Error).name).toBe("TimeoutError") + expect((error as Error).message).toBe("The TestProvider completion request timed out") + expect((error as Error).cause).toBeInstanceOf(openai.APIUserAbortError) + // The caller never cancelled: the timeout fired on the merged signal. + expect(controller.signal.aborted).toBe(false) + expect(requestSignal?.aborted).toBe(true) + expect(requestSignal?.reason?.name).toBe("TimeoutError") + }) }) diff --git a/src/api/providers/__tests__/base-openai-compatible-provider.abort-bridge.spec.ts b/src/api/providers/__tests__/base-openai-compatible-provider.abort-bridge.spec.ts new file mode 100644 index 00000000000..b6a37f1f4e4 --- /dev/null +++ b/src/api/providers/__tests__/base-openai-compatible-provider.abort-bridge.spec.ts @@ -0,0 +1,364 @@ +// npx vitest run api/providers/__tests__/base-openai-compatible-provider.abort-bridge.spec.ts + +import { getEventListeners } from "node:events" + +import type OpenAI from "openai" + +import type { ModelInfo } from "@roo-code/types" + +import type { ApiStreamChunk } from "../../transform/stream" + +import { BaseOpenAiCompatibleProvider } from "../base-openai-compatible-provider" +import { makeCreateMessageMetadata } from "../../../test-utils/api" +import { collectStream, sseResponse } from "../../../test-utils/stream" + +// This spec deliberately does not mock the openai module: the quantity under test is how many abort +// listeners the SDK leaves behind on the caller's signal, and a mocked client never installs one. Each +// row runs the installed SDK (5.23.2) against a stubbed global fetch, so the anonymous listener that +// client.mjs attaches to whichever signal it is handed - and never removes - is the thing being counted. +// Counting goes through node:events, since an AbortSignal has no listenerCount method of its own. + +const INFO: ModelInfo = { + maxTokens: 4096, + contextWindow: 12800, + supportsImages: false, + supportsPromptCache: false, +} + +class BridgeProbeProvider extends BaseOpenAiCompatibleProvider<"probe"> { + constructor() { + super({ + providerName: "BridgeProbe", + baseURL: "https://bridge.example.com/v1", + defaultProviderModelId: "probe", + providerModels: { probe: INFO }, + apiKey: "probe-key", + }) + } +} + +function sseChunk(delta: Record, finishReason: string | null): string { + return `data: ${JSON.stringify({ + id: "bridge-probe", + object: "chat.completion.chunk", + created: 1, + model: "probe", + choices: [{ index: 0, delta, finish_reason: finishReason }], + })}\n\n` +} + +function usageEvent(): string { + return `data: ${JSON.stringify({ + id: "bridge-probe", + object: "chat.completion.chunk", + created: 1, + model: "probe", + choices: [], + usage: { prompt_tokens: 1, completion_tokens: 2, total_tokens: 3 }, + })}\n\n` +} + +/** A well-formed stream that ends on its own: two text chunks, a stop, then usage. */ +function completedStreamBody(): string { + return ( + sseChunk({ role: "assistant", content: "a" }, null) + + sseChunk({ content: "b" }, null) + + sseChunk({ content: "" }, "stop") + + usageEvent() + + "data: [DONE]\n\n" + ) +} + +/** A non-streaming completion body, which is what completePrompt parses. */ +/** A successful non-streaming response body, as completePrompt parses it. */ +function jsonOk(): Response { + return new Response(completionBody(), { status: 200, headers: { "content-type": "application/json" } }) +} + +function completionBody(): string { + return JSON.stringify({ + id: "bridge-probe", + object: "chat.completion", + created: 1, + model: "probe", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 1, completion_tokens: 2, total_tokens: 3 }, + }) +} + +const requests: { signal?: AbortSignal }[] = [] +const handed: { signal?: AbortSignal }[] = [] + +/** + * How many abort listeners are attached to a signal. Node exposes this through events.getEventListeners + * for any EventTarget; an AbortSignal carries no listenerCount method of its own. + */ +function abortListeners(signal: AbortSignal): number { + return getEventListeners(signal, "abort").length +} + +/** + * Replaces global fetch so the SDK runs for real while every request signal is captured: the signal in + * the fetch init is precisely the one the provider handed over, which is what the rows below measure. + */ +function stubFetch(respond: (attempt: number, requestSignal?: AbortSignal) => Response): void { + requests.length = 0 + handed.length = 0 + vi.spyOn(globalThis, "fetch").mockImplementation(async (_input, init) => { + const requestSignal = init?.signal ?? undefined + requests.push({ signal: requestSignal }) + return respond(requests.length - 1, requestSignal) + }) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** + * An SSE body that delivers one chunk and then stays open until the request signal aborts, which is how + * a stalled upstream response reaches the consumer. Erroring the body on abort mirrors what a transport + * does to an aborted request; the stub is the only party here that knows the request was cancelled. + */ +function heldOpenStream(requestSignal?: AbortSignal): Response { + return eventStream(requestSignal, sseChunk({ role: "assistant", content: "a" }, null)) +} + +/** A response whose body never yields, so only a deadline or an abort can end the request. */ +function unanswered(requestSignal?: AbortSignal): Response { + return eventStream(requestSignal, undefined) +} + +function eventStream(requestSignal: AbortSignal | undefined, firstEvent: string | undefined): Response { + const encoder = new TextEncoder() + const stream = new ReadableStream({ + start(controller) { + if (firstEvent) { + controller.enqueue(encoder.encode(firstEvent)) + } + if (requestSignal?.aborted) { + controller.error(new Error("request aborted before the response")) + return + } + requestSignal?.addEventListener("abort", () => controller.error(new Error("request aborted")), { + once: true, + }) + }, + }) + return new Response(stream, { headers: { "content-type": "text/event-stream" } }) +} + +/** + * A fresh provider per row, recording the signal it hands to the SDK client. The client keeps the + * fetch implementation it was constructed with, so the stub has to be installed before the provider is + * built, and a row must not share a client with another row. The recording wraps the original create + * call, so the SDK still runs for real; the assertion cast is on the wrapper, not on the SDK call. + */ +function newProvider(): BridgeProbeProvider { + const handler = new BridgeProbeProvider() + const completions = handler["client"].chat.completions + const create = completions.create + vi.spyOn(completions, "create").mockImplementation((( + params: OpenAI.Chat.Completions.ChatCompletionCreateParams, + options?: OpenAI.RequestOptions, + ) => { + handed.push({ signal: options?.signal ?? undefined }) + return create.call(completions, params, options) + }) as typeof completions.create) + return handler +} + +function streamedRequest(handler: BridgeProbeProvider, metadata?: ReturnType) { + return handler.createMessage("go", [{ role: "user", content: "go" }], metadata) +} + +function completionRequest( + handler: BridgeProbeProvider, + abortSignal?: AbortSignal, + timeoutMs?: number, +): Promise { + return handler.completePrompt("hi", { abortSignal, timeoutMs }) +} + +async function nextChunk(iterator: AsyncIterator): Promise { + const next = await iterator.next() + if (next.done) { + throw new Error("expected another chunk") + } + return next.value +} + +describe("abort listener lifecycle on the caller's signal", () => { + it("detaches the request listener after a streamed request completes", async () => { + stubFetch(() => sseResponse(completedStreamBody())) + const handler = newProvider() + const controller = new AbortController() + const chunks = await collectStream( + streamedRequest(handler, makeCreateMessageMetadata({ abortSignal: controller.signal })), + ) + expect(chunks.flatMap((chunk) => (chunk.type === "text" ? [chunk.text] : [])).join("")).toBe("ab") + expect(chunks.some((chunk) => chunk.type === "usage")).toBe(true) + // The SDK added one listener to the signal it was handed; the bridge must have removed it. + expect(abortListeners(controller.signal)).toBe(0) + }) + + it("detaches the request listener after a completion request", async () => { + stubFetch(() => jsonOk()) + const handler = newProvider() + const controller = new AbortController() + await expect(completionRequest(handler, controller.signal)).resolves.toBe("ok") + expect(abortListeners(controller.signal)).toBe(0) + }) + + it("does not accumulate listeners across sequential completion requests", async () => { + stubFetch(() => jsonOk()) + const handler = newProvider() + const controller = new AbortController() + // A task reuses one signal across several model calls, so a listener that survives one request is + // still attached to the next, and the count is what a long task would pay for. + for (let attempt = 0; attempt < 3; attempt++) { + await completionRequest(handler, controller.signal) + expect(abortListeners(controller.signal)).toBe(0) + } + }) + + it("detaches the request listener when the caller stops consuming the stream early", async () => { + stubFetch(() => sseResponse(completedStreamBody())) + const handler = newProvider() + const controller = new AbortController() + const iterator = streamedRequest(handler, makeCreateMessageMetadata({ abortSignal: controller.signal }))[ + Symbol.asyncIterator + ]() + expect(await nextChunk(iterator)).toMatchObject({ type: "text", text: "a" }) + // A caller that stops after the first chunk: the generator resumes at its finally instead of running + // the remaining yields, so this is the early-exit release path the reviewer asked to see. + await iterator.return?.(undefined) + expect(abortListeners(controller.signal)).toBe(0) + }) + + it("detaches the request listener when a completion request fails", async () => { + stubFetch(() => new Response(JSON.stringify({ error: { message: "upstream boom" } }), { status: 500 })) + const handler = newProvider() + const controller = new AbortController() + await expect(completionRequest(handler, controller.signal)).rejects.toThrow() + // Retries attach one listener per attempt, so an undisposed bridge shows the attempt count here. + expect(requests.length).toBeGreaterThan(1) + expect(abortListeners(controller.signal)).toBe(0) + }) + + it("detaches the request listener when a streamed request fails at creation", async () => { + stubFetch(() => new Response(JSON.stringify({ error: { message: "upstream boom" } }), { status: 500 })) + const handler = newProvider() + const controller = new AbortController() + const iterator = streamedRequest(handler, makeCreateMessageMetadata({ abortSignal: controller.signal }))[ + Symbol.asyncIterator + ]() + let failure = new Error("expected the stream to fail") + try { + await iterator.next() + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + // The request never became a stream, so this is the creation-failure release path. + expect(failure.message).toContain("500") + expect(abortListeners(controller.signal)).toBe(0) + }) +}) + +describe("the bridged request signal keeps caller semantics", () => { + it("hands the SDK a request signal of its own for a streamed request", async () => { + stubFetch(() => sseResponse(completedStreamBody())) + const handler = newProvider() + const controller = new AbortController() + await collectStream(streamedRequest(handler, makeCreateMessageMetadata({ abortSignal: controller.signal }))) + expect(handed.length).toBe(1) + expect(handed[0].signal).toBeDefined() + // The signal the client receives is where its listener is attached, so it must not be the task's + // own signal: that is what accumulates one retained listener per completed request. + expect(handed[0].signal).not.toBe(controller.signal) + }) + + it("hands the SDK a request signal of its own for a completion request", async () => { + stubFetch(() => jsonOk()) + const handler = newProvider() + const controller = new AbortController() + await completionRequest(handler, controller.signal) + expect(handed.length).toBe(1) + expect(handed[0].signal).toBeDefined() + expect(handed[0].signal).not.toBe(controller.signal) + }) + + it("reports a mid-stream caller abort to the consumer as an abort", async () => { + stubFetch((_attempt, requestSignal) => heldOpenStream(requestSignal)) + const handler = newProvider() + const controller = new AbortController() + const iterator = streamedRequest(handler, makeCreateMessageMetadata({ abortSignal: controller.signal }))[ + Symbol.asyncIterator + ]() + expect(await nextChunk(iterator)).toMatchObject({ type: "text", text: "a" }) + controller.abort() + let failure = new Error("expected the stream to fail") + try { + await iterator.next() + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + expect(controller.signal.aborted).toBe(true) + expect(failure.name).toBe("AbortError") + expect(failure.message).toBe("The BridgeProbe request was aborted") + expect(abortListeners(controller.signal)).toBe(0) + }) + + it("classifies a configured deadline as a timeout rather than a caller cancellation", async () => { + stubFetch((_attempt, requestSignal) => unanswered(requestSignal)) + const handler = newProvider() + const controller = new AbortController() + let failure = new Error("expected the request to fail") + try { + await completionRequest(handler, controller.signal, 200) + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + // The deadline belongs to the request, not to the caller, so it must not read as a cancellation. + expect(failure.name).toBe("TimeoutError") + expect(failure.message).toBe("The BridgeProbe completion request timed out") + expect(controller.signal.aborted).toBe(false) + }) + + it("leaves the caller signal listener-free when a deadline is configured", async () => { + stubFetch(() => jsonOk()) + const handler = newProvider() + const controller = new AbortController() + await expect(completionRequest(handler, controller.signal, 5000)).resolves.toBe("ok") + // A merged signal already shielded this path before the bridge existed; the bridge must not reopen + // it by attaching to the caller signal instead of a per-request one. + expect(abortListeners(controller.signal)).toBe(0) + }) + + it( + "forwards a caller abort to the bridged request signal while the stream is still suspended", + { timeout: 1500 }, + async () => { + stubFetch((_attempt, requestSignal) => heldOpenStream(requestSignal)) + const handler = newProvider() + const controller = new AbortController() + const iterator = streamedRequest(handler, makeCreateMessageMetadata({ abortSignal: controller.signal }))[ + Symbol.asyncIterator + ]() + expect(await nextChunk(iterator)).toMatchObject({ type: "text", text: "a" }) + controller.abort() + // Observed on the signal the provider handed the client, and without pulling another chunk: + // a bridge released before the stream is over stops forwarding at once, so this fails by + // assertion inside the row's own short timeout instead of by the suite timeout. + await vi.waitFor(() => expect(handed[0]?.signal?.aborted).toBe(true), { timeout: 1000, interval: 25 }) + }, + ) + + it("completes requests when the caller passes no signal at all", async () => { + stubFetch(() => jsonOk()) + await expect(completionRequest(newProvider())).resolves.toBe("ok") + stubFetch(() => sseResponse(completedStreamBody())) + const chunks = await collectStream(streamedRequest(newProvider())) + expect(chunks.flatMap((chunk) => (chunk.type === "text" ? [chunk.text] : [])).join("")).toBe("ab") + }) +}) diff --git a/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts b/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts index 1ffd63aa12a..3c2a2a8bf84 100644 --- a/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts +++ b/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts @@ -1,18 +1,25 @@ // npx vitest run api/providers/__tests__/base-openai-compatible-provider.spec.ts +import { getEventListeners } from "node:events" + import { Anthropic } from "@anthropic-ai/sdk" +import { APIUserAbortError } from "openai" import { type ModelInfo, openAiModelInfoSaneDefaults } from "@roo-code/types" import { BaseOpenAiCompatibleProvider } from "../base-openai-compatible-provider" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" +import { captureError } from "../../../test-utils/errors" +import { MAX_TIMEOUT_MS } from "../utils/abort-signal" // Create mock functions const mockCreate = vi.fn() // Mock OpenAI module vi.mock("openai", () => ({ + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, default: vi.fn(function () { return { chat: { @@ -297,6 +304,549 @@ describe("BaseOpenAiCompatibleProvider", () => { expect(firstChunk.done).toBe(false) expect(firstChunk.value).toMatchObject({ type: "usage", inputTokens: 100, outputTokens: 50 }) }) + + it("should keep the last usage when a later chunk carries none", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: {} }], + usage: { prompt_tokens: 10, completion_tokens: 5 }, + }, + { choices: [{ delta: { content: "tail" } }] }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // The recorded usage is only replaced by a chunk that actually carries + // usage; a later usage-less chunk must not wipe out the metrics. + const usageChunks = chunks.filter((chunk) => chunk.type === "usage") + expect(usageChunks).toHaveLength(1) + expect(usageChunks[0]).toMatchObject({ type: "usage", inputTokens: 10, outputTokens: 5 }) + }) + }) + + describe("stream chunk shape edge cases", () => { + it("should surface the choices access as the failure site for a null chunk", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([null, { choices: [{ delta: { content: "after" } }] }]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // A null chunk passes the base_resp guard (typeof null is "object" but + // the !== null check short-circuits) and only fails at the first choices + // access; pinning the message proves the guard is evaluated first. + expect(result.name).toBe("Error") + expect(result.message).toBe( + "TestProvider completion error: Cannot read properties of null (reading 'choices')", + ) + }) + + it("should continue streaming content after a primitive chunk", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom(["unexpected-chunk", { choices: [{ delta: { content: "after" } }] }]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + // A primitive chunk fails the base_resp guard's object check and its + // property reads short-circuit through optional chaining, so the stream + // must carry on with the next real chunk. + expect(chunks).toEqual([{ type: "text", text: "after" }]) + }) + + it("should skip an empty choices array without crashing the delta reads", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([{ choices: [] }, { choices: [{ delta: { content: "after" } }] }]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + // With no first choice, delta and finish_reason resolve to undefined; + // the optional chaining must keep the iteration alive for the next chunk. + expect(chunks).toEqual([{ type: "text", text: "after" }]) + }) + }) + + describe("abort signal wiring", () => { + it("should hand the client a per-request signal that follows the caller's abort", async () => { + const controller = new AbortController() + // The double records the request options it received, and the assertions below go by + // non-identity plus forwarding while the request is live: the provider hands the SDK a + // disposable bridge signal rather than the caller's own, and comparing by identity would + // pin the leak the bridge exists to remove. A chunk is yielded so the generator is still + // suspended - the request still live - when the caller aborts. + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return asyncStreamFrom([{ choices: [{ delta: { content: "a" } }] }]) + }) + + const stream = handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await stream.next() + controller.abort() + + expect(first.value).toMatchObject({ type: "text", text: "a" }) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), { + signal: expect.any(AbortSignal), + }) + expect(sentOptions?.signal).toBeDefined() + expect(sentOptions?.signal).not.toBe(controller.signal) + expect(sentOptions?.signal?.aborted).toBe(true) + }) + + it("should reject before issuing any request when the abort signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect(async () => { + for await (const _ of handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + })) { + // consume + } + }).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("should normalize the SDK APIUserAbortError from the stream path into the abort contract", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // The SDK error has name "Error" and a message ending in a period; the + // provider must rethrow the Task.ts contract shape instead. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should normalize a rejected-Promise APIUserAbortError from request creation", async () => { + // The provider awaits request creation so a REJECTED promise (the + // shape the SDK actually returns when the request is aborted before + // the response) reaches the abort normalization; the sync-throw test + // above would pass even if the await were removed. + mockCreate.mockRejectedValueOnce(new APIUserAbortError()) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("should normalize a rejected-Promise abort from an overriding createStream that does not await", async () => { + // Subclasses such as FriendliHandler return the SDK promise without awaiting it, + // so their own catch cannot fire. The base createMessage must normalize the + // creation-time rejection for every subclass. + class UnawaitedCreateStreamProvider extends TestOpenAiCompatibleProvider { + protected override createStream() { + return Promise.reject(new APIUserAbortError()) + } + } + + const provider = new UnawaitedCreateStreamProvider("test-api-key") + const result = await captureError( + (async () => { + for await (const _ of provider.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("should normalize an abort error raised during stream iteration into the abort contract", async () => { + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // The iterator rejects after the first chunk; the provider must normalize + // it to the Task.ts contract shape (name + message ending in "aborted"). + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should stop yielding buffered chunks and reject with the abort contract when aborted mid-stream", async () => { + let releaseSecond = () => {} + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + // The second chunk is deferred: it only becomes available after the caller + // aborts, so the loop's next for-await pull is a suspension point only the + // top-of-loop break can decide on. Removing the break leaks "world"; removing + // the post-loop check ends the stream normally instead of rejecting. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "hello " } }] } + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = handler.createMessage("system prompt", [], metadata) + + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "hello " }) + + controller.abort() + releaseSecond() + + // Anything yielded after the abort is a leak: the deferred second chunk + // must not come through an aborted stream — only the top-of-loop break + // stops the loop from processing content pulled after the abort. + const leaked: string[] = [] + const result = await captureError( + (async () => { + for await (const chunk of gen) { + if (chunk.type === "text") { + leaked.push(chunk.text) + } + } + })(), + ) + + expect(leaked).toEqual([]) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should wrap a non-abort base_resp stream error with the provider prefix through the iteration wrapper", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "partial" } }], + base_resp: { status_code: 1041, status_msg: "Invalid token" }, + }, + ]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: TestProvider API Error (1041): Invalid token") + }) + + it("should fall back to an Unknown error when a base_resp stream chunk has no status_msg", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "partial" } }], + base_resp: { status_code: 1041 }, + }, + ]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: TestProvider API Error (1041): Unknown error") + }) + + it("should ignore a zero base_resp status_code because 0 is a success sentinel", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: 0 }, + }, + ]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + expect(chunks).toEqual([{ type: "text", text: "ok" }]) + }) + + it("should ignore an empty-string base_resp status_code", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: "" }, + }, + ]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + + expect(chunks).toEqual([{ type: "text", text: "ok" }]) + }) + + it("should report a string base_resp status_code with its status_msg", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + base_resp: { status_code: "1001", status_msg: "bad token" }, + }, + ]), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: TestProvider API Error (1001): bad token") + }) + + it("should fall back to Unknown error when a base_resp status_msg is an empty string", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: 1041, status_msg: "" }, + }, + ]), + ) + + // Same fallback as the completePrompt path: an empty status_msg is not a + // message, so the error must not read as "API Error (1041): ". + await expect(collectStream(handler.createMessage("system prompt", []))).rejects.toThrow( + "TestProvider API Error (1041): Unknown error", + ) + }) + + it("should still report a boolean base_resp status_code, as before the guard refactor", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { content: "ok" } }], + base_resp: { status_code: true }, + }, + ]), + ) + + // The guard refactor must not change what counts as an error status: + // any truthy non-zero status_code is reported, whatever its type. + await expect(collectStream(handler.createMessage("system prompt", []))).rejects.toThrow( + "TestProvider API Error (true): Unknown error", + ) + }) + + it("should still wrap non-abort request errors with the provider prefix", async () => { + mockCreate.mockImplementationOnce(() => { + throw new Error("boom") + }) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.message).toBe("TestProvider completion error: boom") + }) + + it("should hand the completePrompt request a per-request signal and release it on completion", async () => { + const controller = new AbortController() + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return Promise.resolve({ choices: [{ message: { content: "response" } }] }) + }) + + const result = await handler.completePrompt("test prompt", { abortSignal: controller.signal }) + + expect(result).toBe("response") + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), { + signal: expect.any(AbortSignal), + }) + expect(sentOptions?.signal).toBeDefined() + expect(sentOptions?.signal).not.toBe(controller.signal) + // The request has completed by this point, so the bridge listener must already be gone from + // the caller's signal: that count is what a long task pays for every completed request. + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + }) + + it("should merge the completePrompt abort signal and timeoutMs into one request signal", async () => { + const controller = new AbortController() + // Emulate the OpenAI SDK: the pending request rejects when its signal aborts, so the + // assertions below observe the request while it is still in flight. + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const requestPromise = handler.completePrompt("test prompt", { + abortSignal: controller.signal, + timeoutMs: 5000, + }) + const resultPromise = captureError(requestPromise) + await vi.waitFor(() => expect(mockCreate).toHaveBeenCalled()) + + const requestOptions = capturedOptions + // The request signal is the request's own - not the caller's - and it still follows the + // caller's stop, which is what keeps the SDK's per-request listener off the caller. + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + expect(requestOptions?.signal).not.toBe(controller.signal) + expect(requestOptions?.signal?.aborted).toBe(false) + // A positive timeoutMs must be forwarded as the per-request SDK timeout. + expect(requestOptions?.timeout).toBe(5000) + // A timeout-only merged signal would still pass the assertions above; + // aborting the caller's controller proves caller cancellation survives. + controller.abort() + expect(requestOptions?.signal?.aborted).toBe(true) + + const result = await resultPromise + expect(result.name).toBe("AbortError") + }) + + it("should cap an oversized completePrompt timeoutMs before handing it to the SDK", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { timeoutMs: MAX_TIMEOUT_MS + 1 }) + + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + // The SDK passes this straight to a Node timer, which clamps anything past 2^31-1 ms + // to ~1 ms: uncapped, the request would abort at once instead of waiting. + expect(requestOptions?.timeout).toBe(MAX_TIMEOUT_MS) + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + }) + + it("should omit the request timeout for a non-finite completePrompt timeoutMs", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { timeoutMs: Number.POSITIVE_INFINITY }) + + // Infinity satisfies a bare `> 0` check but is not a legal timer delay; it means + // "no explicit timeout", so no request options are sent at all. + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), undefined) + }) + + it("should abort the request when a timeout-only completePrompt timeoutMs elapses", async () => { + // Emulate the OpenAI SDK: the pending request rejects when its signal aborts. + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + // No caller signal: the timeout branch is exercised on its own. AbortSignal.timeout + // is backed by a native self-managed timer (not the fakeable global), so poll with + // vi.waitFor the same way abort-signal.spec.ts does. + const requestPromise = handler.completePrompt("test prompt", { timeoutMs: 50 }) + // Attach the rejection handler immediately so the timeout rejection + // is never observed as unhandled while we poll for the abort. + const resultPromise = captureError(requestPromise) + + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + // A timeout that fires through the merged signal is a timeout, not a user + // cancellation, so the caller must still be able to tell them apart. + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The TestProvider completion request timed out") + }) + + it("should not set a request signal for zero completePrompt timeoutMs", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { timeoutMs: 0 }) + + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), undefined) + }) + + it("should reject before any request when the completePrompt signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect( + handler.completePrompt("test prompt", { abortSignal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("should normalize the SDK APIUserAbortError from completePrompt", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError(handler.completePrompt("test prompt")) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) }) describe("getModel", () => { @@ -364,7 +914,13 @@ describe("BaseOpenAiCompatibleProvider", () => { await customHandler.completePrompt("hello") - expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "some/custom-model-not-in-list" })) + // completePrompt forwards the request config (abort signal + per-request timeout) as the + // SDK second argument. With no signal and no timeoutMs the builder returns undefined, so + // the argument is still passed - asserting it keeps the two-argument call shape pinned. + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "some/custom-model-not-in-list" }), + undefined, + ) }) }) @@ -486,5 +1042,284 @@ describe("BaseOpenAiCompatibleProvider", () => { const endChunks = chunks.filter((chunk) => chunk.type === "tool_call_end") expect(endChunks).toHaveLength(0) }) + + it("should yield a tool_call_partial with undefined name and arguments when function is absent", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [{ delta: { tool_calls: [{ index: 0, id: "call_fn" }] } }], + }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // A first-chunk tool call may carry only its id; the optional chaining + // on function must yield undefined fields instead of throwing. + expect(chunks).toEqual([ + { type: "tool_call_partial", index: 0, id: "call_fn", name: undefined, arguments: undefined }, + ]) + }) + + it("should emit the tool_call_end after the trailing content, not before it", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + tool_calls: [ + { index: 0, id: "call_seq", function: { name: "seq_tool", arguments: "{}" } }, + ], + }, + }, + ], + }, + { choices: [{ delta: { content: "between" } }] }, + { choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // The end event must only be emitted when finish_reason arrives; + // emitting it on finish-less chunks would reorder this sequence. + expect(chunks).toEqual([ + { type: "tool_call_partial", index: 0, id: "call_seq", name: "seq_tool", arguments: "{}" }, + { type: "text", text: "between" }, + { type: "tool_call_end", id: "call_seq" }, + ]) + }) + + it("should clear the tracked tool call ids after emitting tool_call_end", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + tool_calls: [ + { index: 0, id: "call_dup", function: { name: "dup_tool", arguments: "{}" } }, + ], + }, + }, + ], + }, + { choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + { choices: [{ delta: { content: "more" } }] }, + { choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + ]), + ) + + const stream = handler.createMessage("system prompt", []) + const chunks = await collectStream(stream) + + // Without the clear(), the second tool_calls finish would re-emit the + // end event for the already-finalized call. + const endChunks = chunks.filter((chunk) => chunk.type === "tool_call_end") + expect(endChunks).toEqual([{ type: "tool_call_end", id: "call_dup" }]) + }) + }) +}) + +describe("BaseOpenAiCompatibleProvider cancellation ordering (PR 1311 reviewer rows)", () => { + let handler: TestOpenAiCompatibleProvider + + beforeEach(() => { + clearAllMocks() + handler = new TestOpenAiCompatibleProvider("test-api-key") + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it("releases reasoning, content and tool events from one chunk when nothing cancels", async () => { + // Positive control for the fixture below: with no cancellation this single chunk + // yields all three event kinds, so an empty post-abort list is the guards' doing + // and not the fixture withholding content. + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + content: "plan\n\ntail", + tool_calls: [ + { index: 0, id: "call_gate", function: { name: "gate_tool", arguments: "{}" } }, + ], + }, + finish_reason: "tool_calls", + }, + ], + }, + ]), + ) + + const chunks = await collectStream(handler.createMessage("system prompt", [])) + expect(chunks.map((chunk) => chunk.type)).toEqual(["reasoning", "text", "tool_call_partial", "tool_call_end"]) + }) + + it("releases none of the remaining yields from a chunk once the caller aborts", async () => { + // The chunk above carries reasoning, content and a tool call plus its finish reason. + // Cancelling after the first yield must suppress the content and both tool events + // already parsed out of this same chunk, and the stream must reject with the abort + // contract rather than end normally after the buffered events. + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + content: "plan\n\ntail", + tool_calls: [ + { index: 0, id: "call_gate", function: { name: "gate_tool", arguments: "{}" } }, + ], + }, + finish_reason: "tool_calls", + }, + ], + }, + ]), + ) + + const controller = new AbortController() + const gen = handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await gen.next() + expect(first.done).toBe(false) + expect(first.value).toMatchObject({ type: "reasoning", text: "plan\n" }) + + controller.abort() + + const leaked: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of gen) { + leaked.push(chunk) + } + })(), + ) + + expect(leaked).toEqual([]) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("hands the captured usage record to the caller before raising the cancellation", async () => { + let releaseSecond!: () => void + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { + choices: [{ delta: { content: "hello " } }], + usage: { prompt_tokens: 3, completion_tokens: 5 }, + } + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const gen = handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await gen.next() + expect(first.value).toMatchObject({ type: "text", text: "hello " }) + + controller.abort() + releaseSecond() + + // The full post-abort list, unfiltered: the captured usage record must reach the + // caller and the deferred chunk must not. + const postAbort: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of gen) { + postAbort.push(chunk) + } + })(), + ) + + expect(postAbort).toMatchObject([{ type: "usage", inputTokens: 3, outputTokens: 5 }]) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The TestProvider request was aborted") + }) + + it("records the captured usage before an iterator error instead of bypassing it", async () => { + // No cancellation at all: an async iterator that fails on the next pull used to + // discard the usage record captured from the first chunk, because the catch + // normalized the error before the usage yield was reached. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { + choices: [{ delta: { content: "hello " } }], + usage: { prompt_tokens: 1, completion_tokens: 2 }, + } + throw new Error("upstream died") + })(), + ) + + const collected: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of handler.createMessage("system prompt", [])) { + collected.push(chunk) + } + })(), + ) + + expect(collected).toMatchObject([ + { type: "text", text: "hello " }, + { type: "usage", inputTokens: 1, outputTokens: 2 }, + ]) + expect(result.message).toBe("TestProvider completion error: upstream died") + }) + + it("rejects when the iterator rejects with undefined instead of completing", async () => { + // A rejection whose reason is `undefined` is still a failure. Tracking the failure only + // through the captured value made the post-loop check read "no error", so the stream + // completed normally after the partial output it had already emitted. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial " } }] } + throw undefined + })(), + ) + + const collected: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of handler.createMessage("system prompt", [])) { + collected.push(chunk) + } + })(), + ) + + expect(collected).toMatchObject([{ type: "text", text: "partial " }]) + expect(result.message).toBe("TestProvider completion error: undefined") + }) + + it("discards a completePrompt response that arrives after the caller aborted", async () => { + // The create() call resolves normally while the caller's abort lands in the same + // window: the post-await re-check must discard the response and raise the abort + // contract instead of returning its content as a completed prompt. + const controller = new AbortController() + mockCreate.mockImplementationOnce(async () => { + controller.abort() + return { choices: [{ message: { content: "answer" } }] } + }) + + await expect(handler.completePrompt("prompt", { abortSignal: controller.signal })).rejects.toMatchObject({ + name: "AbortError", + message: "The TestProvider request was aborted", + }) }) }) diff --git a/src/api/providers/__tests__/fireworks.spec.ts b/src/api/providers/__tests__/fireworks.spec.ts index 480f965894d..a7d27486d3e 100644 --- a/src/api/providers/__tests__/fireworks.spec.ts +++ b/src/api/providers/__tests__/fireworks.spec.ts @@ -23,6 +23,8 @@ vi.mock("openai", () => ({ }, } }), + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, })) describe("FireworksHandler", () => { diff --git a/src/api/providers/__tests__/friendli.spec.ts b/src/api/providers/__tests__/friendli.spec.ts index 1ff1b1475ba..dc514af0ac6 100644 --- a/src/api/providers/__tests__/friendli.spec.ts +++ b/src/api/providers/__tests__/friendli.spec.ts @@ -25,6 +25,14 @@ vi.mock("../fetchers/friendli", () => ({ getFriendliModels: mockGetFriendliModel // Mock OpenAI module vi.mock("openai", () => ({ + // 1311 adds an APIUserAbortError import at api/providers/utils/error-handler.ts:12 and reads + // it in handleOpenAIRequestError at :150 and :160, so a mock without that named export lets + // vitest's missing-export error replace the 401 job 129957461109 saw asserted at + // friendli.spec.ts:104:29 (2 failed of 66 twice at this head against 66 passed twice at + // main tip 18861b2e3572, CI ubuntu and local Windows agreeing exactly). Ten sibling + // provider specs already stub the export; this mock joins them rather than bending + // production error handling around a test double. + APIUserAbortError: class extends Error {}, default: vi.fn(function () { return { chat: { diff --git a/src/api/providers/__tests__/kimi-code.oauth-cancellation.spec.ts b/src/api/providers/__tests__/kimi-code.oauth-cancellation.spec.ts new file mode 100644 index 00000000000..740b18b0c08 --- /dev/null +++ b/src/api/providers/__tests__/kimi-code.oauth-cancellation.spec.ts @@ -0,0 +1,148 @@ +import { clearAllMocks } from "../../../test-utils/reset" +import { captureError } from "../../../test-utils/errors" +import { makeCreateMessageMetadata } from "../../../test-utils/api" + +const { mockGetModels, mockGetKimiCodeModels } = vi.hoisted(() => ({ + mockGetModels: vi.fn(), + mockGetKimiCodeModels: vi.fn(), +})) + +vi.mock("../fetchers/modelCache", () => ({ + getModels: mockGetModels, + refreshModels: mockGetModels, +})) + +vi.mock("../fetchers/kimi-code", () => ({ + getKimiCodeModels: mockGetKimiCodeModels, +})) + +import { KimiCodeHandler } from "../kimi-code" +import { kimiCodeOAuthManager } from "../../../integrations/kimi-code/oauth" + +const KIMI_CODE_CREDENTIALS_KEY = "kimi-code-oauth-credentials" + +describe("KimiCodeHandler OAuth cancellation", () => { + beforeEach(() => { + clearAllMocks() + mockGetModels.mockRejectedValue(new Error("offline")) + mockGetKimiCodeModels.mockResolvedValue({}) + // The OAuth manager is a singleton: a pair cached by one attempt would let the next one skip the + // token POST, so every attempt starts from an empty cache. + kimiCodeOAuthManager["credentials"] = null + }) + + it("rejects with the AbortError contract when the caller cancels before the refresh enrolls", async () => { + // The caller stops before the credential read resumes, so no token POST starts at all: the + // provider surfaces the contract AbortError, not the caller's custom reason. + const values = new Map() + values.set( + KIMI_CODE_CREDENTIALS_KEY, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const secrets = { + get: vi.fn(async (key: string) => values.get(key)), + store: vi.fn(async (key: string, value: string) => void values.set(key, value)), + delete: vi.fn(async (key: string) => void values.delete(key)), + } + kimiCodeOAuthManager.initialize({ secrets } as never) + + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(((_url, init) => { + const signal = (init as RequestInit)?.signal as AbortSignal + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { once: true }) + }) + }) as typeof fetch) + + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const controller = new AbortController() + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + ) + const next = stream.next() + controller.abort(new Error("cancelled by the caller")) + + await expect(next).rejects.toMatchObject({ name: "AbortError" }) + expect(fetchSpy, "an unenrolled caller starts no token POST").not.toHaveBeenCalled() + }) + + it("cancels one enrolled waiter without aborting the shared refresh the other waiter needs", async () => { + // Two provider requests enroll in the same shared refresh. The first caller cancels + // with an ordinary Error reason; the POST must stay alive for the second waiter, + // which must then authenticate and stream. + const values = new Map() + values.set( + KIMI_CODE_CREDENTIALS_KEY, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const secrets = { + get: vi.fn(async (key: string) => values.get(key)), + store: vi.fn(async (key: string, value: string) => void values.set(key, value)), + delete: vi.fn(async (key: string) => void values.delete(key)), + } + kimiCodeOAuthManager.initialize({ secrets } as never) + let resolveTokenPost!: (response: Response) => void + let refreshSignal: AbortSignal | undefined + let tokenPosts = 0 + vi.spyOn(globalThis, "fetch").mockImplementation(((url, init) => { + if (String(url).includes("/oauth/token")) { + tokenPosts++ + refreshSignal = (init as RequestInit)?.signal as AbortSignal + return new Promise((resolve) => { + resolveTokenPost = resolve + }) + } + return Promise.resolve( + new Response('data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}\n\n', { + status: 200, + headers: { "content-type": "text/event-stream" }, + }), + ) + }) as typeof fetch) + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const first = new AbortController() + const second = new AbortController() + const firstStream = handler.createMessage( + "system", + [{ role: "user", content: "test" }], + makeCreateMessageMetadata({ abortSignal: first.signal }), + ) + const firstNext = firstStream.next() + const secondStream = handler.createMessage( + "system", + [{ role: "user", content: "test" }], + makeCreateMessageMetadata({ abortSignal: second.signal }), + ) + const secondNext = secondStream.next() + await vi.waitFor(() => expect(tokenPosts).toBe(1)) + first.abort(new Error("cancelled by the first caller")) + await expect(firstNext).rejects.toMatchObject({ name: "AbortError" }) + expect(refreshSignal?.aborted).toBe(false) + resolveTokenPost( + new Response(JSON.stringify({ access_token: "new", refresh_token: "rotated", expires_in: 3600 }), { + status: 200, + }), + ) + await expect(secondNext).resolves.toMatchObject({ value: { type: "text", text: "ok" } }) + expect(tokenPosts).toBe(1) + // Close the second caller's stream so the shared refresh state is released. + await secondStream.return(undefined) + }) + + it("carries the caller's reason as the cause when a request-building guard fast-fails", async () => { + // A caller that stopped before the request was built is recorded only by the fast-fail + // guard, so the cause must carry the reason while name and message stay byte-identical + // for the Task.ts abort contract. + const controller = new AbortController() + const reason = new Error("cancelled before the request was built") + controller.abort(reason) + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + + const error = await captureError(handler.completePrompt("test", { abortSignal: controller.signal })) + + expect(error.name).toBe("AbortError") + expect(error.message).toBe("This operation was aborted") + expect(error.cause).toBe(reason) + }) +}) diff --git a/src/api/providers/__tests__/kimi-code.spec.ts b/src/api/providers/__tests__/kimi-code.spec.ts index a190ef3e7b7..b8bc5e26aa9 100644 --- a/src/api/providers/__tests__/kimi-code.spec.ts +++ b/src/api/providers/__tests__/kimi-code.spec.ts @@ -2,12 +2,17 @@ import { buildApiHandler } from "../../index" import { KimiCodeHandler } from "../kimi-code" import { clearAllMocks } from "../../../test-utils/reset" +import { captureError } from "../../../test-utils/errors" +import { makeCreateMessageMetadata } from "../../../test-utils/api" import { providerIdentifiers } from "@roo-code/types/provider-identifiers" +import OpenAI from "openai" +import { Stream } from "openai/streaming" -const { mockGetAccessToken, mockForceRefreshAccessToken, mockGetModels } = vi.hoisted(() => ({ +const { mockGetAccessToken, mockForceRefreshAccessToken, mockGetModels, mockGetKimiCodeModels } = vi.hoisted(() => ({ mockGetAccessToken: vi.fn(), mockForceRefreshAccessToken: vi.fn(), mockGetModels: vi.fn(), + mockGetKimiCodeModels: vi.fn(), })) vi.mock("../../../integrations/kimi-code/oauth", () => ({ @@ -22,12 +27,30 @@ vi.mock("../fetchers/modelCache", () => ({ refreshModels: mockGetModels, })) +vi.mock("../fetchers/kimi-code", () => ({ + getKimiCodeModels: mockGetKimiCodeModels, +})) + +/** + * Spies on the inherited OpenAI client's chat.completions.create. `client` is + * protected on the OpenAiHandler base (not on the public interface), so it is + * reached through a documented `as unknown as` projection onto the real SDK + * client type (AGENTS.md last resort; no `as any`). The spy keeps the SDK + * method's own signature, so the mock values below use full SDK response + * shapes (ChatCompletion / Stream of ChatCompletionChunk). + */ +function completionsCreate(handler: KimiCodeHandler) { + const client = (handler as unknown as { client: OpenAI }).client + return vi.spyOn(client.chat.completions, "create") +} + describe("KimiCodeHandler", () => { beforeEach(() => { clearAllMocks() mockGetAccessToken.mockResolvedValue("oauth-token") mockForceRefreshAccessToken.mockResolvedValue("refreshed-token") mockGetModels.mockRejectedValue(new Error("offline")) + mockGetKimiCodeModels.mockResolvedValue({}) }) it("is dispatched separately from Moonshot and preserves an unknown selected model", () => { @@ -104,6 +127,26 @@ describe("KimiCodeHandler", () => { }).rejects.toThrow("Not authenticated with Kimi Code") }) + it("surfaces a token refresh deadline unchanged instead of the sign-in error", async () => { + // The manager re-raises its deadline as a typed timeout and the provider has no mapping for + // it: a POST that never got an answer must stay distinguishable from a signed-out session, + // which is exactly what the "Not authenticated" null path above cannot express. + const deadline = Object.assign(new Error("Kimi Code OAuth request timed out"), { name: "TimeoutError" }) + mockGetAccessToken.mockRejectedValueOnce(deadline) + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const createCompletion = completionsCreate(handler) + const error = await captureError(handler.completePrompt("test")) + expect(error, "the provider does not replace the deadline with its own error").toBe(deadline) + expect(error.name).toBe("TimeoutError") + expect(error.message).toBe("Kimi Code OAuth request timed out") + expect(error.message, "a timeout is not reported as a missing sign-in").not.toContain("Not authenticated") + expect( + createCompletion, + "a deadline during token resolution issues no completion request", + ).not.toHaveBeenCalled() + expect(mockForceRefreshAccessToken, "a deadline does not start a second OAuth refresh").not.toHaveBeenCalled() + }) + it("throws error when API key auth is missing the key", async () => { const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key" }) const gen = handler.createMessage("system", [{ role: "user", content: "test" }]) @@ -115,7 +158,9 @@ describe("KimiCodeHandler", () => { }) it("retries with forced refresh on 401 when using OAuth", async () => { - const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + // The SDK client binds globalThis.fetch when it is constructed, so the completion stub + // has to be installed before the handler exists; written the other way round this test + // passes only because an earlier test left a fetch spy in place. const fetchSpy = vi.spyOn(globalThis, "fetch") fetchSpy.mockResolvedValueOnce(new Response(null, { status: 401 })) fetchSpy.mockResolvedValueOnce( @@ -123,6 +168,7 @@ describe("KimiCodeHandler", () => { status: 200, }), ) + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) const gen = handler.createMessage("system", [{ role: "user", content: "test" }]) try { for await (const _chunk of gen) { @@ -134,13 +180,55 @@ describe("KimiCodeHandler", () => { expect(mockForceRefreshAccessToken).toHaveBeenCalledOnce() }) + it("does not refresh or retry when the caller cancels before the 401 retry branch", async () => { + const controller = new AbortController() + // The completion request answers 401 in the same tick the caller cancels: the retry + // branch must observe the cancellation and stop instead of forcing an OAuth refresh + // and a second completion request. + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementationOnce(async () => { + controller.abort() + return new Response(null, { status: 401 }) + }) + // Stub first, handler second, for the same reason: the SDK client binds + // globalThis.fetch at construction. + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + + const error = await captureError( + (async () => { + for await (const _chunk of handler.createMessage( + "system", + [{ role: "user", content: "test" }], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + )) { + // consume + } + })(), + ) + + expect(error).toMatchObject({ name: "AbortError" }) + expect(mockForceRefreshAccessToken).not.toHaveBeenCalled() + expect(fetchSpy).toHaveBeenCalledTimes(1) + }) + it("force-refreshes and retries exactly once after a non-streaming OAuth 401", async () => { const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) const unauthorized = Object.assign(new Error("Unauthorized"), { status: 401 }) - const createCompletion = vi - .spyOn((handler as any).client.chat.completions, "create") + const createCompletion = completionsCreate(handler) .mockRejectedValueOnce(unauthorized) - .mockResolvedValueOnce({ choices: [{ message: { content: "retried" } }] }) + .mockResolvedValueOnce({ + id: "cmpl-1", + object: "chat.completion", + created: 0, + model: "kimi-for-coding", + choices: [ + { + index: 0, + message: { role: "assistant", content: "retried", refusal: null }, + logprobs: null, + finish_reason: "stop", + }, + ], + }) await expect(handler.completePrompt("test")).resolves.toBe("retried") expect(mockForceRefreshAccessToken).toHaveBeenCalledOnce() @@ -255,4 +343,311 @@ describe("KimiCodeHandler", () => { }) expect(handler.getModel().reasoning).toEqual({ reasoning_effort: "max" }) }) + + it("forwards the metadata abort signal to the inherited OpenAI SDK request", async () => { + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" }) + const controller = new AbortController() + const streamChunks = new Stream( + () => + (async function* (): AsyncGenerator { + yield { + id: "cmpl-1", + object: "chat.completion.chunk", + created: 0, + model: "kimi-for-coding", + choices: [{ index: 0, delta: { content: "hi" }, finish_reason: null }], + } + })()[Symbol.asyncIterator](), + new AbortController(), + ) + const createCompletion = completionsCreate(handler).mockResolvedValueOnce(streamChunks) + + const gen = handler.createMessage("system", [{ role: "user", content: "test" }], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await gen.next() + + expect(first.value).toEqual({ type: "text", text: "hi" }) + expect(createCompletion).toHaveBeenCalledWith(expect.anything(), { signal: expect.any(AbortSignal) }) + // toHaveBeenCalledWith compares an AbortSignal structurally, so any fresh signal + // would satisfy the shape above. setAbortSignal forwards the caller's signal, so + // pin the identity of the one this controller owns. + expect(createCompletion.mock.calls[0]?.[1]?.signal).toBe(controller.signal) + }) + + it("rejects before any request when the createMessage abort signal is already aborted", async () => { + // OAuth auth so the token assertions below are not vacuous: without the + // cancellation guard, resolveAccessToken would invoke the OAuth mocks. + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const controller = new AbortController() + controller.abort() + const createCompletion = completionsCreate(handler) + + const gen = handler.createMessage("system", [{ role: "user", content: "test" }], { + taskId: "test-task", + abortSignal: controller.signal, + }) + + await expect(async () => { + for await (const _ of gen) { + // consume + } + }).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + expect(createCompletion).not.toHaveBeenCalled() + // Cancellation must also skip model discovery and OAuth token work. + expect(mockGetModels).not.toHaveBeenCalled() + expect(mockGetAccessToken).not.toHaveBeenCalled() + expect(mockForceRefreshAccessToken).not.toHaveBeenCalled() + }) + + it("stops before the completion request when the signal aborts during model preparation", async () => { + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const controller = new AbortController() + // Cancellation lands WHILE model discovery is in flight. Discovery itself fails + // (it is best-effort and prepareRequest swallows it), so the contract under test is + // the observable one: no completion request may be issued once the caller has + // cancelled. The override's re-check after preparation is what stops it here; the + // inherited handler also guards, which is why removing only the override's check does + // not open a hole - the check keeps the cancellation from entering the base flow. + mockGetModels.mockImplementation(async () => { + controller.abort() + throw new Error("discovery cancelled") + }) + const createCompletion = completionsCreate(handler) + + const gen = handler.createMessage("system", [{ role: "user", content: "test" }], { + taskId: "test-task", + abortSignal: controller.signal, + }) + + await expect(async () => { + for await (const _ of gen) { + // consume + } + }).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + // Preparation really ran (so this is not the already-aborted path), and the + // completion request was never issued after the cancellation landed. + expect(mockGetModels).toHaveBeenCalled() + expect(createCompletion).not.toHaveBeenCalled() + }) + + it("forwards the discovery cancellation signal to the Kimi catalog fetcher", async () => { + // Issue #404: a cancellation during handler-driven discovery must reach + // the discovery HTTP request itself, not just stop the caller waiting. + mockGetKimiCodeModels.mockResolvedValueOnce({ "test-model": { maxTokens: 1000 } }) + const controller = new AbortController() + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" }) + + await handler.fetchModels({ provider: providerIdentifiers.kimiCode, apiKey: "key", signal: controller.signal }) + + expect(mockGetKimiCodeModels).toHaveBeenCalledWith("key", { signal: expect.any(AbortSignal) }) + // Identity, not structural equality: only this controller's signal can cancel + // the catalog fetch, and a fresh signal would pass the shape check above. + const discoveryCall = mockGetKimiCodeModels.mock.calls[0] as [string, { signal?: AbortSignal }] | undefined + expect(discoveryCall?.[1]?.signal).toBe(controller.signal) + }) + + it("prefers the explicit model-cache signal over options.signal", async () => { + mockGetKimiCodeModels.mockResolvedValueOnce({}) + const cacheSignal = new AbortController().signal + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" }) + + await handler.fetchModels( + { provider: providerIdentifiers.kimiCode, apiKey: "key", signal: new AbortController().signal }, + cacheSignal, + ) + + expect(mockGetKimiCodeModels).toHaveBeenCalledWith("key", { signal: expect.any(AbortSignal) }) + // The signal that wins must be the cache signal itself, not a fresh equivalent. + const cacheCall = mockGetKimiCodeModels.mock.calls[0] as [string, { signal?: AbortSignal }] | undefined + expect(cacheCall?.[1]?.signal).toBe(cacheSignal) + }) + + it("retries model discovery on a later request when the caller aborts during discovery", async () => { + // The SDK client binds globalThis.fetch at construction, so the completion + // stub must be installed before the handler is created. + vi.spyOn(globalThis, "fetch").mockImplementation( + async () => new Response(JSON.stringify({ choices: [{ message: { content: "ok" } }] }), { status: 200 }), + ) + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" }) + const controller = new AbortController() + // The caller cancels while discovery is in flight. The swallowed + // cancellation must not consume the single discovery attempt. + mockGetModels.mockImplementationOnce(async () => { + controller.abort() + throw new DOMException("This operation was aborted", "AbortError") + }) + const gen = handler.createMessage("system", [{ role: "user", content: "test" }], { + taskId: "test-task", + abortSignal: controller.signal, + }) + await expect(async () => { + for await (const _ of gen) { + // consume + } + }).rejects.toMatchObject({ name: "AbortError" }) + expect(mockGetModels).toHaveBeenCalledTimes(1) + // The handler must hand the caller's signal to the discovery path so the + // in-flight discovery request is cancellable (Issue #404), not merely + // observed after the fact. + expect(mockGetModels).toHaveBeenCalledWith( + expect.objectContaining({ signal: controller.signal }), + expect.anything(), + ) + + // A later request on the same handler must retry discovery rather than + // keep the fallback metadata. + mockGetModels.mockImplementationOnce(async () => ({ "kimi-for-coding": { maxTokens: 7777 } })) + await handler.completePrompt("second") + expect(mockGetModels).toHaveBeenCalledTimes(2) + // Adoption is observable through the public accessor: the record discovery returned + // must be what the handler serves afterwards, not the pre-discovery fallback. + expect(handler.getModel().id).toBe("kimi-for-coding") + expect(handler.getModel().info.maxTokens).toBe(7777) + }) + + it("forwards completePrompt abort options and timeoutMs through the override on both 401 retry attempts", async () => { + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const unauthorized = Object.assign(new Error("Unauthorized"), { status: 401 }) + const pendingAttempt = { + id: "cmpl-1", + object: "chat.completion", + created: 0, + model: "kimi-for-coding", + choices: [ + { + index: 0, + message: { role: "assistant", content: "retried", refusal: null }, + logprobs: null, + finish_reason: "stop", + }, + ], + } + let releaseRetry!: () => void + const retryGate = new Promise((resolve) => { + releaseRetry = () => resolve(pendingAttempt) + }) + const createCompletion = completionsCreate(handler) + .mockRejectedValueOnce(unauthorized) + // The double keeps the SDK's promise type; the value never reaches the caller because the + // request is cancelled while this gate is still closed (AGENTS.md last-resort cast). + .mockImplementationOnce( + (() => retryGate) as unknown as Parameters[0], + ) + const controller = new AbortController() + + const request = captureError( + handler.completePrompt("test", { abortSignal: controller.signal, timeoutMs: 30_000 }), + ) + // The second attempt stays pending, so the assertions below run while it is in flight. + await vi.waitFor(() => expect(createCompletion).toHaveBeenCalledTimes(2)) + expect(mockForceRefreshAccessToken).toHaveBeenCalledOnce() + for (const call of createCompletion.mock.calls) { + // A positive timeoutMs must reach the per-request config on both + // attempts: the external signal is merged in (never passed raw) and + // the SDK-level timeout is set, so a retry that dropped either would + // be caught here. + const options = call[1] + expect(options).toBeDefined() + expect(options?.timeout).toBe(30_000) + expect(options?.signal).toBeInstanceOf(AbortSignal) + expect(options?.signal).not.toBe(controller.signal) + expect(options?.signal?.aborted).toBe(false) + } + const retryOptions = createCompletion.mock.calls[1][1] + controller.abort() + expect(retryOptions?.signal?.aborted, "the pending retry follows the caller's stop").toBe(true) + // The rejection settles before the SDK's promise is released: the race ends the wait, not the mock. + expect((await request).name).toBe("AbortError") + releaseRetry() + }) + + it("aborts the first completion attempt's signal when the caller stops while it is in flight", async () => { + // The row above can only speak about the retry's signal: its first attempt has already + // rejected with the 401 by the time the caller stops, and its per-attempt loop asserts that + // each signal is merged and not yet aborted. Kept pending here, the first attempt's own + // signal is the one read after controller.abort(), so a first attempt wired to the deadline + // alone - without the caller's signal merged in - cannot pass this row. + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const firstAttempt = { + id: "cmpl-1", + object: "chat.completion", + created: 0, + model: "kimi-for-coding", + choices: [ + { + index: 0, + message: { role: "assistant", content: "first", refusal: null }, + logprobs: null, + finish_reason: "stop", + }, + ], + } + let releaseFirst!: () => void + const firstGate = new Promise((resolve) => { + releaseFirst = () => resolve(firstAttempt) + }) + // The double keeps the SDK's promise type; the value never reaches the caller because the + // request is cancelled while this gate is still closed (AGENTS.md last-resort cast). + const createCompletion = completionsCreate(handler).mockImplementationOnce( + (() => firstGate) as unknown as Parameters[0], + ) + const controller = new AbortController() + const request = captureError( + handler.completePrompt("test", { abortSignal: controller.signal, timeoutMs: 30_000 }), + ) + await vi.waitFor(() => expect(createCompletion).toHaveBeenCalledTimes(1)) + const options = createCompletion.mock.calls[0][1] + expect(options).toBeDefined() + expect(options?.timeout).toBe(30_000) + expect(options?.signal).toBeInstanceOf(AbortSignal) + expect(options?.signal).not.toBe(controller.signal) + expect(options?.signal?.aborted, "the first attempt is still in flight").toBe(false) + const attemptSignal = options?.signal + controller.abort() + expect(attemptSignal?.aborted, "the in-flight first attempt follows the caller's stop").toBe(true) + // Release only after the abort is observed, so the pending request is the thing that settles. + releaseFirst() + expect((await request).name).toBe("AbortError") + expect(mockForceRefreshAccessToken, "a caller stop must not trigger an OAuth refresh").not.toHaveBeenCalled() + }) + + it("rejects before any request when the completePrompt signal is already aborted", async () => { + // OAuth auth so the token assertions below are not vacuous: without the + // cancellation guard, resolveAccessToken would invoke the OAuth mocks. + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" }) + const controller = new AbortController() + controller.abort() + const createCompletion = completionsCreate(handler) + + await expect(handler.completePrompt("test", { abortSignal: controller.signal })).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(createCompletion).not.toHaveBeenCalled() + // Cancellation must also skip model discovery and OAuth token work. + expect(mockGetModels).not.toHaveBeenCalled() + expect(mockGetAccessToken).not.toHaveBeenCalled() + expect(mockForceRefreshAccessToken).not.toHaveBeenCalled() + }) + + it("surfaces a normalized AbortError when the SDK aborts a streaming request", async () => { + const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" }) + // The real SDK class: this spec does not mock the openai module. + const { APIUserAbortError } = await import("openai") + completionsCreate(handler).mockRejectedValueOnce(new APIUserAbortError()) + + const gen = handler.createMessage("system", [{ role: "user", content: "test" }], { taskId: "test-task" }) + const result = await captureError( + (async () => { + for await (const _ of gen) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) }) diff --git a/src/api/providers/__tests__/mimo.spec.ts b/src/api/providers/__tests__/mimo.spec.ts index 062d2fd9228..acafdb14dc0 100644 --- a/src/api/providers/__tests__/mimo.spec.ts +++ b/src/api/providers/__tests__/mimo.spec.ts @@ -4,6 +4,10 @@ import { clearAllMocks } from "../../../test-utils/reset" vi.mock("openai", () => { return { __esModule: true, + // The provider normalizes an aborted request out of an APIUserAbortError, so the mock has to + // export the class: without it the module under test destructures undefined and every abort + // row here would throw before it reaches the handler. + APIUserAbortError: class extends Error {}, default: vi.fn().mockImplementation(function () { return { chat: { @@ -39,6 +43,12 @@ import { MimoHandler } from "../mimo" import { convertToR1Format } from "../../transform/r1-format" import { sanitizeOpenAiCallId } from "../../../utils/tool-id" +// The wrapped error carries the HTTP status that Task.backoffAndAnnounce uses for its retry +// header. Read it through a shape check rather than widening the error type. +function preservedStatus(error: unknown): number | undefined { + return error instanceof Error && "status" in error ? (error as Error & { status: number }).status : undefined +} + describe("MimoHandler", () => { let handler: MimoHandler let mockOptions: ApiHandlerOptions @@ -891,9 +901,14 @@ describe("MimoHandler", () => { }) it("should handle API errors with provider prefix", async () => { - mockCreate.mockRejectedValueOnce(new Error("401 Unauthorized")) + mockCreate.mockRejectedValueOnce(Object.assign(new Error("401 Unauthorized"), { status: 401 })) - await expect(handler.completePrompt("Test prompt")).rejects.toThrow("OpenAI completion error:") + const failure = await handler.completePrompt("Test prompt").catch((error: unknown) => error) + // The prefix alone would pass on a wrapper that dropped the reason. Pin the text the SDK + // reported as well, and the status that Task.backoffAndAnnounce reads to pick a retry. + expect(failure).toBeInstanceOf(Error) + expect((failure as Error).message).toContain("OpenAI completion error: 401 Unauthorized") + expect(preservedStatus(failure)).toBe(401) }) it("should return empty string when choices array is empty", async () => { @@ -915,13 +930,24 @@ describe("MimoHandler", () => { it("should propagate network errors with provider prefix", async () => { mockCreate.mockRejectedValueOnce(new Error("ECONNREFUSED")) - await expect(handler.completePrompt("Test prompt")).rejects.toThrow("OpenAI completion error:") + const failure = await handler.completePrompt("Test prompt").catch((error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + // Containment for the same reason as the row above: the doubled prefix is real output of this + // path and is left as its own question rather than pinned as the expected shape. + expect((failure as Error).message).toContain("OpenAI completion error: ECONNREFUSED") + // A connection failure carries no HTTP status, and the wrapper must not invent one: a + // fabricated status would reach the retry header as a number nobody earned. + expect(preservedStatus(failure)).toBeUndefined() }) it("should propagate rate limit errors with provider prefix", async () => { - mockCreate.mockRejectedValueOnce(new Error("429 Too Many Requests")) + mockCreate.mockRejectedValueOnce(Object.assign(new Error("429 Too Many Requests"), { status: 429 })) - await expect(handler.completePrompt("Test prompt")).rejects.toThrow("OpenAI completion error:") + const failure = await handler.completePrompt("Test prompt").catch((error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + expect((failure as Error).message).toContain("OpenAI completion error: 429 Too Many Requests") + // 429 is the status that decides the backoff, so it has to survive the wrap. + expect(preservedStatus(failure)).toBe(429) }) it("should use correct model ID for mimo-v2.5 variant", async () => { diff --git a/src/api/providers/__tests__/model-catalog-adapters.spec.ts b/src/api/providers/__tests__/model-catalog-adapters.spec.ts index 61224791142..fc8322535e3 100644 --- a/src/api/providers/__tests__/model-catalog-adapters.spec.ts +++ b/src/api/providers/__tests__/model-catalog-adapters.spec.ts @@ -164,7 +164,7 @@ const cases: AdapterCase[] = [ fetcher: "getKimiCodeModels", scope: { urlScoped: false, keyScoped: true, authScoped: true }, expectedArgs: [API_KEY], - forwardsSignal: false, + forwardsSignal: true, prewarms: false, }, { diff --git a/src/api/providers/__tests__/openai.cancellation.spec.ts b/src/api/providers/__tests__/openai.cancellation.spec.ts new file mode 100644 index 00000000000..4e8d035b451 --- /dev/null +++ b/src/api/providers/__tests__/openai.cancellation.spec.ts @@ -0,0 +1,333 @@ +// npx vitest run api/providers/__tests__/openai.cancellation.spec.ts + +import { OpenAiHandler } from "../openai" +import { makeApiHandlerOptions, makeCreateMessageMetadata } from "../../../test-utils/api" +import { asyncStreamFrom } from "../../../test-utils/stream" +import type { ApiStreamChunk } from "../../transform/stream" + +vitest.mock("../utils/timeout-config", () => ({ + getApiRequestTimeout: vitest.fn().mockReturnValue(300_000), +})) + +const mockCreate = vitest.fn() + +vitest.mock("openai", () => { + const mockConstructor = vitest.fn() + return { + __esModule: true, + APIUserAbortError: class extends Error {}, + default: mockConstructor.mockImplementation(function () { + return { chat: { completions: { create: mockCreate } } } + }), + } +}) + +const standardHandler = () => + new OpenAiHandler( + makeApiHandlerOptions({ + openAiApiKey: "test-api-key", + openAiModelId: "gpt-4", + openAiBaseUrl: "https://api.openai.com/v1", + }), + ) + +// The O-series dispatch is a model-id check in createMessage, so the same construct is reached +// through an o3 model id on the same handler class. +const oSeriesHandler = (streamingEnabled = true) => + new OpenAiHandler( + makeApiHandlerOptions({ + openAiApiKey: "test-api-key", + openAiModelId: "o3-mini", + openAiBaseUrl: "https://api.openai.com/v1", + openAiStreamingEnabled: streamingEnabled, + }), + ) + +const standardNonStreamingHandler = () => + new OpenAiHandler( + makeApiHandlerOptions({ + openAiApiKey: "test-api-key", + openAiModelId: "gpt-4", + openAiBaseUrl: "https://api.openai.com/v1", + openAiStreamingEnabled: false, + }), + ) + +const toolCall = (index: number, id: string) => ({ + index, + id, + type: "function", + function: { name: "test_tool_" + String(index), arguments: '{"arg":' + String(index) + "}" }, +}) + +const usageFixture = { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } + +const nonStreamingResponse = (message: Record) => ({ + id: "test-completion", + choices: [{ message: { role: "assistant", refusal: null, ...message }, finish_reason: "stop", index: 0 }], + usage: usageFixture, +}) + +/** + * Consume a stream lazily, cancel the caller the moment its first event arrives, and record + * every event that still reaches the caller afterwards. The assertions ask the question the row + * asks - the complete subsequent event array must be empty - rather than checking only the + * events the provider happens to drop. + */ +async function cancelAtFirstEvent(handler: OpenAiHandler): Promise<{ + preAbort: ApiStreamChunk[] + postAbort: ApiStreamChunk[] + failure: unknown +}> { + const controller = new AbortController() + const preAbort: ApiStreamChunk[] = [] + const postAbort: ApiStreamChunk[] = [] + const consuming = (async () => { + try { + for await (const event of handler.createMessage( + "system prompt", + [], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + )) { + if (preAbort.length === 0) { + preAbort.push(event) + controller.abort() + continue + } + postAbort.push(event) + } + return null + } catch (error) { + return error + } + })() + return { preAbort, postAbort, failure: await consuming } +} + +/** + * Resolve the mocked request only once the caller has cancelled: the arrived answer exists, and + * the provider is the one that has to decide what to do with it. + */ +function resolveAfterCallerCancels(controller: AbortController, value: unknown) { + mockCreate.mockImplementationOnce(() => { + if (controller.signal.aborted) { + return Promise.resolve(value) + } + return new Promise((resolve) => { + controller.signal.addEventListener("abort", () => resolve(value), { once: true }) + }) + }) +} + +const expectAbortContract = (failure: unknown) => { + const error = failure as Error + expect(error?.name, JSON.stringify(failure)).toBe("AbortError") + expect(error.message.endsWith("request was aborted"), error.message).toBe(true) +} + +describe("OpenAiHandler cancellation", () => { + beforeEach(() => { + mockCreate.mockReset() + }) + + describe("streaming: no events after the caller cancels", () => { + it("releases nothing left in a chunk that mixed reasoning, content and tool calls (standard OpenAI)", async () => { + // One chunk carries every event class at once: reasoning, content, two tool-call + // partials and the finish_reason that would finalize them. A cancellation landing after + // the first event must stop the rest instead of draining the chunk. + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { + reasoning_content: "thinking", + content: "tail", + tool_calls: [toolCall(0, "call_1"), toolCall(1, "call_2")], + }, + finish_reason: "tool_calls", + index: 0, + }, + ], + }, + ]), + ) + + const { preAbort, postAbort, failure } = await cancelAtFirstEvent(standardHandler()) + + // The reasoning event is what the cancellation lands on: with it dropped, the helper would + // cancel after the text event instead and this row would stop pinning the transition. + expect(preAbort).toEqual([{ type: "reasoning", text: "thinking" }]) + expect(postAbort).toEqual([]) + expectAbortContract(failure) + }) + + it("releases nothing left in a chunk that mixed content and tool calls (O-series)", async () => { + mockCreate.mockImplementationOnce(() => + asyncStreamFrom([ + { + choices: [ + { + delta: { content: "tail", tool_calls: [toolCall(0, "call_1"), toolCall(1, "call_2")] }, + finish_reason: "tool_calls", + index: 0, + }, + ], + }, + ]), + ) + + const { preAbort, postAbort, failure } = await cancelAtFirstEvent(oSeriesHandler()) + + expect(preAbort).toEqual([{ type: "text", text: "tail" }]) + expect(postAbort).toEqual([]) + expectAbortContract(failure) + }) + }) + + describe("non-streaming: the signal is re-read after the response arrives", () => { + const mixedToolCallResponse = nonStreamingResponse({ + content: "answer", + tool_calls: [toolCall(0, "call_1")], + }) + + const drainUntilCancelled = async (handler: OpenAiHandler, controller: AbortController) => { + const released: ApiStreamChunk[] = [] + const done = (async () => { + try { + for await (const event of handler.createMessage( + "system prompt", + [], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + )) { + released.push(event) + } + return null + } catch (error) { + return error + } + })() + controller.abort() + return { released, failure: await done } + } + + it("discards the arrived text and tool calls when the caller cancelled in flight (standard OpenAI)", async () => { + const controller = new AbortController() + resolveAfterCallerCancels(controller, mixedToolCallResponse) + + const { released, failure } = await drainUntilCancelled(standardNonStreamingHandler(), controller) + + expect(released).toEqual([]) + expectAbortContract(failure) + }) + + it("discards the arrived text and tool calls when the caller cancelled in flight (O-series)", async () => { + const controller = new AbortController() + resolveAfterCallerCancels(controller, mixedToolCallResponse) + + const { released, failure } = await drainUntilCancelled(oSeriesHandler(false), controller) + + expect(released).toEqual([]) + expectAbortContract(failure) + }) + + it("does not report a completed prompt when the caller cancelled while the answer was in flight", async () => { + const controller = new AbortController() + // The answer is resolved first and the stop is queued behind it: the answer wins the request + // race, so only the post-response signal check can keep it from being reported as completed. + mockCreate.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveAnswer = resolve + }), + ) + let resolveAnswer: (value: unknown) => void = () => {} + + const handler = standardNonStreamingHandler() + const answered = handler.completePrompt("prompt", { abortSignal: controller.signal }) + resolveAnswer(nonStreamingResponse({ content: "answer" })) + queueMicrotask(() => controller.abort()) + const failure = await answered.then( + (): unknown => null, + (error: unknown) => error, + ) + + expectAbortContract(failure) + }) + }) + + describe("non-streaming: the signal is re-read between content yields", () => { + // A yield suspends the generator, so a cancellation can land between two pieces of one arrived + // response. Each case cancels after a given number of events and then asks which events still + // reach the caller. + const cancelAfterEvents = async (handler: OpenAiHandler, pulls: number) => { + const controller = new AbortController() + const released: ApiStreamChunk[] = [] + const draining = (async () => { + try { + for await (const event of handler.createMessage( + "system prompt", + [], + makeCreateMessageMetadata({ abortSignal: controller.signal }), + )) { + released.push(event) + if (released.length === pulls) { + controller.abort() + } + } + return null + } catch (error) { + return error + } + })() + return { released, failure: await draining } + } + + const twoToolCalls = nonStreamingResponse({ + content: "answer", + tool_calls: [toolCall(0, "call_1"), toolCall(1, "call_2")], + }) + const oneToolCall = nonStreamingResponse({ content: "answer", tool_calls: [toolCall(0, "call_1")] }) + + // openai.ts carries the non-streaming body twice: the standard dispatch and the O-series + // dispatch, so both are checked. + describe.each([ + { label: "standard OpenAI", makeHandler: standardNonStreamingHandler }, + { label: "O-series", makeHandler: () => oSeriesHandler(false) }, + ])("$label", ({ makeHandler }) => { + it("stops before the second tool call when the caller cancels after the first one", async () => { + mockCreate.mockImplementationOnce(async () => twoToolCalls) + + const { released, failure } = await cancelAfterEvents(makeHandler(), 1) + + expect(released).toEqual([ + { type: "tool_call", id: "call_1", name: "test_tool_0", arguments: '{"arg":0}' }, + ]) + expectAbortContract(failure) + }) + + it("stops before the text that follows the last tool call", async () => { + mockCreate.mockImplementationOnce(async () => oneToolCall) + + const { released, failure } = await cancelAfterEvents(makeHandler(), 1) + + expect(released).toEqual([ + { type: "tool_call", id: "call_1", name: "test_tool_0", arguments: '{"arg":0}' }, + ]) + expectAbortContract(failure) + }) + + it("stops before the usage event that follows the text", async () => { + mockCreate.mockImplementationOnce(async () => oneToolCall) + + const { released, failure } = await cancelAfterEvents(makeHandler(), 2) + + expect(released).toEqual([ + { type: "tool_call", id: "call_1", name: "test_tool_0", arguments: '{"arg":0}' }, + { type: "text", text: "answer" }, + ]) + expectAbortContract(failure) + }) + }) + }) +}) diff --git a/src/api/providers/__tests__/openai.spec.ts b/src/api/providers/__tests__/openai.spec.ts index c07ac2a3028..151b4740af1 100644 --- a/src/api/providers/__tests__/openai.spec.ts +++ b/src/api/providers/__tests__/openai.spec.ts @@ -9,7 +9,7 @@ import { prepareApiConversationMessage } from "../../../core/task/apiConversatio import { OpenAiHandler, getOpenAiModels } from "../openai" import { ApiHandlerOptions } from "../../../shared/api" import { Anthropic } from "@anthropic-ai/sdk" -import OpenAI, { AzureOpenAI } from "openai" +import OpenAI, { AzureOpenAI, APIUserAbortError } from "openai" import { openAiModelInfoSaneDefaults, DEEP_SEEK_DEFAULT_TEMPERATURE, @@ -19,8 +19,12 @@ import { } from "@roo-code/types" import { Package } from "../../../shared/package" import { makeApiHandlerOptions, makeCreateMessageMetadata } from "../../../test-utils/api" +import { getEventListeners } from "node:events" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +import { captureError } from "../../../test-utils/errors" + import { expectNoLoneSurrogates } from "../../../test-utils/surrogates" +import { MAX_TIMEOUT_MS } from "../utils/abort-signal" import axios from "axios" import { signedAssistantMessage, @@ -41,8 +45,10 @@ const mockResponsesCreate = vitest.fn() vitest.mock("openai", () => { const mockConstructor = vitest.fn() const mockAzureConstructor = vitest.fn() + const APIUserAbortError = class extends Error {} return { __esModule: true, + APIUserAbortError, default: mockConstructor.mockImplementation(function (options: { baseURL: string }) { return { baseURL: options.baseURL, @@ -502,6 +508,139 @@ describe("OpenAiHandler", () => { expect(textChunks[0].text).toBe("Test response") }) + it("should treat a streaming chunk without a delta as an empty delta", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([ + { choices: [{ delta: { content: "hello " }, index: 0 }] }, + // Some providers emit a final chunk with no delta field at all; the + // iteration must fall back to an empty object and not throw. + { choices: [{ finish_reason: "stop", index: 0 }] }, + ]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + const textChunks = chunks.filter((chunk) => chunk.type === "text") + expect(textChunks).toEqual([{ type: "text", text: "hello " }]) + }) + + it("should treat a streaming chunk without choices as an empty delta", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([ + { usage: { prompt_tokens: 1, completion_tokens: 2 } }, + { choices: [{ delta: { content: "tail" }, index: 0 }] }, + ]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + // A usage-only chunk has no choices at all; the optional chaining must + // resolve to the empty-delta fallback instead of throwing. + const textChunks = chunks.filter((chunk) => chunk.type === "text") + expect(textChunks).toEqual([{ type: "text", text: "tail" }]) + }) + + it("yields a recorded usage chunk ahead of the abort verdict when the stream is cancelled after the usage chunk", async () => { + // The abort verdict must not swallow usage the stream already reported: Task.ts prices the task + // from usage events, and the tokens behind a chunk that carried usage are spent whether or not + // the caller stops before the stream ends. Buffered matcher content stays suppressed. + const controller = new AbortController() + mockCreate.mockImplementationOnce(async () => + (async function* () { + yield { + choices: [{ delta: { content: "partial " }, index: 0 }], + usage: { prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 }, + } + controller.abort() + yield { choices: [{ delta: {}, index: 0 }] } + })(), + ) + + const emitted: Array<{ type: string; inputTokens?: number; outputTokens?: number }> = [] + let failure: Error | undefined + const stream = handler.createMessage( + systemPrompt, + messages, + makeCreateMessageMetadata({ abortSignal: controller.signal }), + ) + try { + for await (const chunk of stream) { + emitted.push(chunk) + } + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + + expect(emitted.map((chunk) => chunk.type)).toEqual(["text", "usage"]) + // Task.ts prices the task from the counts, not from the event type: a usage event with + // zero tokens would satisfy an assertion that only reads `type`. + expect(emitted[1]).toMatchObject({ inputTokens: 11, outputTokens: 7 }) + expect(failure?.name).toBe("AbortError") + expect(failure?.message).toBe("The OpenAI request was aborted") + }) + it("yields the recorded usage before an iterator error instead of discarding it", async () => { + // A stream that recorded usage and then failed on the next pull used to lose that record: + // the catch normalized the error before the usage yield was reached, so Task.ts never + // priced the tokens the stream had already reported. + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { + choices: [{ delta: { content: "partial " }, index: 0 }], + usage: { prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 }, + } + throw new Error("upstream died") + })(), + ) + + const collected: unknown[] = [] + const result = await captureError( + (async () => { + for await (const chunk of handler.createMessage(systemPrompt, messages)) { + collected.push(chunk) + } + })(), + ) + + expect(collected).toMatchObject([ + { type: "text", text: "partial " }, + { type: "usage", inputTokens: 11, outputTokens: 7 }, + ]) + expect(result.message).toBe("OpenAI completion error: upstream died") + }) + + it("should treat a streaming chunk with an empty choices array as an empty delta", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([{ choices: [] }, { choices: [{ delta: { content: "tail" }, index: 0 }] }]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + // With no first choice, delta and finish_reason resolve to undefined; + // the optional chaining must keep the iteration alive for the next chunk. + const textChunks = chunks.filter((chunk) => chunk.type === "text") + expect(textChunks).toEqual([{ type: "text", text: "tail" }]) + }) + + it("should keep the last usage when a later chunk carries none", async () => { + mockCreate.mockImplementationOnce(async () => + asyncStreamFrom([ + { + choices: [{ delta: { content: "hi" }, index: 0 }], + usage: { prompt_tokens: 7, completion_tokens: 3, total_tokens: 10 }, + }, + { choices: [{ delta: {}, index: 0 }] }, + ]), + ) + + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) + + // The recorded usage is only replaced by a chunk that actually carries + // usage; a later usage-less chunk must not wipe out the metrics. + const usageChunks = chunks.filter((chunk) => chunk.type === "usage") + expect(usageChunks).toHaveLength(1) + expect(usageChunks[0]).toMatchObject({ type: "usage", inputTokens: 7, outputTokens: 3 }) + }) + it("should forward the task abortSignal to streaming requests", async () => { const controller = new AbortController() @@ -1230,6 +1369,592 @@ describe("OpenAiHandler", () => { }) }) + describe("abort signal wiring", () => { + // toHaveBeenCalledWith compares arguments by value, so two live AbortSignals in the same state + // compare equal; the forwarded signal is the caller's own object or it is not, so it is read + // back and checked by identity. + const capturedRequestOptions = () => + mockCreate.mock.calls.at(-1)?.[1] as { path?: string; signal?: AbortSignal } | undefined + + it("should pass the metadata abort signal to the streaming createMessage request", async () => { + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = handler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: mockOptions.openAiModelId, stream: true }), + expect.anything(), + ) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should pass the metadata abort signal to the non-streaming createMessage request", async () => { + const nonStreamingHandler = new OpenAiHandler({ ...mockOptions, openAiStreamingEnabled: false }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = nonStreamingHandler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: mockOptions.openAiModelId }), + expect.anything(), + ) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should pass the metadata abort signal to the o3-family streaming request", async () => { + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = o3Handler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "o3-mini", stream: true }), + expect.anything(), + ) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should pass the metadata abort signal to the o3-family non-streaming request", async () => { + const o3Handler = new OpenAiHandler({ + ...mockOptions, + openAiModelId: "o3-mini", + openAiStreamingEnabled: false, + }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = o3Handler.createMessage("system prompt", [], metadata) + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "Test response" }) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "o3-mini" }), expect.anything()) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + it("should keep the Azure AI Inference path while passing the abort signal", async () => { + const azureHandler = new OpenAiHandler({ + ...mockOptions, + openAiBaseUrl: "https://test.services.ai.azure.com", + openAiModelId: "deepseek-v3", + }) + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = azureHandler.createMessage("system prompt", [], metadata) + await gen.next() + expect(capturedRequestOptions()).toMatchObject({ path: "/models/chat/completions" }) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + // The Azure path test above covers createMessage and the completePrompt signal test + // uses a non-Azure handler; neither pins both options in one request config, which is + // what the Azure completePrompt branch composes (path + merged signal). + it("should keep the Azure AI Inference path and release the request-local signal when the request settles", async () => { + const azureHandler = new OpenAiHandler({ + ...mockOptions, + openAiBaseUrl: "https://test.services.ai.azure.com", + openAiModelId: "deepseek-v3", + }) + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + const result = await azureHandler.completePrompt("test prompt", { abortSignal: controller.signal }) + + expect(result).toBe("response") + expect(capturedRequestOptions()).toMatchObject({ path: "/models/chat/completions" }) + const requestSignal = capturedRequestOptions()?.signal as AbortSignal + // Compared by identity the other way round this row would pin the very reuse the bridge + // exists to remove: the SDK gets a request-local controller, and by the time the prompt + // returns the caller's signal must already carry no abort listener. + expect(requestSignal, "the SDK is not handed the caller's own signal").not.toBe(controller.signal) + expect(requestSignal.aborted).toBe(false) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + }) + it("should hand completePrompt a request-local signal and release it when the request settles", async () => { + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + const result = await handler.completePrompt("test prompt", { abortSignal: controller.signal }) + + expect(result).toBe("response") + const requestSignal = capturedRequestOptions()?.signal as AbortSignal + expect(requestSignal, "the SDK is not handed the caller's own signal").not.toBe(controller.signal) + expect(requestSignal.aborted).toBe(false) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + }) + + it("should merge the completePrompt abort signal and timeout into a single request signal", async () => { + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + const result = await handler.completePrompt("test prompt", { + abortSignal: controller.signal, + timeoutMs: 5000, + }) + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + expect(result).toBe("response") + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + expect(requestOptions?.signal.aborted).toBe(false) + // The merged signal is request-local, not the caller's controller, and it is released when + // the request settles: a stop made after this point is deliberately not forwarded, so the + // cancellation half is proved by the listener count the caller would otherwise pay per + // completed request. + expect(requestOptions?.signal).not.toBe(controller.signal) + // A positive timeoutMs must be forwarded as the per-request SDK timeout. + expect(requestOptions?.timeout).toBe(5000) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + }) + it("keeps the caller stop wired into the chat request while it is in flight", async () => { + const controller = new AbortController() + let abortedInFlight: boolean | undefined + mockCreate.mockImplementationOnce(async (_params, options) => { + controller.abort() + abortedInFlight = options?.signal?.aborted + options?.signal?.throwIfAborted() + }) + + await expect( + handler.completePrompt("test prompt", { abortSignal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + }) + + // The stop arrives before the request settles, so it still reaches the SDK through the + // request-local signal: disposing the bridge earlier than this point would strand the + // caller mid-request. The signal handed over is request-local, and once the request is + // over the caller's own signal carries no listener again. + // Recorded from inside the request: the stop must already have reached the signal the SDK + // was handed. Disposing the bridge before the request settles strands the caller + // mid-flight, and the provider's own post-hoc caller check would still answer AbortError. + expect(abortedInFlight, "the caller stop reaches the request signal while in flight").toBe(true) + expect(mockCreate.mock.calls.at(-1)?.[1]?.signal).not.toBe(controller.signal) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + }) + + it("should abort the merged request signal on the deadline while the caller signal stays live", async () => { + // The two-input branch has to merge both inputs, not forward one of them: the timeout-only + // row below cannot reach this branch, so forwarding just the raw caller signal would pass + // that row and park here forever. + const controller = new AbortController() + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const resultPromise = captureError( + handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 50 }), + ) + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + // Nobody pressed stop: the deadline expired and the caller's own signal is still live. + expect(controller.signal.aborted).toBe(false) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The OpenAI completion request timed out") + }) + + it("should pass a timeout-only request signal when completePrompt timeoutMs is positive", async () => { + // The request must actually observe the merged signal firing: resolving the mock + // immediately only proves a signal was passed, not that a live (non-aborted) + // one aborts on timeout. Keep the request parked until its signal aborts, then + // assert the abort plus the retained timeout and error contract. + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const requestPromise = handler.completePrompt("test prompt", { timeoutMs: 50 }) + const resultPromise = captureError(requestPromise) + + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + // The timeout classification must survive the outer catch, which otherwise + // re-normalizes every abort as a user cancellation. + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The OpenAI completion request timed out") + }) + + it("should not pass a request signal for zero timeoutMs in completePrompt", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + await handler.completePrompt("test prompt", { timeoutMs: 0 }) + expect(mockCreate).toHaveBeenCalledWith(expect.anything(), {}) + }) + + it("should cap an oversized completePrompt timeoutMs before handing it to the SDK", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + await handler.completePrompt("test prompt", { timeoutMs: MAX_TIMEOUT_MS + 1 }) + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + // The merged abort signal already caps the delay; the SDK timeout option is the + // same value, because an uncapped one is clamped to ~1 ms by the timer itself. + expect(requestOptions?.timeout).toBe(MAX_TIMEOUT_MS) + }) + + it("should omit the request timeout for a non-finite completePrompt timeoutMs", async () => { + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + await handler.completePrompt("test prompt", { timeoutMs: Number.POSITIVE_INFINITY }) + // Infinity passes a bare `> 0` check but is not a legal timer delay, so it must + // mean "no explicit timeout" rather than reaching the SDK. + expect(mockCreate).toHaveBeenCalledWith(expect.anything(), {}) + }) + + it("should reject before issuing any request when the abort signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + await expect( + (async () => { + for await (const _ of handler.createMessage("system prompt", [], metadata)) { + // consume + } + })(), + ).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + expect(mockCreate).not.toHaveBeenCalled() + + mockCreate.mockClear() + await expect( + handler.completePrompt("test prompt", { abortSignal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("should normalize the SDK APIUserAbortError from the streaming path into the abort contract", async () => { + const controller = new AbortController() + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [], metadata)) { + // consume + } + })(), + ) + // The SDK error has name "Error" and a message ending in a period; the + // provider must rethrow the Task.ts contract shape instead. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("should normalize an abort error raised during stream iteration into the abort contract", async () => { + const controller = new AbortController() + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [], metadata)) { + // consume + } + })(), + ) + + // The iterator rejects after the first chunk; the provider must normalize + // it to the Task.ts contract shape instead of leaking the raw SDK error. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("stops a second pull that is already pending and rejects with the abort contract", async () => { + let releaseSecond = () => {} + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + // The second chunk is deferred and the caller cancels while that pull is still in + // flight. The for-await has already pulled it, so only the top-of-loop break stops the + // chunk from being processed: removing the break leaks "world", and removing the + // post-loop check ends the stream normally instead of rejecting. + let secondPullStarted = false + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "hello " } }] } + secondPullStarted = true + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const gen = handler.createMessage("system prompt", [], metadata) + + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "hello " }) + + const pendingPull = gen.next() + // Cancel while the pull is pending rather than before it starts: that is the + // interleaving the deferred chunk exists to create. + await vi.waitFor(() => expect(secondPullStarted).toBe(true)) + controller.abort() + releaseSecond() + + const leaked: string[] = [] + let failure: Error | undefined + try { + const pulled = await pendingPull + if (pulled.value?.type === "text") { + leaked.push(pulled.value.text) + } + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + + expect(leaked).toEqual([]) + expect(failure?.name).toBe("AbortError") + expect(failure?.message).toBe("The OpenAI request was aborted") + }) + + it("stops a second pull that is already pending and rejects with the abort contract (o3 family)", async () => { + let releaseSecond = () => {} + const secondGate = new Promise((resolve) => { + releaseSecond = resolve + }) + // The second chunk is deferred and the caller cancels while that pull is still in + // flight. The for-await has already pulled it, so only the top-of-loop break stops the + // chunk from being processed: removing the break leaks "world", and removing the + // post-loop check ends the stream normally instead of rejecting. + let secondPullStarted = false + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "hello " } }] } + secondPullStarted = true + await secondGate + yield { choices: [{ delta: { content: "world" } }] } + })(), + ) + + const controller = new AbortController() + const metadata = { taskId: "test-task", abortSignal: controller.signal } + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const gen = o3Handler.createMessage("system prompt", [], metadata) + + const first = await gen.next() + expect(first.value).toEqual({ type: "text", text: "hello " }) + + const pendingPull = gen.next() + // Cancel while the pull is pending rather than before it starts: that is the + // interleaving the deferred chunk exists to create. + await vi.waitFor(() => expect(secondPullStarted).toBe(true)) + controller.abort() + releaseSecond() + + const leaked: string[] = [] + let failure: Error | undefined + try { + const pulled = await pendingPull + if (pulled.value?.type === "text") { + leaked.push(pulled.value.text) + } + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } + + expect(leaked).toEqual([]) + expect(failure?.name).toBe("AbortError") + expect(failure?.message).toBe("The OpenAI request was aborted") + }) + + it("should wrap a non-abort stream error with the provider prefix when no metadata is passed", async () => { + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new Error("mid-stream boom") + })(), + ) + + const result = await captureError( + (async () => { + for await (const _ of handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // Without metadata there is no abort signal to consult; the raw error + // must still be normalized through the completion-error wrapper. + expect(result.name).toBe("Error") + expect(result.message).toBe("OpenAI completion error: mid-stream boom") + }) + + it("should normalize the SDK APIUserAbortError from completePrompt without an external signal", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const result = await captureError(handler.completePrompt("test prompt")) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize a fetch-level AbortError from completePrompt into the abort contract", async () => { + const fetchAbort = new Error("The operation was aborted.") + fetchAbort.name = "AbortError" + mockCreate.mockImplementationOnce(() => { + throw fetchAbort + }) + const result = await captureError(handler.completePrompt("test prompt")) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.cause).toBe(fetchAbort) + }) + + // The Responses route hands the caller's options straight to the SDK, so an + // APIUserAbortError raised after the signal is aborted reaches completePrompt's outer + // catch without going through the request-site handler. That is the one path that + // rebuilds the contract error, and the rebuild has to carry the failure that caused it. + it("keeps the SDK abort as the cause when the Responses route rejects it mid-flight", async () => { + const responsesHandler = new OpenAiHandler({ ...mockOptions, openAiUseResponsesApi: true }) + const controller = new AbortController() + const sdkAbort = new APIUserAbortError() + mockResponsesCreate.mockImplementationOnce(() => { + controller.abort() + throw sdkAbort + }) + const result = await captureError( + responsesHandler.completePrompt("test prompt", { abortSignal: controller.signal }), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.cause).toBe(sdkAbort) + }) + + // A native AbortError (the shape fetch raises) has no SDK identity to classify it by, so the + // Responses branch has to normalize it at its own request site: the outer catch rethrows an + // error whose name already reads AbortError, which would surface the transport's wording and + // drop the provider contract the rest of the abort paths pin. + it("normalizes a native abort raised by the Responses completion request", async () => { + const responsesHandler = new OpenAiHandler({ ...mockOptions, openAiUseResponsesApi: true }) + const controller = new AbortController() + const nativeAbort = new Error("The operation was aborted.") + nativeAbort.name = "AbortError" + mockResponsesCreate.mockImplementationOnce(() => { + controller.abort() + throw nativeAbort + }) + const result = await captureError( + responsesHandler.completePrompt("test prompt", { abortSignal: controller.signal }), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect(result.cause).toBe(nativeAbort) + }) + + it("should normalize the SDK APIUserAbortError from the non-streaming createMessage path", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const noStreamHandler = new OpenAiHandler({ ...mockOptions, openAiStreamingEnabled: false }) + const result = await captureError( + (async () => { + for await (const _ of noStreamHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize the SDK APIUserAbortError from the o3-family streaming path", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const result = await captureError( + (async () => { + for await (const _ of o3Handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize an abort error raised during o3-family stream iteration into the abort contract", async () => { + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + const o3Handler = new OpenAiHandler({ ...mockOptions, openAiModelId: "o3-mini" }) + const result = await captureError( + (async () => { + for await (const _ of o3Handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // handleStreamResponse consumes the iterator; a mid-stream abort must be + // normalized to the Task.ts contract shape, not leak as the raw SDK error. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should normalize the SDK APIUserAbortError from the o3-family non-streaming path", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + const o3Handler = new OpenAiHandler({ + ...mockOptions, + openAiModelId: "o3-mini", + openAiStreamingEnabled: false, + }) + const result = await captureError( + (async () => { + for await (const _ of o3Handler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("should still wrap non-abort completion errors with the provider prefix", async () => { + mockCreate.mockImplementationOnce(() => { + throw new Error("boom") + }) + const result = await captureError(handler.completePrompt("test prompt")) + expect(result.name).toBe("Error") + // The inner catch already wraps with the provider prefix and the outer + // catch wraps again (pre-existing double-wrap of openai.ts completePrompt). + expect(result.message).toBe("OpenAI completion error: OpenAI completion error: boom") + }) + }) + describe.each([ { name: "streaming chat", openAiModelId: "custom-model", streaming: true, singleCompletion: false }, { name: "non-streaming chat", openAiModelId: "custom-model", streaming: false, singleCompletion: false }, @@ -2699,8 +3424,19 @@ describe("OpenAiHandler Responses API (openAiUseResponsesApi)", () => { store: false, service_tier: "flex", }), - { signal: controller.signal, timeout: 1234 }, + expect.anything(), ) + // The request carries a request-local merge of the caller signal and the deadline, so the + // deadline stays armed while the SDK reads the JSON body. The bridge is disposed once the + // request settles, so what the caller would otherwise pay per completed request is the + // listener count left on its own signal - and in-flight cancellation is proved by the + // aborted-completion row below, which stops the caller from inside the request. + const responseOptions = mockResponsesCreate.mock.calls[0][1] + expect(responseOptions.timeout).toBe(1234) + expect(responseOptions.signal).toBeInstanceOf(AbortSignal) + expect(responseOptions.signal).not.toBe(controller.signal) + expect(responseOptions.signal?.aborted).toBe(false) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) expectNoLoneSurrogates(mockResponsesCreate.mock.calls[0][0]) }, ) @@ -2882,7 +3618,29 @@ describe("OpenAiHandler Responses API (openAiUseResponsesApi)", () => { await expect(handler.completePrompt("prompt", { abortSignal: controller.signal })).rejects.toMatchObject({ name: "AbortError", }) - expect(mockResponsesCreate.mock.calls[0][1].signal).toBe(controller.signal) + const responseOptions = mockResponsesCreate.mock.calls[0][1] + // The stop lands while the request is in flight, so it still reaches the SDK even though the + // signal it was handed is request-local rather than the caller's own object. + expect(responseOptions.signal).not.toBe(controller.signal) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + }) + + it("keeps the caller stop wired into the Responses request while it is in flight", async () => { + const handler = new OpenAiHandler(baseOptions) + const controller = new AbortController() + let abortedInFlight: boolean | undefined + mockResponsesCreate.mockImplementationOnce(async (_body, options) => { + controller.abort() + abortedInFlight = options?.signal?.aborted + options?.signal?.throwIfAborted() + }) + await expect(handler.completePrompt("prompt", { abortSignal: controller.signal })).rejects.toMatchObject({ + name: "AbortError", + }) + // Same datum as the chat row above, on the Responses branch: the stop is observed on the + // signal the SDK was handed while the request is still open. + expect(abortedInFlight, "the caller stop reaches the request signal while in flight").toBe(true) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) }) it.each(["failure", "close", "construction"])("clears prior reasoning on $s", async (exit) => { diff --git a/src/api/providers/__tests__/sambanova.spec.ts b/src/api/providers/__tests__/sambanova.spec.ts index 2a19d5659c4..18636f9c4ff 100644 --- a/src/api/providers/__tests__/sambanova.spec.ts +++ b/src/api/providers/__tests__/sambanova.spec.ts @@ -15,6 +15,8 @@ vitest.mock("openai", () => { default: vitest.fn(function () { return { chat: { completions: { create: createMock } } } }), + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, } }) diff --git a/src/api/providers/__tests__/zai.spec.ts b/src/api/providers/__tests__/zai.spec.ts index 49ed82a66c6..4a526d7bb63 100644 --- a/src/api/providers/__tests__/zai.spec.ts +++ b/src/api/providers/__tests__/zai.spec.ts @@ -1,6 +1,8 @@ // npx vitest run src/api/providers/__tests__/zai.spec.ts -import OpenAI from "openai" +import { getEventListeners } from "node:events" + +import OpenAI, { APIUserAbortError } from "openai" import { Anthropic } from "@anthropic-ai/sdk" import { @@ -17,10 +19,14 @@ import { import { ZAiHandler } from "../zai" import { asyncStreamFrom } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" +import { captureError } from "../../../test-utils/errors" +import { MAX_TIMEOUT_MS } from "../utils/abort-signal" vitest.mock("openai", () => { const createMock = vitest.fn() return { + // Named export consumed by the provider for abort-error normalization + APIUserAbortError: class extends Error {}, default: vitest.fn(function () { return { chat: { completions: { create: createMock } } } }), @@ -634,6 +640,469 @@ describe("ZAiHandler", () => { }) }) + describe("abort signal wiring", () => { + beforeEach(() => { + handler = new ZAiHandler({ zaiApiKey: "test-zai-api-key", zaiApiLine: "international_coding" }) + }) + + it("createMessage should pass a per-request abort signal on the GLM thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // The double records the request options it received. The provider hands the SDK a + // disposable bridge signal rather than the caller's own, so the assertions below go by + // non-identity plus forwarding while the request is live: comparing a live signal by + // identity would pin the leak the bridge exists to remove, and a structural match alone + // would accept a signal that ignores the caller. A chunk is yielded so the generator is + // still suspended - the request still live - when the caller aborts. + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return asyncStreamFrom([{ choices: [{ delta: { content: "a" } }] }]) + }) + + const gen = thinkingHandler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await gen.next() + controller.abort() + + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ model: "glm-4.7", thinking: { type: "enabled" } }), + expect.anything(), + ) + expect(first.value).toMatchObject({ type: "text", text: "a" }) + expect(sentOptions?.signal).toBeDefined() + expect(sentOptions?.signal).not.toBe(controller.signal) + expect(sentOptions?.signal?.aborted).toBe(true) + }) + + it("createMessage should pass a per-request abort signal for non-thinking models via the base path", async () => { + const plainHandler = new ZAiHandler({ + apiModelId: "glm-4.6", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // The double records the request options it received. The provider hands the SDK a + // disposable bridge signal rather than the caller's own, so the assertions below go by + // non-identity plus forwarding while the request is live: comparing a live signal by + // identity would pin the leak the bridge exists to remove, and a structural match alone + // would accept a signal that ignores the caller. A chunk is yielded so the generator is + // still suspended - the request still live - when the caller aborts. + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return asyncStreamFrom([{ choices: [{ delta: { content: "a" } }] }]) + }) + + const gen = plainHandler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + const first = await gen.next() + controller.abort() + + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "glm-4.6" }), expect.anything()) + expect(first.value).toMatchObject({ type: "text", text: "a" }) + expect(sentOptions?.signal).toBeDefined() + expect(sentOptions?.signal).not.toBe(controller.signal) + expect(sentOptions?.signal?.aborted).toBe(true) + }) + + it("createMessage should reject before any request when the abort signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect(async () => { + for await (const _ of handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + })) { + // consume + } + }).rejects.toMatchObject({ name: "AbortError", message: "This operation was aborted" }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("createMessage should normalize the SDK APIUserAbortError on the thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("createMessage should normalize a rejected-Promise APIUserAbortError on the thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + // The awaited request creation rejects (the SDK's pre-abort shape); + // normalization must catch it, not only synchronous throws. + mockCreate.mockRejectedValueOnce(new APIUserAbortError()) + + const result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + }) + + it("createMessage should wrap a non-abort thinking-path creation failure exactly once", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + // The thinking override used to normalize the failure itself and the base + // createMessage normalized it again on top: doubled prefix, doubled log line. + mockCreate.mockRejectedValueOnce(new Error("boom")) + const errorLog = vitest.spyOn(console, "error").mockImplementation(() => {}) + + // captureError throws when the operation resolves instead of rejecting - the very contract + // violation this test exists to catch - so the restoration has to span the await: a restoring + // finally that starts after it leaks the console.error spy into whichever test runs next. + let result: Error + try { + result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + expect(result.message).toBe("Z.ai completion error: boom") + expect(errorLog).toHaveBeenCalledTimes(1) + } finally { + errorLog.mockRestore() + } + }) + + it("createMessage leaves no console.error spy installed when the mocked create resolves", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + // The resolving shape: an empty async iterable satisfies the stream loop and rejects nothing, + // so the only failure left is captureError's own "expected a rejection" assertion. + mockCreate.mockResolvedValueOnce((async function* () {})()) + const errorLog = vitest.spyOn(console, "error").mockImplementation(() => {}) + let failure: Error | undefined + try { + failure = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + } catch (error) { + failure = error instanceof Error ? error : new Error(String(error)) + } finally { + errorLog.mockRestore() + } + expect(failure?.message).toBe("Expected the operation to reject") + expect(vitest.isMockFunction(console.error), "the spy must not outlive its own test").toBe(false) + }) + + it("createMessage should normalize an abort error raised during stream iteration on the thinking path", async () => { + const thinkingHandler = new ZAiHandler({ + apiModelId: "glm-4.7", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockImplementationOnce(() => + (async function* () { + yield { choices: [{ delta: { content: "partial" } }] } + throw new APIUserAbortError() + })(), + ) + + const result = await captureError( + (async () => { + for await (const _ of thinkingHandler.createMessage("system prompt", [])) { + // consume + } + })(), + ) + + // The thinking path inherits stream iteration from the base provider; a + // mid-stream abort must normalize to the Task.ts contract shape. + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + expect(result.message.endsWith("aborted")).toBe(true) + }) + + it("completePrompt should pass a per-request abort signal and release it on completion", async () => { + const controller = new AbortController() + // The double records the request options it received. The provider hands the SDK a + // disposable bridge signal rather than the caller's own, and the assertions below go by + // non-identity plus release: comparing a live signal by identity would pin the leak the + // bridge exists to remove, and by the time completePrompt returns the request is over, so + // the caller's signal must already carry no listener - that count is what a long task + // pays for on every completed request. + let sentOptions: { signal?: AbortSignal } | undefined + mockCreate.mockImplementationOnce((_params: unknown, options: { signal?: AbortSignal }) => { + sentOptions = options + return Promise.resolve({ choices: [{ message: { content: "response" } }] }) + }) + + const result = await handler.completePrompt("test prompt", { abortSignal: controller.signal }) + + expect(result).toBe("response") + expect(sentOptions?.signal).toBeDefined() + expect(sentOptions?.signal).not.toBe(controller.signal) + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + }) + + it("completePrompt should reject before any request when the signal is already aborted", async () => { + const controller = new AbortController() + controller.abort() + + await expect( + handler.completePrompt("test prompt", { abortSignal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("completePrompt should normalize the SDK APIUserAbortError", async () => { + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError(handler.completePrompt("test prompt")) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + }) + + it("completePrompt should cap an oversized timeoutMs before handing it to the SDK", async () => { + // GLM-5.3 has its own completePrompt path; other models delegate to the base + // provider, so the override is what this test has to exercise. + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await h53.completePrompt("test prompt", { timeoutMs: MAX_TIMEOUT_MS + 1 }) + + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + // Same capped normalization as the merged abort signal: uncapped, the SDK timer + // clamps the delay to ~1 ms and aborts the request almost immediately. + expect(requestOptions?.timeout).toBe(MAX_TIMEOUT_MS) + }) + + it("completePrompt should omit the request timeout for a non-finite timeoutMs", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await h53.completePrompt("test prompt", { timeoutMs: Number.POSITIVE_INFINITY }) + + // Infinity satisfies a bare `> 0` check but is not a legal timer delay, so it has + // to mean "no explicit timeout" and leave the request config unset. + expect(mockCreate).toHaveBeenCalledWith(expect.anything(), undefined) + }) + + it("glm-5.3 completePrompt should cancel the in-flight request when the caller signal aborts", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // Emulate the OpenAI SDK: the pending request rejects when its signal aborts. + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const requestPromise = h53.completePrompt("prompt", { abortSignal: controller.signal, timeoutMs: 5000 }) + await vi.waitFor(() => expect(mockCreate).toHaveBeenCalled()) + const requestCall = mockCreate.mock.calls.at(-1) + const requestOptions = requestCall?.[1] + // The merged signal follows the caller's own stop, and it does so long before the five-second + // deadline, so a provider that forwarded only the timeout signal fails here. + expect(requestOptions?.signal?.aborted).toBe(false) + controller.abort() + expect(requestOptions?.signal?.aborted).toBe(true) + + const result = await captureError(requestPromise) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + expect(requestCall?.[0]).toEqual( + expect.objectContaining({ model: "glm-5.3", thinking: { type: "enabled", clear_thinking: false } }), + ) + // A positive timeoutMs must be forwarded as the per-request SDK timeout. + expect(requestOptions?.timeout).toBe(5000) + }) + + it("glm-5.3 completePrompt discards an answer that arrives after the caller cancelled", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + // The GLM endpoint answered, and the answer arrived after the caller had already + // cancelled: the provider must not turn a cancelled request into a completed prompt. + // The answer has to win the race against the request signal. Resolving the mock from the + // abort callback cannot show that: the same abort rejects the race first, so the provider + // never reaches the guard that discards the arrived content. So the mock hands back a + // pending promise - the endpoint answered on its own, nothing about it waits for the stop - + // the test fulfils it, and the caller stops one microtask later: after the race has taken + // the answer, before the provider wakes up to read the response. + let resolveAnswer: (value: unknown) => void = () => {} + mockCreate.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveAnswer = resolve + }), + ) + + const answered = h53.completePrompt("prompt", { abortSignal: controller.signal }) + resolveAnswer({ choices: [{ message: { role: "assistant", content: "late answer" } }] }) + queueMicrotask(() => controller.abort()) + + const failure = await answered.then( + (): unknown => null, + (error: unknown) => error, + ) + + expect((failure as Error)?.name, JSON.stringify(failure)).toBe("AbortError") + expect(String((failure as Error)?.message)).toContain("request was aborted") + }) + + it("glm-5.3 completePrompt should normalize the SDK APIUserAbortError", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockImplementationOnce(() => { + throw new APIUserAbortError() + }) + + const result = await captureError(h53.completePrompt("prompt")) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Z.ai request was aborted") + }) + + it("glm-5.3 completePrompt should omit the request timeout when timeoutMs is zero", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await expect(h53.completePrompt("prompt", { timeoutMs: 0 })).resolves.toBe("response") + + // Values <= 0 mean "no explicit timeout": with no caller signal either, + // the built request config is empty and nothing is forwarded to the SDK. + expect(mockCreate.mock.calls.at(-1)?.[1]).toBeUndefined() + }) + + // The pre-aborted guard in the glm-5.3 override is its own: the shared + // pre-aborted test above uses the default glm-4.7 model, which delegates to + // super.completePrompt, so it never reaches this override's throwIfAborted. + it("glm-5.3 completePrompt should reject before any request when the signal is already aborted", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + const controller = new AbortController() + controller.abort() + + await expect(h53.completePrompt("prompt", { abortSignal: controller.signal })).rejects.toMatchObject({ + name: "AbortError", + message: "This operation was aborted", + }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + // A timeout with no caller abort must stay a TimeoutError: the caller signal is + // absent, so only the merged request signal carries a TimeoutError reason, and the + // override's own catch is what classifies it. + it("glm-5.3 completePrompt should classify a timeout-only abort as TimeoutError", async () => { + const h53 = new ZAiHandler({ + apiModelId: "glm-5.3", + zaiApiKey: "test-zai-api-key", + zaiApiLine: "international_coding", + }) + let capturedOptions: { signal?: AbortSignal; timeout?: number } | undefined + mockCreate.mockImplementationOnce( + async (_params: unknown, options?: { signal?: AbortSignal; timeout?: number }) => { + capturedOptions = options + await new Promise((resolve) => { + if (options?.signal?.aborted) { + resolve() + } else { + options?.signal?.addEventListener("abort", () => resolve(), { once: true }) + } + }) + throw new APIUserAbortError() + }, + ) + + const requestPromise = h53.completePrompt("prompt", { timeoutMs: 50 }) + const resultPromise = captureError(requestPromise) + + await vi.waitFor(() => expect(capturedOptions?.signal?.aborted).toBe(true)) + expect(capturedOptions?.timeout).toBe(50) + + const result = await resultPromise + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The Z.ai completion request timed out") + expect(result.cause).toBeInstanceOf(Error) + }) + }) + describe("GLM-4.7 Thinking Mode", () => { it("should cap GLM-5.1 max_tokens to 20% of context window by default", async () => { const handlerWithModel = new ZAiHandler({ @@ -652,6 +1121,7 @@ describe("ZAiHandler", () => { model: "glm-5.1", max_tokens: 40_000, }), + undefined, ) }) @@ -684,6 +1154,7 @@ describe("ZAiHandler", () => { model: "glm-5.1", max_tokens: 100_000, }), + undefined, ) }) @@ -706,6 +1177,7 @@ describe("ZAiHandler", () => { model: "glm-4.7", thinking: { type: "enabled" }, }), + undefined, ) }) @@ -728,6 +1200,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled" }, reasoning_effort: "high", }), + undefined, ) }) @@ -750,6 +1223,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled" }, reasoning_effort: "max", }), + undefined, ) }) @@ -773,6 +1247,7 @@ describe("ZAiHandler", () => { reasoning_effort: "max", temperature: 1, }), + undefined, ) }) @@ -799,6 +1274,7 @@ describe("ZAiHandler", () => { reasoning_effort: "max", temperature: 1, }), + undefined, ) }) @@ -822,6 +1298,7 @@ describe("ZAiHandler", () => { reasoning_effort: "max", temperature: 1, }), + undefined, ) }) @@ -844,6 +1321,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled", clear_thinking: false }, reasoning_effort: "max", }), + undefined, ) }) @@ -858,13 +1336,16 @@ describe("ZAiHandler", () => { mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) await expect(handlerWithModel.completePrompt("prompt")).resolves.toBe("response") - expect(mockCreate).toHaveBeenCalledWith({ - model: "glm-5.3", - messages: [{ role: "user", content: "prompt" }], - temperature: 1, - thinking: { type: "enabled", clear_thinking: false }, - reasoning_effort: "low", - }) + expect(mockCreate).toHaveBeenCalledWith( + { + model: "glm-5.3", + messages: [{ role: "user", content: "prompt" }], + temperature: 1, + thinking: { type: "enabled", clear_thinking: false }, + reasoning_effort: "low", + }, + undefined, + ) }) it("should use the official GLM-5.3-Flash parameters for completePrompt", async () => { @@ -878,13 +1359,16 @@ describe("ZAiHandler", () => { mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) await expect(handlerWithModel.completePrompt("prompt")).resolves.toBe("response") - expect(mockCreate).toHaveBeenCalledWith({ - model: "glm-5.3-flash", - messages: [{ role: "user", content: "prompt" }], - temperature: 1, - thinking: { type: "enabled", clear_thinking: false }, - reasoning_effort: "low", - }) + expect(mockCreate).toHaveBeenCalledWith( + { + model: "glm-5.3-flash", + messages: [{ role: "user", content: "prompt" }], + temperature: 1, + thinking: { type: "enabled", clear_thinking: false }, + reasoning_effort: "low", + }, + undefined, + ) }) it("should omit reasoning_effort for GLM-5.2 when reasoningEffort is set to disable", async () => { @@ -924,6 +1408,7 @@ describe("ZAiHandler", () => { thinking: { type: "enabled" }, reasoning_effort: "high", }), + undefined, ) }) @@ -947,6 +1432,7 @@ describe("ZAiHandler", () => { model: "glm-4.7", thinking: { type: "disabled" }, }), + undefined, ) }) @@ -970,6 +1456,7 @@ describe("ZAiHandler", () => { model: "glm-4.7", thinking: { type: "enabled" }, }), + undefined, ) }) @@ -1007,6 +1494,7 @@ describe("ZAiHandler", () => { model: "glm-5-turbo", thinking: { type: "enabled" }, }), + undefined, ) }) @@ -1029,6 +1517,7 @@ describe("ZAiHandler", () => { model: "glm-5-turbo", thinking: { type: "disabled" }, }), + undefined, ) }) }) diff --git a/src/api/providers/base-openai-compatible-provider.ts b/src/api/providers/base-openai-compatible-provider.ts index b177726f852..b923980bd64 100644 --- a/src/api/providers/base-openai-compatible-provider.ts +++ b/src/api/providers/base-openai-compatible-provider.ts @@ -6,14 +6,23 @@ import { type ModelInfo, openAiModelInfoSaneDefaults } from "@roo-code/types" import { type ApiHandlerOptions, getModelMaxOutputTokens } from "../../shared/api" import { TagMatcher } from "../../utils/tag-matcher" import { ApiStream, ApiStreamUsageChunk } from "../transform/stream" +import { handleOpenAIRequestError } from "./utils/error-handler" import { convertToOpenAiMessages } from "../transform/openai-format" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" import { DEFAULT_HEADERS } from "./constants" import { BaseProvider } from "./base-provider" -import { handleOpenAIError } from "./utils/error-handler" import { calculateApiCostOpenAI } from "../../shared/cost" import { extractReasoningFromDelta } from "./utils/extract-reasoning" +import { RequestConfigBuilder } from "./config-builder/request-config-builder" +import { + bridgeExternalAbortSignal, + createAbortError, + mergeAbortSignalAndTimeout, + rejectOnAbort, + throwIfAborted, +} from "./utils/abort-signal" +import { getRequestTimeoutMs } from "./utils/request-timeout" type BaseOpenAiCompatibleProviderOptions = ApiHandlerOptions & { providerName: string @@ -23,6 +32,13 @@ type BaseOpenAiCompatibleProviderOptions = ApiHandlerO defaultTemperature?: number } +/** Subset of OpenAI.RequestOptions built per request for the abort-signal wiring. */ +type OpenAiRequestConfig = { + signal?: AbortSignal + /** Per-request SDK timeout (ms); overrides the client-level default when set. */ + timeout?: number +} + export abstract class BaseOpenAiCompatibleProvider extends BaseProvider implements SingleCompletionHandler @@ -67,7 +83,7 @@ export abstract class BaseOpenAiCompatibleProvider }) } - protected createStream( + protected async createStream( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, @@ -103,11 +119,10 @@ export abstract class BaseOpenAiCompatibleProvider ;(params as any).thinking = { type: "enabled" } } - try { - return this.client.chat.completions.create(params, requestOptions) - } catch (error) { - throw handleOpenAIError(error, this.providerName) - } + // Creation errors are normalized once in createMessage: subclasses can override this + // method and return the SDK promise without awaiting it, so a catch here would not + // cover every provider. + return await this.client.chat.completions.create(params, requestOptions) } override async *createMessage( @@ -115,7 +130,36 @@ export abstract class BaseOpenAiCompatibleProvider messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { - const stream = await this.createStream(systemPrompt, messages, metadata) + throwIfAborted(metadata?.abortSignal) + const signal = metadata?.abortSignal + + // Per-request abort wiring (RequestConfigBuilder adoption): subclasses inherit + // it by receiving the built config as createStream's requestOptions. The bridge, not the + // caller's signal, is what the SDK receives: OpenAI 5.23.2 attaches an anonymous abort + // listener to whichever signal it is handed and never removes it, so a task-level signal + // would carry one more retained listener for every request that completed. Disposal runs + // on each completion path below. + const abortBridge = bridgeExternalAbortSignal(metadata?.abortSignal) + const requestConfig = new RequestConfigBuilder() + .setOption("signal", abortBridge.signal) + .build() + // Request creation can reject before the stream exists. Some subclasses return the + // SDK promise without awaiting it (e.g. FriendliHandler.createStream), so their own + // catch cannot fire; normalize creation-time failures here so an abort during request + // creation reaches Task.ts as an AbortError instead of a raw APIUserAbortError. + let stream: AsyncIterable + try { + // The SDK can sleep through a 429 backoff without observing the signal, so the creation + // await is raced against it: a stop settles the request instead of waiting out the sleep. + // Some subclasses return a thenable rather than a real promise, so normalise before racing it. + const created = () => Promise.resolve(this.createStream(systemPrompt, messages, metadata, requestConfig)) + const createdSignal = requestConfig?.signal + stream = createdSignal ? await rejectOnAbort(created(), createdSignal, this.providerName) : await created() + } catch (error) { + // The request ended before a stream existed, so nothing is left to forward to. + abortBridge.dispose() + throw handleOpenAIRequestError(error, this.providerName, signal) + } const matcher = new TagMatcher( ["think", "thought"], @@ -129,64 +173,127 @@ export abstract class BaseOpenAiCompatibleProvider let lastUsage: OpenAI.CompletionUsage | undefined const activeToolCallIds = new Set() - for await (const chunk of stream) { - // Check for provider-specific error responses (e.g., MiniMax base_resp) - const chunkAny = chunk as any - if (chunkAny.base_resp?.status_code && chunkAny.base_resp.status_code !== 0) { - throw new Error( - `${this.providerName} API Error (${chunkAny.base_resp.status_code}): ${chunkAny.base_resp.status_msg || "Unknown error"}`, - ) - } + // An iterator error is normalized only after the usage record below has been handed to the + // caller, so a mid-stream failure cannot bypass the tokens already streamed. The failure is + // tracked beside its value because a rejection can carry `undefined`, and that rejection must + // still reach the handler instead of ending the stream normally after partial output. + let streamError: unknown = undefined + let streamFailed = false - const delta = chunk.choices?.[0]?.delta - const finishReason = chunk.choices?.[0]?.finish_reason + try { + for await (const chunk of stream) { + // Streaming-loop abort defense: the for-await above already pulled this + // chunk; the top-of-loop break stops *processing* (and yielding) buffered + // content that arrived after the caller's signal aborted. + if (signal?.aborted) { + break + } + // Check for provider-specific error responses (e.g., MiniMax base_resp). + // ChatCompletionChunk has no base_resp member, so read it through an + // unknown guard instead of casting the whole chunk. + const chunkUnknown: unknown = chunk + const baseResp: unknown = + typeof chunkUnknown === "object" && chunkUnknown !== null && "base_resp" in chunkUnknown + ? (chunkUnknown as { base_resp?: unknown }).base_resp + : undefined + const baseRespFields = + baseResp !== null && typeof baseResp === "object" + ? (baseResp as Record) + : undefined + const baseRespStatusCode = baseRespFields?.["status_code"] + const baseRespStatusMsg = baseRespFields?.["status_msg"] + if (baseRespStatusCode && baseRespStatusCode !== 0) { + throw new Error( + `${this.providerName} API Error (${baseRespStatusCode}): ${String(baseRespStatusMsg || "Unknown error")}`, + ) + } - const reasoningText = extractReasoningFromDelta(delta) - if (reasoningText) { - yield { type: "reasoning", text: reasoningText } - } + const delta = chunk.choices?.[0]?.delta + const finishReason = chunk.choices?.[0]?.finish_reason - if (delta?.content) { - for (const processedChunk of matcher.update(delta.content)) { - yield processedChunk + const reasoningText = extractReasoningFromDelta(delta) + if (reasoningText) { + yield { type: "reasoning", text: reasoningText } } - } - // Emit raw tool call chunks - NativeToolCallParser handles state management - if (delta?.tool_calls) { - for (const toolCall of delta.tool_calls) { - if (toolCall.id) { - activeToolCallIds.add(toolCall.id) + if (delta?.content) { + for (const processedChunk of matcher.update(delta.content)) { + if (signal?.aborted) { + break + } + yield processedChunk } - yield { - type: "tool_call_partial", - index: toolCall.index, - id: toolCall.id, - name: toolCall.function?.name, - arguments: toolCall.function?.arguments, + } + + // Emit raw tool call chunks - NativeToolCallParser handles state management + if (delta?.tool_calls) { + for (const toolCall of delta.tool_calls) { + if (signal?.aborted) { + break + } + if (toolCall.id) { + activeToolCallIds.add(toolCall.id) + } + yield { + type: "tool_call_partial", + index: toolCall.index, + id: toolCall.id, + name: toolCall.function?.name, + arguments: toolCall.function?.arguments, + } } } - } - // Emit tool_call_end events when finish_reason is "tool_calls" - // This ensures tool calls are finalized even if the stream doesn't properly close - if (finishReason === "tool_calls" && activeToolCallIds.size > 0) { - for (const id of activeToolCallIds) { - yield { type: "tool_call_end", id } + // Emit tool_call_end events when finish_reason is "tool_calls" + // This ensures tool calls are finalized even if the stream doesn't properly close + if (finishReason === "tool_calls" && activeToolCallIds.size > 0) { + for (const id of activeToolCallIds) { + if (signal?.aborted) { + break + } + yield { type: "tool_call_end", id } + } + activeToolCallIds.clear() } - activeToolCallIds.clear() - } - if (chunk.usage) { - lastUsage = chunk.usage + if (chunk.usage) { + lastUsage = chunk.usage + } } + } catch (error) { + // Normalize here, not after the usage yield: a caller that stops before the next pull must + // still see this failure instead of an AbortError from its own later stop. + streamError = handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) + streamFailed = true + } finally { + // Every exit of the consumption block lands here: normal end, an iterator + // error, the abort-driven break, and the early return() of a caller that stops + // mid-stream - which resumes at this finally instead of running the rest of the + // generator. The bridge is released the moment the stream is over, never before. + abortBridge.dispose() } + // Usage before the verdict: a captured usage record must reach the caller ahead of an + // abort or an iterator error, or the cost of the tokens already streamed disappears + // from the task's accounting exactly when the stream stops early. if (lastUsage) { yield this.processUsageMetrics(lastUsage, this.getModel().info) } - // Process any remaining content + if (streamFailed) { + throw streamError + } + + // Post-loop abort defense: a signal that aborted while the loop was running must + // surface the Task.ts abort contract instead of letting the stream end normally + // with the matcher.final() content below. + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } + + // Process any remaining content. No cancellation re-check is needed here: the throw above + // already covers an aborted caller signal, and matcher.final() is a synchronous array, so + // no await exists between that check and this loop in which an abort could appear. for (const processedChunk of matcher.final()) { yield processedChunk } @@ -212,7 +319,9 @@ export abstract class BaseOpenAiCompatibleProvider } } - async completePrompt(prompt: string, _options?: CompletePromptOptions): Promise { + async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + throwIfAborted(options?.abortSignal) + const { id: modelId, info: modelInfo } = this.getModel() const params: OpenAI.Chat.Completions.ChatCompletionCreateParams = { @@ -225,8 +334,35 @@ export abstract class BaseOpenAiCompatibleProvider ;(params as any).thinking = { type: "enabled" } } + // CompletePromptOptions is not ApiHandlerCreateMessageMetadata (required taskId), + // so the abort/timeout merge goes through setOption; the helper treats + // timeoutMs <= 0 as "no explicit timeout". The per-request timeout is + // forwarded as well: without it the SDK falls back to the client-level + // default, which can still expire before a larger per-request timeoutMs. + const requestTimeout = getRequestTimeoutMs(options?.timeoutMs) + // Bridged rather than handed over directly: see the note in createMessage. The timeout + // still merges in beside the bridge, so a deadline stays classifiable as a timeout while + // the caller stays free of the SDK's per-request listener. + const abortBridge = bridgeExternalAbortSignal(options?.abortSignal) + const requestSignal = mergeAbortSignalAndTimeout(abortBridge.signal, options?.timeoutMs) + const requestConfig = new RequestConfigBuilder() + .setOption("signal", requestSignal) + .setOption("timeout", requestTimeout) + .build() + try { - const response = await this.client.chat.completions.create(params) + const response = await this.client.chat.completions.create(params, requestConfig) + + // A cancellation that lands while the response is in flight must not be reported as a + // completed prompt: the response is discarded and the abort contract is raised instead. + if (options?.abortSignal?.aborted) { + throw handleOpenAIRequestError( + createAbortError(this.providerName), + this.providerName, + options.abortSignal, + requestSignal, + ) + } // Check for provider-specific error responses (e.g., MiniMax base_resp) const responseAny = response as any @@ -238,7 +374,11 @@ export abstract class BaseOpenAiCompatibleProvider return response.choices?.[0]?.message.content || "" } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, options?.abortSignal, requestSignal) + } finally { + // Completion, HTTP failure and the abort-driven throw all leave the request + // through here, so the bridge is released on whichever path the request took. + abortBridge.dispose() } } diff --git a/src/api/providers/fetchers/__tests__/kimi-code.spec.ts b/src/api/providers/fetchers/__tests__/kimi-code.spec.ts index cae0f01eefb..a1c0df973cb 100644 --- a/src/api/providers/fetchers/__tests__/kimi-code.spec.ts +++ b/src/api/providers/fetchers/__tests__/kimi-code.spec.ts @@ -1,3 +1,4 @@ +import { captureError } from "../../../../test-utils/errors" import { getKimiCodeModels, kimiCodeModelSchema, mapKimiCodeModel } from "../kimi-code" describe("Kimi Code model discovery", () => { @@ -98,6 +99,59 @@ describe("Kimi Code model discovery", () => { expect(vi.getTimerCount()).toBe(0) }) + // The handler calls this fetcher from a Task-scoped request path, so the caller's + // cancellation - not just the 10s ceiling - has to own the discovery request. + it("rejects before the request when the caller signal is already aborted", async () => { + const fetchSpy = vi.spyOn(globalThis, "fetch") + await expect(getKimiCodeModels("token", { signal: AbortSignal.abort() })).rejects.toMatchObject({ + name: "AbortError", + }) + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it("aborts the in-flight models request when the caller signal aborts", async () => { + vi.spyOn(globalThis, "fetch").mockImplementation((_input, init) => { + return new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }) + }) + }) + const controller = new AbortController() + const result = getKimiCodeModels("token", { signal: controller.signal }) + const reason = new Error("caller cancelled") + controller.abort(reason) + + await expect(result).rejects.toBe(reason) + // The fetch must observe a signal that follows the caller, proving the caller signal + // was merged with the timeout bound rather than dropped. + expect(vi.mocked(fetch).mock.calls[0][1]?.signal?.aborted).toBe(true) + }) + + it("aborts the models request on the deadline while the caller signal stays live", async () => { + // The deadline must be armed alongside the caller's signal: a stalled discovery is bounded by + // the 10 s ceiling, and the caller's controller is not the thing that fired. + vi.useFakeTimers() + let fetchSignal: AbortSignal | undefined + vi.spyOn(globalThis, "fetch").mockImplementation(((_input, init) => { + fetchSignal = init?.signal as AbortSignal + return new Promise((_resolve, reject) => { + fetchSignal?.addEventListener("abort", () => reject(fetchSignal?.reason), { once: true }) + }) + }) as typeof fetch) + const controller = new AbortController() + const pending = captureError(getKimiCodeModels("token", { signal: controller.signal })) + await vi.advanceTimersByTimeAsync(0) + expect(fetchSignal?.aborted).toBe(false) + + // One millisecond before the ceiling the signal is still live, so a regression to a 1 ms deadline + // cannot pass this row. + await vi.advanceTimersByTimeAsync(9_999) + expect(fetchSignal?.aborted, "the deadline has not fired yet").toBe(false) + await vi.advanceTimersByTimeAsync(1) + await pending + expect(fetchSignal?.aborted, "the deadline reached the discovery request").toBe(true) + expect(controller.signal.aborted, "the deadline is not the caller's stop").toBe(false) + }) + it("overrides maxTokens from server max_tokens in mapKimiCodeModel", () => { const mapped = mapKimiCodeModel({ id: "kimi-for-coding", diff --git a/src/api/providers/fetchers/kimi-code.ts b/src/api/providers/fetchers/kimi-code.ts index 02bf9180f70..a266ed6b10d 100644 --- a/src/api/providers/fetchers/kimi-code.ts +++ b/src/api/providers/fetchers/kimi-code.ts @@ -1,5 +1,7 @@ import { z } from "zod" +import { mergeAbortSignals, throwIfAborted } from "../utils/abort-signal" + import { KIMI_CODE_BASE_URL, kimiCodeDefaultModelInfo, @@ -37,8 +39,10 @@ export function mapKimiCodeModel(model: z.infer): Mo } } -export async function getKimiCodeModels(apiKey?: string): Promise { +export async function getKimiCodeModels(apiKey?: string, opts?: { signal?: AbortSignal }): Promise { if (!apiKey) throw new Error("Kimi Code authentication is required to fetch models") + // A caller that already cancelled must not start a discovery request at all. + throwIfAborted(opts?.signal) const controller = new AbortController() const timeout = setTimeout( () => controller.abort(new Error("Kimi Code models request timed out")), @@ -47,7 +51,10 @@ export async function getKimiCodeModels(apiKey?: string): Promise { try { const response = await fetch(`${KIMI_CODE_BASE_URL}/models`, { headers: { Accept: "application/json", Authorization: `Bearer ${apiKey}` }, - signal: controller.signal, + // The 10s bound is a ceiling, not the cancellation contract: the caller's signal + // (a Task abort) has to stop this fetch too, otherwise discovery keeps running + // after the request that triggered it was cancelled. + signal: mergeAbortSignals(controller.signal, opts?.signal), }) if (!response.ok) { const error = new Error(`Kimi Code models request failed: ${response.status} ${response.statusText}`) diff --git a/src/api/providers/kimi-code.ts b/src/api/providers/kimi-code.ts index d8d4d55aafd..2938be77116 100644 --- a/src/api/providers/kimi-code.ts +++ b/src/api/providers/kimi-code.ts @@ -13,13 +13,14 @@ import { import type { ApiHandlerOptions, GetModelsOptions } from "../../shared/api" import { kimiCodeOAuthManager } from "../../integrations/kimi-code/oauth" -import type { ApiHandlerCreateMessageMetadata, ModelCacheScope } from "../index" +import type { ApiHandlerCreateMessageMetadata, CompletePromptOptions, ModelCacheScope } from "../index" import type { ApiStream } from "../transform/stream" import { getModelParams } from "../transform/model-params" import { OpenAiHandler } from "./openai" import { NOT_PROVIDED } from "./constants" import { getModels } from "./fetchers/modelCache" +import { isRequestAborted, throwIfAborted } from "./utils/abort-signal" import { getKimiCodeModels } from "./fetchers/kimi-code" const OAUTH_AUTH_METHOD: KimiCodeAuthMethod = "oauth" @@ -59,31 +60,47 @@ export class KimiCodeHandler extends OpenAiHandler { return { urlScoped: false, keyScoped: true, authScoped: true } } - async fetchModels(options: GetModelsOptions): Promise { - return getKimiCodeModels(options.apiKey) + async fetchModels(options: GetModelsOptions, signal?: AbortSignal): Promise { + // Forward cancellation (explicit model-cache signal, else the caller + // signal carried on options) so a cancellation during discovery aborts + // the in-flight discovery HTTP request, not just the caller's wait. + const cancellation = signal ?? options.signal + return cancellation + ? getKimiCodeModels(options.apiKey, { signal: cancellation }) + : getKimiCodeModels(options.apiKey) } - private async resolveAccessToken(forceRefresh = false): Promise { + private async resolveAccessToken(forceRefresh = false, signal?: AbortSignal): Promise { if ((this.kimiOptions.kimiCodeAuthMethod ?? OAUTH_AUTH_METHOD) === API_KEY_AUTH_METHOD) { if (!this.kimiOptions.kimiCodeApiKey) throw new Error("Kimi Code API key is required") return this.kimiOptions.kimiCodeApiKey } const token = forceRefresh - ? await kimiCodeOAuthManager.forceRefreshAccessToken() - : await kimiCodeOAuthManager.getAccessToken() + ? await kimiCodeOAuthManager.forceRefreshAccessToken(signal) + : await kimiCodeOAuthManager.getAccessToken(false, signal) if (!token) throw new Error("Not authenticated with Kimi Code. Sign in from provider settings.") return token } - private async prepareRequest(forceRefresh = false): Promise { - const accessToken = await this.resolveAccessToken(forceRefresh) + private async prepareRequest(forceRefresh = false, abortSignal?: AbortSignal): Promise { + const accessToken = await this.resolveAccessToken(forceRefresh, abortSignal) this.client.apiKey = accessToken if (!this.modelDiscoveryAttempted) { this.modelDiscoveryAttempted = true try { - this.models = await getModels({ provider: providerIdentifiers.kimiCode, apiKey: accessToken }, this) + this.models = await getModels( + { provider: providerIdentifiers.kimiCode, apiKey: accessToken, signal: abortSignal }, + this, + ) } catch (error) { + // A caller cancellation must not consume the single discovery attempt: + // reset the flag so a later request on this handler retries discovery + // instead of keeping fallback metadata. Ordinary discovery failures + // keep the one-attempt behavior. + if (isRequestAborted(error, abortSignal)) { + this.modelDiscoveryAttempted = false + } // Model discovery is best-effort; preserve the configured ID and fallback metadata. console.debug("[KimiCode] Model discovery failed; using fallback model metadata", { message: error instanceof Error ? error.message : String(error), @@ -101,24 +118,35 @@ export class KimiCodeHandler extends OpenAiHandler { messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { - await this.prepareRequest() + throwIfAborted(metadata?.abortSignal) + await this.prepareRequest(false, metadata?.abortSignal) + // Preparation awaits model discovery; a cancellation that lands during it must + // stop here rather than issue the completion request. + throwIfAborted(metadata?.abortSignal) try { yield* super.createMessage(systemPrompt, messages, metadata) } catch (error) { if (getHttpStatus(error) !== 401 || !this.canRefreshOAuth()) throw error - await this.prepareRequest(true) + // Never start an OAuth refresh + retry for a caller that has already cancelled. + throwIfAborted(metadata?.abortSignal) + await this.prepareRequest(true, metadata?.abortSignal) yield* super.createMessage(systemPrompt, messages, metadata) } } - override async completePrompt(prompt: string): Promise { - await this.prepareRequest() + override async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + throwIfAborted(options?.abortSignal) + await this.prepareRequest(false, options?.abortSignal) + throwIfAborted(options?.abortSignal) try { - return await super.completePrompt(prompt) + // Forward abort/timeout options so the inherited OpenAiHandler wiring + // applies (the createMessage override inherits the same via metadata). + return await super.completePrompt(prompt, options) } catch (error) { if (getHttpStatus(error) !== 401 || !this.canRefreshOAuth()) throw error - await this.prepareRequest(true) - return super.completePrompt(prompt) + throwIfAborted(options?.abortSignal) + await this.prepareRequest(true, options?.abortSignal) + return super.completePrompt(prompt, options) } } diff --git a/src/api/providers/openai.ts b/src/api/providers/openai.ts index f54a8853696..6e6a3626f8d 100644 --- a/src/api/providers/openai.ts +++ b/src/api/providers/openai.ts @@ -39,7 +39,7 @@ import { getModelParams } from "../transform/model-params" import { DEFAULT_HEADERS, NOT_PROVIDED } from "./constants" import { BaseProvider } from "./base-provider" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" -import { handleOpenAIError } from "./utils/error-handler" +import { handleOpenAIError, handleOpenAIRequestError } from "./utils/error-handler" import { applyThoughtSignatures, thoughtSignatureOrigin, ThoughtSignatureReader } from "./utils/thought-signature" import { extractReasoningFromDelta } from "./utils/extract-reasoning" import { @@ -48,7 +48,21 @@ import { isRequestAborted, hasUsableTimeout, toSdkTimeoutMs, + mergeAbortSignalAndTimeout, + throwIfAborted, + rejectOnAbort, + isTimeoutAbort, } from "./utils/abort-signal" +import { RequestConfigBuilder } from "./config-builder/request-config-builder" +import { getRequestTimeoutMs } from "./utils/request-timeout" + +/** Subset of OpenAI.RequestOptions built per request for the abort-signal wiring. */ +type OpenAiRequestConfig = { + path?: string + signal?: AbortSignal + /** Per-request SDK timeout; a positive timeoutMs overrides the client default. */ + timeout?: number +} function isAzureV1BaseUrl(baseUrl?: string): boolean { try { @@ -162,15 +176,24 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl // `reasoning_effort` combined with function tools on /chat/completions and // require /responses instead. if (this.options.openAiUseResponsesApi) { + // The Responses route hands the caller's signal to the SDK at request construction, + // where it is bridged, so the SDK rejects it there. Throwing before the handoff would + // skip the request entirely and drop the signal the caller passed. yield* this.handleResponsesApiMessage(systemPrompt, messages, metadata) return } + const signal = metadata?.abortSignal + + // The routes below attach the caller's signal to the request they issue themselves, so a + // signal that is already aborted fails before any of that work happens. The Responses route + // above hands its own bridged signal to the SDK, and is guarded there rather than here. + throwIfAborted(signal) + const { info: modelInfo, reasoning } = this.getModel() const modelUrl = this.options.openAiBaseUrl ?? "" // Stryker disable next-line LogicalOperator: equivalent. An unset option makes `&&` // yield undefined, which the parameter default in convertToolsForOpenAI turns back into - // the same strict value as `??`. const strictToolSchemas = this.options.openAiStrictToolSchemas ?? DEFAULT_OPEN_AI_STRICT_TOOL_SCHEMAS const isAzureAiInference = this._isAzureAiInference(modelUrl) const deepseekReasoner = this.usesR1Format(modelId) @@ -264,12 +287,12 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let stream try { - stream = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(isAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + stream = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(isAzureAiInference, metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } const matcher = new TagMatcher( @@ -284,36 +307,78 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let lastUsage const activeToolCallIds = new Set() - for await (const chunk of stream) { - const delta = chunk.choices?.[0]?.delta ?? {} - const finishReason = chunk.choices?.[0]?.finish_reason - signatureReader.update(delta.tool_calls) + // An iterator error is normalized only after the usage record below has been handed to + // the caller. The failure is tracked beside its value because a rejection can carry + // `undefined`, and that rejection must still reach the handler instead of completing + // the stream after partial output. + let streamError: unknown = undefined + let streamFailed = false - const reasoningText = extractReasoningFromDelta(delta) - if (reasoningText) { - yield { type: "reasoning", text: reasoningText } - } + try { + for await (const chunk of stream) { + // A frame the SDK already returned still carries its usage. Record it before the + // abort check below, or the tokens buffered behind the last text yield are lost. + if (chunk.usage) { + lastUsage = chunk.usage + } + // Streaming-loop abort defense: the for-await above already pulled this + // chunk; the top-of-loop break stops *processing* (and yielding) buffered + // content that arrived after the caller's signal aborted. + if (signal?.aborted) { + break + } + const delta = chunk.choices?.[0]?.delta ?? {} + const finishReason = chunk.choices?.[0]?.finish_reason + signatureReader.update(delta.tool_calls) - if (delta.content) { - for (const chunk of matcher.update(delta.content)) { - yield chunk + const reasoningText = extractReasoningFromDelta(delta) + if (reasoningText) { + yield { type: "reasoning", text: reasoningText } } - } - yield* this.processToolCalls(delta, finishReason, activeToolCallIds) + if (delta.content) { + for (const chunk of matcher.update(delta.content)) { + // Same-chunk abort defense: the reasoning yield above may already have been + // the last event the caller wanted, so the signal is re-read between the yields a + // single chunk produces instead of only between chunks. + if (signal?.aborted) { + break + } - if (chunk.usage) { - lastUsage = chunk.usage - } - } + yield chunk + } + } - for (const chunk of matcher.final()) { - yield chunk + yield* this.processToolCalls(delta, finishReason, activeToolCallIds, signal) + } + } catch (error) { + // Normalize here, not after the usage yield: a caller that stops before the next pull + // must still see this failure instead of an AbortError from its own later stop. + streamError = handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) + streamFailed = true } + // Usage before the verdict: a stream that recorded usage and then observed the cancellation + // still has to hand that usage record to the caller, or the cost of the tokens it already + // streamed disappears from the task's accounting exactly when the stream stops early. if (lastUsage) { yield this.processUsageMetrics(lastUsage, modelInfo) } + + if (streamFailed) { + throw streamError + } + + // Post-loop abort defense: a signal that aborted while the loop was running must + // surface the Task.ts abort contract instead of letting the stream end normally + // with the buffered matcher content below. + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } + + for (const chunk of matcher.final()) { + yield chunk + } } else { let requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = { model: modelId, @@ -336,20 +401,27 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let response try { - response = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(this._isAzureAiInference(modelUrl) ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + response = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(this._isAzureAiInference(modelUrl), metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } + // A cancellation that lands while the response is in flight must not be reported as + // completed work: the arrived text and tool calls are discarded and the abort contract + // is raised instead, so Task.ts never sees content the caller already cancelled. + this.throwIfRequestAborted(signal) + const message = response.choices?.[0]?.message signatureReader.update(message?.tool_calls) if (message?.tool_calls) { for (const toolCall of message.tool_calls) { if (toolCall.type === "function") { + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "tool_call", id: toolCall.id, @@ -360,11 +432,15 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "text", text: message?.content || "", } + // A cancellation after the last content chunk must not be reported as usage metrics. + this.throwIfRequestAborted(signal) yield this.processUsageMetrics(response.usage, modelInfo) } } @@ -525,6 +601,8 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + throwIfAborted(options?.abortSignal) + try { if (this.options.openAiUseResponsesApi) { const model = this.getModel() @@ -538,13 +616,35 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl extraBody: this.extraBody, reasoningScope: responsesReasoningScope(this.client.baseURL), }) - const response = await this.client.responses.create( - { ...body, stream: false }, - { - ...(options?.abortSignal ? { signal: options.abortSignal } : {}), - ...(hasUsableTimeout(options?.timeoutMs) ? { timeout: toSdkTimeoutMs(options.timeoutMs) } : {}), - }, - ) + // The SDK clears its own fetch timer once the headers arrive and then reads the body, so the + // deadline only stays armed if it is forwarded as this request's signal. + // Bridged onto a request-local controller for the reason the chat branch below states: the + // SDK keeps one abort listener per attempt, so the caller's own signal would retain a + // controller for every completed prompt. + const callerBridge = bridgeExternalAbortSignal(options?.abortSignal) + const requestSignal = mergeAbortSignalAndTimeout(callerBridge.signal, options?.timeoutMs) + let response + try { + response = await this.client.responses.create( + { ...body, stream: false }, + { + ...(requestSignal ? { signal: requestSignal } : {}), + ...(hasUsableTimeout(options?.timeoutMs) + ? { timeout: toSdkTimeoutMs(options.timeoutMs) } + : {}), + }, + ) + } catch (error) { + // Only an abort or a deadline is normalized here. A native abort raised while the + // Responses body is read reaches the caller as the provider's contract error, as the + // Chat Completions branch below does; any other failure is wrapped once, by the outer catch. + if (isRequestAborted(error, options?.abortSignal) || isTimeoutAbort(requestSignal)) { + throw handleOpenAIRequestError(error, this.providerName, options?.abortSignal, requestSignal) + } + throw error + } finally { + callerBridge.dispose() + } assertResponsesApiSuccess(response) return response.output .flatMap((item) => @@ -571,19 +671,60 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl requestOptions = this.withExtraBody(requestOptions) let response + // Bridged onto a request-local controller: the SDK attaches one abort listener per attempt + // and does not detach it when the call settles, so handing it the caller's own signal would + // retain a controller for every completed prompt on a signal that outlives this request. The + // bridge is disposed in the finally below, which runs on completion, on failure and when the + // abort race settles the call first. + const callerBridge = bridgeExternalAbortSignal(options?.abortSignal) + const requestConfig = this.buildCompletePromptRequestConfig( + isAzureAiInference, + options, + callerBridge.signal, + ) try { - response = await this.client.chat.completions.create( - requestOptions, - isAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}, - ) + const create = this.client.chat.completions.create(requestOptions, requestConfig) + // The SDK sleeps between retries and does not observe the merged signal: race the call so + // a deadline still settles the prompt while a 429 backoff is pending. + const requestSignal = requestConfig.signal as AbortSignal | undefined + response = requestSignal ? await rejectOnAbort(create, requestSignal, this.providerName) : await create } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError( + error, + this.providerName, + options?.abortSignal, + requestConfig.signal ?? undefined, + ) + } finally { + callerBridge.dispose() + } + + // A cancellation that lands while the response is in flight must not be reported as a + // completed prompt: the answer is discarded and the abort contract is raised instead. + if (options?.abortSignal?.aborted) { + throw handleOpenAIRequestError( + createAbortError(this.providerName), + this.providerName, + options.abortSignal, + requestConfig.signal ?? undefined, + ) } return response.choices?.[0]?.message.content || "" } catch (error) { if (error instanceof OutputTokenLimitError) throw error - if (isRequestAborted(error, options?.abortSignal)) throw createAbortError(this.providerName) + if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) { + // The request-site handler already turned this into the contract error and chained + // the underlying failure as its cause. Re-wrapping it here would drop that cause, so + // name, message and cause are preserved exactly as they arrive. + throw error + } + // A raw SDK abort (name APIUserAbortError) or a signal that aborted mid-flight still + // needs the contract error, with the failure that triggered it kept as the cause. + if (isRequestAborted(error, options?.abortSignal)) { + throw createAbortError(this.providerName, error) + } + if (error instanceof Error) { const wrapped = new Error(`${this.providerName} completion error: ${error.message}`, { cause: error }) const source = error as Error & { status?: number; errorDetails?: unknown; code?: unknown } @@ -598,6 +739,45 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } + /** + * Builds the per-request OpenAI SDK options for a chat completions create + * (createMessage paths): the Azure AI Inference path when applicable, plus + * the caller's abort signal, via RequestConfigBuilder adoption. + */ + private buildChatRequestConfig( + isAzureAiInference: boolean, + metadata?: ApiHandlerCreateMessageMetadata, + ): OpenAI.RequestOptions { + return ( + new RequestConfigBuilder() + .setOption("path", isAzureAiInference ? OPENAI_AZURE_AI_INFERENCE_PATH : undefined) + .setAbortSignal(metadata) + .build() ?? {} + ) + } + + /** + * Builds the per-request options for completePrompt. CompletePromptOptions + * is not ApiHandlerCreateMessageMetadata (required taskId), so the merged + * abort/timeout signal and the per-request SDK timeout (a positive timeoutMs + * overrides the client-level default) go through setOption instead of + * setAbortSignal. + */ + private buildCompletePromptRequestConfig( + isAzureAiInference: boolean, + options?: CompletePromptOptions, + callerSignal?: AbortSignal, + ): OpenAI.RequestOptions { + const requestTimeout = getRequestTimeoutMs(options?.timeoutMs) + return ( + new RequestConfigBuilder() + .setOption("path", isAzureAiInference ? OPENAI_AZURE_AI_INFERENCE_PATH : undefined) + .setOption("signal", mergeAbortSignalAndTimeout(callerSignal, options?.timeoutMs)) + .setOption("timeout", requestTimeout) + .build() ?? {} + ) + } + private async *handleO3FamilyMessage( modelId: string, systemPrompt: string, @@ -606,10 +786,9 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl ): ApiStream { const { info: modelInfo, reasoning } = this.getModel() const methodIsAzureAiInference = this._isAzureAiInference(this.options.openAiBaseUrl) - // Stryker disable next-line LogicalOperator: equivalent. An unset option makes `&&` // yield undefined, which the parameter default in convertToolsForOpenAI turns back into - // the same strict value as `??`. const strictToolSchemas = this.options.openAiStrictToolSchemas ?? DEFAULT_OPEN_AI_STRICT_TOOL_SCHEMAS + const signal = metadata?.abortSignal if (this.options.openAiStreamingEnabled ?? true) { const isGrokXAI = this._isGrokXAI(this.options.openAiBaseUrl) @@ -641,15 +820,28 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let stream try { - stream = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(methodIsAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + stream = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(methodIsAzureAiInference, metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } - yield* this.handleStreamResponse(stream) + try { + yield* this.handleStreamResponse(stream, signal) + } catch (error) { + // The creation-site catch does not cover errors raised by the async + // iterator itself (e.g. a mid-stream abort); normalize them the same way. + throw handleOpenAIRequestError(error, this.providerName, signal) + } + + // Post-loop abort defense: a signal that aborted while the loop was running + // must surface the Task.ts abort contract instead of letting the stream end + // normally with the buffered content it may have pulled. + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } } else { let requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = { model: modelId, @@ -676,18 +868,25 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl let response try { - response = await this.client.chat.completions.create(requestOptions, { - signal: metadata?.abortSignal, - ...(methodIsAzureAiInference ? { path: OPENAI_AZURE_AI_INFERENCE_PATH } : {}), - }) + response = await this.client.chat.completions.create( + requestOptions, + this.buildChatRequestConfig(methodIsAzureAiInference, metadata), + ) } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, metadata?.abortSignal) } + // A cancellation that lands while the response is in flight must not be reported as + // completed work: the arrived text and tool calls are discarded and the abort contract + // is raised instead, so Task.ts never sees content the caller already cancelled. + this.throwIfRequestAborted(signal) + const message = response.choices?.[0]?.message if (message?.tool_calls) { for (const toolCall of message.tool_calls) { if (toolCall.type === "function") { + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "tool_call", id: toolCall.id, @@ -698,18 +897,49 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } + // A yield suspends this generator: the caller can cancel before the next piece of content. + this.throwIfRequestAborted(signal) yield { type: "text", text: message?.content || "", } + // A cancellation after the last content chunk must not be reported as usage metrics. + this.throwIfRequestAborted(signal) yield this.processUsageMetrics(response.usage) } } - private async *handleStreamResponse(stream: AsyncIterable): ApiStream { + /** + * Raise the normalized abort contract for this provider when the caller has cancelled. + * + * A `yield` suspends this generator, so the caller can cancel between yields. Each piece of + * content a non-streaming response hands over is therefore re-checked before it is yielded, not + * only the first piece after the response arrives. + */ + private throwIfRequestAborted(signal?: AbortSignal): void { + if (signal?.aborted) { + throw handleOpenAIRequestError(createAbortError(this.providerName), this.providerName, signal) + } + } + + private async *handleStreamResponse( + stream: AsyncIterable, + signal?: AbortSignal, + ): ApiStream { const activeToolCallIds = new Set() for await (const chunk of stream) { + // A usage-only frame the SDK already returned must reach the caller even when the abort + // landed in between: the break below stops content, not the token counts. + if (chunk.usage) { + yield this.processUsageMetrics(chunk.usage) + } + // Streaming-loop abort defense: the for-await above already pulled this + // chunk; the top-of-loop break stops *processing* (and yielding) buffered + // content that arrived after the caller's signal aborted. + if (signal?.aborted) { + break + } const delta = chunk.choices?.[0]?.delta const finishReason = chunk.choices?.[0]?.finish_reason @@ -721,11 +951,7 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } } - yield* this.processToolCalls(delta, finishReason, activeToolCallIds) - } - - if (chunk.usage) { - yield this.processUsageMetrics(chunk.usage) + yield* this.processToolCalls(delta, finishReason, activeToolCallIds, signal) } } } @@ -736,11 +962,14 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl * @param delta - The delta object from the stream chunk * @param finishReason - The finish_reason from the stream chunk * @param activeToolCallIds - Set to track active tool call IDs (mutated in place) + * @param signal - Caller abort signal, re-read before each yield so a cancelled caller stops + * receiving tool-call events instead of draining the ones that already arrived */ protected *processToolCalls( delta: OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta | undefined, finishReason: string | null | undefined, activeToolCallIds: Set, + signal?: AbortSignal, ): Generator< | { type: "tool_call_partial"; index: number; id?: string; name?: string; arguments?: string } | { type: "tool_call_end"; id: string } @@ -750,6 +979,11 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl if (toolCall.id) { activeToolCallIds.add(toolCall.id) } + // A cancelled caller must not receive tool-call partials that arrived after the + // cancellation; the guard is read before the yield, not after it. + if (signal?.aborted) { + break + } yield { type: "tool_call_partial", index: toolCall.index, @@ -764,6 +998,9 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl // This ensures tool calls are finalized even if the stream doesn't properly close if (finishReason === "tool_calls" && activeToolCallIds.size > 0) { for (const id of activeToolCallIds) { + if (signal?.aborted) { + break + } yield { type: "tool_call_end", id } } activeToolCallIds.clear() diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550a..cc3838c2afc 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -540,6 +540,25 @@ describe("abort-signal utilities", () => { expect((caught as Error).name).toBe("AbortError") expect((caught as Error).message).toBe("This operation was aborted") }) + + it("attaches the signal's own reason as the cause", () => { + // The name and message are the caller-facing half of the contract; the cause is the + // diagnostic half, so a guard rejection can still say which failure the stop caused. + const controller = new AbortController() + const reason = new Error("caller gave up before the request") + controller.abort(reason) + + let caught: unknown + try { + throwIfAborted(controller.signal) + } catch (error) { + caught = error + } + + expect((caught as Error).name).toBe("AbortError") + expect((caught as Error).message).toBe("This operation was aborted") + expect((caught as Error).cause).toBe(reason) + }) }) describe("isRequestAborted", () => { @@ -600,6 +619,25 @@ describe("abort-signal utilities", () => { expect(createAbortError("Qwen Code").message).toBe("The Qwen Code request was aborted") }) + it("keeps the supplied cause under the contract name and message", () => { + const cause = new Error("socket reset by peer") + const error = createAbortError("OpenAI", cause) + + expect(error.name).toBe("AbortError") + expect(error.message).toBe("The OpenAI request was aborted") + expect(error.cause).toBe(cause) + }) + + it("leaves the cause unset when the caller supplies none", () => { + const error = createAbortError("OpenAI") + + expect(error.name).toBe("AbortError") + expect(error.message).toBe("The OpenAI request was aborted") + // A bare new Error(message, { cause: undefined }) defines the property, so the absence is + // asserted rather than compared with undefined. + expect("cause" in error).toBe(false) + }) + it("returns a fresh error on each call", () => { expect(createAbortError("X")).not.toBe(createAbortError("X")) }) diff --git a/src/api/providers/utils/__tests__/error-handler.spec.ts b/src/api/providers/utils/__tests__/error-handler.spec.ts index 3e6bfc9271a..436f05d86a6 100644 --- a/src/api/providers/utils/__tests__/error-handler.spec.ts +++ b/src/api/providers/utils/__tests__/error-handler.spec.ts @@ -1,4 +1,13 @@ -import { getNumericHttpStatus, handleOpenAIError, handleProviderError, hasNumericHttpStatus } from "../error-handler" +import { APIUserAbortError } from "openai" + +import { + getNumericHttpStatus, + handleOpenAIError, + handleOpenAIRequestError, + handleProviderError, + hasNumericHttpStatus, +} from "../error-handler" +import { isTimeoutAbort, mergeAbortSignals } from "../abort-signal" describe("handleProviderError", () => { const providerName = "TestProvider" @@ -424,3 +433,115 @@ describe("getNumericHttpStatus", () => { expect(getNumericHttpStatus(Object.assign(() => undefined, { statusCode: 429 }))).toBeUndefined() }) }) + +describe("handleOpenAIRequestError (abort awareness)", () => { + it("normalizes a generic error to a fresh AbortError when the caller signal aborted", () => { + const controller = new AbortController() + controller.abort() + const original = new Error("network failure") + + const result = handleOpenAIRequestError(original, "OpenAI", controller.signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect((result as Error & { cause?: unknown }).cause).toBe(original) + }) + + it("normalizes the SDK user-abort error when no signal was passed", () => { + const result = handleOpenAIRequestError(new APIUserAbortError(), "Zai") + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Zai request was aborted") + }) + + it("keeps a timeout-triggered SDK abort classified as a timeout when the caller did not abort", () => { + const original = new APIUserAbortError() + const requestSignal = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + + const result = handleOpenAIRequestError(original, "OpenAI", undefined, requestSignal) + + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The OpenAI completion request timed out") + expect((result as Error & { cause?: unknown }).cause).toBe(original) + }) + + it("keeps the abort contract when the request signal has not aborted", () => { + // The guard must not assume a reason exists: an SDK abort can arrive while the + // merged request signal is still live, and reading .name on an undefined reason + // would turn a cancellation into a TypeError. + const result = handleOpenAIRequestError( + new APIUserAbortError(), + "OpenAI", + undefined, + new AbortController().signal, + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + it("keeps a caller cancellation classified as an abort even when the request signal timed out", () => { + const controller = new AbortController() + controller.abort() + const requestSignal = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + + const result = handleOpenAIRequestError(new APIUserAbortError(), "OpenAI", controller.signal, requestSignal) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + it("keeps the abort contract for a caller that stops after a real merged signal timed out", () => { + // The row above approximates this interleaving with a signal it builds by hand. This one merges the + // way the providers merge: mergeAbortSignals is AbortSignal.any([caller, timeout]) (abort-signal.ts:67), + // reached from mergeAbortSignalAndTimeout (abort-signal.ts:52) and from + // config-builder/request-config-builder.ts:94 - the composition that produces the requestSignal handed + // to the guard at base-openai-compatible-provider.ts:344 and openai.ts:617. The timeout signal is + // already aborted when the merge is built, so "the deadline fired first" is a property of the fixture + // and not a race; the caller then stops its own controller, and the aggregate keeps the TimeoutError + // reason. Only the !abortSignal?.aborted term at error-handler.ts:186 can route this call to the abort + // contract, so this row is what pins "the caller's stop wins" for a genuine merged signal. + const caller = new AbortController() + const timedOut = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + const requestSignal = mergeAbortSignals(caller.signal, timedOut) + caller.abort() + + // These three assertions are the premise the classification rests on. A merged signal that stopped + // carrying a TimeoutError reason would make isTimeoutAbort false, and the fall-through at + // error-handler.ts:196-201 would then answer AbortError for the wrong reason - this row would stay + // green while the guard meant nothing. + expect(requestSignal.aborted, "the merge is already aborted by the timeout").toBe(true) + expect((requestSignal.reason as { name?: string } | undefined)?.name).toBe("TimeoutError") + expect(isTimeoutAbort(requestSignal), "the predicate the guard consults").toBe(true) + + const result = handleOpenAIRequestError(new APIUserAbortError(), "OpenAI", caller.signal, requestSignal) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("normalizes a native fetch-level AbortError when no signal was passed", () => { + const result = handleOpenAIRequestError( + Object.assign(new Error("aborted"), { name: "AbortError" }), + "Fireworks", + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Fireworks request was aborted") + }) + + it("keeps the provider-prefix wrap for a non-abort failure", () => { + const original = new Error("rate limited") + + const result = handleOpenAIRequestError(original, "OpenAI", new AbortController().signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("Error") + expect(result.message).toBe("OpenAI completion error: rate limited") + }) + + it("falls back to the provider-prefix wrap when no signal is available", () => { + const result = handleOpenAIRequestError(new Error("boom"), "Kimi Code") + + expect(result.message).toBe("Kimi Code completion error: boom") + }) +}) diff --git a/src/api/providers/utils/__tests__/request-timeout.spec.ts b/src/api/providers/utils/__tests__/request-timeout.spec.ts index 8190faebe36..c9763e759d2 100644 --- a/src/api/providers/utils/__tests__/request-timeout.spec.ts +++ b/src/api/providers/utils/__tests__/request-timeout.spec.ts @@ -1,3 +1,4 @@ +import { MAX_TIMEOUT_MS } from "../abort-signal" import { createTimeoutError, getRequestTimeoutMs } from "../request-timeout" describe("getRequestTimeoutMs", () => { @@ -35,6 +36,16 @@ describe("getRequestTimeoutMs", () => { // (e.g. user settings); the double cast exercises the typeof guard. expect(getRequestTimeoutMs("5000" as unknown as number)).toBeUndefined() }) + + it("caps timeouts past the maximum timer delay instead of letting Node clamp them", () => { + // A delay above 2^31-1 ms is not a legal timer value: Node clamps it to ~1 ms, so an + // oversized setting would abort the request almost immediately rather than wait. The + // cap belongs here because this value also goes to the SDK's own timeout option. + expect(getRequestTimeoutMs(MAX_TIMEOUT_MS)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(MAX_TIMEOUT_MS + 1)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(2 ** 32)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(Number.MAX_SAFE_INTEGER)).toBe(MAX_TIMEOUT_MS) + }) }) describe("createTimeoutError", () => { diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 6abbc124371..4bd754e1660 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -112,13 +112,16 @@ export function bridgeExternalAbortSignal(externalSignal?: AbortSignal): { * Use as a fast-fail guard at the top of request-building code paths so * callers receive a consistent `name === "AbortError"` when the operation * was cancelled before it started, without building or issuing the request. + * The signal's own reason rides along as `cause`: a guard rejection that only + * says "aborted" cannot tell a caller stop down from an internal deadline, and + * the name and message stay byte-identical for the Task.ts abort contract. */ export function throwIfAborted(signal?: AbortSignal): void { if (!signal?.aborted) { return } - const abortError = new Error("This operation was aborted") + const abortError = new Error("This operation was aborted", { cause: signal.reason }) abortError.name = "AbortError" throw abortError } @@ -159,8 +162,8 @@ export function isRequestAborted(error: unknown, signal?: AbortSignal): boolean * message "Request was aborted."), so raw SDK abort errors must be * normalized instead of rethrown. */ -export function createAbortError(providerName: string): Error { - const abortError = new Error(`The ${providerName} request was aborted`) +export function createAbortError(providerName: string, cause?: unknown): Error { + const abortError = new Error(`The ${providerName} request was aborted`, cause === undefined ? undefined : { cause }) abortError.name = "AbortError" return abortError } @@ -312,9 +315,10 @@ export function createTimeoutError(providerName: string): Error { * caller's stop signal. */ export function isTimeoutAbort(requestSignal: AbortSignal | undefined): boolean { - // Classify by the merged signal's retained abort reason: if its own timeout fired first, the - // reason stays the TimeoutError even when the caller aborts later, so the failure must still be - // reported as a deadline. A caller-first abort retains the caller's reason instead. + // Classify by the merged signal's retained abort reason: a deadline that fired first keeps the + // TimeoutError reason even if the caller stops later, so this answers only which signal fired + // first. handleOpenAIRequestError answers a caller that also pressed stop with the abort + // contract - error-handler.spec.ts:483-492 pins that answer for the interleaving. return Boolean( requestSignal?.aborted && (requestSignal.reason as { name?: string } | undefined)?.name === "TimeoutError", ) diff --git a/src/api/providers/utils/error-handler.ts b/src/api/providers/utils/error-handler.ts index 2247ed182c4..96ce8e1fbd8 100644 --- a/src/api/providers/utils/error-handler.ts +++ b/src/api/providers/utils/error-handler.ts @@ -9,7 +9,11 @@ * - Enables telemetry and debugging with complete error context */ +import { APIUserAbortError } from "openai" + import i18n from "../../../i18n/setup" +import { createAbortError, isTimeoutAbort } from "./abort-signal" +import { createTimeoutError } from "./request-timeout" /** * Handles API provider errors and transforms them into user-friendly messages @@ -163,3 +167,43 @@ export function handleProviderError( export function handleOpenAIError(error: unknown, providerName: string): Error { return handleProviderError(error, providerName, { messagePrefix: "completion" }) } + +/** + * Handles errors from OpenAI Node SDK request sites with abort awareness. + * + * An abort failure (the external signal already aborted, the SDK's + * APIUserAbortError, or a fetch-level AbortError) is normalized to a fresh + * Error with name "AbortError" and a message ending in "aborted" (the Task.ts + * contract) instead of being wrapped as a regular completion error, which a + * plain rethrow of the SDK abort error would produce. + */ +export function handleOpenAIRequestError( + error: unknown, + providerName: string, + abortSignal?: AbortSignal, + requestSignal?: AbortSignal, +): Error { + // A terminal HTTP failure keeps its own identity even when the caller stops in the same tick: + // backoff reads the top-level status, so masking a 401/429 as AbortError hides the provider error. + if (hasNumericHttpStatus(error)) return handleOpenAIError(error, providerName) + + // The deadline, not the caller's stop, ended this request. Classified before the abort branch so a + // native AbortError raised by the SDK's JSON body read is reported as a timeout as well. + if (!abortSignal?.aborted && isTimeoutAbort(requestSignal)) { + // The abort came from this merged signal's own deadline, not the caller's stop: a timeout + // must stay distinguishable from a user cancellation, so the shared helper's name and + // message are used and the SDK abort is attached as the cause. A caller that pressed stop + // never reaches here - error-handler.spec.ts:483-492 pins the abort for that interleaving. + const timeoutError = createTimeoutError(providerName, "completion request") + timeoutError.cause = error + return timeoutError + } + + if ( + abortSignal?.aborted || + (error instanceof Error && (error.name === "AbortError" || error instanceof APIUserAbortError)) + ) { + return createAbortError(providerName, error) + } + return handleOpenAIError(error, providerName) +} diff --git a/src/api/providers/utils/request-timeout.ts b/src/api/providers/utils/request-timeout.ts index 672922415a5..89067ac80fd 100644 --- a/src/api/providers/utils/request-timeout.ts +++ b/src/api/providers/utils/request-timeout.ts @@ -1,17 +1,19 @@ +import { hasUsableTimeout, toSdkTimeoutMs } from "./abort-signal" + /** * 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 * (or undefined) mean 'no per-request timeout': the option is omitted * entirely, because some SDKs (e.g. the OpenAI Node SDK) treat timeout: 0 as - * an IMMEDIATE timeout. Finite values are rounded up to whole milliseconds: - * downstream AbortSignal.timeout() validates its delay as uint32 and throws - * for fractions. + * an IMMEDIATE timeout. Values that do survive validation are handed to + * toSdkTimeoutMs, which rounds fractions up (AbortSignal.timeout validates its + * delay as uint32 and throws for fractions) and caps them at the maximum timer + * delay: a Node timer clamps anything past 2^31-1 ms to ~1 ms, which would + * abort the request almost immediately instead of honouring the timeout. */ export function getRequestTimeoutMs(timeoutMs?: number): number | undefined { - return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 - ? Math.ceil(timeoutMs) - : undefined + return hasUsableTimeout(timeoutMs) ? toSdkTimeoutMs(timeoutMs) : undefined } /** diff --git a/src/api/providers/zai.ts b/src/api/providers/zai.ts index c5b7f436194..5dedc64689d 100644 --- a/src/api/providers/zai.ts +++ b/src/api/providers/zai.ts @@ -16,7 +16,16 @@ import { convertToZAiFormat } from "../transform/zai-format" import type { ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" import { BaseOpenAiCompatibleProvider } from "./base-openai-compatible-provider" import { NOT_PROVIDED } from "./constants" -import { handleOpenAIError } from "./utils/error-handler" +import { handleOpenAIRequestError } from "./utils/error-handler" +import { RequestConfigBuilder } from "./config-builder/request-config-builder" +import { + bridgeExternalAbortSignal, + createAbortError, + mergeAbortSignalAndTimeout, + rejectOnAbort, + throwIfAborted, +} from "./utils/abort-signal" +import { getRequestTimeoutMs } from "./utils/request-timeout" // Custom interface for Z.ai params to support thinking mode and reasoning effort tiers. // Z.ai accepts the standard `reasoning_effort` ladder (none/minimal/low/medium/high/xhigh/max) @@ -27,6 +36,13 @@ type ZAiChatCompletionParams = Omit { const isThinkingModel = Array.isArray(info.supportsReasoningEffort) if (isThinkingModel) { - // Create the stream with our custom thinking parameter - return this.createStreamWithThinking(systemPrompt, messages, metadata) + // Create the stream with our custom thinking parameter. + // Forward the per-request options (abort signal) so the thinking path + // keeps them instead of dropping requestOptions. + return this.createStreamWithThinking(systemPrompt, messages, metadata, requestOptions) } // For non-thinking models, use the default behavior @@ -81,10 +99,11 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { /** * Creates a stream with explicit thinking control for GLM thinking-capable models. */ - private createStreamWithThinking( + private async createStreamWithThinking( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, + requestOptions?: OpenAI.RequestOptions, ) { const { id: model, info } = this.getModel() const { reasoningEffort, useReasoning } = this.getReasoningSettings(info) @@ -121,13 +140,13 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { parallel_tool_calls: metadata?.parallelToolCalls ?? true, } - try { - return this.client.chat.completions.create( - params as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming, - ) - } catch (error) { - throw handleOpenAIError(error, this.providerName) - } + // Creation errors are normalized once by the base createMessage; wrapping them here + // too doubled the prefix ("Z.ai completion error: Z.ai completion error: ...") and + // logged every thinking-path failure twice. + return await this.client.chat.completions.create( + params as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming, + requestOptions, + ) } private getReasoningSettings(info: ModelInfo) { @@ -155,6 +174,8 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { return super.completePrompt(prompt, options) } + throwIfAborted(options?.abortSignal) + const { reasoningEffort } = this.getReasoningSettings(info) const params: ZAiChatCompletionParams = { model, @@ -164,13 +185,46 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { reasoning_effort: reasoningEffort, } + // CompletePromptOptions is not ApiHandlerCreateMessageMetadata (required + // taskId), so the abort/timeout merge and the per-request SDK timeout go + // through setOption; a positive timeoutMs overrides the client default and + // values <= 0 mean "no explicit timeout". + // The SDK attaches a listener to whatever signal it is given and keeps it after the request, so + // it gets a per-request bridge instead of the caller's long-lived controller. + const bridge = bridgeExternalAbortSignal(options?.abortSignal) + const requestSignal = mergeAbortSignalAndTimeout(bridge.signal, options?.timeoutMs) + const requestConfig = new RequestConfigBuilder() + .setOption("signal", requestSignal) + .setOption("timeout", getRequestTimeoutMs(options?.timeoutMs)) + .build() + try { - const response = await this.client.chat.completions.create( + // The SDK waits out a 429 backoff without checking the signal, so the await is raced with it. + const created = this.client.chat.completions.create( params as OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming, + requestConfig, ) + const response = requestSignal + ? await rejectOnAbort(created, requestSignal, this.providerName) + : await created + + // A cancellation that lands while the GLM request is in flight must not be reported as a + // completed prompt: the arrived content is discarded and the abort contract is raised + // instead, which is the behaviour the base provider already has for every other model. + if (options?.abortSignal?.aborted) { + throw handleOpenAIRequestError( + createAbortError(this.providerName), + this.providerName, + options.abortSignal, + requestSignal, + ) + } + return response.choices?.[0]?.message.content || "" } catch (error) { - throw handleOpenAIError(error, this.providerName) + throw handleOpenAIRequestError(error, this.providerName, options?.abortSignal, requestSignal) + } finally { + bridge.dispose() } } } diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..2c46065d858 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -74,11 +74,6 @@ "count": 1 } }, - "api/providers/__tests__/kimi-code.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, "api/providers/__tests__/lite-llm.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 26 @@ -191,7 +186,7 @@ }, "api/providers/base-openai-compatible-provider.ts": { "@typescript-eslint/no-explicit-any": { - "count": 6 + "count": 5 } }, "api/providers/base-provider.ts": { diff --git a/src/integrations/kimi-code/__tests__/oauth.spec.ts b/src/integrations/kimi-code/__tests__/oauth.spec.ts index e5d5a4135f0..185799e697f 100644 --- a/src/integrations/kimi-code/__tests__/oauth.spec.ts +++ b/src/integrations/kimi-code/__tests__/oauth.spec.ts @@ -1,6 +1,13 @@ import type { ExtensionContext } from "vscode" -import { KIMI_CODE_OAUTH_CONFIG, KimiCodeOAuthManager } from "../oauth" +import { captureError } from "../../../test-utils/errors" + +import { + KIMI_CODE_OAUTH_CONFIG, + KimiCodeOAuthManager, + refreshKimiCodeAccessToken, + type KimiCodeCredentials, +} from "../oauth" const createContext = () => { const values = new Map() @@ -17,6 +24,12 @@ const createContext = () => { } } +// One successful rotation response, shared by the rows that only need the pair to arrive. +const rotatedTokenResponse = () => + new Response(JSON.stringify({ access_token: "rotated", refresh_token: "rotated-refresh", expires_in: 3600 }), { + status: 200, + }) + describe("KimiCodeOAuthManager", () => { beforeEach(() => vi.restoreAllMocks()) afterEach(() => vi.useRealTimers()) @@ -156,13 +169,92 @@ describe("KimiCodeOAuthManager", () => { }) const tokenPromise = manager.getAccessToken() + // The assertion is attached before the clock moves: the deadline rejects this promise during + // the timer step, so the awaiting assertion is what holds the rejection. + const rejection = expect(tokenPromise).rejects.toMatchObject({ + name: "TimeoutError", + message: "Kimi Code OAuth request timed out", + }) + await vi.advanceTimersByTimeAsync(30_000) - await expect(tokenPromise).resolves.toBeNull() + await rejection expect(vi.mocked(fetch).mock.calls[0][1]?.signal?.aborted).toBe(true) expect(values.has("kimi-code-oauth-credentials")).toBe(true) expect(vi.getTimerCount()).toBe(0) }) + it("surfaces the token refresh deadline as its own typed timeout, not as a cancellation", async () => { + // Answering null for every refresh failure used to reach the caller as the generic "sign in + // from provider settings" error, which is what made a stalled POST indistinguishable from + // being signed out. The deadline is the failure the manager now re-raises, so the type, the + // message and the distance from the cancellation contract are pinned at the manager boundary. + vi.useFakeTimers() + const { context, values } = createContext() + values.set( + "kimi-code-oauth-credentials", + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + vi.spyOn(globalThis, "fetch").mockImplementation((_input, init) => { + return new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }) + }) + }) + // Captured before the clock moves, so the rejection is observed by this row and not by the + // unhandled-rejection handler during the timer step. + const pending = captureError(manager.getAccessToken()) + await vi.advanceTimersByTimeAsync(30_000) + const error = await pending + expect(error.name, "the deadline keeps the repository timeout name").toBe("TimeoutError") + expect(error.message).toBe("Kimi Code OAuth request timed out") + expect(error.name, "the deadline is not laundered into the cancellation contract").not.toBe("AbortError") + expect(error.cause, "a timeout carries no cancellation cause").toBeUndefined() + // The rejection is the deadline's own object: the guard re-raises it instead of wrapping it. + expect( + vi.mocked(fetch).mock.calls[0][1]?.signal?.reason, + "no wrapper stands between the deadline and the caller", + ).toBe(error) + expect(values.has("kimi-code-oauth-credentials"), "the stored pair survives a stalled POST").toBe(true) + expect(vi.getTimerCount()).toBe(0) + vi.useRealTimers() + }) + + it("bounds the answered body read with the request deadline", async () => { + // The deadline must still be armed after the headers arrive: a stalled success body is bounded + // by it, and the timer is cleared once the read settles. + vi.useFakeTimers() + let postSignal: AbortSignal | undefined + vi.spyOn(globalThis, "fetch").mockImplementation((_input, init) => { + postSignal = init?.signal as AbortSignal | undefined + // The body rejects with the signal's own reason, the way Node errors the response stream: + // postForm aborts with Error("Kimi Code OAuth request timed out"), not a DOMException. + const body = new Promise((_resolve, reject) => { + postSignal?.addEventListener("abort", () => reject(postSignal?.reason), { once: true }) + }) + return Promise.resolve(Object.assign(new Response("", { status: 200 }), { json: () => body })) + }) + const credentials: KimiCodeCredentials = { + type: "kimi-code", + accessToken: "old", + refreshToken: "refresh", + expiresAt: 0, + } + + // The rejection is captured before the clock moves, so the stalled body's abort never lands as + // an unhandled rejection inside the fake-timer step. + const pending = captureError(refreshKimiCodeAccessToken(credentials)) + await vi.advanceTimersByTimeAsync(0) + expect(postSignal?.aborted, "the headers arrived and the body is still pending").toBe(false) + + await vi.advanceTimersByTimeAsync(30_000) + // The caller receives the deadline's own failure, not a native AbortError wrapper. + expect((await pending).message).toBe("Kimi Code OAuth request timed out") + expect(postSignal?.aborted, "the deadline reached the pending body").toBe(true) + expect(vi.getTimerCount()).toBe(0) + vi.useRealTimers() + }) + it("keeps the newer polling lifecycle when a prior poll finishes cancellation", async () => { const { context } = createContext() const manager = new KimiCodeOAuthManager() @@ -465,4 +557,1365 @@ describe("KimiCodeOAuthManager", () => { const stored = JSON.parse(values.get("kimi-code-oauth-credentials")!) expect(stored.refreshToken).toBe("keep") }) + + it("threads the caller abort signal into the token refresh request", async () => { + const controller = new AbortController() + controller.abort() + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + // The forwarded request signal must already be aborted when the caller cancelled. + expect((init as RequestInit | undefined)?.signal?.aborted).toBe(true) + throw new DOMException("This operation was aborted", "AbortError") + }) + + await expect( + refreshKimiCodeAccessToken( + { type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }, + controller.signal, + ), + ).rejects.toMatchObject({ name: "AbortError" }) + expect(fetchSpy).toHaveBeenCalledTimes(1) + }) + + it("reports a cancelled refresh instead of returning the not-authenticated null", async () => { + const { context, values } = createContext() + values.set( + "kimi-code-oauth-credentials", + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + const controller = new AbortController() + controller.abort() + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockRejectedValue(new DOMException("This operation was aborted", "AbortError")) + + await expect(manager.getAccessToken(false, controller.signal)).rejects.toMatchObject({ name: "AbortError" }) + // The cancellation must not store anything or log the user out. + expect(context.secrets.store).not.toHaveBeenCalled() + expect(context.secrets.delete).not.toHaveBeenCalled() + + // forceRefreshAccessToken forwards the same caller signal. + await expect(manager.forceRefreshAccessToken(controller.signal)).rejects.toMatchObject({ name: "AbortError" }) + // Neither call may start a POST. Without the entry check both would fetch and only then reject + // through awaitRefresh, which the rejection assertions above cannot tell apart. + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it("reports the cancellation that lands while the credential read is pending", async () => { + const { context } = createContext() + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + // Nothing is stored, so the secret read is what decides whether the caller is signed in. The read + // parks so the caller can cancel while it is in flight, which is the ordinary case for a slow + // secret store. + let releaseRead!: () => void + const readPending = new Promise((resolve) => { + releaseRead = resolve + }) + vi.mocked(context.secrets.get).mockImplementation(async () => { + await readPending + return undefined + }) + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("", { status: 200 })) + const controller = new AbortController() + const pending = manager.getAccessToken(false, controller.signal) + controller.abort() + releaseRead() + + // The answer must be the cancellation. Answering null here surfaces as the sign-in error inside + // resolveAccessToken, and the provider never reaches its post-preparation throwIfAborted + // because prepareRequest already threw. + await expect(pending).rejects.toMatchObject({ + name: "AbortError", + message: "The Kimi Code OAuth request was aborted", + }) + expect(fetchSpy).not.toHaveBeenCalled() + expect(context.secrets.store).not.toHaveBeenCalled() + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("lets one caller cancel its wait without aborting a shared refresh another waiter needs", async () => { + const { context, values } = createContext() + values.set( + "kimi-code-oauth-credentials", + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let resolveFetch: ((response: Response) => void) | undefined + let fetchedSignal: AbortSignal | undefined + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(((_url, init) => { + fetchedSignal = (init as RequestInit)?.signal as AbortSignal + return new Promise((resolve) => { + resolveFetch = resolve + }) + }) as typeof fetch) + + const first = new AbortController() + const second = new AbortController() + const firstResult = manager.getAccessToken(false, first.signal).then( + () => "resolved", + (error: Error) => error.name, + ) + const secondResult = manager.getAccessToken(false, second.signal) + await vi.waitFor(() => { + expect(fetchSpy).toHaveBeenCalledTimes(1) + }) + + first.abort() + + await expect(firstResult).resolves.toBe("AbortError") + // The shared POST is still alive for the second caller. + expect(fetchedSignal?.aborted).toBe(false) + + resolveFetch?.( + new Response(JSON.stringify({ access_token: "new", refresh_token: "rotated", expires_in: 3600 }), { + status: 200, + }), + ) + await expect(secondResult).resolves.toBe("new") + }) + + it("lets the shared refresh POST finish after every waiter cancelled and stores its pair", async () => { + // The server rotates the refresh token when it answers, so a pair already on the wire is the + // only copy of it. A detach only stops that caller's wait; the POST finishes and its pair is + // stored. + const { context, values } = createContext() + values.set( + "kimi-code-oauth-credentials", + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let fetchedSignal: AbortSignal | undefined + let resolveFetch!: (response: Response) => void + vi.spyOn(globalThis, "fetch").mockImplementation(((_url, init) => { + fetchedSignal = (init as RequestInit)?.signal as AbortSignal + return new Promise((resolve) => { + resolveFetch = resolve + }) + }) as typeof fetch) + + const first = new AbortController() + const second = new AbortController() + const firstResult = manager.getAccessToken(false, first.signal).catch((error: Error) => error.name) + const secondResult = manager.getAccessToken(false, second.signal).catch((error: Error) => error.name) + await vi.waitFor(() => expect(fetchedSignal).toBeDefined()) + + first.abort() + second.abort() + await expect(firstResult).resolves.toBe("AbortError") + await expect(secondResult).resolves.toBe("AbortError") + // Nobody is waiting any more, and the POST is still allowed to finish. + expect(fetchedSignal?.aborted).toBe(false) + + resolveFetch(rotatedTokenResponse()) + await vi.waitFor(() => expect(manager.getState().status).toBe("authenticated")) + expect(values.get("kimi-code-oauth-credentials")).toContain("rotated-refresh") + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("joins a signal-less waiter when a signaled caller aborts", async () => { + const { context, values } = createContext() + values.set( + "kimi-code-oauth-credentials", + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let fetchedSignal: AbortSignal | undefined + let resolveFetch!: (response: Response) => void + vi.spyOn(globalThis, "fetch").mockImplementation(((_url, init) => { + fetchedSignal = (init as RequestInit)?.signal as AbortSignal + return new Promise((resolve) => { + resolveFetch = resolve + }) + }) as typeof fetch) + + // The signal-less caller is the one that must keep the shared POST alive; the signaled + // caller joins and then detaches without cancelling it. + const signalLessResult = manager.getAccessToken(false) + const controller = new AbortController() + const signaledResult = manager.getAccessToken(false, controller.signal).catch((error: Error) => error.name) + await vi.waitFor(() => expect(fetchedSignal).toBeDefined()) + + controller.abort() + + await expect(signaledResult).resolves.toBe("AbortError") + expect(fetchedSignal?.aborted).toBe(false) + + resolveFetch( + new Response(JSON.stringify({ access_token: "new", refresh_token: "rotated", expires_in: 3600 }), { + status: 200, + }), + ) + await expect(signalLessResult).resolves.toBe("new") + }) + + it("normalizes a caller abort that lands after the token POST started", async () => { + let startedResolve!: () => void + const started = new Promise((resolve) => { + startedResolve = resolve + }) + let fetchedSignal: AbortSignal | undefined + vi.spyOn(globalThis, "fetch").mockImplementation(((_url, init) => { + const signal = (init as RequestInit)?.signal as AbortSignal + fetchedSignal = signal + startedResolve() + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { once: true }) + }) + }) as typeof fetch) + + const controller = new AbortController() + const result = refreshKimiCodeAccessToken( + { type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }, + controller.signal, + ).catch((error: Error) => error) + await started + + controller.abort(new Error("cancelled by the caller")) + + const error = await result + expect(error).toBeInstanceOf(Error) + expect((error as Error).name).toBe("AbortError") + expect(fetchedSignal?.aborted).toBe(true) + }) + + it("preserves an independent fetch failure that races an aborted caller signal", async () => { + let rejectFetch!: (error: Error) => void + let startedResolve!: () => void + const started = new Promise((resolve) => { + startedResolve = resolve + }) + vi.spyOn(globalThis, "fetch").mockImplementation((() => { + startedResolve() + return new Promise((_resolve, reject) => { + rejectFetch = reject + }) + }) as typeof fetch) + + const controller = new AbortController() + const result = refreshKimiCodeAccessToken( + { type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }, + controller.signal, + ).catch((error: Error) => error) + await started + + controller.abort(new Error("cancelled by the caller")) + const independent = new Error("network exploded") + rejectFetch(independent) + + // The independent failure is not the caller's abort: it must be preserved unchanged. + await expect(result).resolves.toBe(independent) + }) + + it("normalizes a caller abort with an ordinary-Error reason to AbortError", async () => { + const { context, values } = createContext() + values.set( + "kimi-code-oauth-credentials", + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + vi.spyOn(globalThis, "fetch").mockImplementation(((_url, init) => { + const signal = (init as RequestInit)?.signal as AbortSignal + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { once: true }) + }) + }) as typeof fetch) + + const controller = new AbortController() + const result = manager.getAccessToken(false, controller.signal) + controller.abort(new Error("cancelled by the caller")) + await expect(result).rejects.toMatchObject({ name: "AbortError" }) + }) + + it("a sign-in that completes inside a parked sign-out delete leaves no credentials behind", async () => { + const { context, values } = createContext() + const key = "kimi-code-oauth-credentials" + values.set( + key, + JSON.stringify({ + type: "kimi-code", + accessToken: "old", + refreshToken: "refresh", + expiresAt: 0, + tokenType: "Bearer", + }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + const order: string[] = [] + let releaseDelete: () => void = () => {} + let deleteFinished: () => void = () => {} + const deleteGate = new Promise((resolve) => { + deleteFinished = resolve + }) + const store = vi.mocked(context.secrets.store) + const remove = vi.mocked(context.secrets.delete) + store.mockImplementation(async (k: string, v: string) => { + // The host runs both secret operations through one sequencer, so this store cannot pass the + // sign-out's pending delete: it waits for it here, the way it does in the extension host. + await deleteGate + order.push("store") + values.set(k, v) + }) + remove.mockImplementation( + (k: string) => + new Promise((resolve) => { + order.push("delete:start") + releaseDelete = () => { + order.push("delete:end") + values.delete(k) + deleteFinished() + resolve() + } + }), + ) + const signingOut = manager.clearCredentials() + await new Promise((resolve) => setImmediate(resolve)) + // The sign-out is held inside its own delete, which is the window the row asks about. + expect(manager["clearFenceCount"], "sign-out holds its fence across the parked delete").toBe(1) + expect(order).toEqual(["delete:start"]) + + // A full sign-in - device authorization plus the token poll - completes inside the park. + const fetchSpy = vi.spyOn(globalThis, "fetch") + fetchSpy + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + device_code: "device", + user_code: "ABCD-EFGH", + verification_uri: "https://auth.kimi.com/device", + expires_in: 600, + // The schema requires a positive interval; one second is the shortest the endpoint accepts. + interval: 1, + }), + { status: 200 }, + ), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + access_token: "fresh", + refresh_token: "fresh-refresh", + expires_in: 3_600_000, + token_type: "Bearer", + }), + { status: 200 }, + ), + ) + await manager.startAuthorization() + const signIn = manager.waitForAuthorization() + // The sign-in's write is queued behind the sign-out's pending delete, so it cannot land yet. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(order, "the token write waits for the pending delete").toEqual(["delete:start"]) + + releaseDelete() + const signedIn = await signIn + await signingOut + + expect(signedIn.accessToken).toBe("fresh") + // The host's order: the delete runs first, then the write the sign-in queued behind it. + expect(order).toEqual(["delete:start", "delete:end", "store"]) + expect(store).toHaveBeenCalledWith(key, JSON.stringify(signedIn)) + expect(remove).toHaveBeenCalledTimes(1) + expect(values.get(key), "the sign-in's pair survives the earlier delete").toContain("fresh-refresh") + expect(manager["clearFenceCount"]).toBe(0) + }) + + it("holds the sign-out fence until the last of two overlapping sign-outs finishes", async () => { + // One boolean fence cannot serve two sign-outs. The first one's finally lowers it while the + // second is still inside its own delete, and the only startRefresh() call site - + // getAccessToken(), downstream of the fence check - is open again in that window: a refresh + // started there captures the generation the second sign-out already bumped, so its save + // passes isCurrent() and re-installs what that delete removes. The depth counter keeps the + // fence held until every sign-out in flight has finished its own finally. + const { context, values } = createContext() + const key = "kimi-code-oauth-credentials" + values.set( + key, + JSON.stringify({ + type: "kimi-code", + accessToken: "old", + refreshToken: "refresh", + expiresAt: 0, + tokenType: "Bearer", + }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + const releases: Array<() => void> = [] + const remove = vi.mocked(context.secrets.delete) + remove.mockImplementation( + (k: string) => + new Promise((resolve) => { + releases.push(() => { + values.delete(k) + resolve() + }) + }), + ) + const first = manager.clearCredentials() + await new Promise((resolve) => setImmediate(resolve)) + const second = manager.clearCredentials() + await new Promise((resolve) => setImmediate(resolve)) + expect(releases.length, "both sign-outs reached their own delete").toBe(2) + + releases[0]?.() + await first + expect(manager["clearFenceCount"], "the second sign-out still holds the fence").toBe(1) + + releases[1]?.() + await second + expect(manager["clearFenceCount"], "the last sign-out releases the fence").toBe(0) + expect(values.has(key)).toBe(false) + expect(await manager.getAccessToken()).toBeNull() + }) + it("a sign-out that lands while a sign-in is storing rejects that write instead of installing it", async () => { + const { context, values } = createContext() + const key = "kimi-code-oauth-credentials" + values.set( + key, + JSON.stringify({ + type: "kimi-code", + accessToken: "old", + refreshToken: "refresh", + expiresAt: 0, + tokenType: "Bearer", + }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let releaseStore: () => void = () => {} + const store = vi.mocked(context.secrets.store) + const remove = vi.mocked(context.secrets.delete) + const read = vi.mocked(context.secrets.get) + const deletes: string[] = [] + // VS Code 1.100.0 runs every secret operation of one extension through a single sequencer: + // store, get and delete are each queued on the extension id, in the order the host received + // them (mainThreadSecretState.ts, _sequencer.queue(extensionId, ...) for all three). So a + // sign-out delete cannot overtake the write that is still in flight, and a read queued after + // it sees what the delete left behind. The doubles keep that order; the shared + // createContext double answers every call immediately, which is what let the delete run + // before the parked write here. + let chain: Promise = Promise.resolve() + const enqueue = (run: () => Promise): Promise => { + const next = chain.then(run) + chain = next.then( + () => undefined, + () => undefined, + ) + return next + } + store.mockImplementation((k: string, v: string) => + enqueue(async () => { + await new Promise((resolve) => { + releaseStore = () => { + values.set(k, v) + resolve() + } + }) + }), + ) + remove.mockImplementation((k: string) => + enqueue(async () => { + deletes.push(k) + values.delete(k) + }), + ) + read.mockImplementation((k: string) => enqueue(async () => values.get(k))) + vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + device_code: "device", + user_code: "ABCD-EFGH", + verification_uri: "https://auth.kimi.com/device", + expires_in: 600, + // The schema requires a positive interval; one second is the shortest the endpoint accepts. + interval: 1, + }), + { status: 200 }, + ), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + access_token: "late", + refresh_token: "late-refresh", + expires_in: 3_600_000, + token_type: "Bearer", + }), + { status: 200 }, + ), + ) + // The token poll sleeps for the endpoint's interval, so the clock is taken over + // before the poll starts and then advanced: the write is reached deterministically + // instead of by wall-clock luck. + vi.useFakeTimers() + await manager.startAuthorization() + const signingIn = manager.waitForAuthorization() + await vi.advanceTimersByTimeAsync(1_000) + await vi.advanceTimersByTimeAsync(1) + expect(store.mock.calls.length, "the sign-in reached the credential write").toBe(1) + + // Sign-out lands while that write is parked, which makes the write stale before it commits. + const signingOut = manager.clearCredentials() + await vi.advanceTimersByTimeAsync(1) + releaseStore() + + await expect(signingIn).rejects.toMatchObject({ message: "Kimi Code authorization was cancelled" }) + await signingOut + + // The parked write never becomes the stored state: it is removed and nothing is installed. + expect(manager["credentials"]).toBeNull() + expect(manager.getState()).toEqual({ status: "idle" }) + expect(values.has(key)).toBe(false) + // One delete, not two. The host runs the sign-out delete after the parked write commits, so + // the write is removed rather than installed; the stale write's rollback read then queues + // behind that same delete, finds no value, and issues no second delete. + expect(deletes.length).toBe(1) + expect(manager["clearFenceCount"]).toBe(0) + }) + it("a delayed invalid_grant from a stale refresh keeps credentials a newer sign-in saved", async () => { + const { context, values } = createContext() + const key = "kimi-code-oauth-credentials" + values.set( + key, + JSON.stringify({ + type: "kimi-code", + accessToken: "old", + refreshToken: "old-rotating", + expiresAt: 0, + tokenType: "Bearer", + }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + // The refresh POST is parked: its invalid_grant verdict - and the credential + // clearing that follows it - lands only after the newer sign-in below. + let releaseRefresh: (response: Response) => void = () => {} + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementationOnce( + () => + new Promise((resolve) => { + releaseRefresh = resolve + }), + ) + const stale = manager.getAccessToken(false) + // Let the refresh POST actually start first: it captures its generation at POST start, + // and the interleaving under test is the stale verdict arriving after a newer install. + await new Promise((resolve) => setImmediate(resolve)) + await new Promise((resolve) => setImmediate(resolve)) + expect(manager["refreshPromise"] !== null, "refresh started before the sign-in").toBe(true) + // A newer sign-in installs fresh credentials while the old POST is still in flight. + await manager["saveCredentials"]({ + type: "kimi-code", + accessToken: "new", + refreshToken: "new-rotating", + expiresAt: Date.now() + 3_600_000, + tokenType: "Bearer", + }) + releaseRefresh(new Response(JSON.stringify({ error: "invalid_grant" }), { status: 400 })) + // The stale refresh's own caller still settles (null: its generation lost the save + // race), but the verdict must not touch what the newer save installed. + await expect(stale).resolves.toBeNull() + expect(manager["credentials"]?.accessToken).toBe("new") + expect(manager.getState().status).toBe("authenticated") + expect(values.has(key)).toBe(true) + // The fresh token is served without a new POST: the newer credentials survived. + await expect(manager.getAccessToken(false)).resolves.toBe("new") + expect(fetchSpy).toHaveBeenCalledTimes(1) + }) + + it("drains an in-flight refresh before sign-out deletes credentials and refuses a re-install", async () => { + const { context, values } = createContext() + const key = "kimi-code-oauth-credentials" + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + const writes: string[] = [] + const store = vi.mocked(context.secrets.store) + const remove = vi.mocked(context.secrets.delete) + store.mockImplementation(async (k: string, v: string) => { + writes.push("store") + values.set(k, v) + }) + remove.mockImplementation(async (k: string) => { + writes.push("delete") + values.delete(k) + }) + let resolveRefresh!: (response: Response) => void + let posts = 0 + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(() => { + posts++ + if (posts === 1) { + return new Promise((resolve) => { + resolveRefresh = resolve + }) + } + return Promise.resolve( + new Response(JSON.stringify({ access_token: "fresh", refresh_token: "rotated", expires_in: 3600 }), { + status: 200, + }), + ) + }) + const tokenPromise = manager.getAccessToken(false) + await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledOnce()) + const clearPromise = manager.clearCredentials() + // While the clear holds its fence a new caller has no token to be served and must not start + // the network work the sign-out is draining. + await expect(manager.getAccessToken(false)).resolves.toBeNull() + // The 401-retry path is fenced the same way: it is offered no token and starts no POST while + // the sign-out is still draining. + await expect(manager.forceRefreshAccessToken()).resolves.toBeNull() + expect(fetchSpy).toHaveBeenCalledTimes(1) + resolveRefresh( + new Response(JSON.stringify({ access_token: "stale", refresh_token: "rotated", expires_in: 3600 }), { + status: 200, + }), + ) + await clearPromise + await expect(tokenPromise).resolves.toBeNull() + // The delete is the last write: the refresh that resolved after sign-out began was drained + // first, and its save was refused by the generation the clear moved past. + expect(writes).toEqual(["delete"]) + expect(values.has(key)).toBe(false) + // The fence is released with the clear: a later caller with expired credentials gets its own + // POST and its save is installed. + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "mid", refreshToken: "refresh", expiresAt: 0 }), + ) + await expect(manager.getAccessToken(false)).resolves.toBe("fresh") + expect(writes).toEqual(["delete", "store"]) + expect(fetchSpy).toHaveBeenCalledTimes(2) + }) + + it("keeps the rotated pair when the caller stops after the response headers arrive", async () => { + // The provider rotated the token when it answered, so the pair in this body is the only copy + // of it: the caller's stop must not abandon the read. + const controller = new AbortController() + let resolveBody: (value: unknown) => void = () => {} + const bodyPending = new Promise>((resolve) => { + resolveBody = resolve as (value: unknown) => void + }) + const stalledResponse = new Response("", { status: 200 }) + vi.spyOn(stalledResponse, "json").mockImplementation(() => bodyPending) + vi.spyOn(globalThis, "fetch").mockResolvedValue(stalledResponse) + const credentials: KimiCodeCredentials = { + type: "kimi-code", + accessToken: "old", + refreshToken: "refresh", + expiresAt: 0, + } + const pending = refreshKimiCodeAccessToken(credentials, controller.signal) + await vi.waitFor(() => expect(stalledResponse.json).toHaveBeenCalled()) + controller.abort() + resolveBody({ access_token: "rotated", refresh_token: "rotated-refresh", expires_in: 3600 }) + + await expect(pending).resolves.toMatchObject({ + accessToken: "rotated", + refreshToken: "rotated-refresh", + }) + }) + + it("does not abort the answered response when the caller stops during the token body read", async () => { + // Only the POST before the server answers is cancelled: the response stream stays open, so a + // pair the provider already issued still reaches the store. + let fetchedSignal: AbortSignal | undefined + let bodyReadStarted = false + let resolveBody: (value: unknown) => void = () => {} + const bodyPending = new Promise((resolve) => { + resolveBody = resolve + }) + vi.spyOn(globalThis, "fetch").mockImplementation((_url, init) => { + fetchedSignal = init?.signal as AbortSignal | undefined + return Promise.resolve( + Object.assign(new Response("", { status: 200 }), { + json: () => { + bodyReadStarted = true + return bodyPending + }, + }), + ) + }) + const controller = new AbortController() + const credentials: KimiCodeCredentials = { + type: "kimi-code", + accessToken: "old", + refreshToken: "refresh", + expiresAt: 0, + } + const pending = refreshKimiCodeAccessToken(credentials, controller.signal) + await vi.waitFor(() => expect(bodyReadStarted).toBe(true)) + controller.abort() + expect(fetchedSignal?.aborted, "the abort no longer reaches the answered response").toBe(false) + resolveBody({ access_token: "rotated", refresh_token: "rotated-refresh", expires_in: 3600 }) + await expect(pending).resolves.toMatchObject({ refreshToken: "rotated-refresh" }) + }) + + it("honors an answered error body's verdict after the caller stops", async () => { + // The failure path reads a body too. Once the headers are in, the verdict in that body is + // authoritative, so a caller's stop must not abandon it. + let fetchedSignal: AbortSignal | undefined + let bodyReadStarted = false + let resolveBody: (value: string) => void = () => {} + const textPending = new Promise((resolve) => { + resolveBody = resolve + }) + vi.spyOn(globalThis, "fetch").mockImplementation((_url, init) => { + fetchedSignal = init?.signal as AbortSignal | undefined + return Promise.resolve( + Object.assign(new Response("", { status: 400, statusText: "Bad Request" }), { + text: () => { + bodyReadStarted = true + return textPending + }, + }), + ) + }) + const controller = new AbortController() + const credentials: KimiCodeCredentials = { + type: "kimi-code", + accessToken: "old", + refreshToken: "refresh", + expiresAt: 0, + } + const pending = refreshKimiCodeAccessToken(credentials, controller.signal) + await vi.waitFor(() => expect(bodyReadStarted).toBe(true)) + controller.abort() + expect(fetchedSignal?.aborted, "the answered error body is not abandoned").toBe(false) + resolveBody(JSON.stringify({ error: "invalid_grant" })) + await expect(pending).rejects.toMatchObject({ code: "invalid_grant" }) + }) + + it("never aborts a replacement refresh on behalf of a waiter enrolled in the previous one", async () => { + const { context, values } = createContext() + values.set( + "kimi-code-oauth-credentials", + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + // Store calls are recorded in order so the test can tell the replacement's write from the one + // the late response writes after it. + const storedWrites: string[] = [] + vi.mocked(context.secrets.store).mockImplementation(async (storedKey, value) => { + storedWrites.push(value) + values.set(storedKey, value) + }) + let resolveFirst!: (response: Response) => void + let resolveSecond!: (response: Response) => void + let firstSignal: AbortSignal | undefined + let secondSignal: AbortSignal | undefined + let posts = 0 + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation((_url, init) => { + posts++ + const signal = (init as RequestInit)?.signal as AbortSignal + if (posts === 1) { + firstSignal = signal + return new Promise((resolve) => { + resolveFirst = resolve + }) + } + secondSignal = signal + return new Promise((resolve) => { + resolveSecond = resolve + }) + }) + const leaving = new AbortController() + const leavingWaiter = manager.getAccessToken(false, leaving.signal) + await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledOnce()) + // The promise this caller joined, captured before a replacement can replace it. + const firstRefresh = manager["refreshPromise"] + const staying = new AbortController() + const stayingWaiter = manager.getAccessToken(false, staying.signal) + // Both callers must be enrolled in the shared POST before anybody leaves it, so the enrollment + // is not racing the abort. + await vi.waitFor(() => expect(manager["refreshWaiters"]?.size).toBe(2)) + // One waiter detaching while another still needs the shared POST must not cancel that POST. + leaving.abort() + await expect(leavingWaiter).rejects.toMatchObject({ name: "AbortError" }) + expect(firstSignal?.aborted).toBe(false) + // The POST this waiter enrolled in then dies on its own lifecycle, and a replacement takes + // its place before the remaining waiter detaches. That waiter must cancel the POST it joined, + // which is already dead, and leave the replacement it never enrolled in alone. + manager["refreshController"]?.abort() + const replacement = manager.getAccessToken(false) + await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(2)) + staying.abort() + await expect(stayingWaiter).rejects.toMatchObject({ name: "AbortError" }) + expect(firstSignal?.aborted).toBe(true) + expect(secondSignal?.aborted).toBe(false) + resolveSecond( + new Response(JSON.stringify({ access_token: "new", refresh_token: "rotated", expires_in: 3600 }), { + status: 200, + }), + ) + await expect(replacement).resolves.toBe("new") + // The stalled POST the cancelled waiters were enrolled in resolves last, with a controller + // that no longer owns the refresh state, so its save must not install over the replacement's. + resolveFirst( + new Response(JSON.stringify({ access_token: "late", refresh_token: "rotated", expires_in: 3600 }), { + status: 200, + }), + ) + // The replaced refresh settles without a token: its pair arrived after a replacement took the + // refresh state, so the save is refused and nothing is written. + await expect(firstRefresh).resolves.toBeNull() + // It no longer owns the refresh state, so it refuses the write before storing: the replacement is + // the only credential write in this test, and the late token never reaches storage. + expect(storedWrites).toHaveLength(1) + expect(storedWrites[0]).toContain("new") + expect(values.get("kimi-code-oauth-credentials")).toContain("new") + expect(values.get("kimi-code-oauth-credentials")).not.toContain("late") + expect(context.secrets.delete).not.toHaveBeenCalled() + expect(manager.getState().status).toBe("authenticated") + }) + + it("reaches remaining waiters as an abort when the shared POST dies after its controller was aborted", async () => { + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let rejectPost!: (error: Error) => void + vi.spyOn(globalThis, "fetch").mockImplementationOnce(() => { + return new Promise((_resolve, reject) => { + rejectPost = reject + }) + }) + const firstWaiter = manager.getAccessToken() + await vi.waitFor(() => expect(manager["refreshWaiters"]?.size).toBe(1)) + const secondWaiter = manager.getAccessToken() + await vi.waitFor(() => expect(manager["refreshWaiters"]?.size).toBe(2)) + // The abort comes from outside the waiter set while the POST is still in flight: neither + // waiter has detached, so detaching cannot be what killed this POST. + manager["refreshController"]?.abort() + rejectPost(new Error("the token endpoint dropped the connection")) + // Both enrolled callers observe one cancellation instead of the "not authenticated" null + // path that a dead shared POST would otherwise answer with. + await expect(firstWaiter).rejects.toMatchObject({ name: "AbortError" }) + await expect(secondWaiter).rejects.toMatchObject({ name: "AbortError" }) + expect(context.secrets.store).not.toHaveBeenCalled() + expect(context.secrets.delete).not.toHaveBeenCalled() + expect(values.get(key)).toContain("old") + }) + + it("keeps the credentials a cancelled waiter was storing when it detached", async () => { + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + // The store parks so the only waiter detaches while the rotated pair is already on its way to + // SecretStorage. The provider rotated that refresh token, so the write cannot be reproduced: + // rolling it back would delete the only copy and strand the next launch at the sign-in screen. + let releaseStore: () => void = () => {} + const storeGate = new Promise((resolve) => { + releaseStore = resolve + }) + vi.mocked(context.secrets.store).mockImplementation(async (storedKey, value) => { + await storeGate + values.set(storedKey, value) + }) + vi.spyOn(globalThis, "fetch").mockResolvedValue(rotatedTokenResponse()) + const leaving = new AbortController() + const leavingWaiter = manager.getAccessToken(false, leaving.signal) + await vi.waitFor(() => expect(context.secrets.store).toHaveBeenCalledOnce()) + leaving.abort() + await expect(leavingWaiter).rejects.toMatchObject({ name: "AbortError" }) + releaseStore() + await vi.waitFor(() => expect(values.get(key)).toContain("rotated-refresh")) + // The value on disk is this refresh's own write, so the ownership check must not delete it. + expect(context.secrets.delete).not.toHaveBeenCalled() + expect(manager.getState().status).toBe("authenticated") + // A fresh manager reads what was kept, which is the relaunch path the rollback broke. + const reloaded = new KimiCodeOAuthManager() + reloaded.initialize(context) + expect(await reloaded.isAuthenticated()).toBe(true) + expect(await reloaded.getAccessToken()).toBe("rotated") + }) + + it("stores the refreshed credentials when the waiter never detaches", async () => { + // Positive control for the row above: the same fixture without a cancellation stores the + // rotated pair and issues no rollback delete, so the kept write is not an artifact of the race. + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + vi.spyOn(globalThis, "fetch").mockResolvedValue(rotatedTokenResponse()) + + await expect(manager.getAccessToken(false, new AbortController().signal)).resolves.toBe("rotated") + expect(context.secrets.delete).not.toHaveBeenCalled() + expect(values.get(key)).toContain("rotated-refresh") + expect(manager.getState().status).toBe("authenticated") + }) + + it("stores the rotated pair when the only caller stops during the token body read", async () => { + // End to end: the caller that stopped never sees the token, but the pair the provider issued + // is still the only copy of a rotated refresh token, so it reaches the store. + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let bodyReadStarted = false + let resolveBody: (value: unknown) => void = () => {} + const bodyPending = new Promise((resolve) => { + resolveBody = resolve + }) + vi.spyOn(globalThis, "fetch").mockResolvedValue( + Object.assign(new Response("", { status: 200 }), { + json: () => { + bodyReadStarted = true + return bodyPending + }, + }), + ) + const controller = new AbortController() + const waiter = manager.getAccessToken(false, controller.signal) + await vi.waitFor(() => expect(bodyReadStarted).toBe(true)) + controller.abort() + await expect(waiter).rejects.toMatchObject({ name: "AbortError" }) + resolveBody({ access_token: "rotated", refresh_token: "rotated-refresh", expires_in: 3600 }) + + await vi.waitFor(() => expect(manager.getState().status).toBe("authenticated")) + expect(values.get(key)).toContain("rotated-refresh") + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("a stale invalid_grant does not clear a sign-in that queued its write first", async () => { + // The verdict's clear runs on the credential chain with the generation re-checked inside it: the + // sign-in's write queued first, so its generation advance must make the queued clear a no-op. + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let releaseStore: () => void = () => {} + const storeGate = new Promise((resolve) => { + releaseStore = resolve + }) + vi.mocked(context.secrets.store).mockImplementation(async (storedKey, value) => { + await storeGate + values.set(storedKey, value) + }) + let resolvePost!: (response: Response) => void + vi.spyOn(globalThis, "fetch").mockImplementation( + () => + new Promise((resolve) => { + resolvePost = resolve + }), + ) + + const staleRefresh = manager.getAccessToken().catch((error: Error) => error) + await vi.waitFor(() => expect(resolvePost).toBeDefined()) + // The sign-in's write queues behind the parked store before the verdict arrives. + const signInWrite = manager["saveCredentials"]({ + type: "kimi-code", + accessToken: "fresh", + refreshToken: "fresh-refresh", + expiresAt: Date.now() + 3_600_000, + }) + await vi.waitFor(() => expect(context.secrets.store).toHaveBeenCalled()) + resolvePost(new Response(JSON.stringify({ error: "invalid_grant" }), { status: 400 })) + // The verdict's cleanup queues behind that store: nothing is deleted while it is still pending, + // which is what makes this row fail when the generation check sits outside the queued task. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(context.secrets.delete, "the cleanup waits for the queued write").not.toHaveBeenCalled() + + releaseStore() + await expect(signInWrite).resolves.toBe(true) + await staleRefresh + await vi.waitFor(() => expect(manager.getState().status).toBe("authenticated")) + + // The sign-in's pair survives: the queued clear re-read the generation and skipped. + expect(values.get(key)).toContain("fresh-refresh") + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("keeps the rotated pair in memory when the store fails after the token POST", async () => { + // The server rotated the refresh token, so a store failure must not discard the pair: it stays + // in memory, the next request is served from it, and the stored pair is left untouched. + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + vi.mocked(context.secrets.store).mockRejectedValueOnce(new Error("disk full")) + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(rotatedTokenResponse()) + + await expect(manager.getAccessToken()).resolves.toBeNull() + expect(manager["credentials"]).toMatchObject({ + accessToken: "rotated", + refreshToken: "rotated-refresh", + }) + expect(await manager.getAccessToken()).toBe("rotated") + expect(fetchSpy).toHaveBeenCalledTimes(1) + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("a cancellation that lands while the credential store is failing installs nothing", async () => { + // Cancellation is the caller's verdict on its own sign-in: a pair that arrives after it lost + // ownership may not be installed by a store that then fails, because the next request would + // serve credentials the user just threw away. + const { context, values } = createContext() + const key = "kimi-code-oauth-credentials" + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let rejectStore: (error: Error) => void = () => {} + const store = vi.mocked(context.secrets.store) + store.mockImplementation( + () => + new Promise((_resolve, reject) => { + rejectStore = reject + }), + ) + vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + device_code: "device", + user_code: "ABCD-EFGH", + verification_uri: "https://auth.kimi.com/device", + expires_in: 600, + // The schema requires a positive interval; one second is the shortest the endpoint accepts. + interval: 1, + }), + { status: 200 }, + ), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + access_token: "canceled", + refresh_token: "canceled-refresh", + expires_in: 3_600_000, + token_type: "Bearer", + }), + { status: 200 }, + ), + ) + // The token poll sleeps for the endpoint's interval, so the clock is taken over before the poll + // starts and then advanced: the credential write is reached deterministically instead of by + // wall-clock luck. + vi.useFakeTimers() + await manager.startAuthorization() + const signingIn = manager.waitForAuthorization() + await vi.advanceTimersByTimeAsync(1_000) + await vi.advanceTimersByTimeAsync(1) + expect(store.mock.calls.length, "the sign-in reached the credential write").toBe(1) + + // The user cancels the device sign-in while that write is still in flight, and only then does + // the store fail. + manager.cancelAuthorization() + rejectStore(new Error("secret store failed")) + + // The store's own failure still reaches the caller: a cancellation does not swallow it. + await expect(signingIn).rejects.toThrow("secret store failed") + // The canceled pair never becomes the manager's: neither in memory nor as an authenticated + // state a later request could serve. + expect(manager["credentials"]).toBeNull() + expect(manager.getState()).toEqual({ status: "idle" }) + expect(values.has(key)).toBe(false) + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("a store failure while the sign-in still owns its result keeps the pair in memory", async () => { + // A failed store is not a cancellation: the sign-in that still owns its result keeps the pair + // the server rotated once, so the next request is served from memory instead of sending the + // user back to sign-in. + const { context, values } = createContext() + const key = "kimi-code-oauth-credentials" + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + device_code: "device", + user_code: "ABCD-EFGH", + verification_uri: "https://auth.kimi.com/device", + expires_in: 600, + // The schema requires a positive interval; one second is the shortest the endpoint accepts. + interval: 1, + }), + { status: 200 }, + ), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + access_token: "signed-in", + refresh_token: "signed-in-refresh", + expires_in: 3_600_000, + token_type: "Bearer", + }), + { status: 200 }, + ), + ) + let rejectStore: (error: Error) => void = () => {} + vi.mocked(context.secrets.store).mockImplementation( + () => + new Promise((_resolve, reject) => { + rejectStore = reject + }), + ) + vi.useFakeTimers() + await manager.startAuthorization() + const signingIn = manager.waitForAuthorization() + await vi.advanceTimersByTimeAsync(1_000) + await vi.advanceTimersByTimeAsync(1) + rejectStore(new Error("secret store failed")) + + await expect(signingIn).rejects.toThrow("secret store failed") + expect(manager["credentials"]).toMatchObject({ + accessToken: "signed-in", + refreshToken: "signed-in-refresh", + }) + expect(await manager.getAccessToken()).toBe("signed-in") + expect(vi.mocked(globalThis.fetch)).toHaveBeenCalledTimes(2) + expect(values.has(key)).toBe(false) + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + it("keeps a replacement refresh's commit marker when the replaced refresh answers last", async () => { + // A refresh whose waiters all left is replaced. Its answer can still arrive after the + // replacement started storing; that late answer must not touch the replacement's marker, or + // the replacement's next ownership check would read "cancelled" and roll back its write. + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let releaseStore: () => void = () => {} + const storeGate = new Promise((resolve) => { + releaseStore = resolve + }) + const stored: string[] = [] + vi.mocked(context.secrets.store).mockImplementation(async (storedKey, value) => { + stored.push(value) + // The write lands, then the manager's post-store ownership check parks here. + values.set(storedKey, value) + await storeGate + }) + let resolveFirst!: (response: Response) => void + let posts = 0 + vi.spyOn(globalThis, "fetch").mockImplementation(() => { + posts++ + if (posts === 1) { + return new Promise((resolve) => { + resolveFirst = resolve + }) + } + return Promise.resolve(rotatedTokenResponse()) + }) + + const leaving = new AbortController() + const leavingWaiter = manager.getAccessToken(false, leaving.signal) + await vi.waitFor(() => expect(posts).toBe(1)) + const replacedRefresh = manager["refreshPromise"] + // Its only waiter detaches, and the POST itself dies before it answers, so a replacement starts. + leaving.abort() + await expect(leavingWaiter).rejects.toMatchObject({ name: "AbortError" }) + manager["refreshController"]?.abort() + const staying = new AbortController() + const stayingWaiter = manager.getAccessToken(false, staying.signal) + await vi.waitFor(() => expect(stored).toHaveLength(1)) + expect(manager["refreshCommitting"]).toBe(manager["refreshController"]) + + // The replaced refresh answers last: it is not current, so it neither marks nor stores. + resolveFirst(rotatedTokenResponse()) + await expect(replacedRefresh).resolves.toBeNull() + expect(manager["refreshCommitting"]).toBe(manager["refreshController"]) + + // The replacement's own waiter now cancels mid-store: its write must survive. + staying.abort() + await expect(stayingWaiter).rejects.toMatchObject({ name: "AbortError" }) + releaseStore() + await vi.waitFor(() => expect(manager.getState().status).toBe("authenticated")) + expect(values.get(key)).toContain("rotated-refresh") + expect(stored).toHaveLength(1) + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("keeps the newer pair when a stale refresh store lands last", async () => { + // SecretStorage keeps no ordering, so two writes can land out of order and the earlier one can + // overwrite the newer pair. Every write runs on one chain: the newer pair survives even when + // the stale refresh store is still parked, and the rollback issues no delete. + const key = "kimi-code-oauth-credentials" + const { context, values } = createContext() + values.set( + key, + JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }), + ) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let releaseStale: () => void = () => {} + const staleGate = new Promise((resolve) => { + releaseStale = resolve + }) + let stores = 0 + vi.mocked(context.secrets.store).mockImplementation(async (storedKey, value) => { + stores++ + if (stores === 1) await staleGate + values.set(storedKey, value) + }) + vi.spyOn(globalThis, "fetch").mockResolvedValue(rotatedTokenResponse()) + + const staleRefresh = manager.getAccessToken() + await vi.waitFor(() => expect(stores).toBe(1)) + // A newer write, the same one a device-flow sign-in performs, queues behind the parked one. + const newerWrite = manager["saveCredentials"]({ + type: "kimi-code", + accessToken: "newer", + refreshToken: "newer-refresh", + expiresAt: Date.now() + 3_600_000, + }) + expect(stores).toBe(1) + + releaseStale() + await expect(staleRefresh).resolves.toBe("rotated") + await expect(newerWrite).resolves.toBe(true) + + expect(values.get(key)).toContain("newer-refresh") + expect(context.secrets.delete).not.toHaveBeenCalled() + }) + + it("does not delete a newer value written before a stale save reaches its rollback read", async () => { + // The rollback is read, compare, delete on a SecretStorage with no compare-and-delete: a value + // that replaced this save's own write while the store was parked must not be removed by it. + const key = "kimi-code-oauth-credentials" + const initial = JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }) + const newer = JSON.stringify({ + type: "kimi-code", + accessToken: "newer", + refreshToken: "newer-refresh", + expiresAt: 0, + }) + const { context, values } = createContext() + values.set(key, initial) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let written = "" + let releaseStore: () => void = () => {} + const storeGate = new Promise((resolve) => { + releaseStore = resolve + }) + vi.mocked(context.secrets.store).mockImplementation(async (storedKey, value) => { + written = value + // The write lands, then the manager's post-store ownership check parks here. + values.set(storedKey, value) + await storeGate + }) + const readValues: string[] = [] + vi.mocked(context.secrets.get).mockImplementation(async () => { + // Every read answers from the Map the storage is backed by, so a read can only report a + // value storage actually holds, and the list below is the read history, not a script. + const stored = values.get(key) + readValues.push(String(stored)) + return stored + }) + vi.spyOn(globalThis, "fetch").mockResolvedValue(rotatedTokenResponse()) + + const staleSave = manager.getAccessToken() + await vi.waitFor(() => expect(context.secrets.store).toHaveBeenCalledOnce()) + // A newer sign-in's pair supersedes this save while its store is parked. It is installed into + // the Map, not into the mock's return value, because that is the only way a newer write can + // reach a read: a real credential pair, the only shape a sign-in writes. + values.set(key, newer) + manager["credentialsGeneration"]++ + releaseStore() + await expect(staleSave).resolves.toBeNull() + + expect(written).toContain("rotated-refresh") + // The rollback compared against the newer pair rather than this save's own write, so it had + // nothing to delete, and it stopped after that one read instead of re-reading a stale match. + expect(readValues, "the load read and the rollback read, both answered from storage").toEqual([initial, newer]) + expect(context.secrets.delete).not.toHaveBeenCalled() + expect(values.get(key), "the exact pair the newer sign-in wrote is what survives").toBe(newer) + }) + + it("does not delete when the stored value changes between the two rollback reads", async () => { + // The re-read exists because the read above it can already be stale by the time the delete is + // issued: a value that lands in that window must survive as well. + const key = "kimi-code-oauth-credentials" + const initial = JSON.stringify({ type: "kimi-code", accessToken: "old", refreshToken: "refresh", expiresAt: 0 }) + const { context, values } = createContext() + values.set(key, initial) + const manager = new KimiCodeOAuthManager() + manager.initialize(context) + let written = "" + let releaseStore: () => void = () => {} + const storeGate = new Promise((resolve) => { + releaseStore = resolve + }) + vi.mocked(context.secrets.store).mockImplementation(async (storedKey, value) => { + written = value + // The write lands, then the manager's post-store ownership check parks here. + values.set(storedKey, value) + await storeGate + }) + const newer = JSON.stringify({ + type: "kimi-code", + accessToken: "newer", + refreshToken: "newer-refresh", + expiresAt: 0, + }) + let reads = 0 + vi.mocked(context.secrets.get).mockImplementation(async () => { + reads++ + // 1: loadCredentials, 2: the rollback's first read (this save's own value), 3: the re-read. + // A newer sign-in writes its own pair into the storage between those two reads; the + // write goes through the Map the reads answer from, so a read can never report a value + // the storage does not hold. + if (reads === 2) { + queueMicrotask(() => values.set(key, newer)) + } + return values.get(key) + }) + vi.spyOn(globalThis, "fetch").mockResolvedValue(rotatedTokenResponse()) + + const staleSave = manager.getAccessToken() + await vi.waitFor(() => expect(context.secrets.store).toHaveBeenCalledOnce()) + manager["credentialsGeneration"]++ + releaseStore() + await expect(staleSave).resolves.toBeNull() + + // This save's own rotated pair is what the rollback's first read compared against. + expect(written).toContain("rotated-refresh") + expect(reads).toBe(3) + expect(context.secrets.delete).not.toHaveBeenCalled() + // The pair the newer sign-in wrote is what survives: the rollback left it alone rather + // than deleting it or writing this save's own pair back over it. + expect(values.get(key)).toBe(newer) + }) }) diff --git a/src/integrations/kimi-code/oauth.ts b/src/integrations/kimi-code/oauth.ts index 0eb95815126..fa862de6ab4 100644 --- a/src/integrations/kimi-code/oauth.ts +++ b/src/integrations/kimi-code/oauth.ts @@ -72,17 +72,53 @@ class KimiCodeOAuthError extends Error { } } -async function postForm(endpoint: string, values: Record, signal?: AbortSignal): Promise { +/** The request deadline's own failure, typed so a timeout is distinguishable from a + * cancellation without reading its message. The name follows the timeout contract the + * repository already uses for provider timeouts (abort-signal.ts classifies a signal whose + * reason is named "TimeoutError", and openai.ts:700 treats that name as a timeout rather + * than a user cancellation); the message is the string the deadline already raised as a + * plain Error, so nothing that prints it sees new text. */ +class KimiCodeOAuthTimeoutError extends Error { + constructor() { + super("Kimi Code OAuth request timed out") + this.name = "TimeoutError" + } +} + +/** The cancellation contract shared with the provider layer: name AbortError, cause kept. */ +function createOAuthAbortError(cause?: unknown): Error { + const error = new Error("The Kimi Code OAuth request was aborted") + error.name = "AbortError" + if (cause !== undefined) error.cause = cause + return error +} + +/** A form POST whose caller-stop contract ends at the response headers. postForm detaches the + * abort forwarder as soon as the headers arrive, so an abort during the body read no longer + * cancels the underlying response: only the request deadline bounds that read, and a pair that + * is already on the wire is kept. `settle` clears the deadline timer and detaches whatever + * forwarder is still registered; on the no-response path it is the only cleanup that runs. */ +interface CancellingPost { + response: Response + settle: () => void +} + +async function postForm( + endpoint: string, + values: Record, + signal?: AbortSignal, +): Promise { const controller = new AbortController() const forwardAbort = () => controller.abort(signal?.reason) if (signal?.aborted) forwardAbort() else signal?.addEventListener("abort", forwardAbort, { once: true }) - const timeout = setTimeout( - () => controller.abort(new Error("Kimi Code OAuth request timed out")), - OAUTH_REQUEST_TIMEOUT_MS, - ) + const timeout = setTimeout(() => controller.abort(new KimiCodeOAuthTimeoutError()), OAUTH_REQUEST_TIMEOUT_MS) + const settle = () => { + signal?.removeEventListener("abort", forwardAbort) + clearTimeout(timeout) + } try { - return await fetch(endpoint, { + const response = await fetch(endpoint, { method: "POST", headers: { Accept: "application/json", @@ -91,12 +127,28 @@ async function postForm(endpoint: string, values: Record, signal body: new URLSearchParams(values).toString(), signal: controller.signal, }) - } finally { - clearTimeout(timeout) + // The caller's stop no longer abandons the body: only the request deadline bounds the rest of + // the read, and a pair that is already on the wire is kept. signal?.removeEventListener("abort", forwardAbort) + return { response, settle } + } catch (error) { + // Nothing will read a body from a POST that never produced a response, so the forwarder + // is detached on this path and nothing else. + settle() + // Classify from the CALLER signal: only a rejection that came from the caller's own abort + // is normalized. The caller's reason can be an ordinary Error and fetch forwards it + // verbatim, and an independent OAuth/network failure that merely races the abort must be + // thrown unchanged. The internal timeout is never normalized here: timeout errors are + // rethrown as they are so callers can distinguish a stalled POST from a cancellation. + const callerAborted = signal?.aborted === true + const isCallerAbortRejection = + callerAborted && (error === signal?.reason || (error instanceof Error && error.name === "AbortError")) + if (isCallerAbortRejection) { + throw createOAuthAbortError(error) + } + throw error } } - async function readOAuthError(response: Response): Promise { const text = await response.text() try { @@ -108,17 +160,21 @@ async function readOAuthError(response: Response): Promise { } export async function requestDeviceAuthorization(signal?: AbortSignal) { - const response = await postForm( + const { response, settle } = await postForm( KIMI_CODE_OAUTH_CONFIG.deviceAuthorizationEndpoint, { client_id: KIMI_CODE_OAUTH_CONFIG.clientId }, signal, ) - if (!response.ok) throw await readOAuthError(response) - return deviceAuthorizationSchema.parse(await response.json()) + try { + if (!response.ok) throw await readOAuthError(response) + return deviceAuthorizationSchema.parse(await response.json()) + } finally { + settle() + } } async function requestDeviceToken(deviceCode: string, signal?: AbortSignal): Promise { - const response = await postForm( + const { response, settle } = await postForm( KIMI_CODE_OAUTH_CONFIG.tokenEndpoint, { grant_type: KIMI_CODE_OAUTH_CONFIG.deviceGrantType, @@ -127,32 +183,51 @@ async function requestDeviceToken(deviceCode: string, signal?: AbortSignal): Pro }, signal, ) - if (!response.ok) throw await readOAuthError(response) - const tokens = tokenResponseSchema.parse(await response.json()) - if (!tokens.refresh_token) throw new Error("Kimi Code OAuth did not return a refresh token") - return { - type: providerIdentifiers.kimiCode, - accessToken: tokens.access_token, - refreshToken: tokens.refresh_token, - expiresAt: Date.now() + tokens.expires_in * 1000, - tokenType: tokens.token_type, + try { + if (!response.ok) throw await readOAuthError(response) + const tokens = tokenResponseSchema.parse(await response.json()) + if (!tokens.refresh_token) throw new Error("Kimi Code OAuth did not return a refresh token") + return { + type: providerIdentifiers.kimiCode, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresAt: Date.now() + tokens.expires_in * 1000, + tokenType: tokens.token_type, + } + } finally { + settle() } } -export async function refreshKimiCodeAccessToken(credentials: KimiCodeCredentials): Promise { - const response = await postForm(KIMI_CODE_OAUTH_CONFIG.tokenEndpoint, { - grant_type: "refresh_token", - refresh_token: credentials.refreshToken, - client_id: KIMI_CODE_OAUTH_CONFIG.clientId, - }) - if (!response.ok) throw await readOAuthError(response) - const tokens = tokenResponseSchema.parse(await response.json()) - return { - type: providerIdentifiers.kimiCode, - accessToken: tokens.access_token, - refreshToken: tokens.refresh_token ?? credentials.refreshToken, - expiresAt: Date.now() + tokens.expires_in * 1000, - tokenType: tokens.token_type ?? credentials.tokenType, +export async function refreshKimiCodeAccessToken( + credentials: KimiCodeCredentials, + signal?: AbortSignal, +): Promise { + // The caller's signal aborts the token POST itself, not just the caller's wait: a cancelled + // task must not keep a refresh request in flight before the server answers. + const { response, settle } = await postForm( + KIMI_CODE_OAUTH_CONFIG.tokenEndpoint, + { + grant_type: "refresh_token", + refresh_token: credentials.refreshToken, + client_id: KIMI_CODE_OAUTH_CONFIG.clientId, + }, + signal, + ) + try { + // The provider rotated the refresh token when it answered, so the pair in this body is the + // only copy of it. The save runs through the ownership check below. + if (!response.ok) throw await readOAuthError(response) + const tokens = tokenResponseSchema.parse(await response.json()) + return { + type: providerIdentifiers.kimiCode, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token ?? credentials.refreshToken, + expiresAt: Date.now() + tokens.expires_in * 1000, + tokenType: tokens.token_type ?? credentials.tokenType, + } + } finally { + settle() } } @@ -179,7 +254,23 @@ export class KimiCodeOAuthManager { private context: ExtensionContext | null = null private credentials: KimiCodeCredentials | null = null private state: KimiCodeOAuthState = { status: "idle" } - private refreshPromise: Promise | null = null + // One shared refresh POST with independent waiter cancellation: each caller races the shared + // promise against its own signal. The POST is never aborted on a detach - the server rotates the + // refresh token when it answers, so a pair on the wire is the only copy of it. + private refreshPromise: Promise | null = null + private refreshController: AbortController | null = null + private refreshWaiters: Set<{ signal?: AbortSignal }> | null = null + // Commit phase: the controller of the refresh whose token POST has resolved and whose rotated pair + // is on its way to SecretStorage. It must not lose ownership of that write: the rotated refresh + // token is issued once, so rolling back the only copy strands the next launch at the sign-in + // screen. A replacement refresh waits for this phase to end instead of racing the store. + private refreshCommitting: AbortController | null = null + private credentialWrites: Promise = Promise.resolve() + // Sign-out fence: while credentials are being cleared no new refresh may start, so the drain + // in clearCredentials() terminates and a caller cannot re-install what its delete removes. The + // fence is a count rather than a flag because two sign-outs can overlap - the first one's + // finally must not open the gate while the second is still draining its own delete. + private clearFenceCount = 0 private pollingPromise: Promise | null = null private pollingController: AbortController | null = null private credentialsGeneration = 0 @@ -206,20 +297,58 @@ export class KimiCodeOAuthManager { } } - private async saveCredentials( - credentials: KimiCodeCredentials, - isCurrent: () => boolean = () => true, - ): Promise { + /** + * Queue one task on the credential chain. SecretStorage keeps no ordering of its own, so two + * writes can land out of order and the earlier-issued one can overwrite the newer value. Every + * store, and every delete that a save decides on, runs here one at a time. + */ + private queueCredentialWrite(task: () => Promise): Promise { + const queued = this.credentialWrites.then(task) + this.credentialWrites = queued.catch(() => false) + return queued + } + + private saveCredentials(credentials: KimiCodeCredentials, isCurrent: () => boolean = () => true): Promise { + return this.queueCredentialWrite(() => this.writeCredentials(credentials, isCurrent)) + } + + private async writeCredentials(credentials: KimiCodeCredentials, isCurrent: () => boolean): Promise { if (!this.context) throw new Error("Kimi Code OAuth manager is not initialized") if (!isCurrent()) return false const serialized = JSON.stringify(credentials) - await this.context.secrets.store(KIMI_CODE_CREDENTIALS_KEY, serialized) + try { + await this.context.secrets.store(KIMI_CODE_CREDENTIALS_KEY, serialized) + } catch (error) { + // Ownership is re-read here: a sign-in cancelled while this store was in flight lost its + // pair, so the fallback below must not install it or claim the manager is authenticated. + // A refresh that still owns its result keeps the pair: the server rotated it once, and + // dropping it would strand the next launch at the sign-in screen. + if (!isCurrent()) throw error + // The server already rotated the pair, so a failed store must not discard it: it stays in + // memory, the next request keeps working, and the next save retries the store. + this.credentials = credentials + this.state = { status: "authenticated" } + throw error + } if (!isCurrent()) { - if ((await this.context.secrets.get(KIMI_CODE_CREDENTIALS_KEY)) === serialized) { + // The rollback is read, compare, delete on a SecretStorage that has no compare-and-delete, so the + // value can change after it is read. The read is repeated immediately before the delete: a newer + // sign-in or replacement save that lands in between is caught before the delete is issued instead + // of being removed by it. A generation re-check cannot stand in for that - this branch is only + // reached because the caller already lost ownership - and without a CAS primitive the window + // narrows but never closes: a write that lands after the second read, or from another extension + // host sharing the same secret, can still be removed by the delete already in flight. The + // credential chain orders every write this host makes; a second host sharing the secret is + // outside it, which is the residual window this comment records. + const stored = await this.context.secrets.get(KIMI_CODE_CREDENTIALS_KEY) + if (stored === serialized && (await this.context.secrets.get(KIMI_CODE_CREDENTIALS_KEY)) === serialized) { await this.context.secrets.delete(KIMI_CODE_CREDENTIALS_KEY) } return false } + // Install under a new generation: a delayed invalid_grant from an older refresh + // (whose captured generation is now stale) can no longer clear what this save put in. + this.credentialsGeneration++ this.credentials = credentials this.state = { status: "authenticated" } return true @@ -228,49 +357,186 @@ export class KimiCodeOAuthManager { async clearCredentials(): Promise { this.credentialsGeneration++ this.cancelAuthorization() - const refreshPromise = this.refreshPromise - if (refreshPromise) await refreshPromise.catch(() => null) - await this.context?.secrets.delete(KIMI_CODE_CREDENTIALS_KEY) - this.credentials = null - this.state = { status: "idle" } + // Sign-out fences the refresh path. The capture-and-await only waited for the refresh that + // existed at entry, so a refresh started during that await could still store credentials + // after the delete. Holding the fence across the await closes that window instead of + // re-polling for a refresh that cannot appear: the only startRefresh() call site is + // getAccessToken(), downstream of the fence check below, so while the fence is held no new + // refresh can begin and the entry-captured one is the only work the delete has to wait for. + // A second sign-out raises the count, so its own finally is the one that opens the gate. + this.clearFenceCount++ + try { + const refreshPromise = this.refreshPromise + if (refreshPromise) { + await refreshPromise.catch(() => null) + } + // The delete stays outside the write chain: the fence already keeps a refresh from starting, + // and the host's own secret sequencer orders this delete against a sign-in write (the two + // callers cannot interleave). Putting it on the chain would invert the sign-out-wins rows. + await this.context?.secrets.delete(KIMI_CODE_CREDENTIALS_KEY) + this.credentials = null + this.state = { status: "idle" } + } finally { + this.clearFenceCount-- + } } async isAuthenticated(): Promise { return (await this.getAccessToken()) !== null } - async getAccessToken(forceRefresh = false): Promise { + async getAccessToken(forceRefresh = false, signal?: AbortSignal): Promise { const credentials = await this.loadCredentials() + // Cancellation is checked before any early answer, including the empty-credentials one: a caller + // that cancelled while the secret read was pending must reach the cancellation. Answering null + // here surfaces as the sign-in error in the caller's resolveAccessToken, and its post-preparation + // throwIfAborted never runs because prepareRequest already threw. A caller that arrives + // mid-sign-out has no token to be served either: starting a refresh would duplicate the one the + // sign-out is draining and could re-install what its delete removes. + if (signal?.aborted) throw createOAuthAbortError() + // The fence is read before the cached answer: during sign-out the cached pair is still in + // memory while its delete is queued, so serving it would hand out a token being removed. + if (this.clearFenceCount > 0) return null if (!credentials) return null if (!forceRefresh && Date.now() < credentials.expiresAt - TOKEN_EXPIRY_BUFFER_MS) { return credentials.accessToken } - if (!this.refreshPromise) { - const generation = this.credentialsGeneration - this.refreshPromise = refreshKimiCodeAccessToken(credentials) - .then(async (next) => { - if (!(await this.saveCredentials(next, () => generation === this.credentialsGeneration))) - return null - return next - }) - .catch(async (error) => { - if (error instanceof KimiCodeOAuthError && error.code === "invalid_grant") { + // A pending refresh whose controller was already aborted can never settle successfully: + // start a replacement even if the old promise has not run its finally yet. A refresh that + // is committing its own write is the exception - it still settles with that write's token. + if (!this.refreshPromise || (this.refreshController?.signal.aborted && !this.refreshCommitting)) { + this.startRefresh(credentials) + } + return this.awaitRefresh(signal) + } + + /** Start the shared refresh POST; callers join it through awaitRefresh(). */ + private startRefresh(credentials: KimiCodeCredentials): void { + const generation = this.credentialsGeneration + const controller = new AbortController() + this.refreshController = controller + this.refreshWaiters = new Set() + // Only this refresh may change persisted state: its captured generation must still be current + // and its controller must not have been cancelled. A replacement refresh can start only after + // this refresh's controller was aborted (the check in getAccessToken), so the cancellation half + // is what keeps a cancelled refresh from advancing the generation while a replacement that + // captured the same generation is still storing - without it, that replacement would fail its + // own post-store check and delete the credentials it had just written. The commit phase is the + // one window where a cancellation no longer revokes ownership: the write it would roll back is + // the rotated pair this very refresh obtained, and no later POST can re-issue it. + const ownsThisRefresh = () => + generation === this.credentialsGeneration && + this.refreshController === controller && + (this.refreshCommitting === controller || !controller.signal.aborted) + this.refreshPromise = refreshKimiCodeAccessToken(credentials, controller.signal) + .then(async (next) => { + // A pair that arrives after this refresh was replaced is dropped: a replacement was + // started because this POST looked dead, and its answer owns the stored value now. + if (this.refreshController !== controller) return null + // The POST resolved, so the save that follows owns its write until it settles. + this.refreshCommitting = controller + if (!(await this.saveCredentials(next, ownsThisRefresh))) return null + return next.accessToken + }) + .catch(async (error) => { + // A stale refresh must not clear credentials a newer sign-in installed: the + // generation only changes when a save lands or credentials are cleared, so a + // mismatch here means this POST's verdict belongs to superseded credentials. + // The clear runs on the credential chain, and the generation is re-checked inside the + // queued task: a save that queued before this verdict must not be deleted by it. + if (error instanceof KimiCodeOAuthError && error.code === "invalid_grant") { + await this.queueCredentialWrite(async () => { + if (generation !== this.credentialsGeneration) return false this.credentialsGeneration++ await this.context?.secrets.delete(KIMI_CODE_CREDENTIALS_KEY) this.credentials = null this.state = { status: "idle" } - } - return null - }) - .finally(() => { - this.refreshPromise = null - }) + return true + }) + } + // The request deadline is the one failure re-raised rather than answered with null: it is + // typed, and answering null for it would reach the caller as the generic "sign in from + // provider settings" error even though the pair is intact and a retry could succeed. + if (error instanceof KimiCodeOAuthTimeoutError) throw error + // Waiter detachment does not abort the shared POST. This guard covers an abort from + // another source, and reaches each caller as one instead of the "not authenticated" null path. + if (controller.signal.aborted) throw createOAuthAbortError() + return null + }) + .finally(() => { + // Only the refresh that is committing may clear the marker. An older refresh can still + // be draining its invalid_grant delete when a replacement has already started saving; + // an unconditional reset here would drop the replacement's marker, and its next + // ownership check would then roll back the rotated pair it had just stored. + if (this.refreshCommitting === controller) this.refreshCommitting = null + // A replacement refresh may have started while this one was settling: only the + // still-current refresh may clear the shared state, so a replaced refresh cannot + // drop the response-phase flag of the one that took over. + if (this.refreshController !== controller) return + this.refreshPromise = null + this.refreshController = null + this.refreshWaiters = null + }) + // Callers observe the rejection through awaitRefresh(); this guard keeps a refresh whose + // waiters all detached from surfacing as an unhandled rejection in the extension host. + void this.refreshPromise.catch(() => {}) + } + + /** + * Wait for the shared refresh with this caller's own cancellation: an abort detaches only this + * waiter and the shared POST keeps running while another caller still needs it. + */ + private awaitRefresh(signal?: AbortSignal): Promise { + const promise = this.refreshPromise + const waiters = this.refreshWaiters + if (!promise) return Promise.resolve(null) + if (!waiters) return promise + + const waiter: { signal?: AbortSignal } = { signal } + waiters.add(waiter) + if (!signal) { + // A caller without an AbortSignal cannot detach: keep it registered until the shared + // POST settles so an aborting signaled caller cannot cancel a refresh this caller needs. + return promise.finally(() => waiters.delete(waiter)) + } + if (signal.aborted) { + // A waiter that stops only drops its own wait: the shared POST is not cancelled, because a + // token the server already rotated cannot be produced again. + waiters.delete(waiter) + return Promise.reject(createOAuthAbortError(signal.reason)) } - return (await this.refreshPromise)?.accessToken ?? null + return new Promise((resolve, reject) => { + let settled = false + const cleanup = () => { + settled = true + waiters.delete(waiter) + signal.removeEventListener("abort", onAbort) + } + const onAbort = () => { + if (settled) return + cleanup() + // The caller's own reason is kept as the cause, so the provider layer can report what + // stopped the request instead of a bare abort. + reject(createOAuthAbortError(signal.reason)) + } + signal.addEventListener("abort", onAbort, { once: true }) + void promise.then( + (value) => { + if (settled) return + cleanup() + resolve(value) + }, + (error) => { + if (settled) return + cleanup() + reject(error) + }, + ) + }) } - async forceRefreshAccessToken(): Promise { - return this.getAccessToken(true) + async forceRefreshAccessToken(signal?: AbortSignal): Promise { + return this.getAccessToken(true, signal) } async startAuthorization(): Promise { diff --git a/src/test-utils/__tests__/errors.spec.ts b/src/test-utils/__tests__/errors.spec.ts new file mode 100644 index 00000000000..c666b5e9774 --- /dev/null +++ b/src/test-utils/__tests__/errors.spec.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest" + +import { captureError } from "../errors" + +describe("error capture utility", () => { + it("returns the rejecting Error instance untouched", async () => { + const original = new Error("provider failed") + + expect(await captureError(Promise.reject(original))).toBe(original) + }) + + it("re-wraps a non-Error rejection so the original failure message stays visible", async () => { + const captured = await captureError(Promise.reject("plain string failure")) + + expect(captured).toBeInstanceOf(Error) + expect(captured.message).toBe("plain string failure") + }) + + it("rejects when the operation resolves, because resolving violates the contract", async () => { + await expect(captureError(Promise.resolve("value"))).rejects.toThrow("Expected the operation to reject") + }) +}) diff --git a/src/test-utils/errors.ts b/src/test-utils/errors.ts new file mode 100644 index 00000000000..67d897b2423 --- /dev/null +++ b/src/test-utils/errors.ts @@ -0,0 +1,17 @@ +/** + * Captures the rejection of an operation as an `Error`. + * + * Provider abort normalization always throws an `Error`, but an awaited + * operation is typed `unknown`, so the guard keeps strict typing without + * casts. A non-Error rejection is re-wrapped so the original failure message + * stays visible, and a resolving operation — the contract violation the + * surrounding test exists to catch — becomes a failing assertion. + */ +export async function captureError(operation: Promise): Promise { + try { + await operation + } catch (error) { + return error instanceof Error ? error : new Error(String(error)) + } + throw new Error("Expected the operation to reject") +}