fix(webui): allow custom context window token budgets (#5901)

* fix(webui): allow custom context window token budgets

* fix(i18n): translate context window hints in all locales

* fix(webui): accept context window K and M shorthand

* fix(webui): shorten context window hints

* refactor(webui): simplify context window validation
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-24 18:26:03 +08:00
1 parent fdee134afb
commit eb3fc07087
17 files changed
+135 -49

No files matched your search

+3 -17
View File
@@ -85,7 +85,6 @@ class ModelSettingsPayload(TypedDict):
providers: list[dict[str, Any]] providers: list[dict[str, Any]]
_CONTEXT_WINDOW_TOKEN_OPTIONS = {65_536, 200_000, 262_144, 500_000, 1_048_576}
_OAUTH_PROXY_PROVIDERS = {"openai_codex", "xai_grok"} _OAUTH_PROXY_PROVIDERS = {"openai_codex", "xai_grok"}
_WEBUI_OAUTH_TIMEOUT_S = 600 _WEBUI_OAUTH_TIMEOUT_S = 600
_MODEL_CONFIGURATION_SLUG_RE = re.compile(r"[^a-z0-9_-]+") _MODEL_CONFIGURATION_SLUG_RE = re.compile(r"[^a-z0-9_-]+")
@@ -758,20 +757,6 @@ def provider_models_payload(
} }
def _parse_context_window_tokens(value: str | None) -> int | None:
if value is None:
return None
try:
parsed = int(value)
except ValueError:
raise WebUISettingsError("context_window_tokens must be an integer") from None
if parsed not in _CONTEXT_WINDOW_TOKEN_OPTIONS:
raise WebUISettingsError(
"context_window_tokens must be 65536, 200000, 262144, 500000, or 1048576"
)
return parsed
def _parse_positive_int(value: str | None, field: str) -> int | None: def _parse_positive_int(value: str | None, field: str) -> int | None:
if value is None: if value is None:
return None return None
@@ -1162,8 +1147,9 @@ def update_agent_model_settings(
defaults.provider = provider defaults.provider = provider
changed = True changed = True
context_window_tokens = _parse_context_window_tokens( context_window_tokens = _parse_positive_int(
query_first_alias(query, "context_window_tokens", "contextWindowTokens") query_first_alias(query, "context_window_tokens", "contextWindowTokens"),
"context_window_tokens",
) )
if ( if (
context_window_tokens is not None context_window_tokens is not None
+4 -6
View File
@@ -1066,7 +1066,7 @@ def test_update_model_configuration_preserves_custom_context_windows(
assert saved.model_presets["codex"].context_window_tokens == 128000 assert saved.model_presets["codex"].context_window_tokens == 128000
def test_update_context_window_rejects_unknown_values( def test_update_context_window_persists_custom_value(
tmp_path, tmp_path,
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
) -> None: ) -> None:
@@ -1074,11 +1074,9 @@ def test_update_context_window_rejects_unknown_values(
save_config(Config(), config_path) save_config(Config(), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path) monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
with pytest.raises( payload = update_agent_settings({"context_window_tokens": ["128000"]})
WebUISettingsError, assert payload["agent"]["context_window_tokens"] == 128000
match="context_window_tokens must be 65536, 200000, 262144, 500000, or 1048576", assert load_config(config_path).agents.defaults.context_window_tokens == 128000
):
update_agent_settings({"context_window_tokens": ["128000"]})
def test_update_model_configuration_rejects_default_preset( def test_update_model_configuration_rejects_default_preset(
+23
View File
@@ -2,8 +2,11 @@ from __future__ import annotations
from typing import Any from typing import Any
import pytest
from nanobot.config.schema import Config from nanobot.config.schema import Config
from nanobot.webui.settings_models import ( from nanobot.webui.settings_models import (
WebUISettingsError,
model_settings_payload, model_settings_payload,
update_agent_model_settings, update_agent_model_settings,
update_provider_settings, update_provider_settings,
@@ -57,3 +60,23 @@ def test_model_domain_owns_dto_and_config_updates() -> None:
"providers", "providers",
} }
assert payload["agent"]["model"] == "openai/gpt-5.4" assert payload["agent"]["model"] == "openai/gpt-5.4"
@pytest.mark.parametrize("tokens", [128_000, 131_072, 1_000_000])
def test_default_context_window_accepts_custom_tokens(tokens: int) -> None:
config = Config()
assert update_agent_model_settings(
config, {"context_window_tokens": [str(tokens)]}, oauth_status=_oauth_status,
)
assert config.agents.defaults.context_window_tokens == tokens
assert model_settings_payload(config, oauth_status=_oauth_status)["agent"]["context_window_tokens"] == tokens
@pytest.mark.parametrize("value", ["", "0", "-1", "1.5", "abc"])
def test_default_context_window_rejects_invalid_tokens(value: str) -> None:
config = Config()
with pytest.raises(WebUISettingsError, match="context_window_tokens must"):
update_agent_model_settings(
config, {"context_window_tokens": [value]}, oauth_status=_oauth_status,
)
assert config.agents.defaults.context_window_tokens == 200_000
@@ -18,6 +18,8 @@ import {
ProviderPicker, ProviderPicker,
ProviderPickerIcon, ProviderPickerIcon,
formatContextWindow, formatContextWindow,
formatContextWindowInput,
parseContextWindowTokens,
formatModelContextWindow, formatModelContextWindow,
normalizeContextWindowTokens, normalizeContextWindowTokens,
settingsProviderConfigured, settingsProviderConfigured,
@@ -39,7 +41,6 @@ import {
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { SettingsPayload } from "@/lib/types"; import type { SettingsPayload } from "@/lib/types";
@@ -55,8 +56,6 @@ export interface AgentSettingsDraft {
toolHintMaxLength: number; toolHintMaxLength: number;
} }
const CONTEXT_WINDOW_TOKEN_OPTIONS = [65_536, 200_000, 262_144, 500_000, 1_048_576] as const;
function modelPresetValue(payload: SettingsPayload): string { function modelPresetValue(payload: SettingsPayload): string {
return ( return (
payload.model_call_order?.[0] ?? payload.model_call_order?.[0] ??
@@ -517,7 +516,7 @@ export function ModelsSettings({
"settings.models.advancedSummary", "settings.models.advancedSummary",
"Context {{context}} · Max {{max}} tokens", "Context {{context}} · Max {{max}} tokens",
{ {
context: formatModelContextWindow(form.contextWindowTokens), context: Number.isFinite(form.contextWindowTokens) ? formatModelContextWindow(form.contextWindowTokens) : "—",
max: formatContextWindow(form.maxTokens), max: formatContextWindow(form.maxTokens),
}, },
)} )}
@@ -897,9 +896,10 @@ function ModelAdvancedFields({
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const contextWindowOptions = Array.from( const [contextDraft, setContextDraft] = useState<{ text: string; tokens: number } | null>(null);
new Set([...CONTEXT_WINDOW_TOKEN_OPTIONS, contextWindowTokens]), const contextWindowInputId = useId();
).sort((left, right) => left - right); const contextWindowHintId = `${contextWindowInputId}-hint`;
const contextWindowValid = Number.isSafeInteger(contextWindowTokens) && contextWindowTokens > 0;
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
@@ -938,20 +938,32 @@ function ModelAdvancedFields({
</label> </label>
</div> </div>
<div> <div>
<span className="mb-2 block text-[12px] font-medium text-muted-foreground"> <label htmlFor={contextWindowInputId} className="mb-1.5 block text-[12px] font-medium text-muted-foreground">
{tx("settings.rows.contextWindow", "Context window")} {tx("settings.rows.contextWindow", "Context window")}
</span> </label>
<SegmentedControl <Input
value={String(contextWindowTokens)} id={contextWindowInputId}
animateIndicator={false} type="text"
options={contextWindowOptions.map((tokens) => ({ autoCapitalize="none"
value: String(tokens), spellCheck={false}
label: formatModelContextWindow(tokens), required
}))} value={contextDraft && Object.is(contextDraft.tokens, contextWindowTokens)
onChange={(value) => ? contextDraft.text : formatContextWindowInput(contextWindowTokens)}
onChange({ contextWindowTokens: normalizeContextWindowTokens(Number(value)) }) onChange={(event) => {
} const text = event.target.value;
const tokens = parseContextWindowTokens(text);
setContextDraft({ text, tokens });
onChange({ contextWindowTokens: tokens });
}}
aria-invalid={!contextWindowValid}
aria-describedby={contextWindowHintId}
className="h-9 text-[13px]"
/> />
<p id={contextWindowHintId} className={cn("mt-1.5 text-[12px]", contextWindowValid ? "text-muted-foreground" : "text-destructive")}>
{contextWindowValid
? t("settings.models.contextWindowHint", { tokens: contextWindowTokens.toLocaleString(), defaultValue: "{{tokens}} tokens" })
: tx("settings.models.contextWindowError", "Enter a positive token count, such as 200k, 1m, or 131072.")}
</p>
</div> </div>
<label className="block"> <label className="block">
<span className="mb-1.5 block text-[12px] font-medium text-muted-foreground"> <span className="mb-1.5 block text-[12px] font-medium text-muted-foreground">
@@ -159,7 +159,9 @@ export function useModelSettingsActions({
!settings || !settings ||
saving || saving ||
modelCallOrderSaving || modelCallOrderSaving ||
modelConfigurationSaving modelConfigurationSaving ||
!Number.isSafeInteger(form.contextWindowTokens) ||
form.contextWindowTokens <= 0
) { ) {
return; return;
} }
@@ -173,7 +175,6 @@ export function useModelSettingsActions({
!provider || !provider ||
!model || !model ||
form.maxTokens <= 0 || form.maxTokens <= 0 ||
form.contextWindowTokens <= 0 ||
form.temperature < 0 || form.temperature < 0 ||
form.temperature > 2 form.temperature > 2
) { ) {
@@ -60,6 +60,21 @@ export function normalizeContextWindowTokens(value: number | null | undefined):
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 200_000; return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 200_000;
} }
export function parseContextWindowTokens(value: string): number {
const match = /^(\d+(?:\.\d+)?)\s*([km]?)$/i.exec(value.trim());
if (!match) return NaN;
const exponent = { k: 3, m: 6 }[match[2].toLowerCase()] ?? 0;
const tokens = Number(`${match[1]}e${exponent}`);
return Number.isSafeInteger(tokens) && tokens > 0 ? tokens : NaN;
}
export function formatContextWindowInput(tokens: number): string {
if (!Number.isFinite(tokens)) return "";
if (tokens % 1_000_000 === 0) return `${tokens / 1_000_000}m`;
if (tokens % 1_000 === 0) return `${tokens / 1_000}k`;
return String(tokens);
}
function settingsProviderRow( function settingsProviderRow(
payload: SettingsPayload, payload: SettingsPayload,
provider: string | null | undefined, provider: string | null | undefined,
+2
View File
@@ -465,6 +465,8 @@
"presetNamePlaceholder": "e.g. Fast writing", "presetNamePlaceholder": "e.g. Fast writing",
"advancedOptions": "Advanced options", "advancedOptions": "Advanced options",
"advancedSummary": "Context {{context}} · Max {{max}} tokens", "advancedSummary": "Context {{context}} · Max {{max}} tokens",
"contextWindowHint": "{{tokens}} tokens",
"contextWindowError": "Enter a positive token count, such as 200k, 1m, or 131072.",
"maxTokens": "Max output tokens", "maxTokens": "Max output tokens",
"temperature": "Temperature", "temperature": "Temperature",
"reasoningEffort": "Reasoning effort", "reasoningEffort": "Reasoning effort",
+2
View File
@@ -581,6 +581,8 @@
"presetNamePlaceholder": "p. ej., Escritura rápida", "presetNamePlaceholder": "p. ej., Escritura rápida",
"advancedOptions": "Opciones avanzadas", "advancedOptions": "Opciones avanzadas",
"advancedSummary": "Contexto {{context}} · Máx. {{max}} tokens", "advancedSummary": "Contexto {{context}} · Máx. {{max}} tokens",
"contextWindowHint": "{{tokens}} tokens",
"contextWindowError": "Introduce una cantidad positiva de tokens, como 200k, 1m o 131072.",
"maxTokens": "Máx. tokens de salida", "maxTokens": "Máx. tokens de salida",
"temperature": "Temperatura", "temperature": "Temperatura",
"reasoningEffort": "Esfuerzo de razonamiento", "reasoningEffort": "Esfuerzo de razonamiento",
+2
View File
@@ -581,6 +581,8 @@
"presetNamePlaceholder": "p. ex. Rédaction rapide", "presetNamePlaceholder": "p. ex. Rédaction rapide",
"advancedOptions": "Options avancées", "advancedOptions": "Options avancées",
"advancedSummary": "Contexte {{context}} · Max. {{max}} tokens", "advancedSummary": "Contexte {{context}} · Max. {{max}} tokens",
"contextWindowHint": "{{tokens}} tokens",
"contextWindowError": "Saisissez un nombre positif de tokens, par exemple 200k, 1m ou 131072.",
"maxTokens": "Tokens de sortie max.", "maxTokens": "Tokens de sortie max.",
"temperature": "Température", "temperature": "Température",
"reasoningEffort": "Effort de raisonnement", "reasoningEffort": "Effort de raisonnement",
+2
View File
@@ -581,6 +581,8 @@
"presetNamePlaceholder": "mis. Menulis cepat", "presetNamePlaceholder": "mis. Menulis cepat",
"advancedOptions": "Opsi lanjutan", "advancedOptions": "Opsi lanjutan",
"advancedSummary": "Konteks {{context}} · Maks. {{max}} token", "advancedSummary": "Konteks {{context}} · Maks. {{max}} token",
"contextWindowHint": "{{tokens}} token",
"contextWindowError": "Masukkan jumlah token positif, seperti 200k, 1m, atau 131072.",
"maxTokens": "Maks. token keluaran", "maxTokens": "Maks. token keluaran",
"temperature": "Temperatur", "temperature": "Temperatur",
"reasoningEffort": "Upaya penalaran", "reasoningEffort": "Upaya penalaran",
+2
View File
@@ -581,6 +581,8 @@
"presetNamePlaceholder": "例:文章作成用", "presetNamePlaceholder": "例:文章作成用",
"advancedOptions": "詳細オプション", "advancedOptions": "詳細オプション",
"advancedSummary": "コンテキスト {{context}} · 最大 {{max}} トークン", "advancedSummary": "コンテキスト {{context}} · 最大 {{max}} トークン",
"contextWindowHint": "{{tokens}} トークン",
"contextWindowError": "200k、1m、131072 など、正のトークン数を入力してください。",
"maxTokens": "最大出力トークン", "maxTokens": "最大出力トークン",
"temperature": "温度", "temperature": "温度",
"reasoningEffort": "推論の強度", "reasoningEffort": "推論の強度",
+2
View File
@@ -581,6 +581,8 @@
"presetNamePlaceholder": "예: 빠른 작성", "presetNamePlaceholder": "예: 빠른 작성",
"advancedOptions": "고급 옵션", "advancedOptions": "고급 옵션",
"advancedSummary": "컨텍스트 {{context}} · 최대 {{max}} 토큰", "advancedSummary": "컨텍스트 {{context}} · 최대 {{max}} 토큰",
"contextWindowHint": "{{tokens}} 토큰",
"contextWindowError": "200k, 1m, 131072처럼 양수 토큰 수를 입력하세요.",
"maxTokens": "최대 출력 토큰", "maxTokens": "최대 출력 토큰",
"temperature": "온도", "temperature": "온도",
"reasoningEffort": "추론 강도", "reasoningEffort": "추론 강도",
+2
View File
@@ -279,6 +279,8 @@
"presetNamePlaceholder": "ex.: Escrita rápida", "presetNamePlaceholder": "ex.: Escrita rápida",
"advancedOptions": "Opções avançadas", "advancedOptions": "Opções avançadas",
"advancedSummary": "Contexto {{context}} · Máx. {{max}} tokens", "advancedSummary": "Contexto {{context}} · Máx. {{max}} tokens",
"contextWindowHint": "{{tokens}} tokens",
"contextWindowError": "Insira uma quantidade positiva de tokens, como 200k, 1m ou 131072.",
"maxTokens": "Máx. de tokens de saída", "maxTokens": "Máx. de tokens de saída",
"temperature": "Temperatura", "temperature": "Temperatura",
"reasoningEffort": "Esforço de raciocínio", "reasoningEffort": "Esforço de raciocínio",
+2
View File
@@ -581,6 +581,8 @@
"presetNamePlaceholder": "ví dụ: Viết nhanh", "presetNamePlaceholder": "ví dụ: Viết nhanh",
"advancedOptions": "Tùy chọn nâng cao", "advancedOptions": "Tùy chọn nâng cao",
"advancedSummary": "Ngữ cảnh {{context}} · Tối đa {{max}} token", "advancedSummary": "Ngữ cảnh {{context}} · Tối đa {{max}} token",
"contextWindowHint": "{{tokens}} token",
"contextWindowError": "Nhập số lượng token dương, chẳng hạn 200k, 1m hoặc 131072.",
"maxTokens": "Token đầu ra tối đa", "maxTokens": "Token đầu ra tối đa",
"temperature": "Nhiệt độ", "temperature": "Nhiệt độ",
"reasoningEffort": "Mức suy luận", "reasoningEffort": "Mức suy luận",
+2
View File
@@ -465,6 +465,8 @@
"presetNamePlaceholder": "例如:快速写作", "presetNamePlaceholder": "例如:快速写作",
"advancedOptions": "高级选项", "advancedOptions": "高级选项",
"advancedSummary": "上下文 {{context}} · 输出上限 {{max}} Token", "advancedSummary": "上下文 {{context}} · 输出上限 {{max}} Token",
"contextWindowHint": "{{tokens}} Token",
"contextWindowError": "请输入正数 Token 数量,例如 200k、1m 或 131072。",
"maxTokens": "输出 Token 上限", "maxTokens": "输出 Token 上限",
"temperature": "温度", "temperature": "温度",
"reasoningEffort": "推理强度", "reasoningEffort": "推理强度",
+2
View File
@@ -581,6 +581,8 @@
"presetNamePlaceholder": "例如:快速寫作", "presetNamePlaceholder": "例如:快速寫作",
"advancedOptions": "進階選項", "advancedOptions": "進階選項",
"advancedSummary": "上下文 {{context}} · 輸出上限 {{max}} Token", "advancedSummary": "上下文 {{context}} · 輸出上限 {{max}} Token",
"contextWindowHint": "{{tokens}} Token",
"contextWindowError": "請輸入正數 Token 數量,例如 200k、1m 或 131072。",
"maxTokens": "輸出 Token 上限", "maxTokens": "輸出 Token 上限",
"temperature": "溫度", "temperature": "溫度",
"reasoningEffort": "推理強度", "reasoningEffort": "推理強度",
+36 -5
View File
@@ -283,17 +283,48 @@ describe("Settings models", () => {
expect(await screen.findByText("Context window")).toBeInTheDocument(); expect(await screen.findByText("Context window")).toBeInTheDocument();
expect(screen.getByText("Temperature")).toBeInTheDocument(); expect(screen.getByText("Temperature")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "64K" })).toBeInTheDocument(); expect(screen.getByRole("textbox", { name: "Context window" })).toHaveValue("200k");
expect(screen.getByRole("button", { name: "200K" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "256K" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "500K" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "1M" })).toBeInTheDocument();
const reasoningEffort = screen.getByLabelText("Reasoning effort"); const reasoningEffort = screen.getByLabelText("Reasoning effort");
expect(reasoningEffort).toHaveProperty("type", "text"); expect(reasoningEffort).toHaveProperty("type", "text");
fireEvent.change(reasoningEffort, { target: { value: "provider-native-mode" } }); fireEvent.change(reasoningEffort, { target: { value: "provider-native-mode" } });
expect(reasoningEffort).toHaveValue("provider-native-mode"); expect(reasoningEffort).toHaveValue("provider-native-mode");
}); });
it.each([["128000", 128000], ["131072", 131072], ["272k", 272000], ["256K", 256000], ["1.5m", 1500000], ["1.001k", 1001]] as const)("saves a custom context budget (%s)", async (input, tokens) => {
const payload = settingsPayload();
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>(() => {})));
requestMutationMock.mockResolvedValue({
...payload,
model_presets: payload.model_presets.map((preset) => ({ ...preset, context_window_tokens: tokens })),
});
renderSettingsView({ initialSection: "models", initialSettings: payload });
await togglePresetEditor();
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
fireEvent.change(screen.getByRole("textbox", { name: "Context window" }), {
target: { value: input },
});
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", expect.objectContaining({ context_window_tokens: tokens }), expect.any(Number),
));
expect(screen.getByRole("textbox", { name: "Context window" })).toHaveValue(input);
});
it.each(["", "0", "-1", "1.5", "abc", "2ki", "0.0001k", "9007199254740992"])("keeps invalid context input unsaved (%s)", async (value) => {
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>(() => {})));
renderSettingsView({ initialSection: "models", initialSettings: settingsPayload() });
await togglePresetEditor();
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
const input = screen.getByRole("textbox", { name: "Context window" });
fireEvent.change(input, { target: { value } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
expect(input).toHaveAttribute("aria-invalid", "true");
expect(input).toHaveAccessibleDescription("Enter a positive token count, such as 200k, 1m, or 131072.");
await new Promise((resolve) => setTimeout(resolve, 750));
expect(requestMutationMock).not.toHaveBeenCalled();
expect(input).toHaveValue(value);
});
it("opens the preset editor in a dialog and protects the primary preset", async () => { it("opens the preset editor in a dialog and protects the primary preset", async () => {
vi.stubGlobal( vi.stubGlobal(
"fetch", "fetch",