diff --git a/internal/handler/config.go b/internal/handler/config.go index fe943610..fcc73b25 100644 --- a/internal/handler/config.go +++ b/internal/handler/config.go @@ -730,6 +730,7 @@ type UpdateConfigRequest struct { Proxy *config.ProxyConfig `json:"proxy,omitempty"` AgentRuntime *AgentRuntimeUpdate `json:"agent_runtime,omitempty"` AI *config.AIConfig `json:"ai,omitempty"` + AIChannel *AIChannelUpdate `json:"ai_channel,omitempty"` OpenAI *config.OpenAIConfig `json:"openai,omitempty"` Vision *config.VisionConfig `json:"vision,omitempty"` FOFA *config.FofaConfig `json:"fofa,omitempty"` @@ -808,6 +809,19 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) { h.mu.Lock() defer h.mu.Unlock() + channelUpdate := req.AIChannel != nil + if channelUpdate { + if req.AI != nil || req.OpenAI != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "ai_channel 不能与 ai 或 openai 同时更新"}) + return + } + ai, err := req.AIChannel.merge(h.config) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + req.AI, req.AIChannel = ai, nil + } if err := restoreConfigRequestSecrets(&req, h.config); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return @@ -829,11 +843,15 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) { previousProxy := h.config.Proxy previousRuntime := h.config.AgentRuntime - proxySaved := false + previousAI, previousOpenAI := h.config.AI, h.config.OpenAI + saved := false defer func() { - if !proxySaved { + if !saved { h.config.Proxy = previousProxy h.config.AgentRuntime = previousRuntime + if channelUpdate { + h.config.AI, h.config.OpenAI = previousAI, previousOpenAI + } } }() if req.Proxy != nil { @@ -1281,7 +1299,7 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) { return } - proxySaved = true + saved = true if req.Proxy != nil && h.executor != nil { h.executor.SetProxyConfig(h.config.Proxy) } @@ -2110,7 +2128,9 @@ func (h *ConfigHandler) saveConfig() error { updateAgentConfig(root, h.config.Agent) updateAgentRuntimeConfig(root, h.config.AgentRuntime) updateMCPConfig(root, h.config.MCP) - updateAIConfig(root, h.config.AI) + if err := updateAIConfig(root, h.config.AI); err != nil { + return err + } removeKeyFromMap(root.Content[0], "openai") updateVisionConfig(root, h.config.Vision) updateUpdateSourceConfig(root, h.config.Update) @@ -2332,7 +2352,7 @@ func updateOpenAIConfig(doc *yaml.Node, cfg config.OpenAIConfig) { } } -func updateAIConfig(doc *yaml.Node, cfg config.AIConfig) { +func updateAIConfig(doc *yaml.Node, cfg config.AIConfig) error { root := doc.Content[0] aiNode := ensureMap(root, "ai") if strings.TrimSpace(cfg.DefaultChannel) != "" { @@ -2400,10 +2420,17 @@ func updateAIConfig(doc *yaml.Node, cfg config.AIConfig) { if strings.TrimSpace(ch.Reasoning.Profile) != "" { setStringInMap(rn, "profile", ch.Reasoning.Profile) } + if len(ch.Reasoning.ExtraRequestFields) > 0 { + _, value := ensureKeyValue(rn, "extra_request_fields") + if err := value.Encode(ch.Reasoning.ExtraRequestFields); err != nil { + return fmt.Errorf("保存 AI 通道 %s 的扩展请求字段失败: %w", id, err) + } + } if len(rn.Content) == 0 { removeKeyFromMap(channelNode, "reasoning") } } + return nil } func updateFOFAConfig(doc *yaml.Node, cfg config.FofaConfig) { diff --git a/internal/handler/config_ai_channel.go b/internal/handler/config_ai_channel.go new file mode 100644 index 00000000..eb8b4e4a --- /dev/null +++ b/internal/handler/config_ai_channel.go @@ -0,0 +1,72 @@ +package handler + +import ( + "fmt" + "maps" + "strings" + + "cyberstrike-ai/internal/config" +) + +// AIChannelUpdate edits an existing channel without replacing the channel map. +// An empty ID selects the legacy openai configuration when there are no channels. +type AIChannelUpdate struct { + ChannelID string `json:"channel_id"` + MakeDefault bool `json:"make_default,omitempty"` + Name *string `json:"name,omitempty"` + Provider *string `json:"provider,omitempty"` + BaseURL *string `json:"base_url,omitempty"` + APIKey *string `json:"api_key,omitempty"` + Model *string `json:"model,omitempty"` + ContextProfile *string `json:"context_profile,omitempty"` + ContextWindow *int `json:"context_window,omitempty"` + MaxTotalTokens *int `json:"max_total_tokens,omitempty"` + MaxCompletionTokens *int `json:"max_completion_tokens,omitempty"` +} + +func (u AIChannelUpdate) merge(cfg *config.Config) (*config.AIConfig, error) { + ai := cfg.AI + ai.Channels = maps.Clone(ai.Channels) + id := strings.TrimSpace(u.ChannelID) + if id == "" && len(ai.Channels) == 0 { + ai.EnsureDefaultFromOpenAI(cfg.OpenAI) + id = ai.DefaultChannel + } + ch, ok := ai.Channels[id] + if !ok || id == "" { + return nil, fmt.Errorf("通道已不存在,请刷新配置后重试") + } + + for _, field := range []struct{ target, value *string }{ + {&ch.Name, u.Name}, + {&ch.Provider, u.Provider}, + {&ch.BaseURL, u.BaseURL}, + {&ch.APIKey, u.APIKey}, + {&ch.Model, u.Model}, + {&ch.ContextProfile, u.ContextProfile}, + } { + if field.value != nil { + *field.target = strings.TrimSpace(*field.value) + } + } + for _, field := range []struct { + name string + target, value *int + }{ + {"context_window", &ch.ContextWindow, u.ContextWindow}, + {"max_total_tokens", &ch.MaxTotalTokens, u.MaxTotalTokens}, + {"max_completion_tokens", &ch.MaxCompletionTokens, u.MaxCompletionTokens}, + } { + if field.value != nil { + if *field.value < 0 { + return nil, fmt.Errorf("%s 不能为负数", field.name) + } + *field.target = *field.value + } + } + if u.MakeDefault { + ai.DefaultChannel = id + } + ai.Channels[id] = ch + return &ai, nil +} diff --git a/internal/handler/config_ai_channel_test.go b/internal/handler/config_ai_channel_test.go new file mode 100644 index 00000000..8c7b5007 --- /dev/null +++ b/internal/handler/config_ai_channel_test.go @@ -0,0 +1,90 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "cyberstrike-ai/internal/config" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func TestUpdateConfigEditsOneAIChannel(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "config.yaml") + initial := `ai: + default_channel: primary + channels: + primary: + name: Primary + model: model-one + api_key: fixture-primary + secondary: + name: Secondary + model: model-two + api_key: fixture-secondary + headers: + X-Gateway-Token: fixture-header + reasoning: + extra_request_fields: + example_option: true +` + if err := os.WriteFile(path, []byte(initial), 0600); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(path) + if err != nil { + t.Fatal(err) + } + h := &ConfigHandler{configPath: path, config: cfg, logger: zap.NewNop()} + router := gin.New() + router.PUT("/config", h.UpdateConfig) + update := func(body string, status int) { + t.Helper() + req := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + res := httptest.NewRecorder() + router.ServeHTTP(res, req) + if res.Code != status { + t.Fatalf("status = %d, want %d: %s", res.Code, status, res.Body.String()) + } + } + + update(`{"ai_channel":{"channel_id":"secondary","name":"Local","model":"manual-model","context_window":65536}}`, http.StatusOK) + if cfg.AI.DefaultChannel != "primary" || cfg.OpenAI.Model != "model-one" { + t.Fatal("editing another channel changed the default") + } + update(`{"ai_channel":{"channel_id":"primary","model":"updated-primary"}}`, http.StatusOK) + update(`{"ai_channel":{"channel_id":"secondary","make_default":true,"api_key":"********"}}`, http.StatusOK) + update(`{"ai_channel":{"channel_id":"secondary","max_total_tokens":-1}}`, http.StatusBadRequest) + update(`{"ai_channel":{"channel_id":"missing","model":"unused"}}`, http.StatusBadRequest) + + saved, err := config.Load(path) + if err != nil { + t.Fatal(err) + } + secondary := saved.AI.Channels["secondary"] + if saved.AI.DefaultChannel != "secondary" || saved.OpenAI.Model != "manual-model" || secondary.Name != "Local" || secondary.ContextWindow != 65536 { + t.Fatal("selected channel edits or new default did not survive reload") + } + if saved.OpenAI.APIKey != "fixture-secondary" || secondary.Headers["X-Gateway-Token"] != "fixture-header" || + secondary.Reasoning.ExtraRequestFields["example_option"] != true { + t.Fatal("editing the channel dropped its saved configuration") + } + if primary := saved.AI.Channels["primary"]; primary.Model != "updated-primary" || primary.APIKey != "fixture-primary" { + t.Fatal("editing the other channel overwrote primary") + } + if len(saved.AI.Channels) != 2 { + t.Fatal("editing channels changed the number of channels") + } + + h.configPath = filepath.Join(t.TempDir(), "missing.yaml") + update(`{"ai_channel":{"channel_id":"secondary","model":"unsaved-model"}}`, http.StatusInternalServerError) + if cfg.OpenAI.Model != "manual-model" || cfg.AI.Channels["secondary"].Model != "manual-model" { + t.Fatal("a failed save left the edited model in memory") + } +} diff --git a/internal/handler/config_context_test.go b/internal/handler/config_context_test.go index 79fb0d6d..8c07a151 100644 --- a/internal/handler/config_context_test.go +++ b/internal/handler/config_context_test.go @@ -20,7 +20,9 @@ func TestDetectedContextSettingsRoundTripThroughSavedYAML(t *testing.T) { } for _, profile := range []string{"local_auto", "custom", ""} { ch := config.AIChannelConfig{Model: "fixture", ContextWindow: 32768, ContextProfile: profile} - updateAIConfig(&doc, config.AIConfig{DefaultChannel: "local", Channels: map[string]config.AIChannelConfig{"local": ch}}) + if err := updateAIConfig(&doc, config.AIConfig{DefaultChannel: "local", Channels: map[string]config.AIChannelConfig{"local": ch}}); err != nil { + t.Fatal(err) + } raw, err := yaml.Marshal(&doc) if err != nil { t.Fatal(err) diff --git a/web/frontend/src/pages/settings/page.css b/web/frontend/src/pages/settings/page.css index 96a885a5..3852e0f6 100644 --- a/web/frontend/src/pages/settings/page.css +++ b/web/frontend/src/pages/settings/page.css @@ -63,6 +63,8 @@ .settings-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; } .settings-field-wide { grid-column: span 2; } .settings-probe-actions { margin-top: 14px; } +.settings-channel-panel .semi-card-header-wrapper { align-items: center; gap: 8px; } +.settings-channel-notices { display: grid; gap: 8px; margin-top: 14px; } .settings-probe-result { margin-top: 12px; display: flex; flex-direction: column; gap: 10px; } .settings-model-tags { display: flex; @@ -122,6 +124,12 @@ .settings-yaml-input .semi-input-textarea { min-height: 300px; } } +@media (max-width: 480px) { + .settings-channel-panel .semi-card-header-wrapper { flex-direction: column-reverse; align-items: stretch; } + .settings-channel-panel .semi-card-header-wrapper-title { margin-inline: 0; } + .settings-probe-secondary { grid-template-columns: minmax(0, 1fr); } +} + .settings-update-source-form { display: flex; flex-direction: column; diff --git a/web/frontend/src/pages/settings/sections/ModelsSection.jsx b/web/frontend/src/pages/settings/sections/ModelsSection.jsx index b1407d90..20719b9c 100644 --- a/web/frontend/src/pages/settings/sections/ModelsSection.jsx +++ b/web/frontend/src/pages/settings/sections/ModelsSection.jsx @@ -1,4 +1,4 @@ -/** 模型与工具:模型连接探测(ProbePanel)+ 工具开关(ToolsPanel)。 */ +/** 模型与工具:通道配置、模型连接探测和工具开关。 */ import { useCallback } from 'react'; import { api } from '../../../lib/http'; import { useAuth } from '../../../lib/auth'; @@ -25,7 +25,13 @@ export default function ModelsSection() { {config.loading && !config.data ? : ( <> - {config.data && } + {config.data && ( + + )} )} diff --git a/web/frontend/src/pages/settings/sections/ProbePanel.jsx b/web/frontend/src/pages/settings/sections/ProbePanel.jsx index b76d06d2..5ae390e9 100644 --- a/web/frontend/src/pages/settings/sections/ProbePanel.jsx +++ b/web/frontend/src/pages/settings/sections/ProbePanel.jsx @@ -1,13 +1,11 @@ /** - * 模型连接与能力探测:/config/test-openai、/config/detect-context、/config/list-models、 - * /config/test-vision、/config/test-typesafe。密钥字段来自 GET /config,服务端用 ******** - * 作为「沿用已保存凭据」的标记。 + * 编辑所选模型通道,并使用表单中的值测试连接或探测模型能力。 */ -import { useEffect, useMemo, useState } from 'react'; +import { useId, useState } from 'react'; import { Banner, Button, Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui'; import { api } from '../../../lib/http'; import { useT } from '../../../lib/i18n'; -import { ErrorBanner, KeyValueList, SectionCard } from '../../../components/ui'; +import { ErrorBanner, KeyValueList, SectionCard, toastSuccess } from '../../../components/ui'; import { Hint } from './common'; const { Text } = Typography; @@ -18,7 +16,13 @@ const PROVIDERS = [ { value: 'openai_compatible', key: 'settingsProbe.compatible', fallback: '兼容 OpenAI 的接口' }, { value: 'claude', key: 'settingsBasic.providerClaude', fallback: 'Claude(Anthropic Messages)' } ]; -const CONTEXT_PROFILES = ['', 'auto', 'local_auto', 'custom']; +const CONTEXT_PROFILES = ['', 'auto', 'local_auto', 'local', 'economy', 'custom']; +const TOKEN_LIMITS = [ + ['context_window', 'settingsBasic.contextWindow', '模型上下文窗口(Token)'], + ['max_total_tokens', 'settingsBasic.maxTotalTokens', '最大上下文令牌数'], + ['max_completion_tokens', 'settingsBasic.maxCompletionTokens', '最大输出令牌数'] +]; +const EMPTY_PROBE = { key: '', payload: null, error: null }; const CONTEXT_WARNING_KEYS = { context_window_unknown: 'contextWarnUnknown', context_runtime_unknown: 'contextWarnRuntimeUnknown', @@ -38,31 +42,22 @@ function profileLabel(t, value) { } function numberValue(raw) { - const value = parseInt(raw, 10); - return Number.isFinite(value) && value > 0 ? value : 0; + const value = Number(raw); + return Number.isSafeInteger(value) && value >= 0 ? value : 0; } -function channelValues(config, id) { - if (id === MAIN_CHANNEL) { - const main = config.openai || {}; - return { - provider: main.provider || 'openai_compatible', - base_url: main.base_url || '', - api_key: main.api_key || '', - model: main.model || '', - context_profile: main.context_profile || '', - max_total_tokens: main.max_total_tokens || 0, - max_completion_tokens: main.max_completion_tokens || 0, - headers: main.headers || undefined - }; - } - const channel = config.ai?.channels?.[id] || {}; +function channelValues(channel) { + let provider = channel.provider || 'openai_compatible'; + if (provider === 'openai') provider = 'openai_compatible'; + if (provider === 'anthropic') provider = 'claude'; return { - provider: channel.provider || 'openai_compatible', + name: channel.name || '', + provider, base_url: channel.base_url || '', api_key: channel.api_key || '', model: channel.model || '', context_profile: channel.context_profile || '', + context_window: channel.context_window || 0, max_total_tokens: channel.max_total_tokens || 0, max_completion_tokens: channel.max_completion_tokens || 0, headers: channel.headers || undefined @@ -179,32 +174,121 @@ function ProbeOutput({ state }) { ); } -export default function ProbePanel({ config, canWrite }) { +export default function ProbePanel({ config, canWrite, reloadConfig }) { const t = useT(); + const channelLabelId = useId(); const channels = config.ai?.channels || NO_CHANNELS; - const [channelId, setChannelId] = useState(() => config.ai?.default_channel || MAIN_CHANNEL); - const [form, setForm] = useState(() => channelValues(config, config.ai?.default_channel || MAIN_CHANNEL)); + const channelIds = Object.keys(channels); + const defaultId = config.ai?.default_channel; + const [selectedId, setSelectedId] = useState(''); + const channelId = [selectedId, defaultId].find(id => Object.hasOwn(channels, id)) || channelIds[0] || MAIN_CHANNEL; + const legacy = channelId === MAIN_CHANNEL; + const baseline = channelValues((legacy ? config.openai : channels[channelId]) || {}); + const [drafts, setDrafts] = useState({}); + const draft = drafts[channelId] || {}; + const form = { ...baseline, ...draft }; + const dirty = Object.keys(draft).length > 0; const [busy, setBusy] = useState(''); - const [state, setState] = useState({ key: '', payload: null, error: null }); - - useEffect(() => { - setForm(channelValues(config, channelId)); - }, [channelId, config]); - - const channelOptions = useMemo(() => [ - { value: MAIN_CHANNEL, label: t('settingsProbe.mainChannel', null, '主模型通道') }, - ...Object.keys(channels).map(id => ({ + const [state, setState] = useState(EMPTY_PROBE); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(null); + const [applyPending, setApplyPending] = useState(false); + const locked = !canWrite || saving; + const channelOptions = legacy + ? [{ value: MAIN_CHANNEL, label: t('settingsProbe.mainChannel', null, '主模型通道') }] + : channelIds.map(id => ({ value: id, - label: `${id}${id === config.ai?.default_channel ? t('settingsProbe.defaultChannelSuffix', null, '(默认)') : ''}` - })) - ], [channels, config.ai?.default_channel, t]); + label: (channels[id].name && channels[id].name !== id ? `${channels[id].name} · ${id}` : id) + + (id === defaultId ? t('settingsProbe.defaultChannelSuffix', null, '(默认)') : '') + })); + const providerOptions = PROVIDERS.map(({ value, key, fallback }) => ({ value, label: t(key, null, fallback) })); + if (!providerOptions.some(option => option.value === form.provider)) { + providerOptions.push({ value: form.provider, label: form.provider }); + } - const update = (key, value) => setForm(current => ({ ...current, [key]: value })); + const clearDraft = () => { + setDrafts(current => { + const next = { ...current }; + delete next[channelId]; + return next; + }); + }; + const update = (key, value) => { + setDrafts(current => { + const next = { ...current[channelId] }; + if (value === String(baseline[key])) delete next[key]; + else next[key] = value; + return { ...current, [channelId]: next }; + }); + }; + const selectChannel = id => { + setSelectedId(id); + setState(EMPTY_PROBE); + if (!applyPending) setSaveError(null); + }; + + const discardDraft = () => { + clearDraft(); + setState(EMPTY_PROBE); + if (!applyPending) setSaveError(null); + }; + + const apply = async message => { + try { + await api.post('/config/apply'); + setApplyPending(false); + toastSuccess(message); + } catch (error) { + setApplyPending(true); + setSaveError(error); + } + }; + + const save = async (makeDefault = false) => { + if (locked || busy || (!dirty && !makeDefault)) return; + setSaveError(null); + const invalidLimit = TOKEN_LIMITS.find(([key]) => !/^\d*$/.test(String(form[key]).trim()) + || !Number.isSafeInteger(Number(form[key]))); + if (invalidLimit) { + const [, key, fallback] = invalidLimit; + setSaveError(new Error(t('settingsProbe.invalidLimit', { field: t(key, null, fallback) }, '请输入非负整数'))); + return; + } + const changes = { ...draft }; + for (const [key] of TOKEN_LIMITS) { + if (Object.hasOwn(changes, key)) changes[key] = numberValue(form[key]); + } + + setSaving(true); + try { + await api.put('/config', { ai_channel: { channel_id: legacy ? '' : channelId, make_default: makeDefault, ...changes } }); + clearDraft(); + await apply(makeDefault + ? t('settingsBasic.aiChannelDefaultSaved', null, '已设为默认通道') + : t('settingsBasic.aiChannelSaved', null, '通道已保存')); + await reloadConfig({ silent: true }); + } catch (error) { + setSaveError(error); + } finally { + setSaving(false); + } + }; + + const retryApply = async () => { + if (locked || !applyPending) return; + setSaving(true); + setSaveError(null); + try { + await apply(t('settings.apply.applySuccess', null, '配置已成功应用')); + } finally { + setSaving(false); + } + }; const run = async (key, path, body) => { - if (!canWrite) return; + if (locked || busy) return; setBusy(key); - setState({ key: '', payload: null, error: null }); + setState(EMPTY_PROBE); try { const payload = await api.post(path, body); setState({ key, payload, error: null }); @@ -217,8 +301,8 @@ export default function ProbePanel({ config, canWrite }) { const probeBody = () => ({ provider: form.provider, - channel_id: channelId === MAIN_CHANNEL ? undefined : channelId, - credential_scope: channelId === MAIN_CHANNEL ? 'openai' : undefined, + channel_id: legacy ? undefined : channelId, + credential_scope: legacy ? 'openai' : undefined, base_url: form.base_url, api_key: form.api_key, model: form.model, @@ -280,19 +364,38 @@ export default function ProbePanel({ config, canWrite }) { return ( {t('settings.probeReadOnly', null, '缺少 config:write,探测接口不可用')} + title={t('settingsProbe.channelTitle', null, '模型通道与连接测试')} + description={t('settingsProbe.channelHelp', null, '保存后应用所选通道的设置。显示 ******** 时沿用已保存的密钥。')} + className="settings-channel-panel" + extra={canWrite ? ( + + {dirty && ( + + )} + {!legacy && channelId !== defaultId && ( + + )} + + + ) : ( + {t('settingsProbe.channelReadOnly', null, '只读')} )} >
+ - + {TOKEN_LIMITS.map(([field, key, fallback]) => ( + + ))}
+ {(applyPending || saveError) && ( +
+ {applyPending && ( + + {t('settingsProbe.savedApplyFailed', null, '通道已写入配置,应用失败。')} + + + )} /> + )} + +
+ )} +