import { App, Button, Form, Input, InputNumber, Popconfirm, Select, Tag, Tooltip } from "antd"; import { ArrowLeft, Boxes, CircleCheck, Cloud, Info, Plus, RadioTower, RefreshCw, SlidersHorizontal, Trash2 } from "lucide-react"; import { useEffect, useState, type ReactNode } from "react"; import { useNavigate, useSearchParams } from "react-router"; import { UserOSSSettingsForm } from "@/components/layout/user-oss-settings-form"; import { WorkspaceState } from "@/components/layout/workspace-state"; import { WorkspaceSignalIcon } from "@/components/ui/aceternity/workspace-signal-icon"; import { refreshSystemChannels } from "@/lib/user-session"; import { MODEL_PROTOCOL_OPTIONS, modelProtocolLabel } from "@/lib/model-protocols"; import { fetchChannelModels } from "@/services/api/image"; import { audioFormatOptions, audioVoiceOptions, normalizeAudioSpeedValue } from "@/lib/audio-generation"; import { createModelChannel, defaultBaseUrlForApiFormat, defaultBaseUrlForChannelInterface, defaultConfig, filterModelsByCapability, modelOptionsFromChannels, useConfigStore, type AiConfig, type ChannelInterfaceType, type ModelChannel, } from "@/stores/use-config-store"; import { useUserStore } from "@/stores/use-user-store"; import { ChannelModelSettings } from "./channel-video-pricing"; import { ModelDefaultGrid } from "./model-default-grid"; type ConfigSectionKey = "channels" | "models" | "preferences" | "storage"; const configSections: Array<{ key: ConfigSectionKey; label: string; description: string; icon: ReactNode }> = [ { key: "channels", label: "自定义渠道", description: "连接你自己的模型服务", icon: }, { key: "models", label: "模型选择", description: "按领域选择默认模型", icon: }, { key: "preferences", label: "生成偏好", description: "画布、音频与系统提示词", icon: }, { key: "storage", label: "我的 OSS", description: "管理个人媒体存储", icon: }, ]; type UserChannelProtocol = ChannelInterfaceType | "auto" | "gemini"; const channelProtocolOptions = [ { label: "OpenAI 自动兼容", value: "auto" }, { label: "Google Gemini(模型级选择)", value: "gemini" }, ...MODEL_PROTOCOL_OPTIONS, ]; function isConfigSection(value: string | null): value is ConfigSectionKey { return configSections.some((section) => section.key === value); } export default function SettingsPage() { const { message } = App.useApp(); const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); const requestedSection = searchParams.get("section"); const [activeTab, setActiveTab] = useState(isConfigSection(requestedSection) ? requestedSection : "channels"); const [loadingChannelIds, setLoadingChannelIds] = useState([]); const config = useConfigStore((state) => state.config); const updateConfig = useConfigStore((state) => state.updateConfig); const replaceConfig = useConfigStore((state) => state.replaceConfig); const shouldPromptContinue = searchParams.get("continue") === "1"; const userId = useUserStore((state) => state.user?.id); const userChannels = config.channels.filter((channel) => channel.scope !== "system"); useEffect(() => { if (isConfigSection(requestedSection)) setActiveTab(requestedSection); }, [requestedSection]); useEffect(() => { if (!userId) return; let cancelled = false; void refreshSystemChannels().catch((error) => { if (!cancelled) message.warning(error instanceof Error ? `系统模型刷新失败:${error.message}` : "系统模型刷新失败,继续使用本地缓存"); }); return () => { cancelled = true; }; }, [message, userId]); const selectSection = (section: ConfigSectionKey) => { setActiveTab(section); const next = new URLSearchParams(searchParams); next.set("section", section); setSearchParams(next, { replace: true }); }; const finishConfig = () => { const invalidChannel = userChannels.find((channel) => channelValidationError(channel)); if (invalidChannel) { selectSection("channels"); message.warning(`${invalidChannel.name || "未命名渠道"}:${channelValidationError(invalidChannel)}`); focusInvalidChannelField(invalidChannel); return; } const ready = config.channels.some(isChannelReady); if (!ready) { selectSection("channels"); message.error(shouldPromptContinue ? "请先完成至少一个渠道的 Base URL、API Key 和模型配置" : "当前没有可用渠道,请先完成连接信息和模型配置"); return; } message.success("配置已保存,正在返回创作页面"); navigate(-1); }; const updateChannels = (channels: ModelChannel[], baseConfig = config) => { replaceConfig(withChannels(baseConfig, channels)); }; const updateChannel = (id: string, patch: Partial) => { updateChannels(config.channels.map((channel) => { if (channel.id !== id) return channel; const models = patch.models ? uniqueModels(patch.models) : channel.models; return { ...channel, ...patch, models, modelCosts: patch.modelCosts !== undefined ? patch.modelCosts : (patch.models ? channel.modelCosts?.filter((item) => models.includes(item.model)) : channel.modelCosts), }; })); }; const updateChannelProtocol = (channel: ModelChannel, protocol: UserChannelProtocol) => { const apiFormat = protocol === "gemini" || protocol === "gemini-veo" ? "gemini" : "openai"; const interfaceType = protocol === "auto" || protocol === "gemini" ? undefined : protocol; const defaultBaseUrl = protocol === "gemini" ? defaultBaseUrlForApiFormat("gemini") : defaultBaseUrlForChannelInterface(interfaceType); const baseUrl = isKnownDefaultBaseUrl(channel.baseUrl) ? defaultBaseUrl : channel.baseUrl; updateChannel(channel.id, { apiFormat, interfaceType, baseUrl }); }; const addChannel = () => { const channel = createModelChannel({ name: `渠道 ${userChannels.length + 1}` }); updateChannels([...config.channels, channel]); requestAnimationFrame(() => document.getElementById(`channel-${channel.id}-name`)?.focus()); }; const deleteChannel = (id: string) => { const channel = config.channels.find((item) => item.id === id); if (channel?.scope === "system") { message.warning("系统渠道由管理员维护"); return; } updateChannels(config.channels.filter((item) => item.id !== id)); }; const setChannelLoading = (id: string, loading: boolean) => { setLoadingChannelIds((items) => (loading ? Array.from(new Set([...items, id])) : items.filter((item) => item !== id))); }; const refreshChannelModels = async (channel: ModelChannel) => { const connectionError = channelConnectionError(channel); if (connectionError) { message.error(`${channel.name || "当前渠道"}:${connectionError}`); return; } setChannelLoading(channel.id, true); try { const models = await fetchChannelModels(channel, true); if (!models.length) { message.warning(`${channel.name || "当前渠道"}未返回模型,已保留现有手工模型`); return; } const latestConfig = useConfigStore.getState().config; const latestChannel = latestConfig.channels.find((item) => item.id === channel.id); if (!latestChannel) return; if (channelConnectionSignature(latestChannel) !== channelConnectionSignature(channel)) { message.warning(`${latestChannel.name || "当前渠道"}的连接配置已改变,已忽略旧的拉取结果`); return; } updateChannels( latestConfig.channels.map((item) => (item.id === channel.id ? { ...item, models } : item)), latestConfig, ); message.success(`${latestChannel.name || "当前渠道"}模型列表已更新`); } catch (error) { message.error(error instanceof Error ? `${error.message};也可以直接在模型列表中手动输入模型名` : "读取模型失败,可直接手动输入模型名"); } finally { setChannelLoading(channel.id, false); } }; const refreshAllModels = async () => { const runnable = userChannels.filter((channel) => !channelConnectionError(channel)); const skipped = userChannels.filter((channel) => channelConnectionError(channel)); if (!runnable.length) { const detail = skipped.map((channel) => `${channel.name || "未命名渠道"}:${channelConnectionError(channel)}`).join(";"); message.error(detail || "没有可拉取的自定义渠道,请先填写有效 Base URL 和 API Key"); return; } setChannelLoading("all", true); try { const results = await Promise.all( runnable.map(async (channel) => { try { const models = await fetchChannelModels(channel, true); return { channel, models, error: "" }; } catch (error) { return { channel, models: [] as string[], error: error instanceof Error ? error.message : "读取失败" }; } }), ); const latestConfig = useConfigStore.getState().config; const successful = results.filter((item) => { const latestChannel = latestConfig.channels.find((channel) => channel.id === item.channel.id); return Boolean(item.models.length && latestChannel && channelConnectionSignature(latestChannel) === channelConnectionSignature(item.channel)); }); const stale = results.filter((item) => { const latestChannel = latestConfig.channels.find((channel) => channel.id === item.channel.id); return Boolean(item.models.length && (!latestChannel || channelConnectionSignature(latestChannel) !== channelConnectionSignature(item.channel))); }); const failed = results.filter((item) => !item.models.length); if (successful.length) { const modelMap = new Map(successful.map((item) => [item.channel.id, item.models] as const)); updateChannels( latestConfig.channels.map((channel) => (modelMap.has(channel.id) ? { ...channel, models: modelMap.get(channel.id) || channel.models } : channel)), latestConfig, ); message.success(`已更新 ${successful.length} 个渠道的模型`); } const warnings = [ ...failed.map((item) => `${item.channel.name || "未命名渠道"}:${item.error || "未返回模型"}`), ...stale.map((item) => `${item.channel.name || "未命名渠道"}:连接配置已改变,已忽略旧结果`), ...skipped.map((channel) => `${channel.name || "未命名渠道"}:${channelConnectionError(channel)}`), ]; if (warnings.length) { message.warning(`${warnings.join(";")}。未更新的渠道已保留原有模型列表`); } } catch (error) { message.error(error instanceof Error ? error.message : "批量读取模型失败,原有模型列表未改动"); } finally { setChannelLoading("all", false); } }; return ( {shouldPromptContinue ? ( navigate(-1)} aria-label="返回创作页面" title="返回创作页面"> ) : null} 配置与用户偏好 模型连接、生成默认值与个人媒体存储 {shouldPromptContinue ? 保存并返回创作 : null} {([ { key: "channels", label: "渠道", children: ( 渠道保存连接和默认协议;拉取模型后,请为需要特殊路径的模型单独选择请求协议。 selectSection("models")}> 打开模型选择 } loading={loadingChannelIds.includes("all")} disabled={loadingChannelIds.some((id) => id !== "all")} onClick={() => void refreshAllModels()} > 拉取全部 } onClick={addChannel}> 新增渠道 {userChannels.length ? ( {userChannels.map((channel) => ( {channel.name || "未命名渠道"} {channelProtocolLabel(channel)} · 已保存 {channel.models.length} 个模型 } loading={loadingChannelIds.includes(channel.id)} disabled={loadingChannelIds.includes("all")} onClick={() => void refreshChannelModels(channel)} > 拉取模型 deleteChannel(channel.id)}> } /> updateChannel(channel.id, { name: event.target.value })} onBlur={(event) => updateChannel(channel.id, { name: event.target.value.trim() || "未命名渠道" })} /> id={`channel-${channel.id}-protocol`} value={channelProtocolValue(channel)} options={channelProtocolOptions} onChange={(value) => updateChannelProtocol(channel, value)} /> updateChannel(channel.id, { baseUrl: event.target.value })} onBlur={(event) => updateChannel(channel.id, { baseUrl: event.target.value.trim().replace(/\/+$/, "") })} /> updateChannel(channel.id, { apiKey: event.target.value })} onBlur={(event) => updateChannel(channel.id, { apiKey: event.target.value.trim() })} /> updateChannel(channel.id, { models: uniqueModels(models) })} /> updateChannel(channel.id, { modelCosts })} /> ))} ) : ( } onClick={addChannel}>新增自定义渠道} /> )} ), }, { key: "models", label: "模型", children: ( updateConfig(key, model)} /> ), }, { key: "preferences", label: "生成偏好", children: ( 画布生成设置新建生成任务时使用的初始值,节点内仍可单独覆盖。 updateConfig("canvasImageCount", normalizeImageCount(String(value ?? defaultConfig.canvasImageCount)))} /> 音频默认值用于新建音频节点和未单独设置参数的生成任务。 updateConfig("audioVoice", value)} /> updateConfig("audioFormat", value)} /> updateConfig("audioSpeed", normalizeAudioSpeedValue(String(value ?? defaultConfig.audioSpeed)))} /> 默认指令在未单独填写时附加到对应生成请求。 updateConfig("audioInstructions", event.target.value)} /> updateConfig("systemPrompt", event.target.value)} /> ), }, { key: "storage", label: ( 我的 OSS ), children: ( ), }, ] as Array<{ key: ConfigSectionKey; label: ReactNode; children: ReactNode }>).find((item) => item.key === activeTab)?.children} ); } function SettingsPane({ children }: { children: ReactNode }) { return {children}; } function ChannelStatus({ channel }: { channel: ModelChannel }) { const error = channelValidationError(channel); return error ? ( {error} ) : ( } className="m-0"> 可用 ); } function withChannels(config: AiConfig, channels: ModelChannel[]): AiConfig { const models = modelOptionsFromChannels(channels); const imageModels = filterModelsByCapability(models, "image", channels); const videoModels = filterModelsByCapability(models, "video", channels); const textModels = filterModelsByCapability(models, "text", channels); const audioModels = filterModelsByCapability(models, "audio", channels); return { ...config, channels, models, baseUrl: channels[0]?.baseUrl || config.baseUrl, apiKey: channels[0]?.apiKey || config.apiKey, apiFormat: channels[0]?.apiFormat || config.apiFormat, imageModels, videoModels, textModels, audioModels, imageModel: normalizeDefaultModel(config.imageModel, imageModels), videoModel: normalizeDefaultModel(config.videoModel, videoModels), textModel: normalizeDefaultModel(config.textModel, textModels), audioModel: normalizeDefaultModel(config.audioModel, audioModels), }; } function normalizeDefaultModel(value: string, options: string[]) { if (options.includes(value)) return value; return options[0] || ""; } function normalizeImageCount(value: string) { return String(Math.max(1, Math.min(15, Math.floor(Math.abs(Number(value)) || Number(defaultConfig.canvasImageCount))))); } function uniqueModels(models: string[]) { return Array.from(new Set(models.map((model) => model.trim()).filter(Boolean))); } function channelProtocolValue(channel: ModelChannel): UserChannelProtocol { if (channel.apiFormat === "gemini") return "gemini"; return channel.interfaceType || "auto"; } function channelConnectionError(channel: ModelChannel) { const baseUrl = channel.baseUrl.trim(); if (!baseUrl) return "请填写 Base URL"; try { const parsed = new URL(baseUrl); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "Base URL 只支持 HTTP 或 HTTPS"; } catch { return "Base URL 格式不正确"; } if (!channel.apiKey.trim()) return "请填写 API Key"; return ""; } function channelConnectionSignature(channel: ModelChannel) { return [channel.baseUrl.trim(), channel.apiKey.trim(), channel.apiFormat, channel.interfaceType || "auto"].join("\n"); } function channelValidationError(channel: ModelChannel) { return channelConnectionError(channel) || (!channel.models.length ? "请添加至少一个模型" : ""); } function isChannelReady(channel: ModelChannel) { return !channelValidationError(channel); } function focusInvalidChannelField(channel: ModelChannel) { const baseUrlError = channelConnectionError({ ...channel, apiKey: "valid" }); const field = baseUrlError ? "base-url" : !channel.apiKey.trim() ? "api-key" : "models"; requestAnimationFrame(() => { const element = document.getElementById(`channel-${channel.id}-${field}`); element?.scrollIntoView({ behavior: "smooth", block: "center" }); element?.focus({ preventScroll: true }); }); } function channelProtocolLabel(channel: ModelChannel) { const protocol = channelProtocolValue(channel); switch (protocol) { case "gemini": return "Gemini 原生"; case "chat-completion": return "Chat Completions"; case "openai-response": return "OpenAI Responses"; case "openai-image": return "OpenAI Images"; default: return protocol === "auto" ? "OpenAI 自动兼容" : modelProtocolLabel(protocol); } } function isKnownDefaultBaseUrl(value: string) { const normalized = value.trim().replace(/\/+$/, ""); if (!normalized) return true; return [defaultBaseUrlForApiFormat("openai"), defaultBaseUrlForApiFormat("gemini")].some((candidate) => candidate.replace(/\/+$/, "") === normalized); }
模型连接、生成默认值与个人媒体存储
设置新建生成任务时使用的初始值,节点内仍可单独覆盖。
用于新建音频节点和未单独设置参数的生成任务。
在未单独填写时附加到对应生成请求。