Skip to content

Commit 6088f40

Browse files
committed
fix(api): forward discovery cancellation into the Kimi catalog fetch
CodeRabbit pre-merge checks (Linked Issues error + Regression Evidence warning): - KimiCodeHandler.fetchModels now forwards cancellation (explicit model-cache signal, else the caller signal carried on options.signal) to getKimiCodeModels, so a cancellation during handler-driven discovery aborts the in-flight discovery HTTP request instead of only stopping the caller's wait (Issue #404). Pinned by two new handler tests plus the model-catalog-adapters case flipped to forwardsSignal. - The discovery-retry test now asserts getModels receives the caller signal (previously only call counts were checked). - base-openai-compatible-provider and zai: added rejected-Promise request-creation cases (mockRejectedValueOnce(new APIUserAbortError())) - the awaited create() rejects with that shape in practice, and the sync-throw-only tests passed even with the await removed. Negative controls: reverting the signal forwarding, dropping the signal from prepareRequest, and removing each await each fail exactly one test. The Lifecycle Resource Cleanup warning's OAuth-refresh half (resolveAccessToken -> postForm threading) lives in src/integrations/kimi-code/oauth.ts, outside this unit's diff; registered in the PR body as a follow-up.
1 parent e3360c1 commit 6088f40

5 files changed

Lines changed: 89 additions & 4 deletions

File tree

‎src/api/providers/__tests__/base-openai-compatible-provider.spec.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,25 @@ describe("BaseOpenAiCompatibleProvider", () => {
424424
expect(result.message.endsWith("aborted")).toBe(true)
425425
})
426426

