sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization
- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等, semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi - 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复 - 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志 - 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求 - 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新 - 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
This commit is contained in:
@@ -0,0 +1,379 @@
|
||||
/*
|
||||
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, { useMemo, useState, useEffect } from 'react';
|
||||
import { Button, Empty, Segmented, Skeleton, theme } from 'antd';
|
||||
import { VChart } from '@visactor/react-vchart';
|
||||
import { Info } from 'lucide-react';
|
||||
import { RefreshCw } from '@/components/common/icons/ActionIcons';
|
||||
import { ConsoleDrawer } from '@/components/console/ConsolePrimitives';
|
||||
import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly';
|
||||
import { useIsMobile } from '../../hooks/common/useIsMobile';
|
||||
|
||||
// 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。
|
||||
// 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。
|
||||
const abbr = (n) => {
|
||||
const v = Number(n) || 0;
|
||||
const abs = Math.abs(v);
|
||||
if (abs >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
|
||||
if (abs >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
|
||||
if (abs >= 1e3) return `${(v / 1e3).toFixed(2)}K`;
|
||||
return `${v}`;
|
||||
};
|
||||
|
||||
const money = (n) => {
|
||||
const v = Number(n) || 0;
|
||||
if (Math.abs(v) >= 1000) return `$${(v / 1000).toFixed(2)}K`;
|
||||
return `$${v.toFixed(2)}`;
|
||||
};
|
||||
|
||||
// unix 秒 → 本地「MM-DD HH:00」。后端返回的是小时桶起点,整点整分,不做四舍五入。
|
||||
const hourLabel = (unixSec) => {
|
||||
const d = new Date((Number(unixSec) || 0) * 1000);
|
||||
const p = (x) => String(x).padStart(2, '0');
|
||||
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:00`;
|
||||
};
|
||||
|
||||
const SERIES_COLORS = {
|
||||
input: '#3b82f6',
|
||||
output: '#10b981',
|
||||
cacheCreation: '#f59e0b',
|
||||
cacheRead: '#8b5cf6',
|
||||
hitRate: '#ef4444',
|
||||
};
|
||||
|
||||
const StatBlock = ({ label, value, sub, color }) => (
|
||||
<div className='flex-1 min-w-[110px]'>
|
||||
<div className='text-xs text-[var(--text-secondary)] mb-1'>{label}</div>
|
||||
<div
|
||||
className='text-lg font-semibold'
|
||||
style={color ? { color } : undefined}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
{sub ? (
|
||||
<div className='text-xs text-[var(--text-secondary)] mt-0.5'>{sub}</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
/**
|
||||
* 单企业逐小时缓存命中率报表抽屉。
|
||||
*
|
||||
* 数据源是企业小时聚合表,不是 logs —— 口径与成本理由见
|
||||
* model/analytics_org_cache.go 顶部注释。
|
||||
*/
|
||||
const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
|
||||
const isMobile = useIsMobile();
|
||||
const { token } = theme.useToken();
|
||||
const [hours, setHours] = useState(24);
|
||||
// 关闭后重开默认回到 24h:上次选了 7d 不该粘到下一家企业上。
|
||||
useEffect(() => {
|
||||
if (!visible) setHours(24);
|
||||
}, [visible]);
|
||||
|
||||
const orgId = visible ? org?.org_id : null;
|
||||
const { data, loading, error, refresh } = useOrgCacheHourly(orgId, hours);
|
||||
|
||||
const points = useMemo(() => data?.points || [], [data]);
|
||||
const totals = data?.totals || null;
|
||||
// 全窗口零流量:补出来的点都是 0,画出来是一条贴底的直线,不如直接给空态。
|
||||
const hasTraffic = points.some((p) => (p.requests || 0) > 0);
|
||||
|
||||
const spec = useMemo(() => {
|
||||
if (!points.length || !hasTraffic) return null;
|
||||
|
||||
const inputKey = t('输入');
|
||||
const outputKey = t('输出');
|
||||
const creationKey = t('写缓存');
|
||||
const readKey = t('读缓存');
|
||||
|
||||
const stacked = [];
|
||||
const rateRows = [];
|
||||
points.forEach((p) => {
|
||||
const label = hourLabel(p.hour);
|
||||
stacked.push(
|
||||
{ hour: label, kind: inputKey, value: p.input || 0 },
|
||||
{ hour: label, kind: outputKey, value: p.output || 0 },
|
||||
{ hour: label, kind: creationKey, value: p.cache_creation || 0 },
|
||||
{ hour: label, kind: readKey, value: p.cache_read || 0 },
|
||||
);
|
||||
rateRows.push({
|
||||
hour: label,
|
||||
// 该小时无流量时后端给 null;这里原样传下去并让序列 invalidType='break',
|
||||
// 折线在空洞处断开,而不是掉到 0% 被误读成命中率暴跌。
|
||||
hit_rate:
|
||||
p.hit_rate === null || p.hit_rate === undefined ? null : p.hit_rate,
|
||||
actual_cost: p.actual_cost || 0,
|
||||
requests: p.requests || 0,
|
||||
});
|
||||
});
|
||||
|
||||
const rateKey = t('缓存命中率');
|
||||
|
||||
return {
|
||||
type: 'common',
|
||||
data: [
|
||||
{ id: 'tokens', values: stacked },
|
||||
{ id: 'rate', values: rateRows },
|
||||
],
|
||||
series: [
|
||||
{
|
||||
type: 'bar',
|
||||
id: 'tokens',
|
||||
dataIndex: 0,
|
||||
xField: 'hour',
|
||||
yField: 'value',
|
||||
seriesField: 'kind',
|
||||
stack: true,
|
||||
bar: { style: { cornerRadius: [0, 0, 0, 0] } },
|
||||
tooltip: {
|
||||
visible: true,
|
||||
mark: {
|
||||
content: [
|
||||
{
|
||||
key: (datum) => datum?.kind,
|
||||
value: (datum) => `${abbr(datum?.value)} tokens`,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
id: 'rate',
|
||||
name: rateKey,
|
||||
dataIndex: 1,
|
||||
xField: 'hour',
|
||||
yField: 'hit_rate',
|
||||
// 空洞断线,不要 connectNulls 把两段无关的曲线连起来
|
||||
invalidType: 'break',
|
||||
point: {
|
||||
visible: true,
|
||||
size: 3,
|
||||
style: { fill: SERIES_COLORS.hitRate },
|
||||
},
|
||||
line: { style: { stroke: SERIES_COLORS.hitRate, lineWidth: 2 } },
|
||||
tooltip: {
|
||||
visible: true,
|
||||
mark: {
|
||||
content: [
|
||||
{
|
||||
key: () => rateKey,
|
||||
value: (datum) =>
|
||||
datum?.hit_rate === null || datum?.hit_rate === undefined
|
||||
? t('无流量')
|
||||
: `${Number(datum.hit_rate).toFixed(1)}%`,
|
||||
},
|
||||
{
|
||||
key: () => t('实际消费'),
|
||||
value: (datum) => money(datum?.actual_cost),
|
||||
},
|
||||
{
|
||||
key: () => t('请求数'),
|
||||
value: (datum) => (datum?.requests || 0).toLocaleString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
color: [
|
||||
SERIES_COLORS.input,
|
||||
SERIES_COLORS.output,
|
||||
SERIES_COLORS.cacheCreation,
|
||||
SERIES_COLORS.cacheRead,
|
||||
],
|
||||
legends: {
|
||||
visible: true,
|
||||
orient: 'top',
|
||||
position: 'middle',
|
||||
padding: { top: 0, bottom: 12, left: 0, right: 0 },
|
||||
layoutType: 'normal',
|
||||
},
|
||||
tooltip: { visible: true, dimension: { visible: true } },
|
||||
crosshair: { xField: { visible: true, line: { visible: true } } },
|
||||
axes: [
|
||||
{
|
||||
orient: 'bottom',
|
||||
// 7d = 168 个桶,标签必须自动抽稀,否则重叠成黑条
|
||||
label: { style: { angle: -45 }, autoLimit: true, autoHide: true },
|
||||
},
|
||||
{
|
||||
orient: 'left',
|
||||
title: { visible: true, text: t('Token 数') },
|
||||
label: { formatMethod: (v) => abbr(v) },
|
||||
seriesIndex: [0],
|
||||
},
|
||||
{
|
||||
orient: 'right',
|
||||
title: { visible: true, text: t('命中率 (%)') },
|
||||
// 固定 0~100:让曲线的高低在不同企业、不同窗口之间可比。
|
||||
// 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。
|
||||
min: 0,
|
||||
max: 100,
|
||||
label: { formatMethod: (v) => `${Math.round(v)}%` },
|
||||
seriesIndex: [1],
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [points, hasTraffic, t]);
|
||||
|
||||
const orgTitle = org?.org_name || (org ? `${t('企业')} ${org.org_id}` : '');
|
||||
|
||||
return (
|
||||
<ConsoleDrawer
|
||||
open={visible}
|
||||
onClose={onClose}
|
||||
size={isMobile ? '100%' : 820}
|
||||
title={
|
||||
<div className='flex items-center gap-2 flex-wrap'>
|
||||
<span className='font-semibold'>{t('缓存命中率明细')}</span>
|
||||
<span className='text-sm font-normal text-[var(--text-secondary)]'>
|
||||
{orgTitle}
|
||||
</span>
|
||||
{org?.org_id ? (
|
||||
<span className='text-xs font-normal text-[var(--text-secondary)]'>
|
||||
#{org.org_id}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className='flex items-center justify-between gap-3 flex-wrap mb-4'>
|
||||
<Segmented
|
||||
value={hours}
|
||||
onChange={setHours}
|
||||
options={[
|
||||
{ label: t('近 24 小时'), value: 24 },
|
||||
{ label: t('近 7 天'), value: 24 * 7 },
|
||||
]}
|
||||
/>
|
||||
<Button
|
||||
icon={<RefreshCw size={16} />}
|
||||
onClick={refresh}
|
||||
loading={loading}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{totals ? (
|
||||
<div
|
||||
className='flex flex-wrap gap-4 px-4 py-3 mb-4 rounded-lg'
|
||||
style={{ background: token.colorFillAlter }}
|
||||
>
|
||||
<StatBlock
|
||||
label={t('缓存命中率')}
|
||||
value={
|
||||
totals.hit_rate === null || totals.hit_rate === undefined
|
||||
? '--'
|
||||
: `${Number(totals.hit_rate).toFixed(2)}%`
|
||||
}
|
||||
sub={t('按 token 加权')}
|
||||
color={SERIES_COLORS.hitRate}
|
||||
/>
|
||||
<StatBlock label={t('输入')} value={abbr(totals.input)} />
|
||||
<StatBlock label={t('输出')} value={abbr(totals.output)} />
|
||||
<StatBlock
|
||||
label={t('写缓存')}
|
||||
value={abbr(totals.cache_creation)}
|
||||
color={SERIES_COLORS.cacheCreation}
|
||||
/>
|
||||
<StatBlock
|
||||
label={t('读缓存')}
|
||||
value={abbr(totals.cache_read)}
|
||||
color={SERIES_COLORS.cacheRead}
|
||||
/>
|
||||
<StatBlock
|
||||
label={t('实际消费')}
|
||||
value={money(totals.actual_cost)}
|
||||
sub={t('{{n}} 次请求', {
|
||||
n: (totals.requests || 0).toLocaleString(),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{loading && !points.length ? (
|
||||
<Skeleton active title={false} paragraph={{ rows: 8 }} />
|
||||
) : error ? (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
className='py-12'
|
||||
description={
|
||||
<>
|
||||
<div className='text-[var(--text-primary)]'>{t('加载失败')}</div>
|
||||
<div>{error}</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
) : spec ? (
|
||||
<VChart
|
||||
spec={spec}
|
||||
option={{ mode: 'desktop-browser' }}
|
||||
style={{ height: 360 }}
|
||||
/>
|
||||
) : (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
className='py-12'
|
||||
description={
|
||||
<>
|
||||
<div className='text-[var(--text-primary)]'>
|
||||
{t('该时间段内没有流量')}
|
||||
</div>
|
||||
<div>{t('所选窗口内这家企业没有产生可统计的请求')}</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 口径脚注:不写清楚的话,运营会拿这张图去对账单,然后发现对不上。 */}
|
||||
<div
|
||||
className='mt-4 px-3 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed rounded-md'
|
||||
style={{ background: token.colorFillAlter }}
|
||||
>
|
||||
<div className='flex items-start gap-1.5'>
|
||||
<Info aria-hidden className='w-3.5 h-3.5 mt-0.5 flex-shrink-0' />
|
||||
<div>
|
||||
<div>
|
||||
{t(
|
||||
'命中率 = 读缓存 ÷(输入 + 写缓存 + 读缓存)。输出 token 与缓存无关,不计入分母。',
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
{t(
|
||||
'数据来自企业小时聚合表,按自然小时切桶;最后一个小时尚未走完,数字仍在累加。',
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
{t(
|
||||
'「实际消费」为本平台实际计费金额;标准价对比待官方价目表配置完成后再上。',
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ConsoleDrawer>
|
||||
);
|
||||
};
|
||||
|
||||
export { abbr as formatTokenAbbr, money as formatUsd, hourLabel };
|
||||
export default OrgCacheHourlySheet;
|
||||
@@ -0,0 +1,407 @@
|
||||
/*
|
||||
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, { useState, useCallback } from 'react';
|
||||
import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd';
|
||||
import { ArrowDown } from 'lucide-react';
|
||||
import {
|
||||
ConsoleCard,
|
||||
ConsoleTable,
|
||||
} from '@/components/console/ConsolePrimitives';
|
||||
import OrgCacheHourlySheet from './OrgCacheHourlySheet';
|
||||
|
||||
// 并发占用比对应的色阶:接近上限提前变黄,打满变红。
|
||||
const WARN_RATIO = 0.8;
|
||||
|
||||
// 缓存命中率色阶。90% 是与客户约定的 KPI 线(严格口径),所以绿/黄的分界放在这里;
|
||||
// 70% 以下基本意味着会话结构出了问题(深轮首触、子代理扇出),标红提示排查。
|
||||
const CACHE_GOOD = 90;
|
||||
const CACHE_WARN = 70;
|
||||
|
||||
// 色阶取主题语义 token(成功 / 警告 / 错误 / 主色),阈值不变
|
||||
const cacheRateColor = (rate, token) => {
|
||||
if (rate >= CACHE_GOOD) return token.colorSuccess;
|
||||
if (rate >= CACHE_WARN) return token.colorWarning;
|
||||
return token.colorError;
|
||||
};
|
||||
|
||||
const concurrencyColor = (ratio, token) => {
|
||||
if (ratio >= 1) return token.colorError;
|
||||
if (ratio >= WARN_RATIO) return token.colorWarning;
|
||||
return token.colorPrimary;
|
||||
};
|
||||
|
||||
// 可点击的表头:点一下换排序维度,始终降序(后端只支持降序 TOP-N)。
|
||||
const SortableTitle = ({ label, field, sortBy, onSort }) => {
|
||||
const active = sortBy === field;
|
||||
return (
|
||||
<span
|
||||
role='button'
|
||||
tabIndex={0}
|
||||
aria-pressed={active}
|
||||
className={`inline-flex items-center gap-1 cursor-pointer select-none transition-colors ${
|
||||
active
|
||||
? 'text-brand font-semibold'
|
||||
: 'text-[var(--text-secondary)] hover:text-brand'
|
||||
}`}
|
||||
onClick={() => onSort(field)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
onSort(field);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
<ArrowDown
|
||||
aria-hidden
|
||||
className={`w-3 h-3 ${active ? 'opacity-100' : 'opacity-25'}`}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const OrgRealtimeUsage = ({
|
||||
data,
|
||||
loading,
|
||||
sortBy,
|
||||
onSortChange,
|
||||
limit = 10,
|
||||
title,
|
||||
icon,
|
||||
t,
|
||||
}) => {
|
||||
const { token } = theme.useToken();
|
||||
const items = data?.items || [];
|
||||
const windowSeconds = data?.window_seconds || 60;
|
||||
|
||||
// 抽屉状态放在这里而不是提到页面级:它完全由本表的行点击驱动,
|
||||
// 页面不需要知道它的存在。
|
||||
const [detailOrg, setDetailOrg] = useState(null);
|
||||
const closeDetail = useCallback(() => setDetailOrg(null), []);
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('企业'),
|
||||
dataIndex: 'org_name',
|
||||
key: 'org_name',
|
||||
width: 220,
|
||||
fixed: 'left',
|
||||
render: (text, record) => (
|
||||
<div className='flex items-center gap-2 min-w-0'>
|
||||
<span className='text-sm font-medium truncate' title={text || ''}>
|
||||
{text || `${t('企业')} ${record.org_id}`}
|
||||
</span>
|
||||
<span className='text-xs text-[var(--text-secondary)] flex-shrink-0'>
|
||||
#{record.org_id}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<SortableTitle
|
||||
label={t('并发占用')}
|
||||
field='concurrency'
|
||||
sortBy={sortBy}
|
||||
onSort={onSortChange}
|
||||
/>
|
||||
),
|
||||
dataIndex: 'concurrency',
|
||||
key: 'concurrency',
|
||||
width: 220,
|
||||
render: (val, record) => {
|
||||
const current = val || 0;
|
||||
const limit = record.max_concurrency || 0;
|
||||
// 0 表示未配置上限:不画进度条(没有分母,画出来就是误导)。
|
||||
if (limit <= 0) {
|
||||
return (
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-sm font-semibold text-[var(--text-primary)]'>
|
||||
{current.toLocaleString()}
|
||||
</span>
|
||||
<span className='text-xs text-[var(--text-secondary)]'>
|
||||
/ {t('不限制')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const ratio = current / limit;
|
||||
const color = concurrencyColor(ratio, token);
|
||||
return (
|
||||
<div className='min-w-0'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-sm font-semibold' style={{ color }}>
|
||||
{current.toLocaleString()}
|
||||
</span>
|
||||
<span className='text-xs text-[var(--text-secondary)]'>
|
||||
/ {limit.toLocaleString()}
|
||||
</span>
|
||||
{record.rejected > 0 && (
|
||||
<Tooltip
|
||||
title={t(
|
||||
'近 {{seconds}} 秒内有 {{times}} 次请求因超过并发上限被限流(429)',
|
||||
{
|
||||
seconds: windowSeconds,
|
||||
times: record.rejected,
|
||||
},
|
||||
)}
|
||||
>
|
||||
<Tag color='error' variant='filled'>
|
||||
{t('限流中')}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<Progress
|
||||
percent={Math.min(ratio * 100, 100)}
|
||||
showInfo={false}
|
||||
size='small'
|
||||
className='mt-1'
|
||||
strokeColor={color}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<SortableTitle
|
||||
label='RPM'
|
||||
field='rpm'
|
||||
sortBy={sortBy}
|
||||
onSort={onSortChange}
|
||||
/>
|
||||
),
|
||||
dataIndex: 'rpm',
|
||||
key: 'rpm',
|
||||
width: 140,
|
||||
align: 'right',
|
||||
render: (val) => (
|
||||
<span className='text-sm font-semibold text-[var(--text-primary)]'>
|
||||
{(val || 0).toLocaleString()}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<SortableTitle
|
||||
label='TPM'
|
||||
field='tpm'
|
||||
sortBy={sortBy}
|
||||
onSort={onSortChange}
|
||||
/>
|
||||
),
|
||||
dataIndex: 'tpm',
|
||||
key: 'tpm',
|
||||
width: 180,
|
||||
align: 'right',
|
||||
render: (val) => (
|
||||
<span className='text-sm font-semibold text-brand-deep'>
|
||||
{(val || 0).toLocaleString()}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
// 这一列不可排序:后端的 TOP-N 是按内存计数器(并发/RPM/TPM)排的,
|
||||
// 命中率是取完 TOP-N 之后再补的落库数据,没有「按命中率取前 N 名」这回事。
|
||||
title: (
|
||||
<Tooltip
|
||||
title={t(
|
||||
'近 1 小时的缓存命中率 = 读缓存 ÷(输入 + 写缓存 + 读缓存)。与左侧 RPM/TPM 的 60 秒窗口不同:命中率在分钟级噪声很大,按 60 秒算每次刷新都会跳。点击数字查看逐小时明细。',
|
||||
)}
|
||||
>
|
||||
<span className='inline-flex items-center gap-1 text-[var(--text-secondary)] border-b border-dashed border-[var(--border-subtle)]'>
|
||||
{t('1h 缓存命中率')}
|
||||
</span>
|
||||
</Tooltip>
|
||||
),
|
||||
dataIndex: 'cache_hit_rate',
|
||||
key: 'cache_hit_rate',
|
||||
width: 170,
|
||||
align: 'right',
|
||||
render: (val, record) => {
|
||||
// 分母为 0 = 这一小时没有可统计的 token,不是「命中率 0%」。
|
||||
// 两者混为一谈会让刚接入的企业看起来像缓存全丢。
|
||||
if (!record.cache_tokens) {
|
||||
return (
|
||||
<Tooltip
|
||||
title={
|
||||
data?.cache_degraded
|
||||
? t('缓存数据暂时不可用(小时聚合表查询失败)')
|
||||
: t('近 1 小时没有可统计的 token')
|
||||
}
|
||||
>
|
||||
<span
|
||||
className='text-sm'
|
||||
style={{ color: token.colorTextQuaternary }}
|
||||
>
|
||||
--
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
const rate = val || 0;
|
||||
return (
|
||||
<span
|
||||
role='button'
|
||||
tabIndex={0}
|
||||
className='inline-flex items-center justify-end gap-1 cursor-pointer select-none group'
|
||||
onClick={() => setDetailOrg(record)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
setDetailOrg(record);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className='text-sm font-semibold group-hover:underline'
|
||||
style={{ color: cacheRateColor(rate, token) }}
|
||||
>
|
||||
{rate.toFixed(1)}%
|
||||
</span>
|
||||
<span
|
||||
aria-hidden
|
||||
className='text-xs text-[var(--text-secondary)] group-hover:text-brand'
|
||||
>
|
||||
›
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<ConsoleCard
|
||||
title={
|
||||
<div className='flex items-center justify-between w-full flex-wrap gap-2'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-brand'>{icon}</span>
|
||||
<span className='font-semibold'>{title}</span>
|
||||
<span className='text-xs font-normal text-[var(--text-secondary)] ml-2'>
|
||||
{t('取前 {{limit}} 名', { limit })}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-3'>
|
||||
{data && data.enforced === false && (
|
||||
<Tooltip
|
||||
title={t(
|
||||
'当前只计量不拦截(ORG_CONCURRENCY_LIMIT_ENABLED=false):即使占满上限也不会返回 429',
|
||||
)}
|
||||
>
|
||||
<Tag color='default' variant='filled'>
|
||||
{t('仅观测')}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
{data?.degraded ? (
|
||||
<Tooltip
|
||||
title={t(
|
||||
'未启用 Redis 或心跳异常,当前仅统计本实例的数据,多节点部署时会偏小',
|
||||
)}
|
||||
>
|
||||
<Badge
|
||||
status='warning'
|
||||
text={
|
||||
<span className='text-xs font-normal'>
|
||||
{t('单实例口径')}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip
|
||||
title={t(
|
||||
'统计 {{instances}} 个实例,窗口为近 {{seconds}} 秒滚动',
|
||||
{
|
||||
instances: data?.instances || 1,
|
||||
seconds: windowSeconds,
|
||||
},
|
||||
)}
|
||||
>
|
||||
<Badge
|
||||
status='processing'
|
||||
color={token.colorSuccess}
|
||||
text={
|
||||
<span className='text-xs font-normal'>
|
||||
{t('实时 · 近 {{seconds}} 秒滚动', {
|
||||
seconds: windowSeconds,
|
||||
})}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
styles={{ body: { padding: 0 } }}
|
||||
>
|
||||
{loading && items.length === 0 ? (
|
||||
<div className='px-4 py-6'>
|
||||
<Skeleton active title={false} paragraph={{ rows: 5 }} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ConsoleTable
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
pagination={false}
|
||||
scroll={{ x: 930 }}
|
||||
size='small'
|
||||
rowKey='org_id'
|
||||
locale={{
|
||||
emptyText: (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={t('近 {{seconds}} 秒内没有企业产生请求', {
|
||||
seconds: windowSeconds,
|
||||
})}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
{/* 口径脚注:并发/RPM 只盖同步转发,TPM 还滞后一个请求时长。
|
||||
不写出来的话,运营会拿这张表去对账单,然后发现对不上。 */}
|
||||
<div className='px-4 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed border-t border-[var(--border-subtle)]'>
|
||||
{t(
|
||||
'口径:仅统计 /v1、/v1beta 同步转发接口;Midjourney、Suno、视频与异步图片任务提交后在后台执行,不计入本表。',
|
||||
)}{' '}
|
||||
{t(
|
||||
'RPM 含被限流拒绝的请求;TPM 在请求结束时才计入,长流式请求会在结束的那一秒形成毛刺。',
|
||||
)}{' '}
|
||||
{t(
|
||||
'缓存命中率的窗口是近 1 小时(读企业小时聚合表),与左侧 60 秒窗口的指标不同步。',
|
||||
)}
|
||||
</div>
|
||||
<OrgCacheHourlySheet
|
||||
visible={!!detailOrg}
|
||||
org={detailOrg}
|
||||
onClose={closeDetail}
|
||||
t={t}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</ConsoleCard>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgRealtimeUsage;
|
||||
@@ -286,6 +286,9 @@ const LoginForm = () => {
|
||||
}
|
||||
|
||||
async function handleSubmit(e) {
|
||||
// Semi Form 里的按钮同时具备原生 submit 行为;先阻止浏览器
|
||||
// 刷新/跳转,确保登录请求和 finishLogin 流程完整执行。
|
||||
e?.preventDefault?.();
|
||||
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
|
||||
showInfo(t('请先阅读并同意用户协议和隐私政策'));
|
||||
return;
|
||||
|
||||
@@ -35,6 +35,7 @@ const OrgCredentialResult = ({ creds, onLogin }) => {
|
||||
|
||||
const isPending = creds.status === 'pending';
|
||||
|
||||
// 走公共 copy:HTTP 部署下 navigator.clipboard 为 undefined,直接调用会同步抛错、点了无反应
|
||||
const copy = async (val) => {
|
||||
if (await copyText(val)) {
|
||||
Toast.success(t('已复制到剪贴板'));
|
||||
|
||||
@@ -95,11 +95,11 @@ const PasswordResetConfirm = () => {
|
||||
if (success) {
|
||||
let password = res.data.data;
|
||||
setNewPassword(password);
|
||||
// 复制发生在异步请求之后,已脱离用户点击手势,降级复制可能失败;失败时只展示密码
|
||||
if (await copy(password)) {
|
||||
showNotice(`${t('密码已重置并已复制到剪贴板:')} ${password}`);
|
||||
} else {
|
||||
showNotice(t('密码已重置'));
|
||||
showError(t('复制失败,请手动复制'));
|
||||
showNotice(`${t('密码已重置')}:${password}`);
|
||||
}
|
||||
} else {
|
||||
showError(message);
|
||||
|
||||
@@ -48,7 +48,9 @@ export default function ConsolePageContainer({ children }) {
|
||||
data-console-page={page.key}
|
||||
style={themeStyle}
|
||||
>
|
||||
<header className='console-page-header'>
|
||||
<header
|
||||
className={`console-page-header${page.hideHeading ? ' console-page-header--crumb-only' : ''}`}
|
||||
>
|
||||
<Breadcrumb
|
||||
className='console-breadcrumb'
|
||||
items={page.breadcrumbs.map((item, index) => ({
|
||||
@@ -61,15 +63,17 @@ export default function ConsolePageContainer({ children }) {
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
<div className='console-page-header-main'>
|
||||
<div className='console-page-heading'>
|
||||
<h1 className='console-page-title'>{t(page.title)}</h1>
|
||||
<p className='console-page-description'>
|
||||
{t(`consoleUi.descriptions.${page.description}`)}
|
||||
</p>
|
||||
{!page.hideHeading && (
|
||||
<div className='console-page-header-main'>
|
||||
<div className='console-page-heading'>
|
||||
<h1 className='console-page-title'>{t(page.title)}</h1>
|
||||
<p className='console-page-description'>
|
||||
{t(`consoleUi.descriptions.${page.description}`)}
|
||||
</p>
|
||||
</div>
|
||||
<div className='console-page-actions' ref={setActionsTarget} />
|
||||
</div>
|
||||
<div className='console-page-actions' ref={setActionsTarget} />
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
<div className='console-page-body'>{children}</div>
|
||||
</main>
|
||||
|
||||
@@ -20,6 +20,10 @@
|
||||
.console-page-header {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
/* 页面自带标题时外壳只保留面包屑:面包屑到页面标题的 24px 由面包屑下边距提供 */
|
||||
.console-page-header--crumb-only {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.console-page .console-breadcrumb.ant-breadcrumb {
|
||||
margin-bottom: var(--console-space-3);
|
||||
font-size: 12px;
|
||||
|
||||
@@ -52,7 +52,21 @@ export const consolePages = [
|
||||
description: 'demo-reservations',
|
||||
},
|
||||
{ key: 'personal', title: '个人设置', description: 'personal' },
|
||||
{ key: 'my-commission', title: '我的提成', description: 'my-commission' },
|
||||
{
|
||||
key: 'my-commission',
|
||||
title: '我的提成',
|
||||
description: 'my-commission',
|
||||
// 伙伴工作台自带随子视图切换的标题与左侧导航,外壳只保留面包屑
|
||||
hideHeading: true,
|
||||
},
|
||||
{
|
||||
key: 'commission',
|
||||
title: '分佣管理',
|
||||
description: 'commission',
|
||||
// 页面自带随子视图切换的标题(合作伙伴 / 分佣档位…),外壳只保留面包屑
|
||||
hideHeading: true,
|
||||
},
|
||||
{ key: 'smart-router', title: '智能路由', description: 'smart-router' },
|
||||
{ key: 'partner', title: '合作伙伴', description: 'partner' },
|
||||
{
|
||||
key: 'skill-platform',
|
||||
|
||||
@@ -96,7 +96,14 @@ const PageLayout = () => {
|
||||
const [giftQuota, setGiftQuota] = useState(0);
|
||||
|
||||
const isConsoleRoute = isNavigationPathActive(location.pathname, '/console');
|
||||
const showSider = isConsoleRoute && (!isMobile || drawerOpen);
|
||||
// 伙伴端保留原型中的独立伙伴工作台侧栏:桌面端隐藏重复的平台侧栏,移动端仍使用平台抽屉。
|
||||
// (管理端分佣 /console/commission 使用控制台主侧栏子菜单,内边距由 ConsolePageContainer 统一。)
|
||||
const isPartnerCommissionWorkspace =
|
||||
location.pathname === '/console/my-commission';
|
||||
const showSider =
|
||||
isConsoleRoute &&
|
||||
(!isPartnerCommissionWorkspace || isMobile) &&
|
||||
(!isMobile || drawerOpen);
|
||||
const isHomePage = location.pathname === '/';
|
||||
|
||||
// 隐私政策和用户协议页面需要隐藏顶部工具栏
|
||||
|
||||
@@ -30,6 +30,7 @@ import { getLucideIcon } from '../../helpers/render';
|
||||
import '../../styles/center-layout.css';
|
||||
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
|
||||
import { useSidebar } from '../../hooks/common/useSidebar';
|
||||
import { usePartnerWorkspaceEntry } from '../../hooks/common/usePartnerWorkspaceEntry';
|
||||
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
|
||||
import { isAdmin, isRoot, showError } from '../../helpers';
|
||||
import {
|
||||
@@ -42,6 +43,10 @@ import {
|
||||
canAccessDelegatedAdminPage,
|
||||
getDelegatedSettingTabs,
|
||||
} from '../../helpers/adminDelegation';
|
||||
import {
|
||||
loadPersonalConsentGranted,
|
||||
readPersonalConsentCache,
|
||||
} from '../smart-router/api';
|
||||
import SkeletonWrapper from './components/SkeletonWrapper';
|
||||
import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi';
|
||||
|
||||
@@ -50,6 +55,18 @@ const routerMap = {
|
||||
...consoleMenuPaths,
|
||||
about: '/about',
|
||||
pricing: '/market',
|
||||
// weiyuan 新增入口:consoleRoutes 未登记的路由在此补齐(智能路由、分佣管理子菜单)
|
||||
'smart-router': '/console/smart-router',
|
||||
commission: '/console/commission',
|
||||
// 新版分佣使用控制台主侧栏展开子菜单,子项沿用现有 view 路由。
|
||||
'commission-overview': '/console/commission?view=overview',
|
||||
'commission-partners': '/console/commission?view=partners',
|
||||
'commission-assignments': '/console/commission?view=assignments',
|
||||
'commission-tiers': '/console/commission?view=tiers',
|
||||
'commission-adjustments': '/console/commission?view=adjustments',
|
||||
'commission-bills': '/console/commission?view=bills',
|
||||
'commission-exceptions': '/console/commission?view=exceptions',
|
||||
'commission-audit': '/console/commission?view=audit',
|
||||
};
|
||||
|
||||
// forceExpanded:手机端抽屉态。抽屉本来就是临时全宽浮层,折叠成 60px 图标条毫无意义,
|
||||
@@ -65,6 +82,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
} = useSidebar();
|
||||
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const showPartnerWorkspace = usePartnerWorkspaceEntry();
|
||||
const [userState] = useContext(UserContext);
|
||||
const delegatedPermissions = statusState?.status?.AdminDelegatedSettingTabs;
|
||||
// 系统设置 tab 权限下放:普通管理员在被下放了至少一个 tab 时,才显示「系统设置」入口
|
||||
@@ -74,10 +92,30 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
);
|
||||
const canAccessSetting =
|
||||
isRoot() || (isAdmin() && delegatedSettingTabs.length > 0);
|
||||
const commissionEnabled = statusState?.status?.commission_enabled !== false;
|
||||
|
||||
const showSkeleton = useMinimumLoadingTime(sidebarLoading, 200);
|
||||
|
||||
const [selectedKeys, setSelectedKeys] = useState(['home']);
|
||||
// 平台关闭智能路由后,仍有生效中出境同意的普通用户保留入口以便撤回(§9.5,与企业"仅授权模式"同口径)
|
||||
const [routerConsentGranted, setRouterConsentGranted] = useState(
|
||||
() => readPersonalConsentCache() === '1',
|
||||
);
|
||||
const smartRouterEnabled = statusState?.status?.smart_router_enabled;
|
||||
useEffect(() => {
|
||||
if (smartRouterEnabled !== false || isAdmin()) return;
|
||||
if (!localStorage.getItem('user')) return; // 未登录不请求,避免 401 跳转
|
||||
if (readPersonalConsentCache() !== null) return;
|
||||
let alive = true;
|
||||
loadPersonalConsentGranted()
|
||||
.then((granted) => {
|
||||
if (alive) setRouterConsentGranted(granted);
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [smartRouterEnabled]);
|
||||
const [chatItems, setChatItems] = useState([]);
|
||||
const [openedKeys, setOpenedKeys] = useState([]);
|
||||
const [foldedGroups, setFoldedGroups] = useState([]);
|
||||
@@ -122,16 +160,39 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
itemKey: 'monitor',
|
||||
to: '/monitor',
|
||||
},
|
||||
{
|
||||
// 智能路由:已登记在 sidebarModules 注册表(console.smart-router),管理员可隐藏
|
||||
text: t('智能路由'),
|
||||
itemKey: 'smart-router',
|
||||
to: '/console/smart-router',
|
||||
},
|
||||
];
|
||||
|
||||
// 根据配置过滤项目
|
||||
const filteredItems = items.filter((item) => {
|
||||
// 智能路由:管理员始终可见(全局设置在该页),普通用户在平台开启后才显示,
|
||||
// 避免升级后所有用户突然多出一个尚未启用的入口
|
||||
if (
|
||||
item.itemKey === 'smart-router' &&
|
||||
!isAdmin() &&
|
||||
smartRouterEnabled !== true &&
|
||||
!routerConsentGranted
|
||||
)
|
||||
return false;
|
||||
const configVisible = isModuleVisible('console', item.itemKey);
|
||||
return configVisible;
|
||||
});
|
||||
|
||||
return filteredItems;
|
||||
}, [dataExportFlag, drawingFlag, taskFlag, t, isModuleVisible]);
|
||||
}, [
|
||||
smartRouterEnabled,
|
||||
routerConsentGranted,
|
||||
dataExportFlag,
|
||||
drawingFlag,
|
||||
taskFlag,
|
||||
t,
|
||||
isModuleVisible,
|
||||
]);
|
||||
|
||||
const financeItems = useMemo(() => {
|
||||
const items = [
|
||||
@@ -157,26 +218,16 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
return configVisible;
|
||||
});
|
||||
|
||||
// 我的提成:新模块不在 sidebar 配置注册表内,直接追加(非销售用户页面为空态)
|
||||
filteredItems.push({
|
||||
text: t('我的提成'),
|
||||
itemKey: 'my-commission',
|
||||
});
|
||||
|
||||
// 合作伙伴:受平台总开关控制(参数设置页可配),开放后对全部登录用户可见
|
||||
if (statusState?.status?.commission_partner_portal_enabled === true) {
|
||||
// 与顶栏和伙伴页面共用新版伙伴权限判断,避免无权限账号误入。
|
||||
if (showPartnerWorkspace) {
|
||||
filteredItems.push({
|
||||
text: t('合作伙伴'),
|
||||
itemKey: 'partner',
|
||||
text: t('我的提成'),
|
||||
itemKey: 'my-commission',
|
||||
});
|
||||
}
|
||||
|
||||
return filteredItems;
|
||||
}, [
|
||||
t,
|
||||
isModuleVisible,
|
||||
statusState?.status?.commission_partner_portal_enabled,
|
||||
]);
|
||||
}, [t, isModuleVisible, showPartnerWorkspace]);
|
||||
|
||||
const adminItems = useMemo(() => {
|
||||
const items = [
|
||||
@@ -185,6 +236,21 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
itemKey: 'analytics',
|
||||
className: isAdmin() ? '' : 'tableHiddle',
|
||||
},
|
||||
{
|
||||
text: t('分佣管理'),
|
||||
itemKey: 'commission',
|
||||
items: [
|
||||
{ text: t('分佣工作台'), itemKey: 'commission-overview' },
|
||||
{ text: t('合作伙伴'), itemKey: 'commission-partners' },
|
||||
{ text: t('客户归属'), itemKey: 'commission-assignments' },
|
||||
{ text: t('分佣档位'), itemKey: 'commission-tiers' },
|
||||
{ text: t('调整单'), itemKey: 'commission-adjustments' },
|
||||
{ text: t('销售提成'), itemKey: 'commission-bills' },
|
||||
{ text: t('异常中心'), itemKey: 'commission-exceptions' },
|
||||
{ text: t('分佣审计日志'), itemKey: 'commission-audit' },
|
||||
],
|
||||
className: isRoot() ? '' : 'tableHiddle',
|
||||
},
|
||||
{
|
||||
text: t('渠道管理'),
|
||||
itemKey: 'channel',
|
||||
@@ -281,6 +347,12 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
// 分佣管理:新增模块不在 sidebar 配置注册表内,绕过 isModuleVisible(Root 硬门控)。
|
||||
// 分佣总开关关闭时整组隐藏(接口已被后端闸门拦截);旧后端不返回该字段,视为开启。
|
||||
// 合并恢复:weiyuan 原逻辑(5e67eff82),合并 SiderBar 时被 ui 过滤函数覆盖丢失
|
||||
if (item.itemKey === 'commission') {
|
||||
return isRoot() && commissionEnabled;
|
||||
}
|
||||
// 系统设置入口:被下放了至少一个 tab 的普通管理员强制可见
|
||||
// (需绕过 isModuleVisible,因为 GetSelf 默认对普通管理员置 admin.setting=false)。
|
||||
// root 及其它情况仍走原有 isModuleVisible 逻辑,保留 root 自行隐藏该入口的能力。
|
||||
@@ -304,6 +376,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
delegatedSettingTabs,
|
||||
delegatedPermissions,
|
||||
userState?.user?.role,
|
||||
commissionEnabled,
|
||||
]);
|
||||
|
||||
const chatMenuItems = useMemo(() => {
|
||||
@@ -380,6 +453,28 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
// 根据当前路径设置选中的菜单项
|
||||
useEffect(() => {
|
||||
const currentPath = location.pathname;
|
||||
if (currentPath === '/console/commission') {
|
||||
const view =
|
||||
new URLSearchParams(location.search).get('view') || 'overview';
|
||||
const childKey = `commission-${view}`;
|
||||
const validChildKeys = [
|
||||
'commission-overview',
|
||||
'commission-partners',
|
||||
'commission-assignments',
|
||||
'commission-tiers',
|
||||
'commission-adjustments',
|
||||
'commission-bills',
|
||||
'commission-exceptions',
|
||||
'commission-audit',
|
||||
];
|
||||
setSelectedKeys([
|
||||
validChildKeys.includes(childKey) ? childKey : 'commission-overview',
|
||||
]);
|
||||
setOpenedKeys((keys) =>
|
||||
keys.includes('commission') ? keys : [...keys, 'commission'],
|
||||
);
|
||||
return;
|
||||
}
|
||||
let matchingKeys = getConsoleMenuKeys(currentPath, routerMapState);
|
||||
|
||||
// 处理聊天路由
|
||||
@@ -396,7 +491,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
if (matchingKeys.length) {
|
||||
setSelectedKeys(matchingKeys);
|
||||
}
|
||||
}, [location.pathname, routerMapState]);
|
||||
}, [location.pathname, location.search, routerMapState]);
|
||||
|
||||
// 监控折叠状态变化以更新 body class(--sidebar-current-width 由它驱动)。
|
||||
// 抽屉态下跳过:body class 是全局的,抽屉临时展开不该顺手把桌面侧栏宽度也改掉。
|
||||
@@ -450,20 +545,24 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderNavItem = (item) => {
|
||||
// nested:二级菜单项(无图标,靠缩进与引导线表达层级);forceActive:收起态父项代表任一子项选中
|
||||
const renderNavItem = (
|
||||
item,
|
||||
{ nested = false, forceActive = false } = {},
|
||||
) => {
|
||||
if (item.className === 'tableHiddle') return null;
|
||||
const active = selectedKeys.includes(item.itemKey);
|
||||
const active = forceActive || selectedKeys.includes(item.itemKey);
|
||||
return (
|
||||
<Link
|
||||
key={item.itemKey}
|
||||
to={routerMapState[item.itemKey] || routerMap[item.itemKey] || '#'}
|
||||
onClick={onNavigate}
|
||||
className='ui-center-menu-item'
|
||||
className={`ui-center-menu-item${nested ? ' ui-console-submenu-item' : ''}`}
|
||||
data-active={active || undefined}
|
||||
aria-current={active ? 'page' : undefined}
|
||||
title={collapsed ? item.text : undefined}
|
||||
>
|
||||
{renderMenuIcon(item.itemKey)}
|
||||
{!nested && renderMenuIcon(item.itemKey)}
|
||||
{!collapsed && (
|
||||
<span className='ui-center-menu-label'>{item.text}</span>
|
||||
)}
|
||||
@@ -474,14 +573,25 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
const renderSubItem = (item) => {
|
||||
if (!item.items?.length) return renderNavItem(item);
|
||||
const open = openedKeys.includes(item.itemKey);
|
||||
const childActive = item.items.some((child) =>
|
||||
selectedKeys.includes(child.itemKey),
|
||||
);
|
||||
// 收起态没有展开空间:父项作为入口直达模块首页,任一子项选中时父项高亮
|
||||
if (collapsed) {
|
||||
return renderNavItem(
|
||||
{ ...item, items: undefined },
|
||||
{ forceActive: childActive },
|
||||
);
|
||||
}
|
||||
const groupId = `ui-console-submenu-${item.itemKey}`;
|
||||
return (
|
||||
<div key={item.itemKey}>
|
||||
<div key={item.itemKey} className='ui-console-submenu'>
|
||||
<button
|
||||
type='button'
|
||||
className='ui-center-menu-item ui-console-submenu-toggle'
|
||||
title={collapsed ? item.text : undefined}
|
||||
aria-label={item.text}
|
||||
data-child-active={childActive || undefined}
|
||||
aria-expanded={open}
|
||||
aria-controls={groupId}
|
||||
onClick={() =>
|
||||
setOpenedKeys((previous) =>
|
||||
previous.includes(item.itemKey)
|
||||
@@ -491,12 +601,21 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
}
|
||||
>
|
||||
{renderMenuIcon(item.itemKey)}
|
||||
{!collapsed && (
|
||||
<span className='ui-center-menu-label'>{item.text}</span>
|
||||
)}
|
||||
<span className='ui-center-menu-label'>{item.text}</span>
|
||||
<ActionChevronDown
|
||||
size={14}
|
||||
className='ui-console-submenu-arrow'
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
<div className='ui-org-group-items' hidden={!open}>
|
||||
{item.items.map(renderNavItem)}
|
||||
<div
|
||||
id={groupId}
|
||||
role='group'
|
||||
aria-label={item.text}
|
||||
className='ui-org-group-items ui-console-submenu-items'
|
||||
hidden={!open}
|
||||
>
|
||||
{item.items.map((child) => renderNavItem(child, { nested: true }))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -534,7 +653,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
renderGroup(
|
||||
'console-group',
|
||||
t('控制台'),
|
||||
workspaceItems.map(renderNavItem),
|
||||
workspaceItems.map((item) => renderNavItem(item)),
|
||||
)}
|
||||
|
||||
{/* 个人中心区域 */}
|
||||
@@ -542,15 +661,17 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
||||
renderGroup(
|
||||
'personal-group',
|
||||
t('个人中心'),
|
||||
financeItems.map(renderNavItem),
|
||||
financeItems.map((item) => renderNavItem(item)),
|
||||
)}
|
||||
|
||||
{/* 管理员区域:按角色、权限下放及菜单配置过滤。 */}
|
||||
{/* 管理员区域:按角色、权限下放及菜单配置过滤。分佣管理为子菜单,走 renderSubItem。 */}
|
||||
{isAdmin() &&
|
||||
renderGroup(
|
||||
'admin-group',
|
||||
t('管理员'),
|
||||
adminItems.map(renderNavItem),
|
||||
adminItems
|
||||
.filter((item) => item.className !== 'tableHiddle')
|
||||
.map(renderSubItem),
|
||||
)}
|
||||
</nav>
|
||||
</SkeletonWrapper>
|
||||
|
||||
@@ -82,6 +82,7 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
|
||||
menuItems.push({
|
||||
key: link.itemKey,
|
||||
text: link.text,
|
||||
mobileText: link.mobileText,
|
||||
to: targetPath,
|
||||
active: isPathActive(link.activePrefix || targetPath),
|
||||
});
|
||||
@@ -137,13 +138,14 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
|
||||
theme='borderless'
|
||||
type='tertiary'
|
||||
aria-label={t('主导航')}
|
||||
title={activeItem?.text}
|
||||
aria-haspopup='menu'
|
||||
aria-expanded={visible}
|
||||
icon={<ActionCompass size={16} />}
|
||||
className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.ant-btn-content]:min-w-0'
|
||||
>
|
||||
<span className='ml-1 text-[13px] font-semibold truncate'>
|
||||
{activeItem ? activeItem.text : t('导航')}
|
||||
{activeItem?.mobileText || activeItem?.text || t('导航')}
|
||||
</span>
|
||||
</Button>
|
||||
</span>
|
||||
|
||||
@@ -23,6 +23,7 @@ import { isAuthPagePath } from '../../../helpers';
|
||||
import { useHeaderBar } from '../../../hooks/common/useHeaderBar';
|
||||
import { useNotifications } from '../../../hooks/common/useNotifications';
|
||||
import { useNavigation } from '../../../hooks/common/useNavigation';
|
||||
import { usePartnerWorkspaceEntry } from '../../../hooks/common/usePartnerWorkspaceEntry';
|
||||
import NoticeModal from '../NoticeModal';
|
||||
import MobileMenuButton from './MobileMenuButton';
|
||||
import HeaderLogo from './HeaderLogo';
|
||||
@@ -74,13 +75,14 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
|
||||
|
||||
const userRole = userState?.user?.role || 0;
|
||||
const userGroup = userState?.user?.group || 'default';
|
||||
const showPartnerEntry = usePartnerWorkspaceEntry();
|
||||
const { mainNavLinks: configuredNavLinks } = useNavigation(
|
||||
t,
|
||||
docsLink,
|
||||
headerNavModules,
|
||||
userRole,
|
||||
userGroup,
|
||||
{ showOrgEntry, orgEntryPath },
|
||||
{ showOrgEntry, orgEntryPath, showPartnerEntry },
|
||||
);
|
||||
const mainNavLinks = configuredNavLinks.filter(
|
||||
(link) => link.itemKey !== 'keyManagement',
|
||||
|
||||
@@ -105,7 +105,8 @@ const SSEViewer = ({ sseData }) => {
|
||||
)
|
||||
.join('\n\n');
|
||||
|
||||
if (!(await copy(allData))) throw new Error('Clipboard copy failed');
|
||||
// copy 失败返回 false 而不抛错,交给下方 catch 统一提示
|
||||
if (!(await copy(allData))) throw new Error('copy failed');
|
||||
setCopied(true);
|
||||
Toast.success(t('已复制全部数据'));
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
@@ -121,7 +122,7 @@ const SSEViewer = ({ sseData }) => {
|
||||
const textToCopy = item.parsed
|
||||
? JSON.stringify(item.parsed, null, 2)
|
||||
: item.raw;
|
||||
if (!(await copy(textToCopy))) throw new Error('Clipboard copy failed');
|
||||
if (!(await copy(textToCopy))) throw new Error('copy failed');
|
||||
Toast.success(t('已复制'));
|
||||
} catch (err) {
|
||||
Toast.error(t('复制失败'));
|
||||
|
||||
@@ -284,14 +284,22 @@ const PromotionPosterModal = ({ visible, onClose }) => {
|
||||
}
|
||||
};
|
||||
|
||||
// 复制并按实际结果提示(此前调用未处理结果,点击后无任何反馈)
|
||||
const copyWithFeedback = async (text, name) => {
|
||||
if (await copy(text)) {
|
||||
showSuccess(t('已复制:{{name}}', { name }));
|
||||
} else {
|
||||
showError(t('复制失败,请手动复制'));
|
||||
}
|
||||
};
|
||||
|
||||
// 复制邀请链接
|
||||
const handleCopyLink = async () => {
|
||||
if (!affLink) {
|
||||
showError(t('邀请链接获取中,请稍后'));
|
||||
return;
|
||||
}
|
||||
if (await copy(affLink)) showSuccess(t('邀请链接已复制到剪切板'));
|
||||
else showError(t('复制失败,请手动复制'));
|
||||
copyWithFeedback(affLink, t('邀请链接'));
|
||||
};
|
||||
|
||||
// 复制邀请码
|
||||
@@ -300,8 +308,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
|
||||
showError(t('邀请码获取中,请稍后'));
|
||||
return;
|
||||
}
|
||||
if (await copy(affCode)) showSuccess(t('复制成功'));
|
||||
else showError(t('复制失败,请手动复制'));
|
||||
copyWithFeedback(affCode, t('邀请码'));
|
||||
};
|
||||
|
||||
// 链接分享模式 - PC友好
|
||||
|
||||
@@ -42,6 +42,7 @@ const ModelSetting = () => {
|
||||
'claude.thinking_adapter_budget_tokens_percentage': 0.8,
|
||||
'claude.cache_creation_5m_ratio': 1.25,
|
||||
'claude.cache_creation_1h_ratio': 2,
|
||||
'claude.cache_creation_default_ttl': '1h',
|
||||
'claude.cache_ttl_override': 'off',
|
||||
'global.pass_through_request_enabled': false,
|
||||
'global.thinking_model_blacklist': '[]',
|
||||
|
||||
@@ -89,6 +89,8 @@ const OperationSetting = () => {
|
||||
DefaultCollapseSidebar: false,
|
||||
DemoSiteEnabled: false,
|
||||
SelfUseModeEnabled: false,
|
||||
/* 分佣总开关:布尔必须在此声明,getOptions 才会 toBoolean */
|
||||
CommissionEnabled: true,
|
||||
|
||||
/* 语言与地区(JSON,按 IP 国家自动选择界面语言) */
|
||||
LanguageSetting: '',
|
||||
|
||||
@@ -515,8 +515,9 @@ const PersonalSetting = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 复制用户ID
|
||||
const copyUserId = () => {
|
||||
// 复制用户ID:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
|
||||
// 直接调用 writeText 会同步抛错,.catch 降级永远走不到。
|
||||
const copyUserId = async () => {
|
||||
const userId = String(userState?.user?.id || '');
|
||||
writeClipboardText(userId)
|
||||
.then(() => {
|
||||
|
||||
@@ -53,6 +53,7 @@ const RatioSetting = () => {
|
||||
});
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [costVisited, setCostVisited] = useState(false);
|
||||
|
||||
const getOptions = async () => {
|
||||
const res = await API.get('/api/option/');
|
||||
@@ -99,7 +100,12 @@ const RatioSetting = () => {
|
||||
<Spin spinning={loading} size='large'>
|
||||
{/* 模型倍率设置以及可视化编辑器 */}
|
||||
<Card className='settings-section'>
|
||||
<Tabs type='card'>
|
||||
<Tabs
|
||||
type='card'
|
||||
onChange={(key) => {
|
||||
if (key === 'model_cost') setCostVisited(true);
|
||||
}}
|
||||
>
|
||||
<Tabs.TabPane tab={t('模型倍率设置')} itemKey='model'>
|
||||
<ModelRatioSettings options={inputs} refresh={onRefresh} />
|
||||
</Tabs.TabPane>
|
||||
@@ -122,7 +128,7 @@ const RatioSetting = () => {
|
||||
)}
|
||||
{isRoot() && (
|
||||
<Tabs.TabPane tab={t('模型成本价格')} itemKey='model_cost'>
|
||||
<ModelCostSettings />
|
||||
{costVisited && <ModelCostSettings />}
|
||||
</Tabs.TabPane>
|
||||
)}
|
||||
<Tabs.TabPane tab={t('未设置倍率模型')} itemKey='unset_models'>
|
||||
|
||||
@@ -193,7 +193,7 @@ const TwoFASetting = ({ t }) => {
|
||||
}
|
||||
};
|
||||
|
||||
// 通用复制函数
|
||||
// 通用复制函数:走公共剪贴板封装(HTTP 部署下 navigator.clipboard 为 undefined 时降级 execCommand)
|
||||
const copyTextToClipboard = (text, successMessage = t('已复制到剪贴板')) => {
|
||||
writeClipboardText(text)
|
||||
.then(() => {
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
/*
|
||||
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, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Empty,
|
||||
Modal,
|
||||
Spin,
|
||||
Switch,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { showError, showSuccess } from '../../helpers';
|
||||
import { getConsents, updateConsent } from './api';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const kindText = (t, kind) =>
|
||||
({
|
||||
judge: {
|
||||
title: t('智能判定'),
|
||||
desc: t(
|
||||
'把脱敏、截断后的请求片段发送给境外判定服务(Jev),用于选择合适的模型。',
|
||||
),
|
||||
},
|
||||
eval: {
|
||||
title: t('质量打分'),
|
||||
desc: t(
|
||||
'把脱敏、截断后的请求与回答片段发送给境外判定服务,用于质量评估。',
|
||||
),
|
||||
},
|
||||
shadow: {
|
||||
title: t('影子评审'),
|
||||
desc: t('把正式脱敏后的请求发送给基线模型和评审模型,用于对比质量。'),
|
||||
},
|
||||
replay: {
|
||||
title: t('回放留存'),
|
||||
desc: t('把脱敏后的请求加密留存最多 90 天,用于离线评估。'),
|
||||
},
|
||||
})[kind] || { title: kind, desc: '' };
|
||||
|
||||
// 同意记录(§9.5)。企业同意只能由真实的企业所有者操作。
|
||||
// onChange:授权状态变化后回调最新列表(企业中心"仅授权模式"据此刷新入口)
|
||||
const ConsentPanel = ({ mode, orgId, canWrite = true, onChange }) => {
|
||||
const { t } = useTranslation();
|
||||
const [rows, setRows] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
setRows((await getConsents(mode, orgId)) || []);
|
||||
} catch (e) {
|
||||
setError(e?.message || t('加载失败'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [mode, orgId, t]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const toggle = (row, granted) => {
|
||||
const text = kindText(t, row.kind);
|
||||
const doIt = async () => {
|
||||
try {
|
||||
const next = await updateConsent(mode, orgId, row.kind, granted);
|
||||
setRows(next);
|
||||
onChange?.(next);
|
||||
showSuccess(granted ? t('已授权') : t('已撤回'));
|
||||
} catch (e) {
|
||||
if (e?.message) showError(e.message);
|
||||
load(); // 写入可能已成功、只是回读失败:重新拉取,避免开关停在旧状态
|
||||
}
|
||||
};
|
||||
if (!granted) return doIt();
|
||||
Modal.confirm({
|
||||
title: `${t('确认授权')} · ${text.title}`,
|
||||
content: (
|
||||
<div className='flex flex-col gap-2'>
|
||||
<Text>{text.desc}</Text>
|
||||
{row.overseas && (
|
||||
<Alert
|
||||
type='warning'
|
||||
showIcon
|
||||
title={t(
|
||||
'该项涉及数据出境(发送到境外服务),可随时撤回,撤回后立即生效。',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{mode === 'org' && (
|
||||
<Text type='secondary' className='smart-router-sub'>
|
||||
{t('授权后会覆盖企业「数据安全」「不用于训练」功能的默认保护。')}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
onOk: doIt,
|
||||
});
|
||||
};
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<div className='smart-router-state'>
|
||||
<Spin />
|
||||
</div>
|
||||
);
|
||||
if (error)
|
||||
return (
|
||||
<Alert
|
||||
type='error'
|
||||
showIcon
|
||||
title={error}
|
||||
action={
|
||||
<Button size='small' onClick={load}>
|
||||
{t('重试')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
const available = rows.filter((r) => r.available);
|
||||
if (available.length === 0)
|
||||
return (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={t('平台暂未开放需要授权的智能路由功能')}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className='smart-router-stack'>
|
||||
{!canWrite && (
|
||||
<Alert
|
||||
type='info'
|
||||
showIcon
|
||||
title={t('企业出境同意只能由企业所有者操作。')}
|
||||
/>
|
||||
)}
|
||||
{available.map((r) => {
|
||||
const text = kindText(t, r.kind);
|
||||
return (
|
||||
<div key={r.kind} className='smart-router-consent-row'>
|
||||
<div className='min-w-0'>
|
||||
<div className='smart-router-consent-head'>
|
||||
<Text strong>{text.title}</Text>
|
||||
{r.overseas && (
|
||||
<Tag color='warning' variant='filled'>
|
||||
{t('境外处理')}
|
||||
</Tag>
|
||||
)}
|
||||
{r.valid ? (
|
||||
<Tag color='success' variant='filled'>
|
||||
{t('已生效')}
|
||||
</Tag>
|
||||
) : r.granted ? (
|
||||
<Tag color='default' variant='filled'>
|
||||
{t('文案已更新,需要重新授权')}
|
||||
</Tag>
|
||||
) : null}
|
||||
</div>
|
||||
<Text type='secondary' className='smart-router-sub'>
|
||||
{text.desc}
|
||||
</Text>
|
||||
</div>
|
||||
<Switch
|
||||
size='small'
|
||||
checked={r.valid}
|
||||
disabled={!canWrite}
|
||||
onChange={(v) => toggle(r, v)}
|
||||
aria-label={text.title}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConsentPanel;
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
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, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, Button, Empty, Table, Tag } from 'antd';
|
||||
import { listDecisions } from './api';
|
||||
import { gateText, jevReasonText, srcText } from './labels';
|
||||
|
||||
// 判定明细:只读 router_eval_records(§12.3)
|
||||
const DecisionTable = ({ mode, orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const [data, setData] = useState({ items: [], total: 0 });
|
||||
const [page, setPage] = useState(1);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
setData(
|
||||
(await listDecisions(mode, orgId, { p: page, page_size: 20 })) || {
|
||||
items: [],
|
||||
total: 0,
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
setError(e?.message || t('加载失败'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [mode, orgId, page, t]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('时间'),
|
||||
dataIndex: 'created_at',
|
||||
width: 180,
|
||||
render: (v) => (
|
||||
<span className='smart-router-num'>
|
||||
{new Date(v * 1000).toLocaleString()}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('虚拟模型'),
|
||||
dataIndex: 'virtual_model',
|
||||
width: 180,
|
||||
render: (v) => <span className='smart-router-mono'>{v}</span>,
|
||||
},
|
||||
{
|
||||
title: t('实际模型'),
|
||||
dataIndex: 'actual_model',
|
||||
width: 200,
|
||||
render: (v) => <span className='smart-router-mono'>{v || '-'}</span>,
|
||||
},
|
||||
{
|
||||
title: t('判定来源'),
|
||||
dataIndex: 'src',
|
||||
width: 200,
|
||||
render: (v, r) => (
|
||||
<Tag variant='filled' color={v === 'error' ? 'error' : 'blue'}>
|
||||
{srcText(t, v)}
|
||||
{r.reason ? ` · ${jevReasonText(t, r.reason)}` : ''}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('任务 / 难度档'),
|
||||
key: 'task',
|
||||
width: 140,
|
||||
render: (_, r) => `${r.task || '-'} / ${r.difficulty_tier}`,
|
||||
},
|
||||
{
|
||||
title: t('合规闸门'),
|
||||
dataIndex: 'gate',
|
||||
width: 140,
|
||||
render: (v) => gateText(t, v),
|
||||
},
|
||||
{
|
||||
title: t('状态码'),
|
||||
dataIndex: 'status_code',
|
||||
width: 90,
|
||||
align: 'right',
|
||||
render: (v) => <span className='smart-router-num'>{v}</span>,
|
||||
},
|
||||
{
|
||||
title: t('判定耗时'),
|
||||
dataIndex: 'judge_ms',
|
||||
width: 110,
|
||||
align: 'right',
|
||||
render: (v) => (
|
||||
<span className='smart-router-num'>{v ? `${v} ms` : '-'}</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
if (error)
|
||||
return (
|
||||
<Alert
|
||||
type='error'
|
||||
showIcon
|
||||
title={error}
|
||||
action={
|
||||
<Button size='small' onClick={load}>
|
||||
{t('重试')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<Table
|
||||
rowKey='id'
|
||||
size='middle'
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data.items || []}
|
||||
scroll={{ x: 'max-content' }}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={t('还没有智能路由请求')}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
pagination={{
|
||||
// 接口固定 page_size=20,不提供每页条数切换
|
||||
current: page,
|
||||
pageSize: 20,
|
||||
total: data.total || 0,
|
||||
size: 'small',
|
||||
showSizeChanger: false,
|
||||
showTotal: (total) => t('共 {{total}} 条', { total }),
|
||||
onChange: setPage,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default DecisionTable;
|
||||
@@ -0,0 +1,542 @@
|
||||
/*
|
||||
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, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Switch,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
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
|
||||
style={{ width: 200 }}
|
||||
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
|
||||
style={{ width: 200 }}
|
||||
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
|
||||
style={{ maxWidth: 360 }}
|
||||
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}>
|
||||
{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>
|
||||
<Input.Password
|
||||
style={{ width: 320 }}
|
||||
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;
|
||||
@@ -0,0 +1,954 @@
|
||||
/*
|
||||
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, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
Collapse,
|
||||
Drawer,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
Switch,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { Plus, Trash2 } from '../common/icons/ActionIcons';
|
||||
import { showError, showSuccess } from '../../helpers';
|
||||
import { saveProfile } from './api';
|
||||
|
||||
const { TextArea } = Input;
|
||||
|
||||
// 等价 Semi Select 的 filter + allowCreate:可搜索,输入的新模型名作为临时选项出现,
|
||||
// 只有选中后才回调 onChange(与原行为一致,不在每次键入时写值)。
|
||||
const CreatableSelect = ({ options, value, onChange, ...props }) => {
|
||||
const [search, setSearch] = useState('');
|
||||
const keyword = search.trim();
|
||||
const merged =
|
||||
keyword && !options.some((o) => o.value === keyword)
|
||||
? [...options, { label: keyword, value: keyword }]
|
||||
: options;
|
||||
return (
|
||||
<Select
|
||||
{...props}
|
||||
showSearch
|
||||
optionFilterProp='label'
|
||||
value={value}
|
||||
options={merged}
|
||||
onSearch={setSearch}
|
||||
onChange={(v) => {
|
||||
setSearch('');
|
||||
onChange(v);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const RULES_LABELS = [
|
||||
'coding',
|
||||
'math',
|
||||
'translate',
|
||||
'extract',
|
||||
'analysis',
|
||||
'writing',
|
||||
'chat',
|
||||
'general',
|
||||
];
|
||||
|
||||
const LABEL_PATTERN = /^[a-z0-9_]{1,32}$/;
|
||||
|
||||
let uidSeq = 0;
|
||||
const uid = () => `l${Date.now().toString(36)}${(uidSeq += 1)}`;
|
||||
|
||||
const defaultLabels = (t) =>
|
||||
[
|
||||
['coding', '编写、修改、调试、解释代码'],
|
||||
['math', '数学计算、推导、证明'],
|
||||
['writing', '创作、改写、润色长文本'],
|
||||
['analysis', '数据分析、方案对比、专业问答'],
|
||||
['extract', '信息抽取、格式转换、分类'],
|
||||
['translate', '翻译'],
|
||||
['chat', '闲聊、简单查询'],
|
||||
['general', '无法归入以上类别的请求'],
|
||||
].map(([name, desc]) => ({
|
||||
id: uid(),
|
||||
name,
|
||||
desc: t(desc),
|
||||
rules_label: '',
|
||||
}));
|
||||
|
||||
const emptyCaps = {
|
||||
vision: false,
|
||||
tools: false,
|
||||
json_mode: false,
|
||||
reasoning: false,
|
||||
max_context: 0,
|
||||
};
|
||||
|
||||
const parseCaps = (raw) => {
|
||||
if (!raw) return { ...emptyCaps };
|
||||
try {
|
||||
return {
|
||||
...emptyCaps,
|
||||
...(typeof raw === 'string' ? JSON.parse(raw) : raw),
|
||||
};
|
||||
} catch (e) {
|
||||
return { ...emptyCaps };
|
||||
}
|
||||
};
|
||||
|
||||
const emptyRow = () => ['', '', '', ''];
|
||||
|
||||
// 矩阵按标签的稳定 id 存储:改名时不搬动行,保存时再按名字重建(避免改名到已有名字时覆盖别的行)
|
||||
const toState = (profile, t) => {
|
||||
if (!profile) {
|
||||
const labels = defaultLabels(t);
|
||||
return {
|
||||
slug: '',
|
||||
name: '',
|
||||
description: '',
|
||||
strategy: 'balanced',
|
||||
tier_thresholds: '',
|
||||
min_task_conf: 0,
|
||||
reasoning_threshold: 0,
|
||||
reasoning_model: '',
|
||||
default_model: '',
|
||||
baseline_model: '',
|
||||
sticky_enabled: true,
|
||||
sticky_ttl_sec: 1800,
|
||||
jev_allowed: false,
|
||||
status: 1,
|
||||
labels,
|
||||
matrix: Object.fromEntries(labels.map((l) => [l.id, emptyRow()])),
|
||||
rules: '[]',
|
||||
models: [],
|
||||
};
|
||||
}
|
||||
const labels = (profile.task_labels_obj || []).map((l) => ({
|
||||
id: uid(),
|
||||
name: l.name,
|
||||
desc: l.desc || '',
|
||||
rules_label: l.rules_label || '',
|
||||
}));
|
||||
const matrix = {};
|
||||
labels.forEach((l) => {
|
||||
const row = (profile.matrix_obj || {})[l.name] || [];
|
||||
matrix[l.id] = [0, 1, 2, 3].map((i) => row[i] || '');
|
||||
});
|
||||
return {
|
||||
id: profile.id,
|
||||
slug: profile.slug,
|
||||
name: profile.name,
|
||||
description: profile.description,
|
||||
strategy: profile.strategy,
|
||||
tier_thresholds: profile.tier_thresholds || '',
|
||||
min_task_conf: profile.min_task_conf || 0,
|
||||
reasoning_threshold: profile.reasoning_threshold || 0,
|
||||
reasoning_model: profile.reasoning_model || '',
|
||||
default_model: profile.default_model,
|
||||
baseline_model: profile.baseline_model,
|
||||
sticky_enabled: profile.sticky_enabled,
|
||||
sticky_ttl_sec: profile.sticky_ttl_sec || 1800,
|
||||
jev_allowed: profile.jev_allowed,
|
||||
status: profile.status,
|
||||
labels,
|
||||
matrix,
|
||||
rules: JSON.stringify(profile.rules_obj || [], null, 2),
|
||||
models: (profile.models || []).map((m) => ({
|
||||
model_name: m.model_name,
|
||||
model_tier: m.model_tier,
|
||||
description: m.description || '',
|
||||
enabled: m.enabled,
|
||||
caps: parseCaps(m.capabilities),
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
// 一键生成:按能力档把候选分配到 4 列(只作为初始值,§8.6)
|
||||
const autoMatrix = (labels, models) => {
|
||||
const enabled = models.filter((m) => m.model_name && m.enabled);
|
||||
if (enabled.length === 0) return null;
|
||||
const sorted = [...enabled].sort((a, b) => a.model_tier - b.model_tier);
|
||||
const col = (k) => {
|
||||
const hit = sorted.find((m) => m.model_tier >= k);
|
||||
return (hit || sorted[sorted.length - 1]).model_name;
|
||||
};
|
||||
const row = [col(0), col(1), col(2), col(3)];
|
||||
return Object.fromEntries(labels.map((l) => [l.id, [...row]]));
|
||||
};
|
||||
|
||||
// 替换矩阵与角色字段中对某个候选名的引用
|
||||
const replaceModelRefs = (s, from, to) => {
|
||||
if (!from) return s;
|
||||
const matrix = {};
|
||||
Object.entries(s.matrix).forEach(([k, row]) => {
|
||||
matrix[k] = row.map((c) => (c === from ? to : c));
|
||||
});
|
||||
const swap = (v) => (v === from ? to : v);
|
||||
return {
|
||||
...s,
|
||||
matrix,
|
||||
default_model: swap(s.default_model),
|
||||
baseline_model: swap(s.baseline_model),
|
||||
reasoning_model: swap(s.reasoning_model),
|
||||
};
|
||||
};
|
||||
|
||||
const ProfileEditor = ({
|
||||
visible,
|
||||
mode,
|
||||
orgId,
|
||||
profile,
|
||||
candidateModels,
|
||||
onClose,
|
||||
onSaved,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState(() => toState(profile, t));
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [activePanels, setActivePanels] = useState([
|
||||
'basic',
|
||||
'models',
|
||||
'matrix',
|
||||
'roles',
|
||||
]);
|
||||
// 进入编辑时 general 行的标签 id:只锁定这一行,避免改名成 general 后整行被锁死
|
||||
const generalIdRef = useRef(null);
|
||||
|
||||
// 只在打开抽屉(或换了要编辑的集合)时重置;切换语言不能清掉未保存的编辑
|
||||
const tRef = useRef(t);
|
||||
tRef.current = t;
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
const next = toState(profile, tRef.current);
|
||||
generalIdRef.current =
|
||||
next.labels.find((l) => l.name === 'general')?.id || null;
|
||||
setState(next);
|
||||
setActivePanels(['basic', 'models', 'matrix', 'roles']);
|
||||
}
|
||||
}, [visible, profile]);
|
||||
|
||||
const set = (k, v) => setState((s) => ({ ...s, [k]: v }));
|
||||
const candidateNames = useMemo(
|
||||
() => state.models.map((m) => m.model_name).filter(Boolean),
|
||||
[state.models],
|
||||
);
|
||||
const candidateOptions = candidateNames.map((m) => ({ label: m, value: m }));
|
||||
const modelOptions = useMemo(
|
||||
() => (candidateModels || []).map((m) => ({ label: m, value: m })),
|
||||
[candidateModels],
|
||||
);
|
||||
const duplicateLabels = useMemo(() => {
|
||||
const seen = new Set();
|
||||
const dup = new Set();
|
||||
state.labels.forEach((l) => {
|
||||
if (seen.has(l.name)) dup.add(l.name);
|
||||
seen.add(l.name);
|
||||
});
|
||||
return dup;
|
||||
}, [state.labels]);
|
||||
|
||||
const updateModel = (idx, patch) =>
|
||||
setState((s) => {
|
||||
let next = s;
|
||||
if (patch.model_name !== undefined) {
|
||||
const from = s.models[idx].model_name;
|
||||
const usedElsewhere = (name) =>
|
||||
s.models.some((m, i) => i !== idx && m.model_name === name);
|
||||
// 改名时同步替换矩阵与角色字段中的引用;新旧名字被其他行占用时不级联,避免误改别的候选的引用
|
||||
if (from && !usedElsewhere(from) && !usedElsewhere(patch.model_name)) {
|
||||
next = replaceModelRefs(s, from, patch.model_name);
|
||||
}
|
||||
}
|
||||
const models = next.models.map((m, i) =>
|
||||
i === idx ? { ...m, ...patch } : m,
|
||||
);
|
||||
return { ...next, models };
|
||||
});
|
||||
const updateCaps = (idx, patch) =>
|
||||
setState((s) => ({
|
||||
...s,
|
||||
models: s.models.map((m, i) =>
|
||||
i === idx ? { ...m, caps: { ...m.caps, ...patch } } : m,
|
||||
),
|
||||
}));
|
||||
const removeModel = (idx) => {
|
||||
const removed = state.models[idx]?.model_name;
|
||||
const general = state.matrix[generalIdRef.current] || [];
|
||||
if (removed && general.includes(removed)) {
|
||||
showError(t('该模型在 general 行中被引用,请先替换 general 行的单元格'));
|
||||
return;
|
||||
}
|
||||
setState((s) => {
|
||||
const stillUsed = s.models.some(
|
||||
(m, i) => i !== idx && m.model_name === removed,
|
||||
);
|
||||
const next = stillUsed ? s : replaceModelRefs(s, removed, '');
|
||||
return { ...next, models: next.models.filter((_, i) => i !== idx) };
|
||||
});
|
||||
};
|
||||
|
||||
const updateLabel = (id, patch) =>
|
||||
setState((s) => ({
|
||||
...s,
|
||||
labels: s.labels.map((l) => (l.id === id ? { ...l, ...patch } : l)),
|
||||
}));
|
||||
const removeLabel = (id) =>
|
||||
setState((s) => {
|
||||
const matrix = { ...s.matrix };
|
||||
delete matrix[id];
|
||||
return { ...s, labels: s.labels.filter((l) => l.id !== id), matrix };
|
||||
});
|
||||
const addLabel = () =>
|
||||
setState((s) => {
|
||||
const names = new Set(s.labels.map((l) => l.name));
|
||||
let n = s.labels.length + 1;
|
||||
while (names.has(`label_${n}`)) n += 1;
|
||||
const id = uid();
|
||||
return {
|
||||
...s,
|
||||
labels: [
|
||||
...s.labels,
|
||||
{ id, name: `label_${n}`, desc: '', rules_label: '' },
|
||||
],
|
||||
matrix: { ...s.matrix, [id]: emptyRow() },
|
||||
};
|
||||
});
|
||||
|
||||
const setCell = (id, col, value) =>
|
||||
setState((s) => {
|
||||
const row = [...(s.matrix[id] || emptyRow())];
|
||||
row[col] = value || '';
|
||||
return { ...s, matrix: { ...s.matrix, [id]: row } };
|
||||
});
|
||||
|
||||
const applyAutoMatrix = () => {
|
||||
const next = autoMatrix(state.labels, state.models);
|
||||
if (!next) {
|
||||
showError(t('请先添加并启用候选模型'));
|
||||
return;
|
||||
}
|
||||
Modal.confirm({
|
||||
title: t('一键生成(仅作为初始值)'),
|
||||
content: t('会覆盖当前矩阵中的全部单元格,是否继续?'),
|
||||
onOk: () => set('matrix', next),
|
||||
});
|
||||
};
|
||||
|
||||
// 保存前的客户端检查:把必填项问题指向对应面板,避免只看到后端报错
|
||||
const precheck = () => {
|
||||
if (!state.id && !/^[a-z0-9][a-z0-9-]{0,47}$/.test(state.slug.trim())) {
|
||||
return ['basic', t('短名只允许小写字母、数字和连字符,最长 48 个字符')];
|
||||
}
|
||||
if (state.models.some((m) => !m.model_name)) {
|
||||
return ['models', t('有候选模型还没有选择模型名')];
|
||||
}
|
||||
if (candidateNames.length === 0)
|
||||
return ['models', t('至少需要一个候选模型')];
|
||||
if (new Set(candidateNames).size !== candidateNames.length) {
|
||||
return ['models', t('候选模型不能重复')];
|
||||
}
|
||||
for (const l of state.labels) {
|
||||
if (!LABEL_PATTERN.test(l.name)) {
|
||||
return [
|
||||
'labels',
|
||||
t('任务标签只允许小写字母、数字和下划线,最长 32 个字符'),
|
||||
];
|
||||
}
|
||||
}
|
||||
if (duplicateLabels.size > 0) return ['labels', t('任务标签不能重名')];
|
||||
if (!state.labels.some((l) => l.name === 'general')) {
|
||||
return ['labels', t('任务标签必须包含 general')];
|
||||
}
|
||||
const general = state.labels.find((l) => l.name === 'general');
|
||||
if ((state.matrix[general.id] || []).some((c) => !c)) {
|
||||
return ['matrix', t('general 行的 4 个单元格必须全部填写')];
|
||||
}
|
||||
if (!state.default_model) return ['roles', t('请选择默认模型')];
|
||||
if (!state.baseline_model) return ['roles', t('请选择基线模型')];
|
||||
// 自定义规则引用的模型 / 行必须仍然存在(改名、删除后容易遗漏)
|
||||
try {
|
||||
const rules = JSON.parse(state.rules || '[]');
|
||||
const labelNames = new Set(state.labels.map((l) => l.name));
|
||||
for (let i = 0; i < (Array.isArray(rules) ? rules.length : 0); i += 1) {
|
||||
const th = rules[i]?.then || {};
|
||||
if (
|
||||
(th.model && !candidateNames.includes(th.model)) ||
|
||||
(th.row && !labelNames.has(th.row))
|
||||
) {
|
||||
return [
|
||||
'rules',
|
||||
`${t('自定义规则引用了不存在的模型或行')} #${i + 1}`,
|
||||
];
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// JSON 格式错误在保存时单独提示
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
const problem = precheck();
|
||||
if (problem) {
|
||||
setActivePanels((p) => (p.includes(problem[0]) ? p : [...p, problem[0]]));
|
||||
showError(problem[1]);
|
||||
return;
|
||||
}
|
||||
let rules;
|
||||
try {
|
||||
rules = JSON.parse(state.rules || '[]');
|
||||
if (!Array.isArray(rules)) throw new Error('not array');
|
||||
} catch (e) {
|
||||
setActivePanels((p) => (p.includes('rules') ? p : [...p, 'rules']));
|
||||
showError(t('自定义规则必须是合法的 JSON 数组'));
|
||||
return;
|
||||
}
|
||||
const matrix = {};
|
||||
state.labels.forEach((l) => {
|
||||
matrix[l.name] = [...(state.matrix[l.id] || emptyRow())].slice(0, 4);
|
||||
});
|
||||
const payload = {
|
||||
id: state.id,
|
||||
slug: state.slug.trim(),
|
||||
name: state.name,
|
||||
description: state.description,
|
||||
mode: 'matrix',
|
||||
strategy: state.strategy,
|
||||
tier_thresholds: state.tier_thresholds,
|
||||
min_task_conf: Number(state.min_task_conf) || 0,
|
||||
reasoning_threshold: Number(state.reasoning_threshold) || 0,
|
||||
reasoning_model: state.reasoning_model || '',
|
||||
default_model: state.default_model || '',
|
||||
baseline_model: state.baseline_model || '',
|
||||
sticky_enabled: state.sticky_enabled,
|
||||
sticky_ttl_sec: Number(state.sticky_ttl_sec) || 1800,
|
||||
jev_allowed: state.jev_allowed,
|
||||
status: state.status,
|
||||
task_labels: state.labels.map((l) => ({
|
||||
name: l.name.trim(),
|
||||
desc: l.desc,
|
||||
...(l.rules_label ? { rules_label: l.rules_label } : {}),
|
||||
})),
|
||||
difficulty_levels: profile?.difficulty_levels_obj || undefined,
|
||||
matrix,
|
||||
rules,
|
||||
models: state.models.map((m) => ({
|
||||
model_name: m.model_name,
|
||||
model_tier: Number(m.model_tier) || 0,
|
||||
description: m.description,
|
||||
enabled: m.enabled,
|
||||
capabilities: {
|
||||
...m.caps,
|
||||
max_context: Number(m.caps.max_context) || 0,
|
||||
},
|
||||
})),
|
||||
};
|
||||
setSaving(true);
|
||||
try {
|
||||
await saveProfile(mode, orgId, payload);
|
||||
showSuccess(t('已保存'));
|
||||
onSaved?.();
|
||||
} catch (e) {
|
||||
showError(e?.message || t('保存失败,请稍后重试'));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const tierOptions = [0, 1, 2, 3, 4].map((v) => ({
|
||||
label: `${t('能力档')} ${v}`,
|
||||
value: v,
|
||||
}));
|
||||
const strategyOptions = [
|
||||
{ label: t('质量优先'), value: 'quality' },
|
||||
{ label: t('平衡'), value: 'balanced' },
|
||||
{ label: t('成本优先'), value: 'cost' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
rootClassName='smart-router-sheet'
|
||||
open={visible}
|
||||
onClose={onClose}
|
||||
size={Math.min(
|
||||
820,
|
||||
typeof window !== 'undefined' ? window.innerWidth : 820,
|
||||
)}
|
||||
title={profile ? t('编辑智能路由集合') : t('新建智能路由集合')}
|
||||
footer={
|
||||
<div className='smart-router-sheet-footer'>
|
||||
<Button onClick={onClose}>{t('取消')}</Button>
|
||||
<Button type='primary' loading={saving} onClick={handleSave}>
|
||||
{t('保存')}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{/* 字段均为受控 state;Form 只提供竖排标签与间距,不接管取值、校验与提交 */}
|
||||
<Form layout='vertical' component='div' requiredMark={false}>
|
||||
<Collapse
|
||||
activeKey={activePanels}
|
||||
onChange={(keys) => setActivePanels(keys || [])}
|
||||
items={[
|
||||
{
|
||||
key: 'basic',
|
||||
label: t('基本信息'),
|
||||
children: (
|
||||
<div className='smart-router-grid'>
|
||||
<Form.Item
|
||||
label={t(
|
||||
'短名(虚拟模型名为 router/短名,创建后不可修改)',
|
||||
)}
|
||||
>
|
||||
<Input
|
||||
value={state.slug}
|
||||
disabled={!!state.id}
|
||||
prefix='router/'
|
||||
onChange={(e) =>
|
||||
set('slug', e.target.value.toLowerCase())
|
||||
}
|
||||
placeholder='coding'
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label={t('名称')}>
|
||||
<Input
|
||||
value={state.name}
|
||||
onChange={(e) => set('name', e.target.value)}
|
||||
maxLength={64}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
className='smart-router-grid-full'
|
||||
label={t('说明')}
|
||||
>
|
||||
<Input
|
||||
value={state.description}
|
||||
onChange={(e) => set('description', e.target.value)}
|
||||
maxLength={255}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label={t('策略')}>
|
||||
<Select
|
||||
value={state.strategy}
|
||||
options={strategyOptions}
|
||||
onChange={(v) => set('strategy', v)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label={t('高级:难度档阈值 τ1,τ2,τ3(留空使用策略默认值)')}
|
||||
>
|
||||
<Input
|
||||
value={state.tier_thresholds}
|
||||
onChange={(e) => set('tier_thresholds', e.target.value)}
|
||||
placeholder='0.45,0.50,0.55'
|
||||
/>
|
||||
</Form.Item>
|
||||
<div className='smart-router-inline'>
|
||||
<Switch
|
||||
size='small'
|
||||
checked={state.status === 1}
|
||||
onChange={(v) => set('status', v ? 1 : 2)}
|
||||
aria-label={t('启用')}
|
||||
/>
|
||||
<Text>{t('启用')}</Text>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'models',
|
||||
label: t('候选模型'),
|
||||
children: (
|
||||
<div className='smart-router-stack'>
|
||||
<Text type='secondary' className='smart-router-sub'>
|
||||
{t(
|
||||
'能力档 0~4:数值越大能力越强;推理模型通常配为 4。能力标签用于按请求过滤候选。',
|
||||
)}
|
||||
</Text>
|
||||
{state.models.map((m, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className='smart-router-card smart-router-card--compact'
|
||||
>
|
||||
<div className='smart-router-inline'>
|
||||
<CreatableSelect
|
||||
className='smart-router-model-select'
|
||||
value={m.model_name || undefined}
|
||||
options={modelOptions.filter(
|
||||
(o) =>
|
||||
o.value === m.model_name ||
|
||||
!state.models.some(
|
||||
(x, i) => i !== idx && x.model_name === o.value,
|
||||
),
|
||||
)}
|
||||
placeholder={t('选择模型')}
|
||||
aria-label={t('选择模型')}
|
||||
onChange={(v) =>
|
||||
updateModel(idx, { model_name: v || '' })
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
style={{ width: 150 }}
|
||||
value={m.model_tier}
|
||||
options={tierOptions}
|
||||
aria-label={t('能力档')}
|
||||
onChange={(v) => updateModel(idx, { model_tier: v })}
|
||||
/>
|
||||
<Switch
|
||||
size='small'
|
||||
checked={m.enabled}
|
||||
onChange={(v) => updateModel(idx, { enabled: v })}
|
||||
aria-label={t('启用')}
|
||||
/>
|
||||
<Button
|
||||
type='text'
|
||||
danger
|
||||
icon={<Trash2 size={16} />}
|
||||
aria-label={t('删除')}
|
||||
onClick={() => removeModel(idx)}
|
||||
/>
|
||||
</div>
|
||||
<div className='smart-router-inline smart-router-section'>
|
||||
<Checkbox
|
||||
checked={m.caps.vision}
|
||||
onChange={(e) =>
|
||||
updateCaps(idx, { vision: e.target.checked })
|
||||
}
|
||||
>
|
||||
{t('图片输入')}
|
||||
</Checkbox>
|
||||
<Checkbox
|
||||
checked={m.caps.tools}
|
||||
onChange={(e) =>
|
||||
updateCaps(idx, { tools: e.target.checked })
|
||||
}
|
||||
>
|
||||
{t('工具调用')}
|
||||
</Checkbox>
|
||||
<Checkbox
|
||||
checked={m.caps.json_mode}
|
||||
onChange={(e) =>
|
||||
updateCaps(idx, { json_mode: e.target.checked })
|
||||
}
|
||||
>
|
||||
{t('JSON 输出')}
|
||||
</Checkbox>
|
||||
<Checkbox
|
||||
checked={m.caps.reasoning}
|
||||
onChange={(e) =>
|
||||
updateCaps(idx, { reasoning: e.target.checked })
|
||||
}
|
||||
>
|
||||
{t('推理模型')}
|
||||
</Checkbox>
|
||||
<InputNumber
|
||||
style={{ width: 200 }}
|
||||
prefix={t('上下文')}
|
||||
min={0}
|
||||
value={m.caps.max_context}
|
||||
onChange={(v) =>
|
||||
updateCaps(idx, { max_context: Number(v) || 0 })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<Button
|
||||
icon={<Plus size={16} />}
|
||||
onClick={() =>
|
||||
set('models', [
|
||||
...state.models,
|
||||
{
|
||||
model_name: '',
|
||||
model_tier: 1,
|
||||
description: '',
|
||||
enabled: true,
|
||||
caps: { ...emptyCaps },
|
||||
},
|
||||
])
|
||||
}
|
||||
>
|
||||
{t('添加候选模型')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'labels',
|
||||
label: t('任务标签'),
|
||||
children: (
|
||||
<div className='smart-router-stack'>
|
||||
<Text type='secondary' className='smart-router-sub'>
|
||||
{t(
|
||||
'标签修改后,任务置信度阈值建议观察 7 天后再调整。必须包含 general。',
|
||||
)}
|
||||
</Text>
|
||||
{state.labels.map((l) => {
|
||||
const locked = l.id === generalIdRef.current;
|
||||
const invalid =
|
||||
duplicateLabels.has(l.name) ||
|
||||
!LABEL_PATTERN.test(l.name);
|
||||
return (
|
||||
<div key={l.id} className='smart-router-inline'>
|
||||
<Input
|
||||
style={{ width: 160 }}
|
||||
value={l.name}
|
||||
disabled={locked}
|
||||
status={invalid ? 'error' : undefined}
|
||||
aria-label={t('任务类型')}
|
||||
onChange={(e) =>
|
||||
updateLabel(l.id, {
|
||||
name: e.target.value.toLowerCase(),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
style={{ flex: 1, minWidth: 200 }}
|
||||
value={l.desc}
|
||||
aria-label={t('说明')}
|
||||
onChange={(e) =>
|
||||
updateLabel(l.id, { desc: e.target.value })
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
style={{ width: 170 }}
|
||||
placeholder={t('对应规则判定器标签')}
|
||||
allowClear
|
||||
value={l.rules_label || undefined}
|
||||
options={RULES_LABELS.map((x) => ({
|
||||
label: x,
|
||||
value: x,
|
||||
}))}
|
||||
onChange={(v) =>
|
||||
updateLabel(l.id, { rules_label: v || '' })
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
type='text'
|
||||
danger
|
||||
icon={<Trash2 size={16} />}
|
||||
disabled={locked}
|
||||
aria-label={t('删除')}
|
||||
onClick={() => removeLabel(l.id)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{duplicateLabels.size > 0 && (
|
||||
<Text type='danger' className='smart-router-sub'>
|
||||
{t('任务标签不能重名')}
|
||||
</Text>
|
||||
)}
|
||||
<div>
|
||||
<Button
|
||||
icon={<Plus size={16} />}
|
||||
disabled={state.labels.length >= 32}
|
||||
onClick={addLabel}
|
||||
>
|
||||
{t('添加标签')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'matrix',
|
||||
label: t('路由矩阵'),
|
||||
children: (
|
||||
<div className='smart-router-stack'>
|
||||
<div className='smart-router-toolbar'>
|
||||
<Text type='secondary' className='smart-router-sub'>
|
||||
{t('行是任务类型,列是难度档;general 行必须全部填写。')}
|
||||
</Text>
|
||||
<Button onClick={applyAutoMatrix}>
|
||||
{t('一键生成(仅作为初始值)')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className='smart-router-matrix'>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{t('任务类型')}</th>
|
||||
<th>{t('0 简单')}</th>
|
||||
<th>{t('1 常规')}</th>
|
||||
<th>{t('2 较难')}</th>
|
||||
<th>{t('3 困难')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{state.labels.map((l) => (
|
||||
<tr key={l.id}>
|
||||
<td className='smart-router-mono smart-router-sub'>
|
||||
{l.name}
|
||||
</td>
|
||||
{[0, 1, 2, 3].map((col) => (
|
||||
<td key={col}>
|
||||
<Select
|
||||
style={{ width: 150 }}
|
||||
size='small'
|
||||
allowClear={l.name !== 'general'}
|
||||
value={
|
||||
(state.matrix[l.id] || [])[col] || undefined
|
||||
}
|
||||
options={candidateOptions}
|
||||
aria-label={`${l.name} · ${col}`}
|
||||
onChange={(v) => setCell(l.id, col, v)}
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'roles',
|
||||
label: t('模型角色与阈值'),
|
||||
children: (
|
||||
<div className='smart-router-grid'>
|
||||
<Form.Item label={t('默认模型(判定失败时使用)')}>
|
||||
<Select
|
||||
value={state.default_model || undefined}
|
||||
options={candidateOptions}
|
||||
onChange={(v) => set('default_model', v || '')}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label={t('基线模型(用于节省率,必须出现在矩阵中)')}
|
||||
>
|
||||
<Select
|
||||
value={state.baseline_model || undefined}
|
||||
options={candidateOptions}
|
||||
onChange={(v) => set('baseline_model', v || '')}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label={t('推理模型(可选)')}>
|
||||
<Select
|
||||
allowClear
|
||||
value={state.reasoning_model || undefined}
|
||||
options={candidateOptions}
|
||||
onChange={(v) => set('reasoning_model', v || '')}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label={t('推理阈值(0 表示默认 0.7)')}>
|
||||
<InputNumber
|
||||
className='w-full'
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={state.reasoning_threshold}
|
||||
onChange={(v) =>
|
||||
set('reasoning_threshold', Number(v) || 0)
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label={t('任务置信度下限(0 表示默认)')}>
|
||||
<InputNumber
|
||||
className='w-full'
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={state.min_task_conf}
|
||||
onChange={(v) => set('min_task_conf', Number(v) || 0)}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'session',
|
||||
label: t('会话与判定'),
|
||||
children: (
|
||||
<div className='smart-router-stack'>
|
||||
<div className='smart-router-inline'>
|
||||
<Switch
|
||||
size='small'
|
||||
checked={state.sticky_enabled}
|
||||
onChange={(v) => set('sticky_enabled', v)}
|
||||
aria-label={t('会话粘性(只升档不降档)')}
|
||||
/>
|
||||
<Text>{t('会话粘性(只升档不降档)')}</Text>
|
||||
<InputNumber
|
||||
style={{ width: 220 }}
|
||||
prefix={t('有效期(秒)')}
|
||||
min={60}
|
||||
max={86400}
|
||||
value={state.sticky_ttl_sec}
|
||||
onChange={(v) => set('sticky_ttl_sec', Number(v) || 1800)}
|
||||
/>
|
||||
</div>
|
||||
<div className='smart-router-inline'>
|
||||
<Switch
|
||||
size='small'
|
||||
checked={state.jev_allowed}
|
||||
onChange={(v) => set('jev_allowed', v)}
|
||||
aria-label={t(
|
||||
'允许使用 Jev 判定(还需平台开启与出境同意)',
|
||||
)}
|
||||
/>
|
||||
<Text>
|
||||
{t('允许使用 Jev 判定(还需平台开启与出境同意)')}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'rules',
|
||||
label: t('自定义规则(高级)'),
|
||||
children: (
|
||||
<div className='smart-router-stack'>
|
||||
<Alert
|
||||
type='info'
|
||||
showIcon
|
||||
title={t(
|
||||
'JSON 数组,按顺序第一条命中即生效。动作:model 直接指定模型;tier(可带 row)强制难度档;tier_min / tier_max 约束区间。',
|
||||
)}
|
||||
/>
|
||||
<TextArea
|
||||
className='smart-router-mono'
|
||||
autoSize={{ minRows: 6, maxRows: 16 }}
|
||||
value={state.rules}
|
||||
aria-label={t('自定义规则(高级)')}
|
||||
onChange={(e) => set('rules', e.target.value)}
|
||||
placeholder='[{"if":{"user_contains":"review"},"then":{"tier":3,"row":"coding"}}]'
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Form>
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfileEditor;
|
||||
@@ -0,0 +1,272 @@
|
||||
/*
|
||||
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, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Empty,
|
||||
Popconfirm,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { Plus } from '../common/icons/ActionIcons';
|
||||
import { copy, showError, showSuccess } from '../../helpers';
|
||||
import { deleteProfile, listCandidateModels, listProfiles } from './api';
|
||||
import ProfileEditor from './ProfileEditor';
|
||||
import SimulateModal from './SimulateModal';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
|
||||
const { t } = useTranslation();
|
||||
const [list, setList] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [editing, setEditing] = useState(null); // null 关闭;{} 新建;profile 编辑
|
||||
const [simulating, setSimulating] = useState(null);
|
||||
const [models, setModels] = useState([]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
setList((await listProfiles(mode, orgId)) || []);
|
||||
} catch (e) {
|
||||
setError(e?.message || t('加载失败'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [mode, orgId, t]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canWrite) return;
|
||||
listCandidateModels(mode, orgId)
|
||||
.then(setModels)
|
||||
.catch(() => setModels([]));
|
||||
}, [mode, orgId, canWrite]);
|
||||
|
||||
const strategyText = (s) =>
|
||||
({ quality: t('质量优先'), balanced: t('平衡'), cost: t('成本优先') })[s] ||
|
||||
s;
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('虚拟模型'),
|
||||
dataIndex: 'virtual_model',
|
||||
width: 280,
|
||||
render: (v, r) => (
|
||||
<div className='min-w-0'>
|
||||
<Button
|
||||
type='link'
|
||||
size='small'
|
||||
className='smart-router-mono smart-router-copy'
|
||||
aria-label={`${t('复制')} ${v}`}
|
||||
onClick={async () => {
|
||||
if (await copy(v)) showSuccess(t('已复制'));
|
||||
}}
|
||||
>
|
||||
{v}
|
||||
</Button>
|
||||
<div>
|
||||
<Text
|
||||
type='secondary'
|
||||
className='smart-router-sub smart-router-name'
|
||||
ellipsis={{ tooltip: r.name }}
|
||||
>
|
||||
{r.name}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('策略'),
|
||||
dataIndex: 'strategy',
|
||||
width: 110,
|
||||
render: strategyText,
|
||||
},
|
||||
{
|
||||
title: t('候选模型'),
|
||||
dataIndex: 'models',
|
||||
width: 100,
|
||||
align: 'right',
|
||||
render: (ms) => (
|
||||
<span className='smart-router-num'>
|
||||
{(ms || []).filter((m) => m.enabled).length}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('默认模型'),
|
||||
dataIndex: 'default_model',
|
||||
width: 220,
|
||||
render: (v) => <span className='smart-router-mono'>{v}</span>,
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: 140,
|
||||
render: (v, r) => (
|
||||
<Space size={8}>
|
||||
{v === 1 ? (
|
||||
<Tag color='success' variant='filled'>
|
||||
{t('启用')}
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag color='default' variant='filled'>
|
||||
{t('停用')}
|
||||
</Tag>
|
||||
)}
|
||||
{r.jev_allowed && (
|
||||
<Tag color='blue' variant='filled'>
|
||||
Jev
|
||||
</Tag>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
key: 'actions',
|
||||
fixed: 'right',
|
||||
width: 180,
|
||||
render: (_, r) => (
|
||||
<Space size={8} wrap>
|
||||
<Button
|
||||
type='link'
|
||||
size='small'
|
||||
onClick={() => setSimulating(r)}
|
||||
disabled={!canWrite}
|
||||
>
|
||||
{t('试路由')}
|
||||
</Button>
|
||||
{canWrite && (
|
||||
<>
|
||||
<Button type='link' size='small' onClick={() => setEditing(r)}>
|
||||
{t('编辑')}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={t('确认删除该集合?')}
|
||||
description={t('使用该虚拟模型名的请求将返回"模型不存在"。')}
|
||||
okButtonProps={{ danger: true }}
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await deleteProfile(mode, orgId, r.id);
|
||||
showSuccess(t('已删除'));
|
||||
load();
|
||||
} catch (e) {
|
||||
if (e?.message) showError(e.message);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button type='link' size='small' danger>
|
||||
{t('删除')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='smart-router-stack'>
|
||||
<div className='smart-router-toolbar'>
|
||||
<Text type='secondary' className='smart-router-sub'>
|
||||
{emptyHint}
|
||||
</Text>
|
||||
{canWrite && (
|
||||
<Button
|
||||
type='primary'
|
||||
icon={<Plus size={16} />}
|
||||
onClick={() => setEditing({})}
|
||||
>
|
||||
{t('新建集合')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{error ? (
|
||||
<Alert
|
||||
type='error'
|
||||
showIcon
|
||||
title={error}
|
||||
action={
|
||||
<Button size='small' onClick={load}>
|
||||
{t('重试')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<Table
|
||||
rowKey='id'
|
||||
size='middle'
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={list}
|
||||
pagination={false}
|
||||
scroll={{ x: 'max-content' }}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={t('还没有智能路由集合')}
|
||||
>
|
||||
{canWrite && (
|
||||
<Button type='primary' onClick={() => setEditing({})}>
|
||||
{t('新建集合')}
|
||||
</Button>
|
||||
)}
|
||||
</Empty>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<ProfileEditor
|
||||
visible={editing !== null}
|
||||
mode={mode}
|
||||
orgId={orgId}
|
||||
profile={editing && editing.id ? editing : null}
|
||||
candidateModels={models}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => {
|
||||
setEditing(null);
|
||||
load();
|
||||
}}
|
||||
/>
|
||||
<SimulateModal
|
||||
visible={!!simulating}
|
||||
mode={mode}
|
||||
orgId={orgId}
|
||||
profile={simulating}
|
||||
onClose={() => setSimulating(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfileTable;
|
||||
@@ -0,0 +1,209 @@
|
||||
/*
|
||||
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, { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, Button, Input, Modal, Progress, Tag, Typography } from 'antd';
|
||||
import { simulateProfile } from './api';
|
||||
import { gateText, reasonText, srcText } from './labels';
|
||||
|
||||
const { Text } = Typography;
|
||||
const { TextArea } = Input;
|
||||
|
||||
const ProbBars = ({ probs }) => {
|
||||
if (!probs) return null;
|
||||
const entries = Array.isArray(probs)
|
||||
? probs.map((v, i) => [String(i), v])
|
||||
: Object.entries(probs).sort((a, b) => b[1] - a[1]);
|
||||
return (
|
||||
<div className='smart-router-prob-list'>
|
||||
{entries.map(([k, v]) => (
|
||||
<div key={k} className='smart-router-prob'>
|
||||
<span className='smart-router-mono smart-router-prob-label'>{k}</span>
|
||||
<Progress
|
||||
className='smart-router-prob-bar'
|
||||
percent={Math.round((v || 0) * 100)}
|
||||
showInfo={false}
|
||||
size='small'
|
||||
/>
|
||||
<span className='smart-router-num smart-router-prob-value'>
|
||||
{Math.round((v || 0) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const SimulateModal = ({ visible, mode, orgId, profile, onClose }) => {
|
||||
const { t } = useTranslation();
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [system, setSystem] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [result, setResult] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
setResult(null);
|
||||
setError('');
|
||||
}
|
||||
}, [visible]);
|
||||
|
||||
// 换了集合就清空上一次的输入
|
||||
useEffect(() => {
|
||||
setPrompt('');
|
||||
setSystem('');
|
||||
}, [profile?.id]);
|
||||
|
||||
const run = async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
setResult(
|
||||
await simulateProfile(mode, orgId, profile.id, { prompt, system }),
|
||||
);
|
||||
} catch (e) {
|
||||
setError(e?.message || t('试路由失败,请稍后重试'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
rootClassName='smart-router-sheet'
|
||||
open={visible}
|
||||
title={`${t('试路由')} · router/${profile?.slug || ''}`}
|
||||
onCancel={onClose}
|
||||
footer={null}
|
||||
width={760}
|
||||
>
|
||||
<div className='smart-router-stack'>
|
||||
<TextArea
|
||||
autoSize={{ minRows: 2, maxRows: 4 }}
|
||||
placeholder={t('可选:system 提示词')}
|
||||
aria-label={t('可选:system 提示词')}
|
||||
value={system}
|
||||
onChange={(e) => setSystem(e.target.value)}
|
||||
/>
|
||||
<TextArea
|
||||
autoSize={{ minRows: 4, maxRows: 10 }}
|
||||
placeholder={t('粘贴一段要路由的用户请求')}
|
||||
aria-label={t('粘贴一段要路由的用户请求')}
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
/>
|
||||
<div>
|
||||
<Button
|
||||
type='primary'
|
||||
loading={loading}
|
||||
disabled={!prompt.trim()}
|
||||
onClick={run}
|
||||
>
|
||||
{t('试路由')}
|
||||
</Button>
|
||||
</div>
|
||||
{error && <Alert type='error' showIcon title={error} />}
|
||||
{result && (
|
||||
<div className='smart-router-card'>
|
||||
{result.error ? (
|
||||
<Alert type='warning' showIcon title={result.error} />
|
||||
) : (
|
||||
<dl className='smart-router-kv'>
|
||||
<dt>{t('实际模型')}</dt>
|
||||
<dd>
|
||||
<span className='smart-router-mono'>{result.model}</span>{' '}
|
||||
<Tag variant='filled'>
|
||||
{t('能力档')} {result.model_tier}
|
||||
</Tag>
|
||||
</dd>
|
||||
<dt>{t('判定来源')}</dt>
|
||||
<dd>
|
||||
<Tag variant='filled' color='blue'>
|
||||
{srcText(t, result.src)}
|
||||
</Tag>{' '}
|
||||
<span className='smart-router-mono'>{result.why}</span>
|
||||
</dd>
|
||||
<dt>{t('合规闸门')}</dt>
|
||||
<dd>{gateText(t, result.gate)}</dd>
|
||||
<dt>{t('任务 / 难度档')}</dt>
|
||||
<dd>
|
||||
{result.task} /{' '}
|
||||
<span className='smart-router-num'>
|
||||
{result.difficulty_tier}
|
||||
</span>
|
||||
</dd>
|
||||
<dt>{t('规则判定器')}</dt>
|
||||
<dd>
|
||||
{result.rules_task} /{' '}
|
||||
<span className='smart-router-num'>{result.rules_tier}</span>
|
||||
</dd>
|
||||
{result.judge_ms > 0 && (
|
||||
<>
|
||||
<dt>{t('判定耗时')}</dt>
|
||||
<dd className='smart-router-num'>{result.judge_ms} ms</dd>
|
||||
</>
|
||||
)}
|
||||
<dt>{t('基线模型')}</dt>
|
||||
<dd className='smart-router-mono'>{result.baseline_model}</dd>
|
||||
{result.features && (
|
||||
<>
|
||||
<dt>{t('请求特征')}</dt>
|
||||
<dd className='smart-router-num'>
|
||||
{t('预估 token')} {result.features.est_tokens} ·{' '}
|
||||
{t('对话 token')} {result.features.conv_tokens} ·{' '}
|
||||
{t('用户轮次')} {result.features.user_turns}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
{result.task_probs && Object.keys(result.task_probs).length > 0 && (
|
||||
<div className='smart-router-section'>
|
||||
<Text strong>{t('任务类型概率')}</Text>
|
||||
<ProbBars probs={result.task_probs} />
|
||||
</div>
|
||||
)}
|
||||
{result.difficulty_probs && result.difficulty_probs.length > 0 && (
|
||||
<div className='smart-router-section'>
|
||||
<Text strong>{t('难度概率')}</Text>
|
||||
<ProbBars probs={result.difficulty_probs} />
|
||||
</div>
|
||||
)}
|
||||
{result.filtered && Object.keys(result.filtered).length > 0 && (
|
||||
<div className='smart-router-section'>
|
||||
<Text strong>{t('被过滤的候选')}</Text>
|
||||
<div className='smart-router-tags'>
|
||||
{Object.entries(result.filtered).map(([m, r]) => (
|
||||
<Tag key={m} variant='filled' color='default'>
|
||||
{m} · {reasonText(t, r)}
|
||||
</Tag>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default SimulateModal;
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
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 { API, showError } from '../../helpers';
|
||||
import i18n from '../../i18n/i18n';
|
||||
|
||||
// 智能模型路由接口(后端 router/smart-router.go)。
|
||||
// mode: personal(个人)/ admin(平台 system 集合)/ org(企业,X-Org-Id 由 API 拦截器注入)
|
||||
// 所有请求都跳过全局错误提示(skipErrorHandler),由调用方只弹一次业务文案,避免英文报错与重复提示。
|
||||
export const routerBase = (mode) => {
|
||||
if (mode === 'admin') return '/api/router/admin';
|
||||
if (mode === 'org') return '/api/org/router';
|
||||
return '/api/router';
|
||||
};
|
||||
|
||||
const opts = (orgId, extra = {}) => ({
|
||||
skipErrorHandler: true,
|
||||
...(orgId ? { headers: { 'X-Org-Id': String(orgId) } } : {}),
|
||||
...extra,
|
||||
});
|
||||
|
||||
const friendly = (e) => {
|
||||
const msg = e?.response?.data?.message;
|
||||
if (msg) return msg;
|
||||
const status = e?.response?.status;
|
||||
if (status === 429) return i18n.t('操作过于频繁,请稍后再试');
|
||||
if (status === 401 || status === 403) return i18n.t('没有权限执行该操作');
|
||||
return i18n.t('请求失败,请稍后重试');
|
||||
};
|
||||
|
||||
const call = async (fn) => {
|
||||
let res;
|
||||
try {
|
||||
res = await fn();
|
||||
} catch (e) {
|
||||
// 401 交给全局处理:清理登录态并跳转登录页(skipErrorHandler 会跳过它)。
|
||||
// 之后不再抛出,调用方也就不会再弹一次"没有权限"——页面马上会跳走
|
||||
if (e?.response?.status === 401) {
|
||||
showError(e);
|
||||
return new Promise(() => {});
|
||||
}
|
||||
throw new Error(friendly(e));
|
||||
}
|
||||
const { success, message, data } = res?.data || {};
|
||||
if (!success) throw new Error(message || i18n.t('请求失败,请稍后重试'));
|
||||
return data;
|
||||
};
|
||||
|
||||
export const listProfiles = (mode, orgId) =>
|
||||
call(() => API.get(`${routerBase(mode)}/profiles`, opts(orgId)));
|
||||
|
||||
export const saveProfile = (mode, orgId, profile) => {
|
||||
const base = routerBase(mode);
|
||||
return call(() =>
|
||||
profile.id
|
||||
? API.put(`${base}/profiles/${profile.id}`, profile, opts(orgId))
|
||||
: API.post(`${base}/profiles`, profile, opts(orgId)),
|
||||
);
|
||||
};
|
||||
|
||||
export const deleteProfile = (mode, orgId, id) =>
|
||||
call(() => API.delete(`${routerBase(mode)}/profiles/${id}`, opts(orgId)));
|
||||
|
||||
export const simulateProfile = (mode, orgId, id, payload) =>
|
||||
call(() =>
|
||||
API.post(
|
||||
`${routerBase(mode)}/profiles/${id}/simulate`,
|
||||
payload,
|
||||
opts(orgId),
|
||||
),
|
||||
);
|
||||
|
||||
export const listDecisions = (mode, orgId, params) =>
|
||||
call(() => API.get(`${routerBase(mode)}/decisions`, opts(orgId, { params })));
|
||||
|
||||
export const getConsents = (mode, orgId) =>
|
||||
call(() => API.get(`${routerBase(mode)}/consents`, opts(orgId)));
|
||||
|
||||
// 个人是否仍有生效中的出境同意:平台关闭智能路由后,侧边栏据此保留入口供撤回(会话内缓存,避免每次进页面都请求)
|
||||
const CONSENT_CACHE_KEY = 'smart_router_personal_consent_granted';
|
||||
|
||||
export const readPersonalConsentCache = () => {
|
||||
try {
|
||||
return sessionStorage.getItem(CONSENT_CACHE_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const writePersonalConsentCache = (rows) => {
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
CONSENT_CACHE_KEY,
|
||||
(rows || []).some((x) => x && x.granted === true) ? '1' : '0',
|
||||
);
|
||||
} catch {
|
||||
// 无痕模式等场景下 sessionStorage 不可用:不缓存即可
|
||||
}
|
||||
};
|
||||
|
||||
export const loadPersonalConsentGranted = async () => {
|
||||
const rows = await getConsents('personal');
|
||||
writePersonalConsentCache(rows);
|
||||
return (rows || []).some((x) => x && x.granted === true);
|
||||
};
|
||||
|
||||
export const updateConsent = async (mode, orgId, kind, granted) => {
|
||||
const rows = await call(() =>
|
||||
API.put(`${routerBase(mode)}/consents`, { kind, granted }, opts(orgId)),
|
||||
);
|
||||
if (mode !== 'org' && mode !== 'admin') writePersonalConsentCache(rows);
|
||||
return rows;
|
||||
};
|
||||
|
||||
// 候选模型下拉的数据来源:个人=自己分组可用模型;平台=全部启用模型;企业=企业可用模型
|
||||
export const listCandidateModels = async (mode, orgId) => {
|
||||
let url = '/api/user/models';
|
||||
if (mode === 'admin') url = '/api/channel/models_enabled';
|
||||
if (mode === 'org') url = '/api/org/models';
|
||||
const data = await call(() => API.get(url, opts(orgId)));
|
||||
return (data || []).filter(
|
||||
(m) => typeof m === 'string' && !m.startsWith('router/'),
|
||||
);
|
||||
};
|
||||
|
||||
export const getAdminStatus = () =>
|
||||
call(() => API.get('/api/router/admin/status', opts()));
|
||||
|
||||
export const setJevKey = (provider, key, clear = false) =>
|
||||
call(() =>
|
||||
API.put('/api/router/admin/jev-key', { provider, key, clear }, opts()),
|
||||
);
|
||||
|
||||
export const loadOptions = () => call(() => API.get('/api/option/', opts()));
|
||||
|
||||
export const saveOption = (key, value) =>
|
||||
call(() => API.put('/api/option/', { key, value }, opts()));
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// 判定来源 / 闸门 / 过滤原因的展示文案(与后端 decide.go、gate.go、filter.go 的代码一一对应)
|
||||
export const reasonText = (t, code) =>
|
||||
({
|
||||
disabled: t('已停用'),
|
||||
level: t('等级不可用'),
|
||||
scope: t('不在企业作用域白名单'),
|
||||
experience_center: t('不在体验中心白名单'),
|
||||
no_channel: t('分组内没有可用渠道'),
|
||||
channel_query_failed: t('渠道查询失败'),
|
||||
protocol: t('渠道不支持该入口格式'),
|
||||
vision: t('不支持图片输入'),
|
||||
tools: t('不支持工具调用'),
|
||||
json_mode: t('不支持 JSON 输出'),
|
||||
context: t('超出上下文长度'),
|
||||
tool_id_format: t('工具调用 ID 格式不兼容'),
|
||||
strip_incompatible: t('不兼容历史剥离'),
|
||||
reasoning: t('不支持推理 / 思考'),
|
||||
})[code] || code;
|
||||
|
||||
// Jev 调用失败原因(jev.FailureReason);http_xxx 为上游状态码
|
||||
export const jevReasonText = (t, code) => {
|
||||
if (!code) return '';
|
||||
if (/^http_\d+$/.test(code))
|
||||
return t('上游返回 {{code}}', { code: code.slice(5) });
|
||||
return (
|
||||
{
|
||||
timeout: t('判定超时'),
|
||||
breaker: t('通道熔断中'),
|
||||
no_key: t('未配置密钥'),
|
||||
parse: t('返回格式异常'),
|
||||
error: t('调用失败'),
|
||||
}[code] || code
|
||||
);
|
||||
};
|
||||
|
||||
export const gateText = (t, code) =>
|
||||
({
|
||||
jev: t('已调用 Jev'),
|
||||
platform_off: t('平台未开启 Jev 出境'),
|
||||
sensitive: t('命中敏感词'),
|
||||
desens_off: t('脱敏未启用'),
|
||||
desens_block: t('脱敏策略会拦截'),
|
||||
guard_input: t('内容审核输入审查生效'),
|
||||
org_no_consent: t('企业未授权'),
|
||||
user_no_consent: t('个人未授权'),
|
||||
profile_off: t('集合未允许使用 Jev'),
|
||||
no_quota: t('余额不足,未调用 Jev'),
|
||||
jev_cap: t('今日 Jev 判定次数已达上限'),
|
||||
desens_residual: t('脱敏后仍有敏感信息'),
|
||||
'n/a': t('未经过闸门'),
|
||||
})[code] ||
|
||||
(code && code.startsWith('rules:') ? gateText(t, code.slice(6)) : code) ||
|
||||
'-';
|
||||
|
||||
export const srcText = (t, code) =>
|
||||
({
|
||||
jev: t('Jev 判定'),
|
||||
cache: t('判定缓存'),
|
||||
rules: t('规则判定器'),
|
||||
rules_fallback: t('Jev 失败,规则判定'),
|
||||
rule: t('自定义规则'),
|
||||
rule_tier: t('自定义规则强制档位'),
|
||||
forced: t('请求指定档位'),
|
||||
single: t('唯一候选'),
|
||||
sticky: t('会话粘性'),
|
||||
continuation: t('工具调用续写'),
|
||||
default: t('默认模型'),
|
||||
cheapest: t('最便宜的候选'),
|
||||
disabled: t('未启用,使用默认模型'),
|
||||
error: t('路由失败'),
|
||||
})[code] || code;
|
||||
@@ -0,0 +1,271 @@
|
||||
/* 智能模型路由:配色只引用语义变量(tokens.css),同时用于控制台与企业中心,保持中性 */
|
||||
.smart-router-page,
|
||||
.smart-router-scope,
|
||||
.smart-router-sheet {
|
||||
--sr-ink: var(--text-primary);
|
||||
--sr-muted: var(--text-secondary);
|
||||
--sr-line: var(--border-subtle);
|
||||
--sr-accent: var(--brand-primary);
|
||||
}
|
||||
|
||||
.smart-router-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
color: var(--sr-ink);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.smart-router-alert {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
/* 控制台介绍区:无图标、无渐变的说明块;标题与内边距由公共页头 / 容器统一 */
|
||||
.smart-router-hero {
|
||||
padding: 16px 24px;
|
||||
border: 1px solid var(--sr-line);
|
||||
border-radius: 10px;
|
||||
background: var(--surface-card);
|
||||
}
|
||||
|
||||
.smart-router-eyebrow {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--sr-accent);
|
||||
}
|
||||
|
||||
.smart-router-hero h1 {
|
||||
margin: 4px 0 0;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
line-height: 24px;
|
||||
color: var(--sr-ink);
|
||||
}
|
||||
|
||||
.smart-router-hero p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 22px;
|
||||
color: var(--sr-muted);
|
||||
}
|
||||
|
||||
/* 区块卡:控制台 / 企业中心页内的子卡与弹层内结果卡 */
|
||||
.smart-router-card {
|
||||
border: 1px solid var(--sr-line);
|
||||
border-radius: 10px;
|
||||
background: var(--surface-card);
|
||||
padding: 16px 24px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.smart-router-card--compact {
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.smart-router-card-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
.smart-router-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.smart-router-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.smart-router-inline {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 16px;
|
||||
}
|
||||
|
||||
.smart-router-section {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.smart-router-state {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 24px 0;
|
||||
}
|
||||
|
||||
.smart-router-sub {
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.smart-router-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* 数据出境授权行 */
|
||||
.smart-router-consent-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 16px 24px;
|
||||
border: 1px solid var(--sr-line);
|
||||
border-radius: 10px;
|
||||
background: var(--surface-card);
|
||||
}
|
||||
|
||||
.smart-router-consent-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.smart-router-consent-head .ant-tag {
|
||||
margin-inline-end: 0;
|
||||
}
|
||||
|
||||
/* 集合表:可点击复制的虚拟模型名 */
|
||||
.smart-router-copy.ant-btn {
|
||||
height: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.smart-router-name {
|
||||
max-width: 260px;
|
||||
}
|
||||
|
||||
.smart-router-field-label {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.smart-router-field-label .ant-tag {
|
||||
margin-inline-end: 0;
|
||||
}
|
||||
|
||||
/* 编辑抽屉 */
|
||||
.smart-router-sheet-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.smart-router-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0 16px;
|
||||
}
|
||||
|
||||
.smart-router-grid-full {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.smart-router-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.smart-router-model-select {
|
||||
flex: 1;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.smart-router-mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.smart-router-num {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.smart-router-matrix {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.smart-router-matrix table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 8px 8px;
|
||||
min-width: 640px;
|
||||
}
|
||||
|
||||
.smart-router-matrix th {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--sr-muted);
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 试路由概率条:antd Progress,颜色沿用主题主色 */
|
||||
.smart-router-prob-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.smart-router-prob {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.smart-router-prob-label {
|
||||
width: 80px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.smart-router-prob-bar.ant-progress {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.smart-router-prob-value {
|
||||
width: 40px;
|
||||
flex: none;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.smart-router-kv {
|
||||
display: grid;
|
||||
grid-template-columns: max-content 1fr;
|
||||
gap: 8px 16px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.smart-router-kv dt {
|
||||
color: var(--sr-muted);
|
||||
}
|
||||
|
||||
.smart-router-kv dd {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
word-break: break-all;
|
||||
}
|
||||
@@ -390,7 +390,7 @@ export const getChannelsColumns = ({
|
||||
size='small'
|
||||
type='primary'
|
||||
theme='outline'
|
||||
onClick={(e) => {
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
writeClipboardText(record.remark)
|
||||
.then(() => {
|
||||
|
||||
@@ -180,6 +180,7 @@ const originInputs = {
|
||||
chat_image_to_images_enabled: false,
|
||||
system_prompt: '',
|
||||
system_prompt_override: false,
|
||||
responses_system_prompt_mode: 'native',
|
||||
client_only: false, // 只接受 Claude Code 客户端请求
|
||||
bound_user_ids: '', // 绑定用户ID列表
|
||||
os_restriction: [], // 操作系统白名单,仅 Claude 原生渠道(type=14)生效,空数组=无限制
|
||||
@@ -190,6 +191,7 @@ const originInputs = {
|
||||
sticky_user_id_mode: 'native', // 注入形态:native(仿 Claude Code 原生)/ opaque
|
||||
cache_breakpoint_fill: false, // 给完全没有 cache_control 的大上下文请求补一个缓存断点
|
||||
cache_breakpoint_min_tokens: 0, // 注入门限(估算 prompt token),0=用后端默认 10000
|
||||
cache_creation_default_ttl: '', // 未分档缓存创建按哪档计费,''=跟随全局,可选 5m/1h
|
||||
settings: '',
|
||||
// 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
|
||||
vertex_key_type: 'json',
|
||||
@@ -423,6 +425,8 @@ const EditChannelModal = (props) => {
|
||||
pass_through_body_enabled: false,
|
||||
chat_image_to_images_enabled: false,
|
||||
system_prompt: '',
|
||||
system_prompt_override: false,
|
||||
responses_system_prompt_mode: 'native',
|
||||
client_only: false,
|
||||
bound_user_ids: '',
|
||||
os_restriction: [],
|
||||
@@ -433,6 +437,7 @@ const EditChannelModal = (props) => {
|
||||
sticky_user_id_mode: 'native',
|
||||
cache_breakpoint_fill: false,
|
||||
cache_breakpoint_min_tokens: 0,
|
||||
cache_creation_default_ttl: '',
|
||||
});
|
||||
const showApiConfigCard = true; // 控制是否显示 API 配置卡片
|
||||
const getInitValues = () => ({
|
||||
@@ -626,6 +631,10 @@ const EditChannelModal = (props) => {
|
||||
data.system_prompt = parsedSettings.system_prompt || '';
|
||||
data.system_prompt_override =
|
||||
parsedSettings.system_prompt_override || false;
|
||||
data.responses_system_prompt_mode =
|
||||
parsedSettings.responses_system_prompt_mode === 'input_user_message'
|
||||
? 'input_user_message'
|
||||
: 'native';
|
||||
data.client_only = parsedSettings.client_only || false;
|
||||
data.bound_user_ids = parsedSettings.bound_user_ids || '';
|
||||
data.os_restriction = Array.isArray(parsedSettings.os_restriction)
|
||||
@@ -646,6 +655,11 @@ const EditChannelModal = (props) => {
|
||||
parsedSettings.cache_breakpoint_fill || false;
|
||||
data.cache_breakpoint_min_tokens =
|
||||
parsedSettings.cache_breakpoint_min_tokens || 0;
|
||||
data.cache_creation_default_ttl = ['5m', '1h'].includes(
|
||||
parsedSettings.cache_creation_default_ttl,
|
||||
)
|
||||
? parsedSettings.cache_creation_default_ttl
|
||||
: '';
|
||||
} catch (error) {
|
||||
console.error('解析渠道设置失败:', error);
|
||||
data.force_format = false;
|
||||
@@ -656,6 +670,7 @@ const EditChannelModal = (props) => {
|
||||
data.chat_image_to_images_enabled = false;
|
||||
data.system_prompt = '';
|
||||
data.system_prompt_override = false;
|
||||
data.responses_system_prompt_mode = 'native';
|
||||
data.client_only = false;
|
||||
data.bound_user_ids = '';
|
||||
data.os_restriction = [];
|
||||
@@ -666,6 +681,7 @@ const EditChannelModal = (props) => {
|
||||
data.sticky_user_id_mode = 'native';
|
||||
data.cache_breakpoint_fill = false;
|
||||
data.cache_breakpoint_min_tokens = 0;
|
||||
data.cache_creation_default_ttl = '';
|
||||
}
|
||||
} else {
|
||||
data.force_format = false;
|
||||
@@ -676,6 +692,7 @@ const EditChannelModal = (props) => {
|
||||
data.chat_image_to_images_enabled = false;
|
||||
data.system_prompt = '';
|
||||
data.system_prompt_override = false;
|
||||
data.responses_system_prompt_mode = 'native';
|
||||
data.client_only = false;
|
||||
data.bound_user_ids = '';
|
||||
data.os_restriction = [];
|
||||
@@ -686,6 +703,7 @@ const EditChannelModal = (props) => {
|
||||
data.sticky_user_id_mode = 'native';
|
||||
data.cache_breakpoint_fill = false;
|
||||
data.cache_breakpoint_min_tokens = 0;
|
||||
data.cache_creation_default_ttl = '';
|
||||
}
|
||||
|
||||
if (data.settings) {
|
||||
@@ -792,6 +810,8 @@ const EditChannelModal = (props) => {
|
||||
data.chat_image_to_images_enabled || false,
|
||||
system_prompt: data.system_prompt,
|
||||
system_prompt_override: data.system_prompt_override || false,
|
||||
responses_system_prompt_mode:
|
||||
data.responses_system_prompt_mode || 'native',
|
||||
client_only: data.client_only || false,
|
||||
bound_user_ids: data.bound_user_ids || '',
|
||||
os_restriction: Array.isArray(data.os_restriction)
|
||||
@@ -806,6 +826,7 @@ const EditChannelModal = (props) => {
|
||||
sticky_user_id_mode: data.sticky_user_id_mode || 'native',
|
||||
cache_breakpoint_fill: data.cache_breakpoint_fill || false,
|
||||
cache_breakpoint_min_tokens: data.cache_breakpoint_min_tokens || 0,
|
||||
cache_creation_default_ttl: data.cache_creation_default_ttl || '',
|
||||
});
|
||||
initialModelsRef.current = (data.models || [])
|
||||
.map((model) => (model || '').trim())
|
||||
@@ -1075,6 +1096,7 @@ const EditChannelModal = (props) => {
|
||||
chat_image_to_images_enabled: false,
|
||||
system_prompt: '',
|
||||
system_prompt_override: false,
|
||||
responses_system_prompt_mode: 'native',
|
||||
client_only: false,
|
||||
bound_user_ids: '',
|
||||
os_restriction: [],
|
||||
@@ -1085,6 +1107,7 @@ const EditChannelModal = (props) => {
|
||||
sticky_user_id_mode: 'native',
|
||||
cache_breakpoint_fill: false,
|
||||
cache_breakpoint_min_tokens: 0,
|
||||
cache_creation_default_ttl: '',
|
||||
});
|
||||
// 重置密钥模式状态
|
||||
setKeyMode('append');
|
||||
@@ -1403,6 +1426,11 @@ const EditChannelModal = (props) => {
|
||||
localInputs.chat_image_to_images_enabled || false,
|
||||
system_prompt: localInputs.system_prompt || '',
|
||||
system_prompt_override: localInputs.system_prompt_override || false,
|
||||
responses_system_prompt_mode: ['native', 'input_user_message'].includes(
|
||||
localInputs.responses_system_prompt_mode,
|
||||
)
|
||||
? localInputs.responses_system_prompt_mode
|
||||
: 'native',
|
||||
client_only: localInputs.client_only || false,
|
||||
bound_user_ids: localInputs.bound_user_ids || '',
|
||||
os_restriction: Array.isArray(localInputs.os_restriction)
|
||||
@@ -1432,6 +1460,13 @@ const EditChannelModal = (props) => {
|
||||
0,
|
||||
parseInt(localInputs.cache_breakpoint_min_tokens, 10) || 0,
|
||||
),
|
||||
// '' = 跟随全局「Claude设置」里的未分档缓存创建默认档位。
|
||||
// 枚举外的值一律落回 '',后端 ValidateSettings 也会拒绝脏值。
|
||||
cache_creation_default_ttl: ['5m', '1h'].includes(
|
||||
localInputs.cache_creation_default_ttl,
|
||||
)
|
||||
? localInputs.cache_creation_default_ttl
|
||||
: '',
|
||||
};
|
||||
try {
|
||||
localInputs.setting = mergeChannelSettings(
|
||||
@@ -1502,8 +1537,10 @@ const EditChannelModal = (props) => {
|
||||
delete localInputs.sticky_user_id_mode;
|
||||
delete localInputs.cache_breakpoint_fill;
|
||||
delete localInputs.cache_breakpoint_min_tokens;
|
||||
delete localInputs.cache_creation_default_ttl;
|
||||
delete localInputs.system_prompt;
|
||||
delete localInputs.system_prompt_override;
|
||||
delete localInputs.responses_system_prompt_mode;
|
||||
delete localInputs.is_enterprise_account;
|
||||
// 顶层的 vertex_key_type 不应发送给后端
|
||||
delete localInputs.vertex_key_type;
|
||||
@@ -2753,12 +2790,10 @@ const EditChannelModal = (props) => {
|
||||
showInfo(t('没有模型可以复制'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!(await copy(inputs.models.join(',')))) {
|
||||
throw new Error('Clipboard copy failed');
|
||||
}
|
||||
// copy 失败返回 false 而不抛错,以返回值为准
|
||||
if (await copy(inputs.models.join(','))) {
|
||||
showSuccess(t('模型列表已复制到剪贴板'));
|
||||
} catch (error) {
|
||||
} else {
|
||||
showError(t('复制失败'));
|
||||
}
|
||||
}}
|
||||
@@ -3756,6 +3791,26 @@ const EditChannelModal = (props) => {
|
||||
)}
|
||||
/>
|
||||
|
||||
<Form.Select
|
||||
field='cache_creation_default_ttl'
|
||||
label={t('未分档缓存创建默认档位')}
|
||||
style={{ width: '100%' }}
|
||||
optionList={[
|
||||
{ label: t('跟随全局'), value: '' },
|
||||
{ label: t('按 5 分钟档计费'), value: '5m' },
|
||||
{ label: t('按 1 小时档计费'), value: '1h' },
|
||||
]}
|
||||
onChange={(value) =>
|
||||
handleChannelSettingsChange(
|
||||
'cache_creation_default_ttl',
|
||||
value,
|
||||
)
|
||||
}
|
||||
extraText={t(
|
||||
'本渠道上游只返回缓存创建总量、未给出 5m/1h 拆分时,这部分按哪一档倍率计费,优先级高于「模型设置 → Claude设置」里的全局默认档位。上游已明确分档的 token 永远按实际返回结算,与此项无关。号池确定「不带 ttl 参数即落 5 分钟」的渠道才需要改成 5m。',
|
||||
)}
|
||||
/>
|
||||
|
||||
<Form.Input
|
||||
field='proxy'
|
||||
label={t('代理地址')}
|
||||
@@ -3797,6 +3852,29 @@ const EditChannelModal = (props) => {
|
||||
'如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
|
||||
)}
|
||||
/>
|
||||
<Form.Select
|
||||
field='responses_system_prompt_mode'
|
||||
label={t('Responses 系统提示词兼容模式')}
|
||||
optionList={[
|
||||
{
|
||||
label: t('原生模式(默认)'),
|
||||
value: 'native',
|
||||
},
|
||||
{
|
||||
label: t('号池兼容:放入 input 用户消息'),
|
||||
value: 'input_user_message',
|
||||
},
|
||||
]}
|
||||
onChange={(value) =>
|
||||
handleChannelSettingsChange(
|
||||
'responses_system_prompt_mode',
|
||||
value,
|
||||
)
|
||||
}
|
||||
extraText={t(
|
||||
'仅对命中 ForceResponsesModels 的 Chat→Responses 桥接请求生效;直接 Responses 请求和图片接口不转换。',
|
||||
)}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -20,6 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
import React from 'react';
|
||||
import { Tag as AntTag } from 'antd';
|
||||
import { Progress, Tooltip, Typography } from '@/components/ui';
|
||||
import { fundAccountDisplay } from '../../../pages/Organization/fund/fundFormat';
|
||||
import {
|
||||
Music,
|
||||
FileText,
|
||||
@@ -570,6 +571,33 @@ export const getTaskLogsColumns = ({
|
||||
);
|
||||
},
|
||||
},
|
||||
...(COLUMN_KEYS.FUND_DEPT
|
||||
? [
|
||||
{
|
||||
key: COLUMN_KEYS.FUND_DEPT,
|
||||
title: t('归属部门'),
|
||||
dataIndex: 'fund_dept_name',
|
||||
render: (v) => (
|
||||
<span className='block max-w-[140px] truncate' title={v || ''}>
|
||||
{v === undefined || v === null ? '—' : v || t('未归属部门')}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: COLUMN_KEYS.FUND_ACCOUNT,
|
||||
title: t('扣费账户'),
|
||||
dataIndex: 'fund_account_type',
|
||||
render: (v, record) =>
|
||||
v === undefined || v === null ? (
|
||||
'—'
|
||||
) : (
|
||||
<span className='block max-w-[180px] truncate'>
|
||||
{fundAccountDisplay(t, v, record.fund_dept_name)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
key: COLUMN_KEYS.FAIL_REASON,
|
||||
title: t('详情'),
|
||||
|
||||
@@ -72,6 +72,7 @@ const ContentModal = ({
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
// 走公共 copy:HTTP 部署下 navigator.clipboard 为 undefined,裸调会同步抛错、点了无反应
|
||||
const handleCopyUrl = () => {
|
||||
writeClipboardText(shareUrl)
|
||||
.then(() => showSuccess(t('链接已复制')))
|
||||
|
||||
@@ -844,6 +844,10 @@ export const getLogsColumns = ({
|
||||
other.cache_creation_ratio_1h ||
|
||||
other.cache_creation_ratio ||
|
||||
1.0,
|
||||
other.cache_creation_tokens_unlabeled || 0,
|
||||
other.cache_creation_ratio_unlabeled ||
|
||||
other.cache_creation_ratio ||
|
||||
1.0,
|
||||
false,
|
||||
1.0,
|
||||
other?.is_system_prompt_overwritten,
|
||||
@@ -862,6 +866,8 @@ export const getLogsColumns = ({
|
||||
1.0,
|
||||
0,
|
||||
1.0,
|
||||
0,
|
||||
1.0,
|
||||
false,
|
||||
1.0,
|
||||
other?.is_system_prompt_overwritten,
|
||||
|
||||
@@ -116,15 +116,18 @@ const UsageBillingDetail = ({
|
||||
const other = getLogOther(record.other) || {};
|
||||
const inputTokens = Number(record.prompt_tokens || 0);
|
||||
const outputTokens = Number(record.completion_tokens || 0);
|
||||
const cacheTokens =
|
||||
Number(other.cache_tokens || 0) +
|
||||
Number(other.cache_creation_tokens || 0) +
|
||||
Number(other.cache_creation_tokens_5m || 0) +
|
||||
Number(other.cache_creation_tokens_1h || 0);
|
||||
const textTokens = inputTokens + outputTokens;
|
||||
// 有 5m/1h 分档时只展示分档,不再重复展示未分档的总量与倍率
|
||||
// 缓存创建按上游实际返回分三桶:明确的 5m / 1h,以及上游只给了总量没给分档的「未分档」。
|
||||
// 三桶按各自倍率结算,所以三桶都得露出来——少露一桶,用户拿界面上的 token × 倍率就加不出账单金额。
|
||||
const hasSplitCacheCreation =
|
||||
other.cache_creation_tokens_5m > 0 || other.cache_creation_tokens_1h > 0;
|
||||
// 未分档桶只在与分档并存时单独成行;没有分档时,下面的「缓存创建 / 缓存创建倍率」
|
||||
// 本身说的就是这一桶,再列一遍是重复
|
||||
const unlabeledCacheCreation = Number(
|
||||
other.cache_creation_tokens_unlabeled || 0,
|
||||
);
|
||||
const showUnlabeledCacheCreation =
|
||||
hasSplitCacheCreation && unlabeledCacheCreation > 0;
|
||||
const effectiveGroupRatio =
|
||||
Number.isFinite(Number(other.user_group_ratio)) &&
|
||||
Number(other.user_group_ratio) !== -1
|
||||
@@ -151,6 +154,10 @@ const UsageBillingDetail = ({
|
||||
label: t('1h 缓存创建'),
|
||||
value: formatCount(other.cache_creation_tokens_1h),
|
||||
},
|
||||
showUnlabeledCacheCreation && {
|
||||
label: t('未分档缓存创建'),
|
||||
value: formatCount(unlabeledCacheCreation),
|
||||
},
|
||||
other.model_ratio != null && {
|
||||
label: t('模型倍率'),
|
||||
value: formatRatio(other.model_ratio),
|
||||
@@ -160,7 +167,10 @@ const UsageBillingDetail = ({
|
||||
value: formatRatio(other.completion_ratio),
|
||||
},
|
||||
other.cache_ratio != null &&
|
||||
cacheTokens > 0 && {
|
||||
other.cache_tokens > 0 && {
|
||||
// cache_ratio 是缓存命中(读)的倍率,与缓存创建(写)无关。
|
||||
// 过去这里的闸门把写入 token 也算进来,于是只写不读的请求也会挂一个
|
||||
// 没有对应 token 的「缓存倍率 0.1x」,看着像漏算了一笔钱。
|
||||
label: t('缓存倍率'),
|
||||
value: formatRatio(other.cache_ratio),
|
||||
},
|
||||
@@ -180,6 +190,11 @@ const UsageBillingDetail = ({
|
||||
label: t('1h 缓存倍率'),
|
||||
value: formatRatio(other.cache_creation_ratio_1h),
|
||||
},
|
||||
showUnlabeledCacheCreation &&
|
||||
other.cache_creation_ratio_unlabeled != null && {
|
||||
label: t('未分档缓存倍率'),
|
||||
value: formatRatio(other.cache_creation_ratio_unlabeled),
|
||||
},
|
||||
effectiveGroupRatio != null && {
|
||||
label: t('分组倍率'),
|
||||
value: formatRatio(effectiveGroupRatio),
|
||||
|
||||
@@ -246,8 +246,10 @@ const renderOperations = (
|
||||
|
||||
const currentRole = Number(getUserData()?.role || 0);
|
||||
const recordRole = Number(record.role || 0);
|
||||
const canManage = isAdmin() && (currentRole >= 100 || recordRole < 100);
|
||||
const canChangeRole = canManage && recordRole < 100;
|
||||
// 与后端 canManageUserOfRole 一致:非超级管理员只能管理角色低于自己的用户;提升/降级仅超级管理员
|
||||
const canManage =
|
||||
isAdmin() && (currentRole >= 100 || recordRole < currentRole);
|
||||
const canChangeRole = canManage && currentRole >= 100 && recordRole < 100;
|
||||
|
||||
// 低频动作全部收进「更多」下拉,操作列稳定为一行三个控件,避免跨行撑高行高
|
||||
const moreMenu = [];
|
||||
|
||||
@@ -373,6 +373,13 @@ const toDate = (value) =>
|
||||
Array.isArray(value)
|
||||
? value.map((v) => v?.toDate() ?? null)
|
||||
: (value?.toDate() ?? null);
|
||||
// Semi 契约:DatePicker / TimePicker 的 onChange 为 (Date | Date[], 文本 | 文本[])(onChangeWithDateFirst
|
||||
// 默认 true),存量页面与 Form.DatePicker(取第一个参数为字段值)都按此编写;清空时 Date 为 null、文本为 ''。
|
||||
// format 沿用 Semi 的 date-fns 记法(yyyy-MM-dd),在此转换为 dayjs 记法(YYYY-MM-DD)。
|
||||
const toDayjsFormat = (format) =>
|
||||
typeof format === 'string'
|
||||
? format.replace(/y/g, 'Y').replace(/d/g, 'D')
|
||||
: format;
|
||||
export function DatePicker({
|
||||
type,
|
||||
value,
|
||||
@@ -386,6 +393,7 @@ export function DatePicker({
|
||||
inputReadOnly,
|
||||
dropdownClassName,
|
||||
dropdownStyle,
|
||||
format,
|
||||
...props
|
||||
}) {
|
||||
const range = type?.toLowerCase().includes('range');
|
||||
@@ -394,6 +402,7 @@ export function DatePicker({
|
||||
return (
|
||||
<Component
|
||||
{...props}
|
||||
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
|
||||
classNames={{
|
||||
...props.classNames,
|
||||
popup: {
|
||||
@@ -422,17 +431,20 @@ export function DatePicker({
|
||||
value: convert(p.value || (p.start && [p.start, p.end])),
|
||||
}))}
|
||||
onChange={(dates, strings) =>
|
||||
onChange?.(dates ? (range ? strings : strings) : '', toDate(dates))
|
||||
onChange?.(dates ? toDate(dates) : null, dates ? strings : '')
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export function TimePicker({ value, onChange, ...props }) {
|
||||
export function TimePicker({ value, onChange, format, ...props }) {
|
||||
return (
|
||||
<AntTimePicker
|
||||
{...props}
|
||||
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
|
||||
value={toDay(value)}
|
||||
onChange={(date, string) => onChange?.(string, date?.toDate())}
|
||||
onChange={(date, string) =>
|
||||
onChange?.(date ? date.toDate() : null, date ? string : '')
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user