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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
feat(studio): opt-in reasoning for Custom Chat Completions connections (#12743)
Wasim Yousef Said6530c3ae2e88
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex d70c67233e0..09edc19fefe 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -32,6 +32,10 @@ from core.inference.openai_responses_shared import (response_event_type,)from core.inference.sse_control_frames import sanitize_provider_sse_line+from models.providers import (+ normalize_provider_reasoning_config,+ validate_provider_reasoning_contract,+)# Local servers, not hosted APIs: each applies the model's own chat template on the way in, so a prompt built here is# templated just like an in-process one (#7066). "custom" is a user-supplied OpenAI-compatible base_url, i.e. how a@@ -1407,6 +1411,35 @@ def _build_kimi_tool_end()+def _apply_custom_reasoning_controls(+ body: dict[str, Any],+ config: Optional[dict],+ enable_thinking: Optional[bool],+ reasoning_effort: Optional[str],+) -> None:+ """Emit exactly one explicitly configured dialect. Disabled/corrupt config emits nothing."""+ if not config or not config["enabled"]:+ return+ off = enable_thinking is False or reasoning_effort == "none"+ # Explicit off must still reach the server when a previous model left a wider effort level.+ if (+ not off+ and reasoning_effort is not None+ and reasoning_effort not in {"low", "medium", "high"}+ ):+ return+ effort = "none" if off else (reasoning_effort or "medium")+ style = config["style"]+ if style == "reasoning_effort":+ body["reasoning_effort"] = effort+ elif style == "reasoning":+ body["reasoning"] = {"enabled": False} if off else {"effort": effort}+ elif style == "thinking":+ body["thinking"] = {"type": "disabled" if off else "enabled"}+ elif style == "chat_template_kwargs.enable_thinking":+ body["chat_template_kwargs"] = {"enable_thinking": not off}++class ExternalProviderClient:"""Async proxy for OpenAI-compatible external APIs."""@@ -1418,10 +1451,17 @@ class ExternalProviderClient:timeout: float = 120.0,*,api_type: str = "chat_completions",+ reasoning_config: Optional[dict] = None,managed_loopback: bool = False,):self.provider_type = provider_typeself.api_type = api_type if provider_type == "custom" else "chat_completions"+ self.reasoning_config = (+ normalize_provider_reasoning_config(reasoning_config)+ if provider_type == "custom"+ else None+ )+ validate_provider_reasoning_contract(provider_type, self.api_type, self.reasoning_config)from core.inference.providers import validate_provider_base_urlself.base_url = (@@ -1738,6 +1778,10 @@ class ExternalProviderClient:_apply_ollama_reasoning_controls(body, enable_thinking, reasoning_effort)elif self.provider_type == "lemonade":_apply_fastflowlm_reasoning_controls(body, enable_thinking, reasoning_effort)+ elif self.provider_type == "custom":+ _apply_custom_reasoning_controls(+ body, self.reasoning_config, enable_thinking, reasoning_effort+ )# OpenRouter's unified `reasoning` field gates per-model thinking. Some routes# (`*_MANDATORY_REASONING_MODELS`) 400 on explicit off.diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex c490f6b8457..5261e4dd389 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -34,6 +34,7 @@ from core.inference.llama_server_args import (from core.inference.runtime_context import MAX_REQUESTABLE_CONTEXTfrom core.inference.video_families import MAX_VIDEO_NUM_FRAMESfrom picker.schemas import MAX_CHAT_TEMPLATE_BYTES+from models.providers import ProviderReasoningConfigfrom utils.reasoning_budget import validate_reasoning_budget_message@@ -2841,6 +2842,10 @@ class ChatCompletionRequest(BaseModel):description = "[x-unsloth] Saved provider config ID. Its stored key is used when encrypted_api_key is omitted.",)provider_api_type: Literal["chat_completions", "responses"] = "chat_completions"+ provider_reasoning_config: Optional[ProviderReasoningConfig] = Field(+ None,+ description = "[x-unsloth] Explicit Custom reasoning dialect; saved provider configuration takes precedence.",+ )provider_type: Optional[str] = Field(None,description = "[x-unsloth] Provider type (e.g. 'openai', 'mistral'). Used if provider_id is not set.",diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.pyindex 43e7ce3ed74..492c4036e2d 100644--- a/studio/backend/models/providers.py+++ b/studio/backend/models/providers.py@@ -5,10 +5,42 @@from typing import Literal, Optional-from pydantic import BaseModel, Field+from pydantic import BaseModel, ConfigDict, Field, StrictBool, ValidationErrorProviderApiType = Literal["chat_completions", "responses", "systemone"]++class ProviderReasoningConfig(BaseModel):+ """Explicit Custom Chat Completions wire dialect, never inferred from the URL."""++ model_config = ConfigDict(extra = "forbid")++ enabled: StrictBool+ style: Literal[+ "reasoning_effort", "reasoning", "thinking", "chat_template_kwargs.enable_thinking"+ ]+++def normalize_provider_reasoning_config(value) -> Optional[dict]:+ """Treat absent or corrupt persisted/internal configuration as unconfigured."""+ if isinstance(value, ProviderReasoningConfig):+ value = value.model_dump()+ try:+ return ProviderReasoningConfig.model_validate(value).model_dump()+ except (ValidationError, TypeError, ValueError):+ return None+++def validate_provider_reasoning_contract(provider_type: str, api_type: str, config) -> None:+ if config is None:+ return+ if provider_type != "custom":+ raise ValueError("reasoning_config is supported only for Custom connections.")+ normalized = normalize_provider_reasoning_config(config)+ if normalized and normalized["enabled"] and api_type != "chat_completions":+ raise ValueError("Enabled Custom reasoning requires the Chat Completions API.")++MAX_JSON_SAFE_INTEGER = 9_007_199_254_740_991@@ -54,6 +86,7 @@ class ProviderCreate(BaseModel):"""Request to create a saved provider configuration."""api_type: ProviderApiType = "chat_completions"+ reasoning_config: Optional[ProviderReasoningConfig] = Noneprovider_type: str = Field(..., description = "Provider type from the registry")display_name: str = Field(..., description = "User-chosen label (e.g. 'My OpenAI Key')")@@ -87,6 +120,7 @@ class ProviderUpdate(BaseModel):"""Request to update a saved provider configuration."""api_type: Optional[ProviderApiType] = None+ reasoning_config: Optional[ProviderReasoningConfig] = Nonedisplay_name: Optional[str] = Field(None, description = "New display name")base_url: Optional[str] = Field(None, description = "New base URL")@@ -128,6 +162,7 @@ class ProviderResponse(BaseModel):"""A saved provider configuration (returned by list/get endpoints)."""api_type: ProviderApiType = "chat_completions"+ reasoning_config: Optional[ProviderReasoningConfig] = Noneid: str = Field(..., description = "Unique provider config ID")provider_type: str = Field(..., description = "Provider type (e.g. 'openai')")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 29f8f16506c..5deda297954 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3976,6 +3976,10 @@ from core.inference.studio_tool_loop import (from core.inference.chat_templates import resolve_effective_chat_template_overridefrom routes.provider_credentials import provider_config_guard, resolve_provider_api_key_or_400from storage import providers_db+from models.providers import (+ normalize_provider_reasoning_config,+ validate_provider_reasoning_contract,+)from utils.utils import is_hf_authentication_error, safe_error_detail, log_and_http_errorimport io@@ -27216,14 +27220,18 @@ async def _proxy_to_external_provider(provider_type = payload.provider_typebase_url = payload.provider_base_urlapi_type = payload.provider_api_type+ reasoning_config = normalize_provider_reasoning_config(payload.provider_reasoning_config)saved_provider_snapshot: Optional[dict] = Noneif managed is not None:provider_type = managed.provider_typebase_url = managed.base_urlapi_type = "chat_completions"- elif payload.provider_id and not payload.encrypted_api_key:- # Saved-provider SQLite reads must not block the event loop.+ reasoning_config = None+ elif payload.provider_id and (+ not payload.encrypted_api_key or payload.provider_reasoning_config is not None+ ):+ # Legacy explicit-key requests retain editable routing; reasoning opt-ins use the saved contract.config = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)if config is None:raise HTTPException(@@ -27241,6 +27249,7 @@ async def _proxy_to_external_provider(provider_type = config["provider_type"]base_url = config["base_url"]api_type = config.get("api_type", "chat_completions")+ reasoning_config = normalize_provider_reasoning_config(config.get("reasoning_config"))if not provider_type:raise HTTPException(@@ -27248,6 +27257,13 @@ async def _proxy_to_external_provider(detail = "Either provider_id or provider_type is required for external provider routing.",)_refuse_decision_connection(provider_type, api_type)+ if provider_type == "custom":+ try:+ validate_provider_reasoning_contract(provider_type, api_type, reasoning_config)+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+ else:+ reasoning_config = None# Unsloth's tools run on this host, so any provider whose wire format can# carry a tool schema out and a result back can use them. The capability is@@ -27795,7 +27811,13 @@ async def _proxy_to_external_provider(elif saved_provider_snapshot is not None:async with provider_config_guard(payload.provider_id):current = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)- routing_fields = ("provider_type", "base_url", "api_type", "is_enabled")+ routing_fields = (+ "provider_type",+ "base_url",+ "api_type",+ "is_enabled",+ "reasoning_config",+ )if current is None or any(current.get(field) != saved_provider_snapshot.get(field) for field in routing_fields):@@ -27806,7 +27828,7 @@ async def _proxy_to_external_provider(api_key = await asyncio.to_thread(resolve_provider_api_key_or_400,payload.provider_id,- None,+ payload.encrypted_api_key,allow_saved_key = (not _request_has_api_key(request)or _request_is_saved_credential_workflow(request)@@ -27876,6 +27898,7 @@ async def _proxy_to_external_provider(base_url = base_url,api_key = api_key,api_type = api_type,+ **({"reasoning_config": reasoning_config} if reasoning_config is not None else {}),**({"managed_loopback": True} if managed is not None else {}),)_non_stream_custom_responses = (diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex 4c150c311b3..f00407ce763 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -62,6 +62,7 @@ from models.providers import (ProviderTestRequest,ProviderTestResult,ProviderUpdate,+ validate_provider_reasoning_contract,)from storage import credential_secrets, providers_dbfrom hub.services.models import account_access@@ -84,6 +85,7 @@ def _provider_response(row: dict) -> ProviderResponse:display_name = row["display_name"],base_url = row["base_url"],api_type = row.get("api_type", "chat_completions"),+ reasoning_config = row.get("reasoning_config"),is_enabled = bool(row["is_enabled"]),has_api_key = credential_secrets.has_secret(credential_secrets.PROVIDER_API_KEY_KIND,@@ -235,6 +237,13 @@ async def create_provider_config(f"Use GET /api/providers/registry to see available types.",)+ try:+ validate_provider_reasoning_contract(+ payload.provider_type, payload.api_type, payload.reasoning_config+ )+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+_validate_max_output_tokens_contract(payload.provider_type,"max_output_tokens" in payload.model_fields_set,@@ -273,6 +282,7 @@ async def create_provider_config(available_models = payload.available_models,max_output_tokens = payload.max_output_tokens,api_type = payload.api_type,+ reasoning_config = payload.reasoning_config,)try:if api_key:@@ -300,6 +310,19 @@ async def update_provider_config(if not existing:raise HTTPException(status_code = 404, detail = "Provider not found")+ reasoning_config_requested = "reasoning_config" in payload.model_fields_set+ effective_reasoning_config = (+ payload.reasoning_config if reasoning_config_requested else existing.get("reasoning_config")+ )+ try:+ validate_provider_reasoning_contract(+ existing["provider_type"],+ payload.api_type or existing.get("api_type", "chat_completions"),+ effective_reasoning_config,+ )+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from None+existing_info = get_provider_info(existing["provider_type"]) or {}max_output_tokens_requested = "max_output_tokens" in payload.model_fields_set_validate_max_output_tokens_contract(@@ -364,6 +387,7 @@ async def update_provider_config("available_models","max_output_tokens","api_type",+ "reasoning_config",}metadata_requested = bool(payload.model_fields_set & metadata_fields)@@ -398,6 +422,12 @@ async def update_provider_config()if max_output_tokens_requested:metadata_updates["max_output_tokens"] = payload.max_output_tokens+ if reasoning_config_requested:+ metadata_updates["reasoning_config"] = (+ payload.reasoning_config.model_dump()+ if payload.reasoning_config is not None+ else None+ )# The row snapshot this request found, keyed the way update_provider takes it._restorable = dict(@@ -408,6 +438,7 @@ async def update_provider_config(available_models = existing.get("available_models") or [],max_output_tokens = existing.get("max_output_tokens"),api_type = existing.get("api_type", "chat_completions"),+ reasoning_config = existing.get("reasoning_config"),)def _current_matches(current: dict, field: str, written) -> bool:@@ -434,9 +465,8 @@ async def update_provider_config(for field, written in metadata_updates.items():if field == "id":continue- # None means "not sent" for every column but max_output_tokens, which is only present here when it was- # explicitly requested. update_provider left the unsent ones alone, so there is nothing to take back.- if written is None and field != "max_output_tokens":+ # Explicit null clears nullable overrides; elsewhere it means "not sent".+ if written is None and field not in {"max_output_tokens", "reasoning_config"}:continueif not _current_matches(current, field, written):continuediff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.pyindex fb16ff5bcd9..3a2f7d0b806 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -24,6 +24,7 @@ from urllib.parse import urlparselogger = logging.getLogger(__name__)+from models.providers import ProviderReasoningConfig, normalize_provider_reasoning_configfrom storage.studio_db import connect_studio_dbfrom utils.paths import studio_db_path, ensure_dir@@ -94,6 +95,23 @@ def _decode_models_json(raw: Optional[str]) -> list[str]:return [str(model).strip() for model in parsed if str(model).strip()]+def _encode_reasoning_config(config) -> Optional[str]:+ if config is None:+ return None+ if isinstance(config, ProviderReasoningConfig):+ config = config.model_dump()+ return ProviderReasoningConfig.model_validate(config).model_dump_json()+++def _decode_reasoning_config(raw) -> Optional[dict]:+ if not raw:+ return None+ try:+ return normalize_provider_reasoning_config(json.loads(raw))+ except (json.JSONDecodeError, TypeError):+ return None++def _row_models(row: sqlite3.Row) -> tuple[list[str], list[str]]:return (_decode_models_json(row["models_json"] if "models_json" in row.keys() else None),@@ -133,6 +151,8 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:_migrate_legacy_custom_provider_types(conn)if "max_output_tokens" not in existing_cols:conn.execute("ALTER TABLE llm_providers ADD COLUMN max_output_tokens INTEGER")+ if "reasoning_config_json" not in existing_cols:+ conn.execute("ALTER TABLE llm_providers ADD COLUMN reasoning_config_json TEXT")# ALTER TABLE persists independently in SQLite, but its one-time data migration does not.conn.commit()@@ -194,8 +214,10 @@ def create_provider(available_models: Optional[list[str]] = None,max_output_tokens: Optional[int] = None,api_type: str = "chat_completions",+ reasoning_config: Optional[dict] = None,) -> None:"""Insert a new provider configuration."""+ reasoning_json = _encode_reasoning_config(reasoning_config)now = datetime.now(timezone.utc).isoformat()conn = get_connection()try:@@ -204,9 +226,9 @@ def create_provider(INSERT INTO llm_providers (id, provider_type, display_name, base_url,models_json, available_models_json, max_output_tokens, api_type,- created_at, updated_at+ reasoning_config_json, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(id,@@ -217,6 +239,7 @@ def create_provider(_encode_models_json(available_models),max_output_tokens,api_type,+ reasoning_json,now,now,),@@ -237,6 +260,7 @@ def update_provider(*,connection: sqlite3.Connection | None = None,api_type: str | None = None,+ reasoning_config: dict | None | object = _UNSET,) -> bool:"""Update fields on an existing provider. Returns True if a row was updated."""updates = []@@ -262,6 +286,9 @@ def update_provider(if max_output_tokens is not _UNSET:updates.append("max_output_tokens = ?")params.append(max_output_tokens)+ if reasoning_config is not _UNSET:+ updates.append("reasoning_config_json = ?")+ params.append(_encode_reasoning_config(reasoning_config))if not updates:return Falseupdates.append("updated_at = ?")@@ -302,6 +329,7 @@ def get_provider(id: str) -> Optional[dict]:if not row:return Nonedata = dict(row)+ data["reasoning_config"] = _decode_reasoning_config(data.pop("reasoning_config_json", None))models, available_models = _row_models(row)data["models"] = modelsdata["available_models"] = available_models@@ -318,6 +346,9 @@ def list_providers() -> list[dict]:providers: list[dict] = []for row in rows:data = dict(row)+ data["reasoning_config"] = _decode_reasoning_config(+ data.pop("reasoning_config_json", None)+ )models, available_models = _row_models(row)data["models"] = modelsdata["available_models"] = available_modelsdiff --git a/studio/backend/tests/test_custom_provider_reasoning_config.py b/studio/backend/tests/test_custom_provider_reasoning_config.pynew file mode 100644index 00000000000..0b7434a9b35--- /dev/null+++ b/studio/backend/tests/test_custom_provider_reasoning_config.py@@ -0,0 +1,313 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Per-connection Custom reasoning contracts, including actual HTTP payloads."""++import asyncio+import base64+import json+import os+import re+import sqlite3+from http.server import BaseHTTPRequestHandler+from pathlib import Path+from types import SimpleNamespace++import httpx+import pytest+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.asymmetric import padding, rsa+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient+from pydantic import ValidationError++from auth import storage as auth_storage+from core.inference import external_provider as ep, key_exchange+from models.inference import ChatCompletionRequest+from models.providers import ProviderCreate, ProviderUpdate+from routes import inference, providers+from storage import credential_secrets, providers_db+from .test_external_provider_sampling_over_the_wire import _Server++STYLES = ("reasoning_effort", "reasoning", "thinking", "chat_template_kwargs.enable_thinking")+BAD = [+ {"enabled": "true", "style": "thinking"},+ {"enabled": 1, "style": "thinking"},+ {"enabled": True, "style": "unknown"},+ {"enabled": True, "style": "thinking", "extra": 1},+ {"style": "thinking"},+ ["thinking"],+]+KEYS = {"reasoning_effort", "reasoning", "thinking", "chat_template_kwargs", "enable_thinking"}+PROVIDER = {"provider_type": "custom", "display_name": "Gateway"}+CHAT = {"messages": [{"role": "user", "content": "hi"}], "model": "test-model"}+++def config(style = "reasoning_effort", enabled = True):+ return {"enabled": enabled, "style": style}+++def expected(style, effort = "medium"):+ off = effort == "none"+ return {+ "reasoning_effort": {"reasoning_effort": effort},+ "reasoning": {"reasoning": {"enabled": False} if off else {"effort": effort}},+ "thinking": {"thinking": {"type": "disabled" if off else "enabled"}},+ "chat_template_kwargs.enable_thinking": {+ "chat_template_kwargs": {"enable_thinking": not off}+ },+ }[style]+++def reasoning(body):+ return {key: value for key, value in body.items() if key in KEYS}+++class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self): # noqa: N802+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ self.server.recorded.append(+ {"path": self.path, "body": body, "auth": self.headers.get("Authorization")}+ )+ data = (+ b'data: {"type":"response.output_text.delta","delta":"ok"}\n\n'+ b'data: {"type":"response.completed","response":{"id":"resp_test"}}\n\n'+ if self.path.endswith("/responses")+ else b'data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n'+ )+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)+++def harness(tmp_path, monkeypatch, request):+ # conftest isolates studio.db and schema caches; auth.DB_PATH is import-time state.+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_credential_encryption_key_cache", None)+ app = FastAPI()+ app.include_router(providers.router, prefix = "/api/providers")+ app.dependency_overrides[providers.get_current_subject] = lambda: "alice"+ app.dependency_overrides[providers.get_current_credential] = lambda: ("alice", None)+ app.dependency_overrides[providers.authenticated_via_api_key] = lambda: False++ async def disconnected():+ return False++ route_request = SimpleNamespace(+ headers = {}, state = SimpleNamespace(skip_api_monitor = True), is_disconnected = disconnected+ )+ with _Server(Handler) as server, TestClient(app) as client:++ async def send(+ mode = "client",+ cfg = None,+ api_type = "chat_completions",+ **fields,+ ):+ async with httpx.AsyncClient(trust_env = False) as transport:+ monkeypatch.setattr(ep, "_http_client", transport)+ if mode == "client":+ upstream = ep.ExternalProviderClient(+ "custom", server.base_url, "", api_type = api_type, reasoning_config = cfg+ )+ output = upstream.stream_chat_completion(**CHAT, **fields)+ else:+ defaults = dict(+ CHAT,+ stream = True,+ provider_type = "custom",+ provider_base_url = server.base_url,+ provider_reasoning_config = cfg,+ )+ payload = ChatCompletionRequest(**{**defaults, **fields})+ response = await inference._proxy_to_external_provider(payload, route_request)+ output = response.body_iterator+ assert "ok" in "".join([line async for line in output])+ path = "responses" if api_type == "responses" else "chat/completions"+ assert server.bodies[-1]["path"] == f"/v1/{path}"+ return server.bodies[-1]["body"]++ def api(+ method,+ path = "/",+ status = 200,+ **payload,+ ):+ response = client.request(method, "/api/providers" + path, json = payload)+ assert response.status_code == status, response.text+ return response.json()++ yield SimpleNamespace(+ db = providers_db.studio_db_path(),+ url = server.base_url,+ api = api,+ send = lambda *args, **kwargs: asyncio.run(send(*args, **kwargs)),+ recorded = server.bodies,+ )+ root = os.environ.get("UNSLOTH_REASONING_EVIDENCE_DIR")+ if root:+ path = Path(root)+ path.mkdir(parents = True, exist_ok = True)+ name = re.sub(r"[^a-zA-Z0-9_.-]", "_", request.node.name)+ (path / f"{name}.json").write_text(json.dumps(server.bodies, indent = 2) + "\n")++[email protected]("schema", [ProviderCreate, ProviderUpdate, ChatCompletionRequest])+def test_strict_schema(schema):+ field = "provider_reasoning_config" if schema is ChatCompletionRequest else "reasoning_config"+ payload = dict(PROVIDER, messages = [])+ for value in [None, *[config(style, enabled) for style in STYLES for enabled in (True, False)]]:+ assert schema(**payload, **{field: value}).model_dump()[field] == value+ for bad in BAD:+ with pytest.raises(ValidationError):+ schema(**payload, **{field: bad})++[email protected]("style", STYLES)+def test_api_persistence_and_wire(harness, style):+ h = harness+ created = h.api("POST", status = 201, **PROVIDER, base_url = h.url, reasoning_config = config(style))+ assert created["reasoning_config"] == config(style)+ provider_id = created["id"]+ for update, value in [+ ({"display_name": "Renamed"}, config(style)),+ ({"reasoning_config": config(style, False)}, config(style, False)),+ ({"reasoning_config": None}, None),+ ]:+ assert h.api("PUT", f"/{provider_id}", **update)["reasoning_config"] == value+ providers_db.reset_schema_state_for_tests()+ assert providers_db.get_provider(provider_id)["reasoning_config"] == value+ assert h.api("GET")[0]["reasoning_config"] == value+ assert providers_db.list_providers()[0]["reasoning_config"] == value+ body = h.send("route", config("thinking"), provider_id = provider_id, reasoning_effort = "high")+ assert reasoning(body) == (expected(style, "high") if value and value["enabled"] else {})++[email protected]("style", STYLES)[email protected]("mode", ["client", "route"])+def test_style_controls_real_http(harness, style, mode):+ for controls, effort in [+ ({}, "medium"),+ ({"enable_thinking": True}, "medium"),+ ({"enable_thinking": False}, "none"),+ ({"reasoning_effort": "none"}, "none"),+ ({"enable_thinking": False, "reasoning_effort": "max"}, "none"),+ *[({"reasoning_effort": e}, e) for e in ("low", "medium", "high")],+ ({"reasoning_effort": "max"}, None),+ ]:+ body = harness.send(mode, config(style), **controls)+ assert reasoning(body) == (expected(style, effort) if effort else {}), controls+++def test_fail_closed_and_legacy_body(harness):+ h = harness+ controls = {"enable_thinking": True, "reasoning_effort": "high"}+ legacy = h.send()+ for value in [None, *[config(style, False) for style in STYLES], *BAD]:+ assert h.send(cfg = value, **controls) == legacy+ with sqlite3.connect(h.db) as conn:+ conn.execute(+ "CREATE TABLE llm_providers (id TEXT PRIMARY KEY, provider_type TEXT, display_name TEXT, base_url TEXT, is_enabled INTEGER, created_at TEXT, updated_at TEXT)"+ )+ conn.execute(+ "INSERT INTO llm_providers VALUES ('legacy', 'custom', 'Gateway', ?, 1, '', '')",+ (h.url,),+ )+ assert providers_db.get_provider("legacy")["reasoning_config"] is None+ legacy_route = h.send("route", provider_id = "legacy")+ assert reasoning(legacy_route) == {}+ for raw in ["not json", "[]", *[json.dumps(bad) for bad in BAD]]:+ with sqlite3.connect(h.db) as conn:+ conn.execute("UPDATE llm_providers SET reasoning_config_json = ?", (raw,))+ assert providers_db.get_provider("legacy")["reasoning_config"] is None+ assert providers_db.list_providers()[0]["reasoning_config"] is None+ assert h.send("route", config(), provider_id = "legacy", **controls) == legacy_route++[email protected]("api_type", ["responses", "systemone"])+def test_incompatible_contracts(harness, api_type):+ h = harness+ payload = dict(PROVIDER, api_type = api_type, reasoning_config = config())+ h.api("POST", status = 400, **payload)+ with pytest.raises(ValueError, match = "Chat Completions"):+ ep.ExternalProviderClient("custom", h.url, "", api_type = api_type, reasoning_config = config())+ if api_type == "responses":+ with pytest.raises(HTTPException) as exc:+ h.send("route", config(), provider_api_type = api_type)+ assert exc.value.status_code == 400+ assert h.recorded == []+ payload["api_type"] = "chat_completions"+ provider_id = h.api("POST", status = 201, **payload)["id"]+ for update, status in [+ ({"api_type": api_type}, 400),+ ({"api_type": api_type, "reasoning_config": config(enabled = False)}, 200),+ ({"reasoning_config": config()}, 400),+ ({"reasoning_config": None}, 200),+ ]:+ response = h.api("PUT", f"/{provider_id}", status, **update)+ assert response["api_type"] == api_type+ for extra, status in [({"reasoning_config": BAD[3]}, 422), ({"provider_type": "ollama"}, 400)]:+ h.api("POST", status = status, **{**payload, **extra})++[email protected]("encrypted", [False, True])+def test_saved_authority_and_connection_isolation(harness, monkeypatch, encrypted):+ if encrypted:+ private = rsa.generate_private_key(public_exponent = 65537, key_size = 2048)+ monkeypatch.setattr(key_exchange, "_private_key", private)+ oaep = padding.OAEP(+ mgf = padding.MGF1(hashes.SHA256()), algorithm = hashes.SHA256(), label = None+ )+ cipher = base64.b64encode(private.public_key().encrypt(b"browser-test-key", oaep)).decode()+ for provider_id, value in [+ ("enabled", config("thinking")),+ ("disabled", config(enabled = False)),+ ("legacy", None),+ ("enabled-again", config("thinking")),+ ]:+ providers_db.create_provider(+ provider_id, "custom", provider_id, harness.url, reasoning_config = value+ )+ credential_secrets.save_provider_api_key(provider_id, "local-test-key")+ fields = dict(+ provider_id = provider_id,+ provider_type = "openai",+ provider_api_type = "responses",+ provider_base_url = "https://unrelated.invalid/v1",+ reasoning_effort = "high",+ enable_thinking = True,+ )+ if encrypted:+ fields["encrypted_api_key"] = cipher+ body = harness.send("route", config(), **fields)+ assert reasoning(body) == (expected("thinking") if value and value["enabled"] else {})+ assert harness.recorded[-1]["auth"] == (+ "Bearer browser-test-key" if encrypted else "Bearer local-test-key"+ )+++def test_saved_config_race_refused(harness, monkeypatch):+ rows = iter([config(), config("thinking")])+ row = dict(PROVIDER, base_url = harness.url, api_type = "chat_completions", is_enabled = True)+ monkeypatch.setattr(+ providers_db, "get_provider", lambda _: dict(row, reasoning_config = next(rows))+ )+ with pytest.raises(HTTPException) as exc:+ harness.send("route", provider_id = "saved")+ assert exc.value.status_code == 409+ assert harness.recorded == []+++def test_responses_legacy_semantics(harness):+ bodies = [+ harness.send(cfg = value, api_type = "responses", reasoning_effort = "high")+ for value in (None, config("thinking", False))+ ]+ assert bodies[0] == bodies[1]+ assert bodies[0]["reasoning"] == {"effort": "high", "summary": "auto"}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex edc24b66bed..e80dc7fce6c 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -5974,6 +5974,7 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({// Lets the resolver detect custom Gemini OAI-compat gateways.baseUrl: selectedExternalProvider?.baseUrl ?? null,apiType: selectedExternalProvider?.apiType,+ reasoningConfig: selectedExternalProvider?.reasoningConfig,},): null;diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex da2587e83ac..71f5cb82a52 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -184,6 +184,7 @@ import {} from "../tool-call-id";import { buildResearchInferenceRequest } from "../research-inference-request";+import { customReasoningRequestFields } from "../custom-reasoning";import { pickFriendlyContainerName } from "../lib/friendly-names";import {buildExternalRoutingFields,@@ -5994,6 +5995,7 @@ export function createOpenAIStreamAdapter(isReasoningProvider: externalProvider.isReasoningModel === true,baseUrl: externalProvider.baseUrl ?? null,apiType: externalProvider.apiType,+ reasoningConfig: externalProvider.reasoningConfig,},): {@@ -6027,19 +6029,26 @@ export function createOpenAIStreamAdapter(reasoningEffortLevels,);const externalReasoningFields: ReasoningRequestFields =- externalReasoningCaps.supportsReasoning- ? externalReasoningCaps.reasoningStyle === "reasoning_effort"- ? externalReasoningEnabled- ? { reasoning_effort: selectedExternalEffort }- : externalReasoningCaps.supportsReasoningOff- ? { reasoning_effort: "none" }- : { reasoning_effort: fallbackExternalEffort }- : {- thinking: {- type: externalReasoningEnabled ? "enabled" : "disabled",- },- }- : {};+ externalProvider?.providerType === "custom" &&+ externalProvider.apiType !== "responses"+ ? customReasoningRequestFields(+ externalProvider.reasoningConfig,+ externalReasoningEnabled,+ selectedExternalEffort,+ )+ : externalReasoningCaps.supportsReasoning+ ? externalReasoningCaps.reasoningStyle === "reasoning_effort"+ ? externalReasoningEnabled+ ? { reasoning_effort: selectedExternalEffort }+ : externalReasoningCaps.supportsReasoningOff+ ? { reasoning_effort: "none" }+ : { reasoning_effort: fallbackExternalEffort }+ : {+ thinking: {+ type: externalReasoningEnabled ? "enabled" : "disabled",+ },+ }+ : {};const localReasoningFields: ReasoningRequestFields = supportsReasoning? reasoningStyle === "enable_thinking_effort"? // GLM-5.2-style gate plus level, e.g. high|max.diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.tsindex 2fd72655bd7..d5f03bb5954 100644--- a/studio/frontend/src/features/chat/api/providers-api.ts+++ b/studio/frontend/src/features/chat/api/providers-api.ts@@ -5,6 +5,7 @@ import forge from "node-forge";import { authFetch } from "@/features/auth/api";import { formatFastApiDetail } from "@/lib/format-fastapi-error";import type { ModelCatalogSnapshotEntry } from "../model-catalog-snapshot";+import type { CustomReasoningConfig } from "../custom-reasoning";export type ProviderAuthKind = "api_key" | "chatgpt_oauth";@@ -53,6 +54,7 @@ export interface ProviderConfig {models?: string[];available_models?: string[];max_output_tokens?: number | null;+ reasoning_config?: CustomReasoningConfig | null;created_at: string;updated_at: string;}@@ -214,6 +216,7 @@ export async function createProviderConfig(payload: {models?: string[];availableModels?: string[];maxOutputTokens?: number | null;+ reasoningConfig?: CustomReasoningConfig | null;apiKey?: string;}): Promise<ProviderConfig> {return withApiKeyEncryptionRetry(payload.apiKey ?? "", async (encryptedApiKey) => {@@ -230,6 +233,9 @@ export async function createProviderConfig(payload: {...(payload.maxOutputTokens === undefined? {}: { max_output_tokens: payload.maxOutputTokens }),+ ...(payload.reasoningConfig === undefined+ ? {}+ : { reasoning_config: payload.reasoningConfig }),encrypted_api_key: encryptedApiKey,}),});@@ -262,6 +268,7 @@ export async function updateProviderConfig(models?: string[];availableModels?: string[];maxOutputTokens?: number | null;+ reasoningConfig?: CustomReasoningConfig | null;apiKey?: string;clearApiKey?: boolean;},@@ -282,6 +289,9 @@ export async function updateProviderConfig(...(payload.maxOutputTokens === undefined? {}: { max_output_tokens: payload.maxOutputTokens }),+ ...(payload.reasoningConfig === undefined+ ? {}+ : { reasoning_config: payload.reasoningConfig }),...(payload.apiKey === undefined ? {} : { encrypted_api_key: encryptedApiKey }),...(payload.clearApiKey === undefined ? {} : { clear_api_key: payload.clearApiKey }),}),diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex f96b2231da6..a608fef2b73 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -2961,6 +2961,7 @@ export function ChatPage({isReasoningProvider: provider?.isReasoningModel === true,baseUrl: provider?.baseUrl ?? null,apiType: provider?.apiType,+ reasoningConfig: provider?.reasoningConfig,},);const state = useChatRuntimeStore.getState();@@ -3114,6 +3115,7 @@ export function ChatPage({isReasoningProvider: provider?.isReasoningModel === true,baseUrl: provider?.baseUrl ?? null,apiType: provider?.apiType,+ reasoningConfig: provider?.reasoningConfig,},);reconcilePinnedReasoningEffort({@@ -3146,6 +3148,7 @@ export function ChatPage({isReasoningProvider: provider?.isReasoningModel === true,baseUrl: provider?.baseUrl ?? null,apiType: provider?.apiType,+ reasoningConfig: provider?.reasoningConfig,},);useChatRuntimeStore.setState(@@ -3705,6 +3708,7 @@ export function ChatPage({isReasoningProvider: selectedProvider?.isReasoningModel === true,baseUrl: selectedProvider?.baseUrl ?? null,apiType: selectedProvider?.apiType,+ reasoningConfig: selectedProvider?.reasoningConfig,},);const effortLevels = reasoningCaps.reasoningEffortLevels;diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsxindex a8213c83613..4e27f9fee61 100644--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx@@ -58,6 +58,10 @@ import {updateProviderConfig,} from "./api/providers-api";+import {+ type CustomReasoningConfig,+ normalizeCustomReasoningConfig,+} from "./custom-reasoning";import { resolveProviderCredentialEdit } from "./provider-credential-edit";import { getExternalMinOutputTokens } from "./provider-capabilities";import type { ExternalProviderConfig } from "./external-providers";@@ -294,6 +298,7 @@ export function ChatProvidersSettings({CUSTOM_PROVIDER_DISPLAY_NAME,);const [isReasoningModel, setIsReasoningModel] = useState(false);+ const [reasoningConfig, setReasoningConfig] = useState<CustomReasoningConfig | null>(null);const [autoReloadModels, setAutoReloadModels] = useState(false);const modelFieldsAtOpenRef = useRef<string | null>(null);const reduceMotion = useReducedMotion();@@ -316,6 +321,12 @@ export function ChatProvidersSettings({// llama.cpp hides the key field. Ollama and vLLM show an optional key: Ollama cloud and// secured vLLM need one; local servers leave it empty.const showReasoningToggle = supportsProviderReasoningToggle(providerType);+ // Legacy OpenAI rows also appear as Custom in the UI, but must not gain this opt-in.+ const isCustomReasoningConnection =+ providerType === LEGACY_CUSTOM_PROVIDER_TYPE &&+ (!editingProviderId || editingBackendProviderType === "custom");+ const showCustomReasoning =+ isCustomReasoningConnection && apiType === "chat_completions";// Unsloth runs Search, Code, MCP and RAG on this machine for any provider advertising the// capability, with no extra opt-in. Say so where the connection is created: tool results// also travel back to the provider as the next turn's input.@@ -422,6 +433,7 @@ export function ChatProvidersSettings({seededProviderTypeRef.current = providerType;setMaxOutputTokensDraft("");setApiType("chat_completions");+ setReasoningConfig(null);setEditingBackendProviderType(null);const entry = registryByType.get(providerType);if (!entry) {@@ -547,6 +559,7 @@ export function ChatProvidersSettings({setBaseUrlDraft("");setMaxOutputTokensDraft("");setApiType("chat_completions");+ setReasoningConfig(null);setEditingBackendProviderType(null);setAvailableModels([]);setSelectedModelIds([]);@@ -909,6 +922,9 @@ export function ChatProvidersSettings({? []: pruneProviderModelIds(providerType, availableModels),maxOutputTokens,+ reasoningConfig: isCustomReasoningConnection+ ? (showCustomReasoning ? reasoningConfig : null)+ : undefined,apiKey: apiKey.trim(),});@@ -934,6 +950,9 @@ export function ChatProvidersSettings({? []: pruneProviderModelIds(providerType, availableModels),maxOutputTokens: created.max_output_tokens ?? undefined,+ reasoningConfig: created.provider_type === "custom"+ ? normalizeCustomReasoningConfig(created.reasoning_config)+ : undefined,hasApiKey: created.has_api_key,@@ -1081,6 +1100,9 @@ export function ChatProvidersSettings({models: keepSavedModels ? undefined : modelsToSave,availableModels: keepSavedModels ? undefined : availableModelsToSave,maxOutputTokens,+ reasoningConfig: isCustomReasoningConnection+ ? (showCustomReasoning ? reasoningConfig : null)+ : undefined,...(credentialEdit.action === "replace"? { apiKey: credentialEdit.apiKey }: credentialEdit.action === "clear"@@ -1110,6 +1132,9 @@ export function ChatProvidersSettings({? (updated.available_models?.length ? updated.available_models : existing.availableModels): availableModelsToSave,maxOutputTokens: updated.max_output_tokens ?? undefined,+ reasoningConfig: updated.provider_type === "custom"+ ? normalizeCustomReasoningConfig(updated.reasoning_config)+ : undefined,hasApiKey: updated.has_api_key,autoReloadModels:@@ -1223,6 +1248,14 @@ export function ChatProvidersSettings({setApiType(provider.decisionsOnly ? "systemone" : (provider.apiType ?? "chat_completions"),);+ setReasoningConfig(+ provider.providerType === LEGACY_CUSTOM_PROVIDER_TYPE &&+ provider.backendProviderType === "custom" &&+ !provider.decisionsOnly &&+ (provider.apiType ?? "chat_completions") === "chat_completions"+ ? (normalizeCustomReasoningConfig(provider.reasoningConfig) ?? null)+ : null,+ );// Seeded at the floor: parseMaxOutputTokens throws below it, so a row stored under one would// fail every unrelated edit. The resolver already reads it as the floor.setMaxOutputTokensDraft(@@ -1460,6 +1493,7 @@ export function ChatProvidersSettings({onValueChange={(value) => {if (editingProviderId) return;setProviderType(value);+ setReasoningConfig(null);setAvailableModels([]);setSelectedModelIds([]);setManualModelIds("");@@ -1633,7 +1667,10 @@ export function ChatProvidersSettings({</div><Selectvalue={apiType}- onValueChange={(value) => setApiType(value as ConnectionApiType)}+ onValueChange={(value) => {+ setApiType(value as ConnectionApiType);+ if (value !== "chat_completions") setReasoningConfig(null);+ }}><SelectTrigger id="provider-api-type" className="h-9 w-full text-sm"><SelectValue />@@ -1753,6 +1790,72 @@ export function ChatProvidersSettings({/></div>) : null}+ {showCustomReasoning ? (+ <>+ <div className="grid grid-cols-[minmax(140px,0.8fr)_minmax(0,1.2fr)] items-start gap-4 px-4 py-3 @max-[520px]:grid-cols-1">+ <div className="flex min-w-0 flex-col gap-0.5">+ <Label htmlFor="provider-reasoning-support" className="text-sm font-medium">+ Reasoning support+ </Label>+ <p id="provider-reasoning-support-help" className="text-xs leading-snug text-muted-foreground">+ Opt in only if this endpoint accepts reasoning controls. Otherwise no reasoning fields are sent.+ </p>+ </div>+ <label htmlFor="provider-reasoning-support" className="flex cursor-pointer items-center gap-2 text-sm">+ <Checkbox+ id="provider-reasoning-support"+ checked={reasoningConfig?.enabled === true}+ aria-describedby="provider-reasoning-support-help"+ onCheckedChange={(checked) => setReasoningConfig({+ enabled: checked === true,+ style: reasoningConfig?.style ?? "reasoning_effort",+ })}+ />+ Enable reasoning controls+ </label>+ </div>+ {reasoningConfig?.enabled ? (+ <div className="grid grid-cols-[minmax(140px,0.8fr)_minmax(0,1.2fr)] items-start gap-4 px-4 py-3 @max-[520px]:grid-cols-1">+ <div className="flex min-w-0 flex-col gap-0.5">+ <Label htmlFor="provider-reasoning-style" className="text-sm font-medium">+ Reasoning parameter style+ </Label>+ <p className="text-xs leading-snug text-muted-foreground">+ Choose the request format your endpoint supports.+ </p>+ </div>+ <div className="flex min-w-0 flex-col gap-1.5">+ <Select+ value={reasoningConfig.style}+ onValueChange={(style) => setReasoningConfig({+ enabled: true,+ style: style as CustomReasoningConfig["style"],+ })}+ >+ <SelectTrigger id="provider-reasoning-style" className="h-9 w-full text-sm" aria-describedby="provider-reasoning-style-help">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="reasoning_effort">reasoning_effort</SelectItem>+ <SelectItem value="reasoning">reasoning (enabled / effort)</SelectItem>+ <SelectItem value="thinking">thinking (enabled / disabled)</SelectItem>+ <SelectItem value="chat_template_kwargs.enable_thinking">chat_template_kwargs.enable_thinking</SelectItem>+ </SelectContent>+ </Select>+ <p id="provider-reasoning-style-help" className="text-xs leading-snug text-muted-foreground">+ {reasoningConfig.style === "reasoning_effort"+ ? 'Thinking off sends reasoning_effort: "none".'+ : reasoningConfig.style === "reasoning"+ ? "Thinking off sends reasoning: { enabled: false }."+ : reasoningConfig.style === "thinking"+ ? 'Thinking off sends thinking: { type: "disabled" }.'+ : "Thinking off sends chat_template_kwargs: { enable_thinking: false }."}+ </p>+ </div>+ </div>+ ) : null}+ </>+ ) : null}{showReasoningToggle ? (<div className="grid grid-cols-[minmax(140px,0.8fr)_minmax(0,1.2fr)] items-center gap-4 px-4 py-3 @max-[520px]:grid-cols-1"><Labeldiff --git a/studio/frontend/src/features/chat/custom-reasoning.ts b/studio/frontend/src/features/chat/custom-reasoning.tsnew file mode 100644index 00000000000..fc19480455e--- /dev/null+++ b/studio/frontend/src/features/chat/custom-reasoning.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Explicit connection contract, never inferred from a URL or a model name. */+export const CUSTOM_REASONING_STYLES = [+ "reasoning_effort",+ "reasoning",+ "thinking",+ "chat_template_kwargs.enable_thinking",+] as const;++export type CustomReasoningStyle = (typeof CUSTOM_REASONING_STYLES)[number];+export type CustomReasoningConfig = {+ enabled: boolean;+ style: CustomReasoningStyle;+};++/** Cached or legacy malformed contracts fail closed. */+export function normalizeCustomReasoningConfig(+ value: unknown,+): CustomReasoningConfig | undefined {+ if (!value || typeof value !== "object" || Array.isArray(value))+ return undefined;+ const config = value as Record<string, unknown>;+ if (+ Object.keys(config).some((key) => key !== "enabled" && key !== "style") ||+ typeof config.enabled !== "boolean" ||+ !CUSTOM_REASONING_STYLES.includes(config.style as CustomReasoningStyle)+ ) {+ return undefined;+ }+ return {+ enabled: config.enabled,+ style: config.style as CustomReasoningStyle,+ };+}++/** Studio's generic controls; the backend alone translates them to the selected wire style. */+export function customReasoningRequestFields(+ value: unknown,+ enabled: boolean,+ effort: string,+): {+ reasoning_effort?: "none" | "low" | "medium" | "high";+ thinking?: { type: "enabled" | "disabled" };+} {+ const config = normalizeCustomReasoningConfig(value);+ if (!config?.enabled) return {};+ if (config.style === "reasoning_effort" || config.style === "reasoning") {+ const level = effort === "low" || effort === "high" ? effort : "medium";+ return { reasoning_effort: !enabled || effort === "none" ? "none" : level };+ }+ return { thinking: { type: enabled ? "enabled" : "disabled" } };+}diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.tsindex 2f58e0a025e..2018a3ca773 100644--- a/studio/frontend/src/features/chat/external-providers.ts+++ b/studio/frontend/src/features/chat/external-providers.ts@@ -8,6 +8,10 @@ import type {ProviderAuthStatus,} from "./api/providers-api";import { modelCatalogSupportsVision } from "./model-catalog.ts";+import {+ type CustomReasoningConfig,+ normalizeCustomReasoningConfig,+} from "./custom-reasoning.ts";export interface ExternalProviderConfig {id: string;@@ -18,6 +22,7 @@ export interface ExternalProviderConfig {/** Provider base URL (default from registry or backend-saved override). */baseUrl: string;apiType?: ProviderApiType;+ reasoningConfig?: CustomReasoningConfig;decisionsOnly?: boolean;/** Model ids user enabled from `/api/providers/models`. */models: string[];@@ -613,6 +618,12 @@ function normalizeProvider(raw: ExternalProviderConfig): ExternalProviderConfigname: raw.name.trim(),baseUrl: raw.baseUrl.trim(),apiType: raw.apiType === "responses" ? "responses" : "chat_completions",+ reasoningConfig:+ providerType === "custom" &&+ (raw.backendProviderType === undefined || raw.backendProviderType === "custom") &&+ raw.apiType !== "responses" && raw.decisionsOnly !== true+ ? normalizeCustomReasoningConfig(raw.reasoningConfig)+ : undefined,models: raw.models.map((model) => model.trim()).filter((model) => model.length > 0),diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.tsindex d5f7f3fd7c5..f891e3fdc79 100644--- a/studio/frontend/src/features/chat/provider-capabilities.ts+++ b/studio/frontend/src/features/chat/provider-capabilities.ts@@ -15,6 +15,8 @@ import {sortReasoningEfforts,} from "./model-catalog";+import { normalizeCustomReasoningConfig } from "./custom-reasoning";+export { modelCatalogVersion, subscribeModelCatalog } from "./model-catalog";/** Per-provider sampling capability matrix from each provider's chat docs (2026-05).@@ -1159,6 +1161,7 @@ export interface ExternalReasoningResolveOptions {baseUrl?: string | null;/** Custom providers can opt into OpenAI's Responses API and its reasoning controls. */apiType?: "chat_completions" | "responses";+ reasoningConfig?: unknown;}export function effectiveExternalReasoningProviderType(@@ -1299,6 +1302,29 @@ export function getExternalReasoningCapabilities(modelId: string | null | undefined,options?: ExternalReasoningResolveOptions,): ExternalReasoningCapabilities {+ // Check the connection before the catalog: known models must not opt Custom in.+ if (+ providerType?.trim().toLowerCase() === "custom" &&+ options?.apiType !== "responses"+ ) {+ const config = normalizeCustomReasoningConfig(options?.reasoningConfig);+ if (!config?.enabled) {+ return isOpenRouterMandatoryReasoningModel(modelId ?? "")+ ? withEnableThinkingStyle({+ supportsReasoning: true,+ reasoningAlwaysOn: true,+ supportsReasoningOff: false,+ })+ : withEnableThinkingStyle();+ }+ return config.style === "reasoning_effort" || config.style === "reasoning"+ ? withReasoningEffortStyle({+ supportsReasoning: true,+ supportsReasoningOff: true,+ reasoningEffortLevels: ["none", "low", "medium", "high"],+ })+ : withEnableThinkingStyle({ supportsReasoning: true, supportsReasoningOff: true });+ }// The capability map is keyed by the catalog's id, so look it up before case-folding.const catalogModel = modelId?.trim() ?? "";const normalizedModel = catalogModel.toLowerCase();diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 5b0596cbb17..2b86398e3ba 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -864,6 +864,7 @@ export function SharedComposer({selectedExternalProvider?.isReasoningModel === true,baseUrl: selectedExternalProvider?.baseUrl ?? null,apiType: selectedExternalProvider?.apiType,+ reasoningConfig: selectedExternalProvider?.reasoningConfig,},): null;diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.tsindex 90279677a58..75110db2cd5 100644--- a/studio/frontend/src/features/chat/sync-external-providers.ts+++ b/studio/frontend/src/features/chat/sync-external-providers.ts@@ -15,6 +15,7 @@ import {migrateProviderApiKey,updateProviderConfig,} from "./api/providers-api";+import { normalizeCustomReasoningConfig } from "./custom-reasoning";import {modelsDevCatalogFetchedAt,providerModelCatalogFetchedAt,@@ -318,6 +319,11 @@ export async function syncExternalProvidersFromBackend(models: resolvedModels,availableModels: resolvedAvailableModels,maxOutputTokens: config.max_output_tokens ?? undefined,+ reasoningConfig:+ config.provider_type === "custom" &&+ config.api_type !== "responses" && config.api_type !== "systemone"+ ? normalizeCustomReasoningConfig(config.reasoning_config)+ : undefined,hasApiKey: config.has_api_key,diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 40905fcc9f7..1984ec21f4c 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import type { TransformersUpgradeInfo } from "@/features/transformers-upgrade";+import type { CustomReasoningConfig } from "../custom-reasoning";export type CpuFallbackReason = "vulkan_startup_crash";@@ -735,6 +736,7 @@ export interface OpenAIChatCompletionsRequest {encrypted_api_key?: string;provider_base_url?: string | null;provider_api_type?: "chat_completions" | "responses";+ provider_reasoning_config?: CustomReasoningConfig;/** Boolean toggle for OpenAI/Anthropic ephemeral cache_control. For Gemini the backend also accepts* a cached-content resource name, forwarded as `generationConfig.cachedContent`. */enable_prompt_caching?: boolean | string | null;diff --git a/studio/frontend/src/features/chat/utils/chat-title.ts b/studio/frontend/src/features/chat/utils/chat-title.tsindex da167e65ffe..c6747e9b59d 100644--- a/studio/frontend/src/features/chat/utils/chat-title.ts+++ b/studio/frontend/src/features/chat/utils/chat-title.ts@@ -6,6 +6,10 @@ import {parseExternalModelId,} from "../external-providers";import { encryptProviderApiKey } from "../api/providers-api";+import {+ type CustomReasoningConfig,+ normalizeCustomReasoningConfig,+} from "../custom-reasoning";import {type ExternalProviderConfig,getExternalProviderApiKey,@@ -211,6 +215,7 @@ export interface ExternalRoutingFields {external_model: string;provider_base_url: string | null;provider_api_type: "chat_completions" | "responses";+ provider_reasoning_config?: CustomReasoningConfig;encrypted_api_key?: string;}@@ -269,12 +274,19 @@ export async function buildExternalRoutingFields(options: { forceRefreshPublicKey?: boolean } = {},): Promise<ExternalRoutingFields> {const { provider, modelId, apiKey } = connection;+ const reasoningConfig =+ provider.providerType === "custom" &&+ (provider.backendProviderType === undefined || provider.backendProviderType === "custom") &&+ provider.apiType !== "responses" && !provider.decisionsOnly+ ? normalizeCustomReasoningConfig(provider.reasoningConfig)+ : undefined;return {provider_id: provider.id,provider_type: toExternalBackendProviderType(provider.providerType),external_model: modelId,provider_base_url: provider.baseUrl || null,provider_api_type: provider.apiType ?? "chat_completions",+ ...(reasoningConfig?.enabled ? { provider_reasoning_config: reasoningConfig } : {}),...(apiKey? {encrypted_api_key: await encryptProviderApiKey(@@ -336,6 +348,7 @@ function titleReasoningCaps(connection: ResolvedExternalConnection) {isReasoningProvider: provider.isReasoningModel === true,baseUrl: provider.baseUrl ?? null,apiType: provider.apiType,+ reasoningConfig: provider.reasoningConfig,});}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/connected-model-info-dialog.tsx b/studio/frontend/src/features/model-picker/components/model-selector/connected-model-info-dialog.tsxindex e4b1e53f54d..73bd6d79d86 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/connected-model-info-dialog.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/connected-model-info-dialog.tsx@@ -19,6 +19,8 @@ import {} from "@/components/ui/dialog";import { modelCatalogVersion, subscribeModelCatalog } from "@/features/chat";import type { ProviderApiType } from "@/features/chat/api/providers-api";+// eslint-disable-next-line no-restricted-imports -- Connection contract has no React dependencies.+import type { CustomReasoningConfig } from "@/features/chat/custom-reasoning";// eslint-disable-next-line no-restricted-imports -- Avoid the chat barrel's React exports.import { resolveModelCatalogEntry } from "@/features/chat/model-catalog";// eslint-disable-next-line no-restricted-imports -- Avoid the chat barrel's React exports.@@ -67,6 +69,7 @@ export function ConnectedModelInfoDialog({apiType,baseUrl,isReasoningProvider,+ reasoningConfig,}: {open: boolean;onOpenChange: (open: boolean) => void;@@ -79,6 +82,7 @@ export function ConnectedModelInfoDialog({baseUrl?: string | null;/** A vLLM connection flagged as serving a reasoning model: the only signal a self-host gives. */isReasoningProvider?: boolean;+ reasoningConfig?: CustomReasoningConfig;}) {// Every figure below is read from the catalogue, which can land after this renders.useSyncExternalStore(subscribeModelCatalog, modelCatalogVersion);@@ -92,6 +96,7 @@ export function ConnectedModelInfoDialog({// The resolver behind the composer's Thinking chip, not the catalogue alone.const reasoning = getExternalReasoningCapabilities(providerType, modelId, {isReasoningProvider,+ reasoningConfig,baseUrl,apiType,});diff --git a/studio/frontend/src/features/model-picker/components/model-selector/connected-model-settings-dialog.tsx b/studio/frontend/src/features/model-picker/components/model-selector/connected-model-settings-dialog.tsxindex c0f44dac353..1a15bff7433 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/connected-model-settings-dialog.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/connected-model-settings-dialog.tsx@@ -27,6 +27,8 @@ import {} from "@/components/ui/select";import { Textarea } from "@/components/ui/textarea";import type { ProviderApiType } from "@/features/chat/api/providers-api";+// eslint-disable-next-line no-restricted-imports -- Connection contract has no React dependencies.+import type { CustomReasoningConfig } from "@/features/chat/custom-reasoning";import {modelCatalogVersion,reconcilePinnedReasoningEffort,@@ -56,6 +58,7 @@ export function ConnectedModelSettingsDialog({apiType,baseUrl,isReasoningProvider,+ reasoningConfig,connectionMaxOutputTokens,}: {open: boolean;@@ -70,6 +73,7 @@ export function ConnectedModelSettingsDialog({baseUrl?: string | null;/** A vLLM connection flagged as serving a reasoning model. */isReasoningProvider?: boolean;+ reasoningConfig?: CustomReasoningConfig;/** The connection's own output cap, which lowers the model's documented one. */connectionMaxOutputTokens?: number | null;}) {@@ -100,6 +104,7 @@ export function ConnectedModelSettingsDialog({// levels offered here are the ones the provider actually accepts. "none" is the off switch.const reasoning = getExternalReasoningCapabilities(providerType, modelId, {isReasoningProvider,+ reasoningConfig,baseUrl,apiType,});diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 8c5c9db2296..1483ace6c28 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -52,6 +52,8 @@ import type {LocalModelInfo,} from "@/features/chat";import type { ProviderApiType } from "@/features/chat/api/providers-api";+// eslint-disable-next-line no-restricted-imports -- Connection contract has no React dependencies.+import type { CustomReasoningConfig } from "@/features/chat/custom-reasoning";import { normalizeGgufVisionCapability } from "@/features/chat/utils/model-vision-capability";import {DotTag,@@ -4847,6 +4849,18 @@ export function HubModelPicker({),[externalProviders],);+ const externalReasoningConfigById = useMemo(+ () =>+ new Map(+ externalProviders.map((provider) => [+ provider.id,+ provider.backendProviderType === "custom" && !provider.decisionsOnly+ ? provider.reasoningConfig+ : undefined,+ ]),+ ),+ [externalProviders],+ );// A provider catalogue arrives after first paint and decides most of the marks, so re-read it.const catalogVersion = useSyncExternalStore(subscribeModelCatalog,@@ -4876,6 +4890,7 @@ export function HubModelPicker({apiType?: ProviderApiType;baseUrl: string | null;isReasoningProvider: boolean;+ reasoningConfig?: CustomReasoningConfig;} | null>(null);const [settingsModel, setSettingsModel] = useState<{model: ExternalModelOption;@@ -4883,6 +4898,7 @@ export function HubModelPicker({apiType?: ProviderApiType;baseUrl: string | null;isReasoningProvider: boolean;+ reasoningConfig?: CustomReasoningConfig;connectionMaxOutputTokens: number | null;} | null>(null);@@ -6167,6 +6183,7 @@ export function HubModelPicker({baseUrl,isReasoningProvider:externalReasoningFlagById.get(model.providerId) === true,+ reasoningConfig: externalReasoningConfigById.get(model.providerId),connectionMaxOutputTokens:externalMaxOutputById.get(model.providerId) ?? null,})@@ -6199,6 +6216,7 @@ export function HubModelPicker({baseUrl,isReasoningProvider:externalReasoningFlagById.get(model.providerId) === true,+ reasoningConfig: externalReasoningConfigById.get(model.providerId),}),},{@@ -8496,6 +8514,7 @@ export function HubModelPicker({apiType={settingsModel.apiType}baseUrl={settingsModel.baseUrl}isReasoningProvider={settingsModel.isReasoningProvider}+ reasoningConfig={settingsModel.reasoningConfig}connectionMaxOutputTokens={settingsModel.connectionMaxOutputTokens}/>) : null}@@ -8512,6 +8531,7 @@ export function HubModelPicker({apiType={infoModel.apiType}baseUrl={infoModel.baseUrl}isReasoningProvider={infoModel.isReasoningProvider}+ reasoningConfig={infoModel.reasoningConfig}/>) : null}</CapabilityScope.Provider>diff --git a/studio/frontend/tests/connected-model-row-actions.test.ts b/studio/frontend/tests/connected-model-row-actions.test.tsindex 59733d1628c..8ce25475b8d 100644--- a/studio/frontend/tests/connected-model-row-actions.test.ts+++ b/studio/frontend/tests/connected-model-row-actions.test.ts@@ -729,7 +729,7 @@ test("reasoning is read through the resolver the composer uses", () => {for (const source of [infoDialog, settingsDialog]) {assert.match(source,- /getExternalReasoningCapabilities\(providerType, modelId, \{\s*isReasoningProvider,\s*baseUrl,\s*apiType,\s*\}\)/,+ /getExternalReasoningCapabilities\(providerType, modelId, \{\s*isReasoningProvider,\s*reasoningConfig,\s*baseUrl,\s*apiType,\s*\}\)/,);// "none" is the off switch, not a level on offer.assert.match(source, /\(level\) => level !== "none"/);diff --git a/studio/frontend/tests/custom-reasoning-capabilities.test.ts b/studio/frontend/tests/custom-reasoning-capabilities.test.tsnew file mode 100644index 00000000000..ebec2bf35b4--- /dev/null+++ b/studio/frontend/tests/custom-reasoning-capabilities.test.ts@@ -0,0 +1,53 @@+// 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 { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const { getExternalReasoningCapabilities } = await import(+ "../src/features/chat/provider-capabilities.ts"+);++for (const style of [+ "reasoning_effort",+ "reasoning",+ "thinking",+ "chat_template_kwargs.enable_thinking",+]) {+ test(`Custom explicitly opts into ${style}, independently of model or URL`, () => {+ // Structural options keep the red control failing on behavior, not imports.+ const options = { reasoningConfig: { enabled: true, style } };+ const caps = getExternalReasoningCapabilities(+ "custom",+ "unlisted-model",+ options,+ );+ assert.equal(caps.supportsReasoning, true);+ assert.equal(caps.supportsReasoningOff, true);+ assert.equal(+ caps.reasoningStyle,+ ["reasoning_effort", "reasoning"].includes(style)+ ? "reasoning_effort"+ : "enable_thinking",+ );+ if (caps.reasoningStyle === "reasoning_effort") {+ assert.deepEqual(+ [...caps.reasoningEffortLevels],+ ["none", "low", "medium", "high"],+ );+ }+ });+}++test("unconfigured Custom keeps mandatory-reasoning routes always on", () => {+ const caps = getExternalReasoningCapabilities("custom", "deepseek/deepseek-r1", {});+ assert.equal(caps.supportsReasoning, true);+ assert.equal(caps.reasoningAlwaysOn, true);+ assert.equal(caps.supportsReasoningOff, false);+ assert.equal(+ getExternalReasoningCapabilities("custom", "unlisted-model", {}).supportsReasoning,+ false,+ );+});diff --git a/studio/frontend/tests/custom-reasoning.test.ts b/studio/frontend/tests/custom-reasoning.test.tsnew file mode 100644index 00000000000..e61dc6d86d3--- /dev/null+++ b/studio/frontend/tests/custom-reasoning.test.ts@@ -0,0 +1,259 @@+// 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, { after } from "node:test";+import { createServer } from "vite";+import type { ExternalProviderConfig } from "../src/features/chat/external-providers.ts";+import { installLocalStorageFake } from "./helpers/kit.ts";++installLocalStorageFake();+Object.assign(window.location, { href: "http://localhost/" });+const vite = await createServer({ server: { middlewareMode: true } });+after(() => vite.close());+const caps = await vite.ssrLoadModule(+ "/src/features/chat/provider-capabilities.ts",+);+const providers = await vite.ssrLoadModule(+ "/src/features/chat/external-providers.ts",+);+const api = await vite.ssrLoadModule("/src/features/chat/api/providers-api.ts");+const sync = await vite.ssrLoadModule(+ "/src/features/chat/sync-external-providers.ts",+);+const routing = await vite.ssrLoadModule(+ "/src/features/chat/utils/chat-title.ts",+);+const reasoning = await vite.ssrLoadModule(+ "/src/features/chat/custom-reasoning.ts",+);++const styles = [+ "reasoning_effort",+ "reasoning",+ "thinking",+ "chat_template_kwargs.enable_thinking",+] as const;+const connection = {+ id: "custom-a",+ providerType: "custom",+ backendProviderType: "custom",+ name: "Gateway",+ baseUrl: "http://localhost:9000/v1",+ models: ["same-model"],+ createdAt: 1,+ updatedAt: 1,+};++for (const style of styles) {+ test(`${style}: opt-in capabilities, generic controls, API and cache round trip`, async () => {+ const config = { enabled: true, style };+ const resolved = caps.getExternalReasoningCapabilities(+ "custom",+ "same-model",+ { reasoningConfig: config },+ );+ const effort = style === "reasoning_effort" || style === "reasoning";+ assert.equal(resolved.supportsReasoning, true);+ assert.equal(resolved.supportsReasoningOff, true);+ assert.equal(resolved.reasoningAlwaysOn, false);+ assert.equal(+ resolved.reasoningStyle,+ effort ? "reasoning_effort" : "enable_thinking",+ );+ if (effort)+ assert.deepEqual(+ [...resolved.reasoningEffortLevels],+ ["none", "low", "medium", "high"],+ );+ for (const level of ["low", "medium", "high"]) {+ assert.deepEqual(+ reasoning.customReasoningRequestFields(config, true, level),+ effort+ ? { reasoning_effort: level }+ : { thinking: { type: "enabled" } },+ );+ }+ assert.deepEqual(+ reasoning.customReasoningRequestFields(config, false, "high"),+ effort+ ? { reasoning_effort: "none" }+ : { thinking: { type: "disabled" } },+ );+ if (effort)+ assert.deepEqual(+ reasoning.customReasoningRequestFields(config, true, "none"),+ { reasoning_effort: "none" },+ );++ const bodies: Record<string, unknown>[] = [];+ const original = globalThis.fetch;+ globalThis.fetch = (async (_url, init) => {+ bodies.push(JSON.parse(String(init?.body)));+ return Response.json({ reasoning_config: config });+ }) as typeof fetch;+ try {+ const created = await api.createProviderConfig({+ providerType: "custom",+ displayName: "Gateway",+ reasoningConfig: config,+ });+ assert.deepEqual(created.reasoning_config, config);+ await api.updateProviderConfig("custom-a", { reasoningConfig: config });+ await api.updateProviderConfig("custom-a", { reasoningConfig: null });+ await api.updateProviderConfig("custom-a", { displayName: "Renamed" });+ } finally {+ globalThis.fetch = original;+ }+ assert.deepEqual(+ bodies.slice(0, 2).map((body) => body.reasoning_config),+ [config, config],+ );+ assert.equal(bodies[2].reasoning_config, null);+ assert.equal("reasoning_config" in bodies[3], false);+ providers.saveExternalProviders([+ { ...connection, reasoningConfig: config },+ ]);+ const loaded = providers.loadExternalProviders()[0];+ assert.deepEqual(loaded.reasoningConfig, config);+ assert.deepEqual(+ (+ await routing.buildExternalRoutingFields({+ provider: loaded,+ modelId: "same-model",+ apiKey: "",+ })+ ).provider_reasoning_config,+ config,+ );+ });+}++test("legacy, disabled and malformed Custom contracts fail closed even for known model names/URLs", async () => {+ for (const config of [+ undefined,+ null,+ {},+ { enabled: false, style: "thinking" },+ { enabled: "true", style: "thinking" },+ { enabled: true, style: "unknown" },+ { enabled: true, style: "thinking", extra: 1 },+ [],+ "thinking",+ ]) {+ const resolved = caps.getExternalReasoningCapabilities(+ "custom",+ "openrouter/auto",+ {+ isReasoningProvider: true,+ baseUrl: "https://api.openai.com/v1",+ reasoningConfig: config,+ },+ );+ assert.equal(resolved.supportsReasoning, false);+ assert.deepEqual(+ reasoning.customReasoningRequestFields(config, true, "high"),+ {},+ );+ providers.saveExternalProviders([+ { ...connection, reasoningConfig: config },+ ]);+ const loaded = providers.loadExternalProviders()[0];+ const fields = await routing.buildExternalRoutingFields({+ provider: loaded,+ modelId: "same-model",+ apiKey: "",+ });+ assert.equal("provider_reasoning_config" in fields, false);+ }+ for (const overrides of [+ { backendProviderType: "openai" },+ { apiType: "responses" },+ { decisionsOnly: true },+ { providerType: "vllm" },+ ]) {+ providers.saveExternalProviders([+ {+ ...connection,+ ...overrides,+ reasoningConfig: { enabled: true, style: "thinking" },+ },+ ]);+ assert.equal(+ providers.loadExternalProviders()[0].reasoningConfig,+ undefined,+ );+ }+});++test("switching same-model connections never leaks the contract and server sync is authoritative", async () => {+ const a: ExternalProviderConfig = {+ ...connection,+ reasoningConfig: { enabled: true, style: "reasoning" },+ };+ const b: ExternalProviderConfig = { ...connection, id: "custom-b" };+ const c: ExternalProviderConfig = {+ ...connection,+ id: "custom-c",+ reasoningConfig: { enabled: true, style: "thinking" },+ };+ for (const provider of [a, b, c, b, a]) {+ const resolved = caps.getExternalReasoningCapabilities(+ provider.providerType,+ "same-model",+ { reasoningConfig: provider.reasoningConfig },+ );+ assert.equal(resolved.supportsReasoning, provider !== b);+ const fields = await routing.buildExternalRoutingFields({+ provider,+ modelId: "same-model",+ apiKey: "",+ });+ assert.equal(fields.provider_id, provider.id);+ assert.deepEqual(+ fields.provider_reasoning_config,+ provider.reasoningConfig,+ );+ }+ assert.equal(sync.mergeLocalProviderOptions(a, b).reasoningConfig, undefined);+ const original = globalThis.fetch;+ globalThis.fetch = (async (url) => {+ const path = String(url);+ if (path.includes("/registry")) return Response.json([]);+ if (path.endsWith("/api/providers/"))+ return Response.json([+ {+ id: "custom-a",+ provider_type: "custom",+ display_name: "Gateway",+ base_url: connection.baseUrl,+ is_enabled: true,+ models: ["same-model"],+ available_models: ["same-model"],+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ reasoning_config: null,+ },+ {+ id: "custom-c",+ provider_type: "custom",+ display_name: "Other",+ base_url: connection.baseUrl,+ is_enabled: true,+ models: ["same-model"],+ available_models: ["same-model"],+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ reasoning_config: c.reasoningConfig,+ },+ ]);+ return Response.json({ fetched_at: 1, providers: {} });+ }) as typeof fetch;+ try {+ const synced = await sync.syncExternalProvidersFromBackend([a, c]);+ assert.equal(synced[0].reasoningConfig, undefined);+ assert.deepEqual(synced[1].reasoningConfig, c.reasoningConfig);+ } finally {+ globalThis.fetch = original;+ }+});diff --git a/studio/frontend/tests/external-thinking-wire.test.ts b/studio/frontend/tests/external-thinking-wire.test.tsindex f028e484730..b277d0d468a 100644--- a/studio/frontend/tests/external-thinking-wire.test.ts+++ b/studio/frontend/tests/external-thinking-wire.test.ts@@ -3,6 +3,7 @@import assert from "node:assert/strict";import test from "node:test";+import type { CustomReasoningConfig } from "../src/features/chat/custom-reasoning.ts";import { installLocalStorageFake, readSrc, registerBundlerResolver } from "./helpers/kit.ts";@@ -16,10 +17,17 @@ const { requestParsesThinkTags } = await import("../src/features/chat/utils/chat-generation-recovery.ts");+const { customReasoningRequestFields } = await import("../src/features/chat/custom-reasoning.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, effort = "high"): unknown {+function externalReasoningFields(+ caps: Caps,+ reasoningEnabled: boolean,+ effort = "high",+ externalProvider?: { providerType: string; reasoningConfig?: CustomReasoningConfig },+): unknown {const adapter = readSrc("features/chat/api/chat-adapter.ts");const enabledAt = adapter.indexOf("const externalReasoningEnabled =");const fieldsAt = adapter.indexOf("const externalReasoningFields", enabledAt);@@ -31,9 +39,11 @@ function externalReasoningFields(caps: Caps, reasoningEnabled: boolean, effort ="reasoningEnabled","selectedExternalEffort","fallbackExternalEffort",+ "externalProvider",+ "customReasoningRequestFields",`const externalReasoningEnabled = ${enabled};\nreturn ${fields};`,);- return build(caps, reasoningEnabled, effort, "high");+ return build(caps, reasoningEnabled, effort, "high", externalProvider, customReasoningRequestFields);}test("an always-on catalog model sends thinking on even when the chat stored it off", () => {@@ -64,6 +74,22 @@ test("a toggleable catalog model still sends the stored choice", () => {assert.deepEqual(externalReasoningFields(qwen, true), { thinking: { type: "enabled" } });});+test("the shipped adapter sends Custom controls only for the selected connection's opt-in", () => {+ for (const style of ["reasoning_effort", "reasoning", "thinking", "chat_template_kwargs.enable_thinking"] as const) {+ const reasoningConfig = { enabled: true, style };+ const custom = { providerType: "custom", reasoningConfig };+ const caps = getExternalReasoningCapabilities("custom", "same-model", { reasoningConfig });+ const effort = style === "reasoning_effort" || style === "reasoning";+ assert.deepEqual(externalReasoningFields(caps, true, "low", custom),+ effort ? { reasoning_effort: "low" } : { thinking: { type: "enabled" } });+ assert.deepEqual(externalReasoningFields(caps, false, "high", custom),+ effort ? { reasoning_effort: "none" } : { thinking: { type: "disabled" } });+ const disabled = { providerType: "custom", reasoningConfig: { ...reasoningConfig, enabled: false } };+ assert.deepEqual(externalReasoningFields(caps, true, "high", disabled), {});+ assert.deepEqual(externalReasoningFields(caps, true, "high", { providerType: "custom" }), {});+ }+});+test("an external effort of none reads as thinking off", () => {const gpt = getExternalReasoningCapabilities("openai", "gpt-5.1");assert.equal(gpt.reasoningStyle, "reasoning_effort");