import { Popconfirm } from '@/components/ui'; import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm'; import { formatIdReference, formatNumber, formatPercent, } from '../../helpers/safeDisplay'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { Plus as ActionPlus, RefreshCw as ActionRefreshCw, Search as ActionSearch, } from '@/components/common/icons/ActionIcons'; import { Card } from 'antd'; import TableEmpty from '../../components/common/table/TableEmpty'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { Button, Input, InputNumber, Select, Table, Tag, TextArea, Toast, } 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 { OrgListCard } from './components/OrgListCard'; import OrgModal from './components/OrgModal'; import OrgPageHeader from './components/OrgPageHeader'; import './org-effectiveness.css'; 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 false; } 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 = []; } OrgModal.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') ? formatNumber(value('quality.score', true), 1, t('数据不足')) : 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 (
setExperiment({ ...experiment, name })} /> {[ 'skill_id', 'version_a_id', 'version_b_id', 'stable_version_id', ].map((key) => ( setExperiment({ ...experiment, [key]: next })} /> ))}