refactor(models): separate API routing and editor state

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-10 01:33:02 +08:00
1 parent 5eb160099b
commit ed0eb89178
11 files changed
+357 -319

No files matched your search

@@ -1,31 +1,13 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { modelAPIConfigurable, preferredModelAPI, REQUEST_API_LABELS } from "@/components/settings/models/modelAPI";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { SettingsRow } from "@/components/settings/shared/SettingsControls";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import type { ModelAPIConfig, ProviderRequestAPI, SettingsPayload } from "@/lib/types";
export function modelAPIConfigurable(provider: SettingsPayload["providers"][number] | undefined): boolean {
if (Array.isArray(provider?.request_apis)) {
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"
? "prefer_responses"
: "prefer_chat";
}
export function ModelAPIControl({
provider,
automaticAPI,
@@ -43,17 +25,13 @@ export function ModelAPIControl({
const configurable = modelAPIConfigurable(provider);
const fixedAPI = requestAPIs?.length === 1 ? requestAPIs[0] : undefined;
const labels = {
responses: "Responses",
chat_completions: "Chat Completions",
anthropic_messages: "Anthropic Messages",
...REQUEST_API_LABELS,
bedrock_converse: "Bedrock Converse",
transcription: t("settings.models.apiTranscription"),
};
const fixedLabel = fixedAPI ? labels[fixedAPI] : undefined;
const selection = modelAPISelection(value);
const selectedAPI = selection === "prefer_responses" ? "responses"
: selection === "prefer_chat" ? "chat_completions" : selection;
const allowChatFallback = selection === "prefer_responses";
const selectedAPI = preferredModelAPI(value);
const allowChatFallback = selectedAPI === "responses" && value?.supported_apis.includes("chat_completions") === true;
const options = [
{
value: "auto",
@@ -1,5 +1,6 @@
import { ProviderIcon } from "@/components/settings/models/ProviderSettings";
import { ModelAPIControl } from "@/components/settings/models/ModelAPIControl";
import { useAutomaticModelAPI } from "@/components/settings/models/useAutomaticModelAPI";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";
@@ -43,8 +44,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { fetchAutomaticModelAPI } from "@/lib/api";
import type { AutomaticModelAPIPayload, ModelAPIConfig, SettingsPayload } from "@/lib/types";
import type { ModelAPIConfig, SettingsPayload } from "@/lib/types";
export interface AgentSettingsDraft {
model: string;
@@ -238,30 +238,15 @@ export function ModelsSettings({
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
t(key, { defaultValue: fallback, ...(values ?? {}) });
const [editorOpen, setEditorOpen] = useState(false);
const [automaticAPI, setAutomaticAPI] = useState<{
scope: string;
result: AutomaticModelAPIPayload;
} | null>(null);
const { provider: apiProvider, model: apiModel, reasoningEffort: apiReasoningEffort } = form;
const automaticAPIScope = JSON.stringify([
token, apiProvider, apiModel, apiReasoningEffort, settings.providers,
]);
useEffect(() => {
if (!editorOpen || settings.model_api_resolution_supported !== true || !apiModel.trim()) return;
let cancelled = false;
const timer = window.setTimeout(() => {
void fetchAutomaticModelAPI(token, apiProvider, apiModel, apiReasoningEffort)
.then((result) => {
if (!cancelled) setAutomaticAPI({ scope: automaticAPIScope, result });
})
.catch(() => {
if (!cancelled) setAutomaticAPI(null);
});
}, 150);
return () => { cancelled = true; window.clearTimeout(timer); };
}, [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 resolvedAutomaticAPI = useAutomaticModelAPI({
token,
provider: form.provider,
model: form.model,
reasoningEffort: form.reasoningEffort,
providers: settings.providers,
supported: settings.model_api_resolution_supported === true,
editorOpen,
});
const editorTriggerRef = useRef<HTMLElement | null>(null);
const presetNameInputRef = useRef<HTMLInputElement>(null);
const suggestedPresetNameRef = useRef<string | null>(null);
@@ -1,16 +1,11 @@
import { useTranslation } from "react-i18next";
import { MODEL_REQUEST_APIS, REQUEST_API_LABELS } from "@/components/settings/models/modelAPI";
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;
@@ -33,17 +28,17 @@ export function ProviderAPIControl({ value, onChange }: {
<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);
{MODEL_REQUEST_APIS.map((api) => {
const checked = supported.includes(api);
return (
<div key={api.value} className="flex items-center justify-between gap-3 text-[13px]">
<span>{api.label}</span>
<div key={api} className="flex items-center justify-between gap-3 text-[13px]">
<span>{REQUEST_API_LABELS[api]}</span>
<ToggleButton
label={api.label}
label={REQUEST_API_LABELS[api]}
checked={checked}
disabled={checked && supported.length === 1}
onChange={(enabled) => {
const next = enabled ? [...supported, api.value] : supported.filter((item) => item !== api.value);
const next = enabled ? [...supported, api] : supported.filter((item) => item !== api);
onChange({ supported_apis: next, preferred_api: next.includes(preferred) ? preferred : next[0] });
}}
/>
@@ -62,8 +57,8 @@ export function ProviderAPIControl({ value, onChange }: {
<SelectValue />
</SelectTrigger>
<SelectContent>
{APIS.filter((api) => supported.includes(api.value)).map((api) => (
<SelectItem key={api.value} value={api.value}>{api.label}</SelectItem>
{MODEL_REQUEST_APIS.filter((api) => supported.includes(api)).map((api) => (
<SelectItem key={api} value={api}>{REQUEST_API_LABELS[api]}</SelectItem>
))}
</SelectContent>
</Select>
@@ -0,0 +1,32 @@
import type { ModelAPIConfig, ModelRequestAPI, SettingsPayload } from "@/lib/types";
export const MODEL_REQUEST_APIS = ["chat_completions", "responses", "anthropic_messages"] as const;
export const REQUEST_API_LABELS: Record<ModelRequestAPI, string> = {
chat_completions: "Chat Completions",
responses: "Responses",
anthropic_messages: "Anthropic Messages",
};
export function modelAPIConfigurable(provider: SettingsPayload["providers"][number] | undefined): boolean {
if (Array.isArray(provider?.request_apis)) {
const supported = provider.request_apis;
return MODEL_REQUEST_APIS.filter((api) => supported.includes(api)).length > 1;
}
return provider?.model_api_configurable === true;
}
export function preferredModelAPI(api: ModelAPIConfig | null | undefined): ModelRequestAPI | "auto" {
return api?.preferred_api ?? api?.supported_apis[0] ?? "auto";
}
export function modelAPISelection(api: ModelAPIConfig | null | undefined): string {
const preferred = preferredModelAPI(api);
if (preferred === "responses" && api?.supported_apis.includes("chat_completions")) {
return "prefer_responses";
}
if (preferred === "chat_completions" && api?.supported_apis.includes("responses")) {
return "prefer_chat";
}
return preferred;
}
@@ -0,0 +1,42 @@
import { useEffect, useState } from "react";
import { fetchAutomaticModelAPI } from "@/lib/api";
import type { AutomaticModelAPIPayload, SettingsPayload } from "@/lib/types";
export function useAutomaticModelAPI({
token, provider, model, reasoningEffort, providers, supported, editorOpen,
}: {
token: string;
provider: string;
model: string;
reasoningEffort: string;
providers: SettingsPayload["providers"];
supported: boolean;
editorOpen: boolean;
}): AutomaticModelAPIPayload | null {
const scope = JSON.stringify([token, provider, model, reasoningEffort, providers]);
const [preview, setPreview] = useState<{
scope: string;
result: AutomaticModelAPIPayload;
} | null>(null);
useEffect(() => {
if (!editorOpen || !supported || !model.trim()) return;
let cancelled = false;
const timer = window.setTimeout(() => {
void fetchAutomaticModelAPI(token, provider, model, reasoningEffort)
.then((result) => {
if (!cancelled) setPreview({ scope, result });
})
.catch(() => {
if (!cancelled) setPreview(null);
});
}, 150);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}, [editorOpen, supported, scope, token, provider, model, reasoningEffort]);
return supported && preview?.scope === scope ? preview.result : null;
}
@@ -7,7 +7,7 @@ import type {
PendingRestartSections,
} from "@/components/settings/contracts";
import { agentDraftFromPayload } from "@/components/settings/models/ModelsSettings";
import { modelAPISelection } from "@/components/settings/models/ModelAPIControl";
import { modelAPISelection } from "@/components/settings/models/modelAPI";
import {
CUSTOM_PROVIDER_CREATION_KEY,
providerFormFromRow,
@@ -20,7 +20,7 @@ import type {
SettingsSectionKey,
} from "@/components/settings/contracts";
import { agentDraftFromPayload } from "@/components/settings/models/ModelsSettings";
import { modelAPISelection } from "@/components/settings/models/ModelAPIControl";
import { modelAPISelection } from "@/components/settings/models/modelAPI";
import { useModelSettingsActions } from "@/components/settings/models/useModelSettingsActions";
import {
useProviderFormsSync,