feat(providers): declare supported APIs for custom connections
This commit is contained in:
1 parent
73a27e0726
commit
34fd4ed75a
29 files changed
+799
-108
No files matched your search
@@ -9,13 +9,16 @@ import type { ModelAPIConfig, ProviderRequestAPI, SettingsPayload } from "@/lib/
|
||||
|
||||
export function modelAPIConfigurable(provider: SettingsPayload["providers"][number] | undefined): boolean {
|
||||
if (Array.isArray(provider?.request_apis)) {
|
||||
return provider.request_apis.includes("chat_completions") && provider.request_apis.includes("responses");
|
||||
const supported = provider.request_apis;
|
||||
return (["chat_completions", "responses", "anthropic_messages"] as const)
|
||||
.filter((api) => supported.includes(api)).length > 1;
|
||||
}
|
||||
return provider?.model_api_configurable === true;
|
||||
}
|
||||
|
||||
export function modelAPISelection(api: ModelAPIConfig | null | undefined): string {
|
||||
if (!api) return "auto";
|
||||
if (api.supported_apis.includes("anthropic_messages")) return "anthropic_messages";
|
||||
if (!api.supported_apis.includes("responses")) return "chat_completions";
|
||||
if (!api.supported_apis.includes("chat_completions")) return "responses";
|
||||
return (api.preferred_api ?? api.supported_apis[0]) === "responses"
|
||||
@@ -58,8 +61,9 @@ export function ModelAPIControl({
|
||||
? `${t("settings.models.apiAuto")} (${labels[automaticAPI]})`
|
||||
: t("settings.models.apiAuto"),
|
||||
},
|
||||
{ value: "responses", label: "Responses" },
|
||||
{ value: "chat_completions", label: "Chat Completions" },
|
||||
...(["responses", "chat_completions", "anthropic_messages"] as const)
|
||||
.filter((api) => requestAPIs ? requestAPIs.includes(api) : api !== "anthropic_messages")
|
||||
.map((api) => ({ value: api, label: labels[api] })),
|
||||
];
|
||||
if (!configurable && !fixedLabel) return null;
|
||||
|
||||
@@ -70,7 +74,7 @@ export function ModelAPIControl({
|
||||
<Select value={selectedAPI} onValueChange={(api) => {
|
||||
if (api === selectedAPI) return;
|
||||
if (api === "auto") onChange(null);
|
||||
else if (api === "responses" || api === "chat_completions") {
|
||||
else if (api === "responses" || api === "chat_completions" || api === "anthropic_messages") {
|
||||
onChange({ supported_apis: [api], preferred_api: api });
|
||||
}
|
||||
}}>
|
||||
@@ -98,7 +102,7 @@ export function ModelAPIControl({
|
||||
<span className="block text-[13px] text-muted-foreground sm:text-right">{fixedLabel}</span>
|
||||
)}
|
||||
</SettingsRow>
|
||||
{configurable && selectedAPI === "responses" ? (
|
||||
{configurable && selectedAPI === "responses" && (!requestAPIs || requestAPIs.includes("chat_completions")) ? (
|
||||
<div className="mx-4 mb-3 flex items-start justify-between gap-4 rounded-xl bg-muted/30 px-3 py-3 sm:mx-5">
|
||||
<div className="min-w-0">
|
||||
<p className="text-[13px] leading-5 text-foreground">{t("settings.models.apiFallback")}</p>
|
||||
|
||||
@@ -242,14 +242,15 @@ export function ModelsSettings({
|
||||
scope: string;
|
||||
result: AutomaticModelAPIPayload;
|
||||
} | null>(null);
|
||||
const { provider: apiProvider, model: apiModel, reasoningEffort: apiReasoningEffort } = form;
|
||||
const automaticAPIScope = JSON.stringify([
|
||||
token, form.provider, form.model, form.reasoningEffort, settings.providers,
|
||||
token, apiProvider, apiModel, apiReasoningEffort, settings.providers,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (!editorOpen || settings.model_api_resolution_supported !== true || !form.model.trim()) return;
|
||||
if (!editorOpen || settings.model_api_resolution_supported !== true || !apiModel.trim()) return;
|
||||
let cancelled = false;
|
||||
const timer = window.setTimeout(() => {
|
||||
void fetchAutomaticModelAPI(token, form.provider, form.model, form.reasoningEffort)
|
||||
void fetchAutomaticModelAPI(token, apiProvider, apiModel, apiReasoningEffort)
|
||||
.then((result) => {
|
||||
if (!cancelled) setAutomaticAPI({ scope: automaticAPIScope, result });
|
||||
})
|
||||
@@ -258,7 +259,7 @@ export function ModelsSettings({
|
||||
});
|
||||
}, 150);
|
||||
return () => { cancelled = true; window.clearTimeout(timer); };
|
||||
}, [editorOpen, settings.model_api_resolution_supported, automaticAPIScope, token, form]);
|
||||
}, [editorOpen, settings.model_api_resolution_supported, automaticAPIScope, token, apiProvider, apiModel, apiReasoningEffort]);
|
||||
const resolvedAutomaticAPI = settings.model_api_resolution_supported === true
|
||||
&& automaticAPI?.scope === automaticAPIScope ? automaticAPI.result : null;
|
||||
const editorTriggerRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import type { ModelAPIConfig, ModelRequestAPI } from "@/lib/types";
|
||||
|
||||
const APIS: Array<{ value: ModelRequestAPI; label: string }> = [
|
||||
{ value: "chat_completions", label: "Chat Completions" },
|
||||
{ value: "responses", label: "Responses" },
|
||||
{ value: "anthropic_messages", label: "Anthropic Messages" },
|
||||
];
|
||||
|
||||
export function ProviderAPIControl({ value, onChange }: {
|
||||
value: ModelAPIConfig | null;
|
||||
onChange: (api: ModelAPIConfig) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (value === null) {
|
||||
return (
|
||||
<Button variant="outline" className="rounded-full" onClick={() => onChange({
|
||||
supported_apis: ["chat_completions"], preferred_api: "chat_completions",
|
||||
})}>
|
||||
{t("settings.providers.declareAPIs")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
const supported = value.supported_apis;
|
||||
const preferred = value.preferred_api ?? supported[0];
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<fieldset className="space-y-3 rounded-xl border border-border/60 p-3">
|
||||
<legend className="px-1 text-[12px] font-medium text-muted-foreground">
|
||||
{t("settings.providers.supportedAPIs")}
|
||||
</legend>
|
||||
{APIS.map((api) => {
|
||||
const checked = supported.includes(api.value);
|
||||
return (
|
||||
<div key={api.value} className="flex items-center justify-between gap-3 text-[13px]">
|
||||
<span>{api.label}</span>
|
||||
<ToggleButton
|
||||
label={api.label}
|
||||
checked={checked}
|
||||
disabled={checked && supported.length === 1}
|
||||
onChange={(enabled) => {
|
||||
const next = enabled ? [...supported, api.value] : supported.filter((item) => item !== api.value);
|
||||
onChange({ supported_apis: next, preferred_api: next.includes(preferred) ? preferred : next[0] });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
<div className="space-y-1.5">
|
||||
<span className="text-[12px] font-medium text-muted-foreground">
|
||||
{t("settings.providers.defaultAPI")}
|
||||
</span>
|
||||
<Select value={preferred} onValueChange={(api) => onChange({
|
||||
supported_apis: supported, preferred_api: api as ModelRequestAPI,
|
||||
})}>
|
||||
<SelectTrigger aria-label={t("settings.providers.defaultAPI")} className="w-full rounded-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{APIS.filter((api) => supported.includes(api.value)).map((api) => (
|
||||
<SelectItem key={api.value} value={api.value}>{api.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
SettingsSectionTitle,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ProviderAPIControl } from "@/components/settings/models/ProviderAPIControl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -54,6 +55,7 @@ import { cn } from "@/lib/utils";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import type {
|
||||
NanobotFeaturesPayload,
|
||||
ModelAPIConfig,
|
||||
ProviderOAuthAuthorizationRequired,
|
||||
SettingsPayload,
|
||||
} from "@/lib/types";
|
||||
@@ -67,6 +69,7 @@ export type ProviderForm = {
|
||||
apiKey: string;
|
||||
apiBase: string;
|
||||
apiType: ProviderApiType;
|
||||
api: ModelAPIConfig | null;
|
||||
proxy: string;
|
||||
extraHeaders: string;
|
||||
extraBody: string;
|
||||
@@ -208,6 +211,7 @@ export function providerFormFromRow(
|
||||
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),
|
||||
extraBody: providerJsonValue(provider.extra_body),
|
||||
@@ -225,6 +229,7 @@ function emptyCustomProviderDraft(): CustomProviderDraft {
|
||||
apiKey: "",
|
||||
apiBase: "",
|
||||
apiType: "auto",
|
||||
api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },
|
||||
proxy: "",
|
||||
extraHeaders: "",
|
||||
extraBody: "",
|
||||
@@ -1038,6 +1043,12 @@ export function ProvidersSettings({
|
||||
form={form}
|
||||
onChange={(value) => onChangeProviderForm(provider.name, value)}
|
||||
/>
|
||||
{provider.provider_api_configurable && (
|
||||
<ProviderAPIControl
|
||||
value={form.api}
|
||||
onChange={(api) => onChangeProviderForm(provider.name, { api })}
|
||||
/>
|
||||
)}
|
||||
<ProviderAdvancedOptions
|
||||
fields={advancedFields}
|
||||
form={form}
|
||||
@@ -1178,6 +1189,12 @@ export function ProvidersSettings({
|
||||
</Button>
|
||||
</div>
|
||||
</label>
|
||||
{settings.provider_api_configuration_supported && (
|
||||
<ProviderAPIControl
|
||||
value={customProviderDraft.api}
|
||||
onChange={(api) => setCustomProviderDraft((current) => ({ ...current, api }))}
|
||||
/>
|
||||
)}
|
||||
<ProviderAdvancedOptions
|
||||
fields={CUSTOM_PROVIDER_ADVANCED_FIELDS}
|
||||
form={customProviderDraft}
|
||||
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
PendingRestartSections,
|
||||
} from "@/components/settings/contracts";
|
||||
import { agentDraftFromPayload } from "@/components/settings/models/ModelsSettings";
|
||||
import { modelAPIConfigurable, modelAPISelection } from "@/components/settings/models/ModelAPIControl";
|
||||
import { modelAPISelection } from "@/components/settings/models/ModelAPIControl";
|
||||
import {
|
||||
CUSTOM_PROVIDER_CREATION_KEY,
|
||||
providerFormFromRow,
|
||||
@@ -196,8 +196,7 @@ export function useModelSettingsActions({
|
||||
contextWindowTokens: form.contextWindowTokens,
|
||||
temperature: form.temperature,
|
||||
reasoningEffort: form.reasoningEffort || null,
|
||||
api: modelAPIConfigurable(settings.providers.find((row) => row.name === provider))
|
||||
? form.api : undefined,
|
||||
api: form.api ?? undefined,
|
||||
});
|
||||
const createdPreset = payload.created_model_preset;
|
||||
const nextOrder = createdPreset ? [...modelCallOrder, createdPreset] : null;
|
||||
@@ -260,10 +259,7 @@ export function useModelSettingsActions({
|
||||
form.temperature !== selectedPreset.temperature ? form.temperature : undefined,
|
||||
reasoningEffort:
|
||||
reasoningEffort !== selectedPreset.reasoning_effort ? reasoningEffort : undefined,
|
||||
api: modelAPIConfigurable(settings.providers.find((row) => row.name === (
|
||||
form.provider === "auto" ? selectedPreset.resolved_provider : form.provider
|
||||
))) &&
|
||||
modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
|
||||
api: modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
|
||||
? form.api : undefined,
|
||||
});
|
||||
applyPayload(payload);
|
||||
@@ -411,6 +407,7 @@ export function useModelSettingsActions({
|
||||
update.apiKey = apiKey || undefined;
|
||||
update.apiBase = providerForm.apiBase.trim();
|
||||
if (provider.is_custom) update.displayName = providerForm.displayName.trim();
|
||||
if (provider.provider_api_configurable) update.api = providerForm.api;
|
||||
}
|
||||
for (const field of provider.advanced_fields ?? []) {
|
||||
if (field === "api_type") update.apiType = providerForm.apiType;
|
||||
@@ -464,6 +461,7 @@ export function useModelSettingsActions({
|
||||
name: draft.name.trim(),
|
||||
apiKey: draft.apiKey.trim() || undefined,
|
||||
apiBase: draft.apiBase.trim(),
|
||||
...(settings?.provider_api_configuration_supported ? { api: draft.api } : {}),
|
||||
proxy: draft.proxy.trim(),
|
||||
extraHeaders: draft.extraHeaders.trim(),
|
||||
extraBody: draft.extraBody.trim(),
|
||||
|
||||
@@ -1194,6 +1194,9 @@
|
||||
"saveProvider": "Save provider",
|
||||
"advancedOptions": "Advanced options",
|
||||
"saveAdvancedBeforeSignIn": "Save advanced changes before signing in.",
|
||||
"supportedAPIs": "Supported APIs",
|
||||
"defaultAPI": "Default API",
|
||||
"declareAPIs": "Set supported APIs",
|
||||
"apiType": "API type",
|
||||
"proxy": "Network proxy",
|
||||
"thinkingStyle": "Reasoning format",
|
||||
|
||||
@@ -774,6 +774,9 @@
|
||||
"saveProvider": "Guardar proveedor",
|
||||
"advancedOptions": "Opciones avanzadas",
|
||||
"saveAdvancedBeforeSignIn": "Guarda los cambios avanzados antes de iniciar sesión.",
|
||||
"supportedAPIs": "API compatibles",
|
||||
"defaultAPI": "API predeterminada",
|
||||
"declareAPIs": "Configurar API compatibles",
|
||||
"apiType": "Tipo de API",
|
||||
"proxy": "Proxy de red",
|
||||
"thinkingStyle": "Formato de razonamiento",
|
||||
|
||||
@@ -774,6 +774,9 @@
|
||||
"saveProvider": "Enregistrer le fournisseur",
|
||||
"advancedOptions": "Options avancées",
|
||||
"saveAdvancedBeforeSignIn": "Enregistrez les options avancées avant de vous connecter.",
|
||||
"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",
|
||||
|
||||
@@ -774,6 +774,9 @@
|
||||
"saveProvider": "Simpan penyedia",
|
||||
"advancedOptions": "Opsi lanjutan",
|
||||
"saveAdvancedBeforeSignIn": "Simpan perubahan lanjutan sebelum masuk.",
|
||||
"supportedAPIs": "API yang didukung",
|
||||
"defaultAPI": "API default",
|
||||
"declareAPIs": "Atur API yang didukung",
|
||||
"apiType": "Jenis API",
|
||||
"proxy": "Proksi jaringan",
|
||||
"thinkingStyle": "Format penalaran",
|
||||
|
||||
@@ -774,6 +774,9 @@
|
||||
"saveProvider": "プロバイダーを保存",
|
||||
"advancedOptions": "詳細オプション",
|
||||
"saveAdvancedBeforeSignIn": "サインインする前に詳細オプションを保存してください。",
|
||||
"supportedAPIs": "対応する API",
|
||||
"defaultAPI": "デフォルトの API",
|
||||
"declareAPIs": "対応する API を設定",
|
||||
"apiType": "API タイプ",
|
||||
"proxy": "ネットワークプロキシ",
|
||||
"thinkingStyle": "推論の形式",
|
||||
|
||||
@@ -774,6 +774,9 @@
|
||||
"saveProvider": "제공업체 저장",
|
||||
"advancedOptions": "고급 옵션",
|
||||
"saveAdvancedBeforeSignIn": "로그인하기 전에 고급 옵션을 저장하세요.",
|
||||
"supportedAPIs": "지원 API",
|
||||
"defaultAPI": "기본 API",
|
||||
"declareAPIs": "지원 API 설정",
|
||||
"apiType": "API 유형",
|
||||
"proxy": "네트워크 프록시",
|
||||
"thinkingStyle": "추론 형식",
|
||||
|
||||
@@ -1008,6 +1008,9 @@
|
||||
"saveProvider": "Salvar provedor",
|
||||
"advancedOptions": "Opções avançadas",
|
||||
"saveAdvancedBeforeSignIn": "Salve as alterações avançadas antes de entrar.",
|
||||
"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",
|
||||
|
||||
@@ -774,6 +774,9 @@
|
||||
"saveProvider": "Lưu nhà cung cấp",
|
||||
"advancedOptions": "Tùy chọn nâng cao",
|
||||
"saveAdvancedBeforeSignIn": "Lưu các thay đổi nâng cao trước khi đăng nhập.",
|
||||
"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",
|
||||
|
||||
@@ -1194,6 +1194,9 @@
|
||||
"saveProvider": "保存提供商",
|
||||
"advancedOptions": "高级选项",
|
||||
"saveAdvancedBeforeSignIn": "请先保存高级选项再登录。",
|
||||
"supportedAPIs": "支持的协议",
|
||||
"defaultAPI": "默认协议",
|
||||
"declareAPIs": "设置支持的协议",
|
||||
"apiType": "API 类型",
|
||||
"proxy": "网络代理",
|
||||
"thinkingStyle": "推理格式",
|
||||
|
||||
@@ -774,6 +774,9 @@
|
||||
"saveProvider": "儲存供應商",
|
||||
"advancedOptions": "進階選項",
|
||||
"saveAdvancedBeforeSignIn": "請先儲存進階選項再登入。",
|
||||
"supportedAPIs": "支援的協定",
|
||||
"defaultAPI": "預設協定",
|
||||
"declareAPIs": "設定支援的協定",
|
||||
"apiType": "API 類型",
|
||||
"proxy": "網路代理",
|
||||
"thinkingStyle": "推理格式",
|
||||
|
||||
+11
-3
@@ -595,9 +595,11 @@ export interface RuntimeCapabilities {
|
||||
can_export_diagnostics: boolean;
|
||||
}
|
||||
|
||||
export type ModelRequestAPI = "chat_completions" | "responses" | "anthropic_messages";
|
||||
|
||||
export interface ModelAPIConfig {
|
||||
supported_apis: Array<"chat_completions" | "responses">;
|
||||
preferred_api?: "chat_completions" | "responses" | null;
|
||||
supported_apis: ModelRequestAPI[];
|
||||
preferred_api?: ModelRequestAPI | null;
|
||||
}
|
||||
|
||||
export type ProviderRequestAPI =
|
||||
@@ -712,6 +714,7 @@ export interface SettingsPayload {
|
||||
model_configuration_migratable?: boolean;
|
||||
/** Host can resolve the default request API for an unsaved model configuration. */
|
||||
model_api_resolution_supported?: boolean;
|
||||
provider_api_configuration_supported?: boolean;
|
||||
created_model_preset?: string;
|
||||
created_provider?: string;
|
||||
providers: Array<{
|
||||
@@ -727,8 +730,11 @@ export interface SettingsPayload {
|
||||
model_selectable?: boolean;
|
||||
model_catalog?: ProviderModelsPayload["catalog_kind"];
|
||||
model_api_configurable?: boolean;
|
||||
/** Request formats implemented by the host's provider adapter. */
|
||||
/** Request formats allowed by this connection, or adapter formats when undeclared. */
|
||||
request_apis?: ProviderRequestAPI[];
|
||||
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;
|
||||
@@ -1349,6 +1355,7 @@ export interface ProviderSettingsUpdate {
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
apiType?: "auto" | "chat_completions" | "responses";
|
||||
api?: ModelAPIConfig | null;
|
||||
proxy?: string;
|
||||
extraHeaders?: string;
|
||||
extraBody?: string;
|
||||
@@ -1362,6 +1369,7 @@ export interface ProviderCreationUpdate {
|
||||
name: string;
|
||||
apiKey?: string;
|
||||
apiBase: string;
|
||||
api?: ModelAPIConfig | null;
|
||||
proxy?: string;
|
||||
extraHeaders?: string;
|
||||
extraBody?: string;
|
||||
|
||||
@@ -148,6 +148,82 @@ describe("Settings models", () => {
|
||||
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/model-api?"))).toBe(false);
|
||||
});
|
||||
|
||||
it("saves and restores Anthropic Messages for a custom gateway", async () => {
|
||||
let payload = settingsPayload();
|
||||
payload.providers = [{
|
||||
name: "tenant", label: "Tenant", configured: true,
|
||||
request_apis: ["chat_completions", "responses", "anthropic_messages"],
|
||||
}];
|
||||
payload.model_presets[0].provider = "tenant";
|
||||
payload.model_presets[0].resolved_provider = "tenant";
|
||||
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(payload)));
|
||||
requestMutationMock.mockImplementation(async (action, args) => {
|
||||
expect(action).toBe("settings.model_configuration.update");
|
||||
payload = {
|
||||
...payload,
|
||||
model_presets: payload.model_presets.map((preset) => ({ ...preset, api: args.api })),
|
||||
};
|
||||
return payload;
|
||||
});
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
await togglePresetEditor();
|
||||
await openPopover(screen.getByLabelText("API connection"));
|
||||
expect(screen.getAllByRole("option")).toHaveLength(4);
|
||||
fireEvent.click(screen.getByRole("option", { name: "Anthropic Messages" }));
|
||||
expect(screen.queryByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_configuration.update",
|
||||
{ name: "primary", api: { supported_apis: ["anthropic_messages"], preferred_api: "anthropic_messages" } },
|
||||
20_000,
|
||||
));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Save" })).toBeDisabled());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
|
||||
await togglePresetEditor();
|
||||
expect(screen.getByLabelText("API connection")).toHaveTextContent("Anthropic Messages");
|
||||
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
|
||||
await openPopover(screen.getByLabelText("API connection"));
|
||||
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
|
||||
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeChecked();
|
||||
});
|
||||
|
||||
it("saves an explicit API after an Auto provider resolves the changed model to a new connection", async () => {
|
||||
const payload = settingsPayload();
|
||||
payload.model_api_resolution_supported = true;
|
||||
payload.model_presets[0] = {
|
||||
...payload.model_presets[0], provider: "auto", model: "anthropic/claude-sonnet-4",
|
||||
resolved_provider: "anthropic",
|
||||
};
|
||||
payload.providers = [
|
||||
{ name: "anthropic", label: "Anthropic", configured: true, request_apis: ["anthropic_messages"] },
|
||||
{ name: "openai", label: "OpenAI", configured: true, request_apis: ["chat_completions", "responses"] },
|
||||
];
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
if (url.pathname !== "/api/settings/model-api") return jsonResponse(payload);
|
||||
return jsonResponse(url.searchParams.get("model")?.startsWith("gpt")
|
||||
? { provider: "openai", api: "chat_completions" }
|
||||
: { provider: "anthropic", api: "anthropic_messages" });
|
||||
}));
|
||||
requestMutationMock.mockResolvedValue(payload);
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
await togglePresetEditor();
|
||||
await openPopover(screen.getByRole("button", { name: "anthropic/claude-sonnet-4", exact: true }));
|
||||
const search = screen.getByRole("combobox", { name: "Search or type model ID" });
|
||||
fireEvent.change(search, { target: { value: "gpt-4o" } });
|
||||
fireEvent.keyDown(search, { key: "Enter" });
|
||||
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
|
||||
await openPopover(screen.getByLabelText("API connection"));
|
||||
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", {
|
||||
name: "primary", model: "gpt-4o",
|
||||
api: { supported_apis: ["responses"], preferred_api: "responses" },
|
||||
}, 20_000,
|
||||
));
|
||||
});
|
||||
|
||||
it("shows the host's automatic API and discards an older reasoning resolution", async () => {
|
||||
const payload = settingsPayload();
|
||||
payload.model_api_resolution_supported = true;
|
||||
@@ -228,7 +304,7 @@ describe("Settings models", () => {
|
||||
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it.each([undefined, ["future_api"], "responses"])("hides API controls when host support is unconfirmed (%s)", async (requestAPIs) => {
|
||||
it.each([undefined, ["future_api"], ["future_api", "future_api_v2"], "responses"])("hides API controls when host support is unconfirmed (%s)", async (requestAPIs) => {
|
||||
const payload = settingsPayload();
|
||||
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({
|
||||
...payload,
|
||||
|
||||
@@ -981,4 +981,61 @@ describe("Settings providers", () => {
|
||||
screen.getByRole("button", { name: "Add provider" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
it("declares custom connection APIs on creation and preserves them when editing", async () => {
|
||||
const user = userEvent.setup();
|
||||
let payload = settingsPayload();
|
||||
payload.provider_api_configuration_supported = true;
|
||||
const api = { supported_apis: ["anthropic_messages" as const], preferred_api: "anthropic_messages" as const };
|
||||
requestMutationMock.mockImplementation(async (action, args) => {
|
||||
if (action === "settings.provider.create") {
|
||||
payload = {
|
||||
...payload,
|
||||
providers: [...payload.providers, {
|
||||
name: "tenant", label: "Tenant", is_custom: true, configured: true,
|
||||
api_base: args.apiBase, api: args.api,
|
||||
provider_api_configurable: true,
|
||||
request_apis: args.api.supported_apis,
|
||||
}],
|
||||
};
|
||||
}
|
||||
if (action === "settings.provider.update") {
|
||||
payload = { ...payload, providers: payload.providers.map((row) => row.name === "tenant"
|
||||
? { ...row, api: args.api, request_apis: args.api.supported_apis } : row) };
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
await user.click(screen.getByRole("button", { name: "Add provider" }));
|
||||
await user.click(screen.getByRole("button", { name: "Custom provider" }));
|
||||
await user.type(screen.getByPlaceholderText("My model provider"), "Tenant");
|
||||
await user.type(screen.getByPlaceholderText("https://api.example.com/v1"), "https://tenant.test");
|
||||
expect(screen.getByRole("switch", { name: "Chat Completions" })).toBeDisabled();
|
||||
await user.click(screen.getByRole("switch", { name: "Anthropic Messages" }));
|
||||
await user.click(screen.getByRole("switch", { name: "Chat Completions" }));
|
||||
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Anthropic Messages");
|
||||
expect(screen.getByRole("switch", { name: "Anthropic Messages" })).toBeDisabled();
|
||||
await user.click(screen.getByRole("button", { name: "Save provider" }));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.create", expect.objectContaining({ api }), 20_000);
|
||||
await user.click(screen.getByRole("button", { name: "Tenant", exact: true }));
|
||||
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Anthropic Messages");
|
||||
await user.click(screen.getByRole("switch", { name: "Responses" }));
|
||||
await user.click(screen.getByRole("combobox", { name: "Default API" }));
|
||||
await user.click(screen.getByRole("option", { name: "Responses" }));
|
||||
await user.click(screen.getByRole("button", { name: "Save provider" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
|
||||
provider: "tenant", api: { supported_apis: ["anthropic_messages", "responses"], preferred_api: "responses" },
|
||||
}), 20_000));
|
||||
await user.click(screen.getByRole("button", { name: "Tenant", exact: true }));
|
||||
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Responses");
|
||||
});
|
||||
|
||||
it("hides connection API declarations on hosts without the capability", async () => {
|
||||
renderSettingsView({ initialSection: "models", initialSettings: settingsPayload() });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add provider" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Custom provider" }));
|
||||
expect(screen.queryByRole("combobox", { name: "Default API" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "Supported APIs" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
});
|
||||
Reference in new issue
Block a user