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
+784
View File
@@ -0,0 +1,784 @@
/*
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, useState } from 'react';
import {
Button,
Input,
InputNumber,
Modal,
Popconfirm,
Select,
Table,
Tag,
TextArea,
Toast,
Typography,
} from '@douyinfe/semi-ui';
import {
Activity,
FlaskConical,
Gauge,
RefreshCw,
ShieldAlert,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import {
usePageGuide,
PageGuideDrawer,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import OrgPanel from './components/OrgPanel';
import './org-effectiveness.css';
const { Title, Text } = Typography;
const dimensions = [
{ value: 'organization', label: '企业总览' },
{ value: 'department', label: '部门' },
{ value: 'project', label: '项目' },
{ value: 'expert', label: '专家' },
{ value: 'skill', label: 'Skill' },
];
const initialExperiment = {
name: '',
skill_id: 0,
version_a_id: 0,
version_b_id: 0,
stable_version_id: 0,
hypothesis: '',
primary_metric: 'quality.adoption_rate',
guardrail_metrics: 'efficiency.quota,quality.return_rate',
target_sample: 100,
allocation_bps: 5000,
stop_conditions: '{"max_cost_increase":0.2,"min_quality_score":60}',
};
const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
const [dimension, setDimension] = useState('organization');
const [dimensionId, setDimensionId] = useState(0);
const [data, setData] = useState({ metrics: [], alerts: [], states: [] });
const [experiments, setExperiments] = useState([]);
const [loading, setLoading] = useState(false);
const [experimentVisible, setExperimentVisible] = useState(false);
const [experiment, setExperiment] = useState(initialExperiment);
const [comparisonSkillId, setComparisonSkillId] = useState(0);
const [comparison, setComparison] = useState([]);
// 直连链路的技能使用统计(方案 §5.3)。云脑面的效能由 agent_effectiveness 覆盖,
// 直连面此前完全没有回流口径——同一个技能在网关上被用了多少次是看不到的。
const [directUsage, setDirectUsage] = useState([]);
const load = useCallback(async () => {
setLoading(true);
try {
const params = {};
if (dimension !== 'organization') {
params.dimension_type = dimension;
params.dimension_id = dimensionId;
} else {
params.dimension_type = 'organization';
params.dimension_id = 0;
}
const [metrics, experimentRows, usageRows] = await Promise.all([
API.get('/api/org/effectiveness', { headers, params }),
API.get('/api/org/effectiveness/experiments', { headers }),
API.get('/api/org/effectiveness/skill-usage', { headers }),
]);
if (metrics.data?.success) setData(metrics.data.data || {});
if (experimentRows.data?.success)
setExperiments(experimentRows.data.data || []);
// 直连统计失败不阻断整页:它是新增的补充维度,企业若未开 agent_effectiveness
// 功能开关、或成员无 agent_effect_view 权限,该接口会拒绝,此时留空即可。
setDirectUsage(usageRows.data?.success ? usageRows.data.data || [] : []);
} catch (error) {
Toast.error(error.message);
} finally {
setLoading(false);
}
}, [dimension, dimensionId, headers]);
useEffect(() => {
void load();
}, [load]);
const metric = useMemo(() => {
const result = new Map();
for (const row of data.metrics || []) {
const current = result.get(row.metric_key) || {
value: 0,
numerator: 0,
denominator: 0,
};
current.value += Number(row.value || 0);
current.numerator += Number(row.numerator || 0);
current.denominator += Number(row.denominator || 0);
current.latest = row;
result.set(row.metric_key, current);
}
return result;
}, [data.metrics]);
const value = (key, rate = false) => {
const row = metric.get(key);
if (!row) return 0;
return rate && row.denominator
? row.numerator / row.denominator
: row.value;
};
const aggregateToday = async () => {
const metricDate = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(new Date());
const response = await API.post(
'/api/org/effectiveness/aggregate',
{ metric_date: metricDate },
{ headers },
);
if (response.data?.success) {
Toast.success(t('聚合已完成'));
await load();
}
};
const createExperiment = async () => {
let stopConditions;
try {
stopConditions = JSON.parse(experiment.stop_conditions);
} catch {
Toast.error(t('停止条件必须是合法 JSON'));
return;
}
const response = await API.post(
'/api/org/effectiveness/experiments',
{
...experiment,
guardrail_metrics: experiment.guardrail_metrics
.split(',')
.map((item) => item.trim())
.filter(Boolean),
stop_conditions: stopConditions,
},
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('创建失败'));
return;
}
setExperimentVisible(false);
setExperiment(initialExperiment);
await load();
};
const experimentAction = async (row, action) => {
const endpoint = `/api/org/effectiveness/experiments/${row.id}/${action}`;
const payload =
action === 'start'
? {}
: {
rollback: true,
winner_version_id: row.stable_version_id,
reason: '管理员立即停止并回退到稳定版本',
};
const response = await API.post(endpoint, payload, { headers });
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
await load();
};
// 实验此前只能建、只能起停:建错的草稿和终态实验会永久堆在列表里。
// 运行中的实验后端会拒绝删除(须先停止或回退),这里按状态禁用按钮先行拦一层。
const deleteExperiment = async (row) => {
const response = await API.delete(
`/api/org/effectiveness/experiments/${row.id}`,
{ headers },
);
if (!response.data?.success) {
Toast.error(response.data?.message || t('操作失败'));
return;
}
Toast.success(t('实验已删除'));
await load();
};
const loadComparison = async () => {
if (!comparisonSkillId) return;
const response = await API.get(
`/api/org/effectiveness/quality/skills/${comparisonSkillId}/versions`,
{ headers },
);
if (response.data?.success) setComparison(response.data.data || []);
};
const showAlertSamples = (row) => {
let ids = [];
try {
ids = JSON.parse(row.sample_run_ids || '[]');
} catch {
ids = [];
}
Modal.info({
title: t('告警任务样本'),
content: (
<div className='org-effect-samples'>
{ids.map((id) => (
<code key={id}>{id}</code>
))}
</div>
),
});
};
const cards = [
{
label: t('覆盖任务'),
value: Math.round(value('coverage.task_count')).toLocaleString(),
detail: `${Math.round(value('coverage.active_member_count'))} ${t('活跃员工')}`,
icon: Activity,
},
{
label: t('节省时间'),
value: `${Math.round(value('efficiency.saved_minutes'))} min`,
detail: `${Math.round(value('efficiency.manual_minutes'))} min ${t('人工基线')}`,
icon: Gauge,
},
{
label: t('质量评分'),
value: metric.has('quality.score')
? value('quality.score', true).toFixed(1)
: t('数据不足'),
detail: `${Math.round(value('quality.feedback_count'))} ${t('反馈样本')}`,
icon: FlaskConical,
},
{
label: t('治理风险'),
value: Math.round(value('governance.failed_tool_call_count')),
detail: `${Math.round(value('governance.write_call_count'))} ${t('写操作')}`,
icon: ShieldAlert,
},
];
// 使用指引:看板阅读指南(无上手流程,不出进度胶囊)——重点解释
// 每个指标的口径和数据来源,避免管理员把抽样数据当精确账。
const guide = usePageGuide({
guideKey: 'org-effectiveness',
title: t('效能分析 · 使用指引'),
intro: t('回答四个问题:谁在用、省了多少时间、成本对不对账、质量是否改善'),
steps: [
{
title: t('选维度查看'),
detail: t('从企业总览切到部门 / 项目 / 专家 / Skill 维度'),
points: [
t('非总览维度需在旁边输入框填对应 ID(部门 ID、项目 ID 等)'),
t('切换后数据自动刷新;「刷新」按钮可随时重拉'),
],
},
{
title: t('读懂四张指标卡'),
detail: t('覆盖、节省、质量、风险各一张'),
points: [
t('「节省时间」的基线来自成员完成任务后的「确认节省时间」抽样'),
t('「质量评分」样本不足时显示「数据不足」,不是故障'),
t('「治理风险」统计失败的工具调用与写操作次数'),
],
},
{
title: t('下钻分析'),
detail: t('从汇总数字追到具体任务与版本'),
points: [
t('「成本对账」三栏:运行结算、消费明细、差额;差额红色需关注'),
t('「质量告警」每行可「下钻」查看样本任务 ID'),
t('「灰度版本质量对比」输入 Skill ID 可对比各版本首交付通过率'),
],
},
{
title: t('让数据更准'),
detail: t('看板质量取决于回流数据的完整度'),
points: [
t('鼓励成员在任务完成后点 👍/👎 并填写「确认节省时间」'),
t('「网关直连技能使用」需密钥开启「技能注入」后才有数据'),
t('注意:直连面板的 token 与额度是整请求口径,不能跨技能相加'),
],
},
],
faq: [
{
q: t('指标全是 0 或「数据不足」?'),
a: t('刚启用时样本少属正常,随任务量与成员反馈积累会逐步补全'),
},
{
q: t('「重算今日」是干什么的?'),
a: t(
'管理员手动触发当日指标聚合(按 Asia/Shanghai 日期),通常无需使用',
),
},
],
});
return (
<div className='org-effect-page'>
<header className='org-effect-hero'>
<div>
<Title heading={2}>{t('效能分析')}</Title>
<Text type='tertiary'>
{t('回答谁在用、节省多少时间、成本是否对账、质量与安全是否改善。')}
</Text>
</div>
<div className='org-effect-toolbar'>
<PageGuideTrigger guide={guide} />
<Select
value={dimension}
optionList={dimensions}
onChange={setDimension}
/>
{dimension !== 'organization' && (
<InputNumber
min={1}
value={dimensionId}
onChange={setDimensionId}
/>
)}
<Button
icon={<RefreshCw size={15} />}
loading={loading}
onClick={load}
>
{t('刷新')}
</Button>
{canManagePolicy && (
<Button onClick={aggregateToday}>{t('重算今日')}</Button>
)}
</div>
</header>
<PageGuideDrawer guide={guide} />
<section className='org-effect-grid'>
{cards.map(({ label, value: cardValue, detail, icon: Icon }) => (
<article className='org-effect-card' key={label}>
<Icon size={20} />
<Text>{label}</Text>
<strong>{cardValue}</strong>
<small>{detail}</small>
</article>
))}
</section>
<OrgPanel title={t('网关直连技能使用(近 30 天)')}>
{directUsage.length === 0 ? (
<Text type='tertiary'>
{t(
'暂无数据。开启密钥的「技能注入」后,用该密钥直连调用的技能使用情况会回流到这里。',
)}
</Text>
) : (
<>
<Text type='tertiary' size='small'>
{t(
'统计口径:token 与额度是整条请求的量级,多技能同时命中时全额计入每个技能,不是按技能分摊的成本,勿相加。',
)}
</Text>
<Table
size='small'
pagination={false}
dataSource={directUsage}
rowKey='skill_id'
columns={[
{
title: t('技能'),
dataIndex: 'name',
render: (name, record) =>
name || record.canonical_id || `#${record.skill_id}`,
},
{ title: t('调用次数'), dataIndex: 'request_count' },
{
title: t('占比'),
dataIndex: 'share_percent',
render: (share) => `${(share || 0).toFixed(1)}%`,
},
{
title: t('提示词 token'),
dataIndex: 'prompt_tokens',
render: (tokens) => (tokens || 0).toLocaleString(),
},
]}
/>
</>
)}
</OrgPanel>
<div className='org-effect-columns'>
<OrgPanel title={t('成本对账')}>
<div className='org-effect-reconcile'>
<span>{t('运行结算')}</span>
<b>{Math.round(value('efficiency.quota')).toLocaleString()}</b>
<span>{t('消费明细')}</span>
<b>
{Math.round(
value('efficiency.settlement_quota') +
value('efficiency.adjustment_quota'),
).toLocaleString()}
</b>
<span>{t('差额')}</span>
<b
className={
value('efficiency.reconciliation_gap') ? 'is-risk' : 'is-ok'
}
>
{Math.round(
value('efficiency.reconciliation_gap'),
).toLocaleString()}
</b>
</div>
</OrgPanel>
<OrgPanel title={t('质量告警')}>
{isMobile ? (
<div className='org-effect-mobile-list'>
{(data.alerts || []).map((row) => (
<article key={row.id}>
<div>
<strong>Skill #{row.dimension_id}</strong>
<Tag color={row.status === 'open' ? 'red' : 'green'}>
{row.status}
</Tag>
</div>
<span>
{t('评分')}: {Number(row.score).toFixed(1)}
</span>
<span>
{t('样本')}: {row.sample_count}
</span>
<Button size='small' onClick={() => showAlertSamples(row)}>
{t('下钻')}
</Button>
</article>
))}
</div>
) : (
<Table
size='small'
pagination={false}
dataSource={data.alerts || []}
columns={[
{ title: t('Skill'), dataIndex: 'dimension_id' },
{
title: t('评分'),
dataIndex: 'score',
render: (score) => Number(score).toFixed(1),
},
{ title: t('样本'), dataIndex: 'sample_count' },
{
title: t('样本任务'),
render: (_, row) => (
<Button size='small' onClick={() => showAlertSamples(row)}>
{t('下钻')}
</Button>
),
},
{
title: t('状态'),
dataIndex: 'status',
render: (status) => (
<Tag color={status === 'open' ? 'red' : 'green'}>
{status}
</Tag>
),
},
]}
/>
)}
</OrgPanel>
</div>
<OrgPanel
title={t('灰度版本质量对比')}
actions={
<div className='flex gap-2'>
<InputNumber
min={1}
placeholder='Skill ID'
value={comparisonSkillId}
onChange={setComparisonSkillId}
/>
<Button onClick={loadComparison}>{t('下钻版本')}</Button>
</div>
}
>
{isMobile ? (
<div className='org-effect-mobile-list'>
{comparison.map((row) => (
<article key={row.version_id}>
<strong>
{t('版本')} #{row.version_id}
</strong>
<span>
{t('首次交付样本')}: {row.first_delivery_count}
</span>
<span>
{t('首次交付通过率')}:{' '}
{row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
: t('数据不足')}
</span>
<span>
{t('退回率')}:{' '}
{row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%`
: t('数据不足')}
</span>
<span>
{t('平均成本')}:{' '}
{row.data_sufficient
? Number(row.average_quota).toFixed(1)
: t('数据不足')}
</span>
</article>
))}
</div>
) : (
<Table
pagination={false}
dataSource={comparison}
columns={[
{ title: t('版本'), dataIndex: 'version_id' },
{ title: t('首次交付样本'), dataIndex: 'first_delivery_count' },
{
title: t('首次交付通过率'),
render: (_, row) =>
row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
: t('数据不足'),
},
{
title: t('退回率'),
render: (_, row) =>
row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%`
: t('数据不足'),
},
{
title: t('平均成本'),
render: (_, row) =>
row.data_sufficient
? Number(row.average_quota).toFixed(1)
: t('数据不足'),
},
]}
/>
)}
</OrgPanel>
<OrgPanel
title={t('Skill A/B 实验')}
actions={
canManageSkills ? (
<Button onClick={() => setExperimentVisible(true)}>
{t('新建实验')}
</Button>
) : null
}
>
{isMobile ? (
<div className='org-effect-mobile-list'>
{experiments.map((row) => (
<article key={row.id}>
<div>
<strong>{row.name}</strong>
<Tag>{row.status}</Tag>
</div>
<span>Skill #{row.skill_id}</span>
<span>
A / B: {row.version_a_id} / {row.version_b_id}
</span>
<span>
{t('目标样本')}: {row.target_sample}
</span>
{canManageSkills && (
<div className='flex gap-1'>
<Button
size='small'
type={row.status === 'running' ? 'danger' : 'primary'}
disabled={!['draft', 'running'].includes(row.status)}
onClick={() =>
experimentAction(
row,
row.status === 'draft' ? 'start' : 'stop',
)
}
>
{row.status === 'draft' ? t('开始') : t('停止并回退')}
</Button>
<Popconfirm
title={t('确认删除该实验?')}
content={t(
'删除后实验配置与分桶结果一并清除,起停记录已在审计中留痕。',
)}
onConfirm={() => deleteExperiment(row)}
>
<Button
size='small'
theme='light'
type='danger'
disabled={row.status === 'running'}
>
{t('删除')}
</Button>
</Popconfirm>
</div>
)}
</article>
))}
</div>
) : (
<Table
pagination={false}
dataSource={experiments}
columns={[
{ title: t('实验'), dataIndex: 'name' },
{ title: 'Skill', dataIndex: 'skill_id' },
{
title: 'A / B',
render: (_, row) => `${row.version_a_id} / ${row.version_b_id}`,
},
{ title: t('目标样本'), dataIndex: 'target_sample' },
{
title: t('状态'),
dataIndex: 'status',
render: (status) => <Tag>{status}</Tag>,
},
{
title: t('操作'),
render: (_, row) =>
canManageSkills && (
<div className='flex gap-1'>
<Button
size='small'
type={row.status === 'running' ? 'danger' : 'primary'}
disabled={!['draft', 'running'].includes(row.status)}
onClick={() =>
experimentAction(
row,
row.status === 'draft' ? 'start' : 'stop',
)
}
>
{row.status === 'draft' ? t('开始') : t('停止并回退')}
</Button>
<Popconfirm
title={t('确认删除该实验?')}
content={t(
'删除后实验配置与分桶结果一并清除,起停记录已在审计中留痕。',
)}
onConfirm={() => deleteExperiment(row)}
>
<Button
size='small'
theme='light'
type='danger'
disabled={row.status === 'running'}
>
{t('删除')}
</Button>
</Popconfirm>
</div>
),
},
]}
/>
)}
</OrgPanel>
<Modal
title={t('新建 Skill A/B 实验')}
visible={experimentVisible}
onCancel={() => setExperimentVisible(false)}
onOk={createExperiment}
width={680}
>
<div className='org-effect-form'>
<Input
placeholder={t('实验名称')}
value={experiment.name}
onChange={(name) => setExperiment({ ...experiment, name })}
/>
{[
'skill_id',
'version_a_id',
'version_b_id',
'stable_version_id',
].map((key) => (
<InputNumber
key={key}
min={1}
placeholder={key}
value={experiment[key]}
onChange={(next) => setExperiment({ ...experiment, [key]: next })}
/>
))}
<TextArea
placeholder={t('实验假设')}
value={experiment.hypothesis}
onChange={(hypothesis) =>
setExperiment({ ...experiment, hypothesis })
}
/>
<Input
placeholder={t('主指标')}
value={experiment.primary_metric}
onChange={(primary_metric) =>
setExperiment({ ...experiment, primary_metric })
}
/>
<Input
placeholder={t('护栏指标,逗号分隔')}
value={experiment.guardrail_metrics}
onChange={(guardrail_metrics) =>
setExperiment({ ...experiment, guardrail_metrics })
}
/>
<InputNumber
min={10}
placeholder={t('目标样本')}
value={experiment.target_sample}
onChange={(target_sample) =>
setExperiment({ ...experiment, target_sample })
}
/>
<TextArea
placeholder={t('停止条件 JSON')}
value={experiment.stop_conditions}
onChange={(stop_conditions) =>
setExperiment({ ...experiment, stop_conditions })
}
/>
</div>
</Modal>
</div>
);
};
export default OrgEffectiveness;