From 221e12138723ca1a570d35b86ca00d46eddc614b Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:13:30 +0800 Subject: [PATCH] fix(settings): use a setup template for ShengSuanYun --- docs/configuration.md | 2 +- nanobot/config/schema.py | 1 - nanobot/providers/registry.py | 13 -- tests/providers/test_shengsuanyun_provider.py | 188 ------------------ tests/webui/test_settings_api.py | 41 ++++ .../settings/models/ProviderSearchList.tsx | 53 +++-- .../settings/models/ProviderSettings.tsx | 32 ++- .../settings/models/providerForm.ts | 11 + .../settings/shared/ModelControls.tsx | 1 - webui/src/lib/provider-brand.ts | 2 +- webui/src/lib/provider-icons.ts | 1 - webui/src/tests/provider-icon.test.tsx | 2 +- webui/src/tests/settings-providers.test.tsx | 34 +++- 13 files changed, 142 insertions(+), 239 deletions(-) delete mode 100644 tests/providers/test_shengsuanyun_provider.py diff --git a/docs/configuration.md b/docs/configuration.md index fbbab093b..6692be8df 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -304,7 +304,7 @@ A Base URL is the service address nanobot sends model requests to. Change it onl > - **Kimi Coding Plan**: Use `providers.kimiCoding` with `provider: "kimi_coding"` for Kimi's dedicated Anthropic Messages API endpoint. The endpoint requires a Claude-compatible `User-Agent`; nanobot sends `claude-code/0.1.0` by default, and you can override it with `extraHeaders.User-Agent` if your account requires a different value. > - **VolcEngine / BytePlus Coding Plan**: Subscription endpoints are configured through dedicated providers `volcengineCodingPlan` or `byteplusCodingPlan`, separate from the pay-per-use `volcengine` / `byteplus` providers. > - **OpenCode Zen / Go**: `providers.opencode` (canonical Zen), the legacy-compatible `providers.opencodeZen`, and `providers.opencodeGo` use the same `OPENCODE_API_KEY`, but route to different OpenCode gateways. These providers use OpenCode's OpenAI-compatible `chat/completions` endpoints; choose model IDs from that endpoint family. -> - **ShengSuanYun (胜算云)**: The built-in connection uses `providers.shengsuanyunRouter` and `provider: "shengsuanyun_router"`. Keep the model's namespace, for example `deepseek/deepseek-v4-flash`. Chat Completions is the default; select Responses in a preset's **Advanced options** only for a model that [ShengSuanYun lists as supporting it](https://lean.shengsuanyun.com/openai-api). Existing custom connections named `shengsuanyun` continue to work as configured. +> - **ShengSuanYun (胜算云)**: Search for **ShengSuanYun Router** in **Add provider** to prefill the [Router API URL](https://lean.shengsuanyun.com/apidocs/guides/quick-start). Enter your API key and save the custom connection. Use the full model ID, for example `deepseek/deepseek-v4-flash`. Chat Completions is the default; select Responses in a preset's **Advanced options** only for a model that supports it. > - **Zhipu Coding Plan**: If you're on Zhipu's coding plan, open the zhipu connection in **Settings → Models** and set its base URL to `https://open.bigmodel.cn/api/coding/paas/v4`. > - **Alibaba Cloud BaiLian**: The built-in `dashscope` provider already defaults to `https://dashscope.aliyuncs.com/compatible-mode/v1`; no endpoint override is needed for that service. > - **ModelScope**: The built-in `modelscope` provider already defaults to `https://api-inference.modelscope.cn/v1`; no endpoint override is needed for that service. diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index e5a8a2bfb..62db8a6f8 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -324,7 +324,6 @@ class ProvidersConfig(Base): openai: ProviderConfig = Field(default_factory=ProviderConfig) openrouter: ProviderConfig = Field(default_factory=ProviderConfig) orcarouter: ProviderConfig = Field(default_factory=ProviderConfig) - shengsuanyun_router: ProviderConfig = Field(default_factory=ProviderConfig) assemblyai: ProviderConfig = Field(default_factory=ProviderConfig) huggingface: ProviderConfig = Field(default_factory=ProviderConfig) skywork: ProviderConfig = Field(default_factory=ProviderConfig) diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.py index 4ef35bedc..f1e8c584d 100644 --- a/nanobot/providers/registry.py +++ b/nanobot/providers/registry.py @@ -281,19 +281,6 @@ PROVIDERS: tuple[ProviderSpec, ...] = ( detect_by_base_keyword="orcarouter", default_api_base="https://api.orcarouter.ai/v1", ), - # Keep the Router ID separate from existing custom connections named "shengsuanyun". - # Upstream model IDs retain their provider namespace (e.g. deepseek/model). - ProviderSpec( - name="shengsuanyun_router", - keywords=("shengsuanyun_router",), - env_key="SHENGSUANYUN_API_KEY", - request_apis=("chat_completions", "responses"), - display_name="ShengSuanYun Router", - backend="openai_compat", - is_gateway=True, - default_api_base="https://router.shengsuanyun.com/api/v1", - strip_model_prefixes=("shengsuanyun_router",), - ), # Eden AI: OpenAI-compatible gateway. Models use the "provider/model" # naming scheme (e.g. "anthropic/claude-sonnet-4-5"); the full id is sent upstream. ProviderSpec( diff --git a/tests/providers/test_shengsuanyun_provider.py b/tests/providers/test_shengsuanyun_provider.py deleted file mode 100644 index 46827f40b..000000000 --- a/tests/providers/test_shengsuanyun_provider.py +++ /dev/null @@ -1,188 +0,0 @@ -import json -from pathlib import Path - -import httpx -import pytest -from openai import AsyncOpenAI - -from nanobot.config.loader import load_config, save_config -from nanobot.config.schema import Config -from nanobot.providers.factory import make_provider -from nanobot.providers.openai_compat_provider import OpenAICompatProvider -from nanobot.providers.routing import resolve_provider_route -from nanobot.webui.settings_models import ( - create_model_configuration, - model_settings_payload, - provider_models_payload, - update_provider_settings, -) - - -def _config(model: str = "deepseek/deepseek-v4-flash") -> Config: - return Config.model_validate({ - "providers": {"shengsuanyunRouter": {"apiKey": "test-key"}}, - "agents": {"defaults": {"provider": "shengsuanyun_router", "model": model}}, - }) - - -def test_catalog_uses_gateway_credentials_and_preserves_model_ids() -> None: - def get(url: str, **kwargs: object) -> httpx.Response: - assert url == "https://router.shengsuanyun.com/api/v1/models" - assert kwargs["headers"] == { - "Accept": "application/json", "Authorization": "Bearer test-key", - } - return httpx.Response(200, json={"data": [{"id": "deepseek/deepseek-v4-flash"}]}, - request=httpx.Request("GET", url)) - - payload = provider_models_payload(_config(), {"provider": ["shengsuanyun_router"]}, http_get=get) - assert payload["status"] == "available" - assert payload["models"][0]["id"] == "deepseek/deepseek-v4-flash" - - -def test_settings_exposes_gateway_without_exposing_api_key() -> None: - payload = model_settings_payload(_config(), oauth_status=_not_signed_in) - row = next(row for row in payload["providers"] if row["name"] == "shengsuanyun_router") - assert row["configured"] is True - assert row["default_api_base"] == "https://router.shengsuanyun.com/api/v1" - assert "test-key" not in str(payload) - - -def _not_signed_in(_: object) -> dict[str, object]: - return {"configured": False, "account": None, "expires_at": None, "login_supported": False} - - -def test_existing_custom_shengsuanyun_connection_keeps_anthropic_route(tmp_path: Path) -> None: - path = tmp_path / "config.json" - path.write_text(json.dumps({ - "providers": {"shengsuanyun": { - "apiKey": "old-key", - "apiBase": "https://router.shengsuanyun.com/api", - "api": {"supportedApis": ["anthropic_messages"], "preferredApi": "anthropic_messages"}, - }}, - "agents": {"defaults": {"provider": "shengsuanyun", "model": "anthropic/claude-sonnet-4-6"}}, - }), encoding="utf-8") - - config = load_config(path) - route = resolve_provider_route(config, preset=config.resolve_preset()) - assert route.backend == "anthropic" - assert config.get_api_base() == "https://router.shengsuanyun.com/api" - row = next(item for item in model_settings_payload( - config, oauth_status=_not_signed_in, - )["providers"] if item["name"] == "shengsuanyun") - assert row["is_custom"] and row["provider_api_configurable"] - - assert update_provider_settings(config, { - "provider": ["shengsuanyun"], "api_key": ["rotated-key"], "display_name": [row["label"]], - })[0] - save_config(config, path) - reloaded = load_config(path) - assert reloaded.get_api_key() == "rotated-key" - assert resolve_provider_route(reloaded, preset=reloaded.resolve_preset()).backend == "anthropic" - - -def test_explicit_gateway_prefix_routes_even_with_another_provider_configured() -> None: - config = Config.model_validate({ - "providers": { - "shengsuanyunRouter": {"apiKey": "test-key"}, - "deepseek": {"apiKey": "other-key"}, - }, - "agents": {"defaults": {"model": "shengsuanyun_router/deepseek/deepseek-v4-flash"}}, - }) - assert config.get_provider_name(config.agents.defaults.model) == "shengsuanyun_router" - assert config.get_api_key(config.agents.defaults.model) == "test-key" - - -@pytest.mark.parametrize("model", [ - "deepseek/deepseek-v4-flash", "shengsuanyun_router/deepseek/deepseek-v4-flash", -]) -async def test_chat_and_stream_route_model_and_tools(model: str) -> None: - requests = [] - - def handler(request: httpx.Request) -> httpx.Response: - requests.append(json.loads(request.content)) - assert str(request.url) == "https://router.shengsuanyun.com/api/v1/chat/completions" - assert request.headers["Authorization"] == "Bearer test-key" - assert requests[-1]["model"] == "deepseek/deepseek-v4-flash" - assert requests[-1]["tools"][0]["function"]["name"] == "weather" - if requests[-1].get("stream"): - events = [ - {"id": "1", "object": "chat.completion.chunk", "created": 0, - "model": model, "choices": [{"index": 0, "delta": {"content": "Hello"}, - "finish_reason": None}]}, - {"id": "1", "object": "chat.completion.chunk", "created": 0, - "model": model, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}, - ] - content = "".join(f"data: {json.dumps(event)}\n\n" for event in events) + "data: [DONE]\n\n" - return httpx.Response(200, text=content, headers={"content-type": "text/event-stream"}) - return httpx.Response(200, json={ - "id": "1", "object": "chat.completion", "created": 0, "model": model, - "choices": [{"index": 0, "finish_reason": "tool_calls", "message": { - "role": "assistant", "content": None, "tool_calls": [{ - "id": "call_1", "type": "function", - "function": {"name": "weather", "arguments": '{"city":"Shanghai"}'}, - }], - }}], - }) - - provider = make_provider(_config(model)) - assert isinstance(provider, OpenAICompatProvider) - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: - provider._client = AsyncOpenAI(api_key="test-key", base_url=provider._effective_base, - http_client=http, max_retries=0) - tools = [{"type": "function", "function": {"name": "weather", "parameters": {"type": "object"}}}] - result = await provider.chat([{"role": "user", "content": "Weather?"}], tools=tools) - assert result.tool_calls[0].name == "weather" - assert result.tool_calls[0].arguments == {"city": "Shanghai"} - deltas = [] - - async def on_delta(text: str) -> None: - deltas.append(text) - - result = await provider.chat_stream([{"role": "user", "content": "Hi"}], tools=tools, - on_content_delta=on_delta) - assert result.content == "Hello" - assert deltas == ["Hello"] - assert len(requests) == 2 - - -async def test_saved_responses_preset_uses_router_with_full_model_id( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, -) -> None: - config = Config.model_validate({"providers": {"openai": {"apiKey": "other-key"}}}) - assert update_provider_settings(config, { - "provider": ["shengsuanyun_router"], "api_key": ["test-key"], - })[0] - name = create_model_configuration(config, { - "name": ["Router GPT"], - "provider": ["shengsuanyun_router"], - "model": ["openai/gpt-5.4"], - "api": ['{"supportedApis":["responses"],"preferredApi":"responses"}'], - }, oauth_status=_not_signed_in) - path = tmp_path / "config.json" - save_config(config, path) - - def handler(request: httpx.Request) -> httpx.Response: - assert str(request.url) == "https://router.shengsuanyun.com/api/v1/responses" - assert request.headers["Authorization"] == "Bearer test-key" - body = json.loads(request.content) - assert body["model"] == "openai/gpt-5.4" - assert body["input"][0]["content"][0]["text"] == "Hi" - return httpx.Response(200, json={ - "id": "resp_1", "object": "response", "status": "completed", - "output": [{ - "id": "msg_1", "type": "message", "role": "assistant", "status": "completed", - "content": [{"type": "output_text", "text": "Hello", "annotations": []}], - }], - }) - - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: - def create_client(**kwargs): - return AsyncOpenAI(**(kwargs | {"http_client": http})) - - monkeypatch.setattr("nanobot.providers.openai_compat_provider.AsyncOpenAI", create_client) - provider = make_provider(load_config(path), preset_name=name) - try: - response = await provider.chat([{"role": "user", "content": "Hi"}]) - assert response.content == "Hello" - finally: - await provider.aclose() diff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.py index c11438158..606d593e4 100644 --- a/tests/webui/test_settings_api.py +++ b/tests/webui/test_settings_api.py @@ -17,6 +17,7 @@ from nanobot.llm_usage.models import LLMCallRecord from nanobot.providers.base import LLMUsage from nanobot.providers.oauth_model_catalog import OAuthModelCatalogSnapshot from nanobot.providers.registry import ProviderModelSpec, find_by_name +from nanobot.providers.routing import resolve_provider_route from nanobot.session.manager import SessionManager from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY from nanobot.webui.settings_api import ( @@ -2885,6 +2886,46 @@ def test_custom_connection_api_create_edit_and_preset_ceiling(tmp_path, monkeypa assert load_config(config_path).providers.model_extra[key].api is None +@pytest.mark.parametrize("legacy_key", ["shengsuanyun_router", "shengsuanyun-router"]) +def test_setup_template_keeps_existing_provider_with_matching_name(tmp_path, monkeypatch, legacy_key): + config_path = tmp_path / "config.json" + legacy_config = { + "providers": {legacy_key: { + "apiBase": "https://legacy.example/api", + "apiKey": "legacy-key", + "api": {"supportedApis": ["anthropic_messages"]}, + }}, + "agents": {"defaults": {"model": "anthropic/old-model", "provider": legacy_key}}, + } + config_path.write_text(json.dumps(legacy_config), encoding="utf-8") + before = load_config(config_path) + monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path) + + payload = create_provider_settings({ + "name": ["ShengSuanYun Router 2"], + "apiBase": ["https://router.shengsuanyun.com/api/v1"], + "apiKey": ["new-key"], + "api": [json.dumps({ + "supportedApis": ["chat_completions", "responses"], "preferredApi": "chat_completions", + })], + }) + key = payload["created_provider"] + saved = load_config(config_path) + assert saved.get_provider_name() == legacy_key + assert saved.get_provider() == before.get_provider() + assert resolve_provider_route(saved, preset=saved.resolve_preset()).backend == "anthropic" + + def fake_get(url: str, **kwargs): + assert url == "https://router.shengsuanyun.com/api/v1/models" + assert kwargs["headers"]["Authorization"] == "Bearer new-key" + return httpx.Response(200, json={"data": [{"id": "deepseek/deepseek-v4-flash"}]}, + request=httpx.Request("GET", url)) + + monkeypatch.setattr("nanobot.webui.settings_api.httpx.get", fake_get) + catalog = provider_models_payload({"provider": [key]}) + assert catalog["models"][0]["id"] == "deepseek/deepseek-v4-flash" + + @pytest.mark.parametrize("api", [ {"supportedApis": []}, {"supportedApis": ["responses"], "preferredApi": "anthropic_messages"}, diff --git a/webui/src/components/settings/models/ProviderSearchList.tsx b/webui/src/components/settings/models/ProviderSearchList.tsx index 653b13899..c2183791f 100644 --- a/webui/src/components/settings/models/ProviderSearchList.tsx +++ b/webui/src/components/settings/models/ProviderSearchList.tsx @@ -27,7 +27,6 @@ const PROVIDER_SEARCH_ALIASES: Record = { minimax: "海螺 稀宇", minimax_anthropic: "海螺 稀宇", siliconflow: "硅基流动 矽基流動 硅基流動", - shengsuanyun_router: "胜算云 勝算雲", stepfun: "阶跃星辰 階躍星辰", xiaomi_mimo: "小米 mimo", longcat: "美团 美團", @@ -35,8 +34,9 @@ const PROVIDER_SEARCH_ALIASES: Record = { ant_ling: "蚂蚁 螞蟻 百灵 百靈", }; -export function ProviderSearchList({ providers, showBrandLogos, query, onQueryChange, onSelect, onCustom, onClose }: { +export function ProviderSearchList({ providers, setupOption, showBrandLogos, query, onQueryChange, onSelect, onCustom, onClose }: { providers: SettingsPayload["providers"]; + setupOption?: { id: string; label: string; searchAliases: string; onSelect: () => void }; showBrandLogos: boolean; query: string; onQueryChange: (query: string) => void; @@ -51,23 +51,34 @@ export function ProviderSearchList({ providers, showBrandLogos, query, onQueryCh useEffect(() => { if (!mobile) inputRef.current?.focus({ preventScroll: true }); }, [mobile]); - const filtered = useMemo(() => { + const groups = useMemo(() => { const normalize = (value: string) => value.toLocaleLowerCase().replace(/[\s_.-]+/g, ""); const normalizedQuery = normalize(query); - return providers.filter((provider) => normalize( - `${provider.name} ${provider.label} ${PROVIDER_SEARCH_ALIASES[provider.name] ?? ""}`, - ).includes(normalizedQuery)); - }, [providers, query]); - const groups = useMemo(() => PROVIDER_GROUPS.map((group) => ({ - ...group, - providers: filtered.filter((provider) => providerGroup(provider) === group.id), - })).filter((group) => group.providers.length > 0), [filtered]); - const values = useMemo( - () => groups.flatMap((group) => group.providers.map((provider) => provider.name)), - [groups], - ); + const options = providers.map((provider) => ({ + id: `provider:${provider.name}`, + icon: provider.name, + label: provider.label, + searchText: `${provider.name} ${provider.label} ${PROVIDER_SEARCH_ALIASES[provider.name] ?? ""}`, + group: providerGroup(provider), + select: () => onSelect(provider.name), + })); + if (setupOption) options.push({ + id: setupOption.id, icon: setupOption.id, label: setupOption.label, group: "api_key", + searchText: `${setupOption.label} ${setupOption.searchAliases}`, + select: setupOption.onSelect, + }); + const filtered = options.filter(({ searchText }) => + normalize(searchText).includes(normalizedQuery), + ); + return PROVIDER_GROUPS.map((group) => ({ + ...group, options: filtered.filter((option) => option.group === group.id), + })).filter((group) => group.options.length > 0); + }, [providers, query, setupOption, onSelect]); + const options = groups.flatMap((group) => group.options); + const values = options.map((option) => option.id); const { inputProps, listProps, getOptionProps } = useComboboxNavigation({ - open: true, values, onSelect, onClose, + open: true, values, onClose, + onSelect: (id) => options.find((option) => option.id === id)?.select(), }); const searchLabel = t("settings.providers.searchPlaceholder", { defaultValue: "Search providers" }); return <> @@ -88,17 +99,17 @@ export function ProviderSearchList({ providers, showBrandLogos, query, onQueryCh {t(group.labelKey, { defaultValue: group.label })}
- {group.providers.map((provider) => - - + + )}
))} - {filtered.length === 0 ?

+ {groups.length === 0 ?

{t("settings.providers.noMatches", { defaultValue: "No matching providers." })}

: null} diff --git a/webui/src/components/settings/models/ProviderSettings.tsx b/webui/src/components/settings/models/ProviderSettings.tsx index 67ca2e99d..41bb85890 100644 --- a/webui/src/components/settings/models/ProviderSettings.tsx +++ b/webui/src/components/settings/models/ProviderSettings.tsx @@ -47,6 +47,7 @@ import { Textarea } from "@/components/ui/textarea"; import { ProviderParameterFields } from "@/components/settings/models/ProviderParameterFields"; import { CUSTOM_PROVIDER_CREATION_KEY, + SHENGSUANYUN_TEMPLATE, emptyCustomProviderDraft, parseProviderObject, providerFormFromRow, @@ -525,7 +526,8 @@ export type ProviderSettingsEntry = | { kind: "edit"; provider: string }; type ProviderSettingsView = - | { kind: "list" | "picker" | "custom" } + | { kind: "list" | "picker" } + | { kind: "custom"; requiresApiKey: boolean } | { kind: "provider"; name: string; adding: boolean }; export function ProvidersSettings({ @@ -639,10 +641,20 @@ export function ProvidersSettings({ returnToOrigin(); } }; - const beginCustomProviderCreation = () => { - setCustomProviderDraft(emptyCustomProviderDraft()); + const beginCustomProviderCreation = (template?: typeof SHENGSUANYUN_TEMPLATE) => { + const draft = emptyCustomProviderDraft(); + if (template) { + draft.name = template.name; + const names = new Set(settings.providers.map((provider) => provider.label.trim().toLowerCase())); + for (let suffix = 2; names.has(draft.name.toLowerCase()); suffix += 1) { + draft.name = `${template.name} ${suffix}`; + } + draft.apiBase = template.apiBase; + draft.api = template.api; + } + setCustomProviderDraft(draft); setCustomProviderKeyVisible(false); - setView({ kind: "custom" }); + setView({ kind: "custom", requiresApiKey: Boolean(template) }); }; const saveCustomProvider = async () => { if (customProviderSaving) return; @@ -1068,7 +1080,8 @@ export function ProvidersSettings({ disabled={ customProviderSaving || !customProviderDraft.name.trim() || - !customProviderDraft.apiBase.trim() + !customProviderDraft.apiBase.trim() || + (view.requiresApiKey && !customProviderDraft.apiKey.trim()) } className="rounded-full" > @@ -1131,7 +1144,14 @@ export function ProvidersSettings({ editProvider(name, true)} - onCustom={beginCustomProviderCreation} onClose={entry.kind === "manage" ? goBack : closePanel} /> + onCustom={() => beginCustomProviderCreation()} + setupOption={{ + id: SHENGSUANYUN_TEMPLATE.id, + label: SHENGSUANYUN_TEMPLATE.name, + searchAliases: SHENGSUANYUN_TEMPLATE.searchAliases, + onSelect: () => beginCustomProviderCreation(SHENGSUANYUN_TEMPLATE), + }} + onClose={entry.kind === "manage" ? goBack : closePanel} /> ) : (
{view.kind === "custom" ? customProviderForm : selectedProvider ? renderProviderForm(selectedProvider) : null} diff --git a/webui/src/components/settings/models/providerForm.ts b/webui/src/components/settings/models/providerForm.ts index d8489734c..9467145e7 100644 --- a/webui/src/components/settings/models/providerForm.ts +++ b/webui/src/components/settings/models/providerForm.ts @@ -19,6 +19,17 @@ export type ProviderForm = { export type CustomProviderDraft = ProviderForm & { name: string }; export const CUSTOM_PROVIDER_CREATION_KEY = "__custom_provider__"; +export const SHENGSUANYUN_TEMPLATE = { + id: "template:shengsuanyun", + name: "ShengSuanYun Router", + searchAliases: "胜算云 勝算雲", + apiBase: "https://router.shengsuanyun.com/api/v1", + api: { + supported_apis: ["chat_completions", "responses"], + preferred_api: "chat_completions", + } satisfies ModelAPIConfig, +}; + export function providerJsonValue(value: Record | null | undefined): string { return value && Object.keys(value).length > 0 ? JSON.stringify(value, null, 2) : ""; } diff --git a/webui/src/components/settings/shared/ModelControls.tsx b/webui/src/components/settings/shared/ModelControls.tsx index 23a9b0523..bbb2b8f7a 100644 --- a/webui/src/components/settings/shared/ModelControls.tsx +++ b/webui/src/components/settings/shared/ModelControls.tsx @@ -38,7 +38,6 @@ const DEFERRED_MODEL_LIST_PROVIDERS = new Set([ "openrouter", "orcarouter", "ovms", - "shengsuanyun_router", "siliconflow", "vllm", "volcengine", diff --git a/webui/src/lib/provider-brand.ts b/webui/src/lib/provider-brand.ts index 906ef7da0..0d27cbceb 100644 --- a/webui/src/lib/provider-brand.ts +++ b/webui/src/lib/provider-brand.ts @@ -228,7 +228,7 @@ const PROVIDER_BRANDS: Record = { initials: "SX", }, siliconflow: brand("siliconflow.cn", "#111827", "SF"), - shengsuanyun_router: { ...brand("shengsuanyun.com", "#5742EE", "SSY", [ + "template:shengsuanyun": { ...brand("shengsuanyun.com", "#5742EE", "SSY", [ "https://www.shengsuanyun.com/svg/logo-C_e87Vaj.svg", ]), logoLayout: "tile" }, skywork: brand("skywork.ai", "#5B5BF6", "SW"), diff --git a/webui/src/lib/provider-icons.ts b/webui/src/lib/provider-icons.ts index 95adf454b..d003127d2 100644 --- a/webui/src/lib/provider-icons.ts +++ b/webui/src/lib/provider-icons.ts @@ -20,7 +20,6 @@ export const PROVIDER_ICONS: Record = { gemini: Gem, mistral: Orbit, siliconflow: Layers, - shengsuanyun_router: Cloud, volcengine: Cloud, volcengine_coding_plan: Cloud, byteplus: Cloud, diff --git a/webui/src/tests/provider-icon.test.tsx b/webui/src/tests/provider-icon.test.tsx index 855552883..30054aad5 100644 --- a/webui/src/tests/provider-icon.test.tsx +++ b/webui/src/tests/provider-icon.test.tsx @@ -48,7 +48,7 @@ describe("settings provider icons", () => { it.each([ "aihubmix", "bedrock", "exa", "groq", "lm_studio", "minimax", "minimax_anthropic", - "modelscope", "moonshot", "olostep", "shengsuanyun_router", "tavily", "xiaomi_mimo", "zhipu", + "modelscope", "moonshot", "olostep", "template:shengsuanyun", "tavily", "xiaomi_mimo", "zhipu", ])( "does not double-frame %s's primary tile, but preserves unknown fallback assets", (provider) => { diff --git a/webui/src/tests/settings-providers.test.tsx b/webui/src/tests/settings-providers.test.tsx index d2d4366ea..9e77a48d5 100644 --- a/webui/src/tests/settings-providers.test.tsx +++ b/webui/src/tests/settings-providers.test.tsx @@ -21,16 +21,40 @@ async function chooseProviderToConfigure(label: string) { describe("Settings providers", () => { installSettingsViewTestHooks(); - it("finds ShengSuanYun by its Chinese name and opens its credential form", async () => { + it("sets up ShengSuanYun as a custom connection without updating an existing provider", async () => { const user = userEvent.setup(); const payload = settingsPayload(); - payload.providers = [{ name: "shengsuanyun_router", label: "ShengSuanYun Router", configured: false }]; + const existing = { name: "shengsuanyun_router", label: "ShengSuanYun Router", configured: true }; + payload.providers = [existing]; + payload.provider_api_configuration_supported = true; + requestMutationMock.mockResolvedValueOnce({ + ...payload, + created_provider: "custom-shengsuanyun-router-2", + providers: [existing, { name: "custom-shengsuanyun-router-2", label: "ShengSuanYun Router 2", configured: true, is_custom: true }], + }); renderProviderManager({ initialSection: "models", initialSettings: payload }); await user.click(screen.getByRole("button", { name: "Add provider" })); await user.type(screen.getByRole("combobox", { name: "Search providers" }), "胜算云"); - await user.click(screen.getByRole("option", { name: "ShengSuanYun Router" })); - expect(screen.getByRole("dialog", { name: "ShengSuanYun Router" })).toBeVisible(); - expect(screen.getByPlaceholderText("Enter API key")).toBeInTheDocument(); + await user.keyboard("{ArrowDown}{Enter}"); + const form = screen.getByRole("dialog", { name: "Custom" }); + expect(within(form).getByPlaceholderText("My model provider")).toHaveValue("ShengSuanYun Router 2"); + expect(within(form).getByLabelText("API URL")).toHaveValue("https://router.shengsuanyun.com/api/v1"); + expect(requestMutationMock).not.toHaveBeenCalled(); + const save = within(form).getByRole("button", { name: "Add provider" }); + expect(save).toBeDisabled(); + await user.type(within(form).getByPlaceholderText("Enter API key"), "test-key"); + await user.click(save); + expect(requestMutationMock).toHaveBeenCalledTimes(1); + const [action, values] = requestMutationMock.mock.calls[0]; + expect(action).toBe("settings.provider.create"); + expect(values).toMatchObject({ + name: "ShengSuanYun Router 2", + apiKey: "test-key", + apiBase: "https://router.shengsuanyun.com/api/v1", + api: { supported_apis: ["chat_completions", "responses"], preferred_api: "chat_completions" }, + }); + expect(await screen.findByRole("button", { name: "ShengSuanYun Router 2" })).toBeVisible(); + expect(await screen.findByRole("button", { name: "ShengSuanYun Router" })).toBeVisible(); }); it("manages providers unused by presets and returns focus through the manager", async () => {