From c6f18d3e15febd1fb0d89055f6ff15aefe16a81a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:43:42 +0800 Subject: [PATCH 1/5] feat(api): add the shared abort, timeout and error plumbing (#1311 split u0) Unit u0 of the split plan in #2799. It carries the shared helpers that the provider units of #1311 consume, and nothing provider-specific. - abort-signal.ts: mergeAbortSignalAndTimeout, rejectOnAbort, and the timeout classification helpers (isTimeoutAbort, createTimeoutError). - error-handler.ts: handleOpenAIRequestError keeps an HTTP failure's identity over a racing abort and reports a deadline as TimeoutError. - request-timeout.ts: getRequestTimeoutMs for the per-request SDK timeout. - test-utils/errors.ts: captureError, used by the cancellation rows of the provider units. Evidence: 643 rows across the utils and test-utils specs pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. --- .../utils/__tests__/abort-signal.spec.ts | 19 +++ .../utils/__tests__/error-handler.spec.ts | 123 +++++++++++++++++- .../utils/__tests__/request-timeout.spec.ts | 11 ++ src/api/providers/utils/abort-signal.ts | 11 +- src/api/providers/utils/error-handler.ts | 44 +++++++ src/api/providers/utils/request-timeout.ts | 14 +- src/eslint-suppressions.json | 7 +- src/test-utils/__tests__/errors.spec.ts | 22 ++++ src/test-utils/errors.ts | 17 +++ 9 files changed, 250 insertions(+), 18 deletions(-) create mode 100644 src/test-utils/__tests__/errors.spec.ts create mode 100644 src/test-utils/errors.ts diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550a..7159732c59e 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -600,6 +600,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..05fa373ae9f 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -159,8 +159,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 +312,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/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/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") +} From 8dc468bd627c66979ab9ed72fe9af7a9af1aaa1c Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:13:19 +0800 Subject: [PATCH 2/5] fix(api): clear the abort-plumbing lint and knip gates (#1311 split u0) The shared abort, timeout and error helpers landed with two required checks red: compile (eslint) and knip. This commit clears both without re-inflating suppressions, and adds the test that the guard was missing. compile: ESLint 9.39.5 count-based suppressions are all-or-nothing. In suppressions-service.js:171 a file is suppressed only while violationsCount <= suppressionsCount, and :177 rewrites the remainder only when violationsCount < suppressionsCount, so a file that is over its count reports every violation rather than the excess. The previous commit lowered base-openai-compatible-provider.ts from 6 to 5 while the file still held 6 assertions, and deleted the kimi-code.spec.ts entry while that file still held 1, which turned all 7 into reported errors. The fix retypes only what costs nothing. modelInfo goes from any to ModelInfo: the type is already imported in this file and calculateApiCostOpenAI in shared/cost.ts is its only consumer, so the assertion disappears without new machinery and the file drops to exactly its remaining count of 5. The kimi mock reaches the handler's protected client by bracket access, with the seam narrowed to the one create call it replaces - the shape anthropic-vertex.spec.ts:277 and :581 already use. Bracket access alone was not enough: it produced a fresh TS2739 on the ChatCompletionMessage mock literal, so the seam type is load-bearing and not decoration. Its suppression entry stays deleted because the file now asserts nothing, so a count of zero is the honest count rather than an allowance. The other five assertions stay suppressed on purpose: they sit on lines the suite never executes. Coverage over the 18 provider and api specs reports zero hits for both thinking assignments (lines 103 and 225) and for both base_resp throws (lines 136 and 234). Retyping an unexecuted line only moves it into the mutation cell, where no existing test could kill a mutant, and the file is upstream-owned (blame 6cfa82f57103, #11462) rather than part of this unit, as is the mock's owner (78c1410d1db9, #945). Type-checking adds nothing here either way: tsc over src reports the same diagnostics before and after this change. knip: handleOpenAIRequestError has no production importer in this unit - only error-handler.spec.ts imports it, and the request sites arrive with the later splits - so knip --production reports it while dev knip does not, which is the difference between the two runs rather than a finding about the code being wrong. Marked @internal with the reason: an intentional direct-test seam, the exception docs/development-quality-checks.md sanctions and abort-signal.ts:254 already uses in this same directory. The new row is coverage-closing, not a red-first repro: the status-first guard already behaved correctly, but no row reached it because none of the abort-awareness inputs carries a numeric status, so its early return had nothing executing it. It is not free-standing either: deleting the guard fails exactly this row - "expected 'AbortError' to be 'Error'" - while the other 49 rows keep passing. Suppression debt moves down, and the baseline is the merge-base dd30249147159dad2d410845527a14a8e55d1463, which is what AGENTS.md states the rule against - not the PR head: 261 entries and 2844 suppressed occurrences there, 260 and 2842 here. The provider entry stays at 5 and the kimi entry stays gone, so a prune run leaves the count map unchanged and only reflows indentation. Cost against that same base, on the mutation gate's own measure: this cell reports 19 changed executable lines against a cap of 500, one more than the 18 the previous commit measured, and that one line is the retyped signature. Not closed by this commit: - the five remaining provider assertions, which are worth typing only once tests execute the thinking and base_resp paths, and only next to the splits that make them live code - production importers for handleOpenAIRequestError, which arrive with split/1311-u1-openai-family and its siblings - the whole-file typed removal for the provider, sketched during this investigation: it clears all 5 remaining assertions but raises the cell from 18 to 33 changed executable lines, so it should land after the two unexecuted paths have tests of their own --- src/api/providers/__tests__/kimi-code.spec.ts | 8 +++++++- .../base-openai-compatible-provider.ts | 2 +- .../utils/__tests__/error-handler.spec.ts | 18 ++++++++++++++++++ src/api/providers/utils/error-handler.ts | 4 ++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/api/providers/__tests__/kimi-code.spec.ts b/src/api/providers/__tests__/kimi-code.spec.ts index a190ef3e7b7..e8ad4c28e82 100644 --- a/src/api/providers/__tests__/kimi-code.spec.ts +++ b/src/api/providers/__tests__/kimi-code.spec.ts @@ -10,6 +10,9 @@ const { mockGetAccessToken, mockForceRefreshAccessToken, mockGetModels } = vi.ho mockGetModels: vi.fn(), })) +/** The one production call this test replaces: a non-streaming chat completion. */ +type CompletionCreateSeam = { create: (body: unknown) => Promise } + vi.mock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { getAccessToken: mockGetAccessToken, @@ -138,7 +141,10 @@ describe("KimiCodeHandler", () => { 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") + // `client` is protected on the handler, so the mock reaches it by bracket + // access; the seam is narrowed to the single create call the mock replaces + // (same shape as anthropic-vertex.spec.ts:277/581) instead of widening to `any`. + .spyOn(handler["client"].chat.completions as unknown as CompletionCreateSeam, "create") .mockRejectedValueOnce(unauthorized) .mockResolvedValueOnce({ choices: [{ message: { content: "retried" } }] }) diff --git a/src/api/providers/base-openai-compatible-provider.ts b/src/api/providers/base-openai-compatible-provider.ts index b177726f852..9211c1d4412 100644 --- a/src/api/providers/base-openai-compatible-provider.ts +++ b/src/api/providers/base-openai-compatible-provider.ts @@ -192,7 +192,7 @@ export abstract class BaseOpenAiCompatibleProvider } } - protected processUsageMetrics(usage: any, modelInfo?: any): ApiStreamUsageChunk { + protected processUsageMetrics(usage: any, modelInfo?: ModelInfo): ApiStreamUsageChunk { const inputTokens = usage?.prompt_tokens || 0 const outputTokens = usage?.completion_tokens || 0 const cacheWriteTokens = usage?.prompt_tokens_details?.cache_write_tokens || 0 diff --git a/src/api/providers/utils/__tests__/error-handler.spec.ts b/src/api/providers/utils/__tests__/error-handler.spec.ts index 436f05d86a6..17dfa0b1a1d 100644 --- a/src/api/providers/utils/__tests__/error-handler.spec.ts +++ b/src/api/providers/utils/__tests__/error-handler.spec.ts @@ -448,6 +448,24 @@ describe("handleOpenAIRequestError (abort awareness)", () => { expect((result as Error & { cause?: unknown }).cause).toBe(original) }) + it("keeps a terminal HTTP failure status-classified when the caller has already aborted", () => { + // Coverage-closing row for the status-first early return in handleOpenAIRequestError, not + // repro: the guard already works, but no row above reaches it because none of their inputs + // carries a numeric status, so that early return had nothing executing it. A 401/429 that + // lands in the same tick as the caller's stop must keep its own identity - backoff and the + // UI read the top-level status, and masking it as AbortError would hide the provider error. + const original = Object.assign(new Error("Too many requests"), { status: 429 }) + const controller = new AbortController() + controller.abort() + + const result = handleOpenAIRequestError(original, "OpenAI", controller.signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("Error") + expect(result.message).toBe("OpenAI completion error: Too many requests") + expect((result as Error & { status?: number }).status).toBe(429) + }) + it("normalizes the SDK user-abort error when no signal was passed", () => { const result = handleOpenAIRequestError(new APIUserAbortError(), "Zai") diff --git a/src/api/providers/utils/error-handler.ts b/src/api/providers/utils/error-handler.ts index 96ce8e1fbd8..4adffa14fb8 100644 --- a/src/api/providers/utils/error-handler.ts +++ b/src/api/providers/utils/error-handler.ts @@ -176,6 +176,10 @@ export function handleOpenAIError(error: unknown, providerName: string): Error { * 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. + * + * @internal Exported for the provider request sites that adopt it in the follow-up + * #1311 splits; direct contract tests cover it here (docs/development-quality-checks.md + * "intentional direct-test seam"). */ export function handleOpenAIRequestError( error: unknown, From 8631311862fe0726b9d8fcaba84f0fc111b0b4bf Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:45:22 +0800 Subject: [PATCH 3/5] feat(api): honour caller cancellation in the openai family (#1311 split u1) Unit u1 of the split plan in #2799. It carries openai.ts and the OpenAI-compatible base, with their cancellation rows. undefined- The two abort contracts stay apart: the caller's signal goes to the undefinedrequest each route issues, and a mid-flight abort or a raw SDK abort becomes the provider's contract error with the failure kept as the cause. Each request site normalizes its own failure, including the Responses completion. undefined- A stream failure is a flag beside its value, so a rejection carrying undefined`undefined` still reaches the handler, and the recorded usage is yielded before the error. A usage frame the SDK already returned is recorded before the abort break. undefined- The Responses completion forwards the merged caller and deadline undefinedsignal, so the deadline stays armed while the SDK reads the JSON body. - Request creation is raced against the request signal, so a 429 backoff sleep cannot outlast a deadline. undefinedEvidence: openai, base-provider and cancellation rows 725 pass; tsc undefined--noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. This commit also drops the provider entry in src/eslint-suppressions.json from five to four, because rewriting the provider is what made the fifth count stale: the earlier cell fixed one of the six positions the merge-base entry covered, and this commit's rewrite removes another, so four violations remain against an entry that still says five. eslint treats a surplus entry as an error in its own right: suppressions-service.js line 171 suppresses a file when its violations are at most its count, line 177 rewrites the remainder when they are strictly fewer, and once nothing is left to suppress the run exits two with the message about suppressions that no longer occur, which is what the lint step would have reported as soon as the other error was gone. The count moves down and is the only change in the file. The file is written with the single-tab indentation the committed copy uses, because the writer's own output is two-space and would have churned every line; prettier --check on the file exits 0, and a prune run afterwards changes no count - its writer reformats indentation, so the check that matters compares the parsed counts rather than the bytes. --- ...openai-compatible-provider-timeout.spec.ts | 51 +- .../base-openai-compatible-provider.spec.ts | 786 +++++++++++++++++- src/api/providers/__tests__/fireworks.spec.ts | 2 + src/api/providers/__tests__/friendli.spec.ts | 8 + src/api/providers/__tests__/mimo.spec.ts | 36 +- .../__tests__/openai.cancellation.spec.ts | 333 ++++++++ src/api/providers/__tests__/openai.spec.ts | 694 +++++++++++++++- src/api/providers/__tests__/sambanova.spec.ts | 2 + .../base-openai-compatible-provider.ts | 213 +++-- src/api/providers/openai.ts | 346 ++++++-- src/eslint-suppressions.json | 2 +- 11 files changed, 2346 insertions(+), 127 deletions(-) create mode 100644 src/api/providers/__tests__/openai.cancellation.spec.ts 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.spec.ts b/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts index 1ffd63aa12a..67bbadccb74 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,23 @@ // npx vitest run api/providers/__tests__/base-openai-compatible-provider.spec.ts 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 +302,500 @@ 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 pass the metadata abort signal to the client request", async () => { + const controller = new AbortController() + mockCreate.mockImplementationOnce(() => asyncStreamFrom([])) + + const stream = handler.createMessage("system prompt", [], { + taskId: "test-task", + abortSignal: controller.signal, + }) + await stream.next() + + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), { + signal: controller.signal, + }) + }) + + 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 pass the completePrompt abort signal to the client request", 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") + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "test-model" }), { + signal: controller.signal, + }) + }) + + it("should merge the completePrompt abort signal and timeoutMs into one request signal", async () => { + const controller = new AbortController() + mockCreate.mockResolvedValueOnce({ choices: [{ message: { content: "response" } }] }) + + await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 5000 }) + + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + 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) + }) + + 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 +863,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 +991,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__/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__/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..b77d2feaec1 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, @@ -20,7 +20,10 @@ import { import { Package } from "../../../shared/package" import { makeApiHandlerOptions, makeCreateMessageMetadata } from "../../../test-utils/api" 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 +44,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 +507,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 +1368,551 @@ 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 while passing the completePrompt abort signal", 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" } }] }) + + await expect(azureHandler.completePrompt("test prompt", { abortSignal: controller.signal })).resolves.toBe( + "response", + ) + + expect(capturedRequestOptions()).toMatchObject({ path: "/models/chat/completions" }) + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + it("should pass the completePrompt abort signal to the request", 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") + expect(capturedRequestOptions()?.signal).toBe(controller.signal) + }) + + 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" } }] }) + await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 5000 }) + const requestOptions = mockCreate.mock.calls.at(-1)?.[1] + expect(requestOptions?.signal).toBeInstanceOf(AbortSignal) + expect(requestOptions?.signal.aborted).toBe(false) + // The merged signal must follow the caller's controller: a regression + // that drops options.abortSignal (keeping only the timeout signal) + // would stop aborting here and fail the test. + controller.abort() + expect(requestOptions?.signal.aborted).toBe(true) + // A positive timeoutMs must be forwarded as the per-request SDK timeout. + expect(requestOptions?.timeout).toBe(5000) + }) + + 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 +3382,15 @@ describe("OpenAiHandler Responses API (openAiUseResponsesApi)", () => { store: false, service_tier: "flex", }), - { signal: controller.signal, timeout: 1234 }, + expect.anything(), ) + // The request carries the merged caller and deadline signal, so the deadline stays armed + // while the SDK reads the JSON body. + const responseOptions = mockResponsesCreate.mock.calls[0][1] + expect(responseOptions.timeout).toBe(1234) + expect(responseOptions.signal?.aborted).toBe(false) + controller.abort() + expect(responseOptions.signal?.aborted).toBe(true) expectNoLoneSurrogates(mockResponsesCreate.mock.calls[0][0]) }, ) 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/base-openai-compatible-provider.ts b/src/api/providers/base-openai-compatible-provider.ts index 9211c1d4412..f22fa3e0b51 100644 --- a/src/api/providers/base-openai-compatible-provider.ts +++ b/src/api/providers/base-openai-compatible-provider.ts @@ -6,14 +6,17 @@ 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 { createAbortError, mergeAbortSignalAndTimeout, rejectOnAbort, throwIfAborted } from "./utils/abort-signal" +import { getRequestTimeoutMs } from "./utils/request-timeout" type BaseOpenAiCompatibleProviderOptions = ApiHandlerOptions & { providerName: string @@ -23,6 +26,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 +77,7 @@ export abstract class BaseOpenAiCompatibleProvider }) } - protected createStream( + protected async createStream( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, @@ -103,11 +113,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 +124,27 @@ 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. + const requestConfig = new RequestConfigBuilder().setAbortSignal(metadata).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) { + throw handleOpenAIRequestError(error, this.providerName, signal) + } const matcher = new TagMatcher( ["think", "thought"], @@ -129,64 +158,121 @@ 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 } + // 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 +298,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 +313,31 @@ 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) + const requestSignal = mergeAbortSignalAndTimeout(options?.abortSignal, 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 +349,7 @@ 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) } } diff --git a/src/api/providers/openai.ts b/src/api/providers/openai.ts index f54a8853696..ba1e56f6a78 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,29 @@ 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. + const requestSignal = mergeAbortSignalAndTimeout(options?.abortSignal, 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 + } assertResponsesApiSuccess(response) return response.output .flatMap((item) => @@ -571,19 +665,50 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl requestOptions = this.withExtraBody(requestOptions) let response + const requestConfig = this.buildCompletePromptRequestConfig(isAzureAiInference, options) 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, + ) + } + + // 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. + // 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 +723,44 @@ 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, + ): OpenAI.RequestOptions { + const requestTimeout = getRequestTimeoutMs(options?.timeoutMs) + return ( + new RequestConfigBuilder() + .setOption("path", isAzureAiInference ? OPENAI_AZURE_AI_INFERENCE_PATH : undefined) + .setOption("signal", mergeAbortSignalAndTimeout(options?.abortSignal, options?.timeoutMs)) + .setOption("timeout", requestTimeout) + .build() ?? {} + ) + } + private async *handleO3FamilyMessage( modelId: string, systemPrompt: string, @@ -606,10 +769,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 +803,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 +851,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 +880,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 +934,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 +945,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 +962,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 +981,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/eslint-suppressions.json b/src/eslint-suppressions.json index 2c46065d858..3f5f43525f4 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -186,7 +186,7 @@ }, "api/providers/base-openai-compatible-provider.ts": { "@typescript-eslint/no-explicit-any": { - "count": 5 + "count": 4 } }, "api/providers/base-provider.ts": { From d6e0af33cd46716fab067cde6ebfbd9686ca9d6f Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:37:45 +0800 Subject: [PATCH 4/5] test(api): give the zai openai mock its abort-error export The api coverage lane fails at this head (CI job 143658284755, ubuntu test:coverage:api; the same failure repeats for #2803 at job 143661531345) on api/providers/__tests__/zai.spec.ts > ZAiHandler > API Methods > "should handle errors in completePrompt": the mock factory at zai.spec.ts:21-28 returns only a default export, while this unit's error path reads the named export APIUserAbortError (api/providers/base-openai-compatible-provider.ts:136, api/providers/openai.ts:706), so vitest's missing-export error replaces the asserted Z.ai message. This unit already stubbed that export in the four sibling specs it touched (fireworks +2/-0, friendli +8/-0, sambanova +2/-0, mimo +31/-5), but zai.spec.ts belongs to u2, so its mock stayed incomplete; u3 inherits this head and repeats the same failure. Fix: add the same two lines the sibling specs already use. Test-only; no production behaviour changes, and no suppression count moves. Gates (both sides): - before: vitest run --config vitest.api.config.ts --coverage in src/ -> RC=1, Test Files 1 failed | 128 passed (129), Tests 1 failed | 6245 passed | 2 skipped (6248), 19s (local Windows). CI ubuntu collected 1 failed | 6278 passed | 2 skipped (6281) in 80.86s for the same head; CI sits 33 tests higher on both heads with the same 129 files and the same 2 skipped. - after: the same command -> RC=0, Test Files 129 passed (129), Tests 6246 passed | 2 skipped (6248), 18s. - eslint --max-warnings=0 --no-warn-ignored on the changed file: RC=0. - prettier --check on the changed file: RC=0. - the compile lane is deliberately untouched: its single error (kimi-code.spec.ts:141 Unexpected any) is rooted in u0's suppression hunks (c6f18d3e15) and is held for the #2800 menu. Mutation-gate calibers (scripts/stryker-diff.mjs primitives, cap 500): - cell, base=91c6af4bb0c46f69333372125763ab0c2207da59 (this PR head): changedExecutableLines total 0, readSource=checkout and readSource=commit agree, because src/api/providers/__tests__/ paths are excluded from the manifest. - unit delta, base=c6f18d3e15febd1fb0d89055f6ff15aefe16a81a (u0 head, upstream): extension 228 -> 228, identical under both readSource values. - cumulative, base=dd30249147159dad2d410845527a14a8e55d1463 (merge-base with upstream main): extension 246 -> 246, identical under both readSource values. src/eslint-suppressions.json is byte-identical to the parent commit (git blob sha1 unchanged): no suppression entry was added, lowered or pruned here. Not closed by this commit: - local api-lane totals sit 33 tests below CI on both heads; the mechanism is unverified, and the CI job log carries no per-file test counts, so a file-by-file comparison cannot be made from it. - #2802's ancestry relative to u0 and u1 is unverified: fetching refs/pull/2802/head collided with a pre-existing stale refs/tmp/u2 ref. - whether these two lines auto-merge when u2 rebases its rewritten zai.spec.ts onto them is unverified. --- src/api/providers/__tests__/zai.spec.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/providers/__tests__/zai.spec.ts b/src/api/providers/__tests__/zai.spec.ts index 0a33e7ad66f..6ac3b0d415e 100644 --- a/src/api/providers/__tests__/zai.spec.ts +++ b/src/api/providers/__tests__/zai.spec.ts @@ -21,6 +21,8 @@ import { clearAllMocks } from "../../../test-utils/reset" 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 } } } }), From 6127541a58841f797eea6fcc954c5ac0ca0da993 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:48:13 +0800 Subject: [PATCH 5/5] feat(api): honour caller cancellation in kimi code and its oauth refresh (#1311 split u3) Unit u3 of the split plan in #2799. Stacked on u1 (#2801). - The Kimi Code handler forwards the caller's signal through model discovery and the completion request, and retries once after a 401 refresh. - The OAuth refresh keeps the pair the server rotated: a cancelled waiter no longer rolls back the write it was making, the shared POST is never aborted once sent, an older refresh cannot clear a newer one's commit marker, and every credential write runs on one chain. A store failure after a rotation keeps the pair in memory. - The invalid_grant clear runs on that chain with the generation re-checked inside. Evidence: kimi provider, oauth, fetcher and model-catalog rows 201 pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. --- .../tla/KimiOAuthRefresh.Variant.cfg | 5 + docs/architecture/tla/KimiOAuthRefresh.cfg | 5 + docs/architecture/tla/KimiOAuthRefresh.tla | 111 ++ .../kimi-code.oauth-cancellation.spec.ts | 131 ++ src/api/providers/__tests__/kimi-code.spec.ts | 341 ++++- .../__tests__/model-catalog-adapters.spec.ts | 2 +- .../fetchers/__tests__/kimi-code.spec.ts | 54 + src/api/providers/fetchers/kimi-code.ts | 11 +- src/api/providers/kimi-code.ts | 60 +- .../kimi-code/__tests__/oauth.spec.ts | 1203 ++++++++++++++++- src/integrations/kimi-code/oauth.ts | 373 ++++- 11 files changed, 2201 insertions(+), 95 deletions(-) create mode 100644 docs/architecture/tla/KimiOAuthRefresh.Variant.cfg create mode 100644 docs/architecture/tla/KimiOAuthRefresh.cfg create mode 100644 docs/architecture/tla/KimiOAuthRefresh.tla create mode 100644 src/api/providers/__tests__/kimi-code.oauth-cancellation.spec.ts 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/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..fb0fb5250cc --- /dev/null +++ b/src/api/providers/__tests__/kimi-code.oauth-cancellation.spec.ts @@ -0,0 +1,131 @@ +import { clearAllMocks } from "../../../test-utils/reset" +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) + }) +}) diff --git a/src/api/providers/__tests__/kimi-code.spec.ts b/src/api/providers/__tests__/kimi-code.spec.ts index e8ad4c28e82..bf98788aae0 100644 --- a/src/api/providers/__tests__/kimi-code.spec.ts +++ b/src/api/providers/__tests__/kimi-code.spec.ts @@ -2,17 +2,19 @@ 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(), })) -/** The one production call this test replaces: a non-streaming chat completion. */ -type CompletionCreateSeam = { create: (body: unknown) => Promise } - vi.mock("../../../integrations/kimi-code/oauth", () => ({ kimiCodeOAuthManager: { getAccessToken: mockGetAccessToken, @@ -25,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", () => { @@ -118,7 +138,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( @@ -126,6 +148,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) { @@ -137,16 +160,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 - // `client` is protected on the handler, so the mock reaches it by bracket - // access; the seam is narrowed to the single create call the mock replaces - // (same shape as anthropic-vertex.spec.ts:277/581) instead of widening to `any`. - .spyOn(handler["client"].chat.completions as unknown as CompletionCreateSeam, "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() @@ -261,4 +323,261 @@ 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("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__/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/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/integrations/kimi-code/__tests__/oauth.spec.ts b/src/integrations/kimi-code/__tests__/oauth.spec.ts index e5d5a4135f0..bc2b2fd0bef 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()) @@ -163,6 +176,41 @@ describe("KimiCodeOAuthManager", () => { expect(vi.getTimerCount()).toBe(0) }) + 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 +513,1157 @@ 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 deletes: string[] = [] + store.mockImplementation( + (k: string, v: string) => + new Promise((resolve) => { + releaseStore = () => { + values.set(k, v) + resolve() + } + }), + ) + remove.mockImplementation(async (k: string) => { + deletes.push(k) + values.delete(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) + // Once for the sign-out and once for the stale write's own cleanup. + expect(deletes.length).toBe(2) + 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("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("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 { 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 + }) + let reads = 0 + vi.mocked(context.secrets.get).mockImplementation(async () => { + reads++ + return reads === 1 ? initial : "newer-credentials" + }) + vi.spyOn(globalThis, "fetch").mockResolvedValue(rotatedTokenResponse()) + + const staleSave = manager.getAccessToken() + await vi.waitFor(() => expect(context.secrets.store).toHaveBeenCalledOnce()) + // A newer write supersedes this save while its store is parked. + manager["credentialsGeneration"]++ + values.set(key, "newer-credentials") + releaseStore() + await expect(staleSave).resolves.toBeNull() + + expect(written).toContain("rotated-refresh") + expect(context.secrets.delete).not.toHaveBeenCalled() + expect(values.get(key)).toBe("newer-credentials") + }) + + 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 + }) + 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. + if (reads === 1) return initial + return reads === 2 ? written : "newer-credentials" + }) + 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() + + expect(reads).toBe(3) + expect(context.secrets.delete).not.toHaveBeenCalled() + }) }) diff --git a/src/integrations/kimi-code/oauth.ts b/src/integrations/kimi-code/oauth.ts index 0eb95815126..2b596e8a956 100644 --- a/src/integrations/kimi-code/oauth.ts +++ b/src/integrations/kimi-code/oauth.ts @@ -72,7 +72,27 @@ class KimiCodeOAuthError extends Error { } } -async function postForm(endpoint: string, values: Record, signal?: AbortSignal): Promise { +/** 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 cancellation contract outlives the response headers: `settle` detaches the + * caller's abort forwarder once the body is consumed, so an abort during a body read cancels the + * underlying response too. An abort detaches the forwarder by itself ({ once: true }). */ +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() @@ -81,8 +101,12 @@ async function postForm(endpoint: string, values: Record, signal () => controller.abort(new Error("Kimi Code OAuth request timed out")), 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 +115,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 +148,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 +171,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 +242,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 +285,53 @@ 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) { + // 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 +340,182 @@ 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 shared POST aborts only after every waiter detached, which is a cancellation: + // reach 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 {