/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import React, { useEffect, useRef } from 'react'; import { Select, Spin, Typography, Empty, Tag, Tooltip } from '@/components/ui'; import { Lock } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { useModelSelector } from '../../hooks/models/useModelSelector'; import { MODEL_CATEGORY_NAMES } from '../../constants'; const { Text } = Typography; /** * 模型选择器组件 * @param {string} category - 模型分类(可选) * @param {string} value - 当前选中的模型ID或名称 * @param {function} onChange - 模型变化回调 * @param {string} placeholder - 占位文本 * @param {boolean} disabled - 是否禁用 * @param {string} size - 尺寸 */ const ModelSelector = ({ category = null, value, onChange, placeholder, disabled = false, size = 'default', showCategoryLabel = false, // 加载完成后向父组件回传模型列表(用于父组件按 name 反查 model 对象,避免重复 fetch) onModelsLoaded, // 是否在初次加载完成后自动选中第一个模型(外部需要"先回填再生成"时可关闭) autoSelectFirst = true, }) => { const { t } = useTranslation(); const { models, loading, selectedModel, setSelectedModel } = useModelSelector(category); const isInitializedRef = useRef(false); // 当模型加载完成时,自动选择第一个「可调用」模型(避免默认选中锁定模型) useEffect(() => { if (!loading && models.length > 0 && !isInitializedRef.current) { if (autoSelectFirst) { const firstModel = models.find((m) => !m.level_locked); setSelectedModel(firstModel || null); if (firstModel && onChange) { onChange(firstModel); } } isInitializedRef.current = true; } }, [loading, models, setSelectedModel, onChange, autoSelectFirst]); // 把加载好的模型列表传给父组件 useEffect(() => { if (!onModelsLoaded) return; if (loading) return; onModelsLoaded(models); }, [models, loading, onModelsLoaded]); // 处理模型选择:锁定(仅可见)模型不可选中 const handleChange = (selectedValue) => { const model = models.find( (m) => m.id === selectedValue || m.model_name === selectedValue, ); if (model && !model.level_locked) { setSelectedModel(model); if (onChange) { onChange(model); } } }; // 渲染模型选项:level_state=visible 展示锁态并禁用 const renderOption = (model) => { const locked = model.level_locked; return (
{model.model_name} {model.vendor && ( ({model.vendor}) )} {locked && ( } style={{ marginLeft: '8px' }} > {t('仅可见')} )}
); }; if (loading) { return (
); } if (models.length === 0) { return ( ); } return (
{showCategoryLabel && category && ( {MODEL_CATEGORY_NAMES[category]} )}
); }; export default ModelSelector;