427+
it("should normalize a rejected-Promise APIUserAbortError from request creation", async () => {
428+
// The provider awaits request creation so a REJECTED promise (the
429+
// shape the SDK actually returns when the request is aborted before
430+
// the response) reaches the abort normalization; the sync-throw test
431+
// above would pass even if the await were removed.
432+
mockCreate.mockRejectedValueOnce(new APIUserAbortError())
433+
434+
const result = await captureError(
435+
(async () => {
436+
for await (const _ of handler.createMessage("system prompt", [])) {
437+
// consume
438+
}
439+
})(),
440+
)
441+
442+
expect(result.name).toBe("AbortError")
443+
expect(result.message).toBe("TestProvider request aborted")
444+
})
445+
427446
it("should normalize an abort error raised during stream iteration into the abort contract", async () => {
428447
mockCreate.mockImplementationOnce(() =>
429448
(async function* () {

‎src/api/providers/__tests__/kimi-code.spec.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ import { providerIdentifiers } from "@roo-code/types/provider-identifiers"
77
import OpenAI from "openai"
88
import { Stream } from "openai/streaming"
99

10-
const { mockGetAccessToken, mockForceRefreshAccessToken, mockGetModels } = vi.hoisted(() => ({
10+
const { mockGetAccessToken, mockForceRefreshAccessToken, mockGetModels, mockGetKimiCodeModels } = vi.hoisted(() => ({
1111
mockGetAccessToken: vi.fn(),
1212
mockForceRefreshAccessToken: vi.fn(),
1313
mockGetModels: vi.fn(),
14+
mockGetKimiCodeModels: vi.fn(),
1415
}))
1516

1617
vi.mock("../../../integrations/kimi-code/oauth", () => ({
@@ -25,6 +26,10 @@ vi.mock("../fetchers/modelCache", () => ({
2526
refreshModels: mockGetModels,
2627
}))
2728

29+
vi.mock("../fetchers/kimi-code", () => ({
30+
getKimiCodeModels: mockGetKimiCodeModels,
31+
}))
32+
2833
/**
2934
* Spies on the inherited OpenAI client's chat.completions.create. `client` is
3035
* protected on the OpenAiHandler base (not on the public interface), so it is
@@ -44,6 +49,7 @@ describe("KimiCodeHandler", () => {
4449
mockGetAccessToken.mockResolvedValue("oauth-token")
4550
mockForceRefreshAccessToken.mockResolvedValue("refreshed-token")
4651
mockGetModels.mockRejectedValue(new Error("offline"))
52+
mockGetKimiCodeModels.mockResolvedValue({})
4753
})
4854

4955
it("is dispatched separately from Moonshot and preserves an unknown selected model", () => {
@@ -352,6 +358,31 @@ describe("KimiCodeHandler", () => {
352358
expect(createCompletion).not.toHaveBeenCalled()
353359
})
354360

361+
it("forwards the discovery cancellation signal to the Kimi catalog fetcher", async () => {
362+
// Issue #404: a cancellation during handler-driven discovery must reach
363+
// the discovery HTTP request itself, not just stop the caller waiting.
364+
mockGetKimiCodeModels.mockResolvedValueOnce({ "test-model": { maxTokens: 1000 } })
365+
const controller = new AbortController()
366+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" })
367+
368+
await handler.fetchModels({ provider: providerIdentifiers.kimiCode, apiKey: "key", signal: controller.signal })
369+
370+
expect(mockGetKimiCodeModels).toHaveBeenCalledWith("key", { signal: controller.signal })
371+
})
372+
373+
it("prefers the explicit model-cache signal over options.signal", async () => {
374+
mockGetKimiCodeModels.mockResolvedValueOnce({})
375+
const cacheSignal = new AbortController().signal
376+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" })
377+
378+
await handler.fetchModels(
379+
{ provider: providerIdentifiers.kimiCode, apiKey: "key", signal: new AbortController().signal },
380+
cacheSignal,
381+
)
382+
383+
expect(mockGetKimiCodeModels).toHaveBeenCalledWith("key", { signal: cacheSignal })
384+
})
385+
355386
it("retries model discovery on a later request when the caller aborts during discovery", async () => {
356387
// The SDK client binds globalThis.fetch at construction, so the completion
357388
// stub must be installed before the handler is created.
@@ -376,6 +407,13 @@ describe("KimiCodeHandler", () => {
376407
}
377408
}).rejects.toMatchObject({ name: "AbortError" })
378409
expect(mockGetModels).toHaveBeenCalledTimes(1)
410+
// The handler must hand the caller's signal to the discovery path so the
411+
// in-flight discovery request is cancellable (Issue #404), not merely
412+
// observed after the fact.
413+
expect(mockGetModels).toHaveBeenCalledWith(
414+
expect.objectContaining({ signal: controller.signal }),
415+
expect.anything(),
416+
)
379417

380418
// A later request on the same handler must retry discovery rather than
381419
// keep the fallback metadata.

‎src/api/providers/__tests__/model-catalog-adapters.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ const cases: AdapterCase[] = [
145145
fetcher: "getKimiCodeModels",
146146
scope: { urlScoped: false, keyScoped: true, authScoped: true },
147147
expectedArgs: [API_KEY],
148-
forwardsSignal: false,
148+
forwardsSignal: true,
149149
},
150150
{
151151
name: "LiteLLM",

‎src/api/providers/__tests__/zai.spec.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,28 @@ describe("ZAiHandler", () => {
680680
expect(result.message.endsWith("aborted")).toBe(true)
681681
})
682682

683+
it("createMessage should normalize a rejected-Promise APIUserAbortError on the thinking path", async () => {
684+
const thinkingHandler = new ZAiHandler({
685+
apiModelId: "glm-4.7",
686+
zaiApiKey: "test-zai-api-key",
687+
zaiApiLine: "international_coding",
688+
})
689+
// The awaited request creation rejects (the SDK's pre-abort shape);
690+
// normalization must catch it, not only synchronous throws.
691+
mockCreate.mockRejectedValueOnce(new APIUserAbortError())
692+
693+
const result = await captureError(
694+
(async () => {
695+
for await (const _ of thinkingHandler.createMessage("system prompt", [])) {
696+
// consume
697+
}
698+
})(),
699+
)
700+
701+
expect(result.name).toBe("AbortError")
702+
expect(result.message).toBe("Z.ai request aborted")
703+
})
704+
683705
it("createMessage should normalize an abort error raised during stream iteration on the thinking path", async () => {
684706
const thinkingHandler = new ZAiHandler({
685707
apiModelId: "glm-4.7",

‎src/api/providers/kimi-code.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,14 @@ export class KimiCodeHandler extends OpenAiHandler {
5656
return { urlScoped: false, keyScoped: true, authScoped: true }
5757
}
5858

59-
async fetchModels(options: GetModelsOptions): Promise<ModelRecord> {
60-
return getKimiCodeModels(options.apiKey)
59+
async fetchModels(options: GetModelsOptions, signal?: AbortSignal): Promise<ModelRecord> {
60+
// Forward cancellation (explicit model-cache signal, else the caller
61+
// signal carried on options) so a cancellation during discovery aborts
62+
// the in-flight discovery HTTP request, not just the caller's wait.
63+
const cancellation = signal ?? options.signal
64+
return cancellation
65+
? getKimiCodeModels(options.apiKey, { signal: cancellation })
66+
: getKimiCodeModels(options.apiKey)
6167
}
6268

6369
private async resolveAccessToken(forceRefresh = false): Promise<string> {

0 commit comments

Comments
 (0)