Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,729 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {
Banner,
Button,
Card,
Descriptions,
Form,
Input,
Modal,
Space,
Spin,
Table,
TabPane,
Tabs,
Tag,
Typography,
} from '@douyinfe/semi-ui';
import { RefreshCw, Save, ShieldAlert, TestTube2 } from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers';
import { useTranslation } from 'react-i18next';
import {
ENFORCE_CHECK_FIELDS,
normalizeContentGuardConfig,
} from './contentGuardConfig.js';
const DEFAULT_CONFIG = {
provider: 'uguard',
enabled: false,
mode: 'observe',
base_url: '',
api_key: '',
input_enabled: true,
output_enabled: true,
text_enabled: true,
image_enabled: true,
video_enabled: true,
text_timeout_ms: 30000,
image_timeout_ms: 60000,
video_timeout_ms: 180000,
text_concurrency: 16,
image_concurrency: 4,
video_concurrency: 2,
text_cluster_qps: 20,
image_cluster_qps: 5,
video_cluster_qps: 2,
observe_queue_size: 256,
observe_workers: 4,
stream_memory_threshold_bytes: 1048576,
stream_response_cap_bytes: 16777216,
stream_spool_cap_bytes: 1073741824,
image_temp_cap_bytes: 1073741824,
video_temp_cap_bytes: 10737418240,
groups: [],
user_ids: [],
confirm_enforce: false,
};
const errorMessage = (error) =>
error?.response?.data?.message || error?.message || '请求失败';
const statusTag = (config, t) => {
if (config.lifecycle_state === 'decommissioned') {
return <Tag color='grey'>{t('已永久下线')}</Tag>;
}
if (config.lifecycle_state === 'draining') {
return <Tag color='orange'>{t('清算中')}</Tag>;
}
if (config.emergency_disabled) {
return <Tag color='red'>{t('紧急关闭')}</Tag>;
}
return config.enabled ? (
<Tag color='green'>{t('运行中')}</Tag>
) : (
<Tag>{t('未启用')}</Tag>
);
};
export default function ContentGuardSetting() {
const { t } = useTranslation();
const formApi = useRef(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [config, setConfig] = useState(DEFAULT_CONFIG);
const [groups, setGroups] = useState([]);
const [users, setUsers] = useState([]);
const [logs, setLogs] = useState({ items: [], total: 0, page: 1, size: 20 });
const [metrics, setMetrics] = useState({});
const [decommission, setDecommission] = useState(null);
const [killReason, setKillReason] = useState('');
const [userKeyword, setUserKeyword] = useState('');
const [isEnforceMode, setIsEnforceMode] = useState(false);
const formValues = useMemo(
() => ({
...DEFAULT_CONFIG,
...config,
api_key: '',
confirm_enforce: false,
}),
[config],
);
const loadUsers = useCallback(async (keyword = '') => {
try {
const response = await API.get('/api/content-guard/users', {
params: { keyword, limit: 100 },
});
if (response.data.success) setUsers(response.data.data || []);
} catch (error) {
showError(errorMessage(error));
}
}, []);
const loadLogs = async (page = 1, size = logs.size || 20) => {
try {
const response = await API.get('/api/content-guard/logs', {
params: { page, size },
});
if (response.data.success) {
setLogs(response.data.data || { items: [], total: 0, page, size });
}
} catch (error) {
showError(errorMessage(error));
}
};
const loadAll = useCallback(async () => {
setLoading(true);
try {
const [configRes, groupsRes, metricsRes, decommissionRes, logsRes] =
await Promise.all([
API.get('/api/content-guard/config'),
API.get('/api/content-guard/groups'),
API.get('/api/content-guard/metrics', { params: { hours: 24 } }),
API.get('/api/content-guard/decommission'),
API.get('/api/content-guard/logs', { params: { page: 1, size: 20 } }),
]);
const nextConfig = configRes.data.data || DEFAULT_CONFIG;
setConfig(nextConfig);
setIsEnforceMode(nextConfig.mode === 'enforce');
setGroups(groupsRes.data.data || []);
setMetrics(metricsRes.data.data || {});
setDecommission(decommissionRes.data.data || null);
setLogs(logsRes.data.data || { items: [], total: 0, page: 1, size: 20 });
await loadUsers();
setTimeout(
() =>
formApi.current?.setValues({
...DEFAULT_CONFIG,
...nextConfig,
api_key: '',
}),
0,
);
} catch (error) {
showError(errorMessage(error));
} finally {
setLoading(false);
}
}, [loadUsers]);
useEffect(() => {
loadAll();
}, [loadAll]);
const handleModeChange = (event) => {
const mode = event?.target?.value;
setIsEnforceMode(mode === 'enforce');
if (mode === 'enforce') {
formApi.current?.setValues(
Object.fromEntries(ENFORCE_CHECK_FIELDS.map((field) => [field, true])),
);
}
};
const saveConfig = async (values) => {
const normalized = normalizeContentGuardConfig(values);
if (
normalized.enabled &&
normalized.mode === 'enforce' &&
!normalized.confirm_enforce
) {
showError(t('启用强制阻断模式前,请勾选风险确认'));
return;
}
setSaving(true);
try {
const response = await API.put('/api/content-guard/config', {
...normalized,
provider: 'uguard',
expected_version: config.version,
api_key: normalized.api_key || '',
});
if (!response.data.success) throw new Error(response.data.message);
const result = response.data.data;
setConfig(result.config);
formApi.current?.setValue('api_key', '');
if (result.activation_pending) {
showSuccess(
t('异步发布门禁已建立。节点确认完成后,请再次保存以正式启用。'),
);
} else {
showSuccess(t('防护配置已保存'));
}
await loadAll();
} catch (error) {
showError(errorMessage(error));
} finally {
setSaving(false);
}
};
const testPermission = async (kind) => {
try {
const response = await API.post('/api/content-guard/test', { kind });
const result = response.data.data;
showSuccess(`${kind}: ${result.safety}, ${result.latency_ms} ms`);
} catch (error) {
showError(errorMessage(error));
}
};
const setKillSwitch = async (disabled) => {
if (!killReason.trim()) {
showError(t('请填写操作原因'));
return;
}
try {
await API.post('/api/content-guard/kill-switch', {
expected_version: config.version,
disabled,
reason: killReason.trim(),
});
showSuccess(disabled ? t('已紧急关闭') : t('已解除紧急关闭'));
setKillReason('');
await loadAll();
} catch (error) {
showError(errorMessage(error));
}
};
const startDecommission = () => {
let confirmText = '';
Modal.confirm({
title: t('开始永久下线清算'),
content: (
<div>
<p>{t('此操作会立即停止新防护判定,并处理所有历史异步资源。')}</p>
<Input
placeholder='DECOMMISSION CONTENT GUARD'
onChange={(value) => (confirmText = value)}
/>
</div>
),
onOk: async () => {
if (confirmText !== 'DECOMMISSION CONTENT GUARD') {
showError(t('确认短语不正确'));
return Promise.reject();
}
await API.post('/api/content-guard/decommission/start', {
expected_version: config.version,
policy: 'block_unknown',
inflight_action: 'wait',
confirm: true,
});
await loadAll();
},
});
};
const completeDecommission = async () => {
try {
await API.post('/api/content-guard/decommission/complete', {
expected_version: decommission?.version,
confirm: 'DECOMMISSION CONTENT GUARD',
});
showSuccess(t('防护模块已永久下线,密钥和范围配置已清除'));
await loadAll();
} catch (error) {
showError(errorMessage(error));
}
};
const cancelDecommission = () => {
let reason = '';
Modal.confirm({
title: t('取消永久下线清算'),
content: (
<Input
placeholder={t('填写取消原因')}
onChange={(value) => (reason = value)}
/>
),
onOk: async () => {
if (!reason.trim()) {
showError(t('请填写取消原因'));
return Promise.reject();
}
await API.post('/api/content-guard/decommission/cancel', {
expected_version: decommission?.version,
reason: reason.trim(),
});
showSuccess(t('清算已取消;防护仍保持紧急关闭和未启用状态'));
await loadAll();
},
});
};
const auditColumns = [
{
title: t('时间'),
dataIndex: 'created_at',
render: (v) => new Date(v).toLocaleString(),
},
{ title: t('用户'), dataIndex: 'user_id', width: 80 },
{ title: t('分组'), dataIndex: 'using_group' },
{ title: t('模型'), dataIndex: 'model' },
{ title: t('方向'), dataIndex: 'direction' },
{ title: t('类型'), dataIndex: 'content_type' },
{
title: t('结果'),
dataIndex: 'safety',
render: (value) => (
<Tag
color={
value === '合规' ? 'green' : value === '违规' ? 'red' : 'orange'
}
>
{value || '-'}
</Tag>
),
},
{ title: t('动作'), dataIndex: 'action' },
{
title: t('耗时'),
dataIndex: 'latency_ms',
render: (v) => `${v || 0} ms`,
},
{ title: t('错误码'), dataIndex: 'error_code' },
];
if (loading) {
return <Spin spinning style={{ display: 'block', margin: '80px auto' }} />;
}
return (
<div style={{ padding: 20 }}>
<Space vertical align='start' spacing='medium' style={{ width: '100%' }}>
<Banner
fullMode={false}
type={config.available && config.schema_ready ? 'info' : 'warning'}
description={
config.available && config.schema_ready
? t(
'UGuard 仅作用于同时命中用户和实际调用分组的请求。未命中请求不会调用防护服务。',
)
: t('运行环境或数据库迁移尚未允许启用内容防护。')
}
/>
<Card style={{ width: '100%' }}>
<Space style={{ justifyContent: 'space-between', width: '100%' }}>
<Space>
<ShieldAlert size={20} />
<Typography.Title heading={4} style={{ margin: 0 }}>
{t('大模型内容防护')}
</Typography.Title>
{statusTag(config, t)}
</Space>
<Button
icon={<RefreshCw size={16} />}
onClick={loadAll}
aria-label={t('刷新')}
/>
</Space>
<Descriptions
row
size='small'
data={[
{ key: t('配置版本'), value: config.version },
{
key: t('节点确认'),
value: `${config.acknowledged_nodes}/${config.expected_nodes}`,
},
{
key: t('API Key'),
value: config.api_key_configured
? `****${config.api_key_suffix}`
: t('未配置'),
},
{ key: t('24小时检测'), value: metrics.total || 0 },
{ key: t('24小时阻断'), value: metrics.blocked || 0 },
]}
/>
</Card>
<Tabs type='line' style={{ width: '100%' }}>
<TabPane tab={t('配置')} itemKey='config'>
<Form
key={config.version}
initValues={formValues}
getFormApi={(api) => (formApi.current = api)}
onSubmit={saveConfig}
labelPosition='top'
>
<Card title={t('连接与生效范围')}>
<div className='grid grid-cols-1 gap-3 md:grid-cols-2'>
<Form.Switch field='enabled' label={t('启用内容防护')} />
<Form.RadioGroup
field='mode'
label={t('运行模式')}
onChange={handleModeChange}
options={[
{ label: t('观察'), value: 'observe' },
{ label: t('强制阻断'), value: 'enforce' },
]}
/>
<Form.Input
field='base_url'
label='Base URL'
placeholder='http://uguard.example.com'
/>
<Form.Input
field='api_key'
mode='password'
label='API Key'
placeholder={
config.api_key_configured
? t('留空保持当前密钥')
: t('请输入密钥')
}
/>
<Form.Select
field='groups'
label={t('启用分组')}
multiple
filter
optionList={groups.map((group) => ({
label: group,
value: group,
}))}
/>
<Form.Select
field='user_ids'
label={t('启用用户')}
multiple
filter
remote
onSearch={(value) => {
setUserKeyword(value);
loadUsers(value);
}}
optionList={users.map((user) => ({
value: user.id,
label: `${user.display_name || user.username} (#${user.id})`,
}))}
emptyContent={
userKeyword
? t('没有匹配用户')
: t('输入用户名或邮箱搜索')
}
/>
</div>
<Space wrap>
<Form.Switch
field='input_enabled'
label={t('检测输入')}
disabled={isEnforceMode}
/>
<Form.Switch
field='output_enabled'
label={t('检测输出')}
disabled={isEnforceMode}
/>
<Form.Switch
field='text_enabled'
label={t('文本')}
disabled={isEnforceMode}
/>
<Form.Switch
field='image_enabled'
label={t('图片')}
disabled={isEnforceMode}
/>
<Form.Switch
field='video_enabled'
label={t('视频')}
disabled={isEnforceMode}
/>
</Space>
<Form.Checkbox field='confirm_enforce'>
{t(
'我确认强制模式会在 UGuard 不可用、疑似、违规或未识别时拒绝命中请求',
)}
</Form.Checkbox>
</Card>
<Card title={t('性能与容量')} style={{ marginTop: 12 }}>
<div className='grid grid-cols-1 gap-3 md:grid-cols-3'>
{[
['text_timeout_ms', '文本超时(ms)'],
['image_timeout_ms', '图片超时(ms)'],
['video_timeout_ms', '视频超时(ms)'],
['text_concurrency', '文本并发'],
['image_concurrency', '图片并发'],
['video_concurrency', '视频并发'],
['text_cluster_qps', '文本集群QPS'],
['image_cluster_qps', '图片集群QPS'],
['video_cluster_qps', '视频集群QPS'],
['observe_queue_size', '观察队列'],
['observe_workers', '观察任务数'],
['stream_memory_threshold_bytes', '响应内存阈值(bytes)'],
['stream_response_cap_bytes', '单响应上限(bytes)'],
['stream_spool_cap_bytes', '响应临时空间预算(bytes)'],
['image_temp_cap_bytes', '图片临时空间预算(bytes)'],
['video_temp_cap_bytes', '视频临时空间预算(bytes)'],
].map(([field, label]) => (
<Form.InputNumber
key={field}
field={field}
label={t(label)}
min={1}
style={{ width: '100%' }}
/>
))}
</div>
<Descriptions
row
size='small'
style={{ marginTop: 12 }}
data={[
{
key: t('文本并发'),
value: `${metrics.runtime?.text_inflight || 0}/${metrics.runtime?.text_concurrency || 0}`,
},
{
key: t('图片并发'),
value: `${metrics.runtime?.image_inflight || 0}/${metrics.runtime?.image_concurrency || 0}`,
},
{
key: t('视频并发'),
value: `${metrics.runtime?.video_inflight || 0}/${metrics.runtime?.video_concurrency || 0}`,
},
{
key: t('观察队列'),
value: `${metrics.runtime?.observe_queue_depth || 0}/${metrics.runtime?.observe_queue_capacity || 0}`,
},
{
key: t('审计队列'),
value: `${metrics.runtime?.audit_queue_depth || 0}/${metrics.runtime?.audit_queue_capacity || 0}`,
},
{
key: t('审计丢弃'),
value: metrics.runtime?.audit_dropped || 0,
},
{
key: t('响应临时空间'),
value: `${metrics.runtime?.stream_temporary_bytes || 0} bytes`,
},
{
key: t('媒体临时空间'),
value: `${(metrics.runtime?.image_temporary_bytes || 0) + (metrics.runtime?.video_temporary_bytes || 0)} bytes`,
},
]}
/>
</Card>
<Space style={{ marginTop: 16 }}>
<Button
htmlType='submit'
type='primary'
loading={saving}
icon={<Save size={16} />}
>
{t('保存配置')}
</Button>
<Button
icon={<TestTube2 size={16} />}
onClick={() => testPermission('moderate')}
>
moderate
</Button>
<Button
icon={<TestTube2 size={16} />}
onClick={() => testPermission('stream_moderate')}
>
stream_moderate
</Button>
</Space>
</Form>
<Card title={t('紧急熔断')} style={{ marginTop: 12 }}>
<Space wrap>
<Input
value={killReason}
onChange={setKillReason}
placeholder={t('填写操作原因')}
style={{ width: 360, maxWidth: '100%' }}
/>
<Button type='danger' onClick={() => setKillSwitch(true)}>
{t('立即关闭')}
</Button>
<Button
disabled={!config.emergency_disabled}
onClick={() => setKillSwitch(false)}
>
{t('解除关闭')}
</Button>
</Space>
</Card>
</TabPane>
<TabPane tab={t('审计')} itemKey='audit'>
<Table
rowKey='id'
columns={auditColumns}
dataSource={logs.items || []}
scroll={{ x: 'max-content' }}
pagination={{
total: logs.total || 0,
pageSize: logs.size || 20,
currentPage: logs.page || 1,
showTotal: true,
onPageChange: (page) => loadLogs(page, logs.size || 20),
onPageSizeChange: (size) => loadLogs(1, size),
}}
/>
</TabPane>
<TabPane tab={t('永久下线')} itemKey='decommission'>
<Banner
fullMode={false}
type='warning'
description={t(
'永久下线用于未来彻底移除 UGuard。清算完成前,历史异步资源门禁不会被跳过。',
)}
/>
<Card style={{ marginTop: 12 }}>
<Descriptions
row
data={[
{
key: t('生命周期'),
value: decommission?.lifecycle_state || '-',
},
{ key: t('清算代次'), value: decommission?.generation || 0 },
{
key: t('活动租约'),
value: decommission?.active_leases || 0,
},
{
key: t('临时空间占用'),
value: `${decommission?.temporary_bytes || 0} bytes`,
},
{
key: t('清算动作'),
value: decommission?.retirement_actions || 0,
},
{
key: t('完成条件'),
value: decommission?.readiness ? t('已满足') : t('未满足'),
},
]}
/>
{!!decommission?.blocking_reasons?.length && (
<Banner
type='warning'
description={decommission.blocking_reasons.join(', ')}
/>
)}
<Space style={{ marginTop: 16 }}>
<Button
type='danger'
disabled={config.lifecycle_state !== 'active'}
onClick={startDecommission}
>
{t('开始清算')}
</Button>
<Button
disabled={
config.lifecycle_state !== 'draining' ||
!decommission?.cancel_allowed
}
onClick={cancelDecommission}
>
{t('取消清算')}
</Button>
<Button
type='danger'
disabled={
!decommission?.readiness ||
config.lifecycle_state !== 'draining'
}
onClick={completeDecommission}
>
{t('完成永久下线')}
</Button>
</Space>
</Card>
</TabPane>
</Tabs>
</Space>
</div>
);
}