Skip to content

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

studio: allow a per-connection max tokens limit on every provider (#8944)

Maheswar Kumarc41d4916ed45
diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.py
index ebfb5757255..3f948a8b6bd 100644
--- a/studio/backend/models/providers.py
+++ b/studio/backend/models/providers.py
@@ -76,7 +76,7 @@ class ProviderCreate(BaseModel):
strict = True,
ge = 64,
le = MAX_JSON_SAFE_INTEGER,
- description = "Optional maximum Max Tokens cap for a generic Custom connection",
+ description = "Optional maximum Max Tokens cap for this connection",
)
encrypted_api_key: Optional[str] = Field(
@@ -101,7 +101,7 @@ class ProviderUpdate(BaseModel):
strict = True,
ge = 64,
le = MAX_JSON_SAFE_INTEGER,
- description = "Optional maximum Max Tokens cap for a generic Custom connection",
+ description = "Optional maximum Max Tokens cap for this connection",
)
encrypted_api_key: Optional[str] = Field(
@@ -147,7 +147,7 @@ class ProviderResponse(BaseModel):
)
max_output_tokens: Optional[int] = Field(
None,
- description = "Configured maximum Max Tokens cap for a generic Custom connection",
+ description = "Configured maximum Max Tokens cap for this 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.py
index 4599aa0292d..01815e5a1b2 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -117,17 +117,20 @@ def _validate_max_output_tokens_contract(
field_was_set: bool,
value: Optional[int] = None,
) -> None:
- """Reject a non-null override on a provider type with its own documented caps.
+ """Reject a non-null override on a ChatGPT subscription.
- 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.
+ Codex routing, model list and output cap are all fixed, so an override stored there
+ would never be read. Every other type takes one: the frontend uses it to lower a
+ model's documented cap, or to replace the 32,768-token fallback for a model with no
+ documented cap.
+
+ An explicit null is allowed everywhere, Codex included: a blank field serialises as
+ null rather than as an omission, and clearing an absent override is a no-op.
"""
- if field_was_set and value is not None and provider_type != "custom":
+ if field_was_set and value is not None and provider_type == "openai_codex":
raise HTTPException(
status_code = 400,
- detail = "Max Tokens limit can only be overridden for generic Custom providers.",
+ detail = "ChatGPT subscriptions use a fixed Max Tokens limit.",
)
diff --git a/studio/backend/tests/test_credential_routes.py b/studio/backend/tests/test_credential_routes.py
index b40f4273b22..3f5cad3bbc4 100644
--- a/studio/backend/tests/test_credential_routes.py
+++ b/studio/backend/tests/test_credential_routes.py
@@ -221,34 +221,52 @@ def test_custom_max_output_tokens_requires_a_safe_integer(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,
- )
+def test_known_and_custom_preset_providers_accept_a_non_null_max_output_override():
+ """The override replaces the frontend's 32,768-token fallback, which every type
+ reaches for a model with no documented cap."""
+ for provider_type in ("openai", "openrouter", "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 = 65536,
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert created.max_output_tokens == 65536
+ assert providers_db.get_provider(created.id)["max_output_tokens"] == 65536
+
+
+def test_chatgpt_subscription_rejects_a_non_null_max_output_override():
+ """Codex routing, model list and output cap are fixed, so a stored override would
+ never be read."""
+ with pytest.raises(HTTPException) as error:
+ asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT",
+ max_output_tokens = 65536,
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
)
- assert error.value.status_code == 400
+ )
+ assert error.value.status_code == 400
+ # on the detail, not the status: a Codex create with no models also 400s on auth
+ assert error.value.detail == "ChatGPT subscriptions use a fixed Max Tokens limit."
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.
+ So every provider type has to accept the null, ChatGPT subscriptions included: an
+ unrelated edit -- a rename, a model change, a key rotation -- carries the blank field
+ along. Only a non-null value on a subscription is refused.
"""
for provider_type in ("openai", "vllm", "ollama", "llama_cpp"):
created = asyncio.run(
@@ -267,7 +285,7 @@ def test_known_and_custom_preset_providers_accept_an_explicit_null_max_output_ov
assert providers_db.get_provider(created.id)["max_output_tokens"] is None
-def test_known_provider_rejects_max_output_override_update():
+def test_known_provider_accepts_max_output_override_update():
providers_db.create_provider(
id = "openai-1",
provider_type = "openai",
@@ -275,16 +293,16 @@ def test_known_provider_rejects_max_output_override_update():
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,
- )
+ updated = 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
+ )
+ assert updated.max_output_tokens == 65536
+ assert providers_db.get_provider("openai-1")["max_output_tokens"] == 65536
def test_known_provider_accepts_a_null_max_output_override_update():
diff --git a/studio/backend/tests/test_custom_max_output_tokens_contract.py b/studio/backend/tests/test_provider_max_output_tokens_contract.py
similarity index 88%
rename from studio/backend/tests/test_custom_max_output_tokens_contract.py
rename to studio/backend/tests/test_provider_max_output_tokens_contract.py
index 34b32e6ad24..4e252efdb6e 100644
--- a/studio/backend/tests/test_custom_max_output_tokens_contract.py
+++ b/studio/backend/tests/test_provider_max_output_tokens_contract.py
@@ -8,10 +8,9 @@ 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.
+* the route contract, where an explicit null has to be accepted on every provider type:
+ the dialog sends null for a blank field rather than omitting it, so rejecting it broke
+ every unrelated edit of a row that carries no override.
No network, no GPU, no server: the routes are driven as plain coroutines and every
database is a per-test temporary file.
@@ -66,9 +65,9 @@ finally:
CREDENTIAL = ("alice", None)
-# Read from the registry rather than hardcoded, so a provider added later is covered
-# without an edit here.
+# From the registry, 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")
+OVERRIDABLE_PROVIDER_TYPES = tuple(t for t in PROVIDER_REGISTRY if t != "openai_codex")
# 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.
@@ -277,15 +276,9 @@ def _update(provider_id: str, payload: ProviderUpdate):
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.
- """
+ """A blank Max Tokens limit field serialises as null rather than as an omission, so
+ an unrelated edit of a row with no override -- a rename, a model change, a key
+ rotation -- sends the null along and rejecting it failed the whole edit."""
providers_db.create_provider(
id = f"{provider_type}-1",
provider_type = provider_type,
@@ -300,22 +293,51 @@ def test_a_non_custom_provider_accepts_an_explicit_null_override(
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(
[email protected]("provider_type", OVERRIDABLE_PROVIDER_TYPES)
+def test_every_provider_type_but_codex_takes_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."""
+ """A documented per-model cap still wins in the frontend; the override replaces the
+ 32,768-token fallback every provider reaches for an unlisted model."""
providers_db.create_provider(
id = f"{provider_type}-1",
provider_type = provider_type,
display_name = provider_type,
base_url = "https://example.com/v1",
)
+ assert (
+ _update(f"{provider_type}-1", ProviderUpdate(max_output_tokens = 262144)).max_output_tokens
+ == 262144
+ )
+ assert _raw_override(provider_routes, f"{provider_type}-1") == 262144
+
+
+def test_a_chatgpt_subscription_rejects_a_real_override(provider_routes: Path):
+ """Codex routing, model list and output cap are fixed, so a stored override would
+ never be read."""
+ providers_db.create_provider(
+ id = "openai_codex-1",
+ provider_type = "openai_codex",
+ display_name = "ChatGPT",
+ base_url = "https://chatgpt.com/backend-api/codex",
+ )
with pytest.raises(HTTPException) as error:
- _update(f"{provider_type}-1", ProviderUpdate(max_output_tokens = 65536))
+ _update("openai_codex-1", ProviderUpdate(max_output_tokens = 65536))
assert error.value.status_code == 400
- assert _raw_override(provider_routes, f"{provider_type}-1") is None
+ assert _raw_override(provider_routes, "openai_codex-1") is None
+
+ # Create takes the same contract, and reaches it before the auth one, so the caller
+ # is told which rule stopped them.
+ with pytest.raises(HTTPException) as created:
+ _create(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT",
+ max_output_tokens = 65536,
+ )
+ )
+ assert created.value.status_code == 400
+ assert "fixed Max Tokens limit" in created.value.detail
def test_a_custom_connection_can_set_preserve_and_clear_its_override(provider_routes: Path):
diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
index 29d64b4900d..a576ac5de2d 100644
--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx
+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
@@ -50,6 +50,7 @@ import {
} from "./api/providers-api";
import { resolveProviderCredentialEdit } from "./provider-credential-edit";
+import { getExternalMinOutputTokens } from "./provider-capabilities";
import type { ExternalProviderConfig } from "./external-providers";
import {
CUSTOM_PROVIDER_PRESETS,
@@ -58,14 +59,14 @@ import {
customProviderDisplayName,
customProviderModelIdsPlaceholder,
customPresetSkipsApiKeyField,
- CUSTOM_MAX_OUTPUT_TOKENS_MIN,
+ PROVIDER_MAX_OUTPUT_TOKENS_MIN,
getExternalProviderApiKey,
isCustomProviderType,
LEGACY_CUSTOM_PROVIDER_TYPE,
CUSTOM_PROVIDER_DISPLAY_NAME,
providerModelSupportsStudioTools,
removeExternalProviderApiKey,
- supportsCustomMaxOutputTokens,
+ supportsProviderMaxOutputTokens,
supportsProviderReasoningToggle,
supportsRemoteModelCatalog,
toExternalBackendProviderType,
@@ -193,9 +194,8 @@ 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(
+ // a connection being created has no stored type yet, so only the UI type can decide
+ const supportsMaxOutputTokens = supportsProviderMaxOutputTokens(
providerType,
editingProviderId ? editingBackendProviderType : null,
);
@@ -500,9 +500,14 @@ export function ChatProvidersSettings({
if (!Number.isSafeInteger(value)) {
throw new Error("Max Tokens limit must be a safe integer.");
}
- if (value < CUSTOM_MAX_OUTPUT_TOKENS_MIN) {
+ // getExternalMaxOutputTokens raises a sub-floor cap anyway, so say so instead of storing it
+ const floor = Math.max(
+ PROVIDER_MAX_OUTPUT_TOKENS_MIN,
+ getExternalMinOutputTokens(providerType),
+ );
+ if (value < floor) {
throw new Error(
- `Max Tokens limit must be at least ${CUSTOM_MAX_OUTPUT_TOKENS_MIN.toLocaleString()}.`,
+ `Max Tokens limit must be at least ${floor.toLocaleString()}.`,
);
}
return value;
@@ -933,7 +938,16 @@ export function ChatProvidersSettings({
setClearApiKeyRequested(false);
setShowApiKey(false);
setBaseUrlDraft(provider.baseUrl);
- setMaxOutputTokensDraft(provider.maxOutputTokens?.toString() ?? "");
+ // 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(
+ provider.maxOutputTokens == null
+ ? ""
+ : Math.max(
+ provider.maxOutputTokens,
+ getExternalMinOutputTokens(provider.providerType),
+ ).toString(),
+ );
setEditingBackendProviderType(provider.backendProviderType ?? null);
setModelSearchQuery("");
setIsReasoningModel(
@@ -1324,7 +1338,9 @@ export function ChatProvidersSettings({
id="provider-max-output-tokens-help"
className="text-xs leading-snug text-muted-foreground"
>
- Leave blank to use the 32,768-token default.
+ Caps Max Tokens for this connection. Never raises it past a
+ model's documented limit. Leave blank to use that limit, or
+ 32,768 for a model without one.
</p>
</div>
<div className="flex min-w-0 flex-col gap-1.5">
diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.ts
index 0b987cf3bea..68eccaf0702 100644
--- a/studio/frontend/src/features/chat/external-providers.ts
+++ b/studio/frontend/src/features/chat/external-providers.ts
@@ -24,7 +24,7 @@ export interface ExternalProviderConfig {
* custom name or base URL as "custom". Absent means unknown, not custom.
*/
backendProviderType?: string;
- /** Optional maximum Max Tokens cap for a generic Custom connection. */
+ /** Optional Max Tokens cap for this connection, replacing the undocumented-model fallback. */
maxOutputTokens?: number;
/** Whether the backend has an installation-saved key. */
@@ -262,17 +262,16 @@ export function externalModelSupportsStudioTools(
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;
+const OPENAI_CODEX_PROVIDER_TYPE = "openai_codex";
+export const PROVIDER_MAX_OUTPUT_TOKENS_MIN = 64;
-export function normalizeCustomMaxOutputTokens(
- providerType: string | null | undefined,
+export function normalizeProviderMaxOutputTokens(
value: unknown,
): number | undefined {
if (
- providerType !== LEGACY_CUSTOM_PROVIDER_TYPE ||
typeof value !== "number" ||
!Number.isSafeInteger(value) ||
- value < CUSTOM_MAX_OUTPUT_TOKENS_MIN
+ value < PROVIDER_MAX_OUTPUT_TOKENS_MIN
) {
return undefined;
}
@@ -280,23 +279,22 @@ export function normalizeCustomMaxOutputTokens(
}
/**
- * Whether a connection may carry a per-connection Max Tokens limit.
+ * Whether a connection may carry a per-connection Max Tokens limit. Every type may,
+ * except ChatGPT subscriptions, whose routing, model list and output cap are all fixed,
+ * so an override there would be stored and never read.
*
- * 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.
+ * Both types are checked: the stored one is what the server validates against, the UI
+ * one is all the dialog has for a connection with no server row yet.
*/
-export function supportsCustomMaxOutputTokens(
+export function supportsProviderMaxOutputTokens(
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;
+ if (!uiProviderType) return false;
+ return (
+ uiProviderType !== OPENAI_CODEX_PROVIDER_TYPE &&
+ backendProviderType !== OPENAI_CODEX_PROVIDER_TYPE
+ );
}
export const CUSTOM_PROVIDER_PRESETS = [
@@ -521,10 +519,7 @@ function normalizeProvider(raw: ExternalProviderConfig): ExternalProviderConfig
raw.backendProviderType.trim().length > 0
? raw.backendProviderType.trim()
: undefined,
- maxOutputTokens: normalizeCustomMaxOutputTokens(
- providerType,
- raw.maxOutputTokens,
- ),
+ maxOutputTokens: normalizeProviderMaxOutputTokens(raw.maxOutputTokens),
enablePromptCaching: supportsProviderPromptCaching(providerType)
? raw.enablePromptCaching !== false
: undefined,
diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.ts
index d476bd50024..7fe7e848da9 100644
--- a/studio/frontend/src/features/chat/provider-capabilities.ts
+++ b/studio/frontend/src/features/chat/provider-capabilities.ts
@@ -2,8 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
- LEGACY_CUSTOM_PROVIDER_TYPE,
- normalizeCustomMaxOutputTokens,
+ normalizeProviderMaxOutputTokens,
providerModelSupportsStudioTools,
} from "./external-providers";
@@ -75,10 +74,7 @@ export function clampReasoningEffortToLevels(
return effortLevels[0] ?? "low";
}
-/**
- * Fallback cap for unknown providers / models and Custom connections without
- * an explicit per-connection override.
- */
+/** Fallback cap for a model with no documented limit and no connection override. */
export const EXTERNAL_MAX_OUTPUT_TOKENS = 32768;
/**
@@ -137,25 +133,40 @@ const EXTERNAL_MAX_OUTPUT_TOKENS_BY_MODEL: Array<{
];
/**
- * Documented per-model output cap; unknown ids fall back to
- * `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.
+ * The connection's effective Max Tokens ceiling for one model.
+ *
+ * A documented per-model cap bounds the connection override rather than replacing it:
+ * one connection fronts many models on a router, so a limit set for a 256k-output model
+ * must not raise the slider past what a smaller model accepts. An undocumented model
+ * takes the override outright, then `EXTERNAL_MAX_OUTPUT_TOKENS`. The provider's output
+ * floor wins over both, so the slider is never handed a max below its min.
*/
export function getExternalMaxOutputTokens(
providerType: string | null | undefined,
modelId: string | null | undefined,
- customMaxOutputTokens?: number | null,
+ connectionMaxOutputTokens?: 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 override = normalizeProviderMaxOutputTokens(connectionMaxOutputTokens);
+ const documented = _documentedMaxOutputTokens(providerType, modelId);
+ const resolved =
+ documented != null
+ ? Math.min(documented, override ?? documented)
+ : (override ?? EXTERNAL_MAX_OUTPUT_TOKENS);
+ return Math.max(resolved, getExternalMinOutputTokens(providerType));
+}
+
+/**
+ * The published per-model cap, or null when nothing documents this id. No table entry
+ * targets a generic Custom connection, so those always read as undocumented. OpenRouter
+ * `provider/model` ids have the prefix stripped before matching.
+ */
+function _documentedMaxOutputTokens(
+ providerType: string | null | undefined,
+ modelId: string | null | undefined,
+): number | null {
+ if (!providerType || !modelId) return null;
const normalized = modelId.trim().toLowerCase();
- if (!normalized) return EXTERNAL_MAX_OUTPUT_TOKENS;
+ if (!normalized) return null;
const stripped =
providerType === "openrouter" && normalized.includes("/")
? normalized.split("/").slice(-1)[0]
@@ -174,18 +185,17 @@ export function getExternalMaxOutputTokens(
return entry.cap;
}
}
- return EXTERNAL_MAX_OUTPUT_TOKENS;
+ return null;
}
/**
* 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.
+ * 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;
@@ -204,7 +214,6 @@ export function resolveExternalMaxTokensClamp(input: {
function _inferProviderFromOpenrouterId(
normalizedId: string,
): string | null {
- // Map OpenRouter `provider/model` prefix to our internal providerType.
if (normalizedId.startsWith("openai/")) return "openai";
if (normalizedId.startsWith("anthropic/")) return "anthropic";
if (normalizedId.startsWith("google/")) return "gemini";
diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.ts
index f5e0455ad69..c3b82d69cf8 100644
--- a/studio/frontend/src/features/chat/sync-external-providers.ts
+++ b/studio/frontend/src/features/chat/sync-external-providers.ts
@@ -250,10 +250,7 @@ export async function syncExternalProvidersFromBackend(
baseUrl: config.base_url ?? "",
models: resolvedModels,
availableModels: resolvedAvailableModels,
- maxOutputTokens:
- uiProviderType === LEGACY_CUSTOM_PROVIDER_TYPE
- ? (config.max_output_tokens ?? undefined)
- : undefined,
+ maxOutputTokens: config.max_output_tokens ?? 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.ts
deleted file mode 100644
index f0c02cba45b..00000000000
--- a/studio/frontend/tests/custom-provider-max-output-tokens-guards.test.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-// 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/provider-capabilities-current-models.test.ts b/studio/frontend/tests/provider-capabilities-current-models.test.ts
index 3178cb60d64..208aa15af38 100644
--- a/studio/frontend/tests/provider-capabilities-current-models.test.ts
+++ b/studio/frontend/tests/provider-capabilities-current-models.test.ts
@@ -21,10 +21,9 @@ const { providerModelSupportsVision, setProviderModelCapabilities } = await impo
"../src/features/chat/external-providers.ts"
);
-// The picker's default_models list (backend core/inference/providers.py) grew a
-// Claude 5 / gpt-5.6 / gemini-3.6 generation. Every table here is prefix-based,
-// so an un-widened prefix silently drops the control instead of failing loudly:
-// a model with no reasoning entry loses its Thinking picker entirely.
+// Every capability table is prefix-based, so an un-widened prefix silently drops a
+// control instead of failing loudly: a model with no reasoning entry loses its
+// Thinking picker entirely.
test("Claude 5 and Opus 4.8 expose the adaptive effort ladder", () => {
for (const model of [
@@ -45,7 +44,7 @@ test("Claude 5 and Opus 4.8 expose the adaptive effort ladder", () => {
});
test("Fable 5 thinks always, so no off switch is offered", () => {
- // `thinking.type: "disabled"` 400s on Fable/Mythos 5.
+ // `thinking.type: "disabled"` 400s on Fable/Mythos 5
const caps = getExternalReasoningCapabilities("anthropic", "claude-fable-5");
assert.equal(caps.supportsReasoning, true);
assert.equal(caps.supportsReasoningOff, false);
@@ -56,7 +55,7 @@ test("fast mode is offered on Opus 5 / 4.8 and nowhere else", () => {
for (const model of ["claude-opus-5", "claude-opus-4-8-2026-02-01"]) {
assert.equal(providerSupportsFastMode("anthropic", model), true, model);
}
- // 4.7 errors on `speed`; 4.6 accepts it but answers at standard speed.
+ // 4.7 errors on `speed`; 4.6 accepts it but answers at standard speed
for (const model of ["claude-opus-4-7", "claude-opus-4-6", "claude-sonnet-5"]) {
assert.equal(providerSupportsFastMode("anthropic", model), false, model);
}
@@ -67,7 +66,7 @@ test("the gpt-5.6 family gets the gpt-5.5 reasoning ladder", () => {
const caps = getExternalReasoningCapabilities("openai", model);
assert.equal(caps.supportsReasoning, true, model);
assert.equal(caps.supportsReasoningOff, true, model);
- // The API rejects "minimal" on this family.
+ // the API rejects "minimal" on this family
assert.deepEqual(
[...caps.reasoningEffortLevels],
["none", "low", "medium", "high", "xhigh"],
@@ -110,7 +109,7 @@ test("ChatGPT subscription vision gating follows the curated model", () => {
test("Gemini 3.x minors keep the thinkingLevel ladder", () => {
- // gemini-3.6-flash must not fall through to the 2.5 integer-budget branch.
+ // gemini-3.6-flash must not fall through to the 2.5 integer-budget branch
for (const model of ["gemini-3.6-flash", "gemini-3.5-flash-lite", "gemini-3-flash-preview"]) {
const caps = getExternalReasoningCapabilities("gemini", model);
assert.equal(caps.reasoningStyle, "reasoning_effort", model);
@@ -136,7 +135,8 @@ test("new Anthropic and OpenAI ids keep their max-output cap and code pill", ()
});
test("generic Custom connections use only their explicit max-output override", () => {
- // Model names that resemble known hosted families must not change Custom's cap.
+ // no capability row targets `custom`, so a model id resembling a hosted family
+ // never enters the decision
assert.equal(getExternalMaxOutputTokens("custom", "gpt-5.6-sol"), 32768);
assert.equal(getExternalMaxOutputTokens("custom", "claude-opus-5"), 32768);
@@ -146,7 +146,7 @@ test("generic Custom connections use only their explicit max-output override", (
);
assert.equal(getExternalMaxOutputTokens("custom", null, 65536), 65536);
- // Invalid persisted values fail closed to the conservative default.
+ // 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(
@@ -154,8 +154,8 @@ test("generic Custom connections use only their explicit max-output override", (
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.
+ // the override is provider-owned, so values above Studio's context-length convention
+ // stay 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),
@@ -163,8 +163,11 @@ test("generic Custom connections use only their explicit max-output override", (
);
});
-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);
+test("a connection override cannot raise a documented per-model cap", () => {
+ assert.equal(getExternalMaxOutputTokens("openai", "gpt-5.6-sol", 999999), 128000);
+ assert.equal(getExternalMaxOutputTokens("anthropic", "claude-opus-5", 999999), 128000);
+ // it lowers one, though: a gateway or spend policy below the published cap is real
+ assert.equal(getExternalMaxOutputTokens("openai", "gpt-5.6-sol", 8192), 8192);
+ // a vLLM server hosting an id borrowed from OpenAI has no documented cap of its own
+ assert.equal(getExternalMaxOutputTokens("vllm", "gpt-5.6-sol", 131072), 131072);
});
diff --git a/studio/frontend/tests/provider-max-output-tokens-guards.test.ts b/studio/frontend/tests/provider-max-output-tokens-guards.test.ts
new file mode 100644
index 00000000000..ab832a8a695
--- /dev/null
+++ b/studio/frontend/tests/provider-max-output-tokens-guards.test.ts
@@ -0,0 +1,208 @@
+// 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 {
+ LEGACY_CUSTOM_PROVIDER_TYPE,
+ loadExternalProviders,
+ normalizeProviderMaxOutputTokens,
+ PROVIDER_MAX_OUTPUT_TOKENS_MIN,
+ saveExternalProviders,
+ supportsProviderMaxOutputTokens,
+} = await import("../src/features/chat/external-providers.ts");
+
+const {
+ EXTERNAL_MAX_OUTPUT_TOKENS,
+ getExternalMaxOutputTokens,
+ getExternalMinOutputTokens,
+ resolveExternalMaxTokensClamp,
+} = await import("../src/features/chat/provider-capabilities.ts");
+
+// The UI type is what the dialog draws (`resolveUiProviderTypeFromConfig`); the backend
+// type is what the server row holds. They disagree for a row saved as `openai` with a
+// custom display name or base URL.
+test("the override is offered on every connection except a ChatGPT subscription", () => {
+ assert.equal(supportsProviderMaxOutputTokens("custom", "custom"), true);
+ assert.equal(supportsProviderMaxOutputTokens("custom", "openai"), true);
+ assert.equal(supportsProviderMaxOutputTokens("openrouter", "openrouter"), true);
+ assert.equal(supportsProviderMaxOutputTokens("anthropic", "anthropic"), true);
+
+ // a codex override would be stored and never read, and either type saying so is enough
+ assert.equal(supportsProviderMaxOutputTokens("openai_codex", "openai_codex"), false);
+ assert.equal(supportsProviderMaxOutputTokens("openai_codex", null), false);
+ assert.equal(supportsProviderMaxOutputTokens("openai", "openai_codex"), false);
+
+ // Unknown backend type: a connection being created has no server row yet, and an entry
+ // synced before the field existed carries no value. The UI type decides both.
+ assert.equal(supportsProviderMaxOutputTokens("custom", null), true);
+ assert.equal(supportsProviderMaxOutputTokens("custom", undefined), true);
+ assert.equal(supportsProviderMaxOutputTokens("custom", ""), true);
+ assert.equal(supportsProviderMaxOutputTokens("openai", null), true);
+ assert.equal(supportsProviderMaxOutputTokens(null, null), false);
+});
+
+test("a stored override is dropped unless it is a usable value", () => {
+ assert.equal(normalizeProviderMaxOutputTokens(384000), 384000);
+ assert.equal(normalizeProviderMaxOutputTokens(PROVIDER_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(normalizeProviderMaxOutputTokens(junk), undefined);
+ }
+});
+
+test("a documented per-model cap bounds the connection override", () => {
+ const cases: Array<[string, string, number]> = [
+ ["openai", "gpt-5.6", 128000],
+ ["openai", "gpt-5.3", 16384],
+ ["gemini", "gemini-3-pro", 65536],
+ ["deepseek", "deepseek-reasoner", 384000],
+ ["openrouter", "deepseek/deepseek-reasoner", 384000],
+ ["openai_codex", "gpt-5.3-codex", 128000],
+ ];
+ for (const [providerType, modelId, documented] of cases) {
+ assert.equal(getExternalMaxOutputTokens(providerType, modelId), documented);
+ assert.equal(getExternalMaxOutputTokens(providerType, modelId, null), documented);
+ // a router connection fronts models of every size, so one limit must not raise them all
+ assert.equal(
+ getExternalMaxOutputTokens(providerType, modelId, 999999),
+ documented,
+ );
+ // lowering is the whole point of a limit, so that half is honoured
+ assert.equal(getExternalMaxOutputTokens(providerType, modelId, 8192), 8192);
+ }
+});
+
+test("a model with no documented cap takes the connection override", () => {
+ // the reported case: a router id no capability row matches pinned at 32,768
+ const undocumented: Array<[string, string | null]> = [
+ ["openrouter", "minimax/minimax-m3"],
+ ["openai", "gpt-4o"],
+ ["vllm", "some/local-model"],
+ ["ollama", null],
+ [LEGACY_CUSTOM_PROVIDER_TYPE, "any-model"],
+ [LEGACY_CUSTOM_PROVIDER_TYPE, "gpt-4o"],
+ ];
+ for (const [providerType, modelId] of undocumented) {
+ assert.equal(
+ getExternalMaxOutputTokens(providerType, modelId),
+ EXTERNAL_MAX_OUTPUT_TOKENS,
+ );
+ assert.equal(getExternalMaxOutputTokens(providerType, modelId, 262144), 262144);
+ assert.equal(getExternalMaxOutputTokens(providerType, modelId, 1024), 1024);
+ // an unusable stored value fails closed to the fallback rather than to 0
+ assert.equal(
+ getExternalMaxOutputTokens(providerType, modelId, 0),
+ EXTERNAL_MAX_OUTPUT_TOKENS,
+ );
+ }
+});
+
+/** Kimi is the one provider with an output floor of its own (16,000) and no documented
+ * per-model cap, so without this its override alone could set the slider's max below
+ * the slider's min. */
+test("a provider's own output floor outranks a lower connection override", () => {
+ const kimiFloor = getExternalMinOutputTokens("kimi");
+ assert.equal(kimiFloor, 16000);
+
+ assert.equal(getExternalMaxOutputTokens("kimi", "kimi-k2.6", 8000), kimiFloor);
+ assert.equal(getExternalMaxOutputTokens("kimi", "kimi-k2.6", 262144), 262144);
+ assert.equal(
+ getExternalMaxOutputTokens("kimi", "kimi-k2.6"),
+ 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, settings hydrated 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 asks for no further change
+ const once = resolveExternalMaxTokensClamp(base);
+ assert.equal(resolveExternalMaxTokensClamp({ ...base, maxTokens: once as number }), null);
+});
+
+// deliberately not a Custom row: that one type round-trips the same with or without the gate
+test("an entry saved by an older install loads without gaining a cap", () => {
+ const legacy = [
+ {
+ id: "legacy-1",
+ providerType: "openrouter",
+ name: "Old Router",
+ 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);
+
+ // 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 guard has to hold at every clamp site, not just the effect: a preset or checkpoint
+// applied while the provider is unresolved would 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/provider-max-output-tokens.test.ts
similarity index 56%
rename from studio/frontend/tests/custom-provider-max-output-tokens.test.ts
rename to studio/frontend/tests/provider-max-output-tokens.test.ts
index 4d4843292c8..f61a376c7b6 100644
--- a/studio/frontend/tests/custom-provider-max-output-tokens.test.ts
+++ b/studio/frontend/tests/provider-max-output-tokens.test.ts
@@ -23,38 +23,44 @@ test("all max-output cap callers pass the selected connection override", () => {
);
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.
+ // inside the `if (provider)` guard, so no optional chain: 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/,
);
+
+ // re-gating this on the UI provider type makes the feature a no-op on the next sync
+ assert.match(
+ source("sync-external-providers.ts"),
+ /maxOutputTokens: config\.max_output_tokens \?\? undefined,/,
+ );
});
-test("the generic Custom editor exposes a bounded optional cap and warning", () => {
+test("the connection 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.
+ // Match the predicate, not the UI type: the `providerType === LEGACY_CUSTOM_PROVIDER_TYPE`
+ // line is a display-name lookup and would still match with the gate gone.
assert.match(
dialog,
- /const supportsMaxOutputTokens = supportsCustomMaxOutputTokens\(/,
+ /const supportsMaxOutputTokens = supportsProviderMaxOutputTokens\(/,
);
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,
+ /Caps Max Tokens for this connection\. Never raises it past a\s+model's documented limit\. Leave blank to use that limit, or\s+32,768 for a model without one\./,
+ );
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.
+ // A TEXT input: a `number` input sanitizes "131,072" to the empty string, which
+ // means "no override" here and would silently CLEAR it on save. Bounds live in
+ // `parseMaxOutputTokens` instead of in DOM attributes.
assert.match(
dialog,
/id="provider-max-output-tokens"\s+type="text"\s+inputMode="numeric"/,
@@ -63,9 +69,20 @@ test("the generic Custom editor exposes a bounded optional cap and warning", ()
dialog,
/id="provider-max-output-tokens"\s+type="number"/,
);
- assert.match(dialog, /value < CUSTOM_MAX_OUTPUT_TOKENS_MIN/);
+ // the floor is per provider, so Kimi's 16,000 outranks the generic 64
+ assert.match(
+ dialog,
+ /const floor = Math\.max\(\s*PROVIDER_MAX_OUTPUT_TOKENS_MIN,\s*getExternalMinOutputTokens\(providerType\),\s*\);\s*if \(value < floor\)/,
+ );
assert.match(dialog, /Number\.isSafeInteger\(value\)/);
assert.match(dialog, /\/\^\\d\+\$\/\.test\(trimmed\)/);
+
+ // seeding the draft raw would wedge every edit of a row stored below the floor,
+ // since the parse above throws on it and the field is submitted untouched
+ assert.match(
+ dialog,
+ /setMaxOutputTokensDraft\(\s*provider\.maxOutputTokens == null\s*\? ""\s*: Math\.max\(\s*provider\.maxOutputTokens,\s*getExternalMinOutputTokens\(provider\.providerType\),\s*\)\.toString\(\),\s*\);/,
+ );
});
test("preset application clamps live Max Tokens to the active external cap", () => {
@@ -73,10 +90,9 @@ test("preset application clamps live Max Tokens to the active external cap", ()
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.
+ // The provider guard is part of the shape: unresolved, the cap is the 32,768
+ // fallback and a preset would lower the value for good. The guards test covers
+ // the other two clamp sites.
/function applyPresetParamsWithinCurrentLimits\([\s\S]*?if \(!isExternalModel \|\| activeExternalProvider == null\) return nextParams;[\s\S]*?Math\.min\(nextParams\.maxTokens, maxTokensMax\)/,
);
assert.match(
@@ -92,10 +108,9 @@ test("preset application clamps live Max Tokens to the active external cap", ()
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.
+ // `resolveExternalMaxTokensClamp` decides (unit-tested in the guards test); this
+ // asserts the effect still asks it, still passes the availability inputs, and still
+ // writes 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\)/,