Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: show the right reasoning effort and image options for every API model (#10933)

Nilay02751d21f39b
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index e158660e300..0fe082bc82e 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -617,6 +617,7 @@ _MISTRAL_THINKING_SPECS = (
),
)
+_OPENROUTER_REASONING_EFFORTS = frozenset({"minimal", "low", "medium", "high", "xhigh", "max"})
_OPENROUTER_MANDATORY_REASONING_MODELS = frozenset(
{
"~google/gemini-pro-latest",
@@ -1298,15 +1299,15 @@ class ExternalProviderClient:
# (`*_MANDATORY_REASONING_MODELS`) 400 on explicit off.
if self.provider_type == "openrouter":
normalized_or_model = model.strip().lower()
- if reasoning_effort in ("low", "medium", "high"):
+ if reasoning_effort in _OPENROUTER_REASONING_EFFORTS:
body["reasoning"] = {"effort": reasoning_effort}
- elif enable_thinking is True:
- body["reasoning"] = {"enabled": True}
- elif enable_thinking is False:
+ elif reasoning_effort == "none" or enable_thinking is False:
if normalized_or_model in _OPENROUTER_MANDATORY_REASONING_MODELS:
body.pop("reasoning", None)
else:
body["reasoning"] = {"enabled": False}
+ elif enable_thinking is True:
+ body["reasoning"] = {"enabled": True}
# OpenRouter web plugin works on every model id including meta-routers (unlike `:online`). Forced-function
# tool_choice suppresses it, matching Gemini/Anthropic.
diff --git a/studio/backend/core/inference/provider_model_capabilities.py b/studio/backend/core/inference/provider_model_capabilities.py
new file mode 100644
index 00000000000..31bee006a48
--- /dev/null
+++ b/studio/backend/core/inference/provider_model_capabilities.py
@@ -0,0 +1,77 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+from typing import Any
+
+REASONING_EFFORT_SCALE = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
+
+MODEL_CAPABILITY_PROVIDERS = frozenset({"openrouter"})
+
+
+def _sorted_efforts(values: Any) -> list[str] | None:
+ if not isinstance(values, list):
+ return None
+ known = {v for v in values if isinstance(v, str) and v in REASONING_EFFORT_SCALE}
+ return [level for level in REASONING_EFFORT_SCALE if level in known]
+
+
+def _string_list(values: Any) -> list[str] | None:
+ if not isinstance(values, list):
+ return None
+ items = [v.strip().lower() for v in values if isinstance(v, str) and v.strip()]
+ return items or None
+
+
+def _positive_int(value: Any) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ return int(value) if value > 0 else None
+
+
+def openrouter_model_capabilities(raw: dict[str, Any]) -> dict[str, Any] | None:
+ model_id = raw.get("id")
+ if not isinstance(model_id, str) or not model_id.strip():
+ return None
+ architecture = raw.get("architecture")
+ architecture = architecture if isinstance(architecture, dict) else {}
+ top_provider = raw.get("top_provider")
+ top_provider = top_provider if isinstance(top_provider, dict) else {}
+
+ reasoning_raw = raw.get("reasoning")
+ reasoning: dict[str, Any] | None = None
+ if isinstance(reasoning_raw, dict):
+ default_effort = reasoning_raw.get("default_effort")
+ reasoning = {
+ "supported_efforts": (
+ list(REASONING_EFFORT_SCALE)
+ if "supported_efforts" in reasoning_raw
+ and reasoning_raw["supported_efforts"] is None
+ else _sorted_efforts(reasoning_raw.get("supported_efforts"))
+ ),
+ "mandatory": reasoning_raw.get("mandatory") is True,
+ "default_effort": default_effort if default_effort in REASONING_EFFORT_SCALE else None,
+ "default_enabled": (
+ reasoning_raw.get("default_enabled")
+ if isinstance(reasoning_raw.get("default_enabled"), bool)
+ else None
+ ),
+ }
+
+ return {
+ "id": model_id.strip(),
+ "input_modalities": _string_list(architecture.get("input_modalities")),
+ "reasoning": reasoning,
+ "max_output_tokens": _positive_int(top_provider.get("max_completion_tokens")),
+ "supported_parameters": _string_list(raw.get("supported_parameters")),
+ }
+
+
+def provider_model_capabilities(
+ provider_type: str, models: list[dict[str, Any]]
+) -> list[dict[str, Any]]:
+ if provider_type != "openrouter":
+ return []
+ mapped = (openrouter_model_capabilities(m) for m in models if isinstance(m, dict))
+ return [entry for entry in mapped if entry is not None]
diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.py
index 689c81330c1..dc512c69251 100644
--- a/studio/backend/models/providers.py
+++ b/studio/backend/models/providers.py
@@ -156,6 +156,21 @@ class ProviderModelInfo(BaseModel):
owned_by: Optional[str] = Field(None, description = "Model owner/organization")
+class ProviderModelReasoningInfo(BaseModel):
+ supported_efforts: Optional[list[str]] = None
+ mandatory: bool = False
+ default_effort: Optional[str] = None
+ default_enabled: Optional[bool] = None
+
+
+class ProviderModelCapabilityInfo(BaseModel):
+ id: str
+ input_modalities: Optional[list[str]] = None
+ reasoning: Optional[ProviderModelReasoningInfo] = None
+ max_output_tokens: Optional[int] = None
+ supported_parameters: Optional[list[str]] = None
+
+
class ProviderModelsRequest(BaseModel):
"""Request to list models from an external provider."""
diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.py
index 9f993895721..fba6a079050 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -6,6 +6,7 @@ configurations and their API keys, the RSA public key used to encrypt those keys
listing.
"""
+import time
import uuid
from typing import Optional
@@ -38,10 +39,15 @@ from core.inference.pricing import pricing_snapshot
from core.inference.external_provider import ExternalProviderClient
from core.inference import openai_codex_auth, openai_codex_client
+from core.inference.provider_model_capabilities import (
+ MODEL_CAPABILITY_PROVIDERS,
+ provider_model_capabilities,
+)
from models.providers import (
ProviderCreate,
ProviderCredentialMigration,
ProviderModelsRequest,
+ ProviderModelCapabilityInfo,
ProviderModelInfo,
ProviderResponse,
ProviderRegistryEntry,
@@ -731,6 +737,66 @@ async def test_provider(
await client.close()
+_MODEL_CAPABILITY_CACHE_TTL_SECONDS = 3600.0
+_model_capability_cache: dict[str, tuple[float, list[dict]]] = {}
+
+
[email protected]("/model-capabilities", response_model = list[ProviderModelCapabilityInfo])
+async def list_provider_model_capabilities(
+ payload: ProviderModelsRequest,
+ _current_subject: str = Depends(get_current_subject),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+):
+ payload = _bind_saved_provider_target(payload)
+ info = get_provider_info(payload.provider_type)
+ if info is None:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Unknown provider type: {payload.provider_type}",
+ )
+ if payload.provider_type not in MODEL_CAPABILITY_PROVIDERS:
+ return []
+
+ api_key = resolve_provider_api_key_or_400(
+ payload.provider_id,
+ payload.encrypted_api_key,
+ allow_saved_key = not via_api_key,
+ )
+ base_url = payload.base_url or info["base_url"]
+ try:
+ base_url = validate_provider_base_url(base_url)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from None
+
+ cache_key = f"{payload.provider_type}\n{base_url}"
+ cached = _model_capability_cache.get(cache_key)
+ if cached is not None and time.monotonic() - cached[0] < _MODEL_CAPABILITY_CACHE_TTL_SECONDS:
+ return cached[1]
+
+ client = ExternalProviderClient(
+ provider_type = payload.provider_type,
+ base_url = base_url,
+ api_key = api_key,
+ timeout = 15.0,
+ )
+ try:
+ models = await client.list_models()
+ except Exception as exc:
+ raise log_and_http_error(
+ exc,
+ 502,
+ f"Failed to list model capabilities from {payload.provider_type}.",
+ event = "providers.list_model_capabilities_failed",
+ log = logger,
+ )
+ finally:
+ await client.close()
+ capabilities = provider_model_capabilities(payload.provider_type, models)
+ if capabilities:
+ _model_capability_cache[cache_key] = (time.monotonic(), capabilities)
+ return capabilities
+
+
@router.post("/models", response_model = list[ProviderModelInfo])
async def list_provider_models(
payload: ProviderModelsRequest,
diff --git a/studio/backend/tests/test_provider_model_capabilities.py b/studio/backend/tests/test_provider_model_capabilities.py
new file mode 100644
index 00000000000..129d675a909
--- /dev/null
+++ b/studio/backend/tests/test_provider_model_capabilities.py
@@ -0,0 +1,256 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import json
+import sys
+import types
+from pathlib import Path
+
+import httpx
+import pytest
+
+from core.inference import external_provider as ep_mod
+from core.inference.external_provider import ExternalProviderClient
+from core.inference.provider_model_capabilities import (
+ openrouter_model_capabilities,
+ provider_model_capabilities,
+)
+from models.providers import ProviderModelsRequest
+
+
+def _load_providers_route():
+ routes_dir = Path(__file__).resolve().parents[1] / "routes"
+ previous = sys.modules.get("routes")
+ package = types.ModuleType("routes")
+ package.__path__ = [str(routes_dir)]
+ sys.modules["routes"] = package
+ try:
+ for name, path in (
+ ("routes.provider_credentials", routes_dir / "provider_credentials.py"),
+ ("_capabilities_providers_route", routes_dir / "providers.py"),
+ ):
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+ finally:
+ sys.modules.pop("routes.provider_credentials", None)
+ if previous is None:
+ sys.modules.pop("routes", None)
+ else:
+ sys.modules["routes"] = previous
+
+
+providers_route = _load_providers_route()
+
+
+_RAW_GPT = {
+ "id": "openai/gpt-5.5",
+ "architecture": {"input_modalities": ["file", "image", "text"], "output_modalities": ["text"]},
+ "reasoning": {
+ "mandatory": False,
+ "default_enabled": True,
+ "supported_efforts": ["xhigh", "high", "medium", "low", "none", "turbo"],
+ "default_effort": "medium",
+ },
+ "top_provider": {"context_length": 400000, "max_completion_tokens": 128000},
+ "supported_parameters": ["reasoning", "tools", "Temperature"],
+}
+
+_RAW_R1 = {
+ "id": "deepseek/deepseek-r1",
+ "architecture": {"input_modalities": ["text"]},
+ "reasoning": {"mandatory": True},
+ "top_provider": {"max_completion_tokens": None},
+}
+
+
+def test_openrouter_entry_maps_efforts_modalities_and_cap():
+ mapped = openrouter_model_capabilities(_RAW_GPT)
+ assert mapped == {
+ "id": "openai/gpt-5.5",
+ "input_modalities": ["file", "image", "text"],
+ "reasoning": {
+ "supported_efforts": ["none", "low", "medium", "high", "xhigh"],
+ "mandatory": False,
+ "default_effort": "medium",
+ "default_enabled": True,
+ },
+ "max_output_tokens": 128000,
+ "supported_parameters": ["reasoning", "tools", "temperature"],
+ }
+
+
+def test_mandatory_only_reasoning_and_missing_fields():
+ mapped = openrouter_model_capabilities(_RAW_R1)
+ assert mapped["reasoning"] == {
+ "supported_efforts": None,
+ "mandatory": True,
+ "default_effort": None,
+ "default_enabled": None,
+ }
+ assert mapped["max_output_tokens"] is None
+ assert mapped["supported_parameters"] is None
+ plain = openrouter_model_capabilities({"id": "acme/plain"})
+ assert plain["reasoning"] is None
+ assert plain["input_modalities"] is None
+ assert openrouter_model_capabilities({"id": ""}) is None
+ assert openrouter_model_capabilities({"name": "no id"}) is None
+
+
+def test_only_openrouter_is_mapped():
+ assert provider_model_capabilities("openai", [_RAW_GPT]) == []
+ assert [
+ m["id"] for m in provider_model_capabilities("openrouter", [_RAW_GPT, "junk", _RAW_R1])
+ ] == [
+ "openai/gpt-5.5",
+ "deepseek/deepseek-r1",
+ ]
+
+
+class _FakeClient:
+ calls = 0
+ raw: list[dict] = []
+ fail = False
+
+ def __init__(self, **kwargs):
+ pass
+
+ async def list_models(self):
+ type(self).calls += 1
+ if type(self).fail:
+ raise RuntimeError("upstream down")
+ return list(type(self).raw)
+
+ async def close(self):
+ pass
+
+
+def capability_route(monkeypatch):
+ providers_route._model_capability_cache.clear()
+ _FakeClient.calls = 0
+ _FakeClient.raw = [_RAW_GPT, _RAW_R1]
+ _FakeClient.fail = False
+ monkeypatch.setattr(providers_route, "ExternalProviderClient", _FakeClient)
+ monkeypatch.setattr(
+ providers_route, "resolve_provider_api_key_or_400", lambda *a, **k: "sk-test"
+ )
+
+ def call(provider_type: str):
+ return asyncio.run(
+ providers_route.list_provider_model_capabilities(
+ ProviderModelsRequest(provider_type = provider_type),
+ _current_subject = "tester",
+ via_api_key = False,
+ )
+ )
+
+ yield call
+ providers_route._model_capability_cache.clear()
+
+
+def test_route_maps_and_caches_the_openrouter_catalog(capability_route):
+ first = capability_route("openrouter")
+ assert [m["id"] for m in first] == ["openai/gpt-5.5", "deepseek/deepseek-r1"]
+ assert first[0]["reasoning"]["supported_efforts"] == ["none", "low", "medium", "high", "xhigh"]
+ _FakeClient.fail = True
+ assert capability_route("openrouter") == first
+ assert _FakeClient.calls == 1
+
+
+def test_route_answers_empty_for_providers_without_a_capability_catalog(capability_route):
+ assert capability_route("openai") == []
+ assert _FakeClient.calls == 0
+
+
+def test_route_surfaces_upstream_failure_when_nothing_is_cached(capability_route):
+ _FakeClient.fail = True
+ with pytest.raises(Exception) as excinfo:
+ capability_route("openrouter")
+ assert getattr(excinfo.value, "status_code", None) == 502
+
+
+def _openrouter_body(model: str = "deepseek/deepseek-v4-pro", **kwargs) -> dict:
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode())
+ sse = 'data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n'
+ return httpx.Response(200, content = sse, headers = {"content-type": "text/event-stream"})
+
+ mock_client = httpx.AsyncClient(transport = httpx.MockTransport(handler))
+ client = ExternalProviderClient(
+ provider_type = "openrouter",
+ base_url = "https://openrouter.ai/api/v1",
+ api_key = "sk-test",
+ )
+
+ async def run() -> None:
+ try:
+ async for _ in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = model,
+ **kwargs,
+ ):
+ pass
+ finally:
+ await mock_client.aclose()
+
+ loop = asyncio.new_event_loop()
+ previous = ep_mod._http_client
+ ep_mod._http_client = mock_client
+ try:
+ loop.run_until_complete(run())
+ finally:
+ ep_mod._http_client = previous
+ loop.close()
+ return captured["body"]
+
+
[email protected]("effort", ["minimal", "low", "medium", "high", "xhigh", "max"])
+def test_every_effort_level_reaches_openrouter(effort):
+ assert _openrouter_body(reasoning_effort = effort, enable_thinking = True)["reasoning"] == {
+ "effort": effort
+ }
+
+
+def test_none_effort_switches_reasoning_off():
+ assert _openrouter_body(reasoning_effort = "none", enable_thinking = False)["reasoning"] == {
+ "enabled": False
+ }
+
+
+def test_none_effort_on_a_mandatory_route_sends_no_reasoning_field():
+ body = _openrouter_body(
+ model = "deepseek/deepseek-r1", reasoning_effort = "none", enable_thinking = False
+ )
+ assert "reasoning" not in body
+
+
+def test_a_bare_toggle_still_maps_to_enabled():
+ assert _openrouter_body(enable_thinking = True)["reasoning"] == {"enabled": True}
+ assert _openrouter_body(enable_thinking = False)["reasoning"] == {"enabled": False}
+ assert "reasoning" not in _openrouter_body()
+
+
+def test_null_efforts_accept_the_full_scale_while_omitted_efforts_remain_toggle_only():
+ unrestricted = openrouter_model_capabilities(
+ {"id": "acme/reasoning", "reasoning": {"supported_efforts": None}}
+ )
+ assert unrestricted["reasoning"]["supported_efforts"] == [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ ]
+ toggle = openrouter_model_capabilities({"id": "acme/reasoning", "reasoning": {}})
+ assert toggle["reasoning"]["supported_efforts"] is None
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 8aa518cfc8c..2211dff415c 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -165,7 +165,12 @@ import {
} from "@/features/settings";
import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";
import { create } from "zustand";
-import { getExternalReasoningCapabilities } from "@/features/chat/provider-capabilities";
+import {
+ clampReasoningEffortToLevels,
+ getExternalReasoningCapabilities,
+ modelCatalogVersion,
+ subscribeModelCatalog,
+} from "@/features/chat/provider-capabilities";
import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";
import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-menu-item";
import { PermissionModeComposerPill } from "@/features/chat/permission-mode-select";
@@ -5452,9 +5457,6 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({
(s) => s.reasoningEffortLevels,
);
const setReasoningEffort = useChatRuntimeStore((s) => s.setReasoningEffort);
- const lastOpenRouterChosenModel = useChatRuntimeStore(
- (s) => s.lastOpenRouterChosenModel,
- );
const connectionsEnabled = useExternalProvidersStore(
(s) => s.connectionsEnabled,
);
@@ -5473,17 +5475,13 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({
);
const preserveThinking = useChatRuntimeStore((s) => s.preserveThinking);
const setPreserveThinking = useChatRuntimeStore((s) => s.setPreserveThinking);
- const effectiveExternalModelId =
- selectedExternalProvider?.providerType === "openrouter" &&
- externalSelection?.modelId === "openrouter/free" &&
- lastOpenRouterChosenModel
- ? lastOpenRouterChosenModel
- : externalSelection?.modelId;
+ useSyncExternalStore(subscribeModelCatalog, modelCatalogVersion);
const externalReasoningCaps =
externalSelection != null
? getExternalReasoningCapabilities(
selectedExternalProvider?.providerType,
- effectiveExternalModelId,
+ // The adapter resolves reasoning for the selected id; openrouter/free can route each turn elsewhere.
+ externalSelection?.modelId,
{
isReasoningProvider:
selectedExternalProvider?.isReasoningModel === true,
@@ -5506,8 +5504,14 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({
effectiveSupportsReasoning &&
(effectiveReasoningAlwaysOn || !effectiveSupportsReasoningOff);
const effectiveReasoningEnabled = reasoningLockedOn ? true : reasoningEnabled;
+ // What the adapter sends: the stored effort clamped to the current ladder, so a catalog refresh that
+ // drops the stored level is shown truthfully without overwriting the choice.
+ const displayedEffort =
+ effectiveReasoningEffortLevels.length > 0
+ ? clampReasoningEffortToLevels(reasoningEffort, effectiveReasoningEffortLevels)
+ : reasoningEffort;
const effectiveReasoningVisualEnabled =
- effectiveReasoningEnabled && reasoningEffort !== "none";
+ effectiveReasoningEnabled && displayedEffort !== "none";
const disabled = !(modelLoaded && effectiveSupportsReasoning);
const formatEffortLabel = (level: typeof reasoningEffort): string => {
if (level !== "xhigh")
@@ -5521,7 +5525,7 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({
}
return "Extra High";
};
- const effortLabel = formatEffortLabel(reasoningEffort);
+ const effortLabel = formatEffortLabel(displayedEffort);
// Only rendered for models that can reason.
if (!effectiveSupportsReasoning) {
@@ -5557,7 +5561,7 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({
aria-label={thinkEffortAriaLabel({
modelLoaded,
reasoningDisabled: disabled,
- reasoningEffort,
+ reasoningEffort: displayedEffort,
})}
>
<ThinkIcon />
@@ -5621,7 +5625,7 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({
"unsloth-tick size-4",
!(
effectiveReasoningVisualEnabled &&
- reasoningEffort === level
+ displayedEffort === level
) && "opacity-0",
)}
/>
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 8dd9f01cfa5..a38543dbf35 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -6109,7 +6109,7 @@ export function createOpenAIStreamAdapter(
}
: {
thinking: {
- type: reasoningEnabled ? "enabled" : "disabled",
+ type: externalReasoningEnabled ? "enabled" : "disabled",
},
}
: {}),
diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.ts
index f4f08d4331f..0dd752085d1 100644
--- a/studio/frontend/src/features/chat/api/providers-api.ts
+++ b/studio/frontend/src/features/chat/api/providers-api.ts
@@ -61,6 +61,21 @@ export interface ProviderModelInfo {
vision?: boolean | null;
}
+export interface ProviderModelReasoningInfo {
+ supported_efforts?: string[] | null;
+ mandatory?: boolean | null;
+ default_effort?: string | null;
+ default_enabled?: boolean | null;
+}
+
+export interface ProviderModelCapabilityInfo {
+ id: string;
+ input_modalities?: string[] | null;
+ reasoning?: ProviderModelReasoningInfo | null;
+ max_output_tokens?: number | null;
+ supported_parameters?: string[] | null;
+}
+
export interface ProviderTestResult {
success: boolean;
message: string;
@@ -341,6 +356,27 @@ export async function listProviderModels(payload: {
});
}
+export async function listProviderModelCapabilities(payload: {
+ providerType: string;
+ providerId?: string | null;
+ apiKey: string;
+ baseUrl?: string | null;
+}): Promise<ProviderModelCapabilityInfo[]> {
+ return withApiKeyEncryptionRetry(payload.apiKey, async (encryptedApiKey) => {
+ const response = await authFetch("/api/providers/model-capabilities", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ provider_type: payload.providerType,
+ provider_id: payload.providerId ?? null,
+ encrypted_api_key: encryptedApiKey,
+ base_url: payload.baseUrl ?? null,
+ }),
+ });
+ return parseJsonOrThrow<ProviderModelCapabilityInfo[]>(response);
+ });
+}
+
export interface CodexSubscriptionModels {
models: ProviderModelInfo[];
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index dff5f0eb149..d1de996f544 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -127,6 +127,7 @@ import {
useMemo,
useRef,
useState,
+ useSyncExternalStore,
} from "react";
import type { PanelImperativeHandle } from "react-resizable-panels";
import { notifyChatHistoryUpdated } from "./api/chat-api";
@@ -184,12 +185,15 @@ import {
clampReasoningEffortToLevels,
getExternalReasoningCapabilities,
getProviderCapabilities,
+ modelCatalogVersion,
providerHostsCodeExecution,
providerSupportsBuiltinCodeExecution,
providerSupportsBuiltinImageGeneration,
providerSupportsBuiltinWebFetch,
providerSupportsBuiltinWebSearch,
providerSupportsFastMode,
+ reasoningFieldsAfterCatalogRefresh,
+ subscribeModelCatalog,
} from "./provider-capabilities";
import {
COMPOSER_INPUT_SELECTOR,
@@ -2549,14 +2553,20 @@ export function ChatPage({
: effortLevels.includes("medium")
? "medium"
: clampedEffort;
+ const catalogDefaultEffort =
+ reasoningCaps.defaultEffort &&
+ effortLevels.includes(reasoningCaps.defaultEffort)
+ ? reasoningCaps.defaultEffort
+ : null;
const nextReasoningEffort = reasoningCaps.supportsReasoning
- ? isAnthropic
- ? anthropicTopEffort
- : isOpenAI
- ? openaiDefaultEffort
- : effortLevels.includes("medium")
- ? "medium"
- : clampedEffort
+ ? (catalogDefaultEffort ??
+ (isAnthropic
+ ? anthropicTopEffort
+ : isOpenAI
+ ? openaiDefaultEffort
+ : effortLevels.includes("medium")
+ ? "medium"
+ : clampedEffort))
: state.reasoningEffort;
const supportsBuiltinWebSearch = providerSupportsBuiltinWebSearch(
provider?.providerType,
@@ -2653,6 +2663,34 @@ export function ChatPage({
// Reruns once settings hydrate: this normalization reads the stored pills and clamps them to the
// model, and hydration refreshes what it reads, so it has to be applied last.
}, [externalProvidersForChat, inferenceParams.checkpoint, settingsHydrated]);
+ // A catalog that lands after selection refreshes only the stored reasoning fields (the effort shortcut reads them),
+ // never the selection defaults above, so a chosen effort and the pills survive the refresh.
+ const modelCatalogChange = useSyncExternalStore(
+ subscribeModelCatalog,
+ modelCatalogVersion,
+ );
+ const appliedCatalogChange = useRef(modelCatalogChange);
+ useEffect(() => {
+ if (appliedCatalogChange.current === modelCatalogChange) return;
+ appliedCatalogChange.current = modelCatalogChange;
+ const selection = parseExternalModelId(inferenceParams.checkpoint);
+ if (!selection) return;
+ const { providers, connectionsEnabled: enabled } = useExternalProvidersStore.getState();
+ const provider = enabled
+ ? providers.find((p) => p.id === selection.providerId)
+ : undefined;
+ const caps = getExternalReasoningCapabilities(
+ provider?.providerType,
+ selection.modelId,
+ {
+ isReasoningProvider: provider?.isReasoningModel === true,
+ baseUrl: provider?.baseUrl ?? null,
+ },
+ );
+ useChatRuntimeStore.setState(
+ reasoningFieldsAfterCatalogRefresh(useChatRuntimeStore.getState(), caps),
+ );
+ }, [modelCatalogChange, inferenceParams.checkpoint]);
const canCompare = useMemo(() => {
return Boolean(inferenceParams.checkpoint) && !isExternalModel;
}, [inferenceParams.checkpoint, isExternalModel]);
@@ -3165,14 +3203,20 @@ export function ChatPage({
: effortLevels.includes("medium")
? "medium"
: clampedEffort;
+ const catalogDefaultEffort =
+ reasoningCaps.defaultEffort &&
+ effortLevels.includes(reasoningCaps.defaultEffort)
+ ? reasoningCaps.defaultEffort
+ : null;
const nextReasoningEffort = reasoningCaps.supportsReasoning
- ? isAnthropic
- ? anthropicTopEffort
- : isOpenAI
- ? openaiDefaultEffort
- : effortLevels.includes("medium")
- ? "medium"
- : clampedEffort
+ ? (catalogDefaultEffort ??
+ (isAnthropic
+ ? anthropicTopEffort
+ : isOpenAI
+ ? openaiDefaultEffort
+ : effortLevels.includes("medium")
+ ? "medium"
+ : clampedEffort))
: store.reasoningEffort;
// Clear any cached router-picked openrouter/free model unless staying on openrouter/free, else
// the chip keeps a stale ":<chosen>" suffix.
diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
index 4913dea94d1..19dd529c952 100644
--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx
+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
@@ -83,6 +83,7 @@ import { useExternalProvidersStore } from "./stores/external-providers-store";
import {
mergeLearnedModelCapabilities,
pruneProviderModelIds,
+ refreshProviderModelCatalogs,
syncExternalProvidersFromBackend,
} from "./sync-external-providers";
@@ -755,6 +756,7 @@ export function ChatProvidersSettings({
];
providersRef.current = nextProviders;
onProvidersChange(nextProviders);
+ void refreshProviderModelCatalogs([provider]);
setSelectedModelIds(models);
setAvailableModels(available);
setEditingProviderId(created.id);
@@ -881,6 +883,7 @@ export function ChatProvidersSettings({
...providers.filter((p) => p.id !== created.id),
provider,
]);
+ void refreshProviderModelCatalogs([provider]);
resetForm();
autoOpenedAddFormRef.current = true;
setPage("list");
@@ -1005,31 +1008,31 @@ export function ChatProvidersSettings({
const updatedAt = Number.isFinite(Date.parse(updated.updated_at))
? Date.parse(updated.updated_at)
: Date.now();
+ const editedProvider: ExternalProviderConfig = {
+ ...existing,
+ backendProviderType: updated.provider_type,
+ name: updated.display_name,
+ baseUrl: updated.base_url ?? "",
+ models: modelsToSave,
+ availableModels: manualOnly
+ ? []
+ : pruneProviderModelIds(existing.providerType, availableModels),
+ maxOutputTokens: updated.max_output_tokens ?? undefined,
+
+ hasApiKey: updated.has_api_key,
+ isReasoningModel: supportsProviderReasoningToggle(
+ existing.providerType,
+ )
+ ? isReasoningModel
+ : undefined,
+ updatedAt,
+ };
onProvidersChange(
providers.map((provider) =>
- provider.id === editingProviderId
- ? {
- ...provider,
- backendProviderType: updated.provider_type,
- name: updated.display_name,
- baseUrl: updated.base_url ?? "",
- models: modelsToSave,
- availableModels: manualOnly
- ? []
- : pruneProviderModelIds(existing.providerType, availableModels),
- maxOutputTokens: updated.max_output_tokens ?? undefined,
-
- hasApiKey: updated.has_api_key,
- isReasoningModel: supportsProviderReasoningToggle(
- existing.providerType,
- )
- ? isReasoningModel
- : undefined,
- updatedAt,
- }
- : provider,
+ provider.id === editingProviderId ? editedProvider : provider,
),
);
+ void refreshProviderModelCatalogs([editedProvider]);
toast.success("Connection updated.");
resetForm();
autoOpenedAddFormRef.current = true;
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 48ff54f1b0d..a43ba0135ad 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -66,7 +66,14 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Braces, ChevronDown, ExternalLink } from "lucide-react";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import { type CSSProperties, Fragment, type ReactNode } from "react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
import { OpenAICodeExecSection } from "./components/openai-code-exec-section";
import { PermissionModeDropdown } from "./permission-mode-select";
import { resyncInferenceStatusAfterServerModelChange } from "./hooks/use-chat-model-runtime";
@@ -101,9 +108,11 @@ import {
type ProviderCapabilities,
getExternalMaxOutputTokens,
getExternalMinOutputTokens,
+ modelCatalogVersion,
providerSupportsBuiltinCodeExecution,
providerSupportsFastMode,
resolveExternalMaxTokensClamp,
+ subscribeModelCatalog,
} from "./provider-capabilities";
import {
isLocalModelPath,
@@ -788,6 +797,8 @@ export function ChatSettingsPanel({
const externalSelection = currentCheckpoint
? parseExternalModelId(currentCheckpoint)
: null;
+ // The OpenRouter cap comes from the live catalog, which can land after this panel renders.
+ useSyncExternalStore(subscribeModelCatalog, modelCatalogVersion);
const maxTokensMax = isExternalModel
? getExternalMaxOutputTokens(
externalProviderType,
diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.ts
index 25edf84bd31..92f54c65759 100644
--- a/studio/frontend/src/features/chat/external-providers.ts
+++ b/studio/frontend/src/features/chat/external-providers.ts
@@ -5,6 +5,7 @@ import type {
ProviderAuthKind,
ProviderAuthStatus,
} from "./api/providers-api";
+import { modelCatalogSupportsVision } from "./model-catalog.ts";
export interface ExternalProviderConfig {
id: string;
@@ -204,6 +205,8 @@ export function providerModelSupportsVision(
const capability = REGISTRY_MODEL_CAPABILITIES.get(providerType)?.[modelId];
if (typeof capability?.vision === "boolean") return capability.vision;
}
+ const catalogVision = modelCatalogSupportsVision(providerType, modelId);
+ if (catalogVision != null) return catalogVision;
return providerTypeSupportsVision(providerType);
}
diff --git a/studio/frontend/src/features/chat/model-catalog.ts b/studio/frontend/src/features/chat/model-catalog.ts
new file mode 100644
index 00000000000..ec2bfdc6e85
--- /dev/null
+++ b/studio/frontend/src/features/chat/model-catalog.ts
@@ -0,0 +1,207 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { ProviderModelCapabilityInfo } from "./api/providers-api";
+
+export type ReasoningEffortLevel =
+ | "none"
+ | "minimal"
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max";
+
+/** Weakest -> strongest. Must stay in sync with _REASONING_EFFORT_SCALE in
+ * backend core/inference/llama_cpp.py. */
+export const REASONING_EFFORT_SCALE = [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+] as const satisfies readonly ReasoningEffortLevel[];
+
+export interface ModelCatalogEntry {
+ reasoning: boolean;
+ efforts: readonly ReasoningEffortLevel[];
+ mandatory: boolean;
+ defaultEffort: ReasoningEffortLevel | null;
+ inputModalities: readonly string[] | null;
+ maxOutputTokens: number | null;
+}
+
+interface LiveCatalogRecord {
+ fetchedAt: number;
+ models: Record<string, ModelCatalogEntry>;
+}
+
+const LIVE_CATALOG_KEY = "unsloth_chat_provider_model_catalog";
+const LIVE_CATALOG = new Map<string, LiveCatalogRecord>();
+let liveCatalogHydrated = false;
+
+const catalogListeners = new Set<() => void>();
+let catalogVersion = 0;
+
+function notifyCatalogChange(): void {
+ catalogVersion += 1;
+ for (const listener of catalogListeners) listener();
+}
+
+export function subscribeModelCatalog(listener: () => void): () => void {
+ catalogListeners.add(listener);
+ return () => {
+ catalogListeners.delete(listener);
+ };
+}
+
+/** `useSyncExternalStore` snapshot: changes whenever a catalog lands, so capability reads re-render. */
+export function modelCatalogVersion(): number {
+ return catalogVersion;
+}
+
+function canUseStorage(): boolean {
+ return typeof window !== "undefined";
+}
+
+function isEffortLevel(value: unknown): value is ReasoningEffortLevel {
+ return (
+ typeof value === "string" &&
+ (REASONING_EFFORT_SCALE as readonly string[]).includes(value)
+ );
+}
+
+export function sortReasoningEfforts(
+ levels: Iterable<unknown>,
+): ReasoningEffortLevel[] {
+ const known = new Set<ReasoningEffortLevel>();
+ for (const level of levels) {
+ if (isEffortLevel(level)) known.add(level);
+ }
+ return REASONING_EFFORT_SCALE.filter((level) => known.has(level));
+}
+
+function hydrateLiveCatalog(): void {
+ if (liveCatalogHydrated) return;
+ liveCatalogHydrated = true;
+ if (!canUseStorage()) return;
+ try {
+ const parsed = JSON.parse(
+ localStorage.getItem(LIVE_CATALOG_KEY) ?? "{}",
+ ) as Record<string, LiveCatalogRecord>;
+ for (const [providerType, record] of Object.entries(parsed)) {
+ if (
+ record &&
+ typeof record === "object" &&
+ typeof record.fetchedAt === "number" &&
+ record.models &&
+ typeof record.models === "object"
+ ) {
+ LIVE_CATALOG.set(providerType, record);
+ }
+ }
+ } catch {
+ // Invalid browser state; the next refresh rewrites it.
+ }
+}
+
+function persistLiveCatalog(): void {
+ if (!canUseStorage()) return;
+ try {
+ localStorage.setItem(
+ LIVE_CATALOG_KEY,
+ JSON.stringify(Object.fromEntries(LIVE_CATALOG)),
+ );
+ } catch {
+ // Storage failures leave the in-memory copy valid for this session.
+ }
+}
+
+function fromLiveModel(model: ProviderModelCapabilityInfo): ModelCatalogEntry {
+ const reasoning = model.reasoning ?? null;
+ const defaultEffort = reasoning?.default_effort;
+ return {
+ reasoning: reasoning != null,
+ efforts: sortReasoningEfforts(reasoning?.supported_efforts ?? []),
+ mandatory: reasoning?.mandatory === true,
+ defaultEffort: isEffortLevel(defaultEffort) ? defaultEffort : null,
+ inputModalities: Array.isArray(model.input_modalities)
+ ? model.input_modalities
+ : null,
+ maxOutputTokens:
+ typeof model.max_output_tokens === "number" && model.max_output_tokens > 0
+ ? model.max_output_tokens
+ : null,
+ };
+}
+
+export function setProviderModelCatalog(
+ providerType: string,
+ models: readonly ProviderModelCapabilityInfo[],
+ fetchedAt: number = Date.now(),
+): void {
+ hydrateLiveCatalog();
+ const entries: Record<string, ModelCatalogEntry> = {};
+ for (const model of models) {
+ const id = model.id?.trim().toLowerCase();
+ if (id) entries[id] = fromLiveModel(model);
+ }
+ LIVE_CATALOG.set(providerType, { fetchedAt, models: entries });
+ persistLiveCatalog();
+ notifyCatalogChange();
+}
+
+export function clearProviderModelCatalog(providerType: string): void {
+ hydrateLiveCatalog();
+ if (!LIVE_CATALOG.delete(providerType)) return;
+ persistLiveCatalog();
+ notifyCatalogChange();
+}
+
+export function providerModelCatalogFetchedAt(providerType: string): number | null {
+ hydrateLiveCatalog();
+ return LIVE_CATALOG.get(providerType)?.fetchedAt ?? null;
+}
+
+function lookupCandidates(providerType: string, modelId: string): string[] {
+ const normalized = modelId.trim().toLowerCase();
+ if (!normalized) return [];
+ const candidates = [normalized];
+ if (providerType === "openrouter") {
+ const bare = normalized.startsWith("~") ? normalized.slice(1) : normalized;
+ if (bare !== normalized) candidates.push(bare);
+ const variant = bare.indexOf(":");
+ if (variant > 0) candidates.push(bare.slice(0, variant));
+ }
+ return candidates;
+}
+
+export function resolveModelCatalogEntry(
+ providerType: string | null | undefined,
+ modelId: string | null | undefined,
+): ModelCatalogEntry | null {
+ if (!providerType || !modelId) return null;
+ const normalizedProvider = providerType.trim().toLowerCase();
+ const candidates = lookupCandidates(normalizedProvider, modelId);
+ if (candidates.length === 0) return null;
+ hydrateLiveCatalog();
+ const live = LIVE_CATALOG.get(normalizedProvider)?.models;
+ if (live) {
+ for (const candidate of candidates) {
+ const entry = live[candidate];
+ if (entry) return entry;
+ }
+ }
+ return null;
+}
+
+export function modelCatalogSupportsVision(
+ providerType: string | null | undefined,
+ modelId: string | null | undefined,
+): boolean | null {
+ const modalities = resolveModelCatalogEntry(providerType, modelId)?.inputModalities;
+ if (!modalities) return null;
+ return modalities.includes("image");
+}
diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.ts
index b31642fda2c..2e825d4f1a2 100644
--- a/studio/frontend/src/features/chat/provider-capabilities.ts
+++ b/studio/frontend/src/features/chat/provider-capabilities.ts
@@ -5,6 +5,15 @@ import {
normalizeProviderMaxOutputTokens,
providerModelSupportsStudioTools,
} from "./external-providers";
+import {
+ type ModelCatalogEntry,
+ REASONING_EFFORT_SCALE,
+ type ReasoningEffortLevel,
+ resolveModelCatalogEntry,
+ sortReasoningEfforts,
+} from "./model-catalog";
+
+export { modelCatalogVersion, subscribeModelCatalog } from "./model-catalog";
/** Per-provider sampling capability matrix from each provider's chat docs (2026-05).
* Params a provider rejects are hidden; local models use a null capability, so all render. */
@@ -31,29 +40,10 @@ export type ExternalReasoningCapabilities = {
reasoningStyle: "enable_thinking" | "reasoning_effort" | "enable_thinking_effort";
reasoningAlwaysOn: boolean;
supportsReasoningOff: boolean;
- reasoningEffortLevels: readonly (
- | "none"
- | "minimal"
- | "low"
- | "medium"
- | "high"
- | "max"
- | "xhigh"
- )[];
+ reasoningEffortLevels: readonly ReasoningEffortLevel[];
+ defaultEffort?: ReasoningEffortLevel | null;
};
-/** Weakest -> strongest. Must stay in sync with _REASONING_EFFORT_SCALE in
- * backend core/inference/llama_cpp.py. */
-const REASONING_EFFORT_SCALE = [
- "none",
- "minimal",
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
-] as const satisfies ExternalReasoningCapabilities["reasoningEffortLevels"];
-
/** Pick a stored effort level present in `effortLevels`, mapping legacy "xhigh" to "max"
* when only the latter is exposed (Claude 4.6).
*
@@ -249,7 +239,9 @@ function _publishedMaxOutputTokens(
providerType: string | null | undefined,
modelId: string | null | undefined,
): number | null {
- if (providerType === "openrouter") return null;
+ if (providerType === "openrouter") {
+ return resolveModelCatalogEntry(providerType, modelId)?.maxOutputTokens ?? null;
+ }
return _documentedMaxOutputTokens(providerType, modelId);
}
@@ -265,6 +257,10 @@ function _documentedMaxOutputTokens(
if (!providerType || !modelId) return null;
const normalized = modelId.trim().toLowerCase();
if (!normalized) return null;
+ if (providerType === "openrouter") {
+ const live = resolveModelCatalogEntry(providerType, normalized)?.maxOutputTokens;
+ if (live != null) return live;
+ }
const stripped =
providerType === "openrouter" && normalized.includes("/")
? normalized.split("/").slice(-1)[0]
@@ -1003,8 +999,76 @@ function resolveConnectionLevelReasoning(
return null;
}
-/** Resolve external-model thinking capabilities. Per-provider resolvers do the matching;
- * anything else defaults to no reasoning controls. */
+type ReasoningWire = {
+ levels: readonly ReasoningEffortLevel[] | null;
+ aliases?: Partial<Record<ReasoningEffortLevel, ReasoningEffortLevel>>;
+ off: "unified" | "none-level";
+};
+
+/** What the OpenRouter branch in external_provider.py can put on the wire: the whole effort scale, with one
+ * unified off switch. */
+const CATALOG_REASONING_WIRE: Record<string, ReasoningWire> = {
+ openrouter: { levels: null, off: "unified" },
+};
+
+function projectCatalogEntry(
+ entry: ModelCatalogEntry,
+ wire: ReasoningWire,
+): ExternalReasoningCapabilities {
+ if (!entry.reasoning) return withEnableThinkingStyle();
+ const supportsOff =
+ wire.off === "unified" ? !entry.mandatory : entry.efforts.includes("none");
+ let levels: ReasoningEffortLevel[] = [];
+ if (wire.levels === null || wire.levels.length > 0) {
+ const mapped = entry.efforts
+ .filter((level) => level !== "none")
+ .map((level) => wire.aliases?.[level] ?? level)
+ .filter((level) => wire.levels === null || wire.levels.includes(level));
+ levels = sortReasoningEfforts(mapped);
+ }
+ if (levels.length === 0) {
+ return withEnableThinkingStyle({
+ supportsReasoning: true,
+ reasoningAlwaysOn: entry.mandatory,
+ supportsReasoningOff: supportsOff,
+ });
+ }
+ const ladder: ReasoningEffortLevel[] = supportsOff ? ["none", ...levels] : levels;
+ // Checked against the final ladder: OpenRouter reports default_effort "none" for models such as openai/gpt-5.1.
+ const mappedDefault = entry.defaultEffort
+ ? (wire.aliases?.[entry.defaultEffort] ?? entry.defaultEffort)
+ : null;
+ const defaultEffort = mappedDefault && ladder.includes(mappedDefault) ? mappedDefault : null;
+ return {
+ ...withReasoningEffortStyle({
+ supportsReasoning: true,
+ supportsReasoningOff: supportsOff,
+ reasoningEffortLevels: ladder,
+ }),
+ defaultEffort,
+ };
+}
+
+function catalogCapabilities(
+ providerType: string,
+ modelId: string,
+): ExternalReasoningCapabilities | null {
+ const wire = CATALOG_REASONING_WIRE[providerType];
+ if (!wire) return null;
+ const entry = resolveModelCatalogEntry(providerType, modelId);
+ return entry ? projectCatalogEntry(entry, wire) : null;
+}
+
+const OPENROUTER_GENERIC_TOGGLE: ExternalReasoningCapabilities = {
+ supportsReasoning: true,
+ reasoningStyle: "enable_thinking",
+ reasoningAlwaysOn: false,
+ supportsReasoningOff: true,
+ reasoningEffortLevels: DEFAULT_EFFORT_LEVELS,
+};
+
+/** Resolve external-model thinking capabilities: the connection pin, then the live OpenRouter catalog for
+ * OpenRouter routes, then the hand-maintained per-provider tables; anything else has no reasoning controls. */
export function getExternalReasoningCapabilities(
providerType: string | null | undefined,
modelId: string | null | undefined,
@@ -1023,6 +1087,11 @@ export function getExternalReasoningCapabilities(
return withEnableThinkingStyle();
}
+ if (normalizedProvider === "openrouter" && !normalizedModel.startsWith("openrouter/")) {
+ const catalog = catalogCapabilities(normalizedProvider, normalizedModel);
+ if (catalog) return catalog;
+ }
+
// Some OpenRouter-routed ids are mandatory-reasoning and must stay on even when they
// arrive through aliased or custom provider routes.
if (isOpenRouterMandatoryReasoningModel(normalizedModel)) {
@@ -1042,22 +1111,13 @@ export function getExternalReasoningCapabilities(
const isOpenAIProvider =
normalizedProvider === "openai" || normalizedProvider === "openai_codex";
const isAnthropicProvider = normalizedProvider === "anthropic";
- const isKimiProvider = normalizedProvider === "kimi";
- const isMistralProvider = normalizedProvider === "mistral";
- const isOpenRouterProvider = normalizedProvider === "openrouter";
- if (isOpenRouterProvider) {
+ if (normalizedProvider === "openrouter") {
// OpenRouter's unified `reasoning` param is accepted everywhere and no-ops for non-reasoning
- // models, so past the mandatory guard everything gets a toggleable control.
- return {
- supportsReasoning: true,
- reasoningStyle: "enable_thinking",
- reasoningAlwaysOn: false,
- supportsReasoningOff: true,
- reasoningEffortLevels: DEFAULT_EFFORT_LEVELS,
- };
+ // models, so a route the live catalog does not know still gets a toggleable control.
+ return OPENROUTER_GENERIC_TOGGLE;
}
- if (isKimiProvider) return resolveKimiReasoningCapabilities(modelForMatching);
- if (isMistralProvider) return resolveMistralReasoningCapabilities(modelForMatching);
+ if (normalizedProvider === "kimi") return resolveKimiReasoningCapabilities(modelForMatching);
+ if (normalizedProvider === "mistral") return resolveMistralReasoningCapabilities(modelForMatching);
if (normalizedProvider === "gemini") {
// Custom Gemini OAI-compat gateways route through /chat/completions, which drops the native
// thinkingConfig payload, so hide the ladder.
@@ -1079,3 +1139,30 @@ export function getExternalReasoningCapabilities(
return withEnableThinkingStyle();
}
+
+export type RuntimeReasoningFields = Pick<
+ ExternalReasoningCapabilities,
+ "supportsReasoning" | "reasoningAlwaysOn" | "reasoningStyle" | "supportsReasoningOff" | "reasoningEffortLevels"
+> & { reasoningEffort: ReasoningEffortLevel; reasoningEnabled: boolean };
+
+/** Runtime reasoning fields for a catalog that lands after the model is selected. A chosen effort the new ladder
+ * still offers is kept and one it dropped is clamped; the model-selection defaults and pills are left alone. */
+export function reasoningFieldsAfterCatalogRefresh(
+ current: { reasoningEffort: ReasoningEffortLevel; reasoningEnabled: boolean },
+ caps: ExternalReasoningCapabilities,
+): RuntimeReasoningFields {
+ const levels = caps.reasoningEffortLevels;
+ return {
+ supportsReasoning: caps.supportsReasoning,
+ reasoningAlwaysOn: caps.reasoningAlwaysOn,
+ reasoningStyle: caps.reasoningStyle,
+ supportsReasoningOff: caps.supportsReasoningOff,
+ reasoningEffortLevels: levels,
+ reasoningEffort:
+ levels.length > 0 && !levels.includes(current.reasoningEffort)
+ ? clampReasoningEffortToLevels(current.reasoningEffort, levels)
+ : current.reasoningEffort,
+ reasoningEnabled:
+ caps.supportsReasoning && !caps.supportsReasoningOff ? true : current.reasoningEnabled,
+ };
+}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index aece9a16ff5..69bcd25cb59 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -177,11 +177,13 @@ import {
useChatRuntimeStore,
} from "./stores/chat-runtime-store";
import {
+ clampReasoningEffortToLevels,
getExternalReasoningCapabilities,
providerSupportsBuiltinCodeExecution,
providerSupportsBuiltinImageGeneration,
providerSupportsBuiltinWebFetch,
} from "./provider-capabilities";
+import { modelCatalogVersion, subscribeModelCatalog } from "./model-catalog";
import {
type CompositionEvent,
type ClipboardEvent,
@@ -197,6 +199,7 @@ import {
useEffect,
useRef,
useState,
+ useSyncExternalStore,
} from "react";
export type CompareMessagePart =
@@ -704,6 +707,7 @@ export function SharedComposer({
const lastOpenRouterChosenModel = useChatRuntimeStore(
(s) => s.lastOpenRouterChosenModel,
);
+ useSyncExternalStore(subscribeModelCatalog, modelCatalogVersion);
const externalSelection = parseExternalModelId(checkpoint);
const isExternalModel = externalSelection !== null;
const selectedExternalProvider =
@@ -738,7 +742,8 @@ export function SharedComposer({
externalSelection != null
? getExternalReasoningCapabilities(
selectedExternalProvider?.providerType,
- effectiveExternalModelId,
+ // The adapter resolves reasoning for the selected id; openrouter/free can route each turn elsewhere.
+ externalSelection?.modelId,
{
isReasoningProvider:
selectedExternalProvider?.isReasoningModel === true,
@@ -767,8 +772,14 @@ export function SharedComposer({
// one on flips the other off, so the visible state matches what the backend sends.
const isKimiExternal = selectedExternalProvider?.providerType === "kimi";
const effectiveReasoningEnabled = reasoningLockedOn ? true : reasoningEnabled;
+ // What the adapter sends: the stored effort clamped to the current ladder, so a catalog refresh that
+ // drops the stored level is shown truthfully without overwriting the choice.
+ const displayedEffort =
+ effectiveReasoningEffortLevels.length > 0
+ ? clampReasoningEffortToLevels(reasoningEffort, effectiveReasoningEffortLevels)
+ : reasoningEffort;
const effectiveReasoningVisualEnabled =
- effectiveReasoningEnabled && reasoningEffort !== "none";
+ effectiveReasoningEnabled && displayedEffort !== "none";
const reasoningDisabled = !modelLoaded || !effectiveSupportsReasoning;
const showReasoningControl =
effectiveSupportsReasoning || effectiveReasoningAlwaysOn;
@@ -2596,7 +2607,7 @@ export function SharedComposer({
aria-label={thinkEffortAriaLabel({
modelLoaded,
reasoningDisabled,
- reasoningEffort,
+ reasoningEffort: displayedEffort,
})}
>
<BulbIcon className="size-[15.5px]" />
@@ -2604,7 +2615,7 @@ export function SharedComposer({
<span className="unsloth-thinking-label">
{isEffort
? `Thinking · ${formatReasoningEffortLabel(
- reasoningEffort,
+ displayedEffort,
externalSelection?.modelId,
)}`
: "Thinking"}
@@ -2663,7 +2674,7 @@ export function SharedComposer({
"unsloth-tick size-4",
!(
effectiveReasoningVisualEnabled &&
- reasoningEffort === level
+ displayedEffort === level
) && "opacity-0",
)}
/>
diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.ts
index 32037f3fb70..4f85de54f45 100644
--- a/studio/frontend/src/features/chat/sync-external-providers.ts
+++ b/studio/frontend/src/features/chat/sync-external-providers.ts
@@ -9,10 +9,15 @@ import {
import {
type ProviderRegistryEntry,
listProviderConfigs,
+ listProviderModelCapabilities,
listProviderRegistry,
migrateProviderApiKey,
updateProviderConfig,
} from "./api/providers-api";
+import {
+ providerModelCatalogFetchedAt,
+ setProviderModelCatalog,
+} from "./model-catalog";
import {
CUSTOM_BACKEND_PROVIDER_TYPE,
CUSTOM_PROVIDER_PRESETS,
@@ -311,5 +316,45 @@ export async function syncExternalProvidersFromBackend(
if (isCurrent && !isCurrent()) return existingProviders;
await settleTasksIfCurrent(backfillTasks, isCurrent);
+ void refreshProviderModelCatalogs(syncedProviders, isCurrent);
return syncedProviders;
}
+
+const MODEL_CATALOG_TTL_MS = 24 * 60 * 60 * 1000;
+// The live catalog is stored per provider type, so only the provider's own endpoint may write it; a connection
+// pointed at a compatible gateway keeps the built-in tables instead of overwriting OpenRouter's entries.
+const MODEL_CATALOG_PROVIDER_BASE_URLS: Record<string, string> = {
+ openrouter: "https://openrouter.ai/api/v1",
+};
+
+function usesProviderCatalogEndpoint(provider: ExternalProviderConfig): boolean {
+ const expected = MODEL_CATALOG_PROVIDER_BASE_URLS[provider.providerType];
+ if (!expected) return false;
+ const baseUrl = (provider.baseUrl ?? "").trim().replace(/\/+$/, "").toLowerCase();
+ return baseUrl === "" || baseUrl === expected;
+}
+
+export async function refreshProviderModelCatalogs(
+ providers: readonly ExternalProviderConfig[],
+ isCurrent?: () => boolean,
+): Promise<void> {
+ for (const provider of providers) {
+ const providerType = provider.providerType;
+ if (!usesProviderCatalogEndpoint(provider)) continue;
+ // A successful fetch makes the catalog fresh, so later connections of the same type skip;
+ // a failed one leaves it stale and the next connection gets a turn.
+ const fetchedAt = providerModelCatalogFetchedAt(providerType);
+ if (fetchedAt != null && Date.now() - fetchedAt < MODEL_CATALOG_TTL_MS) continue;
+ try {
+ const models = await listProviderModelCapabilities({
+ providerType,
+ providerId: provider.id,
+ apiKey: "",
+ });
+ if (isCurrent && !isCurrent()) return;
+ if (models.length > 0) setProviderModelCatalog(providerType, models);
+ } catch {
+ // Offline or unauthorized: the built-in tables answer until the next sync.
+ }
+ }
+}
diff --git a/studio/frontend/tests/external-thinking-wire.test.ts b/studio/frontend/tests/external-thinking-wire.test.ts
new file mode 100644
index 00000000000..7abe602baee
--- /dev/null
+++ b/studio/frontend/tests/external-thinking-wire.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { installLocalStorageFake, readSrc, registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+installLocalStorageFake();
+
+const { clearProviderModelCatalog, setProviderModelCatalog } = await import("../src/features/chat/model-catalog.ts");
+const { getExternalReasoningCapabilities } = await import(
+ "../src/features/chat/provider-capabilities.ts"
+);
+
+type Caps = ReturnType<typeof getExternalReasoningCapabilities>;
+
+// Runs the adapter's own external reasoning expressions, so the test follows the shipped code.
+function externalReasoningFields(caps: Caps, reasoningEnabled: boolean): unknown {
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ const enabledAt = adapter.indexOf("const externalReasoningEnabled =");
+ const fieldsAt = adapter.indexOf("...(externalReasoningCaps.supportsReasoning", enabledAt);
+ assert.ok(enabledAt > 0 && fieldsAt > enabledAt, "the adapter's external reasoning fields moved");
+ const enabled = adapter.slice(adapter.indexOf("=", enabledAt) + 1, adapter.indexOf(";", enabledAt));
+ const fields = adapter.slice(fieldsAt + 3, adapter.indexOf(": {}),", fieldsAt) + ": {})".length);
+ const build = new Function(
+ "externalReasoningCaps",
+ "reasoningEnabled",
+ "selectedExternalEffort",
+ "fallbackExternalEffort",
+ `const externalReasoningEnabled = ${enabled};\nreturn ${fields};`,
+ );
+ return build(caps, reasoningEnabled, "high", "high");
+}
+
+test("an always-on catalog model sends thinking on even when the chat stored it off", () => {
+ setProviderModelCatalog("openrouter", [{ id: "acme/always-thinking", reasoning: { mandatory: true } }], 1);
+ try {
+ const caps = getExternalReasoningCapabilities("openrouter", "acme/always-thinking");
+ assert.equal(caps.reasoningStyle, "enable_thinking");
+ assert.equal(caps.supportsReasoningOff, false);
+ assert.deepEqual(externalReasoningFields(caps, false), { thinking: { type: "enabled" } });
+ } finally {
+ clearProviderModelCatalog("openrouter");
+ }
+});
+
+test("every Thinking control resolves reasoning for the id the adapter sends, not the router's last pick", () => {
+ const modelArguments = (relative: string): string[] => {
+ const calls = [...readSrc(relative).matchAll(/getExternalReasoningCapabilities\(\s*[^,]+,\s*(?:\/\/[^\n]*\n\s*)?([^,]+),/g)];
+ assert.ok(calls.length > 0, relative);
+ return calls.map((match) => match[1].trim().replace("?.", "."));
+ };
+ assert.deepEqual(modelArguments("features/chat/api/chat-adapter.ts"), ["externalSelection.modelId"]);
+ for (const file of ["features/chat/shared-composer.tsx", "components/assistant-ui/thread.tsx"]) {
+ assert.deepEqual(modelArguments(file), ["externalSelection.modelId"], file);
+ }
+ assert.equal(getExternalReasoningCapabilities("openrouter", "openrouter/free").reasoningStyle, "enable_thinking");
+});
+
+test("a toggleable catalog model still sends the stored choice", () => {
+ setProviderModelCatalog("openrouter", [{ id: "acme/toggle-thinking", reasoning: { mandatory: false } }], 1);
+ try {
+ const caps = getExternalReasoningCapabilities("openrouter", "acme/toggle-thinking");
+ assert.equal(caps.reasoningStyle, "enable_thinking");
+ assert.equal(caps.supportsReasoningOff, true);
+ assert.deepEqual(externalReasoningFields(caps, false), { thinking: { type: "disabled" } });
+ assert.deepEqual(externalReasoningFields(caps, true), { thinking: { type: "enabled" } });
+ } finally {
+ clearProviderModelCatalog("openrouter");
+ }
+});
diff --git a/studio/frontend/tests/model-catalog.test.ts b/studio/frontend/tests/model-catalog.test.ts
new file mode 100644
index 00000000000..3f4f7b24168
--- /dev/null
+++ b/studio/frontend/tests/model-catalog.test.ts
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { installLocalStorageFake, registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+installLocalStorageFake();
+
+const {
+ clearProviderModelCatalog,
+ modelCatalogVersion,
+ providerModelCatalogFetchedAt,
+ resolveModelCatalogEntry,
+ setProviderModelCatalog,
+ subscribeModelCatalog,
+} = await import("../src/features/chat/model-catalog.ts");
+const {
+ getExternalReasoningCapabilities,
+ getPublishedExternalMaxOutputTokens,
+ reasoningFieldsAfterCatalogRefresh,
+} = await import("../src/features/chat/provider-capabilities.ts");
+const { providerModelSupportsVision } = await import(
+ "../src/features/chat/external-providers.ts"
+);
+
+const LIVE = [
+ {
+ id: "deepseek/deepseek-v4-pro",
+ input_modalities: ["text"],
+ reasoning: { supported_efforts: ["max", "high", "bogus"], mandatory: false, default_effort: "high" },
+ max_output_tokens: 65536,
+ },
+ { id: "acme/plain-chat", input_modalities: ["text", "image"], reasoning: null },
+ { id: "acme/always-thinking", input_modalities: ["text"], reasoning: { mandatory: true } },
+];
+
+function withLiveCatalog(run: () => void): void {
+ setProviderModelCatalog("openrouter", LIVE, 1234);
+ try {
+ run();
+ } finally {
+ clearProviderModelCatalog("openrouter");
+ }
+}
+
+test("without a live catalog every OpenRouter route keeps the generic toggle", () => {
+ assert.equal(providerModelCatalogFetchedAt("openrouter"), null);
+ for (const model of ["openrouter/free", "openrouter/auto", "acme/never-heard-of-it", "deepseek/deepseek-v4-pro"]) {
+ const caps = getExternalReasoningCapabilities("openrouter", model);
+ assert.equal(caps.supportsReasoning, true, model);
+ assert.equal(caps.reasoningStyle, "enable_thinking", model);
+ assert.equal(caps.supportsReasoningOff, true, model);
+ assert.equal(caps.reasoningAlwaysOn, false, model);
+ }
+ assert.equal(getPublishedExternalMaxOutputTokens("openrouter", "deepseek/deepseek-v4-pro"), null);
+});
+
+test("the live catalog carries the effort ladder, default effort, output cap and mandatory routes", () => {
+ withLiveCatalog(() => {
+ assert.equal(providerModelCatalogFetchedAt("openrouter"), 1234);
+ const caps = getExternalReasoningCapabilities("openrouter", "deepseek/deepseek-v4-pro");
+ assert.equal(caps.reasoningStyle, "reasoning_effort");
+ assert.deepEqual([...caps.reasoningEffortLevels], ["none", "high", "max"]);
+ assert.equal(caps.defaultEffort, "high");
+ assert.equal(getPublishedExternalMaxOutputTokens("openrouter", "deepseek/deepseek-v4-pro"), 65536);
+
+ assert.equal(getExternalReasoningCapabilities("openrouter", "acme/plain-chat").supportsReasoning, false);
+
+ const mandatory = getExternalReasoningCapabilities("openrouter", "acme/always-thinking");
+ assert.equal(mandatory.reasoningStyle, "enable_thinking");
+ assert.equal(mandatory.reasoningAlwaysOn, true);
+ assert.equal(mandatory.supportsReasoningOff, false);
+ assert.equal(
+ getExternalReasoningCapabilities("openrouter", "openrouter/free").reasoningStyle,
+ "enable_thinking",
+ "meta-routers keep the generic toggle",
+ );
+ });
+ assert.equal(providerModelCatalogFetchedAt("openrouter"), null);
+ assert.equal(
+ getExternalReasoningCapabilities("openrouter", "deepseek/deepseek-v4-pro").reasoningStyle,
+ "enable_thinking",
+ );
+});
+
+test("variant suffixes and the ~ prefix resolve through the base id", () => {
+ withLiveCatalog(() => {
+ const base = getExternalReasoningCapabilities("openrouter", "deepseek/deepseek-v4-pro");
+ for (const model of ["~deepseek/deepseek-v4-pro", "deepseek/deepseek-v4-pro:nitro", "DeepSeek/DeepSeek-V4-Pro"]) {
+ assert.deepEqual(getExternalReasoningCapabilities("openrouter", model), base, model);
+ }
+ assert.ok(resolveModelCatalogEntry("openrouter", "deepseek/deepseek-v4-pro:nitro"));
+ });
+});
+
+test("OpenRouter vision follows the live catalog's input modalities", () => {
+ withLiveCatalog(() => {
+ assert.equal(providerModelSupportsVision("openrouter", "acme/plain-chat"), true);
+ assert.equal(providerModelSupportsVision("openrouter", "deepseek/deepseek-v4-pro"), false);
+ assert.equal(providerModelSupportsVision("openrouter", "acme/never-heard-of-it"), true);
+ });
+ assert.equal(providerModelSupportsVision("openrouter", "deepseek/deepseek-v4-pro"), true);
+});
+
+test("providers other than OpenRouter keep their existing resolvers", () => {
+ withLiveCatalog(() => {
+ const opus = getExternalReasoningCapabilities("anthropic", "claude-opus-5");
+ assert.deepEqual([...opus.reasoningEffortLevels], ["none", "low", "medium", "high", "xhigh", "max"]);
+ for (const [provider, model] of [
+ ["deepseek", "deepseek-v4-pro"],
+ ["ollama", "gpt-oss:120b"],
+ ["vllm", "openai/gpt-oss-20b"],
+ ["llama_cpp", "Qwen3-0.6B-Q4_K_M.gguf"],
+ ["anthropic", "claude-3-7-sonnet-20250219"],
+ ] as const) {
+ assert.equal(getExternalReasoningCapabilities(provider, model).supportsReasoning, false, `${provider} ${model}`);
+ }
+ assert.equal(providerModelSupportsVision("deepseek", "deepseek-v4-pro"), false);
+ });
+});
+
+test("a live catalog default of none survives when the model can switch reasoning off", () => {
+ setProviderModelCatalog(
+ "openrouter",
+ [
+ {
+ id: "openai/gpt-5.1",
+ reasoning: { supported_efforts: ["high", "medium", "low", "none"], mandatory: false, default_effort: "none" },
+ },
+ {
+ id: "acme/always-on",
+ reasoning: { supported_efforts: ["high", "none"], mandatory: true, default_effort: "none" },
+ },
+ ],
+ 1,
+ );
+ try {
+ const gpt51 = getExternalReasoningCapabilities("openrouter", "openai/gpt-5.1");
+ assert.deepEqual([...gpt51.reasoningEffortLevels], ["none", "low", "medium", "high"]);
+ assert.equal(gpt51.defaultEffort, "none");
+ const alwaysOn = getExternalReasoningCapabilities("openrouter", "acme/always-on");
+ assert.equal(alwaysOn.supportsReasoningOff, false);
+ assert.equal(alwaysOn.defaultEffort, null, "a mandatory model cannot default to off");
+ } finally {
+ clearProviderModelCatalog("openrouter");
+ }
+});
+
+test("every catalog write notifies subscribers, so a composer already on screen re-renders", () => {
+ let notified = 0;
+ const unsubscribe = subscribeModelCatalog(() => {
+ notified += 1;
+ });
+ const before = modelCatalogVersion();
+ try {
+ setProviderModelCatalog("openrouter", [{ id: "acme/late", reasoning: { supported_efforts: ["high"] } }], 1);
+ assert.equal(notified, 1);
+ clearProviderModelCatalog("openrouter");
+ assert.equal(notified, 2);
+ clearProviderModelCatalog("openrouter");
+ assert.equal(notified, 2, "clearing an absent catalog changes nothing");
+ } finally {
+ unsubscribe();
+ }
+ assert.notEqual(modelCatalogVersion(), before);
+ setProviderModelCatalog("openrouter", [{ id: "acme/late" }], 1);
+ clearProviderModelCatalog("openrouter");
+ assert.equal(notified, 2, "an unsubscribed listener is not called");
+});
+
+test("a catalog that lands after selection refreshes the stored reasoning fields without resetting a valid effort", () => {
+ const generic = getExternalReasoningCapabilities("openrouter", "deepseek/deepseek-v4-pro");
+ assert.equal(generic.reasoningStyle, "enable_thinking");
+ withLiveCatalog(() => {
+ const caps = getExternalReasoningCapabilities("openrouter", "deepseek/deepseek-v4-pro");
+ const kept = reasoningFieldsAfterCatalogRefresh({ reasoningEffort: "high", reasoningEnabled: false }, caps);
+ assert.equal(kept.supportsReasoning, true);
+ assert.equal(kept.reasoningStyle, "reasoning_effort");
+ assert.deepEqual([...kept.reasoningEffortLevels], ["none", "high", "max"]);
+ assert.equal(kept.reasoningEffort, "high", "a chosen effort the ladder still offers is kept");
+ assert.equal(kept.reasoningEnabled, false, "a toggleable model keeps the stored choice");
+
+ const clamped = reasoningFieldsAfterCatalogRefresh({ reasoningEffort: "medium", reasoningEnabled: true }, caps);
+ assert.equal(clamped.reasoningEffort, "high", "an effort the ladder dropped is clamped onto an offered one");
+
+ const alwaysOn = reasoningFieldsAfterCatalogRefresh(
+ { reasoningEffort: "medium", reasoningEnabled: false },
+ getExternalReasoningCapabilities("openrouter", "acme/always-thinking"),
+ );
+ assert.equal(alwaysOn.reasoningAlwaysOn, true);
+ assert.equal(alwaysOn.reasoningEnabled, true, "a model without an off switch is forced on");
+ });
+});
+
+test("a mandatory OpenRouter alias keeps its catalog effort ladder", () => {
+ setProviderModelCatalog("openrouter", [{
+ id: "~google/gemini-pro-latest",
+ reasoning: {
+ mandatory: true,
+ supported_efforts: ["high", "medium", "low"],
+ default_effort: "medium",
+ },
+ }]);
+ try {
+ const caps = getExternalReasoningCapabilities("openrouter", "~google/gemini-pro-latest");
+ assert.equal(caps.reasoningStyle, "reasoning_effort");
+ assert.deepEqual([...caps.reasoningEffortLevels], ["low", "medium", "high"]);
+ assert.equal(caps.supportsReasoningOff, false);
+ assert.equal(caps.defaultEffort, "medium");
+ } finally {
+ clearProviderModelCatalog("openrouter");
+ }
+ const fallback = getExternalReasoningCapabilities("openrouter", "~google/gemini-pro-latest");
+ assert.equal(fallback.reasoningAlwaysOn, true);
+ assert.equal(fallback.supportsReasoningOff, false);
+});
diff --git a/studio/frontend/tests/provider-capabilities-current-models.test.ts b/studio/frontend/tests/provider-capabilities-current-models.test.ts
index 2fefb211f3e..a7750187951 100644
--- a/studio/frontend/tests/provider-capabilities-current-models.test.ts
+++ b/studio/frontend/tests/provider-capabilities-current-models.test.ts
@@ -187,7 +187,7 @@ test("the effort scale matches the backend's _REASONING_EFFORT_SCALE", () => {
// ladders from the backend one, so drift hands the clamp a level it cannot rank.
const here = path.dirname(fileURLToPath(import.meta.url));
const frontend = readFileSync(
- path.join(here, "../src/features/chat/provider-capabilities.ts"),
+ path.join(here, "../src/features/chat/model-catalog.ts"),
"utf8",
);
const backend = readFileSync(
diff --git a/studio/frontend/tests/provider-catalog-refresh.test.ts b/studio/frontend/tests/provider-catalog-refresh.test.ts
new file mode 100644
index 00000000000..49e8bcd8f3d
--- /dev/null
+++ b/studio/frontend/tests/provider-catalog-refresh.test.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { after, before, test } from "node:test";
+import { createServer, type ViteDevServer } from "vite";
+
+import { readSrc } from "./helpers/kit.ts";
+
+let vite: ViteDevServer;
+
+before(async () => {
+ vite = await createServer({ appType: "custom", server: { middlewareMode: true } });
+});
+
+after(async () => {
+ await vite.close();
+});
+
+test("a failing OpenRouter connection leaves the catalog for the next connection to refresh", async () => {
+ const { refreshProviderModelCatalogs } = await vite.ssrLoadModule(
+ "/src/features/chat/sync-external-providers.ts",
+ );
+ const catalog = await vite.ssrLoadModule("/src/features/chat/model-catalog.ts");
+ const asked: string[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ const { provider_id: providerId } = JSON.parse(String(init?.body));
+ asked.push(providerId);
+ return providerId === "expired-key"
+ ? Response.json({ detail: "Invalid API key" }, { status: 502 })
+ : Response.json([{ id: "acme/fresh", reasoning: { supported_efforts: ["low", "high"] } }]);
+ }) as typeof fetch;
+ try {
+ await refreshProviderModelCatalogs([
+ { id: "expired-key", providerType: "openrouter" },
+ { id: "working-key", providerType: "openrouter" },
+ { id: "second-working-key", providerType: "openrouter" },
+ ]);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ assert.deepEqual(asked, ["expired-key", "working-key"]);
+ assert.deepEqual(catalog.resolveModelCatalogEntry("openrouter", "acme/fresh")?.efforts, ["low", "high"]);
+ catalog.clearProviderModelCatalog("openrouter");
+});
+
+test("an OpenRouter connection on a gateway base URL never writes the shared catalog", async () => {
+ const { refreshProviderModelCatalogs } = await vite.ssrLoadModule(
+ "/src/features/chat/sync-external-providers.ts",
+ );
+ const catalog = await vite.ssrLoadModule("/src/features/chat/model-catalog.ts");
+ const asked: string[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ const { provider_id: providerId } = JSON.parse(String(init?.body));
+ asked.push(providerId);
+ return providerId === "gateway"
+ ? Response.json([{ id: "acme/fresh", reasoning: { supported_efforts: ["max"] } }])
+ : Response.json([{ id: "acme/fresh", reasoning: { supported_efforts: ["low", "high"] } }]);
+ }) as typeof fetch;
+ try {
+ await refreshProviderModelCatalogs([
+ { id: "gateway", providerType: "openrouter", baseUrl: "https://gateway.example/api/v1" },
+ { id: "openrouter", providerType: "openrouter", baseUrl: "https://openrouter.ai/api/v1/" },
+ ]);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ try {
+ assert.deepEqual(asked, ["openrouter"]);
+ assert.deepEqual(catalog.resolveModelCatalogEntry("openrouter", "acme/fresh")?.efforts, ["low", "high"]);
+ } finally {
+ catalog.clearProviderModelCatalog("openrouter");
+ }
+});
+
+test("editing a connection refreshes the catalog with the saved base URL, not the one it replaced", async () => {
+ const dialog = readSrc("features/chat/chat-providers-dialog.tsx");
+ const saveAt = dialog.indexOf("async function saveProviderEdits()");
+ const save = dialog.slice(saveAt, dialog.indexOf("\n async function ", saveAt + 1));
+ const refreshed = save.match(/refreshProviderModelCatalogs\(\[(\w+)\]\)/)?.[1];
+ assert.ok(saveAt > 0 && refreshed, "the edit save path no longer refreshes the catalog");
+ const literalAt = save.indexOf(`const ${refreshed}: ExternalProviderConfig = {`);
+ assert.ok(literalAt > 0, `${refreshed} is not the edited connection`);
+ assert.match(save.slice(literalAt, save.indexOf("\n };", literalAt)), /baseUrl: updated\.base_url/);
+
+ const { refreshProviderModelCatalogs } = await vite.ssrLoadModule(
+ "/src/features/chat/sync-external-providers.ts",
+ );
+ const catalog = await vite.ssrLoadModule("/src/features/chat/model-catalog.ts");
+ const asked: string[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ asked.push(JSON.parse(String(init?.body)).provider_id);
+ return Response.json([{ id: "acme/fresh", reasoning: { supported_efforts: ["low", "high"] } }]);
+ }) as typeof fetch;
+ try {
+ await refreshProviderModelCatalogs([
+ { id: "edited", providerType: "openrouter", baseUrl: "https://openrouter.ai/api/v1" },
+ ]);
+ assert.deepEqual(asked, ["edited"]);
+ } finally {
+ globalThis.fetch = realFetch;
+ catalog.clearProviderModelCatalog("openrouter");
+ }
+});
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py
index 95db53c2a02..3c9baaf3010 100644
--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py
@@ -547,6 +547,8 @@ NOT_GATED: dict[str, str] = {
"studio/backend/core/inference/key_exchange.py": "encrypts stored credentials. studiobench "
"posts its provider without one, so this code is not on the measured path",
"studio/backend/core/inference/pricing.py": "cost figures, which the scene never renders",
+ "studio/backend/core/inference/provider_model_capabilities.py": "OpenRouter and models.dev "
+ "capability catalogs; studiobench registers a custom provider, which neither catalog describes",
"studio/backend/utils/utils.py": "generic helpers imported by most of the backend; gating on "
"it would run this workflow on nearly every PR and defeat the filter",
"studio/backend/utils/account_context.py": "request identity ContextVar imported across the "