mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-11-30 00:27:42 +08:00
完善管理后台真实数据统计与筛选
This commit is contained in:
1 parent
2f1189cf8a
commit
a19b3b00a7
33 files changed
+1857
-787
No files matched your search
@@ -0,0 +1,45 @@
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export function StatisticsFeedback({
|
||||
loading,
|
||||
error,
|
||||
empty,
|
||||
reload,
|
||||
}: {
|
||||
loading: boolean
|
||||
error?: string
|
||||
empty?: boolean
|
||||
reload: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
if (error)
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-destructive/40 p-4 text-sm"
|
||||
>
|
||||
<span>{error}</span>
|
||||
<Button variant="outline" onClick={reload}>
|
||||
{t("statistics.retry")}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
if (loading)
|
||||
return (
|
||||
<p role="status" className="p-4 text-sm text-muted-foreground">
|
||||
{t("statistics.loading")}
|
||||
</p>
|
||||
)
|
||||
if (empty)
|
||||
return (
|
||||
<p
|
||||
role="status"
|
||||
className="rounded-lg border p-4 text-sm text-muted-foreground"
|
||||
>
|
||||
{t("statistics.empty")}
|
||||
</p>
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -17,7 +17,7 @@ type StatisticsMetricCardProps = {
|
||||
comparison: string
|
||||
icon: IconSvgElement
|
||||
label: string
|
||||
trend: string
|
||||
trend?: string
|
||||
trendDirection?: "up" | "down"
|
||||
value: string
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export function StatisticsMetricCard({
|
||||
icon,
|
||||
label,
|
||||
trend,
|
||||
trendDirection = "up",
|
||||
trendDirection,
|
||||
value,
|
||||
}: StatisticsMetricCardProps) {
|
||||
return (
|
||||
@@ -47,23 +47,26 @@ export function StatisticsMetricCard({
|
||||
<p className="text-2xl font-semibold tracking-tight tabular-nums">
|
||||
{value}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">
|
||||
<HugeiconsIcon
|
||||
icon={
|
||||
trendDirection === "up"
|
||||
? ArrowUpRight01Icon
|
||||
: ArrowDownRight01Icon
|
||||
}
|
||||
data-icon="inline-start"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{trend}
|
||||
</Badge>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{comparison}
|
||||
</span>
|
||||
</div>
|
||||
{trend && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">
|
||||
<HugeiconsIcon
|
||||
icon={
|
||||
(trendDirection ?? (/[-−]/.test(trend) ? "down" : "up")) ===
|
||||
"down"
|
||||
? ArrowDownRight01Icon
|
||||
: ArrowUpRight01Icon
|
||||
}
|
||||
data-icon="inline-start"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{trend}
|
||||
</Badge>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{comparison}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
|
||||
import { api } from "@/lib/api"
|
||||
|
||||
export function useStatistics<T>(path: string, interval = 0) {
|
||||
const [revision, setRevision] = useState(0)
|
||||
const [result, setResult] = useState<{
|
||||
path: string
|
||||
revision: number
|
||||
data?: T
|
||||
error?: string
|
||||
}>()
|
||||
const reload = useCallback(() => setRevision((value) => value + 1), [])
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
async function load() {
|
||||
try {
|
||||
const data = await api<T>(path, { signal: controller.signal })
|
||||
if (!controller.signal.aborted) setResult({ path, revision, data })
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({
|
||||
path,
|
||||
revision,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
} finally {
|
||||
if (interval > 0 && !controller.signal.aborted) {
|
||||
timer = setTimeout(tick, interval)
|
||||
}
|
||||
}
|
||||
}
|
||||
function tick() {
|
||||
if (document.visibilityState === "hidden")
|
||||
timer = setTimeout(tick, interval)
|
||||
else void load()
|
||||
}
|
||||
void load()
|
||||
return () => {
|
||||
controller.abort()
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [path, revision, interval])
|
||||
|
||||
const current =
|
||||
result?.path === path && result.revision === revision ? result : undefined
|
||||
return {
|
||||
data: current?.data,
|
||||
lastData: result?.data,
|
||||
error: current?.error,
|
||||
loading: !current,
|
||||
reload,
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,20 @@ export const ar = {
|
||||
documentTitle: "إدارة MonkeyAI",
|
||||
adminConsole: "لوحة الإدارة",
|
||||
},
|
||||
statistics: {
|
||||
loading: "جارٍ تحميل الإحصاءات…",
|
||||
retry: "إعادة المحاولة",
|
||||
refresh: "تحديث",
|
||||
empty: "لا توجد بيانات لعوامل التصفية المحددة.",
|
||||
deleted: "محذوف",
|
||||
modelScope:
|
||||
"تُحسب الاستدعاءات حسب وقت البدء والأرصدة حسب وقت الخصم والاسترداد. معدل إصابة الذاكرة المؤقتة هو نسبة الاستدعاءات التي استخدمتها.",
|
||||
taskScope:
|
||||
"الجلسات التي بدأت خلال الفترة. معدل الإكمال هو الناجحة / الإجمالي، ومتوسط المدة للجلسات المنتهية فقط. يلزم إرسال بيانات من العميل.",
|
||||
realtimeScope:
|
||||
"تحديث كل 30 ثانية. الإنتاجية حسب الاستدعاءات المكتملة، والمهام النشطة هي الجلسات المفتوحة ذات النشاط الحديث.",
|
||||
updated: "آخر تحديث {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "مسار التنقل",
|
||||
close: "إغلاق",
|
||||
@@ -128,13 +142,13 @@ export const ar = {
|
||||
totalTasks: "إجمالي المهام",
|
||||
completionRate: "معدل الإنجاز",
|
||||
averageDuration: "متوسط المدة",
|
||||
runningTasks: "المهام قيد التشغيل",
|
||||
runningTasks: "المهام المفتوحة",
|
||||
},
|
||||
taskTrend: "اتجاه المهام",
|
||||
statusDistribution: "توزيع الحالات",
|
||||
statuses: {
|
||||
completed: "مكتملة",
|
||||
running: "قيد التشغيل",
|
||||
running: "مفتوحة",
|
||||
failed: "فشلت",
|
||||
},
|
||||
taskTypeDetails: "تفاصيل أنواع المهام",
|
||||
|
||||
@@ -6,6 +6,20 @@ export const deDE = {
|
||||
documentTitle: "MonkeyAI-Administration",
|
||||
adminConsole: "Administrationskonsole",
|
||||
},
|
||||
statistics: {
|
||||
loading: "Statistik wird geladen…",
|
||||
retry: "Erneut versuchen",
|
||||
refresh: "Aktualisieren",
|
||||
empty: "Keine Daten für die ausgewählten Filter.",
|
||||
deleted: "Gelöscht",
|
||||
modelScope:
|
||||
"Aufrufe nach Startzeit, Credits nach Buchungs- und Erstattungszeit. Cache-Trefferquote: Anteil der Aufrufe mit Cache-Treffern.",
|
||||
taskScope:
|
||||
"Im Zeitraum gestartete Sitzungen. Abschlussquote: erfolgreich / gesamt. Durchschnittsdauer nur für beendete Sitzungen. Erfordert Client-Meldungen.",
|
||||
realtimeScope:
|
||||
"Aktualisierung alle 30 Sekunden. Durchsatz aus abgeschlossenen Aufrufen; aktive Aufgaben sind kürzlich aktive, offene Sitzungen.",
|
||||
updated: "Aktualisiert: {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "Brotkrümelnavigation",
|
||||
close: "Schließen",
|
||||
@@ -133,13 +147,13 @@ export const deDE = {
|
||||
totalTasks: "Aufgaben insgesamt",
|
||||
completionRate: "Abschlussquote",
|
||||
averageDuration: "Durchschnittliche Dauer",
|
||||
runningTasks: "Laufende Aufgaben",
|
||||
runningTasks: "Offene Aufgaben",
|
||||
},
|
||||
taskTrend: "Aufgabentrend",
|
||||
statusDistribution: "Statusverteilung",
|
||||
statuses: {
|
||||
completed: "Abgeschlossen",
|
||||
running: "In Bearbeitung",
|
||||
running: "Offen",
|
||||
failed: "Fehlgeschlagen",
|
||||
},
|
||||
taskTypeDetails: "Details nach Aufgabentyp",
|
||||
|
||||
@@ -24,6 +24,20 @@ export const enUS = {
|
||||
documentTitle: "MonkeyAI Admin",
|
||||
adminConsole: "Admin Console",
|
||||
},
|
||||
statistics: {
|
||||
loading: "Loading statistics…",
|
||||
retry: "Retry",
|
||||
refresh: "Refresh",
|
||||
empty: "No data for the selected filters.",
|
||||
deleted: "Deleted",
|
||||
modelScope:
|
||||
"Calls use start time; credits use charge and refund time. Cache hit rate is the share of calls with cache hits.",
|
||||
taskScope:
|
||||
"Sessions started in this period. Completion rate is successful sessions / total; average duration includes ended sessions only. Session data requires client reporting.",
|
||||
realtimeScope:
|
||||
"Refreshes every 30 seconds. Throughput uses calls completed in the window; active tasks are recently active, open sessions.",
|
||||
updated: "Updated {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "Breadcrumb",
|
||||
close: "Close",
|
||||
@@ -149,13 +163,13 @@ export const enUS = {
|
||||
totalTasks: "Total tasks",
|
||||
completionRate: "Completion rate",
|
||||
averageDuration: "Average duration",
|
||||
runningTasks: "Running tasks",
|
||||
runningTasks: "Open tasks",
|
||||
},
|
||||
taskTrend: "Task trend",
|
||||
statusDistribution: "Status distribution",
|
||||
statuses: {
|
||||
completed: "Completed",
|
||||
running: "Running",
|
||||
running: "Open",
|
||||
failed: "Failed",
|
||||
},
|
||||
taskTypeDetails: "Task type details",
|
||||
|
||||
@@ -6,6 +6,20 @@ export const es419 = {
|
||||
documentTitle: "Administración de MonkeyAI",
|
||||
adminConsole: "Panel de administración",
|
||||
},
|
||||
statistics: {
|
||||
loading: "Cargando estadísticas…",
|
||||
retry: "Reintentar",
|
||||
refresh: "Actualizar",
|
||||
empty: "No hay datos para los filtros seleccionados.",
|
||||
deleted: "Eliminado",
|
||||
modelScope:
|
||||
"Llamadas por hora de inicio; créditos por hora de cobro y reembolso. La tasa de caché es la proporción de llamadas con aciertos.",
|
||||
taskScope:
|
||||
"Sesiones iniciadas en el período. Tasa de finalización: exitosas / total; duración media solo de sesiones terminadas. Requiere informes del cliente.",
|
||||
realtimeScope:
|
||||
"Se actualiza cada 30 segundos. Rendimiento de llamadas terminadas; tareas activas: sesiones abiertas con actividad reciente.",
|
||||
updated: "Actualizado a las {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "Ruta de navegación",
|
||||
close: "Cerrar",
|
||||
@@ -132,13 +146,13 @@ export const es419 = {
|
||||
totalTasks: "Total de tareas",
|
||||
completionRate: "Tasa de finalización",
|
||||
averageDuration: "Duración promedio",
|
||||
runningTasks: "Tareas en ejecución",
|
||||
runningTasks: "Tareas abiertas",
|
||||
},
|
||||
taskTrend: "Tendencia de tareas",
|
||||
statusDistribution: "Distribución por estado",
|
||||
statuses: {
|
||||
completed: "Completadas",
|
||||
running: "En ejecución",
|
||||
running: "Abiertas",
|
||||
failed: "Fallidas",
|
||||
},
|
||||
taskTypeDetails: "Detalle por tipo de tarea",
|
||||
|
||||
@@ -6,6 +6,20 @@ export const frFR = {
|
||||
documentTitle: "Administration MonkeyAI",
|
||||
adminConsole: "Console d’administration",
|
||||
},
|
||||
statistics: {
|
||||
loading: "Chargement des statistiques…",
|
||||
retry: "Réessayer",
|
||||
refresh: "Actualiser",
|
||||
empty: "Aucune donnée pour les filtres sélectionnés.",
|
||||
deleted: "Supprimé",
|
||||
modelScope:
|
||||
"Appels par heure de début ; crédits par heure de débit et de remboursement. Le taux de cache est la part des appels avec un cache utilisé.",
|
||||
taskScope:
|
||||
"Sessions démarrées sur la période. Taux de réussite : réussies / total ; durée moyenne des sessions terminées uniquement. Nécessite les rapports du client.",
|
||||
realtimeScope:
|
||||
"Actualisation toutes les 30 secondes. Débit des appels terminés ; tâches actives : sessions ouvertes avec une activité récente.",
|
||||
updated: "Mis à jour à {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "Fil d’Ariane",
|
||||
close: "Fermer",
|
||||
@@ -132,13 +146,13 @@ export const frFR = {
|
||||
totalTasks: "Nombre total de tâches",
|
||||
completionRate: "Taux d’achèvement",
|
||||
averageDuration: "Durée moyenne",
|
||||
runningTasks: "Tâches en cours",
|
||||
runningTasks: "Tâches ouvertes",
|
||||
},
|
||||
taskTrend: "Évolution des tâches",
|
||||
statusDistribution: "Répartition par statut",
|
||||
statuses: {
|
||||
completed: "Terminées",
|
||||
running: "En cours",
|
||||
running: "Ouvertes",
|
||||
failed: "Échouées",
|
||||
},
|
||||
taskTypeDetails: "Détail par type de tâche",
|
||||
|
||||
@@ -6,6 +6,20 @@ export const jaJP = {
|
||||
documentTitle: "MonkeyAI 管理コンソール",
|
||||
adminConsole: "管理コンソール",
|
||||
},
|
||||
statistics: {
|
||||
loading: "統計を読み込み中…",
|
||||
retry: "再試行",
|
||||
refresh: "更新",
|
||||
empty: "選択した条件のデータはありません。",
|
||||
deleted: "削除済み",
|
||||
modelScope:
|
||||
"呼び出しは開始時刻、クレジットは課金・返金時刻で集計します。キャッシュヒット率はヒットした呼び出しの割合です。",
|
||||
taskScope:
|
||||
"期間内に開始したセッション。完了率は成功数 / 総数、平均時間は終了したセッションのみです。クライアントからの報告が必要です。",
|
||||
realtimeScope:
|
||||
"30 秒ごとに更新。スループットは期間内に完了した呼び出し、アクティブタスクは最近活動した未終了セッションです。",
|
||||
updated: "更新時刻 {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "パンくずリスト",
|
||||
close: "閉じる",
|
||||
@@ -131,13 +145,13 @@ export const jaJP = {
|
||||
totalTasks: "タスク総数",
|
||||
completionRate: "完了率",
|
||||
averageDuration: "平均所要時間",
|
||||
runningTasks: "実行中のタスク",
|
||||
runningTasks: "未終了タスク",
|
||||
},
|
||||
taskTrend: "タスクの推移",
|
||||
statusDistribution: "ステータス分布",
|
||||
statuses: {
|
||||
completed: "完了",
|
||||
running: "実行中",
|
||||
running: "未終了",
|
||||
failed: "失敗",
|
||||
},
|
||||
taskTypeDetails: "タスク種別の詳細",
|
||||
|
||||
@@ -6,6 +6,20 @@ export const koKR = {
|
||||
documentTitle: "MonkeyAI 관리자 콘솔",
|
||||
adminConsole: "관리자 콘솔",
|
||||
},
|
||||
statistics: {
|
||||
loading: "통계 로딩 중…",
|
||||
retry: "재시도",
|
||||
refresh: "새로 고침",
|
||||
empty: "선택한 조건에 데이터가 없습니다.",
|
||||
deleted: "삭제됨",
|
||||
modelScope:
|
||||
"호출은 시작 시각, 크레딧은 청구 및 환불 시각 기준입니다. 캐시 적중률은 적중한 호출의 비율입니다.",
|
||||
taskScope:
|
||||
"기간 내 시작한 세션입니다. 완료율은 성공 수 / 전체 수이며 평균 시간은 종료된 세션만 포함합니다. 클라이언트 보고가 필요합니다.",
|
||||
realtimeScope:
|
||||
"30초마다 갱신합니다. 처리량은 기간 내 완료된 호출, 활성 작업은 최근 활동한 미종료 세션 기준입니다.",
|
||||
updated: "{{time}} 업데이트",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "이동 경로",
|
||||
close: "닫기",
|
||||
@@ -129,13 +143,13 @@ export const koKR = {
|
||||
totalTasks: "전체 작업",
|
||||
completionRate: "완료율",
|
||||
averageDuration: "평균 소요 시간",
|
||||
runningTasks: "실행 중인 작업",
|
||||
runningTasks: "미종료 작업",
|
||||
},
|
||||
taskTrend: "작업 추세",
|
||||
statusDistribution: "상태 분포",
|
||||
statuses: {
|
||||
completed: "완료",
|
||||
running: "실행 중",
|
||||
running: "미종료",
|
||||
failed: "실패",
|
||||
},
|
||||
taskTypeDetails: "작업 유형 상세",
|
||||
|
||||
@@ -6,6 +6,20 @@ export const ruRU = {
|
||||
documentTitle: "Администрирование MonkeyAI",
|
||||
adminConsole: "Панель администратора",
|
||||
},
|
||||
statistics: {
|
||||
loading: "Загрузка статистики…",
|
||||
retry: "Повторить",
|
||||
refresh: "Обновить",
|
||||
empty: "Нет данных для выбранных фильтров.",
|
||||
deleted: "Удалено",
|
||||
modelScope:
|
||||
"Вызовы учитываются по времени начала, кредиты — списания и возврата. Попадания в кэш — доля вызовов с использованием кэша.",
|
||||
taskScope:
|
||||
"Сессии, начатые за период. Доля завершения: успешные / все; средняя длительность только завершённых сессий. Требуются отчёты клиента.",
|
||||
realtimeScope:
|
||||
"Обновление каждые 30 секунд. Пропускная способность по завершённым вызовам; активные задачи — открытые сессии с недавней активностью.",
|
||||
updated: "Обновлено в {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "Навигационная цепочка",
|
||||
close: "Закрыть",
|
||||
@@ -132,13 +146,13 @@ export const ruRU = {
|
||||
totalTasks: "Всего задач",
|
||||
completionRate: "Процент завершения",
|
||||
averageDuration: "Средняя длительность",
|
||||
runningTasks: "Выполняемые задачи",
|
||||
runningTasks: "Открытые задачи",
|
||||
},
|
||||
taskTrend: "Динамика задач",
|
||||
statusDistribution: "Распределение по статусам",
|
||||
statuses: {
|
||||
completed: "Завершено",
|
||||
running: "Выполняется",
|
||||
running: "Открытые",
|
||||
failed: "Ошибка",
|
||||
},
|
||||
taskTypeDetails: "Статистика по типам задач",
|
||||
|
||||
@@ -22,6 +22,20 @@ export const zhCN = {
|
||||
documentTitle: "MonkeyAI 管理后台",
|
||||
adminConsole: "管理后台",
|
||||
},
|
||||
statistics: {
|
||||
loading: "加载统计数据…",
|
||||
retry: "重试",
|
||||
refresh: "刷新",
|
||||
empty: "当前筛选范围内暂无数据。",
|
||||
deleted: "已删除",
|
||||
modelScope:
|
||||
"调用按开始时间统计,积分按扣费与退款发生时间统计;缓存命中率为命中缓存的调用占比。",
|
||||
taskScope:
|
||||
"统计范围内新建的会话;完成率为成功结束数 / 总数,平均耗时仅包含已结束会话。任务数据依赖客户端上报。",
|
||||
realtimeScope:
|
||||
"每 30 秒刷新。吞吐按窗口内完成的调用计算;活跃任务为近期有活动的未结束会话。",
|
||||
updated: "更新于 {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "面包屑导航",
|
||||
close: "关闭",
|
||||
@@ -144,13 +158,13 @@ export const zhCN = {
|
||||
totalTasks: "任务总数",
|
||||
completionRate: "完成率",
|
||||
averageDuration: "平均耗时",
|
||||
runningTasks: "运行中任务",
|
||||
runningTasks: "未结束任务",
|
||||
},
|
||||
taskTrend: "任务趋势",
|
||||
statusDistribution: "状态分布",
|
||||
statuses: {
|
||||
completed: "已完成",
|
||||
running: "运行中",
|
||||
running: "未结束",
|
||||
failed: "失败",
|
||||
},
|
||||
taskTypeDetails: "任务类型明细",
|
||||
|
||||
@@ -6,6 +6,20 @@ export const zhTW = {
|
||||
documentTitle: "MonkeyAI 管理後台",
|
||||
adminConsole: "管理後台",
|
||||
},
|
||||
statistics: {
|
||||
loading: "載入統計資料…",
|
||||
retry: "重試",
|
||||
refresh: "重新整理",
|
||||
empty: "目前篩選範圍內沒有資料。",
|
||||
deleted: "已刪除",
|
||||
modelScope:
|
||||
"呼叫按開始時間統計,積分按扣費與退款時間統計;快取命中率為命中快取的呼叫比例。",
|
||||
taskScope:
|
||||
"期間內建立的工作階段;完成率為成功結束數 / 總數,平均耗時僅含已結束工作階段。資料須由用戶端回報。",
|
||||
realtimeScope:
|
||||
"每 30 秒更新。吞吐量依期間內完成的呼叫計算;活躍任務為近期有活動的未結束工作階段。",
|
||||
updated: "更新於 {{time}}",
|
||||
},
|
||||
common: {
|
||||
breadcrumb: "麵包屑導覽",
|
||||
close: "關閉",
|
||||
@@ -128,13 +142,13 @@ export const zhTW = {
|
||||
totalTasks: "任務總數",
|
||||
completionRate: "完成率",
|
||||
averageDuration: "平均耗時",
|
||||
runningTasks: "執行中任務",
|
||||
runningTasks: "未結束任務",
|
||||
},
|
||||
taskTrend: "任務趨勢",
|
||||
statusDistribution: "狀態分布",
|
||||
statuses: {
|
||||
completed: "已完成",
|
||||
running: "執行中",
|
||||
running: "未結束",
|
||||
failed: "失敗",
|
||||
},
|
||||
taskTypeDetails: "任務類型明細",
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
export type Period = { from: string; until: string }
|
||||
export type ModelSummary = {
|
||||
calls: number
|
||||
input_tokens: number
|
||||
output_tokens: number
|
||||
cache_hit_rate: number | null
|
||||
success_rate: number | null
|
||||
credits: string
|
||||
}
|
||||
export type ModelStatistics = Period & {
|
||||
summary: ModelSummary
|
||||
previous: ModelSummary
|
||||
models: { id: string; name: string; deleted: boolean }[]
|
||||
trend: {
|
||||
at: string
|
||||
calls: number
|
||||
input_tokens: number
|
||||
output_tokens: number
|
||||
credits: string
|
||||
}[]
|
||||
}
|
||||
export type TaskSummary = {
|
||||
total: number
|
||||
completed: number
|
||||
failed: number
|
||||
running: number
|
||||
completion_rate: number | null
|
||||
average_duration_seconds: number | null
|
||||
}
|
||||
export type TaskStatistics = Period & {
|
||||
summary: TaskSummary
|
||||
previous: TaskSummary
|
||||
trend: { at: string; completed: number; failed: number; running: number }[]
|
||||
types: (TaskSummary & { key: string })[]
|
||||
}
|
||||
export type RealtimeStatistics = Period & {
|
||||
model_consumption: string
|
||||
p95_response_time: number | null
|
||||
model_success_rate: number | null
|
||||
model_calls: number
|
||||
tpm: number
|
||||
rpm: number
|
||||
input_tokens: number
|
||||
output_tokens: number
|
||||
active_users: number
|
||||
active_tasks: number
|
||||
new_tasks: number
|
||||
}
|
||||
|
||||
export function change(
|
||||
current: number | null,
|
||||
previous: number | null,
|
||||
locale: string,
|
||||
points = false
|
||||
): string | undefined {
|
||||
if (current === null || previous === null || (!points && previous === 0))
|
||||
return undefined
|
||||
const delta = points
|
||||
? current - previous
|
||||
: ((current - previous) / Math.abs(previous)) * 100
|
||||
return `${new Intl.NumberFormat(locale, { signDisplay: "exceptZero", maximumFractionDigits: 1 }).format(delta)}${points ? " pp" : "%"}`
|
||||
}
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { Line, LineChart, XAxis } from "recharts"
|
||||
|
||||
import { useStatistics } from "@/hooks/use-statistics"
|
||||
import { change, type ModelStatistics } from "@/lib/statistics"
|
||||
import { StatisticsFeedback } from "@/components/statistics-feedback"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { StatisticsMetricCard } from "@/components/statistics-metric-card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import {
|
||||
@@ -35,194 +39,11 @@ import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
|
||||
type TimeRange = "24h" | "7d" | "30d"
|
||||
|
||||
const MODEL_ROWS = [
|
||||
{
|
||||
id: "gpt-5",
|
||||
model: "GPT-5",
|
||||
calls: 24340,
|
||||
inputTokens: 32800000,
|
||||
outputTokens: 11600000,
|
||||
credits: 486800,
|
||||
cacheHitRate: 61.8,
|
||||
},
|
||||
{
|
||||
id: "claude-3-7-sonnet",
|
||||
model: "Claude 3.7 Sonnet",
|
||||
calls: 18870,
|
||||
inputTokens: 27100000,
|
||||
outputTokens: 9200000,
|
||||
credits: 424575,
|
||||
cacheHitRate: 55.4,
|
||||
},
|
||||
{
|
||||
id: "deepseek-v3",
|
||||
model: "DeepSeek V3",
|
||||
calls: 13640,
|
||||
inputTokens: 17600000,
|
||||
outputTokens: 6300000,
|
||||
credits: 102300,
|
||||
cacheHitRate: 72.6,
|
||||
},
|
||||
{
|
||||
id: "gemini-2-5-pro",
|
||||
model: "Gemini 2.5 Pro",
|
||||
calls: 9560,
|
||||
inputTokens: 11900000,
|
||||
outputTokens: 4300000,
|
||||
credits: 191200,
|
||||
cacheHitRate: 64.1,
|
||||
},
|
||||
{
|
||||
id: "qwen3-235b",
|
||||
model: "Qwen3 235B",
|
||||
calls: 7808,
|
||||
inputTokens: 9000000,
|
||||
outputTokens: 2800000,
|
||||
credits: 85888,
|
||||
cacheHitRate: 68.9,
|
||||
},
|
||||
] as const
|
||||
|
||||
type ModelFilter = "all" | (typeof MODEL_ROWS)[number]["id"]
|
||||
type ModelStatsRow = (typeof MODEL_ROWS)[number]
|
||||
|
||||
const RANGE_SCALE: Record<TimeRange, number> = {
|
||||
"24h": 0.043,
|
||||
"7d": 0.25,
|
||||
"30d": 1,
|
||||
}
|
||||
|
||||
const RANGE_POINTS: Record<TimeRange, number> = {
|
||||
"24h": 24 * 12,
|
||||
"7d": 7 * 24 * 2,
|
||||
"30d": 30 * 12,
|
||||
}
|
||||
|
||||
const RANGE_INTERVAL_MINUTES: Record<TimeRange, number> = {
|
||||
"24h": 5,
|
||||
"7d": 30,
|
||||
"30d": 120,
|
||||
}
|
||||
|
||||
const RANGE_TRENDS: Record<
|
||||
TimeRange,
|
||||
readonly [string, string, string, string]
|
||||
> = {
|
||||
"24h": ["+4.6%", "+0.7%", "+5.2%", "+3.8%"],
|
||||
"7d": ["+9.8%", "+1.2%", "+11.2%", "+8.4%"],
|
||||
"30d": ["+15.7%", "+1.8%", "+18.9%", "+13.6%"],
|
||||
}
|
||||
|
||||
function distributeTotal(total: number, count: number, phase: number) {
|
||||
const weights = Array.from(
|
||||
{ length: count },
|
||||
(_, index) =>
|
||||
1 +
|
||||
Math.sin((index / count) * Math.PI * 12 + phase) * 0.18 +
|
||||
(index / Math.max(1, count - 1)) * 0.14
|
||||
)
|
||||
const weightTotal = weights.reduce((sum, value) => sum + value, 0)
|
||||
let assigned = 0
|
||||
|
||||
return weights.map((weight, index) => {
|
||||
if (index === count - 1) return total - assigned
|
||||
|
||||
const value = Math.round((total * weight) / weightTotal)
|
||||
assigned += value
|
||||
return value
|
||||
})
|
||||
}
|
||||
|
||||
function getSummary(model: ModelFilter, range: TimeRange) {
|
||||
const rows: readonly ModelStatsRow[] =
|
||||
model === "all" ? MODEL_ROWS : MODEL_ROWS.filter((row) => row.id === model)
|
||||
const scale = RANGE_SCALE[range]
|
||||
const calls = rows.reduce(
|
||||
(sum, row) => sum + Math.round(row.calls * scale),
|
||||
0
|
||||
)
|
||||
const weightedCacheHits = rows.reduce(
|
||||
(sum, row) => sum + row.calls * row.cacheHitRate,
|
||||
0
|
||||
)
|
||||
const baseCalls = rows.reduce((sum, row) => sum + row.calls, 0)
|
||||
|
||||
return {
|
||||
calls,
|
||||
cacheHitRate: weightedCacheHits / baseCalls,
|
||||
inputTokens: rows.reduce(
|
||||
(sum, row) => sum + Math.round(row.inputTokens * scale),
|
||||
0
|
||||
),
|
||||
outputTokens: rows.reduce(
|
||||
(sum, row) => sum + Math.round(row.outputTokens * scale),
|
||||
0
|
||||
),
|
||||
credits: rows.reduce(
|
||||
(sum, row) => sum + Math.round(row.credits * scale),
|
||||
0
|
||||
),
|
||||
trends: RANGE_TRENDS[range],
|
||||
}
|
||||
}
|
||||
|
||||
function buildTrendData(
|
||||
range: TimeRange,
|
||||
model: ModelFilter,
|
||||
summary: ReturnType<typeof getSummary>,
|
||||
locale: string
|
||||
) {
|
||||
const points = RANGE_POINTS[range]
|
||||
const intervalMinutes = RANGE_INTERVAL_MINUTES[range]
|
||||
const endDate = new Date(2026, 8, 2, 12)
|
||||
const modelIndex = Math.max(
|
||||
0,
|
||||
MODEL_ROWS.findIndex((row) => row.id === model)
|
||||
)
|
||||
const callValues = distributeTotal(summary.calls, points, modelIndex * 0.43)
|
||||
const inputTokenValues = distributeTotal(
|
||||
summary.inputTokens,
|
||||
points,
|
||||
modelIndex * 0.43 + 0.7
|
||||
)
|
||||
const outputTokenValues = distributeTotal(
|
||||
summary.outputTokens,
|
||||
points,
|
||||
modelIndex * 0.43 + 1.1
|
||||
)
|
||||
const creditValues = distributeTotal(
|
||||
summary.credits,
|
||||
points,
|
||||
modelIndex * 0.43 + 1.5
|
||||
)
|
||||
const labelFormatter = new Intl.DateTimeFormat(
|
||||
locale,
|
||||
range === "24h"
|
||||
? { hour: "2-digit", minute: "2-digit" }
|
||||
: {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}
|
||||
)
|
||||
|
||||
return Array.from({ length: points }, (_, index) => {
|
||||
const date = new Date(endDate)
|
||||
date.setMinutes(date.getMinutes() - (points - 1 - index) * intervalMinutes)
|
||||
|
||||
return {
|
||||
date: labelFormatter.format(date),
|
||||
calls: callValues[index],
|
||||
inputTokens: inputTokenValues[index],
|
||||
outputTokens: outputTokenValues[index],
|
||||
credits: creditValues[index],
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type TrendData = ReturnType<typeof buildTrendData>
|
||||
type TrendKey = "calls" | "inputTokens" | "outputTokens" | "credits"
|
||||
type TrendData = (Omit<ModelStatistics["trend"][number], "credits"> & {
|
||||
date: string
|
||||
credits: number
|
||||
})[]
|
||||
type TrendKey = "calls" | "input_tokens" | "output_tokens" | "credits"
|
||||
|
||||
function ModelTrendCard({
|
||||
color,
|
||||
@@ -267,6 +88,7 @@ function ModelTrendCard({
|
||||
content={<ChartTooltipContent indicator="line" />}
|
||||
/>
|
||||
<Line
|
||||
isAnimationActive={false}
|
||||
dataKey={dataKey}
|
||||
dot={false}
|
||||
stroke={`var(--color-${dataKey})`}
|
||||
@@ -283,7 +105,7 @@ function ModelTrendCard({
|
||||
export function ModelStatisticsPage() {
|
||||
const { i18n, t } = useTranslation()
|
||||
const [timeRange, setTimeRange] = useState<TimeRange>("30d")
|
||||
const [model, setModel] = useState<ModelFilter>("all")
|
||||
const [model, setModel] = useState<string>("all")
|
||||
const locale = i18n.resolvedLanguage ?? i18n.language
|
||||
const numberFormatter = new Intl.NumberFormat(locale)
|
||||
const compactNumberFormatter = new Intl.NumberFormat(locale, {
|
||||
@@ -294,11 +116,28 @@ export function ModelStatisticsPage() {
|
||||
maximumFractionDigits: 1,
|
||||
minimumFractionDigits: 1,
|
||||
})
|
||||
const summary = getSummary(model, timeRange)
|
||||
const trendData = buildTrendData(timeRange, model, summary, locale)
|
||||
const request = useStatistics<ModelStatistics>(
|
||||
`/api/admin/v1/statistics/models?range=${timeRange}${model === "all" ? "" : `&model_id=${encodeURIComponent(model)}`}`
|
||||
)
|
||||
const summary = request.data?.summary
|
||||
const previous = request.data?.previous
|
||||
const dateFormatter = new Intl.DateTimeFormat(locale, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
const trendData = (request.data?.trend ?? []).map((row) => ({
|
||||
...row,
|
||||
credits: Number(row.credits),
|
||||
date: dateFormatter.format(new Date(row.at)),
|
||||
}))
|
||||
const modelOptions = [
|
||||
{ value: "all", label: t("pages.modelStatistics.allModels") },
|
||||
...MODEL_ROWS.map((row) => ({ value: row.id, label: row.model })),
|
||||
...(request.data?.models ?? request.lastData?.models ?? []).map((row) => ({
|
||||
value: row.id,
|
||||
label: `${row.name}${row.deleted ? ` (${t("statistics.deleted")})` : ""}`,
|
||||
})),
|
||||
]
|
||||
return (
|
||||
<section className="flex flex-1 flex-col gap-4 p-4 pt-0">
|
||||
@@ -306,7 +145,7 @@ export function ModelStatisticsPage() {
|
||||
<Select
|
||||
items={modelOptions}
|
||||
value={model}
|
||||
onValueChange={(value) => setModel(value as ModelFilter)}
|
||||
onValueChange={(value) => setModel(value ?? "all")}
|
||||
>
|
||||
<SelectTrigger
|
||||
className="w-full sm:w-64"
|
||||
@@ -339,79 +178,117 @@ export function ModelStatisticsPage() {
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={Activity01Icon}
|
||||
label={t("pages.modelStatistics.metrics.totalCalls")}
|
||||
trend={summary.trends[0]}
|
||||
value={numberFormatter.format(summary.calls)}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={Database02Icon}
|
||||
label={t("pages.modelStatistics.metrics.cacheHitRate")}
|
||||
trend={summary.trends[1]}
|
||||
value={`${percentFormatter.format(summary.cacheHitRate)}%`}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={TokenCircleIcon}
|
||||
label={t("pages.modelStatistics.metrics.inputTokens")}
|
||||
trend={summary.trends[2]}
|
||||
value={compactNumberFormatter.format(summary.inputTokens)}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={ZapIcon}
|
||||
label={t("pages.modelStatistics.metrics.outputTokens")}
|
||||
trend={summary.trends[3]}
|
||||
value={compactNumberFormatter.format(summary.outputTokens)}
|
||||
/>
|
||||
<div className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
|
||||
<span>{t("statistics.modelScope")}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={request.reload}
|
||||
disabled={request.loading}
|
||||
>
|
||||
{t("statistics.refresh")}
|
||||
</Button>
|
||||
</div>
|
||||
<StatisticsFeedback
|
||||
{...request}
|
||||
empty={summary?.calls === 0 && Number(summary.credits) === 0}
|
||||
/>
|
||||
{summary && previous && (
|
||||
<>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={Activity01Icon}
|
||||
label={t("pages.modelStatistics.metrics.totalCalls")}
|
||||
trend={change(summary.calls, previous.calls, locale)}
|
||||
value={numberFormatter.format(summary.calls)}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={Database02Icon}
|
||||
label={t("pages.modelStatistics.metrics.cacheHitRate")}
|
||||
trend={change(
|
||||
summary.cache_hit_rate,
|
||||
previous.cache_hit_rate,
|
||||
locale,
|
||||
true
|
||||
)}
|
||||
value={
|
||||
summary.cache_hit_rate === null
|
||||
? "—"
|
||||
: `${percentFormatter.format(summary.cache_hit_rate)}%`
|
||||
}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={TokenCircleIcon}
|
||||
label={t("pages.modelStatistics.metrics.inputTokens")}
|
||||
trend={change(
|
||||
summary.input_tokens,
|
||||
previous.input_tokens,
|
||||
locale
|
||||
)}
|
||||
value={compactNumberFormatter.format(summary.input_tokens)}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.modelStatistics.comparedToPrevious")}
|
||||
icon={ZapIcon}
|
||||
label={t("pages.modelStatistics.metrics.outputTokens")}
|
||||
trend={change(
|
||||
summary.output_tokens,
|
||||
previous.output_tokens,
|
||||
locale
|
||||
)}
|
||||
value={compactNumberFormatter.format(summary.output_tokens)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<ModelTrendCard
|
||||
color="var(--chart-2)"
|
||||
data={trendData}
|
||||
dataKey="calls"
|
||||
label={t("pages.modelStatistics.series.calls")}
|
||||
title={t("pages.modelStatistics.callTrend")}
|
||||
total={t("pages.modelStatistics.totals.calls", {
|
||||
count: numberFormatter.format(summary.calls),
|
||||
})}
|
||||
/>
|
||||
<ModelTrendCard
|
||||
color="var(--chart-1)"
|
||||
data={trendData}
|
||||
dataKey="inputTokens"
|
||||
label={t("pages.modelStatistics.series.inputTokens")}
|
||||
title={t("pages.modelStatistics.inputTokenTrend")}
|
||||
total={t("pages.modelStatistics.totals.tokens", {
|
||||
count: numberFormatter.format(summary.inputTokens),
|
||||
})}
|
||||
/>
|
||||
<ModelTrendCard
|
||||
color="var(--chart-3)"
|
||||
data={trendData}
|
||||
dataKey="outputTokens"
|
||||
label={t("pages.modelStatistics.series.outputTokens")}
|
||||
title={t("pages.modelStatistics.outputTokenTrend")}
|
||||
total={t("pages.modelStatistics.totals.tokens", {
|
||||
count: numberFormatter.format(summary.outputTokens),
|
||||
})}
|
||||
/>
|
||||
<ModelTrendCard
|
||||
color="var(--chart-4)"
|
||||
data={trendData}
|
||||
dataKey="credits"
|
||||
label={t("pages.modelStatistics.series.credits")}
|
||||
title={t("pages.modelStatistics.creditTrend")}
|
||||
total={t("pages.modelStatistics.totals.credits", {
|
||||
count: numberFormatter.format(summary.credits),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<ModelTrendCard
|
||||
color="var(--chart-2)"
|
||||
data={trendData}
|
||||
dataKey="calls"
|
||||
label={t("pages.modelStatistics.series.calls")}
|
||||
title={t("pages.modelStatistics.callTrend")}
|
||||
total={t("pages.modelStatistics.totals.calls", {
|
||||
count: numberFormatter.format(summary.calls),
|
||||
})}
|
||||
/>
|
||||
<ModelTrendCard
|
||||
color="var(--chart-1)"
|
||||
data={trendData}
|
||||
dataKey="input_tokens"
|
||||
label={t("pages.modelStatistics.series.inputTokens")}
|
||||
title={t("pages.modelStatistics.inputTokenTrend")}
|
||||
total={t("pages.modelStatistics.totals.tokens", {
|
||||
count: numberFormatter.format(summary.input_tokens),
|
||||
})}
|
||||
/>
|
||||
<ModelTrendCard
|
||||
color="var(--chart-3)"
|
||||
data={trendData}
|
||||
dataKey="output_tokens"
|
||||
label={t("pages.modelStatistics.series.outputTokens")}
|
||||
title={t("pages.modelStatistics.outputTokenTrend")}
|
||||
total={t("pages.modelStatistics.totals.tokens", {
|
||||
count: numberFormatter.format(summary.output_tokens),
|
||||
})}
|
||||
/>
|
||||
<ModelTrendCard
|
||||
color="var(--chart-4)"
|
||||
data={trendData}
|
||||
dataKey="credits"
|
||||
label={t("pages.modelStatistics.series.credits")}
|
||||
title={t("pages.modelStatistics.creditTrend")}
|
||||
total={t("pages.modelStatistics.totals.credits", {
|
||||
count: new Intl.NumberFormat(locale, {
|
||||
maximumFractionDigits: 6,
|
||||
}).format(Number(summary.credits)),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
Coins01Icon,
|
||||
DashboardSpeed01Icon,
|
||||
GaugeIcon,
|
||||
Message01Icon,
|
||||
Task01Icon,
|
||||
TaskDone01Icon,
|
||||
TokenCircleIcon,
|
||||
@@ -23,104 +22,34 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card"
|
||||
import { useStatistics } from "@/hooks/use-statistics"
|
||||
import { type RealtimeStatistics } from "@/lib/statistics"
|
||||
import { StatisticsFeedback } from "@/components/statistics-feedback"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
|
||||
type RealtimeRange = "5m" | "15m" | "30m" | "60m"
|
||||
|
||||
type RealtimeSnapshot = {
|
||||
modelConsumption: number
|
||||
p95ResponseTime: number
|
||||
modelSuccessRate: number
|
||||
modelCalls: number
|
||||
tpm: number
|
||||
rpm: number
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
activeUsers: number
|
||||
activeTasks: number
|
||||
newTasks: number
|
||||
conversations: number
|
||||
}
|
||||
|
||||
type MetricKey = keyof RealtimeSnapshot
|
||||
|
||||
const REALTIME_SNAPSHOTS: Record<RealtimeRange, RealtimeSnapshot> = {
|
||||
"5m": {
|
||||
modelConsumption: 128,
|
||||
p95ResponseTime: 842,
|
||||
modelSuccessRate: 99.7,
|
||||
modelCalls: 1430,
|
||||
tpm: 378400,
|
||||
rpm: 286,
|
||||
inputTokens: 1480000,
|
||||
outputTokens: 412000,
|
||||
activeUsers: 184,
|
||||
activeTasks: 96,
|
||||
newTasks: 421,
|
||||
conversations: 1312,
|
||||
},
|
||||
"15m": {
|
||||
modelConsumption: 362,
|
||||
p95ResponseTime: 896,
|
||||
modelSuccessRate: 99.5,
|
||||
modelCalls: 4140,
|
||||
tpm: 366800,
|
||||
rpm: 276,
|
||||
inputTokens: 4320000,
|
||||
outputTokens: 1182000,
|
||||
activeUsers: 326,
|
||||
activeTasks: 207,
|
||||
newTasks: 1248,
|
||||
conversations: 3864,
|
||||
},
|
||||
"30m": {
|
||||
modelConsumption: 711,
|
||||
p95ResponseTime: 931,
|
||||
modelSuccessRate: 99.4,
|
||||
modelCalls: 7900,
|
||||
tpm: 354600,
|
||||
rpm: 263,
|
||||
inputTokens: 8360000,
|
||||
outputTokens: 2278000,
|
||||
activeUsers: 451,
|
||||
activeTasks: 318,
|
||||
newTasks: 2436,
|
||||
conversations: 7542,
|
||||
},
|
||||
"60m": {
|
||||
modelConsumption: 1384,
|
||||
p95ResponseTime: 1024,
|
||||
modelSuccessRate: 99.2,
|
||||
modelCalls: 15660,
|
||||
tpm: 344300,
|
||||
rpm: 261,
|
||||
inputTokens: 16240000,
|
||||
outputTokens: 4418000,
|
||||
activeUsers: 612,
|
||||
activeTasks: 428,
|
||||
newTasks: 4680,
|
||||
conversations: 14620,
|
||||
},
|
||||
}
|
||||
type MetricKey = Exclude<keyof RealtimeStatistics, "from" | "until">
|
||||
|
||||
const METRICS = [
|
||||
{
|
||||
key: "modelConsumption",
|
||||
key: "model_consumption",
|
||||
labelKey: "pages.realtimeStatus.metrics.modelConsumption",
|
||||
icon: Coins01Icon,
|
||||
},
|
||||
{
|
||||
key: "p95ResponseTime",
|
||||
key: "p95_response_time",
|
||||
labelKey: "pages.realtimeStatus.metrics.p95ResponseTime",
|
||||
icon: Clock01Icon,
|
||||
},
|
||||
{
|
||||
key: "modelSuccessRate",
|
||||
key: "model_success_rate",
|
||||
labelKey: "pages.realtimeStatus.metrics.modelSuccessRate",
|
||||
icon: TaskDone01Icon,
|
||||
},
|
||||
{
|
||||
key: "modelCalls",
|
||||
key: "model_calls",
|
||||
labelKey: "pages.realtimeStatus.metrics.modelCalls",
|
||||
icon: Activity01Icon,
|
||||
},
|
||||
@@ -135,35 +64,30 @@ const METRICS = [
|
||||
icon: GaugeIcon,
|
||||
},
|
||||
{
|
||||
key: "inputTokens",
|
||||
key: "input_tokens",
|
||||
labelKey: "pages.realtimeStatus.metrics.inputTokens",
|
||||
icon: TokenCircleIcon,
|
||||
},
|
||||
{
|
||||
key: "outputTokens",
|
||||
key: "output_tokens",
|
||||
labelKey: "pages.realtimeStatus.metrics.outputTokens",
|
||||
icon: AiChat02Icon,
|
||||
},
|
||||
{
|
||||
key: "activeUsers",
|
||||
key: "active_users",
|
||||
labelKey: "pages.realtimeStatus.metrics.activeUsers",
|
||||
icon: UserMultiple02Icon,
|
||||
},
|
||||
{
|
||||
key: "activeTasks",
|
||||
key: "active_tasks",
|
||||
labelKey: "pages.realtimeStatus.metrics.activeTasks",
|
||||
icon: Task01Icon,
|
||||
},
|
||||
{
|
||||
key: "newTasks",
|
||||
key: "new_tasks",
|
||||
labelKey: "pages.realtimeStatus.metrics.newTasks",
|
||||
icon: AddSquareIcon,
|
||||
},
|
||||
{
|
||||
key: "conversations",
|
||||
labelKey: "pages.realtimeStatus.metrics.conversations",
|
||||
icon: Message01Icon,
|
||||
},
|
||||
] as const
|
||||
|
||||
function RealtimeMetricCard({
|
||||
@@ -210,29 +134,50 @@ export function RealtimeStatusPage() {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
})
|
||||
const snapshot = REALTIME_SNAPSHOTS[timeRange]
|
||||
const valueLabels: Record<MetricKey, string> = {
|
||||
modelConsumption: t("pages.realtimeStatus.units.credits", {
|
||||
count: numberFormatter.format(snapshot.modelConsumption),
|
||||
}),
|
||||
p95ResponseTime: t("pages.realtimeStatus.units.milliseconds", {
|
||||
count: numberFormatter.format(snapshot.p95ResponseTime),
|
||||
}),
|
||||
modelSuccessRate: `${percentFormatter.format(snapshot.modelSuccessRate)}%`,
|
||||
modelCalls: numberFormatter.format(snapshot.modelCalls),
|
||||
tpm: compactNumberFormatter.format(snapshot.tpm),
|
||||
rpm: numberFormatter.format(snapshot.rpm),
|
||||
inputTokens: compactNumberFormatter.format(snapshot.inputTokens),
|
||||
outputTokens: compactNumberFormatter.format(snapshot.outputTokens),
|
||||
activeUsers: numberFormatter.format(snapshot.activeUsers),
|
||||
activeTasks: numberFormatter.format(snapshot.activeTasks),
|
||||
newTasks: numberFormatter.format(snapshot.newTasks),
|
||||
conversations: numberFormatter.format(snapshot.conversations),
|
||||
}
|
||||
const request = useStatistics<RealtimeStatistics>(
|
||||
`/api/admin/v1/statistics/realtime?range=${timeRange}`,
|
||||
30000
|
||||
)
|
||||
const snapshot = request.data
|
||||
const valueLabels: Record<MetricKey, string> | undefined = snapshot
|
||||
? {
|
||||
model_consumption: t("pages.realtimeStatus.units.credits", {
|
||||
count: new Intl.NumberFormat(locale, {
|
||||
maximumFractionDigits: 6,
|
||||
}).format(Number(snapshot.model_consumption)),
|
||||
}),
|
||||
p95_response_time:
|
||||
snapshot.p95_response_time === null
|
||||
? "—"
|
||||
: t("pages.realtimeStatus.units.milliseconds", {
|
||||
count: numberFormatter.format(snapshot.p95_response_time),
|
||||
}),
|
||||
model_success_rate:
|
||||
snapshot.model_success_rate === null
|
||||
? "—"
|
||||
: `${percentFormatter.format(snapshot.model_success_rate)}%`,
|
||||
model_calls: numberFormatter.format(snapshot.model_calls),
|
||||
tpm: compactNumberFormatter.format(snapshot.tpm),
|
||||
rpm: numberFormatter.format(snapshot.rpm),
|
||||
input_tokens: compactNumberFormatter.format(snapshot.input_tokens),
|
||||
output_tokens: compactNumberFormatter.format(snapshot.output_tokens),
|
||||
active_users: numberFormatter.format(snapshot.active_users),
|
||||
active_tasks: numberFormatter.format(snapshot.active_tasks),
|
||||
new_tasks: numberFormatter.format(snapshot.new_tasks),
|
||||
}
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<section className="flex flex-1 flex-col gap-4 p-4 pt-0">
|
||||
<div className="flex justify-end">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={request.reload}
|
||||
disabled={request.loading}
|
||||
>
|
||||
{t("statistics.refresh")}
|
||||
</Button>
|
||||
<Tabs
|
||||
value={timeRange}
|
||||
onValueChange={(value) => setTimeRange(value as RealtimeRange)}
|
||||
@@ -247,16 +192,24 @@ export function RealtimeStatusPage() {
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
{METRICS.map((metric) => (
|
||||
<RealtimeMetricCard
|
||||
icon={metric.icon}
|
||||
key={metric.key}
|
||||
label={t(metric.labelKey)}
|
||||
valueLabel={valueLabels[metric.key]}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("statistics.realtimeScope")}
|
||||
{snapshot &&
|
||||
` · ${t("statistics.updated", { time: new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", second: "2-digit" }).format(new Date(snapshot.until)) })}`}
|
||||
</p>
|
||||
<StatisticsFeedback {...request} />
|
||||
{valueLabels && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
{METRICS.map((metric) => (
|
||||
<RealtimeMetricCard
|
||||
icon={metric.icon}
|
||||
key={metric.key}
|
||||
label={t(metric.labelKey)}
|
||||
valueLabel={valueLabels[metric.key]}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
Search02Icon,
|
||||
} from "@hugeicons/core-free-icons"
|
||||
import { HugeiconsIcon } from "@hugeicons/react"
|
||||
import { endOfDay, startOfDay } from "date-fns"
|
||||
import { addDays, startOfDay } from "date-fns"
|
||||
import {
|
||||
ar,
|
||||
de,
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
} from "date-fns/locale"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { useStatistics } from "@/hooks/use-statistics"
|
||||
import { StatisticsFeedback } from "@/components/statistics-feedback"
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Calendar } from "@/components/ui/calendar"
|
||||
@@ -50,27 +52,21 @@ import {
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
type TaskStatus = "completed" | "running" | "failed" | "cancelled"
|
||||
type TaskType = "conversation" | "workflow" | "retrieval" | "tool" | "scheduled"
|
||||
type ClientType = "desktop" | "web" | "extension" | "mobile"
|
||||
|
||||
type TaskHistoryEntry = {
|
||||
id: string
|
||||
title: string
|
||||
type: TaskType
|
||||
clientType: ClientType
|
||||
clientName: string
|
||||
deviceId: string
|
||||
owner: string
|
||||
ownerEmail: string
|
||||
status: TaskStatus
|
||||
startedAt: string
|
||||
lastActiveAt: string
|
||||
conversationCount: number
|
||||
durationSeconds: number | null
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
credits: number
|
||||
user_name: string
|
||||
user_email: string
|
||||
started_at: string
|
||||
last_active_at: string
|
||||
turn_count: number
|
||||
}
|
||||
|
||||
type TaskHistory = {
|
||||
items: TaskHistoryEntry[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
|
||||
type TaskHistoryFilters = {
|
||||
@@ -168,225 +164,6 @@ function DatePickerField({
|
||||
)
|
||||
}
|
||||
|
||||
const TASK_HISTORY: TaskHistoryEntry[] = [
|
||||
{
|
||||
id: "task_9f2c8a1d",
|
||||
title: "生成季度经营分析报告",
|
||||
type: "workflow",
|
||||
clientType: "desktop",
|
||||
clientName: "MonkeyCode macOS",
|
||||
deviceId: "MCP-MAC-7H2K",
|
||||
owner: "张明",
|
||||
ownerEmail: "zhangming@example.com",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T07:42:18Z",
|
||||
lastActiveAt: "2026-09-02T07:44:46Z",
|
||||
conversationCount: 18,
|
||||
durationSeconds: 148,
|
||||
inputTokens: 128640,
|
||||
outputTokens: 24680,
|
||||
credits: 96,
|
||||
},
|
||||
{
|
||||
id: "task_8b4e6f20",
|
||||
title: "排查订单服务响应变慢问题",
|
||||
type: "conversation",
|
||||
clientType: "web",
|
||||
clientName: "Web Console",
|
||||
deviceId: "WEB-SESSION-83A1",
|
||||
owner: "李娜",
|
||||
ownerEmail: "lina@example.com",
|
||||
status: "running",
|
||||
startedAt: "2026-09-02T07:35:04Z",
|
||||
lastActiveAt: "2026-09-02T07:48:12Z",
|
||||
conversationCount: 12,
|
||||
durationSeconds: null,
|
||||
inputTokens: 46920,
|
||||
outputTokens: 8640,
|
||||
credits: 35,
|
||||
},
|
||||
{
|
||||
id: "task_72ad3c94",
|
||||
title: "整理竞品功能调研结果",
|
||||
type: "retrieval",
|
||||
clientType: "extension",
|
||||
clientName: "Chrome Extension",
|
||||
deviceId: "EXT-CHROME-2D91",
|
||||
owner: "王琦",
|
||||
ownerEmail: "wangqi@example.com",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T06:58:31Z",
|
||||
lastActiveAt: "2026-09-02T06:59:45Z",
|
||||
conversationCount: 6,
|
||||
durationSeconds: 74,
|
||||
inputTokens: 58940,
|
||||
outputTokens: 11320,
|
||||
credits: 44,
|
||||
},
|
||||
{
|
||||
id: "task_615ee4b7",
|
||||
title: "修复移动端登录状态丢失",
|
||||
type: "tool",
|
||||
clientType: "desktop",
|
||||
clientName: "MonkeyCode Windows",
|
||||
deviceId: "MCP-WIN-4F6B",
|
||||
owner: "陈晨",
|
||||
ownerEmail: "chenchen@example.com",
|
||||
status: "failed",
|
||||
startedAt: "2026-09-02T06:26:47Z",
|
||||
lastActiveAt: "2026-09-02T06:27:39Z",
|
||||
conversationCount: 9,
|
||||
durationSeconds: 52,
|
||||
inputTokens: 31760,
|
||||
outputTokens: 4280,
|
||||
credits: 23,
|
||||
},
|
||||
{
|
||||
id: "task_5cd8913a",
|
||||
title: "同步产品帮助中心知识库",
|
||||
type: "scheduled",
|
||||
clientType: "web",
|
||||
clientName: "Web Console",
|
||||
deviceId: "WEB-SCHEDULER",
|
||||
owner: "系统",
|
||||
ownerEmail: "system@monkeyai.local",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T05:00:00Z",
|
||||
lastActiveAt: "2026-09-02T05:03:56Z",
|
||||
conversationCount: 4,
|
||||
durationSeconds: 236,
|
||||
inputTokens: 284500,
|
||||
outputTokens: 18720,
|
||||
credits: 158,
|
||||
},
|
||||
{
|
||||
id: "task_49e72b6c",
|
||||
title: "总结客户访谈录音",
|
||||
type: "conversation",
|
||||
clientType: "mobile",
|
||||
clientName: "MonkeyCode iOS",
|
||||
deviceId: "IOS-15PM-8A31",
|
||||
owner: "周悦",
|
||||
ownerEmail: "zhouyue@example.com",
|
||||
status: "cancelled",
|
||||
startedAt: "2026-09-02T04:42:16Z",
|
||||
lastActiveAt: "2026-09-02T04:42:47Z",
|
||||
conversationCount: 3,
|
||||
durationSeconds: 31,
|
||||
inputTokens: 18420,
|
||||
outputTokens: 2180,
|
||||
credits: 12,
|
||||
},
|
||||
{
|
||||
id: "task_330af85e",
|
||||
title: "生成 API 接口测试用例",
|
||||
type: "workflow",
|
||||
clientType: "desktop",
|
||||
clientName: "MonkeyCode Linux",
|
||||
deviceId: "MCP-LINUX-91C7",
|
||||
owner: "赵磊",
|
||||
ownerEmail: "zhaolei@example.com",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T03:54:02Z",
|
||||
lastActiveAt: "2026-09-02T03:55:54Z",
|
||||
conversationCount: 15,
|
||||
durationSeconds: 112,
|
||||
inputTokens: 96480,
|
||||
outputTokens: 22460,
|
||||
credits: 78,
|
||||
},
|
||||
{
|
||||
id: "task_2ed64a10",
|
||||
title: "检查发布分支代码变更",
|
||||
type: "tool",
|
||||
clientType: "extension",
|
||||
clientName: "VS Code Extension",
|
||||
deviceId: "EXT-VSCODE-44E2",
|
||||
owner: "张明",
|
||||
ownerEmail: "zhangming@example.com",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T03:18:49Z",
|
||||
lastActiveAt: "2026-09-02T03:20:18Z",
|
||||
conversationCount: 8,
|
||||
durationSeconds: 89,
|
||||
inputTokens: 74120,
|
||||
outputTokens: 12680,
|
||||
credits: 55,
|
||||
},
|
||||
{
|
||||
id: "task_1a9c37fd",
|
||||
title: "提取合同中的风险条款",
|
||||
type: "retrieval",
|
||||
clientType: "mobile",
|
||||
clientName: "MonkeyCode Android",
|
||||
deviceId: "ANDROID-P9-6D0A",
|
||||
owner: "李娜",
|
||||
ownerEmail: "lina@example.com",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T02:47:35Z",
|
||||
lastActiveAt: "2026-09-02T02:48:43Z",
|
||||
conversationCount: 5,
|
||||
durationSeconds: 68,
|
||||
inputTokens: 52640,
|
||||
outputTokens: 9780,
|
||||
credits: 41,
|
||||
},
|
||||
{
|
||||
id: "task_0f5632bc",
|
||||
title: "分析本周客服会话主题",
|
||||
type: "scheduled",
|
||||
clientType: "web",
|
||||
clientName: "Web Console",
|
||||
deviceId: "WEB-SCHEDULER",
|
||||
owner: "系统",
|
||||
ownerEmail: "system@monkeyai.local",
|
||||
status: "failed",
|
||||
startedAt: "2026-09-02T02:00:00Z",
|
||||
lastActiveAt: "2026-09-02T02:03:04Z",
|
||||
conversationCount: 7,
|
||||
durationSeconds: 184,
|
||||
inputTokens: 192300,
|
||||
outputTokens: 15640,
|
||||
credits: 121,
|
||||
},
|
||||
{
|
||||
id: "task_f82d10a7",
|
||||
title: "优化数据导入脚本",
|
||||
type: "conversation",
|
||||
clientType: "desktop",
|
||||
clientName: "MonkeyCode macOS",
|
||||
deviceId: "MCP-MAC-7H2K",
|
||||
owner: "张明",
|
||||
ownerEmail: "zhangming@example.com",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T01:26:53Z",
|
||||
lastActiveAt: "2026-09-02T01:30:16Z",
|
||||
conversationCount: 21,
|
||||
durationSeconds: 203,
|
||||
inputTokens: 156840,
|
||||
outputTokens: 31860,
|
||||
credits: 117,
|
||||
},
|
||||
{
|
||||
id: "task_e47ba291",
|
||||
title: "制作新品发布会内容大纲",
|
||||
type: "workflow",
|
||||
clientType: "web",
|
||||
clientName: "Web Console",
|
||||
deviceId: "WEB-SESSION-61B3",
|
||||
owner: "周悦",
|
||||
ownerEmail: "zhouyue@example.com",
|
||||
status: "completed",
|
||||
startedAt: "2026-09-02T00:38:12Z",
|
||||
lastActiveAt: "2026-09-02T00:40:18Z",
|
||||
conversationCount: 14,
|
||||
durationSeconds: 126,
|
||||
inputTokens: 88260,
|
||||
outputTokens: 19740,
|
||||
credits: 69,
|
||||
},
|
||||
]
|
||||
|
||||
export function TaskHistoryPage() {
|
||||
const { i18n, t } = useTranslation()
|
||||
const [filterInput, setFilterInput] =
|
||||
@@ -398,44 +175,26 @@ export function TaskHistoryPage() {
|
||||
const language = locale.split("-")[0]
|
||||
const calendarLocale = DATE_LOCALES[locale] ?? DATE_LOCALES[language] ?? enUS
|
||||
|
||||
const filteredTasks = useMemo(() => {
|
||||
const taskNameQuery = filters.taskName.trim().toLocaleLowerCase(locale)
|
||||
const userNameQuery = filters.userName.trim().toLocaleLowerCase(locale)
|
||||
const startTimestamp = filters.startTime
|
||||
? startOfDay(filters.startTime).getTime()
|
||||
: null
|
||||
const endTimestamp = filters.endTime
|
||||
? endOfDay(filters.endTime).getTime()
|
||||
: null
|
||||
|
||||
return TASK_HISTORY.filter((task) => {
|
||||
const startedAt = new Date(task.startedAt).getTime()
|
||||
const matchesTaskName =
|
||||
taskNameQuery.length === 0 ||
|
||||
[task.id, task.title].some((value) =>
|
||||
value.toLocaleLowerCase(locale).includes(taskNameQuery)
|
||||
)
|
||||
const matchesUserName =
|
||||
userNameQuery.length === 0 ||
|
||||
[task.owner, task.ownerEmail].some((value) =>
|
||||
value.toLocaleLowerCase(locale).includes(userNameQuery)
|
||||
)
|
||||
const matchesStartTime =
|
||||
startTimestamp === null || startedAt >= startTimestamp
|
||||
const matchesEndTime = endTimestamp === null || startedAt <= endTimestamp
|
||||
|
||||
return (
|
||||
matchesTaskName && matchesUserName && matchesStartTime && matchesEndTime
|
||||
)
|
||||
})
|
||||
}, [filters, locale])
|
||||
|
||||
const pageCount = Math.max(1, Math.ceil(filteredTasks.length / pageSize))
|
||||
const currentPage = Math.min(page, pageCount)
|
||||
const query = new URLSearchParams({
|
||||
task: filters.taskName,
|
||||
user: filters.userName,
|
||||
page: String(page),
|
||||
page_size: String(pageSize),
|
||||
})
|
||||
if (filters.startTime)
|
||||
query.set("from", startOfDay(filters.startTime).toISOString())
|
||||
if (filters.endTime)
|
||||
query.set("until", startOfDay(addDays(filters.endTime, 1)).toISOString())
|
||||
const request = useStatistics<TaskHistory>(
|
||||
`/api/admin/v1/statistics/history?${query}`
|
||||
)
|
||||
const total = request.data?.total ?? 0
|
||||
const pageCount = Math.max(1, Math.ceil(total / pageSize))
|
||||
const currentPage = request.data?.page ?? page
|
||||
const pageStart = (currentPage - 1) * pageSize
|
||||
const visibleTasks = filteredTasks.slice(pageStart, pageStart + pageSize)
|
||||
const firstVisible = filteredTasks.length === 0 ? 0 : pageStart + 1
|
||||
const lastVisible = Math.min(pageStart + pageSize, filteredTasks.length)
|
||||
const visibleTasks = request.data?.items ?? []
|
||||
const firstVisible = total === 0 ? 0 : pageStart + 1
|
||||
const lastVisible = Math.min(pageStart + pageSize, total)
|
||||
const numberFormatter = useMemo(() => new Intl.NumberFormat(locale), [locale])
|
||||
const dateFormatter = useMemo(
|
||||
() =>
|
||||
@@ -464,11 +223,13 @@ export function TaskHistoryPage() {
|
||||
const applySearch = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
setFilters(filterInput)
|
||||
request.reload()
|
||||
resetPage()
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="flex min-h-0 flex-1 flex-col p-4 pt-0">
|
||||
<StatisticsFeedback {...request} />
|
||||
<Card>
|
||||
<CardContent className="gap-4 px-0">
|
||||
<form onSubmit={applySearch} className="px-(--card-spacing)">
|
||||
@@ -593,26 +354,28 @@ export function TaskHistoryPage() {
|
||||
<TableCell>
|
||||
<div
|
||||
className="flex max-w-52 items-center gap-3"
|
||||
title={task.ownerEmail}
|
||||
title={task.user_email}
|
||||
>
|
||||
<Avatar className="size-6">
|
||||
<AvatarFallback>
|
||||
{task.owner.slice(0, 1).toLocaleUpperCase(locale)}
|
||||
{task.user_name
|
||||
.slice(0, 1)
|
||||
.toLocaleUpperCase(locale)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate font-medium">
|
||||
{task.owner}
|
||||
{task.user_name}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-muted-foreground">
|
||||
{dateFormatter.format(new Date(task.startedAt))}
|
||||
{dateFormatter.format(new Date(task.started_at))}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-muted-foreground">
|
||||
{dateFormatter.format(new Date(task.lastActiveAt))}
|
||||
{dateFormatter.format(new Date(task.last_active_at))}
|
||||
</TableCell>
|
||||
<TableCell className="pe-(--card-spacing) text-end tabular-nums">
|
||||
{numberFormatter.format(task.conversationCount)}
|
||||
{numberFormatter.format(task.turn_count)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
@@ -622,7 +385,11 @@ export function TaskHistoryPage() {
|
||||
colSpan={5}
|
||||
className="h-40 text-center text-muted-foreground"
|
||||
>
|
||||
{t("pages.taskHistory.empty")}
|
||||
{request.loading
|
||||
? t("statistics.loading")
|
||||
: request.error
|
||||
? "—"
|
||||
: t("pages.taskHistory.empty")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@@ -660,7 +427,7 @@ export function TaskHistoryPage() {
|
||||
{t("pages.operationLogs.pagination.summary", {
|
||||
from: firstVisible,
|
||||
to: lastVisible,
|
||||
total: filteredTasks.length,
|
||||
total,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
@@ -675,8 +442,10 @@ export function TaskHistoryPage() {
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
disabled={currentPage === 1}
|
||||
onClick={() => setPage((value) => Math.max(1, value - 1))}
|
||||
disabled={
|
||||
request.loading || !!request.error || currentPage === 1
|
||||
}
|
||||
onClick={() => setPage(Math.max(1, currentPage - 1))}
|
||||
aria-label={t("pages.operationLogs.pagination.previous")}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
@@ -688,10 +457,10 @@ export function TaskHistoryPage() {
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
disabled={currentPage === pageCount}
|
||||
onClick={() =>
|
||||
setPage((value) => Math.min(pageCount, value + 1))
|
||||
disabled={
|
||||
request.loading || !!request.error || currentPage >= pageCount
|
||||
}
|
||||
onClick={() => setPage(Math.min(pageCount, currentPage + 1))}
|
||||
aria-label={t("pages.operationLogs.pagination.next")}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useState } from "react"
|
||||
import {
|
||||
Clock01Icon,
|
||||
Loading03Icon,
|
||||
@@ -15,6 +16,11 @@ import {
|
||||
YAxis,
|
||||
} from "recharts"
|
||||
|
||||
import { useStatistics } from "@/hooks/use-statistics"
|
||||
import { change, type TaskStatistics } from "@/lib/statistics"
|
||||
import { StatisticsFeedback } from "@/components/statistics-feedback"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { StatisticsMetricCard } from "@/components/statistics-metric-card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import {
|
||||
@@ -39,46 +45,51 @@ import {
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
const TASK_SUMMARY = {
|
||||
total: 12846,
|
||||
completionRate: 92.4,
|
||||
averageDurationSeconds: 102,
|
||||
running: 186,
|
||||
trends: ["+12.5%", "+2.1%", "-8.4%", "+14"],
|
||||
} as const
|
||||
|
||||
const TASK_TYPE_ROWS = [
|
||||
{ key: "conversation", total: 5150, completionRate: 94.8, duration: 48 },
|
||||
{ key: "workflow", total: 2980, completionRate: 91.2, duration: 136 },
|
||||
{ key: "retrieval", total: 2236, completionRate: 93.5, duration: 64 },
|
||||
{ key: "tool", total: 1720, completionRate: 88.9, duration: 82 },
|
||||
{ key: "scheduled", total: 760, completionRate: 90.7, duration: 174 },
|
||||
] as const
|
||||
|
||||
function buildTaskTrendData(dateFormatter: Intl.DateTimeFormat) {
|
||||
const days = 30
|
||||
const points = 10
|
||||
const endDate = new Date(2026, 8, 2)
|
||||
|
||||
return Array.from({ length: points }, (_, index) => {
|
||||
const date = new Date(endDate)
|
||||
const daysAgo = Math.round(
|
||||
((points - 1 - index) * (days - 1)) / (points - 1)
|
||||
)
|
||||
date.setDate(date.getDate() - daysAgo)
|
||||
|
||||
return {
|
||||
date: dateFormatter.format(date),
|
||||
completed: Math.round(276 + index * 11 + Math.sin(index * 1.35) * 32),
|
||||
failed: Math.max(8, Math.round(26 + Math.cos(index * 1.1) * 9)),
|
||||
}
|
||||
})
|
||||
export function TaskStatisticsPage() {
|
||||
const { t } = useTranslation()
|
||||
const [timeRange, setTimeRange] = useState("30d")
|
||||
const request = useStatistics<TaskStatistics>(
|
||||
`/api/admin/v1/statistics/tasks?range=${timeRange}`
|
||||
)
|
||||
return (
|
||||
<section className="flex flex-1 flex-col gap-4 p-4 pt-0">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<Tabs value={timeRange} onValueChange={setTimeRange}>
|
||||
<TabsList aria-label={t("pages.taskStatistics.timeRange")}>
|
||||
{(["7d", "30d", "90d"] as const).map((range) => (
|
||||
<TabsTrigger key={range} value={range}>
|
||||
{t(`pages.taskStatistics.ranges.${range}`)}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={request.reload}
|
||||
disabled={request.loading}
|
||||
>
|
||||
{t("statistics.refresh")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("statistics.taskScope")}
|
||||
</p>
|
||||
<StatisticsFeedback
|
||||
{...request}
|
||||
empty={request.data?.summary.total === 0}
|
||||
/>
|
||||
{request.data && <TaskDetails data={request.data} />}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export function TaskStatisticsPage() {
|
||||
function TaskDetails({ data }: { data: TaskStatistics }) {
|
||||
const { i18n, t } = useTranslation()
|
||||
const locale = i18n.resolvedLanguage ?? i18n.language
|
||||
const numberFormatter = new Intl.NumberFormat(locale)
|
||||
const numberFormatter = new Intl.NumberFormat(locale, {
|
||||
maximumFractionDigits: 1,
|
||||
})
|
||||
const compactNumberFormatter = new Intl.NumberFormat(locale, {
|
||||
notation: "compact",
|
||||
maximumFractionDigits: 1,
|
||||
@@ -87,30 +98,26 @@ export function TaskStatisticsPage() {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
const summary = TASK_SUMMARY
|
||||
const trendData = buildTaskTrendData(dateFormatter)
|
||||
const completedTasks = Math.round(
|
||||
(summary.total * summary.completionRate) / 100
|
||||
)
|
||||
const failedTasks = Math.max(
|
||||
0,
|
||||
summary.total - completedTasks - summary.running
|
||||
)
|
||||
const summary = data.summary
|
||||
const trendData = data.trend.map((row) => ({
|
||||
...row,
|
||||
date: dateFormatter.format(new Date(row.at)),
|
||||
}))
|
||||
const statusData = [
|
||||
{
|
||||
status: "completed",
|
||||
value: completedTasks,
|
||||
fill: "var(--color-completed)",
|
||||
value: summary.completed,
|
||||
fill: "var(--chart-2)",
|
||||
},
|
||||
{
|
||||
status: "running",
|
||||
value: summary.running,
|
||||
fill: "var(--color-running)",
|
||||
fill: "var(--chart-3)",
|
||||
},
|
||||
{
|
||||
status: "failed",
|
||||
value: failedTasks,
|
||||
fill: "var(--color-failed)",
|
||||
value: summary.failed,
|
||||
fill: "var(--chart-5)",
|
||||
},
|
||||
]
|
||||
const trendChartConfig = {
|
||||
@@ -137,53 +144,60 @@ export function TaskStatisticsPage() {
|
||||
color: "var(--chart-5)",
|
||||
},
|
||||
} satisfies ChartConfig
|
||||
const scaledTaskTypes = TASK_TYPE_ROWS.map((row) => {
|
||||
const total = row.total
|
||||
|
||||
return {
|
||||
...row,
|
||||
total,
|
||||
completed: Math.round((total * row.completionRate) / 100),
|
||||
}
|
||||
})
|
||||
const formatDuration = (seconds: number) =>
|
||||
seconds < 60
|
||||
? t("pages.taskStatistics.durationSeconds", { count: seconds })
|
||||
const scaledTaskTypes = data.types
|
||||
const formatDuration = (seconds: number | null) => {
|
||||
if (seconds === null) return "—"
|
||||
const rounded = Math.round(seconds)
|
||||
return rounded < 60
|
||||
? t("pages.taskStatistics.durationSeconds", { count: rounded })
|
||||
: t("pages.taskStatistics.durationMinutes", {
|
||||
minutes: Math.floor(seconds / 60),
|
||||
seconds: seconds % 60,
|
||||
minutes: Math.floor(rounded / 60),
|
||||
seconds: rounded % 60,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="flex flex-1 flex-col gap-4 p-4 pt-0">
|
||||
<>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.taskStatistics.comparedToPrevious")}
|
||||
icon={Task01Icon}
|
||||
label={t("pages.taskStatistics.metrics.totalTasks")}
|
||||
trend={summary.trends[0]}
|
||||
trend={change(summary.total, data.previous.total, locale)}
|
||||
value={numberFormatter.format(summary.total)}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.taskStatistics.comparedToPrevious")}
|
||||
icon={TaskDone01Icon}
|
||||
label={t("pages.taskStatistics.metrics.completionRate")}
|
||||
trend={summary.trends[1]}
|
||||
value={`${summary.completionRate}%`}
|
||||
trend={change(
|
||||
summary.completion_rate,
|
||||
data.previous.completion_rate,
|
||||
locale,
|
||||
true
|
||||
)}
|
||||
value={
|
||||
summary.completion_rate === null
|
||||
? "—"
|
||||
: `${numberFormatter.format(summary.completion_rate)}%`
|
||||
}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.taskStatistics.comparedToPrevious")}
|
||||
icon={Clock01Icon}
|
||||
label={t("pages.taskStatistics.metrics.averageDuration")}
|
||||
trend={summary.trends[2]}
|
||||
trendDirection="down"
|
||||
value={formatDuration(summary.averageDurationSeconds)}
|
||||
trend={change(
|
||||
summary.average_duration_seconds,
|
||||
data.previous.average_duration_seconds,
|
||||
locale
|
||||
)}
|
||||
value={formatDuration(summary.average_duration_seconds)}
|
||||
/>
|
||||
<StatisticsMetricCard
|
||||
comparison={t("pages.taskStatistics.comparedToPrevious")}
|
||||
icon={Loading03Icon}
|
||||
label={t("pages.taskStatistics.metrics.runningTasks")}
|
||||
trend={summary.trends[3]}
|
||||
trend={change(summary.running, data.previous.running, locale)}
|
||||
value={numberFormatter.format(summary.running)}
|
||||
/>
|
||||
</div>
|
||||
@@ -220,6 +234,7 @@ export function TaskStatisticsPage() {
|
||||
content={<ChartTooltipContent indicator="line" />}
|
||||
/>
|
||||
<Area
|
||||
isAnimationActive={false}
|
||||
dataKey="completed"
|
||||
fill="var(--color-completed)"
|
||||
fillOpacity={0.22}
|
||||
@@ -228,6 +243,7 @@ export function TaskStatisticsPage() {
|
||||
type="monotone"
|
||||
/>
|
||||
<Area
|
||||
isAnimationActive={false}
|
||||
dataKey="failed"
|
||||
fill="var(--color-failed)"
|
||||
fillOpacity={0.1}
|
||||
@@ -257,6 +273,7 @@ export function TaskStatisticsPage() {
|
||||
content={<ChartTooltipContent hideLabel nameKey="status" />}
|
||||
/>
|
||||
<Pie
|
||||
isAnimationActive={false}
|
||||
data={statusData}
|
||||
dataKey="value"
|
||||
innerRadius={56}
|
||||
@@ -330,10 +347,14 @@ export function TaskStatisticsPage() {
|
||||
{numberFormatter.format(row.completed)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{row.completionRate}%</Badge>
|
||||
<Badge variant="outline">
|
||||
{row.completion_rate === null
|
||||
? "—"
|
||||
: `${numberFormatter.format(row.completion_rate)}%`}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="pe-(--card-spacing) text-end tabular-nums">
|
||||
{formatDuration(row.duration)}
|
||||
{formatDuration(row.average_duration_seconds)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -341,6 +362,6 @@ export function TaskStatisticsPage() {
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -25,6 +25,13 @@ function getLeafPaths(value, prefix = "") {
|
||||
})
|
||||
}
|
||||
|
||||
test("统计反馈在每种语言中提供相同字段", () => {
|
||||
const expected = getLeafPaths(enUS.statistics).sort()
|
||||
for (const [language, resource] of Object.entries(resources)) {
|
||||
assert.deepEqual(getLeafPaths(resource.statistics).sort(), expected, language)
|
||||
}
|
||||
})
|
||||
|
||||
test("billing details describe the item and usage in one content column", async () => {
|
||||
const source = await readFile(
|
||||
new URL("../src/pages/billing-details-page.tsx", import.meta.url),
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { change } from "../src/lib/statistics.ts"
|
||||
|
||||
test("没有可比样本时不生成虚假环比", () => {
|
||||
assert.equal(change(10, 0, "zh-CN"), undefined)
|
||||
assert.equal(change(0, 0, "zh-CN"), undefined)
|
||||
assert.equal(change(null, 20, "zh-CN"), undefined)
|
||||
assert.equal(change(20, null, "zh-CN"), undefined)
|
||||
})
|
||||
|
||||
test("数量环比与百分比指标使用不同单位", () => {
|
||||
assert.equal(change(120, 100, "zh-CN"), "+20%")
|
||||
assert.equal(change(50, 100, "zh-CN"), "-50%")
|
||||
assert.equal(change(0, 100, "zh-CN"), "-100%")
|
||||
assert.equal(change(51, 50, "zh-CN", true), "+1 pp")
|
||||
assert.equal(change(20, 0, "zh-CN", true), "+20 pp")
|
||||
})
|
||||
@@ -5,6 +5,195 @@ info:
|
||||
security:
|
||||
- AdminSession: []
|
||||
paths:
|
||||
/api/admin/v1/statistics/models:
|
||||
get:
|
||||
summary: 模型统计与真实环比
|
||||
description: 仅管理员可访问。单次请求在同一 PostgreSQL 只读快照中聚合,不返回模拟数据。
|
||||
parameters:
|
||||
- name: range
|
||||
in: query
|
||||
required: false
|
||||
description: 以服务端当前时间为终点的滚动窗口。
|
||||
schema:
|
||||
type: string
|
||||
enum:
|
||||
- 24h
|
||||
- 7d
|
||||
- 30d
|
||||
- 90d
|
||||
default: 30d
|
||||
- name: model_id
|
||||
in: query
|
||||
required: false
|
||||
description: 模型 UUID,省略时汇总全部模型;支持已有历史事实的软删除模型。
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
responses:
|
||||
"200":
|
||||
description: 统计结果。
|
||||
headers:
|
||||
Cache-Control:
|
||||
schema:
|
||||
type: string
|
||||
const: private, no-store
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatisticsModels"
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/ResourceError401"
|
||||
"403":
|
||||
$ref: "#/components/responses/ResourceError403"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/statistics/tasks:
|
||||
get:
|
||||
summary: 会话统计与真实环比
|
||||
description: 仅管理员可访问。单次请求在同一 PostgreSQL 只读快照中聚合,不返回模拟数据。
|
||||
parameters:
|
||||
- name: range
|
||||
in: query
|
||||
required: false
|
||||
description: 以服务端当前时间为终点的滚动窗口。
|
||||
schema:
|
||||
type: string
|
||||
enum:
|
||||
- 24h
|
||||
- 7d
|
||||
- 30d
|
||||
- 90d
|
||||
default: 30d
|
||||
responses:
|
||||
"200":
|
||||
description: 统计结果。
|
||||
headers:
|
||||
Cache-Control:
|
||||
schema:
|
||||
type: string
|
||||
const: private, no-store
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatisticsTasks"
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/ResourceError401"
|
||||
"403":
|
||||
$ref: "#/components/responses/ResourceError403"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/statistics/realtime:
|
||||
get:
|
||||
summary: 实时运行统计
|
||||
description: 仅管理员可访问。单次请求在同一 PostgreSQL 只读快照中聚合,不返回模拟数据。
|
||||
parameters:
|
||||
- name: range
|
||||
in: query
|
||||
required: false
|
||||
description: 以服务端当前时间为终点的滚动窗口。
|
||||
schema:
|
||||
type: string
|
||||
enum:
|
||||
- 5m
|
||||
- 15m
|
||||
- 30m
|
||||
- 60m
|
||||
default: 15m
|
||||
responses:
|
||||
"200":
|
||||
description: 统计结果。
|
||||
headers:
|
||||
Cache-Control:
|
||||
schema:
|
||||
type: string
|
||||
const: private, no-store
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatisticsRealtime"
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/ResourceError401"
|
||||
"403":
|
||||
$ref: "#/components/responses/ResourceError403"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/statistics/history:
|
||||
get:
|
||||
summary: 分页查询会话历史
|
||||
description: 仅管理员可访问。单次请求在同一 PostgreSQL 只读快照中聚合,不返回模拟数据。
|
||||
parameters:
|
||||
- name: task
|
||||
in: query
|
||||
required: false
|
||||
description: 按会话标题或 UUID 包含匹配;百分号和下划线作为普通字符。
|
||||
schema:
|
||||
type: string
|
||||
maxLength: 200
|
||||
- name: user
|
||||
in: query
|
||||
required: false
|
||||
description: 按用户名或邮箱包含匹配,忽略大小写。
|
||||
schema:
|
||||
type: string
|
||||
maxLength: 200
|
||||
- name: from
|
||||
in: query
|
||||
required: false
|
||||
description: 会话开始时间下界,包含;必须携带时区。
|
||||
schema:
|
||||
type: string
|
||||
format: date-time
|
||||
- name: until
|
||||
in: query
|
||||
required: false
|
||||
description: 会话开始时间上界,不包含;必须晚于 from。日期筛选应传次日零点。
|
||||
schema:
|
||||
type: string
|
||||
format: date-time
|
||||
- name: page
|
||||
in: query
|
||||
required: false
|
||||
description: 页码。
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 1000000
|
||||
default: 1
|
||||
- name: page_size
|
||||
in: query
|
||||
required: false
|
||||
description: 每页条数。
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 500
|
||||
default: 20
|
||||
responses:
|
||||
"200":
|
||||
description: 统计结果。
|
||||
headers:
|
||||
Cache-Control:
|
||||
schema:
|
||||
type: string
|
||||
const: private, no-store
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatisticsHistory"
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/ResourceError401"
|
||||
"403":
|
||||
$ref: "#/components/responses/ResourceError403"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/billing/settings:
|
||||
get:
|
||||
summary: 读取计费策略与远程连接状态
|
||||
@@ -3426,6 +3615,323 @@ components:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorResponse"
|
||||
schemas:
|
||||
StatisticsModelSummary:
|
||||
type: object
|
||||
required:
|
||||
- calls
|
||||
- input_tokens
|
||||
- output_tokens
|
||||
- cache_hit_rate
|
||||
- success_rate
|
||||
- credits
|
||||
properties:
|
||||
calls:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 按开始时间计数,包含成功、失败和取消调用。
|
||||
input_tokens:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 输入 Token 总量,包含缓存输入。
|
||||
output_tokens:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 输出 Token 总量。
|
||||
cache_hit_rate:
|
||||
type:
|
||||
- number
|
||||
- "null"
|
||||
description: 命中缓存的调用次数 / 调用总数 × 100;没有调用时为 null。
|
||||
success_rate:
|
||||
type:
|
||||
- number
|
||||
- "null"
|
||||
description: 成功调用 / 已结束调用 × 100;没有已结束调用时为 null。
|
||||
credits: &a1
|
||||
type: string
|
||||
pattern: ^-?[0-9]+(\.[0-9]{1,6})?$
|
||||
description: 扣费减退款后的积分净消费,十进制字符串;纯退款周期可为负值。
|
||||
StatisticsModels:
|
||||
type: object
|
||||
required:
|
||||
- from
|
||||
- until
|
||||
- summary
|
||||
- previous
|
||||
- models
|
||||
- trend
|
||||
properties:
|
||||
from: &a2
|
||||
type: string
|
||||
format: date-time
|
||||
description: 查询窗口起点,包含。
|
||||
until: &a3
|
||||
type: string
|
||||
format: date-time
|
||||
description: 查询窗口终点,不包含;由服务端统一确定。
|
||||
summary:
|
||||
$ref: "#/components/schemas/StatisticsModelSummary"
|
||||
previous:
|
||||
$ref: "#/components/schemas/StatisticsModelSummary"
|
||||
description: 紧邻当前窗口之前的等长周期。
|
||||
models:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- id
|
||||
- name
|
||||
- deleted
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
name:
|
||||
type: string
|
||||
description: 模型显示名。
|
||||
deleted:
|
||||
type: boolean
|
||||
description: 模型是否已软删除;历史调用和消费仍保留。
|
||||
trend:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- at
|
||||
- calls
|
||||
- input_tokens
|
||||
- output_tokens
|
||||
- credits
|
||||
properties:
|
||||
at:
|
||||
type: string
|
||||
format: date-time
|
||||
description: 分桶起点,从窗口起点每 1 小时(24h)或 24 小时递增,不按自然日对齐;空桶补零。
|
||||
calls:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 本桶调用数。
|
||||
input_tokens:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 本桶输入 Token。
|
||||
output_tokens:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 本桶输出 Token。
|
||||
credits: *a1
|
||||
StatisticsTaskSummary:
|
||||
type: object
|
||||
required:
|
||||
- total
|
||||
- completed
|
||||
- failed
|
||||
- running
|
||||
- completion_rate
|
||||
- average_duration_seconds
|
||||
properties:
|
||||
total:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 窗口内新建且未软删除的会话总数。
|
||||
completed:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 已结束且失败代码、失败描述均为空的会话数。
|
||||
failed:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 已结束且失败代码或失败描述非空的会话数,包含异常取消。
|
||||
running:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 尚未结束的会话数,可能处于空闲状态。
|
||||
completion_rate:
|
||||
type:
|
||||
- number
|
||||
- "null"
|
||||
description: 成功结束数 / 会话总数 × 100;无会话时为 null。
|
||||
average_duration_seconds:
|
||||
type:
|
||||
- number
|
||||
- "null"
|
||||
description: 已结束会话的平均耗时,单位秒;没有已结束会话时为 null。
|
||||
StatisticsTasks:
|
||||
type: object
|
||||
required:
|
||||
- from
|
||||
- until
|
||||
- summary
|
||||
- previous
|
||||
- trend
|
||||
- types
|
||||
properties:
|
||||
from: *a2
|
||||
until: *a3
|
||||
summary:
|
||||
$ref: "#/components/schemas/StatisticsTaskSummary"
|
||||
previous:
|
||||
$ref: "#/components/schemas/StatisticsTaskSummary"
|
||||
description: 紧邻当前窗口之前的等长周期,按会话当前结果汇总。
|
||||
trend:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- at
|
||||
- completed
|
||||
- failed
|
||||
- running
|
||||
properties:
|
||||
at:
|
||||
type: string
|
||||
format: date-time
|
||||
description: 分桶起点,从窗口起点每 1 小时(24h)或 24 小时递增;按会话开始时间归桶,空桶补零。
|
||||
completed:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 本桶成功结束数。
|
||||
failed:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 本桶失败数。
|
||||
running:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 本桶未结束数。
|
||||
types:
|
||||
type: array
|
||||
items:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/StatisticsTaskSummary"
|
||||
- type: object
|
||||
required:
|
||||
- key
|
||||
properties:
|
||||
key:
|
||||
type: string
|
||||
enum:
|
||||
- conversation
|
||||
- workflow
|
||||
- tool
|
||||
- scheduled
|
||||
StatisticsRealtime:
|
||||
type: object
|
||||
required:
|
||||
- from
|
||||
- until
|
||||
- model_consumption
|
||||
- p95_response_time
|
||||
- model_success_rate
|
||||
- model_calls
|
||||
- tpm
|
||||
- rpm
|
||||
- input_tokens
|
||||
- output_tokens
|
||||
- active_users
|
||||
- active_tasks
|
||||
- new_tasks
|
||||
properties:
|
||||
from: *a2
|
||||
until: *a3
|
||||
model_consumption: *a1
|
||||
p95_response_time:
|
||||
type:
|
||||
- number
|
||||
- "null"
|
||||
description: 窗口内完成的模型调用响应耗时 P95,单位毫秒;优先使用记录的耗时,否则使用完成时间减开始时间。无样本为 null。
|
||||
model_success_rate:
|
||||
type:
|
||||
- number
|
||||
- "null"
|
||||
description: 窗口内成功调用 / 已结束调用 × 100;取消计入分母,无样本为 null。
|
||||
model_calls:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 窗口内完成的模型调用总数。
|
||||
tpm:
|
||||
type: number
|
||||
description: 窗口内完成调用的输入加输出 Token 总量 / 窗口分钟数。
|
||||
rpm:
|
||||
type: number
|
||||
description: 窗口内完成调用总数 / 窗口分钟数。
|
||||
input_tokens:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 窗口内完成调用的输入 Token,包含缓存输入。
|
||||
output_tokens:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 窗口内完成调用的输出 Token。
|
||||
active_users:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 窗口内完成模型或 MCP 调用、有会话活动或发起仍在执行的计费调用的去重用户数;并非登录 DAU。
|
||||
active_tasks:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 最近活动时间在窗口内且未结束、未删除的会话数。
|
||||
new_tasks:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 窗口内创建且未删除的会话数。
|
||||
StatisticsHistory:
|
||||
type: object
|
||||
required:
|
||||
- items
|
||||
- total
|
||||
- page
|
||||
- page_size
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- id
|
||||
- title
|
||||
- user_name
|
||||
- user_email
|
||||
- started_at
|
||||
- last_active_at
|
||||
- turn_count
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
title:
|
||||
type: string
|
||||
description: 会话标题。
|
||||
user_name:
|
||||
type: string
|
||||
description: 所属用户当前姓名。
|
||||
user_email:
|
||||
type: string
|
||||
description: 所属用户当前邮箱。
|
||||
started_at:
|
||||
type: string
|
||||
format: date-time
|
||||
description: 会话开始时间。
|
||||
last_active_at:
|
||||
type: string
|
||||
format: date-time
|
||||
description: 最近活动时间。
|
||||
turn_count:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 会话累计对话轮数;不表示筛选窗口内新增轮数。
|
||||
total:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: 符合筛选条件的总记录数。
|
||||
page:
|
||||
type: integer
|
||||
minimum: 1
|
||||
description: 实际页码;超过最后一页时回退到最后一页。
|
||||
page_size:
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 500
|
||||
CreateMemberGroupInput:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/MemberGroupInput"
|
||||
|
||||
@@ -29,6 +29,7 @@ import (
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/rule"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/setting"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/skill"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/stats"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
@@ -127,6 +128,7 @@ func newApplicationHandler(ctx context.Context, logger *slog.Logger, pool *pgxpo
|
||||
group.NewService(pool).WithAccountPreserver(charges).RegisterAdmin(admin)
|
||||
settings.RegisterAdmin(admin)
|
||||
charges.RegisterAdmin(admin)
|
||||
stats.NewService(pool).RegisterAdmin(admin)
|
||||
keys.RegisterAdmin(admin)
|
||||
models.RegisterAdmin(admin)
|
||||
store.RegisterAdmin(admin)
|
||||
|
||||
@@ -103,6 +103,11 @@ func TestBillingIntegration(t *testing.T) {
|
||||
if code, _, _ := call("GET", "/api/admin/v1/billing/settings", nil, "", ""); code != 401 {
|
||||
t.Fatalf("匿名管理接口: %d", code)
|
||||
}
|
||||
for _, path := range []string{"realtime", "models", "tasks", "history"} {
|
||||
if code, _, _ := call("GET", "/api/admin/v1/statistics/"+path, nil, "", ""); code != 401 {
|
||||
t.Fatalf("匿名统计接口 %s: %d", path, code)
|
||||
}
|
||||
}
|
||||
must("POST", "/api/auth/v1/admin/login", resource.Object{"email": "billing-http@example.com", "password": "billing-test-password"}, "")
|
||||
var user string
|
||||
if err = pool.QueryRow(ctx, `SELECT id FROM users WHERE email='billing-http@example.com'`).Scan(&user); err != nil {
|
||||
@@ -268,4 +273,17 @@ func TestBillingIntegration(t *testing.T) {
|
||||
if len(reconciliation["differences"].([]any)) != 0 || reconciliation.Int("total") != 0 {
|
||||
t.Fatalf("MCP 账目不平: %v", reconciliation)
|
||||
}
|
||||
modelStats := must("GET", "/api/admin/v1/statistics/models?range=24h", nil, "")
|
||||
if modelStats["summary"].(map[string]any)["calls"].(float64) == 0 {
|
||||
t.Fatal("真实模型调用未进入统计")
|
||||
}
|
||||
for _, path := range []string{"realtime", "tasks", "history"} {
|
||||
must("GET", "/api/admin/v1/statistics/"+path, nil, "")
|
||||
}
|
||||
savedCookie := cookie
|
||||
cookie = nil
|
||||
if code, _, _ := call("GET", "/api/admin/v1/statistics/models", nil, "billing-oauth-test", ""); code != 401 {
|
||||
t.Fatalf("Agent token 不应获得管理统计: %d", code)
|
||||
}
|
||||
cookie = savedCookie
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const historyFilter = ` FROM sessions s JOIN users u ON u.id=s.owner_user_id WHERE s.deleted_at IS NULL
|
||||
AND ($1='' OR strpos(lower(s.title),lower($1))>0 OR strpos(s.id::text,lower($1))>0)
|
||||
AND ($2='' OR strpos(lower(u.name),lower($2))>0 OR strpos(lower(u.email),lower($2))>0)
|
||||
AND ($3::timestamptz IS NULL OR s.started_at >= $3) AND ($4::timestamptz IS NULL OR s.started_at < $4)`
|
||||
|
||||
func (s *Service) history(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
title, user := strings.TrimSpace(q.Get("task")), strings.TrimSpace(q.Get("user"))
|
||||
if len(title) > 200 || len(user) > 200 {
|
||||
resource.Fail(w, resource.Invalid("搜索条件过长"))
|
||||
return
|
||||
}
|
||||
var from, until *time.Time
|
||||
for key, target := range map[string]**time.Time{"from": &from, "until": &until} {
|
||||
if value := q.Get(key); value != "" {
|
||||
at, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
resource.Fail(w, resource.Invalid("筛选时间需使用带时区的 ISO 格式"))
|
||||
return
|
||||
}
|
||||
*target = &at
|
||||
}
|
||||
}
|
||||
if from != nil && until != nil && !from.Before(*until) {
|
||||
resource.Fail(w, resource.Invalid("结束时间必须晚于开始时间"))
|
||||
return
|
||||
}
|
||||
page, size := 1, 20
|
||||
for key, target := range map[string]*int{"page": &page, "page_size": &size} {
|
||||
if value := q.Get(key); value != "" {
|
||||
n, err := strconv.Atoi(value)
|
||||
if err != nil || n < 1 || n > 1_000_000 || (key == "page_size" && n > 500) {
|
||||
resource.Fail(w, resource.Invalid("分页参数无效"))
|
||||
return
|
||||
}
|
||||
*target = n
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
args := []any{title, user, from, until}
|
||||
var total int64
|
||||
if err = tx.QueryRow(ctx, `SELECT count(*)`+historyFilter, args...).Scan(&total); err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
pages := max(1, (total+int64(size)-1)/int64(size))
|
||||
page = min(page, int(pages))
|
||||
items, err := resource.Rows(ctx, tx, `SELECT jsonb_build_object('id',s.id,'title',s.title,'user_name',u.name,'user_email',u.email,
|
||||
'started_at',s.started_at,'last_active_at',s.last_active_at,'turn_count',s.turn_count)`+historyFilter+` ORDER BY s.started_at DESC,s.id DESC LIMIT $5 OFFSET $6`, append(args, size, (page-1)*size)...)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
resource.JSON(w, http.StatusOK, resource.Object{"items": items, "total": total, "page": page, "page_size": size})
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const modelSummary = `jsonb_build_object(
|
||||
'calls',count(*),
|
||||
'input_tokens',COALESCE(sum(input_tokens),0),
|
||||
'output_tokens',COALESCE(sum(output_tokens),0),
|
||||
'cache_hit_rate',100.0*count(*) FILTER(WHERE cache_hit)/NULLIF(count(*),0),
|
||||
'success_rate',100.0*count(*) FILTER(WHERE status='succeeded')/NULLIF(count(*) FILTER(WHERE status<>'running'),0))`
|
||||
|
||||
func models(ctx context.Context, tx pgx.Tx, w window) (resource.Object, error) {
|
||||
args := []any{w.from, w.until, w.model}
|
||||
out, err := resource.Row(ctx, tx, `WITH periods AS (
|
||||
SELECT 0 AS n,$1::timestamptz AS start_at,$2::timestamptz AS end_at
|
||||
UNION ALL SELECT 1,$1::timestamptz-($2::timestamptz-$1::timestamptz),$1::timestamptz
|
||||
), totals AS (
|
||||
SELECT n,(SELECT `+modelSummary+` FROM model_calls c
|
||||
WHERE c.started_at>=p.start_at AND c.started_at<p.end_at AND ($3='' OR c.model_id=NULLIF($3,'')::uuid)) ||
|
||||
jsonb_build_object('credits',(SELECT COALESCE(-sum(credit_delta),0)::text FROM credit_ledger_entries e
|
||||
WHERE e.occurred_at>=p.start_at AND e.occurred_at<p.end_at AND e.category='model'
|
||||
AND e.entry_type IN ('charge','refund') AND ($3='' OR e.resource_id=NULLIF($3,'')::uuid))) AS summary
|
||||
FROM periods p
|
||||
) SELECT jsonb_build_object('summary',(SELECT summary FROM totals WHERE n=0),'previous',(SELECT summary FROM totals WHERE n=1))`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
trend, err := resource.Rows(ctx, tx, `WITH buckets AS (
|
||||
SELECT generate_series($1::timestamptz,$2::timestamptz-interval '1 microsecond',$4::bigint*interval '1 second') AS at
|
||||
), calls AS (
|
||||
SELECT floor(extract(epoch FROM (started_at-$1::timestamptz))/$4)::bigint AS bucket,
|
||||
count(*) AS calls,sum(input_tokens) AS input_tokens,sum(output_tokens) AS output_tokens
|
||||
FROM model_calls WHERE started_at >= $1 AND started_at < $2 AND ($3='' OR model_id=NULLIF($3,'')::uuid) GROUP BY 1
|
||||
), credits AS (
|
||||
SELECT floor(extract(epoch FROM (occurred_at-$1::timestamptz))/$4)::bigint AS bucket,-sum(credit_delta) AS credits
|
||||
FROM credit_ledger_entries WHERE occurred_at >= $1 AND occurred_at < $2 AND category='model'
|
||||
AND entry_type IN ('charge','refund') AND ($3='' OR resource_id=NULLIF($3,'')::uuid) GROUP BY 1
|
||||
) SELECT jsonb_build_object('at',b.at,'calls',COALESCE(c.calls,0),'input_tokens',COALESCE(c.input_tokens,0),
|
||||
'output_tokens',COALESCE(c.output_tokens,0),'credits',COALESCE(e.credits,0)::text)
|
||||
FROM buckets b LEFT JOIN calls c ON c.bucket=floor(extract(epoch FROM (b.at-$1::timestamptz))/$4)::bigint
|
||||
LEFT JOIN credits e ON e.bucket=floor(extract(epoch FROM (b.at-$1::timestamptz))/$4)::bigint ORDER BY b.at`, append(args, int64(w.step.Seconds()))...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options, err := resource.Rows(ctx, tx, `SELECT jsonb_build_object('id',id,'name',display_name,'deleted',deleted_at IS NOT NULL)
|
||||
FROM models WHERE deleted_at IS NULL OR id=NULLIF($3,'')::uuid OR id IN (SELECT model_id FROM model_calls WHERE started_at >= $1 AND started_at < $2)
|
||||
OR id IN (SELECT resource_id FROM credit_ledger_entries WHERE category='model' AND occurred_at >= $1 AND occurred_at < $2)
|
||||
ORDER BY display_name,id`, w.from, w.until, w.model)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["trend"], out["models"] = trend, options
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func realtime(ctx context.Context, tx pgx.Tx, w window) (resource.Object, error) {
|
||||
return resource.Row(ctx, tx, `WITH calls AS (
|
||||
SELECT * FROM model_calls WHERE completed_at >= $1 AND completed_at < $2
|
||||
), active_users AS (
|
||||
SELECT user_id FROM calls
|
||||
UNION SELECT user_id FROM mcp_tool_calls WHERE completed_at >= $1 AND completed_at < $2
|
||||
UNION SELECT owner_user_id FROM sessions WHERE last_active_at >= $1 AND last_active_at < $2 AND deleted_at IS NULL
|
||||
UNION SELECT user_id FROM billing_transactions WHERE status='running' AND started_at >= $1 AND started_at < $2
|
||||
) SELECT jsonb_build_object(
|
||||
'model_consumption',(SELECT COALESCE(-sum(credit_delta),0)::text FROM credit_ledger_entries WHERE occurred_at >= $1 AND occurred_at < $2 AND category='model' AND entry_type IN ('charge','refund')),
|
||||
'p95_response_time',(SELECT percentile_cont(0.95) WITHIN GROUP (ORDER BY COALESCE(response_duration_ms,extract(epoch FROM (completed_at-started_at))*1000)) FROM calls WHERE status<>'running'),
|
||||
'model_success_rate',(SELECT 100.0*count(*) FILTER(WHERE status='succeeded')/NULLIF(count(*) FILTER(WHERE status<>'running'),0) FROM calls),
|
||||
'model_calls',(SELECT count(*) FROM calls),
|
||||
'tpm',(SELECT COALESCE(sum(input_tokens+output_tokens),0) FROM calls)/$3::numeric,
|
||||
'rpm',(SELECT count(*) FROM calls)/$3::numeric,
|
||||
'input_tokens',(SELECT COALESCE(sum(input_tokens),0) FROM calls),
|
||||
'output_tokens',(SELECT COALESCE(sum(output_tokens),0) FROM calls),
|
||||
'active_users',(SELECT count(*) FROM active_users),
|
||||
'active_tasks',(SELECT count(*) FROM sessions WHERE ended_at IS NULL AND last_active_at >= $1 AND last_active_at < $2 AND deleted_at IS NULL),
|
||||
'new_tasks',(SELECT count(*) FROM sessions WHERE started_at >= $1 AND started_at < $2 AND deleted_at IS NULL))`, w.from, w.until, w.until.Sub(w.from).Minutes())
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
pool *pgxpool.Pool
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewService(pool *pgxpool.Pool) *Service {
|
||||
return &Service{pool: pool, now: time.Now}
|
||||
}
|
||||
|
||||
type window struct {
|
||||
from, until time.Time
|
||||
step time.Duration
|
||||
model string
|
||||
}
|
||||
|
||||
func period(r *http.Request, now time.Time, realtime bool) (window, error) {
|
||||
ranges := map[string]time.Duration{"24h": 24 * time.Hour, "7d": 7 * 24 * time.Hour, "30d": 30 * 24 * time.Hour, "90d": 90 * 24 * time.Hour}
|
||||
value := r.URL.Query().Get("range")
|
||||
if realtime {
|
||||
ranges = map[string]time.Duration{"5m": 5 * time.Minute, "15m": 15 * time.Minute, "30m": 30 * time.Minute, "60m": time.Hour}
|
||||
if value == "" {
|
||||
value = "15m"
|
||||
}
|
||||
} else if value == "" {
|
||||
value = "30d"
|
||||
}
|
||||
duration, ok := ranges[value]
|
||||
if !ok {
|
||||
return window{}, resource.Invalid("统计周期无效")
|
||||
}
|
||||
w := window{from: now.Add(-duration), until: now, step: 24 * time.Hour, model: r.URL.Query().Get("model_id")}
|
||||
if duration <= 24*time.Hour {
|
||||
w.step = time.Hour
|
||||
}
|
||||
if w.model != "" {
|
||||
var id pgtype.UUID
|
||||
if err := id.Scan(w.model); err != nil || !id.Valid {
|
||||
return window{}, resource.Invalid("模型 ID 无效")
|
||||
}
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (s *Service) RegisterAdmin(r chi.Router) {
|
||||
r.Get("/statistics/realtime", s.read(true, realtime))
|
||||
r.Get("/statistics/models", s.read(false, models))
|
||||
r.Get("/statistics/tasks", s.read(false, tasks))
|
||||
r.Get("/statistics/history", s.history)
|
||||
}
|
||||
|
||||
func (s *Service) read(live bool, query func(context.Context, pgx.Tx, window) (resource.Object, error)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
period, err := period(r, s.now().UTC(), live)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
out, err := query(ctx, tx, period)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
out["from"], out["until"] = period.from, period.until
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
resource.JSON(w, http.StatusOK, out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func fixture(t *testing.T) (*Service, string, string) {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("MONKEYAI_TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("设置 MONKEYAI_TEST_DATABASE_URL 运行统计数据库测试")
|
||||
}
|
||||
ctx := t.Context()
|
||||
root, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := "stats_test_" + strings.ReplaceAll(resource.ID(), "-", "")
|
||||
if _, err = root.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
||||
root.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
pool.Close()
|
||||
_, _ = root.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE")
|
||||
root.Close()
|
||||
})
|
||||
paths, err := filepath.Glob("../../migrations/*.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range paths {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, string(data)); err != nil {
|
||||
t.Fatalf("迁移 %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
s := NewService(pool)
|
||||
s.now = func() time.Time { return time.Date(2026, 9, 8, 12, 0, 0, 0, time.UTC) }
|
||||
user, model := resource.ID(), resource.ID()
|
||||
exec(t, s, `INSERT INTO users(id,name,email,role) VALUES($1,'统计用户','stats@example.com','admin')`, user)
|
||||
exec(t, s, `INSERT INTO models(id,ownership_type,display_name,model_id,protocol,base_url,api_key,advanced_config,owner_user_id) VALUES($1,'system','历史模型','upstream','openai_chat_completions','https://example.com','test','{}',$2)`, model, user)
|
||||
return s, user, model
|
||||
}
|
||||
func exec(t *testing.T, s *Service, query string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := s.pool.Exec(t.Context(), query, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func request(t *testing.T, s *Service, path string, code int) resource.Object {
|
||||
t.Helper()
|
||||
r := chi.NewRouter()
|
||||
s.RegisterAdmin(r)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
|
||||
if w.Code != code {
|
||||
t.Fatalf("%s: %d %s", path, w.Code, w.Body.String())
|
||||
}
|
||||
if code == 200 && w.Header().Get("Cache-Control") != "private, no-store" {
|
||||
t.Fatal("统计响应应禁止缓存")
|
||||
}
|
||||
var out resource.Object
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
func number(t *testing.T, out map[string]any, key string, want float64) {
|
||||
t.Helper()
|
||||
got, ok := out[key].(float64)
|
||||
if !ok || math.Abs(got-want) > 0.00001 {
|
||||
t.Fatalf("%s: %v,期望 %v", key, out[key], want)
|
||||
}
|
||||
}
|
||||
func call(t *testing.T, s *Service, user, model, status string, start, end time.Time, input, cached, output int64, duration any) {
|
||||
t.Helper()
|
||||
exec(t, s, `INSERT INTO model_calls(user_id,model_id,status,started_at,completed_at,input_tokens,cached_input_tokens,output_tokens,cache_hit,response_duration_ms) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$7::bigint>0,$9)`, user, model, status, start, end, input, cached, output, duration)
|
||||
}
|
||||
func TestModels(t *testing.T) {
|
||||
s, user, model := fixture(t)
|
||||
now := s.now()
|
||||
from := now.Add(-24 * time.Hour)
|
||||
call(t, s, user, model, "succeeded", now.Add(-2*time.Minute), now.Add(-time.Minute), 100, 50, 20, nil)
|
||||
call(t, s, user, model, "failed", now.Add(-time.Minute), now.Add(-30*time.Second), 40, 0, 10, 2000)
|
||||
call(t, s, user, model, "succeeded", from.Add(-time.Second), from, 800, 0, 80, nil)
|
||||
call(t, s, user, model, "succeeded", now, now, 900, 0, 90, nil)
|
||||
other := resource.ID()
|
||||
exec(t, s, `INSERT INTO models(id,ownership_type,display_name,model_id,protocol,base_url,api_key,advanced_config,owner_user_id) VALUES($1,'system','其他模型','other','openai_chat_completions','https://example.com','test','{}',$2)`, other, user)
|
||||
call(t, s, user, other, "succeeded", from, from.Add(time.Minute), 50, 0, 5, 1000)
|
||||
account := resource.ID()
|
||||
exec(t, s, `INSERT INTO credit_accounts(id,user_id,period_start_at,period_end_at,last_refreshed_at) VALUES($1,$2,$3,$4,$3)`, account, user, from, now)
|
||||
for _, entry := range []struct {
|
||||
kind, amount, model string
|
||||
at time.Time
|
||||
}{
|
||||
{"charge", "-10", model, now.Add(-time.Minute)}, {"refund", "4", model, now.Add(-time.Minute)},
|
||||
{"grant", "500", model, now.Add(-time.Minute)}, {"charge", "-3", other, now.Add(-time.Minute)},
|
||||
{"charge", "-7", model, from.Add(-time.Second)}, {"charge", "-100", model, now},
|
||||
} {
|
||||
exec(t, s, `INSERT INTO credit_ledger_entries(account_id,user_id,entry_type,category,resource_type,resource_id,item_name,credit_delta,balance_after,occurred_at) VALUES($1,$2,$3,'model','model',$4,'测试',$5,0,$6)`, account, user, entry.kind, entry.model, entry.amount, entry.at)
|
||||
}
|
||||
exec(t, s, `UPDATE models SET deleted_at=$2 WHERE id=$1`, model, now)
|
||||
out := request(t, s, "/statistics/models?range=24h&model_id="+model, 200)
|
||||
summary := out["summary"].(map[string]any)
|
||||
for key, want := range map[string]float64{"calls": 2, "input_tokens": 140, "output_tokens": 30, "cache_hit_rate": 50, "success_rate": 50} {
|
||||
number(t, summary, key, want)
|
||||
}
|
||||
if summary["credits"] != "6.000000" {
|
||||
t.Fatalf("退款或类别归属错误: %v", summary)
|
||||
}
|
||||
previous := out["previous"].(map[string]any)
|
||||
number(t, previous, "calls", 1)
|
||||
if previous["credits"] != "7.000000" {
|
||||
t.Fatalf("上一周期: %v", previous)
|
||||
}
|
||||
trend := out["trend"].([]any)
|
||||
if len(trend) != 24 {
|
||||
t.Fatalf("趋势分桶: %d", len(trend))
|
||||
}
|
||||
var calls, input float64
|
||||
for _, point := range trend {
|
||||
row := point.(map[string]any)
|
||||
calls += row["calls"].(float64)
|
||||
input += row["input_tokens"].(float64)
|
||||
}
|
||||
if calls != 2 || input != 140 {
|
||||
t.Fatalf("趋势与总计不一致: %v %v", calls, input)
|
||||
}
|
||||
options := out["models"].([]any)
|
||||
found := false
|
||||
for _, item := range options {
|
||||
row := item.(map[string]any)
|
||||
if row["id"] == model {
|
||||
found = row["deleted"] == true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("已删除模型的历史统计必须可筛选")
|
||||
}
|
||||
all := request(t, s, "/statistics/models?range=24h", 200)
|
||||
number(t, all["summary"].(map[string]any), "calls", 3)
|
||||
}
|
||||
func TestRealtime(t *testing.T) {
|
||||
s, user, model := fixture(t)
|
||||
now := s.now()
|
||||
call(t, s, user, model, "succeeded", now.Add(-time.Hour), now.Add(-2*time.Minute), 100, 0, 20, 1000)
|
||||
call(t, s, user, model, "failed", now.Add(-2*time.Minute), now.Add(-time.Minute), 50, 0, 30, 9000)
|
||||
call(t, s, user, model, "succeeded", now.Add(-2*time.Hour), now.Add(-time.Hour), 999, 0, 999, 999)
|
||||
out := request(t, s, "/statistics/realtime?range=5m", 200)
|
||||
for key, want := range map[string]float64{"model_calls": 2, "model_success_rate": 50, "p95_response_time": 8600, "rpm": 0.4, "tpm": 40, "active_users": 1} {
|
||||
number(t, out, key, want)
|
||||
}
|
||||
exec(t, s, `UPDATE model_calls SET response_duration_ms=NULL WHERE completed_at=$1`, now.Add(-time.Minute))
|
||||
out = request(t, s, "/statistics/realtime?range=5m", 200)
|
||||
number(t, out, "p95_response_time", 57050)
|
||||
}
|
||||
func TestTasksAndHistory(t *testing.T) {
|
||||
s, user, _ := fixture(t)
|
||||
now := s.now()
|
||||
from := now.Add(-7 * 24 * time.Hour)
|
||||
for _, row := range []struct {
|
||||
title string
|
||||
start time.Time
|
||||
ended any
|
||||
failure, deleted any
|
||||
turns int
|
||||
}{
|
||||
{"报告 100%", from, from.Add(100 * time.Second), nil, nil, 2},
|
||||
{"报告失败", now.Add(-3 * time.Minute), now.Add(-time.Minute), "upstream_failed", nil, 3},
|
||||
{"继续处理", now.Add(-2 * time.Minute), nil, nil, nil, 1},
|
||||
{"已删除", now.Add(-time.Minute), now, nil, now, 99},
|
||||
{"上一周期", from.Add(-time.Second), from, nil, nil, 0},
|
||||
{"右边界", now, nil, nil, nil, 0},
|
||||
} {
|
||||
exec(t, s, `INSERT INTO sessions(owner_user_id,title,session_type,client_type,client_name,started_at,last_active_at,ended_at,failure_code,deleted_at,turn_count) VALUES($1,$2,'conversation','desktop','测试客户端',$3,$3,$4,$5,$6,$7)`, user, row.title, row.start, row.ended, row.failure, row.deleted, row.turns)
|
||||
}
|
||||
out := request(t, s, "/statistics/tasks?range=7d", 200)
|
||||
summary := out["summary"].(map[string]any)
|
||||
for key, want := range map[string]float64{"total": 3, "completed": 1, "failed": 1, "running": 1, "average_duration_seconds": 110, "completion_rate": 100.0 / 3} {
|
||||
number(t, summary, key, want)
|
||||
}
|
||||
if len(out["trend"].([]any)) != 7 || len(out["types"].([]any)) != 1 {
|
||||
t.Fatalf("分桶或类型错误: %v", out)
|
||||
}
|
||||
number(t, out["previous"].(map[string]any), "total", 1)
|
||||
out = request(t, s, "/statistics/history?task=100%25&user=STATS&page=99&page_size=1", 200)
|
||||
number(t, out, "total", 1)
|
||||
number(t, out, "page", 1)
|
||||
if out["items"].([]any)[0].(map[string]any)["title"] != "报告 100%" {
|
||||
t.Fatalf("文本过滤错误: %v", out)
|
||||
}
|
||||
out = request(t, s, "/statistics/history?from="+from.Format(time.RFC3339)+"&until="+now.Format(time.RFC3339)+"&page_size=1&page=2", 200)
|
||||
number(t, out, "total", 3)
|
||||
number(t, out, "page", 2)
|
||||
number(t, out["items"].([]any)[0].(map[string]any), "turn_count", 3)
|
||||
}
|
||||
func TestEmptyAndInvalid(t *testing.T) {
|
||||
s, _, _ := fixture(t)
|
||||
for _, path := range []string{"/statistics/models", "/statistics/tasks", "/statistics/realtime", "/statistics/history"} {
|
||||
request(t, s, path, 200)
|
||||
}
|
||||
out := request(t, s, "/statistics/realtime", 200)
|
||||
if out["p95_response_time"] != nil || out["model_success_rate"] != nil {
|
||||
t.Fatalf("空样本不能产生百分比或时延: %v", out)
|
||||
}
|
||||
for _, path := range []string{"/statistics/models?range=invalid", "/statistics/realtime?range=7d", "/statistics/models?model_id=bad", "/statistics/history?page=0", "/statistics/history?page_size=501", "/statistics/history?from=bad", "/statistics/history?from=2026-09-09T00:00:00Z&until=2026-09-08T00:00:00Z"} {
|
||||
request(t, s, path, 400)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const taskSummary = `jsonb_build_object(
|
||||
'total',count(*),
|
||||
'completed',count(*) FILTER(WHERE ended_at IS NOT NULL AND NULLIF(failure_code,'') IS NULL AND NULLIF(failure_message,'') IS NULL),
|
||||
'failed',count(*) FILTER(WHERE ended_at IS NOT NULL AND (NULLIF(failure_code,'') IS NOT NULL OR NULLIF(failure_message,'') IS NOT NULL)),
|
||||
'running',count(*) FILTER(WHERE ended_at IS NULL),
|
||||
'completion_rate',100.0*count(*) FILTER(WHERE ended_at IS NOT NULL AND NULLIF(failure_code,'') IS NULL AND NULLIF(failure_message,'') IS NULL)/NULLIF(count(*),0),
|
||||
'average_duration_seconds',avg(extract(epoch FROM (ended_at-started_at))))`
|
||||
|
||||
func tasks(ctx context.Context, tx pgx.Tx, w window) (resource.Object, error) {
|
||||
args := []any{w.from, w.until}
|
||||
out, err := resource.Row(ctx, tx, `WITH periods AS (
|
||||
SELECT 0 AS n,$1::timestamptz AS start_at,$2::timestamptz AS end_at
|
||||
UNION ALL SELECT 1,$1::timestamptz-($2::timestamptz-$1::timestamptz),$1::timestamptz
|
||||
), totals AS (
|
||||
SELECT n,(SELECT `+taskSummary+` FROM sessions s WHERE s.started_at>=p.start_at AND s.started_at<p.end_at AND s.deleted_at IS NULL) AS summary FROM periods p
|
||||
) SELECT jsonb_build_object('summary',(SELECT summary FROM totals WHERE n=0),'previous',(SELECT summary FROM totals WHERE n=1))`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
trend, err := resource.Rows(ctx, tx, `WITH buckets AS (
|
||||
SELECT generate_series($1::timestamptz,$2::timestamptz-interval '1 microsecond',$3::bigint*interval '1 second') AS at
|
||||
), totals AS (
|
||||
SELECT floor(extract(epoch FROM (started_at-$1::timestamptz))/$3)::bigint AS bucket,
|
||||
count(*) FILTER(WHERE ended_at IS NOT NULL AND NULLIF(failure_code,'') IS NULL AND NULLIF(failure_message,'') IS NULL) AS completed,
|
||||
count(*) FILTER(WHERE ended_at IS NOT NULL AND (NULLIF(failure_code,'') IS NOT NULL OR NULLIF(failure_message,'') IS NOT NULL)) AS failed,
|
||||
count(*) FILTER(WHERE ended_at IS NULL) AS running
|
||||
FROM sessions WHERE started_at >= $1 AND started_at < $2 AND deleted_at IS NULL GROUP BY 1
|
||||
) SELECT jsonb_build_object('at',b.at,'completed',COALESCE(t.completed,0),'failed',COALESCE(t.failed,0),'running',COALESCE(t.running,0))
|
||||
FROM buckets b LEFT JOIN totals t ON t.bucket=floor(extract(epoch FROM (b.at-$1::timestamptz))/$3)::bigint ORDER BY b.at`, append(args, int64(w.step.Seconds()))...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
types, err := resource.Rows(ctx, tx, `SELECT `+taskSummary+`||jsonb_build_object('key',session_type) FROM sessions
|
||||
WHERE started_at >= $1 AND started_at < $2 AND deleted_at IS NULL GROUP BY session_type ORDER BY count(*) DESC,session_type`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["trend"], out["types"] = trend, types
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
BEGIN;
|
||||
DROP INDEX sessions_last_active_idx;
|
||||
DROP INDEX sessions_started_idx;
|
||||
DROP INDEX mcp_tool_calls_completed_idx;
|
||||
DROP INDEX model_calls_completed_idx;
|
||||
DROP INDEX model_calls_started_idx;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,7 @@
|
||||
BEGIN;
|
||||
CREATE INDEX model_calls_started_idx ON model_calls (started_at);
|
||||
CREATE INDEX model_calls_completed_idx ON model_calls (completed_at) WHERE completed_at IS NOT NULL;
|
||||
CREATE INDEX mcp_tool_calls_completed_idx ON mcp_tool_calls (completed_at) WHERE completed_at IS NOT NULL;
|
||||
CREATE INDEX sessions_started_idx ON sessions (started_at DESC,id DESC) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX sessions_last_active_idx ON sessions (last_active_at) WHERE deleted_at IS NULL;
|
||||
COMMIT;
|
||||
@@ -4,7 +4,9 @@
|
||||
- `000002_billing_create_transactions`:计费账户、额度与流水。
|
||||
- `000003_group_virtual_root`:将旧部署的系统分组转换为虚拟团队根节点的结构。新库同样执行此版本,不会创建分组。
|
||||
|
||||
运行 `migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up`。成功后应为 `version=3, dirty=false`,再次执行为 `no change`。已有版本 1 或 2 的数据库执行增量升级,无需清库或 `force`。
|
||||
- `000004_stats_add_indexes`:为统计查询补充调用与会话的时间索引,仅增索引,可独立回滚。
|
||||
|
||||
运行 `migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up`。成功后应为 `version=4, dirty=false`,再次执行为 `no change`。已有版本 1、2 或 3 的数据库执行增量升级,无需清库或 `force`。
|
||||
|
||||
团队根节点仅用于界面展示,名称读取 `settings` 中 `branding` 的 `workspace_name`,不写入 `groups`。`parent_id IS NULL` 的记录均为团队根节点的直属子分组;成员关系通过 `group_users` 显式维护,不根据用户角色自动建组或分配。
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# 管理后台统计
|
||||
|
||||
四个统计页面使用 `/api/admin/v1/statistics/{realtime,models,tasks,history}`,由 `internal/stats` 显式注册并复用管理员 Cookie 鉴权。Agent token 和调用密钥没有访问权限。查询使用 PostgreSQL 只读 Repeatable Read 快照,单次请求限时 15 秒,返回 `private, no-store`。
|
||||
|
||||
## 数据口径
|
||||
|
||||
| 页面 | 数据来源 | 时间与计算规则 |
|
||||
| --- | --- | --- |
|
||||
| 模型统计 | `model_calls`、`models`、`credit_ledger_entries` | 调用按 `started_at`,积分按 `occurred_at`;模型筛选同时作用于调用和消费。缓存命中率为命中缓存的调用数 / 全部调用数。输入 Token 已包含缓存输入,不能再次累加。 |
|
||||
| 实时状态 | `model_calls`、`mcp_tool_calls`、`billing_transactions`、`sessions`、积分流水 | 吞吐与时延按窗口内完成的模型调用;RPM、TPM 分别除以整个窗口分钟数。成功率分母包含失败和取消,排除运行中记录。P95 优先使用响应耗时,未记录时取完成时间减开始时间。 |
|
||||
| 任务统计 | `sessions` | 按开始时间选择新建会话,按当前结束结果分类:未结束、成功结束、异常结束。完成率为成功结束数 / 全部会话数;平均耗时仅取已结束会话。取消若以失败字段记录,归入异常结束。 |
|
||||
| 任务历史 | `sessions`、`users` | 按开始时间倒序并以 UUID 稳定排序;支持标题 / UUID、姓名 / 邮箱包含搜索,以及日期和分页。只展示累计轮次,不把它解释为窗口内新增对话数。 |
|
||||
|
||||
- 统计周期为相对于服务端当前时间的滚动窗口,统一使用 `[from, until)`;环比查询紧邻的上一等长周期。
|
||||
- 24 小时趋势按 1 小时分桶,7 / 30 / 90 天趋势按固定 24 小时分桶,从窗口起点开始,空桶补零,不对齐自然日。页面标签按浏览器语言及时区格式化。
|
||||
- 积分净消费只累加 `category=model` 的 `charge` 和 `refund`,扣除退款;额度发放、重置、人工调整不计入模型消费。纯退款窗口允许负值。调用与积分独立聚合,避免多笔流水放大调用量。
|
||||
- 积分通过 PostgreSQL `numeric` 聚合并以十进制字符串返回,前端仅在展示和绘图时转为数值,不参与计费。
|
||||
- 无调用时成功率、缓存命中率及 P95 为 `null`;无已结束会话时平均耗时为 `null`,页面显示 `—`。上一周期为零时不展示数量增长率;比率指标环比使用百分点。
|
||||
- 已软删除模型的历史调用和消费保留,模型选项包含窗口内有历史事实的已删除模型。已软删除会话不进入任务统计与历史。
|
||||
- 实时活跃用户按有完成模型 / MCP 调用、有会话活动、或窗口内发起且仍在执行计费调用的真实用户 ID 去重,不代表登录 DAU。活跃任务仅指近期有活动的未结束会话。
|
||||
- 实时页每 30 秒刷新,标签页隐藏时暂停自动请求。筛选变化会中止旧请求,旧响应不覆盖新筛选结果;网络错误提供重试。
|
||||
|
||||
## 会话采集边界
|
||||
|
||||
当前模型 / MCP 网关已经通过计费生命周期记录调用事实,模型统计可直接使用这些数据。
|
||||
|
||||
当前 `internal/session` 尚未实现会话上报,Desktop / Agent 也没有接通此表。本次只完善管理端统计读取,没有新增客户端采集协议。因此新部署中的任务统计、任务历史以及实时任务指标在接通会话采集前为空;页面明确说明这一依赖,不生成示例数据,也不将一次模型请求伪装成一个任务。历史已有会话事实的实例可直接查询。
|
||||
|
||||
## 迁移与验证
|
||||
|
||||
新增 `000004_stats_add_indexes`,为模型调用开始 / 完成时间、MCP 完成时间以及会话开始 / 活跃时间补充索引。部署前执行增量迁移至版本 4。该版本仅添加索引,可以单独 down / up;大量历史数据下建索引会占用写锁,按既有迁移发布流程安排维护窗口。
|
||||
|
||||
验证使用独立 PostgreSQL / RustFS 测试容器:
|
||||
|
||||
- 统计集成测试覆盖左闭右开边界、真实环比、退款净额、模型隔离、软删除历史、空桶、长调用跨窗口、P95 缺失耗时回退、任务分类、筛选与分页。
|
||||
- 应用集成测试通过真实模型 / MCP 计费入口产生事实,再访问统计路由,并校验匿名访问和 Agent token 被拒绝。
|
||||
- 前端测试覆盖零基数环比和百分点口径,同时执行已有测试、lint、build。
|
||||
- OpenAPI 检查重复键、本地引用以及迁移序号;新增迁移在空库执行 up / down / up。
|
||||
|
||||
本轮验证结果:后端完整 PostgreSQL / RustFS 集成测试、`go vet ./...`、统计模块 race 测试、前端 45 项测试、lint 和生产构建通过。浏览器使用独立测试数据验证模型筛选、任务状态与历史分页、空结果、网络错误重试、延迟旧请求隔离和 390 像素布局。统计图表关闭入场动画,避免隐藏标签页停留在空白初始帧;图例直接引用主题颜色,使图表容器外的状态标识正常显示。
|
||||
Reference in new issue
Block a user