perf(webui): streamline model preset saves (#6631)
* perf(webui): streamline model preset saves * fix(webui): type optional settings usage payload
This commit is contained in:
1 parent
3c61bcfdf0
commit
28d73b6942
10 files changed
+174
-59
No files matched your search
@@ -29,6 +29,7 @@ UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
|
||||
CONTEXT_GRAPH_REFERENCES_CAPABILITY = "webui.context-graph.references.v1"
|
||||
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
|
||||
SANDBOX_SETTINGS_CAPABILITY = "webui.sandbox-settings.v1"
|
||||
MODEL_PRESET_SAVE_CAPABILITY = "webui.model-preset-save.v1"
|
||||
|
||||
|
||||
class Compatibility(TypedDict):
|
||||
@@ -49,7 +50,7 @@ def webui_contract() -> dict[str, object]:
|
||||
UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
|
||||
UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
|
||||
PROMPT_NAVIGATION_CAPABILITY, CONTEXT_GRAPH_REFERENCES_CAPABILITY,
|
||||
SANDBOX_SETTINGS_CAPABILITY,
|
||||
SANDBOX_SETTINGS_CAPABILITY, MODEL_PRESET_SAVE_CAPABILITY,
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -161,6 +161,7 @@ def settings_payload(
|
||||
restart_required_sections: list[str] | None = None,
|
||||
apply_state: dict[str, Any] | None = None,
|
||||
config_path: Path | None = None,
|
||||
include_usage: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
config = _load_settings_config(config_path)
|
||||
payload: dict[str, Any] = {
|
||||
@@ -176,6 +177,7 @@ def settings_payload(
|
||||
config,
|
||||
config_path=_settings_config_path(config_path),
|
||||
version=__version__,
|
||||
include_usage=include_usage,
|
||||
),
|
||||
"requires_restart": requires_restart,
|
||||
}
|
||||
@@ -223,8 +225,12 @@ def create_model_configuration(
|
||||
query,
|
||||
oauth_status=_oauth_provider_status,
|
||||
)
|
||||
if _query_first(query, "append_to_order") == "true":
|
||||
models.append_model_call_order(config, name, oauth_status=_oauth_provider_status)
|
||||
_save_settings_config(config, config_path)
|
||||
payload = settings_payload(config_path=config_path)
|
||||
payload = settings_payload(
|
||||
config_path=config_path, include_usage=_query_first(query, "include_usage") != "false",
|
||||
)
|
||||
payload["created_model_preset"] = name
|
||||
return payload
|
||||
|
||||
@@ -259,7 +265,9 @@ def update_model_configuration(
|
||||
raise
|
||||
else:
|
||||
_save_settings_config(config, config_path)
|
||||
return settings_payload(config_path=config_path)
|
||||
return settings_payload(
|
||||
config_path=config_path, include_usage=_query_first(query, "include_usage") != "false",
|
||||
)
|
||||
|
||||
|
||||
def update_model_call_order(
|
||||
|
||||
@@ -1483,6 +1483,19 @@ def update_model_call_order(
|
||||
raise WebUISettingsError("model call order must contain at least one preset")
|
||||
|
||||
normalized_order = [cast(str, name).strip() for name in cast(list[object], order)]
|
||||
return _set_model_call_order(config, normalized_order, oauth_status=oauth_status)
|
||||
|
||||
|
||||
def append_model_call_order(config: Config, name: str, *, oauth_status: OAuthStatusReader) -> None:
|
||||
order, _ = _model_call_order_state(config)
|
||||
if name not in order:
|
||||
order.append(name)
|
||||
_set_model_call_order(config, order, oauth_status=oauth_status)
|
||||
|
||||
|
||||
def _set_model_call_order(
|
||||
config: Config, normalized_order: list[str], *, oauth_status: OAuthStatusReader,
|
||||
) -> bool:
|
||||
unknown = [name for name in normalized_order if name not in config.model_presets]
|
||||
if unknown:
|
||||
raise WebUISettingsError(f"unknown model preset: {unknown[0]}")
|
||||
|
||||
@@ -10,7 +10,7 @@ import time
|
||||
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TypedDict, cast
|
||||
from typing import TYPE_CHECKING, Any, NotRequired, TypedDict, cast
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import httpx
|
||||
@@ -100,7 +100,7 @@ class GatewayEnvironmentPayload(TypedDict):
|
||||
class SystemSettingsPayload(TypedDict):
|
||||
runtime_config: dict[str, Any]
|
||||
runtime: dict[str, Any]
|
||||
usage: dict[str, Any]
|
||||
usage: NotRequired[dict[str, Any]]
|
||||
advanced: dict[str, Any]
|
||||
version: dict[str, Any]
|
||||
environment: GatewayEnvironmentPayload
|
||||
@@ -136,6 +136,7 @@ def system_settings_payload(
|
||||
*,
|
||||
config_path: Path,
|
||||
version: str,
|
||||
include_usage: bool = True,
|
||||
) -> SystemSettingsPayload:
|
||||
defaults = config.agents.defaults
|
||||
exec_config = config.tools.exec
|
||||
@@ -143,7 +144,7 @@ def system_settings_payload(
|
||||
restrict_to_workspace=config.tools.restrict_to_workspace,
|
||||
workspace=config.workspace_path,
|
||||
)
|
||||
return {
|
||||
payload: SystemSettingsPayload = {
|
||||
"runtime_config": runtime_config_payload(config),
|
||||
"runtime": {
|
||||
"config_path": str(config_path.expanduser()),
|
||||
@@ -159,7 +160,6 @@ def system_settings_payload(
|
||||
},
|
||||
"unified_session": defaults.unified_session,
|
||||
},
|
||||
"usage": llm_usage_payload(timezone_name=defaults.timezone),
|
||||
"advanced": {
|
||||
"restrict_to_workspace": config.tools.restrict_to_workspace,
|
||||
"workspace_sandbox": sandbox_status.as_dict(),
|
||||
@@ -181,6 +181,9 @@ def system_settings_payload(
|
||||
},
|
||||
"docs": docs_payload(version),
|
||||
}
|
||||
if include_usage:
|
||||
payload["usage"] = llm_usage_payload(timezone_name=defaults.timezone)
|
||||
return payload
|
||||
|
||||
|
||||
def settings_usage_payload(config: Config) -> dict[str, Any]:
|
||||
|
||||
@@ -216,6 +216,66 @@ def _dynamic_provider_config(
|
||||
return Config.model_validate(raw_config)
|
||||
|
||||
|
||||
def test_create_model_configuration_appends_atomically_without_querying_usage(
|
||||
tmp_path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.openai.api_key = "sk-test"
|
||||
config.model_presets["primary"] = ModelPresetConfig(model="openai/gpt-4o", provider="openai")
|
||||
config.agents.defaults.model_preset = "primary"
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_system.llm_usage_payload",
|
||||
lambda **_kwargs: pytest.fail("model save must not query usage"),
|
||||
)
|
||||
query = {
|
||||
"name": ["Writer"], "provider": ["openai"], "model": ["openai/gpt-4o-mini"],
|
||||
"append_to_order": ["true"], "include_usage": ["false"],
|
||||
}
|
||||
result = create_model_configuration(query, config_path=config_path)
|
||||
assert result["model_call_order"] == ["primary", "Writer"]
|
||||
assert "usage" not in result
|
||||
assert load_config(config_path).agents.defaults.fallback_models == ["Writer"]
|
||||
updated = update_model_configuration(
|
||||
{"name": ["Writer"], "temperature": ["0.5"], "include_usage": ["false"]},
|
||||
config_path=config_path,
|
||||
)
|
||||
assert updated["model_call_order"] == ["primary", "Writer"]
|
||||
assert "usage" not in updated
|
||||
|
||||
|
||||
def test_create_and_append_first_preset_is_primary_once(tmp_path) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.openai.api_key = "sk-test"
|
||||
save_config(config, config_path)
|
||||
result = create_model_configuration(
|
||||
{"name": ["Writer"], "provider": ["openai"], "model": ["openai/gpt-4o-mini"],
|
||||
"append_to_order": ["true"]}, config_path=config_path,
|
||||
)
|
||||
assert result["model_call_order"] == ["Writer"]
|
||||
saved = load_config(config_path)
|
||||
assert saved.agents.defaults.model_preset == "Writer"
|
||||
assert saved.agents.defaults.fallback_models == []
|
||||
|
||||
|
||||
def test_create_and_append_does_not_persist_when_legacy_order_needs_migration(tmp_path) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.openai.api_key = "sk-test"
|
||||
config.agents.defaults.model = "openai/gpt-4o"
|
||||
config.agents.defaults.provider = "openai"
|
||||
save_config(config, config_path)
|
||||
before = config_path.read_bytes()
|
||||
with pytest.raises(WebUISettingsError, match="convert"):
|
||||
create_model_configuration(
|
||||
{"name": ["Writer"], "provider": ["openai"], "model": ["openai/gpt-4o-mini"],
|
||||
"append_to_order": ["true"]}, config_path=config_path,
|
||||
)
|
||||
assert config_path.read_bytes() == before
|
||||
|
||||
|
||||
def test_create_model_configuration_accepts_legacy_label_without_changing_call_order(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
@@ -64,6 +64,7 @@ interface ModelSettingsActionsOptions {
|
||||
setError: Dispatch<SetStateAction<string | null>>;
|
||||
onModelNameChange: (modelName: string | null) => void;
|
||||
remoteBrowserAccess: boolean;
|
||||
optimizedPresetSave: boolean;
|
||||
closeProviderOAuthFlow: (cancelPending?: boolean) => void;
|
||||
installCapabilities: (names: string[]) => Promise<boolean>;
|
||||
configuredModelProviderOptions: Array<{ name: string; label: string }>;
|
||||
@@ -80,6 +81,7 @@ export function useModelSettingsActions({
|
||||
setError,
|
||||
onModelNameChange,
|
||||
remoteBrowserAccess,
|
||||
optimizedPresetSave,
|
||||
closeProviderOAuthFlow,
|
||||
installCapabilities,
|
||||
configuredModelProviderOptions,
|
||||
@@ -199,7 +201,7 @@ export function useModelSettingsActions({
|
||||
setModelPresetNameError(null);
|
||||
setModelConfigurationSaving(true);
|
||||
try {
|
||||
const payload = await createModelConfiguration(client, {
|
||||
const result = await createModelConfiguration(client, {
|
||||
name,
|
||||
provider,
|
||||
model,
|
||||
@@ -213,27 +215,22 @@ export function useModelSettingsActions({
|
||||
extraQuery: form.extraQuery,
|
||||
extraBody: form.extraBody,
|
||||
} : {}),
|
||||
});
|
||||
}, optimizedPresetSave);
|
||||
let payload: SettingsPayload = { ...result, usage: result.usage ?? latestSettings.current?.usage ?? settings.usage };
|
||||
const createdPreset = payload.created_model_preset;
|
||||
const nextOrder = createdPreset ? [...modelCallOrder, createdPreset] : null;
|
||||
if (!optimizedPresetSave && createdPreset) {
|
||||
applyPayload(payload, { preserveCapabilityForms: true });
|
||||
setForm(agentDraftFromPayload(payload, createdPreset));
|
||||
setModelPresetEditingName(createdPreset);
|
||||
payload = await updateModelCallOrder(client, [...modelCallOrder, createdPreset]);
|
||||
}
|
||||
applyPayload(payload, { preserveCapabilityForms: true });
|
||||
if (createdPreset) {
|
||||
setForm(agentDraftFromPayload(payload, createdPreset));
|
||||
setModelPresetEditingName(createdPreset);
|
||||
}
|
||||
|
||||
let finalPayload = payload;
|
||||
if (nextOrder) {
|
||||
const orderedPayload = await updateModelCallOrder(client, nextOrder);
|
||||
applyPayload(orderedPayload, { preserveCapabilityForms: true });
|
||||
finalPayload = orderedPayload;
|
||||
}
|
||||
if (createdPreset) {
|
||||
setForm(agentDraftFromPayload(finalPayload, createdPreset));
|
||||
setModelPresetEditingName(createdPreset);
|
||||
}
|
||||
modelPresetBeforeCreateRef.current = null;
|
||||
onModelNameChange(finalPayload.agent.model || null);
|
||||
onModelNameChange(payload.agent.model || null);
|
||||
setModelPresetNameError(null);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
@@ -259,7 +256,7 @@ export function useModelSettingsActions({
|
||||
const reasoningEffort = form.reasoningEffort || null;
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = await updateModelConfiguration(client, {
|
||||
const result = await updateModelConfiguration(client, {
|
||||
name: selectedPreset.name,
|
||||
newName: nameChanged ? nextName : undefined,
|
||||
model: form.model !== selectedPreset.model ? form.model : undefined,
|
||||
@@ -282,7 +279,8 @@ export function useModelSettingsActions({
|
||||
extraQuery: form.extraQuery !== providerJsonValue(selectedPreset.extra_query) ? form.extraQuery : undefined,
|
||||
extraBody: form.extraBody !== providerJsonValue(selectedPreset.extra_body) ? form.extraBody : undefined,
|
||||
} : {}),
|
||||
});
|
||||
}, optimizedPresetSave);
|
||||
const payload = { ...result, usage: result.usage ?? latestSettings.current?.usage ?? settings.usage };
|
||||
latestSettings.current = payload;
|
||||
editTarget.name = nextName;
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
@@ -303,12 +301,14 @@ export function useModelSettingsActions({
|
||||
};
|
||||
|
||||
const saveModelRequestSettings = async (values: Partial<RequestParameterDraft>) => {
|
||||
if (!settings) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = await updateModelConfiguration(client, {
|
||||
const result = await updateModelConfiguration(client, {
|
||||
name: modelPresetEditingName,
|
||||
...values,
|
||||
});
|
||||
}, optimizedPresetSave);
|
||||
const payload = { ...result, usage: result.usage ?? latestSettings.current?.usage ?? settings.usage };
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setForm((current) => current === form ? agentDraftFromPayload(payload, modelPresetEditingName) : current);
|
||||
setError(null);
|
||||
|
||||
@@ -82,7 +82,7 @@ export function useSettingsController({
|
||||
onNativeEngineRestart,
|
||||
}: SettingsControllerOptions) {
|
||||
const { t } = useTranslation();
|
||||
const { client, getToken, token } = useClient();
|
||||
const { client, getToken, token, webuiCapabilities } = useClient();
|
||||
const pageVisible = usePageVisibility();
|
||||
const remoteBrowserAccess =
|
||||
typeof window !== "undefined" && !isLoopbackHost(window.location.hostname);
|
||||
@@ -433,6 +433,7 @@ export function useSettingsController({
|
||||
setError,
|
||||
onModelNameChange,
|
||||
remoteBrowserAccess,
|
||||
optimizedPresetSave: webuiCapabilities.includes("webui.model-preset-save.v1"),
|
||||
closeProviderOAuthFlow,
|
||||
installCapabilities,
|
||||
configuredModelProviderOptions,
|
||||
|
||||
@@ -1397,14 +1397,16 @@ function modelGenerationSettingsPayload(
|
||||
export async function createModelConfiguration(
|
||||
transport: WebUIMutationTransport,
|
||||
configuration: ModelConfigurationCreate,
|
||||
): Promise<SettingsPayload> {
|
||||
return mutation<SettingsPayload>(
|
||||
optimized = false,
|
||||
): Promise<Omit<SettingsPayload, "usage"> & Partial<Pick<SettingsPayload, "usage">>> {
|
||||
return mutation<Omit<SettingsPayload, "usage">>(
|
||||
transport,
|
||||
"settings.model_configuration.create",
|
||||
{
|
||||
name: configuration.name,
|
||||
provider: configuration.provider,
|
||||
model: configuration.model,
|
||||
...(optimized ? { append_to_order: true, include_usage: false } : {}),
|
||||
...modelGenerationSettingsPayload(configuration),
|
||||
},
|
||||
);
|
||||
@@ -1413,12 +1415,14 @@ export async function createModelConfiguration(
|
||||
export async function updateModelConfiguration(
|
||||
transport: WebUIMutationTransport,
|
||||
configuration: ModelConfigurationUpdate,
|
||||
): Promise<SettingsPayload> {
|
||||
return mutation<SettingsPayload>(
|
||||
optimized = false,
|
||||
): Promise<Omit<SettingsPayload, "usage"> & Partial<Pick<SettingsPayload, "usage">>> {
|
||||
return mutation<Omit<SettingsPayload, "usage">>(
|
||||
transport,
|
||||
"settings.model_configuration.update",
|
||||
{
|
||||
name: configuration.name,
|
||||
...(optimized ? { include_usage: false } : {}),
|
||||
...(configuration.newName !== undefined ? { new_name: configuration.newName } : {}),
|
||||
...(configuration.provider !== undefined ? { provider: configuration.provider } : {}),
|
||||
...(configuration.model !== undefined ? { model: configuration.model } : {}),
|
||||
|
||||
@@ -716,7 +716,7 @@ describe("webui API helpers", () => {
|
||||
contextWindowTokens: 128000,
|
||||
temperature: 0.4,
|
||||
reasoningEffort: "high",
|
||||
});
|
||||
}, true);
|
||||
|
||||
expect(requestMutation).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.create",
|
||||
@@ -724,6 +724,8 @@ describe("webui API helpers", () => {
|
||||
name: "Fast writing",
|
||||
provider: "openai",
|
||||
model: "openai/gpt-4.1-mini",
|
||||
append_to_order: true,
|
||||
include_usage: false,
|
||||
max_tokens: 4096,
|
||||
context_window_tokens: 128000,
|
||||
temperature: 0.4,
|
||||
@@ -743,12 +745,13 @@ describe("webui API helpers", () => {
|
||||
contextWindowTokens: 65536,
|
||||
temperature: 0,
|
||||
reasoningEffort: null,
|
||||
});
|
||||
}, true);
|
||||
|
||||
expect(requestMutation).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update",
|
||||
{
|
||||
name: "codex",
|
||||
include_usage: false,
|
||||
new_name: "Codex",
|
||||
provider: "openai_codex",
|
||||
model: "openai-codex/gpt-5.5",
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import type { ProviderModelsPayload, SettingsPayload } from "@/lib/types";
|
||||
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
|
||||
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView as renderSettingsViewBase, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
|
||||
|
||||
const renderSettingsView: typeof renderSettingsViewBase = (options = {}) => renderSettingsViewBase({
|
||||
webuiCapabilities: ["webui.model-preset-save.v1"], ...options,
|
||||
});
|
||||
|
||||
|
||||
function settingsPayloadWithBackup() {
|
||||
@@ -140,14 +144,14 @@ describe("Settings models", () => {
|
||||
expect(within(editor).getByRole("textbox")).toHaveValue('{"X-Route":"preset"}');
|
||||
fireEvent.click(within(editor).getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", extra_headers: '{"X-Route":"preset"}' }, 20_000,
|
||||
"settings.model_configuration.update", { include_usage: false, name: "primary", extra_headers: '{"X-Route":"preset"}' }, 20_000,
|
||||
));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Headers Entries: 1 Edit" }));
|
||||
editor = screen.getByRole("dialog", { name: "Headers" });
|
||||
fireEvent.change(within(editor).getByRole("textbox", { name: "Headers" }), { target: { value: "" } });
|
||||
fireEvent.click(within(editor).getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", extra_headers: "" }, 20_000,
|
||||
"settings.model_configuration.update", { include_usage: false, name: "primary", extra_headers: "" }, 20_000,
|
||||
));
|
||||
expect(await screen.findByRole("button", { name: "Headers Use provider settings Edit" })).toBeEnabled();
|
||||
});
|
||||
@@ -182,7 +186,7 @@ describe("Settings models", () => {
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_configuration.update",
|
||||
{ name: "primary", api: { supported_apis: ["responses"], preferred_api: "responses" } },
|
||||
{ include_usage: false, name: "primary", api: { supported_apis: ["responses"], preferred_api: "responses" } },
|
||||
20_000,
|
||||
));
|
||||
await waitFor(() => expect(presetSaveButton()).toBeDisabled());
|
||||
@@ -194,7 +198,7 @@ describe("Settings models", () => {
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_configuration.update",
|
||||
{ name: "primary", api: { supported_apis: ["responses", "chat_completions"], preferred_api: "responses" } },
|
||||
{ include_usage: false, name: "primary", api: { supported_apis: ["responses", "chat_completions"], preferred_api: "responses" } },
|
||||
20_000,
|
||||
));
|
||||
await waitFor(() => expect(presetSaveButton()).toBeDisabled());
|
||||
@@ -211,7 +215,7 @@ describe("Settings models", () => {
|
||||
await returnToPresetEditor();
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", api: null }, 20_000,
|
||||
"settings.model_configuration.update", { include_usage: false, name: "primary", api: null }, 20_000,
|
||||
));
|
||||
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/model-api?"))).toBe(false);
|
||||
});
|
||||
@@ -243,7 +247,7 @@ describe("Settings models", () => {
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_configuration.update",
|
||||
{ name: "primary", api: { supported_apis: ["anthropic_messages"], preferred_api: "anthropic_messages" } },
|
||||
{ include_usage: false, name: "primary", api: { supported_apis: ["anthropic_messages"], preferred_api: "anthropic_messages" } },
|
||||
20_000,
|
||||
));
|
||||
await waitFor(() => expect(presetSaveButton()).toBeDisabled());
|
||||
@@ -294,7 +298,7 @@ describe("Settings models", () => {
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", {
|
||||
name: "primary",
|
||||
include_usage: false, name: "primary",
|
||||
api: { supported_apis: ["responses"], preferred_api: "responses" },
|
||||
}, 20_000,
|
||||
));
|
||||
@@ -342,7 +346,7 @@ describe("Settings models", () => {
|
||||
await act(async () => { finishHigh(jsonResponse({ provider: "openai", api: "responses" })); });
|
||||
expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)");
|
||||
expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", reasoning_effort: "high" }, 20_000,
|
||||
"settings.model_configuration.update", { include_usage: false, name: "primary", reasoning_effort: "high" }, 20_000,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -371,7 +375,7 @@ describe("Settings models", () => {
|
||||
await returnToPresetEditor();
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", reasoning_effort: "high" }, 20_000,
|
||||
"settings.model_configuration.update", { include_usage: false, name: "primary", reasoning_effort: "high" }, 20_000,
|
||||
));
|
||||
});
|
||||
|
||||
@@ -424,7 +428,7 @@ describe("Settings models", () => {
|
||||
await returnToPresetEditor();
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", new_name: "Renamed" }, 20_000,
|
||||
"settings.model_configuration.update", { include_usage: false, name: "primary", new_name: "Renamed" }, 20_000,
|
||||
));
|
||||
});
|
||||
|
||||
@@ -558,7 +562,7 @@ describe("Settings models", () => {
|
||||
await waitFor(() => {
|
||||
expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update",
|
||||
{ name: "Fast", temperature: 0.4 },
|
||||
{ include_usage: false, name: "Fast", temperature: 0.4 },
|
||||
20_000,
|
||||
);
|
||||
});
|
||||
@@ -591,7 +595,7 @@ describe("Settings models", () => {
|
||||
await waitFor(() => {
|
||||
expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update",
|
||||
{ name: "primary", new_name: "Codex" },
|
||||
{ include_usage: false, name: "primary", new_name: "Codex" },
|
||||
20_000,
|
||||
);
|
||||
});
|
||||
@@ -1178,8 +1182,14 @@ describe("Settings models", () => {
|
||||
expect(requestMutationMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("appends a new model preset to the call order immediately", async () => {
|
||||
const { payload } = settingsPayloadWithBackup();
|
||||
it.each([true, false])("appends a new model preset with optimized host support: %s", async (optimized) => {
|
||||
const { payload: base } = settingsPayloadWithBackup();
|
||||
const payload: SettingsPayload = { ...base, usage: {
|
||||
days: [], total_tokens: 1500, total_tokens_30d: 1500, total_tokens_365d: 1500,
|
||||
peak_day_tokens: 1500, current_streak_days: 1, longest_streak_days: 1,
|
||||
active_days_30d: 1, requests_30d: 2,
|
||||
} };
|
||||
const onSettingsChange = vi.fn();
|
||||
const writerPreset = {
|
||||
...payload.model_presets[0],
|
||||
name: "Writer",
|
||||
@@ -1193,12 +1203,12 @@ describe("Settings models", () => {
|
||||
...payload,
|
||||
model_presets: [...payload.model_presets, writerPreset],
|
||||
created_model_preset: writerPreset.name,
|
||||
model_call_order: optimized ? ["primary", "backup", "Writer"] : ["primary", "backup"],
|
||||
};
|
||||
const orderedPayload: SettingsPayload = {
|
||||
...createdPayload,
|
||||
model_call_order: ["primary", "backup", "Writer"],
|
||||
created_model_preset: undefined,
|
||||
...createdPayload, model_call_order: ["primary", "backup", "Writer"],
|
||||
};
|
||||
if (optimized) delete createdPayload.usage;
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url === "/api/settings") return jsonResponse(payload);
|
||||
@@ -1211,11 +1221,11 @@ describe("Settings models", () => {
|
||||
return { ok: false, status: 404, json: async () => ({}) } as Response;
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
requestMutationMock
|
||||
.mockResolvedValueOnce(createdPayload)
|
||||
.mockResolvedValueOnce(orderedPayload);
|
||||
requestMutationMock.mockResolvedValueOnce(createdPayload);
|
||||
if (!optimized) requestMutationMock.mockResolvedValueOnce(orderedPayload);
|
||||
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload, onSettingsChange,
|
||||
webuiCapabilities: optimized ? ["webui.model-preset-save.v1"] : [] });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
@@ -1241,13 +1251,25 @@ describe("Settings models", () => {
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_call_order.update",
|
||||
{ order: ["primary", "backup", "Writer"] },
|
||||
expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.create",
|
||||
expect.objectContaining(optimized
|
||||
? { name: "Writer", append_to_order: true, include_usage: false }
|
||||
: { name: "Writer" }),
|
||||
20_000,
|
||||
);
|
||||
if (optimized) {
|
||||
expect(requestMutationMock).toHaveBeenCalledTimes(1);
|
||||
} else {
|
||||
const createCall = requestMutationMock.mock.calls.find(([action]) => action === "settings.model_configuration.create");
|
||||
expect(createCall?.[1]).not.toHaveProperty("append_to_order");
|
||||
expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_call_order.update", { order: ["primary", "backup", "Writer"] }, 20_000,
|
||||
);
|
||||
}
|
||||
});
|
||||
const writerRow = await screen.findByTestId("model-call-order-row-Writer");
|
||||
expect(onSettingsChange).toHaveBeenLastCalledWith(expect.objectContaining({ usage: payload.usage }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
expect(within(writerRow).getByRole("switch", { name: "Disable preset" })).toBeChecked();
|
||||
expect(screen.getAllByText("Writer").length).toBeGreaterThan(0);
|
||||
@@ -2248,7 +2270,7 @@ describe("Settings models", () => {
|
||||
action === "settings.model_configuration.update",
|
||||
);
|
||||
expect(saveCall).toBeDefined();
|
||||
expect(saveCall?.[1]).toEqual({ name: "primary", model: "deepseek-reasoner" });
|
||||
expect(saveCall?.[1]).toEqual({ include_usage: false, name: "primary", model: "deepseek-reasoner" });
|
||||
expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", expect.objectContaining({ reasoning_effort: "provider-native-mode" }), 20_000,
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user