import { toGroupList } from '@/helpers/groupList'; import { formatIdReference } from '../../../../helpers/safeDisplay'; import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import '../../../console/module-alignment.css'; import React, { useEffect, useState, useRef, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import { API, showError, showInfo, showSuccess, verifyJSON, } from '../../../../helpers'; import { useIsMobile } from '../../../../hooks/common/useIsMobile'; import { CHANNEL_OPTIONS } from '../../../../constants'; import { SideSheet, Space, Spin, Button, Typography, Checkbox, Banner, Modal, ImagePreview, Card, Tag, Avatar, Form, Row, Col, Highlight, } from '@/components/ui'; import { getChannelModels, copy, getChannelIcon, getModelCategories, selectFilter, } from '../../../../helpers'; import ModelSelectModal from './ModelSelectModal'; import { mergeChannelSettings } from '../../../../helpers/baiduChannelSettings'; import JSONEditor from '../../../common/ui/JSONEditor'; import SecureVerificationModal from '../../../common/modals/SecureVerificationModal'; import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay'; import { useSecureVerification } from '../../../../hooks/common/useSecureVerification'; import { createApiCalls } from '../../../../services/secureVerification'; import { Code, Globe, Server, Settings, Zap } from 'lucide-react'; const { Text } = Typography; const MODEL_MAPPING_EXAMPLE = { 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125', }; const STATUS_CODE_MAPPING_EXAMPLE = { 400: '500', }; const REGION_EXAMPLE = { default: 'global', 'gemini-1.5-pro-002': 'europe-west2', 'gemini-1.5-flash-002': 'europe-west2', 'claude-3-5-sonnet-20240620': 'europe-west1', }; // 支持并且已适配通过接口获取模型列表的渠道类型 const MODEL_FETCHABLE_TYPES = new Set([ 1, 4, 14, 34, 17, 26, 27, 24, 47, 25, 20, 23, 31, 35, 40, 42, 48, 43, ]); function type2secretPrompt(type) { // inputs.type === 15 ? '按照如下格式输入:APIKey|SecretKey' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥') switch (type) { case 15: return '按照如下格式输入:APIKey|SecretKey'; case 18: return '按照如下格式输入:APPID|APISecret|APIKey'; case 22: return '按照如下格式输入:APIKey-AppId,例如:fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041'; case 23: return '按照如下格式输入:AppId|SecretId|SecretKey'; case 33: return '按照如下格式输入:Ak|Sk|Region'; case 45: return '请输入渠道对应的鉴权密钥, 豆包语音输入:AppId|AccessToken'; case 50: return '按照如下格式输入: AccessKey|SecretKey, 如果上游是New API,则直接输ApiKey'; case 51: return '按照如下格式输入: AccessKey|SecretAccessKey'; case 57: case 59: return '按照如下格式输入:SecretId|SecretKey|SubAppId[|Region]'; default: return '请输入渠道对应的鉴权密钥'; } } // 工作时间小时选项列表(0-23),提升到组件外部避免重复创建 const WORK_HOURS_OPTIONS = Array.from({ length: 24 }, (_, i) => ({ value: i, label: `${String(i).padStart(2, '0')}:00`, })); // 时区选项列表 const TIMEZONE_OPTIONS = [ { value: 'Asia/Shanghai', label: 'Asia/Shanghai (UTC+8)' }, { value: 'Asia/Tokyo', label: 'Asia/Tokyo (UTC+9)' }, { value: 'Asia/Singapore', label: 'Asia/Singapore (UTC+8)' }, { value: 'Asia/Hong_Kong', label: 'Asia/Hong_Kong (UTC+8)' }, { value: 'America/New_York', label: 'America/New_York (UTC-5)' }, { value: 'America/Los_Angeles', label: 'America/Los_Angeles (UTC-8)' }, { value: 'America/Chicago', label: 'America/Chicago (UTC-6)' }, { value: 'Europe/London', label: 'Europe/London (UTC+0)' }, { value: 'Europe/Paris', label: 'Europe/Paris (UTC+1)' }, { value: 'Europe/Berlin', label: 'Europe/Berlin (UTC+1)' }, { value: 'Pacific/Auckland', label: 'Pacific/Auckland (UTC+12)' }, { value: 'Australia/Sydney', label: 'Australia/Sydney (UTC+10)' }, { value: 'UTC', label: 'UTC (UTC+0)' }, ]; // 表单初始值定义在组件外部,保持引用稳定,避免 Semi Design Form 的 initValues 在每次渲染时创建新对象 const originInputs = { name: '', type: 1, key: '', openai_organization: '', max_input_tokens: 0, base_url: '', other: '', model_mapping: '', status_code_mapping: '', models: [], auto_ban: true, test_model: '', groups: ['default'], priority: 0, weight: 0, fallback_channel_ids: [], // 兜底渠道 ID 数组,按数组顺序为兜底链;空数组 = 不启用兜底 fallback_primary_attempts: 1, // 主渠道连续失败达到该次数才切兜底(1 = 失败即切) fallback_hop_attempts: 1, // 兜底链每一跳连续失败达到该次数才切下一个 region: '', // 渠道地域(CN/US/EU/SG/JP),用于跨境合规判定;空 = 未标记 daily_quota_limit: 0, work_hours_start: undefined, work_hours_end: undefined, work_hours_timezone: 'Asia/Shanghai', tag: '', multi_key_mode: 'random', // 渠道额外设置的默认值 ali_data_inspection_disabled: false, baidu_liveness_header_mode: 'legacy', force_format: false, thinking_to_content: false, proxy: '', pass_through_body_enabled: false, pass_through_model_mapping_enabled: false, chat_image_to_images_enabled: false, system_prompt: '', system_prompt_override: false, responses_system_prompt_mode: 'native', client_only: false, // 只接受 Claude Code 客户端请求 bound_user_ids: '', // 绑定用户ID列表 os_restriction: [], // 操作系统白名单,仅 Claude 原生渠道(type=14)生效,空数组=无限制 client_type_restriction: [], // 客户端类型白名单(cli/vscode),仅 type=14 生效 client_version_min: '', // 客户端版本下界(x.y.z),空=从最早 client_version_max: '', // 客户端版本上界(x.y.z),空=至最新 sticky_user_id_fill: false, // 为缺失的 metadata.user_id 补会话内稳定值,让上游按 user_id 哈希粘号 sticky_user_id_mode: 'native', // 注入形态:native(仿 Claude Code 原生)/ opaque cache_breakpoint_fill: false, // 给完全没有 cache_control 的大上下文请求补一个缓存断点 cache_breakpoint_min_tokens: 0, // 注入门限(估算 prompt token),0=用后端默认 10000 cache_creation_default_ttl: '', // 未分档缓存创建按哪档计费,''=跟随全局,可选 5m/1h settings: '', // 仅 Vertex: 密钥格式(存入 settings.vertex_key_type) vertex_key_type: 'json', // 仅 AWS: 密钥格式和区域(存入 settings.aws_key_type 和 settings.aws_region) aws_key_type: 'ak_sk', // 企业账户设置 is_enterprise_account: false, // 字段透传控制默认值 allow_service_tier: false, disable_store: false, // false = 允许透传(默认开启) allow_safety_identifier: false, }; const EditChannelModal = (props) => { const { t } = useTranslation(); const channelId = props.editingChannel.id; const isEdit = channelId !== undefined; const [loading, setLoading] = useState(isEdit); const isMobile = useIsMobile(); const handleCancel = () => { props.handleClose(); }; const [batch, setBatch] = useState(false); const [multiToSingle, setMultiToSingle] = useState(false); const [multiKeyMode, setMultiKeyMode] = useState('random'); const [inputs, setInputs] = useState(originInputs); const [originModelOptions, setOriginModelOptions] = useState([]); const [modelOptions, setModelOptions] = useState([]); const [groupOptions, setGroupOptions] = useState([]); const [basicModels, setBasicModels] = useState([]); const [fullModels, setFullModels] = useState([]); const [modelGroups, setModelGroups] = useState([]); const [customModel, setCustomModel] = useState(''); const [modalImageUrl] = useState(''); const [isModalOpenurl, setIsModalOpenurl] = useState(false); const [modelModalVisible, setModelModalVisible] = useState(false); const [fetchedModels, setFetchedModels] = useState([]); const formApiRef = useRef(null); const [vertexKeys, setVertexKeys] = useState([]); const [vertexFileList, setVertexFileList] = useState([]); const vertexErroredNames = useRef(new Set()); // 避免重复报错 const [isMultiKeyChannel, setIsMultiKeyChannel] = useState(false); const [channelSearchValue, setChannelSearchValue] = useState(''); const [useManualInput, setUseManualInput] = useState(false); // 是否使用手动输入模式 const [keyMode, setKeyMode] = useState('append'); // 密钥模式:replace(覆盖)或 append(追加) const [, setIsEnterpriseAccount] = useState(false); // 是否为企业账户 const [doubaoApiEditUnlocked, setDoubaoApiEditUnlocked] = useState(false); // 豆包渠道自定义 API 地址隐藏入口 const redirectModelList = useMemo(() => { const mapping = inputs.model_mapping; if (typeof mapping !== 'string') return []; const trimmed = mapping.trim(); if (!trimmed) return []; try { const parsed = JSON.parse(trimmed); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return []; } const values = Object.values(parsed) .map((value) => (typeof value === 'string' ? value.trim() : undefined)) .filter((value) => value); return Array.from(new Set(values)); } catch (error) { return []; } }, [inputs.model_mapping]); // 密钥显示状态 const [keyDisplayState, setKeyDisplayState] = useState({ showModal: false, keyData: '', }); // 专门的2FA验证状态(用于TwoFactorAuthModal) const [_show2FAVerifyModal, _setShow2FAVerifyModal] = useState(false); const [_verifyCode, _setVerifyCode] = useState(''); const [_verifyLoading, _setVerifyLoading] = useState(false); // 兜底渠道候选列表(用于"兜底渠道"下拉选择) // 走专用接口拉全部渠道(不分页、含禁用),过滤掉自己; // 禁用渠道作为 disabled option 仅用于回显,不能新增 // 请求序号:弹窗切换渠道时丢弃过期响应,避免 A 的数据落到 B 上 const fallbackLoadSeqRef = useRef(0); const [fallbackCandidates, setFallbackCandidates] = useState([]); const [fallbackCandidatesLoaded, setFallbackCandidatesLoaded] = useState(false); const loadFallbackCandidates = async (seq, selfId) => { try { const res = await API.get('/api/channel/fallback_candidates'); if (seq !== fallbackLoadSeqRef.current) return; if (res?.data?.success && Array.isArray(res.data.data)) { setFallbackCandidates( res.data.data .filter((ch) => ch.id !== selfId) .map((ch) => { const label = `${formatIdReference(ch.id)} ${ch.name}`; if (ch.status !== 1) { const searchLabel = `${label}${t('(已禁用)')}`; return { value: ch.id, label, searchLabel, title: searchLabel, disabled: true, }; } const searchLabel = [label, ch.group, ch.region] .filter(Boolean) .join(' · '); return { value: ch.id, label, searchLabel }; }), ); setFallbackCandidatesLoaded(true); } } catch (err) { console.error('加载兜底渠道候选失败:', err); } }; // 反向引用:当前渠道被哪些其他渠道列为兜底(Phase 3) const [fallbackReferrers, setFallbackReferrers] = useState([]); const loadFallbackReferrers = async (seq, selfId) => { if (selfId === undefined || selfId === null) return; try { const res = await API.get(`/api/channel/${selfId}/fallback_referrers`); if (seq !== fallbackLoadSeqRef.current) return; if (res?.data?.success && Array.isArray(res.data.data)) { setFallbackReferrers(res.data.data); } } catch (err) { console.error('加载反向引用失败:', err); } }; const reloadFallbackData = () => { fallbackLoadSeqRef.current += 1; const seq = fallbackLoadSeqRef.current; setFallbackReferrers([]); setFallbackCandidates([]); setFallbackCandidatesLoaded(false); loadFallbackCandidates(seq, channelId); loadFallbackReferrers(seq, channelId); }; // 兜底链下拉选项:候选 + 链中已存在但候选里没有的 ID(渠道已删除)。 // 仅在候选加载成功后才补"已删除",避免加载中把全部 ID 误标为已删除 const fallbackOptionList = useMemo(() => { const ids = Array.isArray(inputs.fallback_channel_ids) ? inputs.fallback_channel_ids : []; if (!fallbackCandidatesLoaded || ids.length === 0) { return fallbackCandidates; } const known = new Set(fallbackCandidates.map((o) => o.value)); const missing = ids .filter((id) => !known.has(id) && id !== channelId) .map((id) => ({ value: id, label: `${formatIdReference(id)}${t('(已删除)')}`, disabled: true, })); return missing.length ? [...fallbackCandidates, ...missing] : fallbackCandidates; }, [ fallbackCandidates, fallbackCandidatesLoaded, inputs.fallback_channel_ids, channelId, t, ]); const doubaoApiClickCountRef = useRef(0); const initialModelsRef = useRef([]); const initialModelMappingRef = useRef(''); // 使用通用安全验证 Hook const { isModalVisible, verificationMethods, verificationState, withVerification, executeVerification, cancelVerification, setVerificationCode, switchVerificationMethod, } = useSecureVerification({ onSuccess: (result) => { // 验证成功后显示密钥 console.log('Verification success, result:', result); if (result && result.success && result.data?.key) { showSuccess(t('密钥获取成功')); setKeyDisplayState({ showModal: true, keyData: result.data.key, }); } else if (result && result.key) { // 直接返回了 key(没有包装在 data 中) showSuccess(t('密钥获取成功')); setKeyDisplayState({ showModal: true, keyData: result.key, }); } }, }); // 重置密钥显示状态 const resetKeyDisplayState = () => { setKeyDisplayState({ showModal: false, keyData: '', }); }; const handleApiConfigSecretClick = () => { if (inputs.type !== 45) return; const next = doubaoApiClickCountRef.current + 1; doubaoApiClickCountRef.current = next; if (next >= 10) { setDoubaoApiEditUnlocked((unlocked) => { if (!unlocked) { showInfo(t('已解锁豆包自定义 API 地址编辑')); } return true; }); } }; // 渠道额外设置状态 const [channelSettings, setChannelSettings] = useState({ ali_data_inspection_disabled: false, force_format: false, thinking_to_content: false, proxy: '', pass_through_body_enabled: false, pass_through_model_mapping_enabled: false, chat_image_to_images_enabled: false, system_prompt: '', system_prompt_override: false, responses_system_prompt_mode: 'native', client_only: false, bound_user_ids: '', os_restriction: [], client_type_restriction: [], client_version_min: '', client_version_max: '', sticky_user_id_fill: false, sticky_user_id_mode: 'native', cache_breakpoint_fill: false, cache_breakpoint_min_tokens: 0, cache_creation_default_ttl: '', }); const showApiConfigCard = true; // 控制是否显示 API 配置卡片 const getInitValues = () => ({ ...originInputs, models: [], groups: ['default'], }); // 处理渠道额外设置的更新 const handleChannelSettingsChange = (key, value) => { // 更新内部状态 setChannelSettings((prev) => ({ ...prev, [key]: value })); // 同步更新到表单字段 if (formApiRef.current) { formApiRef.current.setValue(key, value); } // 同步更新inputs状态 setInputs((prev) => ({ ...prev, [key]: value })); // 生成setting JSON并更新 const newSettings = { ...channelSettings, [key]: value }; const settingsJson = JSON.stringify(newSettings); handleInputChange('setting', settingsJson); }; const handleChannelOtherSettingsChange = (key, value) => { // 更新内部状态 setChannelSettings((prev) => ({ ...prev, [key]: value })); // 同步更新到表单字段 if (formApiRef.current) { formApiRef.current.setValue(key, value); } // 同步更新inputs状态 setInputs((prev) => ({ ...prev, [key]: value })); // 需要更新settings,是一个json,例如{"azure_responses_version": "preview"} let settings = {}; if (inputs.settings) { try { settings = JSON.parse(inputs.settings); } catch (error) { console.error('解析设置失败:', error); } } settings[key] = value; const settingsJson = JSON.stringify(settings); handleInputChange('settings', settingsJson); }; const handleInputChange = (name, value) => { if (formApiRef.current) { formApiRef.current.setValue(name, value); } if (name === 'models' && Array.isArray(value)) { value = Array.from(new Set(value.map((m) => (m || '').trim()))); } if (name === 'base_url' && value.endsWith('/v1')) { Modal.confirm({ title: t('警告'), content: t( '不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?', ), onOk: () => { setInputs((inputs) => ({ ...inputs, [name]: value })); }, }); return; } setInputs((inputs) => ({ ...inputs, [name]: value })); if (name === 'type') { let localModels = []; switch (value) { case 2: localModels = [ 'mj_imagine', 'mj_variation', 'mj_reroll', 'mj_blend', 'mj_upscale', 'mj_describe', 'mj_uploads', ]; break; case 5: localModels = [ 'swap_face', 'mj_imagine', 'mj_video', 'mj_edits', 'mj_variation', 'mj_reroll', 'mj_blend', 'mj_upscale', 'mj_describe', 'mj_zoom', 'mj_shorten', 'mj_modal', 'mj_inpaint', 'mj_custom_zoom', 'mj_high_variation', 'mj_low_variation', 'mj_pan', 'mj_uploads', ]; break; case 36: localModels = ['suno_music', 'suno_lyrics']; break; case 45: localModels = getChannelModels(value); setInputs((prevInputs) => ({ ...prevInputs, base_url: 'https://ark.cn-beijing.volces.com', })); break; default: localModels = getChannelModels(value); break; } if (inputs.models.length === 0) { setInputs((inputs) => ({ ...inputs, models: localModels })); } setBasicModels(localModels); // 重置手动输入模式状态 setUseManualInput(false); } }; const loadChannel = async () => { setLoading(true); let res = await API.get(`/api/channel/${channelId}`); if (res === undefined) { return; } const { success, message, data } = res.data; if (success) { if (data.models === '') { data.models = []; } else { data.models = data.models.split(','); } data.groups = toGroupList(data.group); if (data.model_mapping !== '') { data.model_mapping = JSON.stringify( JSON.parse(data.model_mapping), null, 2, ); } const chInfo = data.channel_info || {}; const isMulti = chInfo.is_multi_key === true; setIsMultiKeyChannel(isMulti); if (isMulti) { setBatch(true); setMultiToSingle(true); const modeVal = chInfo.multi_key_mode || 'random'; setMultiKeyMode(modeVal); data.multi_key_mode = modeVal; } else { setBatch(false); setMultiToSingle(false); } // 解析渠道额外设置并合并到data中 data.baidu_liveness_header_mode = 'legacy'; if (data.setting) { try { const parsedSettings = JSON.parse(data.setting); data.baidu_liveness_header_mode = parsedSettings.baidu_liveness_header_mode ?? 'legacy'; data.ali_data_inspection_disabled = parsedSettings.ali_data_inspection_disabled === true; data.force_format = parsedSettings.force_format || false; data.thinking_to_content = parsedSettings.thinking_to_content || false; data.proxy = parsedSettings.proxy || ''; data.pass_through_body_enabled = parsedSettings.pass_through_body_enabled || false; data.pass_through_model_mapping_enabled = parsedSettings.pass_through_model_mapping_enabled === true; data.chat_image_to_images_enabled = parsedSettings.chat_image_to_images_enabled || false; data.system_prompt = parsedSettings.system_prompt || ''; data.system_prompt_override = parsedSettings.system_prompt_override || false; data.responses_system_prompt_mode = parsedSettings.responses_system_prompt_mode === 'input_user_message' ? 'input_user_message' : 'native'; data.client_only = parsedSettings.client_only || false; data.bound_user_ids = parsedSettings.bound_user_ids || ''; data.os_restriction = Array.isArray(parsedSettings.os_restriction) ? parsedSettings.os_restriction : []; data.client_type_restriction = Array.isArray( parsedSettings.client_type_restriction, ) ? parsedSettings.client_type_restriction : []; data.client_version_min = parsedSettings.client_version_min || ''; data.client_version_max = parsedSettings.client_version_max || ''; data.sticky_user_id_fill = parsedSettings.sticky_user_id_fill || false; data.sticky_user_id_mode = parsedSettings.sticky_user_id_mode || 'native'; data.cache_breakpoint_fill = parsedSettings.cache_breakpoint_fill || false; data.cache_breakpoint_min_tokens = parsedSettings.cache_breakpoint_min_tokens || 0; data.cache_creation_default_ttl = ['5m', '1h'].includes( parsedSettings.cache_creation_default_ttl, ) ? parsedSettings.cache_creation_default_ttl : ''; } catch (error) { console.error('解析渠道设置失败:', error); data.force_format = false; data.ali_data_inspection_disabled = false; data.thinking_to_content = false; data.proxy = ''; data.pass_through_body_enabled = false; data.pass_through_model_mapping_enabled = false; data.chat_image_to_images_enabled = false; data.system_prompt = ''; data.system_prompt_override = false; data.responses_system_prompt_mode = 'native'; data.client_only = false; data.bound_user_ids = ''; data.os_restriction = []; data.client_type_restriction = []; data.client_version_min = ''; data.client_version_max = ''; data.sticky_user_id_fill = false; data.sticky_user_id_mode = 'native'; data.cache_breakpoint_fill = false; data.cache_breakpoint_min_tokens = 0; data.cache_creation_default_ttl = ''; } } else { data.force_format = false; data.ali_data_inspection_disabled = false; data.thinking_to_content = false; data.proxy = ''; data.pass_through_body_enabled = false; data.pass_through_model_mapping_enabled = false; data.chat_image_to_images_enabled = false; data.system_prompt = ''; data.system_prompt_override = false; data.responses_system_prompt_mode = 'native'; data.client_only = false; data.bound_user_ids = ''; data.os_restriction = []; data.client_type_restriction = []; data.client_version_min = ''; data.client_version_max = ''; data.sticky_user_id_fill = false; data.sticky_user_id_mode = 'native'; data.cache_breakpoint_fill = false; data.cache_breakpoint_min_tokens = 0; data.cache_creation_default_ttl = ''; } if (data.settings) { try { const parsedSettings = JSON.parse(data.settings); data.azure_responses_version = parsedSettings.azure_responses_version || ''; // 读取 Vertex 密钥格式 data.vertex_key_type = parsedSettings.vertex_key_type || 'json'; // 读取 AWS 密钥格式和区域 data.aws_key_type = parsedSettings.aws_key_type || 'ak_sk'; // 读取企业账户设置 data.is_enterprise_account = parsedSettings.openrouter_enterprise === true; // 读取字段透传控制设置 data.allow_service_tier = parsedSettings.allow_service_tier || false; data.disable_store = parsedSettings.disable_store || false; data.allow_safety_identifier = parsedSettings.allow_safety_identifier || false; } catch (error) { console.error('解析其他设置失败:', error); data.azure_responses_version = ''; data.region = ''; data.vertex_key_type = 'json'; data.aws_key_type = 'ak_sk'; data.is_enterprise_account = false; data.allow_service_tier = false; data.disable_store = false; data.allow_safety_identifier = false; } } else { // 兼容历史数据:老渠道没有 settings 时,默认按 json 展示 data.vertex_key_type = 'json'; data.aws_key_type = 'ak_sk'; data.is_enterprise_account = false; data.allow_service_tier = false; data.disable_store = false; data.allow_safety_identifier = false; } if ( data.type === 45 && (!data.base_url || (typeof data.base_url === 'string' && data.base_url.trim() === '')) ) { data.base_url = 'https://ark.cn-beijing.volces.com'; } // 日消耗限额统一使用 token(quota)单位,无需转换 // 工作时间字段:将 null 转为 undefined,确保 Semi Design Form.Select 能正确识别"无选中"状态 if (data.work_hours_start === null) data.work_hours_start = undefined; if (data.work_hours_end === null) data.work_hours_end = undefined; if (data.work_hours_timezone === null) data.work_hours_timezone = undefined; // 解析兜底渠道 ID 列表(后端 JSON string -> 前端数组) if ( data.fallback_channel_ids && typeof data.fallback_channel_ids === 'string' ) { try { const parsed = JSON.parse(data.fallback_channel_ids); data.fallback_channel_ids = Array.isArray(parsed) ? parsed.filter((x) => Number.isInteger(x) && x > 0) : []; } catch (e) { data.fallback_channel_ids = []; } } else if (!Array.isArray(data.fallback_channel_ids)) { data.fallback_channel_ids = []; } // 兜底触发失败次数:后端 NULL 表示 1 if (!data.fallback_primary_attempts) data.fallback_primary_attempts = 1; if (!data.fallback_hop_attempts) data.fallback_hop_attempts = 1; data.auto_ban = Boolean(data.auto_ban ?? originInputs.auto_ban); setInputs(data); if (formApiRef.current) { formApiRef.current.setValues(data); // 显式设置工作时间字段,确保 Form.Select 组件正确回显 formApiRef.current.setValue('work_hours_start', data.work_hours_start); formApiRef.current.setValue('work_hours_end', data.work_hours_end); formApiRef.current.setValue( 'work_hours_timezone', data.work_hours_timezone || 'Asia/Shanghai', ); } // 同步企业账户状态 setIsEnterpriseAccount(data.is_enterprise_account || false); setBasicModels(getChannelModels(data.type)); // 同步更新channelSettings状态显示 setChannelSettings({ ali_data_inspection_disabled: data.ali_data_inspection_disabled === true, force_format: data.force_format, thinking_to_content: data.thinking_to_content, proxy: data.proxy, pass_through_body_enabled: data.pass_through_body_enabled, pass_through_model_mapping_enabled: data.pass_through_model_mapping_enabled, chat_image_to_images_enabled: data.chat_image_to_images_enabled || false, system_prompt: data.system_prompt, system_prompt_override: data.system_prompt_override || false, responses_system_prompt_mode: data.responses_system_prompt_mode || 'native', client_only: data.client_only || false, bound_user_ids: data.bound_user_ids || '', os_restriction: Array.isArray(data.os_restriction) ? data.os_restriction : [], client_type_restriction: Array.isArray(data.client_type_restriction) ? data.client_type_restriction : [], client_version_min: data.client_version_min || '', client_version_max: data.client_version_max || '', sticky_user_id_fill: data.sticky_user_id_fill || false, sticky_user_id_mode: data.sticky_user_id_mode || 'native', cache_breakpoint_fill: data.cache_breakpoint_fill || false, cache_breakpoint_min_tokens: data.cache_breakpoint_min_tokens || 0, cache_creation_default_ttl: data.cache_creation_default_ttl || '', }); initialModelsRef.current = (data.models || []) .map((model) => (model || '').trim()) .filter(Boolean); initialModelMappingRef.current = data.model_mapping || ''; // console.log(data); } else { showError(message); } setLoading(false); }; const fetchUpstreamModelList = async (name) => { // if (inputs['type'] !== 1) { // showError(t('仅支持 OpenAI 接口格式')); // return; // } setLoading(true); const models = []; let err = false; if (isEdit) { // 如果是编辑模式,使用已有的 channelId 获取模型列表 const res = await API.get('/api/channel/fetch_models/' + channelId, { skipErrorHandler: true, }); if (res && res.data && res.data.success) { models.push(...res.data.data); } else { err = true; } } else { // 如果是新建模式,通过后端代理获取模型列表 if (!inputs?.['key']) { showError(t('请填写密钥')); err = true; } else { try { const res = await API.post( '/api/channel/fetch_models', { base_url: inputs['base_url'], type: inputs['type'], key: inputs['key'], }, { skipErrorHandler: true }, ); if (res && res.data && res.data.success) { models.push(...res.data.data); } else { err = true; } } catch (error) { console.error('Error fetching models:', error); err = true; } } } if (!err) { const uniqueModels = Array.from(new Set(models)); setFetchedModels(uniqueModels); setModelModalVisible(true); } else { showError(t('获取模型列表失败')); } setLoading(false); }; const fetchModels = async () => { try { let res = await API.get(`/api/channel/models`); const localModelOptions = res.data.data.map((model) => { const id = (model.id || '').trim(); return { key: id, label: id, value: id, }; }); setOriginModelOptions(localModelOptions); setFullModels(res.data.data.map((model) => model.id)); setBasicModels( res.data.data .filter((model) => { return model.id.startsWith('gpt-') || model.id.startsWith('text-'); }) .map((model) => model.id), ); } catch (error) { showError(error.message); } }; const fetchGroups = async () => { try { let res = await API.get(`/api/group/`); if (res === undefined) { return; } setGroupOptions( res.data.data.map((group) => ({ label: group, value: group, })), ); } catch (error) { showError(error.message); } }; const fetchModelGroups = async () => { try { const res = await API.get('/api/prefill_group?type=model'); if (res?.data?.success) { setModelGroups(res.data.data || []); } } catch (error) { // ignore } }; // 查看渠道密钥(透明验证) const handleShow2FAModal = async () => { try { // 使用 withVerification 包装,会自动处理需要验证的情况 const result = await withVerification( createApiCalls.viewChannelKey(channelId), { title: t('查看渠道密钥'), description: t('为了保护账户安全,请验证您的身份。'), preferredMethod: 'passkey', // 优先使用 Passkey }, ); // 如果直接返回了结果(已验证),显示密钥 if (result && result.success && result.data?.key) { showSuccess(t('密钥获取成功')); setKeyDisplayState({ showModal: true, keyData: result.data.key, }); } } catch (error) { console.error('Failed to view channel key:', error); showError(error.message || t('获取密钥失败')); } }; useEffect(() => { if (inputs.type !== 45) { doubaoApiClickCountRef.current = 0; setDoubaoApiEditUnlocked(false); } }, [inputs.type]); useEffect(() => { const modelMap = new Map(); originModelOptions.forEach((option) => { const v = (option.value || '').trim(); if (!modelMap.has(v)) { modelMap.set(v, option); } }); inputs.models.forEach((model) => { const v = (model || '').trim(); if (!modelMap.has(v)) { modelMap.set(v, { key: v, label: v, value: v, }); } }); const categories = getModelCategories(t); const optionsWithIcon = Array.from(modelMap.values()).map((opt) => { const modelName = opt.value; let icon = null; for (const [key, category] of Object.entries(categories)) { if (key !== 'all' && category.filter({ model_name: modelName })) { icon = category.icon; break; } } return { ...opt, label: ( {icon} {modelName} ), }; }); setModelOptions(optionsWithIcon); }, [originModelOptions, inputs.models, t]); const onScopeChange = useEffectEvent(() => { fetchModels().then(); fetchGroups().then(); if (!isEdit) { const initVals = getInitValues(); setInputs(initVals); if (formApiRef.current) { formApiRef.current.setValues(initVals); } let localModels = getChannelModels(inputs.type); setBasicModels(localModels); setInputs((inputs) => ({ ...inputs, models: localModels })); } }); useEffect(() => onScopeChange(), [onScopeChange, props.editingChannel.id]); useEffect(() => { if (formApiRef.current) { formApiRef.current.setValues(inputs); } }, [inputs]); const onVisibilityChange2 = useEffectEvent(() => { if (props.visible) { if (isEdit) { loadChannel(); } else { formApiRef.current?.setValues(getInitValues()); } // 每次打开(或打开状态下切换渠道)都重新拉兜底候选与反向引用, // 避免连续新建或重复打开同一渠道时沿用旧数据 reloadFallbackData(); fetchModelGroups(); // 重置手动输入模式状态 setUseManualInput(false); } else { // 统一的模态框关闭重置逻辑 resetModalState(); // 关闭后作废在途的兜底数据请求 fallbackLoadSeqRef.current += 1; } }); useEffect( () => onVisibilityChange2(), [onVisibilityChange2, props.visible, channelId], ); useEffect(() => { if (!isEdit) { initialModelsRef.current = []; initialModelMappingRef.current = ''; } }, [isEdit, props.visible]); // 统一的模态框重置函数 const resetModalState = () => { formApiRef.current?.reset(); // 重置渠道设置状态 setChannelSettings({ ali_data_inspection_disabled: false, force_format: false, thinking_to_content: false, proxy: '', pass_through_body_enabled: false, pass_through_model_mapping_enabled: false, chat_image_to_images_enabled: false, system_prompt: '', system_prompt_override: false, responses_system_prompt_mode: 'native', client_only: false, bound_user_ids: '', os_restriction: [], client_type_restriction: [], client_version_min: '', client_version_max: '', sticky_user_id_fill: false, sticky_user_id_mode: 'native', cache_breakpoint_fill: false, cache_breakpoint_min_tokens: 0, cache_creation_default_ttl: '', }); // 重置密钥模式状态 setKeyMode('append'); // 重置企业账户状态 setIsEnterpriseAccount(false); // 重置豆包隐藏入口状态 setDoubaoApiEditUnlocked(false); doubaoApiClickCountRef.current = 0; // 清空表单中的key_mode字段 if (formApiRef.current) { formApiRef.current.setValue('key_mode', undefined); } // 重置本地输入,避免下次打开残留上一次的 JSON 字段值 setInputs(getInitValues()); // 重置密钥显示状态 resetKeyDisplayState(); }; const handleVertexUploadChange = ({ fileList }) => { vertexErroredNames.current.clear(); (async () => { let validFiles = []; let keys = []; const errorNames = []; for (const item of fileList) { const fileObj = item.fileInstance; if (!fileObj) continue; try { const txt = await fileObj.text(); keys.push(JSON.parse(txt)); validFiles.push(item); } catch (err) { if (!vertexErroredNames.current.has(item.name)) { errorNames.push(item.name); vertexErroredNames.current.add(item.name); } } } // 非批量模式下只保留一个文件(最新选择的),避免重复叠加 if (!batch && validFiles.length > 1) { validFiles = [validFiles[validFiles.length - 1]]; keys = [keys[keys.length - 1]]; } setVertexKeys(keys); setVertexFileList(validFiles); if (formApiRef.current) { formApiRef.current.setValue('vertex_files', validFiles); } setInputs((prev) => ({ ...prev, vertex_files: validFiles })); if (errorNames.length > 0) { showError( t('以下文件解析失败,已忽略:{{list}}', { list: errorNames.join(', '), }), ); } })(); }; const confirmMissingModelMappings = (missingModels) => new Promise((resolve) => { const modal = Modal.confirm({ title: t('模型未加入列表,可能无法调用'), content: (