/*
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 .
For commercial licensing, please contact support@quantumnous.com
*/
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
Button,
Input,
InputNumber,
Modal,
Popconfirm,
Select,
Table,
Tag,
TextArea,
Toast,
Typography,
} from '@/components/ui';
import { Activity, FlaskConical, Gauge, 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';
import OrgBreadcrumb from './components/OrgBreadcrumb';
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: (
{ids.map((id) => (
{id}
))}
),
});
};
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 (
{cards.map(({ label, value: cardValue, detail, icon: Icon }) => (
{label}
{cardValue}
{detail}
))}
{directUsage.length === 0 ? (
{t(
'暂无数据。开启密钥的「技能注入」后,用该密钥直连调用的技能使用情况会回流到这里。',
)}
) : (
<>
{t(
'统计口径:token 与额度是整条请求的量级,多技能同时命中时全额计入每个技能,不是按技能分摊的成本,勿相加。',
)}
name ||
record.canonical_id ||
formatIdReference(record.skill_id),
},
{ title: t('调用次数'), dataIndex: 'request_count' },
{
title: t('占比'),
dataIndex: 'share_percent',
render: (share) => formatPercent(share, 1),
},
{
title: t('提示词 token'),
dataIndex: 'prompt_tokens',
render: (tokens) => (tokens || 0).toLocaleString(),
},
]}
/>
>
)}
{t('运行结算')}
{Math.round(value('efficiency.quota')).toLocaleString()}
{t('消费明细')}
{Math.round(
value('efficiency.settlement_quota') +
value('efficiency.adjustment_quota'),
).toLocaleString()}
{t('差额')}
{Math.round(
value('efficiency.reconciliation_gap'),
).toLocaleString()}
{isMobile ? (
{(data.alerts || []).map((row) => (
{t('技能 #{{id}}', { id: row.dimension_id })}
{row.status}
{t('评分')}: {Number(row.score).toFixed(1)}
{t('样本')}: {row.sample_count}
))}
) : (
Number(score).toFixed(1),
},
{ title: t('样本'), dataIndex: 'sample_count' },
{
title: t('样本任务'),
render: (_, row) => (
),
},
{
title: t('状态'),
dataIndex: 'status',
render: (status) => (
{status}
),
},
]}
/>
)}
}
>
{isMobile ? (
{comparison.map((row) => (
{t('版本')} #{row.version_id}
{t('首次交付样本')}: {row.first_delivery_count}
{t('首次交付通过率')}:{' '}
{row.data_sufficient
? formatPercent(
Number(row.first_delivery_pass_rate) * 100,
1,
)
: t('数据不足')}
{t('退回率')}:{' '}
{row.data_sufficient
? formatPercent(Number(row.return_rate) * 100, 1)
: t('数据不足')}
{t('平均成本')}:{' '}
{row.data_sufficient
? Number(row.average_quota).toFixed(1)
: t('数据不足')}
))}
) : (
row.data_sufficient
? formatPercent(
Number(row.first_delivery_pass_rate) * 100,
1,
)
: t('数据不足'),
},
{
title: t('退回率'),
render: (_, row) =>
row.data_sufficient
? formatPercent(Number(row.return_rate) * 100, 1)
: t('数据不足'),
},
{
title: t('平均成本'),
render: (_, row) =>
row.data_sufficient
? Number(row.average_quota).toFixed(1)
: t('数据不足'),
},
]}
/>
)}
setExperimentVisible(true)}>
{t('新建实验')}
) : null
}
>
{isMobile ? (
{experiments.map((row) => (
{row.name}
{row.status}
{t('技能 #{{id}}', { id: row.skill_id })}
{I18N_TECHNICAL_TEXT.AB_METRICS_PREFIX} {row.version_a_id} /{' '}
{row.version_b_id}
{t('目标样本')}: {row.target_sample}
{canManageSkills && (
deleteExperiment(row)}
>
)}
))}
) : (
`${row.version_a_id} / ${row.version_b_id}`,
},
{ title: t('目标样本'), dataIndex: 'target_sample' },
{
title: t('状态'),
dataIndex: 'status',
render: (status) => {status},
},
{
title: t('操作'),
render: (_, row) =>
canManageSkills && (
deleteExperiment(row)}
>
),
},
]}
/>
)}
setExperimentVisible(false)}
onOk={createExperiment}
width={680}
>
setExperiment({ ...experiment, name })}
/>
{[
'skill_id',
'version_a_id',
'version_b_id',
'stable_version_id',
].map((key) => (
setExperiment({ ...experiment, [key]: next })}
/>
))}
);
};
export default OrgEffectiveness;