import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; import { DisclosureContent } from "@/components/ui/disclosure"; import { ChevronDown, ChevronLeft, ChevronRight, Clipboard, Eye, EyeOff, ExternalLink, Globe2, Hexagon, Loader2, Pencil, Plus, Search, Zap, } from "lucide-react"; import { useTranslation } from "react-i18next"; import { PROVIDER_ICONS } from "@/components/settings/shared/ModelControls"; import { CapabilityInstallNotice, SettingsGroup, SettingsSectionTitle, } from "@/components/settings/shared/SettingsControls"; import { ToggleButton } from "@/components/settings/ToggleButton"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Input } from "@/components/ui/input"; import { ComboboxOption, useComboboxNavigation } from "@/components/ui/combobox"; import { SheetContent } from "@/components/ui/sheet"; import { FloatingPortalContext } from "@/components/ui/floating-portal"; import { Textarea } from "@/components/ui/textarea"; import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor"; import { useLogoFallback } from "@/hooks/useLogoFallback"; import { useMediaQuery } from "@/hooks/useMediaQuery"; import { providerBrand } from "@/lib/provider-brand"; import { cn } from "@/lib/utils"; import type { NanobotFeaturesPayload, ProviderOAuthAuthorizationRequired, SettingsPayload, } from "@/lib/types"; type ProviderApiType = "auto" | "chat_completions" | "responses"; type ProviderAdvancedField = NonNullable< SettingsPayload["providers"][number]["advanced_fields"] >[number]; export type ProviderForm = { displayName: string; apiKey: string; apiBase: string; apiType: ProviderApiType; proxy: string; extraHeaders: string; extraBody: string; extraQuery: string; thinkingStyle: string; region: string; profile: string; }; export type CustomProviderDraft = ProviderForm & { name: string }; const OAUTH_PROXY_PROVIDERS = new Set(["openai_codex", "xai_grok"]); type ProviderRequestOption = { kind: "priority" | "hosted_tool"; titleKey: string; title: string; helpKey: string; help: string; toolType?: "web_search" | "x_search"; defaultEnabled?: boolean; forceResponses?: boolean; }; const PROVIDER_REQUEST_OPTIONS: Partial> = { openai_codex: [{ kind: "priority", titleKey: "settings.providers.capabilityFastMode", title: "Fast mode", helpKey: "settings.providers.capabilityFastModeHelp", help: "Use OpenAI's priority service tier for faster responses. This consumes credits faster.", }], openai: [{ kind: "hosted_tool", titleKey: "settings.providers.capabilityOpenAISearch", title: "OpenAI web search", helpKey: "settings.providers.capabilityOpenAISearchHelp", help: "Allow compatible Responses API models to search the web. Search activity appears in chat.", toolType: "web_search", forceResponses: true, }], deepseek: [{ kind: "hosted_tool", titleKey: "settings.providers.capabilityDeepSeekSearch", title: "DeepSeek web search", helpKey: "settings.providers.capabilityDeepSeekSearchHelp", help: "Let DeepSeek V4 Flash search the web through its Responses API. Search activity appears in chat.", toolType: "web_search", defaultEnabled: true, }], xai_grok: [{ kind: "hosted_tool", titleKey: "settings.providers.capabilityXSearch", title: "X Search", helpKey: "settings.providers.capabilityXSearchHelp", help: "Allow supported Grok models to use xAI-hosted X Search. Search activity appears in chat.", toolType: "x_search", defaultEnabled: true, }], }; export const CUSTOM_PROVIDER_CREATION_KEY = "__custom_provider__"; const CUSTOM_PROVIDER_ADVANCED_FIELDS: ProviderAdvancedField[] = [ "extra_headers", "extra_body", "extra_query", "proxy", "thinking_style", ]; function providerJsonValue(value: Record | null | undefined): string { return value && Object.keys(value).length > 0 ? JSON.stringify(value, null, 2) : ""; } function parseProviderExtraBody(value: string): Record | null { if (!value.trim()) return {}; try { const parsed: unknown = JSON.parse(value); return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record : null; } catch { return null; } } function isHostedSearchTool(tool: unknown, toolType: "web_search" | "x_search"): boolean { if (!tool || typeof tool !== "object" || Array.isArray(tool)) return false; const configuredType = (tool as Record).type; if (typeof configuredType !== "string") return false; return configuredType === toolType || (toolType === "web_search" && configuredType.startsWith("web_search_")); } function hasHostedSearchTool(value: unknown, toolType: "web_search" | "x_search"): boolean { return Array.isArray(value) && value.some((tool) => isHostedSearchTool(tool, toolType)); } function providerRequestOptionEnabled( option: ProviderRequestOption, extraBody: Record, ): boolean { if (option.kind === "priority") return extraBody.service_tier === "priority"; if (Object.prototype.hasOwnProperty.call(extraBody, "tools")) { return hasHostedSearchTool(extraBody.tools, option.toolType!); } return option.defaultEnabled === true; } function updateProviderRequestOption( option: ProviderRequestOption, enabled: boolean, form: ProviderForm, ): Partial { const extraBody = { ...(parseProviderExtraBody(form.extraBody) ?? {}) }; if (option.kind === "priority") { if (enabled) extraBody.service_tier = "priority"; else if (extraBody.service_tier === "priority") delete extraBody.service_tier; } else { const toolType = option.toolType!; const tools = Array.isArray(extraBody.tools) ? extraBody.tools.filter((tool) => !isHostedSearchTool(tool, toolType)) : []; if (enabled) tools.push({ type: toolType }); if (tools.length || option.defaultEnabled) { extraBody.tools = tools; } else { delete extraBody.tools; } } return { extraBody: providerJsonValue(extraBody), ...(option.forceResponses && enabled ? { apiType: "responses" as const } : {}), }; } export function providerFormFromRow( provider: SettingsPayload["providers"][number], ): ProviderForm { return { displayName: provider.is_custom ? provider.label : "", apiKey: "", apiBase: provider.api_base ?? provider.default_api_base ?? "", apiType: provider.api_type ?? "auto", proxy: provider.proxy ?? "", extraHeaders: providerJsonValue(provider.extra_headers), extraBody: providerJsonValue(provider.extra_body), extraQuery: providerJsonValue(provider.extra_query), thinkingStyle: provider.thinking_style ?? "", region: provider.region ?? "", profile: provider.profile ?? "", }; } function emptyCustomProviderDraft(): CustomProviderDraft { return { name: "", displayName: "", apiKey: "", apiBase: "", apiType: "auto", proxy: "", extraHeaders: "", extraBody: "", extraQuery: "", thinkingStyle: "", region: "", profile: "", }; } 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, index, ]), ); export function ProviderOAuthLoginDialog({ flow, providerLabel, authorizationResponse, completing, error, remoteBrowserAccess, onAuthorizationResponseChange, onOpenAuthorization, onComplete, onClose, }: { flow: ProviderOAuthAuthorizationRequired | null; providerLabel: string; authorizationResponse: string; completing: boolean; error: string | null; remoteBrowserAccess: boolean; onAuthorizationResponseChange: (value: string) => void; onOpenAuthorization: () => void; onComplete: () => void; onClose: () => void; }) { const { t } = useTranslation(); const expectsCallbackUrl = flow?.completion_input === "callback_url"; const inputId = expectsCallbackUrl ? "provider-oauth-callback" : "provider-oauth-code"; const inputLabel = expectsCallbackUrl ? t("settings.oauth.callbackUrl") : t("settings.oauth.authorizationCode"); return ( { if (!open) onClose(); }} >
{ event.preventDefault(); onComplete(); }} > {providerLabel} {expectsCallbackUrl ? remoteBrowserAccess ? t("settings.oauth.remoteCallbackHelp") : t("settings.oauth.localCallbackHelp") : remoteBrowserAccess ? t("settings.oauth.remoteCodeHelp") : t("settings.oauth.localCodeHelp")}
{expectsCallbackUrl && remoteBrowserAccess ? ( ) : ( )} {expectsCallbackUrl && remoteBrowserAccess ? t("settings.oauth.pasteCallbackToContinue") : t("settings.oauth.waitingForCallback")}
{expectsCallbackUrl ? (