refactor(providers): migrate legacy API selector at input boundary

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-10 01:33:02 +08:00
1 parent ed0eb89178
commit 7e2e804b5c
36 files changed
+294 -181

No files matched your search

@@ -11,15 +11,18 @@ import type { ModelAPIConfig, ProviderRequestAPI, SettingsPayload } from "@/lib/
export function ModelAPIControl({
provider,
automaticAPI,
title,
value,
onChange,
}: {
provider: SettingsPayload["providers"][number] | undefined;
automaticAPI?: ProviderRequestAPI;
title?: string;
value: ModelAPIConfig | null;
onChange: (api: ModelAPIConfig | null) => void;
}) {
const { t } = useTranslation();
const controlTitle = title ?? t("settings.models.requestAPI");
const [pointerFocus, setPointerFocus] = useState(false);
const requestAPIs = Array.isArray(provider?.request_apis) ? provider.request_apis : undefined;
const configurable = modelAPIConfigurable(provider);
@@ -47,7 +50,7 @@ export function ModelAPIControl({
return (
<div>
<SettingsRow title={t("settings.models.requestAPI")}>
<SettingsRow title={controlTitle}>
{configurable ? (
<Select value={selectedAPI} onValueChange={(api) => {
if (api === selectedAPI) return;
@@ -57,7 +60,7 @@ export function ModelAPIControl({
}
}}>
<SelectTrigger
aria-label={t("settings.models.requestAPI")}
aria-label={controlTitle}
className={cn("w-full rounded-full", pointerFocus && "focus-visible:ring-0")}
onPointerDown={() => setPointerFocus(true)}
onKeyDown={() => setPointerFocus(false)}
@@ -25,6 +25,7 @@ import {
SettingsSectionTitle,
} from "@/components/settings/shared/SettingsControls";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { ModelAPIControl } from "@/components/settings/models/ModelAPIControl";
import { ProviderAPIControl } from "@/components/settings/models/ProviderAPIControl";
import { Button } from "@/components/ui/button";
import {
@@ -60,7 +61,6 @@ import type {
SettingsPayload,
} from "@/lib/types";
type ProviderApiType = "auto" | "chat_completions" | "responses";
type ProviderAdvancedField = NonNullable<
SettingsPayload["providers"][number]["advanced_fields"]
>[number];
@@ -68,7 +68,6 @@ export type ProviderForm = {
displayName: string;
apiKey: string;
apiBase: string;
apiType: ProviderApiType;
api: ModelAPIConfig | null;
proxy: string;
extraHeaders: string;
@@ -198,7 +197,7 @@ function updateProviderRequestOption(
return {
extraBody: providerJsonValue(extraBody),
...(option.forceResponses && enabled
? { apiType: "responses" as const }
? { api: { supported_apis: ["responses"], preferred_api: "responses" } satisfies ModelAPIConfig }
: {}),
};
}
@@ -210,7 +209,6 @@ export function providerFormFromRow(
displayName: provider.is_custom ? provider.label : "",
apiKey: "",
apiBase: provider.api_base ?? provider.default_api_base ?? "",
apiType: provider.api_type ?? "auto",
api: provider.api ?? null,
proxy: provider.proxy ?? "",
extraHeaders: providerJsonValue(provider.extra_headers),
@@ -228,7 +226,6 @@ function emptyCustomProviderDraft(): CustomProviderDraft {
displayName: "",
apiKey: "",
apiBase: "",
apiType: "auto",
api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },
proxy: "",
extraHeaders: "",
@@ -240,12 +237,6 @@ function emptyCustomProviderDraft(): CustomProviderDraft {
};
}
const OPENAI_API_TYPE_OPTIONS: Array<{ value: ProviderApiType; label: string }> = [
{ value: "auto", label: "Auto" },
{ value: "chat_completions", label: "Chat Completions" },
{ value: "responses", label: "Responses" },
];
const LOCAL_UNCONFIGURED_PROVIDER_ORDER = new Map(
["vllm", "ollama", "lm_studio", "atomic_chat", "ovms"].map((name, index) => [
name,
@@ -411,14 +402,17 @@ export function ProviderOAuthLoginDialog({
function ProviderRequestOptions({
providerName,
form,
apiConfigurable,
onChange,
}: {
providerName: string;
form: ProviderForm;
apiConfigurable: boolean;
onChange: (value: Partial<ProviderForm>) => void;
}) {
const { t } = useTranslation();
const options = PROVIDER_REQUEST_OPTIONS[providerName] ?? [];
const options = (PROVIDER_REQUEST_OPTIONS[providerName] ?? [])
.filter((option) => !option.forceResponses || apiConfigurable);
if (options.length === 0) return null;
const extraBody = parseProviderExtraBody(form.extraBody) ?? {};
@@ -509,42 +503,6 @@ function ProviderAdvancedOptions({
<DisclosureContent id={contentId} open={open}>
<div className="py-3">
<div className="grid gap-3 md:grid-cols-2">
{enabled.has("api_type") ? (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-muted-foreground">
{tx("settings.providers.apiType", "API type")}
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
className="h-9 w-full justify-between rounded-full px-3 text-[13px]"
>
<span>
{OPENAI_API_TYPE_OPTIONS.find(
(option) => option.value === form.apiType,
)?.label ?? form.apiType}
</span>
<ChevronDown
className="h-3.5 w-3.5 text-muted-foreground"
aria-hidden
/>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-[220px]">
{OPENAI_API_TYPE_OPTIONS.map((option) => (
<DropdownMenuItem
key={option.value}
onSelect={() => onChange({ apiType: option.value })}
>
{option.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</label>
) : null}
{enabled.has("thinking_style") ? (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-muted-foreground">
@@ -910,6 +868,7 @@ export function ProvidersSettings({
</div>
<ProviderRequestOptions
providerName={provider.name}
apiConfigurable={provider.provider_api_configurable === true}
form={form}
onChange={(value) => onChangeProviderForm(provider.name, value)}
/>
@@ -1040,15 +999,23 @@ export function ProvidersSettings({
</label>
<ProviderRequestOptions
providerName={provider.name}
apiConfigurable={provider.provider_api_configurable === true}
form={form}
onChange={(value) => onChangeProviderForm(provider.name, value)}
/>
{provider.provider_api_configurable && (
{provider.provider_api_configurable && (provider.name === "openai" ? (
<ModelAPIControl
provider={provider}
title={t("settings.providers.defaultAPI")}
value={form.api}
onChange={(api) => onChangeProviderForm(provider.name, { api })}
/>
) : (
<ProviderAPIControl
value={form.api}
onChange={(api) => onChangeProviderForm(provider.name, { api })}
/>
)}
))}
<ProviderAdvancedOptions
fields={advancedFields}
form={form}
@@ -410,7 +410,6 @@ export function useModelSettingsActions({
if (provider.provider_api_configurable) update.api = providerForm.api;
}
for (const field of provider.advanced_fields ?? []) {
if (field === "api_type") update.apiType = providerForm.apiType;
if (field === "proxy") update.proxy = providerForm.proxy.trim();
if (field === "extra_headers") {
update.extraHeaders = providerForm.extraHeaders.trim();
-1
View File
@@ -1197,7 +1197,6 @@
"supportedAPIs": "Supported APIs",
"defaultAPI": "Default API",
"declareAPIs": "Set supported APIs",
"apiType": "API type",
"proxy": "Network proxy",
"thinkingStyle": "Reasoning format",
"region": "Region",
-1
View File
@@ -777,7 +777,6 @@
"supportedAPIs": "API compatibles",
"defaultAPI": "API predeterminada",
"declareAPIs": "Configurar API compatibles",
"apiType": "Tipo de API",
"proxy": "Proxy de red",
"thinkingStyle": "Formato de razonamiento",
"region": "Región",
-1
View File
@@ -777,7 +777,6 @@
"supportedAPIs": "API prises en charge",
"defaultAPI": "API par défaut",
"declareAPIs": "Définir les API prises en charge",
"apiType": "Type d’API",
"proxy": "Proxy réseau",
"thinkingStyle": "Format du raisonnement",
"region": "Région",
-1
View File
@@ -777,7 +777,6 @@
"supportedAPIs": "API yang didukung",
"defaultAPI": "API default",
"declareAPIs": "Atur API yang didukung",
"apiType": "Jenis API",
"proxy": "Proksi jaringan",
"thinkingStyle": "Format penalaran",
"region": "Wilayah",
-1
View File
@@ -777,7 +777,6 @@
"supportedAPIs": "対応する API",
"defaultAPI": "デフォルトの API",
"declareAPIs": "対応する API を設定",
"apiType": "API タイプ",
"proxy": "ネットワークプロキシ",
"thinkingStyle": "推論の形式",
"region": "リージョン",
-1
View File
@@ -777,7 +777,6 @@
"supportedAPIs": "지원 API",
"defaultAPI": "기본 API",
"declareAPIs": "지원 API 설정",
"apiType": "API 유형",
"proxy": "네트워크 프록시",
"thinkingStyle": "추론 형식",
"region": "리전",
-1
View File
@@ -1011,7 +1011,6 @@
"supportedAPIs": "APIs compatíveis",
"defaultAPI": "API padrão",
"declareAPIs": "Definir APIs compatíveis",
"apiType": "Tipo de API",
"proxy": "Proxy de rede",
"thinkingStyle": "Formato de raciocínio",
"region": "Região",
-1
View File
@@ -777,7 +777,6 @@
"supportedAPIs": "API được hỗ trợ",
"defaultAPI": "API mặc định",
"declareAPIs": "Đặt API được hỗ trợ",
"apiType": "Loại API",
"proxy": "Proxy mạng",
"thinkingStyle": "Định dạng suy luận",
"region": "Khu vực",
-1
View File
@@ -1197,7 +1197,6 @@
"supportedAPIs": "支持的协议",
"defaultAPI": "默认协议",
"declareAPIs": "设置支持的协议",
"apiType": "API 类型",
"proxy": "网络代理",
"thinkingStyle": "推理格式",
"region": "区域",
-1
View File
@@ -777,7 +777,6 @@
"supportedAPIs": "支援的協定",
"defaultAPI": "預設協定",
"declareAPIs": "設定支援的協定",
"apiType": "API 類型",
"proxy": "網路代理",
"thinkingStyle": "推理格式",
"region": "區域",
-3
View File
@@ -735,13 +735,11 @@ export interface SettingsPayload {
adapter_request_apis?: ProviderRequestAPI[];
provider_api_configurable?: boolean;
api?: ModelAPIConfig | null;
api_type?: "auto" | "chat_completions" | "responses";
oauth_account?: string | null;
oauth_expires_at?: number | null;
oauth_login_supported?: boolean;
proxy?: string | null;
advanced_fields?: Array<
| "api_type"
| "extra_headers"
| "extra_body"
| "extra_query"
@@ -1354,7 +1352,6 @@ export interface ProviderSettingsUpdate {
displayName?: string;
apiKey?: string;
apiBase?: string;
apiType?: "auto" | "chat_completions" | "responses";
api?: ModelAPIConfig | null;
proxy?: string;
extraHeaders?: string;
+64 -7
View File
@@ -696,8 +696,9 @@ describe("Settings providers", () => {
api_key_required: true,
api_key_hint: "sk-••••test",
api_base: "https://api.openai.com/v1",
api_type: "auto",
advanced_fields: ["api_type", "extra_body"],
provider_api_configurable: true,
request_apis: ["chat_completions", "responses"],
advanced_fields: ["extra_body"],
extra_body: null,
},
];
@@ -769,11 +770,11 @@ describe("Settings providers", () => {
.map(([, values]) => {
const update = values as {
provider: string;
apiType?: string;
api?: { supported_apis: string[]; preferred_api: string };
extraBody?: string;
};
return [update.provider, {
...(update.apiType ? { apiType: update.apiType } : {}),
...(update.api ? { api: update.api } : {}),
extraBody: JSON.parse(update.extraBody ?? "{}"),
}] as const;
});
@@ -782,7 +783,7 @@ describe("Settings providers", () => {
["openai_codex", { extraBody: { service_tier: "priority" } }],
["deepseek", { extraBody: { tools: [] } }],
["openai", {
apiType: "responses",
api: { supported_apis: ["responses"], preferred_api: "responses" },
extraBody: { tools: [{ type: "web_search" }] },
}],
]);
@@ -800,8 +801,9 @@ describe("Settings providers", () => {
api_key_required: true,
api_key_hint: "sk-••••test",
api_base: "https://api.openai.com/v1",
api_type: "auto",
advanced_fields: ["api_type", "extra_body"],
provider_api_configurable: true,
request_apis: ["chat_completions", "responses"],
advanced_fields: ["extra_body"],
extra_body: {
metadata: { owner: "legacy-config" },
tools: [
@@ -1038,4 +1040,59 @@ describe("Settings providers", () => {
expect(screen.queryByRole("group", { name: "Supported APIs" })).not.toBeInTheDocument();
});
it("saves and reopens OpenAI defaults, including automatic routing", async () => {
const user = userEvent.setup();
let payload = settingsPayload();
payload.providers = [{
name: "openai", label: "OpenAI", configured: true,
provider_api_configurable: true, request_apis: ["chat_completions", "responses"],
api: { supported_apis: ["responses"], preferred_api: "responses" },
}];
requestMutationMock.mockImplementation(async (_action, args) => {
payload = { ...payload, providers: [{ ...payload.providers[0], api: args.api }] };
return payload;
});
renderSettingsView({ initialSection: "models", initialSettings: payload });
await user.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Responses");
await user.click(screen.getByRole("combobox", { name: "Default API" }));
await user.click(screen.getByRole("option", { name: "Chat Completions", exact: true }));
await user.click(screen.getByRole("button", { name: "Save provider" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
provider: "openai", api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },
}), 20_000);
await user.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Chat Completions");
await user.click(screen.getByRole("combobox", { name: "Default API" }));
await user.click(screen.getByRole("option", { name: "Auto", exact: true }));
await user.click(screen.getByRole("button", { name: "Save provider" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
provider: "openai", api: null,
}), 20_000);
await user.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Auto");
});
it("keeps ordinary OpenAI edits available on hosts without API declarations", async () => {
const payload = settingsPayload();
payload.providers = [{
name: "openai", label: "OpenAI", configured: true,
api_base: "https://api.openai.com/v1", advanced_fields: ["extra_body"],
extra_body: { tools: [{ type: "web_search" }] },
}];
renderSettingsView({ initialSection: "models", initialSettings: payload });
fireEvent.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
expect(screen.queryByRole("combobox", { name: "Default API" })).not.toBeInTheDocument();
expect(screen.queryByRole("switch", { name: "OpenAI web search" })).not.toBeInTheDocument();
fireEvent.change(screen.getByLabelText("API base URL"), { target: { value: "https://gateway.test/v1" } });
fireEvent.click(screen.getByRole("button", { name: "Save provider" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
provider: "openai", apiBase: "https://gateway.test/v1",
}), 20_000));
const update = requestMutationMock.mock.calls.at(-1)?.[1];
expect(JSON.parse(update.extraBody)).toEqual({ tools: [{ type: "web_search" }] });
});
});