Files
quality_analyse/web/src/AnalysisApiSettings.tsx
T
lyun ff7bbe3e46 同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。
补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。
统一午夜黑及其他主题的控件细节、中文和业务数字字体。
排除本地业务数据、凭据、预览、发布与验收产物。

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
2026-10-30 22:40:58 +08:00

97 lines
8.2 KiB
TypeScript

import { usePageCache } from './pageCache';
import { useEffect, useRef, useState } from 'react';
import { Alert, App, Button, Form, Input, Modal, Select, Spin, Switch, Tag } from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import { api } from './api';
import { effectiveThinkingEffort, supportsThinkingEffort } from './analysisThinking';
export type AnalysisModelProfile = { id: string; name: string; baseUrl: string; model: string; hasApiKey: boolean; thinkingEnabled: boolean; thinkingEffort: string };
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string; activeProfileId: string; thinkingEnabled: boolean; thinkingEffort: string; profiles: AnalysisModelProfile[] };
export type AnalysisModelSettingsInput = { baseUrl: string; model: string; apiKey?: string; revision?: string; profileId?: string; thinkingEnabled?: boolean; thinkingEffort?: string };
export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const [form] = Form.useForm<AnalysisModelSettingsInput>();
const { active } = usePageCache();
const thinkingEnabled = Form.useWatch('thinkingEnabled', form);
const model = Form.useWatch('model', form);
const effortSupported = supportsThinkingEffort(model);
useEffect(() => { if (!effortSupported) form.setFieldValue('thinkingEffort', 'auto'); }, [effortSupported, form]);
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [settings, setSettings] = useState<AnalysisModelSettings>();
const [profileId, setProfileId] = useState<string>();
const selectedProfile = settings?.profiles.find(profile => profile.id === profileId);
const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>();
const sequence = useRef(0);
const close = () => { if (saving) return; sequence.current += 1; setOpen(false); form.resetFields(); setNotice(undefined); setTesting(false); };
const load = async () => {
const current = ++sequence.current;
setOpen(true); setLoading(true); setSettings(undefined); setProfileId(undefined); setNotice(undefined); form.resetFields();
try {
const value = await api.analysisSettings();
if (sequence.current !== current) return;
setSettings(value); setProfileId(value.activeProfileId); form.setFieldsValue({ baseUrl: value.baseUrl, model: value.model, apiKey: '', thinkingEnabled: value.thinkingEnabled ?? true, thinkingEffort: effectiveThinkingEffort(value.model, value.thinkingEffort) });
} catch (error) {
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '读取配置失败' });
} finally { if (sequence.current === current) setLoading(false); }
};
const submit = async (test: boolean) => {
if (!settings) return;
let values: AnalysisModelSettingsInput;
try { values = await form.validateFields(); } catch { return; }
const current = sequence.current;
setNotice(undefined); test ? setTesting(true) : setSaving(true);
try {
const body = { ...values, revision: settings.revision, profileId };
if (test) {
const result = await api.testAnalysisSettings(body);
if (sequence.current === current) setNotice({ type: result.success ? 'success' : 'error', text: result.message });
} else {
const result = await api.saveAnalysisSettings(body);
if (sequence.current !== current) return;
setSettings(result); setProfileId(result.activeProfileId); form.setFieldsValue({ baseUrl: result.baseUrl, model: result.model, apiKey: '', thinkingEnabled: result.thinkingEnabled ?? true, thinkingEffort: effectiveThinkingEffort(result.model, result.thinkingEffort) });
setNotice({ type: 'success', text: '已使用此配置,后续新分析将使用它;正在运行的分析继续完成。' }); message.success('API 配置已切换');
}
} catch (error) {
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '操作失败,请重试' });
} finally { if (sequence.current === current) { setTesting(false); setSaving(false); } }
};
return <>
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
<Modal title="API 配置" open={active && open} width={540} onCancel={close} footer={<>
<Button onClick={close} disabled={saving}>关闭</Button>
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
</>}>
{loading ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
{settings && <div style={{ marginBottom: 20 }}>
<div style={{ marginBottom: 8 }}>选择配置 <Tag color="blue">当前使用:{settings.profiles.find(profile => profile.id === settings.activeProfileId)?.name || settings.model}</Tag></div>
<div style={{ display: 'flex', gap: 8 }}>
<Select aria-label="选择 API 配置" style={{ flex: 1, minWidth: 0 }} value={profileId} disabled={saving || testing}
options={settings.profiles.map(profile => ({ value: profile.id, label: `${profile.name} · ${profile.model}` }))}
onChange={id => {
const profile = settings.profiles.find(item => item.id === id);
if (!profile) return;
sequence.current += 1; setProfileId(id); setNotice(undefined);
form.resetFields(); form.setFieldsValue({ baseUrl: profile.baseUrl, model: profile.model, apiKey: '', thinkingEnabled: profile.thinkingEnabled ?? true, thinkingEffort: effectiveThinkingEffort(profile.model, profile.thinkingEffort) });
}} />
<Button disabled={saving || testing || profileId === settings.activeProfileId} loading={saving} onClick={() => void submit(false)}>立即使用</Button>
</div>
</div>}
<Form form={form} layout="vertical" disabled={saving || testing} onValuesChange={() => setNotice(undefined)}>
<Form.Item name="baseUrl" label="接口地址" rules={[{ required: true, whitespace: true, message: '请填写接口地址' }]} extra="支持 OpenAI 兼容接口,可填写含 /v1 的基础地址或完整的 /chat/completions 地址。"><Input placeholder="https://api.example.com/v1" autoComplete="off" maxLength={2048} /></Form.Item>
<Form.Item name="apiKey" label="API Key" extra={selectedProfile?.hasApiKey ? '此配置已保存密钥;留空保留。更换接口地址时需重新填写。' : '密钥仅保存在服务端,保存后不回显。'} rules={selectedProfile?.hasApiKey ? [] : [{ required: true, whitespace: true, message: '请填写 API Key' }]}><Input.Password placeholder={selectedProfile?.hasApiKey ? '已配置,留空保留' : '请输入 API Key'} autoComplete="new-password" maxLength={4096} /></Form.Item>
<Form.Item name="model" label="模型名称" rules={[{ required: true, whitespace: true, message: '请填写模型名称' }]}><Input placeholder="例如 qwen3.8-27b-local" autoComplete="off" maxLength={160} /></Form.Item>
<Form.Item name="thinkingEnabled" label="思考模式" valuePropName="checked"><Switch checkedChildren="开启" unCheckedChildren="关闭" /></Form.Item>
<Form.Item name="thinkingEffort" label="思考强度" extra={!effortSupported ? '该模型暂不区分强度,开启后由模型自动决定。' : undefined}><Select disabled={!thinkingEnabled || !effortSupported || saving || testing} options={effortSupported ? [{value:'auto',label:'模型默认'},{value:'low',label:'低'},{value:'medium',label:'中'},{value:'high',label:'高'}] : [{value:'auto',label:'模型自动'}]} /></Form.Item>
</Form>
{notice && <Alert showIcon type={notice.type} message={notice.text} />}
{!settings && notice && <Button style={{ marginTop: 12 }} onClick={() => void load()}>重新读取</Button>}
</>}
</Modal>
</>;
}