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
Studio: allow max output overrides for custom providers (#8512)
omjha3125-ctrl5e184f50c6ad
diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.pyindex 506b3ada0ba..a1784910c13 100644--- a/studio/backend/models/providers.py+++ b/studio/backend/models/providers.py@@ -7,6 +7,8 @@ from typing import Literal, Optionalfrom pydantic import BaseModel, Field+MAX_JSON_SAFE_INTEGER = 9_007_199_254_740_991+# ── Registry (static provider info) ───────────────────────────────@@ -61,6 +63,13 @@ class ProviderCreate(BaseModel):default_factory = list,description = "Discovered catalog model IDs last fetched for this connection",)+ max_output_tokens: Optional[int] = Field(+ None,+ strict = True,+ ge = 64,+ le = MAX_JSON_SAFE_INTEGER,+ description = "Optional maximum Max Tokens cap for a generic Custom connection",+ )encrypted_api_key: Optional[str] = Field(None,@@ -79,6 +88,13 @@ class ProviderUpdate(BaseModel):None,description = "Discovered catalog model IDs last fetched for this connection",)+ max_output_tokens: Optional[int] = Field(+ None,+ strict = True,+ ge = 64,+ le = MAX_JSON_SAFE_INTEGER,+ description = "Optional maximum Max Tokens cap for a generic Custom connection",+ )encrypted_api_key: Optional[str] = Field(None,@@ -121,6 +137,10 @@ class ProviderResponse(BaseModel):default_factory = list,description = "Discovered catalog model IDs last fetched for this connection",)+ max_output_tokens: Optional[int] = Field(+ None,+ description = "Configured maximum Max Tokens cap for a generic Custom connection",+ )created_at: str = Field(..., description = "ISO 8601 creation timestamp")updated_at: str = Field(..., description = "ISO 8601 last-update timestamp")diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex 4cd293d6c01..5422b56f1e5 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -13,6 +13,8 @@ Endpoints:"""import uuid+from typing import Optional+import structlogfrom fastapi import APIRouter, Depends, HTTPException@@ -85,6 +87,7 @@ def _provider_response(row: dict) -> ProviderResponse:),models = row.get("models") or [],available_models = row.get("available_models") or [],+ max_output_tokens = row.get("max_output_tokens"),created_at = row["created_at"],updated_at = row["updated_at"],)@@ -109,6 +112,25 @@ def _validate_provider_auth_contract(raise HTTPException(status_code = 400, detail = "Choose only curated Codex models.")+def _validate_max_output_tokens_contract(+ provider_type: str,+ field_was_set: bool,+ value: Optional[int] = None,+) -> None:+ """Reject a non-null override on a provider type with its own documented caps.++ An explicit null is allowed through everywhere: the dialog shows the field for rows+ it displays as Custom but the backend stores as `openai`, and a blank field+ serialises as null, so rejecting it failed every unrelated edit of those rows.+ Clearing an override that cannot exist is a no-op.+ """+ if field_was_set and value is not None and provider_type != "custom":+ raise HTTPException(+ status_code = 400,+ detail = "Max Tokens limit can only be overridden for generic Custom providers.",+ )++# ── Public key for API key encryption ─────────────────────────────@@ -171,6 +193,12 @@ async def create_provider_config(f"Use GET /api/providers/registry to see available types.",)+ _validate_max_output_tokens_contract(+ payload.provider_type,+ "max_output_tokens" in payload.model_fields_set,+ payload.max_output_tokens,+ )+_validate_provider_auth_contract(info,encrypted_api_key = payload.encrypted_api_key,@@ -201,6 +229,7 @@ async def create_provider_config(base_url = base_url,models = payload.models,available_models = payload.available_models,+ max_output_tokens = payload.max_output_tokens,)try:if api_key:@@ -228,6 +257,12 @@ async def update_provider_config(raise HTTPException(status_code = 404, detail = "Provider not found")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(+ existing["provider_type"],+ max_output_tokens_requested,+ payload.max_output_tokens,+ )_validate_provider_auth_contract(existing_info,encrypted_api_key = payload.encrypted_api_key,@@ -243,7 +278,14 @@ async def update_provider_config(detail = "Cannot replace and clear an API key in the same request",)- metadata_fields = {"display_name", "base_url", "is_enabled", "models", "available_models"}+ metadata_fields = {+ "display_name",+ "base_url",+ "is_enabled",+ "models",+ "available_models",+ "max_output_tokens",+ }metadata_requested = bool(payload.model_fields_set & metadata_fields)# Only a *changed* base URL is validated. The dialog re-sends the stored value@@ -267,7 +309,7 @@ async def update_provider_config(with current_credential_write(credential):if metadata_requested:- providers_db.update_provider(+ metadata_updates = dict(id = provider_id,display_name = payload.display_name,base_url = base_url,@@ -275,6 +317,9 @@ async def update_provider_config(models = payload.models,available_models = payload.available_models,)+ if max_output_tokens_requested:+ metadata_updates["max_output_tokens"] = payload.max_output_tokens+ providers_db.update_provider(**metadata_updates)try:if replacement_api_key is not None:credential_secrets.save_provider_api_key(provider_id, replacement_api_key)@@ -290,6 +335,7 @@ async def update_provider_config(is_enabled = bool(existing["is_enabled"]),models = existing.get("models") or [],available_models = existing.get("available_models") or [],+ max_output_tokens = existing.get("max_output_tokens"),)except Exception:logger.exception(diff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.pyindex e6f40c5030c..a1cf506716d 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -11,6 +11,8 @@ Enabled model selections and discovered catalog IDs are stored server-side soremote Studio clients see the same connection state (#7281)."""+from __future__ import annotations+import jsonimport loggingimport sqlite3@@ -24,6 +26,7 @@ from utils.paths import studio_db_path, ensure_dir_schema_lock = threading.Lock()_schema_ready = False+_UNSET = object()def _encode_models_json(models: Optional[list[str]]) -> str:@@ -76,6 +79,8 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE llm_providers ADD COLUMN available_models_json TEXT NOT NULL DEFAULT '[]'")+ if "max_output_tokens" not in existing_cols:+ conn.execute("ALTER TABLE llm_providers ADD COLUMN max_output_tokens INTEGER")def get_connection() -> sqlite3.Connection:@@ -104,6 +109,7 @@ def create_provider(base_url: str,models: Optional[list[str]] = None,available_models: Optional[list[str]] = None,+ max_output_tokens: Optional[int] = None,) -> None:"""Insert a new provider configuration."""now = datetime.now(timezone.utc).isoformat()@@ -113,10 +119,10 @@ def create_provider("""INSERT INTO llm_providers (id, provider_type, display_name, base_url,- models_json, available_models_json,+ models_json, available_models_json, max_output_tokens,created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",(id,@@ -125,6 +131,7 @@ def create_provider(base_url,_encode_models_json(models),_encode_models_json(available_models),+ max_output_tokens,now,now,),@@ -141,6 +148,7 @@ def update_provider(is_enabled: Optional[bool] = None,models: Optional[list[str]] = None,available_models: Optional[list[str]] = None,+ max_output_tokens: int | None | object = _UNSET,) -> bool:"""Update fields on an existing provider. Returns True if a row was updated."""updates = []@@ -160,6 +168,9 @@ def update_provider(if available_models is not None:updates.append("available_models_json = ?")params.append(_encode_models_json(available_models))+ if max_output_tokens is not _UNSET:+ updates.append("max_output_tokens = ?")+ params.append(max_output_tokens)if not updates:return Falseupdates.append("updated_at = ?")diff --git a/studio/backend/tests/test_credential_routes.py b/studio/backend/tests/test_credential_routes.pyindex c8374794f30..b40f4273b22 100644--- a/studio/backend/tests/test_credential_routes.py+++ b/studio/backend/tests/test_credential_routes.py@@ -13,6 +13,7 @@ from pathlib import Pathimport pytestfrom fastapi import HTTPException+from pydantic import ValidationErrorfrom auth import storage as auth_storagefrom models.providers import (@@ -148,6 +149,166 @@ def test_provider_create_preserve_replace_clear_and_delete(monkeypatch):assert providers_db.get_provider(created.id) is None+def test_custom_max_output_tokens_create_update_and_clear():+ created = asyncio.run(+ providers_route.create_provider_config(+ ProviderCreate(+ provider_type = "custom",+ display_name = "Custom",+ base_url = "https://example.com/v1",+ models = ["vendor/model"],+ max_output_tokens = 131072,+ ),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert created.max_output_tokens == 131072+ assert providers_db.get_provider(created.id)["max_output_tokens"] == 131072++ updated = asyncio.run(+ providers_route.update_provider_config(+ created.id,+ ProviderUpdate(max_output_tokens = 65536),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert updated.max_output_tokens == 65536++ preserved = asyncio.run(+ providers_route.update_provider_config(+ created.id,+ ProviderUpdate(display_name = "Renamed Custom"),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert preserved.display_name == "Renamed Custom"+ assert preserved.max_output_tokens == 65536++ cleared = asyncio.run(+ providers_route.update_provider_config(+ created.id,+ ProviderUpdate(max_output_tokens = None),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert cleared.max_output_tokens is None++[email protected]("value", [1_048_577, 9_007_199_254_740_991])+def test_custom_max_output_tokens_accepts_safe_integer_values(value):+ payload = ProviderCreate(+ provider_type = "custom",+ display_name = "Custom",+ max_output_tokens = value,+ )+ assert payload.max_output_tokens == value+++ "value",+ [63, 4096.5, "4096", True, 9_007_199_254_740_992],+)+def test_custom_max_output_tokens_requires_a_safe_integer(value):+ with pytest.raises(ValidationError):+ ProviderCreate(+ provider_type = "custom",+ display_name = "Custom",+ max_output_tokens = value,+ )+++def test_known_and_custom_preset_providers_reject_a_non_null_max_output_override():+ for provider_type in ("openai", "vllm", "ollama", "llama_cpp"):+ with pytest.raises(HTTPException) as error:+ asyncio.run(+ providers_route.create_provider_config(+ ProviderCreate(+ provider_type = provider_type,+ display_name = provider_type,+ base_url = "https://example.com/v1",+ max_output_tokens = 65536,+ ),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert error.value.status_code == 400+++def test_known_and_custom_preset_providers_accept_an_explicit_null_max_output_override():+ """A blank Max Tokens limit field serialises as null, not as an omission.++ The dialog renders that field from the UI provider type, which resolves to+ "custom" for a connection STORED as `openai` once the user has renamed it or+ pointed it at another base URL. Rejecting the null as well as a real value meant+ every unrelated edit of such a connection -- a rename, a model change, a key+ rotation -- failed with an error about a field the user never touched. Clearing+ an override that cannot exist is a no-op, so the null is accepted everywhere and+ only a non-null value is refused.+ """+ for provider_type in ("openai", "vllm", "ollama", "llama_cpp"):+ created = asyncio.run(+ providers_route.create_provider_config(+ ProviderCreate(+ provider_type = provider_type,+ display_name = provider_type,+ base_url = "https://example.com/v1",+ max_output_tokens = None,+ ),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert created.max_output_tokens is None+ assert providers_db.get_provider(created.id)["max_output_tokens"] is None+++def test_known_provider_rejects_max_output_override_update():+ providers_db.create_provider(+ id = "openai-1",+ provider_type = "openai",+ display_name = "OpenAI",+ base_url = "https://api.openai.com/v1",+ )++ with pytest.raises(HTTPException) as error:+ asyncio.run(+ providers_route.update_provider_config(+ "openai-1",+ ProviderUpdate(max_output_tokens = 65536),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert error.value.status_code == 400+++def test_known_provider_accepts_a_null_max_output_override_update():+ """The counterpart on the update path: a blank field must not block a rename."""+ providers_db.create_provider(+ id = "openai-1",+ provider_type = "openai",+ display_name = "OpenAI",+ base_url = "https://api.openai.com/v1",+ )++ updated = asyncio.run(+ providers_route.update_provider_config(+ "openai-1",+ ProviderUpdate(display_name = "Renamed", max_output_tokens = None),+ credential = ("alice", None),+ via_api_key = False,+ )+ )+ assert updated.display_name == "Renamed"+ assert updated.max_output_tokens is None+ assert providers_db.get_provider("openai-1")["max_output_tokens"] is None++def test_provider_update_validates_before_writes_and_rolls_back_metadata(monkeypatch):providers_db.create_provider(id = "provider-1",diff --git a/studio/backend/tests/test_custom_max_output_tokens_contract.py b/studio/backend/tests/test_custom_max_output_tokens_contract.pynew file mode 100644index 00000000000..34b32e6ad24--- /dev/null+++ b/studio/backend/tests/test_custom_max_output_tokens_contract.py@@ -0,0 +1,396 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Upgrade, downgrade and contract tests for the per-connection ``max_output_tokens``.++Three things a happy-path test cannot reach:++* an existing studio.db, written before this column existed, opened by this code;+* the same database opened AGAIN by a build that has never heard of the column,+ which is what a user who reverts to the previous release does;+* the route contract, where an explicit null has to be accepted on every provider+ type. The dialog sends null for a blank field, and it renders that field from the+ UI provider type, which is "custom" for rows STORED as `openai` with a custom name+ or base URL -- so rejecting the null broke every unrelated edit of those rows.++No network, no GPU, no server: the routes are driven as plain coroutines and every+database is a per-test temporary file.+"""++from __future__ import annotations++import asyncio+import importlib.util+import sqlite3+import sys+import types+from pathlib import Path++import pytest+from fastapi import HTTPException++from auth import storage as auth_storage+from core.inference.providers import PROVIDER_REGISTRY+from models.providers import ProviderCreate, ProviderUpdate+from storage import credential_secrets, providers_db+++# routes/providers.py imports its siblings as ``routes.*``. Loading it by path under+# a private name is the pattern test_credential_routes.py already uses.+def _load_route_module(module_name: str, path: Path):+ spec = importlib.util.spec_from_file_location(module_name, path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[module_name] = module+ spec.loader.exec_module(module)+ return module+++_routes_dir = Path(__file__).resolve().parents[1] / "routes"+_previous_routes = sys.modules.get("routes")+_routes_package = types.ModuleType("routes")+_routes_package.__path__ = [str(_routes_dir)]+sys.modules["routes"] = _routes_package+try:+ _load_route_module("routes.provider_credentials", _routes_dir / "provider_credentials.py")+ providers_route = _load_route_module(+ "_max_output_contract_providers_route", _routes_dir / "providers.py"+ )+finally:+ sys.modules.pop("routes.provider_credentials", None)+ if _previous_routes is None:+ sys.modules.pop("routes", None)+ else:+ sys.modules["routes"] = _previous_routes+++CREDENTIAL = ("alice", None)++# Read from the registry rather than hardcoded, so a provider added later is covered+# without an edit here.+NON_CUSTOM_PROVIDER_TYPES = tuple(t for t in PROVIDER_REGISTRY if t != "custom")++# The schema as it stood before this column, including the two columns earlier+# releases added by ALTER. A database in this shape is what an upgrading user has.+_PRE_PR_TABLE_DDL = """+ CREATE TABLE llm_providers (+ id TEXT NOT NULL PRIMARY KEY,+ provider_type TEXT NOT NULL,+ display_name TEXT NOT NULL,+ base_url TEXT NOT NULL,+ is_enabled INTEGER NOT NULL DEFAULT 1,+ models_json TEXT NOT NULL DEFAULT '[]',+ available_models_json TEXT NOT NULL DEFAULT '[]',+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+ )+"""+++def isolated_providers_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """A per-test studio.db for direct ``providers_db`` calls."""+ db_path = tmp_path / "studio.db"+ monkeypatch.setattr(providers_db, "studio_db_path", lambda: db_path)+ monkeypatch.setattr(providers_db, "ensure_dir", lambda _path: None)+ providers_db._schema_ready = False+ yield db_path+ providers_db._schema_ready = False+++def provider_routes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """Isolate every database the provider routes touch. Yields the studio.db path."""+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_credential_encryption_key_cache", None)+ studio_db = tmp_path / "studio.db"+ monkeypatch.setattr(providers_db, "studio_db_path", lambda: studio_db)+ monkeypatch.setattr(credential_secrets, "studio_db_path", lambda: studio_db)+ monkeypatch.setattr(providers_db, "ensure_dir", lambda _path: None)+ monkeypatch.setattr(credential_secrets, "ensure_dir", lambda _path: None)+ monkeypatch.setattr(+ credential_secrets,+ "get_or_create_credential_encryption_key",+ auth_storage.get_or_create_credential_encryption_key,+ )+ providers_db._schema_ready = False+ credential_secrets._schema_ready = False+ yield studio_db+ providers_db._schema_ready = False+ credential_secrets._schema_ready = False+ auth_storage._credential_encryption_key_cache = None+++def _columns(db_path: Path) -> list[str]:+ conn = sqlite3.connect(str(db_path))+ try:+ return [row[1] for row in conn.execute("PRAGMA table_info(llm_providers)").fetchall()]+ finally:+ conn.close()+++def _raw_override(db_path: Path, provider_id: str):+ """Read the column straight out of SQLite, bypassing every layer under test."""+ conn = sqlite3.connect(str(db_path))+ try:+ row = conn.execute(+ "SELECT max_output_tokens FROM llm_providers WHERE id = ?", (provider_id,)+ ).fetchone()+ finally:+ conn.close()+ assert row is not None, f"no row for {provider_id!r}"+ return row[0]+++def _write_pre_pr_database(db_path: Path) -> None:+ """Build a studio.db in the pre-column shape and put two rows in it."""+ conn = sqlite3.connect(str(db_path))+ try:+ conn.execute(_PRE_PR_TABLE_DDL)+ for provider_id, provider_type, name in (+ ("old-custom", "custom", "Old Custom"),+ ("old-openai", "openai", "Old OpenAI"),+ ):+ conn.execute(+ "INSERT INTO llm_providers (id, provider_type, display_name, base_url, "+ "is_enabled, models_json, available_models_json, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?)",+ (+ provider_id,+ provider_type,+ name,+ "https://example.com/v1",+ '["vendor/model"]',+ '["vendor/model", "vendor/other"]',+ "2020-01-01T00:00:00+00:00",+ "2020-01-01T00:00:00+00:00",+ ),+ )+ conn.commit()+ finally:+ conn.close()+++# ── Upgrade ───────────────────────────────────────────────────────+++def test_a_pre_column_database_migrates_and_keeps_its_rows(isolated_providers_db: Path):+ """The upgrade case: an existing home opened by this build."""+ _write_pre_pr_database(isolated_providers_db)+ assert "max_output_tokens" not in _columns(isolated_providers_db)++ row = providers_db.get_provider("old-custom")+ assert row["max_output_tokens"] is None, "a pre-existing row must read as no override"+ assert row["models"] == ["vendor/model"]+ assert row["available_models"] == ["vendor/model", "vendor/other"]+ assert {p["id"] for p in providers_db.list_providers()} == {"old-custom", "old-openai"}++ # And the migrated row now accepts one.+ assert providers_db.update_provider(id = "old-custom", max_output_tokens = 262144)+ assert _raw_override(isolated_providers_db, "old-custom") == 262144+ assert _raw_override(isolated_providers_db, "old-openai") is None+++def test_the_migration_is_idempotent(isolated_providers_db: Path):+ """ALTER TABLE has no IF NOT EXISTS, so a second run must not raise."""+ _write_pre_pr_database(isolated_providers_db)+ for _ in range(3):+ providers_db._schema_ready = False+ assert providers_db.get_provider("old-custom")["max_output_tokens"] is None+ assert _columns(isolated_providers_db).count("max_output_tokens") == 1+++def test_a_missing_table_is_created_then_migrated(isolated_providers_db: Path):+ """A fresh home has no table at all: CREATE TABLE never lists the column, so the+ new install reaches it through the same ALTER an upgrade does."""+ assert providers_db.list_providers() == []+ assert "max_output_tokens" in _columns(isolated_providers_db)+++# ── Downgrade ─────────────────────────────────────────────────────+++def test_the_previous_release_still_reads_and_writes_a_migrated_database(+ isolated_providers_db: Path,+):+ """The revert case. The old code selects * and inserts without naming the column,+ so a migrated file must stay readable and writable by it."""+ providers_db.create_provider(+ id = "new-custom",+ provider_type = "custom",+ display_name = "New Custom",+ base_url = "https://example.com/v1",+ models = ["vendor/model"],+ max_output_tokens = 384000,+ )++ conn = sqlite3.connect(str(isolated_providers_db))+ conn.row_factory = sqlite3.Row+ try:+ # Exactly what the previous release's get_provider does.+ row = dict(+ conn.execute("SELECT * FROM llm_providers WHERE id = ?", ("new-custom",)).fetchone()+ )+ assert row["display_name"] == "New Custom"+ assert row["models_json"] == '["vendor/model"]'+ # An INSERT that never mentions the column, as the old code writes.+ conn.execute(+ "INSERT INTO llm_providers (id, provider_type, display_name, base_url, "+ "is_enabled, models_json, available_models_json, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, 1, '[]', '[]', ?, ?)",+ (+ "downgrade-written",+ "openai",+ "Written By Old Code",+ "https://api.openai.com/v1",+ "2020-01-01T00:00:00+00:00",+ "2020-01-01T00:00:00+00:00",+ ),+ )+ conn.commit()+ finally:+ conn.close()++ # Back on this build: the old row reads as no override, the new one kept its value.+ assert providers_db.get_provider("downgrade-written")["max_output_tokens"] is None+ assert providers_db.get_provider("new-custom")["max_output_tokens"] == 384000+++# ── Route contract ────────────────────────────────────────────────+++def _create(payload: ProviderCreate):+ return asyncio.run(+ providers_route.create_provider_config(payload, credential = CREDENTIAL, via_api_key = False)+ )+++def _update(provider_id: str, payload: ProviderUpdate):+ return asyncio.run(+ providers_route.update_provider_config(+ provider_id, payload, credential = CREDENTIAL, via_api_key = False+ )+ )++[email protected]("provider_type", NON_CUSTOM_PROVIDER_TYPES)+def test_a_non_custom_provider_accepts_an_explicit_null_override(+ provider_routes: Path, provider_type: str+):+ """The regression this fix targets.++ The dialog renders the Max Tokens limit row from the UI provider type, and+ `resolveUiProviderTypeFromConfig` reports "custom" for rows stored as `openai`+ with a custom name or base URL. A blank field serialises as null rather than as+ an omission, so rejecting the null made every unrelated edit of such a row -- a+ rename, a model change, a key rotation -- fail with an error about a field the+ user never touched. Clearing an override that cannot exist is a no-op.+ """+ providers_db.create_provider(+ id = f"{provider_type}-1",+ provider_type = provider_type,+ display_name = provider_type,+ base_url = "https://example.com/v1",+ )+ updated = _update(+ f"{provider_type}-1", ProviderUpdate(display_name = "Renamed", max_output_tokens = None)+ )+ assert updated.display_name == "Renamed"+ assert updated.max_output_tokens is None+ assert _raw_override(provider_routes, f"{provider_type}-1") is None++[email protected]("provider_type", NON_CUSTOM_PROVIDER_TYPES)+def test_a_non_custom_provider_still_rejects_a_real_override(+ provider_routes: Path, provider_type: str+):+ """The half of the contract that must NOT be relaxed: providers with documented+ caps of their own do not take a hand-written one."""+ providers_db.create_provider(+ id = f"{provider_type}-1",+ provider_type = provider_type,+ display_name = provider_type,+ base_url = "https://example.com/v1",+ )+ with pytest.raises(HTTPException) as error:+ _update(f"{provider_type}-1", ProviderUpdate(max_output_tokens = 65536))+ assert error.value.status_code == 400+ assert _raw_override(provider_routes, f"{provider_type}-1") is None+++def test_a_custom_connection_can_set_preserve_and_clear_its_override(provider_routes: Path):+ """The whole lifecycle, asserted against the stored row rather than the response."""+ created = _create(+ ProviderCreate(+ provider_type = "custom",+ display_name = "Custom",+ base_url = "https://example.com/v1",+ models = ["vendor/model"],+ max_output_tokens = 131072,+ )+ )+ assert _raw_override(provider_routes, created.id) == 131072++ assert _update(created.id, ProviderUpdate(max_output_tokens = 65536)).max_output_tokens == 65536++ # An unrelated edit must leave it alone: omitted is not the same as null.+ preserved = _update(created.id, ProviderUpdate(display_name = "Renamed Custom"))+ assert preserved.display_name == "Renamed Custom"+ assert _raw_override(provider_routes, created.id) == 65536++ assert _update(created.id, ProviderUpdate(max_output_tokens = None)).max_output_tokens is None+ assert _raw_override(provider_routes, created.id) is None+++def test_an_override_only_update_is_recognised_as_a_metadata_request(provider_routes: Path):+ """A request carrying nothing but the override must not be turned away as+ "No fields to update"."""+ created = _create(+ ProviderCreate(+ provider_type = "custom",+ display_name = "Custom",+ base_url = "https://example.com/v1",+ models = ["vendor/model"],+ )+ )+ assert _update(created.id, ProviderUpdate(max_output_tokens = 200000)).max_output_tokens == 200000+++def test_the_largest_accepted_value_round_trips_exactly(provider_routes: Path):+ """SQLite INTEGER is 8 bytes, so the top of the accepted range must come back+ identical rather than as a float."""+ value = 9007199254740991+ created = _create(+ ProviderCreate(+ provider_type = "custom",+ display_name = "Custom",+ base_url = "https://example.com/v1",+ models = ["vendor/model"],+ max_output_tokens = value,+ )+ )+ stored = _raw_override(provider_routes, created.id)+ assert stored == value and isinstance(stored, int)+++def test_a_failed_credential_write_restores_the_previous_override(+ provider_routes: Path, monkeypatch: pytest.MonkeyPatch+):+ """Metadata is written before the key, so the rollback has to carry the column."""+ created = _create(+ ProviderCreate(+ provider_type = "custom",+ display_name = "Custom",+ base_url = "https://example.com/v1",+ models = ["vendor/model"],+ max_output_tokens = 131072,+ )+ )++ def _boom(*_args, **_kwargs):+ raise RuntimeError("keyring is unavailable")++ monkeypatch.setattr(providers_route.credential_secrets, "save_provider_api_key", _boom)+ with pytest.raises(Exception):+ _update(created.id, ProviderUpdate(max_output_tokens = 262144, encrypted_api_key = "x"))+ assert _raw_override(provider_routes, created.id) == 131072diff --git a/studio/backend/tests/test_providers_db_models.py b/studio/backend/tests/test_providers_db_models.pyindex ca9dffbd703..2d99591c3ef 100644--- a/studio/backend/tests/test_providers_db_models.py+++ b/studio/backend/tests/test_providers_db_models.py@@ -5,6 +5,7 @@from __future__ import annotations+import sqlite3from pathlib import Pathimport pytest@@ -68,3 +69,44 @@ def test_update_provider_models(isolated_providers_db: Path):"meta-llama/Llama-3.2-1B-Instruct","meta-llama/Llama-3.2-3B-Instruct",]+++def test_custom_max_output_tokens_round_trip_and_clear(isolated_providers_db: Path):+ providers_db.create_provider(+ id = "custom1",+ provider_type = "custom",+ display_name = "Custom",+ base_url = "https://example.com/v1",+ max_output_tokens = 131072,+ )++ assert providers_db.get_provider("custom1")["max_output_tokens"] == 131072+ assert providers_db.update_provider(id = "custom1", max_output_tokens = None)+ assert providers_db.get_provider("custom1")["max_output_tokens"] is None+++def test_existing_provider_rows_migrate_to_unset_override(isolated_providers_db: Path):+ conn = sqlite3.connect(isolated_providers_db)+ conn.execute(+ """+ CREATE TABLE llm_providers (+ id TEXT NOT NULL PRIMARY KEY,+ provider_type TEXT NOT NULL,+ display_name TEXT NOT NULL,+ base_url TEXT NOT NULL,+ is_enabled INTEGER NOT NULL DEFAULT 1,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+ )+ """+ )+ conn.execute(+ "INSERT INTO llm_providers VALUES (?, ?, ?, ?, ?, ?, ?)",+ ("existing", "custom", "Existing", "https://example.com/v1", 1, "now", "now"),+ )+ conn.commit()+ conn.close()++ row = providers_db.get_provider("existing")+ assert row is not None+ assert row["max_output_tokens"] is Nonediff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 41c419d7d7b..fff02241c37 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -5013,6 +5013,7 @@ export function createOpenAIStreamAdapter(getExternalMaxOutputTokens(externalProvider?.providerType,externalSelection?.modelId,+ externalProvider?.maxOutputTokens,),),diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.tsindex d4bb1b9ce60..7099bf597b8 100644--- a/studio/frontend/src/features/chat/api/providers-api.ts+++ b/studio/frontend/src/features/chat/api/providers-api.ts@@ -43,6 +43,7 @@ export interface ProviderConfig {auth_status?: ProviderAuthStatus;models?: string[];available_models?: string[];+ max_output_tokens?: number | null;created_at: string;updated_at: string;}@@ -145,6 +146,7 @@ export async function createProviderConfig(payload: {baseUrl?: string | null;models?: string[];availableModels?: string[];+ maxOutputTokens?: number | null;apiKey?: string;}): Promise<ProviderConfig> {return withApiKeyEncryptionRetry(payload.apiKey ?? "", async (encryptedApiKey) => {@@ -157,6 +159,9 @@ export async function createProviderConfig(payload: {base_url: payload.baseUrl ?? null,models: payload.models ?? [],available_models: payload.availableModels ?? [],+ ...(payload.maxOutputTokens === undefined+ ? {}+ : { max_output_tokens: payload.maxOutputTokens }),encrypted_api_key: encryptedApiKey,}),});@@ -188,6 +193,7 @@ export async function updateProviderConfig(isEnabled?: boolean;models?: string[];availableModels?: string[];+ maxOutputTokens?: number | null;apiKey?: string;clearApiKey?: boolean;},@@ -204,6 +210,9 @@ export async function updateProviderConfig(...(payload.availableModels === undefined? {}: { available_models: payload.availableModels }),+ ...(payload.maxOutputTokens === undefined+ ? {}+ : { max_output_tokens: payload.maxOutputTokens }),...(payload.apiKey === undefined ? {} : { encrypted_api_key: encryptedApiKey }),...(payload.clearApiKey === undefined ? {} : { clear_api_key: payload.clearApiKey }),}),diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsxindex 4cc4d6b543e..55d26d789b9 100644--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx@@ -58,11 +58,13 @@ import {customProviderDisplayName,customProviderModelIdsPlaceholder,customPresetSkipsApiKeyField,+ CUSTOM_MAX_OUTPUT_TOKENS_MIN,getExternalProviderApiKey,isCustomProviderType,LEGACY_CUSTOM_PROVIDER_TYPE,CUSTOM_PROVIDER_DISPLAY_NAME,removeExternalProviderApiKey,+ supportsCustomMaxOutputTokens,supportsProviderReasoningToggle,supportsRemoteModelCatalog,toExternalBackendProviderType,@@ -162,6 +164,10 @@ export function ChatProvidersSettings({const [clearApiKeyRequested, setClearApiKeyRequested] = useState(false);const [baseUrlDraft, setBaseUrlDraft] = useState("");+ const [maxOutputTokensDraft, setMaxOutputTokensDraft] = useState("");+ const [editingBackendProviderType, setEditingBackendProviderType] = useState<+ string | null+ >(null);const [editingProviderId, setEditingProviderId] = useState<string | null>(null,);@@ -186,6 +192,12 @@ export function ChatProvidersSettings({(s) => s.setConnectionsEnabled,);const isCustomProvider = isCustomProviderType(providerType);+ // Keyed on the STORED type, not the displayed one. A connection being created has+ // no server row yet, so the helper falls back to what the create call will send.+ const supportsMaxOutputTokens = supportsCustomMaxOutputTokens(+ providerType,+ editingProviderId ? editingBackendProviderType : null,+ );// 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);@@ -282,6 +294,8 @@ export function ChatProvidersSettings({if (!providerType || editingProviderId) return;if (seededProviderTypeRef.current === providerType) return;seededProviderTypeRef.current = providerType;+ setMaxOutputTokensDraft("");+ setEditingBackendProviderType(null);const entry = registryByType.get(providerType);if (!entry) {if (isCustomProviderType(providerType)) {@@ -383,6 +397,8 @@ export function ChatProvidersSettings({setClearApiKeyRequested(false);setShowApiKey(false);setBaseUrlDraft("");+ setMaxOutputTokensDraft("");+ setEditingBackendProviderType(null);setAvailableModels([]);setSelectedModelIds([]);setManualModelIds("");@@ -462,6 +478,24 @@ export function ChatProvidersSettings({});}+ function parseMaxOutputTokens(input: string): number | null {+ const trimmed = input.trim();+ if (!trimmed) return null;+ if (!/^\d+$/.test(trimmed)) {+ throw new Error("Max Tokens limit must be an integer.");+ }+ const value = Number(trimmed);+ if (!Number.isSafeInteger(value)) {+ throw new Error("Max Tokens limit must be a safe integer.");+ }+ if (value < CUSTOM_MAX_OUTPUT_TOKENS_MIN) {+ throw new Error(+ `Max Tokens limit must be at least ${CUSTOM_MAX_OUTPUT_TOKENS_MIN.toLocaleString()}.`,+ );+ }+ return value;+ }+async function loadModels() {if (!providerType) {toast.error("Choose a connection first.");@@ -663,6 +697,9 @@ export function ChatProvidersSettings({isCustomProvider,providerType,);+ const maxOutputTokens = supportsMaxOutputTokens+ ? parseMaxOutputTokens(maxOutputTokensDraft)+ : undefined;const created = await createProviderConfig({providerType: backendProviderType,displayName,@@ -671,6 +708,7 @@ export function ChatProvidersSettings({availableModels: manualOnly? []: pruneProviderModelIds(providerType, availableModels),+ maxOutputTokens,apiKey: apiKey.trim(),});@@ -686,12 +724,15 @@ export function ChatProvidersSettings({const provider: ExternalProviderConfig = {id: created.id,providerType: uiProviderType,+ // Now, not at the next sync, so reopening it this session knows the stored type.+ backendProviderType: created.provider_type,name: created.display_name,baseUrl: created.base_url ?? "",models: modelsToSave,availableModels: manualOnly? []: pruneProviderModelIds(providerType, availableModels),+ maxOutputTokens: created.max_output_tokens ?? undefined,hasApiKey: created.has_api_key,@@ -800,6 +841,9 @@ export function ChatProvidersSettings({isEditingCustomProvider,existing.providerType,);+ const maxOutputTokens = supportsMaxOutputTokens+ ? parseMaxOutputTokens(maxOutputTokensDraft)+ : undefined;const updated = await updateProviderConfig(editingProviderId, {displayName: isEditingCustomProvider? customProviderName.trim() ||@@ -810,6 +854,7 @@ export function ChatProvidersSettings({availableModels: manualOnly? []: pruneProviderModelIds(existing.providerType, availableModels),+ maxOutputTokens,...(credentialEdit.action === "replace"? { apiKey: credentialEdit.apiKey }: credentialEdit.action === "clear"@@ -831,12 +876,14 @@ export function ChatProvidersSettings({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(@@ -874,6 +921,8 @@ export function ChatProvidersSettings({setClearApiKeyRequested(false);setShowApiKey(false);setBaseUrlDraft(provider.baseUrl);+ setMaxOutputTokensDraft(provider.maxOutputTokens?.toString() ?? "");+ setEditingBackendProviderType(provider.backendProviderType ?? null);setModelSearchQuery("");setIsReasoningModel(supportsProviderReasoningToggle(provider.providerType)@@ -1250,6 +1299,59 @@ export function ChatProvidersSettings({</div>) : null}+ {supportsMaxOutputTokens ? (+ <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-max-output-tokens"+ className="text-sm font-medium"+ >+ Max Tokens limit+ </Label>+ <p+ id="provider-max-output-tokens-help"+ className="text-xs leading-snug text-muted-foreground"+ >+ Leave blank to use the 32,768-token default.+ </p>+ </div>+ <div className="flex min-w-0 flex-col gap-1.5">+ {/*+ A TEXT input, deliberately, matching NumericValueInput in the+ run-settings panel. `type="number"` runs the HTML value+ sanitization algorithm, which replaces anything the engine does+ not read as a valid floating-point number with the EMPTY STRING+ (WHATWG HTML 4.10.5). Blank means "no override" here, so a+ grouped or localised entry such as "131,072" would leave the box+ looking filled, report "" to React, and silently CLEAR the+ user's override on save with no error. Keeping the raw string+ lets `parseMaxOutputTokens` reject it and say why.+ */}+ <Input+ id="provider-max-output-tokens"+ type="text"+ inputMode="numeric"+ autoComplete="off"+ spellCheck={false}+ value={maxOutputTokensDraft}+ onChange={(event) =>+ setMaxOutputTokensDraft(event.target.value)+ }+ placeholder="32768"+ aria-describedby="provider-max-output-tokens-help provider-max-output-tokens-warning"+ className="h-9 text-sm"+ />+ <p+ id="provider-max-output-tokens-warning"+ className="text-xs leading-snug text-amber-700 dark:text-amber-400"+ >+ If the upstream provider does not support this value,+ requests may fail.+ </p>+ </div>+ </div>+ ) : 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/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex 3431a60aab0..a406085ddd1 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -99,6 +99,7 @@ import {getExternalMinOutputTokens,providerSupportsBuiltinCodeExecution,providerSupportsFastMode,+ resolveExternalMaxTokensClamp,} from "./provider-capabilities";import {isLocalModelPath,@@ -725,6 +726,7 @@ export function ChatSettingsPanel({? getExternalMaxOutputTokens(externalProviderType,externalSelection?.modelId,+ activeExternalProvider?.maxOutputTokens,): isGguf && baseContext? baseContext@@ -760,15 +762,58 @@ export function ChatSettingsPanel({};}+ // Lower a live Max Tokens that no longer fits the connection's cap.+ // `resolveExternalMaxTokensClamp` documents why an unresolved provider must not be+ // read as the 32,768 fallback.+ useEffect(() => {+ const clampedMaxTokens = resolveExternalMaxTokensClamp({+ settingsHydrated,+ hasActiveExternalProvider: activeExternalProvider != null,+ isExternalModel,+ maxTokens: params.maxTokens,+ maxTokensMax,+ });+ if (clampedMaxTokens == null) {+ return;+ }+ const nextParams = { ...params, maxTokens: clampedMaxTokens };+ const nextSource = isSamePresetConfig(activePresetBaseline, nextParams)+ ? getPresetSource(activePreset)+ : "modified";+ setActivePresetSource(nextSource);+ onParamsChange(nextParams);+ }, [+ activeExternalProvider,+ activePreset,+ activePresetBaseline,+ isExternalModel,+ maxTokensMax,+ onParamsChange,+ params,+ settingsHydrated,+ setActivePresetSource,+ ]);++ function applyPresetParamsWithinCurrentLimits(+ presetParams: Parameters<typeof applyPresetParams>[1],+ ): InferenceParams {+ const nextParams = applyPresetParams(params, presetParams);+ // Same reason the effect waits for a provider: without one `maxTokensMax` is the+ // fallback, so applying a preset here would lower the value for good.+ if (!isExternalModel || activeExternalProvider == null) return nextParams;+ return {+ ...nextParams,+ maxTokens: Math.min(nextParams.maxTokens, maxTokensMax),+ };+ }+function applyPreset(name: string) {if (!settingsHydrated) {return;}const p = presets.find((pr) => pr.name === name);if (p) {- onParamsChange({- ...applyPresetParams(params, p.params),- });+ onParamsChange(applyPresetParamsWithinCurrentLimits(p.params));if (p.loadConfig) {applyPresetLoadConfig(p.loadConfig);}@@ -828,9 +873,9 @@ export function ChatSettingsPanel({setCustomPresets(next);if (activePreset === name) {if (fallbackPreset) {- onParamsChange({- ... applyPresetParams(params, fallbackPreset.params),- });+ onParamsChange(+ applyPresetParamsWithinCurrentLimits(fallbackPreset.params),+ );if (fallbackPreset.loadConfig) {applyPresetLoadConfig(fallbackPreset.loadConfig);}diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.tsindex 0c43fc3b5b3..5a30d634afd 100644--- a/studio/frontend/src/features/chat/external-providers.ts+++ b/studio/frontend/src/features/chat/external-providers.ts@@ -18,6 +18,14 @@ export interface ExternalProviderConfig {models: string[];/** Cached available model ids from the provider's /models response. */availableModels?: string[];+ /**+ * The provider type as the BACKEND stores it, which is not always `providerType`+ * above: `resolveUiProviderTypeFromConfig` shows a row saved as `openai` with a+ * custom name or base URL as "custom". Absent means unknown, not custom.+ */+ backendProviderType?: string;+ /** Optional maximum Max Tokens cap for a generic Custom connection. */+ maxOutputTokens?: number;/** Whether the backend has an installation-saved key. */hasApiKey?: boolean;@@ -197,6 +205,42 @@ export function providerModelSupportsStudioTools(export const CUSTOM_BACKEND_PROVIDER_TYPE = "openai";export const LEGACY_CUSTOM_PROVIDER_TYPE = "custom";export const CUSTOM_PROVIDER_DISPLAY_NAME = "Custom";+export const CUSTOM_MAX_OUTPUT_TOKENS_MIN = 64;++export function normalizeCustomMaxOutputTokens(+ providerType: string | null | undefined,+ value: unknown,+): number | undefined {+ if (+ providerType !== LEGACY_CUSTOM_PROVIDER_TYPE ||+ typeof value !== "number" ||+ !Number.isSafeInteger(value) ||+ value < CUSTOM_MAX_OUTPUT_TOKENS_MIN+ ) {+ return undefined;+ }+ return value;+}++/**+ * Whether a connection may carry a per-connection Max Tokens limit.+ *+ * Both types have to agree: the UI type decides what the dialog draws, the stored type+ * decides what the server accepts, and they differ for a row saved as `openai` with a+ * custom name or base URL. An unknown stored type (synced before this field, or a+ * connection with no server row yet) falls back to what the create call will send.+ */+export function supportsCustomMaxOutputTokens(+ uiProviderType: string | null | undefined,+ backendProviderType: string | null | undefined,+): boolean {+ if (uiProviderType !== LEGACY_CUSTOM_PROVIDER_TYPE) return false;+ const effective =+ typeof backendProviderType === "string" && backendProviderType.length > 0+ ? backendProviderType+ : toExternalBackendProviderType(uiProviderType);+ return effective === LEGACY_CUSTOM_PROVIDER_TYPE;+}export const CUSTOM_PROVIDER_PRESETS = [{@@ -414,6 +458,16 @@ function normalizeProvider(raw: ExternalProviderConfig): ExternalProviderConfigavailableModels: (raw.availableModels ?? []).map((model) => model.trim()).filter((model) => model.length > 0),+ // Junk from a hand-edited entry becomes undefined, i.e. unknown.+ backendProviderType:+ typeof raw.backendProviderType === "string" &&+ raw.backendProviderType.trim().length > 0+ ? raw.backendProviderType.trim()+ : undefined,+ maxOutputTokens: normalizeCustomMaxOutputTokens(+ providerType,+ raw.maxOutputTokens,+ ),enablePromptCaching: supportsProviderPromptCaching(providerType)? raw.enablePromptCaching !== false: undefined,@@ -596,4 +650,4 @@ export function removeExternalProviderApiKey(} catch {// ignore}-}\ No newline at end of file+}diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.tsindex 986f58ebce5..b7194d19c8f 100644--- a/studio/frontend/src/features/chat/provider-capabilities.ts+++ b/studio/frontend/src/features/chat/provider-capabilities.ts@@ -1,7 +1,11 @@// 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 { providerModelSupportsStudioTools } from "./external-providers";+import {+ LEGACY_CUSTOM_PROVIDER_TYPE,+ normalizeCustomMaxOutputTokens,+ providerModelSupportsStudioTools,+} from "./external-providers";/*** Per-provider sampling parameter capability matrix.@@ -72,8 +76,8 @@ export function clampReasoningEffortToLevels(}/**- * Fallback cap for unknown providers / models. Prefer- * `getExternalMaxOutputTokens(providerType, modelId)` for the real cap.+ * Fallback cap for unknown providers / models and Custom connections without+ * an explicit per-connection override.*/export const EXTERNAL_MAX_OUTPUT_TOKENS = 32768;@@ -134,13 +138,21 @@ const EXTERNAL_MAX_OUTPUT_TOKENS_BY_MODEL: Array<{/*** Documented per-model output cap; unknown ids fall back to- * `EXTERNAL_MAX_OUTPUT_TOKENS` (32k). OpenRouter `provider/model` ids have the- * prefix stripped before matching.+ * `EXTERNAL_MAX_OUTPUT_TOKENS` (32k). Generic Custom connections use only their+ * explicit per-connection override and never inspect the model id. OpenRouter+ * `provider/model` ids have the prefix stripped before matching.*/export function getExternalMaxOutputTokens(providerType: string | null | undefined,modelId: string | null | undefined,+ customMaxOutputTokens?: number | null,): number {+ if (providerType === LEGACY_CUSTOM_PROVIDER_TYPE) {+ return (+ normalizeCustomMaxOutputTokens(providerType, customMaxOutputTokens) ??+ EXTERNAL_MAX_OUTPUT_TOKENS+ );+ }if (!providerType || !modelId) return EXTERNAL_MAX_OUTPUT_TOKENS;const normalized = modelId.trim().toLowerCase();if (!normalized) return EXTERNAL_MAX_OUTPUT_TOKENS;@@ -165,6 +177,30 @@ export function getExternalMaxOutputTokens(return EXTERNAL_MAX_OUTPUT_TOKENS;}+/**+ * The lowered Max Tokens the settings panel should write back, or null to leave it be.+ *+ * The availability guards are load-bearing: the caller PERSISTS this and it only ever+ * lowers, while `maxTokensMax` collapses to the 32,768 fallback whenever the provider+ * is momentarily unresolved (connections toggled off, cold hydration, a deleted+ * connection). No provider means the cap is unknown, not 32,768.+ *+ * Returning the cap itself is what makes it converge in one pass.+ */+export function resolveExternalMaxTokensClamp(input: {+ settingsHydrated: boolean;+ hasActiveExternalProvider: boolean;+ isExternalModel: boolean;+ maxTokens: number;+ maxTokensMax: number;+}): number | null {+ if (!input.settingsHydrated || !input.hasActiveExternalProvider) return null;+ if (!input.isExternalModel || input.maxTokens <= input.maxTokensMax) {+ return null;+ }+ return input.maxTokensMax;+}+function _inferProviderFromOpenrouterId(normalizedId: string,): string | null {diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 13cc7f4148e..71105c9840c 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -1972,12 +1972,18 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({.getState().providers.find((p) => p.id === parsed.providerId): null;- const cap = getExternalMaxOutputTokens(- provider?.providerType,- parsed?.modelId,- );- if (nextMaxTokens > cap) {- nextMaxTokens = cap;+ // Only when the connection is known. A checkpoint restored before the+ // provider store hydrates would otherwise read the 32,768 fallback and lower+ // a value nothing puts back. No provider means unknown, not 32,768.+ if (provider) {+ const cap = getExternalMaxOutputTokens(+ provider.providerType,+ parsed?.modelId,+ provider.maxOutputTokens,+ );+ if (nextMaxTokens > cap) {+ nextMaxTokens = cap;+ }}}const nextGgufVariant = ggufVariant ?? null;diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.tsindex 41a2eda055c..8fa0d9b8e5d 100644--- a/studio/frontend/src/features/chat/sync-external-providers.ts+++ b/studio/frontend/src/features/chat/sync-external-providers.ts@@ -226,10 +226,17 @@ export async function syncExternalProvidersFromBackend(const synced: ExternalProviderConfig = {id: config.id,providerType: uiProviderType,+ // Beside the UI type, which disagrees for a legacy row saved as `openai`:+ // only the stored type decides what the backend accepts.+ backendProviderType: config.provider_type,name: config.display_name,baseUrl: config.base_url ?? "",models: resolvedModels,availableModels: resolvedAvailableModels,+ maxOutputTokens:+ uiProviderType === LEGACY_CUSTOM_PROVIDER_TYPE+ ? (config.max_output_tokens ?? undefined)+ : undefined,hasApiKey: config.has_api_key,diff --git a/studio/frontend/tests/custom-provider-max-output-tokens-guards.test.ts b/studio/frontend/tests/custom-provider-max-output-tokens-guards.test.tsnew file mode 100644index 00000000000..f0c02cba45b--- /dev/null+++ b/studio/frontend/tests/custom-provider-max-output-tokens-guards.test.ts@@ -0,0 +1,182 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++registerBundlerResolver();+const { store } = installLocalStorageFake();++const {+ CUSTOM_MAX_OUTPUT_TOKENS_MIN,+ LEGACY_CUSTOM_PROVIDER_TYPE,+ loadExternalProviders,+ normalizeCustomMaxOutputTokens,+ saveExternalProviders,+ supportsCustomMaxOutputTokens,+} = await import("../src/features/chat/external-providers.ts");++const {+ EXTERNAL_MAX_OUTPUT_TOKENS,+ getExternalMaxOutputTokens,+ resolveExternalMaxTokensClamp,+} = await import("../src/features/chat/provider-capabilities.ts");++// Two provider types are in play and they are NOT interchangeable. The UI type is+// what the connections dialog draws, from `resolveUiProviderTypeFromConfig`; the+// backend type is what the server row actually holds. They disagree for a row saved+// as `openai` with a custom display name or base URL, which the dialog shows as+// Custom while the server still rejects an override on it.+test("the override is offered only when both provider types say custom", () => {+ assert.equal(supportsCustomMaxOutputTokens("custom", "custom"), true);+ assert.equal(supportsCustomMaxOutputTokens("custom", "openai"), false);+ assert.equal(supportsCustomMaxOutputTokens("openai", "custom"), false);+ assert.equal(supportsCustomMaxOutputTokens("openai", "openai"), false);++ // Unknown backend type: a connection being created has no server row yet, and an+ // entry synced before the field existed carries no value. Both fall back to the+ // outgoing mapping, so a brand new Custom connection keeps working as before.+ assert.equal(supportsCustomMaxOutputTokens("custom", null), true);+ assert.equal(supportsCustomMaxOutputTokens("custom", undefined), true);+ assert.equal(supportsCustomMaxOutputTokens("custom", ""), true);+ assert.equal(supportsCustomMaxOutputTokens("openai", null), false);+ assert.equal(supportsCustomMaxOutputTokens(null, null), false);+});++test("a stored override is dropped unless it is a usable custom-connection value", () => {+ const custom = LEGACY_CUSTOM_PROVIDER_TYPE;+ assert.equal(normalizeCustomMaxOutputTokens(custom, 384000), 384000);+ assert.equal(normalizeCustomMaxOutputTokens(custom, CUSTOM_MAX_OUTPUT_TOKENS_MIN), 64);++ // Anything a hand-edited or older localStorage entry could hold.+ for (const junk of [+ "384000", 384000.5, -1, 0, 63, Number.NaN, Number.POSITIVE_INFINITY,+ null, undefined, {}, [], 2 ** 53,+ ]) {+ assert.equal(normalizeCustomMaxOutputTokens(custom, junk), undefined);+ }++ // And never for a provider that has documented caps of its own.+ for (const type of ["openai", "anthropic", "gemini", "vllm", "ollama", "llama_cpp"]) {+ assert.equal(normalizeCustomMaxOutputTokens(type, 384000), undefined);+ }+});++test("named providers keep the caps they had before the override existed", () => {+ // Real entries from the capability table, each one a provider with a documented+ // cap of its own. The override argument is passed on every call, so this fails if+ // it ever leaks past the custom-only early return.+ const cases: Array<[string, string | null, number]> = [+ ["openai", "gpt-5.6", 128000],+ ["openai", "gpt-5.3", 16384],+ ["openai", "gpt-4o", EXTERNAL_MAX_OUTPUT_TOKENS],+ ["gemini", "gemini-3-pro", 65536],+ ["deepseek", "deepseek-reasoner", 384000],+ ["openrouter", "deepseek/deepseek-reasoner", 384000],+ ["vllm", "some/local-model", EXTERNAL_MAX_OUTPUT_TOKENS],+ ["ollama", null, EXTERNAL_MAX_OUTPUT_TOKENS],+ ];+ for (const [providerType, modelId, expected] of cases) {+ assert.equal(getExternalMaxOutputTokens(providerType, modelId), expected);+ assert.equal(getExternalMaxOutputTokens(providerType, modelId, 384000), expected);+ assert.equal(getExternalMaxOutputTokens(providerType, modelId, null), expected);+ }+});++test("a custom connection takes its own cap, above or below the fallback", () => {+ const custom = LEGACY_CUSTOM_PROVIDER_TYPE;+ assert.equal(getExternalMaxOutputTokens(custom, "any-model"), EXTERNAL_MAX_OUTPUT_TOKENS);+ assert.equal(getExternalMaxOutputTokens(custom, "any-model", 384000), 384000);+ assert.equal(getExternalMaxOutputTokens(custom, "any-model", 1024), 1024);+ // A model id that matches a known family is still ignored: on a custom endpoint the+ // id space is user-controlled and means nothing.+ assert.equal(getExternalMaxOutputTokens(custom, "gpt-4o"), EXTERNAL_MAX_OUTPUT_TOKENS);+ // An unusable stored value fails closed to the fallback rather than to 0.+ assert.equal(getExternalMaxOutputTokens(custom, "any-model", 0), EXTERNAL_MAX_OUTPUT_TOKENS);+});++// The settings panel PERSISTS what this returns, and it only ever lowers, so the+// availability guards are what stop a blink in the provider list from destroying a+// configured override.+test("a live Max Tokens is only lowered when the cap is actually known", () => {+ const base = {+ settingsHydrated: true,+ hasActiveExternalProvider: true,+ isExternalModel: true,+ maxTokens: 384000,+ maxTokensMax: 32768,+ };+ assert.equal(resolveExternalMaxTokensClamp(base), 32768);++ // No resolved provider: connections toggled off, a cold browser where settings+ // hydrate before the sync lands, or a connection deleted while selected. The cap+ // reads as the 32,768 fallback in all of those, and clamping would be permanent.+ assert.equal(+ resolveExternalMaxTokensClamp({ ...base, hasActiveExternalProvider: false }),+ null,+ );+ assert.equal(resolveExternalMaxTokensClamp({ ...base, settingsHydrated: false }), null);+ assert.equal(resolveExternalMaxTokensClamp({ ...base, isExternalModel: false }), null);+ // Already within the cap, and exactly at it.+ assert.equal(resolveExternalMaxTokensClamp({ ...base, maxTokens: 8192 }), null);+ assert.equal(resolveExternalMaxTokensClamp({ ...base, maxTokens: 32768 }), null);++ // Converges in one pass: feeding the result back in asks for no further change.+ const once = resolveExternalMaxTokensClamp(base);+ assert.equal(resolveExternalMaxTokensClamp({ ...base, maxTokens: once as number }), null);+});++test("an entry saved by an older install loads without gaining a cap", () => {+ const legacy = [+ {+ id: "legacy-1",+ providerType: "custom",+ name: "Old Custom",+ baseUrl: "https://example.com/v1",+ models: ["vendor/model"],+ createdAt: 1,+ updatedAt: 1,+ },+ ];+ store.set("unsloth_chat_external_providers", JSON.stringify(legacy));+ const [loaded] = loadExternalProviders();+ assert.equal(loaded.maxOutputTokens, undefined);+ assert.equal(loaded.backendProviderType, undefined);+ assert.equal(loaded.models.length, 1);++ // And a round trip through save keeps the stored type once it is known.+ saveExternalProviders([{ ...loaded, backendProviderType: "openai", maxOutputTokens: 384000 }]);+ const [reloaded] = loadExternalProviders();+ assert.equal(reloaded.backendProviderType, "openai");+ assert.equal(reloaded.maxOutputTokens, 384000);+});++// The same guard has to hold everywhere a cap is applied, not just in the effect:+// a preset applied, or a checkpoint selected, while the provider is unresolved would+// otherwise lower the value permanently. Source-level assertions, since neither call+// site is reachable without a DOM.+test("every clamp site waits for a resolved provider", () => {+ const settings = readFileSync(+ new URL("../src/features/chat/chat-settings-sheet.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ settings,+ /function applyPresetParamsWithinCurrentLimits\([\s\S]*?if \(!isExternalModel \|\| activeExternalProvider == null\) return nextParams;/,+ );++ const store = readFileSync(+ new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ store,+ /if \(provider\) \{\s*const cap = getExternalMaxOutputTokens\(\s*provider\.providerType/,+ );+});diff --git a/studio/frontend/tests/custom-provider-max-output-tokens.test.ts b/studio/frontend/tests/custom-provider-max-output-tokens.test.tsnew file mode 100644index 00000000000..4d4843292c8--- /dev/null+++ b/studio/frontend/tests/custom-provider-max-output-tokens.test.ts@@ -0,0 +1,103 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++function source(relativePath: string): string {+ return readFileSync(+ new URL(`../src/features/chat/${relativePath}`, import.meta.url),+ "utf8",+ );+}++test("all max-output cap callers pass the selected connection override", () => {+ const settings = source("chat-settings-sheet.tsx");+ const runtime = source("stores/chat-runtime-store.ts");+ const adapter = source("api/chat-adapter.ts");++ assert.match(+ settings,+ /getExternalMaxOutputTokens\([\s\S]*?activeExternalProvider\?\.maxOutputTokens/,+ );+ assert.match(+ runtime,+ // Inside the `if (provider)` guard, so the optional chain is gone: an+ // unresolved provider must not clamp at all, rather than clamp to the fallback.+ /if \(provider\) \{[\s\S]*?getExternalMaxOutputTokens\([\s\S]*?provider\.maxOutputTokens/,+ );+ assert.match(+ adapter,+ /getExternalMaxOutputTokens\([\s\S]*?externalProvider\?\.maxOutputTokens/,+ );+});++test("the generic Custom editor exposes a bounded optional cap and warning", () => {+ const dialog = source("chat-providers-dialog.tsx");++ // Gated on the extracted predicate, not on the UI provider type: line 136's+ // `providerType === LEGACY_CUSTOM_PROVIDER_TYPE` is a display-name lookup and+ // matching it here would pass even if the row lost its gate entirely.+ assert.match(+ dialog,+ /const supportsMaxOutputTokens = supportsCustomMaxOutputTokens\(/,+ );+ assert.match(dialog, /\{supportsMaxOutputTokens \? \(/);+ assert.match(dialog, /Max Tokens limit/);+ assert.match(dialog, /Leave blank to use the 32,768-token default\./);+ assert.match(+ dialog,+ /If the upstream provider does not support this value,\s+requests may fail\./,+ );+ // A TEXT input, not `type="number"`. The HTML value sanitization algorithm+ // replaces anything a `number` input does not read as a valid floating-point+ // number with the empty string, and empty means "no override" here, so a+ // grouped entry like "131,072" would silently CLEAR the user's override on+ // save. The bounds live in `parseMaxOutputTokens` instead of in DOM attributes.+ assert.match(+ dialog,+ /id="provider-max-output-tokens"\s+type="text"\s+inputMode="numeric"/,+ );+ assert.doesNotMatch(+ dialog,+ /id="provider-max-output-tokens"\s+type="number"/,+ );+ assert.match(dialog, /value < CUSTOM_MAX_OUTPUT_TOKENS_MIN/);+ assert.match(dialog, /Number\.isSafeInteger\(value\)/);+ assert.match(dialog, /\/\^\\d\+\$\/\.test\(trimmed\)/);+});++test("preset application clamps live Max Tokens to the active external cap", () => {+ const settings = source("chat-settings-sheet.tsx");++ assert.match(+ settings,+ // The provider guard is part of the shape: without a resolved provider the cap+ // is the 32,768 fallback, and applying a preset there would lower the value for+ // good. `custom-provider-max-output-tokens-guards.test.ts` covers the same rule+ // at the other two clamp sites.+ /function applyPresetParamsWithinCurrentLimits\([\s\S]*?if \(!isExternalModel \|\| activeExternalProvider == null\) return nextParams;[\s\S]*?Math\.min\(nextParams\.maxTokens, maxTokensMax\)/,+ );+ assert.match(+ settings,+ /onParamsChange\(applyPresetParamsWithinCurrentLimits\(p\.params\)\)/,+ );+ assert.match(+ settings,+ /applyPresetParamsWithinCurrentLimits\(fallbackPreset\.params\)/,+ );+});++test("lowering an active external cap immediately clamps live Max Tokens", () => {+ const settings = source("chat-settings-sheet.tsx");++ // The decision itself lives in `resolveExternalMaxTokensClamp` (unit-tested in+ // external-max-tokens-clamp.test.ts). What this asserts is that the effect still+ // asks it, still passes the availability inputs rather than assuming them, and+ // still writes the result back through the preset-source bookkeeping.+ assert.match(+ settings,+ /useEffect\(\(\) => \{\s*const clampedMaxTokens = resolveExternalMaxTokensClamp\(\{[\s\S]*?settingsHydrated,[\s\S]*?hasActiveExternalProvider: activeExternalProvider != null,[\s\S]*?isExternalModel,[\s\S]*?maxTokens: params\.maxTokens,[\s\S]*?maxTokensMax,[\s\S]*?\}\);[\s\S]*?if \(clampedMaxTokens == null\) \{[\s\S]*?maxTokens: clampedMaxTokens[\s\S]*?setActivePresetSource\(nextSource\)[\s\S]*?onParamsChange\(nextParams\)/,+ );+});diff --git a/studio/frontend/tests/provider-capabilities-current-models.test.ts b/studio/frontend/tests/provider-capabilities-current-models.test.tsindex 3b824385b0e..3178cb60d64 100644--- a/studio/frontend/tests/provider-capabilities-current-models.test.ts+++ b/studio/frontend/tests/provider-capabilities-current-models.test.ts@@ -134,3 +134,37 @@ test("new Anthropic and OpenAI ids keep their max-output cap and code pill", ()true,);});++test("generic Custom connections use only their explicit max-output override", () => {+ // Model names that resemble known hosted families must not change Custom's cap.+ assert.equal(getExternalMaxOutputTokens("custom", "gpt-5.6-sol"), 32768);+ assert.equal(getExternalMaxOutputTokens("custom", "claude-opus-5"), 32768);++ assert.equal(+ getExternalMaxOutputTokens("custom", "any/provider-model", 131072),+ 131072,+ );+ assert.equal(getExternalMaxOutputTokens("custom", null, 65536), 65536);++ // Invalid persisted values fail closed to the conservative default.+ assert.equal(getExternalMaxOutputTokens("custom", "model", 63), 32768);+ assert.equal(getExternalMaxOutputTokens("custom", "model", 65536.5), 32768);+ assert.equal(+ getExternalMaxOutputTokens("custom", "model", Number.MAX_SAFE_INTEGER + 1),+ 32768,+ );++ // The override is provider-owned, so values above Studio's context-length+ // convention remain valid as long as they round-trip safely through JSON.+ assert.equal(getExternalMaxOutputTokens("custom", "model", 1048577), 1048577);+ assert.equal(+ getExternalMaxOutputTokens("custom", "model", Number.MAX_SAFE_INTEGER),+ Number.MAX_SAFE_INTEGER,+ );+});++test("Custom overrides cannot alter documented caps for other providers", () => {+ assert.equal(getExternalMaxOutputTokens("openai", "gpt-5.6-sol", 64), 128000);+ assert.equal(getExternalMaxOutputTokens("anthropic", "claude-opus-5", 64), 128000);+ assert.equal(getExternalMaxOutputTokens("vllm", "gpt-5.6-sol", 131072), 32768);+});diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.pyindex 24722c3f628..26871e50bcf 100644--- a/tests/studio/test_new_chat_context_recount.py+++ b/tests/studio/test_new_chat_context_recount.py@@ -178,7 +178,11 @@ function parseExternalModelId(id: string): any {return rest.length > 0 ? { providerId, modelId: rest.join(":") } : null;}const useExternalProvidersStore: any = { getState: () => ({ providers: [] }) };-function getExternalMaxOutputTokens(_providerType: any, _modelId: any): number {+function getExternalMaxOutputTokens(+ _providerType: any,+ _modelId: any,+ _maxOutputTokens?: any,+): number {return 8192;}function shouldAdvanceQueuedSettingsEpoch(