From 4475e11a5cff9775675d4ddfd5d7c85a77d07091 Mon Sep 17 00:00:00 2001 From: Infer by Flow7 Date: Wed, 18 Nov 2026 03:22:54 -0500 Subject: [PATCH 1/4] feat(api): add Infer provider Add Infer as a built-in provider. Infer is an OpenAI-compatible gateway to OpenAI, Anthropic, Google and xAI models. Each model has up to four routes: Low cost, Balanced, Stable and Official. The routes have different prices. The model list comes from the public Infer catalog. The catalog needs no API key, so the extension does not send the key with it. Each available text route becomes one model ID, for example infer/claude-opus-5-5:low-cost. The prices and the limits come from the catalog. Image input is on only for the routes that accept images. Gemini routes are left out for now. Zoo Code fetches the catalog only for Infer users. Infer is not in the startup cache refresh, the same as Friendli. An aggregate model request from a profile that uses another provider skips Infer. The handler has the same structure as the NanoGPT handler, with these changes: - It does not send max_tokens. Infer holds the cost of the output cap before a request starts. Without a cap, Infer sets one from the route, at most 32,768 tokens. - It sends the task ID in the X-Session-Affinity header. Infer then keeps the requests of one task on the same route. This helps later requests reuse the prompt cache of the route. - It reports cache writes and the cost that Infer charged for the request. - It does not send a cleared (null) temperature. - It sends no reasoning parameters, and Infer routes show no reasoning-effort control. Co-Authored-By: Claude Opus 5.5 --- .../utils/__tests__/context-window.test.ts | 1 + packages/types/src/__tests__/infer.test.ts | 27 ++ .../__tests__/provider-identifiers.test.ts | 2 + .../src/__tests__/provider-model-id.test.ts | 1 + packages/types/src/global-settings.ts | 1 + packages/types/src/provider-identifiers.ts | 1 + packages/types/src/provider-settings.ts | 3 + packages/types/src/providers/index.ts | 3 + packages/types/src/providers/infer.ts | 44 ++ src/api/__tests__/index.spec.ts | 2 + src/api/index.ts | 3 + src/api/providers/__tests__/infer.spec.ts | 385 ++++++++++++++++++ .../__tests__/model-catalog-adapters.spec.ts | 16 + .../fetchers/__tests__/infer.spec.ts | 245 +++++++++++ .../fetchers/__tests__/modelCache.spec.ts | 43 ++ src/api/providers/fetchers/infer.ts | 147 +++++++ src/api/providers/index.ts | 1 + src/api/providers/infer.ts | 246 +++++++++++ .../config/__tests__/ContextProxy.spec.ts | 16 + .../webview/__tests__/ClineProvider.spec.ts | 3 + ...webviewMessageHandler.routerModels.spec.ts | 57 +++ .../__tests__/webviewMessageHandler.spec.ts | 8 + src/core/webview/webviewMessageHandler.ts | 11 + src/shared/__tests__/ProfileValidator.spec.ts | 20 + src/shared/api.ts | 1 + .../src/components/settings/ApiOptions.tsx | 12 + .../src/components/settings/ModelPicker.tsx | 1 + .../ApiOptions.interactions.spec.tsx | 2 + .../ApiOptions.provider-filtering.spec.tsx | 1 + .../settings/__tests__/ApiOptions.spec.tsx | 1 + .../settings/__tests__/ModelPicker.spec.tsx | 38 ++ .../SettingsView.unsaved-changes.spec.tsx | 81 ++++ .../__tests__/ThinkingBudget.spec.tsx | 33 +- .../src/components/settings/constants.ts | 1 + .../components/settings/providers/Infer.tsx | 84 ++++ .../providers/__tests__/Infer.spec.tsx | 137 +++++++ .../providers/__tests__/NanoGPT.spec.tsx | 1 + .../components/settings/providers/index.ts | 1 + .../__tests__/providerModelConfig.spec.ts | 8 + .../settings/utils/providerModelConfig.ts | 2 + .../hooks/__tests__/useSelectedModel.spec.ts | 94 +++++ .../components/ui/hooks/useSelectedModel.ts | 22 +- webview-ui/src/i18n/locales/ca/settings.json | 6 + webview-ui/src/i18n/locales/de/settings.json | 6 + webview-ui/src/i18n/locales/en/settings.json | 6 + webview-ui/src/i18n/locales/es/settings.json | 6 + webview-ui/src/i18n/locales/fr/settings.json | 6 + webview-ui/src/i18n/locales/hi/settings.json | 6 + webview-ui/src/i18n/locales/id/settings.json | 6 + webview-ui/src/i18n/locales/it/settings.json | 6 + webview-ui/src/i18n/locales/ja/settings.json | 6 + webview-ui/src/i18n/locales/ko/settings.json | 6 + webview-ui/src/i18n/locales/nl/settings.json | 6 + webview-ui/src/i18n/locales/pl/settings.json | 6 + .../src/i18n/locales/pt-BR/settings.json | 6 + webview-ui/src/i18n/locales/ru/settings.json | 6 + webview-ui/src/i18n/locales/tr/settings.json | 6 + webview-ui/src/i18n/locales/vi/settings.json | 6 + .../src/i18n/locales/zh-CN/settings.json | 6 + .../src/i18n/locales/zh-TW/settings.json | 6 + .../src/utils/__tests__/validate.spec.ts | 41 ++ webview-ui/src/utils/validate.ts | 5 + 62 files changed, 1953 insertions(+), 7 deletions(-) create mode 100644 packages/types/src/__tests__/infer.test.ts create mode 100644 packages/types/src/providers/infer.ts create mode 100644 src/api/providers/__tests__/infer.spec.ts create mode 100644 src/api/providers/fetchers/__tests__/infer.spec.ts create mode 100644 src/api/providers/fetchers/infer.ts create mode 100644 src/api/providers/infer.ts create mode 100644 webview-ui/src/components/settings/providers/Infer.tsx create mode 100644 webview-ui/src/components/settings/providers/__tests__/Infer.spec.tsx diff --git a/apps/cli/src/lib/utils/__tests__/context-window.test.ts b/apps/cli/src/lib/utils/__tests__/context-window.test.ts index 83420592ef2..abbfe778d93 100644 --- a/apps/cli/src/lib/utils/__tests__/context-window.test.ts +++ b/apps/cli/src/lib/utils/__tests__/context-window.test.ts @@ -14,6 +14,7 @@ describe("getContextWindow", () => { [providerIdentifiers.vercelAiGateway, "vercelAiGatewayModelId"], [providerIdentifiers.opencodeGo, "opencodeGoModelId"], [providerIdentifiers.kenari, "kenariModelId"], + [providerIdentifiers.infer, "inferModelId"], [providerIdentifiers.nanogpt, "nanoGptModelId"], [providerIdentifiers.zooGateway, "zooGatewayModelId"], ] as const)("uses the provider-specific model field for %s", (provider, modelField) => { diff --git a/packages/types/src/__tests__/infer.test.ts b/packages/types/src/__tests__/infer.test.ts new file mode 100644 index 00000000000..150fcbc7f9b --- /dev/null +++ b/packages/types/src/__tests__/infer.test.ts @@ -0,0 +1,27 @@ +import { + dynamicProviders, + getModelId, + getProviderDefaultModelId, + inferDefaultModelId, + isSecretStateKey, + providerIdentifiers, + providerSettingsSchema, +} from "../index.js" + +describe("Infer shared contract", () => { + it("registers the stable dynamic-provider identity and default model", () => { + expect(providerIdentifiers.infer).toBe("infer") + expect(dynamicProviders).toContain(providerIdentifiers.infer) + expect(getProviderDefaultModelId(providerIdentifiers.infer, {})).toBe(inferDefaultModelId) + expect(inferDefaultModelId).toBe("infer/claude-opus-5-5:low-cost") + }) + + it("classifies the API key as secret and resolves the configured model", () => { + expect(isSecretStateKey("inferApiKey")).toBe(true) + const settings = providerSettingsSchema.parse({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/model:stable", + }) + expect(getModelId(settings)).toBe("infer/model:stable") + }) +}) diff --git a/packages/types/src/__tests__/provider-identifiers.test.ts b/packages/types/src/__tests__/provider-identifiers.test.ts index 92494a56bc0..39ba18e0684 100644 --- a/packages/types/src/__tests__/provider-identifiers.test.ts +++ b/packages/types/src/__tests__/provider-identifiers.test.ts @@ -35,6 +35,7 @@ const expectedProviderIdentifiers = [ "opencode-go", "kenari", "nanogpt", + "infer", "ollama", "lmstudio", "vscode-lm", @@ -112,6 +113,7 @@ describe("provider identifiers", () => { providerIdentifiers.opencodeGo, providerIdentifiers.kenari, providerIdentifiers.nanogpt, + providerIdentifiers.infer, providerIdentifiers.kimiCode, providerIdentifiers.friendli, ]) diff --git a/packages/types/src/__tests__/provider-model-id.test.ts b/packages/types/src/__tests__/provider-model-id.test.ts index e25341e4c3d..040fee1b70d 100644 --- a/packages/types/src/__tests__/provider-model-id.test.ts +++ b/packages/types/src/__tests__/provider-model-id.test.ts @@ -21,6 +21,7 @@ const expectedModelIdKeys = [ "opencodeGoModelId", "kenariModelId", "nanoGptModelId", + "inferModelId", "zooGatewayModelId", ] as const diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index ef812b01bbd..4fa45a02039 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -385,6 +385,7 @@ export const SECRET_STATE_KEYS = [ "vercelAiGatewayApiKey", "opencodeGoApiKey", "kenariApiKey", + "inferApiKey", "nanoGptApiKey", "basetenApiKey", ] as const diff --git a/packages/types/src/provider-identifiers.ts b/packages/types/src/provider-identifiers.ts index 50646bb6dc0..bdbc0a488a0 100644 --- a/packages/types/src/provider-identifiers.ts +++ b/packages/types/src/provider-identifiers.ts @@ -15,6 +15,7 @@ export const providerIdentifiers = { opencodeGo: "opencode-go", kenari: "kenari", nanogpt: "nanogpt", + infer: "infer", ollama: "ollama", lmstudio: "lmstudio", vscodeLm: "vscode-lm", diff --git a/packages/types/src/provider-settings.ts b/packages/types/src/provider-settings.ts index c31a3948b24..014f1d14ba7 100644 --- a/packages/types/src/provider-settings.ts +++ b/packages/types/src/provider-settings.ts @@ -101,6 +101,7 @@ export const dynamicProviders = [ providerIdentifiers.opencodeGo, providerIdentifiers.kenari, providerIdentifiers.nanogpt, + providerIdentifiers.infer, providerIdentifiers.kimiCode, providerIdentifiers.friendli, ] as const @@ -316,6 +317,7 @@ export const modelIdKeys = [ "opencodeGoModelId", "kenariModelId", "nanoGptModelId", + "inferModelId", "zooGatewayModelId", ] as const satisfies readonly ModelIdKey[] @@ -557,6 +559,7 @@ export const MODELS_BY_PROVIDER: Record< }, [providerIdentifiers.opencodeGo]: { id: providerIdentifiers.opencodeGo, label: "Opencode Go", models: [] }, [providerIdentifiers.kenari]: { id: providerIdentifiers.kenari, label: "Kenari", models: [] }, + [providerIdentifiers.infer]: { id: providerIdentifiers.infer, label: "Infer", models: [] }, [providerIdentifiers.nanogpt]: { id: providerIdentifiers.nanogpt, label: "NanoGPT", models: [] }, [providerIdentifiers.zooGateway]: { id: providerIdentifiers.zooGateway, label: "Zoo Gateway", models: [] }, diff --git a/packages/types/src/providers/index.ts b/packages/types/src/providers/index.ts index cae4f12b288..807d0f005c9 100644 --- a/packages/types/src/providers/index.ts +++ b/packages/types/src/providers/index.ts @@ -29,6 +29,7 @@ export * from "./xai.js" export * from "./vercel-ai-gateway.js" export * from "./opencode-go.js" export * from "./kenari.js" +export * from "./infer.js" export * from "./nanogpt.js" export * from "./kimi-code.js" export * from "./zai.js" @@ -46,6 +47,7 @@ import { fakeAiProviderDefinition } from "./fake-ai.js" import { fireworksProviderDefinition } from "./fireworks.js" import { friendliProviderDefinition } from "./friendli.js" import { geminiProviderDefinition } from "./gemini.js" +import { inferProviderDefinition } from "./infer.js" import { kenariProviderDefinition } from "./kenari.js" import { kimiCodeProviderDefinition } from "./kimi-code.js" import { litellmProviderDefinition } from "./litellm.js" @@ -109,6 +111,7 @@ export const providerDefinitionList = [ opencodeGoProviderDefinition, kenariProviderDefinition, nanoGptProviderDefinition, + inferProviderDefinition, zooGatewayProviderDefinition, basetenProviderDefinition, ] as const satisfies readonly ProviderDefinition[] diff --git a/packages/types/src/providers/infer.ts b/packages/types/src/providers/infer.ts new file mode 100644 index 00000000000..730b264e02e --- /dev/null +++ b/packages/types/src/providers/infer.ts @@ -0,0 +1,44 @@ +import { z } from "zod" + +import { type ModelInfo } from "../model.js" +import { providerIdentifiers } from "../provider-identifiers.js" +import { baseProviderSettingsShape, createModelIdAccessor, createProviderDefinition } from "./common.js" + +// Infer: OpenAI-compatible gateway to OpenAI, Anthropic, Google and xAI models. +// https://infer.flow7.org/docs · base URL: https://infer.flow7.org/v1 +// +// A model id selects a model and a route, for example `infer/claude-opus-5-5:low-cost`. +// The routes are Low cost, Balanced, Stable and Official, at different prices. +// The public catalog lists each route with its prices and limits, so the model list +// is fetched at runtime. The values below are only a fallback for the time before +// the catalog resolves. + +export const INFER_BASE_URL = "https://infer.flow7.org/v1" + +export const INFER_CATALOG_URL = "https://infer.flow7.org/api/public/catalog" + +export const inferDefaultModelId = "infer/claude-opus-5-5:low-cost" + +export const inferDefaultModelInfo: ModelInfo = { + maxTokens: 128_000, + contextWindow: 1_000_000, + supportsImages: false, + supportsPromptCache: false, + // Prices are intentionally omitted: they come only from the live catalog, so a + // fallback never shows a stale price. + description: "Infer model. Routes, prices and limits are resolved dynamically from the public catalog.", +} + +const INFER_MODEL_ID_FIELD = "inferModelId" + +export const inferProviderDefinition = createProviderDefinition({ + apiProvider: providerIdentifiers.infer, + modelIdKey: INFER_MODEL_ID_FIELD, + getModelId: createModelIdAccessor(INFER_MODEL_ID_FIELD), + getDefaultModelId: () => inferDefaultModelId, + schema: { + ...baseProviderSettingsShape, + inferApiKey: z.string().optional(), + [INFER_MODEL_ID_FIELD]: z.string().optional(), + }, +}) diff --git a/src/api/__tests__/index.spec.ts b/src/api/__tests__/index.spec.ts index 303c8f8ec84..074b5487bf3 100644 --- a/src/api/__tests__/index.spec.ts +++ b/src/api/__tests__/index.spec.ts @@ -56,6 +56,7 @@ import { FireworksHandler, FriendliHandler, GeminiHandler, + InferHandler, KenariHandler, KimiCodeHandler, LiteLLMHandler, @@ -117,6 +118,7 @@ const expectedHandlers = { [providerIdentifiers.vercelAiGateway]: VercelAiGatewayHandler, [providerIdentifiers.opencodeGo]: OpencodeGoHandler, [providerIdentifiers.kenari]: KenariHandler, + [providerIdentifiers.infer]: InferHandler, [providerIdentifiers.nanogpt]: NanoGptHandler, [providerIdentifiers.zooGateway]: ZooGatewayHandler, [providerIdentifiers.minimax]: MiniMaxHandler, diff --git a/src/api/index.ts b/src/api/index.ts index f2e52979015..c1253704da4 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -45,6 +45,7 @@ import { VercelAiGatewayHandler, OpencodeGoHandler, KenariHandler, + InferHandler, NanoGptHandler, ZooGatewayHandler, MiniMaxHandler, @@ -285,6 +286,8 @@ export function buildApiHandler(configuration: ProviderSettings): ApiHandler { return new OpencodeGoHandler(options) case providerIdentifiers.kenari: return new KenariHandler(options) + case providerIdentifiers.infer: + return new InferHandler(options) case providerIdentifiers.nanogpt: return new NanoGptHandler(options) case providerIdentifiers.zooGateway: diff --git a/src/api/providers/__tests__/infer.spec.ts b/src/api/providers/__tests__/infer.spec.ts new file mode 100644 index 00000000000..477c1830875 --- /dev/null +++ b/src/api/providers/__tests__/infer.spec.ts @@ -0,0 +1,385 @@ +vi.mock("vscode", () => ({ + workspace: { getConfiguration: () => ({ get: (_key: string, defaultValue?: unknown) => defaultValue }) }, +})) + +import { Anthropic } from "@anthropic-ai/sdk" +import OpenAI from "openai" + +import { INFER_BASE_URL, inferDefaultModelId, providerIdentifiers } from "@roo-code/types" + +import { buildApiHandler } from "../../index" +import { prepareApiConversationMessage } from "../../../core/task/apiConversationHistory" +import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +import { clearAllMocks } from "../../../test-utils/reset" +import { InferHandler } from "../infer" +import { getModels } from "../fetchers/modelCache" + +const MODEL_ID = "infer/test-model:low-cost" +const MODEL_INFO = { maxTokens: 128_000, contextWindow: 1_000_000, supportsImages: false, supportsPromptCache: true } + +vi.mock("openai") +vi.mock("../fetchers/modelCache", () => ({ + getModels: vi.fn(), + getModelsFromCache: vi.fn(), + refreshModels: vi.fn().mockResolvedValue({}), +})) + +const mockCreate = vi.fn() +vi.mocked(OpenAI).mockImplementation(function () { + return { chat: { completions: { create: mockCreate } } } as unknown as OpenAI +}) + +const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }] + +/** Flattens every argument of every console.error call into one searchable string. */ +const loggedText = (spy: { mock: { calls: unknown[][] } }) => + spy.mock.calls + .flat() + .map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg))) + .join("\n") + +describe("InferHandler", () => { + beforeEach(() => { + clearAllMocks() + vi.mocked(getModels).mockResolvedValue({ [MODEL_ID]: MODEL_INFO }) + mockCreate.mockResolvedValue(asyncStreamFrom([])) + }) + + it("is constructed by the backend provider registry", () => { + expect(buildApiHandler({ apiProvider: providerIdentifiers.infer })).toBeInstanceOf(InferHandler) + }) + + it("sends requests to the fixed Infer endpoint with the configured key", () => { + new InferHandler({ inferApiKey: "test-key" }) + expect(vi.mocked(OpenAI)).toHaveBeenCalledWith( + expect.objectContaining({ baseURL: INFER_BASE_URL, apiKey: "test-key" }), + ) + }) + + it("resolves the default model when none is configured", async () => { + const handler = new InferHandler({}) + await collectStream(handler.createMessage("system", messages)) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: inferDefaultModelId }), { + signal: undefined, + }) + }) + + it("uses the configured route selector and streams text, reasoning, and tool calls", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { choices: [{ delta: { role: "assistant", content: "" } }] }, + { choices: [{ delta: { reasoning: "thinking" } }] }, + { choices: [{ delta: { content: "answer" } }] }, + { + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call-1", + type: "function", + function: { name: "read_file", arguments: "" }, + }, + ], + }, + }, + ], + }, + { choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: '{"path":' } }] } }] }, + ]), + ) + const chunks = await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: MODEL_ID }), { signal: undefined }) + expect(chunks).toEqual([ + { type: "reasoning", text: "thinking" }, + { type: "text", text: "answer" }, + { type: "tool_call_partial", index: 0, id: "call-1", name: "read_file", arguments: "" }, + { type: "tool_call_partial", index: 0, id: undefined, name: undefined, arguments: '{"path":' }, + ]) + }) + + it("forwards native tools, usage streaming, session affinity, and cancellation without an output cap", async () => { + const signal = new AbortController().signal + const tools: OpenAI.Chat.ChatCompletionTool[] = [ + { type: "function", function: { name: "read_file", description: "Read", parameters: { type: "object" } } }, + ] + const handler = new InferHandler({ inferModelId: MODEL_ID, modelTemperature: 0.7 }) + await collectStream( + handler.createMessage("sys", messages, { + taskId: "task-1", + tools, + tool_choice: "required", + parallelToolCalls: false, + abortSignal: signal, + }), + ) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + model: MODEL_ID, + messages: [ + { role: "system", content: "sys" }, + { role: "user", content: "Hello" }, + ], + stream: true, + stream_options: { include_usage: true }, + temperature: 0.7, + tools: [ + expect.objectContaining({ + type: "function", + function: expect.objectContaining({ name: "read_file", description: "Read" }), + }), + ], + tool_choice: "required", + parallel_tool_calls: false, + }), + { signal, headers: { "X-Session-Affinity": "task-1" } }, + ) + // Infer holds the cost of the output cap before the request, so no cap is sent. + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("max_tokens") + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("max_completion_tokens") + }) + + it("maps usage, cache writes, and the settled charge from the final chunk", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { choices: [{ delta: {}, finish_reason: "stop" }], relay: { customer_cost_usd: 0.0042 } }, + { + choices: [], + usage: { + prompt_tokens: 1000, + completion_tokens: 50, + prompt_tokens_details: { cached_tokens: 600, cache_write_tokens: 300 }, + }, + relay: { customer_cost_usd: 0.0042 }, + }, + ]), + ) + expect( + await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)), + ).toEqual([ + { + type: "usage", + inputTokens: 1000, + outputTokens: 50, + cacheReadTokens: 600, + cacheWriteTokens: 300, + totalCost: 0.0042, + }, + ]) + }) + + it("preserves zero cache counts and omits the charge when the chunk has none", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { + choices: [], + usage: { + prompt_tokens: 20, + completion_tokens: 10, + prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 }, + }, + }, + ]), + ) + expect( + await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)), + ).toEqual([{ type: "usage", inputTokens: 20, outputTokens: 10, cacheReadTokens: 0, cacheWriteTokens: 0 }]) + }) + + it.each(["0.0042", Number.POSITIVE_INFINITY, null])( + "does not report a charge that is not a finite number (%s)", + async (charge) => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { + choices: [], + usage: { prompt_tokens: 20, completion_tokens: 10 }, + relay: { customer_cost_usd: charge }, + }, + ]), + ) + const [usage] = await collectStream( + new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages), + ) + expect(usage).toEqual({ type: "usage", inputTokens: 20, outputTokens: 10 }) + expect(usage).not.toHaveProperty("totalCost") + }, + ) + + it("redacts the API key from streaming errors and from the logged error", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue(new Error("upstream rejected secret-key")) + const handler = new InferHandler({ inferApiKey: "secret-key", inferModelId: MODEL_ID }) + await expect(collectStream(handler.createMessage("sys", messages))).rejects.toMatchObject({ + message: "Infer streaming error: upstream rejected [REDACTED]", + }) + // The error handler logs message + stack before the transformer runs, + // so the key must already be gone from both. + expect(consoleErrorSpy).toHaveBeenCalledWith( + "[Infer] API error:", + expect.objectContaining({ + message: "upstream rejected [REDACTED]", + stack: expect.stringContaining("[REDACTED]"), + }), + ) + expect(loggedText(consoleErrorSpy)).not.toContain("secret-key") + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("serializes and redacts an object-valued raw error body and keeps the status", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue( + Object.assign(new Error("Request failed"), { + status: 402, + error: { metadata: { raw: { detail: "insufficient credits for secret-key" } } }, + }), + ) + const handler = new InferHandler({ inferApiKey: "secret-key", inferModelId: MODEL_ID }) + await expect(collectStream(handler.createMessage("sys", messages))).rejects.toMatchObject({ + message: 'Infer streaming error: {"detail":"insufficient credits for [REDACTED]"}', + status: 402, + }) + expect(loggedText(consoleErrorSpy)).not.toContain("secret-key") + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("redacts the API key from non-Error rejections and their log line", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue("upstream rejected secret-key") + const handler = new InferHandler({ inferApiKey: "secret-key", inferModelId: MODEL_ID }) + await expect(collectStream(handler.createMessage("sys", messages))).rejects.toMatchObject({ + message: "Infer streaming error: upstream rejected [REDACTED]", + }) + expect(consoleErrorSpy).toHaveBeenCalledWith("[Infer] Non-Error exception:", "upstream rejected [REDACTED]") + expect(loggedText(consoleErrorSpy)).not.toContain("secret-key") + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("completePrompt wraps upstream errors without a configured key", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue(new Error("boom")) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + await expect(handler.completePrompt("ping")).rejects.toMatchObject({ + message: "Infer completion error: boom", + }) + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("completePrompt sends the prompt as a single user message without an output cap", async () => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + expect(await handler.completePrompt("ping")).toBe("ok") + // A bare call passes no request options: the OpenAI SDK rejects a present-but-undefined `timeout`. + expect(mockCreate).toHaveBeenCalledWith( + { model: MODEL_ID, messages: [{ role: "user", content: "ping" }], stream: false }, + undefined, + ) + }) + + it("completePrompt returns an empty string when the response has no choices", async () => { + mockCreate.mockResolvedValue({ choices: [] }) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + expect(await handler.completePrompt("ping")).toBe("") + }) + + it("completePrompt forwards abort and timeout options when provided", async () => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const signal = new AbortController().signal + const handler = new InferHandler({ inferModelId: MODEL_ID }) + await handler.completePrompt("ping", { abortSignal: signal, timeoutMs: 5_000 }) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ stream: false }), { signal, timeout: 5_000 }) + }) + + it.each([0, -5, Number.NaN, Number.POSITIVE_INFINITY])( + "completePrompt does not forward an unusable timeoutMs (%s)", + async (timeoutMs) => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + await handler.completePrompt("ping", { timeoutMs }) + expect(mockCreate.mock.calls[0][1]).toBeUndefined() + }, + ) + + it("does not send the OpenAI Compatible custom headers to the fixed endpoint", () => { + new InferHandler({ inferApiKey: "test-key", openAiHeaders: { "X-Custom-Header": "leaked" } }) + expect(vi.mocked(OpenAI)).toHaveBeenCalledTimes(1) + const clientOptions = vi.mocked(OpenAI).mock.calls[0][0] + expect(clientOptions?.defaultHeaders).not.toHaveProperty("X-Custom-Header") + }) + + it("omits a cleared (null) temperature in both request paths", async () => { + const handler = new InferHandler({ inferModelId: MODEL_ID, modelTemperature: null }) + + await collectStream(handler.createMessage("system", messages)) + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") + + mockCreate.mockClear() + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + expect(await handler.completePrompt("ping")).toBe("ok") + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") + }) + + it("completePrompt forwards the configured temperature", async () => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const handler = new InferHandler({ inferModelId: MODEL_ID, modelTemperature: 0.7 }) + expect(await handler.completePrompt("ping")).toBe("ok") + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ stream: false, temperature: 0.7 }), undefined) + }) + + it.each(["reasoning_effort", "reasoning", "thinking", "include_reasoning"])( + "sends no %s parameter, even when the profile turns reasoning on", + async (field) => { + // Zoo Code cannot send a model's reasoning back to Infer on the next turn, so the + // handler never asks a model to reason, whatever the profile or the model info says. + vi.mocked(getModels).mockResolvedValue({ + [MODEL_ID]: { + ...MODEL_INFO, + supportsReasoningEffort: true, + reasoningEffort: "high", + supportsReasoningBudget: true, + }, + }) + const handler = new InferHandler({ + inferModelId: MODEL_ID, + enableReasoningEffort: true, + reasoningEffort: "high", + modelMaxThinkingTokens: 8_192, + }) + + await collectStream(handler.createMessage("sys", messages)) + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + await handler.completePrompt("ping") + + expect(mockCreate).toHaveBeenCalledTimes(2) + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty(field) + expect(mockCreate.mock.calls[1][0]).not.toHaveProperty(field) + }, + ) + + it("keeps no reasoning state for the next turn", () => { + // Zoo Code sends reasoning_details back only when the handler returned them. The streamed + // reply has reasoning text only, so the stored assistant turn carries none. + const stored = prepareApiConversationMessage({ + message: { role: "assistant", content: [{ type: "text", text: "answer" }] }, + reasoning: "thinking", + api: new InferHandler({ inferModelId: MODEL_ID }), + apiConfiguration: { apiProvider: providerIdentifiers.infer, inferModelId: MODEL_ID }, + apiConversationHistory: [], + }) + + expect(stored).not.toHaveProperty("reasoning_details") + }) +}) diff --git a/src/api/providers/__tests__/model-catalog-adapters.spec.ts b/src/api/providers/__tests__/model-catalog-adapters.spec.ts index 61224791142..5c8ee4423ea 100644 --- a/src/api/providers/__tests__/model-catalog-adapters.spec.ts +++ b/src/api/providers/__tests__/model-catalog-adapters.spec.ts @@ -11,6 +11,7 @@ import type { ApiHandler, ModelCacheScope } from "../../index" const fetchers = vi.hoisted(() => ({ getDeepSeekModels: vi.fn(), + getInferModels: vi.fn(), getKenariModels: vi.fn(), getKimiCodeModels: vi.fn(), getLiteLLMModels: vi.fn(), @@ -45,6 +46,10 @@ vi.mock("../fetchers/deepseek", async (importOriginal) => ({ ...(await importOriginal()), getDeepSeekModels: fetchers.getDeepSeekModels, })) +vi.mock("../fetchers/infer", async (importOriginal) => ({ + ...(await importOriginal()), + getInferModels: fetchers.getInferModels, +})) vi.mock("../fetchers/kenari", async (importOriginal) => ({ ...(await importOriginal()), getKenariModels: fetchers.getKenariModels, @@ -104,6 +109,7 @@ vi.mock("../fetchers/zoo-gateway", async (importOriginal) => ({ import { AnthropicHandler } from "../anthropic" import { DeepSeekHandler } from "../deepseek" +import { InferHandler } from "../infer" import { KenariHandler } from "../kenari" import { KimiCodeHandler } from "../kimi-code" import { LiteLLMHandler } from "../lite-llm" @@ -149,6 +155,16 @@ const cases: AdapterCase[] = [ forwardsSignal: true, prewarms: false, }, + { + name: "Infer", + create: () => new InferHandler({ inferApiKey: API_KEY }), + fetcher: "getInferModels", + // The public catalog is the same for every key, so the key is not sent with it. + scope: { urlScoped: false, keyScoped: false, authScoped: false }, + expectedArgs: [], + forwardsSignal: true, + prewarms: false, + }, { name: "Kenari", create: () => new KenariHandler({ kenariApiKey: API_KEY }), diff --git a/src/api/providers/fetchers/__tests__/infer.spec.ts b/src/api/providers/fetchers/__tests__/infer.spec.ts new file mode 100644 index 00000000000..39115254857 --- /dev/null +++ b/src/api/providers/fetchers/__tests__/infer.spec.ts @@ -0,0 +1,245 @@ +import axios from "axios" + +import { INFER_CATALOG_URL, openAiModelInfoSaneDefaults } from "@roo-code/types" + +import { getInferModels } from "../infer" + +vi.mock("axios") + +/** A route as the public catalog publishes it, with overridable fields. */ +const route = (selector: string, overrides: Record = {}) => ({ + selector, + available: true, + input_per_million_usd: 2, + cached_input_per_million_usd: 0.2, + cache_write_per_million_usd: 2.5, + output_per_million_usd: 10, + runtime: { max_context_tokens: null, max_output_tokens: null, vision: false, tools: true, streaming: true }, + ...overrides, +}) + +/** A text model with model-level limits and the given routes. */ +const model = (slug: string, tiers: Record, overrides: Record = {}) => ({ + slug, + name: slug, + kind: "exact", + runtime: { max_context_tokens: 200_000, max_output_tokens: 64_000, vision: false, tools: true, streaming: true }, + tiers, + ...overrides, +}) + +const mockCatalog = (models: unknown[]) => vi.mocked(axios.get).mockResolvedValue({ data: { models } }) + +describe("Infer model fetcher", () => { + beforeEach(() => vi.clearAllMocks()) + + it("requests the public catalog without credentials", async () => { + mockCatalog([]) + await getInferModels() + expect(axios.get).toHaveBeenCalledWith(INFER_CATALOG_URL, { timeout: 10_000, signal: undefined }) + }) + + it("forwards the caller's abort signal to the request", async () => { + mockCatalog([]) + const controller = new AbortController() + + await getInferModels({ signal: controller.signal }) + + expect(axios.get).toHaveBeenCalledWith(INFER_CATALOG_URL, { timeout: 10_000, signal: controller.signal }) + }) + + it("rejects with an AbortError when the signal aborts the pending request", async () => { + const controller = new AbortController() + vi.mocked(axios.get).mockImplementation((_url, config) => { + // Mirror the HTTP client: a pending request rejects when its signal fires. + return new Promise((_resolve, reject) => { + config?.signal?.addEventListener?.("abort", () => reject(new Error("canceled")), { once: true }) + }) + }) + + const fetchPromise = getInferModels({ signal: controller.signal }) + controller.abort() + + await expect(fetchPromise).rejects.toMatchObject({ name: "AbortError" }) + }) + + it("lists each available route under its selector with exact per-million prices and route limits", async () => { + mockCatalog([ + model("model-a", { + "low-cost": route("infer/model-a:low-cost"), + official: route("infer/model-a:official", { + input_per_million_usd: 5, + cached_input_per_million_usd: 0.5, + cache_write_per_million_usd: 6.25, + output_per_million_usd: 25, + runtime: { + max_context_tokens: 1_000_000, + max_output_tokens: 128_000, + vision: true, + tools: true, + streaming: true, + }, + }), + }), + ]) + + const models = await getInferModels() + + expect(Object.keys(models)).toEqual(["infer/model-a:low-cost", "infer/model-a:official"]) + // A discount route publishes no limits of its own, so the model-level limits apply. + expect(models["infer/model-a:low-cost"]).toEqual({ + contextWindow: 200_000, + maxTokens: 64_000, + supportsImages: false, + supportsPromptCache: true, + inputPrice: 2, + outputPrice: 10, + cacheReadsPrice: 0.2, + cacheWritesPrice: 2.5, + displayName: "model-a (Low cost)", + }) + expect(models["infer/model-a:official"]).toEqual({ + contextWindow: 1_000_000, + maxTokens: 128_000, + supportsImages: true, + supportsPromptCache: true, + inputPrice: 5, + outputPrice: 25, + cacheReadsPrice: 0.5, + cacheWritesPrice: 6.25, + displayName: "model-a (Official)", + }) + }) + + it.each([ + ["balanced", "Balanced"], + ["stable", "Stable"], + ["future-route", "future-route"], + ["constructor", "constructor"], + ])("labels the %s route as %s", async (routeId, label) => { + mockCatalog([model("model-a", { [routeId]: route(`infer/model-a:${routeId}`) }, { name: "Model A" })]) + const models = await getInferModels() + expect(models[`infer/model-a:${routeId}`].displayName).toBe(`Model A (${label})`) + }) + + it.each([ + "supportsReasoningEffort", + "supportsReasoningBudget", + "supportsReasoningBinary", + "requiredReasoningEffort", + "requiredReasoningBudget", + "reasoningEffort", + "preserveReasoning", + "supportsMaxTokens", + ])("sets no %s flag on any route, so the settings show no reasoning control", async (flag) => { + mockCatalog([ + model("model-a", { + "low-cost": route("infer/model-a:low-cost"), + official: route("infer/model-a:official", { runtime: { vision: true, tools: true, streaming: true } }), + }), + ]) + + const models = await getInferModels() + + expect(models["infer/model-a:low-cost"]).not.toHaveProperty(flag) + expect(models["infer/model-a:official"]).not.toHaveProperty(flag) + }) + + it("falls back to the default context window and omits the output limit when no limit is published", async () => { + mockCatalog([ + model( + "model-b", + { stable: route("infer/model-b:stable", { cached_input_per_million_usd: 0 }) }, + { name: undefined, runtime: { max_context_tokens: null, max_output_tokens: 0 } }, + ), + ]) + + const info = (await getInferModels())["infer/model-b:stable"] + + expect(info.contextWindow).toBe(openAiModelInfoSaneDefaults.contextWindow) + expect(info).not.toHaveProperty("maxTokens") + // No cache-read price means the route does not bill cached input separately. + expect(info.supportsPromptCache).toBe(false) + expect(info.displayName).toBe("model-b (Stable)") + }) + + it("skips generation models and routes that are unavailable, lack tools, or cannot stream", async () => { + mockCatalog([ + model("video-model", { stable: route("infer/video-model:stable") }, { kind: "video_generation" }), + model("image-model", { stable: route("infer/image-model:stable") }, { kind: "image_generation" }), + model("text-model", { + "low-cost": route("infer/text-model:low-cost"), + balanced: route("infer/text-model:balanced", { available: false }), + stable: route("infer/text-model:stable", { runtime: { tools: false } }), + official: route("infer/text-model:official", { runtime: { streaming: false } }), + }), + model("unflagged-model", { stable: route("infer/unflagged-model:stable", { runtime: undefined }) }), + ]) + + expect(Object.keys(await getInferModels())).toEqual([ + "infer/text-model:low-cost", + "infer/unflagged-model:stable", + ]) + }) + + it("leaves out Gemini routes and keeps the Claude ones", async () => { + mockCatalog([ + model("gemini-3.8-flash", { + "low-cost": route("infer/gemini-3.8-flash:low-cost"), + official: route("infer/gemini-3.8-flash:official"), + }), + model("claude-opus-5-5", { + "low-cost": route("infer/claude-opus-5-5:low-cost"), + official: route("infer/claude-opus-5-5:official"), + }), + ]) + + expect(Object.keys(await getInferModels())).toEqual([ + "infer/claude-opus-5-5:low-cost", + "infer/claude-opus-5-5:official", + ]) + }) + + it("skips malformed models and routes", async () => { + mockCatalog([ + { name: "missing slug", tiers: {} }, + model("model-c", { + "low-cost": route("infer/model-c:low-cost"), + balanced: { available: true }, + stable: route("infer/model-c:stable", { input_per_million_usd: -1 }), + }), + ]) + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined) + + expect(Object.keys(await getInferModels())).toEqual(["infer/model-c:low-cost"]) + expect(warning).toHaveBeenCalledTimes(3) + warning.mockRestore() + }) + + it("keeps a hostile selector as an own entry instead of polluting the prototype chain", async () => { + mockCatalog([model("hostile", { stable: route("__proto__"), official: route("constructor") })]) + const models = await getInferModels() + expect(Object.getPrototypeOf(models)).toBeNull() + expect(Object.keys(models)).toEqual(["__proto__", "constructor"]) + expect(models["__proto__"]).toMatchObject({ inputPrice: 2 }) + expect(({} as Record).inputPrice).toBeUndefined() + }) + + it.each([{ models: null }, [], null])("returns no models for invalid top-level data %#", async (data) => { + vi.mocked(axios.get).mockResolvedValue({ data }) + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined) + expect(await getInferModels()).toEqual({}) + warning.mockRestore() + }) + + it.each([new Error("network unavailable"), "network unavailable"])( + "returns no models on network failure", + async (error) => { + vi.mocked(axios.get).mockRejectedValue(error) + const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined) + expect(await getInferModels()).toEqual({}) + expect(consoleError).toHaveBeenCalledWith("Error fetching Infer models: network unavailable") + consoleError.mockRestore() + }, + ) +}) diff --git a/src/api/providers/fetchers/__tests__/modelCache.spec.ts b/src/api/providers/fetchers/__tests__/modelCache.spec.ts index e9818cb7091..a1e9a1850ce 100644 --- a/src/api/providers/fetchers/__tests__/modelCache.spec.ts +++ b/src/api/providers/fetchers/__tests__/modelCache.spec.ts @@ -77,6 +77,7 @@ const OPENROUTER_SCOPE: ModelCacheScope = { urlScoped: false, keyScoped: false, const LITELLM_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: false } const REQUESTY_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: false } const NANOGPT_SCOPE: ModelCacheScope = { urlScoped: false, keyScoped: true, authScoped: false } +const INFER_SCOPE: ModelCacheScope = { urlScoped: false, keyScoped: false, authScoped: false } const ZOO_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: true } const MOONSHOT_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: false } @@ -229,6 +230,24 @@ describe("getModels with new GetModelsOptions", () => { expect(result).toEqual(mockModels) }) + it("dispatches Infer's public catalog without an API key", async () => { + const mockModels = { + "infer/test-model:low-cost": { + maxTokens: 8192, + contextWindow: 128000, + supportsPromptCache: false, + }, + } + const fetchModels = vi.fn().mockResolvedValue(mockModels) + const handler = makeHandler(INFER_SCOPE, fetchModels) + + const options = { provider: providerIdentifiers.infer } as const + const result = await getModels(options, handler) + + expect(fetchModels).toHaveBeenCalledWith(options, expect.any(AbortSignal)) + expect(result).toEqual(mockModels) + }) + it("handles errors and re-throws them", async () => { const expectedError = new Error("LiteLLM connection failed") const fetchModels = vi.fn().mockRejectedValue(expectedError) @@ -1238,6 +1257,30 @@ describe("NanoGPT key-scoped cache isolation", () => { }) }) +describe("Infer shared public catalog cache", () => { + const inferModels = { + "infer/test-model:low-cost": { maxTokens: 8_192, contextWindow: 128_000, supportsPromptCache: false }, + } + + let handler: ApiHandler + + beforeEach(() => { + vi.clearAllMocks() + handler = makeHandler(INFER_SCOPE, vi.fn().mockResolvedValue(inferModels)) + }) + + it("stores one catalog under the bare provider key whatever key is supplied", async () => { + const mockCache = vi.mocked(new (vi.mocked(NodeCache))()) + mockCache.get.mockReturnValue(undefined) + + await getModels({ provider: providerIdentifiers.infer }, handler) + await getModels({ provider: providerIdentifiers.infer, apiKey: "infer-key-a" }, handler) + + const cacheKeys = mockCache.set.mock.calls.map(([key]) => key as string) + expect(new Set(cacheKeys)).toEqual(new Set([providerIdentifiers.infer])) + }) +}) + describe("compound cache key derivation across scoping dimensions", () => { // Exercises every branch of getCacheKey via the public getModels() entry point. // litellm is url-scoped AND key-scoped; openrouter is neither, so it hits the bare diff --git a/src/api/providers/fetchers/infer.ts b/src/api/providers/fetchers/infer.ts new file mode 100644 index 00000000000..c00ef373d91 --- /dev/null +++ b/src/api/providers/fetchers/infer.ts @@ -0,0 +1,147 @@ +import axios from "axios" +import { z } from "zod" + +import { INFER_CATALOG_URL, openAiModelInfoSaneDefaults, type ModelInfo, type ModelRecord } from "@roo-code/types" + +import { throwIfAborted } from "../utils/abort-signal" + +// Each catalog route has an id. The model picker shows its label after the model name. +const INFER_ROUTE_LABELS = new Map([ + ["low-cost", "Low cost"], + ["balanced", "Balanced"], + ["stable", "Stable"], + ["official", "Official"], +]) + +// Image and video generation models use their own endpoints, not chat completions. +const INFER_GENERATION_KINDS = new Set(["image_generation", "video_generation"]) + +const inferRuntimeSchema = z.object({ + max_context_tokens: z.number().nullish(), + max_output_tokens: z.number().nullish(), + vision: z.boolean().optional(), + tools: z.boolean().optional(), + streaming: z.boolean().optional(), +}) + +const inferRouteSchema = z.object({ + selector: z.string().min(1), + available: z.boolean().optional(), + input_per_million_usd: z.number().nonnegative().optional(), + cached_input_per_million_usd: z.number().nonnegative().optional(), + cache_write_per_million_usd: z.number().nonnegative().optional(), + output_per_million_usd: z.number().nonnegative().optional(), + runtime: inferRuntimeSchema.optional(), +}) + +const inferModelSchema = z.object({ + slug: z.string().min(1), + name: z.string().optional(), + kind: z.string().optional(), + runtime: inferRuntimeSchema.optional(), + tiers: z.record(z.string(), z.unknown()), +}) + +const inferCatalogSchema = z.object({ + models: z.array(z.unknown()), +}) + +type InferModel = z.infer +type InferRoute = z.infer +type InferLimit = "max_context_tokens" | "max_output_tokens" + +/** A route limit wins over the model limit. A missing or non-positive value means "not published". */ +const getLimit = (model: InferModel, route: InferRoute, limit: InferLimit): number | undefined => + [route.runtime?.[limit], model.runtime?.[limit]].find( + (value): value is number => typeof value === "number" && value > 0, + ) + +/** Maps one catalog route to model info. Prices are published per 1M tokens in USD, as ModelInfo expects. */ +export const parseInferRoute = (model: InferModel, routeId: string, route: InferRoute): ModelInfo => { + const maxTokens = getLimit(model, route, "max_output_tokens") + + return { + contextWindow: getLimit(model, route, "max_context_tokens") ?? openAiModelInfoSaneDefaults.contextWindow, + ...(maxTokens !== undefined ? { maxTokens } : {}), + // Only some routes accept images, so the flag comes from the route, not the model. + supportsImages: route.runtime?.vision === true, + supportsPromptCache: (route.cached_input_per_million_usd ?? 0) > 0, + ...(route.input_per_million_usd !== undefined ? { inputPrice: route.input_per_million_usd } : {}), + ...(route.output_per_million_usd !== undefined ? { outputPrice: route.output_per_million_usd } : {}), + ...(route.cached_input_per_million_usd !== undefined + ? { cacheReadsPrice: route.cached_input_per_million_usd } + : {}), + ...(route.cache_write_per_million_usd !== undefined + ? { cacheWritesPrice: route.cache_write_per_million_usd } + : {}), + // The name is a remote string and ModelInfo.description is rendered as Markdown, + // so it is only surfaced as the plain-text displayName. + displayName: `${model.name ?? model.slug} (${INFER_ROUTE_LABELS.get(routeId) ?? routeId})`, + } +} + +/** + * Fetches the public Infer catalog and lists each available text route as a model. + * + * The catalog needs no API key and is the same for every account, so no key is sent. + * The model id of a route is its `selector`, for example `infer/claude-opus-5-5:low-cost`. + * + * @param opts - Optional per-request controls; `signal` cancels the in-flight request. + */ +export async function getInferModels(opts?: { signal?: AbortSignal }): Promise { + try { + const response = await axios.get(INFER_CATALOG_URL, { timeout: 10_000, signal: opts?.signal }) + const catalogResult = inferCatalogSchema.safeParse(response.data) + if (!catalogResult.success) { + console.warn("Infer catalog response did not match the expected top-level schema") + return {} + } + + // Use null-prototype object to prevent prototype pollution + const models: ModelRecord = Object.create(null) + for (const rawModel of catalogResult.data.models) { + const modelResult = inferModelSchema.safeParse(rawModel) + if (!modelResult.success) { + console.warn("Skipping invalid Infer catalog model entry") + continue + } + + const model = modelResult.data + if (model.kind !== undefined && INFER_GENERATION_KINDS.has(model.kind)) { + continue + } + + // Gemini models need their thought signatures back on the turn after a tool call, + // and this provider sends no reasoning back, so Gemini routes are left out for now. + if (model.slug.startsWith("gemini-")) { + continue + } + + for (const [routeId, rawRoute] of Object.entries(model.tiers)) { + const routeResult = inferRouteSchema.safeParse(rawRoute) + if (!routeResult.success) { + console.warn("Skipping invalid Infer catalog route entry") + continue + } + + const route = routeResult.data + // Tasks stream their replies and depend on tool calls, so an explicit false + // is authoritative. An omitted flag is unknown and stays eligible. + if (route.available !== true || route.runtime?.tools === false || route.runtime?.streaming === false) { + continue + } + + models[route.selector] = parseInferRoute(model, routeId, route) + } + } + + return models + } catch (error) { + // Surface cancellation as a rejection: logging and returning here would + // present an aborted fetch to callers as a successful (empty) catalog. + throwIfAborted(opts?.signal) + + console.error(`Error fetching Infer models: ${error instanceof Error ? error.message : String(error)}`) + return {} + } +} diff --git a/src/api/providers/index.ts b/src/api/providers/index.ts index 33d90b1c16c..6ce57c21f24 100644 --- a/src/api/providers/index.ts +++ b/src/api/providers/index.ts @@ -30,6 +30,7 @@ export { FriendliHandler } from "./friendli" export { VercelAiGatewayHandler } from "./vercel-ai-gateway" export { OpencodeGoHandler } from "./opencode-go" export { KenariHandler } from "./kenari" +export { InferHandler } from "./infer" export { NanoGptHandler } from "./nanogpt" export { ZooGatewayHandler } from "./zoo-gateway" export { MiniMaxHandler } from "./minimax" diff --git a/src/api/providers/infer.ts b/src/api/providers/infer.ts new file mode 100644 index 00000000000..bec55493764 --- /dev/null +++ b/src/api/providers/infer.ts @@ -0,0 +1,246 @@ +import { Anthropic } from "@anthropic-ai/sdk" +import OpenAI from "openai" + +import { + INFER_BASE_URL, + inferDefaultModelId, + inferDefaultModelInfo, + providerIdentifiers, + type ModelInfo, + type ModelRecord, +} from "@roo-code/types" + +import type { ApiHandlerOptions, GetModelsOptions } from "../../shared/api" + +import type { ApiStream, ApiStreamUsageChunk } from "../transform/stream" +import { convertToOpenAiMessages } from "../transform/openai-format" +import type { + ApiHandlerCreateMessageMetadata, + CompletePromptOptions, + ModelCacheScope, + SingleCompletionHandler, +} from "../index" +import { RouterProvider } from "./router-provider" +import { getInferModels } from "./fetchers/infer" +import { handleProviderError } from "./utils/error-handler" +import { extractReasoningFromDelta } from "./utils/extract-reasoning" +import { hasUsableTimeout, toSdkTimeoutMs } from "./utils/abort-signal" + +/** Infer reports cache writes next to cache reads. */ +type InferUsage = OpenAI.CompletionUsage & { + prompt_tokens_details?: OpenAI.CompletionUsage["prompt_tokens_details"] & { cache_write_tokens?: number } +} + +/** The final chunks also carry `relay`, with the charge that Infer settled for the request. */ +type InferChunk = OpenAI.Chat.ChatCompletionChunk & { relay?: { customer_cost_usd?: number } } + +function mapInferUsage(usage: InferUsage, customerCost: number | undefined): ApiStreamUsageChunk { + return { + type: "usage", + // prompt_tokens includes the cache read and cache write tokens. + inputTokens: usage.prompt_tokens || 0, + outputTokens: usage.completion_tokens || 0, + cacheReadTokens: usage.prompt_tokens_details?.cached_tokens ?? undefined, + cacheWriteTokens: usage.prompt_tokens_details?.cache_write_tokens ?? undefined, + ...(typeof customerCost === "number" && Number.isFinite(customerCost) ? { totalCost: customerCost } : {}), + } +} + +/** + * Infer provider. + * + * OpenAI-compatible Chat Completions endpoint: + * https://infer.flow7.org/v1/chat/completions + * + * A model id selects a model and a route (`infer/:`). The routes are + * listed in the public catalog, which is fetched dynamically. Supports text + * generation, reasoning content, tool calls, and non-streaming prompt completion. + */ +export class InferHandler extends RouterProvider implements SingleCompletionHandler { + /** Creates a new handler bound to the user's API key and selected model. */ + constructor(options: ApiHandlerOptions) { + super({ + // The endpoint is fixed, so the custom headers configured for the + // OpenAI Compatible provider must not be sent to it. + options: { ...options, openAiHeaders: undefined }, + name: providerIdentifiers.infer, + baseURL: INFER_BASE_URL, + apiKey: options.inferApiKey, + modelId: options.inferModelId, + defaultModelId: inferDefaultModelId, + defaultModelInfo: inferDefaultModelInfo, + }) + } + + override getModelCacheScope(): ModelCacheScope { + // The public catalog is the same for every account and needs no key. + return { urlScoped: false, keyScoped: false, authScoped: false } + } + + async fetchModels(_options: GetModelsOptions, signal?: AbortSignal): Promise { + const fetchOpts: [] | [{ signal: AbortSignal }] = signal ? [{ signal }] : [] + return getInferModels(...fetchOpts) + } + + private createSafeError(operation: string, error: unknown): Error { + const apiKey = this.options.inferApiKey + const redact = (text: string) => (apiKey ? text.replaceAll(apiKey, "[REDACTED]") : text) + + // handleProviderError logs the message, stack and the SDK's raw error + // metadata before it applies the transformer, so the key has to be + // scrubbed from the error itself first. + if (error instanceof Error) { + error.message = redact(error.message) + if (error.stack) { + error.stack = redact(error.stack) + } + // handleProviderError calls string methods on this field, so an + // object-valued upstream body is serialized before it is redacted. + const metadata = (error as { error?: { metadata?: { raw?: unknown } } }).error?.metadata + if (metadata && metadata.raw !== undefined && metadata.raw !== null) { + const raw = metadata.raw + metadata.raw = redact(typeof raw === "string" ? raw : (JSON.stringify(raw) ?? String(raw))) + } + } + const safeError = error instanceof Error ? error : redact(String(error)) + + return handleProviderError(safeError, "Infer", { + messagePrefix: operation, + // The transformer input can also come from `error.error.metadata.raw`. + messageTransformer: (message) => `Infer ${operation} error: ${redact(message)}`, + }) + } + + /** A cleared temperature setting is stored as null, so only a number is sent. */ + private getTemperature(modelId: string, info: ModelInfo): number | undefined { + const temperature = this.options.modelTemperature + return typeof temperature === "number" && + info.supportsTemperature !== false && + this.supportsTemperature(modelId) + ? temperature + : undefined + } + + /** + * Streams a chat completion response, yielding typed chunks for text, + * reasoning, partial tool calls, and token usage. + */ + override async *createMessage( + systemPrompt: string, + messages: Anthropic.Messages.MessageParam[], + metadata?: ApiHandlerCreateMessageMetadata, + ): ApiStream { + const { id: modelId, info } = await this.fetchModel() + + const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ + { role: "system", content: systemPrompt }, + ...convertToOpenAiMessages(messages), + ] + + // max_tokens is not sent. Infer holds the cost of the output cap from the wallet + // before a request starts. Without a cap, Infer sets one from the route's output + // room (32,768 tokens at most), so the full output limit of a large model is not held. + const body: OpenAI.Chat.ChatCompletionCreateParamsStreaming = { + model: modelId, + messages: openAiMessages, + stream: true, + stream_options: { include_usage: true }, + tools: this.convertToolsForOpenAI(metadata?.tools), + tool_choice: metadata?.tool_choice, + parallel_tool_calls: metadata?.parallelToolCalls ?? true, + } + + const temperature = this.getTemperature(modelId, info) + if (temperature !== undefined) { + body.temperature = temperature + } + + try { + const completion = await this.client.chat.completions.create(body, { + signal: metadata?.abortSignal, + // Infer keeps the requests of one session on the same route while it is + // healthy. This helps later requests in a task reuse the prompt cache of the route. + ...(metadata?.taskId ? { headers: { "X-Session-Affinity": metadata.taskId } } : {}), + }) + + for await (const chunk of completion) { + const delta = chunk.choices[0]?.delta + + // Infer streams reasoning text in `delta.reasoning`. + const reasoningText = extractReasoningFromDelta(delta) + if (reasoningText) { + yield { type: "reasoning", text: reasoningText } + } + + if (delta?.content) { + yield { type: "text", text: delta.content } + } + + // Emit raw tool call chunks - NativeToolCallParser handles state management. + if (delta?.tool_calls) { + for (const toolCall of delta.tool_calls) { + yield { + type: "tool_call_partial", + index: toolCall.index, + id: toolCall.id, + name: toolCall.function?.name, + arguments: toolCall.function?.arguments, + } + } + } + + if (chunk.usage) { + yield mapInferUsage(chunk.usage, (chunk as InferChunk).relay?.customer_cost_usd) + } + } + } catch (error) { + throw this.createSafeError("streaming", error) + } + } + + /** + * Performs a non-streaming chat completion and returns the full response text. + * + * @param prompt - The user prompt to send as a single user message. + * @returns The model's reply text, or an empty string if no content is returned. + * @throws Error with an Infer prefix if the request fails. + */ + async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + const { id: modelId, info } = await this.fetchModel() + + try { + // max_tokens is not sent, for the same reason as in createMessage. + const requestOptions: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming = { + model: modelId, + messages: [{ role: "user", content: prompt }], + stream: false, + } + + const temperature = this.getTemperature(modelId, info) + if (temperature !== undefined) { + requestOptions.temperature = temperature + } + + // The OpenAI SDK validates a present-but-undefined `timeout` key, so + // request options are only forwarded when they carry a real value. + const completionOptions: OpenAI.RequestOptions = {} + if (options?.abortSignal !== undefined) { + completionOptions.signal = options.abortSignal + } + const timeoutMs = options?.timeoutMs + if (hasUsableTimeout(timeoutMs)) { + completionOptions.timeout = toSdkTimeoutMs(timeoutMs) + } + const hasCompletionOptions = + completionOptions.signal !== undefined || completionOptions.timeout !== undefined + + const response = await this.client.chat.completions.create( + requestOptions, + hasCompletionOptions ? completionOptions : undefined, + ) + return response.choices[0]?.message.content || "" + } catch (error) { + throw this.createSafeError("completion", error) + } + } +} diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 4766f87112f..93143b46719 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -739,6 +739,22 @@ describe("ContextProxy", () => { }) describe("setProviderSettings", () => { + it("stores and returns the complete Infer configuration across secret and global state", async () => { + await proxy.setProviderSettings({ + apiProvider: providerIdentifiers.infer, + inferApiKey: "infer-secret", + inferModelId: "infer/claude-opus-5-5:low-cost", + }) + + expect(mockSecrets.store).toHaveBeenCalledWith("inferApiKey", "infer-secret") + expect(mockGlobalState.update).toHaveBeenCalledWith("inferModelId", "infer/claude-opus-5-5:low-cost") + expect(proxy.getProviderSettings()).toMatchObject({ + apiProvider: providerIdentifiers.infer, + inferApiKey: "infer-secret", + inferModelId: "infer/claude-opus-5-5:low-cost", + }) + }) + it("stores and returns the complete NanoGPT configuration across secret and global state", async () => { await proxy.setProviderSettings({ apiProvider: providerIdentifiers.nanogpt, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa79..ec571a93e7c 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -7312,6 +7312,7 @@ describe("ClineProvider - Router Models", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -7370,6 +7371,7 @@ describe("ClineProvider - Router Models", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -7476,6 +7478,7 @@ describe("ClineProvider - Router Models", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, diff --git a/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts index b7da723414f..da273325bdb 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts @@ -134,6 +134,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -204,6 +206,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -255,6 +259,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -307,6 +313,51 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { expect(getModelsMock.mock.calls[0][1]).toBe(handlerForProvider(providerIdentifiers.openrouter)) }) + it("filters to Infer and fetches its public catalog without the stored key", async () => { + mockProvider.getState.mockResolvedValue({ apiConfiguration: { inferApiKey: "stored-infer-key" } }) + + await webviewMessageHandler(mockProvider, { + type: RouterModelsMessageType.requestRouterModels, + values: { provider: providerIdentifiers.infer }, + }) + + // The catalog is the same for every key, so the stored key is never sent with it. + expect(getModelsMock).toHaveBeenCalledTimes(1) + expect(getModelsMock.mock.calls[0][0]).toStrictEqual({ provider: providerIdentifiers.infer }) + expect(getModelsMock.mock.calls[0][1]).toBe(handlerForProvider(providerIdentifiers.infer)) + expect(flushModelsMock).not.toHaveBeenCalled() + + const response = mockProvider.postMessageToWebview.mock.calls.find( + (call) => call[0]?.type === RouterModelsMessageType.routerModels, + ) + if (!response) throw new Error("Expected routerModels response") + expect(response[0].routerModels).toEqual({ + [providerIdentifiers.infer]: { + "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false }, + }, + }) + }) + + it.each([ + ["uses Infer", { apiProvider: providerIdentifiers.infer, inferApiKey: "stored-infer-key" }, true], + ["uses another provider", { apiProvider: providerIdentifiers.anthropic }, false], + ] as const)( + "fetches Infer's catalog in an aggregate request only when the profile %s", + async (_label, apiConfiguration, fetched) => { + mockProvider.getState.mockResolvedValue({ apiConfiguration }) + + await webviewMessageHandler(mockProvider, { type: RouterModelsMessageType.requestRouterModels }) + + // A Zoo Code install that does not use Infer must not contact it. + const inferCalls = getModelsMock.mock.calls.filter( + ([options]) => options?.provider === providerIdentifiers.infer, + ) + expect(inferCalls.map(([options]) => options)).toStrictEqual( + fetched ? [{ provider: providerIdentifiers.infer }] : [], + ) + }, + ) + it("filters to Kimi Code and dispatches an explicit API key without reading the OAuth token", async () => { const kimiModels = { "kimi-for-coding": { contextWindow: 262_144, supportsPromptCache: true } } getModelsMock.mockResolvedValue(kimiModels) @@ -525,6 +576,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -615,6 +668,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -666,6 +721,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index e1cc7dc8445..2deb71566fb 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1186,6 +1186,11 @@ describe("webviewMessageHandler - requestRouterModels", () => { expect.objectContaining({ provider: providerIdentifiers.kenari }), expect.anything(), ) + // Infer's catalog is fetched only for Infer, so an aggregate request for another profile skips it. + expect(mockGetModels).not.toHaveBeenCalledWith( + expect.objectContaining({ provider: providerIdentifiers.infer }), + expect.anything(), + ) // NanoGPT's detailed catalog is public and may optionally be scoped by a key. expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: undefined }, @@ -1209,6 +1214,7 @@ describe("webviewMessageHandler - requestRouterModels", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -1508,6 +1514,7 @@ describe("webviewMessageHandler - requestRouterModels", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -1574,6 +1581,7 @@ describe("webviewMessageHandler - requestRouterModels", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6641ff259f1..6bbdd6573d8 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -1222,6 +1222,7 @@ export const webviewMessageHandler = async ( [providerIdentifiers.moonshot]: {}, [providerIdentifiers.opencodeGo]: {}, [providerIdentifiers.kenari]: {}, + [providerIdentifiers.infer]: {}, [providerIdentifiers.nanogpt]: {}, [providerIdentifiers.kimiCode]: {}, [providerIdentifiers.friendli]: {}, @@ -1405,6 +1406,16 @@ export const webviewMessageHandler = async ( options: { provider: providerIdentifiers.kenari, apiKey: kenariApiKey }, }) + // Infer's catalog is public and the same for every key, so no key is sent. It is + // fetched only for a request that names Infer or for a profile that uses Infer, so + // an aggregate request from another profile does not contact Infer. + if ( + providerFilter === providerIdentifiers.infer || + apiConfiguration.apiProvider === providerIdentifiers.infer + ) { + candidates.push({ key: providerIdentifiers.infer, options: { provider: providerIdentifiers.infer } }) + } + // NanoGPT's detailed catalog is public, while an optional key can expose a // different allowlist. Prefer an explicitly supplied unsaved key and use the // same key-scoped options for refresh and retrieval. diff --git a/src/shared/__tests__/ProfileValidator.spec.ts b/src/shared/__tests__/ProfileValidator.spec.ts index d9b4c4c5d8a..b1a4644b2ca 100644 --- a/src/shared/__tests__/ProfileValidator.spec.ts +++ b/src/shared/__tests__/ProfileValidator.spec.ts @@ -31,6 +31,7 @@ describe("ProfileValidator", () => { ["ollama", { ollamaModelId: "model" }], ["requesty", { requestyModelId: "model" }], ["unbound", { unboundModelId: "model" }], + ["infer", { inferModelId: "model" }], ["poe", { apiModelId: "model" }], ["moonshot", { apiModelId: "model" }], ["kimiCode", { apiModelId: "model" }], @@ -300,6 +301,25 @@ describe("ProfileValidator", () => { expect(ProfileValidator.isProfileAllowed(profile, allowList)).toBe(true) }) + // Test for infer provider which uses inferModelId + it(`should extract inferModelId for infer provider`, () => { + const allowList: OrganizationAllowList = { + allowAll: false, + providers: { + [providerIdentifiers.infer]: { allowAll: false, models: ["infer/test-model:stable"] }, + }, + } + const profile: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:stable", + } + + expect(ProfileValidator.isProfileAllowed(profile, allowList)).toBe(true) + expect( + ProfileValidator.isProfileAllowed({ ...profile, inferModelId: "infer/test-model:official" }, allowList), + ).toBe(false) + }) + it("should extract vsCodeLmModelSelector.id for vscode-lm provider", () => { const allowList: OrganizationAllowList = { allowAll: false, diff --git a/src/shared/api.ts b/src/shared/api.ts index d65ee30aced..28a795dfbcd 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -184,6 +184,7 @@ const _dynamicProviderExtras = { [providerIdentifiers.moonshot]: {} as { apiKey?: string; baseUrl?: string }, [providerIdentifiers.opencodeGo]: {} as { apiKey?: string }, [providerIdentifiers.kenari]: {} as { apiKey?: string }, + [providerIdentifiers.infer]: {} as object, [providerIdentifiers.nanogpt]: {} as { apiKey?: string }, [providerIdentifiers.kimiCode]: {} as { apiKey?: string }, [providerIdentifiers.friendli]: {} as object, diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index aff93a377ba..fcd5c0f5d41 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -86,6 +86,7 @@ import { VercelAiGateway, OpenCodeGo, Kenari, + Infer, NanoGPT, ZooGateway, MiniMax, @@ -715,6 +716,17 @@ const ApiOptions = ({ /> )} + {selectedProvider === providerIdentifiers.infer && ( + + )} + {selectedProvider === providerIdentifiers.nanogpt && ( { VercelAiGateway: provider("provider-vercel-ai-gateway"), OpenCodeGo: provider("provider-opencode-go"), Kenari: provider("provider-kenari"), + Infer: provider("provider-infer"), NanoGPT: provider("provider-nanogpt"), ZooGateway: provider("provider-zoo-gateway"), MiniMax: provider("provider-minimax"), @@ -403,6 +404,7 @@ describe("ApiOptions interactions", () => { providerIdentifiers.vercelAiGateway, providerIdentifiers.opencodeGo, providerIdentifiers.kenari, + providerIdentifiers.infer, providerIdentifiers.nanogpt, providerIdentifiers.zooGateway, providerIdentifiers.fireworks, diff --git a/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx b/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx index 90f62f5fee5..d8b126299ac 100644 --- a/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx @@ -292,6 +292,7 @@ describe("ApiOptions Provider Filtering", () => { expect(providerValues).toContain("ollama") expect(providerValues).toContain("lmstudio") expect(providerValues).toContain("litellm") + expect(providerValues).toContain("infer") expect(providerValues).toContain("requesty") }) diff --git a/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx b/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx index f9d55fc4699..694b6ef4de2 100644 --- a/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx @@ -517,6 +517,7 @@ describe("ApiOptions", () => { expect(optionTexts).toContain("OpenAI") expect(optionTexts).toContain("Anthropic") expect(optionTexts).toContain("NanoGPT") + expect(optionTexts).toContain("Infer") // Note: The mock doesn't implement search functionality, so we're just verifying // that the select element is rendered with the expected options diff --git a/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx b/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx index 2dce9555e99..9e766d68a9f 100644 --- a/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx @@ -7,6 +7,7 @@ import { type Mock } from "vitest" import { bedrockDefaultModelId, + inferDefaultModelId, litellmDefaultModelId, type ModelInfo, type ProviderSettings, @@ -371,6 +372,43 @@ describe("ModelPicker", () => { }) }) + describe("Infer route selection", () => { + const inferModels: Record = { + "infer/test-model:low-cost": { displayName: "test-model (Low cost)", ...modelInfo }, + "infer/test-model:official": { displayName: "test-model (Official)", ...modelInfo }, + } + + beforeEach(() => { + mockUseRouterModels.mockReturnValue(createRouterModelsResult({ [providerIdentifiers.infer]: inferModels })) + }) + + it("keeps a stored route that the catalog no longer lists instead of reverting to the default", async () => { + // A route can leave the catalog for a while. Requests still use the stored + // selector, so the picker must keep displaying it. + const storedRoute = "infer/test-model:balanced" + const setField = vi.fn() + + await act(async () => { + renderWithExtensionState( + , + { queryClient }, + ) + }) + + expect(screen.getByTestId("model-picker-button")).toHaveTextContent(storedRoute) + expect(setField).not.toHaveBeenCalledWith("inferModelId", inferDefaultModelId, false) + }) + }) + describe("Bedrock pasted ARN", () => { const appProfileArn = "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/abcd1234efgh" const bedrockModels = getStaticModelsForProvider(providerIdentifiers.bedrock) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 758161c1488..a31d3f9861d 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -757,4 +757,85 @@ describe("SettingsView - Unsaved Changes Detection", () => { expect(onDone).toHaveBeenCalledOnce() expect(postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "upsertApiConfiguration" })) }) + + it("buffers and saves the complete Infer provider configuration from cached state", async () => { + const liveApiConfiguration = { + apiProvider: providerIdentifiers.infer, + inferApiKey: "original-key", + inferModelId: "infer/original:low-cost", + } + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + apiConfiguration: liveApiConfiguration, + }) + vi.mocked(ApiOptions).mockImplementation(({ apiConfiguration, setApiConfigurationField }) => ( +
+ setApiConfigurationField("inferApiKey", event.target.value)} + /> + setApiConfigurationField("inferModelId", event.target.value)} + /> +
+ )) + + renderWithExtensionState(, { queryClient }) + + expect(await screen.findByTestId("cached-infer-key")).toHaveValue("original-key") + expect(screen.getByTestId("cached-infer-model")).toHaveValue("infer/original:low-cost") + + fireEvent.change(screen.getByTestId("cached-infer-key"), { target: { value: "unsaved-key" } }) + fireEvent.change(screen.getByTestId("cached-infer-model"), { target: { value: "infer/next:official" } }) + + expect(liveApiConfiguration).toEqual({ + apiProvider: providerIdentifiers.infer, + inferApiKey: "original-key", + inferModelId: "infer/original:low-cost", + }) + expect(postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "upsertApiConfiguration" })) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(postMessage).toHaveBeenCalledWith({ + type: "upsertApiConfiguration", + text: "default", + apiConfiguration: { + apiProvider: providerIdentifiers.infer, + inferApiKey: "unsaved-key", + inferModelId: "infer/next:official", + }, + }) + }) + + it("discards Infer cached edits and restores the extension values", async () => { + const onDone = vi.fn() + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + apiConfiguration: { + apiProvider: providerIdentifiers.infer, + inferApiKey: "saved-key", + inferModelId: "infer/saved:stable", + }, + }) + vi.mocked(ApiOptions).mockImplementation(({ apiConfiguration, setApiConfigurationField }) => ( + setApiConfigurationField("inferApiKey", event.target.value)} + /> + )) + + renderWithExtensionState(, { queryClient }) + fireEvent.change(await screen.findByTestId("cached-infer-key"), { target: { value: "discard-me" } }) + fireEvent.click(screen.getByText("settings:common.done")) + fireEvent.click(await screen.findByText("settings:unsavedChangesDialog.discardButton")) + + await waitFor(() => expect(screen.getByTestId("cached-infer-key")).toHaveValue("saved-key")) + expect(onDone).toHaveBeenCalledOnce() + expect(postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "upsertApiConfiguration" })) + }) }) diff --git a/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx b/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx index 26fec820f2b..b60288ffba3 100644 --- a/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx @@ -1,4 +1,4 @@ -import { bedrockModels, providerIdentifiers } from "@roo-code/types" +import { bedrockModels, inferDefaultModelInfo, providerIdentifiers } from "@roo-code/types" // npx vitest src/components/settings/__tests__/ThinkingBudget.spec.tsx import React from "react" @@ -755,4 +755,35 @@ describe("ThinkingBudget", () => { expect(screen.getByTestId("reasoning-effort")).toBeInTheDocument() }) }) + + // Infer sends no reasoning parameters, so its routes must not offer a reasoning control. + it.each([ + ["the fallback", inferDefaultModelInfo], + [ + "a catalog route", + { + contextWindow: 1_000_000, + maxTokens: 128_000, + supportsImages: false, + supportsPromptCache: true, + inputPrice: 1.97, + outputPrice: 9.81, + displayName: "claude-opus-5-5 (Low cost)", + }, + ], + ])("renders no reasoning control for Infer with %s model info", (_label, modelInfo) => { + const { container } = render( + , + ) + + expect(container).toBeEmptyDOMElement() + }) }) diff --git a/webview-ui/src/components/settings/constants.ts b/webview-ui/src/components/settings/constants.ts index 468010ef6b2..52a33572df9 100644 --- a/webview-ui/src/components/settings/constants.ts +++ b/webview-ui/src/components/settings/constants.ts @@ -71,6 +71,7 @@ export const PROVIDERS: Array<{ value: string; label: string; proxy: boolean }> { value: providerIdentifiers.vercelAiGateway, label: "Vercel AI Gateway", proxy: false }, { value: providerIdentifiers.opencodeGo, label: "Opencode Go", proxy: false }, { value: providerIdentifiers.kenari, label: "Kenari", proxy: false }, + { value: providerIdentifiers.infer, label: "Infer", proxy: false }, { value: providerIdentifiers.nanogpt, label: "NanoGPT", proxy: false }, { value: providerIdentifiers.zooGateway, label: "Zoo Gateway", proxy: false }, { value: providerIdentifiers.minimax, label: "MiniMax", proxy: false }, diff --git a/webview-ui/src/components/settings/providers/Infer.tsx b/webview-ui/src/components/settings/providers/Infer.tsx new file mode 100644 index 00000000000..e1ee5ff9334 --- /dev/null +++ b/webview-ui/src/components/settings/providers/Infer.tsx @@ -0,0 +1,84 @@ +import { useCallback } from "react" +import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" + +import { + type OrganizationAllowList, + type ProviderSettings, + type RouterModels, + inferDefaultModelId, + providerIdentifiers, +} from "@roo-code/types" + +import { VSCodeButtonLink } from "@src/components/common/VSCodeButtonLink" +import { useAppTranslation } from "@src/i18n/TranslationContext" + +import { ModelPicker } from "../ModelPicker" +import { inputEventTransform } from "../transforms" + +type InferProps = { + apiConfiguration: ProviderSettings + setApiConfigurationField: (field: K, value: ProviderSettings[K]) => void + routerModels?: RouterModels + organizationAllowList: OrganizationAllowList + modelValidationError?: string + simplifySettings?: boolean +} + +// The model list comes from Infer's public catalog. The catalog is the same for every +// key, so editing the key does not request a new model list. +export const Infer = ({ + apiConfiguration, + setApiConfigurationField, + routerModels, + organizationAllowList, + modelValidationError, + simplifySettings, +}: InferProps) => { + const { t } = useAppTranslation() + + const handleInputChange = useCallback( + ( + field: K, + transform: (event: E) => ProviderSettings[K] = inputEventTransform, + ) => + (event: E | Event) => { + setApiConfigurationField(field, transform(event as E)) + }, + [setApiConfigurationField], + ) + + return ( + <> + + + +
+ {t("settings:providers.apiKeyStorageNotice")} +
+ {!apiConfiguration.inferApiKey && ( + + {t("settings:providers.infer.getApiKey")} + + )} + + + + ) +} diff --git a/webview-ui/src/components/settings/providers/__tests__/Infer.spec.tsx b/webview-ui/src/components/settings/providers/__tests__/Infer.spec.tsx new file mode 100644 index 00000000000..4a1057f526e --- /dev/null +++ b/webview-ui/src/components/settings/providers/__tests__/Infer.spec.tsx @@ -0,0 +1,137 @@ +import { fireEvent, render, screen } from "@testing-library/react" + +import { + type ModelRecord, + type OrganizationAllowList, + type ProviderSettings, + type RouterModels, + inferDefaultModelId, + providerIdentifiers, +} from "@roo-code/types" + +import { Infer } from "../Infer" + +const { postMessageMock } = vi.hoisted(() => ({ postMessageMock: vi.fn() })) + +vi.mock("@src/utils/vscode", () => ({ vscode: { postMessage: postMessageMock } })) + +vi.mock("@src/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ t: (key: string) => key }), +})) + +vi.mock("@vscode/webview-ui-toolkit/react", () => ({ + VSCodeTextField: ({ + children, + value, + onInput, + type, + }: React.ComponentProps<"input"> & { children: React.ReactNode }) => ( +
+ {children} + +
+ ), +})) + +vi.mock("@src/components/common/VSCodeButtonLink", () => ({ + VSCodeButtonLink: ({ children, href }: React.ComponentProps<"a">) => ( + + {children} + + ), +})) + +vi.mock("../../ModelPicker", () => ({ + ModelPicker: ({ + defaultModelId, + models, + modelIdKey, + serviceName, + serviceUrl, + }: { + defaultModelId: string + models: object + modelIdKey: string + serviceName: string + serviceUrl: string + }) => ( +
+ ), +})) + +describe("Infer", () => { + const organizationAllowList: OrganizationAllowList = { allowAll: true, providers: {} } + const setApiConfigurationField = vi.fn() + const inferModels: ModelRecord = { + "infer/test-model:low-cost": { contextWindow: 1_000_000, maxTokens: 128_000, supportsPromptCache: true }, + "infer/test-model:official": { contextWindow: 1_000_000, maxTokens: 128_000, supportsPromptCache: true }, + } + // The component reads only its own catalog, so the other router entries are left out. + const routerModels = { [providerIdentifiers.infer]: inferModels } as RouterModels + + const renderComponent = (apiConfiguration: ProviderSettings = {}) => + render( + , + ) + + beforeEach(() => vi.clearAllMocks()) + + it("renders the secret key input, the storage notice, and the catalog model picker", () => { + renderComponent({ inferApiKey: "stored" }) + + expect(screen.getByTestId("infer-api-key")).toHaveAttribute("type", "password") + expect(screen.getByText("settings:providers.infer.apiKey")).toBeInTheDocument() + expect(screen.getByText("settings:providers.apiKeyStorageNotice")).toBeInTheDocument() + expect(screen.queryByTestId("infer-get-key")).not.toBeInTheDocument() + + const picker = screen.getByTestId("model-picker") + expect(picker).toHaveAttribute("data-default-model-id", inferDefaultModelId) + expect(picker).toHaveAttribute("data-model-id-key", "inferModelId") + expect(picker).toHaveAttribute("data-model-count", "2") + expect(picker).toHaveAttribute("data-service-name", "settings:providers.infer.provider") + expect(picker).toHaveAttribute("data-service-url", "https://infer.flow7.org/models") + }) + + it("shows the get-key link to the API keys page only when no key is configured", () => { + renderComponent({}) + + expect(screen.getByTestId("infer-get-key")).toHaveAttribute("href", "https://infer.flow7.org/app#/keys") + expect(screen.getByText("settings:providers.infer.getApiKey")).toBeInTheDocument() + }) + + it("updates the cached key with exact values", () => { + renderComponent({ inferApiKey: "" }) + + fireEvent.input(screen.getByTestId("infer-api-key"), { target: { value: "new-secret" } }) + + expect(setApiConfigurationField).toHaveBeenCalledWith("inferApiKey", "new-secret") + }) + + it("does not request a new model list when the key changes", () => { + // The public catalog is the same for every key, so a key edit has nothing to refresh. + const { rerender } = renderComponent({ inferApiKey: "first-key" }) + + rerender( + , + ) + + expect(postMessageMock).not.toHaveBeenCalled() + }) +}) diff --git a/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx b/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx index bdc76a0addd..67429bfd84b 100644 --- a/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx +++ b/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx @@ -103,6 +103,7 @@ describe("NanoGPT", () => { "opencode-go": {}, kenari: {}, nanogpt: { "openai/test": { contextWindow: 1, maxTokens: 1, supportsPromptCache: false } }, + infer: {}, "kimi-code": {}, friendli: {}, ollama: {}, diff --git a/webview-ui/src/components/settings/providers/index.ts b/webview-ui/src/components/settings/providers/index.ts index 12ea4cd7861..b0aa1ba7144 100644 --- a/webview-ui/src/components/settings/providers/index.ts +++ b/webview-ui/src/components/settings/providers/index.ts @@ -26,6 +26,7 @@ export { Friendli } from "./Friendli" export { VercelAiGateway } from "./VercelAiGateway" export { OpenCodeGo } from "./OpenCodeGo" export { Kenari } from "./Kenari" +export { Infer } from "./Infer" export { NanoGPT } from "./NanoGPT" export { ZooGateway } from "./ZooGateway" export { MiniMax } from "./MiniMax" diff --git a/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts b/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts index 5ee319ada19..227d5223ad5 100644 --- a/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts +++ b/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts @@ -2,6 +2,7 @@ import { type RouterModels, anthropicDefaultModelId, friendliModels, + inferDefaultModelId, mainlandZAiDefaultModelId, nanoGptDefaultModelId, providerIdentifiers, @@ -186,6 +187,13 @@ describe("providerModelConfig", () => { default: nanoGptDefaultModelId, }) }) + + it("returns Infer's dynamic model field and fallback", () => { + expect(getProviderModelConfig(providerIdentifiers.infer)).toEqual({ + field: "inferModelId", + default: inferDefaultModelId, + }) + }) }) describe("getProviderDocsSlug", () => { diff --git a/webview-ui/src/components/settings/utils/providerModelConfig.ts b/webview-ui/src/components/settings/utils/providerModelConfig.ts index c70a36a90dc..0f4bb00c13f 100644 --- a/webview-ui/src/components/settings/utils/providerModelConfig.ts +++ b/webview-ui/src/components/settings/utils/providerModelConfig.ts @@ -28,6 +28,7 @@ import { vercelAiGatewayDefaultModelId, opencodeGoDefaultModelId, kenariDefaultModelId, + inferDefaultModelId, nanoGptDefaultModelId, zooGatewayDefaultModelId, getZAiModels, @@ -143,6 +144,7 @@ const PROVIDER_MODEL_CONFIG: Partial> }, [providerIdentifiers.opencodeGo]: { field: "opencodeGoModelId", default: opencodeGoDefaultModelId }, [providerIdentifiers.kenari]: { field: "kenariModelId", default: kenariDefaultModelId }, + [providerIdentifiers.infer]: { field: "inferModelId", default: inferDefaultModelId }, [providerIdentifiers.nanogpt]: { field: "nanoGptModelId", default: nanoGptDefaultModelId }, [providerIdentifiers.zooGateway]: { field: "zooGatewayModelId", default: zooGatewayDefaultModelId }, [providerIdentifiers.openai]: { field: "openAiModelId" }, diff --git a/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts b/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts index 619664b7c6c..b8e067cd27a 100644 --- a/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts +++ b/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts @@ -18,6 +18,8 @@ import { BEDROCK_MAX_TOKENS, bedrockModels, litellmDefaultModelInfo, + inferDefaultModelId, + inferDefaultModelInfo, kenariDefaultModelId, kenariDefaultModelInfo, nanoGptDefaultModelId, @@ -1290,6 +1292,98 @@ describe("useSelectedModel", () => { }) }) + describe("infer provider", () => { + beforeEach(() => { + mockUseOpenRouterModelProviders.mockReturnValue(createOpenRouterModelProvidersResult({})) + }) + + it("uses the catalog metadata of the configured Infer route", () => { + const routeInfo: ModelInfo = { + maxTokens: 128_000, + contextWindow: 1_000_000, + supportsImages: true, + supportsPromptCache: true, + inputPrice: 5, + outputPrice: 25, + displayName: "test-model (Official)", + } + mockUseRouterModels.mockReturnValue( + createRouterModelsResult({ [providerIdentifiers.infer]: { "infer/test-model:official": routeInfo } }), + ) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:official", + }), + { wrapper: createWrapper() }, + ) + + expect(result.current.id).toBe("infer/test-model:official") + expect(result.current.info).toEqual(routeInfo) + }) + + it("uses Infer's shared fallback when its catalog is empty", () => { + mockUseRouterModels.mockReturnValue(createRouterModelsResult({ [providerIdentifiers.infer]: {} })) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + // inferModelId intentionally omitted + }), + { wrapper: createWrapper() }, + ) + + expect(result.current.id).toBe(inferDefaultModelId) + expect(result.current.info).toEqual(inferDefaultModelInfo) + }) + + it("preserves a configured route that is absent from the fetched catalog", () => { + mockUseRouterModels.mockReturnValue( + createRouterModelsResult({ + [providerIdentifiers.infer]: { + "infer/test-model:low-cost": { contextWindow: 1_000_000, supportsPromptCache: true }, + }, + }), + ) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:balanced", + }), + { wrapper: createWrapper() }, + ) + + // A route can leave the catalog for a while. Requests still use the stored + // selector, so the picker shows it; only the metadata falls back. + expect(result.current.id).toBe("infer/test-model:balanced") + expect(result.current.info).toEqual(inferDefaultModelInfo) + }) + + it("preserves the configured route when the catalog fetch errors", () => { + mockUseRouterModels.mockReturnValue( + createRouterModelsResult(undefined, { isLoading: false, isError: true }), + ) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:stable", + }), + { wrapper: createWrapper() }, + ) + + expect(result.current.id).toBe("infer/test-model:stable") + expect(result.current.info).toEqual(inferDefaultModelInfo) + expect(result.current.isError).toBe(true) + }) + }) + describe("openai provider", () => { beforeEach(() => { mockUseRouterModels.mockReturnValue(createRouterModelsResult({ openrouter: {}, requesty: {}, litellm: {} })) diff --git a/webview-ui/src/components/ui/hooks/useSelectedModel.ts b/webview-ui/src/components/ui/hooks/useSelectedModel.ts index 5eb3c64b2ea..43cfa0b935a 100644 --- a/webview-ui/src/components/ui/hooks/useSelectedModel.ts +++ b/webview-ui/src/components/ui/hooks/useSelectedModel.ts @@ -30,6 +30,7 @@ import { lMStudioDefaultModelInfo, opencodeGoDefaultModelInfo, kenariDefaultModelInfo, + inferDefaultModelInfo, nanoGptDefaultModelInfo, BEDROCK_1M_CONTEXT_MODEL_IDS, BEDROCK_DEFAULT_CONTEXT, @@ -125,16 +126,17 @@ export const useSelectedModel = (apiConfiguration: ProviderSettings) => { const needLmStudio = typeof lmStudioModelId !== "undefined" const needOllama = typeof ollamaModelId !== "undefined" - // LiteLLM may legitimately have no entry in the router payload (partial - // listing, failed fetch, renamed deployment) even though the configured ID - // is a valid selection, so it only needs the fetch to settle. Other - // dynamic providers require a populated provider entry before the - // selection is resolved. + // LiteLLM and Infer may legitimately have no entry in the router payload + // (partial listing, failed fetch, renamed deployment, a route that is out + // of the catalog for a while) even though the configured ID is a valid + // selection, so they only need the fetch to settle. Other dynamic + // providers require a populated provider entry before the selection is + // resolved. const hasValidRouterData = needRouterModels && dynamicProvider ? dynamicProvider === providerIdentifiers.friendli ? true // static friendliModels cover the window before /v1/models data arrives - : dynamicProvider === providerIdentifiers.litellm + : dynamicProvider === providerIdentifiers.litellm || dynamicProvider === providerIdentifiers.infer ? !routerModels.isLoading : routerModels.data && routerModels.data[dynamicProvider] !== undefined && @@ -569,6 +571,14 @@ function getSelectedModel({ const info = routerModels[providerIdentifiers.kenari]?.[id] ?? kenariDefaultModelInfo return { id, info } } + case providerIdentifiers.infer: { + // Keep the configured route selector even when the catalog does not list it: + // the handler sends requests with it, and a route can be out of the catalog + // for a while. Only the metadata falls back. + const id = apiConfiguration.inferModelId || defaultModelId + const info = routerModels[providerIdentifiers.infer]?.[id] ?? inferDefaultModelInfo + return { id, info } + } case providerIdentifiers.nanogpt: { const id = getValidatedModelId( apiConfiguration.nanoGptModelId, diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index 77898bd46ee..468dadd2393 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obtenir clau API de Opencode Go", "kenariApiKey": "Clau API de Kenari", "getKenariApiKey": "Obtenir clau API de Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Clau API d'Infer", + "getApiKey": "Obtenir clau API d'Infer", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Clau API de NanoGPT", diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index a62232017d9..f73dec09cf5 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API-Schlüssel erhalten", "kenariApiKey": "Kenari API-Schlüssel", "getKenariApiKey": "Kenari API-Schlüssel erhalten", + "infer": { + "provider": "Infer", + "apiKey": "Infer API-Schlüssel", + "getApiKey": "Infer API-Schlüssel holen", + "model": "Modell" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API-Schlüssel", diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index ab1d9020dc5..722aedf9b50 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -464,6 +464,12 @@ "getOpencodeGoApiKey": "Get Opencode Go API Key", "kenariApiKey": "Kenari API Key", "getKenariApiKey": "Get Kenari API Key", + "infer": { + "provider": "Infer", + "apiKey": "Infer API Key", + "getApiKey": "Get Infer API Key", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API Key", diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 978d51427dc..374545edd1a 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obtener clave API de Opencode Go", "kenariApiKey": "Clave API de Kenari", "getKenariApiKey": "Obtener clave API de Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Clave API de Infer", + "getApiKey": "Obtener clave API de Infer", + "model": "Modelo" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Clave API de NanoGPT", diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index 5114ab8605b..f8c7488efd0 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obtenir la clé API Opencode Go", "kenariApiKey": "Clé API Kenari", "getKenariApiKey": "Obtenir la clé API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Clé API Infer", + "getApiKey": "Obtenir une clé API Infer", + "model": "Modèle" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Clé API NanoGPT", diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index 8d05339db00..0d5f190c509 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API कुंजी प्राप्त करें", "kenariApiKey": "Kenari API कुंजी", "getKenariApiKey": "Kenari API कुंजी प्राप्त करें", + "infer": { + "provider": "Infer", + "apiKey": "Infer API कुंजी", + "getApiKey": "Infer API कुंजी प्राप्त करें", + "model": "मॉडल" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API कुंजी", diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index df4e4545dc8..58338f8fb90 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Dapatkan Opencode Go API Key", "kenariApiKey": "Kenari API Key", "getKenariApiKey": "Dapatkan Kenari API Key", + "infer": { + "provider": "Infer", + "apiKey": "Kunci API Infer", + "getApiKey": "Dapatkan Kunci API Infer", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API Key", diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index 451c8af29be..6065f778079 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Ottieni chiave API Opencode Go", "kenariApiKey": "Chiave API Kenari", "getKenariApiKey": "Ottieni chiave API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Chiave API Infer", + "getApiKey": "Ottieni chiave API Infer", + "model": "Modello" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Chiave API NanoGPT", diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index 0bdf8d6de36..4389f3d5176 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Opencode Go APIキーを取得", "kenariApiKey": "Kenari APIキー", "getKenariApiKey": "Kenari APIキーを取得", + "infer": { + "provider": "Infer", + "apiKey": "Infer APIキー", + "getApiKey": "Infer APIキーを取得", + "model": "モデル" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT APIキー", diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index d0f1bd28103..9de5f937ff5 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Opencode Go API 키 받기", "kenariApiKey": "Kenari API 키", "getKenariApiKey": "Kenari API 키 받기", + "infer": { + "provider": "Infer", + "apiKey": "Infer API 키", + "getApiKey": "Infer API 키 받기", + "model": "모델" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API 키", diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index 880a2784d7d..7af26e4f0f3 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API-sleutel ophalen", "kenariApiKey": "Kenari API-sleutel", "getKenariApiKey": "Kenari API-sleutel ophalen", + "infer": { + "provider": "Infer", + "apiKey": "Infer API-sleutel", + "getApiKey": "Infer API-sleutel ophalen", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API-sleutel", diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index 58b5b024c8a..a017b4bb03d 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -393,6 +393,12 @@ "getOpencodeGoApiKey": "Uzyskaj klucz API Opencode Go", "kenariApiKey": "Klucz API Kenari", "getKenariApiKey": "Uzyskaj klucz API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Klucz API Infer", + "getApiKey": "Uzyskaj klucz API Infer", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Klucz API NanoGPT", diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index 356690664fa..9445c33590b 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obter chave API do Opencode Go", "kenariApiKey": "Chave API do Kenari", "getKenariApiKey": "Obter chave API do Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Chave de API do Infer", + "getApiKey": "Obter chave de API do Infer", + "model": "Modelo" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Chave API do NanoGPT", diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 6e98db3dea6..abef5db2ea7 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -393,6 +393,12 @@ "getOpencodeGoApiKey": "Получить ключ API Opencode Go", "kenariApiKey": "Ключ API Kenari", "getKenariApiKey": "Получить ключ API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "API-ключ Infer", + "getApiKey": "Получить API-ключ Infer", + "model": "Модель" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Ключ API NanoGPT", diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index b95babadde3..8596d008ef4 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API Anahtarı Al", "kenariApiKey": "Kenari API Anahtarı", "getKenariApiKey": "Kenari API Anahtarı Al", + "infer": { + "provider": "Infer", + "apiKey": "Infer API Anahtarı", + "getApiKey": "Infer API Anahtarı Al", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API Anahtarı", diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index d73715351c1..756361128c6 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Lấy khóa API Opencode Go", "kenariApiKey": "Khóa API Kenari", "getKenariApiKey": "Lấy khóa API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Khóa API Infer", + "getApiKey": "Lấy khóa API Infer", + "model": "Mô hình" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Khóa API NanoGPT", diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 096d0cfabd6..98defd469c1 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "获取 Opencode Go API 密钥", "kenariApiKey": "Kenari API 密钥", "getKenariApiKey": "获取 Kenari API 密钥", + "infer": { + "provider": "Infer", + "apiKey": "Infer API 密钥", + "getApiKey": "获取 Infer API 密钥", + "model": "模型" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API 密钥", diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index ec1f23f7219..db1670b9c86 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -417,6 +417,12 @@ "getOpencodeGoApiKey": "取得 Opencode Go API 金鑰", "kenariApiKey": "Kenari API 金鑰", "getKenariApiKey": "取得 Kenari API 金鑰", + "infer": { + "provider": "Infer", + "apiKey": "Infer API 金鑰", + "getApiKey": "取得 Infer API 金鑰", + "model": "模型" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API 金鑰", diff --git a/webview-ui/src/utils/__tests__/validate.spec.ts b/webview-ui/src/utils/__tests__/validate.spec.ts index 816d0cefc5b..48dfddebfb5 100644 --- a/webview-ui/src/utils/__tests__/validate.spec.ts +++ b/webview-ui/src/utils/__tests__/validate.spec.ts @@ -49,6 +49,7 @@ describe("Model Validation Functions", () => { requesty: {}, unbound: {}, litellm: {}, + infer: {}, ollama: {}, lmstudio: {}, "vercel-ai-gateway": {}, @@ -470,6 +471,46 @@ describe("Model Validation Functions", () => { }) }) + describe("Infer validation", () => { + it("returns an apiKey error when the Infer API key is unset", () => { + const config: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:low-cost", + } + + expect(validateApiConfiguration(config, t, mockRouterModels)).toBe("settings:validation.apiKey") + }) + + it("accepts an Infer API key and selected route", () => { + const config: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferApiKey: "valid-key", + inferModelId: "infer/test-model:low-cost", + } + + expect(validateApiConfiguration(config, t, mockRouterModels)).toBeUndefined() + }) + + it("reports a selected route that the fetched catalog no longer lists", () => { + const config: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferApiKey: "valid-key", + inferModelId: "infer/test-model:balanced", + } + const routerModels: RouterModels = { + ...mockRouterModels, + infer: { + "infer/test-model:low-cost": { contextWindow: 128_000, supportsPromptCache: false }, + "infer/test-model:official": { contextWindow: 128_000, supportsPromptCache: false }, + }, + } + + expect(getModelValidationError(config, t, routerModels, allowAllOrganization)).toBe( + "settings:validation.modelAvailability modelId=infer/test-model:balanced", + ) + }) + }) + describe("NanoGPT validation", () => { it("returns an apiKey error when the NanoGPT API key is missing", () => { const config: ProviderSettings = { diff --git a/webview-ui/src/utils/validate.ts b/webview-ui/src/utils/validate.ts index aa34fa4e8d3..119c3d46b72 100644 --- a/webview-ui/src/utils/validate.ts +++ b/webview-ui/src/utils/validate.ts @@ -191,6 +191,11 @@ function validateModelsAndKeysProvided( return t("settings:validation.apiKey") } break + case providerIdentifiers.infer: + if (!apiConfiguration.inferApiKey) { + return t("settings:validation.apiKey") + } + break case providerIdentifiers.nanogpt: if (!apiConfiguration.nanoGptApiKey) { return t("settings:validation.apiKey") From cd9b967b247dbf91988694cf09afbb536f6382f6 Mon Sep 17 00:00:00 2001 From: Infer by Flow7 Date: Wed, 18 Nov 2026 03:23:05 -0500 Subject: [PATCH 2/4] test(webview): add a visual snapshot test for the Infer settings Add a Story Gallery story, a visual test and its baseline for the Infer settings of an unconfigured profile. The visual-regression workflow made the baseline in the pinned Playwright container (run 44874919723), as webview-ui/AGENTS.md describes. Co-Authored-By: Claude Opus 5.5 --- webview-ui/playwright/gallery/stories.tsx | 33 ++++++++++++++++++ .../providers/__tests__/Infer.visual.tsx | 10 ++++++ .../__screenshots__/infer-settings.png | Bin 0 -> 22575 bytes 3 files changed, 43 insertions(+) create mode 100644 webview-ui/src/components/settings/providers/__tests__/Infer.visual.tsx create mode 100644 webview-ui/src/components/settings/providers/__tests__/__screenshots__/infer-settings.png diff --git a/webview-ui/playwright/gallery/stories.tsx b/webview-ui/playwright/gallery/stories.tsx index 9dca3490895..fe53a3e8d37 100644 --- a/webview-ui/playwright/gallery/stories.tsx +++ b/webview-ui/playwright/gallery/stories.tsx @@ -320,6 +320,39 @@ export const stories: Record = { ) }, + "infer-settings": async () => { + const [{ AppProviders }, { Infer }, { providerIdentifiers }] = await Promise.all([ + import("../AppProviders"), + import("@/components/settings/providers/Infer"), + import("@roo-code/types"), + ]) + type ProviderSettings = React.ComponentProps["apiConfiguration"] + + function InferSettingsStory() { + const [apiConfiguration, setApiConfiguration] = useState({ + apiProvider: providerIdentifiers.infer, + }) + return ( +
+
+ + setApiConfiguration((current) => ({ ...current, [field]: value })) + } + organizationAllowList={{ allowAll: true, providers: {} }} + /> +
+
+ ) + } + + return ( + + + + ) + }, "layout-clipped-text": () => (
diff --git a/webview-ui/src/components/settings/providers/__tests__/Infer.visual.tsx b/webview-ui/src/components/settings/providers/__tests__/Infer.visual.tsx new file mode 100644 index 00000000000..9a6a507fef6 --- /dev/null +++ b/webview-ui/src/components/settings/providers/__tests__/Infer.visual.tsx @@ -0,0 +1,10 @@ +import { expect, test } from "../../../../../playwright/coverage-fixture" +import { mountedStory } from "../../../../../playwright/mounted-story" + +test("renders the Infer settings for an unconfigured profile", async ({ mount, page }) => { + await page.setViewportSize({ width: 480, height: 480 }) + const component = mountedStory(await mount("infer-settings")) + const story = component.getByTestId("infer-settings-story") + + await expect(story).toHaveScreenshot("infer-settings.png") +}) diff --git a/webview-ui/src/components/settings/providers/__tests__/__screenshots__/infer-settings.png b/webview-ui/src/components/settings/providers/__tests__/__screenshots__/infer-settings.png new file mode 100644 index 0000000000000000000000000000000000000000..1efdd115be5ede1182921d8700e51e23f26441b6 GIT binary patch literal 22575 zcmcG$RZv{fyX_kx!QCOayF+kyclY29jazVs;O_43?(Xiv-QCa1|K44VuJ!2~znr|B911G<+9gyDeds9t&A8S%PUS>6 z(@v3JWN0up1YszYHTesnFVs*+Ac?*>J~6C1$9lR)Cupns?40?im+dWhSv6J@Ky3axO9{#(ip_!L-bIPD5RTPn$fJ9pp3bI=E}5bQE7|Q-Az!((sNg|rzsrodVKMS z$cLZ)e!SB=rb;d=Xo8x(9*3fHsjdfQ*PVI}4VWt3ccV|{d`&Xne`yvYf${&$PYeG| z>in^;YolE1++RN?B^g;dq{(_0;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?3*&j>@AG6Xy76RorKb3 zD$dp-etqIZh`0*pnQWOCkVAiD2E!3x?|Vqg;tr{t;n0Yl9R1_;c&pSA-p&&@hoCmY z7U&YAssRwcxz5o^(0#)9d+tMN%qZ@Bjo^#^zcPnk8Uevtosmm|U8ZNi#~I{&TtHnD zde>x6l4P5xCzFyLVT!RJe&)t{-S_vK4-b3dVkBLl=D zuhvXYPMRD`-vQuq(zkCFMvaV-`v4^IVChn7!UhM&^6+l*=akoECIIU)5c%oZ?)P|- zGZf;U8d$-+Oh~$w$@x9Z>t`W5)n}My?g$A9T{29M8>l)*T=kH+7PsAQ&eFOpUS4lcUSi7*D09%OYkUs{?O{7CXWhrkx}ocxLJP zL+0O9#UZRQs(Awy>|OHe7f)MKesPmG={Y-HYp~vQ|Nir?Pn|}s1bvu(O)_9$+3p9{ z=3YHMN*SSFu;(@xETst{n2V3zHv~uvj-OXQ&o)D2l3Mt>8AvG7Jd+9xc&O+sxMPtQ zJ;{eNlzg5&Y)LQ&hCmV;> z?e{o)>M=J?zD^rlto#dF>FaszPv1T1z&dvryc;B4sc)}mm3wxm7sJwX;ql`%?*r5F zu6ch?@`Ze}UcRkcmoT?A_ZmOg!x>R;cs z%0~a?_sT^#F#iQYox%Pt9y=@TEB>wTtm~FB&*__$0CZ9A1$7nBBs%@rQ?JhN{&5`B z-qzwD)-=zC-IenLTV#U17{tcDj6`mK2*1Qw*h{~4+X}E4ihR3m7VjWgU9jF zVT9e%(qPf+U8L0hnVwVEUUF6fWVz+ZR0r!`OepYO$t#7zm6gUuohL3 Date: Sat, 21 Nov 2026 10:57:13 -0500 Subject: [PATCH 3/4] fix(api): address review findings for the Infer provider - Price cache writes at the input rate when a route has no separate cache-write price (an omitted or zero rate), as the Infer docs state. - Wait for the catalog with ensureModelFetched(abortSignal) in both request paths, so a cancelled request stops waiting for a cold fetch. - Add tests for both changes and for the default route that is stored when the provider changes to Infer. Co-Authored-By: Claude Opus 5.5 --- src/api/providers/__tests__/infer.spec.ts | 22 +++++++++++++++ .../fetchers/__tests__/infer.spec.ts | 28 +++++++++++++++++++ src/api/providers/fetchers/infer.ts | 10 +++++-- src/api/providers/infer.ts | 7 +++-- .../settings/__tests__/ApiOptions.spec.tsx | 26 ++++++++++++++++- 5 files changed, 87 insertions(+), 6 deletions(-) diff --git a/src/api/providers/__tests__/infer.spec.ts b/src/api/providers/__tests__/infer.spec.ts index 477c1830875..ea4b98102ee 100644 --- a/src/api/providers/__tests__/infer.spec.ts +++ b/src/api/providers/__tests__/infer.spec.ts @@ -313,6 +313,28 @@ describe("InferHandler", () => { }, ) + it.each([ + { + entry: "createMessage", + run: (h: InferHandler, signal: AbortSignal) => + h.createMessage("system", messages, { taskId: "t", abortSignal: signal }).next(), + }, + { + entry: "completePrompt", + run: (h: InferHandler, signal: AbortSignal) => h.completePrompt("ping", { abortSignal: signal }), + }, + ])("$entry stops waiting for a cold catalog when the caller aborts", async ({ run }) => { + vi.mocked(getModels).mockReturnValueOnce(new Promise(() => {})) + const controller = new AbortController() + const handler = new InferHandler({ inferModelId: MODEL_ID }) + const pending = run(handler, controller.signal) + + controller.abort() + + await expect(pending).rejects.toMatchObject({ name: "AbortError" }) + expect(mockCreate).not.toHaveBeenCalled() + }) + it("does not send the OpenAI Compatible custom headers to the fixed endpoint", () => { new InferHandler({ inferApiKey: "test-key", openAiHeaders: { "X-Custom-Header": "leaked" } }) expect(vi.mocked(OpenAI)).toHaveBeenCalledTimes(1) diff --git a/src/api/providers/fetchers/__tests__/infer.spec.ts b/src/api/providers/fetchers/__tests__/infer.spec.ts index 39115254857..2c337ad06bf 100644 --- a/src/api/providers/fetchers/__tests__/infer.spec.ts +++ b/src/api/providers/fetchers/__tests__/infer.spec.ts @@ -111,6 +111,34 @@ describe("Infer model fetcher", () => { }) }) + it.each([ + ["omitted", undefined], + ["zero", 0], + ])("prices cache writes at the input rate when the cache-write rate is %s", async (_label, rate) => { + const overrides: Record = + rate === undefined ? { cache_write_per_million_usd: undefined } : { cache_write_per_million_usd: rate } + mockCatalog([model("model-a", { "low-cost": route("infer/model-a:low-cost", overrides) })]) + + const models = await getInferModels() + + expect(models["infer/model-a:low-cost"].cacheWritesPrice).toBe(2) + }) + + it("omits the cache-write price when the route publishes no prices", async () => { + mockCatalog([ + model("model-a", { + "low-cost": route("infer/model-a:low-cost", { + input_per_million_usd: undefined, + cache_write_per_million_usd: undefined, + }), + }), + ]) + + const models = await getInferModels() + + expect(models["infer/model-a:low-cost"]).not.toHaveProperty("cacheWritesPrice") + }) + it.each([ ["balanced", "Balanced"], ["stable", "Stable"], diff --git a/src/api/providers/fetchers/infer.ts b/src/api/providers/fetchers/infer.ts index c00ef373d91..a7906f82492 100644 --- a/src/api/providers/fetchers/infer.ts +++ b/src/api/providers/fetchers/infer.ts @@ -59,6 +59,12 @@ const getLimit = (model: InferModel, route: InferRoute, limit: InferLimit): numb /** Maps one catalog route to model info. Prices are published per 1M tokens in USD, as ModelInfo expects. */ export const parseInferRoute = (model: InferModel, routeId: string, route: InferRoute): ModelInfo => { const maxTokens = getLimit(model, route, "max_output_tokens") + // Infer bills cache writes at the input rate when a route has no separate cache-write + // price. The catalog shows that as an omitted or zero rate. + const cacheWritesPrice = + route.cache_write_per_million_usd !== undefined && route.cache_write_per_million_usd > 0 + ? route.cache_write_per_million_usd + : route.input_per_million_usd return { contextWindow: getLimit(model, route, "max_context_tokens") ?? openAiModelInfoSaneDefaults.contextWindow, @@ -71,9 +77,7 @@ export const parseInferRoute = (model: InferModel, routeId: string, route: Infer ...(route.cached_input_per_million_usd !== undefined ? { cacheReadsPrice: route.cached_input_per_million_usd } : {}), - ...(route.cache_write_per_million_usd !== undefined - ? { cacheWritesPrice: route.cache_write_per_million_usd } - : {}), + ...(cacheWritesPrice !== undefined ? { cacheWritesPrice } : {}), // The name is a remote string and ModelInfo.description is rendered as Markdown, // so it is only surfaced as the plain-text displayName. displayName: `${model.name ?? model.slug} (${INFER_ROUTE_LABELS.get(routeId) ?? routeId})`, diff --git a/src/api/providers/infer.ts b/src/api/providers/infer.ts index bec55493764..ea5e0890089 100644 --- a/src/api/providers/infer.ts +++ b/src/api/providers/infer.ts @@ -130,7 +130,9 @@ export class InferHandler extends RouterProvider implements SingleCompletionHand messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { - const { id: modelId, info } = await this.fetchModel() + // A cancelled task stops waiting for the catalog. The shared catalog fetch continues. + await this.ensureModelFetched(metadata?.abortSignal) + const { id: modelId, info } = this.getModel() const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ { role: "system", content: systemPrompt }, @@ -206,7 +208,8 @@ export class InferHandler extends RouterProvider implements SingleCompletionHand * @throws Error with an Infer prefix if the request fails. */ async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { - const { id: modelId, info } = await this.fetchModel() + await this.ensureModelFetched(options?.abortSignal) + const { id: modelId, info } = this.getModel() try { // max_tokens is not sent, for the same reason as in createMessage. diff --git a/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx b/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx index 694b6ef4de2..c5b8f135be7 100644 --- a/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx @@ -4,7 +4,12 @@ import { retiredProviderIdentifiers, providerIdentifiers } from "@roo-code/types import { renderWithExtensionState, screen, fireEvent, within } from "@/utils/test-utils" import { type ModelInfo, type ProviderSettings, openAiModelInfoSaneDefaults } from "@roo-code/types" -import { openAiCodexDefaultModelId, opencodeGoModels, zooGatewayDefaultModelId } from "@roo-code/types" +import { + inferDefaultModelId, + openAiCodexDefaultModelId, + opencodeGoModels, + zooGatewayDefaultModelId, +} from "@roo-code/types" import { useSelectedModel } from "@src/components/ui/hooks/useSelectedModel" @@ -365,6 +370,25 @@ describe("ApiOptions", () => { expect(mockSetApiConfigurationField).toHaveBeenCalledWith("zooGatewayModelId", zooGatewayDefaultModelId, false) }) + it.each([ + { stored: undefined, expected: inferDefaultModelId }, + { stored: "infer/claude-opus-5-5:official", expected: undefined }, + ])("stores the default Infer route on switch only when none is stored ($stored)", ({ stored, expected }) => { + const mockSetApiConfigurationField = vi.fn() + + renderApiOptions({ + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, inferApiKey: "key", inferModelId: stored }, + setApiConfigurationField: mockSetApiConfigurationField, + }) + + const providerSelect = screen.getByTestId("provider-select").querySelector("select") as HTMLSelectElement + fireEvent.change(providerSelect, { target: { value: providerIdentifiers.infer } }) + + expect(mockSetApiConfigurationField).toHaveBeenCalledWith("apiProvider", providerIdentifiers.infer) + const modelIdWrites = mockSetApiConfigurationField.mock.calls.filter(([field]) => field === "inferModelId") + expect(modelIdWrites).toEqual(expected === undefined ? [] : [["inferModelId", expected, false]]) + }) + it("renders the Friendli provider form when friendli is selected", () => { renderApiOptions({ apiConfiguration: { From 15672faf1f677ff00665da8ad09d94057ecddd17 Mon Sep 17 00:00:00 2001 From: Infer by Flow7 Date: Tue, 24 Nov 2026 10:52:30 -0500 Subject: [PATCH 4/4] test(api): add the optional review tests for the Infer provider - A settled charge of 0 maps to a total cost of 0. - InferHandler.getModelCacheScope() shares one cache across URLs, keys and auth. - The negative aggregate-request row uses a stored inferApiKey. Co-Authored-By: Claude Opus 5.5 --- src/api/providers/__tests__/infer.spec.ts | 23 +++++++++++++++++++ ...webviewMessageHandler.routerModels.spec.ts | 6 ++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/api/providers/__tests__/infer.spec.ts b/src/api/providers/__tests__/infer.spec.ts index ea4b98102ee..087b197b53b 100644 --- a/src/api/providers/__tests__/infer.spec.ts +++ b/src/api/providers/__tests__/infer.spec.ts @@ -49,6 +49,14 @@ describe("InferHandler", () => { expect(buildApiHandler({ apiProvider: providerIdentifiers.infer })).toBeInstanceOf(InferHandler) }) + it("shares one model cache across URLs, keys and auth, because the catalog is public", () => { + expect(new InferHandler({ inferApiKey: "test-key" }).getModelCacheScope()).toEqual({ + urlScoped: false, + keyScoped: false, + authScoped: false, + }) + }) + it("sends requests to the fixed Infer endpoint with the configured key", () => { new InferHandler({ inferApiKey: "test-key" }) expect(vi.mocked(OpenAI)).toHaveBeenCalledWith( @@ -187,6 +195,21 @@ describe("InferHandler", () => { ).toEqual([{ type: "usage", inputTokens: 20, outputTokens: 10, cacheReadTokens: 0, cacheWriteTokens: 0 }]) }) + it("reports a settled charge of zero as a total cost of zero", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { + choices: [], + usage: { prompt_tokens: 20, completion_tokens: 10 }, + relay: { customer_cost_usd: 0 }, + }, + ]), + ) + expect( + await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)), + ).toEqual([{ type: "usage", inputTokens: 20, outputTokens: 10, totalCost: 0 }]) + }) + it.each(["0.0042", Number.POSITIVE_INFINITY, null])( "does not report a charge that is not a finite number (%s)", async (charge) => { diff --git a/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts index da273325bdb..1c915462b3f 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts @@ -340,7 +340,11 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { it.each([ ["uses Infer", { apiProvider: providerIdentifiers.infer, inferApiKey: "stored-infer-key" }, true], - ["uses another provider", { apiProvider: providerIdentifiers.anthropic }, false], + [ + "uses another provider", + { apiProvider: providerIdentifiers.anthropic, inferApiKey: "stored-infer-key" }, + false, + ], ] as const)( "fetches Infer's catalog in an aggregate request only when the profile %s", async (_label, apiConfiguration, fetched) => {