import { useState, useMemo, useEffect, memo } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert, Bot } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command'; import { Skeleton } from '@/components/ui/skeleton'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { useAISettings } from '@/hooks/useAISettings'; import { useProviderModels } from '@/hooks/useProviderModels'; import { useIsMobile } from '@/hooks/useIsMobile'; import { ModelPricing } from '@/components/ModelPricing'; import { ExternalFavicon } from '@/components/ExternalFavicon'; import { cn } from '@/lib/utils'; interface ModelSelectorProps { value: string; onChange: (value: string) => void; className?: string; disabled?: boolean; placeholder?: string; open?: boolean; onOpenChange?: (open: boolean) => void; } export const ModelSelector = memo(function ModelSelector({ value, onChange, className, disabled = false, placeholder, open: controlledOpen, onOpenChange: setControlledOpen, }: ModelSelectorProps) { const { t } = useTranslation(); const [uncontrolledOpen, setUncontrolledOpen] = useState(false); const [isTooltipOpen, setIsTooltipOpen] = useState(false); // Use controlled state if provided, otherwise use local state const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; const setOpen = setControlledOpen || setUncontrolledOpen; const [isCustomInput, setIsCustomInput] = useState(false); const [customValue, setCustomValue] = useState(''); const { settings, addRecentlyUsedModel, isConfigured, isLoading: isLoadingSettings } = useAISettings(); const { models: allModels, isLoading, error, refetch } = useProviderModels(); const navigate = useNavigate(); const isMobile = useIsMobile(); // Filter models to only include chat models (type is undefined or "chat") const models = useMemo(() => { return allModels.filter(model => model.type === undefined || model.type === 'chat'); }, [allModels]); const defaultPlaceholder = t('selectOrEnterModel'); const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]); // Create a Set of recently used model IDs for efficient lookup const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]); // Determine if we should show the "Recently Used" section const shouldShowRecentlyUsed = useMemo(() => { // If no recently used models, don't show the section if (recentlyUsedModels.length === 0) { return false; } // If there are 5 or more total provider models, always show recently used if (models.length >= 5) { return true; } // If less than 5 total provider models, check if all recently used models // are contained within the available provider models const availableModelIds = new Set(models.map(model => model.fullId)); const allRecentlyUsedAreAvailable = recentlyUsedModels.every(model => availableModelIds.has(model) ); // Hide recently used section if all recently used models are already available return !allRecentlyUsedAreAvailable; }, [recentlyUsedModels, models]); // Group models by provider, excluding models that are in the recently used section // (only exclude them if the recently used section is actually being shown) const modelsByProvider = useMemo(() => { const groups: Record = {}; for (const model of models) { // Only skip models that are in recently used if we're showing the recently used section if (shouldShowRecentlyUsed && recentlyUsedSet.has(model.fullId)) { continue; } if (!groups[model.provider]) { groups[model.provider] = []; } groups[model.provider].push(model); } return groups; }, [models, recentlyUsedSet, shouldShowRecentlyUsed]); // Get provider display name and baseURL for a given provider ID const getProviderInfo = useMemo(() => { return (providerId: string) => { const provider = settings.providers.find(p => p.id === providerId); return { displayName: provider ? provider.name : providerId, baseURL: provider?.baseURL, }; }; }, [settings.providers]); // Get display info for the selected model const selectedModelDisplay = useMemo(() => { if (!value) return null; const providerId = value.split('/')[0]; const modelId = value.split('/').slice(1).join('/') || value; const providerInfo = getProviderInfo(providerId); const modelData = models.find(m => m.fullId === value); const displayName = modelData?.name || modelId; return { displayName, baseURL: providerInfo.baseURL, }; }, [value, getProviderInfo, models]); // Check if the current model is free const isCurrentModelFree = useMemo(() => { if (!value) return false; const currentModel = models.find(model => model.fullId === value); if (!currentModel?.pricing) return false; return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0); }, [value, models]); // Check if the current model is not in the provider's model list const isCurrentModelNotInList = useMemo(() => { if (!value) return false; if (isLoading) return false; // Don't show warning while loading if (models.length === 0) return false; // Don't show warning if no models loaded const currentModel = models.find(model => model.fullId === value); return !currentModel; }, [value, models, isLoading]); // Determine if we should show the warning icon const shouldShowWarning = isCurrentModelFree || isCurrentModelNotInList; // Get the warning message const warningMessage = useMemo(() => { if (isCurrentModelNotInList) { return "This model is not available in your provider's model list. It may not work or may have been deprecated."; } if (isCurrentModelFree) { return "You are using a free model. For better results, switch to a paid model."; } return ""; }, [isCurrentModelNotInList, isCurrentModelFree]); // Don't auto-initialize with recently used models // Let the parent component handle initialization // Close tooltip when clicking outside on mobile useEffect(() => { if (!isMobile || !isTooltipOpen) return; const handleClickOutside = (event: MouseEvent | TouchEvent) => { const target = event.target as Element; // Check if the click is outside the tooltip and trigger if (!target.closest('[data-radix-tooltip-content]') && !target.closest('[data-radix-tooltip-trigger]') && !target.closest('[data-testid="triangle-alert"]')) { setIsTooltipOpen(false); } }; // Add both click and touch event listeners document.addEventListener('click', handleClickOutside, true); document.addEventListener('touchstart', handleClickOutside, true); return () => { document.removeEventListener('click', handleClickOutside, true); document.removeEventListener('touchstart', handleClickOutside, true); }; }, [isMobile, isTooltipOpen]); const handleSelect = (selectedValue: string) => { if (selectedValue === '__custom__') { setIsCustomInput(true); setCustomValue(value); setOpen(false); return; } if (selectedValue === '__manage_providers__') { navigate('/settings/ai'); setOpen(false); return; } onChange(selectedValue); addRecentlyUsedModel(selectedValue); setOpen(false); }; const handleCustomSubmit = () => { if (customValue.trim()) { onChange(customValue.trim()); addRecentlyUsedModel(customValue.trim()); setIsCustomInput(false); setCustomValue(''); } }; const handleCustomKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault(); handleCustomSubmit(); } else if (e.key === 'Escape') { setIsCustomInput(false); setCustomValue(''); } }; if (isCustomInput) { return (
setCustomValue(e.target.value)} onKeyDown={handleCustomKeyDown} onBlur={handleCustomSubmit} placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)" className="h-8 text-xs" autoFocus />
); } return (
{shouldShowWarning && (

{warningMessage}

)} {(isConfigured && models.length >= 5) && ( )}

{t('noModelsFound')}

{t('tryCustomModel')}

{shouldShowRecentlyUsed && ( {recentlyUsedModels.map((modelId) => { const modelData = models.find(m => m.fullId === modelId); const providerId = modelId.split('/')[0]; const providerInfo = getProviderInfo(providerId); const displayModelId = modelId.split('/').slice(1).join('/') || modelId; const displayName = modelData?.name || displayModelId; return ( handleSelect(modelId)} className="cursor-pointer" > {providerInfo.baseURL ? ( } className="mr-2 flex-shrink-0" /> ) : ( )} {displayName} {modelData?.pricing && ( )} ); })} )} {shouldShowRecentlyUsed && } {/* Loading state */} {isLoading && (
)} {/* Error state */} {error && !isLoading && (

{error}

)} {/* Provider models */} {!isLoading && Object.entries(modelsByProvider).map(([providerId, providerModels]) => { const providerInfo = getProviderInfo(providerId); return (
{providerModels.map((model) => ( handleSelect(model.fullId)} className="cursor-pointer" > {providerInfo.baseURL ? ( } className="mr-2 flex-shrink-0" /> ) : ( )} {model.name || model.id} {model.pricing && ( )} ))}
); })} {/* Custom model option and manage providers - moved to bottom */} {isConfigured && ( handleSelect('__custom__')} className="cursor-pointer" > {t('enterCustomModel')} )} handleSelect('__manage_providers__')} className="cursor-pointer" > {t('manageProviders')}
); });