Files
monkey-ai-web/src/components/smart-router/GlobalSettings.jsx
T
zhanjunhao cb9d836227 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

529 lines
15 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Button,
Form,
Input,
InputNumber,
Modal,
Select,
Space,
Spin,
Switch,
Tag,
Typography,
} from 'antd';
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
import { showError, showSuccess } from '../../helpers';
import { getAdminStatus, loadOptions, saveOption, setJevKey } from './api';
const { Text } = Typography;
const { TextArea } = Input;
const PREFIX = 'smart_router_setting.';
// 字段定义:type 决定编辑控件;compliance=true 的是合规相关(只有 root 能改,后端 rootOnlyOptionKeys)
const FIELDS = [
{ key: 'enabled', type: 'bool', label: '总开关', section: 'main' },
{
key: 'rollout_percent',
type: 'int',
label: '灰度比例(%)',
min: 0,
max: 100,
section: 'main',
},
{
key: 'single_node_ack',
type: 'bool',
label: '确认为单节点部署(Redis 未启用时必填)',
section: 'main',
compliance: true,
},
{
key: 'max_profiles_per_user',
type: 'int',
label: '每人最多个人集合数',
min: 0,
max: 100,
section: 'main',
},
{
key: 'jev_egress_allowed',
type: 'bool',
label: '允许调用 Jev(数据出境,合规评估通过后开启)',
section: 'jev',
compliance: true,
},
{
key: 'jev_primary',
type: 'select',
label: '主通道',
options: ['typesafe', 'openrouter'],
section: 'jev',
},
{
key: 'jev_model_typesafe',
type: 'str',
label: 'TypeSafe 模型版本',
section: 'jev',
},
{
key: 'jev_model_openrouter',
type: 'str',
label: 'OpenRouter 模型版本',
section: 'jev',
},
{
key: 'judge_budget_ms',
type: 'int',
label: '判定总预算(毫秒,以国内压测 P95 为准)',
min: 20,
max: 5000,
section: 'jev',
},
{
key: 'judge_hedge_enabled',
type: 'bool',
label: '主备对冲',
section: 'jev',
},
{
key: 'judge_hedge_after_ms',
type: 'int',
label: '对冲触发(毫秒,取压测 P80)',
min: 1,
max: 5000,
section: 'jev',
},
{
key: 'state_max_bytes',
type: 'int',
label: '发给 Jev 的内容上限(字节)',
min: 1000,
max: 30000,
section: 'jev',
},
{
key: 'default_tau_quality',
type: 'str',
label: '质量优先 τ1,τ2,τ3',
section: 'judge',
},
{
key: 'default_tau_balanced',
type: 'str',
label: '平衡 τ1,τ2,τ3',
section: 'judge',
},
{
key: 'default_tau_cost',
type: 'str',
label: '成本优先 τ1,τ2,τ3',
section: 'judge',
},
{
key: 'skill_injection_token_reserve',
type: 'int',
label: 'skill 注入预留 token',
min: 0,
max: 100000,
section: 'judge',
},
{
key: 'strip_incompatible_channel_types',
type: 'str',
label: '未通过剥离兼容性验证的渠道类型(逗号分隔)',
section: 'judge',
compliance: true,
},
{
key: 'rules_judge_config',
type: 'json',
label: '规则判定器关键词与分数(JSON,留空使用内置)',
section: 'judge',
},
{
key: 'consent_text_versions',
type: 'json',
label: '同意文案版本(JSON,如 {"judge":{"v":1,"overseas":true}})',
section: 'consent',
compliance: true,
},
{
key: 'router_eval_retention_days',
type: 'int',
label: '判定明细保留天数',
min: 1,
max: 365,
section: 'retention',
},
{
key: 'simulate_daily_cap_per_user',
type: 'int',
label: '试路由每人每日上限',
min: 0,
max: 100000,
section: 'retention',
},
{
key: 'simulate_daily_cap_per_org',
type: 'int',
label: '试路由每企业每日上限',
min: 0,
max: 1000000,
section: 'retention',
},
{
key: 'max_profiles_per_org',
type: 'int',
label: '每个企业最多集合数',
min: 0,
max: 1000,
section: 'retention',
},
{
key: 'jev_daily_cap_per_user',
type: 'int',
label: 'Jev 判定每人每日上限(0 不限)',
min: 0,
max: 10000000,
section: 'retention',
},
{
key: 'jev_daily_cap_per_org',
type: 'int',
label: 'Jev 判定每企业每日上限(0 不限)',
min: 0,
max: 100000000,
section: 'retention',
},
];
const SECTIONS = [
['main', '总控'],
['jev', 'Jev 判定'],
['judge', '判定参数'],
['consent', '同意文案'],
['retention', '保留与限流'],
];
// 保存顺序:前置条件(single_node_ack)必须先于依赖它的总开关保存
const SAVE_ORDER = ['single_node_ack', 'consent_text_versions'];
const GlobalSettings = () => {
const { t } = useTranslation();
const [values, setValues] = useState({});
const [original, setOriginal] = useState({});
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [saving, setSaving] = useState(false);
const [keys, setKeys] = useState({ typesafe: '', openrouter: '' });
const tRef = useRef(t);
tRef.current = t;
const load = useCallback(async () => {
setLoading(true);
setLoadError('');
try {
const data = await loadOptions();
const v = {};
(data || []).forEach((item) => {
if (item.key.startsWith(PREFIX))
v[item.key.slice(PREFIX.length)] = item.value;
});
setValues(v);
setOriginal(v);
setStatus(await getAdminStatus());
} catch (e) {
setLoadError(e?.message || tRef.current('加载失败'));
} finally {
setLoading(false);
}
}, []); // 不依赖 t:切换语言不能重新加载并丢掉未保存的编辑
useEffect(() => {
load();
}, [load]);
const save = async () => {
const changed = FIELDS.filter(
(f) => String(values[f.key] ?? '') !== String(original[f.key] ?? ''),
).sort((a, b) => {
const ia = SAVE_ORDER.indexOf(a.key);
const ib = SAVE_ORDER.indexOf(b.key);
return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib);
});
if (changed.length === 0) {
showSuccess(t('配置未修改'));
return;
}
setSaving(true);
const saved = {};
try {
for (const f of changed) {
try {
await saveOption(PREFIX + f.key, String(values[f.key] ?? ''));
saved[f.key] = values[f.key];
} catch (e) {
showError(`${t(f.label)} · ${e?.message || ''}`);
// 已保存的项更新基线,未保存的编辑保留在表单里,便于修改后重试
setOriginal((o) => ({ ...o, ...saved }));
return;
}
}
showSuccess(t('已保存'));
await load();
} finally {
setSaving(false);
}
};
const saveKey = async (provider, clear = false) => {
const run = async () => {
try {
await setJevKey(provider, keys[provider], clear);
setKeys((k) => ({ ...k, [provider]: '' }));
showSuccess(clear ? t('已清除') : t('已保存'));
setStatus(await getAdminStatus());
} catch (e) {
showError(e?.message || t('保存失败,请稍后重试'));
}
};
if (!clear) return run();
Modal.confirm({
title: t('确认清除密钥?'),
content: t('清除后该通道无法调用 Jev,判定会降级为规则判定。'),
okButtonProps: { danger: true },
onOk: run,
});
};
const renderField = (f) => {
const v = values[f.key];
const set = (nv) => setValues((s) => ({ ...s, [f.key]: nv }));
switch (f.type) {
case 'bool':
return (
<Switch
checked={v === 'true'}
onChange={(c) => set(c ? 'true' : 'false')}
aria-label={t(f.label)}
/>
);
case 'int':
return (
<InputNumber
className='smart-router-setting-control'
min={f.min}
max={f.max}
value={Number(v) || 0}
onChange={(raw) => {
// antd 清空时回调 null,按原 Semi 的空串语义回落到最小值
const n = raw ?? '';
set(
String(
Number.isFinite(Number(n)) && n !== ''
? Number(n)
: (f.min ?? 0),
),
);
}}
/>
);
case 'select':
return (
<Select
className='smart-router-setting-control'
value={v}
options={f.options.map((o) => ({ label: o, value: o }))}
onChange={set}
/>
);
case 'json':
return (
<TextArea
className='smart-router-mono'
autoSize={{ minRows: 2, maxRows: 10 }}
value={v}
onChange={(e) => set(e.target.value)}
/>
);
default:
return (
<Input
className='smart-router-setting-control'
value={v}
onChange={(e) => set(e.target.value)}
/>
);
}
};
if (loading)
return (
<div className='smart-router-state'>
<Spin />
</div>
);
if (loadError)
return (
<Alert
type='error'
showIcon
title={loadError}
action={
<Button size='small' onClick={load}>
{t('重试')}
</Button>
}
/>
);
return (
<div className='smart-router-stack'>
{status && (
<div className='smart-router-card'>
<div className='smart-router-card-title'>{t('运行状态')}</div>
<Space size={8} wrap>
<Tag color={status.session_store_ready ? 'success' : 'error'}>
{status.session_store_ready
? t('共享会话存储就绪')
: t('共享会话存储未就绪')}
</Tag>
<Tag color={status.redis_enabled ? 'success' : 'default'}>
Redis {status.redis_enabled ? t('已启用') : t('未启用')}
</Tag>
<Tag color={status.typesafe_key_set ? 'success' : 'default'}>
TypeSafe{' '}
{status.typesafe_key_set ? t('密钥已设置') : t('未设置密钥')}
</Tag>
<Tag color={status.openrouter_key_set ? 'success' : 'default'}>
OpenRouter{' '}
{status.openrouter_key_set ? t('密钥已设置') : t('未设置密钥')}
</Tag>
{status.typesafe_breaker && (
<Tag color='error'>{t('TypeSafe 熔断中')}</Tag>
)}
{status.openrouter_breaker && (
<Tag color='error'>{t('OpenRouter 熔断中')}</Tag>
)}
<Tag>
{t('会话写入失败')}{' '}
<span className='smart-router-num'>
{status.session_write_fail}
</span>
</Tag>
<Tag>
{t('评估记录丢弃')}{' '}
<span className='smart-router-num'>{status.eval_dropped}</span>
</Tag>
<Tag>
{t('会话读取失败')}{' '}
<span className='smart-router-num'>
{status.session_read_fail}
</span>
</Tag>
<Tag>
{t('Jev 降级次数')}{' '}
<span className='smart-router-num'>{status.jev_fallback}</span>
</Tag>
<Tag color={status.not_ready ? 'warning' : 'default'}>
{t('存储未就绪拒绝')}{' '}
<span className='smart-router-num'>{status.not_ready}</span>
</Tag>
</Space>
<div className='smart-router-section'>
<Text type='secondary' className='smart-router-sub'>
{t('以上计数为当前节点进程内累计值,进程重启后清零')}
</Text>
</div>
</div>
)}
<Alert
type='warning'
showIcon
title={t(
'标注「合规」的配置项只有超级管理员可以修改。开启 Jev 出境前须完成合规评估。',
)}
/>
{SECTIONS.map(([sec, title]) => (
<div key={sec} className='smart-router-card'>
<div className='smart-router-card-title'>{t(title)}</div>
{/* 受控字段沿用 values 状态,Form 只提供竖排标签布局,不接管取值与提交 */}
<Form
layout='vertical'
component='div'
requiredMark={false}
className='smart-router-settings-form'
>
{FIELDS.filter((f) => f.section === sec).map((f) => (
<Form.Item
key={f.key}
label={
<span className='smart-router-field-label'>
{t(f.label)}
{f.compliance && (
<Tag color='warning' variant='filled'>
{t('合规')}
</Tag>
)}
</span>
}
>
{renderField(f)}
</Form.Item>
))}
{sec === 'jev' &&
['typesafe', 'openrouter'].map((p) => (
<Form.Item
key={p}
label={
<span className='smart-router-field-label'>
{p === 'typesafe'
? t('TypeSafe 密钥')
: t('OpenRouter 密钥')}
({t('加密存储,只有超级管理员可修改')})
</span>
}
>
<Space size={8} wrap className='smart-router-key-tools'>
<Input.Password
className='smart-router-key-input'
placeholder={t('输入新密钥;留空表示不修改')}
value={keys[p]}
onChange={(e) =>
setKeys((k) => ({ ...k, [p]: e.target.value }))
}
/>
<Button onClick={() => saveKey(p)} disabled={!keys[p]}>
{t('保存密钥')}
</Button>
<Button
danger
disabled={
!(p === 'typesafe'
? status?.typesafe_key_set
: status?.openrouter_key_set)
}
onClick={() => saveKey(p, true)}
>
{t('清除')}
</Button>
</Space>
</Form.Item>
))}
</Form>
</div>
))}
<div>
<Button type='primary' loading={saving} onClick={save}>
{t('保存设置')}
</Button>
</div>
</div>
);
};
export default GlobalSettings;