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:
qiubaishen
2026-11-18 10:22:02 +08:00
parent 737c353d84
commit db3dba1e96
157 changed files with 29960 additions and 1197 deletions
@@ -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;