EditChannelModal.jsx 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import React, { useEffect, useState, useRef, useMemo } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import {
  18. API,
  19. showError,
  20. showInfo,
  21. showSuccess,
  22. verifyJSON,
  23. } from '../../../../helpers';
  24. import { useIsMobile } from '../../../../hooks/common/useIsMobile';
  25. import { CHANNEL_OPTIONS } from '../../../../constants';
  26. import {
  27. SideSheet,
  28. Space,
  29. Spin,
  30. Button,
  31. Typography,
  32. Checkbox,
  33. Banner,
  34. Modal,
  35. ImagePreview,
  36. Card,
  37. Tag,
  38. Avatar,
  39. Form,
  40. Row,
  41. Col,
  42. Highlight,
  43. Input,
  44. } from '@douyinfe/semi-ui';
  45. import {
  46. getChannelModels,
  47. copy,
  48. getChannelIcon,
  49. getModelCategories,
  50. selectFilter,
  51. } from '../../../../helpers';
  52. import ModelSelectModal from './ModelSelectModal';
  53. import OllamaModelModal from './OllamaModelModal';
  54. import CodexOAuthModal from './CodexOAuthModal';
  55. import JSONEditor from '../../../common/ui/JSONEditor';
  56. import SecureVerificationModal from '../../../common/modals/SecureVerificationModal';
  57. import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay';
  58. import { useSecureVerification } from '../../../../hooks/common/useSecureVerification';
  59. import { createApiCalls } from '../../../../services/secureVerification';
  60. import {
  61. IconSave,
  62. IconClose,
  63. IconServer,
  64. IconSetting,
  65. IconCode,
  66. IconGlobe,
  67. IconBolt,
  68. IconChevronUp,
  69. IconChevronDown,
  70. } from '@douyinfe/semi-icons';
  71. const { Text, Title } = Typography;
  72. const MODEL_MAPPING_EXAMPLE = {
  73. 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
  74. };
  75. const STATUS_CODE_MAPPING_EXAMPLE = {
  76. 400: '500',
  77. };
  78. const REGION_EXAMPLE = {
  79. default: 'global',
  80. 'gemini-1.5-pro-002': 'europe-west2',
  81. 'gemini-1.5-flash-002': 'europe-west2',
  82. 'claude-3-5-sonnet-20240620': 'europe-west1',
  83. };
  84. // 支持并且已适配通过接口获取模型列表的渠道类型
  85. const MODEL_FETCHABLE_TYPES = new Set([
  86. 1, 4, 14, 34, 17, 26, 27, 24, 47, 25, 20, 23, 31, 40, 42, 48, 43,
  87. ]);
  88. function type2secretPrompt(type) {
  89. // inputs.type === 15 ? '按照如下格式输入:APIKey|SecretKey' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥')
  90. switch (type) {
  91. case 15:
  92. return '按照如下格式输入:APIKey|SecretKey';
  93. case 18:
  94. return '按照如下格式输入:APPID|APISecret|APIKey';
  95. case 22:
  96. return '按照如下格式输入:APIKey-AppId,例如:fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041';
  97. case 23:
  98. return '按照如下格式输入:AppId|SecretId|SecretKey';
  99. case 33:
  100. return '按照如下格式输入:Ak|Sk|Region';
  101. case 45:
  102. return '请输入渠道对应的鉴权密钥, 豆包语音输入:AppId|AccessToken';
  103. case 50:
  104. return '按照如下格式输入: AccessKey|SecretKey, 如果上游是New API,则直接输ApiKey';
  105. case 51:
  106. return '按照如下格式输入: AccessKey|SecretAccessKey';
  107. case 57:
  108. return '请输入 JSON 格式的 OAuth 凭据(必须包含 access_token 和 account_id)';
  109. default:
  110. return '请输入渠道对应的鉴权密钥';
  111. }
  112. }
  113. const EditChannelModal = (props) => {
  114. const { t } = useTranslation();
  115. const channelId = props.editingChannel.id;
  116. const isEdit = channelId !== undefined;
  117. const [loading, setLoading] = useState(isEdit);
  118. const isMobile = useIsMobile();
  119. const handleCancel = () => {
  120. props.handleClose();
  121. };
  122. const originInputs = {
  123. name: '',
  124. type: 1,
  125. key: '',
  126. openai_organization: '',
  127. max_input_tokens: 0,
  128. base_url: '',
  129. other: '',
  130. model_mapping: '',
  131. status_code_mapping: '',
  132. models: [],
  133. auto_ban: 1,
  134. test_model: '',
  135. groups: ['default'],
  136. priority: 0,
  137. weight: 0,
  138. tag: '',
  139. multi_key_mode: 'random',
  140. // 渠道额外设置的默认值
  141. force_format: false,
  142. thinking_to_content: false,
  143. proxy: '',
  144. pass_through_body_enabled: false,
  145. system_prompt: '',
  146. system_prompt_override: false,
  147. settings: '',
  148. // 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
  149. vertex_key_type: 'json',
  150. // 仅 AWS: 密钥格式和区域(存入 settings.aws_key_type 和 settings.aws_region)
  151. aws_key_type: 'ak_sk',
  152. // 企业账户设置
  153. is_enterprise_account: false,
  154. // 字段透传控制默认值
  155. allow_service_tier: false,
  156. disable_store: false, // false = 允许透传(默认开启)
  157. allow_safety_identifier: false,
  158. };
  159. const [batch, setBatch] = useState(false);
  160. const [multiToSingle, setMultiToSingle] = useState(false);
  161. const [multiKeyMode, setMultiKeyMode] = useState('random');
  162. const [autoBan, setAutoBan] = useState(true);
  163. const [inputs, setInputs] = useState(originInputs);
  164. const [originModelOptions, setOriginModelOptions] = useState([]);
  165. const [modelOptions, setModelOptions] = useState([]);
  166. const [groupOptions, setGroupOptions] = useState([]);
  167. const [basicModels, setBasicModels] = useState([]);
  168. const [fullModels, setFullModels] = useState([]);
  169. const [modelGroups, setModelGroups] = useState([]);
  170. const [customModel, setCustomModel] = useState('');
  171. const [modalImageUrl, setModalImageUrl] = useState('');
  172. const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  173. const [modelModalVisible, setModelModalVisible] = useState(false);
  174. const [fetchedModels, setFetchedModels] = useState([]);
  175. const [ollamaModalVisible, setOllamaModalVisible] = useState(false);
  176. const formApiRef = useRef(null);
  177. const [vertexKeys, setVertexKeys] = useState([]);
  178. const [vertexFileList, setVertexFileList] = useState([]);
  179. const vertexErroredNames = useRef(new Set()); // 避免重复报错
  180. const [isMultiKeyChannel, setIsMultiKeyChannel] = useState(false);
  181. const [channelSearchValue, setChannelSearchValue] = useState('');
  182. const [useManualInput, setUseManualInput] = useState(false); // 是否使用手动输入模式
  183. const [keyMode, setKeyMode] = useState('append'); // 密钥模式:replace(覆盖)或 append(追加)
  184. const [isEnterpriseAccount, setIsEnterpriseAccount] = useState(false); // 是否为企业账户
  185. const [doubaoApiEditUnlocked, setDoubaoApiEditUnlocked] = useState(false); // 豆包渠道自定义 API 地址隐藏入口
  186. const redirectModelList = useMemo(() => {
  187. const mapping = inputs.model_mapping;
  188. if (typeof mapping !== 'string') return [];
  189. const trimmed = mapping.trim();
  190. if (!trimmed) return [];
  191. try {
  192. const parsed = JSON.parse(trimmed);
  193. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
  194. return [];
  195. }
  196. const values = Object.values(parsed)
  197. .map((value) => (typeof value === 'string' ? value.trim() : undefined))
  198. .filter((value) => value);
  199. return Array.from(new Set(values));
  200. } catch (error) {
  201. return [];
  202. }
  203. }, [inputs.model_mapping]);
  204. const [isIonetChannel, setIsIonetChannel] = useState(false);
  205. const [ionetMetadata, setIonetMetadata] = useState(null);
  206. const [codexOAuthModalVisible, setCodexOAuthModalVisible] = useState(false);
  207. const [codexCredentialRefreshing, setCodexCredentialRefreshing] =
  208. useState(false);
  209. // 密钥显示状态
  210. const [keyDisplayState, setKeyDisplayState] = useState({
  211. showModal: false,
  212. keyData: '',
  213. });
  214. // 专门的2FA验证状态(用于TwoFactorAuthModal)
  215. const [show2FAVerifyModal, setShow2FAVerifyModal] = useState(false);
  216. const [verifyCode, setVerifyCode] = useState('');
  217. useEffect(() => {
  218. if (!isEdit) {
  219. setIsIonetChannel(false);
  220. setIonetMetadata(null);
  221. }
  222. }, [isEdit]);
  223. const handleOpenIonetDeployment = () => {
  224. if (!ionetMetadata?.deployment_id) {
  225. return;
  226. }
  227. const targetUrl = `/console/deployment?deployment_id=${ionetMetadata.deployment_id}`;
  228. window.open(targetUrl, '_blank', 'noopener');
  229. };
  230. const [verifyLoading, setVerifyLoading] = useState(false);
  231. // 表单块导航相关状态
  232. const formSectionRefs = useRef({
  233. basicInfo: null,
  234. apiConfig: null,
  235. modelConfig: null,
  236. advancedSettings: null,
  237. channelExtraSettings: null,
  238. });
  239. const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
  240. const formSections = [
  241. 'basicInfo',
  242. 'apiConfig',
  243. 'modelConfig',
  244. 'advancedSettings',
  245. 'channelExtraSettings',
  246. ];
  247. const formContainerRef = useRef(null);
  248. const doubaoApiClickCountRef = useRef(0);
  249. const initialModelsRef = useRef([]);
  250. const initialModelMappingRef = useRef('');
  251. // 2FA状态更新辅助函数
  252. const updateTwoFAState = (updates) => {
  253. setTwoFAState((prev) => ({ ...prev, ...updates }));
  254. };
  255. // 使用通用安全验证 Hook
  256. const {
  257. isModalVisible,
  258. verificationMethods,
  259. verificationState,
  260. withVerification,
  261. executeVerification,
  262. cancelVerification,
  263. setVerificationCode,
  264. switchVerificationMethod,
  265. } = useSecureVerification({
  266. onSuccess: (result) => {
  267. // 验证成功后显示密钥
  268. console.log('Verification success, result:', result);
  269. if (result && result.success && result.data?.key) {
  270. showSuccess(t('密钥获取成功'));
  271. setKeyDisplayState({
  272. showModal: true,
  273. keyData: result.data.key,
  274. });
  275. } else if (result && result.key) {
  276. // 直接返回了 key(没有包装在 data 中)
  277. showSuccess(t('密钥获取成功'));
  278. setKeyDisplayState({
  279. showModal: true,
  280. keyData: result.key,
  281. });
  282. }
  283. },
  284. });
  285. // 重置密钥显示状态
  286. const resetKeyDisplayState = () => {
  287. setKeyDisplayState({
  288. showModal: false,
  289. keyData: '',
  290. });
  291. };
  292. // 重置2FA验证状态
  293. const reset2FAVerifyState = () => {
  294. setShow2FAVerifyModal(false);
  295. setVerifyCode('');
  296. setVerifyLoading(false);
  297. };
  298. // 表单导航功能
  299. const scrollToSection = (sectionKey) => {
  300. const sectionElement = formSectionRefs.current[sectionKey];
  301. if (sectionElement) {
  302. sectionElement.scrollIntoView({
  303. behavior: 'smooth',
  304. block: 'start',
  305. inline: 'nearest',
  306. });
  307. }
  308. };
  309. const navigateToSection = (direction) => {
  310. const availableSections = formSections.filter((section) => {
  311. if (section === 'apiConfig') {
  312. return showApiConfigCard;
  313. }
  314. return true;
  315. });
  316. let newIndex;
  317. if (direction === 'up') {
  318. newIndex =
  319. currentSectionIndex > 0
  320. ? currentSectionIndex - 1
  321. : availableSections.length - 1;
  322. } else {
  323. newIndex =
  324. currentSectionIndex < availableSections.length - 1
  325. ? currentSectionIndex + 1
  326. : 0;
  327. }
  328. setCurrentSectionIndex(newIndex);
  329. scrollToSection(availableSections[newIndex]);
  330. };
  331. const handleApiConfigSecretClick = () => {
  332. if (inputs.type !== 45) return;
  333. const next = doubaoApiClickCountRef.current + 1;
  334. doubaoApiClickCountRef.current = next;
  335. if (next >= 10) {
  336. setDoubaoApiEditUnlocked((unlocked) => {
  337. if (!unlocked) {
  338. showInfo(t('已解锁豆包自定义 API 地址编辑'));
  339. }
  340. return true;
  341. });
  342. }
  343. };
  344. // 渠道额外设置状态
  345. const [channelSettings, setChannelSettings] = useState({
  346. force_format: false,
  347. thinking_to_content: false,
  348. proxy: '',
  349. pass_through_body_enabled: false,
  350. system_prompt: '',
  351. });
  352. const showApiConfigCard = true; // 控制是否显示 API 配置卡片
  353. const getInitValues = () => ({ ...originInputs });
  354. // 处理渠道额外设置的更新
  355. const handleChannelSettingsChange = (key, value) => {
  356. // 更新内部状态
  357. setChannelSettings((prev) => ({ ...prev, [key]: value }));
  358. // 同步更新到表单字段
  359. if (formApiRef.current) {
  360. formApiRef.current.setValue(key, value);
  361. }
  362. // 同步更新inputs状态
  363. setInputs((prev) => ({ ...prev, [key]: value }));
  364. // 生成setting JSON并更新
  365. const newSettings = { ...channelSettings, [key]: value };
  366. const settingsJson = JSON.stringify(newSettings);
  367. handleInputChange('setting', settingsJson);
  368. };
  369. const handleChannelOtherSettingsChange = (key, value) => {
  370. // 更新内部状态
  371. setChannelSettings((prev) => ({ ...prev, [key]: value }));
  372. // 同步更新到表单字段
  373. if (formApiRef.current) {
  374. formApiRef.current.setValue(key, value);
  375. }
  376. // 同步更新inputs状态
  377. setInputs((prev) => ({ ...prev, [key]: value }));
  378. // 需要更新settings,是一个json,例如{"azure_responses_version": "preview"}
  379. let settings = {};
  380. if (inputs.settings) {
  381. try {
  382. settings = JSON.parse(inputs.settings);
  383. } catch (error) {
  384. console.error('解析设置失败:', error);
  385. }
  386. }
  387. settings[key] = value;
  388. const settingsJson = JSON.stringify(settings);
  389. handleInputChange('settings', settingsJson);
  390. };
  391. const isIonetLocked = isIonetChannel && isEdit;
  392. const handleInputChange = (name, value) => {
  393. if (isIonetChannel && isEdit && ['type', 'key', 'base_url'].includes(name)) {
  394. return;
  395. }
  396. if (formApiRef.current) {
  397. formApiRef.current.setValue(name, value);
  398. }
  399. if (name === 'models' && Array.isArray(value)) {
  400. value = Array.from(new Set(value.map((m) => (m || '').trim())));
  401. }
  402. if (name === 'base_url' && value.endsWith('/v1')) {
  403. Modal.confirm({
  404. title: '警告',
  405. content:
  406. '不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?',
  407. onOk: () => {
  408. setInputs((inputs) => ({ ...inputs, [name]: value }));
  409. },
  410. });
  411. return;
  412. }
  413. setInputs((inputs) => ({ ...inputs, [name]: value }));
  414. if (name === 'type') {
  415. let localModels = [];
  416. switch (value) {
  417. case 2:
  418. localModels = [
  419. 'mj_imagine',
  420. 'mj_variation',
  421. 'mj_reroll',
  422. 'mj_blend',
  423. 'mj_upscale',
  424. 'mj_describe',
  425. 'mj_uploads',
  426. ];
  427. break;
  428. case 5:
  429. localModels = [
  430. 'swap_face',
  431. 'mj_imagine',
  432. 'mj_video',
  433. 'mj_edits',
  434. 'mj_variation',
  435. 'mj_reroll',
  436. 'mj_blend',
  437. 'mj_upscale',
  438. 'mj_describe',
  439. 'mj_zoom',
  440. 'mj_shorten',
  441. 'mj_modal',
  442. 'mj_inpaint',
  443. 'mj_custom_zoom',
  444. 'mj_high_variation',
  445. 'mj_low_variation',
  446. 'mj_pan',
  447. 'mj_uploads',
  448. ];
  449. break;
  450. case 36:
  451. localModels = ['suno_music', 'suno_lyrics'];
  452. break;
  453. case 45:
  454. localModels = getChannelModels(value);
  455. setInputs((prevInputs) => ({
  456. ...prevInputs,
  457. base_url: 'https://ark.cn-beijing.volces.com',
  458. }));
  459. break;
  460. default:
  461. localModels = getChannelModels(value);
  462. break;
  463. }
  464. if (inputs.models.length === 0) {
  465. setInputs((inputs) => ({ ...inputs, models: localModels }));
  466. }
  467. setBasicModels(localModels);
  468. // 重置手动输入模式状态
  469. setUseManualInput(false);
  470. if (value === 57) {
  471. setBatch(false);
  472. setMultiToSingle(false);
  473. setMultiKeyMode('random');
  474. setVertexKeys([]);
  475. setVertexFileList([]);
  476. if (formApiRef.current) {
  477. formApiRef.current.setValue('vertex_files', []);
  478. }
  479. setInputs((prev) => ({ ...prev, vertex_files: [] }));
  480. }
  481. }
  482. //setAutoBan
  483. };
  484. const formatJsonField = (fieldName) => {
  485. const rawValue = (inputs?.[fieldName] ?? '').trim();
  486. if (!rawValue) return;
  487. try {
  488. const parsed = JSON.parse(rawValue);
  489. handleInputChange(fieldName, JSON.stringify(parsed, null, 2));
  490. } catch (error) {
  491. showError(`${t('JSON格式错误')}: ${error.message}`);
  492. }
  493. };
  494. const loadChannel = async () => {
  495. setLoading(true);
  496. let res = await API.get(`/api/channel/${channelId}`);
  497. if (res === undefined) {
  498. return;
  499. }
  500. const { success, message, data } = res.data;
  501. if (success) {
  502. if (data.models === '') {
  503. data.models = [];
  504. } else {
  505. data.models = data.models.split(',');
  506. }
  507. if (data.group === '') {
  508. data.groups = [];
  509. } else {
  510. data.groups = data.group.split(',');
  511. }
  512. if (data.model_mapping !== '') {
  513. data.model_mapping = JSON.stringify(
  514. JSON.parse(data.model_mapping),
  515. null,
  516. 2,
  517. );
  518. }
  519. const chInfo = data.channel_info || {};
  520. const isMulti = chInfo.is_multi_key === true;
  521. setIsMultiKeyChannel(isMulti);
  522. if (isMulti) {
  523. setBatch(true);
  524. setMultiToSingle(true);
  525. const modeVal = chInfo.multi_key_mode || 'random';
  526. setMultiKeyMode(modeVal);
  527. data.multi_key_mode = modeVal;
  528. } else {
  529. setBatch(false);
  530. setMultiToSingle(false);
  531. }
  532. // 解析渠道额外设置并合并到data中
  533. if (data.setting) {
  534. try {
  535. const parsedSettings = JSON.parse(data.setting);
  536. data.force_format = parsedSettings.force_format || false;
  537. data.thinking_to_content =
  538. parsedSettings.thinking_to_content || false;
  539. data.proxy = parsedSettings.proxy || '';
  540. data.pass_through_body_enabled =
  541. parsedSettings.pass_through_body_enabled || false;
  542. data.system_prompt = parsedSettings.system_prompt || '';
  543. data.system_prompt_override =
  544. parsedSettings.system_prompt_override || false;
  545. } catch (error) {
  546. console.error('解析渠道设置失败:', error);
  547. data.force_format = false;
  548. data.thinking_to_content = false;
  549. data.proxy = '';
  550. data.pass_through_body_enabled = false;
  551. data.system_prompt = '';
  552. data.system_prompt_override = false;
  553. }
  554. } else {
  555. data.force_format = false;
  556. data.thinking_to_content = false;
  557. data.proxy = '';
  558. data.pass_through_body_enabled = false;
  559. data.system_prompt = '';
  560. data.system_prompt_override = false;
  561. }
  562. if (data.settings) {
  563. try {
  564. const parsedSettings = JSON.parse(data.settings);
  565. data.azure_responses_version =
  566. parsedSettings.azure_responses_version || '';
  567. // 读取 Vertex 密钥格式
  568. data.vertex_key_type = parsedSettings.vertex_key_type || 'json';
  569. // 读取 AWS 密钥格式和区域
  570. data.aws_key_type = parsedSettings.aws_key_type || 'ak_sk';
  571. // 读取企业账户设置
  572. data.is_enterprise_account =
  573. parsedSettings.openrouter_enterprise === true;
  574. // 读取字段透传控制设置
  575. data.allow_service_tier = parsedSettings.allow_service_tier || false;
  576. data.disable_store = parsedSettings.disable_store || false;
  577. data.allow_safety_identifier =
  578. parsedSettings.allow_safety_identifier || false;
  579. } catch (error) {
  580. console.error('解析其他设置失败:', error);
  581. data.azure_responses_version = '';
  582. data.region = '';
  583. data.vertex_key_type = 'json';
  584. data.aws_key_type = 'ak_sk';
  585. data.is_enterprise_account = false;
  586. data.allow_service_tier = false;
  587. data.disable_store = false;
  588. data.allow_safety_identifier = false;
  589. }
  590. } else {
  591. // 兼容历史数据:老渠道没有 settings 时,默认按 json 展示
  592. data.vertex_key_type = 'json';
  593. data.aws_key_type = 'ak_sk';
  594. data.is_enterprise_account = false;
  595. data.allow_service_tier = false;
  596. data.disable_store = false;
  597. data.allow_safety_identifier = false;
  598. }
  599. if (
  600. data.type === 45 &&
  601. (!data.base_url ||
  602. (typeof data.base_url === 'string' && data.base_url.trim() === ''))
  603. ) {
  604. data.base_url = 'https://ark.cn-beijing.volces.com';
  605. }
  606. setInputs(data);
  607. if (formApiRef.current) {
  608. formApiRef.current.setValues(data);
  609. }
  610. if (data.auto_ban === 0) {
  611. setAutoBan(false);
  612. } else {
  613. setAutoBan(true);
  614. }
  615. // 同步企业账户状态
  616. setIsEnterpriseAccount(data.is_enterprise_account || false);
  617. setBasicModels(getChannelModels(data.type));
  618. // 同步更新channelSettings状态显示
  619. setChannelSettings({
  620. force_format: data.force_format,
  621. thinking_to_content: data.thinking_to_content,
  622. proxy: data.proxy,
  623. pass_through_body_enabled: data.pass_through_body_enabled,
  624. system_prompt: data.system_prompt,
  625. system_prompt_override: data.system_prompt_override || false,
  626. });
  627. initialModelsRef.current = (data.models || [])
  628. .map((model) => (model || '').trim())
  629. .filter(Boolean);
  630. initialModelMappingRef.current = data.model_mapping || '';
  631. let parsedIonet = null;
  632. if (data.other_info) {
  633. try {
  634. const maybeMeta = JSON.parse(data.other_info);
  635. if (
  636. maybeMeta &&
  637. typeof maybeMeta === 'object' &&
  638. maybeMeta.source === 'ionet'
  639. ) {
  640. parsedIonet = maybeMeta;
  641. }
  642. } catch (error) {
  643. // ignore parse error
  644. }
  645. }
  646. const managedByIonet = !!parsedIonet;
  647. setIsIonetChannel(managedByIonet);
  648. setIonetMetadata(parsedIonet);
  649. // console.log(data);
  650. } else {
  651. showError(message);
  652. }
  653. setLoading(false);
  654. };
  655. const fetchUpstreamModelList = async (name, options = {}) => {
  656. const silent = !!options.silent;
  657. // if (inputs['type'] !== 1) {
  658. // showError(t('仅支持 OpenAI 接口格式'));
  659. // return;
  660. // }
  661. setLoading(true);
  662. const models = [];
  663. let err = false;
  664. if (isEdit) {
  665. // 如果是编辑模式,使用已有的 channelId 获取模型列表
  666. const res = await API.get('/api/channel/fetch_models/' + channelId, {
  667. skipErrorHandler: true,
  668. });
  669. if (res && res.data && res.data.success) {
  670. models.push(...res.data.data);
  671. } else {
  672. err = true;
  673. }
  674. } else {
  675. // 如果是新建模式,通过后端代理获取模型列表
  676. if (!inputs?.['key']) {
  677. showError(t('请填写密钥'));
  678. err = true;
  679. } else {
  680. try {
  681. const res = await API.post(
  682. '/api/channel/fetch_models',
  683. {
  684. base_url: inputs['base_url'],
  685. type: inputs['type'],
  686. key: inputs['key'],
  687. },
  688. { skipErrorHandler: true },
  689. );
  690. if (res && res.data && res.data.success) {
  691. models.push(...res.data.data);
  692. } else {
  693. err = true;
  694. }
  695. } catch (error) {
  696. console.error('Error fetching models:', error);
  697. err = true;
  698. }
  699. }
  700. }
  701. if (!err) {
  702. const uniqueModels = Array.from(new Set(models));
  703. setFetchedModels(uniqueModels);
  704. if (!silent) {
  705. setModelModalVisible(true);
  706. }
  707. } else {
  708. showError(t('获取模型列表失败'));
  709. }
  710. setLoading(false);
  711. };
  712. const fetchModels = async () => {
  713. try {
  714. let res = await API.get(`/api/channel/models`);
  715. const localModelOptions = res.data.data.map((model) => {
  716. const id = (model.id || '').trim();
  717. return {
  718. key: id,
  719. label: id,
  720. value: id,
  721. };
  722. });
  723. setOriginModelOptions(localModelOptions);
  724. setFullModels(res.data.data.map((model) => model.id));
  725. setBasicModels(
  726. res.data.data
  727. .filter((model) => {
  728. return model.id.startsWith('gpt-') || model.id.startsWith('text-');
  729. })
  730. .map((model) => model.id),
  731. );
  732. } catch (error) {
  733. showError(error.message);
  734. }
  735. };
  736. const fetchGroups = async () => {
  737. try {
  738. let res = await API.get(`/api/group/`);
  739. if (res === undefined) {
  740. return;
  741. }
  742. setGroupOptions(
  743. res.data.data.map((group) => ({
  744. label: group,
  745. value: group,
  746. })),
  747. );
  748. } catch (error) {
  749. showError(error.message);
  750. }
  751. };
  752. const fetchModelGroups = async () => {
  753. try {
  754. const res = await API.get('/api/prefill_group?type=model');
  755. if (res?.data?.success) {
  756. setModelGroups(res.data.data || []);
  757. }
  758. } catch (error) {
  759. // ignore
  760. }
  761. };
  762. // 查看渠道密钥(透明验证)
  763. const handleShow2FAModal = async () => {
  764. try {
  765. // 使用 withVerification 包装,会自动处理需要验证的情况
  766. const result = await withVerification(
  767. createApiCalls.viewChannelKey(channelId),
  768. {
  769. title: t('查看渠道密钥'),
  770. description: t('为了保护账户安全,请验证您的身份。'),
  771. preferredMethod: 'passkey', // 优先使用 Passkey
  772. },
  773. );
  774. // 如果直接返回了结果(已验证),显示密钥
  775. if (result && result.success && result.data?.key) {
  776. showSuccess(t('密钥获取成功'));
  777. setKeyDisplayState({
  778. showModal: true,
  779. keyData: result.data.key,
  780. });
  781. }
  782. } catch (error) {
  783. console.error('Failed to view channel key:', error);
  784. showError(error.message || t('获取密钥失败'));
  785. }
  786. };
  787. const handleCodexOAuthGenerated = (key) => {
  788. handleInputChange('key', key);
  789. formatJsonField('key');
  790. };
  791. const handleRefreshCodexCredential = async () => {
  792. if (!isEdit) return;
  793. setCodexCredentialRefreshing(true);
  794. try {
  795. const res = await API.post(
  796. `/api/channel/${channelId}/codex/refresh`,
  797. {},
  798. { skipErrorHandler: true },
  799. );
  800. if (!res?.data?.success) {
  801. throw new Error(res?.data?.message || 'Failed to refresh credential');
  802. }
  803. showSuccess(t('凭证已刷新'));
  804. } catch (error) {
  805. showError(error.message || t('刷新失败'));
  806. } finally {
  807. setCodexCredentialRefreshing(false);
  808. }
  809. };
  810. useEffect(() => {
  811. if (inputs.type !== 45) {
  812. doubaoApiClickCountRef.current = 0;
  813. setDoubaoApiEditUnlocked(false);
  814. }
  815. }, [inputs.type]);
  816. useEffect(() => {
  817. const modelMap = new Map();
  818. originModelOptions.forEach((option) => {
  819. const v = (option.value || '').trim();
  820. if (!modelMap.has(v)) {
  821. modelMap.set(v, option);
  822. }
  823. });
  824. inputs.models.forEach((model) => {
  825. const v = (model || '').trim();
  826. if (!modelMap.has(v)) {
  827. modelMap.set(v, {
  828. key: v,
  829. label: v,
  830. value: v,
  831. });
  832. }
  833. });
  834. const categories = getModelCategories(t);
  835. const optionsWithIcon = Array.from(modelMap.values()).map((opt) => {
  836. const modelName = opt.value;
  837. let icon = null;
  838. for (const [key, category] of Object.entries(categories)) {
  839. if (key !== 'all' && category.filter({ model_name: modelName })) {
  840. icon = category.icon;
  841. break;
  842. }
  843. }
  844. return {
  845. ...opt,
  846. label: (
  847. <span className='flex items-center gap-1'>
  848. {icon}
  849. {modelName}
  850. </span>
  851. ),
  852. };
  853. });
  854. setModelOptions(optionsWithIcon);
  855. }, [originModelOptions, inputs.models, t]);
  856. useEffect(() => {
  857. fetchModels().then();
  858. fetchGroups().then();
  859. if (!isEdit) {
  860. setInputs(originInputs);
  861. if (formApiRef.current) {
  862. formApiRef.current.setValues(originInputs);
  863. }
  864. let localModels = getChannelModels(inputs.type);
  865. setBasicModels(localModels);
  866. setInputs((inputs) => ({ ...inputs, models: localModels }));
  867. }
  868. }, [props.editingChannel.id]);
  869. useEffect(() => {
  870. if (formApiRef.current) {
  871. formApiRef.current.setValues(inputs);
  872. }
  873. }, [inputs]);
  874. useEffect(() => {
  875. if (props.visible) {
  876. if (isEdit) {
  877. loadChannel();
  878. } else {
  879. formApiRef.current?.setValues(getInitValues());
  880. }
  881. fetchModelGroups();
  882. // 重置手动输入模式状态
  883. setUseManualInput(false);
  884. // 重置导航状态
  885. setCurrentSectionIndex(0);
  886. } else {
  887. // 统一的模态框关闭重置逻辑
  888. resetModalState();
  889. }
  890. }, [props.visible, channelId]);
  891. useEffect(() => {
  892. if (!isEdit) {
  893. initialModelsRef.current = [];
  894. initialModelMappingRef.current = '';
  895. }
  896. }, [isEdit, props.visible]);
  897. // 统一的模态框重置函数
  898. const resetModalState = () => {
  899. formApiRef.current?.reset();
  900. // 重置渠道设置状态
  901. setChannelSettings({
  902. force_format: false,
  903. thinking_to_content: false,
  904. proxy: '',
  905. pass_through_body_enabled: false,
  906. system_prompt: '',
  907. system_prompt_override: false,
  908. });
  909. // 重置密钥模式状态
  910. setKeyMode('append');
  911. // 重置企业账户状态
  912. setIsEnterpriseAccount(false);
  913. // 重置豆包隐藏入口状态
  914. setDoubaoApiEditUnlocked(false);
  915. doubaoApiClickCountRef.current = 0;
  916. // 清空表单中的key_mode字段
  917. if (formApiRef.current) {
  918. formApiRef.current.setValue('key_mode', undefined);
  919. }
  920. // 重置本地输入,避免下次打开残留上一次的 JSON 字段值
  921. setInputs(getInitValues());
  922. // 重置密钥显示状态
  923. resetKeyDisplayState();
  924. };
  925. const handleVertexUploadChange = ({ fileList }) => {
  926. vertexErroredNames.current.clear();
  927. (async () => {
  928. let validFiles = [];
  929. let keys = [];
  930. const errorNames = [];
  931. for (const item of fileList) {
  932. const fileObj = item.fileInstance;
  933. if (!fileObj) continue;
  934. try {
  935. const txt = await fileObj.text();
  936. keys.push(JSON.parse(txt));
  937. validFiles.push(item);
  938. } catch (err) {
  939. if (!vertexErroredNames.current.has(item.name)) {
  940. errorNames.push(item.name);
  941. vertexErroredNames.current.add(item.name);
  942. }
  943. }
  944. }
  945. // 非批量模式下只保留一个文件(最新选择的),避免重复叠加
  946. if (!batch && validFiles.length > 1) {
  947. validFiles = [validFiles[validFiles.length - 1]];
  948. keys = [keys[keys.length - 1]];
  949. }
  950. setVertexKeys(keys);
  951. setVertexFileList(validFiles);
  952. if (formApiRef.current) {
  953. formApiRef.current.setValue('vertex_files', validFiles);
  954. }
  955. setInputs((prev) => ({ ...prev, vertex_files: validFiles }));
  956. if (errorNames.length > 0) {
  957. showError(
  958. t('以下文件解析失败,已忽略:{{list}}', {
  959. list: errorNames.join(', '),
  960. }),
  961. );
  962. }
  963. })();
  964. };
  965. const confirmMissingModelMappings = (missingModels) =>
  966. new Promise((resolve) => {
  967. const modal = Modal.confirm({
  968. title: t('模型未加入列表,可能无法调用'),
  969. content: (
  970. <div className='text-sm leading-6'>
  971. <div>
  972. {t(
  973. '模型重定向里的下列模型尚未添加到“模型”列表,调用时会因为缺少可用模型而失败:',
  974. )}
  975. </div>
  976. <div className='font-mono text-xs break-all text-red-600 mt-1'>
  977. {missingModels.join(', ')}
  978. </div>
  979. <div className='mt-2'>
  980. {t(
  981. '你可以在“自定义模型名称”处手动添加它们,然后点击填入后再提交,或者直接使用下方操作自动处理。',
  982. )}
  983. </div>
  984. </div>
  985. ),
  986. centered: true,
  987. footer: (
  988. <Space align='center' className='w-full justify-end'>
  989. <Button
  990. type='tertiary'
  991. onClick={() => {
  992. modal.destroy();
  993. resolve('cancel');
  994. }}
  995. >
  996. {t('返回修改')}
  997. </Button>
  998. <Button
  999. type='primary'
  1000. theme='light'
  1001. onClick={() => {
  1002. modal.destroy();
  1003. resolve('submit');
  1004. }}
  1005. >
  1006. {t('直接提交')}
  1007. </Button>
  1008. <Button
  1009. type='primary'
  1010. theme='solid'
  1011. onClick={() => {
  1012. modal.destroy();
  1013. resolve('add');
  1014. }}
  1015. >
  1016. {t('添加后提交')}
  1017. </Button>
  1018. </Space>
  1019. ),
  1020. });
  1021. });
  1022. const hasModelConfigChanged = (normalizedModels, modelMappingStr) => {
  1023. if (!isEdit) return true;
  1024. const initialModels = initialModelsRef.current;
  1025. if (normalizedModels.length !== initialModels.length) {
  1026. return true;
  1027. }
  1028. for (let i = 0; i < normalizedModels.length; i++) {
  1029. if (normalizedModels[i] !== initialModels[i]) {
  1030. return true;
  1031. }
  1032. }
  1033. const normalizedMapping = (modelMappingStr || '').trim();
  1034. const initialMapping = (initialModelMappingRef.current || '').trim();
  1035. return normalizedMapping !== initialMapping;
  1036. };
  1037. const submit = async () => {
  1038. const formValues = formApiRef.current ? formApiRef.current.getValues() : {};
  1039. let localInputs = { ...formValues };
  1040. if (localInputs.type === 57) {
  1041. if (batch) {
  1042. showInfo(t('Codex 渠道不支持批量创建'));
  1043. return;
  1044. }
  1045. const rawKey = (localInputs.key || '').trim();
  1046. if (!isEdit && rawKey === '') {
  1047. showInfo(t('请输入密钥!'));
  1048. return;
  1049. }
  1050. if (rawKey !== '') {
  1051. if (!verifyJSON(rawKey)) {
  1052. showInfo(t('密钥必须是合法的 JSON 格式!'));
  1053. return;
  1054. }
  1055. try {
  1056. const parsed = JSON.parse(rawKey);
  1057. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
  1058. showInfo(t('密钥必须是 JSON 对象'));
  1059. return;
  1060. }
  1061. const accessToken = String(parsed.access_token || '').trim();
  1062. const accountId = String(parsed.account_id || '').trim();
  1063. if (!accessToken) {
  1064. showInfo(t('密钥 JSON 必须包含 access_token'));
  1065. return;
  1066. }
  1067. if (!accountId) {
  1068. showInfo(t('密钥 JSON 必须包含 account_id'));
  1069. return;
  1070. }
  1071. localInputs.key = JSON.stringify(parsed);
  1072. } catch (error) {
  1073. showInfo(t('密钥必须是合法的 JSON 格式!'));
  1074. return;
  1075. }
  1076. }
  1077. }
  1078. if (localInputs.type === 41) {
  1079. const keyType = localInputs.vertex_key_type || 'json';
  1080. if (keyType === 'api_key') {
  1081. // 直接作为普通字符串密钥处理
  1082. if (!isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
  1083. showInfo(t('请输入密钥!'));
  1084. return;
  1085. }
  1086. } else {
  1087. // JSON 服务账号密钥
  1088. if (useManualInput) {
  1089. if (localInputs.key && localInputs.key.trim() !== '') {
  1090. try {
  1091. const parsedKey = JSON.parse(localInputs.key);
  1092. localInputs.key = JSON.stringify(parsedKey);
  1093. } catch (err) {
  1094. showError(t('密钥格式无效,请输入有效的 JSON 格式密钥'));
  1095. return;
  1096. }
  1097. } else if (!isEdit) {
  1098. showInfo(t('请输入密钥!'));
  1099. return;
  1100. }
  1101. } else {
  1102. // 文件上传模式
  1103. let keys = vertexKeys;
  1104. if (keys.length === 0 && vertexFileList.length > 0) {
  1105. try {
  1106. const parsed = await Promise.all(
  1107. vertexFileList.map(async (item) => {
  1108. const fileObj = item.fileInstance;
  1109. if (!fileObj) return null;
  1110. const txt = await fileObj.text();
  1111. return JSON.parse(txt);
  1112. }),
  1113. );
  1114. keys = parsed.filter(Boolean);
  1115. } catch (err) {
  1116. showError(t('解析密钥文件失败: {{msg}}', { msg: err.message }));
  1117. return;
  1118. }
  1119. }
  1120. if (keys.length === 0) {
  1121. if (!isEdit) {
  1122. showInfo(t('请上传密钥文件!'));
  1123. return;
  1124. } else {
  1125. delete localInputs.key;
  1126. }
  1127. } else {
  1128. localInputs.key = batch
  1129. ? JSON.stringify(keys)
  1130. : JSON.stringify(keys[0]);
  1131. }
  1132. }
  1133. }
  1134. }
  1135. // 如果是编辑模式且 key 为空字符串,避免提交空值覆盖旧密钥
  1136. if (isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
  1137. delete localInputs.key;
  1138. }
  1139. delete localInputs.vertex_files;
  1140. if (!isEdit && (!localInputs.name || !localInputs.key)) {
  1141. showInfo(t('请填写渠道名称和渠道密钥!'));
  1142. return;
  1143. }
  1144. if (!Array.isArray(localInputs.models) || localInputs.models.length === 0) {
  1145. showInfo(t('请至少选择一个模型!'));
  1146. return;
  1147. }
  1148. if (
  1149. localInputs.type === 45 &&
  1150. (!localInputs.base_url || localInputs.base_url.trim() === '')
  1151. ) {
  1152. showInfo(t('请输入API地址!'));
  1153. return;
  1154. }
  1155. const hasModelMapping =
  1156. typeof localInputs.model_mapping === 'string' &&
  1157. localInputs.model_mapping.trim() !== '';
  1158. let parsedModelMapping = null;
  1159. if (hasModelMapping) {
  1160. if (!verifyJSON(localInputs.model_mapping)) {
  1161. showInfo(t('模型映射必须是合法的 JSON 格式!'));
  1162. return;
  1163. }
  1164. try {
  1165. parsedModelMapping = JSON.parse(localInputs.model_mapping);
  1166. } catch (error) {
  1167. showInfo(t('模型映射必须是合法的 JSON 格式!'));
  1168. return;
  1169. }
  1170. }
  1171. const normalizedModels = (localInputs.models || [])
  1172. .map((model) => (model || '').trim())
  1173. .filter(Boolean);
  1174. localInputs.models = normalizedModels;
  1175. if (
  1176. parsedModelMapping &&
  1177. typeof parsedModelMapping === 'object' &&
  1178. !Array.isArray(parsedModelMapping)
  1179. ) {
  1180. const modelSet = new Set(normalizedModels);
  1181. const missingModels = Object.keys(parsedModelMapping)
  1182. .map((key) => (key || '').trim())
  1183. .filter((key) => key && !modelSet.has(key));
  1184. const shouldPromptMissing =
  1185. missingModels.length > 0 &&
  1186. hasModelConfigChanged(normalizedModels, localInputs.model_mapping);
  1187. if (shouldPromptMissing) {
  1188. const confirmAction = await confirmMissingModelMappings(missingModels);
  1189. if (confirmAction === 'cancel') {
  1190. return;
  1191. }
  1192. if (confirmAction === 'add') {
  1193. const updatedModels = Array.from(
  1194. new Set([...normalizedModels, ...missingModels]),
  1195. );
  1196. localInputs.models = updatedModels;
  1197. handleInputChange('models', updatedModels);
  1198. }
  1199. }
  1200. }
  1201. if (localInputs.base_url && localInputs.base_url.endsWith('/')) {
  1202. localInputs.base_url = localInputs.base_url.slice(
  1203. 0,
  1204. localInputs.base_url.length - 1,
  1205. );
  1206. }
  1207. if (localInputs.type === 18 && localInputs.other === '') {
  1208. localInputs.other = 'v2.1';
  1209. }
  1210. // 生成渠道额外设置JSON
  1211. const channelExtraSettings = {
  1212. force_format: localInputs.force_format || false,
  1213. thinking_to_content: localInputs.thinking_to_content || false,
  1214. proxy: localInputs.proxy || '',
  1215. pass_through_body_enabled: localInputs.pass_through_body_enabled || false,
  1216. system_prompt: localInputs.system_prompt || '',
  1217. system_prompt_override: localInputs.system_prompt_override || false,
  1218. };
  1219. localInputs.setting = JSON.stringify(channelExtraSettings);
  1220. // 处理 settings 字段(包括企业账户设置和字段透传控制)
  1221. let settings = {};
  1222. if (localInputs.settings) {
  1223. try {
  1224. settings = JSON.parse(localInputs.settings);
  1225. } catch (error) {
  1226. console.error('解析settings失败:', error);
  1227. }
  1228. }
  1229. // type === 20: 设置企业账户标识,无论是true还是false都要传到后端
  1230. if (localInputs.type === 20) {
  1231. settings.openrouter_enterprise =
  1232. localInputs.is_enterprise_account === true;
  1233. }
  1234. // type === 33 (AWS): 保存 aws_key_type 到 settings
  1235. if (localInputs.type === 33) {
  1236. settings.aws_key_type = localInputs.aws_key_type || 'ak_sk';
  1237. }
  1238. // type === 41 (Vertex): 始终保存 vertex_key_type 到 settings,避免编辑时被重置
  1239. if (localInputs.type === 41) {
  1240. settings.vertex_key_type = localInputs.vertex_key_type || 'json';
  1241. } else if ('vertex_key_type' in settings) {
  1242. delete settings.vertex_key_type;
  1243. }
  1244. // type === 1 (OpenAI) 或 type === 14 (Claude): 设置字段透传控制(显式保存布尔值)
  1245. if (localInputs.type === 1 || localInputs.type === 14) {
  1246. settings.allow_service_tier = localInputs.allow_service_tier === true;
  1247. // 仅 OpenAI 渠道需要 store 和 safety_identifier
  1248. if (localInputs.type === 1) {
  1249. settings.disable_store = localInputs.disable_store === true;
  1250. settings.allow_safety_identifier =
  1251. localInputs.allow_safety_identifier === true;
  1252. }
  1253. }
  1254. localInputs.settings = JSON.stringify(settings);
  1255. // 清理不需要发送到后端的字段
  1256. delete localInputs.force_format;
  1257. delete localInputs.thinking_to_content;
  1258. delete localInputs.proxy;
  1259. delete localInputs.pass_through_body_enabled;
  1260. delete localInputs.system_prompt;
  1261. delete localInputs.system_prompt_override;
  1262. delete localInputs.is_enterprise_account;
  1263. // 顶层的 vertex_key_type 不应发送给后端
  1264. delete localInputs.vertex_key_type;
  1265. // 顶层的 aws_key_type 不应发送给后端
  1266. delete localInputs.aws_key_type;
  1267. // 清理字段透传控制的临时字段
  1268. delete localInputs.allow_service_tier;
  1269. delete localInputs.disable_store;
  1270. delete localInputs.allow_safety_identifier;
  1271. let res;
  1272. localInputs.auto_ban = localInputs.auto_ban ? 1 : 0;
  1273. localInputs.models = localInputs.models.join(',');
  1274. localInputs.group = (localInputs.groups || []).join(',');
  1275. let mode = 'single';
  1276. if (batch) {
  1277. mode = multiToSingle ? 'multi_to_single' : 'batch';
  1278. }
  1279. if (isEdit) {
  1280. res = await API.put(`/api/channel/`, {
  1281. ...localInputs,
  1282. id: parseInt(channelId),
  1283. key_mode: isMultiKeyChannel ? keyMode : undefined, // 只在多key模式下传递
  1284. });
  1285. } else {
  1286. res = await API.post(`/api/channel/`, {
  1287. mode: mode,
  1288. multi_key_mode: mode === 'multi_to_single' ? multiKeyMode : undefined,
  1289. channel: localInputs,
  1290. });
  1291. }
  1292. const { success, message } = res.data;
  1293. if (success) {
  1294. if (isEdit) {
  1295. showSuccess(t('渠道更新成功!'));
  1296. } else {
  1297. showSuccess(t('渠道创建成功!'));
  1298. setInputs(originInputs);
  1299. }
  1300. props.refresh();
  1301. props.handleClose();
  1302. } else {
  1303. showError(message);
  1304. }
  1305. };
  1306. // 密钥去重函数
  1307. const deduplicateKeys = () => {
  1308. const currentKey = formApiRef.current?.getValue('key') || inputs.key || '';
  1309. if (!currentKey.trim()) {
  1310. showInfo(t('请先输入密钥'));
  1311. return;
  1312. }
  1313. // 按行分割密钥
  1314. const keyLines = currentKey.split('\n');
  1315. const beforeCount = keyLines.length;
  1316. // 使用哈希表去重,保持原有顺序
  1317. const keySet = new Set();
  1318. const deduplicatedKeys = [];
  1319. keyLines.forEach((line) => {
  1320. const trimmedLine = line.trim();
  1321. if (trimmedLine && !keySet.has(trimmedLine)) {
  1322. keySet.add(trimmedLine);
  1323. deduplicatedKeys.push(trimmedLine);
  1324. }
  1325. });
  1326. const afterCount = deduplicatedKeys.length;
  1327. const deduplicatedKeyText = deduplicatedKeys.join('\n');
  1328. // 更新表单和状态
  1329. if (formApiRef.current) {
  1330. formApiRef.current.setValue('key', deduplicatedKeyText);
  1331. }
  1332. handleInputChange('key', deduplicatedKeyText);
  1333. // 显示去重结果
  1334. const message = t(
  1335. '去重完成:去重前 {{before}} 个密钥,去重后 {{after}} 个密钥',
  1336. {
  1337. before: beforeCount,
  1338. after: afterCount,
  1339. },
  1340. );
  1341. if (beforeCount === afterCount) {
  1342. showInfo(t('未发现重复密钥'));
  1343. } else {
  1344. showSuccess(message);
  1345. }
  1346. };
  1347. const addCustomModels = () => {
  1348. if (customModel.trim() === '') return;
  1349. const modelArray = customModel.split(',').map((model) => model.trim());
  1350. let localModels = [...inputs.models];
  1351. let localModelOptions = [...modelOptions];
  1352. const addedModels = [];
  1353. modelArray.forEach((model) => {
  1354. if (model && !localModels.includes(model)) {
  1355. localModels.push(model);
  1356. localModelOptions.push({
  1357. key: model,
  1358. label: model,
  1359. value: model,
  1360. });
  1361. addedModels.push(model);
  1362. }
  1363. });
  1364. setModelOptions(localModelOptions);
  1365. setCustomModel('');
  1366. handleInputChange('models', localModels);
  1367. if (addedModels.length > 0) {
  1368. showSuccess(
  1369. t('已新增 {{count}} 个模型:{{list}}', {
  1370. count: addedModels.length,
  1371. list: addedModels.join(', '),
  1372. }),
  1373. );
  1374. } else {
  1375. showInfo(t('未发现新增模型'));
  1376. }
  1377. };
  1378. const batchAllowed = (!isEdit || isMultiKeyChannel) && inputs.type !== 57;
  1379. const batchExtra = batchAllowed ? (
  1380. <Space>
  1381. {!isEdit && (
  1382. <Checkbox
  1383. disabled={isEdit}
  1384. checked={batch}
  1385. onChange={(e) => {
  1386. const checked = e.target.checked;
  1387. if (!checked && vertexFileList.length > 1) {
  1388. Modal.confirm({
  1389. title: t('切换为单密钥模式'),
  1390. content: t(
  1391. '将仅保留第一个密钥文件,其余文件将被移除,是否继续?',
  1392. ),
  1393. onOk: () => {
  1394. const firstFile = vertexFileList[0];
  1395. const firstKey = vertexKeys[0] ? [vertexKeys[0]] : [];
  1396. setVertexFileList([firstFile]);
  1397. setVertexKeys(firstKey);
  1398. formApiRef.current?.setValue('vertex_files', [firstFile]);
  1399. setInputs((prev) => ({ ...prev, vertex_files: [firstFile] }));
  1400. setBatch(false);
  1401. setMultiToSingle(false);
  1402. setMultiKeyMode('random');
  1403. },
  1404. onCancel: () => {
  1405. setBatch(true);
  1406. },
  1407. centered: true,
  1408. });
  1409. return;
  1410. }
  1411. setBatch(checked);
  1412. if (!checked) {
  1413. setMultiToSingle(false);
  1414. setMultiKeyMode('random');
  1415. } else {
  1416. // 批量模式下禁用手动输入,并清空手动输入的内容
  1417. setUseManualInput(false);
  1418. if (inputs.type === 41) {
  1419. // 清空手动输入的密钥内容
  1420. if (formApiRef.current) {
  1421. formApiRef.current.setValue('key', '');
  1422. }
  1423. handleInputChange('key', '');
  1424. }
  1425. }
  1426. }}
  1427. >
  1428. {t('批量创建')}
  1429. </Checkbox>
  1430. )}
  1431. {batch && (
  1432. <>
  1433. <Checkbox
  1434. disabled={isEdit}
  1435. checked={multiToSingle}
  1436. onChange={() => {
  1437. setMultiToSingle((prev) => {
  1438. const nextValue = !prev;
  1439. setInputs((prevInputs) => {
  1440. const newInputs = { ...prevInputs };
  1441. if (nextValue) {
  1442. newInputs.multi_key_mode = multiKeyMode;
  1443. } else {
  1444. delete newInputs.multi_key_mode;
  1445. }
  1446. return newInputs;
  1447. });
  1448. return nextValue;
  1449. });
  1450. }}
  1451. >
  1452. {t('密钥聚合模式')}
  1453. </Checkbox>
  1454. {inputs.type !== 41 && (
  1455. <Button
  1456. size='small'
  1457. type='tertiary'
  1458. theme='outline'
  1459. onClick={deduplicateKeys}
  1460. style={{ textDecoration: 'underline' }}
  1461. >
  1462. {t('密钥去重')}
  1463. </Button>
  1464. )}
  1465. </>
  1466. )}
  1467. </Space>
  1468. ) : null;
  1469. const channelOptionList = useMemo(
  1470. () =>
  1471. CHANNEL_OPTIONS.map((opt) => ({
  1472. ...opt,
  1473. // 保持 label 为纯文本以支持搜索
  1474. label: opt.label,
  1475. })),
  1476. [],
  1477. );
  1478. const renderChannelOption = (renderProps) => {
  1479. const {
  1480. disabled,
  1481. selected,
  1482. label,
  1483. value,
  1484. focused,
  1485. className,
  1486. style,
  1487. onMouseEnter,
  1488. onClick,
  1489. ...rest
  1490. } = renderProps;
  1491. const searchWords = channelSearchValue ? [channelSearchValue] : [];
  1492. // 构建样式类名
  1493. const optionClassName = [
  1494. 'flex items-center gap-3 px-3 py-2 transition-all duration-200 rounded-lg mx-2 my-1',
  1495. focused && 'bg-blue-50 shadow-sm',
  1496. selected &&
  1497. 'bg-blue-100 text-blue-700 shadow-lg ring-2 ring-blue-200 ring-opacity-50',
  1498. disabled && 'opacity-50 cursor-not-allowed',
  1499. !disabled && 'hover:bg-gray-50 hover:shadow-md cursor-pointer',
  1500. className,
  1501. ]
  1502. .filter(Boolean)
  1503. .join(' ');
  1504. return (
  1505. <div
  1506. style={style}
  1507. className={optionClassName}
  1508. onClick={() => !disabled && onClick()}
  1509. onMouseEnter={(e) => onMouseEnter()}
  1510. >
  1511. <div className='flex items-center gap-3 w-full'>
  1512. <div className='flex-shrink-0 w-5 h-5 flex items-center justify-center'>
  1513. {getChannelIcon(value)}
  1514. </div>
  1515. <div className='flex-1 min-w-0'>
  1516. <Highlight
  1517. sourceString={label}
  1518. searchWords={searchWords}
  1519. className='text-sm font-medium truncate'
  1520. />
  1521. </div>
  1522. {selected && (
  1523. <div className='flex-shrink-0 text-blue-600'>
  1524. <svg
  1525. width='16'
  1526. height='16'
  1527. viewBox='0 0 16 16'
  1528. fill='currentColor'
  1529. >
  1530. <path d='M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z' />
  1531. </svg>
  1532. </div>
  1533. )}
  1534. </div>
  1535. </div>
  1536. );
  1537. };
  1538. return (
  1539. <>
  1540. <SideSheet
  1541. placement={isEdit ? 'right' : 'left'}
  1542. title={
  1543. <Space>
  1544. <Tag color='blue' shape='circle'>
  1545. {isEdit ? t('编辑') : t('新建')}
  1546. </Tag>
  1547. <Title heading={4} className='m-0'>
  1548. {isEdit ? t('更新渠道信息') : t('创建新的渠道')}
  1549. </Title>
  1550. </Space>
  1551. }
  1552. bodyStyle={{ padding: '0' }}
  1553. visible={props.visible}
  1554. width={isMobile ? '100%' : 600}
  1555. footer={
  1556. <div className='flex justify-between items-center bg-white'>
  1557. <div className='flex gap-2'>
  1558. <Button
  1559. size='small'
  1560. type='tertiary'
  1561. icon={<IconChevronUp />}
  1562. onClick={() => navigateToSection('up')}
  1563. style={{
  1564. borderRadius: '50%',
  1565. width: '32px',
  1566. height: '32px',
  1567. padding: 0,
  1568. display: 'flex',
  1569. alignItems: 'center',
  1570. justifyContent: 'center',
  1571. }}
  1572. title={t('上一个表单块')}
  1573. />
  1574. <Button
  1575. size='small'
  1576. type='tertiary'
  1577. icon={<IconChevronDown />}
  1578. onClick={() => navigateToSection('down')}
  1579. style={{
  1580. borderRadius: '50%',
  1581. width: '32px',
  1582. height: '32px',
  1583. padding: 0,
  1584. display: 'flex',
  1585. alignItems: 'center',
  1586. justifyContent: 'center',
  1587. }}
  1588. title={t('下一个表单块')}
  1589. />
  1590. </div>
  1591. <Space>
  1592. <Button
  1593. theme='solid'
  1594. onClick={() => formApiRef.current?.submitForm()}
  1595. icon={<IconSave />}
  1596. >
  1597. {t('提交')}
  1598. </Button>
  1599. <Button
  1600. theme='light'
  1601. type='primary'
  1602. onClick={handleCancel}
  1603. icon={<IconClose />}
  1604. >
  1605. {t('取消')}
  1606. </Button>
  1607. </Space>
  1608. </div>
  1609. }
  1610. closeIcon={null}
  1611. onCancel={() => handleCancel()}
  1612. >
  1613. <Form
  1614. key={isEdit ? 'edit' : 'new'}
  1615. initValues={originInputs}
  1616. getFormApi={(api) => (formApiRef.current = api)}
  1617. onSubmit={submit}
  1618. >
  1619. {() => (
  1620. <Spin spinning={loading}>
  1621. <div className='p-2 space-y-3' ref={formContainerRef}>
  1622. <div ref={(el) => (formSectionRefs.current.basicInfo = el)}>
  1623. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  1624. {/* Header: Basic Info */}
  1625. <div className='flex items-center mb-2'>
  1626. <Avatar
  1627. size='small'
  1628. color='blue'
  1629. className='mr-2 shadow-md'
  1630. >
  1631. <IconServer size={16} />
  1632. </Avatar>
  1633. <div>
  1634. <Text className='text-lg font-medium'>
  1635. {t('基本信息')}
  1636. </Text>
  1637. <div className='text-xs text-gray-600'>
  1638. {t('渠道的基本配置信息')}
  1639. </div>
  1640. </div>
  1641. </div>
  1642. {isIonetChannel && (
  1643. <Banner
  1644. type='info'
  1645. closeIcon={null}
  1646. className='mb-4 rounded-xl'
  1647. description={t('此渠道由 IO.NET 自动同步,类型、密钥和 API 地址已锁定。')}
  1648. >
  1649. <Space>
  1650. {ionetMetadata?.deployment_id && (
  1651. <Button
  1652. size='small'
  1653. theme='light'
  1654. type='primary'
  1655. icon={<IconGlobe />}
  1656. onClick={handleOpenIonetDeployment}
  1657. >
  1658. {t('查看关联部署')}
  1659. </Button>
  1660. )}
  1661. </Space>
  1662. </Banner>
  1663. )}
  1664. <Form.Select
  1665. field='type'
  1666. label={t('类型')}
  1667. placeholder={t('请选择渠道类型')}
  1668. rules={[{ required: true, message: t('请选择渠道类型') }]}
  1669. optionList={channelOptionList}
  1670. style={{ width: '100%' }}
  1671. filter={selectFilter}
  1672. autoClearSearchValue={false}
  1673. searchPosition='dropdown'
  1674. onSearch={(value) => setChannelSearchValue(value)}
  1675. renderOptionItem={renderChannelOption}
  1676. onChange={(value) => handleInputChange('type', value)}
  1677. disabled={isIonetLocked}
  1678. />
  1679. {inputs.type === 20 && (
  1680. <Form.Switch
  1681. field='is_enterprise_account'
  1682. label={t('是否为企业账户')}
  1683. checkedText={t('是')}
  1684. uncheckedText={t('否')}
  1685. onChange={(value) => {
  1686. setIsEnterpriseAccount(value);
  1687. handleInputChange('is_enterprise_account', value);
  1688. }}
  1689. extraText={t(
  1690. '企业账户为特殊返回格式,需要特殊处理,如果非企业账户,请勿勾选',
  1691. )}
  1692. initValue={inputs.is_enterprise_account}
  1693. />
  1694. )}
  1695. <Form.Input
  1696. field='name'
  1697. label={t('名称')}
  1698. placeholder={t('请为渠道命名')}
  1699. rules={[{ required: true, message: t('请为渠道命名') }]}
  1700. showClear
  1701. onChange={(value) => handleInputChange('name', value)}
  1702. autoComplete='new-password'
  1703. />
  1704. {inputs.type === 33 && (
  1705. <>
  1706. <Form.Select
  1707. field='aws_key_type'
  1708. label={t('密钥格式')}
  1709. placeholder={t('请选择密钥格式')}
  1710. optionList={[
  1711. {
  1712. label: 'AccessKey / SecretAccessKey',
  1713. value: 'ak_sk',
  1714. },
  1715. { label: 'API Key', value: 'api_key' },
  1716. ]}
  1717. style={{ width: '100%' }}
  1718. value={inputs.aws_key_type || 'ak_sk'}
  1719. onChange={(value) => {
  1720. handleChannelOtherSettingsChange('aws_key_type', value);
  1721. }}
  1722. extraText={t(
  1723. 'AK/SK 模式:使用 AccessKey 和 SecretAccessKey;API Key 模式:使用 API Key',
  1724. )}
  1725. />
  1726. </>
  1727. )}
  1728. {inputs.type === 41 && (
  1729. <Form.Select
  1730. field='vertex_key_type'
  1731. label={t('密钥格式')}
  1732. placeholder={t('请选择密钥格式')}
  1733. optionList={[
  1734. { label: 'JSON', value: 'json' },
  1735. { label: 'API Key', value: 'api_key' },
  1736. ]}
  1737. style={{ width: '100%' }}
  1738. value={inputs.vertex_key_type || 'json'}
  1739. onChange={(value) => {
  1740. // 更新设置中的 vertex_key_type
  1741. handleChannelOtherSettingsChange(
  1742. 'vertex_key_type',
  1743. value,
  1744. );
  1745. // 切换为 api_key 时,关闭批量与手动/文件切换,并清理已选文件
  1746. if (value === 'api_key') {
  1747. setBatch(false);
  1748. setUseManualInput(false);
  1749. setVertexKeys([]);
  1750. setVertexFileList([]);
  1751. if (formApiRef.current) {
  1752. formApiRef.current.setValue('vertex_files', []);
  1753. }
  1754. }
  1755. }}
  1756. extraText={
  1757. inputs.vertex_key_type === 'api_key'
  1758. ? t('API Key 模式下不支持批量创建')
  1759. : t('JSON 模式支持手动输入或上传服务账号 JSON')
  1760. }
  1761. />
  1762. )}
  1763. {batch ? (
  1764. inputs.type === 41 &&
  1765. (inputs.vertex_key_type || 'json') === 'json' ? (
  1766. <Form.Upload
  1767. field='vertex_files'
  1768. label={t('密钥文件 (.json)')}
  1769. accept='.json'
  1770. multiple
  1771. draggable
  1772. dragIcon={<IconBolt />}
  1773. dragMainText={t('点击上传文件或拖拽文件到这里')}
  1774. dragSubText={t('仅支持 JSON 文件,支持多文件')}
  1775. style={{ marginTop: 10 }}
  1776. uploadTrigger='custom'
  1777. beforeUpload={() => false}
  1778. onChange={handleVertexUploadChange}
  1779. fileList={vertexFileList}
  1780. rules={
  1781. isEdit
  1782. ? []
  1783. : [
  1784. {
  1785. required: true,
  1786. message: t('请上传密钥文件'),
  1787. },
  1788. ]
  1789. }
  1790. extraText={batchExtra}
  1791. />
  1792. ) : (
  1793. <Form.TextArea
  1794. field='key'
  1795. label={t('密钥')}
  1796. placeholder={
  1797. inputs.type === 33
  1798. ? inputs.aws_key_type === 'api_key'
  1799. ? t('请输入 API Key,一行一个,格式:APIKey|Region')
  1800. : t(
  1801. '请输入密钥,一行一个,格式:AccessKey|SecretAccessKey|Region',
  1802. )
  1803. : t('请输入密钥,一行一个')
  1804. }
  1805. rules={
  1806. isEdit
  1807. ? []
  1808. : [{ required: true, message: t('请输入密钥') }]
  1809. }
  1810. autosize
  1811. autoComplete='new-password'
  1812. onChange={(value) => handleInputChange('key', value)}
  1813. disabled={isIonetLocked}
  1814. extraText={
  1815. <div className='flex items-center gap-2 flex-wrap'>
  1816. {isEdit &&
  1817. isMultiKeyChannel &&
  1818. keyMode === 'append' && (
  1819. <Text type='warning' size='small'>
  1820. {t(
  1821. '追加模式:新密钥将添加到现有密钥列表的末尾',
  1822. )}
  1823. </Text>
  1824. )}
  1825. {isEdit && (
  1826. <Button
  1827. size='small'
  1828. type='primary'
  1829. theme='outline'
  1830. onClick={handleShow2FAModal}
  1831. >
  1832. {t('查看密钥')}
  1833. </Button>
  1834. )}
  1835. {batchExtra}
  1836. </div>
  1837. }
  1838. showClear
  1839. />
  1840. )
  1841. ) : (
  1842. <>
  1843. {inputs.type === 57 ? (
  1844. <>
  1845. <Form.TextArea
  1846. field='key'
  1847. label={
  1848. isEdit
  1849. ? t('密钥(编辑模式下,保存的密钥不会显示)')
  1850. : t('密钥')
  1851. }
  1852. placeholder={t(
  1853. '请输入 JSON 格式的 OAuth 凭据,例如:\n{\n "access_token": "...",\n "account_id": "..." \n}',
  1854. )}
  1855. rules={
  1856. isEdit
  1857. ? []
  1858. : [{ required: true, message: t('请输入密钥') }]
  1859. }
  1860. autoComplete='new-password'
  1861. onChange={(value) => handleInputChange('key', value)}
  1862. disabled={isIonetLocked}
  1863. extraText={
  1864. <div className='flex flex-col gap-2'>
  1865. <Text type='tertiary' size='small'>
  1866. {t(
  1867. '仅支持 JSON 对象,必须包含 access_token 与 account_id',
  1868. )}
  1869. </Text>
  1870. <Space wrap spacing='tight'>
  1871. <Button
  1872. size='small'
  1873. type='primary'
  1874. theme='outline'
  1875. onClick={() =>
  1876. setCodexOAuthModalVisible(true)
  1877. }
  1878. disabled={isIonetLocked}
  1879. >
  1880. {t('Codex 授权')}
  1881. </Button>
  1882. {isEdit && (
  1883. <Button
  1884. size='small'
  1885. type='primary'
  1886. theme='outline'
  1887. onClick={handleRefreshCodexCredential}
  1888. loading={codexCredentialRefreshing}
  1889. disabled={isIonetLocked}
  1890. >
  1891. {t('刷新凭证')}
  1892. </Button>
  1893. )}
  1894. <Button
  1895. size='small'
  1896. type='primary'
  1897. theme='outline'
  1898. onClick={() => formatJsonField('key')}
  1899. disabled={isIonetLocked}
  1900. >
  1901. {t('格式化')}
  1902. </Button>
  1903. {isEdit && (
  1904. <Button
  1905. size='small'
  1906. type='primary'
  1907. theme='outline'
  1908. onClick={handleShow2FAModal}
  1909. disabled={isIonetLocked}
  1910. >
  1911. {t('查看密钥')}
  1912. </Button>
  1913. )}
  1914. {batchExtra}
  1915. </Space>
  1916. </div>
  1917. }
  1918. autosize
  1919. showClear
  1920. />
  1921. <CodexOAuthModal
  1922. visible={codexOAuthModalVisible}
  1923. onCancel={() => setCodexOAuthModalVisible(false)}
  1924. onSuccess={handleCodexOAuthGenerated}
  1925. />
  1926. </>
  1927. ) : inputs.type === 41 &&
  1928. (inputs.vertex_key_type || 'json') === 'json' ? (
  1929. <>
  1930. {!batch && (
  1931. <div className='flex items-center justify-between mb-3'>
  1932. <Text className='text-sm font-medium'>
  1933. {t('密钥输入方式')}
  1934. </Text>
  1935. <Space>
  1936. <Button
  1937. size='small'
  1938. type={
  1939. !useManualInput ? 'primary' : 'tertiary'
  1940. }
  1941. onClick={() => {
  1942. setUseManualInput(false);
  1943. // 切换到文件上传模式时清空手动输入的密钥
  1944. if (formApiRef.current) {
  1945. formApiRef.current.setValue('key', '');
  1946. }
  1947. handleInputChange('key', '');
  1948. }}
  1949. >
  1950. {t('文件上传')}
  1951. </Button>
  1952. <Button
  1953. size='small'
  1954. type={useManualInput ? 'primary' : 'tertiary'}
  1955. onClick={() => {
  1956. setUseManualInput(true);
  1957. // 切换到手动输入模式时清空文件上传相关状态
  1958. setVertexKeys([]);
  1959. setVertexFileList([]);
  1960. if (formApiRef.current) {
  1961. formApiRef.current.setValue(
  1962. 'vertex_files',
  1963. [],
  1964. );
  1965. }
  1966. setInputs((prev) => ({
  1967. ...prev,
  1968. vertex_files: [],
  1969. }));
  1970. }}
  1971. >
  1972. {t('手动输入')}
  1973. </Button>
  1974. </Space>
  1975. </div>
  1976. )}
  1977. {batch && (
  1978. <Banner
  1979. type='info'
  1980. description={t(
  1981. '批量创建模式下仅支持文件上传,不支持手动输入',
  1982. )}
  1983. className='!rounded-lg mb-3'
  1984. />
  1985. )}
  1986. {useManualInput && !batch ? (
  1987. <Form.TextArea
  1988. field='key'
  1989. label={
  1990. isEdit
  1991. ? t(
  1992. '密钥(编辑模式下,保存的密钥不会显示)',
  1993. )
  1994. : t('密钥')
  1995. }
  1996. placeholder={t(
  1997. '请输入 JSON 格式的密钥内容,例如:\n{\n "type": "service_account",\n "project_id": "your-project-id",\n "private_key_id": "...",\n "private_key": "...",\n "client_email": "...",\n "client_id": "...",\n "auth_uri": "...",\n "token_uri": "...",\n "auth_provider_x509_cert_url": "...",\n "client_x509_cert_url": "..."\n}',
  1998. )}
  1999. rules={
  2000. isEdit
  2001. ? []
  2002. : [
  2003. {
  2004. required: true,
  2005. message: t('请输入密钥'),
  2006. },
  2007. ]
  2008. }
  2009. autoComplete='new-password'
  2010. onChange={(value) =>
  2011. handleInputChange('key', value)
  2012. }
  2013. extraText={
  2014. <div className='flex items-center gap-2'>
  2015. <Text type='tertiary' size='small'>
  2016. {t('请输入完整的 JSON 格式密钥内容')}
  2017. </Text>
  2018. {isEdit &&
  2019. isMultiKeyChannel &&
  2020. keyMode === 'append' && (
  2021. <Text type='warning' size='small'>
  2022. {t(
  2023. '追加模式:新密钥将添加到现有密钥列表的末尾',
  2024. )}
  2025. </Text>
  2026. )}
  2027. {isEdit && (
  2028. <Button
  2029. size='small'
  2030. type='primary'
  2031. theme='outline'
  2032. onClick={handleShow2FAModal}
  2033. >
  2034. {t('查看密钥')}
  2035. </Button>
  2036. )}
  2037. {batchExtra}
  2038. </div>
  2039. }
  2040. autosize
  2041. showClear
  2042. />
  2043. ) : (
  2044. <Form.Upload
  2045. field='vertex_files'
  2046. label={t('密钥文件 (.json)')}
  2047. accept='.json'
  2048. draggable
  2049. dragIcon={<IconBolt />}
  2050. dragMainText={t('点击上传文件或拖拽文件到这里')}
  2051. dragSubText={t('仅支持 JSON 文件')}
  2052. style={{ marginTop: 10 }}
  2053. uploadTrigger='custom'
  2054. beforeUpload={() => false}
  2055. onChange={handleVertexUploadChange}
  2056. fileList={vertexFileList}
  2057. rules={
  2058. isEdit
  2059. ? []
  2060. : [
  2061. {
  2062. required: true,
  2063. message: t('请上传密钥文件'),
  2064. },
  2065. ]
  2066. }
  2067. extraText={batchExtra}
  2068. />
  2069. )}
  2070. </>
  2071. ) : (
  2072. <Form.Input
  2073. field='key'
  2074. label={
  2075. isEdit
  2076. ? t('密钥(编辑模式下,保存的密钥不会显示)')
  2077. : t('密钥')
  2078. }
  2079. placeholder={
  2080. inputs.type === 33
  2081. ? inputs.aws_key_type === 'api_key'
  2082. ? t('请输入 API Key,格式:APIKey|Region')
  2083. : t('按照如下格式输入:AccessKey|SecretAccessKey|Region')
  2084. : t(type2secretPrompt(inputs.type))
  2085. }
  2086. rules={
  2087. isEdit
  2088. ? []
  2089. : [{ required: true, message: t('请输入密钥') }]
  2090. }
  2091. autoComplete='new-password'
  2092. onChange={(value) =>
  2093. handleInputChange('key', value)
  2094. }
  2095. extraText={
  2096. <div className='flex items-center gap-2'>
  2097. {isEdit &&
  2098. isMultiKeyChannel &&
  2099. keyMode === 'append' && (
  2100. <Text type='warning' size='small'>
  2101. {t(
  2102. '追加模式:新密钥将添加到现有密钥列表的末尾',
  2103. )}
  2104. </Text>
  2105. )}
  2106. {isEdit && (
  2107. <Button
  2108. size='small'
  2109. type='primary'
  2110. theme='outline'
  2111. onClick={handleShow2FAModal}
  2112. >
  2113. {t('查看密钥')}
  2114. </Button>
  2115. )}
  2116. {batchExtra}
  2117. </div>
  2118. }
  2119. showClear
  2120. />
  2121. )}
  2122. </>
  2123. )}
  2124. {isEdit && isMultiKeyChannel && (
  2125. <Form.Select
  2126. field='key_mode'
  2127. label={t('密钥更新模式')}
  2128. placeholder={t('请选择密钥更新模式')}
  2129. optionList={[
  2130. { label: t('追加到现有密钥'), value: 'append' },
  2131. { label: t('覆盖现有密钥'), value: 'replace' },
  2132. ]}
  2133. style={{ width: '100%' }}
  2134. value={keyMode}
  2135. onChange={(value) => setKeyMode(value)}
  2136. extraText={
  2137. <Text type='tertiary' size='small'>
  2138. {keyMode === 'replace'
  2139. ? t('覆盖模式:将完全替换现有的所有密钥')
  2140. : t('追加模式:将新密钥添加到现有密钥列表末尾')}
  2141. </Text>
  2142. }
  2143. />
  2144. )}
  2145. {batch && multiToSingle && (
  2146. <>
  2147. <Form.Select
  2148. field='multi_key_mode'
  2149. label={t('密钥聚合模式')}
  2150. placeholder={t('请选择多密钥使用策略')}
  2151. optionList={[
  2152. { label: t('随机'), value: 'random' },
  2153. { label: t('轮询'), value: 'polling' },
  2154. ]}
  2155. style={{ width: '100%' }}
  2156. value={inputs.multi_key_mode || 'random'}
  2157. onChange={(value) => {
  2158. setMultiKeyMode(value);
  2159. handleInputChange('multi_key_mode', value);
  2160. }}
  2161. />
  2162. {inputs.multi_key_mode === 'polling' && (
  2163. <Banner
  2164. type='warning'
  2165. description={t(
  2166. '轮询模式必须搭配Redis和内存缓存功能使用,否则性能将大幅降低,并且无法实现轮询功能',
  2167. )}
  2168. className='!rounded-lg mt-2'
  2169. />
  2170. )}
  2171. </>
  2172. )}
  2173. {inputs.type === 18 && (
  2174. <Form.Input
  2175. field='other'
  2176. label={t('模型版本')}
  2177. placeholder={
  2178. '请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1'
  2179. }
  2180. onChange={(value) => handleInputChange('other', value)}
  2181. showClear
  2182. />
  2183. )}
  2184. {inputs.type === 41 && (
  2185. <JSONEditor
  2186. key={`region-${isEdit ? channelId : 'new'}`}
  2187. field='other'
  2188. label={t('部署地区')}
  2189. placeholder={t(
  2190. '请输入部署地区,例如:us-central1\n支持使用模型映射格式\n{\n "default": "us-central1",\n "claude-3-5-sonnet-20240620": "europe-west1"\n}',
  2191. )}
  2192. value={inputs.other || ''}
  2193. onChange={(value) => handleInputChange('other', value)}
  2194. rules={[
  2195. { required: true, message: t('请填写部署地区') },
  2196. ]}
  2197. template={REGION_EXAMPLE}
  2198. templateLabel={t('填入模板')}
  2199. editorType='region'
  2200. formApi={formApiRef.current}
  2201. extraText={t('设置默认地区和特定模型的专用地区')}
  2202. />
  2203. )}
  2204. {inputs.type === 21 && (
  2205. <Form.Input
  2206. field='other'
  2207. label={t('知识库 ID')}
  2208. placeholder={'请输入知识库 ID,例如:123456'}
  2209. onChange={(value) => handleInputChange('other', value)}
  2210. showClear
  2211. />
  2212. )}
  2213. {inputs.type === 39 && (
  2214. <Form.Input
  2215. field='other'
  2216. label='Account ID'
  2217. placeholder={
  2218. '请输入Account ID,例如:d6b5da8hk1awo8nap34ube6gh'
  2219. }
  2220. onChange={(value) => handleInputChange('other', value)}
  2221. showClear
  2222. />
  2223. )}
  2224. {inputs.type === 49 && (
  2225. <Form.Input
  2226. field='other'
  2227. label={t('智能体ID')}
  2228. placeholder={'请输入智能体ID,例如:7342866812345'}
  2229. onChange={(value) => handleInputChange('other', value)}
  2230. showClear
  2231. />
  2232. )}
  2233. {inputs.type === 1 && (
  2234. <Form.Input
  2235. field='openai_organization'
  2236. label={t('组织')}
  2237. placeholder={t('请输入组织org-xxx')}
  2238. showClear
  2239. helpText={t('组织,不填则为默认组织')}
  2240. onChange={(value) =>
  2241. handleInputChange('openai_organization', value)
  2242. }
  2243. />
  2244. )}
  2245. </Card>
  2246. </div>
  2247. {/* API Configuration Card */}
  2248. {showApiConfigCard && (
  2249. <div ref={(el) => (formSectionRefs.current.apiConfig = el)}>
  2250. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2251. {/* Header: API Config */}
  2252. <div
  2253. className='flex items-center mb-2'
  2254. onClick={handleApiConfigSecretClick}
  2255. >
  2256. <Avatar
  2257. size='small'
  2258. color='green'
  2259. className='mr-2 shadow-md'
  2260. >
  2261. <IconGlobe size={16} />
  2262. </Avatar>
  2263. <div>
  2264. <Text className='text-lg font-medium'>
  2265. {t('API 配置')}
  2266. </Text>
  2267. <div className='text-xs text-gray-600'>
  2268. {t('API 地址和相关配置')}
  2269. </div>
  2270. </div>
  2271. </div>
  2272. {inputs.type === 40 && (
  2273. <Banner
  2274. type='info'
  2275. description={
  2276. <div>
  2277. <Text strong>{t('邀请链接')}:</Text>
  2278. <Text
  2279. link
  2280. underline
  2281. className='ml-2 cursor-pointer'
  2282. onClick={() =>
  2283. window.open(
  2284. 'https://cloud.siliconflow.cn/i/hij0YNTZ',
  2285. )
  2286. }
  2287. >
  2288. https://cloud.siliconflow.cn/i/hij0YNTZ
  2289. </Text>
  2290. </div>
  2291. }
  2292. className='!rounded-lg'
  2293. />
  2294. )}
  2295. {inputs.type === 3 && (
  2296. <>
  2297. <Banner
  2298. type='warning'
  2299. description={t(
  2300. '2025年5月10日后添加的渠道,不需要再在部署的时候移除模型名称中的"."',
  2301. )}
  2302. className='!rounded-lg'
  2303. />
  2304. <div>
  2305. <Form.Input
  2306. field='base_url'
  2307. label='AZURE_OPENAI_ENDPOINT'
  2308. placeholder={t(
  2309. '请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com',
  2310. )}
  2311. onChange={(value) =>
  2312. handleInputChange('base_url', value)
  2313. }
  2314. showClear
  2315. disabled={isIonetLocked}
  2316. />
  2317. </div>
  2318. <div>
  2319. <Form.Input
  2320. field='other'
  2321. label={t('默认 API 版本')}
  2322. placeholder={t(
  2323. '请输入默认 API 版本,例如:2025-04-01-preview',
  2324. )}
  2325. onChange={(value) =>
  2326. handleInputChange('other', value)
  2327. }
  2328. showClear
  2329. />
  2330. </div>
  2331. <div>
  2332. <Form.Input
  2333. field='azure_responses_version'
  2334. label={t(
  2335. '默认 Responses API 版本,为空则使用上方版本',
  2336. )}
  2337. placeholder={t('例如:preview')}
  2338. onChange={(value) =>
  2339. handleChannelOtherSettingsChange(
  2340. 'azure_responses_version',
  2341. value,
  2342. )
  2343. }
  2344. showClear
  2345. />
  2346. </div>
  2347. </>
  2348. )}
  2349. {inputs.type === 8 && (
  2350. <>
  2351. <Banner
  2352. type='warning'
  2353. description={t(
  2354. '如果你对接的是上游One API或者New API等转发项目,请使用OpenAI类型,不要使用此类型,除非你知道你在做什么。',
  2355. )}
  2356. className='!rounded-lg'
  2357. />
  2358. <div>
  2359. <Form.Input
  2360. field='base_url'
  2361. label={t('完整的 Base URL,支持变量{model}')}
  2362. placeholder={t(
  2363. '请输入完整的URL,例如:https://api.openai.com/v1/chat/completions',
  2364. )}
  2365. onChange={(value) =>
  2366. handleInputChange('base_url', value)
  2367. }
  2368. showClear
  2369. disabled={isIonetLocked}
  2370. />
  2371. </div>
  2372. </>
  2373. )}
  2374. {inputs.type === 37 && (
  2375. <Banner
  2376. type='warning'
  2377. description={t(
  2378. 'Dify渠道只适配chatflow和agent,并且agent不支持图片!',
  2379. )}
  2380. className='!rounded-lg'
  2381. />
  2382. )}
  2383. {inputs.type !== 3 &&
  2384. inputs.type !== 8 &&
  2385. inputs.type !== 22 &&
  2386. inputs.type !== 36 &&
  2387. (inputs.type !== 45 || doubaoApiEditUnlocked) && (
  2388. <div>
  2389. <Form.Input
  2390. field='base_url'
  2391. label={t('API地址')}
  2392. placeholder={t(
  2393. '此项可选,用于通过自定义API地址来进行 API 调用,末尾不要带/v1和/',
  2394. )}
  2395. onChange={(value) =>
  2396. handleInputChange('base_url', value)
  2397. }
  2398. showClear
  2399. disabled={isIonetLocked}
  2400. extraText={t(
  2401. '对于官方渠道,new-api已经内置地址,除非是第三方代理站点或者Azure的特殊接入地址,否则不需要填写',
  2402. )}
  2403. />
  2404. </div>
  2405. )}
  2406. {inputs.type === 22 && (
  2407. <div>
  2408. <Form.Input
  2409. field='base_url'
  2410. label={t('私有部署地址')}
  2411. placeholder={t(
  2412. '请输入私有部署地址,格式为:https://fastgpt.run/api/openapi',
  2413. )}
  2414. onChange={(value) =>
  2415. handleInputChange('base_url', value)
  2416. }
  2417. showClear
  2418. disabled={isIonetLocked}
  2419. />
  2420. </div>
  2421. )}
  2422. {inputs.type === 36 && (
  2423. <div>
  2424. <Form.Input
  2425. field='base_url'
  2426. label={t(
  2427. '注意非Chat API,请务必填写正确的API地址,否则可能导致无法使用',
  2428. )}
  2429. placeholder={t(
  2430. '请输入到 /suno 前的路径,通常就是域名,例如:https://api.example.com',
  2431. )}
  2432. onChange={(value) =>
  2433. handleInputChange('base_url', value)
  2434. }
  2435. showClear
  2436. disabled={isIonetLocked}
  2437. />
  2438. </div>
  2439. )}
  2440. {inputs.type === 45 && !doubaoApiEditUnlocked && (
  2441. <div>
  2442. <Form.Select
  2443. field='base_url'
  2444. label={t('API地址')}
  2445. placeholder={t('请选择API地址')}
  2446. onChange={(value) =>
  2447. handleInputChange('base_url', value)
  2448. }
  2449. optionList={[
  2450. {
  2451. value: 'https://ark.cn-beijing.volces.com',
  2452. label: 'https://ark.cn-beijing.volces.com',
  2453. },
  2454. {
  2455. value: 'https://ark.ap-southeast.bytepluses.com',
  2456. label: 'https://ark.ap-southeast.bytepluses.com',
  2457. },
  2458. {
  2459. value: 'doubao-coding-plan',
  2460. label: 'Doubao Coding Plan',
  2461. },
  2462. ]}defaultValue='https://ark.cn-beijing.volces.com'
  2463. disabled={isIonetLocked}
  2464. />
  2465. </div>
  2466. )}
  2467. </Card>
  2468. </div>
  2469. )}
  2470. {/* Model Configuration Card */}
  2471. <div ref={(el) => (formSectionRefs.current.modelConfig = el)}>
  2472. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2473. {/* Header: Model Config */}
  2474. <div className='flex items-center mb-2'>
  2475. <Avatar
  2476. size='small'
  2477. color='purple'
  2478. className='mr-2 shadow-md'
  2479. >
  2480. <IconCode size={16} />
  2481. </Avatar>
  2482. <div>
  2483. <Text className='text-lg font-medium'>
  2484. {t('模型配置')}
  2485. </Text>
  2486. <div className='text-xs text-gray-600'>
  2487. {t('模型选择和映射设置')}
  2488. </div>
  2489. </div>
  2490. </div>
  2491. <Form.Select
  2492. field='models'
  2493. label={t('模型')}
  2494. placeholder={t('请选择该渠道所支持的模型')}
  2495. rules={[{ required: true, message: t('请选择模型') }]}
  2496. multiple
  2497. filter={selectFilter}
  2498. autoClearSearchValue={false}
  2499. searchPosition='dropdown'
  2500. optionList={modelOptions}
  2501. style={{ width: '100%' }}
  2502. onChange={(value) => handleInputChange('models', value)}
  2503. renderSelectedItem={(optionNode) => {
  2504. const modelName = String(optionNode?.value ?? '');
  2505. return {
  2506. isRenderInTag: true,
  2507. content: (
  2508. <span
  2509. className='cursor-pointer select-none'
  2510. role='button'
  2511. tabIndex={0}
  2512. title={t('点击复制模型名称')}
  2513. onClick={async (e) => {
  2514. e.stopPropagation();
  2515. const ok = await copy(modelName);
  2516. if (ok) {
  2517. showSuccess(
  2518. t('已复制:{{name}}', { name: modelName }),
  2519. );
  2520. } else {
  2521. showError(t('复制失败'));
  2522. }
  2523. }}
  2524. >
  2525. {optionNode.label || modelName}
  2526. </span>
  2527. ),
  2528. };
  2529. }}
  2530. extraText={
  2531. <Space wrap>
  2532. <Button
  2533. size='small'
  2534. type='primary'
  2535. onClick={() =>
  2536. handleInputChange('models', basicModels)
  2537. }
  2538. >
  2539. {t('填入相关模型')}
  2540. </Button>
  2541. <Button
  2542. size='small'
  2543. type='secondary'
  2544. onClick={() =>
  2545. handleInputChange('models', fullModels)
  2546. }
  2547. >
  2548. {t('填入所有模型')}
  2549. </Button>
  2550. {MODEL_FETCHABLE_TYPES.has(inputs.type) && (
  2551. <Button
  2552. size='small'
  2553. type='tertiary'
  2554. onClick={() => fetchUpstreamModelList('models')}
  2555. >
  2556. {t('获取模型列表')}
  2557. </Button>
  2558. )}
  2559. {inputs.type === 4 && isEdit && (
  2560. <Button
  2561. size='small'
  2562. type='primary'
  2563. theme='light'
  2564. onClick={() => setOllamaModalVisible(true)}
  2565. >
  2566. {t('Ollama 模型管理')}
  2567. </Button>
  2568. )}
  2569. <Button
  2570. size='small'
  2571. type='warning'
  2572. onClick={() => handleInputChange('models', [])}
  2573. >
  2574. {t('清除所有模型')}
  2575. </Button>
  2576. <Button
  2577. size='small'
  2578. type='tertiary'
  2579. onClick={() => {
  2580. if (inputs.models.length === 0) {
  2581. showInfo(t('没有模型可以复制'));
  2582. return;
  2583. }
  2584. try {
  2585. copy(inputs.models.join(','));
  2586. showSuccess(t('模型列表已复制到剪贴板'));
  2587. } catch (error) {
  2588. showError(t('复制失败'));
  2589. }
  2590. }}
  2591. >
  2592. {t('复制所有模型')}
  2593. </Button>
  2594. {modelGroups &&
  2595. modelGroups.length > 0 &&
  2596. modelGroups.map((group) => (
  2597. <Button
  2598. key={group.id}
  2599. size='small'
  2600. type='primary'
  2601. onClick={() => {
  2602. let items = [];
  2603. try {
  2604. if (Array.isArray(group.items)) {
  2605. items = group.items;
  2606. } else if (typeof group.items === 'string') {
  2607. const parsed = JSON.parse(
  2608. group.items || '[]',
  2609. );
  2610. if (Array.isArray(parsed)) items = parsed;
  2611. }
  2612. } catch {}
  2613. const current =
  2614. formApiRef.current?.getValue('models') ||
  2615. inputs.models ||
  2616. [];
  2617. const merged = Array.from(
  2618. new Set(
  2619. [...current, ...items]
  2620. .map((m) => (m || '').trim())
  2621. .filter(Boolean),
  2622. ),
  2623. );
  2624. handleInputChange('models', merged);
  2625. }}
  2626. >
  2627. {group.name}
  2628. </Button>
  2629. ))}
  2630. </Space>
  2631. }
  2632. />
  2633. <Form.Input
  2634. field='custom_model'
  2635. label={t('自定义模型名称')}
  2636. placeholder={t('输入自定义模型名称')}
  2637. onChange={(value) => setCustomModel(value.trim())}
  2638. value={customModel}
  2639. suffix={
  2640. <Button
  2641. size='small'
  2642. type='primary'
  2643. onClick={addCustomModels}
  2644. >
  2645. {t('填入')}
  2646. </Button>
  2647. }
  2648. />
  2649. <Form.Input
  2650. field='test_model'
  2651. label={t('默认测试模型')}
  2652. placeholder={t('不填则为模型列表第一个')}
  2653. onChange={(value) =>
  2654. handleInputChange('test_model', value)
  2655. }
  2656. showClear
  2657. />
  2658. <JSONEditor
  2659. key={`model_mapping-${isEdit ? channelId : 'new'}`}
  2660. field='model_mapping'
  2661. label={t('模型重定向')}
  2662. placeholder={
  2663. t(
  2664. '此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:',
  2665. ) +
  2666. `\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`
  2667. }
  2668. value={inputs.model_mapping || ''}
  2669. onChange={(value) =>
  2670. handleInputChange('model_mapping', value)
  2671. }
  2672. template={MODEL_MAPPING_EXAMPLE}
  2673. templateLabel={t('填入模板')}
  2674. editorType='keyValue'
  2675. formApi={formApiRef.current}
  2676. extraText={t(
  2677. '键为请求中的模型名称,值为要替换的模型名称',
  2678. )}
  2679. />
  2680. </Card>
  2681. </div>
  2682. {/* Advanced Settings Card */}
  2683. <div
  2684. ref={(el) => (formSectionRefs.current.advancedSettings = el)}
  2685. >
  2686. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  2687. {/* Header: Advanced Settings */}
  2688. <div className='flex items-center mb-2'>
  2689. <Avatar
  2690. size='small'
  2691. color='orange'
  2692. className='mr-2 shadow-md'
  2693. >
  2694. <IconSetting size={16} />
  2695. </Avatar>
  2696. <div>
  2697. <Text className='text-lg font-medium'>
  2698. {t('高级设置')}
  2699. </Text>
  2700. <div className='text-xs text-gray-600'>
  2701. {t('渠道的高级配置选项')}
  2702. </div>
  2703. </div>
  2704. </div>
  2705. <Form.Select
  2706. field='groups'
  2707. label={t('分组')}
  2708. placeholder={t('请选择可以使用该渠道的分组')}
  2709. multiple
  2710. allowAdditions
  2711. additionLabel={t(
  2712. '请在系统设置页面编辑分组倍率以添加新的分组:',
  2713. )}
  2714. optionList={groupOptions}
  2715. style={{ width: '100%' }}
  2716. onChange={(value) => handleInputChange('groups', value)}
  2717. />
  2718. <Form.Input
  2719. field='tag'
  2720. label={t('渠道标签')}
  2721. placeholder={t('渠道标签')}
  2722. showClear
  2723. onChange={(value) => handleInputChange('tag', value)}
  2724. />
  2725. <Form.TextArea
  2726. field='remark'
  2727. label={t('备注')}
  2728. placeholder={t('请输入备注(仅管理员可见)')}
  2729. maxLength={255}
  2730. showClear
  2731. onChange={(value) => handleInputChange('remark', value)}
  2732. />
  2733. <Row gutter={12}>
  2734. <Col span={12}>
  2735. <Form.InputNumber
  2736. field='priority'
  2737. label={t('渠道优先级')}
  2738. placeholder={t('渠道优先级')}
  2739. min={0}
  2740. onNumberChange={(value) =>
  2741. handleInputChange('priority', value)
  2742. }
  2743. style={{ width: '100%' }}
  2744. />
  2745. </Col>
  2746. <Col span={12}>
  2747. <Form.InputNumber
  2748. field='weight'
  2749. label={t('渠道权重')}
  2750. placeholder={t('渠道权重')}
  2751. min={0}
  2752. onNumberChange={(value) =>
  2753. handleInputChange('weight', value)
  2754. }
  2755. style={{ width: '100%' }}
  2756. />
  2757. </Col>
  2758. </Row>
  2759. <Form.Switch
  2760. field='auto_ban'
  2761. label={t('是否自动禁用')}
  2762. checkedText={t('开')}
  2763. uncheckedText={t('关')}
  2764. onChange={(value) => setAutoBan(value)}
  2765. extraText={t(
  2766. '仅当自动禁用开启时有效,关闭后不会自动禁用该渠道',
  2767. )}
  2768. initValue={autoBan}
  2769. />
  2770. <Form.TextArea
  2771. field='param_override'
  2772. label={t('参数覆盖')}
  2773. placeholder={
  2774. t(
  2775. '此项可选,用于覆盖请求参数。不支持覆盖 stream 参数',
  2776. ) +
  2777. '\n' +
  2778. t('旧格式(直接覆盖):') +
  2779. '\n{\n "temperature": 0,\n "max_tokens": 1000\n}' +
  2780. '\n\n' +
  2781. t('新格式(支持条件判断与json自定义):') +
  2782. '\n{\n "operations": [\n {\n "path": "temperature",\n "mode": "set",\n "value": 0.7,\n "conditions": [\n {\n "path": "model",\n "mode": "prefix",\n "value": "gpt"\n }\n ]\n }\n ]\n}'
  2783. }
  2784. autosize
  2785. onChange={(value) =>
  2786. handleInputChange('param_override', value)
  2787. }
  2788. extraText={
  2789. <div className='flex gap-2 flex-wrap'>
  2790. <Text
  2791. className='!text-semi-color-primary cursor-pointer'
  2792. onClick={() =>
  2793. handleInputChange(
  2794. 'param_override',
  2795. JSON.stringify({ temperature: 0 }, null, 2),
  2796. )
  2797. }
  2798. >
  2799. {t('旧格式模板')}
  2800. </Text>
  2801. <Text
  2802. className='!text-semi-color-primary cursor-pointer'
  2803. onClick={() =>
  2804. handleInputChange(
  2805. 'param_override',
  2806. JSON.stringify(
  2807. {
  2808. operations: [
  2809. {
  2810. path: 'temperature',
  2811. mode: 'set',
  2812. value: 0.7,
  2813. conditions: [
  2814. {
  2815. path: 'model',
  2816. mode: 'prefix',
  2817. value: 'gpt',
  2818. },
  2819. ],
  2820. logic: 'AND',
  2821. },
  2822. ],
  2823. },
  2824. null,
  2825. 2,
  2826. ),
  2827. )
  2828. }
  2829. >
  2830. {t('新格式模板')}
  2831. </Text>
  2832. <Text
  2833. className='!text-semi-color-primary cursor-pointer'
  2834. onClick={() => formatJsonField('param_override')}
  2835. >
  2836. {t('格式化')}
  2837. </Text>
  2838. </div>
  2839. }
  2840. showClear
  2841. />
  2842. <Form.TextArea
  2843. field='header_override'
  2844. label={t('请求头覆盖')}
  2845. placeholder={
  2846. t('此项可选,用于覆盖请求头参数') +
  2847. '\n' +
  2848. t('格式示例:') +
  2849. '\n{\n "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0",\n "Authorization": "Bearer {api_key}"\n}'
  2850. }
  2851. autosize
  2852. onChange={(value) =>
  2853. handleInputChange('header_override', value)
  2854. }
  2855. extraText={
  2856. <div className='flex flex-col gap-1'>
  2857. <div className='flex gap-2 flex-wrap items-center'>
  2858. <Text
  2859. className='!text-semi-color-primary cursor-pointer'
  2860. onClick={() =>
  2861. handleInputChange(
  2862. 'header_override',
  2863. JSON.stringify(
  2864. {
  2865. 'User-Agent':
  2866. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
  2867. Authorization: 'Bearer{api_key}',
  2868. },
  2869. null,
  2870. 2,
  2871. ),
  2872. )
  2873. }
  2874. >
  2875. {t('填入模板')}
  2876. </Text>
  2877. <Text
  2878. className='!text-semi-color-primary cursor-pointer'
  2879. onClick={() => formatJsonField('header_override')}
  2880. >
  2881. {t('格式化')}
  2882. </Text>
  2883. </div>
  2884. <div>
  2885. <Text type='tertiary' size='small'>
  2886. {t('支持变量:')}
  2887. </Text>
  2888. <div className='text-xs text-tertiary ml-2'>
  2889. <div>
  2890. {t('渠道密钥')}: {'{api_key}'}
  2891. </div>
  2892. </div>
  2893. </div>
  2894. </div>
  2895. }
  2896. showClear
  2897. />
  2898. <JSONEditor
  2899. key={`status_code_mapping-${isEdit ? channelId : 'new'}`}
  2900. field='status_code_mapping'
  2901. label={t('状态码复写')}
  2902. placeholder={
  2903. t(
  2904. '此项可选,用于复写返回的状态码,仅影响本地判断,不修改返回到上游的状态码,比如将claude渠道的400错误复写为500(用于重试),请勿滥用该功能,例如:',
  2905. ) +
  2906. '\n' +
  2907. JSON.stringify(STATUS_CODE_MAPPING_EXAMPLE, null, 2)
  2908. }
  2909. value={inputs.status_code_mapping || ''}
  2910. onChange={(value) =>
  2911. handleInputChange('status_code_mapping', value)
  2912. }
  2913. template={STATUS_CODE_MAPPING_EXAMPLE}
  2914. templateLabel={t('填入模板')}
  2915. editorType='keyValue'
  2916. formApi={formApiRef.current}
  2917. extraText={t(
  2918. '键为原状态码,值为要复写的状态码,仅影响本地判断',
  2919. )}
  2920. />
  2921. {/* 字段透传控制 - OpenAI 渠道 */}
  2922. {inputs.type === 1 && (
  2923. <>
  2924. <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
  2925. {t('字段透传控制')}
  2926. </div>
  2927. <Form.Switch
  2928. field='allow_service_tier'
  2929. label={t('允许 service_tier 透传')}
  2930. checkedText={t('开')}
  2931. uncheckedText={t('关')}
  2932. onChange={(value) =>
  2933. handleChannelOtherSettingsChange(
  2934. 'allow_service_tier',
  2935. value,
  2936. )
  2937. }
  2938. extraText={t(
  2939. 'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
  2940. )}
  2941. />
  2942. <Form.Switch
  2943. field='disable_store'
  2944. label={t('禁用 store 透传')}
  2945. checkedText={t('开')}
  2946. uncheckedText={t('关')}
  2947. onChange={(value) =>
  2948. handleChannelOtherSettingsChange(
  2949. 'disable_store',
  2950. value,
  2951. )
  2952. }
  2953. extraText={t(
  2954. 'store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用',
  2955. )}
  2956. />
  2957. <Form.Switch
  2958. field='allow_safety_identifier'
  2959. label={t('允许 safety_identifier 透传')}
  2960. checkedText={t('开')}
  2961. uncheckedText={t('关')}
  2962. onChange={(value) =>
  2963. handleChannelOtherSettingsChange(
  2964. 'allow_safety_identifier',
  2965. value,
  2966. )
  2967. }
  2968. extraText={t(
  2969. 'safety_identifier 字段用于帮助 OpenAI 识别可能违反使用政策的应用程序用户。默认关闭以保护用户隐私',
  2970. )}
  2971. />
  2972. </>
  2973. )}
  2974. {/* 字段透传控制 - Claude 渠道 */}
  2975. {inputs.type === 14 && (
  2976. <>
  2977. <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
  2978. {t('字段透传控制')}
  2979. </div>
  2980. <Form.Switch
  2981. field='allow_service_tier'
  2982. label={t('允许 service_tier 透传')}
  2983. checkedText={t('开')}
  2984. uncheckedText={t('关')}
  2985. onChange={(value) =>
  2986. handleChannelOtherSettingsChange(
  2987. 'allow_service_tier',
  2988. value,
  2989. )
  2990. }
  2991. extraText={t(
  2992. 'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
  2993. )}
  2994. />
  2995. </>
  2996. )}
  2997. </Card>
  2998. </div>
  2999. {/* Channel Extra Settings Card */}
  3000. <div
  3001. ref={(el) =>
  3002. (formSectionRefs.current.channelExtraSettings = el)
  3003. }
  3004. >
  3005. <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
  3006. {/* Header: Channel Extra Settings */}
  3007. <div className='flex items-center mb-2'>
  3008. <Avatar
  3009. size='small'
  3010. color='violet'
  3011. className='mr-2 shadow-md'
  3012. >
  3013. <IconBolt size={16} />
  3014. </Avatar>
  3015. <div>
  3016. <Text className='text-lg font-medium'>
  3017. {t('渠道额外设置')}
  3018. </Text>
  3019. </div>
  3020. </div>
  3021. {inputs.type === 1 && (
  3022. <Form.Switch
  3023. field='force_format'
  3024. label={t('强制格式化')}
  3025. checkedText={t('开')}
  3026. uncheckedText={t('关')}
  3027. onChange={(value) =>
  3028. handleChannelSettingsChange('force_format', value)
  3029. }
  3030. extraText={t(
  3031. '强制将响应格式化为 OpenAI 标准格式(只适用于OpenAI渠道类型)',
  3032. )}
  3033. />
  3034. )}
  3035. <Form.Switch
  3036. field='thinking_to_content'
  3037. label={t('思考内容转换')}
  3038. checkedText={t('开')}
  3039. uncheckedText={t('关')}
  3040. onChange={(value) =>
  3041. handleChannelSettingsChange(
  3042. 'thinking_to_content',
  3043. value,
  3044. )
  3045. }
  3046. extraText={t(
  3047. '将 reasoning_content 转换为 <think> 标签拼接到内容中',
  3048. )}
  3049. />
  3050. <Form.Switch
  3051. field='pass_through_body_enabled'
  3052. label={t('透传请求体')}
  3053. checkedText={t('开')}
  3054. uncheckedText={t('关')}
  3055. onChange={(value) =>
  3056. handleChannelSettingsChange(
  3057. 'pass_through_body_enabled',
  3058. value,
  3059. )
  3060. }
  3061. extraText={t('启用请求体透传功能')}
  3062. />
  3063. <Form.Input
  3064. field='proxy'
  3065. label={t('代理地址')}
  3066. placeholder={t('例如: socks5://user:pass@host:port')}
  3067. onChange={(value) =>
  3068. handleChannelSettingsChange('proxy', value)
  3069. }
  3070. showClear
  3071. extraText={t('用于配置网络代理,支持 socks5 协议')}
  3072. />
  3073. <Form.TextArea
  3074. field='system_prompt'
  3075. label={t('系统提示词')}
  3076. placeholder={t(
  3077. '输入系统提示词,用户的系统提示词将优先于此设置',
  3078. )}
  3079. onChange={(value) =>
  3080. handleChannelSettingsChange('system_prompt', value)
  3081. }
  3082. autosize
  3083. showClear
  3084. extraText={t(
  3085. '用户优先:如果用户在请求中指定了系统提示词,将优先使用用户的设置',
  3086. )}
  3087. />
  3088. <Form.Switch
  3089. field='system_prompt_override'
  3090. label={t('系统提示词拼接')}
  3091. checkedText={t('开')}
  3092. uncheckedText={t('关')}
  3093. onChange={(value) =>
  3094. handleChannelSettingsChange(
  3095. 'system_prompt_override',
  3096. value,
  3097. )
  3098. }
  3099. extraText={t(
  3100. '如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
  3101. )}
  3102. />
  3103. </Card>
  3104. </div>
  3105. </div>
  3106. </Spin>
  3107. )}
  3108. </Form>
  3109. <ImagePreview
  3110. src={modalImageUrl}
  3111. visible={isModalOpenurl}
  3112. onVisibleChange={(visible) => setIsModalOpenurl(visible)}
  3113. />
  3114. </SideSheet>
  3115. {/* 使用通用安全验证模态框 */}
  3116. <SecureVerificationModal
  3117. visible={isModalVisible}
  3118. verificationMethods={verificationMethods}
  3119. verificationState={verificationState}
  3120. onVerify={executeVerification}
  3121. onCancel={cancelVerification}
  3122. onCodeChange={setVerificationCode}
  3123. onMethodSwitch={switchVerificationMethod}
  3124. title={verificationState.title}
  3125. description={verificationState.description}
  3126. />
  3127. {/* 使用ChannelKeyDisplay组件显示密钥 */}
  3128. <Modal
  3129. title={
  3130. <div className='flex items-center'>
  3131. <div className='w-8 h-8 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center mr-3'>
  3132. <svg
  3133. className='w-4 h-4 text-green-600 dark:text-green-400'
  3134. fill='currentColor'
  3135. viewBox='0 0 20 20'
  3136. >
  3137. <path
  3138. fillRule='evenodd'
  3139. d='M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z'
  3140. clipRule='evenodd'
  3141. />
  3142. </svg>
  3143. </div>
  3144. {t('渠道密钥信息')}
  3145. </div>
  3146. }
  3147. visible={keyDisplayState.showModal}
  3148. onCancel={resetKeyDisplayState}
  3149. footer={
  3150. <Button type='primary' onClick={resetKeyDisplayState}>
  3151. {t('完成')}
  3152. </Button>
  3153. }
  3154. width={700}
  3155. style={{ maxWidth: '90vw' }}
  3156. >
  3157. <ChannelKeyDisplay
  3158. keyData={keyDisplayState.keyData}
  3159. showSuccessIcon={true}
  3160. successText={t('密钥获取成功')}
  3161. showWarning={true}
  3162. warningText={t(
  3163. '请妥善保管密钥信息,不要泄露给他人。如有安全疑虑,请及时更换密钥。',
  3164. )}
  3165. />
  3166. </Modal>
  3167. <ModelSelectModal
  3168. visible={modelModalVisible}
  3169. models={fetchedModels}
  3170. selected={inputs.models}
  3171. redirectModels={redirectModelList}
  3172. onConfirm={(selectedModels) => {
  3173. handleInputChange('models', selectedModels);
  3174. showSuccess(t('模型列表已更新'));
  3175. setModelModalVisible(false);
  3176. }}
  3177. onCancel={() => setModelModalVisible(false)}
  3178. />
  3179. <OllamaModelModal
  3180. visible={ollamaModalVisible}
  3181. onCancel={() => setOllamaModalVisible(false)}
  3182. channelId={channelId}
  3183. channelInfo={inputs}
  3184. onModelsUpdate={(options = {}) => {
  3185. // 当模型更新后,重新获取模型列表以更新表单
  3186. fetchUpstreamModelList('models', { silent: !!options.silent });
  3187. }}
  3188. onApplyModels={({ mode, modelIds } = {}) => {
  3189. if (!Array.isArray(modelIds) || modelIds.length === 0) {
  3190. return;
  3191. }
  3192. const existingModels = Array.isArray(inputs.models)
  3193. ? inputs.models.map(String)
  3194. : [];
  3195. const incoming = modelIds.map(String);
  3196. const nextModels = Array.from(
  3197. new Set([...existingModels, ...incoming]),
  3198. );
  3199. handleInputChange('models', nextModels);
  3200. if (formApiRef.current) {
  3201. formApiRef.current.setValue('models', nextModels);
  3202. }
  3203. showSuccess(t('模型列表已追加更新'));
  3204. }}
  3205. />
  3206. </>
  3207. );
  3208. };
  3209. export default EditChannelModal;